laminapdf-cos 0.9.0

Read PDF files in Rust, broken ones included: the cross-reference table with repair, object streams, decryption and the page tree, plus an overlay that records edits.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
//! Stable, enumerated warning codes (ADR 0003 §2) and the per-document warning log.

use std::collections::BTreeSet;

use laminapdf_syntax::{ErrorKind, Limits, Location, Position};

use crate::error::{Error, Result};

/// A recoverable problem the tolerant reader repaired or worked around (ADR 0003 §2).
///
/// Each variant has a stable kebab-case [`code`](Warning::code) that is part of the public
/// API in Rust, WASM and TypeScript; codes are never renamed or reused. Variants carry the
/// byte offset or object number where one exists. With
/// [`OpenOptions::with_strict`](crate::OpenOptions::with_strict), every warning is an
/// [`Error::Strict`] instead.
///
/// Added in 0.2.0.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Warning {
    /// `missing-header`: no `%PDF-x.y` in the first 1,024 bytes; parsing went ahead anyway.
    MissingHeader,
    /// `xref-repaired`: the stored cross-reference data was unusable and was rebuilt by scanning.
    XrefRepaired,
    /// `xrefstm-ignored`: a hybrid file's `/XRefStm` could not be read.
    XrefStmIgnored {
        /// Byte offset the `/XRefStm` entry points at.
        offset: u64,
    },
    /// `stream-length-recovered`: a stream's `/Length` was wrong or unresolvable, so its
    /// extent was found by scanning for `endstream`.
    StreamLengthRecovered {
        /// The stream's object number.
        object: u32,
    },
    /// `dictionary-key-skipped`: a dictionary had something other than a name where a key
    /// belongs (a stray keyword, number, string, array or unbalanced `)` or `>`); it was
    /// skipped and the rest of the dictionary read, as pdf.js and PDFium do.
    DictionaryKeySkipped {
        /// The object holding the dictionary (`None` for a trailer or xref-stream dictionary).
        object: Option<u32>,
    },
    /// `stale-generation`: a reference's generation did not match its xref entry, so it
    /// resolved to `null` (§7.3.10).
    StaleGeneration {
        /// The referenced object number.
        object: u32,
        /// The generation the reference asked for.
        generation: u16,
    },
    /// `page-tree-node-skipped`: a page-tree kid or `/Kids` was missing, unparsable, of the
    /// wrong type, or deeper than [`Limits::max_page_tree_depth`].
    PageTreeNodeSkipped {
        /// The skipped node's object number (`None` for a direct object).
        object: Option<u32>,
    },
    /// `page-count-mismatch`: the page-tree root's `/Count` differs from the walked page count.
    PageCountMismatch {
        /// The root node's object number (`None` for a direct object).
        object: Option<u32>,
        /// The `/Count` the file declares.
        declared: i64,
        /// The number of pages the walk found.
        walked: u64,
    },
    /// `flate-truncated`: Flate output was kept despite truncation or a bad checksum.
    FlateTruncated {
        /// The stream's object number, when known.
        object: Option<u32>,
    },
    /// `filter-characters-skipped`: `ASCIIHexDecode` or `ASCII85Decode` data held characters
    /// outside the filter's alphabet, which were skipped.
    ///
    /// Added in 0.4.0.
    FilterCharactersSkipped {
        /// The stream's object number, when known.
        object: Option<u32>,
    },
    /// `objstm-index-mismatch`: an object-stream index was stale and a search found the object.
    ObjStmIndexMismatch {
        /// The object found by searching.
        object: u32,
    },
    /// `object-number-out-of-range`: an xref entry above [`Limits::max_object_number`] was dropped.
    ObjectNumberOutOfRange {
        /// The dropped object number.
        object: u32,
    },
    /// `aes-padding-invalid`: an AES-encrypted string or stream was not `IV ‖ whole blocks`
    /// (kept as stored) or had invalid PKCS#5 padding (decrypted, padding kept). A plaintext
    /// string in an encrypted document (PDFex-style mixing) usually shows up this way.
    AesPaddingInvalid {
        /// The object holding the data.
        object: u32,
    },
    /// `perms-mismatch`: an R5/R6 document's `/Perms` does not decrypt to its `/P` and
    /// `/EncryptMetadata` (ISO 32000-2 Algorithm 13): `/P` may have been tampered with.
    PermsMismatch,
    /// `warnings-truncated`: more than [`Limits::max_warnings`] warnings were raised; the rest
    /// were dropped.
    WarningsTruncated,
    /// `invalid-box`: a page boundary box (`/MediaBox`, `/CropBox`, `/BleedBox`, `/TrimBox`,
    /// `/ArtBox`) is not an array of four numbers; the view reads it as absent.
    InvalidBox {
        /// The page's object number (`None` for a direct page dictionary).
        object: Option<u32>,
        /// The page's index (tells direct pages apart).
        page: u64,
        /// Which box, e.g. `"MediaBox"`.
        key: &'static str,
    },
    /// `invalid-rotate`: a page's `/Rotate` is not an integer or integral real (such as
    /// `90.0`) that is a multiple of 90; the view reads 0.
    InvalidRotate {
        /// The page's object number (`None` for a direct page dictionary).
        object: Option<u32>,
        /// The page's index (tells direct pages apart).
        page: u64,
    },
    /// `name-tree-node-skipped`: a name- or number-tree node, kid or entry was missing,
    /// malformed, reached twice, or deeper than [`Limits::max_tree_depth`]; it was skipped.
    NameTreeNodeSkipped {
        /// The skipped node's object number (`None` for a direct object).
        object: Option<u32>,
    },
    /// `outline-cycle`: an outline item was reached twice; the walk stopped that branch.
    OutlineCycle {
        /// The item reached again.
        object: u32,
    },
    /// `outline-item-skipped`: an outline item was missing, not a dictionary, or deeper than
    /// [`Limits::max_tree_depth`]; it and its subtree were skipped.
    OutlineItemSkipped {
        /// The skipped item's object number (`None` for a direct object).
        object: Option<u32>,
    },
    /// `invalid-date`: an Info date is not a valid PDF date (§7.9.4); the raw string is kept.
    InvalidDate {
        /// The Info dictionary's object number (`None` for a direct one).
        object: Option<u32>,
        /// Which entry, e.g. `"ModDate"` (`"other"` for a key outside the standard ones).
        key: &'static str,
    },
    /// `xmp-invalid`: the catalog's XMP metadata packet isn't readable XMP (not well-formed
    /// XML, a DTD, an undefined entity, an undeclared prefix, too deep or too many
    /// declarations, or no `rdf:RDF`); the model reads it as absent.
    XmpInvalid {
        /// The metadata stream's object number (`None` for a direct one).
        object: Option<u32>,
        /// About where in the stream's decoded bytes reading stopped; `None` when no one place
        /// is at fault (an unknown encoding, no `rdf:RDF`). Data only: the location names the
        /// object, which keeps this rare warning's code small in the WebAssembly modules.
        offset: Option<u64>,
        /// What was wrong: `encoding`, `dtd`, `entity`, `prefix`, `depth`, `limit`, `syntax`
        /// or `no-rdf`.
        reason: &'static str,
    },
    /// `annot-name-duplicate`: two annotations on one page have the same `/NM` (§12.5.2: it
    /// shall be unique on its page); both are kept, and an annotation's ID never depends on it.
    AnnotNameDuplicate {
        /// The second annotation's object number (`None` for a direct one).
        object: Option<u32>,
    },
    /// `xmp-repaired`: the catalog's XMP metadata packet had damage other readers read past, and
    /// was read the same way: bytes that aren't UTF-8 in its `<?xpacket … ?>` header, or one of
    /// XMP's standard prefixes (`dc`, `xmp`, `pdf`, …) used without its declaration.
    XmpRepaired {
        /// The metadata stream's object number (`None` for a direct one).
        object: Option<u32>,
        /// What was repaired: `header-encoding` or `undeclared-prefix`.
        reason: &'static str,
    },
    /// `invalid-page-label`: a `/PageLabels` entry is malformed: not a dictionary, a negative
    /// start, an unknown `/S` style (no numeric part), a `/P` that is not a string (no prefix)
    /// or `/St` below 1 (numbering from 1). The rest of the entry is kept.
    InvalidPageLabel {
        /// The page index the range starts at, as stored (it may be negative).
        start: i64,
    },
    /// `invalid-entry`: an entry a view reads (`/Info`, `/Names`, `/Outlines`, `/Dests`,
    /// `/UserUnit`, …) is unreadable or of the wrong type; the view reads it as absent (or its
    /// default).
    InvalidEntry {
        /// The object holding the entry (`None` for a direct object or the trailer).
        object: Option<u32>,
        /// The entry's key, e.g. `"Info"`.
        key: &'static str,
    },
    /// `content-unknown-operator`: a content stream used an operator ISO 32000-2 Annex A does
    /// not define, outside a `BX`/`EX` compatibility section; it was skipped (ADR 0023).
    ContentUnknownOperator {
        /// The content's object: the page for page content, the Form XObject for a form;
        /// `None` for content interpreted on its own (`interpret_content`) or a direct page.
        object: Option<u32>,
        /// Byte offset of the operator in the decoded content.
        offset: u64,
    },
    /// `content-bad-operands`: a content-stream operator had too few operands or operands of
    /// the wrong type (it was skipped), or extra operands (the last ones were used) (ADR 0023).
    ContentBadOperands {
        /// The content's object (as for `content-unknown-operator`).
        object: Option<u32>,
        /// Byte offset of the operator in the decoded content.
        offset: u64,
    },
    /// `content-unbalanced-q`: a `Q` without a matching `q` (ignored), or a content stream
    /// that ended with saved graphics states still open (restored) (ADR 0023).
    ContentUnbalancedQ {
        /// The content's object (as for `content-unknown-operator`).
        object: Option<u32>,
        /// Byte offset of the `Q`, or the end of the content.
        offset: u64,
    },
    /// `content-unbalanced-bt`: a `BT` inside a text object, an `ET` outside one, a text
    /// operator outside one, or a content stream that ended inside one (ADR 0023).
    ContentUnbalancedBt {
        /// The content's object (as for `content-unknown-operator`).
        object: Option<u32>,
        /// Byte offset of the operator, or the end of the content.
        offset: u64,
    },
    /// `content-unbalanced-marked`: an `EMC` without a matching `BMC`/`BDC` (ignored), or a
    /// content stream that ended with marked-content sequences open (closed) (ADR 0023).
    ContentUnbalancedMarked {
        /// The content's object (as for `content-unknown-operator`).
        object: Option<u32>,
        /// Byte offset of the `EMC`, or the end of the content.
        offset: u64,
    },
    /// `content-syntax`: a content stream held bytes that are not a token (an unbalanced `)`
    /// or `>`, a bad hex digit, an unterminated string or array) or a stray `ID`/`EI`; they
    /// were skipped with the operands read so far (ADR 0023).
    ContentSyntax {
        /// The content's object (as for `content-unknown-operator`).
        object: Option<u32>,
        /// Byte offset of the problem in the decoded content.
        offset: u64,
    },
    /// `content-resource-missing`: an operator named a resource (font, XObject, graphics
    /// state, colour space, shading, property list) that is missing, of the wrong type or
    /// unreadable, or a Form XObject's content could not be decoded; the operator was
    /// skipped, or ran without the resource (ADR 0023).
    ContentResourceMissing {
        /// The content's object (as for `content-unknown-operator`).
        object: Option<u32>,
        /// Byte offset of the operator in the decoded content.
        offset: u64,
        /// The resource category, e.g. `"Font"`.
        category: &'static str,
    },
    /// `inline-image-unterminated`: no `EI` ends an inline image (neither at its declared or
    /// computed length nor by the heuristic of ADR 0023); the rest of the content was
    /// skipped.
    InlineImageUnterminated {
        /// The content's object (as for `content-unknown-operator`).
        object: Option<u32>,
        /// Byte offset of the `BI` in the decoded content.
        offset: u64,
    },
    /// `content-path-unpainted`: a content stream ended with a path that no painting operator
    /// ended; it was dropped (ADR 0023).
    ContentPathUnpainted {
        /// The content's object (as for `content-unknown-operator`).
        object: Option<u32>,
        /// Byte offset of the path's first segment in the decoded content.
        offset: u64,
    },
    /// `xobject-cycle`: a Form XObject draws itself, directly or through other forms; the
    /// inner `Do` was skipped (ADR 0023).
    XObjectCycle {
        /// The form reached again.
        object: u32,
    },
    /// `font-invalid`: a font dictionary read for text extraction has a missing, unreadable
    /// or malformed entry (descendant font, encoding, `/Differences`, widths, font program);
    /// its text was decoded with defaults. Raised by `laminapdf-text`.
    FontInvalid {
        /// The font dictionary's object (`None` for a direct one).
        object: Option<u32>,
    },
    /// `cmap-invalid`: a font's CMap or ToUnicode CMap had malformed entries (skipped), names
    /// a predefined CMap Lamina PDF has no table for (read as Identity), or a `/UseCMap` chain
    /// too deep (cut). Raised by `laminapdf-text`.
    CMapInvalid {
        /// The font dictionary's object (`None` for a direct one).
        object: Option<u32>,
    },
    /// `unmapped-glyph`: a font showed glyphs that neither its ToUnicode CMap, its encoding's
    /// glyph names nor its font program map to text; they extract as U+FFFD. Raised by
    /// `laminapdf-text`.
    UnmappedGlyph {
        /// The font dictionary's object (`None` for a direct one).
        object: Option<u32>,
    },
    /// `extract-limit-blocks`: a page had more runs of text than the extraction's block limit
    /// (each run can be a block); the runs past it were left out. Raised by `laminapdf-extract`.
    ExtractLimitBlocks {
        /// The page's index.
        page: u64,
        /// The limit that was reached.
        limit: u32,
    },
    /// `extract-reading-order-ambiguous`: a page mixes horizontal and vertical writing, so the
    /// order of its blocks is a guess. Raised by `laminapdf-extract`.
    ExtractReadingOrderAmbiguous {
        /// The page's index.
        page: u64,
    },
    /// `extract-table-ambiguous`: a table's rules marked out merged cells that aren't
    /// rectangles, so its cells were taken from the grid unmerged. Raised by `laminapdf-extract`.
    ExtractTableAmbiguous {
        /// The page's index.
        page: u64,
    },
    /// `extract-table-limit`: a page's rules would make a table with more cells than the
    /// extraction's limit (or more crossings than it allows to test); those rules gave no
    /// table. Raised by `laminapdf-extract`.
    ExtractTableLimit {
        /// The page's index.
        page: u64,
        /// The limit that was reached.
        limit: u32,
    },
    /// `extract-struct-tree-ignored`: a tagged page's structure tree failed a plausibility check,
    /// so its reading order came from the layout instead. Raised by `laminapdf-extract`.
    ExtractStructTreeIgnored {
        /// The page's index.
        page: u64,
        /// Which check failed: `coverage` (the tree covers too little of the page's text) or
        /// `order` (its order jumps back across columns too often).
        reason: &'static str,
    },
    /// `extract-untagged-content`: a page read in structure-tree order has visible text outside
    /// the tree and outside artifacts; it follows the tree's blocks, in layout order. Raised by
    /// `laminapdf-extract`.
    ExtractUntaggedContent {
        /// The page's index.
        page: u64,
        /// How many characters (spaces left out) lie outside the tree.
        chars: u64,
    },
    /// `extract-needs-ocr`: a page's text isn't the page's text: it has none (a scan or outlined
    /// glyphs), mostly glyphs without Unicode, or only an invisible OCR layer over an image,
    /// which extraction leaves out. Raised by `laminapdf-extract`.
    ExtractNeedsOcr {
        /// The page's index.
        page: u64,
        /// The page's text-layer status: `needs-ocr` or `ocr-layer`.
        status: &'static str,
    },
    /// `extract-column-order-uncertain`: the layout rules had to guess how a page's columns
    /// are read (a gutter narrower than a font size, a column left and read again, or a grid
    /// read by columns that a wrapped cell kept from reading by rows). Raised by
    /// `laminapdf-extract`.
    ExtractColumnOrderUncertain {
        /// The page's index.
        page: u64,
        /// Which check doubted the order: `narrow-gutter`, `columns-revisited` or `near-grid`.
        reason: &'static str,
    },
}

