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 👇

66.8 KB
Raw Blame
// ©AngelaMos | 2026
// extract.rs

use std::collections::{BTreeMap, BTreeSet};
use std::path::{Path, PathBuf};
use std::sync::{Mutex, PoisonError};

use clang::diagnostic::{Diagnostic, Severity};
use clang::{Clang, Entity, EntityKind, Index, Type, TypeKind};

use crate::signature::{Param, Pointee, Prototype, Returns, Shape, handle_key};

static PARSE_LOCK: Mutex<()> = Mutex::new(());
thread_local! {
    static PARSING: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
}

struct ReentryGuard;

impl Drop for ReentryGuard {
    fn drop(&mut self) {
        PARSING.set(false);
    }
}

pub const MIN_PROJECT_STEM: usize = 3;
pub const MIN_SUFFIX_ENTRY: usize = 2;
pub const C_ARGS: [&str; 3] = ["-x", "c", "-std=c11"];
pub const CPP_ARGS: [&str; 3] = ["-x", "c++", "-std=c++17"];
pub const TEARDOWN_VERBS: [&str; 15] = [
    "free", "destroy", "release", "delete", "close", "cleanup", "end", "fini", "finish", "dispose",
    "uninit", "deinit", "done", "unref", "discard",
];

#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Language {
    #[default]
    C,
    Cpp,
}

impl Language {
    #[must_use]
    pub fn args(self) -> [&'static str; 3] {
        match self {
            Language::C => C_ARGS,
            Language::Cpp => CPP_ARGS,
        }
    }
}

#[derive(Debug, Clone, Default)]
pub struct ParseOptions {
    pub includes: Vec<PathBuf>,
    pub defines: Vec<String>,
    pub extra_args: Vec<String>,
    pub language: Language,
    pub tree_headers: Vec<PathBuf>,
    pub project: String,
}

impl ParseOptions {
    #[must_use]
    pub fn argv(&self) -> Vec<String> {
        let mut args: Vec<String> = self
            .language
            .args()
            .iter()
            .map(|arg| (*arg).to_owned())
            .collect();
        for include in &self.includes {
            args.push(format!("-I{}", include.display()));
        }
        for define in &self.defines {
            args.push(format!("-D{define}"));
        }
        args.extend(self.extra_args.iter().cloned());
        args
    }
}

#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
pub struct Field {
    pub name: String,
    pub spelling: String,
    pub shape: Shape,
}

#[derive(Debug, Clone, Default, PartialEq, Eq, serde::Serialize)]
pub struct Record {
    pub spelling: String,
    pub fields: Vec<Field>,
}

#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Vocabulary {
    pub macros: BTreeSet<String>,
    // Kept apart from `macros` because the two are spelled differently at every use site: an
    // object-like macro is a value and a function-like one is only a value once it is applied
    // to something. Emitting `PNG_IMAGE_SIZE` where `PNG_IMAGE_VERSION` was meant does not
    // compile, so the arity travels with the name rather than being rediscovered.
    pub sizers: BTreeMap<String, usize>,
    pub records: BTreeMap<String, Record>,
    pub produced: BTreeSet<String>,
    pub destructors: BTreeMap<String, BTreeSet<String>>,
    pub producers: BTreeMap<String, BTreeMap<String, Vec<Param>>>,
    // The producers and destructors maps answer "what makes this handle" and "what frees
    // it". Replaying an author's call ORDER asks a third question - "what does the call
    // they made between those two take" - and nothing here could answer it.
    pub functions: BTreeMap<String, Vec<Param>>,
}

impl Vocabulary {
    pub fn absorb(&mut self, other: Vocabulary) {
        self.macros.extend(other.macros);
        for (name, arity) in other.sizers {
            self.sizers.entry(name).or_insert(arity);
        }
        for (name, record) in other.records {
            self.records.entry(name).or_insert(record);
        }
        self.produced.extend(other.produced);
        for (name, params) in other.functions {
            self.functions.entry(name).or_insert(params);
        }
        for (record, functions) in other.destructors {
            self.destructors
                .entry(record)
                .or_default()
                .extend(functions);
        }
        for (handle, functions) in other.producers {
            self.producers.entry(handle).or_default().extend(functions);
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
pub struct Declared {
    pub name: String,
    pub params: Vec<Param>,
    pub result: Returns,
    pub header: PathBuf,
    pub line: u32,
}

#[derive(Debug, thiserror::Error)]
pub enum ExtractError {
    #[error("{0} is not a file")]
    NotAFile(PathBuf),
    #[error("libclang is unavailable: {0}")]
    Libclang(String),
    #[error("io error resolving {path}: {source}")]
    Io {
        path: PathBuf,
        source: std::io::Error,
    },
    #[error("{path} could not be parsed: {reason}")]
    Parse { path: PathBuf, reason: String },
    #[error(
        "{path} does not type check ({count} errors, first: {first}) - ranking it would silently under-report byte buffers"
    )]
    Diagnostics {
        path: PathBuf,
        count: usize,
        first: String,
    },
    #[error(
        "{includer} resolved {spelling:?} to {resolved}, which lies outside the source tree and every include path lisdex was given - that is a different copy of a header this library owns, so the declarations parsed here need not match the sources being built"
    )]
    ForeignInclude {
        path: PathBuf,
        includer: PathBuf,
        spelling: String,
        resolved: PathBuf,
    },
    #[error(
        "a libclang parse was started from inside another one; PARSE_LOCK is not reentrant and would deadlock forever"
    )]
    Reentrant,
}

pub fn with_index<T, F>(action: F) -> Result<T, ExtractError>
where
    F: FnOnce(&Index) -> Result<T, ExtractError>,
{
    // The lock is not reentrant, so a nested parse used to hang with no output at all.
    if PARSING.replace(true) {
        return Err(ExtractError::Reentrant);
    }
    let _reentry = ReentryGuard;
    let _guard = PARSE_LOCK.lock().unwrap_or_else(PoisonError::into_inner);
    let clang = Clang::new().map_err(ExtractError::Libclang)?;
    let index = Index::new(&clang, false, false);
    action(&index)
}

fn is_integral(kind: TypeKind) -> bool {
    matches!(
        kind,
        TypeKind::Bool
            | TypeKind::CharS
            | TypeKind::CharU
            | TypeKind::SChar
            | TypeKind::UChar
            | TypeKind::Short
            | TypeKind::UShort
            | TypeKind::Int
            | TypeKind::UInt
            | TypeKind::Long
            | TypeKind::ULong
            | TypeKind::LongLong
            | TypeKind::ULongLong
            | TypeKind::Int128
            | TypeKind::UInt128
            | TypeKind::Enum
            | TypeKind::WChar
            | TypeKind::Char16
            | TypeKind::Char32
    )
}

fn record_name(ty: &Type) -> String {
    ty.get_declaration()
        .and_then(|declaration| declaration.get_name())
        .unwrap_or_else(|| ty.get_display_name())
}

fn prototype_of(ty: &Type) -> Option<Prototype> {
    Some(Prototype {
        returns: ty
            .get_result_type()?
            .get_canonical_type()
            .get_display_name(),
        params: ty
            .get_argument_types()?
            .iter()
            .map(|argument| argument.get_canonical_type().get_display_name())
            .collect(),
    })
}

fn pointee_of(ty: &Type) -> Pointee {
    match ty.get_kind() {
        TypeKind::UChar => Pointee::UnsignedChar,
        TypeKind::SChar => Pointee::SignedChar,
        TypeKind::CharS | TypeKind::CharU => Pointee::Char,
        TypeKind::Void => Pointee::Void,
        TypeKind::Record => Pointee::Record(record_name(ty)),
        TypeKind::FunctionPrototype => Pointee::Function(prototype_of(ty)),
        TypeKind::FunctionNoPrototype => Pointee::Function(None),
        TypeKind::Pointer => ty.get_pointee_type().map_or(Pointee::Other, |inner| {
            Pointee::Pointer(Box::new(pointee_of(&inner.get_canonical_type())))
        }),
        kind if is_integral(kind) => Pointee::Integral,
        _ => Pointee::Other,
    }
}

