laminapdf-syntax 0.3.0

PDF syntax in Rust: the object model, lexer and parser, stream filters, decryption, and resource limits for untrusted input.
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
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
// @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`.
///
/// Added in 0.2.0.
pub const DOCS_URL_BASE: &str = "https://docs.laminapdf.com/reference/codes/";

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

/// Whether two byte strings are equal, in a `const fn`.
const fn bytes_eq(a: &[u8], b: &[u8]) -> bool {
    if a.len() != b.len() {
        return false;
    }
    let (mut a, mut b) = (a, b);
    while let ([x, a_rest @ ..], [y, b_rest @ ..]) = (a, b) {
        if *x != *y {
            return false;
        }
        a = a_rest;
        b = b_rest;
    }
    true
}

/// 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.
///
/// Added in 0.2.0.
#[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,
    /// `malformed-xmp`: a metadata edit would replace the document's XMP packet, which can't be read, losing what it holds.
    MalformedXmp,
    /// `unknown-source`: an op or a call names a source document that was not added to the session.
    UnknownSource,
    /// `open-action-not-destination`: an op would replace or remove the document's open action, which is an action other than a destination.
    OpenActionNotDestination,
    /// `unknown-outline-item`: an outline op names a bookmark the outline does not have.
    UnknownOutlineItem,
    /// `direct-outline-item`: the bookmark is stored inside another item rather than as an object of its own, so outline ops can't name it yet.
    DirectOutlineItem,
    /// `outline-not-a-sibling`: the position names a bookmark that is not a child of the parent the op names.
    OutlineNotASibling,
    /// `outline-move-into-itself`: a move would put a bookmark inside itself or one of its descendants.
    OutlineMoveIntoItself,
    /// `unknown-named-destination`: the op names a destination the file does not define.
    UnknownNamedDestination,
    /// `named-destination-exists`: a rename to a name another destination already has.
    NamedDestinationExists,
    /// `empty-destination-name`: a destination name is empty.
    EmptyDestinationName,
    /// `link-uri-refused`: a web address that isn't an absolute http, https or mailto address in plain ASCII.
    LinkUriRefused,
    /// `view-not-finite`: a destination's coordinates and zoom must be finite numbers.
    ViewNotFinite,
    /// `xmp-claim-read-only`: an XMP edit would change the file's PDF/A or PDF/UA identification, which only conversion or a check may set.
    XmpClaimReadOnly,
    /// `invalid-xmp-packet`: the XMP packet given to replace the document's doesn't parse.
    InvalidXmpPacket,
    /// `invalid-xmp-property`: an XMP property edit names a property, or gives a value, that can't be written.
    InvalidXmpProperty,
    /// `no-pages-left`: a page deletion would leave the document with no pages.
    NoPagesLeft,
    /// `invalid-op`: an op's values are out of range, such as a page count or a page size.
    InvalidOp,
    /// `unknown-annotation`: the op names an annotation that no page of the document lists.
    UnknownAnnotation,
    /// `annotation-locked`: the annotation's flags forbid the change: Locked forbids deleting it or changing its properties, LockedContents changing its contents.
    AnnotationLocked,
    /// `annotation-not-editable`: the annotation can't be edited by the annotation ops: it is a form field's widget, or a direct dictionary with no object of its own.
    AnnotationNotEditable,
    /// `invalid-label-ranges`: page label ranges whose first isn't on the first page, that are out of page order or share a page, or that number from 0.
    InvalidLabelRanges,
    /// `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,
    /// `invalid-spans`: the styled spans given for a paragraph do not cover its text once, in order.
    InvalidSpans,
    /// `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,
    /// `tag-element-not-open`: a structure element resumed or closed isn't open.
    TagElementNotOpen,
    /// `tag-element-unclosed`: structure elements opened across pages were never closed.
    TagElementUnclosed,
    /// `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,
    /// `flow-content-too-large`: a line or a figure of a flow is taller than the page's body, so no page can hold it.
    FlowContentTooLarge,
    /// `flow-layout-unstable`: a flow's contents page kept changing its page numbers after four layouts.
    FlowLayoutUnstable,
    /// `invalid-document`: a laminapdf.document/1 document has an unknown key, a missing one or a value of the wrong kind.
    InvalidDocument,
    /// `template-data-missing`: a template's $data, $each or $item points to a value the data doesn't have.
    TemplateDataMissing,
    /// `template-data-type`: a template's placeholder found data of the wrong kind: $each over something that isn't a list, or text from an object.
    TemplateDataType,
    /// `template-too-large`: a template would fill in more values, or nest deeper, than a document may hold.
    TemplateTooLarge,
    /// `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,
    /// `export-failed`: an export's PNG, JPEG or TIFF encoder failed on a page that was drawn.
    ExportFailed,
    /// `model-failed`: a layout model, OCR engine or page renderer plugged into an extraction failed; the extraction stops with no partial result.
    ModelFailed,
    /// `model-result-unexpected`: a model result was handed to an extraction job that hadn't asked for it, or was the other model's result.
    ModelResultUnexpected,
    /// `model-needs-host`: an extraction in one call was given a model whose results only the host can give: a host model, or a plug-in model without a page renderer.
    ModelNeedsHost,
    /// `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,
    /// `revision-index-out-of-range`: an earlier revision was asked for by an index past the file's last revision.
    RevisionIndexOutOfRange,
    /// `builder-finished`: a builder or one of its pages was used after it finished.
    BuilderFinished,
    /// `disposed`: a document, builder or other handle was used after free(), or after the using block that held it ended.
    Disposed,
    /// `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,
    /// `invalid-command-line`: the command line doesn't parse: an unknown command or flag, a missing argument, a bad value, or stdin named twice.
    InvalidCommandLine,
    /// `invalid-page-range`: a page range doesn't fit the grammar, or names a page the document lacks.
    InvalidPageRange,
    /// `binary-output-to-terminal`: the command would write a PDF to standard output, and standard output is a terminal.
    BinaryOutputToTerminal,
    /// `unknown-code`: explain was given a code that isn't a Lamina PDF error or warning code.
    UnknownCode,
    /// `overwrite-refused`: the output file exists, or the command would modify its input in place, and --force wasn't given.
    OverwriteRefused,
    /// `input-unreadable`: an input file, standard input or the password file couldn't be read.
    InputUnreadable,
    /// `output-unwritable`: the output couldn't be written: its folder is missing or read-only, the disk is full, or standard output closed.
    OutputUnwritable,
    /// `path-outside-roots`: laminapdf mcp was given a path outside its --root folders, or a link that leads out of them.
    PathOutsideRoots,
}

