citationberg 0.7.0

A parser for CSL files
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
//! Parser for CSL-JSON.
//!
//! This is only available when the `json` feature is enabled.

use std::borrow::Cow;
use std::{collections::BTreeMap, str::FromStr};

use serde::de::Visitor;
use serde::{Deserialize, Serialize};
use unscanny::Scanner;

use crate::taxonomy::Season;

/// A CSL-JSON item.
#[derive(Debug, Serialize, Deserialize, Hash, PartialEq, Eq, Clone)]
#[serde(transparent)]
pub struct Item(pub BTreeMap<String, Value>);

impl Item {
    /// The item's ID.
    pub fn id(&self) -> Option<Cow<'_, str>> {
        self.0.get("id")?.to_str()
    }

    /// The item type.
    pub fn type_(&self) -> Option<Cow<'_, str>> {
        self.0.get("type")?.to_str()
    }

    /// Whether any of the fields values contains any HTML.
    pub fn has_html(&self) -> bool {
        self.0.values().any(|v| v.has_html())
    }

    /// Whether this entry may contain "cheater syntax" for odd fields.
    pub fn may_have_hack(&self) -> bool {
        self.0.contains_key("note")
    }
}

/// A field in an CSL-JSON item.
#[derive(Debug, Serialize, Deserialize, Hash, PartialEq, Eq, Clone)]
#[serde(untagged)]
pub enum Value {
    /// A string value.
    String(String),
    /// A number value.
    Number(i64),
    /// A list of names.
    Names(Vec<NameValue>),
    /// A date value.
    Date(DateValue),
}

impl Value {
    /// Convert to a string if this is a string or number.
    pub fn to_str(&self) -> Option<Cow<'_, str>> {
        match self {
            Value::String(s) => Some(s.as_str().into()),
            Value::Number(n) => Some(n.to_string().into()),
            Value::Date(_) => None,
            Value::Names(_) => None,
        }
    }

    /// Whether the value contains any HTML.
    pub fn has_html(&self) -> bool {
        match self {
            Value::String(s) => s.contains('<'),
            Value::Number(_) => false,
            Value::Date(_) => false,
            Value::Names(_) => false,
        }
    }
}

/// The representation of a name.
#[derive(Debug, Serialize, Deserialize, Hash, PartialEq, Eq, Clone)]
#[serde(untagged)]
pub enum NameValue {
    /// A name that doesn't necessarily follow the schema of a `NameItem`.
    Literal(LiteralName),
    /// A name that is defined by a collection of parts.
    Item(NameItem),
}

/// A name that is defined by a collection of parts.
#[derive(Debug, Serialize, Deserialize, Hash, PartialEq, Eq, Clone)]
#[serde(rename_all = "kebab-case")]
pub struct NameItem {
    /// The family name.
    #[serde(default)]
    pub family: String,
    /// The given name.
    pub given: Option<String>,
    /// A name particle like `"de las"`.
    pub non_dropping_particle: Option<String>,
    /// A name particle like `"Rev."`.
    pub dropping_particle: Option<String>,
    /// A name suffix like `"Jr., Ph.D."`.
    pub suffix: Option<String>,
    /// Whether a comma should be added before the suffix, e.g., `Smith, Jr.`
    pub comma_suffix: Option<bool>,
}

/// A name that doesn't necessarily follow the schema of a `NameItem`. May be
/// useful for institutional names.
#[derive(Debug, Serialize, Deserialize, Hash, PartialEq, Eq, Clone)]
pub struct LiteralName {
    /// The literal name.
    pub literal: String,
}

/// The representation of a date.
#[derive(Clone, Debug, Hash, PartialEq, Eq)]
#[allow(missing_docs)]
pub enum DateValue {
    Raw {
        raw: FixedDateRange,
        literal: Option<String>,
        season: Option<String>,
    },
    DateParts {
        date_parts: VecDateRange,
        literal: Option<String>,
        season: Option<String>,
        circa: bool,
    },
}

impl DateValue {
    /// True iff at least one date is approximate.
    pub fn is_approx(&self) -> bool {
        match self {
            DateValue::Raw { raw, .. } => {
                raw.start.circa || raw.end.map(|d| d.circa).unwrap_or_default()
            }
            DateValue::DateParts { circa, .. } => *circa,
        }
    }
}

