Skip to content

Building 70 Projects ranging from beginner to advanced so anyone can — learn from, build upon, use as a reference, or even copy directly. Owned by my cybersecurity company 👇

37.2 KB
Raw Blame
// ©AngelaMos | 2026
// complexity.rs

use std::collections::{BTreeMap, BTreeSet, VecDeque};
use std::path::{Path, PathBuf};

use clang::{Entity, EntityKind, Linkage, TypeKind};

use crate::extract::{self, ExtractError, ParseOptions};

pub const BASE_COMPLEXITY: u32 = 1;
pub const SIGNATURE_SEPARATOR: &str = ", ";

// C gives a name meaning only within a linkage. An external name is one function across the
// whole program, so the name alone identifies it. An internal name is one function per
// definition site, and libarchive has 71 names that mean different bodies in different files
// - `free_data` is eleven unrelated functions. Keying those on the name alone discarded 107
// distinct bodies and 912 danger. The definition site is what separates them, and it also
// merges the opposite case: openjpeg's `opj_int_ceildiv` is one `static` body in a header
// that 30 translation units each see, and all 30 share this key.
#[derive(Debug, Clone, Default, PartialEq, Eq, PartialOrd, Ord, serde::Serialize)]
pub struct Symbol {
    pub name: String,
    pub unit: Option<PathBuf>,
}

impl Symbol {
    #[must_use]
    pub fn exported(name: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            unit: None,
        }
    }

    #[must_use]
    pub fn internal(name: impl Into<String>, unit: impl Into<PathBuf>) -> Self {
        Self {
            name: name.into(),
            unit: Some(unit.into()),
        }
    }
}

#[derive(Debug, Clone, Default, PartialEq, Eq, serde::Serialize)]
pub struct Defined {
    pub name: String,
    pub origin: PathBuf,
    pub own: u32,
    pub loops: u32,
    pub nested_loops: u32,
    pub max_nesting: u32,
    pub pointer_arithmetic: u32,
    pub calls: Vec<Symbol>,
    pub indirect: Vec<String>,
    pub exported: bool,
}

// The two halves of an indirect call are never in the same translation unit, and one half is
// often in no FUNCTION at all: libarchive names its targets in a file-scope designated
// initializer, `archive_read_vtable = { .archive_read_next_header = _archive_read_next_header }`,
// which is how C dispatch tables are usually written. Scanning only bodies found the format
// readers and missed every public entry point, so the addresses are collected per source and
// resolved once the whole tree has been read.
#[derive(Debug, Clone, Default)]
pub struct Sources {
    pub defined: Vec<Defined>,
    pub taken: Vec<(String, Symbol)>,
}

impl Sources {
    pub fn absorb(&mut self, other: Self, seen: &mut BTreeSet<Symbol>) {
        for item in other.defined {
            if seen.insert(item.symbol()) {
                self.defined.push(item);
            }
        }
        self.taken.extend(other.taken);
    }
}

impl Defined {
    #[must_use]
    pub fn danger(&self) -> u32 {
        self.own
            .saturating_add(self.loops)
            .saturating_add(self.nested_loops)
            .saturating_add(self.max_nesting)
            .saturating_add(self.pointer_arithmetic)
    }

    #[must_use]
    pub fn symbol(&self) -> Symbol {
        if self.exported {
            Symbol::exported(self.name.clone())
        } else {
            Symbol::internal(self.name.clone(), self.origin.clone())
        }
    }
}

#[must_use]
pub fn is_decision(kind: EntityKind) -> bool {
    matches!(
        kind,
        EntityKind::IfStmt
            | EntityKind::ForStmt
            | EntityKind::WhileStmt
            | EntityKind::DoStmt
            | EntityKind::CaseStmt
            | EntityKind::ConditionalOperator
            | EntityKind::CatchStmt
    )
}

#[must_use]
pub fn is_loop(kind: EntityKind) -> bool {
    matches!(
        kind,
        EntityKind::ForStmt | EntityKind::WhileStmt | EntityKind::DoStmt
    )
}

#[must_use]
pub fn is_nesting(kind: EntityKind) -> bool {
    is_loop(kind) || matches!(kind, EntityKind::IfStmt | EntityKind::SwitchStmt)
}

#[derive(Debug, Default)]
struct Metrics {
    decisions: u32,
    loops: u32,
    nested_loops: u32,
    max_nesting: u32,
    pointer_arithmetic: u32,
    calls: BTreeSet<Symbol>,
    indirect: BTreeSet<String>,
    taken: BTreeSet<(String, Symbol)>,
}