fn as_pointer(target: &Type, inherited_const: bool) -> Shape {
    let canonical = target.get_canonical_type();
    Shape::Pointer {
        pointee: pointee_of(&canonical),
        is_const: inherited_const || target.is_const_qualified() || canonical.is_const_qualified(),
    }
}

#[must_use]
pub fn shape_of(ty: &Type) -> Shape {
    let canonical = ty.get_canonical_type();
    match canonical.get_kind() {
        TypeKind::Pointer => canonical
            .get_pointee_type()
            .map_or(Shape::Other, |pointee| as_pointer(&pointee, false)),
        // An array's canonical type carries the const; clang_getElementType returns
        // the element UNQUALIFIED. Without inheriting it, `const unsigned char d[]`
        // reads as non-const and the whole function drops out as NoDataInput.
        TypeKind::ConstantArray
        | TypeKind::IncompleteArray
        | TypeKind::VariableArray
        | TypeKind::DependentSizedArray => {
            let array_is_const = canonical.is_const_qualified() || ty.is_const_qualified();
            canonical
                .get_element_type()
                .map_or(Shape::Other, |element| as_pointer(&element, array_is_const))
        }
        TypeKind::Record => Shape::Record(record_name(&canonical)),
        TypeKind::Float | TypeKind::Double | TypeKind::LongDouble => Shape::Float,
        TypeKind::Void => Shape::Void,
        kind if is_integral(kind) => Shape::Integral,
        _ => Shape::Other,
    }
}

fn declared_in(entity: &Entity, target: &Path) -> Option<u32> {
    let location = entity.get_location()?.get_file_location();
    let file = location.file?;
    let path = std::fs::canonicalize(file.get_path()).ok()?;
    (path == target).then_some(location.line)
}

fn parameters(entity: &Entity) -> Vec<Param> {
    entity
        .get_arguments()
        .unwrap_or_default()
        .iter()
        .map(|argument| {
            let ty = argument.get_type();
            Param {
                name: argument.get_name(),
                spelling: ty
                    .as_ref()
                    .map(clang::Type::get_display_name)
                    .unwrap_or_default(),
                shape: ty.as_ref().map_or(Shape::Other, shape_of),
            }
        })
        .collect()
}

fn result_of(entity: &Entity) -> Returns {
    let ty = entity.get_result_type();
    Returns {
        spelling: ty
            .as_ref()
            .map(clang::Type::get_display_name)
            .unwrap_or_default(),
        shape: ty.as_ref().map_or(Shape::Other, shape_of),
    }
}

fn collect(entity: &Entity, target: &Path, found: &mut Vec<Declared>, seen: &mut BTreeSet<String>) {
    for child in entity.get_children() {
        match child.get_kind() {
            EntityKind::FunctionDecl => {
                let Some(name) = child.get_name() else {
                    continue;
                };
                let Some(line) = declared_in(&child, target) else {
                    continue;
                };
                if seen.insert(name.clone()) {
                    found.push(Declared {
                        name,
                        params: parameters(&child),
                        result: result_of(&child),
                        header: target.to_path_buf(),
                        line,
                    });
                }
            }
            EntityKind::LinkageSpec | EntityKind::Namespace | EntityKind::UnexposedDecl => {
                collect(&child, target, found, seen);
            }
            _ => {}
        }
    }
}

fn record_fields(entity: &Entity) -> Vec<Field> {
    entity
        .get_children()
        .iter()
        .filter(|child| child.get_kind() == EntityKind::FieldDecl)
        .filter_map(|child| {
            let name = child.get_name()?;
            let ty = child.get_type();
            Some(Field {
                name,
                spelling: ty
                    .as_ref()
                    .map(clang::Type::get_display_name)
                    .unwrap_or_default(),
                shape: ty.as_ref().map_or(Shape::Other, shape_of),
            })
        })
        .collect()
}

#[must_use]
pub fn identifier_words(name: &str) -> Vec<String> {
    let mut words = Vec::new();
    for part in name.split(['_', '-']) {
        let chars: Vec<char> = part.chars().collect();
        let mut start = 0;
        for index in 1..chars.len() {
            let upper = chars[index].is_uppercase();
            let after_lower = chars[index - 1].is_lowercase() || chars[index - 1].is_ascii_digit();
            let before_lower = chars.get(index + 1).is_some_and(|next| next.is_lowercase());
            if upper && (after_lower || (chars[index - 1].is_uppercase() && before_lower)) {
                words.push(chars[start..index].iter().collect());
                start = index;
            }
        }
        if start < chars.len() {
            words.push(chars[start..].iter().collect());
        }
    }
    words
}

// A trailing digit on a word is a version or a bit depth, never part of the verb:
// `tj3Compress8`, `tj3Decompress16`, `compress2`, `uncompress2`. Stripping it is what lets
// the verb be seen at all, and it has to happen per WORD rather than per name, because
// `identifier_words` splits `tj3Compress8` into `["tj3", "Compress8"]` and the digit sits in
// the middle of the identifier, not at its end.
//
// An all-digit word trims to the empty string and that needs no guard: "" cannot equal any
// vocabulary entry, and the suffix arm requires `only.len() > entry.len()`, so it cannot
// match a non-empty one either. A guard was written, measured inert on all 629 tests, and
// deleted rather than kept as insurance.
fn without_version_digits(word: &str) -> &str {
    word.trim_end_matches(|character: char| character.is_ascii_digit())
}

#[must_use]
pub fn carries_word(name: &str, vocabulary: &[&str]) -> bool {
    let words: Vec<String> = identifier_words(name)
        .iter()
        .map(|word| without_version_digits(word).to_owned())
        .collect();
    if words.iter().any(|word| {
        vocabulary
            .iter()
            .any(|entry| word.eq_ignore_ascii_case(entry))
    }) {
        return true;
    }
    // An all-lowercase identifier has no boundary to split on, so `gzclose` and `maxlen`
    // read as one word. Fall back to a suffix match, which is where the verb or the
    // extent lands in every case measured.
    match words.as_slice() {
        [only] => vocabulary.iter().any(|entry| {
            entry.len() >= MIN_SUFFIX_ENTRY
                && only.len() > entry.len()
                && only.to_lowercase().ends_with(entry)
        }),
        _ => false,
    }
}

fn is_teardown_name(name: &str) -> bool {
    carries_word(name, &TEARDOWN_VERBS)
}

fn sole_handle_parameter(entity: &Entity) -> Option<String> {
    let arguments = entity.get_arguments()?;
    let [only] = arguments.as_slice() else {
        return None;
    };
    let ty = only.get_type()?;
    handle_key(&ty.get_display_name(), &shape_of(&ty))
}

fn collect_relations(entity: &Entity, target: &Path, into: &mut Vocabulary) {
    let Some(name) = entity.get_name() else {
        return;
    };
    if declared_in(entity, target).is_none() {
        return;
    }
    // A const return is a borrow, not an allocation: libwebp's WebPIDecodedArea hands back
    // a `const WebPDecBuffer *` while WebPInitDecBuffer exists precisely so the caller can
    // own one, and archive_entry_stat hands back a `const struct stat *`.
    into.functions
        .entry(name.clone())
        .or_insert_with(|| parameters(entity));
    let returns = result_of(entity);
    if let Shape::Pointer {
        pointee: Pointee::Record(record),
        is_const: false,
    } = &returns.shape
    {
        into.produced.insert(record.clone());
    }
    // The same borrow-versus-allocation rule decides what may open a producer chain: a
    // function handing back a const pointer did not make the object and calling it will
    // not give the harness one it is allowed to tear down.
    if let Shape::Pointer {
        is_const: false, ..
    } = &returns.shape
        && let Some(handle) = handle_key(&returns.spelling, &returns.shape)
    {
        into.producers
            .entry(handle)
            .or_default()
            .insert(name.clone(), parameters(entity));
    }
    // A double-pointer out-param used to count as an allocation too, on the argument that
    // `int X_create(X **out)` hands the record back through a slot. B84 measured that arm over
    // ten tree-runs and DELETED it: a slot says the library HAS an instance, never that the
    // caller may not declare one. Every real handle it was written for is opaque - `LZ4F_dctx_s`
    // and `LZ4F_cctx_s` from `LZ4F_create*Context(X **)`, `LZ4_readFile_s` from `LZ4F_readOpen` -
    // so the completeness test blocks all four without it, while it blocked seven libpng records
    // that are plain value types a caller declares: `png_color`, `png_time`, `png_text` and four
    // more, every one slotted by a `png_get_*` getter handing back a view into its own state.
    if is_teardown_name(&name)
        && let Some(handle) = sole_handle_parameter(entity)
    {
        into.destructors.entry(handle).or_default().insert(name);
    }
}

