mini-cite 0.2.0

BibTeX-backed inline citations and footnotes for the mini-* family.
Documentation
//! Minimal BibTeX entry parser.
//!
//! Supports the subset real-world `.bib` files actually rely on: `@type{key, field
//! = {value}, field = "value"}` blocks, brace-nested values, multi-line values, and
//! trailing commas. Deliberately unsupported: `@string` macro expansion, `crossref`
//! inheritance, and TeX accent-escape resolution — an accent escape is captured as the
//! literal text the source wrote.

use std::collections::BTreeMap;

use crate::{CiteError, Result};

/// Entry types that carry no bibliographic record and are discarded after parsing.
///
/// They are still scanned for balanced delimiters rather than skipped textually — a
/// `@comment` body can itself contain braces, and desyncing on one would corrupt
/// every entry after it.
const NON_ENTRY_TYPES: [&str; 2] = ["comment", "string"];

/// A single parsed BibTeX entry.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Entry {
    /// The entry type as written after `@`, lowercased (`article`, `book`, ...).
    pub entry_type: String,
    /// Field values keyed by lowercased field name.
    ///
    /// BibTeX field names are conventionally case-insensitive and vary by exporting
    /// tool (`Author`, `AUTHOR`, `author`), so they are normalized here — callers
    /// look up fixed lowercase names without matching case themselves.
    pub fields: BTreeMap<String, String>,
}

/// Parses every entry in a `.bib` source string, in file order.
///
/// Text outside an `@type{...}` block is skipped: real `.bib` files carry prose
/// preambles and editor comments between entries. `@comment` and `@string` blocks are
/// parsed for structure and discarded.
///
/// Returns [`CiteError::Parse`] with `file: None` — the caller knows which file this
/// source came from and attaches that context (see [`crate::Bibliography::load_dir`]).
pub fn parse_entries(source: &str) -> Result<Vec<(String, Entry)>> {
    let chars: Vec<char> = source.chars().collect();
    let mut entries = Vec::new();
    let mut cursor = 0;

    while cursor < chars.len() {
        // Text between entries is not an error — skip to the next entry marker.
        let Some(at_sign) = find_next(&chars, cursor, '@') else {
            break;
        };

        let (key_and_entry, next) = parse_entry(&chars, at_sign)?;
        if let Some((key, entry)) = key_and_entry {
            entries.push((key, entry));
        }

        debug_assert!(next > cursor, "parse_entry must consume input");
        cursor = next;
    }

    Ok(entries)
}

/// Parses one `@type{...}` block starting at `at_sign`.
///
/// Returns the entry (or `None` for a discarded `@comment`/`@string` block) and the
/// index just past the block's closing brace.
fn parse_entry(chars: &[char], at_sign: usize) -> Result<(Option<(String, Entry)>, usize)> {
    debug_assert_eq!(chars[at_sign], '@', "parse_entry must start at an '@'");

    let type_start = at_sign + 1;
    let Some(open_brace) = find_next(chars, type_start, '{') else {
        return Err(parse_error("entry has no opening `{`"));
    };

    let entry_type = collect(chars, type_start, open_brace).trim().to_lowercase();
    if entry_type.is_empty() {
        return Err(parse_error("entry has no type between `@` and `{`"));
    }

    let close_brace = match_closing_brace(chars, open_brace)?;
    let body = collect(chars, open_brace + 1, close_brace);
    let past_entry = close_brace + 1;

    if NON_ENTRY_TYPES.contains(&entry_type.as_str()) {
        return Ok((None, past_entry));
    }

    let (key, fields) = parse_body(&body)?;
    Ok((Some((key, Entry { entry_type, fields })), past_entry))
}

/// Splits an entry body (the text inside the outermost braces) into its citation key
/// and fields.
fn parse_body(body: &str) -> Result<(String, BTreeMap<String, String>)> {
    let parts = split_top_level_commas(body);
    let Some((key_part, field_parts)) = parts.split_first() else {
        return Err(parse_error("entry body is empty"));
    };

    let key = key_part.trim().to_string();
    if key.is_empty() {
        return Err(parse_error("entry has no citation key"));
    }

    let mut fields = BTreeMap::new();
    for part in field_parts {
        // A trailing comma leaves an empty final segment; that is well-formed BibTeX.
        if part.trim().is_empty() {
            continue;
        }
        let (name, value) = parse_field(part, &key)?;
        // Last value wins on a duplicated field name, matching BibTeX tooling.
        fields.insert(name, value);
    }

    Ok((key, fields))
}

