pdfcer_model/parser.rs
1//! # COS object parser (ISO 32000-1 §7.3 object grammar)
2//!
3//! Recursive-descent parser from the token stream (`crate::lexer`) to
4//! the object model (`crate::object`). Spec sources:
5//! `iso32000__s__7.3.md` (grammar), `iso32000__s__7.3.10.md` (indirect
6//! objects, the `N G R` lookahead), `iso32000__s__7.3.8.md` (stream
7//! framing) in the PDF-spec RAG. Clause numbers are ISO 32000-1:2008.
8//!
9//! ## What this layer does and doesn't
10//!
11//! [`Parser`] parses **one syntactic region** — a direct object, or one
12//! complete `N G obj … endobj` indirect-object definition at a known
13//! offset. It does NOT walk cross-reference tables (that's
14//! `crate::xref`), does not resolve references (document layer), and
15//! does not decode stream data (filter layer). The one place it needs
16//! outside help is a stream's `/Length`, which may itself be an
17//! indirect reference (§7.3.10 EXAMPLE 3 sanctions this for single-pass
18//! writers) — the caller supplies a resolver callback for that case,
19//! keeping the parser xref-agnostic.
20//!
21//! ## The `N G R` lookahead (§7.3.10)
22//!
23//! An indirect reference is *three* tokens — `Integer Integer Keyword(R)`
24//! — indistinguishable from two array elements `1 0` followed by more
25//! content until the third token is seen. The parser therefore keeps a
26//! two-token peek buffer: on reading an `Integer`, it peeks up to two
27//! tokens ahead and commits to a reference only when it sees
28//! `Integer` + `R`. (This ambiguity is exactly why §7.8.2 bans indirect
29//! references inside content streams.)
30//!
31//! ## Stream framing rules enforced (§7.3.8.1)
32//!
33//! - The `stream` keyword shall be followed by CRLF or LF alone —
34//! **CR alone is a hard error** (the spec's own NOTE 2 explains the
35//! ambiguity it would create). The RAG calls this "the single
36//! highest-value byte rule in the whole file-structure area."
37//! - Data is exactly `/Length` bytes from the byte after that EOL.
38//! - After the data: optional EOL, then `endstream`, then `endobj`.
39//! Anything else is a `/Length` inconsistency (§7.3.8.2 "an error") —
40//! fail-clean under the default [`StreamLengthPolicy::Strict`].
41//!
42//! ## The one strictness knob: `/Length` vs `endstream`
43//!
44//! The corpus-driven recovery heuristic the point above used to defer is
45//! now here, as an explicit, opt-in [`StreamLengthPolicy`] rather than a
46//! hidden default. Under [`StreamLengthPolicy::RecoverFromEndstream`] an
47//! unusable `/Length` causes the data extent to be re-derived by scanning
48//! for the `endstream` keyword — §7.3.8.2's own definition of `/Length` is
49//! written in terms of that keyword, so it is the other half of the same
50//! normative statement, not a guess. Only [`crate::recover`] and the
51//! recovered branch of [`crate::document::Document::from_bytes`] select it;
52//! the clean load path is byte-for-byte unchanged, which is what keeps the
53//! round-trip invariant (`ARCHITECTURE.md` §5) safe. Every repair is
54//! counted ([`Parser::stream_lengths_recovered`]) and disclosed.
55//!
56//! ## Guards (ARCHITECTURE.md §10 — pdfcer policy, not spec)
57//!
58//! [`MAX_NESTING_DEPTH`] bounds recursion (the spec bounds nothing
59//! here; a `[[[[…` bomb must not overflow the stack).
60
61use crate::lexer::{LexError, Lexer, Token, TokenKind, is_regular};
62use crate::object::{Dict, IndirectObject, Name, ObjId, Object, Provenance, Stream};
63use crate::span::ByteSpan;
64
65/// Maximum container (array/dictionary) nesting depth.
66///
67/// pdfcer policy (ARCHITECTURE.md §10): ISO 32000-1 does not bound
68/// object nesting (Annex C bounds only `q`/`Q` nesting), so the guard
69/// value is ours. 256 is far beyond any legitimate document structure
70/// while keeping worst-case recursion shallow enough for any thread's
71/// stack.
72pub const MAX_NESTING_DEPTH: usize = 256;
73
74/// A structural parse error: what went wrong and where.
75///
76/// C-GOOD-ERR via `thiserror`; offsets are absolute buffer offsets, the
77/// same coordinate system as [`ByteSpan`].
78#[derive(Debug, Clone, PartialEq, thiserror::Error)]
79#[error("parse error at byte {offset}: {kind}")]
80pub struct ParseError {
81 /// Byte offset where the problem was detected.
82 pub offset: usize,
83 /// What was wrong.
84 pub kind: ParseErrorKind,
85}
86
87/// Classification of structural parse errors.
88#[derive(Debug, Clone, PartialEq, thiserror::Error)]
89#[non_exhaustive]
90pub enum ParseErrorKind {
91 /// The lexer failed underneath the parser.
92 #[error("lexical error: {0}")]
93 Lex(#[from] LexError),
94 /// Input ended where an object (or more of one) was required.
95 #[error("unexpected end of input")]
96 UnexpectedEof,
97 /// A token that cannot begin/continue the construct being parsed.
98 /// The payload is a static description of what was expected.
99 #[error("unexpected token; expected {0}")]
100 Unexpected(&'static str),
101 /// Dictionary key position held a non-name object (§7.3.7 "key
102 /// shall be a name").
103 #[error("dictionary key is not a name")]
104 DictKeyNotName,
105 /// The same key appeared twice in one dictionary (§7.3.7).
106 ///
107 /// # What the standard actually says, sourced (`Pass 283.0`)
108 ///
109 /// §7.3.7 body text, its own sentence and **not** a NOTE, identical in
110 /// ISO 32000-1 and ISO 32000-2: *"Multiple entries in the same dictionary
111 /// shall not have the same key."* (Adobe's PDF Reference 1.7 phrased it as
112 /// a `should` inside a `Note:`; the PDF Association records the change as
113 /// stylistic — the two *"have the same technical meaning"*.)
114 ///
115 /// **It is a `shall not` and it binds the FILE, not the reader.** §2.1
116 /// makes conformance a property of files, §2.3 passes it to writers, and
117 /// clause 1 excludes *"methods for validating the conformance of PDF files
118 /// or readers"* outright. A duplicate-key file is not a conforming file,
119 /// so ISO 32000 **neither obliges pdfcer to render it nor obliges pdfcer
120 /// to refuse it**. ISO 32000-2 §6.3 retires the term outright: *"the
121 /// notion of a 'conforming reader' is not useful for this document."*
122 ///
123 /// Reader behaviour for the malformed case is **not merely unstated but
124 /// acknowledged as out of scope** — `pdf-issues` #199, open since 2022:
125 /// *"as soon as a PDF violates a mandated 'shall' requirement (such as 2
126 /// keys in a dictionary with the same name) then how that PDF is to be
127 /// interpreted is beyond the scope of ISO 32000."*
128 ///
129 /// ⇒ Which is why the winner is a **policy** pdfcer picks and discloses
130 /// ([`DuplicateKeyPolicy`]) rather than a rule it obeys. This error is
131 /// what [`DuplicateKeyPolicy::Refuse`] produces, and that policy is no
132 /// longer the document loader's default: refusing the whole document over
133 /// one entry is the strict reading **plus two unstated escalations** —
134 /// dictionary to object, object to document — neither of which §7.3.7
135 /// authorises.
136 #[error("duplicate dictionary key")]
137 DuplicateDictKey,
138 /// Container nesting exceeded [`MAX_NESTING_DEPTH`] (pdfcer guard).
139 #[error("nesting exceeds MAX_NESTING_DEPTH ({MAX_NESTING_DEPTH})")]
140 DepthExceeded,
141 /// An indirect-object header wasn't `N G obj` with valid numbers
142 /// (N positive, G in 0..=65535 — §7.3.10/§7.5.4 ranges).
143 #[error("malformed indirect-object header")]
144 BadObjectHeader,
145 /// `endobj` missing after the object body.
146 #[error("missing endobj")]
147 MissingEndobj,
148 /// `stream` keyword not directly preceded by a dictionary
149 /// (§7.3.8.1 — a stream is a dictionary plus data).
150 #[error("stream keyword without preceding dictionary")]
151 StreamWithoutDict,
152 /// The byte(s) after the `stream` keyword violate §7.3.8.1: must
153 /// be CRLF or LF alone, never CR alone, never anything else.
154 #[error("stream keyword not followed by CRLF or LF (CR alone is forbidden by \u{a7}7.3.8.1)")]
155 BadStreamEol,
156 /// `/Length` missing, non-integer, negative, or (when indirect)
157 /// unresolvable via the caller's resolver.
158 #[error("stream /Length missing, invalid, or unresolvable")]
159 BadStreamLength,
160 /// The `/Length`-delimited data region was not followed by
161 /// (optional EOL +) `endstream` — the file's `/Length` is
162 /// inconsistent (§7.3.8.2).
163 #[error("endstream not found where /Length points (stream extent inconsistent)")]
164 StreamExtentMismatch,
165}
166
167impl ParseError {
168 const fn new(offset: usize, kind: ParseErrorKind) -> Self {
169 Self { offset, kind }
170 }
171}
172
173impl From<LexError> for ParseError {
174 fn from(e: LexError) -> Self {
175 Self {
176 offset: e.offset,
177 kind: ParseErrorKind::Lex(e),
178 }
179 }
180}
181
182/// Resolver for indirect `/Length` values (§7.3.10 EXAMPLE 3 pattern).
183///
184/// Given the referenced id, return the integer value of that object, or
185/// `None` if it cannot be resolved / is not an integer. The document
186/// layer implements this against the xref table; tests implement it
187/// with a closure over a map. Kept as a trait alias-like type for
188/// signature clarity.
189pub type LengthResolver<'r> = &'r mut dyn FnMut(ObjId) -> Option<i64>;
190
191/// How a stream whose `/Length` disagrees with the file should be handled.
192///
193/// This is the one deliberate strictness knob on the parser, and it exists
194/// because §7.3.8.2's own definition of `/Length` is phrased in terms of
195/// the `endstream` keyword: the value "shall be the number of bytes from
196/// the beginning of the line following the keyword `stream` to the last
197/// byte just before the keyword `endstream`". When the stored number and
198/// the keyword disagree, the file contains **two** statements of the same
199/// fact and one of them is wrong. Which one a reader believes is a policy
200/// choice, not a spec choice — so pdfcer makes it an explicit parameter
201/// rather than a hidden default.
202///
203/// **The default is and must stay [`StreamLengthPolicy::Strict`]**: on a
204/// cleanly-loading file the stored `/Length` is authoritative, a
205/// disagreement is real damage the operator should hear about (§7.3.8.2
206/// calls it "an error"), and silently re-deriving extents would put a
207/// guessed span into the writer's byte-identical re-emission path and
208/// break the round-trip/minimal-diff invariant (`ARCHITECTURE.md` §5).
209///
210/// [`StreamLengthPolicy::RecoverFromEndstream`] is reachable **only** from
211/// the rebuild-by-scan recovery path ([`crate::recover`] and the recovered
212/// branch of [`crate::document::Document::from_bytes`]), where the file's
213/// cross-reference machinery has already been proven unparseable, no
214/// byte-identical re-emission is on the table (a recovered document
215/// refuses incremental save and always normalizes), and refusing an object
216/// costs the operator the whole document.
217#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
218#[non_exhaustive]
219pub enum StreamLengthPolicy {
220 /// Believe `/Length`. A disagreement with `endstream` is
221 /// [`ParseErrorKind::StreamExtentMismatch`]; a missing/invalid
222 /// `/Length` is [`ParseErrorKind::BadStreamLength`]. The default, and
223 /// the only policy the clean load path ever uses.
224 #[default]
225 Strict,
226 /// Believe `endstream`. When (and only when) the stored `/Length`
227 /// cannot be used — absent, non-integer, unresolvable, past the end of
228 /// the buffer, or simply not landing on `endstream` — re-derive the
229 /// data extent by scanning forward from the start of the data for the
230 /// `endstream` keyword, then backing off the one end-of-line marker
231 /// §7.3.8.1 says "should" precede it. Every such repair is counted in
232 /// [`Parser::stream_lengths_recovered`] so it can be disclosed (R20,
233 /// fuzzy-never-sneaky) rather than silently absorbed.
234 RecoverFromEndstream,
235}
236
237/// One duplicate-key decision: the key, the value kept, the value discarded
238/// (`Pass 283.0`).
239///
240/// Both values travel because a shell offering the operator the alternative
241/// has to be able to show it. See [`crate::document::LoadAnomaly`].
242#[derive(Debug, Clone, PartialEq)]
243pub struct DuplicateKeyRecord {
244 /// The repeated key, without its leading solidus — `PageMode`.
245 pub key: Vec<u8>,
246 /// The value pdfcer kept, under the policy in force.
247 pub kept: Object,
248 /// The value pdfcer discarded.
249 pub discarded: Object,
250}
251
252/// What to do when one dictionary names the same key twice (§7.3.7).
253///
254/// # The file that forced this, and why the strict answer was too expensive
255///
256/// An operator's 46 KB drawing opens in Acrobat and was **refused whole** by
257/// pdfcer: its document catalog carries `/PageMode` twice, with **different
258/// values** —
259///
260/// ```text
261/// … /PageMode /UseOC /PageLayout /SinglePage /PageLabels << … >>
262/// /PageMode /UseOutlines /Outlines 58 0 R /Metadata 59 0 R >>
263/// ```
264///
265/// One repeated key in one object cost the whole document, on a file every
266/// other reader opens without comment. That is the wrong trade for a malformed
267/// **entry** in an otherwise sound file: pdfcer's fail-clean posture is about
268/// never silently doing the wrong thing, and a counted, disclosed choice is
269/// not silent.
270///
271/// # Why this is a POLICY and not simply a relaxation
272///
273/// The spec's own rule and pdfcer's obligation are different questions. The
274/// rule is recorded at [`ParseErrorKind::DuplicateDictKey`]; what a reader may
275/// do about a violation is not stated, which makes the winner **pdfcer's
276/// choice to make and to disclose** — this project's standing shape for a spec
277/// ambiguity (a setting, a documented default, never a silent decision).
278///
279/// [`Self::Refuse`] stays the type's `Default` so every caller that did not
280/// ask — fuzz targets, the recovery confirmation pass, any future one — keeps
281/// the strict behaviour it was written against. The **document loader** opts
282/// in; the parser does not opt in for it.
283#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
284#[non_exhaustive]
285pub enum DuplicateKeyPolicy {
286 /// Refuse the object with [`ParseErrorKind::DuplicateDictKey`].
287 ///
288 /// The default, and the right answer for a caller whose job is to decide
289 /// whether a file is well-formed rather than to open it.
290 #[default]
291 Refuse,
292 /// Keep the **last** occurrence, and count it.
293 ///
294 /// # Why last rather than first
295 ///
296 /// Nothing in the standard prescribes either — see
297 /// [`ParseErrorKind::DuplicateDictKey`] for the sourcing — so this is
298 /// pdfcer's choice, and it is made on **observed reader behaviour**:
299 /// `qpdf`, `pdf.js` and `pdfium` all keep the last occurrence, and none of
300 /// the three refuses the file. `qpdf` even says so out loud — *"dictionary
301 /// has duplicated key `<key>`; last occurrence overrides earlier ones"* —
302 /// which is the same disclosure pdfcer now makes.
303 ///
304 /// **CORRECTED BEFORE SHIPPING.** This paragraph first argued from
305 /// §7.5.6 — *"every other override-by-repetition in PDF is last-wins; an
306 /// incremental update's newer definition supersedes the older one"* — and
307 /// that is an **analogy dressed as a citation**. §7.5.6 orders objects
308 /// across incremental updates, an ordering the standard deliberately makes
309 /// meaningful; §7.3.7's own preceding sentence says the ordering of a
310 /// dictionary's entries **"shall be ignored"**. Citing it here would have
311 /// borrowed authority from a clause that says the opposite thing about
312 /// this exact structure.
313 ///
314 /// The distinction is not pedantry: ISO's one resolved duplicate-key
315 /// erratum (#3, inline images) picked the winner by **content**, and its
316 /// submission rejected first/last positional logic **by name**, for
317 /// precisely that reason.
318 ///
319 /// The alternative is defensible and is not silently unavailable: a
320 /// caller wanting the first value has [`Self::KeepFirst`], and every
321 /// decision is recorded with BOTH values so a shell can offer the operator
322 /// the swap. What is NOT on offer is pdfcer choosing quietly.
323 KeepLast,
324 /// Keep the **first** occurrence, and count it.
325 ///
326 /// The other half of the operator's choice. A shell that shows *"this file
327 /// names `/PageMode` twice — `UseOC` or `UseOutlines`?"* re-loads under
328 /// this policy when the operator picks the earlier value; nothing else in
329 /// the document changes.
330 ///
331 /// Not the default only because [`Self::KeepLast`] matches every other
332 /// override-by-repetition in PDF; on the evidence available neither is
333 /// wrong, which is exactly why both ship.
334 KeepFirst,
335}
336
337/// What to do when an indirect object's `endobj` keyword is missing.
338///
339/// §7.3.10 requires a definition to be `N G obj … endobj`, so a body that
340/// runs straight into the next `N G obj` header is malformed. But the
341/// object *itself* may have parsed perfectly — the damage is a missing
342/// four-byte keyword, not a corrupt value — and refusing it costs the
343/// operator the whole object.
344///
345/// **The default is and must stay [`TerminatorPolicy::Strict`]**, for the
346/// same reason [`StreamLengthPolicy::Strict`] is: on a cleanly-loading
347/// file a missing `endobj` is real damage the operator should hear about,
348/// and accepting it would put an inferred extent into the writer's
349/// byte-identical re-emission path and break the round-trip/minimal-diff
350/// invariant (`ARCHITECTURE.md` §5).
351///
352/// # Why the lenient policy exists
353///
354/// It was added 2026-08-07 after the veraPDF parse gate found pdfcer
355/// writing a document whose catalog said `/Pages 2 0 R` while object 2
356/// was **absent from the file**. The input (qpdf's `bad6.pdf`) omits
357/// exactly one `endobj` — the one after the `/Pages` node — so
358/// `confirm_candidates` dropped the object as unparseable and the writer
359/// emitted a catalog pointing at nothing. veraPDF could recover the
360/// original and could not recover pdfcer's rewrite of it, which is a
361/// document made strictly worse by passing through pdfcer.
362///
363/// Like [`StreamLengthPolicy::RecoverFromEndstream`], this is reachable
364/// **only** from the rebuild-by-scan recovery path, where the file's
365/// cross-reference machinery has already been proven unparseable and no
366/// byte-identical re-emission is on the table.
367#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
368#[non_exhaustive]
369pub enum TerminatorPolicy {
370 /// A missing `endobj` is [`ParseErrorKind::MissingEndobj`]. The
371 /// default, and the only policy the clean load path ever uses.
372 #[default]
373 Strict,
374 /// Accept a definition whose body parsed cleanly but whose `endobj` is
375 /// missing, **provided the terminator looks like the start of the next
376 /// object header** (an integer) or the buffer ended.
377 ///
378 /// The integer guard is what keeps this from swallowing arbitrary
379 /// garbage: `2 0 obj << … >> 3 0 obj` recovers, while a body followed
380 /// by an unexpected keyword still fails. Every such repair is counted
381 /// in [`Parser::missing_endobj_recovered`] so it can be disclosed
382 /// (R20, fuzzy-never-sneaky) rather than silently absorbed.
383 RecoverAtNextHeader,
384}
385
386/// Recursive-descent parser over a byte buffer.
387///
388/// Create positioned at an offset ([`Parser::at`]) and call one of the
389/// top-level entry points ([`Parser::parse_object`],
390/// [`Parser::parse_indirect_object`]). The parser owns a lexer plus a
391/// two-token peek buffer (see module docs on the `N G R` lookahead).
392#[derive(Debug)]
393pub struct Parser<'a> {
394 buf: &'a [u8],
395 lexer: Lexer<'a>,
396 /// Peeked-but-unconsumed tokens, oldest first (max 2 in practice).
397 peeked: Vec<Token>,
398 /// Strictness for the `/Length`-vs-`endstream` disagreement. Strict
399 /// unless a caller opted in via [`Parser::with_stream_length_policy`].
400 stream_length_policy: StreamLengthPolicy,
401 /// How many streams this parser re-derived an extent for. Only ever
402 /// non-zero under [`StreamLengthPolicy::RecoverFromEndstream`].
403 stream_lengths_recovered: usize,
404 /// Strictness for a missing `endobj`. Strict unless a caller opted in
405 /// via [`Parser::with_terminator_policy`].
406 terminator_policy: TerminatorPolicy,
407 /// How many definitions this parser accepted without an `endobj`. Only
408 /// ever non-zero under [`TerminatorPolicy::RecoverAtNextHeader`].
409 missing_endobj_recovered: usize,
410 /// Strictness for a dictionary that names one key twice (§7.3.7). Strict
411 /// unless a caller opted in via [`Parser::with_duplicate_key_policy`].
412 duplicate_key_policy: DuplicateKeyPolicy,
413 /// Every duplicate key this parser resolved rather than refused, with
414 /// BOTH values.
415 ///
416 /// A list, not a count, and that is the operator ruling: *"if the user
417 /// can intervene in a decision that should always be an option"*. A count
418 /// says pdfcer chose; only the pair says what it chose BETWEEN, which is
419 /// what a shell needs to offer the swap.
420 duplicate_keys: Vec<DuplicateKeyRecord>,
421}
422
423impl<'a> Parser<'a> {
424 /// Parser over `buf` starting at absolute offset `pos`.
425 #[must_use]
426 pub const fn at(buf: &'a [u8], pos: usize) -> Self {
427 Self {
428 buf,
429 lexer: Lexer::at(buf, pos),
430 peeked: Vec::new(),
431 stream_length_policy: StreamLengthPolicy::Strict,
432 stream_lengths_recovered: 0,
433 terminator_policy: TerminatorPolicy::Strict,
434 missing_endobj_recovered: 0,
435 duplicate_key_policy: DuplicateKeyPolicy::Refuse,
436 duplicate_keys: Vec::new(),
437 }
438 }
439
440 /// Set the `/Length`-disagreement policy (builder form).
441 ///
442 /// See [`StreamLengthPolicy`] for why the non-default value is
443 /// restricted to the recovery path.
444 #[must_use]
445 pub const fn with_stream_length_policy(mut self, policy: StreamLengthPolicy) -> Self {
446 self.stream_length_policy = policy;
447 self
448 }
449
450 /// How many stream extents this parser re-derived from `endstream`
451 /// because the stored `/Length` was unusable.
452 ///
453 /// Always `0` under [`StreamLengthPolicy::Strict`] (that policy errors
454 /// instead of repairing), so a non-zero value is proof that the file
455 /// disagreed with itself. Callers propagate it into the counted
456 /// disclosure a front end shows the operator.
457 #[must_use]
458 pub const fn stream_lengths_recovered(&self) -> usize {
459 self.stream_lengths_recovered
460 }
461
462 /// Set the missing-`endobj` policy (builder form).
463 ///
464 /// See [`TerminatorPolicy`] for why the non-default value is
465 /// restricted to the recovery path.
466 #[must_use]
467 pub const fn with_terminator_policy(mut self, policy: TerminatorPolicy) -> Self {
468 self.terminator_policy = policy;
469 self
470 }
471
472 /// How many definitions this parser accepted with no `endobj`.
473 ///
474 /// Always `0` under [`TerminatorPolicy::Strict`], so a non-zero value
475 /// is proof the file omitted a required keyword. Callers propagate it
476 /// into the counted disclosure a front end shows the operator.
477 #[must_use]
478 pub const fn missing_endobj_recovered(&self) -> usize {
479 self.missing_endobj_recovered
480 }
481
482 /// Choose what happens when a dictionary names one key twice (§7.3.7).
483 ///
484 /// [`DuplicateKeyPolicy::Refuse`] unless a caller asks otherwise — see
485 /// that type for why the document loader opts in and the parser does not
486 /// opt in for it.
487 #[must_use]
488 pub const fn with_duplicate_key_policy(mut self, policy: DuplicateKeyPolicy) -> Self {
489 self.duplicate_key_policy = policy;
490 self
491 }
492
493 /// How many duplicate dictionary keys this parser resolved instead of
494 /// refusing.
495 ///
496 /// Always `0` under [`DuplicateKeyPolicy::Refuse`], so a non-zero value is
497 /// proof the file contradicted itself — which is why it is carried out to
498 /// the operator rather than absorbed (R20, fuzzy-never-sneaky). The value
499 /// pdfcer kept is the LAST one; the earlier one is gone from the loaded
500 /// document and would not survive a save.
501 #[must_use]
502 pub fn duplicate_keys_resolved(&self) -> usize {
503 self.duplicate_keys.len()
504 }
505
506 /// Every duplicate key this parser resolved, with the value kept and the
507 /// value discarded.
508 ///
509 /// Empty under [`DuplicateKeyPolicy::Refuse`]. The caller tags each with
510 /// the object it came from and carries it out as a
511 /// [`crate::document::LoadAnomaly`], which is what makes the operator's
512 /// choice offerable rather than theoretical.
513 #[must_use]
514 pub fn duplicate_keys(&self) -> &[DuplicateKeyRecord] {
515 &self.duplicate_keys
516 }
517
518 /// Current absolute offset for diagnostics: the start of the oldest
519 /// unconsumed peeked token, or the lexer cursor.
520 fn offset(&self) -> usize {
521 self.peeked
522 .first()
523 .map_or_else(|| self.lexer.pos(), |t| t.span.start)
524 }
525
526 /// Next token, consuming.
527 fn next(&mut self) -> Result<Option<Token>, ParseError> {
528 if self.peeked.is_empty() {
529 Ok(self.lexer.next_token()?)
530 } else {
531 Ok(Some(self.peeked.remove(0)))
532 }
533 }
534
535 /// Peek the `n`-th upcoming token (0-based) without consuming.
536 fn peek(&mut self, n: usize) -> Result<Option<&Token>, ParseError> {
537 while self.peeked.len() <= n {
538 match self.lexer.next_token()? {
539 Some(t) => self.peeked.push(t),
540 None => break,
541 }
542 }
543 Ok(self.peeked.get(n))
544 }
545
546 /// Next token or `UnexpectedEof`.
547 fn expect_any(&mut self) -> Result<Token, ParseError> {
548 let off = self.offset();
549 self.next()?
550 .ok_or(ParseError::new(off, ParseErrorKind::UnexpectedEof))
551 }
552
553 /// Is `tok` the keyword whose lexeme is `word`? (Keywords carry no
554 /// copied bytes — the span against the buffer is the value; see
555 /// `lexer::TokenKind::Keyword`.)
556 fn is_keyword(&self, tok: &Token, word: &[u8]) -> bool {
557 matches!(tok.kind, TokenKind::Keyword) && tok.lexeme(self.buf) == Some(word)
558 }
559
560 // -----------------------------------------------------------------------
561 // Direct objects
562 // -----------------------------------------------------------------------
563
564 /// Parse one direct object (any §7.3 value, including `N G R`
565 /// references). This is the entry point for trailer dictionaries
566 /// and other bare-value positions.
567 ///
568 /// # Errors
569 ///
570 /// [`ParseError`] on malformed syntax — see [`ParseErrorKind`].
571 pub fn parse_object(&mut self) -> Result<Object, ParseError> {
572 self.parse_value(0)
573 }
574
575 /// Core value parser. `depth` counts container nesting for the
576 /// [`MAX_NESTING_DEPTH`] guard.
577 fn parse_value(&mut self, depth: usize) -> Result<Object, ParseError> {
578 if depth > MAX_NESTING_DEPTH {
579 return Err(ParseError::new(
580 self.offset(),
581 ParseErrorKind::DepthExceeded,
582 ));
583 }
584 let tok = self.expect_any()?;
585 match tok.kind {
586 TokenKind::Integer(v) => self.maybe_reference(v, &tok),
587 TokenKind::Real(v) => Ok(Object::Real(v)),
588 TokenKind::String(s) => Ok(Object::String(s)),
589 TokenKind::Name(n) => Ok(Object::Name(Name(n))),
590 TokenKind::ArrayOpen => self.parse_array_body(depth),
591 TokenKind::DictOpen => Ok(Object::Dict(self.parse_dict_body(depth)?)),
592 TokenKind::Keyword => {
593 let lexeme = tok.lexeme(self.buf).unwrap_or(&[]);
594 match lexeme {
595 b"true" => Ok(Object::Boolean(true)),
596 b"false" => Ok(Object::Boolean(false)),
597 b"null" => Ok(Object::Null),
598 _ => Err(ParseError::new(
599 tok.span.start,
600 ParseErrorKind::Unexpected("an object"),
601 )),
602 }
603 }
604 // Closers/braces at value position are structural errors at
605 // this level; the container parsers consume their own
606 // closers before recursing.
607 _ => Err(ParseError::new(
608 tok.span.start,
609 ParseErrorKind::Unexpected("an object"),
610 )),
611 }
612 }
613
614 /// After an `Integer`, decide reference vs plain integer via the
615 /// two-token lookahead (module docs): `Integer Integer R` → a
616 /// [`Object::Reference`], anything else → the integer stands alone.
617 ///
618 /// The reference's numbers must be in range (§7.3.10: object number
619 /// positive; §7.5.4: generation ≤ 65,535) — out-of-range values
620 /// mean the three tokens were NOT a reference after all, and since
621 /// bare keyword `R` can't otherwise appear at value position, that
622 /// is a structural error surfaced when the parser reaches it.
623 fn maybe_reference(&mut self, value: i64, tok: &Token) -> Result<Object, ParseError> {
624 // Copy out (kind-class, span) pairs so no peek borrow is held
625 // while the buffer is sliced for the `R` check.
626 let t1_is_int = self
627 .peek(0)?
628 .is_some_and(|t| matches!(t.kind, TokenKind::Integer(_)));
629 let looks_like_ref = t1_is_int && {
630 let t2 = self
631 .peek(1)?
632 .map(|t| (matches!(t.kind, TokenKind::Keyword), t.span));
633 match t2 {
634 Some((true, span)) => span.slice(self.buf) == Some(b"R"),
635 _ => false,
636 }
637 };
638 if !looks_like_ref {
639 return Ok(Object::Integer(value));
640 }
641 // Commit: consume `gen` and `R`.
642 let gen_tok = self.expect_any()?;
643 let TokenKind::Integer(gen_value) = gen_tok.kind else {
644 // Unreachable by construction of the lookahead; kept as a
645 // structured error per the panic-free policy.
646 return Err(ParseError::new(
647 gen_tok.span.start,
648 ParseErrorKind::Unexpected("generation number"),
649 ));
650 };
651 self.expect_any()?; // the `R`, verified by the lookahead
652
653 let (Ok(num), Ok(generation)) = (u32::try_from(value), u16::try_from(gen_value)) else {
654 return Err(ParseError::new(
655 tok.span.start,
656 ParseErrorKind::Unexpected("reference numbers in range"),
657 ));
658 };
659 if num == 0 {
660 // Object number 0 is reserved for the free-list head
661 // (§7.5.4); it never identifies a real object.
662 return Err(ParseError::new(
663 tok.span.start,
664 ParseErrorKind::Unexpected("positive object number"),
665 ));
666 }
667 Ok(Object::Reference(ObjId::new(num, generation)))
668 }
669
670 /// Parse array elements after `[`, through the matching `]`.
671 fn parse_array_body(&mut self, depth: usize) -> Result<Object, ParseError> {
672 let mut items = Vec::new();
673 loop {
674 match self.peek(0)? {
675 None => {
676 return Err(ParseError::new(
677 self.offset(),
678 ParseErrorKind::UnexpectedEof,
679 ));
680 }
681 Some(t) if matches!(t.kind, TokenKind::ArrayClose) => {
682 self.next()?;
683 return Ok(Object::Array(items));
684 }
685 Some(_) => items.push(self.parse_value(depth + 1)?),
686 }
687 }
688 }
689
690 /// Parse dictionary entries after `<<`, through the matching `>>`.
691 ///
692 /// Enforces §7.3.7: keys are names; duplicate keys are malformed
693 /// (spec: "shall not have the same key"; reader behaviour
694 /// undefined → Pass 1 strict, real-world tolerance only with
695 /// corpus evidence, per the module's failure philosophy).
696 fn parse_dict_body(&mut self, depth: usize) -> Result<Dict, ParseError> {
697 let mut dict = Dict::new();
698 loop {
699 let tok = self.expect_any()?;
700 match tok.kind {
701 TokenKind::DictClose => return Ok(dict),
702 TokenKind::Name(key) => {
703 let existing = dict.0.iter().position(|(k, _)| k.as_bytes() == key);
704 if existing.is_some() && self.duplicate_key_policy == DuplicateKeyPolicy::Refuse
705 {
706 return Err(ParseError::new(
707 tok.span.start,
708 ParseErrorKind::DuplicateDictKey,
709 ));
710 }
711 // The value is parsed either way: a duplicate key's value
712 // still occupies bytes, and skipping the parse would leave
713 // the token stream pointing into the middle of it.
714 let value = self.parse_value(depth + 1)?;
715 match existing
716 .filter(|_| self.duplicate_key_policy != DuplicateKeyPolicy::KeepFirst)
717 {
718 // REPLACED IN PLACE, not pushed and shadowed. `Dict`
719 // is an ordered Vec whose lookup takes the FIRST match,
720 // so appending a second entry would keep the earlier
721 // value winning while the later one sat in the file's
722 // serialisation — a document that reads one way and
723 // round-trips another. Overwriting the slot keeps the
724 // key in its original position, which is also what a
725 // minimal-diff re-emission wants.
726 Some(at) => {
727 if let Some(slot) = dict.0.get_mut(at) {
728 self.duplicate_keys.push(DuplicateKeyRecord {
729 key: key.clone(),
730 kept: value.clone(),
731 discarded: std::mem::replace(&mut slot.1, value),
732 });
733 }
734 }
735 // Either a first occurrence (push it) or a later one
736 // under `KeepFirst` (drop it on the floor — the value
737 // was still parsed, because its bytes are in the way
738 // either way).
739 None => {
740 if let Some(at) = existing {
741 self.duplicate_keys.push(DuplicateKeyRecord {
742 key: key.clone(),
743 kept: dict.0.get(at).map_or(Object::Null, |(_, v)| v.clone()),
744 discarded: value,
745 });
746 } else {
747 dict.0.push((Name(key), value));
748 }
749 }
750 }
751 }
752 _ => {
753 return Err(ParseError::new(
754 tok.span.start,
755 ParseErrorKind::DictKeyNotName,
756 ));
757 }
758 }
759 }
760 }
761
762 // -----------------------------------------------------------------------
763 // Indirect objects (§7.3.10) + stream bodies (§7.3.8)
764 // -----------------------------------------------------------------------
765
766 /// Parse one complete indirect-object definition
767 /// (`N G obj <value> endobj`, or the stream form) starting at this
768 /// parser's position — normally an offset taken from the xref
769 /// table.
770 ///
771 /// `resolve_length` is consulted only when a stream's `/Length` is
772 /// an indirect reference (§7.3.10 EXAMPLE 3); pass a closure over
773 /// the xref/document (or `&mut |_| None` where indirect lengths
774 /// are illegal, e.g. xref-stream bootstrap — §7.5.8.2's directness
775 /// rules).
776 ///
777 /// # Errors
778 ///
779 /// [`ParseError`] on malformed structure — see [`ParseErrorKind`].
780 pub fn parse_indirect_object(
781 &mut self,
782 resolve_length: LengthResolver<'_>,
783 ) -> Result<IndirectObject, ParseError> {
784 // --- header: N G obj ---
785 let num_tok = self.expect_any()?;
786 let TokenKind::Integer(num) = num_tok.kind else {
787 return Err(ParseError::new(
788 num_tok.span.start,
789 ParseErrorKind::BadObjectHeader,
790 ));
791 };
792 let gen_tok = self.expect_any()?;
793 let TokenKind::Integer(gen_value) = gen_tok.kind else {
794 return Err(ParseError::new(
795 gen_tok.span.start,
796 ParseErrorKind::BadObjectHeader,
797 ));
798 };
799 let obj_tok = self.expect_any()?;
800 if !self.is_keyword(&obj_tok, b"obj") {
801 return Err(ParseError::new(
802 obj_tok.span.start,
803 ParseErrorKind::BadObjectHeader,
804 ));
805 }
806 let (Ok(num), Ok(generation)) = (u32::try_from(num), u16::try_from(gen_value)) else {
807 return Err(ParseError::new(
808 num_tok.span.start,
809 ParseErrorKind::BadObjectHeader,
810 ));
811 };
812 if num == 0 {
813 return Err(ParseError::new(
814 num_tok.span.start,
815 ParseErrorKind::BadObjectHeader,
816 ));
817 }
818 let id = ObjId::new(num, generation);
819
820 // --- body ---
821 let value = self.parse_value(0)?;
822
823 // --- terminator: endobj, or stream … endstream endobj ---
824 let term = self.expect_any()?;
825 if self.is_keyword(&term, b"endobj") {
826 return Ok(IndirectObject {
827 id,
828 value,
829 provenance: Provenance::File(ByteSpan::from_range(
830 num_tok.span.start..term.span.end(),
831 )),
832 });
833 }
834 if self.is_keyword(&term, b"stream") {
835 let Object::Dict(dict) = value else {
836 return Err(ParseError::new(
837 term.span.start,
838 ParseErrorKind::StreamWithoutDict,
839 ));
840 };
841 let before = self.stream_lengths_recovered;
842 let stream = self.parse_stream_tail(dict, &term, resolve_length)?;
843 let end_tok = self.expect_any()?;
844 if !self.is_keyword(&end_tok, b"endobj") {
845 return Err(ParseError::new(
846 end_tok.span.start,
847 ParseErrorKind::MissingEndobj,
848 ));
849 }
850 let span = ByteSpan::from_range(num_tok.span.start..end_tok.span.end());
851 // If this object's extent had to be re-derived, its source
852 // bytes now contradict its parsed value: the bytes still carry
853 // the old `/Length` while the value carries the recovered one.
854 // Mark the provenance so the writer re-serializes rather than
855 // copying the contradiction into a saved file (which would
856 // produce a document pdfcer could not reload). See
857 // `Provenance::RecoveredFile`.
858 let provenance = if self.stream_lengths_recovered > before {
859 Provenance::RecoveredFile(span)
860 } else {
861 Provenance::File(span)
862 };
863 return Ok(IndirectObject {
864 id,
865 value: Object::Stream(stream),
866 provenance,
867 });
868 }
869 // --- no terminator: policy decides -------------------------------
870 //
871 // Under RecoverAtNextHeader, a body that parsed cleanly and is
872 // followed by what looks like the next object header is accepted.
873 // The integer guard matters: `2 0 obj << … >> 3 0 obj` recovers,
874 // while a body followed by an unexpected keyword still fails, so
875 // this cannot swallow arbitrary trailing garbage.
876 //
877 // The provenance is RecoveredFile, NOT File, and that is
878 // load-bearing rather than cosmetic. These source bytes do not
879 // contain an `endobj`, so re-emitting them verbatim would copy the
880 // malformation into the saved file and produce a document pdfcer
881 // could not reload — the same trap the stream-length repair above
882 // documents. RecoveredFile forces the writer to re-serialize.
883 if self.terminator_policy == TerminatorPolicy::RecoverAtNextHeader
884 && matches!(term.kind, TokenKind::Integer(_))
885 {
886 self.missing_endobj_recovered += 1;
887 return Ok(IndirectObject {
888 id,
889 value,
890 // Ends where the value ended — `term` is the NEXT object's
891 // first token and must not be claimed by this one.
892 provenance: Provenance::RecoveredFile(ByteSpan::from_range(
893 num_tok.span.start..term.span.start,
894 )),
895 });
896 }
897 Err(ParseError::new(
898 term.span.start,
899 ParseErrorKind::MissingEndobj,
900 ))
901 }
902
903 /// Handle everything after a `stream` keyword: the §7.3.8.1 EOL
904 /// rule, the `/Length`-delimited data span, and the `endstream`
905 /// keyword. Returns with the parser positioned after `endstream`.
906 fn parse_stream_tail(
907 &mut self,
908 dict: Dict,
909 stream_kw: &Token,
910 resolve_length: LengthResolver<'_>,
911 ) -> Result<Stream, ParseError> {
912 // The peek buffer must be empty here: `stream` was just
913 // consumed and stream *data* must not be lexed. (It is empty by
914 // construction — parse_value never leaves lookahead beyond the
915 // value it returned, and the `stream` token itself was taken
916 // with expect_any. debug_assert documents the reasoning.)
917 debug_assert!(self.peeked.is_empty());
918
919 // §7.3.8.1: `stream` followed by CRLF or LF alone; CR alone is
920 // FORBIDDEN. Data begins at the byte after that EOL.
921 let after_kw = stream_kw.span.end();
922 let data_start = match (self.buf.get(after_kw), self.buf.get(after_kw + 1)) {
923 (Some(b'\r'), Some(b'\n')) => after_kw + 2,
924 (Some(b'\n'), _) => after_kw + 1,
925 _ => {
926 return Err(ParseError::new(after_kw, ParseErrorKind::BadStreamEol));
927 }
928 };
929
930 // /Length: required, integer, non-negative; possibly indirect.
931 // Under RecoverFromEndstream an unusable /Length is not fatal — it
932 // simply means the keyword is the only surviving statement of the
933 // extent, so fall straight through to the scan.
934 let stored_length: Option<usize> = match dict.get(b"Length") {
935 Some(Object::Integer(v)) => usize::try_from(*v).ok(),
936 Some(Object::Reference(id)) => {
937 resolve_length(*id).and_then(|v| usize::try_from(v).ok())
938 }
939 _ => None,
940 };
941 let length = match stored_length {
942 Some(length) => length,
943 None => {
944 return self.recover_stream_extent(
945 dict,
946 data_start,
947 ParseError::new(stream_kw.span.start, ParseErrorKind::BadStreamLength),
948 );
949 }
950 };
951
952 let data_end = data_start.saturating_add(length);
953 if data_end > self.buf.len() {
954 return self.recover_stream_extent(
955 dict,
956 data_start,
957 ParseError::new(data_start, ParseErrorKind::StreamExtentMismatch),
958 );
959 }
960
961 // After the data: optional EOL ("should", not counted in
962 // Length), then `endstream`. Re-enter token scanning there —
963 // the lexer's whitespace skipping absorbs the optional EOL.
964 self.lexer = Lexer::at(self.buf, data_end);
965 let end_tok = self.expect_any().map_err(|e| match e.kind {
966 // EOF right after the data reads better as an extent error.
967 ParseErrorKind::UnexpectedEof => {
968 ParseError::new(data_end, ParseErrorKind::StreamExtentMismatch)
969 }
970 _ => e,
971 })?;
972 if !self.is_keyword(&end_tok, b"endstream") {
973 return self.recover_stream_extent(
974 dict,
975 data_start,
976 ParseError::new(end_tok.span.start, ParseErrorKind::StreamExtentMismatch),
977 );
978 }
979
980 Ok(Stream {
981 dict,
982 data_span: ByteSpan::from_range(data_start..data_end),
983 })
984 }
985
986 /// The `/Length`-disagreement fork: under [`StreamLengthPolicy::Strict`]
987 /// re-raise `strict_err` unchanged; under
988 /// [`StreamLengthPolicy::RecoverFromEndstream`] re-derive the data
989 /// extent from the `endstream` keyword.
990 ///
991 /// ## Why the keyword is a legitimate authority here
992 ///
993 /// §7.3.8.2 Table 5 defines `/Length` *as* "the number of bytes from
994 /// the beginning of the line following the keyword `stream` to the last
995 /// byte just before the keyword `endstream`". The keyword is therefore
996 /// not a heuristic landmark invented by this function — it is the other
997 /// half of the spec's own definition. When the two halves disagree, the
998 /// keyword is the one that is still physically present in the bytes,
999 /// which is why every mature reader (qpdf, pdfium, poppler, pdf.js)
1000 /// prefers it during damage recovery.
1001 ///
1002 /// ## Why the scan starts at `data_start`, not at the stored end
1003 ///
1004 /// The stored length can be wrong in either direction. Too short (the
1005 /// dominant real-world case: a file whose `/Length` values were
1006 /// computed for LF line endings and then converted to CRLF, so every
1007 /// stream grew by one byte per line) leaves `endstream` *after* the
1008 /// stored end; too long leaves it *before*. Scanning forward from the
1009 /// first data byte finds the first terminator in both directions, so a
1010 /// single rule covers both. The cost is that a stream whose binary data
1011 /// happens to contain the literal bytes `endstream` is truncated at
1012 /// that point — acceptable only because this path is unreachable except
1013 /// on a file whose cross-reference machinery has already failed, where
1014 /// the alternative outcome is not "correct data" but "no document".
1015 ///
1016 /// ## The EOL back-off
1017 ///
1018 /// §7.3.8.1 says an EOL marker "should" precede `endstream` and is not
1019 /// counted in `/Length`. One such marker (`\r\n`, `\n`, or a lone `\r`)
1020 /// is therefore removed from the end of the derived span. Exactly one —
1021 /// removing more would eat real data from a stream that legitimately
1022 /// ends in blank lines.
1023 ///
1024 /// ## `/Length` is rewritten to match
1025 ///
1026 /// The returned [`Stream`]'s dictionary carries the **derived** length,
1027 /// not the file's stale one, so the dictionary and the data span never
1028 /// disagree. See the inline commentary at the rewrite for why this is a
1029 /// correctness requirement rather than tidiness.
1030 ///
1031 /// # Errors
1032 ///
1033 /// `strict_err` verbatim under `Strict`; the same error under
1034 /// `RecoverFromEndstream` when no `endstream` keyword follows the data
1035 /// at all (nothing to recover *from*, so the refusal stands — recovery
1036 /// never invents an extent out of nothing).
1037 fn recover_stream_extent(
1038 &mut self,
1039 dict: Dict,
1040 data_start: usize,
1041 strict_err: ParseError,
1042 ) -> Result<Stream, ParseError> {
1043 if self.stream_length_policy != StreamLengthPolicy::RecoverFromEndstream {
1044 return Err(strict_err);
1045 }
1046 let Some(kw_at) = find_keyword(self.buf, data_start, b"endstream") else {
1047 return Err(strict_err);
1048 };
1049 // Back off exactly one EOL marker (§7.3.8.1: "should" be there, and
1050 // it is not part of the data).
1051 let mut data_end = kw_at;
1052 if data_end > data_start && self.buf.get(data_end - 1) == Some(&b'\n') {
1053 data_end -= 1;
1054 }
1055 if data_end > data_start && self.buf.get(data_end - 1) == Some(&b'\r') {
1056 data_end -= 1;
1057 }
1058
1059 // Resume token scanning at the keyword so the caller's `endobj`
1060 // expectation is evaluated exactly as on the clean path.
1061 self.lexer = Lexer::at(self.buf, kw_at);
1062 self.peeked.clear();
1063 let end_tok = self.expect_any()?;
1064 if !self.is_keyword(&end_tok, b"endstream") {
1065 return Err(strict_err);
1066 }
1067
1068 // Rewrite `/Length` to the extent actually found.
1069 //
1070 // This is not cosmetic — it is required for correctness, and the
1071 // round-trip harness is what proves it. `Stream` carries the
1072 // dictionary and the data span as two statements of one fact, and
1073 // the rest of the crate reads them independently: the filter layer
1074 // decodes `data_span`, while the writer re-emits `dict` verbatim.
1075 // Leaving the stale number in the dictionary next to a repaired
1076 // span would make pdfcer *emit* the very inconsistency it just
1077 // recovered from — a saved file whose `/Length` under-runs its own
1078 // data, i.e. a file pdfcer itself would then refuse to reload.
1079 //
1080 // §5.6's "never normalize" is not in tension here: it governs clean
1081 // passthrough, and this branch is unreachable except on a document
1082 // whose cross-reference machinery already failed, which always
1083 // saves as a full rewrite. Correcting a provably-wrong length is
1084 // the only way such a rewrite can be a valid PDF at all.
1085 //
1086 // If `/Length` was an indirect reference (§7.3.10 EXAMPLE 3), it is
1087 // replaced by a direct integer and the length object is simply left
1088 // unreferenced — harmless, and more honest than updating a separate
1089 // object the writer may not re-emit.
1090 let mut dict = dict;
1091 dict.insert(
1092 Name::from(b"Length"),
1093 Object::Integer(i64::try_from(data_end - data_start).unwrap_or(0)),
1094 );
1095
1096 self.stream_lengths_recovered += 1;
1097 Ok(Stream {
1098 dict,
1099 data_span: ByteSpan::from_range(data_start..data_end),
1100 })
1101 }
1102}
1103
1104/// First occurrence of `needle` in `buf` at or after `from` that stands as
1105/// its own token — i.e. the byte after it is not a regular character, so
1106/// `endstreamx` never matches.
1107///
1108/// The byte *before* is deliberately NOT constrained: a stream whose
1109/// declared length was too long, or whose final EOL is missing, can put
1110/// `endstream` flush against the last data byte, and refusing that shape
1111/// would defeat the recovery this helper exists for.
1112fn find_keyword(buf: &[u8], from: usize, needle: &[u8]) -> Option<usize> {
1113 let hay = buf.get(from..)?;
1114 let n = needle.len();
1115 let mut base = 0usize;
1116 while let Some(rel) = hay.get(base..)?.windows(n).position(|w| w == needle) {
1117 let at = base + rel;
1118 let after_ok = !hay.get(at + n).is_some_and(|&b| is_regular(b));
1119 if after_ok {
1120 return Some(from + at);
1121 }
1122 base = at + 1;
1123 }
1124 None
1125}
1126
1127#[cfg(test)]
1128#[allow(
1129 clippy::unwrap_used,
1130 clippy::expect_used,
1131 clippy::panic,
1132 clippy::indexing_slicing
1133)]
1134mod tests {
1135 use super::*;
1136
1137 fn parse(input: &[u8]) -> Object {
1138 Parser::at(input, 0).parse_object().unwrap()
1139 }
1140
1141 fn parse_err(input: &[u8]) -> ParseErrorKind {
1142 Parser::at(input, 0).parse_object().unwrap_err().kind
1143 }
1144
1145 fn no_lengths(_: ObjId) -> Option<i64> {
1146 None
1147 }
1148
1149 // ---- scalars and containers ----
1150
1151 #[test]
1152 fn scalars() {
1153 assert_eq!(parse(b"true"), Object::Boolean(true));
1154 assert_eq!(parse(b"false"), Object::Boolean(false));
1155 assert_eq!(parse(b"null"), Object::Null);
1156 assert_eq!(parse(b"42"), Object::Integer(42));
1157 assert_eq!(parse(b"4."), Object::Real(4.0));
1158 assert_eq!(parse(b"(hi)"), Object::String(b"hi".to_vec()));
1159 assert_eq!(parse(b"/Type"), Object::Name(Name::from(b"Type")));
1160 }
1161
1162 #[test]
1163 fn heterogeneous_array_spec_example() {
1164 // §7.3.6 EXAMPLE.
1165 let Object::Array(a) = parse(b"[ 549 3.14 false (Ralph) /SomeName ]") else {
1166 panic!("not an array");
1167 };
1168 assert_eq!(a.len(), 5);
1169 assert_eq!(a[0], Object::Integer(549));
1170 assert_eq!(a[2], Object::Boolean(false));
1171 assert_eq!(a[4], Object::Name(Name::from(b"SomeName")));
1172 }
1173
1174 #[test]
1175 fn nested_dict() {
1176 let obj = parse(b"<< /A << /B [1 2] >> /C null >>");
1177 let d = obj.as_dict().unwrap();
1178 let inner = d.get(b"A").unwrap().as_dict().unwrap();
1179 assert_eq!(inner.get(b"B").unwrap().as_array().unwrap().len(), 2);
1180 // §7.3.7: null value ≡ absent.
1181 assert!(d.get(b"C").is_none());
1182 }
1183
1184 // ---- the N G R lookahead ----
1185
1186 #[test]
1187 fn reference_lookahead_in_array() {
1188 // §7.3.10: `[1 0 R 2 0 R]` is two references, not six values.
1189 let Object::Array(a) = parse(b"[1 0 R 2 0 R]") else {
1190 panic!("not an array");
1191 };
1192 assert_eq!(
1193 a,
1194 vec![
1195 Object::Reference(ObjId::new(1, 0)),
1196 Object::Reference(ObjId::new(2, 0)),
1197 ]
1198 );
1199 }
1200
1201 #[test]
1202 fn integers_that_are_not_references_stay_integers() {
1203 // Two integers followed by a non-R token: plain integers.
1204 let Object::Array(a) = parse(b"[1 0 3]") else {
1205 panic!("not an array");
1206 };
1207 assert_eq!(
1208 a,
1209 vec![Object::Integer(1), Object::Integer(0), Object::Integer(3)]
1210 );
1211 // Trailing pair at EOF (no third token): plain integers.
1212 let Object::Array(a) = parse(b"[1 0]") else {
1213 panic!("not an array");
1214 };
1215 assert_eq!(a.len(), 2);
1216 }
1217
1218 #[test]
1219 fn reference_as_dict_value() {
1220 let obj = parse(b"<< /Root 2 0 R >>");
1221 let d = obj.as_dict().unwrap();
1222 assert_eq!(
1223 d.get(b"Root").unwrap().as_reference(),
1224 Some(ObjId::new(2, 0))
1225 );
1226 }
1227
1228 /// A missing `endobj` is an error on the STRICT path, and stays one.
1229 ///
1230 /// The recovery leniency added 2026-08-07 must not leak into clean
1231 /// loading. On a file whose xref parses, a missing terminator is real
1232 /// damage the operator should hear about, and accepting it would put an
1233 /// inferred extent into the writer's byte-identical re-emission path
1234 /// and break the round-trip invariant (`ARCHITECTURE.md` §5).
1235 #[test]
1236 fn missing_endobj_is_refused_under_the_default_policy() {
1237 let buf: &[u8] = b"2 0 obj
1238<< /Type /Pages >>
12393 0 obj
1240<< >>
1241endobj
1242";
1243 let err = Parser::at(buf, 0)
1244 .parse_indirect_object(&mut |_| None)
1245 .expect_err("strict parsing must refuse a definition with no endobj");
1246 assert_eq!(err.kind, ParseErrorKind::MissingEndobj);
1247 }
1248
1249 /// The same bytes are ACCEPTED under the recovery policy, and counted.
1250 ///
1251 /// Paired with the test above deliberately: together they prove the
1252 /// difference is caused by the POLICY and not by something incidental
1253 /// about the input. Either test alone would pass against a parser that
1254 /// ignored the policy entirely in one direction.
1255 #[test]
1256 fn missing_endobj_is_recovered_and_counted_under_the_lenient_policy() {
1257 let buf: &[u8] = b"2 0 obj
1258<< /Type /Pages >>
12593 0 obj
1260<< >>
1261endobj
1262";
1263 let mut parser =
1264 Parser::at(buf, 0).with_terminator_policy(TerminatorPolicy::RecoverAtNextHeader);
1265 let io = parser
1266 .parse_indirect_object(&mut |_| None)
1267 .expect("the lenient policy accepts a body that parsed cleanly");
1268 assert_eq!(io.id, ObjId::new(2, 0));
1269 assert_eq!(parser.missing_endobj_recovered(), 1);
1270 // The extent must stop before `3 0 obj` — claiming the next
1271 // object's header would corrupt whatever re-parses this span.
1272 let Provenance::RecoveredFile(span) = io.provenance else {
1273 panic!(
1274 "a terminator-less definition must be RecoveredFile, so the writer re-serializes instead of copying bytes that lack an endobj"
1275 );
1276 };
1277 assert!(span.end() <= buf.windows(7).position(|w| w == b"3 0 obj").unwrap());
1278 }
1279
1280 // ---- strictness ----
1281
1282 #[test]
1283 fn duplicate_dict_key_is_error() {
1284 assert_eq!(
1285 parse_err(b"<< /A 1 /A 2 >>"),
1286 ParseErrorKind::DuplicateDictKey
1287 );
1288 }
1289
1290 #[test]
1291 fn non_name_dict_key_is_error() {
1292 assert_eq!(parse_err(b"<< 1 2 >>"), ParseErrorKind::DictKeyNotName);
1293 }
1294
1295 #[test]
1296 fn depth_guard_trips() {
1297 let mut bomb = vec![b'['; MAX_NESTING_DEPTH + 8];
1298 bomb.extend_from_slice(&vec![b']'; MAX_NESTING_DEPTH + 8]);
1299 assert_eq!(parse_err(&bomb), ParseErrorKind::DepthExceeded);
1300 }
1301
1302 #[test]
1303 fn unclosed_array_is_eof_error() {
1304 assert_eq!(parse_err(b"[1 2"), ParseErrorKind::UnexpectedEof);
1305 }
1306
1307 #[test]
1308 fn stray_keyword_at_value_position_is_error() {
1309 assert!(matches!(
1310 parse_err(b"frobnicate"),
1311 ParseErrorKind::Unexpected(_)
1312 ));
1313 }
1314
1315 // ---- indirect objects ----
1316
1317 #[test]
1318 fn indirect_object_spec_example_and_span() {
1319 // §7.3.10 EXAMPLE 1 — and the span covers the FULL definition
1320 // (the provenance contract, decision 001 §6.1 item 1).
1321 let buf: &[u8] = b"12 0 obj\n (Brillig)\nendobj";
1322 let io = Parser::at(buf, 0)
1323 .parse_indirect_object(&mut no_lengths)
1324 .unwrap();
1325 assert_eq!(io.id, ObjId::new(12, 0));
1326 assert_eq!(io.value, Object::String(b"Brillig".to_vec()));
1327 assert_eq!(io.file_span().unwrap().slice(buf).unwrap(), buf);
1328 }
1329
1330 #[test]
1331 fn stream_with_direct_length() {
1332 let buf: &[u8] = b"5 0 obj << /Length 9 >>\nstream\nsome data\nendstream endobj";
1333 let io = Parser::at(buf, 0)
1334 .parse_indirect_object(&mut no_lengths)
1335 .unwrap();
1336 let Object::Stream(s) = &io.value else {
1337 panic!("not a stream");
1338 };
1339 assert_eq!(s.data_span.slice(buf).unwrap(), b"some data");
1340 assert_eq!(io.file_span().unwrap().slice(buf).unwrap(), buf);
1341 }
1342
1343 #[test]
1344 fn stream_with_crlf_after_keyword() {
1345 let buf: &[u8] = b"5 0 obj << /Length 4 >>\nstream\r\nabcd\nendstream endobj";
1346 let io = Parser::at(buf, 0)
1347 .parse_indirect_object(&mut no_lengths)
1348 .unwrap();
1349 let Object::Stream(s) = &io.value else {
1350 panic!("not a stream");
1351 };
1352 assert_eq!(s.data_span.slice(buf).unwrap(), b"abcd");
1353 }
1354
1355 #[test]
1356 fn stream_cr_alone_after_keyword_is_error() {
1357 // §7.3.8.1: "and NOT by CR alone."
1358 let buf: &[u8] = b"5 0 obj << /Length 4 >>\nstream\rabcd\nendstream endobj";
1359 let e = Parser::at(buf, 0)
1360 .parse_indirect_object(&mut no_lengths)
1361 .unwrap_err();
1362 assert_eq!(e.kind, ParseErrorKind::BadStreamEol);
1363 }
1364
1365 #[test]
1366 fn stream_with_indirect_length_resolves_via_callback() {
1367 // §7.3.10 EXAMPLE 3's single-pass-writer pattern.
1368 let buf: &[u8] = b"7 0 obj << /Length 8 0 R >>\nstream\n0123456\nendstream endobj";
1369 let mut resolver = |id: ObjId| (id == ObjId::new(8, 0)).then_some(7);
1370 let io = Parser::at(buf, 0)
1371 .parse_indirect_object(&mut resolver)
1372 .unwrap();
1373 let Object::Stream(s) = &io.value else {
1374 panic!("not a stream");
1375 };
1376 assert_eq!(s.data_span.slice(buf).unwrap(), b"0123456");
1377 }
1378
1379 #[test]
1380 fn stream_wrong_length_is_extent_mismatch() {
1381 // §7.3.8.2: inconsistent extent "is an error" under the DEFAULT
1382 // Strict policy — no silent endstream scanning on the clean path.
1383 let buf: &[u8] = b"5 0 obj << /Length 3 >>\nstream\nsome data\nendstream endobj";
1384 let e = Parser::at(buf, 0)
1385 .parse_indirect_object(&mut no_lengths)
1386 .unwrap_err();
1387 assert_eq!(e.kind, ParseErrorKind::StreamExtentMismatch);
1388 }
1389
1390 #[test]
1391 fn stream_missing_length_is_error() {
1392 let buf: &[u8] = b"5 0 obj << >>\nstream\nxx\nendstream endobj";
1393 let e = Parser::at(buf, 0)
1394 .parse_indirect_object(&mut no_lengths)
1395 .unwrap_err();
1396 assert_eq!(e.kind, ParseErrorKind::BadStreamLength);
1397 }
1398
1399 // ---- StreamLengthPolicy::RecoverFromEndstream (recovery path only) ----
1400
1401 /// A `/Length` that is too SHORT — the dominant real-world shape (a
1402 /// file whose lengths were computed for LF endings and then converted
1403 /// to CRLF) — re-derives from `endstream` and is counted.
1404 #[test]
1405 fn recovering_policy_repairs_a_short_length() {
1406 let buf: &[u8] = b"5 0 obj << /Length 3 >>\nstream\nsome data\nendstream endobj";
1407 let mut p =
1408 Parser::at(buf, 0).with_stream_length_policy(StreamLengthPolicy::RecoverFromEndstream);
1409 let io = p.parse_indirect_object(&mut no_lengths).unwrap();
1410 let Object::Stream(s) = &io.value else {
1411 panic!("not a stream");
1412 };
1413 // The EOL before `endstream` is backed off (§7.3.8.1), so the data
1414 // is exactly the payload — not `"some data\n"`.
1415 assert_eq!(s.data_span.slice(buf).unwrap(), b"some data");
1416 assert_eq!(p.stream_lengths_recovered(), 1);
1417 // The dictionary must agree with the span, or the writer would
1418 // re-emit the inconsistency it just recovered from.
1419 assert_eq!(s.dict.get(b"Length"), Some(&Object::Integer(9)));
1420 }
1421
1422 /// The dictionary/span agreement holds for an INDIRECT `/Length` too:
1423 /// the reference is replaced by the derived direct integer.
1424 #[test]
1425 fn recovering_policy_replaces_an_indirect_length_with_the_derived_one() {
1426 let buf: &[u8] = b"5 0 obj << /Length 8 0 R >>\nstream\nsome data\nendstream endobj";
1427 // Object 8 resolves to a wrong (too short) value.
1428 let mut resolve = |id: ObjId| -> Option<i64> { (id.num == 8).then_some(3) };
1429 let mut p =
1430 Parser::at(buf, 0).with_stream_length_policy(StreamLengthPolicy::RecoverFromEndstream);
1431 let io = p.parse_indirect_object(&mut resolve).unwrap();
1432 let Object::Stream(s) = &io.value else {
1433 panic!("not a stream");
1434 };
1435 assert_eq!(s.data_span.slice(buf).unwrap(), b"some data");
1436 assert_eq!(s.dict.get(b"Length"), Some(&Object::Integer(9)));
1437 assert_eq!(p.stream_lengths_recovered(), 1);
1438 }
1439
1440 /// A `/Length` that is too LONG is repaired by the same rule: the scan
1441 /// starts at the first data byte, so it finds the terminator whichever
1442 /// side of the stored end it lies on.
1443 #[test]
1444 fn recovering_policy_repairs_a_long_length() {
1445 let buf: &[u8] = b"5 0 obj << /Length 400 >>\nstream\nabc\nendstream endobj";
1446 let mut p =
1447 Parser::at(buf, 0).with_stream_length_policy(StreamLengthPolicy::RecoverFromEndstream);
1448 let io = p.parse_indirect_object(&mut no_lengths).unwrap();
1449 let Object::Stream(s) = &io.value else {
1450 panic!("not a stream");
1451 };
1452 assert_eq!(s.data_span.slice(buf).unwrap(), b"abc");
1453 assert_eq!(p.stream_lengths_recovered(), 1);
1454 }
1455
1456 /// A missing `/Length` is also recoverable — `endstream` is then the
1457 /// only surviving statement of the extent.
1458 #[test]
1459 fn recovering_policy_repairs_a_missing_length() {
1460 let buf: &[u8] = b"5 0 obj << >>\nstream\nxx\nendstream endobj";
1461 let mut p =
1462 Parser::at(buf, 0).with_stream_length_policy(StreamLengthPolicy::RecoverFromEndstream);
1463 let io = p.parse_indirect_object(&mut no_lengths).unwrap();
1464 let Object::Stream(s) = &io.value else {
1465 panic!("not a stream");
1466 };
1467 assert_eq!(s.data_span.slice(buf).unwrap(), b"xx");
1468 assert_eq!(p.stream_lengths_recovered(), 1);
1469 }
1470
1471 /// A CORRECT `/Length` is left completely alone under the recovering
1472 /// policy: no scan, no repair, counter stays 0. This is what makes the
1473 /// policy safe to apply to a whole recovered file rather than only to
1474 /// the objects already known to be broken.
1475 #[test]
1476 fn recovering_policy_does_not_touch_a_correct_length() {
1477 let buf: &[u8] = b"5 0 obj << /Length 9 >>\nstream\nsome data\nendstream endobj";
1478 let mut p =
1479 Parser::at(buf, 0).with_stream_length_policy(StreamLengthPolicy::RecoverFromEndstream);
1480 let io = p.parse_indirect_object(&mut no_lengths).unwrap();
1481 let Object::Stream(s) = &io.value else {
1482 panic!("not a stream");
1483 };
1484 assert_eq!(s.data_span.slice(buf).unwrap(), b"some data");
1485 assert_eq!(
1486 p.stream_lengths_recovered(),
1487 0,
1488 "a file that agrees with itself is never 'repaired'"
1489 );
1490 }
1491
1492 /// With NO `endstream` anywhere there is nothing to recover from, so
1493 /// the strict refusal stands — recovery never invents an extent.
1494 #[test]
1495 fn recovering_policy_still_refuses_when_there_is_no_endstream() {
1496 let buf: &[u8] = b"5 0 obj << /Length 3 >>\nstream\nsome data\nendobj";
1497 let e = Parser::at(buf, 0)
1498 .with_stream_length_policy(StreamLengthPolicy::RecoverFromEndstream)
1499 .parse_indirect_object(&mut no_lengths)
1500 .unwrap_err();
1501 assert_eq!(e.kind, ParseErrorKind::StreamExtentMismatch);
1502 }
1503
1504 /// The default is Strict — the policy must be opted into explicitly,
1505 /// so no clean-path caller can acquire it by accident.
1506 #[test]
1507 fn default_policy_is_strict() {
1508 assert_eq!(StreamLengthPolicy::default(), StreamLengthPolicy::Strict);
1509 }
1510
1511 #[test]
1512 fn object_number_zero_is_rejected() {
1513 // §7.5.4: object 0 is permanently the free-list head.
1514 let buf: &[u8] = b"0 0 obj null endobj";
1515 let e = Parser::at(buf, 0)
1516 .parse_indirect_object(&mut no_lengths)
1517 .unwrap_err();
1518 assert_eq!(e.kind, ParseErrorKind::BadObjectHeader);
1519 }
1520
1521 #[test]
1522 fn missing_endobj_is_error() {
1523 let buf: &[u8] = b"3 0 obj 42 trailer";
1524 let e = Parser::at(buf, 0)
1525 .parse_indirect_object(&mut no_lengths)
1526 .unwrap_err();
1527 assert_eq!(e.kind, ParseErrorKind::MissingEndobj);
1528 }
1529}