fn origin_of(entity: &Entity) -> Option<PathBuf> {
    Some(entity.get_location()?.get_file_location().file?.get_path())
}

// The callee's own linkage decides how it is named, and clang has already resolved the
// reference, so the answer is exact rather than a guess from the call site's file.
fn callee(target: &Entity) -> Option<Symbol> {
    let name = target.get_name()?;
    if target.get_linkage() == Some(Linkage::Internal) {
        let body = target.get_definition().unwrap_or(*target);
        Some(Symbol::internal(name, origin_of(&body)?))
    } else {
        Some(Symbol::exported(name))
    }
}

// Canonical, because a dispatch table is written in the library's own typedefs while the
// function it points at is usually written in the underlying types. openjpeg declares the
// same signature as OPJ_BOOL(...) in one place and int(...) in another, and matching the
// spelling instead of the type would connect neither.
fn signature_of(kind: &clang::Type) -> Option<String> {
    let mut target = kind.get_canonical_type();
    if target.get_kind() == TypeKind::Pointer {
        target = target.get_pointee_type()?.get_canonical_type();
    }
    if target.get_kind() != TypeKind::FunctionPrototype {
        return None;
    }
    let result = target
        .get_result_type()?
        .get_canonical_type()
        .get_display_name();
    let arguments: Vec<String> = target
        .get_argument_types()?
        .iter()
        .map(|argument| argument.get_canonical_type().get_display_name())
        .collect();
    Some(format!("{result}({})", arguments.join(SIGNATURE_SEPARATOR)))
}

// A call whose callee clang cannot resolve to a function is a call through a pointer. The
// canonical libarchive dispatch, `(a->format->read_header)(a, entry)`, resolves to NOTHING -
// not to the FieldDecl - so the signature has to come off the callee EXPRESSION's own type.
fn indirect_signature(entity: &Entity) -> Option<String> {
    let callee = entity.get_children().into_iter().next()?;
    signature_of(&callee.get_type()?)
}

fn is_pointer(entity: &Entity) -> bool {
    entity
        .get_type()
        .is_some_and(|kind| kind.get_canonical_type().get_kind() == TypeKind::Pointer)
}

fn pointer_operands(entity: &Entity) -> usize {
    entity
        .get_children()
        .iter()
        .filter(|child| is_pointer(child))
        .count()
}

fn is_pointer_arithmetic(entity: &Entity) -> bool {
    match entity.get_kind() {
        EntityKind::ArraySubscriptExpr => entity
            .get_children()
            .first()
            .is_some_and(subscript_base_is_pointer),
        EntityKind::BinaryOperator | EntityKind::UnaryOperator => {
            is_pointer(entity) && pointer_operands(entity) == 1
        }
        EntityKind::CompoundAssignOperator => is_pointer(entity),
        _ => false,
    }
}

fn subscript_base_is_pointer(base: &Entity) -> bool {
    let mut node = *base;
    loop {
        if let Some(target) = node.get_reference() {
            return target
                .get_type()
                .is_some_and(|kind| kind.get_canonical_type().get_kind() == TypeKind::Pointer);
        }
        let children = node.get_children();
        if children.len() != 1 {
            return is_pointer(&node);
        }
        node = children[0];
    }
}

fn walk(entity: &Entity, metrics: &mut Metrics, depth: u32, loop_depth: u32, in_callee: bool) {
    let children = entity.get_children();
    let parent_is_if = entity.get_kind() == EntityKind::IfStmt;
    let parent_is_call = entity.get_kind() == EntityKind::CallExpr;
    let last = children.len().saturating_sub(1);
    for (position, child) in children.iter().enumerate() {
        let kind = child.get_kind();
        if is_decision(kind) {
            metrics.decisions += 1;
        }
        let inside_loop = is_loop(kind);
        if inside_loop {
            metrics.loops += 1;
            if loop_depth > 0 {
                metrics.nested_loops += 1;
            }
        }
        if is_pointer_arithmetic(child) {
            metrics.pointer_arithmetic += 1;
        }
        if kind == EntityKind::CallExpr {
            match child.get_reference() {
                Some(target)
                    if target.get_kind() == EntityKind::FunctionDecl
                        && let Some(symbol) = callee(&target) =>
                {
                    metrics.calls.insert(symbol);
                }
                _ => {
                    if let Some(signature) = indirect_signature(child) {
                        metrics.indirect.insert(signature);
                    }
                }
            }
        }
        // Reached outside a callee position, a reference to a function is its ADDRESS, which
        // is the only evidence that some dispatch table may later call it. The flag has to
        // travel the whole callee subtree: the callee sits under an implicit decay cast, so a
        // check one level deep counts every ordinary call as an address taken.
        if kind == EntityKind::DeclRefExpr
            && !in_callee
            && let Some(target) = child.get_reference()
            && target.get_kind() == EntityKind::FunctionDecl
            && let Some(symbol) = callee(&target)
            && let Some(signature) = target.get_type().as_ref().and_then(signature_of)
        {
            metrics.taken.insert((signature, symbol));
        }
        let chained_else = parent_is_if && kind == EntityKind::IfStmt && position == last;
        let next_depth = if is_nesting(kind) && !chained_else {
            depth + 1
        } else {
            depth
        };
        metrics.max_nesting = metrics.max_nesting.max(next_depth);
        walk(
            child,
            metrics,
            next_depth,
            if inside_loop {
                loop_depth + 1
            } else {
                loop_depth
            },
            in_callee || (parent_is_call && position == 0),
        );
    }
}