// libclang exposes a function-like macro's parameters nowhere but the raw tokens, and the
// count is what decides whether the harness can apply it at all: `PNG_IMAGE_SIZE(image)`
// takes the record it is written about, while `PNG_IMAGE_BUFFER_SIZE(image, row_stride)`
// takes a second number the caller owns - and supplying that number is the guess B67 refuses.
fn macro_arity(entity: &Entity) -> Option<usize> {
    let tokens = entity.get_range()?.tokenize();
    let open = tokens
        .iter()
        .position(|token| token.get_spelling() == "(")?;
    let mut depth = 0usize;
    let mut names = 0usize;
    for token in &tokens[open..] {
        match token.get_spelling().as_str() {
            "(" => depth += 1,
            ")" => {
                depth -= 1;
                if depth == 0 {
                    return Some(names);
                }
            }
            "," => {}
            _ if depth == 1 => names += 1,
            _ => {}
        }
    }
    None
}

fn collect_vocabulary(entity: &Entity, target: &Path, into: &mut Vocabulary) {
    for child in entity.get_children() {
        match child.get_kind() {
            EntityKind::FunctionDecl => collect_relations(&child, target, into),
            EntityKind::MacroDefinition => {
                if child.is_builtin_macro() {
                    continue;
                }
                if child.is_function_like_macro() {
                    if let (Some(name), Some(arity)) = (child.get_name(), macro_arity(&child)) {
                        into.sizers.insert(name, arity);
                    }
                    continue;
                }
                if let Some(name) = child.get_name() {
                    into.macros.insert(name);
                }
            }
            EntityKind::StructDecl | EntityKind::UnionDecl => {
                let fields = record_fields(&child);
                if !fields.is_empty()
                    && let Some(ty) = child.get_type()
                {
                    let canonical = ty.get_canonical_type();
                    let key = record_name(&canonical);
                    // clang spells an anonymous typedef'd struct
                    // `struct (unnamed at foo.h:3:9)`, which is not a declarable type.
                    let display = canonical.get_display_name();
                    let spelling = if display.contains('(') {
                        key.clone()
                    } else {
                        display
                    };
                    into.records
                        .entry(key)
                        .or_insert(Record { spelling, fields });
                }
            }
            EntityKind::LinkageSpec | EntityKind::Namespace | EntityKind::UnexposedDecl => {
                collect_vocabulary(&child, target, into);
            }
            _ => {}
        }
    }
}