impl ErrorCode {
    /// Every variant, in `codes.json` order.
    ///
    /// Added in 0.2.0.
    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::MalformedXmp,
        Self::UnknownSource,
        Self::OpenActionNotDestination,
        Self::UnknownOutlineItem,
        Self::DirectOutlineItem,
        Self::OutlineNotASibling,
        Self::OutlineMoveIntoItself,
        Self::UnknownNamedDestination,
        Self::NamedDestinationExists,
        Self::EmptyDestinationName,
        Self::LinkUriRefused,
        Self::ViewNotFinite,
        Self::XmpClaimReadOnly,
        Self::InvalidXmpPacket,
        Self::InvalidXmpProperty,
        Self::NoPagesLeft,
        Self::InvalidOp,
        Self::UnknownAnnotation,
        Self::AnnotationLocked,
        Self::AnnotationNotEditable,
        Self::InvalidLabelRanges,
        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::InvalidSpans,
        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::TagElementNotOpen,
        Self::TagElementUnclosed,
        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::FlowContentTooLarge,
        Self::FlowLayoutUnstable,
        Self::InvalidDocument,
        Self::TemplateDataMissing,
        Self::TemplateDataType,
        Self::TemplateTooLarge,
        Self::RenderTooLarge,
        Self::RenderFailed,
        Self::RenderBackendUnavailable,
        Self::ExportFailed,
        Self::ModelFailed,
        Self::ModelResultUnexpected,
        Self::ModelNeedsHost,
        Self::Cancelled,
        Self::JobFinished,
        Self::DocumentChanged,
        Self::RevisionIndexOutOfRange,
        Self::BuilderFinished,
        Self::Disposed,
        Self::InvalidArgument,
        Self::SourceBudgetExceeded,
        Self::UnknownOption,
        Self::InvalidCommandLine,
        Self::InvalidPageRange,
        Self::BinaryOutputToTerminal,
        Self::UnknownCode,
        Self::OverwriteRefused,
        Self::InputUnreadable,
        Self::OutputUnwritable,
        Self::PathOutsideRoots,
    ];

    /// The code with this name, if there is one.
    ///
    /// Added in 0.2.0.
    #[must_use]
    pub const fn from_code(code: &str) -> Option<Self> {
        let mut rest = Self::ALL;
        while let [first, tail @ ..] = rest {
            if bytes_eq(first.as_str().as_bytes(), code.as_bytes()) {
                return Some(*first);
            }
            rest = tail;
        }
        None
    }

    /// The kebab-case code.
    ///
    /// Added in 0.2.0.
    #[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::MalformedXmp => "malformed-xmp",
            Self::UnknownSource => "unknown-source",
            Self::OpenActionNotDestination => "open-action-not-destination",
            Self::UnknownOutlineItem => "unknown-outline-item",
            Self::DirectOutlineItem => "direct-outline-item",
            Self::OutlineNotASibling => "outline-not-a-sibling",
            Self::OutlineMoveIntoItself => "outline-move-into-itself",
            Self::UnknownNamedDestination => "unknown-named-destination",
            Self::NamedDestinationExists => "named-destination-exists",
            Self::EmptyDestinationName => "empty-destination-name",
            Self::LinkUriRefused => "link-uri-refused",
            Self::ViewNotFinite => "view-not-finite",
            Self::XmpClaimReadOnly => "xmp-claim-read-only",
            Self::InvalidXmpPacket => "invalid-xmp-packet",
            Self::InvalidXmpProperty => "invalid-xmp-property",
            Self::NoPagesLeft => "no-pages-left",
            Self::InvalidOp => "invalid-op",
            Self::UnknownAnnotation => "unknown-annotation",
            Self::AnnotationLocked => "annotation-locked",
            Self::AnnotationNotEditable => "annotation-not-editable",
            Self::InvalidLabelRanges => "invalid-label-ranges",
            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::InvalidSpans => "invalid-spans",
            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::TagElementNotOpen => "tag-element-not-open",
            Self::TagElementUnclosed => "tag-element-unclosed",
            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::FlowContentTooLarge => "flow-content-too-large",
            Self::FlowLayoutUnstable => "flow-layout-unstable",
            Self::InvalidDocument => "invalid-document",
            Self::TemplateDataMissing => "template-data-missing",
            Self::TemplateDataType => "template-data-type",
            Self::TemplateTooLarge => "template-too-large",
            Self::RenderTooLarge => "render-too-large",
            Self::RenderFailed => "render-failed",
            Self::RenderBackendUnavailable => "render-backend-unavailable",
            Self::ExportFailed => "export-failed",
            Self::ModelFailed => "model-failed",
            Self::ModelResultUnexpected => "model-result-unexpected",
            Self::ModelNeedsHost => "model-needs-host",
            Self::Cancelled => "cancelled",
            Self::JobFinished => "job-finished",
            Self::DocumentChanged => "document-changed",
            Self::RevisionIndexOutOfRange => "revision-index-out-of-range",
            Self::BuilderFinished => "builder-finished",
            Self::Disposed => "disposed",
            Self::InvalidArgument => "invalid-argument",
            Self::SourceBudgetExceeded => "source-budget-exceeded",
            Self::UnknownOption => "unknown-option",
            Self::InvalidCommandLine => "invalid-command-line",
            Self::InvalidPageRange => "invalid-page-range",
            Self::BinaryOutputToTerminal => "binary-output-to-terminal",
            Self::UnknownCode => "unknown-code",
            Self::OverwriteRefused => "overwrite-refused",
            Self::InputUnreadable => "input-unreadable",
            Self::OutputUnwritable => "output-unwritable",
            Self::PathOutsideRoots => "path-outside-roots",
        }
    }

    /// The kind (ADR 0026 §2).
    ///
    /// Added in 0.2.0.
    #[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::MalformedXmp => ErrorKind::Input,
            Self::UnknownSource => ErrorKind::Usage,
            Self::OpenActionNotDestination => ErrorKind::Usage,
            Self::UnknownOutlineItem => ErrorKind::Usage,
            Self::DirectOutlineItem => ErrorKind::Unsupported,
            Self::OutlineNotASibling => ErrorKind::Usage,
            Self::OutlineMoveIntoItself => ErrorKind::Usage,
            Self::UnknownNamedDestination => ErrorKind::Usage,
            Self::NamedDestinationExists => ErrorKind::Usage,
            Self::EmptyDestinationName => ErrorKind::Usage,
            Self::LinkUriRefused => ErrorKind::Usage,
            Self::ViewNotFinite => ErrorKind::Usage,
            Self::XmpClaimReadOnly => ErrorKind::Usage,
            Self::InvalidXmpPacket => ErrorKind::Input,
            Self::InvalidXmpProperty => ErrorKind::Usage,
            Self::NoPagesLeft => ErrorKind::Usage,
            Self::InvalidOp => ErrorKind::Usage,
            Self::UnknownAnnotation => ErrorKind::Usage,
            Self::AnnotationLocked => ErrorKind::State,
            Self::AnnotationNotEditable => ErrorKind::Unsupported,
            Self::InvalidLabelRanges => ErrorKind::Usage,
            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::InvalidSpans => 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::TagElementNotOpen => ErrorKind::Usage,
            Self::TagElementUnclosed => 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::FlowContentTooLarge => ErrorKind::Usage,
            Self::FlowLayoutUnstable => ErrorKind::Internal,
            Self::InvalidDocument => ErrorKind::Usage,
            Self::TemplateDataMissing => ErrorKind::Usage,
            Self::TemplateDataType => ErrorKind::Usage,
            Self::TemplateTooLarge => ErrorKind::Usage,
            Self::RenderTooLarge => ErrorKind::Limit,
            Self::RenderFailed => ErrorKind::Input,
            Self::RenderBackendUnavailable => ErrorKind::Io,
            Self::ExportFailed => ErrorKind::Internal,
            Self::ModelFailed => ErrorKind::Internal,
            Self::ModelResultUnexpected => ErrorKind::Usage,
            Self::ModelNeedsHost => ErrorKind::Usage,
            Self::Cancelled => ErrorKind::Cancelled,
            Self::JobFinished => ErrorKind::State,
            Self::DocumentChanged => ErrorKind::State,
            Self::RevisionIndexOutOfRange => ErrorKind::Usage,
            Self::BuilderFinished => ErrorKind::State,
            Self::Disposed => ErrorKind::State,
            Self::InvalidArgument => ErrorKind::Usage,
            Self::SourceBudgetExceeded => ErrorKind::Limit,
            Self::UnknownOption => ErrorKind::Usage,
            Self::InvalidCommandLine => ErrorKind::Usage,
            Self::InvalidPageRange => ErrorKind::Usage,
            Self::BinaryOutputToTerminal => ErrorKind::Usage,
            Self::UnknownCode => ErrorKind::Usage,
            Self::OverwriteRefused => ErrorKind::State,
            Self::InputUnreadable => ErrorKind::Io,
            Self::OutputUnwritable => ErrorKind::Io,
            Self::PathOutsideRoots => ErrorKind::Security,
        }
    }

    /// One lowercase sentence: what happened.
    ///
    /// Added in 0.2.0.
    #[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::MalformedXmp => "a metadata edit would replace the document's XMP packet, which can't be read, losing what it holds",
            Self::UnknownSource => "an op or a call names a source document that was not added to the session",
            Self::OpenActionNotDestination => "an op would replace or remove the document's open action, which is an action other than a destination",
            Self::UnknownOutlineItem => "an outline op names a bookmark the outline does not have",
            Self::DirectOutlineItem => "the bookmark is stored inside another item rather than as an object of its own, so outline ops can't name it yet",
            Self::OutlineNotASibling => "the position names a bookmark that is not a child of the parent the op names",
            Self::OutlineMoveIntoItself => "a move would put a bookmark inside itself or one of its descendants",
            Self::UnknownNamedDestination => "the op names a destination the file does not define",
            Self::NamedDestinationExists => "a rename to a name another destination already has",
            Self::EmptyDestinationName => "a destination name is empty",
            Self::LinkUriRefused => "a web address that isn't an absolute http, https or mailto address in plain ASCII",
            Self::ViewNotFinite => "a destination's coordinates and zoom must be finite numbers",
            Self::XmpClaimReadOnly => "an XMP edit would change the file's PDF/A or PDF/UA identification, which only conversion or a check may set",
            Self::InvalidXmpPacket => "the XMP packet given to replace the document's doesn't parse",
            Self::InvalidXmpProperty => "an XMP property edit names a property, or gives a value, that can't be written",
            Self::NoPagesLeft => "a page deletion would leave the document with no pages",
            Self::InvalidOp => "an op's values are out of range, such as a page count or a page size",
            Self::UnknownAnnotation => "the op names an annotation that no page of the document lists",
            Self::AnnotationLocked => "the annotation's flags forbid the change: Locked forbids deleting it or changing its properties, LockedContents changing its contents",
            Self::AnnotationNotEditable => "the annotation can't be edited by the annotation ops: it is a form field's widget, or a direct dictionary with no object of its own",
            Self::InvalidLabelRanges => "page label ranges whose first isn't on the first page, that are out of page order or share a page, or that number from 0",
            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::InvalidSpans => "the styled spans given for a paragraph do not cover its text once, in order",
            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::TagElementNotOpen => "a structure element resumed or closed isn't open",
            Self::TagElementUnclosed => "structure elements opened across pages were never closed",
            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::FlowContentTooLarge => "a line or a figure of a flow is taller than the page's body, so no page can hold it",
            Self::FlowLayoutUnstable => "a flow's contents page kept changing its page numbers after four layouts",
            Self::InvalidDocument => "a laminapdf.document/1 document has an unknown key, a missing one or a value of the wrong kind",
            Self::TemplateDataMissing => "a template's $data, $each or $item points to a value the data doesn't have",
            Self::TemplateDataType => "a template's placeholder found data of the wrong kind: $each over something that isn't a list, or text from an object",
            Self::TemplateTooLarge => "a template would fill in more values, or nest deeper, than a document may hold",
            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::ExportFailed => "an export's PNG, JPEG or TIFF encoder failed on a page that was drawn",
            Self::ModelFailed => "a layout model, OCR engine or page renderer plugged into an extraction failed; the extraction stops with no partial result",
            Self::ModelResultUnexpected => "a model result was handed to an extraction job that hadn't asked for it, or was the other model's result",
            Self::ModelNeedsHost => "an extraction in one call was given a model whose results only the host can give: a host model, or a plug-in model without a page renderer",
            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::RevisionIndexOutOfRange => "an earlier revision was asked for by an index past the file's last revision",
            Self::BuilderFinished => "a builder or one of its pages was used after it finished",
            Self::Disposed => "a document, builder or other handle was used after free(), or after the using block that held it ended",
            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",
            Self::InvalidCommandLine => "the command line doesn't parse: an unknown command or flag, a missing argument, a bad value, or stdin named twice",
            Self::InvalidPageRange => "a page range doesn't fit the grammar, or names a page the document lacks",
            Self::BinaryOutputToTerminal => "the command would write a PDF to standard output, and standard output is a terminal",
            Self::UnknownCode => "explain was given a code that isn't a Lamina PDF error or warning code",
            Self::OverwriteRefused => "the output file exists, or the command would modify its input in place, and --force wasn't given",
            Self::InputUnreadable => "an input file, standard input or the password file couldn't be read",
            Self::OutputUnwritable => "the output couldn't be written: its folder is missing or read-only, the disk is full, or standard output closed",
            Self::PathOutsideRoots => "laminapdf mcp was given a path outside its --root folders, or a link that leads out of them",
        }
    }

    /// The hint (ADR 0026 §5), with its `{limit}`/`{option}` parameters unfilled.
    ///
    /// Added in 0.2.0.
    #[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::MalformedXmp => "set replaceMalformed on the edit to replace the packet with a new one, or leave the metadata as it is",
            Self::UnknownSource => "add the source document's bytes with addSource before applying ops that name it",
            Self::OpenActionNotDestination => "leave the open page out of the edit, which keeps the open action as it is",
            Self::UnknownOutlineItem => "read the outline again and use one of its item IDs; an item a previous op deleted is gone",
            Self::DirectOutlineItem => "apply any other outline op first: it rewrites the outline and gives every bookmark an object and an ID of its own",
            Self::OutlineNotASibling => "name a position among the parent's own children, or use first or last",
            Self::OutlineMoveIntoItself => "choose a parent outside the bookmark's own branch",
            Self::UnknownNamedDestination => "list the file's named destinations and use one of their names",
            Self::NamedDestinationExists => "choose a name no destination has, or delete the other one first",
            Self::EmptyDestinationName => "give the destination a name of at least one character",
            Self::LinkUriRefused => "use a full address such as https://example.com/page; encode other characters with %",
            Self::ViewNotFinite => "pass finite numbers, or null to keep the viewer's current value",
            Self::XmpClaimReadOnly => "leave the pdfaid: and pdfuaid: properties as they are; edit the other properties, or keep them unchanged in a replaced packet",
            Self::InvalidXmpPacket => "fix the XML at the offset in the error's data (reason says what is wrong), then replace the packet again",
            Self::InvalidXmpProperty => "check the part the error's reason names: the namespace, prefix, name, value, or the shape a mirrored property needs",
            Self::NoPagesLeft => "keep at least one page: delete all but one, or insert a blank page first",
            Self::InvalidOp => "insert between 1 and 10,000 pages at a time, each with a width and height above 0 and up to 14,400 points",
            Self::UnknownAnnotation => "read the page's annotations again and use an ID from that list",
            Self::AnnotationLocked => "clear the lock with an update of its flags first, if you may",
            Self::AnnotationNotEditable => "edit a widget through its form field; an annotation stored inside the page's list can't be edited yet",
            Self::InvalidLabelRanges => "give ranges in page order, the first on the document's first page, each numbered from 1 or more",
            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::InvalidSpans => "give spans in text order, each starting where the one before ends, from byte 0 to the end of the text, between grapheme clusters, each with at least one font from the list",
            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::TagElementNotOpen => "resume and close only elements this builder's pages opened with open_element, and close each once",
            Self::TagElementUnclosed => "close each element from open_element with Builder::close_element once its last page is finished",
            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 => "remove NUL characters (U+0000) from the text, 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::FlowContentTooLarge => "make the figure smaller, the text size smaller or the page's margins narrower",
            Self::FlowLayoutUnstable => "report the flow that fails; a page break after the contents block may avoid it until it is fixed",
            Self::InvalidDocument => "data.pointer names the value; correct it against the document schema, and didYouMean lists the closest known keys",
            Self::TemplateDataMissing => "data.pointer names the value the template asked for; add it to the data or correct the pointer",
            Self::TemplateDataType => "data.pointer names the value and data.expected the kind the template needs there",
            Self::TemplateTooLarge => "data.limit is the limit it passed; repeat fewer items, or split the document",
            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::ExportFailed => "report it with the format and the page: the encoder writes into memory, so this is a bug in Lamina PDF",
            Self::ModelFailed => "check the plug-in's own logs; extract without the model to get the rules-only result",
            Self::ModelResultUnexpected => "call provide only while request() returns a request, with the result its kind asks for",
            Self::ModelNeedsHost => "step an extraction job and hand it each result with provide, or give the plug-in a page renderer",
            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::RevisionIndexOutOfRange => "ask for an index below the document's revision count",
            Self::BuilderFinished => "create a new builder or page: a finished one takes no more drawing, pages, fonts or settings",
            Self::Disposed => "free a handle only after its last use; to keep working, open the document again or create a new builder",
            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",
            Self::InvalidCommandLine => "run the command with --help to see its arguments",
            Self::InvalidPageRange => "write pages as 1-5, z for the last page, r2 for the second from the end, or x3 to leave page 3 out; data.position is the character where the range went wrong",
            Self::BinaryOutputToTerminal => "redirect standard output to a file or a pipe, or write to a file with -o",
            Self::UnknownCode => "check the spelling against didYouMean, or list every code at the docs URL",
            Self::OverwriteRefused => "pass --force, or write to a new file with -o",
            Self::InputUnreadable => "check that the file exists and that you can read it; data.input names it",
            Self::OutputUnwritable => "check that the output's folder exists, that you can write to it and that the disk has room",
            Self::PathOutsideRoots => "use a path inside one of the server's --root folders, or start the server with another --root",
        }
    }

    /// The code's explain page (`docsUrl`, ADR 0026 §6).
    ///
    /// Added in 0.2.0.
    #[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.