pub fn parse_source(path: &Path, options: &ParseOptions) -> Result<Sources, ExtractError> {
    if !path.is_file() {
        return Err(ExtractError::NotAFile(path.to_path_buf()));
    }
    extract::with_index(|index| {
        let unit = index
            .parser(path)
            .arguments(&options.argv())
            .skip_function_bodies(false)
            .detailed_preprocessing_record(true)
            .parse()
            .map_err(|source| ExtractError::Parse {
                path: path.to_path_buf(),
                reason: source.to_string(),
            })?;

        // This path tolerates every diagnostic on purpose, because a partly-parsed source
        // still yields usable call edges. A foreign header is not that: an audit measured
        // it moving libjpeg-turbo's #1 ranked entry point with the run still exiting 0.
        extract::refuse_foreign_includes(&unit.get_entity(), path, options)?;

        let mut found = Sources::default();
        let mut seen = BTreeSet::new();
        for child in unit.get_entity().get_children() {
            collect(&child, &mut found, &mut seen);
        }
        Ok(found)
    })
}

// A file-scope initializer cannot call anything, so every function it names is an address
// being taken. Walking it needs no callee bookkeeping for that reason.
fn initializer_targets(entity: &Entity, taken: &mut Vec<(String, Symbol)>) {
    for child in entity.get_children() {
        if child.get_kind() == EntityKind::DeclRefExpr
            && let Some(target) = child.get_reference()
            && target.get_kind() == EntityKind::FunctionDecl
            && let Some(symbol) = callee(&target)
            && let Some(signature) = target.get_type().as_ref().and_then(signature_of)
        {
            taken.push((signature, symbol));
        }
        initializer_targets(&child, taken);
    }
}

fn collect(entity: &Entity, found: &mut Sources, seen: &mut BTreeSet<String>) {
    match entity.get_kind() {
        EntityKind::VarDecl => initializer_targets(entity, &mut found.taken),
        EntityKind::FunctionDecl => {
            if !entity.is_definition() {
                return;
            }
            let Some(name) = entity.get_name() else {
                return;
            };
            let Some(origin) = origin_of(entity) else {
                return;
            };
            if !seen.insert(name.clone()) {
                return;
            }
            let mut metrics = Metrics::default();
            walk(entity, &mut metrics, 0, 0, false);
            found.taken.extend(metrics.taken);
            found.defined.push(Defined {
                name,
                origin,
                own: BASE_COMPLEXITY + metrics.decisions,
                loops: metrics.loops,
                nested_loops: metrics.nested_loops,
                max_nesting: metrics.max_nesting,
                pointer_arithmetic: metrics.pointer_arithmetic,
                calls: metrics.calls.into_iter().collect(),
                indirect: metrics.indirect.into_iter().collect(),
                exported: entity.get_linkage() != Some(Linkage::Internal),
            });
        }
        EntityKind::LinkageSpec | EntityKind::Namespace | EntityKind::UnexposedDecl => {
            for child in entity.get_children() {
                collect(&child, found, seen);
            }
        }
        _ => {}
    }
}

#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct CallGraph {
    nodes: BTreeMap<Symbol, Defined>,
    dispatch: BTreeMap<String, BTreeSet<Symbol>>,
}

