Skip to main content

flux_config/
flags.rs

1use std::{env, path::PathBuf, process, str::FromStr, sync::LazyLock};
2
3use clap::{ArgMatches, Args, Command, FromArgMatches, parser::ValueSource};
4pub use toml::Value;
5use tracing::Level;
6
7use crate::{
8    IncludePattern, LeanMode, OverflowMode, PointerWidth, RawDerefMode, SmtSolver, UifOps,
9};
10
11const FLUX_FLAG_PREFIX: &str = "-F";
12
13macro_rules! flux_arg {
14    ($name:literal) => {
15        concat!("F", $name)
16    };
17}
18
19/// Exit status code used for invalid flags.
20pub const EXIT_FAILURE: i32 = 2;
21
22#[derive(Args)]
23#[command(next_help_heading = "Flux-Specific Flags")]
24pub struct Flags {
25    /// Sets the directory to dump data.
26    #[arg(
27        long = flux_arg!("log-dir"),
28        value_name = "PATH",
29        default_value = "./log/",
30    )]
31    pub log_dir: PathBuf,
32    /// Sets the directory to put all the emitted lean definitions and verification conditions.
33    #[arg(
34        long = flux_arg!("lean-dir"),
35        value_name = "PATH",
36        default_value = "./"
37    )]
38    pub lean_dir: PathBuf,
39    /// Name of the lean project.
40    #[arg(
41        long = flux_arg!("lean-project"),
42        value_name = "NAME",
43        default_value = "lean_proofs"
44    )]
45    pub lean_project: String,
46    /// If present, only check files matching the [`IncludePattern`] (a glob pattern).
47    #[arg(long = flux_arg!("include"), value_name = "PATTERN")]
48    pub include: Option<IncludePattern>,
49    /// If present, trust items matching [`IncludePattern`]. This implies `-Finclude`
50    #[arg(long = flux_arg!("include-trusted"), value_name = "PATTERN")]
51    pub include_trusted: Option<IncludePattern>,
52    /// If present, trust items matching [`IncludePattern`]. This implies `-Finclude`
53    #[arg(long = flux_arg!("include-trusted-impl"), value_name = "PATTERN")]
54    pub include_trusted_impl: Option<IncludePattern>,
55    /// Set the pointer size (either `32` or `64`), used to determine if an integer cast is lossy.
56    #[arg(
57        long = flux_arg!("pointer-width"),
58        value_name = "WIDTH",
59        default_value = "64"
60    )]
61    pub pointer_width: PointerWidth,
62    /// If present, switches on query caching and saves the cache in the provided directory.
63    #[arg(long = flux_arg!("cache"), value_name = "DIR")]
64    pub cache: Option<PathBuf>,
65    /// Compute statistics about number and size of annotations. Dumps file to [`Self::log_dir`].
66    #[arg(
67        long = flux_arg!("annots"),
68        num_args = 0..=1,
69        default_missing_value = "true"
70    )]
71    pub annots: bool,
72    /// Print statistics about time taken to analyze each function. Also dumps a file with the raw
73    /// times for each function.
74    #[arg(
75        long = flux_arg!("timings"),
76        num_args = 0..=1,
77        default_missing_value = "true"
78    )]
79    pub timings: bool,
80    /// Print statistics about number of functions checked, trusted, etc.
81    #[arg(
82        long = flux_arg!("summary"),
83        num_args = 0..=1,
84        default_value = "true",
85        default_missing_value = "true"
86    )]
87    pub summary: bool,
88    /// Default solver. Either `z3` or `cvc5`.
89    #[arg(
90        long = flux_arg!("solver"),
91        value_name = "SOLVER",
92        default_value = "z3"
93    )]
94    pub solver: SmtSolver,
95    /// Enables qualifier scrapping in fixpoint.
96    #[arg(
97        long = flux_arg!("scrape-quals"),
98        num_args = 0..=1,
99        default_missing_value = "true"
100    )]
101    pub scrape_quals: bool,
102    /// Timeout in seconds for each fixpoint query. If a query doesn't finish in time, fixpoint is
103    /// killed and an error is reported for the item being checked. Disabled by default.
104    #[arg(long = flux_arg!("fixpoint-timeout"), value_name = "SECONDS")]
105    pub fixpoint_timeout: Option<u64>,
106    /// Enables uninterpreted casts.
107    #[arg(
108        long = flux_arg!("allow-uninterpreted-cast"),
109        num_args = 0..=1,
110        default_missing_value = "true"
111    )]
112    pub allow_uninterpreted_cast: bool,
113    /// If `strict` checks for over and underflow on arithmetic integer operations,
114    /// If `lazy` checks for underflow and loses information if possible overflow,
115    /// If `none` (default), it still checks for underflow on unsigned integer subtraction.
116    #[arg(
117        long = flux_arg!("check-overflow"),
118        value_name = "MODE",
119        default_value = "none"
120    )]
121    pub check_overflow: OverflowMode,
122    /// Whether to allow raw pointer dereferences during refinement checking.
123    #[arg(
124        long = flux_arg!("allow-raw-deref"),
125        value_name = "MODE",
126        default_value = "none"
127    )]
128    pub allow_raw_deref: RawDerefMode,
129    /// Binary operators to encode as uninterpreted functions in the constraints, as a comma
130    /// separated list, e.g., `*,/,%`.
131    #[arg(long = flux_arg!("uif-ops"), value_name = "OPS", default_value = "")]
132    pub uif_ops: UifOps,
133    /// Dump constraints generated for each function (debugging).
134    #[arg(
135        long = flux_arg!("dump-constraint"),
136        num_args = 0..=1,
137        default_missing_value = "true"
138    )]
139    pub dump_constraint: bool,
140    /// Dump the call and type dependency graphs as JSON (for tooling)
141    #[arg(
142        long = flux_arg!("dump-dep-graph"),
143        num_args = 0..=1,
144        default_missing_value = "false"
145    )]
146    pub dump_dep_graph: bool,
147    /// Saves the checker's trace (debugging).
148    #[arg(long = flux_arg!("dump-checker-trace"), value_name = "LEVEL")]
149    pub dump_checker_trace: Option<tracing::Level>,
150    /// Saves the `fhir` for each item (debugging).
151    #[arg(
152        long = flux_arg!("dump-fhir"),
153        num_args = 0..=1,
154        default_missing_value = "true"
155    )]
156    pub dump_fhir: bool,
157    /// Saves the the `fhir` (debugging).
158    #[arg(
159        long = flux_arg!("dump-rty"),
160        num_args = 0..=1,
161        default_missing_value = "true"
162    )]
163    pub dump_rty: bool,
164    /// Optimistically keeps running flux even after errors are found to get as many errors as possible.
165    #[arg(
166        long = flux_arg!("catch-bugs"),
167        num_args = 0..=1,
168        default_missing_value = "true"
169    )]
170    pub catch_bugs: bool,
171    /// Whether verification for the current crate is enabled. If false (the default), `flux-driver`
172    /// will behave exactly like `rustc`. This flag is managed by the `cargo flux` and `flux` binaries,
173    /// so you don't need to mess with it.
174    #[arg(
175        long = flux_arg!("verify"),
176        num_args = 0..=1,
177        default_missing_value = "true"
178    )]
179    pub verify: bool,
180    /// If `true`, produce artifacts after analysis. This flag is managed by `cargo flux`, so you
181    /// don't typically have to set it manually.
182    #[arg(
183        long = flux_arg!("full-compilation"),
184        num_args = 0..=1,
185        default_missing_value = "true"
186    )]
187    pub full_compilation: bool,
188    /// Path to the Flux sysroot directory. If not set, the driver infers it from its own binary location.
189    #[arg(long = flux_arg!("sysroot"), value_name = "PATH")]
190    pub sysroot: Option<PathBuf>,
191    /// If `true`, all code is trusted by default. You can selectively untrust items by marking them with `#[trusted(no)]`. The default value of this flag is `false`, i.e., all code is untrusted by default.
192    #[arg(
193        long = flux_arg!("trusted"),
194        num_args = 0..=1,
195        default_missing_value = "true"
196    )]
197    pub trusted_default: bool,
198    /// If `true`, all code will be ignored by default. You can selectively unignore items by marking them with `#[ignore(no)]`. The default value of this flag is `false`, i.e., all code is unignored by default.
199    #[arg(
200        long = flux_arg!("ignore"),
201        num_args = 0..=1,
202        default_missing_value = "true"
203    )]
204    pub ignore_default: bool,
205    #[arg(long = flux_arg!("lean"), value_name = "MODE", default_value = "off")]
206    pub lean: LeanMode,
207    /// If `true`, every function is implicitly labeled with a `no_panic` by default.
208    #[arg(
209        long = flux_arg!("no-panic"),
210        num_args = 0..=1,
211        default_missing_value = "true"
212    )]
213    pub no_panic: bool,
214    /// If `true`, automatically inject `flux_core` and `flux_alloc` as force externs using paths
215    /// from `sysroot.toml`. Off by default.
216    #[arg(
217        long = flux_arg!("std-extern-specs"),
218        num_args = 0..=1,
219        default_missing_value = "true"
220    )]
221    pub std_extern_specs: bool,
222    /// If `true`, produce more detailed error messages (e.g. condition spans for fold errors).
223    #[arg(
224        long = flux_arg!("flux-verbose"),
225        num_args = 0..=1,
226        default_missing_value = "true"
227    )]
228    pub flux_verbose: bool,
229    /// Enable the refinement suggestion engine. Items can opt out with `#[flux::no_suggestions]`.
230    #[arg(
231        long = flux_arg!("suggestions"),
232        num_args = 0..=1,
233        default_value_t = false,
234        default_missing_value = "true"
235    )]
236    pub suggestions: bool,
237    /// If `true` (the default), attach a note to each failing item with a copy-pasteable command to
238    /// re-run the check on just that item. Only applies when running under `cargo flux`.
239    #[arg(
240        long = flux_arg!("rerun-hint"),
241        num_args = 0..=1,
242        default_value = "true",
243        default_missing_value = "true"
244    )]
245    pub rerun_hint: bool,
246}
247
248impl Default for Flags {
249    fn default() -> Self {
250        Self {
251            log_dir: PathBuf::from("./log/"),
252            lean_dir: PathBuf::from("./"),
253            lean_project: "lean_proofs".to_string(),
254            dump_dep_graph: false,
255            dump_constraint: false,
256            dump_checker_trace: None,
257            dump_fhir: false,
258            dump_rty: false,
259            catch_bugs: false,
260            pointer_width: PointerWidth::default(),
261            include: None,
262            include_trusted: None,
263            include_trusted_impl: None,
264            cache: None,
265            check_overflow: OverflowMode::default(),
266            allow_raw_deref: RawDerefMode::default(),
267            uif_ops: UifOps::default(),
268            scrape_quals: false,
269            fixpoint_timeout: None,
270            allow_uninterpreted_cast: false,
271            solver: SmtSolver::default(),
272            annots: false,
273            timings: false,
274            summary: true,
275            verify: false,
276            full_compilation: false,
277            sysroot: None,
278            trusted_default: false,
279            ignore_default: false,
280            lean: LeanMode::default(),
281            no_panic: false,
282            std_extern_specs: false,
283            flux_verbose: false,
284            suggestions: false,
285            rerun_hint: true,
286        }
287    }
288}
289
290impl Flags {
291    // Convert this struct into what we'd need to pass in through the environment var
292    pub fn rustflags(matches: &ArgMatches) -> Vec<String> {
293        let spec = Flags::augment_args(Command::new("flux-flags"));
294        let mut out = Vec::new();
295        for arg in spec.get_arguments() {
296            let id = arg.get_id().as_str();
297            if matches.value_source(id) != Some(ValueSource::CommandLine) {
298                continue;
299            }
300            let Some(long) = arg.get_long() else { continue };
301            match matches.get_raw(id) {
302                Some(values) => {
303                    out.extend(values.map(|v| format!("-{long}={}", v.to_string_lossy())));
304                }
305                None => out.push(format!("-{long}")),
306            }
307        }
308        out
309    }
310}
311
312#[derive(Clone, Debug, Default)]
313pub struct FluxFlags(pub Vec<String>);
314
315impl FromArgMatches for FluxFlags {
316    fn from_arg_matches(m: &ArgMatches) -> Result<Self, clap::Error> {
317        Ok(FluxFlags(Flags::rustflags(m)))
318    }
319    fn update_from_arg_matches(&mut self, m: &ArgMatches) -> Result<(), clap::Error> {
320        self.0 = Flags::rustflags(m);
321        Ok(())
322    }
323}
324
325impl Args for FluxFlags {
326    fn augment_args(cmd: Command) -> Command {
327        Flags::augment_args(cmd)
328    }
329    fn augment_args_for_update(cmd: Command) -> Command {
330        Flags::augment_args_for_update(cmd)
331    }
332}
333
334pub(crate) static FLAGS: LazyLock<Flags> = LazyLock::new(|| {
335    let mut flags = Flags::default();
336    let mut includes: Vec<String> = Vec::new();
337    let mut trusteds: Vec<String> = Vec::new();
338    let mut trusted_impls: Vec<String> = Vec::new();
339    for arg in env::args() {
340        let Some((key, value)) = parse_flux_arg(&arg) else { continue };
341
342        let result = match key {
343            "log-dir" => parse_path_buf(&mut flags.log_dir, value),
344            "lean-dir" => parse_path_buf(&mut flags.lean_dir, value),
345            "lean-project" => parse_string(&mut flags.lean_project, value),
346            "dump-dep-graph" => parse_bool(&mut flags.dump_dep_graph, value),
347            "dump-constraint" => parse_bool(&mut flags.dump_constraint, value),
348            "dump-checker-trace" => parse_opt_level(&mut flags.dump_checker_trace, value),
349            "dump-fhir" => parse_bool(&mut flags.dump_fhir, value),
350            "dump-rty" => parse_bool(&mut flags.dump_rty, value),
351            "catch-bugs" => parse_bool(&mut flags.catch_bugs, value),
352            "pointer-width" => parse_pointer_width(&mut flags.pointer_width, value),
353            "check-overflow" => parse_overflow(&mut flags.check_overflow, value),
354            "allow-raw-deref" => parse_raw_deref(&mut flags.allow_raw_deref, value),
355            "uif-ops" => parse_uif_ops(&mut flags.uif_ops, value),
356            "scrape-quals" => parse_bool(&mut flags.scrape_quals, value),
357            "fixpoint-timeout" => parse_opt_u64(&mut flags.fixpoint_timeout, value),
358            "allow-uninterpreted-cast" => parse_bool(&mut flags.allow_uninterpreted_cast, value),
359            "solver" => parse_solver(&mut flags.solver, value),
360            "annots" => parse_bool(&mut flags.annots, value),
361            "timings" => parse_bool(&mut flags.timings, value),
362            "summary" => parse_bool(&mut flags.summary, value),
363            "cache" => parse_opt_path_buf(&mut flags.cache, value),
364            "include" => parse_opt_include(&mut includes, value),
365            "include-trusted" => parse_opt_include(&mut trusteds, value),
366            "include-trusted-impl" => parse_opt_include(&mut trusted_impls, value),
367            "verify" => parse_bool(&mut flags.verify, value),
368            "full-compilation" => parse_bool(&mut flags.full_compilation, value),
369            "sysroot" => parse_opt_path_buf(&mut flags.sysroot, value),
370            "trusted" => parse_bool(&mut flags.trusted_default, value),
371            "ignore" => parse_bool(&mut flags.ignore_default, value),
372            "lean" => parse_lean_mode(&mut flags.lean, value),
373            "no-panic" => parse_bool(&mut flags.no_panic, value),
374            "std-extern-specs" => parse_bool(&mut flags.std_extern_specs, value),
375            "flux-verbose" => parse_bool(&mut flags.flux_verbose, value),
376            "suggestions" => parse_bool(&mut flags.suggestions, value),
377            "rerun-hint" => parse_bool(&mut flags.rerun_hint, value),
378            _ => {
379                eprintln!("error: unknown flux option: `{key}`");
380                process::exit(EXIT_FAILURE);
381            }
382        };
383        if let Err(reason) = result {
384            eprintln!("error: incorrect value for flux option `{key}` - `{reason}`");
385            process::exit(1);
386        }
387    }
388    if !includes.is_empty() {
389        let include = IncludePattern::new(includes).unwrap_or_else(|err| {
390            eprintln!("error: invalid include pattern: {err}");
391            process::exit(1);
392        });
393        flags.include = Some(include);
394    }
395    if !trusteds.is_empty() {
396        let trusted = IncludePattern::new(trusteds).unwrap_or_else(|err| {
397            eprintln!("error: invalid trusted pattern: {err}");
398            process::exit(1);
399        });
400        flags.include_trusted = Some(trusted);
401    }
402    if !trusted_impls.is_empty() {
403        let trusted_impl = IncludePattern::new(trusted_impls).unwrap_or_else(|err| {
404            eprintln!("error: invalid trusted-impl pattern: {err}");
405            process::exit(1);
406        });
407        flags.include_trusted_impl = Some(trusted_impl);
408    }
409    flags
410});
411
412pub fn is_flux_arg(arg: &str) -> bool {
413    parse_flux_arg(arg).is_some()
414}
415
416fn parse_flux_arg(arg: &str) -> Option<(&str, Option<&str>)> {
417    let arg = arg.strip_prefix(FLUX_FLAG_PREFIX)?;
418    if arg.is_empty() {
419        return None;
420    }
421    if let Some((k, v)) = arg.split_once('=') { Some((k, Some(v))) } else { Some((arg, None)) }
422}
423
424fn parse_bool(slot: &mut bool, v: Option<&str>) -> Result<(), &'static str> {
425    match v {
426        Some("y") | Some("yes") | Some("on") | Some("true") | None => {
427            *slot = true;
428            Ok(())
429        }
430        Some("n") | Some("no") | Some("off") | Some("false") => {
431            *slot = false;
432            Ok(())
433        }
434        _ => {
435            Err(
436                "expected no value or one of `y`, `yes`, `on`, `true`, `n`, `no`, `off`, or `false`",
437            )
438        }
439    }
440}
441
442fn parse_string(slot: &mut String, v: Option<&str>) -> Result<(), &'static str> {
443    match v {
444        Some(s) => {
445            *slot = s.to_string();
446            Ok(())
447        }
448        None => Err("expected a string"),
449    }
450}
451
452fn parse_opt_u64(slot: &mut Option<u64>, v: Option<&str>) -> Result<(), &'static str> {
453    match v.and_then(|s| s.parse().ok()) {
454        Some(n) => {
455            *slot = Some(n);
456            Ok(())
457        }
458        None => Err("expected a non-negative integer"),
459    }
460}
461
462fn parse_path_buf(slot: &mut PathBuf, v: Option<&str>) -> Result<(), &'static str> {
463    match v {
464        Some(s) => {
465            *slot = PathBuf::from(s);
466            Ok(())
467        }
468        None => Err("expected a path"),
469    }
470}
471
472fn parse_pointer_width(slot: &mut PointerWidth, v: Option<&str>) -> Result<(), &'static str> {
473    match v {
474        Some(s) => {
475            *slot = s.parse()?;
476            Ok(())
477        }
478        _ => Err(PointerWidth::ERROR),
479    }
480}
481
482fn parse_lean_mode(slot: &mut LeanMode, v: Option<&str>) -> Result<(), &'static str> {
483    match v {
484        Some(s) => {
485            *slot = s.parse()?;
486            Ok(())
487        }
488        _ => Err(LeanMode::ERROR),
489    }
490}
491
492fn parse_overflow(slot: &mut OverflowMode, v: Option<&str>) -> Result<(), &'static str> {
493    match v {
494        Some(s) => {
495            *slot = s.parse()?;
496            Ok(())
497        }
498        _ => Err(OverflowMode::ERROR),
499    }
500}
501
502fn parse_uif_ops(slot: &mut UifOps, v: Option<&str>) -> Result<(), &'static str> {
503    match v {
504        Some(s) => {
505            *slot = s.parse()?;
506            Ok(())
507        }
508        _ => Err(UifOps::ERROR),
509    }
510}
511
512fn parse_raw_deref(slot: &mut RawDerefMode, v: Option<&str>) -> Result<(), &'static str> {
513    match v {
514        Some(s) => {
515            *slot = s.parse()?;
516            Ok(())
517        }
518        _ => Err(RawDerefMode::ERROR),
519    }
520}
521
522fn parse_solver(slot: &mut SmtSolver, v: Option<&str>) -> Result<(), &'static str> {
523    match v {
524        Some(s) => {
525            *slot = s.parse()?;
526            Ok(())
527        }
528        _ => Err(SmtSolver::ERROR),
529    }
530}
531
532fn parse_opt_path_buf(slot: &mut Option<PathBuf>, v: Option<&str>) -> Result<(), &'static str> {
533    match v {
534        Some(s) => {
535            *slot = Some(PathBuf::from(s));
536            Ok(())
537        }
538        None => Err("expected a path"),
539    }
540}
541
542fn parse_opt_level(slot: &mut Option<Level>, v: Option<&str>) -> Result<(), &'static str> {
543    match v {
544        Some(s) => {
545            *slot = Some(Level::from_str(s).map_err(|_| "invalid level")?);
546            Ok(())
547        }
548        None => Err("a level"),
549    }
550}
551
552fn parse_opt_include(slot: &mut Vec<String>, v: Option<&str>) -> Result<(), &'static str> {
553    if let Some(include) = v {
554        slot.push(include.to_string());
555    }
556    Ok(())
557}