1use std::collections::BTreeMap;
10
11use crate::{CiteError, Result};
12
13const NON_ENTRY_TYPES: [&str; 2] = ["comment", "string"];
19
20#[derive(Debug, Clone, PartialEq, Eq)]
22pub struct Entry {
23 pub entry_type: String,
25 pub fields: BTreeMap<String, String>,
31}
32
33pub 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 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
64fn 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
93fn 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 if part.trim().is_empty() {
110 continue;
111 }
112 let (name, value) = parse_field(part, &key)?;
113 fields.insert(name, value);
115 }
116
117 Ok((key, fields))
118}
119
120fn 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
139fn 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
165fn 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 '"' 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
195fn 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;