laminapdf-syntax 0.2.0-alpha.2

PDF syntax layer: object model, serialization, lexer, parser and stream filters (pure, bytes in / bytes out).
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
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
// @generated by cargo xtask gen codes. DO NOT EDIT.
//! Every error and warning code the Rust crates and the WASM bindings raise, from
//! `fixtures/codes.json` (ADR 0026 §3): kind, summary, hint and `docsUrl` per code.
//! `cargo xtask check docs` fails when this file is stale.
#![allow(
    clippy::too_many_lines,
    clippy::match_same_arms,
    clippy::doc_markdown,
    reason = "generated: one match arm per code; summaries are codes.json text"
)]

use crate::ErrorKind;

/// The base of every `docsUrl` (ADR 0026 §6): `DOCS_URL_BASE` + code + `DOCS_URL_SUFFIX`.
pub const DOCS_URL_BASE: &str = "https://github.com/laudebugs/laminapdf/blob/main/docs/errors/";

/// The suffix of every `docsUrl` (ADR 0026 §6).
pub const DOCS_URL_SUFFIX: &str = ".md";

/// Every error code lamina's Rust crates and its WASM binding raise (the codes only
/// `@laminapdf/sdk` raises are not here), in `codes.json` order.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum ErrorCode {
    /// `not-pdf`: the input does not look like a PDF at all.
    NotPdf,
    /// `missing-root`: no document catalog (/Root) was found, even after repair.
    MissingRoot,
    /// `reference-cycle`: a reference chain or the page tree loops back on itself.
    ReferenceCycle,
    /// `limit-exceeded`: a hard Limits value was exceeded.
    LimitExceeded,
    /// `strict`: strict mode refused something the tolerant reader would have repaired.
    Strict,
    /// `data-pending`: the ByteSource has not fetched the byte ranges the call needs yet.
    DataPending,
    /// `source`: the ByteSource failed to read.
    Source,
    /// `type`: an object had a different type than the structure requires.
    Type,
    /// `invalid-structure`: an object stream, xref section or filter parameter was malformed.
    InvalidStructure,
    /// `unset-object`: a writer object number was reserved but never given a value.
    UnsetObject,
    /// `repaired-base`: an incremental update was requested for a document whose xref needed repair.
    RepairedBase,
    /// `encrypted-base`: a save of an encrypted document was requested.
    EncryptedBase,
    /// `password-required`: the document is encrypted with a user password and none was given.
    PasswordRequired,
    /// `wrong-password`: the given password is neither the user nor the owner password.
    WrongPassword,
    /// `unsupported-security-handler`: the document uses a security handler Lamina PDF cannot decrypt.
    UnsupportedSecurityHandler,
    /// `unexpected-eof`: the input ended before a complete token or object was read.
    UnexpectedEof,
    /// `syntax`: a token or structure did not match the PDF grammar.
    Syntax,
    /// `unsupported-filter`: a stream uses a filter Lamina PDF does not implement.
    UnsupportedFilter,
    /// `decompress`: compressed stream data was corrupt.
    Decompress,
    /// `nested-transaction`: a transaction was started, or undo or redo called, while one is open.
    NestedTransaction,
    /// `no-transaction`: apply, commit or rollback was called without an open transaction.
    NoTransaction,
    /// `unknown-page`: an op names a page the document does not have.
    UnknownPage,
    /// `direct-page`: the page is a direct dictionary, which ops cannot edit yet.
    DirectPage,
    /// `unsupported-version`: an op log has a schema version this reader does not know.
    UnsupportedVersion,
    /// `invalid-op-log`: an op log does not parse: an unknown op or field, a bad value, or not JSON.
    InvalidOpLog,
    /// `saved-not-rebased`: the document was saved to a sink Lamina PDF cannot read back and waits for rebase.
    SavedNotRebased,
    /// `no-pending-save`: rebase was called without a save waiting for it.
    NoPendingSave,
    /// `sink`: the sink failed to take the bytes or could not give them back.
    Sink,
    /// `not-rebased`: the output was written, but rebasing the document onto it failed.
    NotRebased,
    /// `sink-not-empty`: the sink already held bytes before the save started.
    SinkNotEmpty,
    /// `would-invalidate-signatures`: the save would break one or more signatures.
    WouldInvalidateSignatures,
    /// `requires-rewrite`: an incremental save was requested but only a full rewrite is safe.
    RequiresRewrite,
    /// `invalid-font`: font bytes could not be read as a font.
    InvalidFont,
    /// `collection-index`: a font collection member past the end of the collection was asked for.
    CollectionIndex,
    /// `unknown-axis`: an instance was asked for on a variation axis the font does not have.
    UnknownAxis,
    /// `font-not-embeddable`: the font's OS/2 fsType forbids embedding.
    FontNotEmbeddable,
    /// `missing-glyph`: the font has no glyph for a character of the text.
    MissingGlyph,
    /// `glyph-out-of-range`: a glyph ID at or past the font's glyph count was used.
    GlyphOutOfRange,
    /// `unknown-font`: a FontKey was used with a registry that did not hand it out.
    UnknownFont,
    /// `subset-failed`: subsetting a font failed.
    SubsetFailed,
    /// `invalid-axis-value`: a variation axis value was NaN or infinite.
    InvalidAxisValue,
    /// `wrong-document`: finish_fonts was given a document the registry did not reserve its fonts in.
    WrongDocument,
    /// `invalid-feature`: an OpenType feature setting did not parse.
    InvalidFeature,
    /// `invalid-text-range`: a byte range was out of bounds or not on character boundaries of the text.
    InvalidTextRange,
    /// `unsupported-layout-option`: a layout option that is not implemented yet was asked for.
    UnsupportedLayoutOption,
    /// `font-mismatch`: a shaped run was given with a font key for a different font than it was shaped with.
    FontMismatch,
    /// `encoding-full`: a standard 14 font has no free one-byte code left for another glyph.
    EncodingFull,
    /// `font-not-shapable`: a standard 14 font was given to shaping or layout, which need a font program.
    FontNotShapable,
    /// `invalid-image`: image bytes are not a readable image of the format they were given as.
    InvalidImage,
    /// `unsupported-image`: the image uses a feature that PDF or Lamina PDF does not support.
    UnsupportedImage,
    /// `image-too-large`: the image needs more memory than the builder allows (a decoded PNG over 256 MiB, or raw dimensions whose size overflows).
    ImageTooLarge,
    /// `image-data-length`: raw image samples are not width x height x channels bytes long.
    ImageDataLength,
    /// `invalid-icc-profile`: the bytes are not a usable ICC profile.
    InvalidIccProfile,
    /// `color-components`: a colour has the wrong number of components for its colour space.
    ColorComponents,
    /// `invalid-color`: a colour string is not of the form #rgb or #rrggbb.
    InvalidColor,
    /// `invalid-geometry`: a page size, box, /UserUnit, drawing value (coordinate, matrix, line width, dash, miter limit) or image size is not usable.
    InvalidGeometry,
    /// `text-overflow`: a text box's lines don't all fit its height and its options asked for an error.
    TextOverflow,
    /// `page-index-out-of-range`: a link, outline item or destination names a page index the document doesn't have.
    PageIndexOutOfRange,
    /// `unknown-destination`: a link or outline item names a destination that was never defined.
    UnknownDestination,
    /// `invalid-page-labels`: page label ranges that don't start at page 0, don't increase, start past the last page or number from 0.
    InvalidPageLabels,
    /// `profile-version-conflict`: the PDF version asked for is one the profile doesn't allow (PDF/UA-1, PDF/A-2 and PDF/A-3 are based on PDF 1.7).
    ProfileVersionConflict,
    /// `missing-title`: PDF/UA-1 needs a document title, and the metadata gives none.
    MissingTitle,
    /// `missing-lang`: PDF/UA-1 needs the document's natural language, and none was set.
    MissingLang,
    /// `missing-alt-text`: a Figure or Formula has no alternate text (/Alt or /ActualText), which PDF/UA-1 requires.
    MissingAltText,
    /// `untagged-content`: content was drawn outside every structure element and artifact, which PDF/UA-1 forbids.
    UntaggedContent,
    /// `heading-level-skipped`: a heading skips a level (the first is not H1, or an H3 follows an H1), which PDF/UA-1 forbids.
    HeadingLevelSkipped,
    /// `unnumbered-heading-misused`: an unnumbered H heading shares its parent with another H, or the document also uses H1-H6, which PDF/UA-1 forbids.
    UnnumberedHeadingMisused,
    /// `invalid-structure-nesting`: a table or list element sits in a parent its type doesn't allow (a TD outside a TR, a P directly in a Table).
    InvalidStructureNesting,
    /// `link-without-structure`: a link annotation has no Link structure element (it was drawn inside an artifact), which PDF/UA-1 forbids.
    LinkWithoutStructure,
    /// `link-without-contents`: a link annotation has no description (/Contents), which PDF/UA-1 requires.
    LinkWithoutContents,
    /// `font-not-embedded`: a standard 14 font, which is never embedded, was used under a profile that needs every font embedded.
    FontNotEmbedded,
    /// `glyph-without-unicode`: a glyph was drawn without a Unicode value, which PDF/A-2u and PDF/UA-1 forbid.
    GlyphWithoutUnicode,
    /// `device-color-without-output-intent`: a DeviceCMYK colour or image was used, but the PDF/A output intent is sRGB.
    DeviceColorWithoutOutputIntent,
    /// `embedded-file-forbidden`: PDF/A-2 doesn't allow attached files that aren't PDF/A themselves.
    EmbeddedFileForbidden,
    /// `embedded-file-without-mime-type`: an attached file has no MIME type, which every PDF/A profile requires.
    EmbeddedFileWithoutMimeType,
    /// `render-too-large`: the requested tile is larger than the render limits allow; nothing was allocated.
    RenderTooLarge,
    /// `render-failed`: the render engine could not open the document or draw the page.
    RenderFailed,
    /// `render-backend-unavailable`: the render engine is not available: its library or module could not be loaded.
    RenderBackendUnavailable,
    /// `cancelled`: a CancelToken stopped the work; the job is finished and returned no partial result.
    Cancelled,
    /// `job-finished`: a job was stepped after it had finished, failed or been cancelled.
    JobFinished,
    /// `document-changed`: the document a job was created for changed (an edit, undo, redo, save or rebase) or a different document was passed to step.
    DocumentChanged,
    /// `builder-finished`: a builder or one of its pages was used after it finished.
    BuilderFinished,
    /// `invalid-argument`: a value passed to a binding does not have the shape its type declares.
    InvalidArgument,
    /// `source-budget-exceeded`: a sparse source was given more bytes than its byte budget allows.
    SourceBudgetExceeded,
    /// `unknown-option`: an options record passed to a binding has a key Lamina PDF does not know.
    UnknownOption,
}

