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}
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 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 #[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 #[arg(long = "dry-run")]
325 pub dry_run: bool,
326
327 #[arg(short, long, action = clap::ArgAction::Count)]
329 pub verbose: u8,
330
331 #[arg(long)]
334 pub stats: bool,
335
336 #[arg(long)]
339 pub profile: bool,
340
341 #[arg(short, long = "debug-engine")]
355 pub debug_engine: Option<DebugEngineMode>,
356
357 #[arg(long)]
365 pub extract_type_aliases: bool,
366
367 #[command(flatten)]
368 pub translation_options: TranslationOptions,
369
370 #[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 #[clap(name = "into")]
387 Backend(BackendOptions<E>),
388
389 JSON {
391 #[arg(
393 short,
394 long = "output-file",
395 default_value = "hax_frontend_export.json"
396 )]
397 output_file: PathOrDash,
398 #[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 #[arg(long)]
416 use_ids: bool,
417
418 #[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 #[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 #[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 #[arg(long="disable-cargo-cache", action=clap::builder::ArgAction::SetFalse)]
485 pub force_cargo_build: ForceCargoBuild,
486
487 #[arg(long = "deps")]
492 pub deps: bool,
493
494 #[arg(long)]
499 pub no_custom_target_directory: bool,
500
501 #[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";