Skip to main content

flux_config/
lib.rs

1use globset::{Glob, GlobSet, GlobSetBuilder};
2pub use toml::Value;
3use tracing::Level;
4pub mod flags;
5
6use std::{
7    fmt,
8    io::Read,
9    path::{Path, PathBuf},
10    str::FromStr,
11    sync::LazyLock,
12    time::Duration,
13};
14
15use flags::FLAGS;
16use serde::Deserialize;
17
18pub fn dump_checker_trace_info() -> bool {
19    match FLAGS.dump_checker_trace {
20        Some(l) => Level::INFO <= l,
21        None => false,
22    }
23}
24
25pub fn dump_checker_trace() -> Option<Level> {
26    FLAGS.dump_checker_trace
27}
28
29pub fn dump_dep_graph() -> bool {
30    FLAGS.dump_dep_graph
31}
32
33pub fn dump_constraint() -> bool {
34    FLAGS.dump_constraint
35}
36
37pub fn dump_fhir() -> bool {
38    FLAGS.dump_fhir
39}
40
41pub fn dump_rty() -> bool {
42    FLAGS.dump_rty
43}
44
45pub fn pointer_width() -> PointerWidth {
46    FLAGS.pointer_width
47}
48
49pub fn log_dir() -> &'static PathBuf {
50    &FLAGS.log_dir
51}
52
53pub fn lean_dir() -> &'static PathBuf {
54    &FLAGS.lean_dir
55}
56
57pub fn lean_project() -> &'static str {
58    &FLAGS.lean_project
59}
60
61pub fn is_cache_enabled() -> bool {
62    FLAGS.cache.is_some()
63}
64
65pub fn trusted_default() -> bool {
66    FLAGS.trusted_default
67}
68
69pub fn ignore_default() -> bool {
70    FLAGS.ignore_default
71}
72
73pub fn lean() -> LeanMode {
74    FLAGS.lean
75}
76
77pub fn cache_dir() -> Option<&'static Path> {
78    FLAGS.cache.as_deref()
79}
80
81pub fn include_pattern() -> Option<&'static IncludePattern> {
82    FLAGS.include.as_ref()
83}
84
85pub fn trusted_pattern() -> Option<&'static IncludePattern> {
86    FLAGS.include_trusted.as_ref()
87}
88
89pub fn trusted_impl_pattern() -> Option<&'static IncludePattern> {
90    FLAGS.include_trusted_impl.as_ref()
91}
92
93fn check_overflow() -> OverflowMode {
94    FLAGS.check_overflow
95}
96
97fn uif_ops() -> UifOps {
98    FLAGS.uif_ops
99}
100
101fn allow_raw_deref() -> RawDerefMode {
102    FLAGS.allow_raw_deref
103}
104
105pub fn allow_uninterpreted_cast() -> bool {
106    FLAGS.allow_uninterpreted_cast
107}
108
109fn scrape_quals() -> bool {
110    FLAGS.scrape_quals
111}
112
113pub fn no_panic() -> bool {
114    FLAGS.no_panic
115}
116
117pub fn sysroot() -> Option<PathBuf> {
118    if let Some(p) = FLAGS.sysroot.as_deref() {
119        Some(p.to_path_buf())
120    } else {
121        let exe = std::env::current_exe().ok()?;
122        exe.parent().map(|p| p.to_path_buf())
123    }
124}
125
126fn solver() -> SmtSolver {
127    FLAGS.solver
128}
129
130pub fn catch_bugs() -> bool {
131    FLAGS.catch_bugs
132}
133
134pub fn annots() -> bool {
135    FLAGS.annots
136}
137
138pub fn timings() -> bool {
139    FLAGS.timings
140}
141
142pub fn verify() -> bool {
143    FLAGS.verify
144}
145
146pub fn summary() -> bool {
147    FLAGS.summary
148}
149
150pub fn full_compilation() -> bool {
151    FLAGS.full_compilation
152}
153
154pub fn std_extern_specs() -> bool {
155    FLAGS.std_extern_specs
156}
157
158pub fn verbose() -> bool {
159    FLAGS.flux_verbose
160}
161
162pub fn suggestions() -> bool {
163    FLAGS.suggestions
164}
165
166pub fn rerun_hint() -> bool {
167    FLAGS.rerun_hint
168}
169
170pub fn fixpoint_timeout() -> Option<Duration> {
171    FLAGS.fixpoint_timeout.map(Duration::from_secs)
172}
173
174/// Whether the driver is running under `cargo flux` (which sets `FLUX_CARGO=1`), as opposed to a
175/// direct `flux`/`flux-driver` invocation. Used to decide whether to emit the re-run hint.
176pub fn inside_cargo() -> bool {
177    std::env::var_os("FLUX_CARGO").is_some()
178}
179
180#[derive(Clone, Debug, Deserialize)]
181#[serde(try_from = "String")]
182pub struct Pos {
183    pub file: String,
184    pub line: usize,
185    pub column: usize,
186}
187
188impl FromStr for Pos {
189    type Err = &'static str;
190
191    fn from_str(s: &str) -> Result<Self, Self::Err> {
192        let s = s.trim();
193        let parts: Vec<&str> = s.split(':').collect();
194        if parts.len() != 3 {
195            return Err("span format should be '<file>:<line>:<column>'");
196        }
197        let file = parts[0].to_string();
198        let line = parts[1]
199            .parse::<usize>()
200            .map_err(|_| "invalid line number")?;
201        let column = parts[2]
202            .parse::<usize>()
203            .map_err(|_| "invalid column number")?;
204        Ok(Pos { file, line, column })
205    }
206}
207
208impl TryFrom<String> for Pos {
209    type Error = &'static str;
210
211    fn try_from(value: String) -> Result<Self, Self::Error> {
212        value.parse()
213    }
214}
215
216impl fmt::Display for IncludePattern {
217    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
218        write!(f, "[")?;
219        write!(f, "glob:{:?},", self.glob)?;
220        for def in &self.defs {
221            write!(f, "def:{},", def)?;
222        }
223        for pos in &self.spans {
224            write!(f, "span:{}:{}:{}", pos.file, pos.line, pos.column)?;
225        }
226        write!(f, "]")?;
227        Ok(())
228    }
229}
230/// This specifies which `DefId` should be checked. It can be specified via multiple patterns
231/// of the form `-Finclude=<pattern>` and the `DefId` is checked if it matches *any* of the patterns.
232/// Patterns are checked relative to the current working directory.
233#[derive(Clone)]
234pub struct IncludePattern {
235    /// files matching the glob pattern, e.g. `glob:src/ascii/*.rs` to check all files in the `ascii` module
236    pub glob: GlobSet,
237    /// defs (`fn`, `enum`, ...) matching the given function name as a substring, e.g. `def:watermelon`
238    pub defs: Vec<String>,
239    /// fn whose implementation overlaps the file, line, e.g. `span:tests/tests/pos/detached/detach00.rs:13:3`
240    pub spans: Vec<Pos>,
241}
242
243impl IncludePattern {
244    fn new(includes: Vec<String>) -> Result<Self, String> {
245        let mut defs = Vec::new();
246        let mut spans = Vec::new();
247        let mut glob = GlobSetBuilder::new();
248        for include in includes {
249            if let Some(suffix) = include.strip_prefix("def:") {
250                defs.push(suffix.to_string());
251            } else if let Some(suffix) = include.strip_prefix("span:") {
252                spans.push(Pos::from_str(suffix)?);
253            } else {
254                let suffix = include.strip_prefix("glob:").unwrap_or(&include);
255                let glob_pattern = Glob::new(suffix.trim()).map_err(|_| "invalid glob pattern")?;
256                glob.add(glob_pattern);
257            }
258        }
259        let glob = glob.build().map_err(|_| "failed to build glob set")?;
260        Ok(IncludePattern { glob, defs, spans })
261    }
262}
263
264impl FromStr for IncludePattern {
265    type Err = String;
266
267    fn from_str(s: &str) -> Result<Self, Self::Err> {
268        Self::new(vec![s.to_string()])
269    }
270}
271
272#[derive(Clone, Copy, Debug, Deserialize, Default)]
273#[serde(try_from = "String")]
274pub enum LeanMode {
275    /// Don't do anything with lean
276    #[default]
277    Off,
278    /// Emit the lean definitions and VCs for externally proven items
279    Emit,
280    /// (Emit and) Check the lean definitions and VCs for externally proven items
281    Check,
282}
283
284impl LeanMode {
285    const ERROR: &'static str = "expected one of `emit`, or `check`";
286
287    pub fn is_emit(self) -> bool {
288        matches!(self, LeanMode::Emit)
289    }
290
291    pub fn is_check(self) -> bool {
292        matches!(self, LeanMode::Check)
293    }
294}
295
296impl FromStr for LeanMode {
297    type Err = &'static str;
298
299    fn from_str(s: &str) -> Result<Self, Self::Err> {
300        let s = s.to_ascii_lowercase();
301        match s.as_str() {
302            "off" => Ok(LeanMode::Off),
303            "emit" => Ok(LeanMode::Emit),
304            "check" => Ok(LeanMode::Check),
305            _ => Err(Self::ERROR),
306        }
307    }
308}
309
310impl TryFrom<String> for LeanMode {
311    type Error = &'static str;
312
313    fn try_from(value: String) -> Result<Self, Self::Error> {
314        value.parse()
315    }
316}
317
318impl fmt::Display for LeanMode {
319    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
320        match self {
321            LeanMode::Off => write!(f, "off"),
322            LeanMode::Emit => write!(f, "emit"),
323            LeanMode::Check => write!(f, "check"),
324        }
325    }
326}
327
328/// A binary operator that can be encoded as an uninterpreted function, see [`InferOpts::uif_ops`].
329/// These mirror the arithmetic and bitwise operators of the surface syntax.
330#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
331pub enum UifOp {
332    Add,
333    Sub,
334    Mul,
335    Div,
336    Mod,
337    BitAnd,
338    BitOr,
339    BitXor,
340    BitShl,
341    BitShr,
342}
343
344impl UifOp {
345    /// Maps the surface syntax (token) of each operator to the operator.
346    const TOKENS: [(&'static str, UifOp); 10] = [
347        ("+", UifOp::Add),
348        ("-", UifOp::Sub),
349        ("*", UifOp::Mul),
350        ("/", UifOp::Div),
351        ("%", UifOp::Mod),
352        ("&", UifOp::BitAnd),
353        ("|", UifOp::BitOr),
354        ("^", UifOp::BitXor),
355        ("<<", UifOp::BitShl),
356        (">>", UifOp::BitShr),
357    ];
358
359    /// The operator written as `token` in the surface syntax, if any
360    pub fn from_token(token: &str) -> Option<UifOp> {
361        Self::TOKENS
362            .iter()
363            .find_map(|(tok, op)| (*tok == token).then_some(*op))
364    }
365
366    /// The surface syntax of the operator
367    fn token(self) -> &'static str {
368        match self {
369            UifOp::Add => "+",
370            UifOp::Sub => "-",
371            UifOp::Mul => "*",
372            UifOp::Div => "/",
373            UifOp::Mod => "%",
374            UifOp::BitAnd => "&",
375            UifOp::BitOr => "|",
376            UifOp::BitXor => "^",
377            UifOp::BitShl => "<<",
378            UifOp::BitShr => ">>",
379        }
380    }
381
382    fn bit(self) -> u16 {
383        1 << (self as u16)
384    }
385}
386
387/// A set of [`UifOp`]s. It is a bitset so [`InferOpts`] can be `Copy`. It is written as a comma
388/// separated list of operators, e.g., `*,/,%`.
389#[derive(Clone, Copy, PartialEq, Eq, Default, Deserialize)]
390#[serde(try_from = "String")]
391pub struct UifOps(u16);
392
393impl UifOps {
394    const ERROR: &'static str =
395        "expected a comma separated list of `+`, `-`, `*`, `/`, `%`, `&`, `|`, `^`, `<<`, or `>>`";
396
397    pub fn contains(self, op: UifOp) -> bool {
398        self.0 & op.bit() != 0
399    }
400
401    pub fn is_empty(self) -> bool {
402        self.0 == 0
403    }
404
405    pub fn insert(&mut self, op: UifOp) {
406        self.0 |= op.bit();
407    }
408
409    fn iter(self) -> impl Iterator<Item = UifOp> {
410        UifOp::TOKENS
411            .into_iter()
412            .map(|(_, op)| op)
413            .filter(move |op| self.contains(*op))
414    }
415}
416
417impl FromStr for UifOps {
418    type Err = &'static str;
419
420    fn from_str(s: &str) -> Result<Self, Self::Err> {
421        let mut ops = UifOps::default();
422        let tokens = s
423            .split(',')
424            .map(str::trim)
425            .filter(|token| !token.is_empty());
426        for token in tokens {
427            let op = UifOp::from_token(token).ok_or(Self::ERROR)?;
428            ops.insert(op);
429        }
430        Ok(ops)
431    }
432}
433
434impl TryFrom<String> for UifOps {
435    type Error = &'static str;
436
437    fn try_from(value: String) -> Result<Self, Self::Error> {
438        value.parse()
439    }
440}
441
442impl fmt::Display for UifOps {
443    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
444        let tokens: Vec<_> = self.iter().map(UifOp::token).collect();
445        write!(f, "{}", tokens.join(","))
446    }
447}
448
449impl fmt::Debug for UifOps {
450    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
451        write!(f, "UifOps({self})")
452    }
453}
454
455#[derive(Clone, Copy, Debug, Deserialize, Default)]
456#[serde(try_from = "String")]
457pub enum OverflowMode {
458    /// Strict-Underflow, No overflow checking
459    #[default]
460    None,
461    /// Lazy underflow, Lazy overflow checking; lose all information
462    /// unless values are known to be in valid range
463    Lazy,
464    /// Strict underflow, Lazy overflow checking; always check
465    /// unsignedness (non-negativity) but lazy for upper-bound
466    StrictUnder,
467    /// Strict underflow, Strict overflow checking; always check
468    /// values in valid range for type
469    Strict,
470}
471
472impl OverflowMode {
473    const ERROR: &'static str = "expected one of `none`, `lazy`, or `strict`";
474}
475impl FromStr for OverflowMode {
476    type Err = &'static str;
477
478    fn from_str(s: &str) -> Result<Self, Self::Err> {
479        let s = s.to_ascii_lowercase();
480        match s.as_str() {
481            "none" => Ok(OverflowMode::None),
482            "lazy" => Ok(OverflowMode::Lazy),
483            "strict" => Ok(OverflowMode::Strict),
484            "strict-under" => Ok(OverflowMode::StrictUnder),
485            _ => Err(Self::ERROR),
486        }
487    }
488}
489
490impl TryFrom<String> for OverflowMode {
491    type Error = &'static str;
492
493    fn try_from(value: String) -> Result<Self, Self::Error> {
494        value.parse()
495    }
496}
497
498impl fmt::Display for OverflowMode {
499    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
500        match self {
501            OverflowMode::None => write!(f, "none"),
502            OverflowMode::Lazy => write!(f, "lazy"),
503            OverflowMode::Strict => write!(f, "strict"),
504            OverflowMode::StrictUnder => write!(f, "strict-under"),
505        }
506    }
507}
508
509#[derive(Clone, Copy, Debug, Deserialize, Default)]
510#[serde(try_from = "String")]
511pub enum RawDerefMode {
512    /// Don't allow raw pointer dereferences (default)
513    #[default]
514    None,
515    /// Allow raw pointer dereferences
516    Ok,
517}
518
519impl RawDerefMode {
520    const ERROR: &'static str = "expected one of `none` or `ok`";
521}
522
523impl FromStr for RawDerefMode {
524    type Err = &'static str;
525
526    fn from_str(s: &str) -> Result<Self, Self::Err> {
527        let s = s.to_ascii_lowercase();
528        match s.as_str() {
529            "none" => Ok(RawDerefMode::None),
530            "ok" => Ok(RawDerefMode::Ok),
531            _ => Err(Self::ERROR),
532        }
533    }
534}
535
536impl TryFrom<String> for RawDerefMode {
537    type Error = &'static str;
538
539    fn try_from(value: String) -> Result<Self, Self::Error> {
540        value.parse()
541    }
542}
543
544impl fmt::Display for RawDerefMode {
545    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
546        match self {
547            RawDerefMode::None => write!(f, "none"),
548            RawDerefMode::Ok => write!(f, "ok"),
549        }
550    }
551}
552
553#[derive(Clone, Copy, Debug, Deserialize, Default)]
554#[serde(try_from = "String")]
555pub enum SmtSolver {
556    #[default]
557    Z3,
558    CVC5,
559}
560
561impl SmtSolver {
562    const ERROR: &'static str = "expected one of `z3` or `cvc5`";
563}
564
565impl FromStr for SmtSolver {
566    type Err = &'static str;
567
568    fn from_str(s: &str) -> Result<Self, Self::Err> {
569        let s = s.to_ascii_lowercase();
570        match s.as_str() {
571            "z3" => Ok(SmtSolver::Z3),
572            "cvc5" => Ok(SmtSolver::CVC5),
573            _ => Err(Self::ERROR),
574        }
575    }
576}
577
578impl TryFrom<String> for SmtSolver {
579    type Error = &'static str;
580
581    fn try_from(value: String) -> Result<Self, Self::Error> {
582        value.parse()
583    }
584}
585
586impl fmt::Display for SmtSolver {
587    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
588        match self {
589            SmtSolver::Z3 => write!(f, "z3"),
590            SmtSolver::CVC5 => write!(f, "cvc5"),
591        }
592    }
593}
594
595/// Options that change the behavior of refinement type inference locally
596#[derive(Clone, Copy, Debug)]
597pub struct InferOpts {
598    /// Enable overflow checking. This affects the signature of primitive operations and the
599    /// invariants assumed for primitive types.
600    pub check_overflow: OverflowMode,
601    /// Whether qualifiers should be scraped from the constraint.
602    pub scrape_quals: bool,
603    pub solver: SmtSolver,
604    /// Whether to allow uninterpreted casts (e.g., from some random `S` to `int`).
605    pub allow_uninterpreted_cast: bool,
606    /// Whether to allow raw pointer dereferences.
607    pub allow_raw_deref: RawDerefMode,
608    /// Binary operators that are encoded as uninterpreted functions (e.g. to avoid nonlinear arithmetic).
609    pub uif_ops: UifOps,
610}
611
612impl From<PartialInferOpts> for InferOpts {
613    fn from(opts: PartialInferOpts) -> Self {
614        InferOpts {
615            check_overflow: opts.check_overflow.unwrap_or_else(check_overflow),
616            scrape_quals: opts.scrape_quals.unwrap_or_else(scrape_quals),
617            solver: opts.solver.unwrap_or_else(solver),
618            allow_uninterpreted_cast: opts
619                .allow_uninterpreted_cast
620                .unwrap_or_else(allow_uninterpreted_cast),
621            allow_raw_deref: opts.allow_raw_deref.unwrap_or_else(allow_raw_deref),
622            uif_ops: opts.uif_ops.unwrap_or_else(uif_ops),
623        }
624    }
625}
626
627#[derive(Clone, Copy, Default, Deserialize, Debug)]
628pub struct PartialInferOpts {
629    pub check_overflow: Option<OverflowMode>,
630    pub scrape_quals: Option<bool>,
631    pub solver: Option<SmtSolver>,
632    pub allow_uninterpreted_cast: Option<bool>,
633    pub allow_raw_deref: Option<RawDerefMode>,
634    pub uif_ops: Option<UifOps>,
635}
636
637impl PartialInferOpts {
638    pub fn merge(&mut self, other: &Self) {
639        self.check_overflow = self.check_overflow.or(other.check_overflow);
640        self.allow_uninterpreted_cast = self
641            .allow_uninterpreted_cast
642            .or(other.allow_uninterpreted_cast);
643        self.scrape_quals = self.scrape_quals.or(other.scrape_quals);
644        self.solver = self.solver.or(other.solver);
645        self.allow_raw_deref = self.allow_raw_deref.or(other.allow_raw_deref);
646        self.uif_ops = self.uif_ops.or(other.uif_ops);
647    }
648}
649
650#[derive(Copy, Clone, Deserialize, Default)]
651pub enum PointerWidth {
652    W32,
653    #[default]
654    W64,
655}
656
657impl PointerWidth {
658    const ERROR: &str = "pointer width must be 32 or 64";
659
660    pub fn bits(self) -> u64 {
661        match self {
662            PointerWidth::W32 => 32,
663            PointerWidth::W64 => 64,
664        }
665    }
666}
667
668impl FromStr for PointerWidth {
669    type Err = &'static str;
670
671    fn from_str(s: &str) -> Result<Self, Self::Err> {
672        match s {
673            "32" => Ok(PointerWidth::W32),
674            "64" => Ok(PointerWidth::W64),
675            _ => Err(Self::ERROR),
676        }
677    }
678}
679
680fn config_path() -> Option<PathBuf> {
681    // find config file in current or parent directories
682    let mut path = std::env::current_dir().unwrap();
683    loop {
684        for name in ["flux.toml", ".flux.toml"] {
685            let file = path.join(name);
686            if file.exists() {
687                return Some(file);
688            }
689        }
690        if !path.pop() {
691            return None;
692        }
693    }
694}
695
696pub static CONFIG_FILE: LazyLock<Value> = LazyLock::new(|| {
697    if let Some(path) = config_path() {
698        let mut file = std::fs::File::open(path).unwrap();
699        let mut contents = String::new();
700        file.read_to_string(&mut contents).unwrap();
701        toml::from_str(&contents).unwrap()
702    } else {
703        toml::from_str("").unwrap()
704    }
705});