Skip to main content

mini_cite/
parser.rs

1//! Minimal BibTeX entry parser.
2//!
3//! Supports the subset real-world `.bib` files actually rely on: `@type{key, field
4//! = {value}, field = "value"}` blocks, brace-nested values, multi-line values, and
5//! trailing commas. Deliberately unsupported: `@string` macro expansion, `crossref`
6//! inheritance, and TeX accent-escape resolution — an accent escape is captured as the
7//! literal text the source wrote.
8
9use std::collections::BTreeMap;
10
11use crate::{CiteError, Result};
12
13/// Entry types that carry no bibliographic record and are discarded after parsing.
14///
15/// They are still scanned for balanced delimiters rather than skipped textually — a
16/// `@comment` body can itself contain braces, and desyncing on one would corrupt
17/// every entry after it.
18const NON_ENTRY_TYPES: [&str; 2] = ["comment", "string"];
19
20/// A single parsed BibTeX entry.
21#[derive(Debug, Clone, PartialEq, Eq)]
22pub struct Entry {
23    /// The entry type as written after `@`, lowercased (`article`, `book`, ...).
24    pub entry_type: String,
25    /// Field values keyed by lowercased field name.
26    ///
27    /// BibTeX field names are conventionally case-insensitive and vary by exporting
28    /// tool (`Author`, `AUTHOR`, `author`), so they are normalized here — callers
29    /// look up fixed lowercase names without matching case themselves.
30    pub fields: BTreeMap<String, String>,
31}
32
33/// Parses every entry in a `.bib` source string, in file order.
34///
35/// Text outside an `@type{...}` block is skipped: real `.bib` files carry prose
36/// preambles and editor comments between entries. `@comment` and `@string` blocks are
37/// parsed for structure and discarded.
38///
39/// Returns [`CiteError::Parse`] with `file: None` — the caller knows which file this
40/// source came from and attaches that context (see [`crate::Bibliography::load_dir`]).
41pub fn parse_entries(source: &str) -> Result<Vec<(String, Entry)>> {
42    let chars: Vec<char> = source.chars().collect();
43    let mut entries = Vec::new();
44    let mut cursor = 0;
45
46    while cursor < chars.len() {
47        // Text between entries is not an error — skip to the next entry marker.
48        let Some(at_sign) = find_next(&chars, cursor, '@') else {
49            break;
50        };
51
52        let (key_and_entry, next) = parse_entry(&chars, at_sign)?;
53        if let Some((key, entry)) = key_and_entry {
54            entries.push((key, entry));
55        }
56
57        debug_assert!(next > cursor, "parse_entry must consume input");
58        cursor = next;
59    }
60
61    Ok(entries)
62}
63
64/// Parses one `@type{...}` block starting at `at_sign`.
65///
66/// Returns the entry (or `None` for a discarded `@comment`/`@string` block) and the
67/// index just past the block's closing brace.
68fn parse_entry(chars: &[char], at_sign: usize) -> Result<(Option<(String, Entry)>, usize)> {
69    debug_assert_eq!(chars[at_sign], '@', "parse_entry must start at an '@'");
70
71    let type_start = at_sign + 1;
72    let Some(open_brace) = find_next(chars, type_start, '{') else {
73        return Err(parse_error("entry has no opening `{`"));
74    };
75
76    let entry_type = collect(chars, type_start, open_brace).trim().to_lowercase();
77    if entry_type.is_empty() {
78        return Err(parse_error("entry has no type between `@` and `{`"));
79    }
80
81    let close_brace = match_closing_brace(chars, open_brace)?;
82    let body = collect(chars, open_brace + 1, close_brace);
83    let past_entry = close_brace + 1;
84
85    if NON_ENTRY_TYPES.contains(&entry_type.as_str()) {
86        return Ok((None, past_entry));
87    }
88
89    let (key, fields) = parse_body(&body)?;
90    Ok((Some((key, Entry { entry_type, fields })), past_entry))
91}
92
93/// Splits an entry body (the text inside the outermost braces) into its citation key
94/// and fields.
95fn parse_body(body: &str) -> Result<(String, BTreeMap<String, String>)> {
96    let parts = split_top_level_commas(body);
97    let Some((key_part, field_parts)) = parts.split_first() else {
98        return Err(parse_error("entry body is empty"));
99    };
100
101    let key = key_part.trim().to_string();
102    if key.is_empty() {
103        return Err(parse_error("entry has no citation key"));
104    }
105
106    let mut fields = BTreeMap::new();
107    for part in field_parts {
108        // A trailing comma leaves an empty final segment; that is well-formed BibTeX.
109        if part.trim().is_empty() {
110            continue;
111        }
112        let (name, value) = parse_field(part, &key)?;
113        // Last value wins on a duplicated field name, matching BibTeX tooling.
114        fields.insert(name, value);
115    }
116
117    Ok((key, fields))
118}
119
120/// Parses one `name = value` field segment.
121fn parse_field(segment: &str, key: &str) -> Result<(String, String)> {
122    let Some(equals) = segment.find('=') else {
123        return Err(parse_error(&format!(
124            "field in entry `{key}` has no `=`: `{}`",
125            segment.trim()
126        )));
127    };
128
129    let name = segment[..equals].trim().to_lowercase();
130    if name.is_empty() {
131        return Err(parse_error(&format!(
132            "field in entry `{key}` has no name before `=`"
133        )));
134    }
135
136    Ok((name, unwrap_value(&segment[equals + 1..])))
137}
138
139/// Strips the delimiters and TeX capitalization braces from a field value and
140/// collapses the internal whitespace a multi-line value carries.
141///
142/// A bare value (`year = 2020`) has no delimiters to strip and is returned trimmed.
143///
144/// Inner braces are removed rather than preserved: in BibTeX they mark text whose
145/// capitalization a style must not alter (`title = {A {Special} Title}`), which has no
146/// meaning once the value is rendered into HTML — keeping them would print a literal
147/// `A {Special} Title` in the footnote.
148fn unwrap_value(raw: &str) -> String {
149    let trimmed = raw.trim();
150
151    let inner = match (trimmed.chars().next(), trimmed.chars().last()) {
152        (Some('{'), Some('}')) if trimmed.len() >= 2 => &trimmed[1..trimmed.len() - 1],
153        (Some('"'), Some('"')) if trimmed.len() >= 2 => &trimmed[1..trimmed.len() - 1],
154        _ => trimmed,
155    };
156
157    inner
158        .split_whitespace()
159        .map(|word| word.replace(['{', '}'], ""))
160        .filter(|word| !word.is_empty())
161        .collect::<Vec<_>>()
162        .join(" ")
163}
164
165/// Splits an entry body on commas that sit at brace depth zero and outside quotes.
166///
167/// Commas inside a value (`author = {Smith, John}`) separate names, not fields, so
168/// splitting on every comma would shred multi-author entries.
169fn split_top_level_commas(body: &str) -> Vec<String> {
170    let mut parts = Vec::new();
171    let mut current = String::new();
172    let mut depth: usize = 0;
173    let mut in_quotes = false;
174
175    for c in body.chars() {
176        match c {
177            '{' => depth += 1,
178            '}' => depth = depth.saturating_sub(1),
179            // A quote only opens/closes a value at depth zero; inside braces it is
180            // literal text (`title = {He said "hi"}`).
181            '"' if depth == 0 => in_quotes = !in_quotes,
182            ',' if depth == 0 && !in_quotes => {
183                parts.push(std::mem::take(&mut current));
184                continue;
185            }
186            _ => {}
187        }
188        current.push(c);
189    }
190    parts.push(current);
191
192    parts
193}
194
195/// Returns the index of the `}` closing the `{` at `open`, tracking nesting.
196///
197/// Nested braces are how BibTeX preserves capitalization (`title = {A {Special}
198/// Title}`), so stopping at the first `}` would truncate ordinary entries.
199fn match_closing_brace(chars: &[char], open: usize) -> Result<usize> {
200    debug_assert_eq!(chars[open], '{', "match_closing_brace must start at an open brace");
201
202    let mut depth: usize = 0;
203    for (offset, c) in chars[open..].iter().enumerate() {
204        match c {
205            '{' => depth += 1,
206            '}' => {
207                depth -= 1;
208                if depth == 0 {
209                    return Ok(open + offset);
210                }
211            }
212            _ => {}
213        }
214    }
215
216    Err(parse_error("entry has no matching closing `}`"))
217}
218
219fn find_next(chars: &[char], from: usize, target: char) -> Option<usize> {
220    chars[from..].iter().position(|&c| c == target).map(|i| from + i)
221}
222
223fn collect(chars: &[char], start: usize, end: usize) -> String {
224    chars[start..end].iter().collect()
225}
226
227fn parse_error(message: &str) -> CiteError {
228    CiteError::Parse {
229        file: None,
230        message: message.to_string(),
231    }
232}
233
234#[cfg(test)]
235#[path = "../tests/unit/parser.rs"]
236mod tests;