flux_config/
flags.rs

1use std::{env, path::PathBuf, process, str::FromStr, sync::LazyLock};
2
3pub use toml::Value;
4use tracing::Level;
5
6use crate::{IncludePattern, LeanMode, OverflowMode, PointerWidth, SmtSolver};
7
8const FLUX_FLAG_PREFIX: &str = "-F";
9
10/// Exit status code used for invalid flags.
11pub const EXIT_FAILURE: i32 = 2;
12
13pub struct Flags {
14    /// Sets the directory to dump data. Defaults to `./log/`.
15    pub log_dir: PathBuf,
16    /// Sets the directory to put all the emitted lean definitions and verification conditions. Defaults to `./`.
17    pub lean_dir: PathBuf,
18    /// Name of the lean project. Defaults to `lean_proofs`.
19    pub lean_project: String,
20    /// If present, only check files matching the [`IncludePattern`] a glob pattern.
21    pub include: Option<IncludePattern>,
22    /// Set the pointer size (either `32` or `64`), used to determine if an integer cast is lossy
23    /// (default `64`).
24    pub pointer_width: PointerWidth,
25    /// If present switches on query caching and saves the cache in the provided path
26    pub cache: Option<PathBuf>,
27    /// Compute statistics about number and size of annotations. Dumps file to [`Self::log_dir`]
28    pub annots: bool,
29    /// Print statistics about time taken to analyze each fuction. Also dumps a file with the raw
30    /// times for each function.
31    pub timings: bool,
32    /// Print statistics about number of functions checked, trusted, etc.
33    pub summary: bool,
34    /// Default solver. Either `z3` or `cvc5`.
35    pub solver: SmtSolver,
36    /// Enables qualifier scrapping in fixpoint
37    pub scrape_quals: bool,
38    /// Enables uninterpreted casts
39    pub allow_uninterpreted_cast: bool,
40    /// Translates _monomorphic_ `defs` functions into SMT `define-fun` instead of inlining them
41    /// away inside `flux`.
42    pub smt_define_fun: bool,
43    /// If `strict` checks for over and underflow on arithmetic integer operations,
44    /// If `lazy` checks for underflow and loses information if possible overflow,
45    /// If `none` (default), it still checks for underflow on unsigned integer subtraction.
46    pub check_overflow: OverflowMode,
47    /// Dump constraints generated for each function (debugging)
48    pub dump_constraint: bool,
49    /// Saves the checker's trace (debugging)
50    pub dump_checker_trace: Option<tracing::Level>,
51    /// Saves the `fhir` for each item (debugging)
52    pub dump_fhir: bool,
53    /// Saves the the `fhir` (debugging)
54    pub dump_rty: bool,
55    /// Optimistically keeps running flux even after errors are found to get as many errors as possible
56    pub catch_bugs: bool,
57    /// Whether verification for the current crate is enabled. If false (the default), `flux-driver`
58    /// will behave exactly like `rustc`. This flag is managed by the `cargo flux` and `flux` binaries,
59    /// so you don't need to mess with it.
60    pub verify: bool,
61    /// If `true`, produce artifacts after analysis. This flag is managed by `cargo flux`, so you
62    /// don't typically have to set it manually.
63    pub full_compilation: bool,
64    /// 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.
65    pub trusted_default: bool,
66    /// 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.
67    pub ignore_default: bool,
68    pub lean: LeanMode,
69    /// If `true`, every function is implicitly labeled with a `no_panic` by default.
70    pub no_panic: bool,
71}
72
73impl Default for Flags {
74    fn default() -> Self {
75        Self {
76            log_dir: PathBuf::from("./log/"),
77            lean_dir: PathBuf::from("./"),
78            lean_project: "lean_proofs".to_string(),
79            dump_constraint: false,
80            dump_checker_trace: None,
81            dump_fhir: false,
82            dump_rty: false,
83            catch_bugs: false,
84            pointer_width: PointerWidth::default(),
85            include: None,
86            cache: None,
87            check_overflow: OverflowMode::default(),
88            scrape_quals: false,
89            allow_uninterpreted_cast: false,
90            solver: SmtSolver::default(),
91            smt_define_fun: false,
92            annots: false,
93            timings: false,
94            summary: true,
95            verify: false,
96            full_compilation: false,
97            trusted_default: false,
98            ignore_default: false,
99            lean: LeanMode::default(),
100            no_panic: false,
101        }
102    }
103}
104
105pub(crate) static FLAGS: LazyLock<Flags> = LazyLock::new(|| {
106    let mut flags = Flags::default();
107    let mut includes: Vec<String> = Vec::new();
108    for arg in env::args() {
109        let Some((key, value)) = parse_flux_arg(&arg) else { continue };
110
111        let result = match key {
112            "log-dir" => parse_path_buf(&mut flags.log_dir, value),
113            "lean-dir" => parse_path_buf(&mut flags.lean_dir, value),
114            "lean-project" => parse_string(&mut flags.lean_project, value),
115            "dump-constraint" => parse_bool(&mut flags.dump_constraint, value),
116            "dump-checker-trace" => parse_opt_level(&mut flags.dump_checker_trace, value),
117            "dump-fhir" => parse_bool(&mut flags.dump_fhir, value),
118            "dump-rty" => parse_bool(&mut flags.dump_rty, value),
119            "catch-bugs" => parse_bool(&mut flags.catch_bugs, value),
120            "pointer-width" => parse_pointer_width(&mut flags.pointer_width, value),
121            "check-overflow" => parse_overflow(&mut flags.check_overflow, value),
122            "scrape-quals" => parse_bool(&mut flags.scrape_quals, value),
123            "allow-uninterpreted-cast" => parse_bool(&mut flags.allow_uninterpreted_cast, value),
124            "solver" => parse_solver(&mut flags.solver, value),
125            "smt-define-fun" => parse_bool(&mut flags.smt_define_fun, value),
126            "annots" => parse_bool(&mut flags.annots, value),
127            "timings" => parse_bool(&mut flags.timings, value),
128            "summary" => parse_bool(&mut flags.summary, value),
129            "cache" => parse_opt_path_buf(&mut flags.cache, value),
130            "include" => parse_opt_include(&mut includes, value),
131            "verify" => parse_bool(&mut flags.verify, value),
132            "full-compilation" => parse_bool(&mut flags.full_compilation, value),
133            "trusted" => parse_bool(&mut flags.trusted_default, value),
134            "ignore" => parse_bool(&mut flags.ignore_default, value),
135            "lean" => parse_lean_mode(&mut flags.lean, value),
136            "no-panic" => parse_bool(&mut flags.no_panic, value),
137            _ => {
138                eprintln!("error: unknown flux option: `{key}`");
139                process::exit(EXIT_FAILURE);
140            }
141        };
142        if let Err(reason) = result {
143            eprintln!("error: incorrect value for flux option `{key}` - `{reason}`");
144            process::exit(1);
145        }
146    }
147    if !includes.is_empty() {
148        let include = IncludePattern::new(includes).unwrap_or_else(|err| {
149            eprintln!("error: invalid include pattern: {err}");
150            process::exit(1);
151        });
152        flags.include = Some(include);
153    }
154    flags
155});
156
157pub fn is_flux_arg(arg: &str) -> bool {
158    parse_flux_arg(arg).is_some()
159}
160
161fn parse_flux_arg(arg: &str) -> Option<(&str, Option<&str>)> {
162    let arg = arg.strip_prefix(FLUX_FLAG_PREFIX)?;
163    if arg.is_empty() {
164        return None;
165    }
166    if let Some((k, v)) = arg.split_once('=') { Some((k, Some(v))) } else { Some((arg, None)) }
167}
168
169fn parse_bool(slot: &mut bool, v: Option<&str>) -> Result<(), &'static str> {
170    match v {
171        Some("y") | Some("yes") | Some("on") | Some("true") | None => {
172            *slot = true;
173            Ok(())
174        }
175        Some("n") | Some("no") | Some("off") | Some("false") => {
176            *slot = false;
177            Ok(())
178        }
179        _ => {
180            Err(
181                "expected no value or one of `y`, `yes`, `on`, `true`, `n`, `no`, `off`, or `false`",
182            )
183        }
184    }
185}
186
187fn parse_string(slot: &mut String, v: Option<&str>) -> Result<(), &'static str> {
188    match v {
189        Some(s) => {
190            *slot = s.to_string();
191            Ok(())
192        }
193        None => Err("a string"),
194    }
195}
196
197fn parse_path_buf(slot: &mut PathBuf, v: Option<&str>) -> Result<(), &'static str> {
198    match v {
199        Some(s) => {
200            *slot = PathBuf::from(s);
201            Ok(())
202        }
203        None => Err("a path"),
204    }
205}
206
207fn parse_pointer_width(slot: &mut PointerWidth, v: Option<&str>) -> Result<(), &'static str> {
208    match v {
209        Some(s) => {
210            *slot = s.parse()?;
211            Ok(())
212        }
213        _ => Err(PointerWidth::ERROR),
214    }
215}
216
217fn parse_lean_mode(slot: &mut LeanMode, v: Option<&str>) -> Result<(), &'static str> {
218    match v {
219        Some(s) => {
220            *slot = s.parse()?;
221            Ok(())
222        }
223        _ => Err(LeanMode::ERROR),
224    }
225}
226
227fn parse_overflow(slot: &mut OverflowMode, v: Option<&str>) -> Result<(), &'static str> {
228    match v {
229        Some(s) => {
230            *slot = s.parse()?;
231            Ok(())
232        }
233        _ => Err(OverflowMode::ERROR),
234    }
235}
236
237fn parse_solver(slot: &mut SmtSolver, v: Option<&str>) -> Result<(), &'static str> {
238    match v {
239        Some(s) => {
240            *slot = s.parse()?;
241            Ok(())
242        }
243        _ => Err(SmtSolver::ERROR),
244    }
245}
246
247fn parse_opt_path_buf(slot: &mut Option<PathBuf>, v: Option<&str>) -> Result<(), &'static str> {
248    match v {
249        Some(s) => {
250            *slot = Some(PathBuf::from(s));
251            Ok(())
252        }
253        None => Err("a path"),
254    }
255}
256
257fn parse_opt_level(slot: &mut Option<Level>, v: Option<&str>) -> Result<(), &'static str> {
258    match v {
259        Some(s) => {
260            *slot = Some(Level::from_str(s).map_err(|_| "invalid level")?);
261            Ok(())
262        }
263        None => Err("a level"),
264    }
265}
266
267fn parse_opt_include(slot: &mut Vec<String>, v: Option<&str>) -> Result<(), &'static str> {
268    if let Some(include) = v {
269        slot.push(include.to_string());
270    }
271    Ok(())
272}