impl TryFrom<DateValue> for FixedDateRange {
    type Error = ();

    fn try_from(value: DateValue) -> Result<Self, Self::Error> {
        let (mut fixed, season) = match value {
            DateValue::Raw { raw, season, .. } => (raw, season),
            DateValue::DateParts { date_parts, season, circa, .. } => {
                let mut res: FixedDateRange = date_parts.try_into()?;
                res.start.circa = circa;
                (res, season)
            }
        };
        fixed.start.season = season
            .and_then(|s| s.parse::<u8>().ok())
            .and_then(|u| Season::try_from_csl_number(u).ok());
        Ok(fixed)
    }
}

impl From<DateValue> for VecDateRange {
    fn from(value: DateValue) -> Self {
        match value {
            DateValue::Raw { raw, .. } => raw.into(),
            DateValue::DateParts { date_parts, .. } => date_parts,
        }
    }
}

enum BooleanLike {
    String(String),
    Bool(bool),
    Number(u8),
}

impl BooleanLike {
    fn is_true(&self) -> bool {
        match self {
            BooleanLike::String(s) => s == "true",
            BooleanLike::Bool(b) => *b,
            BooleanLike::Number(n) => *n == 1,
        }
    }
}

impl<'de> Deserialize<'de> for BooleanLike {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        struct ValueVisitor;

        impl<'de> Visitor<'de> for ValueVisitor {
            type Value = BooleanLike;

            fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
                formatter.write_str("boolean, string, or unsigned, small number")
            }

            #[inline]
            fn visit_bool<E>(self, v: bool) -> Result<Self::Value, E>
            where
                E: serde::de::Error,
            {
                Ok(BooleanLike::Bool(v))
            }

            fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
            where
                E: serde::de::Error,
            {
                Ok(BooleanLike::String(String::from(v)))
            }

            fn visit_u64<E>(self, v: u64) -> Result<Self::Value, E>
            where
                E: serde::de::Error,
            {
                Ok(BooleanLike::Number(v as u8))
            }
        }

        deserializer.deserialize_any(ValueVisitor)
    }
}

impl<'de> Deserialize<'de> for DateValue {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        #[derive(Deserialize)]
        #[serde(rename_all = "kebab-case", untagged)]
        enum DateReprRaw {
            Raw {
                raw: FixedDateRange,
                literal: Option<String>,
                season: Option<NumberOrString>,
            },
            DateParts {
                #[serde(rename = "date-parts")]
                date_parts: VecDateRange,
                literal: Option<String>,
                season: Option<NumberOrString>,
                circa: Option<BooleanLike>,
            },
        }

        let raw = DateReprRaw::deserialize(deserializer)?;
        Ok(match raw {
            DateReprRaw::Raw { raw, literal, season } => DateValue::Raw {
                raw,
                literal,
                season: season.map(NumberOrString::into_string),
            },
            DateReprRaw::DateParts { date_parts, literal, season, circa } => {
                DateValue::DateParts {
                    date_parts,
                    literal,
                    season: season.map(NumberOrString::into_string),
                    circa: circa.as_ref().map(BooleanLike::is_true).unwrap_or_default(),
                }
            }
        })
    }
}

impl Serialize for DateValue {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        match self {
            DateValue::Raw { raw, .. } => VecDateRange::from(*raw).serialize(serializer),
            DateValue::DateParts { date_parts, .. } => date_parts.serialize(serializer),
        }
    }
}

/// A range of dates defined by arbitrary sequences of integer components.
#[derive(Clone, Debug, Serialize, Deserialize, Hash, PartialEq, Eq)]
#[serde(transparent)]
pub struct VecDateRange(pub Vec<VecDate>);

impl From<FixedDateRange> for VecDateRange {
    fn from(value: FixedDateRange) -> Self {
        let mut v = Vec::new();
        v.push(value.start.into());
        if let Some(end) = value.end {
            v.push(end.into());
        }
        VecDateRange(v)
    }
}

