Oregami
Repositories/oxedyne/fe2o3

oxedyne/fe2o3/fe2o3_text/src/csl/item.rs

9.6 KiB, 15 runs

created by r1870400018:73175, 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//! Ported from hayagriva 0.10.1, Copyright (c) Martin Haug and the hayagriva contributors,
2//! MIT OR Apache-2.0 (`src/types/strings.rs`, `src/types/numeric.rs`, `src/csl/taxonomy.rs`).
3//!
4//! The item model is the least the renderers read.
5use crate::csl::{
6 page::PageVal,
7 person::Person,
8 style::VarForm,
9};
10
11
12
13// Chunked strings
14#[derive(Clone, Copy, Debug, PartialEq, Eq)]
15pub enum ChunkKind {
16 Normal,
17 Verbatim, // case-protected, BibTeX's `{DNA}`
18 Math, // BibTeX's `$...$`, rendered by the host
19}
20
21#[derive(Clone, Debug, PartialEq, Eq)]
22pub struct Chunk {
23 pub kind: ChunkKind,
24 pub value: String,
25}
26
27/// A text variable as pieces, so that text-case leaves protected and mathematical spans alone.
28#[derive(Clone, Debug, Default, PartialEq, Eq)]
29pub struct Chunked(pub Vec<Chunk>);
30
31impl Chunked {
32
33 pub fn normal(s: &str) -> Self {
34 Self(vec![Chunk { kind: ChunkKind::Normal, value: s.to_string() }])
35 }
36
37 pub fn push(&mut self, kind: ChunkKind, s: &str) {
38 match self.0.last_mut() {
39 Some(last) if last.kind == kind && kind != ChunkKind::Math => last.value.push_str(s),
40 _ => self.0.push(Chunk { kind, value: s.to_string() }),
41 }
42 }
43
44 pub fn is_empty(&self) -> bool {
45 self.0.iter().all(|c| c.value.is_empty())
46 }
47
48 /// Is it empty or only whitespace?
49 pub fn is_blank(&self) -> bool {
50 self.0.iter().all(|c| c.value.chars().all(char::is_whitespace))
51 }
52}
53
54impl std::fmt::Display for Chunked {
55 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
56 for c in &self.0 {
57 match c.kind {
58 ChunkKind::Math => { let _ = write!(f, "${}$", c.value); }
59 _ => { let _ = f.write_str(&c.value); }
60 }
61 }
62 Ok(())
63 }
64}
65
66impl From<&str> for Chunked {
67 fn from(s: &str) -> Self {
68 Self::normal(s)
69 }
70}
71
72// Numbers
73#[derive(Clone, Copy, Debug, PartialEq, Eq)]
74pub enum NumDelim { Comma, Ampersand, Hyphen }
75
76impl NumDelim {
77
78 fn from_char(c: char) -> Option<Self> {
79 match c {
80 ',' => Some(Self::Comma),
81 '&' => Some(Self::Ampersand),
82 '-' | '–' => Some(Self::Hyphen),
83 _ => None,
84 }
85 }
86
87 pub fn as_str(self) -> &'static str {
88 match self {
89 Self::Comma => ", ",
90 Self::Ampersand => " & ",
91 Self::Hyphen => "–",
92 }
93 }
94}
95
96fn is_num_delim(c: char) -> bool {
97 NumDelim::from_char(c).is_some()
98}
99
100/// A number variable that parsed as numbers: one, or a set joined by `,`, `&` or a hyphen, with an
101/// optional non-numeric prefix and suffix (`2nd`, `S12`).
102#[derive(Clone, Debug, PartialEq, Eq)]
103pub struct Numeric {
104 pub nums: Vec<(i32, Option<NumDelim>)>, // a single number has one entry and no delimiter
105 pub prefix: Option<String>,
106 pub suffix: Option<String>,
107}
108
109impl Numeric {
110
111 pub fn new(n: i32) -> Self {
112 Self { nums: vec![(n, None)], prefix: None, suffix: None }
113 }
114
115 /// Reads a number as hayagriva's `Numeric::from_str` does, which is stricter than CSL's
116 /// "contains a number": `12a` is numeric (suffix `a`) but `12 a` with text after the suffix
117 /// is not.
118 pub fn parse(src: &str) -> Option<Self> {
119 let chars: Vec<char> = src.chars().collect();
120 let mut i = 0;
121 let eat_ws = |i: &mut usize| {
122 let start = *i;
123 while *i < chars.len() && chars[*i].is_whitespace() { *i += 1; }
124 chars[start..*i].iter().collect::<String>()
125 };
126 eat_ws(&mut i);
127 // Prefix: anything up to a digit or '-', leaving a run of zeros before a non-digit.
128 let pstart = i;
129 while i < chars.len() && !chars[i].is_numeric() && chars[i] != '-' { i += 1; }
130 let zstart = i;
131 while i < chars.len() && chars[i] == '0' { i += 1; }
132 if i > zstart && (i >= chars.len() || !chars[i].is_numeric()) {
133 i -= 1; // unscanny's `uneat` gives back one character
134 }
135 let prefix: String = chars[pstart..i].iter().collect();
136 let number = |i: &mut usize| -> Option<i32> {
137 let neg = *i < chars.len() && chars[*i] == '-';
138 if neg { *i += 1; }
139 let start = *i;
140 while *i < chars.len() && chars[*i].is_numeric() { *i += 1; }
141 if *i == start {
142 return None;
143 }
144 let s: String = chars[start..*i].iter().collect();
145 s.parse::<i32>().ok().map(|n| if neg { -n } else { n })
146 };
147 let first = number(&mut i)?;
148 let space_after = eat_ws(&mut i);
149 let mut nums = Vec::new();
150 match chars.get(i) {
151 Some(&c) if is_num_delim(c) => {
152 i += 1;
153 while i < chars.len() && is_num_delim(chars[i]) { i += 1; }
154 nums.push((first, NumDelim::from_char(c)));
155 loop {
156 eat_ws(&mut i);
157 let n = number(&mut i)?;
158 eat_ws(&mut i);
159 let dstart = i;
160 while i < chars.len() && is_num_delim(chars[i]) { i += 1; }
161 let d: String = chars[dstart..i].iter().collect();
162 let delim = match d.chars().next() {
163 Some(c0) if c0 != '-' && d.len() > c0.len_utf8() => None,
164 Some(c0) => NumDelim::from_char(c0),
165 None => None,
166 };
167 match delim {
168 Some(d) => nums.push((n, Some(d))),
169 None => { nums.push((n, None)); break; }
170 }
171 }
172 }
173 _ => nums.push((first, None)),
174 }
175 eat_ws(&mut i);
176 let pstart2 = i;
177 while i < chars.len() && !chars[i].is_numeric() && !chars[i].is_whitespace() { i += 1; }
178 let post: String = chars[pstart2..i].iter().collect();
179 if i < chars.len() {
180 return None;
181 }
182 Some(Self {
183 nums,
184 prefix: if prefix.is_empty() { None } else { Some(prefix) },
185 suffix: if post.is_empty() { None } else { Some(format!("{}{}", space_after, post)) },
186 })
187 }
188
189 /// Can a number form (ordinal, roman) be applied, there being no prefix or suffix?
190 pub fn will_transform(&self) -> bool {
191 self.prefix.is_none() && self.suffix.is_none()
192 }
193
194 /// Is it plural for a label? `number-of-*` variables count, others are plural when a set.
195 pub fn is_plural(&self, is_number_of: bool) -> bool {
196 match self.nums.len() {
197 1 if is_number_of => self.nums[0].0 != 1,
198 1 => false,
199 _ => true,
200 }
201 }
202}
203
204impl std::fmt::Display for Numeric {
205 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
206 if let Some(p) = &self.prefix { let _ = f.write_str(p); }
207 for (n, d) in &self.nums {
208 let _ = write!(f, "{}", n);
209 if let Some(d) = d { let _ = f.write_str(d.as_str()); }
210 }
211 if let Some(s) = &self.suffix { let _ = f.write_str(s); }
212 Ok(())
213 }
214}
215
216/// A number variable's value: parsed when it reads as a number, otherwise the string.
217#[derive(Clone, Debug, PartialEq, Eq)]
218pub enum NumVal {
219 Typed(Numeric),
220 Str(String),
221 Transparent(usize), // a locator the host renders itself, by citation index
222}
223
224impl NumVal {
225 pub fn from_str(s: &str) -> Self {
226 match Numeric::parse(s) {
227 Some(n) => Self::Typed(n),
228 None => Self::Str(s.to_string()),
229 }
230 }
231}
232
233// Dates
234/// A date as hayagriva holds it, one-based. A BibTeX range such as `2019/2021` arrives as its end
235/// date, as biblatex hands hayagriva only that, and an approximate date (`2015~`, `2015?`) renders
236/// like any other: `approximate` only answers `is-uncertain-date`.
237#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
238pub struct DateVal {
239 pub year: i32,
240 pub month: Option<u8>, // 1-12
241 pub day: Option<u8>, // 1-31
242 pub season: Option<u8>, // 1-4, used when there is no month
243 pub approximate: bool,
244}
245
246impl DateVal {
247 pub fn year(year: i32) -> Self {
248 Self { year, ..Self::default() }
249 }
250}
251
252// Variable taxonomy
253#[derive(Clone, Copy, Debug, PartialEq, Eq)]
254pub enum VarKind { Standard, Number, Page, Date, Name }
255
256const NUMBER_VARS: [&str; 17] = [
257 "chapter-number", "citation-number", "collection-number", "edition",
258 "first-reference-note-number", "issue", "locator", "number", "number-of-pages",
259 "number-of-volumes", "page-first", "part-number", "printing-number", "section",
260 "supplement-number", "version", "volume",
261];
262const DATE_VARS: [&str; 6] = [
263 "accessed", "available-date", "event-date", "issued", "original-date", "submitted",
264];
265const NAME_VARS: [&str; 30] = [
266 "author", "chair", "collection-editor", "compiler", "composer", "container-author",
267 "contributor", "curator", "director", "editor", "editor-translator", "editorial-director",
268 "executive-producer", "guest", "host", "illustrator", "interviewer", "narrator", "organizer",
269 "original-author", "performer", "producer", "recipient", "reviewed-author", "script-writer",
270 "series-creator", "translator", "commenter", "co-author", "colorist",
271];
272
273/// What kind of CSL variable a name is.
274pub fn var_kind(name: &str) -> VarKind {
275 if name == "page" {
276 VarKind::Page
277 } else if NUMBER_VARS.contains(&name) {
278 VarKind::Number
279 } else if DATE_VARS.contains(&name) {
280 VarKind::Date
281 } else if NAME_VARS.contains(&name) {
282 VarKind::Name
283 } else {
284 VarKind::Standard
285 }
286}
287
288/// Does a number variable count things, so that a single `1` is singular and any other plural?
289pub fn is_number_of(name: &str) -> bool {
290 name.starts_with("number-of-")
291}
292
293/// The entry being rendered, as the renderers read it.
294///
295/// Variable names are CSL's. `citation-number`, `citation-label`, `locator` and
296/// `first-reference-note-number` are answered by the citation (see `render::Cite`), not here.
297pub trait Item {
298
299 /// A standard (text) variable, in the form asked for. A short form the entry lacks should
300 /// return the long one, as hayagriva does.
301 fn text(&self, var: &str, form: VarForm) -> Option<Chunked>;
302
303 /// A number variable's raw value. The renderer parses it.
304 fn number(&self, var: &str) -> Option<String>;
305
306 /// The `page` variable, typed when it parses as page ranges (`PageVal::from_str`).
307 fn page(&self) -> Option<PageVal> { None }
308
309 /// The CSL item type, such as `article-journal`.
310 fn csl_type(&self) -> &str;
311
312 /// Does the entry match a CSL type in `choose`? hayagriva lets one entry match several.
313 fn is_type(&self, t: &str) -> bool { self.csl_type() == t }
314
315 /// Is the entry in English? `None` when its language is unknown.
316 fn is_english(&self) -> Option<bool> { None }
317
318 /// The people of a name variable, empty when it is absent.
319 fn names(&self, _var: &str) -> &[Person] { &[] }
320
321 fn date(&self, _var: &str) -> Option<DateVal> { None }
322}