impl Warning {
    /// Every code [`Warning::code`] can return (listed in `fixtures/codes.json`).
    ///
    /// Added in 0.2.0.
    pub const CODES: &'static [&'static str] = &[
        "missing-header",
        "xref-repaired",
        "xrefstm-ignored",
        "stream-length-recovered",
        "dictionary-key-skipped",
        "stale-generation",
        "page-tree-node-skipped",
        "page-count-mismatch",
        "flate-truncated",
        "filter-characters-skipped",
        "objstm-index-mismatch",
        "object-number-out-of-range",
        "aes-padding-invalid",
        "perms-mismatch",
        "warnings-truncated",
        "invalid-box",
        "invalid-rotate",
        "name-tree-node-skipped",
        "outline-cycle",
        "outline-item-skipped",
        "invalid-date",
        "xmp-invalid",
        "annot-name-duplicate",
        "xmp-repaired",
        "invalid-page-label",
        "invalid-entry",
        "content-unknown-operator",
        "content-bad-operands",
        "content-unbalanced-q",
        "content-unbalanced-bt",
        "content-unbalanced-marked",
        "content-syntax",
        "content-resource-missing",
        "inline-image-unterminated",
        "xobject-cycle",
        "content-path-unpainted",
        "font-invalid",
        "cmap-invalid",
        "unmapped-glyph",
        "extract-limit-blocks",
        "extract-reading-order-ambiguous",
        "extract-table-ambiguous",
        "extract-table-limit",
        "extract-struct-tree-ignored",
        "extract-untagged-content",
        "extract-needs-ocr",
        "extract-column-order-uncertain",
    ];

    /// The stable kebab-case code, e.g. `"xref-repaired"`.
    ///
    /// Added in 0.2.0.
    #[must_use]
    pub const fn code(&self) -> &'static str {
        match self {
            Self::MissingHeader => "missing-header",
            Self::XrefRepaired => "xref-repaired",
            Self::XrefStmIgnored { .. } => "xrefstm-ignored",
            Self::StreamLengthRecovered { .. } => "stream-length-recovered",
            Self::DictionaryKeySkipped { .. } => "dictionary-key-skipped",
            Self::StaleGeneration { .. } => "stale-generation",
            Self::PageTreeNodeSkipped { .. } => "page-tree-node-skipped",
            Self::PageCountMismatch { .. } => "page-count-mismatch",
            Self::FlateTruncated { .. } => "flate-truncated",
            Self::FilterCharactersSkipped { .. } => "filter-characters-skipped",
            Self::ObjStmIndexMismatch { .. } => "objstm-index-mismatch",
            Self::ObjectNumberOutOfRange { .. } => "object-number-out-of-range",
            Self::AesPaddingInvalid { .. } => "aes-padding-invalid",
            Self::PermsMismatch => "perms-mismatch",
            Self::WarningsTruncated => "warnings-truncated",
            Self::InvalidBox { .. } => "invalid-box",
            Self::InvalidRotate { .. } => "invalid-rotate",
            Self::NameTreeNodeSkipped { .. } => "name-tree-node-skipped",
            Self::OutlineCycle { .. } => "outline-cycle",
            Self::OutlineItemSkipped { .. } => "outline-item-skipped",
            Self::InvalidDate { .. } => "invalid-date",
            Self::XmpInvalid { .. } => "xmp-invalid",
            Self::AnnotNameDuplicate { .. } => "annot-name-duplicate",
            Self::XmpRepaired { .. } => "xmp-repaired",
            Self::InvalidPageLabel { .. } => "invalid-page-label",
            Self::InvalidEntry { .. } => "invalid-entry",
            Self::ContentUnknownOperator { .. } => "content-unknown-operator",
            Self::ContentBadOperands { .. } => "content-bad-operands",
            Self::ContentUnbalancedQ { .. } => "content-unbalanced-q",
            Self::ContentUnbalancedBt { .. } => "content-unbalanced-bt",
            Self::ContentUnbalancedMarked { .. } => "content-unbalanced-marked",
            Self::ContentSyntax { .. } => "content-syntax",
            Self::ContentResourceMissing { .. } => "content-resource-missing",
            Self::InlineImageUnterminated { .. } => "inline-image-unterminated",
            Self::XObjectCycle { .. } => "xobject-cycle",
            Self::ContentPathUnpainted { .. } => "content-path-unpainted",
            Self::FontInvalid { .. } => "font-invalid",
            Self::CMapInvalid { .. } => "cmap-invalid",
            Self::UnmappedGlyph { .. } => "unmapped-glyph",
            Self::ExtractLimitBlocks { .. } => "extract-limit-blocks",
            Self::ExtractReadingOrderAmbiguous { .. } => "extract-reading-order-ambiguous",
            Self::ExtractTableAmbiguous { .. } => "extract-table-ambiguous",
            Self::ExtractTableLimit { .. } => "extract-table-limit",
            Self::ExtractStructTreeIgnored { .. } => "extract-struct-tree-ignored",
            Self::ExtractUntaggedContent { .. } => "extract-untagged-content",
            Self::ExtractNeedsOcr { .. } => "extract-needs-ocr",
            Self::ExtractColumnOrderUncertain { .. } => "extract-column-order-uncertain",
        }
    }

    /// The object number the warning is about, if any.
    ///
    /// Added in 0.2.0.
    #[must_use]
    pub const fn object(&self) -> Option<u32> {
        match *self {
            Self::StreamLengthRecovered { object }
            | Self::StaleGeneration { object, .. }
            | Self::ObjStmIndexMismatch { object }
            | Self::ObjectNumberOutOfRange { object }
            | Self::OutlineCycle { object }
            | Self::AesPaddingInvalid { object }
            | Self::XObjectCycle { object } => Some(object),
            Self::PageTreeNodeSkipped { object }
            | Self::DictionaryKeySkipped { object }
            | Self::PageCountMismatch { object, .. }
            | Self::FlateTruncated { object }
            | Self::FilterCharactersSkipped { object }
            | Self::InvalidBox { object, .. }
            | Self::InvalidRotate { object, .. }
            | Self::NameTreeNodeSkipped { object }
            | Self::OutlineItemSkipped { object }
            | Self::InvalidDate { object, .. }
            | Self::XmpInvalid { object, .. }
            | Self::AnnotNameDuplicate { object }
            | Self::XmpRepaired { object, .. }
            | Self::InvalidEntry { object, .. }
            | Self::ContentUnknownOperator { object, .. }
            | Self::ContentBadOperands { object, .. }
            | Self::ContentUnbalancedQ { object, .. }
            | Self::ContentUnbalancedBt { object, .. }
            | Self::ContentUnbalancedMarked { object, .. }
            | Self::ContentSyntax { object, .. }
            | Self::ContentResourceMissing { object, .. }
            | Self::InlineImageUnterminated { object, .. }
            | Self::ContentPathUnpainted { object, .. }
            | Self::FontInvalid { object }
            | Self::CMapInvalid { object }
            | Self::UnmappedGlyph { object } => object,
            Self::MissingHeader
            | Self::XrefRepaired
            | Self::XrefStmIgnored { .. }
            | Self::PermsMismatch
            | Self::WarningsTruncated
            | Self::InvalidPageLabel { .. }
            | Self::ExtractLimitBlocks { .. }
            | Self::ExtractReadingOrderAmbiguous { .. }
            | Self::ExtractTableAmbiguous { .. }
            | Self::ExtractTableLimit { .. }
            | Self::ExtractStructTreeIgnored { .. }
            | Self::ExtractUntaggedContent { .. }
            | Self::ExtractNeedsOcr { .. }
            | Self::ExtractColumnOrderUncertain { .. } => None,
        }
    }

    /// The kind of this warning ([ADR 0026] §2), as `fixtures/codes.json` lists it for
    /// [`Warning::code`] (a test checks every variant).
    ///
    /// [ADR 0026]: https://github.com/laudebugs/laminapdf/blob/main/docs/decisions/0026-error-and-diagnostic-contract.md
    ///
    /// Added in 0.2.0.
    #[must_use]
    pub const fn kind(&self) -> ErrorKind {
        match self {
            Self::MissingHeader
            | Self::XrefRepaired
            | Self::XrefStmIgnored { .. }
            | Self::StreamLengthRecovered { .. }
            | Self::DictionaryKeySkipped { .. }
            | Self::StaleGeneration { .. }
            | Self::PageTreeNodeSkipped { .. }
            | Self::PageCountMismatch { .. }
            | Self::FlateTruncated { .. }
            | Self::FilterCharactersSkipped { .. }
            | Self::ObjStmIndexMismatch { .. }
            | Self::InvalidBox { .. }
            | Self::InvalidRotate { .. }
            | Self::NameTreeNodeSkipped { .. }
            | Self::OutlineCycle { .. }
            | Self::OutlineItemSkipped { .. }
            | Self::InvalidDate { .. }
            | Self::XmpInvalid { .. }
            | Self::AnnotNameDuplicate { .. }
            | Self::XmpRepaired { .. }
            | Self::InvalidPageLabel { .. }
            | Self::InvalidEntry { .. }
            | Self::ContentUnknownOperator { .. }
            | Self::ContentBadOperands { .. }
            | Self::ContentUnbalancedQ { .. }
            | Self::ContentUnbalancedBt { .. }
            | Self::ContentUnbalancedMarked { .. }
            | Self::ContentSyntax { .. }
            | Self::ContentResourceMissing { .. }
            | Self::InlineImageUnterminated { .. }
            | Self::XObjectCycle { .. }
            | Self::ContentPathUnpainted { .. }
            | Self::FontInvalid { .. }
            | Self::CMapInvalid { .. }
            | Self::UnmappedGlyph { .. }
            | Self::ExtractStructTreeIgnored { .. }
            | Self::ExtractUntaggedContent { .. } => ErrorKind::Input,
            Self::ExtractReadingOrderAmbiguous { .. }
            | Self::ExtractTableAmbiguous { .. }
            | Self::ExtractNeedsOcr { .. }
            | Self::ExtractColumnOrderUncertain { .. } => ErrorKind::Unsupported,
            Self::ExtractTableLimit { .. } => ErrorKind::Limit,
            Self::ObjectNumberOutOfRange { .. } | Self::WarningsTruncated | Self::ExtractLimitBlocks { .. } => {
                ErrorKind::Limit
            }
            Self::AesPaddingInvalid { .. } | Self::PermsMismatch => ErrorKind::Security,
        }
    }

    /// Where the problem is (ADR 0026 §1.1): the object, a file offset, a page index, or for
    /// content warnings the content's object and the offset in its decoded data (no offset
    /// when the content has no object: content interpreted on its own or a direct page).
    ///
    /// Added in 0.2.0.
    #[must_use]
    pub fn location(&self) -> Location {
        let page_index = match *self {
            Self::XrefStmIgnored { offset } => return Location::from(Position::FileOffset(offset)),
            Self::ContentUnknownOperator { object, offset }
            | Self::ContentBadOperands { object, offset }
            | Self::ContentUnbalancedQ { object, offset }
            | Self::ContentUnbalancedBt { object, offset }
            | Self::ContentUnbalancedMarked { object, offset }
            | Self::ContentSyntax { object, offset }
            | Self::ContentResourceMissing { object, offset, .. }
            | Self::InlineImageUnterminated { object, offset }
            | Self::ContentPathUnpainted { object, offset } => {
                return object.map_or(Location::NONE, |object| {
                    Location::from(Position::InStream { object, offset })
                });
            }
            Self::InvalidBox { page, .. }
            | Self::InvalidRotate { page, .. }
            | Self::ExtractLimitBlocks { page, .. }
            | Self::ExtractReadingOrderAmbiguous { page }
            | Self::ExtractTableAmbiguous { page }
            | Self::ExtractTableLimit { page, .. }
            | Self::ExtractStructTreeIgnored { page, .. }
            | Self::ExtractUntaggedContent { page, .. }
            | Self::ExtractNeedsOcr { page, .. }
            | Self::ExtractColumnOrderUncertain { page, .. } => Some(page),
            Self::InvalidPageLabel { start } => u64::try_from(start).ok(),
            _ => None,
        };
        Location {
            page_index,
            ..Location::object(self.object())
        }
    }

    /// Deduplication key: (code, object, a position — byte offset, page index or label
    /// start — and an entry key), so two different problems on one object are both kept.
    const fn key(&self) -> WarningKey {
        let position = match *self {
            Self::InvalidPageLabel { start } => Some(start as i128),
            Self::InvalidBox { page, .. }
            | Self::InvalidRotate { page, .. }
            | Self::ExtractLimitBlocks { page, .. }
            | Self::ExtractReadingOrderAmbiguous { page }
            | Self::ExtractTableAmbiguous { page }
            | Self::ExtractTableLimit { page, .. }
            | Self::ExtractStructTreeIgnored { page, .. }
            | Self::ExtractUntaggedContent { page, .. }
            | Self::ExtractNeedsOcr { page, .. }
            | Self::ExtractColumnOrderUncertain { page, .. } => Some(page as i128),
            Self::XrefStmIgnored { offset }
            | Self::ContentUnknownOperator { offset, .. }
            | Self::ContentBadOperands { offset, .. }
            | Self::ContentUnbalancedQ { offset, .. }
            | Self::ContentUnbalancedBt { offset, .. }
            | Self::ContentUnbalancedMarked { offset, .. }
            | Self::ContentSyntax { offset, .. }
            | Self::ContentResourceMissing { offset, .. }
            | Self::InlineImageUnterminated { offset, .. }
            | Self::ContentPathUnpainted { offset, .. }
            | Self::XmpInvalid {
                offset: Some(offset), ..
            } => Some(offset as i128),
            _ => None,
        };
        let detail = match *self {
            Self::InvalidBox { key, .. } | Self::InvalidDate { key, .. } | Self::InvalidEntry { key, .. } => Some(key),
            Self::ContentResourceMissing { category, .. } => Some(category),
            Self::XmpInvalid { reason, .. } | Self::XmpRepaired { reason, .. } => Some(reason),
            _ => None,
        };
        (self.code(), self.object(), position, detail)
    }
}

