Skip to main content

pdfcer_model/
lexer.rs

1//! # PDF tokenizer (ISO 32000-1 §7.2 lexical conventions + §7.3 token syntax)
2//!
3//! Byte-classification, token scanning, and the lossy-decode-plus-span
4//! model that underpins pdfcer's round-trip invariant. Spec sources are
5//! the Pass 1 slice of the PDF-spec RAG (`D:\Dev\Rag-Specialized\PDF_Spec\`):
6//! `iso32000__s__7.2.md` (byte classes, EOL, comments),
7//! `iso32000__s__7.3.md` (numerics, keywords), `iso32000__s__7.3.4.md`
8//! (strings), `iso32000__s__7.3.5.md` (names). Clause numbers below are
9//! ISO 32000-1:2008.
10//!
11//! ## Scope and layering
12//!
13//! The lexer produces [`Token`]s — syntax-level units with **decoded
14//! values where decoding is lossy** (strings, names) and a [`ByteSpan`]
15//! recording exactly which source bytes each token came from. It does
16//! **not**:
17//!
18//! - resolve object structure (`obj`/`endobj`/`R` are delivered as
19//!   [`TokenKind::Keyword`]; the object parser interprets them);
20//! - read stream *data* (the parser handles the `stream` keyword's
21//!   `/Length`-governed data span itself — §7.3.8's framing rules need
22//!   the resolved `/Length`, which can be an indirect reference, so data
23//!   extraction is inherently a parser-with-xref concern);
24//! - interpret string bytes as text (§7.9.2 is a later-Pass concern; the
25//!   lexer delivers exact decoded bytes).
26//!
27//! Per §7.8.2 content streams are lexed with **these same rules** — this
28//! one lexer serves both the file body and content streams (operators
29//! arrive as `Keyword` tokens; the sole divergence, inline-image data
30//! between `ID` and `EI`, is handled by the content-stream layer, see
31//! `iso32000__s__8.9.7.md`).
32//!
33//! ## The decode + span model (round-trip, ARCHITECTURE.md §5)
34//!
35//! PDF token syntax is non-canonical: `/A#42` ≡ `/AB` (§7.3.5 NOTE 1), a
36//! bare CRLF inside a literal string decodes to one 0Ah byte (§7.3.4.2 —
37//! lossy *by specification*), and `4.` / `+17` / `0.40` carry formatting
38//! a parsed value cannot reproduce (§7.3.3). Therefore every token
39//! carries its span, tokens never re-emit themselves from decoded
40//! values, and untouched entities re-emit their source bytes verbatim.
41//! See `crate::span` for the full contract
42//! (docs/decisions/001-oxidize-pdf-adopt-vs-build.md §6.1).
43//!
44//! ## Failure philosophy
45//!
46//! Fail-clean (ARCHITECTURE.md §10; decision 001 §6.1 item 4): malformed
47//! syntax yields a structured [`LexError`] with the exact byte offset —
48//! never a silent best-guess decode, never a panic (the crate-level
49//! `deny` lints enforce the latter mechanically). Where the spec leaves
50//! reader behaviour undefined (e.g. `#` in a name followed by non-hex,
51//! §7.3.5 — see that RAG file's gotcha list), Pass 1 errors strictly;
52//! documented tolerances for real-world deviations get added
53//! deliberately, with corpus evidence filed in `C:\personal_rag\pdf\`,
54//! not by default.
55//!
56//! ## Resource guards (ARCHITECTURE.md §10.1 — pdfcer policy, not spec)
57//!
58//! [`MAX_TOKEN_LEN`] bounds name/keyword/number tokens;
59//! [`MAX_STRING_LEN`] bounds decoded string output. Annex C's limits
60//! (name 127 bytes, content-stream string 32,767 bytes) are *writer*
61//! guidance a reader should exceed gracefully (signature `/Contents`
62//! strings routinely blow past 32,767 — `iso32000__s__7.3.4.md`), so the
63//! ceilings here are deliberately far above spec limits: high enough for
64//! any legitimate file, low enough that a hostile file can't force
65//! unbounded allocation from the lexer.
66
67use crate::span::ByteSpan;
68
69// ---------------------------------------------------------------------------
70// Byte classification (§7.2.2, Tables 1 and 2)
71// ---------------------------------------------------------------------------
72
73/// Is `b` one of the six white-space characters (Table 1)?
74///
75/// NUL (00h) **is** white-space — per the spec RAG, "the single most
76/// commonly mis-implemented entry in Table 1."
77#[must_use]
78pub const fn is_whitespace(b: u8) -> bool {
79    matches!(b, 0x00 | 0x09 | 0x0A | 0x0C | 0x0D | 0x20)
80}
81
82/// Is `b` one of the ten delimiter characters (Table 2)?
83///
84/// `{` and `}` are delimiters even though no base-grammar construct uses
85/// them (they belong to Type 4 PostScript-calculator function streams,
86/// §7.10.5) — they still terminate adjacent tokens.
87#[must_use]
88pub const fn is_delimiter(b: u8) -> bool {
89    matches!(
90        b,
91        b'(' | b')' | b'<' | b'>' | b'[' | b']' | b'{' | b'}' | b'/' | b'%'
92    )
93}
94
95/// Is `b` a regular character (everything neither white-space nor
96/// delimiter, §7.2.2)? Includes all bytes 80h–FFh.
97#[must_use]
98pub const fn is_regular(b: u8) -> bool {
99    !is_whitespace(b) && !is_delimiter(b)
100}
101
102// ---------------------------------------------------------------------------
103// Resource-guard policy constants (ARCHITECTURE.md §10.1)
104// ---------------------------------------------------------------------------
105
106/// Maximum length of a single name/keyword/number token, in source bytes.
107///
108/// pdfcer policy, not a spec value: Annex C's 127-byte name limit is
109/// writer guidance ("readers should accept longer") — and PDF/A
110/// §6.1.12 tests that conforming readers do NOT impose the old
111/// Annex-C implementation limits at all. The 2026-07-30 corpus run
112/// proved the point: the original 8 KiB ceiling rejected veraPDF's
113/// `6-1-12-t02-pass-k.pdf`, a VALID file, the only pass-classified
114/// corpus file pdfcer mishandled. Raised to 1 MiB: still a hard bound
115/// against unbounded adversarial buffering, far above anything the
116/// PDF/A limit tests exercise.
117pub const MAX_TOKEN_LEN: usize = 1024 * 1024;
118
119/// Maximum decoded length of a single string token, in bytes.
120///
121/// pdfcer policy, not a spec value: Annex C's 32,767-byte limit applies
122/// only to content-stream strings, and legitimate signature `/Contents`
123/// hex strings exceed it by design. 16 MiB accommodates any plausible
124/// legitimate string (embedded-signature CMS containers included) while
125/// bounding hostile allocation ([`LexErrorKind::StringTooLong`]).
126pub const MAX_STRING_LEN: usize = 16 * 1024 * 1024;
127
128// ---------------------------------------------------------------------------
129// Tokens
130// ---------------------------------------------------------------------------
131
132/// One lexical token: its classified/decoded content plus the exact
133/// source-byte span it was scanned from.
134///
135/// The span is load-bearing (see module docs); [`Token::lexeme`]
136/// recovers the raw source bytes.
137#[derive(Debug, Clone, PartialEq)]
138pub struct Token {
139    /// Classified/decoded content of the token.
140    pub kind: TokenKind,
141    /// Exact source bytes this token was scanned from.
142    pub span: ByteSpan,
143}
144
145impl Token {
146    /// The raw source bytes of this token within `buf` (the buffer it
147    /// was lexed from). `None` indicates the span/buffer pairing is
148    /// wrong — a caller logic error surfaced non-panicking per the
149    /// crate policy.
150    #[must_use]
151    pub fn lexeme<'a>(&self, buf: &'a [u8]) -> Option<&'a [u8]> {
152        self.span.slice(buf)
153    }
154}
155
156/// Token classification.
157///
158/// Where decoding is lossy (strings, names) the decoded bytes are stored
159/// here **and** the raw form remains reachable via [`Token::span`] —
160/// both are needed (decoded for semantics, raw for verbatim re-emission).
161/// Where the lexeme itself is the value (keywords) nothing is copied;
162/// the parser reads the span.
163#[derive(Debug, Clone, PartialEq)]
164#[non_exhaustive]
165pub enum TokenKind {
166    /// Integer (§7.3.3): optional sign, decimal digits. Value parsed as
167    /// `i64` — wider than Annex C's ±2³¹ *writer* range on purpose, so
168    /// large-but-well-formed offsets in big files still lex.
169    Integer(i64),
170    /// Real (§7.3.3): optional sign, digits, one PERIOD — leading
171    /// (`-.002`), trailing (`4.`), or embedded. The stored `f64` is the
172    /// *semantic* value; the source formatting survives via the span.
173    Real(f64),
174    /// Literal (§7.3.4.2) or hexadecimal (§7.3.4.3) string, fully
175    /// decoded to its byte content (escapes applied, EOLs normalized,
176    /// hex pairs assembled). These are raw bytes, not text — §7.9.2
177    /// interpretation happens in later layers.
178    String(Vec<u8>),
179    /// Name (§7.3.5), `#`-escapes decoded, WITHOUT the leading `/`.
180    /// May be empty (the bare `/` is a valid name). Decoding before
181    /// storage is required so `/Type` and `/Ty#70e` compare equal.
182    Name(Vec<u8>),
183    /// `[` (§7.3.6).
184    ArrayOpen,
185    /// `]` (§7.3.6).
186    ArrayClose,
187    /// `<<` (§7.3.7).
188    DictOpen,
189    /// `>>` (§7.3.7).
190    DictClose,
191    /// `{` — a delimiter with no role in the base object grammar; only
192    /// Type 4 function streams (§7.10.5) use it. The lexer emits it so
193    /// that layer can parse; the object parser treats it as a syntax
194    /// error.
195    BraceOpen,
196    /// `}` — see [`TokenKind::BraceOpen`].
197    BraceClose,
198    /// Any other run of regular characters: `true`, `false`, `null`,
199    /// `obj`, `endobj`, `stream`, `R`, `xref`, content-stream operators
200    /// (`BT`, `Tj`, `re`, …), and also malformed numeric-looking runs
201    /// (`1.2.3`) which the *parser* rejects in context. The bytes are
202    /// the span — call [`Token::lexeme`].
203    Keyword,
204}
205
206// ---------------------------------------------------------------------------
207// Errors
208// ---------------------------------------------------------------------------
209
210/// A lexical error: what went wrong and exactly where.
211///
212/// C-GOOD-ERR: implements `std::error::Error` via `thiserror`, is
213/// `Send + Sync + 'static`.
214#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
215#[error("lex error at byte {offset}: {kind}")]
216pub struct LexError {
217    /// Byte offset (absolute, from buffer start) where the error was
218    /// detected.
219    pub offset: usize,
220    /// What was wrong.
221    pub kind: LexErrorKind,
222}
223
224/// Classification of lexical errors.
225#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
226#[non_exhaustive]
227pub enum LexErrorKind {
228    /// EOF inside a literal string before its parentheses balanced, or
229    /// a REVERSE SOLIDUS as the final byte (§7.3.4.2 leaves the latter
230    /// undefined; pdfcer errors).
231    #[error("unterminated literal string")]
232    UnterminatedString,
233    /// EOF inside a hexadecimal string before the closing `>`.
234    #[error("unterminated hexadecimal string")]
235    UnterminatedHexString,
236    /// A byte in a hexadecimal string that is neither a hex digit nor
237    /// white-space (§7.3.4.3; treated as a syntax error per the RAG's
238    /// reading).
239    #[error("invalid byte 0x{0:02X} in hexadecimal string")]
240    InvalidHexStringByte(u8),
241    /// `#` in a name not followed by two hex digits. §7.3.5 defines no
242    /// reader behaviour for this; Pass 1 is strict (see module docs'
243    /// failure philosophy).
244    #[error("malformed #-escape in name")]
245    MalformedNameEscape,
246    /// `#00` in a name — the name definition excludes NUL ("any
247    /// characters except null", §7.3.5).
248    #[error("#00 (NUL) escape in name")]
249    NulInName,
250    /// A delimiter that cannot begin a token: a lone `)` or a `>` not
251    /// followed by another `>`.
252    #[error("unexpected delimiter byte 0x{0:02X}")]
253    UnexpectedByte(u8),
254    /// A numeric-looking token whose integer value exceeds `i64` — far
255    /// outside any legitimate PDF (Annex C writer range is ±2³¹);
256    /// refused rather than silently saturated (fail-clean).
257    #[error("integer token overflows i64")]
258    IntegerOverflow,
259    /// Regular-character run longer than [`MAX_TOKEN_LEN`] (resource
260    /// guard, pdfcer policy).
261    #[error("token exceeds MAX_TOKEN_LEN ({MAX_TOKEN_LEN} bytes)")]
262    TokenTooLong,
263    /// Decoded string output longer than [`MAX_STRING_LEN`] (resource
264    /// guard, pdfcer policy).
265    #[error("string exceeds MAX_STRING_LEN ({MAX_STRING_LEN} bytes)")]
266    StringTooLong,
267}
268
269// ---------------------------------------------------------------------------
270// The lexer
271// ---------------------------------------------------------------------------
272
273/// A pull tokenizer over a byte buffer.
274///
275/// Construct with [`Lexer::new`] (from the buffer start) or
276/// [`Lexer::at`] (from an arbitrary offset — xref-driven parsing jumps
277/// straight to object offsets), then call [`Lexer::next_token`]
278/// repeatedly. White-space and comments are skipped between tokens
279/// (§7.2.2/§7.2.3: a comment separates tokens exactly like white-space);
280/// their bytes remain reconstructable from the buffer because every
281/// token records its span, and untouched-object re-emission works on
282/// whole-object spans anyway (see `crate::span`).
283///
284/// # Examples
285///
286/// ```
287/// use pdfcer_model::lexer::{Lexer, TokenKind};
288///
289/// let mut lx = Lexer::new(b"/Type /Pages % a comment\n42");
290/// assert!(matches!(lx.next_token().unwrap().unwrap().kind,
291///                  TokenKind::Name(ref n) if n == b"Type"));
292/// assert!(matches!(lx.next_token().unwrap().unwrap().kind,
293///                  TokenKind::Name(ref n) if n == b"Pages"));
294/// assert!(matches!(lx.next_token().unwrap().unwrap().kind,
295///                  TokenKind::Integer(42)));
296/// assert!(lx.next_token().unwrap().is_none()); // EOF
297/// ```
298#[derive(Debug, Clone)]
299pub struct Lexer<'a> {
300    buf: &'a [u8],
301    pos: usize,
302}
303
304impl<'a> Lexer<'a> {
305    /// Lexer over `buf`, starting at byte 0.
306    #[must_use]
307    pub const fn new(buf: &'a [u8]) -> Self {
308        Self { buf, pos: 0 }
309    }
310
311    /// Lexer over `buf`, starting at `pos`. If `pos` is past the end of
312    /// `buf`, the lexer is immediately at EOF (a caller passing a bogus
313    /// xref offset gets a clean "no token" rather than a panic).
314    #[must_use]
315    pub const fn at(buf: &'a [u8], pos: usize) -> Self {
316        Self { buf, pos }
317    }
318
319    /// Current byte offset (the next byte the lexer will examine).
320    ///
321    /// After a successful [`Lexer::next_token`] this sits one past the
322    /// returned token — which is exactly where stream data begins after
323    /// a `stream` keyword's EOL, so the parser uses this to take over
324    /// for §7.3.8 data extraction.
325    #[must_use]
326    pub const fn pos(&self) -> usize {
327        self.pos
328    }
329
330    /// Scan and return the next token, `Ok(None)` at end of input.
331    ///
332    /// # Errors
333    ///
334    /// [`LexError`] with the offending byte offset — see
335    /// [`LexErrorKind`] for the cases. After an error the lexer's
336    /// position is unspecified; callers treat lex errors as fatal for
337    /// the current parse unit (recovery strategies live in the parser,
338    /// not here).
339    pub fn next_token(&mut self) -> Result<Option<Token>, LexError> {
340        self.skip_ws_and_comments();
341        let start = self.pos;
342        let Some(b) = self.peek() else {
343            return Ok(None);
344        };
345
346        let kind = match b {
347            b'[' => {
348                self.bump();
349                TokenKind::ArrayOpen
350            }
351            b']' => {
352                self.bump();
353                TokenKind::ArrayClose
354            }
355            b'{' => {
356                self.bump();
357                TokenKind::BraceOpen
358            }
359            b'}' => {
360                self.bump();
361                TokenKind::BraceClose
362            }
363            b'<' => {
364                // `<<` opens a dictionary; `<…` begins a hex string.
365                // One byte of lookahead disambiguates (§7.3.4.3 note in
366                // the RAG).
367                if self.peek_at(1) == Some(b'<') {
368                    self.bump();
369                    self.bump();
370                    TokenKind::DictOpen
371                } else {
372                    self.bump();
373                    TokenKind::String(self.scan_hex_string_body()?)
374                }
375            }
376            b'>' => {
377                if self.peek_at(1) == Some(b'>') {
378                    self.bump();
379                    self.bump();
380                    TokenKind::DictClose
381                } else {
382                    // A single `>` begins nothing.
383                    return Err(self.err_at(start, LexErrorKind::UnexpectedByte(b'>')));
384                }
385            }
386            b'(' => {
387                self.bump();
388                TokenKind::String(self.scan_literal_string_body()?)
389            }
390            b')' => {
391                // A `)` outside a literal string balances nothing.
392                return Err(self.err_at(start, LexErrorKind::UnexpectedByte(b')')));
393            }
394            b'/' => {
395                self.bump();
396                TokenKind::Name(self.scan_name_body()?)
397            }
398            _ => {
399                // A run of regular characters: number or keyword.
400                debug_assert!(is_regular(b));
401                self.scan_regular_run(start)?
402            }
403        };
404
405        Ok(Some(Token {
406            kind,
407            span: ByteSpan::from_range(start..self.pos),
408        }))
409    }
410
411    // -- low-level cursor helpers (all bounds-checked; crate policy) --------
412
413    fn peek(&self) -> Option<u8> {
414        self.buf.get(self.pos).copied()
415    }
416
417    fn peek_at(&self, ahead: usize) -> Option<u8> {
418        self.buf.get(self.pos.saturating_add(ahead)).copied()
419    }
420
421    fn bump(&mut self) {
422        self.pos = self.pos.saturating_add(1);
423    }
424
425    fn err_here(&self, kind: LexErrorKind) -> LexError {
426        LexError {
427            offset: self.pos,
428            kind,
429        }
430    }
431
432    fn err_at(&self, offset: usize, kind: LexErrorKind) -> LexError {
433        LexError { offset, kind }
434    }
435
436    // -- inter-token skipping (§7.2.2 white-space, §7.2.3 comments) ---------
437
438    /// Skip white-space and comments. A comment runs from `%` to (not
439    /// including) the next CR or LF, or to EOF (§7.2.3; the RAG's
440    /// gotcha: a `%` as the file's last byte terminates at EOF). The
441    /// comment's terminating EOL is consumed here too — as white-space,
442    /// which it is.
443    fn skip_ws_and_comments(&mut self) {
444        while let Some(b) = self.peek() {
445            if is_whitespace(b) {
446                self.bump();
447            } else if b == b'%' {
448                self.bump();
449                while let Some(c) = self.peek() {
450                    if c == b'\r' || c == b'\n' {
451                        break;
452                    }
453                    self.bump();
454                }
455            } else {
456                break;
457            }
458        }
459    }
460
461    // -- literal strings (§7.3.4.2) -----------------------------------------
462
463    /// Decode a literal string body. Entered with the opening `(`
464    /// already consumed; consumes through the balancing `)`.
465    ///
466    /// Rules applied (each from `iso32000__s__7.3.4.md`):
467    /// - balanced parens nest without escapes → depth tracking;
468    /// - Table 3 escapes; unknown escape drops the backslash (`\q`→`q`);
469    /// - `\ddd` octal, 1–3 digits, high-order overflow ignored (low 8
470    ///   bits); `\8`/`\9` are NOT octal — they hit the unknown-escape
471    ///   rule;
472    /// - `\` + EOL = line continuation, both dropped (CRLF is one EOL);
473    /// - bare EOL (CR, LF, or CRLF) decodes to a single 0Ah.
474    fn scan_literal_string_body(&mut self) -> Result<Vec<u8>, LexError> {
475        let mut out = Vec::new();
476        let mut depth: usize = 1;
477        loop {
478            if out.len() > MAX_STRING_LEN {
479                return Err(self.err_here(LexErrorKind::StringTooLong));
480            }
481            let Some(b) = self.peek() else {
482                return Err(self.err_here(LexErrorKind::UnterminatedString));
483            };
484            self.bump();
485            match b {
486                b'(' => {
487                    depth += 1;
488                    out.push(b'(');
489                }
490                b')' => {
491                    depth -= 1;
492                    if depth == 0 {
493                        return Ok(out);
494                    }
495                    out.push(b')');
496                }
497                b'\\' => {
498                    let Some(e) = self.peek() else {
499                        // `\` as the final byte: undefined by spec;
500                        // error per the failure philosophy.
501                        return Err(self.err_here(LexErrorKind::UnterminatedString));
502                    };
503                    match e {
504                        b'n' => {
505                            self.bump();
506                            out.push(0x0A);
507                        }
508                        b'r' => {
509                            self.bump();
510                            out.push(0x0D);
511                        }
512                        b't' => {
513                            self.bump();
514                            out.push(0x09);
515                        }
516                        b'b' => {
517                            self.bump();
518                            out.push(0x08);
519                        }
520                        b'f' => {
521                            self.bump();
522                            out.push(0x0C);
523                        }
524                        b'(' | b')' | b'\\' => {
525                            self.bump();
526                            out.push(e);
527                        }
528                        b'0'..=b'7' => {
529                            // 1–3 octal digits; overflow keeps low 8
530                            // bits (§7.3.4.2: "high-order overflow shall
531                            // be ignored").
532                            let mut value: u32 = 0;
533                            let mut digits = 0;
534                            while digits < 3 {
535                                match self.peek() {
536                                    Some(d @ b'0'..=b'7') => {
537                                        self.bump();
538                                        value = (value << 3) | u32::from(d - b'0');
539                                        digits += 1;
540                                    }
541                                    _ => break,
542                                }
543                            }
544                            #[allow(clippy::cast_possible_truncation)] // low 8 bits: spec rule
545                            out.push((value & 0xFF) as u8);
546                        }
547                        b'\r' => {
548                            // Line continuation; CRLF is ONE EOL marker
549                            // (§7.2.2), so both bytes are disregarded.
550                            self.bump();
551                            if self.peek() == Some(b'\n') {
552                                self.bump();
553                            }
554                        }
555                        b'\n' => {
556                            self.bump();
557                        }
558                        _ => {
559                            // Unknown escape: backslash ignored, the
560                            // character stands (`\q` → `q`; also `\8`,
561                            // `\9`).
562                            self.bump();
563                            out.push(e);
564                        }
565                    }
566                }
567                b'\r' => {
568                    // Bare EOL → single 0Ah, whether CR, LF, or CRLF.
569                    if self.peek() == Some(b'\n') {
570                        self.bump();
571                    }
572                    out.push(0x0A);
573                }
574                _ => out.push(b),
575            }
576        }
577    }
578
579    // -- hexadecimal strings (§7.3.4.3) -------------------------------------
580
581    /// Decode a hex string body. Entered with the opening `<` consumed;
582    /// consumes through the closing `>`. White-space between digits is
583    /// ignored; an odd final digit is padded with `0` (`<901FA>` →
584    /// `90 1F A0`); any other byte is a syntax error.
585    fn scan_hex_string_body(&mut self) -> Result<Vec<u8>, LexError> {
586        let mut out = Vec::new();
587        let mut pending: Option<u8> = None;
588        loop {
589            if out.len() > MAX_STRING_LEN {
590                return Err(self.err_here(LexErrorKind::StringTooLong));
591            }
592            let Some(b) = self.peek() else {
593                return Err(self.err_here(LexErrorKind::UnterminatedHexString));
594            };
595            if b == b'>' {
596                self.bump();
597                if let Some(hi) = pending {
598                    // Odd digit count: final digit assumed followed by 0.
599                    out.push(hi << 4);
600                }
601                return Ok(out);
602            }
603            if is_whitespace(b) {
604                self.bump();
605                continue;
606            }
607            let Some(nibble) = hex_value(b) else {
608                return Err(self.err_here(LexErrorKind::InvalidHexStringByte(b)));
609            };
610            self.bump();
611            match pending.take() {
612                Some(hi) => out.push((hi << 4) | nibble),
613                None => pending = Some(nibble),
614            }
615        }
616    }
617
618    // -- names (§7.3.5) ------------------------------------------------------
619
620    /// Decode a name body. Entered with the introducing `/` consumed
621    /// (the `/` is not part of the name). Ends at the first
622    /// non-regular byte, which is NOT consumed. The empty name (`/`
623    /// alone) is valid and yields an empty vec.
624    ///
625    /// `#XX` escapes decode to the byte XX; `#` not followed by two hex
626    /// digits errors (spec-undefined; Pass 1 strict), `#00` errors (NUL
627    /// excluded from names by definition).
628    fn scan_name_body(&mut self) -> Result<Vec<u8>, LexError> {
629        let mut out = Vec::new();
630        while let Some(b) = self.peek() {
631            if !is_regular(b) {
632                break;
633            }
634            if out.len() > MAX_TOKEN_LEN {
635                return Err(self.err_here(LexErrorKind::TokenTooLong));
636            }
637            self.bump();
638            if b == b'#' {
639                let hi = self.peek().and_then(hex_value);
640                let lo = self.peek_at(1).and_then(hex_value);
641                match (hi, lo) {
642                    (Some(hi), Some(lo)) => {
643                        self.bump();
644                        self.bump();
645                        let decoded = (hi << 4) | lo;
646                        if decoded == 0 {
647                            return Err(self.err_here(LexErrorKind::NulInName));
648                        }
649                        out.push(decoded);
650                    }
651                    _ => return Err(self.err_here(LexErrorKind::MalformedNameEscape)),
652                }
653            } else {
654                out.push(b);
655            }
656        }
657        Ok(out)
658    }
659
660    // -- numbers and keywords (§7.3.3, §7.3.2, §7.8.2) -----------------------
661
662    /// Scan a run of regular characters starting at `start` (first byte
663    /// not yet consumed) and classify it: integer, real, or keyword.
664    ///
665    /// Classification (from §7.3.3's grammar): the run is numeric if it
666    /// consists only of `+`/`-`/digits/`.`, with any sign leading only,
667    /// at most one PERIOD, and at least one digit — `4.`, `-.002`,
668    /// `+17` are all valid (spec EXAMPLEs). Anything else — `true`,
669    /// `obj`, `T*`, but also malformed numeric-looking runs like
670    /// `1.2.3` or a bare `.` — is a [`TokenKind::Keyword`], and the
671    /// *parser* decides whether it is meaningful in context. This keeps
672    /// the lexer total over content-stream operators without a
673    /// hardcoded operator list.
674    fn scan_regular_run(&mut self, start: usize) -> Result<TokenKind, LexError> {
675        while let Some(b) = self.peek() {
676            if !is_regular(b) {
677                break;
678            }
679            if self.pos.saturating_sub(start) > MAX_TOKEN_LEN {
680                return Err(self.err_here(LexErrorKind::TokenTooLong));
681            }
682            self.bump();
683        }
684        let run = self.buf.get(start..self.pos).unwrap_or(&[]);
685
686        Ok(match classify_number(run) {
687            NumberClass::Integer => TokenKind::Integer(parse_i64(run).ok_or(LexError {
688                offset: start,
689                kind: LexErrorKind::IntegerOverflow,
690            })?),
691            NumberClass::Real => {
692                // The validated grammar (sign, digits, one period) is a
693                // strict subset of what `f64: FromStr` accepts, so this
694                // parse cannot fail; the fallback keeps the path
695                // panic-free rather than trusting that reasoning.
696                let text = String::from_utf8_lossy(run);
697                text.parse::<f64>()
698                    .map_or(TokenKind::Keyword, TokenKind::Real)
699            }
700            NumberClass::NotANumber => TokenKind::Keyword,
701        })
702    }
703}
704
705/// Value of an ASCII hex digit, or `None`.
706const fn hex_value(b: u8) -> Option<u8> {
707    match b {
708        b'0'..=b'9' => Some(b - b'0'),
709        b'A'..=b'F' => Some(b - b'A' + 10),
710        b'a'..=b'f' => Some(b - b'a' + 10),
711        _ => None,
712    }
713}
714
715/// Outcome of numeric classification for a regular-character run.
716enum NumberClass {
717    Integer,
718    Real,
719    NotANumber,
720}
721
722/// Classify a regular-character run per §7.3.3's numeric grammar (see
723/// [`Lexer::scan_regular_run`] for the rule statement).
724fn classify_number(run: &[u8]) -> NumberClass {
725    let mut digits = 0usize;
726    let mut periods = 0usize;
727    for (i, &b) in run.iter().enumerate() {
728        match b {
729            b'+' | b'-' if i == 0 => {}
730            b'0'..=b'9' => digits += 1,
731            b'.' => periods += 1,
732            _ => return NumberClass::NotANumber,
733        }
734    }
735    match (digits, periods) {
736        (0, _) => NumberClass::NotANumber, // bare `.`, `+`, `-`
737        (_, 0) => NumberClass::Integer,
738        (_, 1) => NumberClass::Real,
739        _ => NumberClass::NotANumber, // `1.2.3` — parser's problem
740    }
741}
742
743/// Parse a (pre-validated) signed decimal integer run into `i64`,
744/// `None` on overflow.
745fn parse_i64(run: &[u8]) -> Option<i64> {
746    let (neg, digits) = match run.split_first() {
747        Some((b'-', rest)) => (true, rest),
748        Some((b'+', rest)) => (false, rest),
749        _ => (false, run),
750    };
751    let mut value: i64 = 0;
752    for &b in digits {
753        let d = i64::from(b.checked_sub(b'0')?);
754        if d > 9 {
755            return None;
756        }
757        value = value.checked_mul(10)?.checked_add(d)?;
758    }
759    Some(if neg { -value } else { value })
760}