flux_config/
flags.rs

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