type WarningKey = (&'static str, Option<u32>, Option<i128>, Option<&'static str>);

/// The warnings a document has raised so far: deduplicated by (code, object) and capped at
/// [`Limits::max_warnings`] (soft limit). Raising is O(log n): resolving a stale reference
/// raises on every call, so dedup must not scan the list.
#[derive(Debug, Clone, Default)]
pub(crate) struct WarningLog {
    list: Vec<Warning>,
    seen: BTreeSet<WarningKey>,
    truncated: bool,
}

impl WarningLog {
    /// Records `warning`, or fails with [`Error::Strict`] in strict mode.
    pub(crate) fn raise(&mut self, warning: Warning, limits: &Limits, strict: bool) -> Result<()> {
        if strict {
            return Err(Error::Strict { warning });
        }
        if self.truncated || !self.seen.insert(warning.key()) {
            return Ok(());
        }
        if self.list.len() >= limits.max_warnings() {
            self.truncated = true;
            self.list.push(Warning::WarningsTruncated);
        } else {
            self.list.push(warning);
        }
        Ok(())
    }

    pub(crate) fn list(&self) -> &[Warning] {
        &self.list
    }
}

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

    /// One value of every variant. The exhaustive match makes a new variant a compile error
    /// here until it is added to the samples (and to [`Warning::CODES`]).
    #[expect(clippy::too_many_lines, reason = "one sample per variant, then the exhaustive match")]
    fn samples() -> Vec<Warning> {
        let all = vec![
            Warning::MissingHeader,
            Warning::XrefRepaired,
            Warning::XrefStmIgnored { offset: 1 },
            Warning::StreamLengthRecovered { object: 1 },
            Warning::DictionaryKeySkipped { object: None },
            Warning::StaleGeneration {
                object: 1,
                generation: 1,
            },
            Warning::PageTreeNodeSkipped { object: None },
            Warning::PageCountMismatch {
                object: None,
                declared: 1,
                walked: 0,
            },
            Warning::FlateTruncated { object: None },
            Warning::FilterCharactersSkipped { object: None },
            Warning::ObjStmIndexMismatch { object: 1 },
            Warning::ObjectNumberOutOfRange { object: 1 },
            Warning::AesPaddingInvalid { object: 1 },
            Warning::PermsMismatch,
            Warning::WarningsTruncated,
            Warning::InvalidBox {
                object: None,
                page: 0,
                key: "MediaBox",
            },
            Warning::InvalidRotate { object: None, page: 0 },
            Warning::NameTreeNodeSkipped { object: None },
            Warning::OutlineCycle { object: 1 },
            Warning::OutlineItemSkipped { object: None },
            Warning::InvalidDate {
                object: None,
                key: "ModDate",
            },
            Warning::XmpInvalid {
                object: None,
                offset: Some(0),
                reason: "dtd",
            },
            Warning::AnnotNameDuplicate { object: None },
            Warning::XmpRepaired {
                object: None,
                reason: "undeclared-prefix",
            },
            Warning::InvalidPageLabel { start: 0 },
            Warning::InvalidEntry {
                object: None,
                key: "Info",
            },
            Warning::ContentUnknownOperator {
                object: None,
                offset: 0,
            },
            Warning::ContentBadOperands {
                object: None,
                offset: 0,
            },
            Warning::ContentUnbalancedQ {
                object: None,
                offset: 0,
            },
            Warning::ContentUnbalancedBt {
                object: None,
                offset: 0,
            },
            Warning::ContentUnbalancedMarked {
                object: None,
                offset: 0,
            },
            Warning::ContentSyntax {
                object: None,
                offset: 0,
            },
            Warning::ContentResourceMissing {
                object: None,
                offset: 0,
                category: "Font",
            },
            Warning::InlineImageUnterminated {
                object: None,
                offset: 0,
            },
            Warning::XObjectCycle { object: 1 },
            Warning::ContentPathUnpainted {
                object: None,
                offset: 0,
            },
            Warning::FontInvalid { object: None },
            Warning::CMapInvalid { object: None },
            Warning::UnmappedGlyph { object: None },
            Warning::ExtractLimitBlocks { page: 0, limit: 1 },
            Warning::ExtractReadingOrderAmbiguous { page: 0 },
            Warning::ExtractTableAmbiguous { page: 0 },
            Warning::ExtractTableLimit { page: 0, limit: 1 },
            Warning::ExtractStructTreeIgnored {
                page: 0,
                reason: "coverage",
            },
            Warning::ExtractUntaggedContent { page: 0, chars: 1 },
            Warning::ExtractNeedsOcr {
                page: 0,
                status: "needs-ocr",
            },
            Warning::ExtractColumnOrderUncertain {
                page: 0,
                reason: "narrow-gutter",
            },
        ];
        for w in &all {
            match w {
                Warning::MissingHeader
                | Warning::XrefRepaired
                | Warning::XrefStmIgnored { .. }
                | Warning::StreamLengthRecovered { .. }
                | Warning::DictionaryKeySkipped { .. }
                | Warning::StaleGeneration { .. }
                | Warning::PageTreeNodeSkipped { .. }
                | Warning::PageCountMismatch { .. }
                | Warning::FlateTruncated { .. }
                | Warning::FilterCharactersSkipped { .. }
                | Warning::ObjStmIndexMismatch { .. }
                | Warning::ObjectNumberOutOfRange { .. }
                | Warning::AesPaddingInvalid { .. }
                | Warning::PermsMismatch
                | Warning::WarningsTruncated
                | Warning::InvalidBox { .. }
                | Warning::InvalidRotate { .. }
                | Warning::NameTreeNodeSkipped { .. }
                | Warning::OutlineCycle { .. }
                | Warning::OutlineItemSkipped { .. }
                | Warning::InvalidDate { .. }
                | Warning::XmpInvalid { .. }
                | Warning::AnnotNameDuplicate { .. }
                | Warning::XmpRepaired { .. }
                | Warning::InvalidPageLabel { .. }
                | Warning::InvalidEntry { .. }
                | Warning::ContentUnknownOperator { .. }
                | Warning::ContentBadOperands { .. }
                | Warning::ContentUnbalancedQ { .. }
                | Warning::ContentUnbalancedBt { .. }
                | Warning::ContentUnbalancedMarked { .. }
                | Warning::ContentSyntax { .. }
                | Warning::ContentResourceMissing { .. }
                | Warning::InlineImageUnterminated { .. }
                | Warning::XObjectCycle { .. }
                | Warning::ContentPathUnpainted { .. }
                | Warning::FontInvalid { .. }
                | Warning::CMapInvalid { .. }
                | Warning::UnmappedGlyph { .. }
                | Warning::ExtractLimitBlocks { .. }
                | Warning::ExtractReadingOrderAmbiguous { .. }
                | Warning::ExtractTableAmbiguous { .. }
                | Warning::ExtractTableLimit { .. }
                | Warning::ExtractStructTreeIgnored { .. }
                | Warning::ExtractUntaggedContent { .. }
                | Warning::ExtractNeedsOcr { .. }
                | Warning::ExtractColumnOrderUncertain { .. } => {}
            }
        }
        all
    }

    #[test]
    fn codes_lists_the_code_of_every_variant_in_order() {
        let codes: Vec<_> = samples().iter().map(Warning::code).collect();
        assert_eq!(codes, Warning::CODES);
    }

    #[test]
    fn every_variant_has_the_kind_codes_json_lists() {
        crate::test_codes::assert_kinds_match(samples().iter().map(|w| (w.code(), w.kind().as_str())));
    }

    #[test]
    fn location_names_the_object_and_the_page_index() {
        let warning = Warning::InvalidRotate {
            object: Some(3),
            page: 2,
        };
        assert_eq!(
            warning.location(),
            Location {
                object: Some(3),
                page_index: Some(2),
                ..Location::NONE
            }
        );
    }

    #[test]
    fn location_of_a_content_warning_is_its_object_and_stream_offset() {
        let warning = Warning::ContentPathUnpainted {
            object: Some(5),
            offset: 40,
        };
        assert_eq!(
            warning.location(),
            Location {
                object: Some(5),
                stream_offset: Some(40),
                ..Location::NONE
            }
        );
    }

    #[test]
    fn location_of_a_content_warning_without_an_object_is_empty() {
        let warning = Warning::ContentSyntax {
            object: None,
            offset: 40,
        };
        assert_eq!(warning.location(), Location::NONE);
    }

    #[test]
    fn location_of_an_ignored_xref_stream_is_a_file_offset() {
        assert_eq!(Warning::XrefStmIgnored { offset: 9 }.location().offset, Some(9));
    }

    #[test]
    fn raise_deduplicates_by_code_and_object() {
        let mut log = WarningLog::default();
        let limits = Limits::default();
        for _ in 0..3 {
            log.raise(Warning::StreamLengthRecovered { object: 4 }, &limits, false)
                .unwrap();
        }
        assert_eq!(log.list(), [Warning::StreamLengthRecovered { object: 4 }]);
    }

    #[test]
    fn raise_keeps_two_problems_on_one_object_apart() {
        let mut log = WarningLog::default();
        let limits = Limits::default();
        for key in ["MediaBox", "CropBox"] {
            let warning = Warning::InvalidBox {
                object: Some(3),
                page: 0,
                key,
            };
            log.raise(warning, &limits, false).unwrap();
        }
        assert_eq!(log.list().len(), 2);
    }

    #[test]
    fn raise_keeps_at_most_max_warnings_then_one_truncation_marker() {
        let mut log = WarningLog::default();
        let limits = Limits::default().with_max_warnings(2);
        for object in 0..5 {
            log.raise(Warning::ObjStmIndexMismatch { object }, &limits, false)
                .unwrap();
        }
        assert_eq!(
            log.list(),
            [
                Warning::ObjStmIndexMismatch { object: 0 },
                Warning::ObjStmIndexMismatch { object: 1 },
                Warning::WarningsTruncated
            ]
        );
    }

    #[test]
    fn raise_in_strict_mode_is_an_error() {
        let mut log = WarningLog::default();
        assert_eq!(
            log.raise(Warning::XrefRepaired, &Limits::default(), true),
            Err(Error::Strict {
                warning: Warning::XrefRepaired
            })
        );
    }
}