Skip to main content

laminapdf_syntax/
lexer.rs

1//! Byte-level tokenizer for PDF syntax (ISO 32000-1 §7.2–7.3).
2//!
3//! The lexer never panics: every slice access is bounds-checked through `get`, and every
4//! loop consumes at least one byte, so lexing is linear in the input length.
5
6use crate::diagnostic::Position;
7use crate::error::{Error, Result};
8use crate::limits::{Limit, Limits};
9use crate::object::{Name, Object, PdfString, StringFormat};
10
11/// One lexical token. Keywords borrow from the input; decoded values are owned.
12///
13/// Added in 0.2.0.
14#[derive(Debug, Clone, PartialEq)]
15pub enum Token<'a> {
16    /// An integer that fits in `i64` (§7.3.3).
17    Integer(i64),
18    /// A real number, or an integer too large for `i64` (§7.3.3).
19    Real(f64),
20    /// A name with `#xx` escapes decoded, without the leading `/` (§7.3.5).
21    Name(Vec<u8>),
22    /// A literal string with escapes decoded (§7.3.4.2).
23    LiteralString(Vec<u8>),
24    /// A hex string, decoded to bytes (§7.3.4.3).
25    HexString(Vec<u8>),
26    /// `[`.
27    ArrayOpen,
28    /// `]`.
29    ArrayClose,
30    /// `<<`.
31    DictOpen,
32    /// `>>`.
33    DictClose,
34    /// Any other run of regular characters: `true`, `obj`, `R`, `stream`, operators, …
35    Keyword(&'a [u8]),
36    /// The end of the input.
37    Eof,
38}
39
40impl Token<'_> {
41    /// The object this token is by itself: a number, name, string, `true`, `false` or `null`
42    /// (`None` for delimiters, other keywords and the end). An integer stays an integer: only
43    /// the parser looks ahead for `gen R`.
44    ///
45    /// Added in 0.2.0.
46    #[must_use]
47    pub fn into_scalar(self) -> Option<Object> {
48        Some(match self {
49            Self::Integer(i) => Object::Integer(i),
50            Self::Real(r) => Object::Real(r),
51            Self::Name(n) => Object::Name(Name(n)),
52            Self::LiteralString(bytes) => Object::String(PdfString {
53                bytes,
54                format: StringFormat::Literal,
55            }),
56            Self::HexString(bytes) => Object::String(PdfString {
57                bytes,
58                format: StringFormat::Hex,
59            }),
60            Self::Keyword(b"true") => Object::Bool(true),
61            Self::Keyword(b"false") => Object::Bool(false),
62            Self::Keyword(b"null") => Object::Null,
63            Self::Keyword(_) | Self::ArrayOpen | Self::ArrayClose | Self::DictOpen | Self::DictClose | Self::Eof => {
64                return None;
65            }
66        })
67    }
68}
69
70/// PDF white-space characters (Table 1).
71///
72/// Added in 0.2.0.
73pub const fn is_whitespace(b: u8) -> bool {
74    matches!(b, b'\0' | b'\t' | b'\n' | b'\x0C' | b'\r' | b' ')
75}
76
77/// PDF delimiter characters (Table 2).
78///
79/// Added in 0.2.0.
80pub const fn is_delimiter(b: u8) -> bool {
81    matches!(b, b'(' | b')' | b'<' | b'>' | b'[' | b']' | b'{' | b'}' | b'/' | b'%')
82}
83
84/// Neither white-space nor delimiter.
85///
86/// Added in 0.2.0.
87pub const fn is_regular(b: u8) -> bool {
88    !is_whitespace(b) && !is_delimiter(b)
89}
90
91pub(crate) const fn hex_value(b: u8) -> Option<u8> {
92    match b {
93        b'0'..=b'9' => Some(b - b'0'),
94        b'a'..=b'f' => Some(b - b'a' + 10),
95        b'A'..=b'F' => Some(b - b'A' + 10),
96        _ => None,
97    }
98}
99
100/// A cursor over PDF bytes that yields [`Token`]s.
101///
102/// Added in 0.2.0.
103#[derive(Debug, Clone)]
104pub struct Lexer<'a> {
105    data: &'a [u8],
106    pos: usize,
107    max_string_length: usize,
108    /// Whether a byte past the end of `data` was looked for (see [`Lexer::reached_end`]).
109    reached_end: bool,
110}
111
112impl<'a> Lexer<'a> {
113    /// A lexer over `data`, starting at byte offset `pos`, with the default [`Limits`].
114    ///
115    /// Added in 0.2.0.
116    pub const fn new(data: &'a [u8], pos: usize) -> Self {
117        Self {
118            data,
119            pos,
120            max_string_length: Limits::new().max_string_length(),
121            reached_end: false,
122        }
123    }
124
125    /// Applies `limits` ([`Limits::max_string_length`] bounds every string and name token).
126    ///
127    /// Added in 0.2.0.
128    #[must_use]
129    pub const fn with_limits(mut self, limits: &Limits) -> Self {
130        self.max_string_length = limits.max_string_length();
131        self
132    }
133
134    /// Fails once a string or name token that started at `start` holds more than
135    /// [`Limits::max_string_length`] bytes.
136    fn check_length(&self, out: &[u8], start: usize) -> Result<()> {
137        if out.len() > self.max_string_length {
138            return Err(Error::limit(Limit::StringLength, Some(start)));
139        }
140        Ok(())
141    }
142
143    /// The current byte offset.
144    ///
145    /// Added in 0.2.0.
146    pub const fn pos(&self) -> usize {
147        self.pos
148    }
149
150    /// Moves the cursor to byte offset `pos` (past the end is fine: the next token is [`Token::Eof`]).
151    ///
152    /// Added in 0.2.0.
153    pub const fn set_pos(&mut self, pos: usize) {
154        self.pos = pos;
155    }
156
157    /// The whole input.
158    ///
159    /// Added in 0.2.0.
160    pub const fn data(&self) -> &'a [u8] {
161        self.data
162    }
163
164    /// Whether lexing so far has looked for a byte past the end of the input (to finish a
165    /// token, skip white-space or find out that there is no next token).
166    ///
167    /// When it has not, every token read so far depends only on the bytes before the end, so
168    /// lexing a window of a larger input gave the same tokens as lexing the whole input would.
169    /// A caller reading a window (`laminapdf-cos` over a source without an in-memory slice)
170    /// retries with a larger one when this is `true` and the window does not end the input.
171    ///
172    /// Added in 0.2.0.
173    pub const fn reached_end(&self) -> bool {
174        self.reached_end
175    }
176
177    fn peek(&mut self) -> Option<u8> {
178        self.peek_at(0)
179    }
180
181    fn peek_at(&mut self, ahead: usize) -> Option<u8> {
182        let byte = self.data.get(self.pos.saturating_add(ahead)).copied();
183        if byte.is_none() {
184            self.reached_end = true;
185        }
186        byte
187    }
188
189    /// Skips white-space and `%` comments.
190    ///
191    /// Added in 0.2.0.
192    pub fn skip_whitespace(&mut self) {
193        while let Some(b) = self.peek() {
194            if is_whitespace(b) {
195                self.pos += 1;
196            } else if b == b'%' {
197                while let Some(c) = self.peek() {
198                    if c == b'\n' || c == b'\r' {
199                        break;
200                    }
201                    self.pos += 1;
202                }
203            } else {
204                break;
205            }
206        }
207    }
208
209    fn syntax(&self, message: &'static str) -> Error {
210        Error::Syntax {
211            at: Position::offset(self.pos),
212            message,
213        }
214    }
215
216    /// Reads the next token, skipping leading white-space and comments.
217    ///
218    /// # Errors
219    /// [`Error::UnexpectedEof`] for an unterminated string, [`Error::Syntax`] for an unbalanced
220    /// `)` or `>` or an invalid hex digit, [`Error::LimitExceeded`] for a string or name longer
221    /// than [`Limits::max_string_length`].
222    ///
223    /// Added in 0.2.0.
224    pub fn next_token(&mut self) -> Result<Token<'a>> {
225        self.skip_whitespace();
226        let Some(b) = self.peek() else {
227            return Ok(Token::Eof);
228        };
229        match b {
230            b'[' => {
231                self.pos += 1;
232                Ok(Token::ArrayOpen)
233            }
234            b']' => {
235                self.pos += 1;
236                Ok(Token::ArrayClose)
237            }
238            b'<' if self.peek_at(1) == Some(b'<') => {
239                self.pos += 2;
240                Ok(Token::DictOpen)
241            }
242            b'>' if self.peek_at(1) == Some(b'>') => {
243                self.pos += 2;
244                Ok(Token::DictClose)
245            }
246            b'<' => self.hex_string(),
247            b'(' => self.literal_string(),
248            b'/' => self.name(),
249            b'{' | b'}' => {
250                let kw = self.data.get(self.pos..=self.pos).unwrap_or_default();
251                self.pos += 1;
252                Ok(Token::Keyword(kw))
253            }
254            b')' | b'>' => Err(self.syntax("unbalanced delimiter")),
255            _ => Ok(self.regular_run()),
256        }
257    }
258
259    fn regular_run(&mut self) -> Token<'a> {
260        let start = self.pos;
261        while self.peek().is_some_and(is_regular) {
262            self.pos += 1;
263        }
264        let run = self.data.get(start..self.pos).unwrap_or_default();
265        parse_number(run).unwrap_or(Token::Keyword(run))
266    }
267
268    fn name(&mut self) -> Result<Token<'a>> {
269        let start = self.pos;
270        self.pos += 1; // the '/'
271        let mut out = Vec::new();
272        while let Some(b) = self.peek().filter(|&b| is_regular(b)) {
273            if b == b'#' {
274                let hi = self.peek_at(1).and_then(hex_value);
275                let lo = self.peek_at(2).and_then(hex_value);
276                if let (Some(hi), Some(lo)) = (hi, lo) {
277                    out.push((hi << 4) | lo);
278                    self.pos += 3;
279                    self.check_length(&out, start)?;
280                    continue;
281                }
282            }
283            out.push(b);
284            self.pos += 1;
285            self.check_length(&out, start)?;
286        }
287        Ok(Token::Name(out))
288    }
289
290    fn hex_string(&mut self) -> Result<Token<'a>> {
291        let start = self.pos;
292        self.pos += 1; // the '<'
293        let mut out = Vec::new();
294        let mut high: Option<u8> = None;
295        loop {
296            let Some(b) = self.peek() else {
297                return Err(Error::UnexpectedEof {
298                    at: Position::offset(self.pos),
299                });
300            };
301            self.pos += 1;
302            if b == b'>' {
303                break;
304            }
305            if is_whitespace(b) {
306                continue;
307            }
308            let Some(v) = hex_value(b) else {
309                return Err(Error::Syntax {
310                    at: Position::offset(self.pos - 1),
311                    message: "invalid hex digit",
312                });
313            };
314            match high.take() {
315                Some(h) => {
316                    out.push((h << 4) | v);
317                    self.check_length(&out, start)?;
318                }
319                None => high = Some(v),
320            }
321        }
322        if let Some(h) = high {
323            out.push(h << 4); // odd length: the missing final digit is 0 (§7.3.4.3)
324            self.check_length(&out, start)?;
325        }
326        Ok(Token::HexString(out))
327    }
328
329    fn literal_string(&mut self) -> Result<Token<'a>> {
330        let start = self.pos;
331        self.pos += 1; // the '('
332        let mut out = Vec::new();
333        let mut depth = 0usize;
334        loop {
335            self.check_length(&out, start)?;
336            let Some(b) = self.peek() else {
337                return Err(Error::UnexpectedEof {
338                    at: Position::offset(self.pos),
339                });
340            };
341            self.pos += 1;
342            match b {
343                b'(' => {
344                    depth += 1;
345                    out.push(b);
346                }
347                b')' if depth == 0 => break,
348                b')' => {
349                    depth -= 1;
350                    out.push(b);
351                }
352                b'\\' => self.string_escape(&mut out)?,
353                b'\r' => {
354                    // An unescaped EOL of any kind reads as a single LF (§7.3.4.2).
355                    if self.peek() == Some(b'\n') {
356                        self.pos += 1;
357                    }
358                    out.push(b'\n');
359                }
360                _ => out.push(b),
361            }
362        }
363        Ok(Token::LiteralString(out))
364    }
365
366    fn string_escape(&mut self, out: &mut Vec<u8>) -> Result<()> {
367        let Some(e) = self.peek() else {
368            return Err(Error::UnexpectedEof {
369                at: Position::offset(self.pos),
370            });
371        };
372        self.pos += 1;
373        match e {
374            b'n' => out.push(b'\n'),
375            b'r' => out.push(b'\r'),
376            b't' => out.push(b'\t'),
377            b'b' => out.push(b'\x08'),
378            b'f' => out.push(b'\x0C'),
379            b'0'..=b'7' => {
380                let mut value = u32::from(e - b'0');
381                for _ in 0..2 {
382                    match self.peek() {
383                        Some(d @ b'0'..=b'7') => {
384                            value = value * 8 + u32::from(d - b'0');
385                            self.pos += 1;
386                        }
387                        _ => break,
388                    }
389                }
390                // High-order overflow is ignored (§7.3.4.2).
391                out.push(value.to_le_bytes()[0]);
392            }
393            b'\r' => {
394                // Line continuation: backslash + EOL produces nothing.
395                if self.peek() == Some(b'\n') {
396                    self.pos += 1;
397                }
398            }
399            b'\n' => {}
400            // `\(`, `\)`, `\\`, and any unknown escape: the backslash is ignored.
401            other => out.push(other),
402        }
403        Ok(())
404    }
405}
406
407/// Parses a run of regular characters as an integer or real, if it is one.
408#[expect(
409    clippy::naive_bytecount,
410    reason = "number tokens are a few bytes long; not worth a dependency"
411)]
412fn parse_number(run: &[u8]) -> Option<Token<'_>> {
413    let (sign_len, digits) = match run.first()? {
414        b'+' | b'-' => (1, run.get(1..)?),
415        _ => (0, run),
416    };
417    let dots = digits.iter().filter(|&&b| b == b'.').count();
418    let all_valid = digits.iter().all(|&b| b.is_ascii_digit() || b == b'.');
419    let has_digit = digits.iter().any(u8::is_ascii_digit);
420    if !all_valid || !has_digit || dots > 1 {
421        return None;
422    }
423    let text = std::str::from_utf8(run).ok()?;
424    if dots == 0
425        && let Ok(i) = text.parse::<i64>()
426    {
427        return Some(Token::Integer(i));
428    }
429    // Reals, and integers too large for i64, degrade gracefully to f64.
430    let normalized = if digits.first() == Some(&b'.') {
431        let (sign, rest) = text.split_at_checked(sign_len)?;
432        format!("{sign}0{rest}")
433    } else {
434        text.to_owned()
435    };
436    normalized.parse::<f64>().ok().map(Token::Real)
437}
438
439#[cfg(test)]
440mod tests {
441    use super::*;
442
443    fn tokens(input: &[u8]) -> Vec<Token<'_>> {
444        let mut lex = Lexer::new(input, 0);
445        let mut out = Vec::new();
446        loop {
447            match lex.next_token() {
448                Ok(Token::Eof) | Err(_) => return out,
449                Ok(t) => out.push(t),
450            }
451        }
452    }
453
454    #[test]
455    fn numbers_accept_leading_dot_sign_and_trailing_dot() {
456        assert_eq!(
457            tokens(b"+5 -.5 4. 0.25 -3"),
458            vec![
459                Token::Integer(5),
460                Token::Real(-0.5),
461                Token::Real(4.0),
462                Token::Real(0.25),
463                Token::Integer(-3)
464            ]
465        );
466    }
467
468    #[test]
469    fn integer_overflow_degrades_to_real() {
470        assert_eq!(tokens(b"99999999999999999999"), vec![Token::Real(1e20)]);
471    }
472
473    #[test]
474    fn comments_and_all_whitespace_kinds_are_skipped() {
475        assert_eq!(
476            tokens(b"%c\r\n\x00\t\x0C 1%x\n2"),
477            vec![Token::Integer(1), Token::Integer(2)]
478        );
479    }
480
481    #[test]
482    fn literal_string_decodes_all_escapes() {
483        assert_eq!(
484            tokens(b"(\\n\\r\\t\\b\\f\\(\\)\\\\\\101\\7x\\q)"),
485            vec![Token::LiteralString(b"\n\r\t\x08\x0C()\\A\x07xq".to_vec())]
486        );
487    }
488
489    #[test]
490    fn literal_string_handles_line_continuation() {
491        assert_eq!(
492            tokens(b"(ab\\\r\ncd\\\nef)"),
493            vec![Token::LiteralString(b"abcdef".to_vec())]
494        );
495    }
496
497    #[test]
498    fn literal_string_keeps_balanced_parens() {
499        assert_eq!(tokens(b"(a(b)c)"), vec![Token::LiteralString(b"a(b)c".to_vec())]);
500    }
501
502    #[test]
503    fn literal_string_normalizes_raw_crlf_to_lf() {
504        assert_eq!(tokens(b"(a\r\nb\rc)"), vec![Token::LiteralString(b"a\nb\nc".to_vec())]);
505    }
506
507    #[test]
508    fn hex_string_ignores_whitespace_and_pads_odd_length() {
509        assert_eq!(tokens(b"<4 1\n4>"), vec![Token::HexString(vec![0x41, 0x40])]);
510    }
511
512    #[test]
513    fn name_decodes_hash_escapes() {
514        assert_eq!(tokens(b"/A#20B#2"), vec![Token::Name(b"A B#2".to_vec())]);
515    }
516
517    fn lex_with_max_string(input: &[u8], max: usize) -> Result<Token<'_>> {
518        Lexer::new(input, 0)
519            .with_limits(&Limits::default().with_max_string_length(max))
520            .next_token()
521    }
522
523    #[test]
524    fn literal_string_at_the_length_limit_is_accepted() {
525        assert_eq!(
526            lex_with_max_string(b"(abcd)", 4),
527            Ok(Token::LiteralString(b"abcd".to_vec()))
528        );
529    }
530
531    #[test]
532    fn literal_string_past_the_length_limit_is_rejected() {
533        assert_eq!(
534            lex_with_max_string(b"(abcde)", 4),
535            Err(Error::LimitExceeded {
536                limit: Limit::StringLength,
537                at: Some(Position::FileOffset(0))
538            })
539        );
540    }
541
542    #[test]
543    fn hex_string_at_the_length_limit_is_accepted() {
544        assert_eq!(
545            lex_with_max_string(b"<41424344>", 4),
546            Ok(Token::HexString(b"ABCD".to_vec()))
547        );
548    }
549
550    #[test]
551    fn hex_string_past_the_length_limit_is_rejected() {
552        assert!(matches!(
553            lex_with_max_string(b"<4142434445>", 4),
554            Err(Error::LimitExceeded {
555                limit: Limit::StringLength,
556                ..
557            })
558        ));
559    }
560
561    #[test]
562    fn name_past_the_length_limit_is_rejected() {
563        assert!(matches!(
564            lex_with_max_string(b"/ABCDE", 4),
565            Err(Error::LimitExceeded {
566                limit: Limit::StringLength,
567                ..
568            })
569        ));
570    }
571
572    #[test]
573    fn unterminated_string_is_an_error() {
574        assert!(Lexer::new(b"(abc", 0).next_token().is_err());
575    }
576
577    fn reached_end_after_one_token(input: &[u8]) -> bool {
578        let mut lex = Lexer::new(input, 0);
579        let _ = lex.next_token();
580        lex.reached_end()
581    }
582
583    #[test]
584    fn a_token_followed_by_a_delimiter_does_not_reach_the_end() {
585        assert!(!reached_end_after_one_token(b"123 "));
586    }
587
588    #[test]
589    fn a_token_that_runs_to_the_end_reaches_it() {
590        // `123` might continue past the end (`1234`), so the result depends on what follows.
591        assert!(reached_end_after_one_token(b"123"));
592    }
593
594    #[test]
595    fn a_lone_less_than_at_the_end_reaches_it() {
596        // `<` could be the start of `<<`.
597        assert!(reached_end_after_one_token(b"<"));
598    }
599}