impl From<Sources> for CallGraph {
    // Resolution has to happen here rather than per translation unit, because the two halves
    // are never in the same one: libarchive dispatches through `a->format->read_header` in
    // archive_read.c while every target's address is taken in its own format reader, passed
    // as an argument to __archive_read_register_format. That is also why the row's suggested
    // "resolve the field's assignments within the TU" cannot work.
    fn from(sources: Sources) -> Self {
        let mut dispatch: BTreeMap<String, BTreeSet<Symbol>> = BTreeMap::new();
        for (signature, symbol) in sources.taken {
            dispatch.entry(signature).or_default().insert(symbol);
        }
        Self {
            nodes: sources
                .defined
                .into_iter()
                .map(|item| (item.symbol(), item))
                .collect(),
            dispatch,
        }
    }
}

impl From<Vec<Defined>> for CallGraph {
    fn from(defined: Vec<Defined>) -> Self {
        Self::from(Sources {
            defined,
            taken: Vec::new(),
        })
    }
}

impl CallGraph {
    // Every by-name query on this graph carries a name a public header declared, and a header
    // declares each name once. Resolving it by name rather than by key keeps that query
    // answerable for the one library that declares a `static inline` in its own header, whose
    // node exists only under an internal key. External linkage sorts first, so an exported
    // definition always wins over a same-named internal one.
    fn resolve(&self, name: &str) -> Option<(&Symbol, &Defined)> {
        self.nodes
            .range(Symbol::exported(name)..)
            .take_while(|(symbol, _)| symbol.name == name)
            .next()
    }

    #[must_use]
    pub fn get(&self, name: &str) -> Option<&Defined> {
        self.resolve(name).map(|(_, node)| node)
    }

    #[must_use]
    pub fn own(&self, symbol: &Symbol) -> u32 {
        self.nodes.get(symbol).map_or(0, |node| node.own)
    }

    #[must_use]
    pub fn reachable_from(&self, seeds: &[String]) -> BTreeSet<Symbol> {
        let mut visited = BTreeSet::new();
        let mut queue: VecDeque<Symbol> = seeds
            .iter()
            .filter_map(|seed| self.resolve(seed).map(|(symbol, _)| symbol.clone()))
            .collect();
        while let Some(symbol) = queue.pop_front() {
            let Some(node) = self.nodes.get(&symbol) else {
                continue;
            };
            if !visited.insert(symbol) {
                continue;
            }
            for call in &node.calls {
                if !visited.contains(call) {
                    queue.push_back(call.clone());
                }
            }
            for signature in &node.indirect {
                let Some(targets) = self.dispatch.get(signature) else {
                    continue;
                };
                for target in targets {
                    if !visited.contains(target) {
                        queue.push_back(target.clone());
                    }
                }
            }
        }
        visited
    }

    #[must_use]
    pub fn dispatch_targets(&self, signature: &str) -> usize {
        self.dispatch.get(signature).map_or(0, BTreeSet::len)
    }

    #[must_use]
    pub fn reaches(&self, reached: &BTreeSet<Symbol>, name: &str) -> bool {
        self.resolve(name)
            .is_some_and(|(symbol, _)| reached.contains(symbol))
    }

    #[must_use]
    pub fn accumulated(&self, name: &str) -> u32 {
        self.reachable_from(std::slice::from_ref(&name.to_owned()))
            .iter()
            .map(|reached| self.own(reached))
            .sum()
    }

    #[must_use]
    pub fn danger(&self, name: &str) -> u32 {
        self.get(name).map_or(0, Defined::danger)
    }

    #[must_use]
    pub fn danger_of(&self, symbol: &Symbol) -> u32 {
        self.nodes.get(symbol).map_or(0, Defined::danger)
    }

    #[must_use]
    pub fn accumulated_danger(&self, name: &str) -> u32 {
        self.reachable_from(std::slice::from_ref(&name.to_owned()))
            .iter()
            .map(|reached| self.danger_of(reached))
            .sum()
    }