/// A date defined by an arbitrary sequence integer components.
#[derive(Clone, Debug, Serialize, Hash, PartialEq, Eq)]
#[serde(transparent)]
pub struct VecDate(pub Vec<i16>);

impl From<FixedDate> for VecDate {
    fn from(value: FixedDate) -> Self {
        let mut v = Vec::new();
        v.push(value.year);
        if let Some(month) = value.month {
            v.push(month as i16);
            if let Some(day) = value.day {
                v.push(day as i16);
            }
        }
        VecDate(v)
    }
}

impl<'de> Deserialize<'de> for VecDate {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let v = Vec::<NumberOrString>::deserialize(deserializer)?;
        Ok(VecDate(
            v.into_iter()
                .filter_map(|v| match v {
                    NumberOrString::Number(n) => Some(Ok(n)),
                    NumberOrString::String(s) if s.is_empty() => None,
                    NumberOrString::String(s) => Some(s.parse().map_err(|_| {
                        serde::de::Error::custom(format!("invalid number: {}", s))
                    })),
                })
                .collect::<Result<_, _>>()?,
        ))
    }
}

/// A range of dates defined by fixed components.
#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)]
pub struct FixedDateRange {
    /// The start of the range.
    pub start: FixedDate,
    /// The optional end of the range.
    pub end: Option<FixedDate>,
}

impl TryFrom<VecDateRange> for FixedDateRange {
    type Error = ();

    fn try_from(value: VecDateRange) -> Result<Self, Self::Error> {
        let mut v = value.0.into_iter();
        let start = v.next().ok_or(())?.into();
        let end = v.next().map(|v| v.into());
        if v.next().is_some() {
            return Err(());
        }
        Ok(FixedDateRange { start, end })
    }
}

impl FromStr for FixedDateRange {
    type Err = ();

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let mut s = Scanner::new(s);
        let start = parse_date(&mut s).ok_or(())?;
        let end =
            if s.eat() == Some('/') { Some(parse_date(&mut s).ok_or(())?) } else { None };

        Ok(FixedDateRange { start, end })
    }
}

impl<'de> Deserialize<'de> for FixedDateRange {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let s = String::deserialize(deserializer)?;
        Self::from_str(&s).map_err(|_| serde::de::Error::custom("invalid date"))
    }
}

/// A date defined by fixed components.
#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)]
#[allow(missing_docs)]
pub struct FixedDate {
    pub year: i16,
    pub month: Option<u8>,
    pub day: Option<u8>,
    pub season: Option<Season>,
    pub circa: bool,
}

impl From<VecDate> for FixedDate {
    fn from(value: VecDate) -> Self {
        let mut v = value.0.into_iter();
        let year = v.next().unwrap();
        let month = v.next().map(|v| (v - 1) as u8);
        let day = v.next().map(|v| (v - 1) as u8);
        FixedDate { year, month, day, season: None, circa: false }
    }
}

impl FromStr for FixedDate {
    type Err = ();

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let mut s = Scanner::new(s);
        parse_date(&mut s).ok_or(())
    }
}

impl<'de> Deserialize<'de> for FixedDate {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let s = String::deserialize(deserializer)?;
        Self::from_str(&s).map_err(|_| serde::de::Error::custom("invalid date"))
    }
}

fn parse_date(s: &mut Scanner<'_>) -> Option<FixedDate> {
    let year = s.eat_while(char::is_ascii_digit);
    let year = year.parse().ok()?;
    if s.peek() != Some('-') {
        return Some(FixedDate {
            year,
            month: None,
            day: None,
            season: None,
            circa: matches!(s.peek(), Some('~')),
        });
    }
    s.eat();

    let month = s.eat_while(char::is_ascii_digit);
    let month = month.parse::<u8>().ok()? - 1;
    if month > 11 {
        return None;
    }

    if s.peek() != Some('-') {
        return Some(FixedDate {
            year,
            month: Some(month),
            day: None,
            season: None,
            circa: matches!(s.peek(), Some('~')),
        });
    }
    s.eat();

    let day = s.eat_while(char::is_ascii_digit);
    let day = day.parse::<u8>().ok()? - 1;
    if day > 31 {
        return None;
    }

    Some(FixedDate {
        year,
        month: Some(month),
        day: Some(day),
        season: None,
        circa: matches!(s.peek(), Some('~')),
    })
}

