Oregami
Repositories/oxedyne/fe2o3

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

31.3 KiB, 19 runs

created by r1870400018:72722, 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

1use crate::{
2 csl::locale::Locale,
3 xml::{
4 Elem as XElem,
5 Xml,
6 },
7};
8
9use oxedyne_fe2o3_core::prelude::*;
10
11use std::collections::BTreeMap;
12
13
14#[derive(Clone, Copy, Debug, PartialEq, Eq)]
15pub enum Class {
16 InText,
17 Note,
18}
19
20#[derive(Clone, Debug, Default, PartialEq)]
21pub struct Info {
22 pub id: String,
23 pub title: String,
24 pub updated: String,
25 pub rights: Option<String>,
26 pub parent: Option<String>, // `independent-parent` link of a dependent style
27}
28
29// Formatting
30#[derive(Clone, Copy, Debug, PartialEq, Eq)]
31pub enum FontStyle { Normal, Italic, Oblique }
32#[derive(Clone, Copy, Debug, PartialEq, Eq)]
33pub enum FontVariant { Normal, SmallCaps }
34#[derive(Clone, Copy, Debug, PartialEq, Eq)]
35pub enum FontWeight { Normal, Bold, Light }
36#[derive(Clone, Copy, Debug, PartialEq, Eq)]
37pub enum Decoration { None, Underline }
38#[derive(Clone, Copy, Debug, PartialEq, Eq)]
39pub enum VAlign { Baseline, Sup, Sub }
40
41/// The CSL formatting attributes of one element. `None` leaves the surrounding formatting as it is.
42#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
43pub struct Fmt {
44 pub style: Option<FontStyle>,
45 pub variant: Option<FontVariant>,
46 pub weight: Option<FontWeight>,
47 pub deco: Option<Decoration>,
48 pub valign: Option<VAlign>,
49}
50
51impl Fmt {
52 pub fn is_plain(&self) -> bool {
53 *self == Self::default()
54 }
55}
56
57#[derive(Clone, Copy, Debug, PartialEq, Eq)]
58pub enum Display { Block, LeftMargin, RightInline, Indent }
59
60#[derive(Clone, Copy, Debug, PartialEq, Eq)]
61pub enum TextCase { Lowercase, Uppercase, CapitaliseFirst, CapitaliseAll, Sentence, Title }
62
63/// What every rendering element may carry besides its own attributes.
64#[derive(Clone, Debug, Default, PartialEq)]
65pub struct Look {
66 pub fmt: Fmt,
67 pub prefix: Option<String>,
68 pub suffix: Option<String>,
69 pub display: Option<Display>,
70 pub quotes: bool,
71 pub strip_periods: bool,
72 pub text_case: Option<TextCase>,
73}
74
75// Elements
76#[derive(Clone, Debug, PartialEq)]
77pub enum Elem {
78 Text(Text),
79 Number(Number),
80 Label(Label),
81 Names(Names),
82 Date(Date),
83 Group(Group),
84 Choose(Choose),
85}
86
87#[derive(Clone, Copy, Debug, PartialEq, Eq)]
88pub enum VarForm { Long, Short }
89
90#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
91pub enum TermForm { Long, Short, Verb, VerbShort, Symbol }
92
93impl TermForm {
94 /// The next form to try where a locale lacks this one: symbol and short fall to long by way of
95 /// short, verb-short to verb, verb to long.
96 pub fn fallback(self) -> Option<Self> {
97 match self {
98 Self::Long => None,
99 Self::Short => Some(Self::Long),
100 Self::Verb => Some(Self::Long),
101 Self::VerbShort => Some(Self::Verb),
102 Self::Symbol => Some(Self::Short),
103 }
104 }
105}
106
107#[derive(Clone, Debug, PartialEq)]
108pub enum TextSrc {
109 Var { name: String, form: VarForm },
110 Macro(String),
111 Term { name: String, form: TermForm, plural: bool },
112 Value(String),
113}
114
115#[derive(Clone, Debug, PartialEq)]
116pub struct Text {
117 pub src: TextSrc,
118 pub look: Look,
119}
120
121#[derive(Clone, Copy, Debug, PartialEq, Eq)]
122pub enum NumForm { Numeric, Ordinal, LongOrdinal, Roman }
123
124#[derive(Clone, Debug, PartialEq)]
125pub struct Number {
126 pub var: String,
127 pub form: NumForm,
128 pub look: Look,
129}
130
131#[derive(Clone, Copy, Debug, PartialEq, Eq)]
132pub enum Plural { Contextual, Always, Never }
133
134#[derive(Clone, Debug, PartialEq)]
135pub struct Label {
136 pub var: String, // empty inside `names`, where the names' variable is meant
137 pub form: TermForm,
138 pub plural: Plural,
139 pub look: Look,
140}
141
142#[derive(Clone, Copy, Debug, PartialEq, Eq)]
143pub enum And { Text, Symbol }
144#[derive(Clone, Copy, Debug, PartialEq, Eq)]
145pub enum DelimRule { Contextual, AfterInvertedName, Always, Never }
146#[derive(Clone, Copy, Debug, PartialEq, Eq)]
147pub enum NameForm { Long, Short, Count }
148#[derive(Clone, Copy, Debug, PartialEq, Eq)]
149pub enum SortOrder { First, All }
150
151/// The inheritable name options. `None` defers to the level above: the `name` element, then the
152/// citation or bibliography, then the style.
153#[derive(Clone, Debug, Default, PartialEq)]
154pub struct NameOpts {
155 pub and: Option<And>,
156 pub delimiter: Option<String>,
157 pub delim_precedes_et_al: Option<DelimRule>,
158 pub delim_precedes_last: Option<DelimRule>,
159 pub et_al_min: Option<u32>,
160 pub et_al_use_first: Option<u32>,
161 pub et_al_subsequent_min: Option<u32>,
162 pub et_al_subsequent_use_first: Option<u32>,
163 pub et_al_use_last: Option<bool>,
164 pub form: Option<NameForm>,
165 pub initialize: Option<bool>,
166 pub initialize_with: Option<String>,
167 pub name_as_sort_order: Option<SortOrder>,
168 pub sort_separator: Option<String>,
169}
170
171macro_rules! over {
172 ($me:ident, $base:ident; $($f:ident),*) => {
173 NameOpts { $($f: match &$me.$f { Some(v) => Some(v.clone()), None => $base.$f.clone() },)* }
174 };
175}
176
177impl NameOpts {
178 /// These options laid over a base: each set field wins.
179 pub fn over(&self, base: &NameOpts) -> NameOpts {
180 over!(self, base; and, delimiter, delim_precedes_et_al, delim_precedes_last, et_al_min,
181 et_al_use_first, et_al_subsequent_min, et_al_subsequent_use_first, et_al_use_last, form,
182 initialize, initialize_with, name_as_sort_order, sort_separator)
183 }
184}
185
186#[derive(Clone, Copy, Debug, PartialEq, Eq)]
187pub enum PartName { Given, Family }
188
189#[derive(Clone, Debug, PartialEq)]
190pub struct NamePart {
191 pub part: PartName,
192 pub look: Look,
193}
194
195#[derive(Clone, Debug, Default, PartialEq)]
196pub struct Name {
197 pub opts: NameOpts,
198 pub parts: Vec<NamePart>,
199 pub look: Look,
200}
201
202#[derive(Clone, Debug, PartialEq)]
203pub struct EtAl {
204 pub term: String, // `et-al` or `and others`
205 pub look: Look,
206}
207
208#[derive(Clone, Debug, PartialEq)]
209pub struct Names {
210 pub vars: Vec<String>,
211 pub delimiter: Option<String>,
212 pub opts: NameOpts, // inheritable name options set on `names` itself
213 pub name: Option<Name>,
214 pub et_al: Option<EtAl>,
215 pub label: Option<Label>,
216 pub label_first: bool, // the label was written before the name
217 pub substitute: Option<Vec<Elem>>,
218 pub look: Look,
219}
220
221impl Names {
222 /// Does this element give no `name`, `et-al` or `label` of its own, so that inside a
223 /// `substitute` it takes its parent's?
224 pub fn is_bare(&self) -> bool {
225 self.name.is_none() && self.et_al.is_none() && self.label.is_none()
226 }
227}
228
229#[derive(Clone, Copy, Debug, PartialEq, Eq)]
230pub enum DateForm { Text, Numeric }
231#[derive(Clone, Copy, Debug, PartialEq, Eq)]
232pub enum DateParts { YearMonthDay, YearMonth, Year }
233#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
234pub enum DatePartName { Day, Month, Year }
235#[derive(Clone, Copy, Debug, PartialEq, Eq)]
236pub enum DatePartForm { Numeric, NumericLeadingZeros, Ordinal, Long, Short }
237
238#[derive(Clone, Debug, PartialEq)]
239pub struct DatePart {
240 pub name: DatePartName,
241 pub form: Option<DatePartForm>,
242 pub range_delimiter: Option<String>,
243 pub look: Look,
244}
245
246#[derive(Clone, Debug, PartialEq)]
247pub struct Date {
248 pub var: String,
249 pub form: Option<DateForm>, // localised where set
250 pub parts_sel: Option<DateParts>, // `None` takes the localised form's, then all three
251 pub parts: Vec<DatePart>,
252 pub delimiter: Option<String>,
253 pub look: Look,
254}
255
256#[derive(Clone, Debug, PartialEq)]
257pub struct Group {
258 pub delimiter: Option<String>,
259 pub elems: Vec<Elem>,
260 pub look: Look,
261}
262
263#[derive(Clone, Copy, Debug, PartialEq, Eq)]
264pub enum Match { All, Any, None }
265
266#[derive(Clone, Copy, Debug, PartialEq, Eq)]
267pub enum Position { First, Subsequent, IbidWithLocator, Ibid, NearNote }
268
269#[derive(Clone, Debug, PartialEq)]
270pub enum Test {
271 Disambiguate(bool),
272 IsNumeric(String),
273 IsUncertainDate(String),
274 Locator(String),
275 Position(Position),
276 Type(String),
277 Variable(String),
278}
279
280#[derive(Clone, Debug, PartialEq)]
281pub struct Cond {
282 pub mode: Match,
283 pub tests: Vec<Test>,
284}
285
286#[derive(Clone, Debug, PartialEq)]
287pub struct Branch {
288 pub cond: Option<Cond>, // `None` for `else`
289 pub elems: Vec<Elem>,
290}
291
292#[derive(Clone, Debug, PartialEq)]
293pub struct Choose {
294 pub branches: Vec<Branch>,
295}
296
297// Sorting
298#[derive(Clone, Debug, PartialEq)]
299pub enum SortSrc {
300 Var(String),
301 Macro(String),
302}
303
304#[derive(Clone, Debug, PartialEq)]
305pub struct SortKey {
306 pub src: SortSrc,
307 pub ascending: bool,
308 pub names_min: Option<u32>,
309 pub names_use_first: Option<u32>,
310 pub names_use_last: Option<bool>,
311}
312
313#[derive(Clone, Debug, Default, PartialEq)]
314pub struct Sort {
315 pub keys: Vec<SortKey>,
316}
317
318#[derive(Clone, Debug, Default, PartialEq)]
319pub struct Layout {
320 pub delimiter: Option<String>,
321 pub elems: Vec<Elem>,
322 pub look: Look,
323}
324
325#[derive(Clone, Copy, Debug, PartialEq, Eq)]
326pub enum Collapse { CitationNumber, Year, YearSuffix, YearSuffixRanged }
327#[derive(Clone, Copy, Debug, PartialEq, Eq)]
328pub enum GivenRule { AllNames, AllNamesWithInitials, PrimaryName, PrimaryNameWithInitials, ByCite }
329
330#[derive(Clone, Debug, PartialEq)]
331pub struct Citation {
332 pub names: NameOpts,
333 pub names_delimiter: Option<String>,
334 pub sort: Option<Sort>,
335 pub layout: Layout,
336 pub add_names: bool,
337 pub add_givenname: bool,
338 pub givenname_rule: GivenRule,
339 pub add_year_suffix: bool,
340 pub cite_group_delimiter: Option<String>,
341 pub collapse: Option<Collapse>,
342 pub year_suffix_delimiter: Option<String>,
343 pub after_collapse_delimiter: Option<String>,
344 pub near_note_distance: u32,
345}
346
347#[derive(Clone, Copy, Debug, PartialEq, Eq)]
348pub enum SecondField { Flush, Margin }
349#[derive(Clone, Copy, Debug, PartialEq, Eq)]
350pub enum SubRule { CompleteAll, CompleteEach, PartialEach, PartialFirst }
351
352#[derive(Clone, Debug, PartialEq)]
353pub struct Bibliography {
354 pub names: NameOpts,
355 pub names_delimiter: Option<String>,
356 pub sort: Option<Sort>,
357 pub layout: Layout,
358 pub hanging_indent: bool,
359 pub second_field_align: Option<SecondField>,
360 pub line_spacing: u32,
361 pub entry_spacing: u32,
362 pub sub_author: Option<String>, // subsequent-author-substitute
363 pub sub_rule: SubRule,
364}
365
366#[derive(Clone, Copy, Debug, PartialEq, Eq)]
367pub enum PageRange { Chicago, Chicago15, Chicago16, Expanded, Minimal, MinimalTwo }
368#[derive(Clone, Copy, Debug, PartialEq, Eq)]
369pub enum Demote { Never, SortOnly, DisplayAndSort }
370
371/// A CSL 1.0.2 independent style.
372#[derive(Clone, Debug, PartialEq)]
373pub struct Style {
374 pub class: Class,
375 pub version: String,
376 pub info: Info,
377 pub default_locale: Option<String>,
378 pub initialize_with_hyphen: bool,
379 pub page_range_format: Option<PageRange>,
380 pub demote_particle: Demote,
381 pub names: NameOpts,
382 pub names_delimiter: Option<String>,
383 pub macros: BTreeMap<String, Vec<Elem>>,
384 pub citation: Citation,
385 pub bibliography: Option<Bibliography>,
386 pub locales: Vec<Locale>, // in-style overrides, in the order written
387}
388
389impl Style {
390
391 /// Reads a style from its CSL XML.
392 ///
393 /// A dependent style, which names a parent and has no layout of its own, is refused by name so
394 /// that the caller can load the parent instead.
395 pub fn parse(src: &str) -> Outcome<Self> {
396 let xml = res!(Xml::parse(src));
397 let root = res!(xml.root());
398 if root.name.local() != "style" {
399 return Err(err!("CSL: the root element is <{}>, not <style>.", root.name.qname; Invalid, Input));
400 }
401 let rd = Rd { xml: &xml };
402 let info = match root.child("info") {
403 Some(e) => rd.info(e),
404 None => Info::default(),
405 };
406 let citation_el = match root.child("citation") {
407 Some(e) => e,
408 None => return Err(match &info.parent {
409 Some(p) => err!("CSL style '{}' is a dependent style of '{}'; load its parent.", info.id, p;
410 Invalid, Input, Unimplemented),
411 None => err!("CSL style '{}' has no <citation>.", info.id; Invalid, Input, Missing),
412 }),
413 };
414 let class = match root.attr("class") {
415 Some("in-text") => Class::InText,
416 Some("note") => Class::Note,
417 other => return Err(err!(
418 "CSL style '{}': class is {:?}, not 'in-text' or 'note'.", info.id, other; Invalid, Input)),
419 };
420 let mut macros = BTreeMap::new();
421 for m in root.children("macro") {
422 let name = res!(rd.req(m, "name"));
423 let elems = res!(rd.elems(m, &info.id));
424 macros.insert(name.to_string(), elems);
425 }
426 let mut locales = Vec::new();
427 for l in root.children("locale") {
428 locales.push(res!(Locale::read(&xml, l)));
429 }
430 let citation = res!(rd.citation(citation_el, &info.id));
431 let bibliography = match root.child("bibliography") {
432 Some(b) => Some(res!(rd.bibliography(b, &info.id))),
433 None => None,
434 };
435 Ok(Self {
436 class,
437 version: root.attr("version").unwrap_or("1.0").to_string(),
438 default_locale: root.attr("default-locale").map(str::to_string),
439 initialize_with_hyphen: res!(rd.bool(root, "initialize-with-hyphen")).unwrap_or(true),
440 page_range_format: res!(rd.page_range(root)),
441 demote_particle: match root.attr("demote-non-dropping-particle") {
442 None | Some("display-and-sort") => Demote::DisplayAndSort,
443 Some("sort-only") => Demote::SortOnly,
444 Some("never") => Demote::Never,
445 Some(v) => return Err(rd.bad(root, "demote-non-dropping-particle", v)),
446 },
447 names: res!(rd.name_opts(root)),
448 names_delimiter: root.attr("names-delimiter").map(str::to_string),
449 info,
450 macros,
451 citation,
452 bibliography,
453 locales,
454 })
455 }
456
457 pub fn get_macro(&self, name: &str) -> Option<&[Elem]> {
458 self.macros.get(name).map(|v| v.as_slice())
459 }
460}
461
462/// Walks every element of a list and its descendants, in document order.
463pub fn walk<'a, F: FnMut(&'a Elem)>(elems: &'a [Elem], f: &mut F) {
464 for e in elems {
465 f(e);
466 match e {
467 Elem::Names(n) => if let Some(s) = &n.substitute { walk(s, f) },
468 Elem::Group(g) => walk(&g.elems, f),
469 Elem::Choose(c) => for b in &c.branches { walk(&b.elems, f) },
470 _ => {}
471 }
472 }
473}
474
475/// The reader: attribute parsing over the XML tree, with errors naming the style.
476pub(crate) struct Rd<'a> {
477 pub xml: &'a Xml,
478}
479
480impl<'a> Rd<'a> {
481
482 pub fn bad(&self, e: &XElem, attr: &str, val: &str) -> Error<ErrTag> {
483 err!("CSL: <{}> at byte {} has {}=\"{}\", which is not a value CSL 1.0.2 allows.",
484 e.name.qname, e.span.start, attr, val; Invalid, Input)
485 }
486
487 pub fn req<'b>(&self, e: &'b XElem, attr: &str) -> Outcome<&'b str> {
488 match e.attr(attr) {
489 Some(v) => Ok(v),
490 None => Err(err!("CSL: <{}> at byte {} lacks its required '{}' attribute.",
491 e.name.qname, e.span.start, attr; Invalid, Input, Missing)),
492 }
493 }
494
495 pub fn bool(&self, e: &XElem, attr: &str) -> Outcome<Option<bool>> {
496 match e.attr(attr) {
497 None => Ok(None),
498 Some("true") => Ok(Some(true)),
499 Some("false") => Ok(Some(false)),
500 Some(v) => Err(self.bad(e, attr, v)),
501 }
502 }
503
504 pub fn uint(&self, e: &XElem, attr: &str) -> Outcome<Option<u32>> {
505 match e.attr(attr) {
506 None => Ok(None),
507 Some(v) => match v.trim().parse::<u32>() {
508 Ok(n) => Ok(Some(n)),
509 Err(_) => Err(self.bad(e, attr, v)),
510 },
511 }
512 }
513
514 fn page_range(&self, e: &XElem) -> Outcome<Option<PageRange>> {
515 Ok(match e.attr("page-range-format") {
516 None => None,
517 Some("chicago") => Some(PageRange::Chicago),
518 Some("chicago-15") => Some(PageRange::Chicago15),
519 Some("chicago-16") => Some(PageRange::Chicago16),
520 Some("expanded") => Some(PageRange::Expanded),
521 Some("minimal") => Some(PageRange::Minimal),
522 Some("minimal-two") => Some(PageRange::MinimalTwo),
523 Some(v) => return Err(self.bad(e, "page-range-format", v)),
524 })
525 }
526
527 fn info(&self, e: &XElem) -> Info {
528 let txt = |name: &str| e.child(name).map(|c| self.xml.text_of(c).trim().to_string());
529 let parent = e.children("link").into_iter()
530 .find(|l| l.attr("rel") == Some("independent-parent"))
531 .and_then(|l| l.attr("href").map(str::to_string));
532 Info {
533 id: txt("id").unwrap_or_default(),
534 title: txt("title").unwrap_or_default(),
535 updated: txt("updated").unwrap_or_default(),
536 rights: txt("rights"),
537 parent,
538 }
539 }
540
541 pub fn look(&self, e: &XElem) -> Outcome<Look> {
542 let fmt = Fmt {
543 style: match e.attr("font-style") {
544 None => None,
545 Some("normal") => Some(FontStyle::Normal),
546 Some("italic") => Some(FontStyle::Italic),
547 Some("oblique") => Some(FontStyle::Oblique),
548 Some(v) => return Err(self.bad(e, "font-style", v)),
549 },
550 variant: match e.attr("font-variant") {
551 None => None,
552 Some("normal") => Some(FontVariant::Normal),
553 Some("small-caps") => Some(FontVariant::SmallCaps),
554 Some(v) => return Err(self.bad(e, "font-variant", v)),
555 },
556 weight: match e.attr("font-weight") {
557 None => None,
558 Some("normal") => Some(FontWeight::Normal),
559 Some("bold") => Some(FontWeight::Bold),
560 Some("light") => Some(FontWeight::Light),
561 Some(v) => return Err(self.bad(e, "font-weight", v)),
562 },
563 deco: match e.attr("text-decoration") {
564 None => None,
565 Some("none") => Some(Decoration::None),
566 Some("underline") => Some(Decoration::Underline),
567 Some(v) => return Err(self.bad(e, "text-decoration", v)),
568 },
569 valign: match e.attr("vertical-align") {
570 None => None,
571 Some("baseline") => Some(VAlign::Baseline),
572 Some("sup") => Some(VAlign::Sup),
573 Some("sub") => Some(VAlign::Sub),
574 Some(v) => return Err(self.bad(e, "vertical-align", v)),
575 },
576 };
577 Ok(Look {
578 fmt,
579 prefix: e.attr("prefix").map(str::to_string),
580 suffix: e.attr("suffix").map(str::to_string),
581 display: match e.attr("display") {
582 None => None,
583 Some("block") => Some(Display::Block),
584 Some("left-margin") => Some(Display::LeftMargin),
585 Some("right-inline") => Some(Display::RightInline),
586 Some("indent") => Some(Display::Indent),
587 Some(v) => return Err(self.bad(e, "display", v)),
588 },
589 quotes: res!(self.bool(e, "quotes")).unwrap_or(false),
590 strip_periods: res!(self.bool(e, "strip-periods")).unwrap_or(false),
591 text_case: match e.attr("text-case") {
592 None => None,
593 Some("lowercase") => Some(TextCase::Lowercase),
594 Some("uppercase") => Some(TextCase::Uppercase),
595 Some("capitalize-first")=> Some(TextCase::CapitaliseFirst),
596 Some("capitalize-all") => Some(TextCase::CapitaliseAll),
597 Some("sentence") => Some(TextCase::Sentence),
598 Some("title") => Some(TextCase::Title),
599 Some(v) => return Err(self.bad(e, "text-case", v)),
600 },
601 })
602 }
603
604 pub fn term_form(&self, e: &XElem) -> Outcome<TermForm> {
605 Ok(match e.attr("form") {
606 None | Some("long") => TermForm::Long,
607 Some("short") => TermForm::Short,
608 Some("verb") => TermForm::Verb,
609 Some("verb-short") => TermForm::VerbShort,
610 Some("symbol") => TermForm::Symbol,
611 Some(v) => return Err(self.bad(e, "form", v)),
612 })
613 }
614
615 pub fn name_opts(&self, e: &XElem) -> Outcome<NameOpts> {
616 let rule = |attr: &str| -> Outcome<Option<DelimRule>> {
617 Ok(match e.attr(attr) {
618 None => None,
619 Some("contextual") => Some(DelimRule::Contextual),
620 Some("after-inverted-name") => Some(DelimRule::AfterInvertedName),
621 Some("always") => Some(DelimRule::Always),
622 Some("never") => Some(DelimRule::Never),
623 Some(v) => return Err(self.bad(e, attr, v)),
624 })
625 };
626 Ok(NameOpts {
627 and: match e.attr("and") {
628 None => None,
629 Some("text") => Some(And::Text),
630 Some("symbol") => Some(And::Symbol),
631 Some(v) => return Err(self.bad(e, "and", v)),
632 },
633 // On `style`, `citation` and `bibliography` the attribute is `name-delimiter`.
634 delimiter: match e.name.local() {
635 "name" => e.attr("delimiter").map(str::to_string),
636 _ => e.attr("name-delimiter").map(str::to_string),
637 },
638 delim_precedes_et_al: res!(rule("delimiter-precedes-et-al")),
639 delim_precedes_last: res!(rule("delimiter-precedes-last")),
640 et_al_min: res!(self.uint(e, "et-al-min")),
641 et_al_use_first: res!(self.uint(e, "et-al-use-first")),
642 et_al_subsequent_min: res!(self.uint(e, "et-al-subsequent-min")),
643 et_al_subsequent_use_first: res!(self.uint(e, "et-al-subsequent-use-first")),
644 et_al_use_last: res!(self.bool(e, "et-al-use-last")),
645 form: match e.attr(match e.name.local() {
646 "name" => "form",
647 _ => "name-form",
648 }) {
649 None => None,
650 Some("long") => Some(NameForm::Long),
651 Some("short") => Some(NameForm::Short),
652 Some("count") => Some(NameForm::Count),
653 Some(v) => return Err(self.bad(e, "form", v)),
654 },
655 initialize: res!(self.bool(e, "initialize")),
656 initialize_with: e.attr("initialize-with").map(str::to_string),
657 name_as_sort_order: match e.attr("name-as-sort-order") {
658 None => None,
659 Some("first") => Some(SortOrder::First),
660 Some("all") => Some(SortOrder::All),
661 Some(v) => return Err(self.bad(e, "name-as-sort-order", v)),
662 },
663 sort_separator: e.attr("sort-separator").map(str::to_string),
664 })
665 }
666
667 fn sort(&self, e: &XElem) -> Outcome<Sort> {
668 let mut keys = Vec::new();
669 for k in e.children("key") {
670 let src = match (k.attr("variable"), k.attr("macro")) {
671 (Some(v), _) => SortSrc::Var(v.to_string()),
672 (None, Some(m)) => SortSrc::Macro(m.to_string()),
673 (None, None) => return Err(err!(
674 "CSL: <key> at byte {} names neither a variable nor a macro.", k.span.start;
675 Invalid, Input, Missing)),
676 };
677 keys.push(SortKey {
678 src,
679 ascending: match k.attr("sort") {
680 None | Some("ascending") => true,
681 Some("descending") => false,
682 Some(v) => return Err(self.bad(k, "sort", v)),
683 },
684 names_min: res!(self.uint(k, "names-min")),
685 names_use_first: res!(self.uint(k, "names-use-first")),
686 names_use_last: res!(self.bool(k, "names-use-last")),
687 });
688 }
689 Ok(Sort { keys })
690 }
691
692 fn layout(&self, e: &XElem, id: &str) -> Outcome<Layout> {
693 Ok(Layout {
694 delimiter: e.attr("delimiter").map(str::to_string),
695 elems: res!(self.elems(e, id)),
696 look: res!(self.look(e)),
697 })
698 }
699
700 fn citation(&self, e: &XElem, id: &str) -> Outcome<Citation> {
701 let layout = match e.child("layout") {
702 Some(l) => res!(self.layout(l, id)),
703 None => return Err(err!("CSL style '{}': <citation> has no <layout>.", id; Invalid, Input, Missing)),
704 };
705 Ok(Citation {
706 names: res!(self.name_opts(e)),
707 names_delimiter: e.attr("names-delimiter").map(str::to_string),
708 sort: match e.child("sort") { Some(s) => Some(res!(self.sort(s))), None => None },
709 layout,
710 add_names: res!(self.bool(e, "disambiguate-add-names")).unwrap_or(false),
711 add_givenname: res!(self.bool(e, "disambiguate-add-givenname")).unwrap_or(false),
712 givenname_rule: match e.attr("givenname-disambiguation-rule") {
713 None | Some("by-cite") => GivenRule::ByCite,
714 Some("all-names") => GivenRule::AllNames,
715 Some("all-names-with-initials") => GivenRule::AllNamesWithInitials,
716 Some("primary-name") => GivenRule::PrimaryName,
717 Some("primary-name-with-initials") => GivenRule::PrimaryNameWithInitials,
718 Some(v) => return Err(self.bad(e, "givenname-disambiguation-rule", v)),
719 },
720 add_year_suffix: res!(self.bool(e, "disambiguate-add-year-suffix")).unwrap_or(false),
721 cite_group_delimiter: e.attr("cite-group-delimiter").map(str::to_string),
722 collapse: match e.attr("collapse") {
723 None => None,
724 Some("citation-number") => Some(Collapse::CitationNumber),
725 Some("year") => Some(Collapse::Year),
726 Some("year-suffix") => Some(Collapse::YearSuffix),
727 Some("year-suffix-ranged") => Some(Collapse::YearSuffixRanged),
728 Some(v) => return Err(self.bad(e, "collapse", v)),
729 },
730 year_suffix_delimiter: e.attr("year-suffix-delimiter").map(str::to_string),
731 after_collapse_delimiter: e.attr("after-collapse-delimiter").map(str::to_string),
732 near_note_distance: res!(self.uint(e, "near-note-distance")).unwrap_or(5),
733 })
734 }
735
736 fn bibliography(&self, e: &XElem, id: &str) -> Outcome<Bibliography> {
737 let layout = match e.child("layout") {
738 Some(l) => res!(self.layout(l, id)),
739 None => return Err(err!("CSL style '{}': <bibliography> has no <layout>.", id; Invalid, Input, Missing)),
740 };
741 Ok(Bibliography {
742 names: res!(self.name_opts(e)),
743 names_delimiter: e.attr("names-delimiter").map(str::to_string),
744 sort: match e.child("sort") { Some(s) => Some(res!(self.sort(s))), None => None },
745 layout,
746 hanging_indent: res!(self.bool(e, "hanging-indent")).unwrap_or(false),
747 second_field_align: match e.attr("second-field-align") {
748 None => None,
749 Some("flush") => Some(SecondField::Flush),
750 Some("margin") => Some(SecondField::Margin),
751 Some(v) => return Err(self.bad(e, "second-field-align", v)),
752 },
753 line_spacing: res!(self.uint(e, "line-spacing")).unwrap_or(1),
754 entry_spacing: res!(self.uint(e, "entry-spacing")).unwrap_or(1),
755 sub_author: e.attr("subsequent-author-substitute").map(str::to_string),
756 sub_rule: match e.attr("subsequent-author-substitute-rule") {
757 None | Some("complete-all") => SubRule::CompleteAll,
758 Some("complete-each") => SubRule::CompleteEach,
759 Some("partial-each") => SubRule::PartialEach,
760 Some("partial-first") => SubRule::PartialFirst,
761 Some(v) => return Err(self.bad(e, "subsequent-author-substitute-rule", v)),
762 },
763 })
764 }
765
766 pub fn elems(&self, parent: &XElem, id: &str) -> Outcome<Vec<Elem>> {
767 let mut out = Vec::new();
768 for e in parent.elems() {
769 out.push(res!(self.elem(e, id)));
770 }
771 Ok(out)
772 }
773
774 fn elem(&self, e: &XElem, id: &str) -> Outcome<Elem> {
775 Ok(match e.name.local() {
776 "text" => Elem::Text(res!(self.text(e))),
777 "number" => Elem::Number(Number {
778 var: res!(self.req(e, "variable")).to_string(),
779 form: match e.attr("form") {
780 None | Some("numeric") => NumForm::Numeric,
781 Some("ordinal") => NumForm::Ordinal,
782 Some("long-ordinal") => NumForm::LongOrdinal,
783 Some("roman") => NumForm::Roman,
784 Some(v) => return Err(self.bad(e, "form", v)),
785 },
786 look: res!(self.look(e)),
787 }),
788 "label" => Elem::Label(res!(self.label(e))),
789 "names" => Elem::Names(res!(self.names(e, id))),
790 "date" => Elem::Date(res!(self.date(e, false))),
791 "group" => Elem::Group(Group {
792 delimiter: e.attr("delimiter").map(str::to_string),
793 elems: res!(self.elems(e, id)),
794 look: res!(self.look(e)),
795 }),
796 "choose" => Elem::Choose(res!(self.choose(e, id))),
797 other => return Err(err!(
798 "CSL style '{}': <{}> at byte {} is not a rendering element.", id, other, e.span.start;
799 Invalid, Input, Unknown)),
800 })
801 }
802
803 fn text(&self, e: &XElem) -> Outcome<Text> {
804 let src = if let Some(v) = e.attr("variable") {
805 TextSrc::Var {
806 name: v.to_string(),
807 form: match e.attr("form") {
808 None | Some("long") => VarForm::Long,
809 Some("short") => VarForm::Short,
810 Some(f) => return Err(self.bad(e, "form", f)),
811 },
812 }
813 } else if let Some(m) = e.attr("macro") {
814 TextSrc::Macro(m.to_string())
815 } else if let Some(t) = e.attr("term") {
816 TextSrc::Term {
817 name: t.to_string(),
818 form: res!(self.term_form(e)),
819 plural: res!(self.bool(e, "plural")).unwrap_or(false),
820 }
821 } else if let Some(v) = e.attr("value") {
822 TextSrc::Value(v.to_string())
823 } else {
824 return Err(err!("CSL: <text> at byte {} names no variable, macro, term or value.",
825 e.span.start; Invalid, Input, Missing));
826 };
827 Ok(Text { src, look: res!(self.look(e)) })
828 }
829
830 fn label(&self, e: &XElem) -> Outcome<Label> {
831 Ok(Label {
832 var: e.attr("variable").unwrap_or("").to_string(),
833 form: res!(self.term_form(e)),
834 plural: match e.attr("plural") {
835 None | Some("contextual") => Plural::Contextual,
836 Some("always") => Plural::Always,
837 Some("never") => Plural::Never,
838 Some(v) => return Err(self.bad(e, "plural", v)),
839 },
840 look: res!(self.look(e)),
841 })
842 }
843
844 fn names(&self, e: &XElem, id: &str) -> Outcome<Names> {
845 let mut out = Names {
846 vars: res!(self.req(e, "variable")).split_whitespace().map(str::to_string).collect(),
847 delimiter: e.attr("delimiter").map(str::to_string),
848 opts: res!(self.name_opts(e)),
849 name: None,
850 et_al: None,
851 label: None,
852 label_first: false,
853 substitute: None,
854 look: res!(self.look(e)),
855 };
856 for k in e.elems() {
857 match k.name.local() {
858 "name" => {
859 let mut parts = Vec::new();
860 for p in k.children("name-part") {
861 parts.push(NamePart {
862 part: match res!(self.req(p, "name")) {
863 "given" => PartName::Given,
864 "family" => PartName::Family,
865 v => return Err(self.bad(p, "name", v)),
866 },
867 look: res!(self.look(p)),
868 });
869 }
870 out.name = Some(Name { opts: res!(self.name_opts(k)), parts, look: res!(self.look(k)) });
871 }
872 "et-al" => out.et_al = Some(EtAl {
873 term: k.attr("term").unwrap_or("et-al").to_string(),
874 look: res!(self.look(k)),
875 }),
876 "label" => {
877 out.label_first = out.name.is_none();
878 out.label = Some(res!(self.label(k)));
879 }
880 "substitute" => out.substitute = Some(res!(self.elems(k, id))),
881 other => return Err(err!(
882 "CSL style '{}': <{}> at byte {} cannot sit inside <names>.", id, other, k.span.start;
883 Invalid, Input, Unknown)),
884 }
885 }
886 Ok(out)
887 }
888
889 /// Reads a `date`; in a locale `var` is absent and `form` names the format being defined.
890 pub fn date(&self, e: &XElem, in_locale: bool) -> Outcome<Date> {
891 let mut parts = Vec::new();
892 for p in e.children("date-part") {
893 parts.push(DatePart {
894 name: match res!(self.req(p, "name")) {
895 "day" => DatePartName::Day,
896 "month" => DatePartName::Month,
897 "year" => DatePartName::Year,
898 v => return Err(self.bad(p, "name", v)),
899 },
900 form: match p.attr("form") {
901 None => None,
902 Some("numeric") => Some(DatePartForm::Numeric),
903 Some("numeric-leading-zeros") => Some(DatePartForm::NumericLeadingZeros),
904 Some("ordinal") => Some(DatePartForm::Ordinal),
905 Some("long") => Some(DatePartForm::Long),
906 Some("short") => Some(DatePartForm::Short),
907 Some(v) => return Err(self.bad(p, "form", v)),
908 },
909 range_delimiter: p.attr("range-delimiter").map(str::to_string),
910 look: res!(self.look(p)),
911 });
912 }
913 Ok(Date {
914 var: match in_locale {
915 true => String::new(),
916 false => res!(self.req(e, "variable")).to_string(),
917 },
918 form: match e.attr("form") {
919 None => None,
920 Some("text") => Some(DateForm::Text),
921 Some("numeric") => Some(DateForm::Numeric),
922 Some(v) => return Err(self.bad(e, "form", v)),
923 },
924 parts_sel: match e.attr("date-parts") {
925 None => None,
926 Some("year-month-day") => Some(DateParts::YearMonthDay),
927 Some("year-month") => Some(DateParts::YearMonth),
928 Some("year") => Some(DateParts::Year),
929 Some(v) => return Err(self.bad(e, "date-parts", v)),
930 },
931 parts,
932 delimiter: e.attr("delimiter").map(str::to_string),
933 look: res!(self.look(e)),
934 })
935 }
936
937 fn choose(&self, e: &XElem, id: &str) -> Outcome<Choose> {
938 let mut branches = Vec::new();
939 for b in e.elems() {
940 let cond = match b.name.local() {
941 "if" | "else-if" => Some(res!(self.cond(b))),
942 "else" => None,
943 other => return Err(err!(
944 "CSL style '{}': <{}> at byte {} cannot sit inside <choose>.", id, other, b.span.start;
945 Invalid, Input, Unknown)),
946 };
947 branches.push(Branch { cond, elems: res!(self.elems(b, id)) });
948 }
949 Ok(Choose { branches })
950 }
951
952 fn cond(&self, e: &XElem) -> Outcome<Cond> {
953 let mut tests = Vec::new();
954 for a in &e.attrs {
955 let words = a.value.split_whitespace();
956 match a.name.qname.as_str() {
957 "disambiguate" => tests.push(Test::Disambiguate(match res!(self.bool(e, "disambiguate")) {
958 Some(b) => b,
959 None => false,
960 })),
961 "is-numeric" => for w in words { tests.push(Test::IsNumeric(w.to_string())) },
962 "is-uncertain-date" => for w in words { tests.push(Test::IsUncertainDate(w.to_string())) },
963 "locator" => for w in words { tests.push(Test::Locator(w.to_string())) },
964 "type" => for w in words { tests.push(Test::Type(w.to_string())) },
965 "variable" => for w in words { tests.push(Test::Variable(w.to_string())) },
966 "position" => for w in words {
967 tests.push(Test::Position(match w {
968 "first" => Position::First,
969 "subsequent" => Position::Subsequent,
970 "ibid-with-locator" => Position::IbidWithLocator,
971 "ibid" => Position::Ibid,
972 "near-note" => Position::NearNote,
973 v => return Err(self.bad(e, "position", v)),
974 }));
975 },
976 _ => {}
977 }
978 }
979 Ok(Cond {
980 mode: match e.attr("match") {
981 None | Some("all") => Match::All,
982 Some("any") => Match::Any,
983 Some("none") => Match::None,
984 Some(v) => return Err(self.bad(e, "match", v)),
985 },
986 tests,
987 })
988 }
989}