biblatex 0.11.0

Parsing, writing, and evaluating BibTeX and BibLaTeX 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
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
//! Low-level representation of a bibliography file.

use std::fmt;

use crate::{Span, Spanned, TypeErrorKind};

use unscanny::Scanner;

/// The content of a field or abbreviation.
pub type Field<'s> = Vec<Spanned<RawChunk<'s>>>;

/// A literal representation of a bibliography file, with abbreviations not yet
/// resolved.
#[derive(Debug, Clone)]
pub struct RawBibliography<'s> {
    /// TeX commands to be prepended to the document, only supported by BibTeX.
    pub preamble: String,
    /// The collection of citation keys and bibliography entries.
    pub entries: Vec<Spanned<RawEntry<'s>>>,
    /// A map of reusable abbreviations, only supported by BibTeX.
    pub abbreviations: Vec<Pair<'s>>,
}

/// A raw extracted entry, with abbreviations not yet resolved.
#[derive(Debug, Clone)]
pub struct RawEntry<'s> {
    /// The citation key.
    pub key: Spanned<&'s str>,
    /// Denotes the type of bibliographic item (e.g., `article`).
    pub kind: Spanned<&'s str>,
    /// Maps from field names to their values.
    pub fields: Vec<Pair<'s>>,
}

/// A literal representation of a bibliography entry field.
#[derive(Debug, Clone, PartialEq)]
pub enum RawChunk<'s> {
    /// A normal field value.
    Normal(&'s str),
    /// A field with strings and abbreviations.
    Abbreviation(&'s str),
}

impl<'s> RawBibliography<'s> {
    /// Parse a raw bibliography from a source string.
    pub fn parse(src: &'s str) -> Result<Self, ParseError> {
        BiblatexParser::new(src).parse()
    }
}

/// Backing struct for parsing a Bib(La)TeX file into a [`RawBibliography`].
struct BiblatexParser<'s> {
    s: Scanner<'s>,
    res: RawBibliography<'s>,
}

/// An error that might occur during initial parsing of the bibliography.
#[derive(Debug, Clone, PartialEq)]
pub struct ParseError {
    /// Where in the source the error occurred.
    pub span: std::ops::Range<usize>,
    /// What kind of error occurred.
    pub kind: ParseErrorKind,
}

impl ParseError {
    pub(crate) fn new(span: std::ops::Range<usize>, kind: ParseErrorKind) -> Self {
        Self { span, kind }
    }
}

impl fmt::Display for ParseError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}: {}-{}", self.kind, self.span.start, self.span.end)
    }
}

impl std::error::Error for ParseError {}

/// Error conditions that might occur during initial parsing of the
/// bibliography.
///
/// Also see [`ParseError`].
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub enum ParseErrorKind {
    /// The file ended prematurely.
    UnexpectedEof,
    /// An unexpected token was encountered.
    Unexpected(Token),
    /// A token was expected, but not found.
    Expected(Token),
    /// A field contained an abbreviation that was not defined.
    UnknownAbbreviation(String),
    /// A TeX command was malformed.
    MalformedCommand,
    /// A duplicate citation key was found.
    DuplicateKey(String),
    /// A type error occurred while trying to resolve cross-references.
    ResolutionError(TypeErrorKind),
}

/// A token that can be encountered during parsing.
#[derive(Debug, Copy, Clone, PartialEq)]
pub enum Token {
    /// An identifier for a field key, citation type, abbreviation, or citation
    /// key.
    Identifier,
    /// An opening brace: `{`.
    OpeningBrace,
    /// A closing brace: `}`.
    ClosingBrace,
    /// A comma: `,`.
    Comma,
    /// A quotation mark: `"`.
    QuotationMark,
    /// An equals sign: `=`.
    Equals,
    /// A decimal point: `.`.
    DecimalPoint,
}

