cverif 0.0.3

Verifies that compiled machine code faithfully matches its C source
Documentation
//! C front end: preprocessor, parser, type checker and CFG lowering.

pub mod ast;
pub mod exec;
pub mod lex;
pub mod lower;
pub mod parse;
pub mod target;

use std::path::{Path, PathBuf};

/// Front-end options.
#[derive(Default, Clone, Debug)]
pub struct Options {
    pub include_dirs: Vec<PathBuf>,
    pub defines: Vec<(String, String)>,
    /// Macros undefined with `-U` (applied after `defines`).
    pub undefines: Vec<String>,
    /// Files included before each source file (`-include`).
    pub forced_includes: Vec<PathBuf>,
    /// Size of enumerated types: `Some(true)` the smallest type that fits (`-fshort-enums`),
    /// `Some(false)` at least `int`.  `None` means GCC's bare-metal ARM default, short enums.
    pub short_enums: Option<bool>,
    /// The compiler and architecture whose predefined macros the preprocessor provides.
    pub target: target::Target,
}

impl Options {
    /// Options matching the ABI variant the binary records in its build attributes.
    pub fn for_image(image: &crate::image::Image) -> Options {
        Options {
            short_enums: image.short_enums,
            target: target::Target::for_image(image),
            ..Default::default()
        }
    }
}

/// Parse a set of C translation units into one program.
pub fn parse_files(paths: &[PathBuf], opts: &Options) -> Result<ast::Program, String> {
    parse_units(paths, opts).map_err(|(_, e)| e)
}

/// Like [`parse_files`], but a translation unit the front end cannot parse is left out
/// instead of failing the whole run: its functions simply have no source.  Returns the
/// program and every file left out with its error.  Nothing of a failed unit is kept (the
/// remaining files are parsed afresh), so no half-read declaration can influence a proof.
pub fn parse_files_lenient(
    paths: &[PathBuf],
    opts: &Options,
) -> Result<(ast::Program, Vec<(PathBuf, String)>), String> {
    let mut paths = paths.to_vec();
    let mut skipped = Vec::new();
    loop {
        match parse_units(&paths, opts) {
            Ok(prog) => return Ok((prog, skipped)),
            Err((Some(i), e)) => skipped.push((paths.remove(i), e)),
            Err((None, e)) => return Err(e),
        }
    }
}

/// On failure, the index of the file at fault (none when the options themselves are wrong).
fn parse_units(paths: &[PathBuf], opts: &Options) -> Result<ast::Program, (Option<usize>, String)> {
    let mut prog = ast::Program::new();
    prog.int_enums = opts.short_enums == Some(false);
    let mut externs = parse::Externs::default();
    let target = opts.target.predefines();
    for (index, path) in paths.iter().enumerate() {
        let at = Some(index);
        let defs: Vec<(String, Option<String>)> = opts
            .defines
            .iter()
            .map(|(k, v)| (k.clone(), Some(v.clone())))
            .chain(opts.undefines.iter().map(|k| (k.clone(), None)))
            .collect();
        let mut pp =
            lex::Preprocessor::new(opts.include_dirs.clone(), &target, &defs).map_err(|e| (None, fmt_err(&[], &e)))?;
        // File ids are per translation unit; rebase them onto the program-wide table.
        let base = prog.files.len() as u16;
        let toks = pp
            .preprocess_file(path, &opts.forced_includes)
            .map_err(|e| (at, fmt_err(&pp.files, &e)))?;
        let files: Vec<PathBuf> = pp.files.clone();
        let toks = toks
            .into_iter()
            .map(|mut t| {
                t.loc.file += base;
                t
            })
            .collect();
        prog.files.extend(files.iter().map(|f| f.display().to_string()));
        parse::parse_unit(&mut prog, &mut externs, toks).map_err(|mut e| {
            e.loc.file -= base;
            (at, fmt_err(&files, &e))
        })?;
        // Everything created while parsing this file belongs to its translation unit.
        let unit = prog.units.len() as u16;
        prog.units.push(path.display().to_string());
        prog.func_unit.resize(prog.funcs.len(), unit);
        prog.global_unit.resize(prog.globals.len(), unit);
    }
    Ok(prog)
}

fn fmt_err(files: &[PathBuf], e: &lex::CError) -> String {
    let f = files
        .get(e.loc.file as usize)
        .map(|p| p.display().to_string())
        .unwrap_or_else(|| "<input>".into());
    format!("{f}:{}: {}", e.loc.line, e.msg)
}

/// Collect the C source files under a path (a file or a directory tree).
pub fn collect_sources(root: &Path) -> std::io::Result<Vec<PathBuf>> {
    let mut out = Vec::new();
    if root.is_file() {
        out.push(root.to_path_buf());
        return Ok(out);
    }
    let mut stack = vec![root.to_path_buf()];
    while let Some(dir) = stack.pop() {
        for ent in std::fs::read_dir(&dir)? {
            let p = ent?.path();
            if p.is_dir() {
                stack.push(p);
            } else if p.extension().is_some_and(|e| e == "c") {
                out.push(p);
            }
        }
    }
    out.sort();
    Ok(out)
}