///
/// Added in 0.2.0.
#[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,
    /// `xmp-invalid`: the XMP metadata packet is not readable XMP and reads as absent.
    XmpInvalid,
    /// `annot-name-duplicate`: two annotations on one page have the same name (/NM), which should be unique on its page.
    AnnotNameDuplicate,
    /// `xmp-repaired`: the XMP metadata packet had damage other readers read past, and was read the same way.
    XmpRepaired,
    /// `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,
    /// `extract-limit-blocks`: a page had more runs of text than the extraction block limit; the runs past it were left out.
    ExtractLimitBlocks,
    /// `extract-reading-order-ambiguous`: a page mixes horizontal and vertical writing, so the order of its blocks is a guess.
    ExtractReadingOrderAmbiguous,
    /// `extract-table-ambiguous`: a table's rules marked out merged cells that aren't rectangles, so its cells were kept unmerged.
    ExtractTableAmbiguous,
    /// `extract-table-limit`: a page's ruling lines would make a table bigger than the extraction's cell limit; those lines gave no table.
    ExtractTableLimit,
    /// `extract-struct-tree-ignored`: a tagged page's structure tree covered too little of its text, or its order jumped back across columns too often, so the layout gave the reading order.
    ExtractStructTreeIgnored,
    /// `extract-untagged-content`: a page read in structure-tree order has visible text that is neither in the tree nor an artifact; it follows the tree's blocks, in layout order.
    ExtractUntaggedContent,
    /// `extract-needs-ocr`: a page has no usable text layer: it is an image (with or without an invisible OCR layer), outlined glyphs, or glyphs without Unicode, so its extracted text is empty or unreliable.
    ExtractNeedsOcr,
    /// `extract-column-order-uncertain`: the layout rules had to guess how a page's columns are read, so its blocks may be in the wrong order; the blocks concerned have a lower confidence.
    ExtractColumnOrderUncertain,
    /// `pdfa-one-author`: the file claims PDF/A-1, which allows one author, and its metadata lists more.
    PdfaOneAuthor,
    /// `pdfua-title-missing`: the file claims PDF/UA-1, which requires a title in its metadata, and it has none.
    PdfuaTitleMissing,
    /// `pdfa-info-mismatch`: the file claims PDF/A, which requires the Info dictionary and the XMP packet to agree, and they differ.
    PdfaInfoMismatch,
    /// `duplicate-tags-incomplete`: a duplicated page's content is partly untagged, which breaks the PDF/UA claim of the document's metadata.
    DuplicateTagsIncomplete,
    /// `imported-tags-dropped`: pages copied in from another document came without their tags, which breaks the PDF/UA claim of the document's metadata.
    ImportedTagsDropped,
    /// `imported-pdfa-unchecked`: pages copied in from a document that doesn't claim the same PDF/A level may break the PDF/A claim of the document's metadata.
    ImportedPdfaUnchecked,
    /// `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,
    /// `flow-keep-broken`: blocks kept together are taller than a page, so the flow split them.
    FlowKeepBroken,
    /// `markdown-html-ignored`: the Markdown holds raw HTML, which the PDF leaves out.
    MarkdownHtmlIgnored,
    /// `markdown-image-missing`: the Markdown names an image that wasn't supplied, so the PDF leaves it out.
    MarkdownImageMissing,
    /// `covered-text`: a page draws text and then paints a shape, an image or an annotation over it, so the text is hidden but still in the file.
    CoveredText,
    /// `redaction-not-applied`: a page has redaction marks that were never applied, so the text under them is still in the file.
    RedactionNotApplied,
    /// `text-in-earlier-revision`: an earlier revision of the file holds text that the latest revision no longer has.
    TextInEarlierRevision,
}