impl fmt::Display for ParseErrorKind {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            Self::UnexpectedEof => write!(f, "unexpected end of file"),
            Self::Expected(token) => write!(f, "expected {}", token),
            Self::Unexpected(token) => write!(f, "unexpected {}", token),
            Self::UnknownAbbreviation(s) => write!(f, "unknown abbreviation {:?}", s),
            Self::MalformedCommand => write!(f, "malformed command"),
            Self::DuplicateKey(s) => write!(f, "duplicate key {:?}", s),
            Self::ResolutionError(e) => {
                write!(f, "type error occurred during crossref resolution: {}", e)
            }
        }
    }
}

impl fmt::Display for Token {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.write_str(match self {
            Self::Identifier => "identifier",
            Self::OpeningBrace => "opening brace",
            Self::ClosingBrace => "closing brace",
            Self::Comma => "comma",
            Self::QuotationMark => "double quote",
            Self::Equals => "equals",
            Self::DecimalPoint => "decimal point",
        })
    }
}

impl<'s> BiblatexParser<'s> {
    /// Constructs a new parser.
    pub fn new(src: &'s str) -> Self {
        Self {
            s: Scanner::new(src),
            res: RawBibliography {
                preamble: String::new(),
                entries: Vec::new(),
                abbreviations: Vec::new(),
            },
        }
    }

    /// Parses the file, consuming the parser in the process.
    pub fn parse(mut self) -> Result<RawBibliography<'s>, ParseError> {
        while !self.s.done() {
            self.s.eat_whitespace();

            match self.s.peek() {
                Some('@') => self.entry()?,
                // Handle comments outside of entry
                Some('%') => self.comment()?,
                Some(_) => {
                    self.s.eat();
                }
                None => break,
            }
        }

