Oregami
Repositories/oxedyne/fe2o3

oxedyne/fe2o3/fe2o3_austenite/src/bib_hayagriva.rs

9.0 KiB, 1 run

created by r1870400018:73715, which is this file's identity for as long as the history lasts, whatever it is later renamed to

download · who wrote it · its history

1// SPDX-License-Identifier: Apache-2.0
2// Hayagriva YAML read into `bib::Entry`, the model the BibTeX reader fills (B6, 2026-10-12). The YAML is
3// parsed by the evaluator's own reader (`eval::lib::data::yaml_parse`, the one behind Typst's `yaml()`);
4// this file maps its value. Each field lands under the BibTeX name the formatters read, and a `parent` is
5// flattened into the container fields BibLaTeX would hold: a periodical's title becomes `journal`, a book's
6// or proceedings' `booktitle`, and the parent's volume, issue, publisher, location, editors and date fill
7// whatever the child leaves unset. Types follow hayagriva 0.10's BibLaTeX interop read in reverse.
8
9use crate::bib::{
10 Entry,
11 EntryKind,
12 Name,
13};
14use crate::eval::value::{
15 Dict,
16 Value,
17};
18
19use oxedyne_fe2o3_core::prelude::*;
20
21/// Reads a parsed Hayagriva document (a dictionary of entries keyed by citation key) into entries, in
22/// file order. A fault is returned as the diagnostic's text.
23pub fn entries(doc: &Value) -> std::result::Result<Vec<Entry>, String> {
24 let top = match doc {
25 Value::Dict(d) => d,
26 Value::None => return Ok(Vec::new()),
27 other => return Err(fmt!(
28 "a Hayagriva bibliography is a dictionary of entries, found {}", other.ty().long_name())),
29 };
30 let mut out = Vec::with_capacity(top.len());
31 for (key, v) in top.iter() {
32 match v {
33 Value::Dict(d) => out.push(entry(key, d)),
34 other => return Err(fmt!(
35 "the Hayagriva entry `{}` must be a dictionary, found {}", key, other.ty().long_name())),
36 }
37 }
38 Ok(out)
39}
40
41fn entry(key: &str, d: &Dict) -> Entry {
42 let ty = text(d.get("type")).map(|t| t.to_ascii_lowercase()).unwrap_or_default();
43 let parent = match d.get("parent") {
44 Some(Value::Dict(p)) => Some(&**p),
45 Some(Value::Array(a)) => a.iter().find_map(|v| match v {
46 Value::Dict(p) => Some(&**p),
47 _ => None,
48 }),
49 _ => None,
50 };
51 let pty = parent.and_then(|p| text(p.get("type"))).map(|t| t.to_ascii_lowercase()).unwrap_or_default();
52 let in_event = matches!(pty.as_str(), "proceedings" | "conference");
53 let kind = match ty.as_str() {
54 "article" if in_event => EntryKind::InProceedings,
55 "article" => EntryKind::Article,
56 "chapter" | "anthos" if in_event => EntryKind::InProceedings,
57 "chapter" | "anthos" => EntryKind::InCollection,
58 "book" | "anthology" | "proceedings"
59 | "reference" => EntryKind::Book,
60 "thesis" => EntryKind::Thesis,
61 "report" => EntryKind::Report,
62 "web" | "blog" | "repository" | "misc" => EntryKind::Online, // as BibTeX's `misc` reads
63 "manuscript" => EntryKind::Unpublished,
64 _ => EntryKind::Misc,
65 };
66
67 let mut f = Fields::default();
68 // The child's own fields, then what the parent supplies and the child left unset.
69 f.own(d, kind);
70 if let Some(p) = parent {
71 if let Some(t) = text(p.get("title")) {
72 let slot = match kind {
73 EntryKind::Article => "journal",
74 EntryKind::InCollection
75 | EntryKind::InProceedings => "booktitle",
76 _ => "series",
77 };
78 f.set(slot, t);
79 }
80 f.inherit(p);
81 }
82 let authors = names(d.get("author"));
83 let mut editors = names(d.get("editor"));
84 if editors.is_empty() {
85 if let Some(p) = parent {
86 if matches!(kind, EntryKind::InCollection | EntryKind::InProceedings) {
87 editors = names(p.get("editor"));
88 }
89 }
90 }
91 Entry::new(key.to_string(), kind, f.0, authors, editors)
92}
93
94// The fields gathered under their BibTeX names, the first value set for a name kept.
95#[derive(Default)]
96struct Fields(Vec<(String, String)>);
97
98impl Fields {
99 fn set(&mut self, name: &str, value: String) {
100 if !value.is_empty() && !self.0.iter().any(|(k, _)| k == name) {
101 self.0.push((name.to_string(), value));
102 }
103 }
104
105 fn own(&mut self, d: &Dict, kind: EntryKind) {
106 if let Some(t) = title(d) {
107 self.set("title", t);
108 }
109 self.shared(d);
110 if let Some(v) = text(d.get("page-range")).or_else(|| text(d.get("pages"))) {
111 self.set("pages", v);
112 }
113 if let Some(v) = text(d.get("page-total")) {
114 self.set("pagetotal", v);
115 }
116 match d.get("url") {
117 Some(Value::Dict(u)) => {
118 if let Some(v) = text(u.get("value")) {
119 self.set("url", v);
120 }
121 if let Some(v) = text(u.get("date")) {
122 self.set("urldate", v);
123 }
124 }
125 other => if let Some(v) = text(other) {
126 self.set("url", v);
127 },
128 }
129 match d.get("serial-number") {
130 Some(Value::Dict(s)) => {
131 for (k, v) in s.iter() {
132 if let Some(v) = text(Some(v)) {
133 let k = k.to_ascii_lowercase();
134 match k.as_str() {
135 "doi" | "isbn" | "issn" | "pmid" | "pmcid" | "arxiv" => self.set(&k, v),
136 _ => self.set("number", v),
137 }
138 }
139 }
140 }
141 other => if let Some(v) = text(other) {
142 self.set("number", v);
143 },
144 }
145 if let Some(v) = text(d.get("organization")) {
146 let slot = match kind {
147 EntryKind::PhdThesis | EntryKind::MastersThesis => "school",
148 EntryKind::Report | EntryKind::TechReport => "institution",
149 _ => "organization",
150 };
151 self.set(slot, v);
152 }
153 if let Some(v) = text(d.get("genre")) {
154 self.set("type", v);
155 }
156 for (from, to) in [
157 ("note", "note"),
158 ("language", "language"),
159 ("doi", "doi"),
160 ("isbn", "isbn"),
161 ("issn", "issn"),
162 ("abstract", "abstract"),
163 ("version", "version"),
164 ] {
165 if let Some(v) = text(d.get(from)) {
166 self.set(to, v);
167 }
168 }
169 }
170
171 // Fields a child and its container share; the child's are read first, so the parent only fills gaps.
172 fn shared(&mut self, d: &Dict) {
173 if let Some((y, m)) = date(d.get("date")) {
174 self.set("year", y);
175 if let Some(m) = m {
176 self.set("month", m);
177 }
178 }
179 for (from, to) in [
180 ("volume", "volume"),
181 ("issue", "number"),
182 ("edition", "edition"),
183 ("location", "address"),
184 ] {
185 if let Some(v) = text(d.get(from)) {
186 self.set(to, v);
187 }
188 }
189 match d.get("publisher") {
190 Some(Value::Dict(p)) => {
191 if let Some(v) = text(p.get("name")) {
192 self.set("publisher", v);
193 }
194 if let Some(v) = text(p.get("location")) {
195 self.set("address", v);
196 }
197 }
198 other => if let Some(v) = text(other) {
199 self.set("publisher", v);
200 },
201 }
202 }
203
204 fn inherit(&mut self, p: &Dict) {
205 self.shared(p);
206 if let Some(v) = text(p.get("organization")) {
207 self.set("organization", v);
208 }
209 match p.get("serial-number") {
210 Some(Value::Dict(s)) => {
211 for (k, v) in s.iter() {
212 let k = k.to_ascii_lowercase();
213 if k == "issn" || k == "isbn" {
214 if let Some(v) = text(Some(v)) {
215 self.set(&k, v);
216 }
217 }
218 }
219 }
220 _ => (),
221 }
222 }
223}
224
225// A title: a string, or a dictionary whose `value` is the title (beside `short` and `verbatim`).
226fn title(d: &Dict) -> Option<String> {
227 match d.get("title") {
228 Some(Value::Dict(t)) => text(t.get("value")),
229 other => text(other),
230 }
231}
232
233// A scalar as text: strings trimmed, numbers as written. A dictionary with a `value` reads as that value.
234fn text(v: Option<&Value>) -> Option<String> {
235 let s = match v {
236 Some(Value::Str(s)) => s.trim().to_string(),
237 Some(Value::Int(i)) => i.to_string(),
238 Some(Value::Float(x)) => x.to_string(),
239 Some(Value::Bool(b)) => b.to_string(),
240 Some(Value::Dict(d)) => return text(d.get("value")),
241 _ => return None,
242 };
243 if s.is_empty() { None } else { Some(s) }
244}
245
246// A Hayagriva date, `YYYY`, `YYYY-MM` or `YYYY-MM-DD` (a year may be signed): the year and the month.
247fn date(v: Option<&Value>) -> Option<(String, Option<String>)> {
248 let s = match text(v) {
249 Some(s) => s,
250 None => return None,
251 };
252 let (sign, body) = match s.strip_prefix('-') {
253 Some(rest) => ("-", rest),
254 None => ("", s.as_str()),
255 };
256 let mut parts = body.split('-');
257 let year = match parts.next() {
258 Some(y) if !y.is_empty() && y.chars().all(|c| c.is_ascii_digit()) => fmt!("{}{}", sign, y),
259 _ => return Some((s.clone(), None)),
260 };
261 let month = parts.next()
262 .filter(|m| !m.is_empty() && m.chars().all(|c| c.is_ascii_digit()))
263 .map(|m| m.trim_start_matches('0').to_string());
264 Some((year, month))
265}
266
267// Names: one or a list, each a `Family, Given[, Suffix]` string (one with no comma kept whole, as hayagriva
268// keeps it) or a dictionary of `name`, `given-name`, `prefix` and `suffix`.
269fn names(v: Option<&Value>) -> Vec<Name> {
270 match v {
271 Some(Value::Array(a)) => a.iter().filter_map(name).collect(),
272 Some(one) => name(one).into_iter().collect(),
273 None => Vec::new(),
274 }
275}
276
277fn name(v: &Value) -> Option<Name> {
278 match v {
279 Value::Str(s) => {
280 let parts: Vec<String> = s.split(',')
281 .map(|p| p.split_whitespace().collect::<Vec<_>>().join(" "))
282 .collect();
283 match parts.as_slice() {
284 [] => None,
285 [one] if one.is_empty() => None,
286 [one] => Some(Name::literal(one.clone())),
287 [family, given, ..] => Some(Name::personal(family.clone(), given.clone())),
288 }
289 }
290 Value::Dict(d) => {
291 let family = match text(d.get("name")) {
292 Some(n) => n,
293 None => return None,
294 };
295 let family = match text(d.get("prefix")) {
296 Some(p) => fmt!("{} {}", p, family),
297 None => family,
298 };
299 match text(d.get("given-name")).or_else(|| text(d.get("given-names"))) {
300 Some(g) => Some(Name::personal(family, g)),
301 None => Some(Name::literal(family)),
302 }
303 }
304 _ => None,
305 }
306}