Skip to main content

flux_bin/
lib.rs

1use anyhow::Context;
2use cargo_metadata::{Package, camino::Utf8Path};
3use flux_config::{LeanMode, OverflowMode, RawDerefMode, SmtSolver, UifOps};
4use serde::Deserialize;
5
6pub mod cargo_flux_opts;
7pub mod cargo_style;
8pub mod config;
9pub mod utils;
10
11/// The `[package.metadata.flux]` table in `Cargo.toml`.
12///
13/// The table describes properties of the crate, e.g., which files are verified and under which
14/// semantics. Settings controlling how Flux runs belong in `.flux/config.toml` (see [`config`]).
15#[derive(Deserialize, Debug, Default)]
16#[serde(default, deny_unknown_fields, rename_all = "kebab-case")]
17pub struct FluxMetadata {
18    /// Whether the package is checked by Flux
19    pub enabled: bool,
20    /// If present, only check files that match any of the glob patterns. Patterns are checked
21    /// relative to the location of the manifest file.
22    pub include: Option<Vec<String>>,
23    /// Overflow checking mode
24    pub check_overflow: Option<OverflowMode>,
25    /// If present, every function in the crate is implicitly labeled with a `no_panic` by default.
26    /// This means that the only way a function can panic is if it calls an external function
27    /// without this attribute.
28    pub no_panic: Option<bool>,
29    /// Enable uninterpreted casts
30    pub allow_uninterpreted_cast: Option<bool>,
31    /// Whether to allow raw pointer dereferences
32    pub allow_raw_deref: Option<RawDerefMode>,
33    /// Lean mode
34    pub lean: Option<LeanMode>,
35    /// The solver used to verify the crate
36    pub solver: Option<SmtSolver>,
37    /// Enable qualifier scrapping in fixpoint
38    pub scrape_quals: Option<bool>,
39    /// Binary operators to encode as uninterpreted functions
40    pub uif_ops: Option<UifOps>,
41    pub trusted: Trusted,
42    pub trusted_impl: TrustedImpl,
43    pub ignore: Ignore,
44}
45
46/// The `[package.metadata.flux.trusted]` table.
47#[derive(Deserialize, Debug, Default)]
48#[serde(default, deny_unknown_fields, rename_all = "kebab-case")]
49pub struct Trusted {
50    /// Whether items are trusted by default
51    pub default: Option<bool>,
52    /// If present, only consider `DefId` in files that match any of the glob patterns as trusted.
53    /// Patterns are checked relative to the location of the manifest file.
54    pub files: Option<Vec<String>>,
55}
56
57/// The `[package.metadata.flux.trusted-impl]` table.
58#[derive(Deserialize, Debug, Default)]
59#[serde(default, deny_unknown_fields, rename_all = "kebab-case")]
60pub struct TrustedImpl {
61    /// If present, only consider `DefId` in files that match any of the glob patterns as
62    /// trusted_impl. Patterns are checked relative to the location of the manifest file.
63    pub files: Option<Vec<String>>,
64}
65
66/// The `[package.metadata.flux.ignore]` table.
67#[derive(Deserialize, Debug, Default)]
68#[serde(default, deny_unknown_fields, rename_all = "kebab-case")]
69pub struct Ignore {
70    /// Whether items are ignored by default
71    pub default: Option<bool>,
72}
73
74impl FluxMetadata {
75    /// Reads the `[package.metadata.flux]` table of `package`.
76    pub fn from_package(package: &Package) -> anyhow::Result<FluxMetadata> {
77        let Some(value) = package.metadata.get("flux") else { return Ok(Self::default()) };
78        let context =
79            || format!("invalid `[package.metadata.flux]` in `{}`", package.manifest_path);
80        serde_json::from_value(value.clone()).with_context(context)
81    }
82
83    pub fn into_flags(
84        self,
85        include_pattern_prefix: Option<&Utf8Path>,
86        only_check: Option<&str>,
87    ) -> Vec<String> {
88        let mut flags = vec![];
89        if let Some(v) = self.solver {
90            flags.push(format!("-Fsolver={v}"));
91        }
92        if let Some(v) = self.check_overflow {
93            flags.push(format!("-Fcheck-overflow={v}"));
94        }
95        if let Some(v) = self.uif_ops {
96            flags.push(format!("-Fuif-ops={v}"));
97        }
98        if let Some(v) = self.lean {
99            flags.push(format!("-Flean={v}"));
100        }
101        if let Some(v) = self.scrape_quals {
102            flags.push(format!("-Fscrape-quals={v}"));
103        }
104        if let Some(v) = self.trusted.default {
105            flags.push(format!("-Ftrusted={v}"));
106        }
107        if let Some(v) = self.no_panic {
108            flags.push(format!("-Fno-panic={v}"));
109        }
110        if let Some(v) = self.ignore.default {
111            flags.push(format!("-Fignore={v}"));
112        }
113        if let Some(v) = self.allow_uninterpreted_cast {
114            flags.push(format!("-Fallow-uninterpreted-cast={v}"));
115        }
116        if let Some(v) = self.allow_raw_deref {
117            flags.push(format!("-Fallow-raw-deref={v}"));
118        }
119        if let Some(only_check) = only_check {
120            flags.push(format!("-Finclude={only_check}"));
121        } else if let Some(patterns) = self.include {
122            for pat in patterns {
123                if let Some(prefix) = include_pattern_prefix {
124                    flags.push(format!("-Finclude={}", prepend_prefix_to_pattern(prefix, &pat)));
125                } else {
126                    flags.push(format!("-Finclude={pat}"));
127                }
128            }
129        }
130        if let Some(patterns) = self.trusted.files {
131            for pat in patterns {
132                if let Some(glob_prefix) = include_pattern_prefix
133                    && !glob_prefix.as_str().is_empty()
134                {
135                    flags.push(format!("-Finclude-trusted={glob_prefix}/{pat}"));
136                } else {
137                    flags.push(format!("-Finclude-trusted={pat}"));
138                }
139            }
140        }
141        if let Some(patterns) = self.trusted_impl.files {
142            for pat in patterns {
143                if let Some(glob_prefix) = include_pattern_prefix
144                    && !glob_prefix.as_str().is_empty()
145                {
146                    flags.push(format!("-Finclude-trusted-impl={glob_prefix}/{pat}"));
147                } else {
148                    flags.push(format!("-Finclude-trusted-impl={pat}"));
149                }
150            }
151        }
152        flags
153    }
154}
155
156fn prepend_prefix_to_pattern(prefix: &Utf8Path, pat: &str) -> String {
157    // don't use the empty `prefix` as that makes the pattern hang off root!
158    if prefix.as_str().is_empty() {
159        return pat.to_string();
160    }
161    if pat.starts_with("def:") {
162        return pat.to_string();
163    }
164    // I haven't tested this on windows, but it should work because `globset`
165    // will normalize patterns to use `/` as separator.
166    if let Some(pat) = pat.strip_prefix("glob:") {
167        format!("glob:{prefix}/{pat}")
168    } else if let Some(pat) = pat.strip_prefix("span:") {
169        // span patterns are of the form `span:<file>:<line>:<column>""
170        format!("span:{prefix}/{pat}")
171    } else {
172        // no prefix defaults to glob patterns.
173        format!("{prefix}/{pat}")
174    }
175}