        Ok(self.res)
    }

    /// Eat a comma.
    fn comma(&mut self) -> Result<(), ParseError> {
        if !self.s.eat_if(',') {
            return Err(ParseError::new(
                self.here(),
                ParseErrorKind::Expected(Token::Comma),
            ));
        }

        Ok(())
    }

    /// Eat a delimiter.
    fn brace(&mut self, open: bool) -> Result<(), ParseError> {
        let (brace, token) =
            if open { ('{', Token::OpeningBrace) } else { ('}', Token::ClosingBrace) };

        let peeked = self.s.peek();

        if peeked == Some(brace) || peeked == Some('\"') {
            self.s.eat();
            Ok(())
        } else {
            Err(ParseError::new(self.here(), ParseErrorKind::Expected(token)))
        }
    }

    /// Eat a quote.
    fn quote(&mut self) -> Result<(), ParseError> {
        if !self.s.eat_if('"') {
            Err(ParseError::new(
                self.here(),
                ParseErrorKind::Expected(Token::QuotationMark),
            ))
        } else {
            Ok(())
        }
    }

    /// Eat an equals sign.
    fn equals(&mut self) -> Result<(), ParseError> {
        if !self.s.eat_if('=') {
            Err(ParseError::new(self.here(), ParseErrorKind::Expected(Token::Equals)))
        } else {
            Ok(())
        }
    }

    /// Eat a string.
    fn string(&mut self) -> Result<Spanned<&'s str>, ParseError> {
        self.quote()?;
        let idx = self.s.cursor();

        while let Some(c) = self.s.peek() {
            match c {
                '"' => {
                    let res = self.s.from(idx);
                    let span = idx..self.s.cursor();
                    self.quote()?;
                    return Ok(Spanned::new(res, span));
                }
                '\\' => {
                    self.s.eat();
                    self.s.eat();
                }
                _ => {
                    self.s.eat();
                }
            }
        }

        Err(ParseError::new(self.here(), ParseErrorKind::UnexpectedEof))
    }

    /// Eat a number.
    fn number(&mut self) -> Result<&'s str, ParseError> {
        let idx = self.s.cursor();
        let mut has_dot = false;

        while let Some(c) = self.s.peek() {
            let start = self.s.cursor();
            match c {
                '0'..='9' => {
                    self.s.eat();
                }
                '.' => {
                    if !has_dot {
                        self.s.eat();
                        has_dot = true;
                    } else {
                        return Err(ParseError::new(
                            start..self.s.cursor(),
                            ParseErrorKind::Unexpected(Token::DecimalPoint),
                        ));
                    }
                }
                _ => {
                    return Ok(self.s.from(idx));
                }
            }
        }

        Err(ParseError::new(self.here(), ParseErrorKind::UnexpectedEof))
    }

    /// Eat a braced value.
    fn braced(&mut self) -> Result<Spanned<RawChunk<'s>>, ParseError> {
        self.brace(true)?;
        let idx = self.s.cursor();
        let mut braces = 0;

        while let Some(c) = self.s.peek() {
            match c {
                '{' => {
                    self.brace(true)?;
                    braces += 1;
                }
                '}' => {
                    let res = self.s.from(idx);
                    let span = idx..self.s.cursor();
                    self.brace(false)?;
                    if braces == 0 {
                        return Ok(Spanned::new(RawChunk::Normal(res), span));
                    }
                    braces -= 1;
                }
                '\\' => {
                    self.s.eat();
                    self.s.eat();
                }
                _ => {
                    self.s.eat();
                }
            }
        }

        Err(ParseError::new(self.here(), ParseErrorKind::UnexpectedEof))
    }

    /// Eat an element of an abbreviation.
    fn abbr_element(&mut self) -> Result<Spanned<RawChunk<'s>>, ParseError> {
        let start = self.s.cursor();
        let res = match self.s.peek() {
            Some(c) if c.is_ascii_digit() => self.number().map(RawChunk::Normal),
            Some(c) if is_id_start(c) => {
                self.ident().map(|s| RawChunk::Abbreviation(s.v))
            }
            _ => {
                return self.single_field();
            }
        };

        res.map(|v| Spanned::new(v, start..self.s.cursor()))
    }

    /// Eat an abbreviation field.
    fn abbr_field(&mut self) -> Result<Spanned<Field<'s>>, ParseError> {
        let start = self.s.cursor();
        let mut elems = vec![];

        loop {
            elems.push(self.abbr_element()?);
            self.s.eat_whitespace();
            if !self.s.eat_if('#') {
                break;
            }
            self.s.eat_whitespace();
        }

        Ok(Spanned::new(elems, start..self.s.cursor()))
    }

    /// Eat a field.
    fn field(&mut self) -> Result<(Spanned<&'s str>, Spanned<Field<'s>>), ParseError> {
        let key = self.ident()?;
        self.s.eat_whitespace();
        self.equals()?;
        self.s.eat_whitespace();

        let value = self.abbr_field()?;

        // Handle inline comments before closing brace at end of entry:
        //     @article{foo,
        //         title={bar},
        //         year={2025}  % A comment
        //     }
        self.s.eat_whitespace();
        self.comment()?;

        Ok((key, value))
    }

    fn single_field(&mut self) -> Result<Spanned<RawChunk<'s>>, ParseError> {
        match self.s.peek() {
            Some('{') => self.braced(),
            Some('"') => {
                self.string().map(|s| Spanned::new(RawChunk::Normal(s.v), s.span))
            }
            _ => Err(ParseError::new(self.here(), ParseErrorKind::UnexpectedEof)),
        }
    }

    /// Eat fields.
    fn fields(&mut self) -> Result<Vec<Pair<'s>>, ParseError> {
        let mut fields = Vec::new();

        while !self.s.done() {
            self.s.eat_whitespace();

            if self.s.peek() == Some('}') {
                return Ok(fields);
            }

            let (key, value) = self.field()?;

            self.s.eat_whitespace();

            fields.push(Pair::new(key, value));

            match self.s.peek() {
                Some(',') => {
                    self.comma()?;

                    // Handle inline comments after comma at end of field
                    //     @article{foo,
                    //         title={bar},  % A comment
                    //         year={2025}
                    //     }
                    self.s.eat_whitespace();
                    self.comment()?;
                }
                Some('}') => {
                    return Ok(fields);
                }
                _ => {
                    return Err(ParseError::new(
                        self.here(),
                        ParseErrorKind::Expected(Token::Comma),
                    ));
                }
            }
        }

        Err(ParseError::new(self.here(), ParseErrorKind::UnexpectedEof))
    }

    /// Eat an entry key.
    fn key(&mut self) -> Result<Spanned<&'s str>, ParseError> {
        let idx = self.s.cursor();
        self.s.eat_while(is_key);

        Ok(Spanned::new(self.s.from(idx), idx..self.s.cursor()))
    }

    /// Eat an identifier.
    fn ident(&mut self) -> Result<Spanned<&'s str>, ParseError> {
        let idx = self.s.cursor();
        let is_start = self.s.peek().map(is_id_start).unwrap_or_default();

        if is_start {
            self.s.eat();
            self.s.eat_while(is_id_continue);
            Ok(Spanned::new(self.s.from(idx), idx..self.s.cursor()))
        } else {
            Err(ParseError::new(self.here(), ParseErrorKind::Expected(Token::Identifier)))
        }
    }

    /// Eat an entry.
    fn entry(&mut self) -> Result<(), ParseError> {
        let start = self.s.cursor();
        if self.s.eat() != Some('@') {
            panic!("must not call entry when not at an '@'");
        }

        let entry_type = self.ident()?;
        self.s.eat_whitespace();
        self.brace(true)?;
        self.s.eat_whitespace();

        match entry_type.v.to_ascii_lowercase().as_str() {
            "string" => self.strings()?,
            "preamble" => self.preamble()?,
            "comment" => {
                self.s.eat_until('}');
            }
            _ => self.body(entry_type, start)?,
        }

        self.s.eat_whitespace();
        self.brace(false)?;

        Ok(())
    }

    /// Eat the body of a strings entry.
    fn strings(&mut self) -> Result<(), ParseError> {
        let fields = self.fields()?;
        self.res.abbreviations.extend(fields);
        Ok(())
    }

    /// Eat the body of a preamble entry.
    fn preamble(&mut self) -> Result<(), ParseError> {
        let idx = self.s.cursor();
        self.string()?;
        let string = self.s.from(idx);

        if !self.res.preamble.is_empty() {
            self.res.preamble.push_str(" # ");
        }

        self.res.preamble.push_str(string);

        Ok(())
    }

    /// Eat the body of an entry.
    fn body(&mut self, kind: Spanned<&'s str>, start: usize) -> Result<(), ParseError> {
        let key = self.key()?;
        self.s.eat_whitespace();
        self.comma()?;

        // Handle inline comments after entry key
        //     @article{foo,  % A comment
        //         title={bar},
        //         year={2025}
        //     }
        self.s.eat_whitespace();
        self.comment()?;

        self.s.eat_whitespace();
        let fields = self.fields()?;

        self.res
            .entries
            .push(Spanned::new(RawEntry { key, kind, fields }, start..self.s.cursor()));
        Ok(())
    }

    /// Eat an inline comment.
    fn comment(&mut self) -> Result<(), ParseError> {
        if self.s.eat_if('%') {
            self.s.eat_until('\n');
        }
        Ok(())
    }

    fn here(&self) -> Span {
        self.s.cursor()..self.s.cursor()
    }
}