impl ErrorCode {
    /// Every variant, in `codes.json` order.
    pub const ALL: &'static [Self] = &[
        Self::NotPdf,
        Self::MissingRoot,
        Self::ReferenceCycle,
        Self::LimitExceeded,
        Self::Strict,
        Self::DataPending,
        Self::Source,
        Self::Type,
        Self::InvalidStructure,
        Self::UnsetObject,
        Self::RepairedBase,
        Self::EncryptedBase,
        Self::PasswordRequired,
        Self::WrongPassword,
        Self::UnsupportedSecurityHandler,
        Self::UnexpectedEof,
        Self::Syntax,
        Self::UnsupportedFilter,
        Self::Decompress,
        Self::NestedTransaction,
        Self::NoTransaction,
        Self::UnknownPage,
        Self::DirectPage,
        Self::UnsupportedVersion,
        Self::InvalidOpLog,
        Self::SavedNotRebased,
        Self::NoPendingSave,
        Self::Sink,
        Self::NotRebased,
        Self::SinkNotEmpty,
        Self::WouldInvalidateSignatures,
        Self::RequiresRewrite,
        Self::InvalidFont,
        Self::CollectionIndex,
        Self::UnknownAxis,
        Self::FontNotEmbeddable,
        Self::MissingGlyph,
        Self::GlyphOutOfRange,
        Self::UnknownFont,
        Self::SubsetFailed,
        Self::InvalidAxisValue,
        Self::WrongDocument,
        Self::InvalidFeature,
        Self::InvalidTextRange,
        Self::UnsupportedLayoutOption,
        Self::FontMismatch,
        Self::EncodingFull,
        Self::FontNotShapable,
        Self::InvalidImage,
        Self::UnsupportedImage,
        Self::ImageTooLarge,
        Self::ImageDataLength,
        Self::InvalidIccProfile,
        Self::ColorComponents,
        Self::InvalidColor,
        Self::InvalidGeometry,
        Self::TextOverflow,
        Self::PageIndexOutOfRange,
        Self::UnknownDestination,
        Self::InvalidPageLabels,
        Self::ProfileVersionConflict,
        Self::MissingTitle,
        Self::MissingLang,
        Self::MissingAltText,
        Self::UntaggedContent,
        Self::HeadingLevelSkipped,
        Self::UnnumberedHeadingMisused,
        Self::InvalidStructureNesting,
        Self::LinkWithoutStructure,
        Self::LinkWithoutContents,
        Self::FontNotEmbedded,
        Self::GlyphWithoutUnicode,
        Self::DeviceColorWithoutOutputIntent,
        Self::EmbeddedFileForbidden,
        Self::EmbeddedFileWithoutMimeType,
        Self::RenderTooLarge,
        Self::RenderFailed,
        Self::RenderBackendUnavailable,
        Self::Cancelled,
        Self::JobFinished,
        Self::DocumentChanged,
        Self::BuilderFinished,
        Self::InvalidArgument,
        Self::SourceBudgetExceeded,
        Self::UnknownOption,
    ];

    /// The code with this name, if there is one.
    #[must_use]
    pub const fn from_code(code: &str) -> Option<Self> {
        Some(match code.as_bytes() {
            b"not-pdf" => Self::NotPdf,
            b"missing-root" => Self::MissingRoot,
            b"reference-cycle" => Self::ReferenceCycle,
            b"limit-exceeded" => Self::LimitExceeded,
            b"strict" => Self::Strict,
            b"data-pending" => Self::DataPending,
            b"source" => Self::Source,
            b"type" => Self::Type,
            b"invalid-structure" => Self::InvalidStructure,
            b"unset-object" => Self::UnsetObject,
            b"repaired-base" => Self::RepairedBase,
            b"encrypted-base" => Self::EncryptedBase,
            b"password-required" => Self::PasswordRequired,
            b"wrong-password" => Self::WrongPassword,
            b"unsupported-security-handler" => Self::UnsupportedSecurityHandler,
            b"unexpected-eof" => Self::UnexpectedEof,
            b"syntax" => Self::Syntax,
            b"unsupported-filter" => Self::UnsupportedFilter,
            b"decompress" => Self::Decompress,
            b"nested-transaction" => Self::NestedTransaction,
            b"no-transaction" => Self::NoTransaction,
            b"unknown-page" => Self::UnknownPage,
            b"direct-page" => Self::DirectPage,
            b"unsupported-version" => Self::UnsupportedVersion,
            b"invalid-op-log" => Self::InvalidOpLog,
            b"saved-not-rebased" => Self::SavedNotRebased,
            b"no-pending-save" => Self::NoPendingSave,
            b"sink" => Self::Sink,
            b"not-rebased" => Self::NotRebased,
            b"sink-not-empty" => Self::SinkNotEmpty,
            b"would-invalidate-signatures" => Self::WouldInvalidateSignatures,
            b"requires-rewrite" => Self::RequiresRewrite,
            b"invalid-font" => Self::InvalidFont,
            b"collection-index" => Self::CollectionIndex,
            b"unknown-axis" => Self::UnknownAxis,
            b"font-not-embeddable" => Self::FontNotEmbeddable,
            b"missing-glyph" => Self::MissingGlyph,
            b"glyph-out-of-range" => Self::GlyphOutOfRange,
            b"unknown-font" => Self::UnknownFont,
            b"subset-failed" => Self::SubsetFailed,
            b"invalid-axis-value" => Self::InvalidAxisValue,
            b"wrong-document" => Self::WrongDocument,
            b"invalid-feature" => Self::InvalidFeature,
            b"invalid-text-range" => Self::InvalidTextRange,
            b"unsupported-layout-option" => Self::UnsupportedLayoutOption,
            b"font-mismatch" => Self::FontMismatch,
            b"encoding-full" => Self::EncodingFull,
            b"font-not-shapable" => Self::FontNotShapable,
            b"invalid-image" => Self::InvalidImage,
            b"unsupported-image" => Self::UnsupportedImage,
            b"image-too-large" => Self::ImageTooLarge,
            b"image-data-length" => Self::ImageDataLength,
            b"invalid-icc-profile" => Self::InvalidIccProfile,
            b"color-components" => Self::ColorComponents,
            b"invalid-color" => Self::InvalidColor,
            b"invalid-geometry" => Self::InvalidGeometry,
            b"text-overflow" => Self::TextOverflow,
            b"page-index-out-of-range" => Self::PageIndexOutOfRange,
            b"unknown-destination" => Self::UnknownDestination,
            b"invalid-page-labels" => Self::InvalidPageLabels,
            b"profile-version-conflict" => Self::ProfileVersionConflict,
            b"missing-title" => Self::MissingTitle,
            b"missing-lang" => Self::MissingLang,
            b"missing-alt-text" => Self::MissingAltText,
            b"untagged-content" => Self::UntaggedContent,
            b"heading-level-skipped" => Self::HeadingLevelSkipped,
            b"unnumbered-heading-misused" => Self::UnnumberedHeadingMisused,
            b"invalid-structure-nesting" => Self::InvalidStructureNesting,
            b"link-without-structure" => Self::LinkWithoutStructure,
            b"link-without-contents" => Self::LinkWithoutContents,
            b"font-not-embedded" => Self::FontNotEmbedded,
            b"glyph-without-unicode" => Self::GlyphWithoutUnicode,
            b"device-color-without-output-intent" => Self::DeviceColorWithoutOutputIntent,
            b"embedded-file-forbidden" => Self::EmbeddedFileForbidden,
            b"embedded-file-without-mime-type" => Self::EmbeddedFileWithoutMimeType,
            b"render-too-large" => Self::RenderTooLarge,
            b"render-failed" => Self::RenderFailed,
            b"render-backend-unavailable" => Self::RenderBackendUnavailable,
            b"cancelled" => Self::Cancelled,
            b"job-finished" => Self::JobFinished,
            b"document-changed" => Self::DocumentChanged,
            b"builder-finished" => Self::BuilderFinished,
            b"invalid-argument" => Self::InvalidArgument,
            b"source-budget-exceeded" => Self::SourceBudgetExceeded,
            b"unknown-option" => Self::UnknownOption,
            _ => return None,
        })
    }

    /// The kebab-case code.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::NotPdf => "not-pdf",
            Self::MissingRoot => "missing-root",
            Self::ReferenceCycle => "reference-cycle",
            Self::LimitExceeded => "limit-exceeded",
            Self::Strict => "strict",
            Self::DataPending => "data-pending",
            Self::Source => "source",
            Self::Type => "type",
            Self::InvalidStructure => "invalid-structure",
            Self::UnsetObject => "unset-object",
            Self::RepairedBase => "repaired-base",
            Self::EncryptedBase => "encrypted-base",
            Self::PasswordRequired => "password-required",
            Self::WrongPassword => "wrong-password",
            Self::UnsupportedSecurityHandler => "unsupported-security-handler",
            Self::UnexpectedEof => "unexpected-eof",
            Self::Syntax => "syntax",
            Self::UnsupportedFilter => "unsupported-filter",
            Self::Decompress => "decompress",
            Self::NestedTransaction => "nested-transaction",
            Self::NoTransaction => "no-transaction",
            Self::UnknownPage => "unknown-page",
            Self::DirectPage => "direct-page",
            Self::UnsupportedVersion => "unsupported-version",
            Self::InvalidOpLog => "invalid-op-log",
            Self::SavedNotRebased => "saved-not-rebased",
            Self::NoPendingSave => "no-pending-save",
            Self::Sink => "sink",
            Self::NotRebased => "not-rebased",
            Self::SinkNotEmpty => "sink-not-empty",
            Self::WouldInvalidateSignatures => "would-invalidate-signatures",
            Self::RequiresRewrite => "requires-rewrite",
            Self::InvalidFont => "invalid-font",
            Self::CollectionIndex => "collection-index",
            Self::UnknownAxis => "unknown-axis",
            Self::FontNotEmbeddable => "font-not-embeddable",
            Self::MissingGlyph => "missing-glyph",
            Self::GlyphOutOfRange => "glyph-out-of-range",
            Self::UnknownFont => "unknown-font",
            Self::SubsetFailed => "subset-failed",
            Self::InvalidAxisValue => "invalid-axis-value",
            Self::WrongDocument => "wrong-document",
            Self::InvalidFeature => "invalid-feature",
            Self::InvalidTextRange => "invalid-text-range",
            Self::UnsupportedLayoutOption => "unsupported-layout-option",
            Self::FontMismatch => "font-mismatch",
            Self::EncodingFull => "encoding-full",
            Self::FontNotShapable => "font-not-shapable",
            Self::InvalidImage => "invalid-image",
            Self::UnsupportedImage => "unsupported-image",
            Self::ImageTooLarge => "image-too-large",
            Self::ImageDataLength => "image-data-length",
            Self::InvalidIccProfile => "invalid-icc-profile",
            Self::ColorComponents => "color-components",
            Self::InvalidColor => "invalid-color",
            Self::InvalidGeometry => "invalid-geometry",
            Self::TextOverflow => "text-overflow",
            Self::PageIndexOutOfRange => "page-index-out-of-range",
            Self::UnknownDestination => "unknown-destination",
            Self::InvalidPageLabels => "invalid-page-labels",
            Self::ProfileVersionConflict => "profile-version-conflict",
            Self::MissingTitle => "missing-title",
            Self::MissingLang => "missing-lang",
            Self::MissingAltText => "missing-alt-text",
            Self::UntaggedContent => "untagged-content",
            Self::HeadingLevelSkipped => "heading-level-skipped",
            Self::UnnumberedHeadingMisused => "unnumbered-heading-misused",
            Self::InvalidStructureNesting => "invalid-structure-nesting",
            Self::LinkWithoutStructure => "link-without-structure",
            Self::LinkWithoutContents => "link-without-contents",
            Self::FontNotEmbedded => "font-not-embedded",
            Self::GlyphWithoutUnicode => "glyph-without-unicode",
            Self::DeviceColorWithoutOutputIntent => "device-color-without-output-intent",
            Self::EmbeddedFileForbidden => "embedded-file-forbidden",
            Self::EmbeddedFileWithoutMimeType => "embedded-file-without-mime-type",
            Self::RenderTooLarge => "render-too-large",
            Self::RenderFailed => "render-failed",
            Self::RenderBackendUnavailable => "render-backend-unavailable",
            Self::Cancelled => "cancelled",
            Self::JobFinished => "job-finished",
            Self::DocumentChanged => "document-changed",
            Self::BuilderFinished => "builder-finished",
            Self::InvalidArgument => "invalid-argument",
            Self::SourceBudgetExceeded => "source-budget-exceeded",
            Self::UnknownOption => "unknown-option",
        }
    }

    /// The kind (ADR 0026 §2).
    #[must_use]
    pub const fn kind(self) -> ErrorKind {
        match self {
            Self::NotPdf => ErrorKind::Input,
            Self::MissingRoot => ErrorKind::Input,
            Self::ReferenceCycle => ErrorKind::Input,
            Self::LimitExceeded => ErrorKind::Limit,
            Self::Strict => ErrorKind::Input,
            Self::DataPending => ErrorKind::State,
            Self::Source => ErrorKind::Io,
            Self::Type => ErrorKind::Input,
            Self::InvalidStructure => ErrorKind::Input,
            Self::UnsetObject => ErrorKind::Internal,
            Self::RepairedBase => ErrorKind::State,
            Self::EncryptedBase => ErrorKind::Unsupported,
            Self::PasswordRequired => ErrorKind::Security,
            Self::WrongPassword => ErrorKind::Security,
            Self::UnsupportedSecurityHandler => ErrorKind::Unsupported,
            Self::UnexpectedEof => ErrorKind::Input,
            Self::Syntax => ErrorKind::Input,
            Self::UnsupportedFilter => ErrorKind::Unsupported,
            Self::Decompress => ErrorKind::Input,
            Self::NestedTransaction => ErrorKind::State,
            Self::NoTransaction => ErrorKind::State,
            Self::UnknownPage => ErrorKind::Usage,
            Self::DirectPage => ErrorKind::Unsupported,
            Self::UnsupportedVersion => ErrorKind::Unsupported,
            Self::InvalidOpLog => ErrorKind::Input,
            Self::SavedNotRebased => ErrorKind::State,
            Self::NoPendingSave => ErrorKind::State,
            Self::Sink => ErrorKind::Io,
            Self::NotRebased => ErrorKind::State,
            Self::SinkNotEmpty => ErrorKind::Usage,
            Self::WouldInvalidateSignatures => ErrorKind::Security,
            Self::RequiresRewrite => ErrorKind::State,
            Self::InvalidFont => ErrorKind::Input,
            Self::CollectionIndex => ErrorKind::Usage,
            Self::UnknownAxis => ErrorKind::Usage,
            Self::FontNotEmbeddable => ErrorKind::Usage,
            Self::MissingGlyph => ErrorKind::Input,
            Self::GlyphOutOfRange => ErrorKind::Usage,
            Self::UnknownFont => ErrorKind::Usage,
            Self::SubsetFailed => ErrorKind::Unsupported,
            Self::InvalidAxisValue => ErrorKind::Usage,
            Self::WrongDocument => ErrorKind::Usage,
            Self::InvalidFeature => ErrorKind::Usage,
            Self::InvalidTextRange => ErrorKind::Usage,
            Self::UnsupportedLayoutOption => ErrorKind::Unsupported,
            Self::FontMismatch => ErrorKind::Usage,
            Self::EncodingFull => ErrorKind::Limit,
            Self::FontNotShapable => ErrorKind::Unsupported,
            Self::InvalidImage => ErrorKind::Input,
            Self::UnsupportedImage => ErrorKind::Unsupported,
            Self::ImageTooLarge => ErrorKind::Limit,
            Self::ImageDataLength => ErrorKind::Usage,
            Self::InvalidIccProfile => ErrorKind::Input,
            Self::ColorComponents => ErrorKind::Usage,
            Self::InvalidColor => ErrorKind::Usage,
            Self::InvalidGeometry => ErrorKind::Usage,
            Self::TextOverflow => ErrorKind::Usage,
            Self::PageIndexOutOfRange => ErrorKind::Usage,
            Self::UnknownDestination => ErrorKind::Usage,
            Self::InvalidPageLabels => ErrorKind::Usage,
            Self::ProfileVersionConflict => ErrorKind::Usage,
            Self::MissingTitle => ErrorKind::Usage,
            Self::MissingLang => ErrorKind::Usage,
            Self::MissingAltText => ErrorKind::Usage,
            Self::UntaggedContent => ErrorKind::Usage,
            Self::HeadingLevelSkipped => ErrorKind::Usage,
            Self::UnnumberedHeadingMisused => ErrorKind::Usage,
            Self::InvalidStructureNesting => ErrorKind::Usage,
            Self::LinkWithoutStructure => ErrorKind::Usage,
            Self::LinkWithoutContents => ErrorKind::Usage,
            Self::FontNotEmbedded => ErrorKind::Usage,
            Self::GlyphWithoutUnicode => ErrorKind::Usage,
            Self::DeviceColorWithoutOutputIntent => ErrorKind::Usage,
            Self::EmbeddedFileForbidden => ErrorKind::Usage,
            Self::EmbeddedFileWithoutMimeType => ErrorKind::Usage,
            Self::RenderTooLarge => ErrorKind::Limit,
            Self::RenderFailed => ErrorKind::Input,
            Self::RenderBackendUnavailable => ErrorKind::Io,
            Self::Cancelled => ErrorKind::Cancelled,
            Self::JobFinished => ErrorKind::State,
            Self::DocumentChanged => ErrorKind::State,
            Self::BuilderFinished => ErrorKind::State,
            Self::InvalidArgument => ErrorKind::Usage,
            Self::SourceBudgetExceeded => ErrorKind::Limit,
            Self::UnknownOption => ErrorKind::Usage,
        }
    }

    /// One lowercase sentence: what happened.
    #[must_use]
    pub const fn summary(self) -> &'static str {
        match self {
            Self::NotPdf => "the input does not look like a PDF at all",
            Self::MissingRoot => "no document catalog (/Root) was found, even after repair",
            Self::ReferenceCycle => "a reference chain or the page tree loops back on itself",
            Self::LimitExceeded => "a hard Limits value was exceeded",
            Self::Strict => "strict mode refused something the tolerant reader would have repaired",
            Self::DataPending => "the ByteSource has not fetched the byte ranges the call needs yet",
            Self::Source => "the ByteSource failed to read",
            Self::Type => "an object had a different type than the structure requires",
            Self::InvalidStructure => "an object stream, xref section or filter parameter was malformed",
            Self::UnsetObject => "a writer object number was reserved but never given a value",
            Self::RepairedBase => "an incremental update was requested for a document whose xref needed repair",
            Self::EncryptedBase => "a save of an encrypted document was requested",
            Self::PasswordRequired => "the document is encrypted with a user password and none was given",
            Self::WrongPassword => "the given password is neither the user nor the owner password",
            Self::UnsupportedSecurityHandler => "the document uses a security handler Lamina PDF cannot decrypt",
            Self::UnexpectedEof => "the input ended before a complete token or object was read",
            Self::Syntax => "a token or structure did not match the PDF grammar",
            Self::UnsupportedFilter => "a stream uses a filter Lamina PDF does not implement",
            Self::Decompress => "compressed stream data was corrupt",
            Self::NestedTransaction => "a transaction was started, or undo or redo called, while one is open",
            Self::NoTransaction => "apply, commit or rollback was called without an open transaction",
            Self::UnknownPage => "an op names a page the document does not have",
            Self::DirectPage => "the page is a direct dictionary, which ops cannot edit yet",
            Self::UnsupportedVersion => "an op log has a schema version this reader does not know",
            Self::InvalidOpLog => "an op log does not parse: an unknown op or field, a bad value, or not JSON",
            Self::SavedNotRebased => "the document was saved to a sink Lamina PDF cannot read back and waits for rebase",
            Self::NoPendingSave => "rebase was called without a save waiting for it",
            Self::Sink => "the sink failed to take the bytes or could not give them back",
            Self::NotRebased => "the output was written, but rebasing the document onto it failed",
            Self::SinkNotEmpty => "the sink already held bytes before the save started",
            Self::WouldInvalidateSignatures => "the save would break one or more signatures",
            Self::RequiresRewrite => "an incremental save was requested but only a full rewrite is safe",
            Self::InvalidFont => "font bytes could not be read as a font",
            Self::CollectionIndex => "a font collection member past the end of the collection was asked for",
            Self::UnknownAxis => "an instance was asked for on a variation axis the font does not have",
            Self::FontNotEmbeddable => "the font's OS/2 fsType forbids embedding",
            Self::MissingGlyph => "the font has no glyph for a character of the text",
            Self::GlyphOutOfRange => "a glyph ID at or past the font's glyph count was used",
            Self::UnknownFont => "a FontKey was used with a registry that did not hand it out",
            Self::SubsetFailed => "subsetting a font failed",
            Self::InvalidAxisValue => "a variation axis value was NaN or infinite",
            Self::WrongDocument => "finish_fonts was given a document the registry did not reserve its fonts in",
            Self::InvalidFeature => "an OpenType feature setting did not parse",
            Self::InvalidTextRange => "a byte range was out of bounds or not on character boundaries of the text",
            Self::UnsupportedLayoutOption => "a layout option that is not implemented yet was asked for",
            Self::FontMismatch => "a shaped run was given with a font key for a different font than it was shaped with",
            Self::EncodingFull => "a standard 14 font has no free one-byte code left for another glyph",
            Self::FontNotShapable => "a standard 14 font was given to shaping or layout, which need a font program",
            Self::InvalidImage => "image bytes are not a readable image of the format they were given as",
            Self::UnsupportedImage => "the image uses a feature that PDF or Lamina PDF does not support",
            Self::ImageTooLarge => "the image needs more memory than the builder allows (a decoded PNG over 256 MiB, or raw dimensions whose size overflows)",
            Self::ImageDataLength => "raw image samples are not width x height x channels bytes long",
            Self::InvalidIccProfile => "the bytes are not a usable ICC profile",
            Self::ColorComponents => "a colour has the wrong number of components for its colour space",
            Self::InvalidColor => "a colour string is not of the form #rgb or #rrggbb",
            Self::InvalidGeometry => "a page size, box, /UserUnit, drawing value (coordinate, matrix, line width, dash, miter limit) or image size is not usable",
            Self::TextOverflow => "a text box's lines don't all fit its height and its options asked for an error",
            Self::PageIndexOutOfRange => "a link, outline item or destination names a page index the document doesn't have",
            Self::UnknownDestination => "a link or outline item names a destination that was never defined",
            Self::InvalidPageLabels => "page label ranges that don't start at page 0, don't increase, start past the last page or number from 0",
            Self::ProfileVersionConflict => "the PDF version asked for is one the profile doesn't allow (PDF/UA-1, PDF/A-2 and PDF/A-3 are based on PDF 1.7)",
            Self::MissingTitle => "PDF/UA-1 needs a document title, and the metadata gives none",
            Self::MissingLang => "PDF/UA-1 needs the document's natural language, and none was set",
            Self::MissingAltText => "a Figure or Formula has no alternate text (/Alt or /ActualText), which PDF/UA-1 requires",
            Self::UntaggedContent => "content was drawn outside every structure element and artifact, which PDF/UA-1 forbids",
            Self::HeadingLevelSkipped => "a heading skips a level (the first is not H1, or an H3 follows an H1), which PDF/UA-1 forbids",
            Self::UnnumberedHeadingMisused => "an unnumbered H heading shares its parent with another H, or the document also uses H1-H6, which PDF/UA-1 forbids",
            Self::InvalidStructureNesting => "a table or list element sits in a parent its type doesn't allow (a TD outside a TR, a P directly in a Table)",
            Self::LinkWithoutStructure => "a link annotation has no Link structure element (it was drawn inside an artifact), which PDF/UA-1 forbids",
            Self::LinkWithoutContents => "a link annotation has no description (/Contents), which PDF/UA-1 requires",
            Self::FontNotEmbedded => "a standard 14 font, which is never embedded, was used under a profile that needs every font embedded",
            Self::GlyphWithoutUnicode => "a glyph was drawn without a Unicode value, which PDF/A-2u and PDF/UA-1 forbid",
            Self::DeviceColorWithoutOutputIntent => "a DeviceCMYK colour or image was used, but the PDF/A output intent is sRGB",
            Self::EmbeddedFileForbidden => "PDF/A-2 doesn't allow attached files that aren't PDF/A themselves",
            Self::EmbeddedFileWithoutMimeType => "an attached file has no MIME type, which every PDF/A profile requires",
            Self::RenderTooLarge => "the requested tile is larger than the render limits allow; nothing was allocated",
            Self::RenderFailed => "the render engine could not open the document or draw the page",
            Self::RenderBackendUnavailable => "the render engine is not available: its library or module could not be loaded",
            Self::Cancelled => "a CancelToken stopped the work; the job is finished and returned no partial result",
            Self::JobFinished => "a job was stepped after it had finished, failed or been cancelled",
            Self::DocumentChanged => "the document a job was created for changed (an edit, undo, redo, save or rebase) or a different document was passed to step",
            Self::BuilderFinished => "a builder or one of its pages was used after it finished",
            Self::InvalidArgument => "a value passed to a binding does not have the shape its type declares",
            Self::SourceBudgetExceeded => "a sparse source was given more bytes than its byte budget allows",
            Self::UnknownOption => "an options record passed to a binding has a key Lamina PDF does not know",
        }
    }

    /// The hint (ADR 0026 §5), with its `{limit}`/`{option}` parameters unfilled.
    #[must_use]
    pub const fn hint(self) -> &'static str {
        match self {
            Self::NotPdf => "check that the bytes passed to open are a PDF file",
            Self::MissingRoot => "use another copy of the file: this one has no usable catalog",
            Self::ReferenceCycle => "use another copy of the file, or repair it with another tool",
            Self::LimitExceeded => "the input exceeds a safety limit; raise {limit} in Limits only if you trust the input",
            Self::Strict => "open without strict mode to read the file with repairs, or fix the file",
            Self::DataPending => "fetch the listed ranges into the source and retry the call",
            Self::Source => "retry the call, or check the source; the document stays usable",
            Self::Type => "use another copy of the file, or repair it with another tool",
            Self::InvalidStructure => "use another copy of the file, or repair it with another tool",
            Self::UnsetObject => "this is a bug in Lamina PDF: report it with the steps that led to it",
            Self::RepairedBase => "save with a full rewrite instead of an incremental update",
            Self::EncryptedBase => "saving encrypted documents is not supported yet; use another tool to decrypt or re-encrypt",
            Self::PasswordRequired => "pass the document's password in OpenOptions",
            Self::WrongPassword => "ask for the password again and retry with the correct one",
            Self::UnsupportedSecurityHandler => "use a tool that supports this encryption to decrypt the file first",
            Self::UnexpectedEof => "use a complete copy of the file: this one looks truncated",
            Self::Syntax => "use another copy of the file, or repair it with another tool",
            Self::UnsupportedFilter => "use a tool that supports the filter to read this stream",
            Self::Decompress => "use another copy of the file: this stream's data is damaged",
            Self::NestedTransaction => "commit or roll back the open transaction first, or use a savepoint inside it",
            Self::NoTransaction => "call begin first, or use transact",
            Self::UnknownPage => "use a PageId from this document's pages()",
            Self::DirectPage => "rewrite the file so that every page is an indirect object, or wait for page-structure ops",
            Self::UnsupportedVersion => "upgrade Lamina PDF to a version that reads this op log version",
            Self::InvalidOpLog => "validate the op log against the op schema; the samples in fixtures/ops show the format",
            Self::SavedNotRebased => "call rebase with the saved bytes before applying ops or saving again",
            Self::NoPendingSave => "call rebase only after a save that returned SavedNotRebased",
            Self::Sink => "check the destination and retry the save; the document is unchanged",
            Self::NotRebased => "retry rebase with the saved output carried by the error",
            Self::SinkNotEmpty => "pass an empty sink: output offsets count from the sink's first byte",
            Self::WouldInvalidateSignatures => "save with SaveMode::Auto, or ask the user and retry with SaveOptions::with_invalidate_signatures",
            Self::RequiresRewrite => "save with SaveMode::Auto or SaveMode::FullRewrite",
            Self::InvalidFont => "pass the complete bytes of a .ttf, .otf, .ttc or .otc file",
            Self::CollectionIndex => "use an index below Font::collection_len",
            Self::UnknownAxis => "check the font's axes before choosing coordinates, or use a variable font",
            Self::FontNotEmbeddable => "use another font, or register it with EmbedPolicy::Override if your licence allows embedding",
            Self::MissingGlyph => "use a font that covers the character, or split the text across fonts",
            Self::GlyphOutOfRange => "pass glyph IDs from the font you registered",
            Self::UnknownFont => "use the key returned by this registry's add",
            Self::SubsetFailed => "try another version or format of the font, and report the font if it is a common one",
            Self::InvalidAxisValue => "pass finite axis values; values outside the axis range are clamped",
            Self::WrongDocument => "use one FontRegistry per document and finish it with that document",
            Self::InvalidFeature => "write it as liga=0, -liga, smcp or aalt=2 (HarfBuzz syntax without ranges)",
            Self::InvalidTextRange => "take ranges from Lamina PDF's results (line_breaks, itemize, break_lines) and pass the same text",
            Self::UnsupportedLayoutOption => "leave the option at its default; justification comes with a later release",
            Self::FontMismatch => "pass the key of the font the run was shaped with (the font index of each line run maps to your keys)",
            Self::EncodingFull => "embed a font with Font::from_bytes, or split the text across two registrations of the standard font",
            Self::FontNotShapable => "draw standard 14 fonts with FontRegistry::encode, or shape with an embedded font",
            Self::InvalidImage => "pass the complete bytes of a JPEG or PNG file to Image::jpeg or Image::png",
            Self::UnsupportedImage => "convert it to a baseline or progressive 8-bit JPEG, or to PNG",
            Self::ImageTooLarge => "scale the image down before adding it",
            Self::ImageDataLength => "pass exactly 4 bytes (RGBA) per pixel, row by row",
            Self::InvalidIccProfile => "pass a complete ICC profile with a Gray, RGB or CMYK data colour space",
            Self::ColorComponents => "give one component per channel of the colour space (/N of the ICC profile)",
            Self::InvalidColor => "write the colour as # followed by 3 or 6 hexadecimal digits",
            Self::InvalidGeometry => "use finite coordinates, positive page sizes and /UserUnit, non-negative line widths and dashes, a miter limit of at least 1, and images of at least one pixel",
            Self::TextOverflow => "make the box taller or the text shorter, or use Overflow::Clip and read TextLayout::overflow",
            Self::PageIndexOutOfRange => "use a 0-based index below the document's page count",
            Self::UnknownDestination => "define it with Builder::destination before the build finishes, or link to a page",
            Self::InvalidPageLabels => "give ranges sorted by first page, the first at page 0, numbered from 1",
            Self::ProfileVersionConflict => "leave the version at 1.7 (the default) or lower; PDF 2.0 needs PDF/A-4 or PDF/UA-2, which Lamina PDF doesn't write yet",
            Self::MissingTitle => "set a title with Builder::metadata (Metadata::with_title)",
            Self::MissingLang => "set the language with Builder::lang, such as \"en-GB\"",
            Self::MissingAltText => "give the figure or formula a description with Tag::with_alt or Surface::figure's alt, or draw decoration as an artifact",
            Self::UntaggedContent => "draw it inside Surface::tag (real content) or Surface::artifact (decoration)",
            Self::HeadingLevelSkipped => "start with H1 and go down one level at a time",
            Self::UnnumberedHeadingMisused => "use numbered headings (H1, H2, ...) throughout, or one H per section",
            Self::InvalidStructureNesting => "nest tables as Table > TR > TH/TD and lists as L > LI > Lbl/LBody",
            Self::LinkWithoutStructure => "draw links outside artifacts, so the builder gives each one a Link element",
            Self::LinkWithoutContents => "pass a description as the link's contents",
            Self::FontNotEmbedded => "load a font file with Builder::font instead of Builder::standard_font",
            Self::GlyphWithoutUnicode => "use text whose glyphs each stand for characters, or choose PDF/A-2b, which doesn't need Unicode",
            Self::DeviceColorWithoutOutputIntent => "use RGB or gray colours, or a CMYK colour with an ICC profile (Color::icc)",
            Self::EmbeddedFileForbidden => "choose PDF/A-3b, which allows attached files of any kind",
            Self::EmbeddedFileWithoutMimeType => "pass the file's MIME type, such as text/xml or application/octet-stream",
            Self::RenderTooLarge => "request smaller tiles (256 to 512 pixels at high zoom) or raise RenderLimits if the larger bitmap is intended",
            Self::RenderFailed => "the file may be damaged or use a feature this engine can't draw; try the other backend, or report the file",
            Self::RenderBackendUnavailable => "run cargo xtask fetch-pdfium or set LAMINA_PDF_PDFIUM_DIR to the folder holding the PDFium library",
            Self::Cancelled => "nothing to do: this is the outcome the caller asked for; start a new job to try again",
            Self::JobFinished => "stop stepping a job once a step returned its result or an error; create a new job",
            Self::DocumentChanged => "pass the document the job was created from, and don't change it while the job runs; create a new job",
            Self::BuilderFinished => "create a new builder or page: a finished one takes no more drawing, pages, fonts or settings",
            Self::InvalidArgument => "pass the value the type declarations describe; the data field says what was wrong",
            Self::SourceBudgetExceeded => "raise the source's budget, or open the file with fewer bytes fetched (smaller blocks, no readahead)",
            Self::UnknownOption => "remove the key or correct its spelling; didYouMean lists the closest known names",
        }
    }

    /// The code's explain page (`docsUrl`, ADR 0026 §6).
    #[must_use]
    pub fn docs_url(self) -> String {
        format!("{DOCS_URL_BASE}{}{DOCS_URL_SUFFIX}", self.as_str())
    }
}

