use std::collections::BTreeMap;
use crate::{CiteError, Result};
const NON_ENTRY_TYPES: [&str; 2] = ["comment", "string"];
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Entry {
pub entry_type: String,
pub fields: BTreeMap<String, String>,
}
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() {
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)
}
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))
}
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 {
if part.trim().is_empty() {
continue;
}
let (name, value) = parse_field(part, &key)?;
fields.insert(name, value);
}
Ok((key, fields))
}
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..])))
}
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(" ")
}
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),
'"' 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
}
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;