/// The keys for fields and their values.
#[derive(Debug, Clone)]
pub struct Pair<'s> {
    /// The key.
    pub key: Spanned<&'s str>,
    /// The value.
    pub value: Spanned<Field<'s>>,
}

impl<'s> Pair<'s> {
    /// Constructs a new key-value pair.
    pub fn new(key: Spanned<&'s str>, value: Spanned<Field<'s>>) -> Self {
        Self { key, value }
    }
}

/// Whether a character is allowed in an entry key
#[inline]
pub fn is_key(c: char) -> bool {
    !matches!(c, ',' | '}') && !c.is_control() && !c.is_whitespace()
}

/// Whether a character can start an identifier.
#[inline]
pub fn is_id_start(c: char) -> bool {
    !matches!(c, ':' | '<' | '-' | '>') && is_id_continue(c)
}

/// Whether a character can continue an identifier.
#[inline]
pub fn is_id_continue(c: char) -> bool {
    !matches!(
        c,
        '@' | '{' | '}' | '"' | '#' | '\'' | '(' | ')' | ',' | '=' | '%' | '\\' | '~'
    ) && !c.is_control()
        && !c.is_whitespace()
}

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

    fn format(field: &Field<'_>) -> String {
        if field.len() == 1 {
            if let Some(RawChunk::Normal(s)) = field.first().map(|s| &s.v) {
                return format!("{{{}}}", s);
            }
        }

        let mut res = String::new();
        let mut first = true;

        for field in field {
            if !first {
                res.push_str(" # ");
            } else {
                first = false;
            }

            match field.v {
                RawChunk::Normal(s) => {
                    res.push('"');
                    res.push_str(s);
                    res.push('"');
                },
                RawChunk::Abbreviation(s) => res.push_str(s),
            }
        }

        res
    }

    #[track_caller]
    fn test_prop(key: &str, value: &str) -> String {
        let test = format!("@article{{test, {}={}}}", key, value);
        let bt = RawBibliography::parse(&test).unwrap();
        let article = &bt.entries[0];
        format(&article.v.fields[0].value.v)
    }

    #[test]
    fn test_entry_key() {
        let file = "@article{!\"#$%&'()*+-./123:;<=>?@ABC[\\]^_`abc{|~,}";
        let bt = RawBibliography::parse(file).unwrap();
        let article = &bt.entries[0];
        assert_eq!(article.v.key.v, "!\"#$%&'()*+-./123:;<=>?@ABC[\\]^_`abc{|~");
    }

    #[test]
    fn test_empty_entry_key() {
        let file = "@article{,}";
        let bt = RawBibliography::parse(file).unwrap();
        let article = &bt.entries[0];
        assert_eq!(article.v.key.v, "");
    }

    #[test]
    fn test_parse_article() {
        let file = "@article{haug2020,
            title = \"Great proceedings\\{\",
            year=2002,
            author={Haug, {Martin} and Haug, Gregor}}";

        let bt = RawBibliography::parse(file).unwrap();
        let article = &bt.entries[0];

        assert_eq!(article.v.kind.v, "article");

        assert_eq!(article.v.fields[0].key.v, "title");
        assert_eq!(article.v.fields[1].key.v, "year");
        assert_eq!(article.v.fields[2].key.v, "author");
        assert_eq!(format(&article.v.fields[0].value.v), "{Great proceedings\\{}");
        assert_eq!(format(&article.v.fields[1].value.v), "{2002}");
        assert_eq!(format(&article.v.fields[2].value.v), "{Haug, {Martin} and Haug, Gregor}");
    }

    #[test]
    fn test_resolve_string() {
        let bt = RawBibliography::parse("@string{BT = \"bibtex\"}").unwrap();
        assert_eq!(bt.abbreviations[0].key.v, "BT");
        assert_eq!(&bt.abbreviations[0].value.v, &vec![Spanned::new(RawChunk::Normal("bibtex"), 14..20)]);
    }

    #[test]
    fn test_escape() {
        assert_eq!(test_prop("author", "{Mister A\\}\"B\"}"), "{Mister A\\}\"B\"}");
    }

    #[test]
    fn test_abbr() {
        assert_eq!(test_prop("author", "dec # {~12}"), "dec # \"~12\"");
    }
}