/// Every warning code, in `codes.json` order.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum WarningCode {
    /// `missing-header`: no %PDF-x.y header in the first 1,024 bytes; parsing went ahead.
    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 and was ignored.
    XrefstmIgnored,
    /// `stream-length-recovered`: a stream's /Length was wrong, so its end was found by scanning for endstream.
    StreamLengthRecovered,
    /// `stale-generation`: a reference's generation did not match its xref entry, so it resolved to null.
    StaleGeneration,
    /// `page-tree-node-skipped`: a page-tree node was missing, malformed or too deep, and was skipped.
    PageTreeNodeSkipped,
    /// `page-count-mismatch`: the page tree's /Count differs from the number of pages walked.
    PageCountMismatch,
    /// `flate-truncated`: Flate data was truncated or had a bad checksum; the partial output was kept.
    FlateTruncated,
    /// `objstm-index-mismatch`: an object stream's index was stale and the object was found by searching.
    ObjstmIndexMismatch,
    /// `object-number-out-of-range`: an xref entry above max_object_number was dropped.
    ObjectNumberOutOfRange,
    /// `aes-padding-invalid`: AES-encrypted data had a bad length or padding and was kept as stored.
    AesPaddingInvalid,
    /// `perms-mismatch`: an R5/R6 document's /Perms does not match its /P and /EncryptMetadata.
    PermsMismatch,
    /// `warnings-truncated`: more than max_warnings warnings were raised and the rest were dropped.
    WarningsTruncated,
    /// `invalid-box`: a page boundary box is not four numbers and reads as absent.
    InvalidBox,
    /// `invalid-rotate`: a page's /Rotate is not a multiple of 90 and reads as 0.
    InvalidRotate,
    /// `name-tree-node-skipped`: a name- or number-tree node was malformed, repeated or too deep, and was skipped.
    NameTreeNodeSkipped,
    /// `outline-cycle`: an outline item was reached twice; that branch of the walk stopped.
    OutlineCycle,
    /// `outline-item-skipped`: an outline item was missing, not a dictionary or too deep, and was skipped with its subtree.
    OutlineItemSkipped,
    /// `invalid-date`: an Info date is not a valid PDF date; the raw string is kept.
    InvalidDate,
    /// `invalid-page-label`: a /PageLabels entry is malformed; the malformed part is dropped.
    InvalidPageLabel,
    /// `invalid-entry`: an entry a view reads is unreadable or of the wrong type and reads as absent.
    InvalidEntry,
    /// `content-unknown-operator`: an operator the spec does not define was skipped outside a BX/EX section.
    ContentUnknownOperator,
    /// `content-bad-operands`: an operator had too few operands or operands of the wrong type, or extra ones.
    ContentBadOperands,
    /// `content-unbalanced-q`: a Q without a matching q was ignored, or saved graphics states were left open.
    ContentUnbalancedQ,
    /// `content-unbalanced-bt`: a text object was opened twice, closed outside one, or left open.
    ContentUnbalancedBt,
    /// `content-unbalanced-marked`: an EMC without a matching BMC or BDC was ignored, or marked content was left open.
    ContentUnbalancedMarked,
    /// `content-syntax`: content-stream bytes that are not a token were skipped.
    ContentSyntax,
    /// `content-resource-missing`: an operator named a resource that is missing, of the wrong type or unreadable.
    ContentResourceMissing,
    /// `inline-image-unterminated`: no EI ends an inline image; the rest of the content was skipped.
    InlineImageUnterminated,
    /// `xobject-cycle`: a Form XObject draws itself, directly or through other forms.
    XobjectCycle,
    /// `content-path-unpainted`: a content stream ended with a path no painting operator ended.
    ContentPathUnpainted,
    /// `font-invalid`: a font dictionary has a missing or malformed entry, so its text was decoded with defaults.
    FontInvalid,
    /// `cmap-invalid`: a font's CMap or ToUnicode CMap is malformed or names a predefined CMap Lamina PDF has no table for.
    CmapInvalid,
    /// `unmapped-glyph`: a font shows glyphs that nothing maps to text.
    UnmappedGlyph,
    /// `tounicode-conflict`: one glyph was used for two different texts; ToUnicode keeps the first.
    TounicodeConflict,
    /// `whole-font-rebuilt`: a font that forbids subsetting was rebuilt with every glyph kept.
    WholeFontRebuilt,
}