impl WarningCode {
    /// Every variant, in `codes.json` order.
    ///
    /// Added in 0.2.0.
    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::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::ExtractLimitBlocks,
        Self::ExtractReadingOrderAmbiguous,
        Self::ExtractTableAmbiguous,
        Self::ExtractTableLimit,
        Self::ExtractStructTreeIgnored,
        Self::ExtractUntaggedContent,
        Self::ExtractNeedsOcr,
        Self::ExtractColumnOrderUncertain,
        Self::PdfaOneAuthor,
        Self::PdfuaTitleMissing,
        Self::PdfaInfoMismatch,
        Self::DuplicateTagsIncomplete,
        Self::ImportedTagsDropped,
        Self::ImportedPdfaUnchecked,
        Self::TounicodeConflict,
        Self::WholeFontRebuilt,
        Self::FlowKeepBroken,
        Self::MarkdownHtmlIgnored,
        Self::MarkdownImageMissing,
        Self::CoveredText,
        Self::RedactionNotApplied,
        Self::TextInEarlierRevision,
    ];

    /// The code with this name, if there is one.
    ///
    /// Added in 0.2.0.
    #[must_use]
    pub const fn from_code(code: &str) -> Option<Self> {
        let mut rest = Self::ALL;
        while let [first, tail @ ..] = rest {
            if bytes_eq(first.as_str().as_bytes(), code.as_bytes()) {
                return Some(*first);
            }
            rest = tail;
        }
        None
    }

    /// The kebab-case code.
    ///
    /// Added in 0.2.0.
    #[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::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",
            Self::PdfaOneAuthor => "pdfa-one-author",
            Self::PdfuaTitleMissing => "pdfua-title-missing",
            Self::PdfaInfoMismatch => "pdfa-info-mismatch",
            Self::DuplicateTagsIncomplete => "duplicate-tags-incomplete",
            Self::ImportedTagsDropped => "imported-tags-dropped",
            Self::ImportedPdfaUnchecked => "imported-pdfa-unchecked",
            Self::TounicodeConflict => "tounicode-conflict",
            Self::WholeFontRebuilt => "whole-font-rebuilt",
            Self::FlowKeepBroken => "flow-keep-broken",
            Self::MarkdownHtmlIgnored => "markdown-html-ignored",
            Self::MarkdownImageMissing => "markdown-image-missing",
            Self::CoveredText => "covered-text",
            Self::RedactionNotApplied => "redaction-not-applied",
            Self::TextInEarlierRevision => "text-in-earlier-revision",
        }
    }

    /// The kind (ADR 0026 §2).
    ///
    /// Added in 0.2.0.
    #[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::XmpInvalid => ErrorKind::Input,
            Self::AnnotNameDuplicate => ErrorKind::Input,
            Self::XmpRepaired => 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::ExtractLimitBlocks => ErrorKind::Limit,
            Self::ExtractReadingOrderAmbiguous => ErrorKind::Unsupported,
            Self::ExtractTableAmbiguous => ErrorKind::Unsupported,
            Self::ExtractTableLimit => ErrorKind::Limit,
            Self::ExtractStructTreeIgnored => ErrorKind::Input,
            Self::ExtractUntaggedContent => ErrorKind::Input,
            Self::ExtractNeedsOcr => ErrorKind::Unsupported,
            Self::ExtractColumnOrderUncertain => ErrorKind::Unsupported,
            Self::PdfaOneAuthor => ErrorKind::Usage,
            Self::PdfuaTitleMissing => ErrorKind::Usage,
            Self::PdfaInfoMismatch => ErrorKind::Input,
            Self::DuplicateTagsIncomplete => ErrorKind::Usage,
            Self::ImportedTagsDropped => ErrorKind::Usage,
            Self::ImportedPdfaUnchecked => ErrorKind::Usage,
            Self::TounicodeConflict => ErrorKind::Usage,
            Self::WholeFontRebuilt => ErrorKind::Usage,
            Self::FlowKeepBroken => ErrorKind::Usage,
            Self::MarkdownHtmlIgnored => ErrorKind::Unsupported,
            Self::MarkdownImageMissing => ErrorKind::Usage,
            Self::CoveredText => ErrorKind::Security,
            Self::RedactionNotApplied => ErrorKind::Security,
            Self::TextInEarlierRevision => ErrorKind::Security,
        }
    }

    /// One lowercase sentence: what happened.
    ///
    /// Added in 0.2.0.
    #[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::XmpInvalid => "the XMP metadata packet is not readable XMP and reads as absent",
            Self::AnnotNameDuplicate => "two annotations on one page have the same name (/NM), which should be unique on its page",
            Self::XmpRepaired => "the XMP metadata packet had damage other readers read past, and was read the same way",
            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::ExtractLimitBlocks => "a page had more runs of text than the extraction block limit; the runs past it were left out",
            Self::ExtractReadingOrderAmbiguous => "a page mixes horizontal and vertical writing, so the order of its blocks is a guess",
            Self::ExtractTableAmbiguous => "a table's rules marked out merged cells that aren't rectangles, so its cells were kept unmerged",
            Self::ExtractTableLimit => "a page's ruling lines would make a table bigger than the extraction's cell limit; those lines gave no table",
            Self::ExtractStructTreeIgnored => "a tagged page's structure tree covered too little of its text, or its order jumped back across columns too often, so the layout gave the reading order",
            Self::ExtractUntaggedContent => "a page read in structure-tree order has visible text that is neither in the tree nor an artifact; it follows the tree's blocks, in layout order",
            Self::ExtractNeedsOcr => "a page has no usable text layer: it is an image (with or without an invisible OCR layer), outlined glyphs, or glyphs without Unicode, so its extracted text is empty or unreliable",
            Self::ExtractColumnOrderUncertain => "the layout rules had to guess how a page's columns are read, so its blocks may be in the wrong order; the blocks concerned have a lower confidence",
            Self::PdfaOneAuthor => "the file claims PDF/A-1, which allows one author, and its metadata lists more",
            Self::PdfuaTitleMissing => "the file claims PDF/UA-1, which requires a title in its metadata, and it has none",
            Self::PdfaInfoMismatch => "the file claims PDF/A, which requires the Info dictionary and the XMP packet to agree, and they differ",
            Self::DuplicateTagsIncomplete => "a duplicated page's content is partly untagged, which breaks the PDF/UA claim of the document's metadata",
            Self::ImportedTagsDropped => "pages copied in from another document came without their tags, which breaks the PDF/UA claim of the document's metadata",
            Self::ImportedPdfaUnchecked => "pages copied in from a document that doesn't claim the same PDF/A level may break the PDF/A claim of the document's metadata",
            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",
            Self::FlowKeepBroken => "blocks kept together are taller than a page, so the flow split them",
            Self::MarkdownHtmlIgnored => "the Markdown holds raw HTML, which the PDF leaves out",
            Self::MarkdownImageMissing => "the Markdown names an image that wasn't supplied, so the PDF leaves it out",
            Self::CoveredText => "a page draws text and then paints a shape, an image or an annotation over it, so the text is hidden but still in the file",
            Self::RedactionNotApplied => "a page has redaction marks that were never applied, so the text under them is still in the file",
            Self::TextInEarlierRevision => "an earlier revision of the file holds text that the latest revision no longer has",
        }
    }

    /// The hint (ADR 0026 §5), with its `{limit}`/`{option}` parameters unfilled.
    ///
    /// Added in 0.2.0.
    #[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::XmpInvalid => "nothing to do; a metadata edit asks before replacing it",
            Self::AnnotNameDuplicate => "nothing to do; both are kept, and annotations are told apart by their own IDs",
            Self::XmpRepaired => "nothing to do; a metadata edit writes the declarations the packet left out",
            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::ExtractLimitBlocks => "raise ExtractLimits::max_blocks_per_page if the page really has that many blocks",
            Self::ExtractReadingOrderAmbiguous => "nothing to do; check the order of that page's blocks, or ask for content order",
            Self::ExtractTableAmbiguous => "nothing to do; check that table's cells, whose text may be split across neighbours",
            Self::ExtractTableLimit => "raise ExtractLimits::max_table_cells if the page really has a table that big",
            Self::ExtractStructTreeIgnored => "nothing to do; ReadingOrder::Tagged uses the tree anyway",
            Self::ExtractUntaggedContent => "nothing to do; tag that text in the file to give it a place in the reading order",
            Self::ExtractNeedsOcr => "run OCR or a vision model on this page; the page's textLayer in the JSON says which case it is",
            Self::ExtractColumnOrderUncertain => "check the page, or send it to a layout model; the warning's reason says which guess was made",
            Self::PdfaOneAuthor => "keep one author (join the names into one), or save knowing the file no longer meets PDF/A-1",
            Self::PdfuaTitleMissing => "give the document a title before saving, or save knowing the file no longer meets PDF/UA-1",
            Self::PdfaInfoMismatch => "edit the metadata with setMetadata, which writes both, or remove the Info entries that differ",
            Self::DuplicateTagsIncomplete => "retag the copy, or duplicate pages whose tagged elements lie on the page alone",
            Self::ImportedTagsDropped => "tag the copied pages in a tagging tool, or copy pages from a document without tags",
            Self::ImportedPdfaUnchecked => "check the saved file with a PDF/A validator such as veraPDF, or copy pages from a document that claims the same level",
            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",
            Self::FlowKeepBroken => "split the keep group or drop keep-with-next on a heading chain, or use a taller page",
            Self::MarkdownHtmlIgnored => "write the content in Markdown instead of HTML, or remove the HTML",
            Self::MarkdownImageMissing => "pass the image's bytes with MarkdownBuildOptions::with_image under the path the Markdown uses",
            Self::CoveredText => "remove the text itself with a tool that deletes what a redaction covers, then save a full rewrite",
            Self::RedactionNotApplied => "apply the redactions in a tool that removes what they cover, then save a full rewrite",
            Self::TextInEarlierRevision => "save the file as a full rewrite, which keeps only the latest revision",
        }
    }

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