    #[must_use]
    pub fn undiscovered_danger(&self, name: &str, already: &BTreeSet<Symbol>) -> u32 {
        self.reachable_from(std::slice::from_ref(&name.to_owned()))
            .iter()
            .filter(|reached| !already.contains(*reached))
            .map(|reached| self.danger_of(reached))
            .sum()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::extract::ParseOptions;
    use std::path::PathBuf;

    fn source(label: &str, body: &str) -> PathBuf {
        let dir = lisdex_core::scratch::path(&format!("complexity-{label}"));
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();
        let path = dir.join("unit.c");
        std::fs::write(&path, body).unwrap();
        path
    }

    fn defined(label: &str, body: &str) -> Vec<Defined> {
        parse_source(&source(label, body), &ParseOptions::default())
            .unwrap()
            .defined
    }

    fn find<'a>(found: &'a [Defined], name: &str) -> &'a Defined {
        found.iter().find(|item| item.name == name).unwrap()
    }

    #[test]
    fn a_straight_line_function_has_the_minimum_complexity_of_one() {
        let found = defined("straight", "int f(int a) { return a + 1; }\n");
        assert_eq!(find(&found, "f").own, 1);
    }

    #[test]
    fn each_branch_adds_one_decision_point() {
        let found = defined(
            "branches",
            "int f(int a) { if (a) { return 1; } if (a > 2) { return 2; } return 0; }\n",
        );
        assert_eq!(find(&found, "f").own, 3);
    }

    #[test]
    fn loops_and_switch_cases_are_decision_points() {
        let found = defined(
            "loops",
            "int f(int a) {\n\
               int i;\n\
               for (i = 0; i < a; i++) { a += i; }\n\
               while (a > 10) { a--; }\n\
               switch (a) { case 1: return 1; case 2: return 2; default: break; }\n\
               return a;\n\
             }\n",
        );
        assert_eq!(find(&found, "f").own, 5);
    }

    #[test]
    fn a_ternary_is_a_decision_point() {
        let found = defined("ternary", "int f(int a) { return a ? 1 : 0; }\n");
        assert_eq!(find(&found, "f").own, 2);
    }

    #[test]
    fn the_functions_a_body_calls_are_recorded_as_edges() {
        let found = defined(
            "edges",
            "int helper(int x) { return x; }\n\
             int other(int x) { return x; }\n\
             int f(int a) { return helper(a) + other(a); }\n",
        );
        let calls = &find(&found, "f").calls;
        assert!(calls.contains(&Symbol::exported("helper")), "{calls:?}");
        assert!(calls.contains(&Symbol::exported("other")), "{calls:?}");
    }

    #[test]
    fn a_declaration_without_a_body_is_not_a_definition() {
        let found = defined("declonly", "int f(int a);\nint g(int a) { return a; }\n");
        assert!(found.iter().all(|item| item.name != "f"), "{found:?}");
        assert!(found.iter().any(|item| item.name == "g"));
    }

    #[test]
    fn control_flow_is_still_counted_when_the_unit_does_not_type_check() {
        let found = defined(
            "typeerrors",
            "int f(UNKNOWN_T a) { if (a) { return 1; } return 0; }\n",
        );
        assert_eq!(
            find(&found, "f").own,
            2,
            "complexity is structural, so unlike type classification it survives a \
             source file we lack the exact flags for"
        );
    }

    #[test]
    fn a_static_function_is_recorded_but_marked_internal() {
        let found = defined(
            "static",
            "static int hidden(int a) { return a; }\nint shown(int a) { return hidden(a); }\n",
        );
        assert!(!find(&found, "hidden").exported);
        assert!(find(&found, "shown").exported);
    }

    #[test]
    fn pointer_arithmetic_counts_advancing_a_pointer_and_nothing_else() {
        let found = defined(
            "leopardptr",
            "int f(char *p, char *q, int n) {\n\
               char *a = p + n;\n\
               char *b = p;\n\
               b += n;\n\
               b++;\n\
               return a[0] + b[1] + (p == q) + (int)(p - q);\n\
             }\n",
        );
        assert_eq!(
            find(&found, "f").pointer_arithmetic,
            5,
            "p + n, b += n, b++, a[0] and b[1] advance a pointer; p == q is int-typed, \
             p - q is ptrdiff_t, and char *b = p is an initialiser rather than arithmetic"
        );
    }

    #[test]
    fn a_function_that_never_touches_a_pointer_scores_zero_pointer_arithmetic() {
        let found = defined(
            "leopardnoptr",
            "int f(int a, int b) { int c = a + b; if (c) { c++; } return c; }\n",
        );
        assert_eq!(
            find(&found, "f").pointer_arithmetic,
            0,
            "integer arithmetic must not be counted, or the metric measures nothing"
        );
    }

    #[test]
    fn indexing_a_real_array_is_not_pointer_arithmetic() {
        let found = defined(
            "leopardarray",
            "int f(int i) { int arr[10]; arr[i] = 1; return arr[0]; }\n",
        );
        assert_eq!(
            find(&found, "f").pointer_arithmetic,
            0,
            "a subscript on a declared array decays to a pointer at the cast, so counting the \
             cast's type would make every array access pointer arithmetic"
        );
    }

    #[test]
    fn taking_an_address_is_not_pointer_arithmetic() {
        let found = defined("leopardaddr", "int f(int a) { int *p = &a; return *p; }\n");
        assert_eq!(
            find(&found, "f").pointer_arithmetic,
            0,
            "&a and *p are pointer-typed or pointer-operand nodes but neither advances a \
             pointer"
        );
    }

    #[test]
    fn assigning_one_pointer_to_another_is_not_pointer_arithmetic() {
        let found = defined(
            "leopardassign",
            "int f(char *p, char *q) { p = q; return *p; }\n",
        );
        assert_eq!(
            find(&found, "f").pointer_arithmetic,
            0,
            "p = q is a pointer-typed binary operator, and only the operand COUNT separates it \
             from p + n"
        );
    }

    #[test]
    fn loops_are_counted_separately_from_branches() {
        let found = defined(
            "leopardloops",
            "int f(int a) { int i; for (i = 0; i < a; i++) { a++; } while (a) { a--; } return a; }\n",
        );
        assert_eq!(find(&found, "f").loops, 2);
    }

    #[test]
    fn a_loop_inside_a_loop_is_counted_as_nested() {
        let found = defined(
            "leopardnested",
            "int f(int a) {\n\
               int i, j;\n\
               for (i = 0; i < a; i++) { for (j = 0; j < a; j++) { a++; } }\n\
               return a;\n\
             }\n",
        );
        let function = find(&found, "f");
        assert_eq!(function.loops, 2);
        assert_eq!(function.nested_loops, 1);
    }

    #[test]
    fn an_else_if_chain_is_flat_not_nested() {
        let chain = defined(
            "elseifchain",
            "int f(int a) {\n\
               if (a == 1) { return 1; }\n\
               else if (a == 2) { return 2; }\n\
               else if (a == 3) { return 3; }\n\
               else if (a == 4) { return 4; }\n\
               return 0;\n\
             }\n",
        );
        assert_eq!(
            find(&chain, "f").max_nesting,
            1,
            "parser chunk dispatch is written as else-if chains; counting them as \
             depth over-reported libarchive by 2.5x"
        );
    }

    #[test]
    fn genuine_nesting_is_still_counted_after_the_else_if_fix() {
        let nested = defined(
            "trulynested",
            "int f(int a) {\n\
               if (a) { if (a > 1) { if (a > 2) { return 3; } } }\n\
               return 0;\n\
             }\n",
        );
        assert_eq!(find(&nested, "f").max_nesting, 3);
    }

    #[test]
    fn maximum_nesting_depth_is_recorded() {
        let found = defined(
            "leoparddepth",
            "int f(int a) {\n\
               if (a) { if (a > 1) { while (a) { a--; } } }\n\
               return a;\n\
             }\n",
        );
        assert_eq!(find(&found, "f").max_nesting, 3);
    }

    #[test]
    fn danger_combines_cyclomatic_complexity_with_the_loop_metrics() {
        let plain = Defined {
            name: "plain".to_owned(),
            origin: PathBuf::new(),
            own: 5,
            loops: 0,
            nested_loops: 0,
            max_nesting: 0,
            pointer_arithmetic: 0,
            calls: Vec::new(),
            indirect: Vec::new(),
            exported: true,
        };
        let looping = Defined {
            loops: 3,
            nested_loops: 2,
            max_nesting: 4,
            ..plain.clone()
        };
        assert_eq!(plain.danger(), 5);
        assert!(
            looping.danger() > plain.danger(),
            "the SoK's top-ranked metric family is loop structure, not raw cyclomatic \
             complexity alone"
        );
    }

    #[test]
    fn undiscovered_danger_excludes_what_an_existing_harness_already_reaches() {
        let graph = CallGraph::from(vec![
            node(
                "entry",
                2,
                vec![Symbol::exported("covered"), Symbol::exported("fresh")],
            ),
            node("covered", 10, vec![]),
            node("fresh", 20, vec![]),
        ]);
        let already = BTreeSet::from([Symbol::exported("covered")]);
        assert_eq!(graph.accumulated_danger("entry"), 32);
        assert_eq!(graph.undiscovered_danger("entry", &already), 22);
    }

    #[test]
    fn undiscovered_equals_accumulated_when_no_harness_exists() {
        let graph = CallGraph::from(vec![
            node("entry", 3, vec![Symbol::exported("leaf")]),
            node("leaf", 9, vec![]),
        ]);
        let nothing = BTreeSet::new();
        assert_eq!(
            graph.undiscovered_danger("entry", &nothing),
            graph.accumulated_danger("entry"),
            "a library with no in-tree harness must degrade gracefully, not to zero"
        );
    }

    fn node(name: &str, danger: u32, calls: Vec<Symbol>) -> Defined {
        Defined {
            name: name.to_owned(),
            origin: PathBuf::new(),
            own: danger,
            loops: 0,
            nested_loops: 0,
            max_nesting: 0,
            pointer_arithmetic: 0,
            calls,
            indirect: Vec::new(),
            exported: true,
        }
    }

    fn hidden(name: &str, unit: &str, danger: u32, calls: Vec<Symbol>) -> Defined {
        Defined {
            name: name.to_owned(),
            origin: PathBuf::from(unit),
            own: danger,
            loops: 0,
            nested_loops: 0,
            max_nesting: 0,
            pointer_arithmetic: 0,
            calls,
            indirect: Vec::new(),
            exported: false,
        }
    }

    fn dispatcher(name: &str, danger: u32, signature: &str) -> Defined {
        Defined {
            indirect: vec![signature.to_owned()],
            ..node(name, danger, Vec::new())
        }
    }

    #[test]
    fn accumulated_complexity_sums_the_whole_reachable_call_tree() {
        let graph = CallGraph::from(vec![
            node("entry", 2, vec![Symbol::internal("middle", "unit.c")]),
            hidden(
                "middle",
                "unit.c",
                5,
                vec![Symbol::internal("leaf", "unit.c")],
            ),
            hidden("leaf", "unit.c", 10, vec![]),
        ]);
        assert_eq!(graph.accumulated("entry"), 17);
        assert_eq!(graph.accumulated("middle"), 15);
        assert_eq!(graph.accumulated("leaf"), 10);
    }

    #[test]
    fn a_recursive_cycle_does_not_hang_or_double_count() {
        let graph = CallGraph::from(vec![
            node("a", 1, vec![Symbol::internal("b", "unit.c")]),
            hidden(
                "b",
                "unit.c",
                2,
                vec![Symbol::exported("a"), Symbol::internal("c", "unit.c")],
            ),
            hidden("c", "unit.c", 4, vec![Symbol::internal("b", "unit.c")]),
        ]);
        assert_eq!(graph.accumulated("a"), 7);
    }

    #[test]
    fn an_unknown_function_accumulates_nothing_rather_than_panicking() {
        let graph = CallGraph::from(Vec::new());
        assert_eq!(graph.accumulated("absent"), 0);
    }

    #[test]
    fn calls_into_functions_with_no_definition_are_ignored_not_counted() {
        let graph = CallGraph::from(vec![node(
            "entry",
            3,
            vec![Symbol::exported("memcpy"), Symbol::exported("malloc")],
        )]);
        assert_eq!(graph.accumulated("entry"), 3);
    }

    #[test]
    fn the_set_of_functions_reachable_from_a_seed_is_the_novelty_frontier() {
        let graph = CallGraph::from(vec![
            node(
                "harness_calls_this",
                1,
                vec![Symbol::internal("deep", "unit.c")],
            ),
            hidden("deep", "unit.c", 1, vec![]),
            node("untouched", 1, vec![]),
        ]);
        let reached = graph.reachable_from(&["harness_calls_this".to_owned()]);
        assert!(graph.reaches(&reached, "harness_calls_this"));
        assert!(graph.reaches(&reached, "deep"));
        assert!(!graph.reaches(&reached, "untouched"));
    }

    #[test]
    fn a_static_name_in_two_files_is_two_nodes_not_one() {
        let graph = CallGraph::from(vec![
            node("entry_a", 1, vec![Symbol::internal("init", "a.c")]),
            node("entry_b", 1, vec![Symbol::internal("init", "b.c")]),
            hidden("init", "a.c", 3, vec![]),
            hidden("init", "b.c", 12, vec![]),
        ]);
        assert_eq!(
            graph.accumulated_danger("entry_a"),
            4,
            "libarchive has 71 names that mean a different body in a different file"
        );
        assert_eq!(
            graph.accumulated_danger("entry_b"),
            13,
            "keying on the bare name reported this as 4 as well, discarding the larger body"
        );
    }

    #[test]
    fn one_static_body_a_header_shares_is_still_a_single_node() {
        let shared = Symbol::internal("inlined", "shared.h");
        let graph = CallGraph::from(vec![
            node("entry_a", 1, vec![shared.clone()]),
            node("entry_b", 1, vec![shared.clone()]),
            hidden("inlined", "shared.h", 7, vec![]),
            hidden("inlined", "shared.h", 7, vec![]),
        ]);
        assert_eq!(
            graph.accumulated_danger("entry_a"),
            8,
            "openjpeg's opj_int_ceildiv is one body that 30 units each see, so separating \
             the copies would have inflated the tree instead of correcting it"
        );
        assert_eq!(graph.reachable_from(&["entry_a".to_owned()]).len(), 2);
    }

    #[test]
    fn an_exported_definition_answers_a_name_query_before_an_internal_one() {
        let graph = CallGraph::from(vec![
            hidden("shared", "front_end.c", 40, vec![]),
            node("shared", 3, vec![]),
        ]);
        assert_eq!(
            graph.danger("shared"),
            3,
            "a name a public header declares is the exported definition, never a front-end \
             static that happens to match"
        );
    }

    #[test]
    fn two_units_defining_the_same_static_keep_both_measured_bodies() {
        let dir = lisdex_core::scratch::path("complexity-tucollide");
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();
        let small = dir.join("a.c");
        let large = dir.join("b.c");
        std::fs::write(
            &small,
            "static int init(void) { return 0; }\n\
             int entry_a(void) { return init(); }\n",
        )
        .unwrap();
        std::fs::write(
            &large,
            "static int init(int a) {\n\
               if (a) { return 1; }\n\
               if (a > 1) { return 2; }\n\
               if (a > 2) { return 3; }\n\
               return 0;\n\
             }\n\
             int entry_b(void) { return init(0); }\n",
        )
        .unwrap();

        let options = ParseOptions::default();
        let mut all = Sources::default();
        let mut seen = BTreeSet::new();
        all.absorb(parse_source(&small, &options).unwrap(), &mut seen);
        all.absorb(parse_source(&large, &options).unwrap(), &mut seen);
        let graph = CallGraph::from(all);

        assert_eq!(graph.accumulated_danger("entry_a"), 2);
        assert_eq!(
            graph.accumulated_danger("entry_b"),
            6,
            "b.c's init is four decisions deep; keying on the bare name kept only a.c's \
             one-line body and reported this as 2"
        );
    }

    #[test]
    fn a_call_through_a_pointer_reaches_every_target_of_that_signature() {
        let signature = "int(char *)".to_owned();
        let graph = CallGraph::from(Sources {
            defined: vec![
                dispatcher("entry", 1, &signature),
                node("handler_one", 10, Vec::new()),
                node("handler_two", 20, Vec::new()),
                node("unrelated", 40, Vec::new()),
            ],
            taken: vec![
                (signature.clone(), Symbol::exported("handler_one")),
                (signature, Symbol::exported("handler_two")),
            ],
        });
        assert_eq!(
            graph.accumulated_danger("entry"),
            31,
            "a dispatch table's targets are the only functions an indirect call can reach, \
             and the ones whose address is never taken are not among them"
        );
    }

    // Two ways to be wrong are covered here, because an empty dispatch table would satisfy a
    // simpler version of this test no matter what the code did. `wrong_signature` IS
    // registered, so the assertion can only hold if the signature is actually consulted, and
    // `never_registered` is not, so it can only hold if registration is required too.
    #[test]
    fn an_indirect_call_reaches_only_targets_registered_under_its_own_signature() {
        let graph = CallGraph::from(Sources {
            defined: vec![
                dispatcher("entry", 1, "int(char *)"),
                node("registered", 10, Vec::new()),
                node("wrong_signature", 90, Vec::new()),
                node("never_registered", 500, Vec::new()),
            ],
            taken: vec![
                ("int(char *)".to_owned(), Symbol::exported("registered")),
                (
                    "void(double)".to_owned(),
                    Symbol::exported("wrong_signature"),
                ),
            ],
        });
        assert_eq!(
            graph.accumulated_danger("entry"),
            11,
            "matching a shared signature alone, or ignoring the signature and taking every \
             registered function, is the over-approximation Fuzz Introspector accepts"
        );
    }

    #[test]
    fn a_dispatch_table_written_at_file_scope_is_read() {
        let dir = lisdex_core::scratch::path("complexity-vtable");
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();
        let path = dir.join("unit.c");
        std::fs::write(
            &path,
            "struct vtable { int (*next_header)(int); };\n\
             static int deep(int a) {\n\
               if (a) { return 1; }\n\
               if (a > 1) { return 2; }\n\
               if (a > 2) { return 3; }\n\
               return 0;\n\
             }\n\
             static const struct vtable table = { .next_header = deep };\n\
             int entry(struct vtable *v, int a) { return (v->next_header)(a); }\n",
        )
        .unwrap();

        let graph = CallGraph::from(parse_source(&path, &ParseOptions::default()).unwrap());
        assert_eq!(
            graph.accumulated_danger("entry"),
            6,
            "entry's own 1 plus deep's 5; libarchive names every public entry point's target \
             in a file-scope designated initializer, so a scan of function bodies alone \
             reports this as 1"
        );
    }
}