impl WarningCode {
    /// Every variant, in `codes.json` order.
    pub const ALL: &'static [Self] = &[
        Self::MissingHeader,
        Self::XrefRepaired,
        Self::XrefstmIgnored,
        Self::StreamLengthRecovered,
        Self::StaleGeneration,
        Self::PageTreeNodeSkipped,
        Self::PageCountMismatch,
        Self::FlateTruncated,
        Self::ObjstmIndexMismatch,
        Self::ObjectNumberOutOfRange,
        Self::AesPaddingInvalid,
        Self::PermsMismatch,
        Self::WarningsTruncated,
        Self::InvalidBox,
        Self::InvalidRotate,
        Self::NameTreeNodeSkipped,
        Self::OutlineCycle,
        Self::OutlineItemSkipped,
        Self::InvalidDate,
        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::TounicodeConflict,
        Self::WholeFontRebuilt,
    ];

    /// The code with this name, if there is one.
    #[must_use]
    pub const fn from_code(code: &str) -> Option<Self> {
        Some(match code.as_bytes() {
            b"missing-header" => Self::MissingHeader,
            b"xref-repaired" => Self::XrefRepaired,
            b"xrefstm-ignored" => Self::XrefstmIgnored,
            b"stream-length-recovered" => Self::StreamLengthRecovered,
            b"stale-generation" => Self::StaleGeneration,
            b"page-tree-node-skipped" => Self::PageTreeNodeSkipped,
            b"page-count-mismatch" => Self::PageCountMismatch,
            b"flate-truncated" => Self::FlateTruncated,
            b"objstm-index-mismatch" => Self::ObjstmIndexMismatch,
            b"object-number-out-of-range" => Self::ObjectNumberOutOfRange,
            b"aes-padding-invalid" => Self::AesPaddingInvalid,
            b"perms-mismatch" => Self::PermsMismatch,
            b"warnings-truncated" => Self::WarningsTruncated,
            b"invalid-box" => Self::InvalidBox,
            b"invalid-rotate" => Self::InvalidRotate,
            b"name-tree-node-skipped" => Self::NameTreeNodeSkipped,
            b"outline-cycle" => Self::OutlineCycle,
            b"outline-item-skipped" => Self::OutlineItemSkipped,
            b"invalid-date" => Self::InvalidDate,
            b"invalid-page-label" => Self::InvalidPageLabel,
            b"invalid-entry" => Self::InvalidEntry,
            b"content-unknown-operator" => Self::ContentUnknownOperator,
            b"content-bad-operands" => Self::ContentBadOperands,
            b"content-unbalanced-q" => Self::ContentUnbalancedQ,
            b"content-unbalanced-bt" => Self::ContentUnbalancedBt,
            b"content-unbalanced-marked" => Self::ContentUnbalancedMarked,
            b"content-syntax" => Self::ContentSyntax,
            b"content-resource-missing" => Self::ContentResourceMissing,
            b"inline-image-unterminated" => Self::InlineImageUnterminated,
            b"xobject-cycle" => Self::XobjectCycle,
            b"content-path-unpainted" => Self::ContentPathUnpainted,
            b"font-invalid" => Self::FontInvalid,
            b"cmap-invalid" => Self::CmapInvalid,
            b"unmapped-glyph" => Self::UnmappedGlyph,
            b"tounicode-conflict" => Self::TounicodeConflict,
            b"whole-font-rebuilt" => Self::WholeFontRebuilt,
            _ => return None,
        })
    }

    /// The kebab-case code.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::MissingHeader => "missing-header",
            Self::XrefRepaired => "xref-repaired",
            Self::XrefstmIgnored => "xrefstm-ignored",
            Self::StreamLengthRecovered => "stream-length-recovered",
            Self::StaleGeneration => "stale-generation",
            Self::PageTreeNodeSkipped => "page-tree-node-skipped",
            Self::PageCountMismatch => "page-count-mismatch",
            Self::FlateTruncated => "flate-truncated",
            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::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::TounicodeConflict => "tounicode-conflict",
            Self::WholeFontRebuilt => "whole-font-rebuilt",
        }
    }

    /// The kind (ADR 0026 §2).
    #[must_use]
    pub const fn kind(self) -> ErrorKind {
        match self {
            Self::MissingHeader => ErrorKind::Input,
            Self::XrefRepaired => ErrorKind::Input,
            Self::XrefstmIgnored => ErrorKind::Input,
            Self::StreamLengthRecovered => ErrorKind::Input,
            Self::StaleGeneration => ErrorKind::Input,
            Self::PageTreeNodeSkipped => ErrorKind::Input,
            Self::PageCountMismatch => ErrorKind::Input,
            Self::FlateTruncated => ErrorKind::Input,
            Self::ObjstmIndexMismatch => ErrorKind::Input,
            Self::ObjectNumberOutOfRange => ErrorKind::Limit,
            Self::AesPaddingInvalid => ErrorKind::Security,
            Self::PermsMismatch => ErrorKind::Security,
            Self::WarningsTruncated => ErrorKind::Limit,
            Self::InvalidBox => ErrorKind::Input,
            Self::InvalidRotate => ErrorKind::Input,
            Self::NameTreeNodeSkipped => ErrorKind::Input,
            Self::OutlineCycle => ErrorKind::Input,
            Self::OutlineItemSkipped => ErrorKind::Input,
            Self::InvalidDate => ErrorKind::Input,
            Self::InvalidPageLabel => ErrorKind::Input,
            Self::InvalidEntry => ErrorKind::Input,
            Self::ContentUnknownOperator => ErrorKind::Input,
            Self::ContentBadOperands => ErrorKind::Input,
            Self::ContentUnbalancedQ => ErrorKind::Input,
            Self::ContentUnbalancedBt => ErrorKind::Input,
            Self::ContentUnbalancedMarked => ErrorKind::Input,
            Self::ContentSyntax => ErrorKind::Input,
            Self::ContentResourceMissing => ErrorKind::Input,
            Self::InlineImageUnterminated => ErrorKind::Input,
            Self::XobjectCycle => ErrorKind::Input,
            Self::ContentPathUnpainted => ErrorKind::Input,
            Self::FontInvalid => ErrorKind::Input,
            Self::CmapInvalid => ErrorKind::Input,
            Self::UnmappedGlyph => ErrorKind::Input,
            Self::TounicodeConflict => ErrorKind::Usage,
            Self::WholeFontRebuilt => ErrorKind::Usage,
        }
    }

    /// One lowercase sentence: what happened.
    #[must_use]
    pub const fn summary(self) -> &'static str {
        match self {
            Self::MissingHeader => "no %PDF-x.y header in the first 1,024 bytes; parsing went ahead",
            Self::XrefRepaired => "the stored cross-reference data was unusable and was rebuilt by scanning",
            Self::XrefstmIgnored => "a hybrid file's /XRefStm could not be read and was ignored",
            Self::StreamLengthRecovered => "a stream's /Length was wrong, so its end was found by scanning for endstream",
            Self::StaleGeneration => "a reference's generation did not match its xref entry, so it resolved to null",
            Self::PageTreeNodeSkipped => "a page-tree node was missing, malformed or too deep, and was skipped",
            Self::PageCountMismatch => "the page tree's /Count differs from the number of pages walked",
            Self::FlateTruncated => "Flate data was truncated or had a bad checksum; the partial output was kept",
            Self::ObjstmIndexMismatch => "an object stream's index was stale and the object was found by searching",
            Self::ObjectNumberOutOfRange => "an xref entry above max_object_number was dropped",
            Self::AesPaddingInvalid => "AES-encrypted data had a bad length or padding and was kept as stored",
            Self::PermsMismatch => "an R5/R6 document's /Perms does not match its /P and /EncryptMetadata",
            Self::WarningsTruncated => "more than max_warnings warnings were raised and the rest were dropped",
            Self::InvalidBox => "a page boundary box is not four numbers and reads as absent",
            Self::InvalidRotate => "a page's /Rotate is not a multiple of 90 and reads as 0",
            Self::NameTreeNodeSkipped => "a name- or number-tree node was malformed, repeated or too deep, and was skipped",
            Self::OutlineCycle => "an outline item was reached twice; that branch of the walk stopped",
            Self::OutlineItemSkipped => "an outline item was missing, not a dictionary or too deep, and was skipped with its subtree",
            Self::InvalidDate => "an Info date is not a valid PDF date; the raw string is kept",
            Self::InvalidPageLabel => "a /PageLabels entry is malformed; the malformed part is dropped",
            Self::InvalidEntry => "an entry a view reads is unreadable or of the wrong type and reads as absent",
            Self::ContentUnknownOperator => "an operator the spec does not define was skipped outside a BX/EX section",
            Self::ContentBadOperands => "an operator had too few operands or operands of the wrong type, or extra ones",
            Self::ContentUnbalancedQ => "a Q without a matching q was ignored, or saved graphics states were left open",
            Self::ContentUnbalancedBt => "a text object was opened twice, closed outside one, or left open",
            Self::ContentUnbalancedMarked => "an EMC without a matching BMC or BDC was ignored, or marked content was left open",
            Self::ContentSyntax => "content-stream bytes that are not a token were skipped",
            Self::ContentResourceMissing => "an operator named a resource that is missing, of the wrong type or unreadable",
            Self::InlineImageUnterminated => "no EI ends an inline image; the rest of the content was skipped",
            Self::XobjectCycle => "a Form XObject draws itself, directly or through other forms",
            Self::ContentPathUnpainted => "a content stream ended with a path no painting operator ended",
            Self::FontInvalid => "a font dictionary has a missing or malformed entry, so its text was decoded with defaults",
            Self::CmapInvalid => "a font's CMap or ToUnicode CMap is malformed or names a predefined CMap Lamina PDF has no table for",
            Self::UnmappedGlyph => "a font shows glyphs that nothing maps to text",
            Self::TounicodeConflict => "one glyph was used for two different texts; ToUnicode keeps the first",
            Self::WholeFontRebuilt => "a font that forbids subsetting was rebuilt with every glyph kept",
        }
    }

    /// The hint (ADR 0026 §5), with its `{limit}`/`{option}` parameters unfilled.
    #[must_use]
    pub const fn hint(self) -> &'static str {
        match self {
            Self::MissingHeader => "nothing to do if the document reads correctly; open in strict mode to refuse such files",
            Self::XrefRepaired => "check the result; save with a full rewrite, since an incremental update refuses a repaired base",
            Self::XrefstmIgnored => "nothing to do; the classic xref table is used instead",
            Self::StreamLengthRecovered => "nothing to do; a full rewrite writes the correct length",
            Self::StaleGeneration => "nothing to do; the reference is treated as missing",
            Self::PageTreeNodeSkipped => "check the page count: pages under the skipped node are missing",
            Self::PageCountMismatch => "nothing to do; Lamina PDF uses the walked page count",
            Self::FlateTruncated => "check the affected content: the end of the stream may be missing",
            Self::ObjstmIndexMismatch => "nothing to do; a full rewrite writes a correct index",
            Self::ObjectNumberOutOfRange => "raise max_object_number in Limits only if you trust the input",
            Self::AesPaddingInvalid => "treat the affected strings and streams as suspect: they may have been tampered with",
            Self::PermsMismatch => "treat the document's permissions as untrusted",
            Self::WarningsTruncated => "raise max_warnings in Limits if you need the full list",
            Self::InvalidBox => "nothing to do; the page uses the next box in the fallback chain",
            Self::InvalidRotate => "set the page rotation explicitly if 0 is wrong",
            Self::NameTreeNodeSkipped => "check the tree's entries: those under the skipped node are missing",
            Self::OutlineCycle => "nothing to do; the outline is read without the loop",
            Self::OutlineItemSkipped => "check the outline: the skipped item and its children are missing",
            Self::InvalidDate => "read the raw value from the Info view if you need it",
            Self::InvalidPageLabel => "nothing to do; affected pages fall back to decimal labels",
            Self::InvalidEntry => "nothing to do; the view uses the entry's default",
            Self::ContentUnknownOperator => "nothing to do; check the page's rendering if the operator mattered",
            Self::ContentBadOperands => "nothing to do; the operator was skipped or used its last operands",
            Self::ContentUnbalancedQ => "nothing to do; the graphics state was restored as the spec intends",
            Self::ContentUnbalancedBt => "nothing to do; text operators outside a text object were handled tolerantly",
            Self::ContentUnbalancedMarked => "check tagged-content results: marked-content sequences were closed for you",
            Self::ContentSyntax => "check the page's content: the bytes around the reported offset were skipped",
            Self::ContentResourceMissing => "check the page's resources: the operator ran without the resource or was skipped",
            Self::InlineImageUnterminated => "check the page's content: everything after the inline image is missing",
            Self::XobjectCycle => "nothing to do; the inner Do was skipped",
            Self::ContentPathUnpainted => "nothing to do; the unpainted path was dropped as the spec intends",
            Self::FontInvalid => "nothing to do; extracted text or positions for that font may be off",
            Self::CmapInvalid => "nothing to do; the bad entries were skipped and the rest of the CMap is used",
            Self::UnmappedGlyph => "nothing to do; those glyphs extract as U+FFFD (the file needs a ToUnicode CMap)",
            Self::TounicodeConflict => "mark the second occurrence with /ActualText so extraction gets its text",
            Self::WholeFontRebuilt => "check that the font's licence allows this, or use a static TrueType or CFF version",
        }
    }

    /// The code's explain page (`docsUrl`, ADR 0026 §6).
    #[must_use]
    pub fn docs_url(self) -> String {
        format!("{DOCS_URL_BASE}{}{DOCS_URL_SUFFIX}", self.as_str())
    }
}