// B30: a system-installed copy of the target satisfies the target's own #includes and the
// parse SUCCEEDS, so no diagnostic can catch it. The trusted set is every path lisdex or the
// user pointed at plus the includer's own directory; the compiler's default search path is
// exactly what is missing from it, which is where the foreign copy lives.
fn trusted_roots(target: &Path, options: &ParseOptions) -> Vec<PathBuf> {
    let mut roots = Vec::new();
    if let Some(parent) = target.parent() {
        roots.push(parent.to_path_buf());
    }
    roots.extend(options.includes.iter().cloned());
    roots
        .iter()
        .filter_map(|root| std::fs::canonicalize(root).ok())
        .collect()
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum IncludeStyle {
    Quoted,
    Angled,
    Computed,
}

// The bracket is NOT the signal. An audit proved it on two real libraries: brotli
// angle-includes its own public headers (`#include <brotli/port.h>`, 30+ sites) and
// libarchive ships `#include PLATFORM_CONFIG_H`, so a quoted-only rule let a foreign copy
// drive the whole analysis. libclang exposes the spelling nowhere but the raw tokens - an
// angled path is punctuation, a quoted one is one literal, and a macro is neither.
fn include_style(entity: &Entity) -> IncludeStyle {
    let Some(range) = entity.get_range() else {
        return IncludeStyle::Computed;
    };
    let tokens = range.tokenize();
    if tokens
        .iter()
        .any(|token| token.get_spelling().starts_with('"'))
    {
        return IncludeStyle::Quoted;
    }
    if tokens.iter().any(|token| token.get_spelling() == "<") {
        return IncludeStyle::Angled;
    }
    IncludeStyle::Computed
}

// The tree shipping a header at this very sub-path means the include names something this
// library owns, so resolving it anywhere else is the wrong copy. This is what catches an
// angled self-include, which no bracket test can see.
fn tree_provides(spelling: &str, tree_headers: &[PathBuf]) -> bool {
    if spelling.is_empty() {
        return false;
    }
    let wanted = Path::new(spelling);
    tree_headers.iter().any(|header| header.ends_with(wanted))
}

// The other half of ownership, for a header the tree does NOT ship because the build
// generates it: libpng's pnglibconf.h and libexpat's expat_config.h both carry the project's
// own name. This is also what keeps libpng analysable - libpng writes `#include "zlib.h"`
// with quotes for a genuine external dependency, so the bracket says "mine" when it is not.
// Matched against the project token AND against its leading run of letters, because trees
// are cloned into directories carrying a version or a fork suffix - `libpng-1.6.40` tokenises
// to `png1640`, which `pnglibconf.h` does not contain while plain `png` does.
fn carries_project_token(spelling: &str, project: &str) -> bool {
    // A token this short matches half the headers in existence: zlib cloned as `libz`
    // tokenises to `z`, which would mark every header carrying a z as ours. Below the floor
    // there is no usable name signal, so ownership falls back to what the tree ships.
    if project.len() < MIN_PROJECT_STEM {
        return false;
    }
    let lowered = spelling.to_lowercase();
    let squashed: String = lowered
        .chars()
        .filter(char::is_ascii_alphanumeric)
        .collect();
    if squashed.contains(project) {
        return true;
    }
    let stem: String = project
        .chars()
        .take_while(char::is_ascii_alphabetic)
        .collect();
    stem.len() >= MIN_PROJECT_STEM && squashed.contains(&stem)
}

// A symlink from inside the tree to a generated header elsewhere is a normal out-of-tree
// build layout, so the raw path counts as trusted even when its target does not.
fn located_in(raw: &Path, canonical: &Path, roots: &[PathBuf]) -> bool {
    roots
        .iter()
        .any(|root| raw.starts_with(root) || canonical.starts_with(root))
}

fn foreign_include(
    entity: &Entity,
    roots: &[PathBuf],
    tree_headers: &[PathBuf],
    project: &str,
) -> Option<(PathBuf, String, PathBuf)> {
    for child in entity.get_children() {
        if child.get_kind() != EntityKind::InclusionDirective {
            continue;
        }
        // The includer must be ours. System headers quote their own siblings, and judging
        // those would refuse every target that includes stdio.h.
        let Some(raw_includer) = child
            .get_location()
            .and_then(|location| location.get_file_location().file)
            .map(|file| file.get_path())
        else {
            continue;
        };
        let includer = std::fs::canonicalize(&raw_includer).unwrap_or(raw_includer.clone());
        if !located_in(&raw_includer, &includer, roots) {
            continue;
        }
        let Some(raw_resolved) = child.get_file().map(|file| file.get_path()) else {
            continue;
        };
        let resolved = std::fs::canonicalize(&raw_resolved).unwrap_or(raw_resolved.clone());
        if located_in(&raw_resolved, &resolved, roots) {
            continue;
        }
        let spelling = child.get_name().unwrap_or_default();
        // The bracket is evidence of nothing, so it is not consulted. Ownership is: the tree
        // ships this exact sub-path, or the name carries the project's own token, or the
        // spelling came from a macro and cannot be judged at all.
        let owned = include_style(&child) == IncludeStyle::Computed
            || tree_provides(&spelling, tree_headers)
            || carries_project_token(&spelling, project);
        if owned {
            return Some((includer, spelling, resolved));
        }
    }
    None
}

pub(crate) fn refuse_foreign_includes(
    entity: &Entity,
    target: &Path,
    options: &ParseOptions,
) -> Result<(), ExtractError> {
    let roots = trusted_roots(target, options);
    match foreign_include(entity, &roots, &options.tree_headers, &options.project) {
        Some((includer, spelling, resolved)) => Err(ExtractError::ForeignInclude {
            path: target.to_path_buf(),
            includer,
            spelling,
            resolved,
        }),
        None => Ok(()),
    }
}

pub fn parse_vocabulary(path: &Path, options: &ParseOptions) -> Result<Vocabulary, ExtractError> {
    if !path.is_file() {
        return Err(ExtractError::NotAFile(path.to_path_buf()));
    }
    let target = std::fs::canonicalize(path).map_err(|source| ExtractError::Io {
        path: path.to_path_buf(),
        source,
    })?;

    with_index(|index| {
        let unit = index
            .parser(&target)
            .arguments(&options.argv())
            .skip_function_bodies(true)
            .detailed_preprocessing_record(true)
            .parse()
            .map_err(|source| ExtractError::Parse {
                path: target.clone(),
                reason: source.to_string(),
            })?;

        let failures: Vec<String> = unit
            .get_diagnostics()
            .iter()
            .filter(|diagnostic| {
                matches!(diagnostic.get_severity(), Severity::Error | Severity::Fatal)
            })
            .map(Diagnostic::get_text)
            .collect();
        // Ahead of the diagnostics verdict on purpose: a foreign copy is usually WHY the
        // header does not type check, and reporting the type error instead hides it.
        refuse_foreign_includes(&unit.get_entity(), &target, options)?;

        if let Some(first) = failures.first() {
            return Err(ExtractError::Diagnostics {
                path: target.clone(),
                count: failures.len(),
                first: first.clone(),
            });
        }

        let mut vocabulary = Vocabulary::default();
        collect_vocabulary(&unit.get_entity(), &target, &mut vocabulary);
        Ok(vocabulary)
    })
}

pub fn parse_header(path: &Path, options: &ParseOptions) -> Result<Vec<Declared>, ExtractError> {
    if !path.is_file() {
        return Err(ExtractError::NotAFile(path.to_path_buf()));
    }
    let target = std::fs::canonicalize(path).map_err(|source| ExtractError::Io {
        path: path.to_path_buf(),
        source,
    })?;

    with_index(|index| {
        let unit = index
            .parser(&target)
            .arguments(&options.argv())
            .skip_function_bodies(true)
            .detailed_preprocessing_record(true)
            .parse()
            .map_err(|source| ExtractError::Parse {
                path: target.clone(),
                reason: source.to_string(),
            })?;

        let failures: Vec<String> = unit
            .get_diagnostics()
            .iter()
            .filter(|diagnostic| {
                matches!(diagnostic.get_severity(), Severity::Error | Severity::Fatal)
            })
            .map(Diagnostic::get_text)
            .collect();
        refuse_foreign_includes(&unit.get_entity(), &target, options)?;

        if let Some(first) = failures.first() {
            return Err(ExtractError::Diagnostics {
                path: target.clone(),
                count: failures.len(),
                first: first.clone(),
            });
        }

        let mut found = Vec::new();
        let mut seen = BTreeSet::new();
        collect(&unit.get_entity(), &target, &mut found, &mut seen);
        Ok(found)
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::signature::{Pointee, Prototype, Shape};
    use std::path::PathBuf;

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

    fn parse(label: &str, body: &str) -> Vec<Declared> {
        let path = header(label, body);
        parse_header(&path, &ParseOptions::default()).unwrap()
    }

    fn vocabulary(label: &str, body: &str) -> Vocabulary {
        let path = header(label, body);
        parse_vocabulary(&path, &ParseOptions::default()).unwrap()
    }

    const SIMPLIFIED_API: &str = r"
#define PNG_IMAGE_VERSION 1
#define PNG_FORMAT_RGBA 3
typedef struct png_image {
    void *opaque;
    unsigned int version;
    unsigned int width;
    unsigned int height;
    unsigned int format;
} png_image;
int png_image_begin_read_from_memory(png_image *image, const void *m, unsigned long s);
";

    const ZLIB_GZ_API: &str = r"
struct gzFile_s { unsigned have; unsigned char *next; long pos; };
typedef struct gzFile_s *gzFile;
gzFile gzopen(const char *path, const char *mode);
int gzclose(gzFile file);
int gzputs(gzFile file, const char *s);
";

    const WEBP_API: &str = r"
typedef struct WebPDecBuffer { int colorspace; unsigned char *rgba; } WebPDecBuffer;
typedef struct WebPDecoderConfig { int bypass; WebPDecBuffer output; } WebPDecoderConfig;
int WebPDecode(const unsigned char *data, unsigned long size, WebPDecoderConfig *config);
void WebPFreeDecBuffer(WebPDecBuffer *buffer);
";

    #[test]
    fn a_nested_parse_errors_instead_of_deadlocking_forever() {
        let inner = header("reentrant_inner", SIMPLIFIED_API);
        let outcome: Result<(), ExtractError> = with_index(|_| {
            parse_header(&inner, &ParseOptions::default())?;
            Ok(())
        });
        assert!(matches!(outcome, Err(ExtractError::Reentrant)));
    }

    #[test]
    fn the_reentrancy_flag_is_cleared_so_the_next_parse_still_works() {
        let path = header("reentrant_after", SIMPLIFIED_API);
        let _ = with_index(|_| {
            parse_header(&path, &ParseOptions::default())?;
            Ok(())
        });
        assert!(parse_header(&path, &ParseOptions::default()).is_ok());
    }

    #[test]
    fn a_record_the_library_allocates_for_you_is_recorded_as_produced() {
        let vocab = vocabulary("produced", ZLIB_GZ_API);
        assert!(
            vocab.produced.contains("gzFile_s"),
            "gzopen returns struct gzFile_s *, so the exposed prefix is not a usable stack local"
        );
    }

    #[test]
    fn a_caller_allocated_context_is_not_recorded_as_produced() {
        let vocab = vocabulary("not_produced", SIMPLIFIED_API);
        assert!(!vocab.produced.contains("png_image"));
    }

    #[test]
    fn a_single_pointer_teardown_is_paired_with_its_record() {
        let vocab = vocabulary("teardown_camel", WEBP_API);
        assert_eq!(
            vocab.destructors.get("WebPDecBuffer"),
            Some(&BTreeSet::from(["WebPFreeDecBuffer".to_owned()])),
            "an unpaired constructor fabricates a LeakSanitizer report inside the target"
        );
    }

    #[test]
    fn a_teardown_is_found_through_a_run_of_capitals() {
        assert_eq!(
            identifier_words("WebPFreeDecBuffer"),
            vec!["Web", "P", "Free", "Dec", "Buffer"]
        );
    }

    #[test]
    fn a_verb_only_matches_a_whole_word_never_a_substring() {
        assert!(!is_teardown_name("archive_entry_append"));
        assert!(!is_teardown_name("png_extend_row"));
        assert!(is_teardown_name("inflateEnd"));
        assert!(is_teardown_name("archive_read_free"));
    }

    // B70. `identifier_words` splits `tj3Compress8` into `["tj3", "Compress8"]`, and
    // "Compress8" is not the word "compress", so libjpeg-turbo's whole compressor family
    // carried NO write signal anywhere in the tool. The digit sits in the MIDDLE of the
    // identifier, which is why the strip has to run per word rather than per name.
    #[test]
    fn a_trailing_digit_is_a_version_or_a_bit_depth_never_part_of_the_verb() {
        use crate::naming::{READ_WORDS, WRITE_WORDS};
        assert!(carries_word("tj3Compress8", &WRITE_WORDS));
        assert!(carries_word("tj3Compress16", &WRITE_WORDS));
        assert!(carries_word("tj3Decompress8", &READ_WORDS));
        assert!(carries_word("compress2", &WRITE_WORDS));
        assert!(carries_word("uncompress2", &READ_WORDS));
    }

    #[test]
    fn a_one_character_entry_is_a_wildcard_on_the_suffix_arm_and_never_matches_there() {
        let vocabulary = ["n", "len"];
        for name in ["align", "token", "column", "pattern", "origin", "main"] {
            assert!(
                !carries_word(name, &vocabulary),
                "{name} ends in n and would match a single-character entry as a suffix"
            );
        }
    }

    #[test]
    fn the_floor_applies_to_the_suffix_arm_alone_and_not_to_token_equality() {
        let vocabulary = ["n", "len"];
        assert!(
            carries_word("n", &vocabulary),
            "a parameter literally named n is an extent by token equality"
        );
        assert!(
            carries_word("num_n", &vocabulary),
            "n as a whole word must still match once there is a boundary to split on"
        );
    }

    #[test]
    fn a_two_character_entry_still_matches_as_a_suffix() {
        let vocabulary = ["sz", "len"];
        assert!(carries_word("bufsz", &vocabulary));
        assert!(
            carries_word("inlen", &vocabulary),
            "the suffix arm is load-bearing for all-lowercase extents and must survive the floor"
        );
    }

    // The isolating control for stripping per WORD rather than per name: the ladder's old
    // local workaround trimmed the whole identifier, which cannot reach a digit that is not
    // the last character. Both must pass, and only the per-word rule satisfies the second.
    #[test]
    fn a_digit_inside_the_identifier_is_reached_too_not_only_a_trailing_one() {
        use crate::naming::READ_WORDS;
        assert!(
            carries_word("Decompress8Bit", &READ_WORDS),
            "a whole-name trim stops at the final 't' and never sees Decompress8"
        );
    }

    // The other direction: stripping must not invent a word that was not there. These are
    // the shapes the census turned up across the seven trees - hash primitives, encodings
    // and type names whose stems sit next to real vocabulary entries.
    #[test]
    fn stripping_digits_does_not_manufacture_a_verb_that_was_never_written() {
        use crate::naming::{READ_WORDS, WRITE_WORDS};
        for name in [
            "crc32",
            "adler32",
            "sha256",
            "md5",
            "blake2xb",
            "poly1305",
            "xxh64",
            "utf8",
            "base64",
            "png16",
            "uint8",
            "VP8YuvToRgb32",
        ] {
            assert!(
                !carries_word(name, &READ_WORDS) && !carries_word(name, &WRITE_WORDS),
                "{name} carries no direction word and must not gain one"
            );
        }
    }

    #[test]
    fn an_all_lowercase_name_falls_back_to_a_suffix_match() {
        assert!(
            is_teardown_name("gzclose"),
            "a glued lowercase identifier has no boundary for the word split"
        );
        assert!(is_teardown_name("bzclose"));
        assert!(!is_teardown_name("gzread"));
    }

    #[test]
    fn the_teardown_verbs_cover_the_shapes_measured_on_real_libraries() {
        for name in [
            "FT_Done_Face",
            "g_object_unref",
            "zip_discard",
            "sqlite3_close_v2",
            "XML_ParserFree",
            "WebPFreeDecBuffer",
            "LZ4F_freeDecompressionContext",
        ] {
            assert!(is_teardown_name(name), "{name} should read as a teardown");
        }
    }

    #[test]
    fn a_const_return_is_a_borrow_not_an_allocation() {
        let vocab = vocabulary(
            "borrowed",
            "struct buf { int n; };\nvoid init_buf(struct buf *b);\nconst struct buf *peek_buf(void);\n",
        );
        assert!(
            !vocab.produced.contains("buf"),
            "libwebp's WebPIDecodedArea returns a const WebPDecBuffer * over a buffer the caller owns"
        );
    }

    #[test]
    fn a_non_const_return_is_still_an_allocation() {
        let vocab = vocabulary(
            "allocated",
            "struct buf { int n; };\nstruct buf *new_buf(void);\n",
        );
        assert!(vocab.produced.contains("buf"));
    }

    // B84. The pair that decides whether a slot is an allocation. `LZ4F_dctx_s`'s shape - opaque,
    // handed back through `int X_create(X **)`, freed by a destructor - must stay unavailable to
    // a caller, and it is the COMPLETENESS test that keeps it so: the header names the struct and
    // never defines it, so there is nothing to declare. Nothing needs `produced` to say it.
    #[test]
    fn a_record_handed_back_through_a_slot_it_never_defines_has_nothing_to_declare() {
        let vocab = vocabulary(
            "slotted_opaque",
            "struct dctx;\nint dctx_create(struct dctx **out);\nvoid dctx_free(struct dctx *d);\n",
        );
        assert!(!vocab.records.contains_key("dctx"));
    }

    // The other half, and the seven libpng records the deleted arm was costing. A getter handing
    // back a pointer INTO its own state says the library has an instance; it says nothing about
    // whether the caller may declare one, and `png_color` is three bytes the caller owns.
    #[test]
    fn a_record_a_getter_hands_back_is_still_the_callers_to_declare() {
        let vocab = vocabulary(
            "slotted_complete",
            "struct png_color_struct { unsigned char red; };\nstruct png_info;\n\
             unsigned png_get_PLTE(struct png_info *i, struct png_color_struct **palette);\n",
        );
        assert!(vocab.records.contains_key("png_color_struct"));
        assert!(
            !vocab.produced.contains("png_color_struct"),
            "a slot is not an allocation; only a returned non-const pointer is"
        );
    }

    #[test]
    fn a_multi_parameter_teardown_is_not_paired() {
        let vocab = vocabulary(
            "teardown_multi",
            "struct s { int a; };\nvoid s_destroy(struct s *p, int mode);\n",
        );
        assert!(vocab.destructors.is_empty());
    }

    #[test]
    fn every_teardown_candidate_for_one_record_is_kept_for_the_planner_to_choose() {
        let vocab = vocabulary(
            "teardown_many",
            "struct z_stream_s { int x; };\ntypedef struct z_stream_s z_stream;\nint deflateEnd(z_stream *s);\nint inflateEnd(z_stream *s);\n",
        );
        assert_eq!(vocab.destructors["z_stream_s"].len(), 2);
    }

    #[test]
    fn a_macro_is_collected_by_name() {
        let vocab = vocabulary("macros", SIMPLIFIED_API);
        assert!(vocab.macros.contains("PNG_IMAGE_VERSION"));
        assert!(vocab.macros.contains("PNG_FORMAT_RGBA"));
    }

    #[test]
    fn builtin_macros_are_not_collected() {
        let vocab = vocabulary("builtins", SIMPLIFIED_API);
        assert!(!vocab.macros.contains("__FILE__"));
        assert!(!vocab.macros.contains("__LINE__"));
    }

    // B82. libpng's real definitions, verbatim in shape: the size macro is written in terms of
    // two more, so its BODY carries nested parentheses and a comma. A count that walked the
    // whole definition instead of stopping at the parameter list would call it four.
    const SIZE_MACROS: &str = r"
#define PNG_IMAGE_VERSION 1
#define PNG_IMAGE_ROW_STRIDE(image) ((image).width)
#define PNG_IMAGE_BUFFER_SIZE(image, row_stride) ((image).height * (row_stride))
#define PNG_IMAGE_SIZE(image) PNG_IMAGE_BUFFER_SIZE(image, PNG_IMAGE_ROW_STRIDE(image))
#define PNG_IMAGE_NOTHING() 0
typedef struct png_image { unsigned int version; unsigned int width; } png_image;
int png_image_finish_read(png_image *image, void *buffer);
";

    #[test]
    fn a_function_like_macro_is_collected_with_the_number_of_arguments_it_takes() {
        let vocab = vocabulary("sizers", SIZE_MACROS);
        assert_eq!(vocab.sizers.get("PNG_IMAGE_SIZE"), Some(&1));
        assert_eq!(vocab.sizers.get("PNG_IMAGE_ROW_STRIDE"), Some(&1));
        assert_eq!(vocab.sizers.get("PNG_IMAGE_BUFFER_SIZE"), Some(&2));
        assert_eq!(vocab.sizers.get("PNG_IMAGE_NOTHING"), Some(&0));
    }

    // The two maps are separate because the two are spelled differently at every use site.
    // `field_bindings` writes a macro name verbatim into `ctx.version = X;`, and doing that
    // with `PNG_IMAGE_SIZE` does not compile.
    #[test]
    fn a_function_like_macro_never_reaches_the_map_that_populates_a_field() {
        let vocab = vocabulary("sizers_apart", SIZE_MACROS);
        assert!(vocab.macros.contains("PNG_IMAGE_VERSION"));
        assert!(!vocab.macros.contains("PNG_IMAGE_SIZE"));
        assert!(!vocab.sizers.contains_key("PNG_IMAGE_VERSION"));
    }

    #[test]
    fn a_record_is_keyed_the_same_way_a_pointee_is() {
        let vocab = vocabulary("records", SIMPLIFIED_API);
        let declared = parse("records_fn", SIMPLIFIED_API);
        let param = &named(&declared, "png_image_begin_read_from_memory").params[0];
        let Shape::Pointer {
            pointee: Pointee::Record(record),
            ..
        } = &param.shape
        else {
            panic!("expected a pointer to a record");
        };
        assert!(
            vocab.records.contains_key(record),
            "vocabulary keys {:?} do not contain the pointee key {record}",
            vocab.records.keys().collect::<Vec<_>>()
        );
    }

    #[test]
    fn record_fields_carry_names_and_shapes() {
        let vocab = vocabulary("fields", SIMPLIFIED_API);
        let record = vocab.records.values().next().expect("one record");
        let version = record
            .fields
            .iter()
            .find(|field| field.name == "version")
            .expect("version field");
        assert_eq!(version.shape, Shape::Integral);
    }

    #[test]
    fn a_tagged_record_keeps_its_struct_tag_even_when_typedefd() {
        let vocab = vocabulary("spelling_typedef", SIMPLIFIED_API);
        assert_eq!(vocab.records["png_image"].spelling, "struct png_image");
    }

    #[test]
    fn an_anonymous_typedefd_record_falls_back_to_a_declarable_name() {
        let vocab = vocabulary(
            "spelling_anon",
            "typedef struct { unsigned int version; } anon_ctx;\nvoid f(anon_ctx *c);",
        );
        let record = vocab.records.values().next().expect("one record");
        assert!(
            !record.spelling.contains('('),
            "`struct (unnamed at ...)` is not a declarable type, got {:?}",
            record.spelling
        );
    }

    #[test]
    fn a_record_with_no_typedef_keeps_its_struct_tag() {
        let vocab = vocabulary(
            "spelling_tag",
            "struct parser_ctx { unsigned int version; }; void f(struct parser_ctx *c);",
        );
        assert_eq!(
            vocab.records["parser_ctx"].spelling, "struct parser_ctx",
            "declaring `parser_ctx ctx;` without the tag is a hard compile error in C"
        );
    }

    #[test]
    fn function_like_macros_are_not_collected_because_they_cannot_be_values() {
        let vocab = vocabulary(
            "fnlike",
            "#define BLOB_CTX_SIZE(n) ((n) * 4u)\n#define BLOB_CTX_VERSION 2\ntypedef struct blob_ctx { unsigned int version; } blob_ctx;",
        );
        assert!(!vocab.macros.contains("BLOB_CTX_SIZE"));
        assert!(vocab.macros.contains("BLOB_CTX_VERSION"));
    }

    #[test]
    fn a_vocabulary_parse_that_does_not_type_check_is_an_error() {
        let path = header("vocab_broken", "#include \"nope/missing.h\"\nint f(void);");
        assert!(matches!(
            parse_vocabulary(&path, &ParseOptions::default()),
            Err(ExtractError::Diagnostics { .. })
        ));
    }

    #[test]
    fn a_record_with_no_fields_is_not_recorded() {
        let vocab = vocabulary(
            "opaque",
            "struct png_struct_def; void f(struct png_struct_def *p);",
        );
        assert!(vocab.records.is_empty());
    }

    #[test]
    fn absorbing_keeps_the_first_definition_of_a_record() {
        let mut left = Vocabulary::default();
        left.records.insert(
            "r".to_owned(),
            Record {
                spelling: "struct r".to_owned(),
                fields: vec![Field {
                    name: "a".to_owned(),
                    spelling: "int".to_owned(),
                    shape: Shape::Integral,
                }],
            },
        );
        let mut right = Vocabulary::default();
        right.records.insert("r".to_owned(), Record::default());
        right.macros.insert("M".to_owned());
        left.absorb(right);
        assert_eq!(left.records["r"].fields.len(), 1);
        assert!(left.macros.contains("M"));
    }

    fn named<'a>(found: &'a [Declared], name: &str) -> &'a Declared {
        found
            .iter()
            .find(|item| item.name == name)
            .unwrap_or_else(|| panic!("{name} not found in {:?}", names(found)))
    }

    fn names(found: &[Declared]) -> Vec<&str> {
        found.iter().map(|item| item.name.as_str()).collect()
    }

    #[test]
    fn a_plain_declaration_yields_its_name_and_parameters() {
        let found = parse(
            "plain",
            "int my_parse(const unsigned char *data, unsigned long size);\n",
        );
        let function = named(&found, "my_parse");
        assert_eq!(function.params.len(), 2);
        assert_eq!(function.params[0].name.as_deref(), Some("data"));
    }

    #[test]
    fn a_macro_wrapped_declaration_is_still_found() {
        let found = parse(
            "macrowrap",
            "#define MYAPI\n\
             #define MYEXPORT(ordinal, type, name, args) type (MYAPI name) args\n\
             MYEXPORT(1, int, png_style_parse, (const unsigned char *data, unsigned long size));\n",
        );
        assert!(
            found.iter().any(|item| item.name == "png_style_parse"),
            "libpng declares every function through a macro like this: {:?}",
            names(&found)
        );
    }

    #[test]
    fn declarations_pulled_in_from_another_header_are_not_part_of_this_surface() {
        let path = header(
            "included",
            "#include \"other.h\"\nint mine_parse(const unsigned char *d, unsigned long n);\n",
        );
        std::fs::write(
            path.parent().unwrap().join("other.h"),
            "int theirs_parse(const unsigned char *d, unsigned long n);\n",
        )
        .unwrap();
        let found = parse_header(&path, &ParseOptions::default()).unwrap();
        assert!(found.iter().any(|item| item.name == "mine_parse"));
        assert!(
            !found.iter().any(|item| item.name == "theirs_parse"),
            "{:?}",
            names(&found)
        );
    }

    #[test]
    fn a_typedef_chain_resolves_to_the_underlying_byte_type() {
        let found = parse(
            "typedefs",
            "typedef unsigned char byte_t;\n\
             typedef byte_t BYTE;\n\
             int parse_frame(BYTE *data, unsigned int len);\n",
        );
        let function = named(&found, "parse_frame");
        assert_eq!(
            function.params[0].shape,
            Shape::Pointer {
                pointee: Pointee::UnsignedChar,
                is_const: false,
            }
        );
        assert_eq!(function.params[1].shape, Shape::Integral);
    }

    #[test]
    fn const_is_read_off_the_pointee_not_the_pointer() {
        let found = parse("constness", "int f(const unsigned char *data, int n);\n");
        let function = named(&found, "f");
        assert_eq!(
            function.params[0].shape,
            Shape::Pointer {
                pointee: Pointee::UnsignedChar,
                is_const: true,
            }
        );
    }

    #[test]
    fn plain_char_is_ambiguous_and_never_reported_as_an_exact_byte() {
        let found = parse("plainchar", "int f(const char *text, int n);\n");
        let function = named(&found, "f");
        let Shape::Pointer { pointee, .. } = &function.params[0].shape else {
            panic!("expected a pointer");
        };
        assert_eq!(*pointee, Pointee::Char);
        assert!(
            !pointee.is_exact_byte(),
            "plain char is CharS here and CharU on ARM; it must not be an unambiguous byte"
        );
    }

    #[test]
    fn an_explicit_unsigned_char_is_an_exact_byte() {
        let found = parse("uchar", "int f(unsigned char *data, int n);\n");
        let Shape::Pointer { pointee, .. } = &named(&found, "f").params[0].shape else {
            panic!("expected a pointer");
        };
        assert!(pointee.is_exact_byte());
    }

    #[test]
    fn an_array_parameter_is_treated_as_the_pointer_it_decays_to() {
        let found = parse("array", "int f(unsigned char data[16], int n);\n");
        let function = named(&found, "f");
        assert_eq!(
            function.params[0].shape,
            Shape::Pointer {
                pointee: Pointee::UnsignedChar,
                is_const: false,
            }
        );
    }

    #[test]
    fn a_function_pointer_parameter_is_reported_as_a_callback() {
        let found = parse(
            "callback",
            "struct ctx;\n\
             typedef void (*read_fn)(struct ctx *, unsigned char *, unsigned long);\n\
             void set_read(struct ctx *c, void *user, read_fn fn);\n",
        );
        let function = named(&found, "set_read");
        assert_eq!(
            function.params[2].shape,
            Shape::Pointer {
                pointee: Pointee::Function(Some(Prototype {
                    returns: "void".to_owned(),
                    params: vec![
                        "struct ctx *".to_owned(),
                        "unsigned char *".to_owned(),
                        "unsigned long".to_owned(),
                    ],
                })),
                is_const: false,
            },
            "a callback that is recognised but carries no prototype cannot have a stub body \
             written for it, which is the whole reason B96 needed the payload"
        );
    }

    #[test]
    fn a_callback_with_no_prototype_carries_no_prototype() {
        let found = parse(
            "callbacknoproto",
            "struct ctx;\n\
             void set_read(struct ctx *c, void (*fn)());\n",
        );
        let function = named(&found, "set_read");
        assert_eq!(
            function.params[1].shape,
            Shape::Pointer {
                pointee: Pointee::Function(None),
                is_const: false,
            },
            "an unprototyped function pointer states a return type and nothing else, so \
             guessing its arguments is exactly what the refusal must keep refusing"
        );
    }

    #[test]
    fn a_stdio_stream_parameter_is_recognised_through_its_glibc_record_name() {
        let found = parse("stdio", "#include <stdio.h>\nint f(FILE *fp);\n");
        let function = named(&found, "f");
        let analysis = crate::signature::analyze(&function.params);
        assert_eq!(
            analysis.fuzzability,
            crate::signature::Fuzzability::Stream,
            "FILE* canonicalises to struct _IO_FILE on glibc: {:?}",
            function.params[0].shape
        );
    }

    #[test]
    fn a_header_that_does_not_type_check_is_refused_rather_than_guessed_at() {
        let path = header("broken", "int parse_frame(BYTE *data, uint32_t len);\n");
        let error = parse_header(&path, &ParseOptions::default()).unwrap_err();
        assert!(
            matches!(error, ExtractError::Diagnostics { .. }),
            "an unresolved typedef silently degrades BYTE* to int*, halving buffer \
             detection, so it must be an error: {error:?}"
        );
    }

    #[test]
    fn an_include_path_repairs_a_header_that_would_otherwise_be_refused() {
        let path = header(
            "repaired",
            "#include \"types.h\"\nint parse_frame(BYTE *data, unsigned int len);\n",
        );
        let inc = path.parent().unwrap().join("inc");
        std::fs::create_dir_all(&inc).unwrap();
        std::fs::write(inc.join("types.h"), "typedef unsigned char BYTE;\n").unwrap();
        let options = ParseOptions {
            includes: vec![inc],
            ..ParseOptions::default()
        };
        let found = parse_header(&path, &options).unwrap();
        let Shape::Pointer { pointee, .. } = &named(&found, "parse_frame").params[0].shape else {
            panic!("expected a pointer");
        };
        assert_eq!(*pointee, Pointee::UnsignedChar);
    }

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

    const GENERATED_CONFIG: &str = "typedef unsigned char CONFIGURED;\n";

    fn tree(label: &str, files: &[(&str, &str)]) -> PathBuf {
        let root = lisdex_core::scratch::path(&format!("extract-tree-{label}"));
        let _ = std::fs::remove_dir_all(&root);
        for (relative, body) in files {
            let path = root.join(relative);
            std::fs::create_dir_all(path.parent().unwrap()).unwrap();
            std::fs::write(&path, body).unwrap();
        }
        root
    }

    // F1. brotli angle-includes its OWN public headers, so an angled include is not proof of
    // somebody else's file. The tree shipping a header at that sub-path is what settles it.
    #[test]
    fn an_angled_include_of_a_header_the_tree_owns_is_refused() {
        let root = tree(
            "angledowned",
            &[
                ("inc/proj/port.h", GENERATED_CONFIG),
                (
                    "api.h",
                    "#include <proj/port.h>\nint parse(CONFIGURED *d, unsigned long n);\n",
                ),
            ],
        );
        let foreign = tree("angledforeign", &[("proj/port.h", GENERATED_CONFIG)]);
        let options = ParseOptions {
            extra_args: vec![format!("-I{}", foreign.display())],
            tree_headers: vec![root.join("inc/proj/port.h")],
            ..ParseOptions::default()
        };
        let error = parse_header(&root.join("api.h"), &options).unwrap_err();
        let ExtractError::ForeignInclude { spelling, .. } = &error else {
            panic!("an angled include of a header the tree owns is the brotli case: {error:?}");
        };
        assert_eq!(spelling, "proj/port.h");
    }

    // The isolating control for the rule above: byte-identical fixture, the tree simply does
    // not own a matching header, so this is an ordinary system include and must be accepted.
    #[test]
    fn an_angled_include_the_tree_does_not_own_is_still_accepted() {
        let root = tree(
            "angledunowned",
            &[(
                "api.h",
                "#include <proj/port.h>\nint parse(CONFIGURED *d, unsigned long n);\n",
            )],
        );
        let foreign = tree("angledunownedforeign", &[("proj/port.h", GENERATED_CONFIG)]);
        let options = ParseOptions {
            extra_args: vec![format!("-I{}", foreign.display())],
            ..ParseOptions::default()
        };
        let found = parse_header(&root.join("api.h"), &options).unwrap();
        assert!(found.iter().any(|item| item.name == "parse"), "{found:?}");
    }

    // F2. libarchive ships `#include PLATFORM_CONFIG_H`. A computed include carries neither a
    // quote token nor an angle token, so it must not fall through to the permissive branch.
    // The dominant B30 shape: a config the build generates, whose name carries no project
    // token at all (jconfig.h, tiffconf.h, opj_config.h). The tree shipping jconfig.h.in is
    // what proves the header is this build's own.
    #[test]
    fn a_header_the_tree_only_ships_a_generator_for_is_still_owned() {
        let root = tree(
            "generated",
            &[(
                "api.h",
                "#include \"genconf.h\"\nint parse(CONFIGURED *d, unsigned long n);\n",
            )],
        );
        let foreign = tree("generatedforeign", &[("genconf.h", GENERATED_CONFIG)]);
        let options = ParseOptions {
            extra_args: vec![format!("-I{}", foreign.display())],
            tree_headers: vec![root.join("src/genconf.h")],
            ..ParseOptions::default()
        };
        let error = parse_header(&root.join("api.h"), &options).unwrap_err();
        assert!(
            matches!(error, ExtractError::ForeignInclude { .. }),
            "the tree generates this header, so a copy from elsewhere is the wrong one: {error:?}"
        );
    }

    #[test]
    fn a_project_token_too_short_to_discriminate_marks_nothing_as_owned() {
        let path = header(
            "shorttoken",
            "#include \"zconf.h\"\nint parse_frame(CONFIGURED *d, unsigned long n);\n",
        );
        let elsewhere = outside_tree("shorttoken", "zconf.h", GENERATED_CONFIG);
        let options = ParseOptions {
            extra_args: vec![format!("-I{}", elsewhere.display())],
            project: "z".to_owned(),
            ..ParseOptions::default()
        };
        let found = parse_header(&path, &options).unwrap();
        assert!(
            found.iter().any(|item| item.name == "parse_frame"),
            "a one-letter token would mark half of every include set as ours: {:?}",
            names(&found)
        );
    }

    #[test]
    fn a_computed_include_resolved_outside_the_tree_is_refused() {
        let root = tree(
            "computed",
            &[(
                "api.h",
                "#define PLATFORM_CONFIG \"conf.h\"\n#include PLATFORM_CONFIG\n\
                 int parse(CONFIGURED *d, unsigned long n);\n",
            )],
        );
        let foreign = tree("computedforeign", &[("conf.h", GENERATED_CONFIG)]);
        let options = ParseOptions {
            extra_args: vec![format!("-I{}", foreign.display())],
            ..ParseOptions::default()
        };
        let error = parse_header(&root.join("api.h"), &options).unwrap_err();
        assert!(
            matches!(error, ExtractError::ForeignInclude { .. }),
            "a macro-spelled include still names a file this library owns: {error:?}"
        );
    }

    #[test]
    fn a_computed_include_resolved_inside_the_tree_is_accepted() {
        let root = tree(
            "computedlocal",
            &[
                ("conf.h", GENERATED_CONFIG),
                (
                    "api.h",
                    "#define PLATFORM_CONFIG \"conf.h\"\n#include PLATFORM_CONFIG\n\
                     int parse(CONFIGURED *d, unsigned long n);\n",
                ),
            ],
        );
        let found = parse_header(&root.join("api.h"), &ParseOptions::default()).unwrap();
        assert!(found.iter().any(|item| item.name == "parse"), "{found:?}");
    }

    // F6. An out-of-tree build that symlinks its generated config into the source tree is a
    // normal layout, and the link lives inside the tree even though its target does not.
    #[test]
    fn a_symlink_from_inside_the_tree_to_a_generated_header_is_not_foreign() {
        let root = tree(
            "symlinked",
            &[(
                "api.h",
                "#include \"conf.h\"\nint parse(CONFIGURED *d, unsigned long n);\n",
            )],
        );
        let built = tree("symlinkedbuild", &[("conf.h", GENERATED_CONFIG)]);
        std::os::unix::fs::symlink(built.join("conf.h"), root.join("conf.h")).unwrap();
        let found = parse_header(&root.join("api.h"), &ParseOptions::default()).unwrap();
        assert!(found.iter().any(|item| item.name == "parse"), "{found:?}");
    }

    // F7. The refusal has to name the file that WROTE the include, not the file the parse
    // happened to start from, or the diagnosis points at the wrong place in a deep tree.
    #[test]
    fn the_refusal_names_the_file_that_wrote_the_include() {
        let root = tree(
            "attribution",
            &[
                (
                    "sub/deep.h",
                    "#include \"lisdexconf.h\"\ntypedef unsigned char DEEP;\n",
                ),
                (
                    "api.h",
                    "#include \"sub/deep.h\"\nint parse(CONFIGURED *d, unsigned long n);\n",
                ),
            ],
        );
        let foreign = tree("attributionforeign", &[("lisdexconf.h", GENERATED_CONFIG)]);
        let options = ParseOptions {
            extra_args: vec![format!("-I{}", foreign.display())],
            project: "lisdex".to_owned(),
            ..ParseOptions::default()
        };
        let error = parse_header(&root.join("api.h"), &options).unwrap_err();
        let ExtractError::ForeignInclude { includer, .. } = &error else {
            panic!("{error:?}");
        };
        assert!(
            includer.ends_with("sub/deep.h"),
            "the include was written by sub/deep.h, not by the parse target: {includer:?}"
        );
    }

    #[test]
    fn a_quoted_include_resolved_outside_every_trusted_root_is_refused() {
        let path = header(
            "foreignquoted",
            "#include \"lisdexconf.h\"\nint parse_frame(CONFIGURED *d, unsigned long n);\n",
        );
        let elsewhere = outside_tree("foreignquoted", "lisdexconf.h", GENERATED_CONFIG);
        let options = ParseOptions {
            extra_args: vec![format!("-I{}", elsewhere.display())],
            project: "lisdex".to_owned(),
            ..ParseOptions::default()
        };
        let error = parse_header(&path, &options).unwrap_err();
        let ExtractError::ForeignInclude {
            spelling, resolved, ..
        } = &error
        else {
            panic!("a foreign copy of a generated header must be refused, not parsed: {error:?}");
        };
        assert_eq!(spelling, "lisdexconf.h");
        assert!(resolved.starts_with(&elsewhere), "{resolved:?}");
    }

    // The isolating control for the rule above: byte-identical fixture and resolution, the
    // only difference is that nothing marks the header as this project's. This is libpng,
    // which writes `#include "zlib.h"` with quotes for a real external dependency - treating
    // the quote as proof of ownership refused libpng outright and took the M3 gate down with
    // it. If ownership stops being required, this test fails while the one above still
    // passes, so neither can alibi the other.
    #[test]
    fn a_quoted_include_of_an_external_dependency_is_not_foreign() {
        let path = header(
            "externaldep",
            "#include \"zlib.h\"\nint parse_frame(CONFIGURED *d, unsigned long n);\n",
        );
        let elsewhere = outside_tree("externaldep", "zlib.h", GENERATED_CONFIG);
        let options = ParseOptions {
            extra_args: vec![format!("-I{}", elsewhere.display())],
            project: "lisdex".to_owned(),
            ..ParseOptions::default()
        };
        let found = parse_header(&path, &options).unwrap();
        assert!(
            found.iter().any(|item| item.name == "parse_frame"),
            "a quoted include naming nothing this project owns is a dependency, not a \
             foreign copy of our own header: {:?}",
            names(&found)
        );
    }

    #[test]
    fn a_quoted_include_beside_the_header_is_not_foreign() {
        let path = header(
            "quotedsibling",
            "#include \"lisdexconf.h\"\nint parse_frame(CONFIGURED *d, unsigned long n);\n",
        );
        std::fs::write(
            path.parent().unwrap().join("lisdexconf.h"),
            GENERATED_CONFIG,
        )
        .unwrap();
        let found = parse_header(&path, &ParseOptions::default()).unwrap();
        assert!(
            found.iter().any(|item| item.name == "parse_frame"),
            "{:?}",
            names(&found)
        );
    }

    #[test]
    fn a_foreign_quoted_include_is_refused_when_mining_the_vocabulary_too() {
        let path = header(
            "foreignvocab",
            "#include \"lisdexconf.h\"\ntypedef struct ctx { int v; } ctx;\nint parse(ctx *c, CONFIGURED *d);\n",
        );
        let elsewhere = outside_tree("foreignvocab", "lisdexconf.h", GENERATED_CONFIG);
        let options = ParseOptions {
            extra_args: vec![format!("-I{}", elsewhere.display())],
            project: "lisdex".to_owned(),
            ..ParseOptions::default()
        };
        let error = parse_vocabulary(&path, &options).unwrap_err();
        assert!(
            matches!(error, ExtractError::ForeignInclude { .. }),
            "the harness compiles against these records, so the vocabulary path needs the \
             same refusal as the declaration path: {error:?}"
        );
    }

    #[test]
    fn functions_inside_an_extern_c_block_are_not_missed() {
        let path = header(
            "externc",
            "extern \"C\" {\nint inner_parse(const unsigned char *d, unsigned long n);\n}\n",
        );
        let options = ParseOptions {
            language: Language::Cpp,
            ..ParseOptions::default()
        };
        let found = parse_header(&path, &options).unwrap();
        assert!(
            found.iter().any(|item| item.name == "inner_parse"),
            "clang::sonar misses these entirely: {:?}",
            names(&found)
        );
    }

    #[test]
    fn a_definition_in_a_header_is_reported_once_not_twice() {
        let found = parse(
            "dedup",
            "int f(const unsigned char *d, unsigned long n);\n\
             int f(const unsigned char *d, unsigned long n);\n",
        );
        assert_eq!(
            found.iter().filter(|item| item.name == "f").count(),
            1,
            "{:?}",
            names(&found)
        );
    }

    #[test]
    fn a_missing_file_is_an_error_not_a_panic() {
        let error = parse_header(
            std::path::Path::new("/nonexistent/lisdex/extract.h"),
            &ParseOptions::default(),
        )
        .unwrap_err();
        assert!(matches!(error, ExtractError::NotAFile(_)), "{error:?}");
    }
}