/// A CSL-JSON citation.
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Citation {
    /// A unique ID for the citation.
    pub citation_id: String,
    /// The individual parts of the citation.
    pub citation_items: Vec<CitationItem>,
    /// The citation's properties.
    pub properties: CitationProperties,
}

/// An individual part of a citation.
#[derive(Debug, Serialize)]
#[serde(rename_all = "kebab-case")]
pub struct CitationItem {
    /// A unique ID for the citation item.
    pub id: String,
    /// A locator value (e.g. a page number).
    pub locator: Option<String>,
    /// What kind of locator to use (e.g. `"page"`).
    pub label: Option<String>,
    /// Whether to suppress the author for this item.
    #[serde(default)]
    pub suppress_author: bool,
    /// Something to print before this item.
    pub prefix: Option<String>,
    /// Something to print after this item.
    pub suffix: Option<String>,
    /// Defines the relationship of this item to other cited items with the same
    /// key.
    pub position: Option<u8>,
    /// Whether this key was already cited in close range before.
    pub near_note: Option<bool>,
}

impl<'de> Deserialize<'de> for CitationItem {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        #[derive(Deserialize)]
        #[serde(rename_all = "kebab-case")]
        struct CitationItemRaw {
            id: NumberOrString,
            locator: Option<NumberOrString>,
            label: Option<String>,
            #[serde(default)]
            suppress_author: bool,
            prefix: Option<String>,
            suffix: Option<String>,
            position: Option<u8>,
            near_note: Option<bool>,
        }

        let raw = CitationItemRaw::deserialize(deserializer)?;
        Ok(CitationItem {
            id: raw.id.into_string(),
            locator: raw.locator.map(NumberOrString::into_string),
            label: raw.label,
            suppress_author: raw.suppress_author,
            prefix: raw.prefix,
            suffix: raw.suffix,
            position: raw.position,
            near_note: raw.near_note,
        })
    }
}

/// Properties of a citation.
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CitationProperties {
    /// The footnote number in which the citation is located in the document.
    note_index: Option<u32>,
}

#[derive(Deserialize)]
#[serde(untagged)]
enum NumberOrString {
    Number(i16),
    String(String),
}

impl NumberOrString {
    fn into_string(self) -> String {
        match self {
            NumberOrString::Number(n) => n.to_string(),
            NumberOrString::String(s) => s,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_serialize() {
        let mut map = BTreeMap::new();
        map.insert("title".to_string(), Value::String("The Title".to_string()));
        map.insert(
            "author".to_string(),
            Value::Names(vec![NameValue::Item(NameItem {
                family: "Doe".to_string(),
                given: Some("John".to_string()),
                non_dropping_particle: None,
                dropping_particle: None,
                suffix: None,
                comma_suffix: None,
            })]),
        );
        map.insert(
            "date".to_string(),
            Value::Date(DateValue::Raw {
                raw: FixedDateRange::from_str("2021-09-10/2022-01-01").unwrap(),
                literal: None,
                season: None,
            }),
        );

        let item = Item(map);
        println!("{}", serde_json::to_string_pretty(&item).unwrap());
    }

    #[test]
    fn test_approximate() {
        let d: DateValue = serde_json::from_str(r#"{"raw": "2025-09~"}"#).unwrap();
        assert!(d.is_approx());

        let d: DateValue = serde_json::from_str(
            r#"{
            "circa": "true",
            "date-parts": [
                [
                    2005,
                    12,
                    15
                ]
            ]}"#,
        )
        .unwrap();
        assert!(d.is_approx());

        let d: DateValue = serde_json::from_str(
            r#"{
            "circa": true,
            "date-parts": [
                [
                    2005,
                    12,
                    15
                ]
            ]}"#,
        )
        .unwrap();
        assert!(d.is_approx());

        let d: DateValue = serde_json::from_str(
            r#"{
            "circa": 1,
            "date-parts": [
                [
                    2005,
                    12,
                    15
                ]
            ]}"#,
        )
        .unwrap();
        assert!(d.is_approx());
    }
}