/// Parses one `name = value` field segment.
fn parse_field(segment: &str, key: &str) -> Result<(String, String)> {
    let Some(equals) = segment.find('=') else {
        return Err(parse_error(&format!(
            "field in entry `{key}` has no `=`: `{}`",
            segment.trim()
        )));
    };

    let name = segment[..equals].trim().to_lowercase();
    if name.is_empty() {
        return Err(parse_error(&format!(
            "field in entry `{key}` has no name before `=`"
        )));
    }

    Ok((name, unwrap_value(&segment[equals + 1..])))
}

/// Strips the delimiters and TeX capitalization braces from a field value and
/// collapses the internal whitespace a multi-line value carries.
///
/// A bare value (`year = 2020`) has no delimiters to strip and is returned trimmed.
///
/// Inner braces are removed rather than preserved: in BibTeX they mark text whose
/// capitalization a style must not alter (`title = {A {Special} Title}`), which has no
/// meaning once the value is rendered into HTML — keeping them would print a literal
/// `A {Special} Title` in the footnote.
fn unwrap_value(raw: &str) -> String {
    let trimmed = raw.trim();

    let inner = match (trimmed.chars().next(), trimmed.chars().last()) {
        (Some('{'), Some('}')) if trimmed.len() >= 2 => &trimmed[1..trimmed.len() - 1],
        (Some('"'), Some('"')) if trimmed.len() >= 2 => &trimmed[1..trimmed.len() - 1],
        _ => trimmed,
    };

    inner
        .split_whitespace()
        .map(|word| word.replace(['{', '}'], ""))
        .filter(|word| !word.is_empty())
        .collect::<Vec<_>>()
        .join(" ")
}

/// Splits an entry body on commas that sit at brace depth zero and outside quotes.
///
/// Commas inside a value (`author = {Smith, John}`) separate names, not fields, so
/// splitting on every comma would shred multi-author entries.
fn split_top_level_commas(body: &str) -> Vec<String> {
    let mut parts = Vec::new();
    let mut current = String::new();
    let mut depth: usize = 0;
    let mut in_quotes = false;

    for c in body.chars() {
        match c {
            '{' => depth += 1,
            '}' => depth = depth.saturating_sub(1),
            // A quote only opens/closes a value at depth zero; inside braces it is
            // literal text (`title = {He said "hi"}`).
            '"' if depth == 0 => in_quotes = !in_quotes,
            ',' if depth == 0 && !in_quotes => {
                parts.push(std::mem::take(&mut current));
                continue;
            }
            _ => {}
        }
        current.push(c);
    }
    parts.push(current);

    parts
}

/// Returns the index of the `}` closing the `{` at `open`, tracking nesting.
///
/// Nested braces are how BibTeX preserves capitalization (`title = {A {Special}
/// Title}`), so stopping at the first `}` would truncate ordinary entries.
fn match_closing_brace(chars: &[char], open: usize) -> Result<usize> {
    debug_assert_eq!(chars[open], '{', "match_closing_brace must start at an open brace");

    let mut depth: usize = 0;
    for (offset, c) in chars[open..].iter().enumerate() {
        match c {
            '{' => depth += 1,
            '}' => {
                depth -= 1;
                if depth == 0 {
                    return Ok(open + offset);
                }
            }
            _ => {}
        }
    }

    Err(parse_error("entry has no matching closing `}`"))
}

fn find_next(chars: &[char], from: usize, target: char) -> Option<usize> {
    chars[from..].iter().position(|&c| c == target).map(|i| from + i)
}

fn collect(chars: &[char], start: usize, end: usize) -> String {
    chars[start..end].iter().collect()
}

fn parse_error(message: &str) -> CiteError {
    CiteError::Parse {
        file: None,
        message: message.to_string(),
    }
}

#[cfg(test)]
#[path = "../tests/unit/parser.rs"]
mod tests;