cellrune 0.1.17

Bounded XLSX/XLSM reading, deterministic calculation, editing, and writing for Rust
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
use std::error::Error;
use std::fmt;

const MESSAGE_ROW_OUT_OF_RANGE: &str = "row is outside the supported Excel range";
const MESSAGE_COLUMN_OUT_OF_RANGE: &str = "column is outside the supported Excel range";
const MESSAGE_CELL_ADDRESS_INVALID: &str = "cell address is not valid A1 notation";
const MESSAGE_RANGE_REVERSED: &str = "range start must not be after range end";
const MESSAGE_SHEET_ID_ZERO: &str = "sheet ID must be greater than zero";
const MESSAGE_SHEET_NAME_EMPTY: &str = "sheet name must not be empty";
const MESSAGE_SHEET_NAME_TOO_LONG: &str = "sheet name exceeds 31 UTF-16 code units";
const MESSAGE_SHEET_NAME_INVALID_CHARACTER: &str = "sheet name contains an invalid character";
const MESSAGE_SHEET_NAME_APOSTROPHE_BOUNDARY: &str =
    "sheet name must not begin or end with an apostrophe";
const MESSAGE_DUPLICATE_SHEET_ID: &str = "workbook contains a duplicate sheet ID";
const MESSAGE_DUPLICATE_SHEET_NAME: &str =
    "workbook contains a duplicate case-insensitive sheet name";
const MESSAGE_DUPLICATE_CELL: &str = "sheet contains a duplicate cell address";
const MESSAGE_DEFINED_NAME_EMPTY: &str = "defined name must not be empty";
const MESSAGE_DEFINED_NAME_TOO_LONG: &str = "defined name exceeds 255 UTF-16 code units";
const MESSAGE_DEFINED_NAME_CONTROL: &str = "defined name contains a control character";
const MESSAGE_DEFINED_NAME_UNKNOWN_SHEET: &str = "defined name scope references an unknown sheet";
const MESSAGE_DUPLICATE_DEFINED_NAME: &str =
    "workbook contains a duplicate case-insensitive defined name in one scope";
const MESSAGE_NON_FINITE_NUMBER: &str = "cell number must be finite";
const MESSAGE_FORMULA_EMPTY: &str = "formula text must not be empty";
const MESSAGE_XLSX_FORMULA_EQUALS: &str =
    "XLSX formula text must not include a leading equals sign";
const MESSAGE_USER_FORMULA_EQUALS: &str = "user formula text must begin with an equals sign";
const MESSAGE_SOURCE_ID_EMPTY: &str = "source ID must not be empty";
const MESSAGE_DIAGNOSTIC_CODE_INVALID: &str =
    "diagnostic code must use lowercase dotted identifiers";
const MESSAGE_PROVIDER_NAME_EMPTY: &str = "provider name must not be empty";
const MESSAGE_PROVIDER_VERSION_EMPTY: &str = "provider version must not be empty";
const MESSAGE_DIAGNOSTIC_MESSAGE_EMPTY: &str = "diagnostic message must not be empty";
const MESSAGE_UNKNOWN_SHEET_ID: &str = "workbook does not contain the requested sheet ID";
const MESSAGE_CELL_NOT_FOUND: &str = "workbook does not contain the requested cell";
const MESSAGE_SHEET_ID_EXHAUSTED: &str = "workbook cannot allocate another sheet ID";
const MESSAGE_LAST_VISIBLE_SHEET: &str = "workbook must retain at least one visible sheet";
const MESSAGE_SEMANTIC_REVISION_EXHAUSTED: &str = "workbook semantic revision is exhausted";
const MESSAGE_PRESENTATION_REVISION_EXHAUSTED: &str = "workbook presentation revision is exhausted";
const MESSAGE_PHONETIC_RANGE_EMPTY: &str = "phonetic text range start must be less than its end";
const MESSAGE_PHONETIC_RANGE_OUT_OF_BOUNDS: &str = "phonetic text range exceeds the base text";
const MESSAGE_PHONETIC_RANGE_SPLITS_SURROGATE: &str =
    "phonetic text range must use UTF-16 character boundaries";
const MESSAGE_PHONETIC_RUNS_OUT_OF_ORDER: &str =
    "phonetic runs must be ordered and non-overlapping";
const MESSAGE_PHONETIC_TEXT_EMPTY: &str = "phonetic text must not be empty";
const MESSAGE_PHONETIC_TEXT_INVALID_CHARACTER: &str =
    "phonetic text contains a character forbidden by XML 1.0";
const MESSAGE_PHONETICS_REQUIRE_TEXT_CELL: &str =
    "phonetic annotations require a literal text cell";
const MESSAGE_PHONETIC_FONT_ID_UNSUPPORTED: &str =
    "phonetic authoring currently supports only the default font record";
const MESSAGE_ANNOTATED_TEXT_REPLACEMENT_REQUIRED: &str =
    "annotated text must be cleared or replaced atomically";
const MESSAGE_FROZEN_ROWS_OUT_OF_RANGE: &str =
    "frozen row count cannot produce a valid top-left cell";
const MESSAGE_FROZEN_COLUMNS_OUT_OF_RANGE: &str =
    "frozen column count cannot produce a valid top-left cell";
const MESSAGE_TABLE_ID_ZERO: &str = "table ID must be greater than zero";
const MESSAGE_TABLE_COLUMN_ID_ZERO: &str = "table column ID must be greater than zero";
const MESSAGE_TABLE_NAME_EMPTY: &str = "table name must not be empty";
const MESSAGE_TABLE_NAME_TOO_LONG: &str = "table name exceeds 255 UTF-16 code units";
const MESSAGE_TABLE_NAME_INVALID_CHARACTER: &str = "table name contains an invalid character";
const MESSAGE_TABLE_NAME_REFERENCE_CONFLICT: &str =
    "table name must not be an A1 or R1C1 reference";
const MESSAGE_DUPLICATE_TABLE_DISPLAY_NAME: &str =
    "workbook contains a duplicate case-insensitive table display name";
const MESSAGE_DUPLICATE_TABLE_ID: &str = "workbook contains a duplicate table ID";
const MESSAGE_DUPLICATE_TABLE_PROGRAMMATIC_NAME: &str =
    "worksheet contains a duplicate case-insensitive programmatic table name";
const MESSAGE_TABLE_DISPLAY_NAME_CONFLICTS_WITH_DEFINED_NAME: &str =
    "table display name conflicts with a workbook defined name";
const MESSAGE_TABLE_COLUMNS_EMPTY: &str = "table must declare at least one column";
const MESSAGE_TABLE_COLUMN_COUNT_MISMATCH: &str =
    "table column count does not match the table range width";
const MESSAGE_TABLE_COLUMN_NAME_EMPTY: &str = "table column name must not be empty";
const MESSAGE_TABLE_COLUMN_NAME_TOO_LONG: &str = "table column name exceeds 255 UTF-16 code units";
const MESSAGE_TABLE_COLUMN_NAME_INVALID_CHARACTER: &str =
    "table column name contains a character forbidden by XML 1.0";
const MESSAGE_TABLE_COLUMN_NAME_SPACE_BOUNDARY: &str =
    "table column name must not begin or end with an ASCII space";
const MESSAGE_DUPLICATE_TABLE_COLUMN_NAME: &str =
    "table contains a duplicate case-insensitive column name";
const MESSAGE_DUPLICATE_TABLE_COLUMN_ID: &str = "table contains a duplicate column identifier";
const MESSAGE_OVERLAPPING_TABLES: &str = "worksheet contains overlapping table ranges";
const MESSAGE_TABLE_ROW_COUNTS_EXCEED_RANGE: &str =
    "table header and totals rows exceed the table range height";
const MESSAGE_INVALID_TABLE_TOTALS_METADATA: &str =
    "table totals label, function, and formula metadata are inconsistent";
const MESSAGE_UNKNOWN_TABLE_ID: &str = "workbook does not contain the requested table ID";
const MESSAGE_UNKNOWN_TABLE_COLUMN_ID: &str = "table does not contain the requested column ID";
const MESSAGE_TABLE_DATA_ROWS_REVERSED: &str = "table data row start must not be after its end";
const MESSAGE_TABLE_RESIZE_HEADER_UNDERFLOW: &str =
    "table data row start cannot accommodate the declared header rows";
const MESSAGE_TABLE_MATERIALIZATION_COLLISION: &str =
    "table materialization would overwrite non-equivalent worksheet content";
const MESSAGE_UNSUPPORTED_TABLE_AUTHORING_METADATA: &str =
    "table metadata cannot be preserved safely by this authoring operation";
const MESSAGE_FORMULA_REWRITE_PARSE_FAILED: &str =
    "a formula related to the rename could not be parsed for typed rewriting";
const MESSAGE_NUMBER_FORMAT_BUILTIN_ID: &str = "built-in number format ID must be less than 164";
const MESSAGE_NUMBER_FORMAT_CUSTOM_ID: &str = "custom number format ID must be at least 164";
const MESSAGE_NUMBER_FORMAT_CODE_EMPTY: &str = "custom number format code must not be empty";

/// Stable machine-readable code for a format-neutral validation failure.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[non_exhaustive]
pub enum ValidationErrorCode {
    /// A row index is outside the supported Excel range.
    RowOutOfRange,
    /// A column index is outside the supported Excel range.
    ColumnOutOfRange,
    /// A cell address is not valid A1 notation.
    CellAddressInvalid,
    /// A range start is after its end.
    RangeStartAfterEnd,
    /// A sheet identifier is zero.
    SheetIdZero,
    /// A sheet name is empty.
    SheetNameEmpty,
    /// A sheet name exceeds Excel's length limit.
    SheetNameTooLong,
    /// A sheet name contains a forbidden character.
    SheetNameInvalidCharacter,
    /// A sheet name begins or ends with an apostrophe.
    SheetNameApostropheBoundary,
    /// A workbook contains a duplicate sheet identifier.
    DuplicateSheetId,
    /// A workbook contains a duplicate case-insensitive sheet name.
    DuplicateSheetName,
    /// A sheet contains a duplicate cell address.
    DuplicateCell,
    /// A defined name is empty.
    DefinedNameEmpty,
    /// A defined name exceeds Excel's length limit.
    DefinedNameTooLong,
    /// A defined name contains a control character.
    DefinedNameControlCharacter,
    /// A sheet-scoped defined name references an unknown sheet.
    DefinedNameUnknownSheet,
    /// A workbook contains a duplicate defined name in one scope.
    DuplicateDefinedName,
    /// A numeric cell contains NaN or infinity.
    NonFiniteNumber,
    /// Formula text is empty.
    FormulaEmpty,
    /// Stored XLSX formula text includes a leading equals sign.
    XlsxFormulaHasLeadingEquals,
    /// User formula text omits a leading equals sign.
    UserFormulaMissingLeadingEquals,
    /// A source identifier is empty.
    SourceIdEmpty,
    /// A diagnostic code does not follow the stable code grammar.
    DiagnosticCodeInvalid,
    /// A provenance provider name is empty.
    ProviderNameEmpty,
    /// A provenance provider version is empty.
    ProviderVersionEmpty,
    /// A diagnostic message is empty.
    DiagnosticMessageEmpty,
    /// A draft operation references an unknown sheet.
    UnknownSheetId,
    /// A draft operation references a missing sparse cell.
    CellNotFound,
    /// No additional nonzero sheet identifier can be allocated.
    SheetIdExhausted,
    /// A workbook edit would hide its last visible sheet.
    LastVisibleSheet,
    /// The semantic revision counter is exhausted.
    SemanticRevisionExhausted,
    /// The presentation revision counter is exhausted.
    PresentationRevisionExhausted,
    /// A phonetic range is empty or reversed.
    PhoneticRangeEmpty,
    /// A phonetic range exceeds its base text.
    PhoneticRangeOutOfBounds,
    /// A phonetic range boundary splits a UTF-16 surrogate pair.
    PhoneticRangeSplitsSurrogate,
    /// Phonetic runs are unordered or overlapping.
    PhoneticRunsOutOfOrder,
    /// A phonetic run contains no text.
    PhoneticTextEmpty,
    /// Phonetic text contains a character forbidden by XML 1.0.
    PhoneticTextInvalidCharacter,
    /// Phonetic annotations target a non-text cell.
    PhoneticsRequireTextCell,
    /// A phonetic annotation references an unsupported font record.
    PhoneticFontIdUnsupported,
    /// A normal value edit would discard an existing annotation.
    AnnotatedTextReplacementRequired,
    /// A frozen row count cannot be represented within worksheet bounds.
    FrozenRowsOutOfRange,
    /// A frozen column count cannot be represented within worksheet bounds.
    FrozenColumnsOutOfRange,
    /// A built-in number format uses a custom-format identifier.
    BuiltInNumberFormatId,
    /// A custom number format uses a reserved built-in identifier.
    CustomNumberFormatId,
    /// A custom number format code is empty.
    NumberFormatCodeEmpty,
    /// A table identifier is zero.
    TableIdZero,
    /// A table column identifier is zero.
    TableColumnIdZero,
    /// A table name is empty.
    TableNameEmpty,
    /// A table name exceeds Excel's length limit.
    TableNameTooLong,
    /// A table name contains a forbidden character.
    TableNameInvalidCharacter,
    /// A table name is an A1 or R1C1 reference.
    TableNameReferenceConflict,
    /// A workbook contains a duplicate case-insensitive table display name.
    DuplicateTableDisplayName,
    /// A workbook contains a duplicate table identifier.
    DuplicateTableId,
    /// One worksheet contains a duplicate programmatic table name.
    DuplicateTableProgrammaticName,
    /// A table display name conflicts with a defined name.
    TableDisplayNameConflictsWithDefinedName,
    /// A table declares no columns.
    TableColumnsEmpty,
    /// A table's column count disagrees with its range width.
    TableColumnCountMismatch,
    /// A table column name is empty.
    TableColumnNameEmpty,
    /// A table column name exceeds Excel's length limit.
    TableColumnNameTooLong,
    /// A table column name contains a character forbidden by XML 1.0.
    TableColumnNameInvalidCharacter,
    /// A table-column authoring name begins or ends with an ASCII space.
    TableColumnNameSpaceBoundary,
    /// A table contains a duplicate case-insensitive column name.
    DuplicateTableColumnName,
    /// A table contains a duplicate column identifier.
    DuplicateTableColumnId,
    /// Two tables on one worksheet have overlapping ranges.
    OverlappingTables,
    /// A table's header and totals rows exceed its range height.
    TableRowCountsExceedRange,
    /// A table column contains inconsistent totals metadata.
    InvalidTableTotalsMetadata,
    /// A draft operation references an unknown table ID.
    UnknownTableId,
    /// A draft operation references an unknown table column ID.
    UnknownTableColumnId,
    /// A table resize declares reversed data rows.
    TableDataRowsReversed,
    /// A table resize cannot place its header above the first data row.
    TableResizeHeaderUnderflow,
    /// Table materialization would overwrite non-equivalent worksheet content.
    TableMaterializationCollision,
    /// Table metadata cannot be safely authored.
    UnsupportedTableAuthoringMetadata,
    /// A target-related formula could not be parsed for typed rewriting.
    FormulaRewriteParseFailed,
}

impl ValidationErrorCode {
    /// Returns the stable dotted identifier used across bindings.
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::RowOutOfRange => "validation.row_out_of_range",
            Self::ColumnOutOfRange => "validation.column_out_of_range",
            Self::CellAddressInvalid => "validation.cell_address_invalid",
            Self::RangeStartAfterEnd => "validation.range_start_after_end",
            Self::SheetIdZero => "validation.sheet_id_zero",
            Self::SheetNameEmpty => "validation.sheet_name_empty",
            Self::SheetNameTooLong => "validation.sheet_name_too_long",
            Self::SheetNameInvalidCharacter => "validation.sheet_name_invalid_character",
            Self::SheetNameApostropheBoundary => "validation.sheet_name_apostrophe_boundary",
            Self::DuplicateSheetId => "validation.duplicate_sheet_id",
            Self::DuplicateSheetName => "validation.duplicate_sheet_name",
            Self::DuplicateCell => "validation.duplicate_cell",
            Self::DefinedNameEmpty => "validation.defined_name_empty",
            Self::DefinedNameTooLong => "validation.defined_name_too_long",
            Self::DefinedNameControlCharacter => "validation.defined_name_control_character",
            Self::DefinedNameUnknownSheet => "validation.defined_name_unknown_sheet",
            Self::DuplicateDefinedName => "validation.duplicate_defined_name",
            Self::NonFiniteNumber => "validation.non_finite_number",
            Self::FormulaEmpty => "validation.formula_empty",
            Self::XlsxFormulaHasLeadingEquals => "validation.xlsx_formula_has_leading_equals",
            Self::UserFormulaMissingLeadingEquals => {
                "validation.user_formula_missing_leading_equals"
            }
            Self::SourceIdEmpty => "validation.source_id_empty",
            Self::DiagnosticCodeInvalid => "validation.diagnostic_code_invalid",
            Self::ProviderNameEmpty => "validation.provider_name_empty",
            Self::ProviderVersionEmpty => "validation.provider_version_empty",
            Self::DiagnosticMessageEmpty => "validation.diagnostic_message_empty",
            Self::UnknownSheetId => "validation.unknown_sheet_id",
            Self::CellNotFound => "validation.cell_not_found",
            Self::SheetIdExhausted => "validation.sheet_id_exhausted",
            Self::LastVisibleSheet => "validation.last_visible_sheet",
            Self::SemanticRevisionExhausted => "validation.semantic_revision_exhausted",
            Self::PresentationRevisionExhausted => "validation.presentation_revision_exhausted",
            Self::PhoneticRangeEmpty => "validation.phonetic_range_empty",
            Self::PhoneticRangeOutOfBounds => "validation.phonetic_range_out_of_bounds",
            Self::PhoneticRangeSplitsSurrogate => "validation.phonetic_range_splits_surrogate",
            Self::PhoneticRunsOutOfOrder => "validation.phonetic_runs_out_of_order",
            Self::PhoneticTextEmpty => "validation.phonetic_text_empty",
            Self::PhoneticTextInvalidCharacter => "validation.phonetic_text_invalid_character",
            Self::PhoneticsRequireTextCell => "validation.phonetics_require_text_cell",
            Self::PhoneticFontIdUnsupported => "validation.phonetic_font_id_unsupported",
            Self::AnnotatedTextReplacementRequired => {
                "validation.annotated_text_replacement_required"
            }
            Self::FrozenRowsOutOfRange => "validation.frozen_rows_out_of_range",
            Self::FrozenColumnsOutOfRange => "validation.frozen_columns_out_of_range",
            Self::BuiltInNumberFormatId => "validation.built_in_number_format_id",
            Self::CustomNumberFormatId => "validation.custom_number_format_id",
            Self::NumberFormatCodeEmpty => "validation.number_format_code_empty",
            Self::TableIdZero => "validation.table_id_zero",
            Self::TableColumnIdZero => "validation.table_column_id_zero",
            Self::TableNameEmpty => "validation.table_name_empty",
            Self::TableNameTooLong => "validation.table_name_too_long",
            Self::TableNameInvalidCharacter => "validation.table_name_invalid_character",
            Self::TableNameReferenceConflict => "validation.table_name_reference_conflict",
            Self::DuplicateTableDisplayName => "validation.duplicate_table_display_name",
            Self::DuplicateTableId => "validation.duplicate_table_id",
            Self::DuplicateTableProgrammaticName => "validation.duplicate_table_programmatic_name",
            Self::TableDisplayNameConflictsWithDefinedName => {
                "validation.table_display_name_conflicts_with_defined_name"
            }
            Self::TableColumnsEmpty => "validation.table_columns_empty",
            Self::TableColumnCountMismatch => "validation.table_column_count_mismatch",
            Self::TableColumnNameEmpty => "validation.table_column_name_empty",
            Self::TableColumnNameTooLong => "validation.table_column_name_too_long",
            Self::TableColumnNameInvalidCharacter => {
                "validation.table_column_name_invalid_character"
            }
            Self::TableColumnNameSpaceBoundary => "validation.table_column_name_space_boundary",
            Self::DuplicateTableColumnName => "validation.duplicate_table_column_name",
            Self::DuplicateTableColumnId => "validation.duplicate_table_column_id",
            Self::OverlappingTables => "validation.overlapping_tables",
            Self::TableRowCountsExceedRange => "validation.table_row_counts_exceed_range",
            Self::InvalidTableTotalsMetadata => "validation.invalid_table_totals_metadata",
            Self::UnknownTableId => "validation.unknown_table_id",
            Self::UnknownTableColumnId => "validation.unknown_table_column_id",
            Self::TableDataRowsReversed => "validation.table_data_rows_reversed",
            Self::TableResizeHeaderUnderflow => "validation.table_resize_header_underflow",
            Self::TableMaterializationCollision => "validation.table_materialization_collision",
            Self::UnsupportedTableAuthoringMetadata => {
                "validation.unsupported_table_authoring_metadata"
            }
            Self::FormulaRewriteParseFailed => "validation.formula_rewrite_parse_failed",
        }
    }
}

/// A violation of a format-neutral workbook invariant.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum ValidationError {
    /// A row index is not in `1..=1_048_576`.
    RowOutOfRange {
        /// Rejected one-based row index.
        value: u32,
    },
    /// A column index is not in `1..=16_384`.
    ColumnOutOfRange {
        /// Rejected one-based column index.
        value: u32,
    },
    /// A cell address does not use an ASCII column label followed by a one-based row number.
    CellAddressInvalid,
    /// A range start is below or to the right of its end.
    RangeStartAfterEnd,
    /// A sheet ID is zero.
    SheetIdZero,
    /// A sheet name is empty.
    SheetNameEmpty,
    /// A sheet name is longer than Excel's 31 UTF-16 code-unit limit.
    SheetNameTooLong {
        /// Length of the rejected name in UTF-16 code units.
        utf16_len: usize,
    },
    /// A sheet name contains a forbidden character.
    SheetNameInvalidCharacter {
        /// Forbidden character found in the sheet name.
        character: char,
    },
    /// A sheet name begins or ends with an apostrophe.
    SheetNameApostropheBoundary,
    /// Two sheets use the same ID.
    DuplicateSheetId {
        /// Repeated nonzero sheet identifier.
        value: u32,
    },
    /// Two sheets use names that compare equal without case.
    DuplicateSheetName {
        /// Repeated sheet name as supplied by the caller.
        name: String,
    },
    /// A sparse sheet contains the same address more than once.
    DuplicateCell {
        /// One-based row of the repeated address.
        row: u32,
        /// One-based column of the repeated address.
        column: u32,
    },
    /// A defined name is empty.
    DefinedNameEmpty,
    /// A defined name exceeds Excel's 255 UTF-16 code-unit limit.
    DefinedNameTooLong {
        /// Length of the rejected name in UTF-16 code units.
        utf16_len: usize,
    },
    /// A defined name contains a control character.
    DefinedNameControlCharacter {
        /// Control character found in the defined name.
        character: char,
    },
    /// A sheet-scoped defined name references no workbook sheet.
    DefinedNameUnknownSheet {
        /// Missing sheet identifier referenced by the scope.
        sheet_id: u32,
    },
    /// Two defined names compare equal in the same scope.
    DuplicateDefinedName {
        /// Repeated defined name as supplied by the caller.
        name: String,
    },
    /// A numeric cell contains NaN or infinity.
    NonFiniteNumber,
    /// Formula text is empty or only whitespace.
    FormulaEmpty,
    /// Stored XLSX formula text incorrectly includes `=`.
    XlsxFormulaHasLeadingEquals,
    /// User-entered formula text is missing `=`.
    UserFormulaMissingLeadingEquals,
    /// A source identifier is empty.
    SourceIdEmpty,
    /// A diagnostic code does not follow the stable code grammar.
    DiagnosticCodeInvalid,
    /// A provenance provider name is empty.
    ProviderNameEmpty,
    /// A provenance provider version is empty.
    ProviderVersionEmpty,
    /// A diagnostic message is empty.
    DiagnosticMessageEmpty,
    /// A draft operation references no workbook sheet.
    UnknownSheetId {
        /// Missing sheet identifier.
        value: u32,
    },
    /// A draft operation requires an existing sparse cell.
    CellNotFound {
        /// Sheet containing the missing address.
        sheet_id: u32,
        /// One-based row of the missing cell.
        row: u32,
        /// One-based column of the missing cell.
        column: u32,
    },
    /// No larger nonzero sheet identifier can be allocated.
    SheetIdExhausted,
    /// A visibility edit would leave the workbook without a visible sheet.
    LastVisibleSheet,
    /// A draft cannot increment its monotonic semantic revision.
    SemanticRevisionExhausted,
    /// A draft cannot increment its monotonic presentation revision.
    PresentationRevisionExhausted,
    /// A phonetic range is empty or reversed.
    PhoneticRangeEmpty {
        /// Rejected zero-based UTF-16 start offset.
        start: u32,
        /// Rejected exclusive zero-based UTF-16 end offset.
        end: u32,
    },
    /// A phonetic range exceeds its base text.
    PhoneticRangeOutOfBounds {
        /// Rejected exclusive zero-based UTF-16 end offset.
        end: u32,
        /// UTF-16 code-unit length of the base text.
        base_utf16_len: u32,
    },
    /// A phonetic range boundary falls between a UTF-16 surrogate pair.
    PhoneticRangeSplitsSurrogate {
        /// Rejected zero-based UTF-16 offset.
        offset: u32,
    },
    /// Authoring runs are not strictly ordered and non-overlapping.
    PhoneticRunsOutOfOrder,
    /// A phonetic run contains no text.
    PhoneticTextEmpty,
    /// Phonetic text contains a character forbidden by XML 1.0.
    PhoneticTextInvalidCharacter {
        /// Rejected character.
        character: char,
    },
    /// A caller attempted to attach phonetics to a non-text cell.
    PhoneticsRequireTextCell {
        /// Sheet containing the rejected cell.
        sheet_id: u32,
        /// One-based row of the rejected cell.
        row: u32,
        /// One-based column of the rejected cell.
        column: u32,
    },
    /// Phonetic authoring referenced a font record outside the initial writer contract.
    PhoneticFontIdUnsupported {
        /// Rejected zero-based font record identifier.
        value: u32,
    },
    /// A normal value edit would silently discard an existing annotation.
    AnnotatedTextReplacementRequired {
        /// Sheet containing the annotated cell.
        sheet_id: u32,
        /// One-based row of the annotated cell.
        row: u32,
        /// One-based column of the annotated cell.
        column: u32,
    },
    /// A frozen row count cannot be represented within Excel worksheet bounds.
    FrozenRowsOutOfRange {
        /// Rejected frozen row count.
        value: u32,
    },
    /// A frozen column count cannot be represented within Excel worksheet bounds.
    FrozenColumnsOutOfRange {
        /// Rejected frozen column count.
        value: u32,
    },
    /// A built-in number format used a custom-format identifier.
    BuiltInNumberFormatId {
        /// Rejected number-format identifier.
        value: u32,
    },
    /// A custom number format used a reserved built-in identifier.
    CustomNumberFormatId {
        /// Rejected number-format identifier.
        value: u32,
    },
    /// A custom number format code is empty.
    NumberFormatCodeEmpty,
    /// An OOXML table identifier is zero.
    TableIdZero,
    /// An OOXML table column identifier is zero.
    TableColumnIdZero,
    /// A table name is empty.
    TableNameEmpty,
    /// A table name is longer than Excel's 255 UTF-16 code-unit limit.
    TableNameTooLong {
        /// Length of the rejected name in UTF-16 code units.
        utf16_len: usize,
    },
    /// A table name contains whitespace or a control character.
    TableNameInvalidCharacter {
        /// Forbidden character found in the table name.
        character: char,
    },
    /// A table name is parsed by Excel as an A1 or R1C1 reference.
    TableNameReferenceConflict,
    /// Two tables anywhere in the workbook use display names that compare equal without case.
    DuplicateTableDisplayName {
        /// Repeated table display name as supplied by the caller.
        name: String,
    },
    /// Two tables in the workbook use the same non-zero identifier.
    DuplicateTableId {
        /// Repeated table identifier.
        id: u32,
    },
    /// Two tables on one worksheet use programmatic names that compare equal without case.
    DuplicateTableProgrammaticName {
        /// Repeated programmatic name as supplied by the caller.
        name: String,
    },
    /// A table display name compares equal to a workbook defined name.
    TableDisplayNameConflictsWithDefinedName {
        /// Conflicting table display name as supplied by the caller.
        name: String,
    },
    /// A table declares no columns.
    TableColumnsEmpty,
    /// A table's declared column count disagrees with its range width.
    TableColumnCountMismatch {
        /// Number of declared columns.
        columns: usize,
        /// Width of the table range in columns.
        width: u32,
    },
    /// A table column name is empty.
    TableColumnNameEmpty,
    /// A table column name is longer than Excel's 255 UTF-16 code-unit limit.
    TableColumnNameTooLong {
        /// Length of the rejected name in UTF-16 code units.
        utf16_len: usize,
    },
    /// A table column name contains a character forbidden by XML 1.0.
    TableColumnNameInvalidCharacter {
        /// Forbidden character found in the table column name.
        character: char,
    },
    /// A table-column authoring name begins or ends with an ASCII space.
    TableColumnNameSpaceBoundary,
    /// Two columns in one table use names that compare equal without case.
    DuplicateTableColumnName {
        /// Repeated column name as supplied by the caller.
        name: String,
    },
    /// Two columns in one table use the same identifier.
    DuplicateTableColumnId {
        /// Repeated column identifier.
        id: u32,
    },
    /// Two tables on one worksheet have overlapping ranges.
    OverlappingTables {
        /// Worksheet containing both tables.
        sheet_id: u32,
        /// First table in deterministic range order.
        first_table_id: u32,
        /// Overlapping table in deterministic range order.
        second_table_id: u32,
    },
    /// A table's header and totals rows do not fit inside its range.
    TableRowCountsExceedRange {
        /// Declared header row count.
        header_row_count: u32,
        /// Declared totals row count.
        totals_row_count: u32,
        /// Height of the table range in rows.
        height: u32,
    },
    /// A table column's totals label, function, and formula metadata are inconsistent.
    InvalidTableTotalsMetadata,
    /// A draft operation references no table with the supplied stable ID.
    UnknownTableId {
        /// Missing table identifier.
        value: u32,
    },
    /// A draft operation references no column with the supplied stable ID.
    UnknownTableColumnId {
        /// Table containing the missing column.
        table_id: u32,
        /// Missing column identifier.
        column_id: u32,
    },
    /// A table resize declares a first data row below its last data row.
    TableDataRowsReversed {
        /// Rejected first data row.
        first_data_row: u32,
        /// Rejected last data row.
        last_data_row: u32,
    },
    /// A table resize cannot place declared header rows above its first data row.
    TableResizeHeaderUnderflow {
        /// Target table.
        table_id: u32,
        /// Rejected first data row.
        first_data_row: u32,
        /// Declared header row count.
        header_row_count: u32,
    },
    /// Table materialization would overwrite non-equivalent worksheet content.
    TableMaterializationCollision {
        /// Target table.
        table_id: u32,
        /// Worksheet containing the collision.
        sheet_id: u32,
        /// One-based row of the collision.
        row: u32,
        /// One-based column of the collision.
        column: u32,
    },
    /// Table metadata cannot be preserved safely by the requested authoring operation.
    UnsupportedTableAuthoringMetadata {
        /// Target table.
        table_id: u32,
    },
    /// A formula related to a rename could not be parsed for typed rewriting.
    FormulaRewriteParseFailed {
        /// Stable parser error code.
        parse_code: String,
        /// Start byte of the parser error.
        start: usize,
        /// End byte of the parser error.
        end: usize,
        /// Stable workbook owner context for the rejected formula, when available.
        owner: Option<String>,
    },
}

impl ValidationError {
    /// Returns the stable machine-readable code for this validation failure.
    pub const fn code(&self) -> ValidationErrorCode {
        match self {
            Self::RowOutOfRange { .. } => ValidationErrorCode::RowOutOfRange,
            Self::ColumnOutOfRange { .. } => ValidationErrorCode::ColumnOutOfRange,
            Self::CellAddressInvalid => ValidationErrorCode::CellAddressInvalid,
            Self::RangeStartAfterEnd => ValidationErrorCode::RangeStartAfterEnd,
            Self::SheetIdZero => ValidationErrorCode::SheetIdZero,
            Self::SheetNameEmpty => ValidationErrorCode::SheetNameEmpty,
            Self::SheetNameTooLong { .. } => ValidationErrorCode::SheetNameTooLong,
            Self::SheetNameInvalidCharacter { .. } => {
                ValidationErrorCode::SheetNameInvalidCharacter
            }
            Self::SheetNameApostropheBoundary => ValidationErrorCode::SheetNameApostropheBoundary,
            Self::DuplicateSheetId { .. } => ValidationErrorCode::DuplicateSheetId,
            Self::DuplicateSheetName { .. } => ValidationErrorCode::DuplicateSheetName,
            Self::DuplicateCell { .. } => ValidationErrorCode::DuplicateCell,
            Self::DefinedNameEmpty => ValidationErrorCode::DefinedNameEmpty,
            Self::DefinedNameTooLong { .. } => ValidationErrorCode::DefinedNameTooLong,
            Self::DefinedNameControlCharacter { .. } => {
                ValidationErrorCode::DefinedNameControlCharacter
            }
            Self::DefinedNameUnknownSheet { .. } => ValidationErrorCode::DefinedNameUnknownSheet,
            Self::DuplicateDefinedName { .. } => ValidationErrorCode::DuplicateDefinedName,
            Self::NonFiniteNumber => ValidationErrorCode::NonFiniteNumber,
            Self::FormulaEmpty => ValidationErrorCode::FormulaEmpty,
            Self::XlsxFormulaHasLeadingEquals => ValidationErrorCode::XlsxFormulaHasLeadingEquals,
            Self::UserFormulaMissingLeadingEquals => {
                ValidationErrorCode::UserFormulaMissingLeadingEquals
            }
            Self::SourceIdEmpty => ValidationErrorCode::SourceIdEmpty,
            Self::DiagnosticCodeInvalid => ValidationErrorCode::DiagnosticCodeInvalid,
            Self::ProviderNameEmpty => ValidationErrorCode::ProviderNameEmpty,
            Self::ProviderVersionEmpty => ValidationErrorCode::ProviderVersionEmpty,
            Self::DiagnosticMessageEmpty => ValidationErrorCode::DiagnosticMessageEmpty,
            Self::UnknownSheetId { .. } => ValidationErrorCode::UnknownSheetId,
            Self::CellNotFound { .. } => ValidationErrorCode::CellNotFound,
            Self::SheetIdExhausted => ValidationErrorCode::SheetIdExhausted,
            Self::LastVisibleSheet => ValidationErrorCode::LastVisibleSheet,
            Self::SemanticRevisionExhausted => ValidationErrorCode::SemanticRevisionExhausted,
            Self::PresentationRevisionExhausted => {
                ValidationErrorCode::PresentationRevisionExhausted
            }
            Self::PhoneticRangeEmpty { .. } => ValidationErrorCode::PhoneticRangeEmpty,
            Self::PhoneticRangeOutOfBounds { .. } => ValidationErrorCode::PhoneticRangeOutOfBounds,
            Self::PhoneticRangeSplitsSurrogate { .. } => {
                ValidationErrorCode::PhoneticRangeSplitsSurrogate
            }
            Self::PhoneticRunsOutOfOrder => ValidationErrorCode::PhoneticRunsOutOfOrder,
            Self::PhoneticTextEmpty => ValidationErrorCode::PhoneticTextEmpty,
            Self::PhoneticTextInvalidCharacter { .. } => {
                ValidationErrorCode::PhoneticTextInvalidCharacter
            }
            Self::PhoneticsRequireTextCell { .. } => ValidationErrorCode::PhoneticsRequireTextCell,
            Self::PhoneticFontIdUnsupported { .. } => {
                ValidationErrorCode::PhoneticFontIdUnsupported
            }
            Self::AnnotatedTextReplacementRequired { .. } => {
                ValidationErrorCode::AnnotatedTextReplacementRequired
            }
            Self::FrozenRowsOutOfRange { .. } => ValidationErrorCode::FrozenRowsOutOfRange,
            Self::FrozenColumnsOutOfRange { .. } => ValidationErrorCode::FrozenColumnsOutOfRange,
            Self::BuiltInNumberFormatId { .. } => ValidationErrorCode::BuiltInNumberFormatId,
            Self::CustomNumberFormatId { .. } => ValidationErrorCode::CustomNumberFormatId,
            Self::NumberFormatCodeEmpty => ValidationErrorCode::NumberFormatCodeEmpty,
            Self::TableIdZero => ValidationErrorCode::TableIdZero,
            Self::TableColumnIdZero => ValidationErrorCode::TableColumnIdZero,
            Self::TableNameEmpty => ValidationErrorCode::TableNameEmpty,
            Self::TableNameTooLong { .. } => ValidationErrorCode::TableNameTooLong,
            Self::TableNameInvalidCharacter { .. } => {
                ValidationErrorCode::TableNameInvalidCharacter
            }
            Self::TableNameReferenceConflict => ValidationErrorCode::TableNameReferenceConflict,
            Self::DuplicateTableDisplayName { .. } => {
                ValidationErrorCode::DuplicateTableDisplayName
            }
            Self::DuplicateTableId { .. } => ValidationErrorCode::DuplicateTableId,
            Self::DuplicateTableProgrammaticName { .. } => {
                ValidationErrorCode::DuplicateTableProgrammaticName
            }
            Self::TableDisplayNameConflictsWithDefinedName { .. } => {
                ValidationErrorCode::TableDisplayNameConflictsWithDefinedName
            }
            Self::TableColumnsEmpty => ValidationErrorCode::TableColumnsEmpty,
            Self::TableColumnCountMismatch { .. } => ValidationErrorCode::TableColumnCountMismatch,
            Self::TableColumnNameEmpty => ValidationErrorCode::TableColumnNameEmpty,
            Self::TableColumnNameTooLong { .. } => ValidationErrorCode::TableColumnNameTooLong,
            Self::TableColumnNameInvalidCharacter { .. } => {
                ValidationErrorCode::TableColumnNameInvalidCharacter
            }
            Self::TableColumnNameSpaceBoundary => ValidationErrorCode::TableColumnNameSpaceBoundary,
            Self::DuplicateTableColumnName { .. } => ValidationErrorCode::DuplicateTableColumnName,
            Self::DuplicateTableColumnId { .. } => ValidationErrorCode::DuplicateTableColumnId,
            Self::OverlappingTables { .. } => ValidationErrorCode::OverlappingTables,
            Self::TableRowCountsExceedRange { .. } => {
                ValidationErrorCode::TableRowCountsExceedRange
            }
            Self::InvalidTableTotalsMetadata => ValidationErrorCode::InvalidTableTotalsMetadata,
            Self::UnknownTableId { .. } => ValidationErrorCode::UnknownTableId,
            Self::UnknownTableColumnId { .. } => ValidationErrorCode::UnknownTableColumnId,
            Self::TableDataRowsReversed { .. } => ValidationErrorCode::TableDataRowsReversed,
            Self::TableResizeHeaderUnderflow { .. } => {
                ValidationErrorCode::TableResizeHeaderUnderflow
            }
            Self::TableMaterializationCollision { .. } => {
                ValidationErrorCode::TableMaterializationCollision
            }
            Self::UnsupportedTableAuthoringMetadata { .. } => {
                ValidationErrorCode::UnsupportedTableAuthoringMetadata
            }
            Self::FormulaRewriteParseFailed { .. } => {
                ValidationErrorCode::FormulaRewriteParseFailed
            }
        }
    }
}

impl fmt::Display for ValidationError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::RowOutOfRange { value } => {
                write!(formatter, "{MESSAGE_ROW_OUT_OF_RANGE}: {value}")
            }
            Self::ColumnOutOfRange { value } => {
                write!(formatter, "{MESSAGE_COLUMN_OUT_OF_RANGE}: {value}")
            }
            Self::CellAddressInvalid => formatter.write_str(MESSAGE_CELL_ADDRESS_INVALID),
            Self::RangeStartAfterEnd => formatter.write_str(MESSAGE_RANGE_REVERSED),
            Self::SheetIdZero => formatter.write_str(MESSAGE_SHEET_ID_ZERO),
            Self::SheetNameEmpty => formatter.write_str(MESSAGE_SHEET_NAME_EMPTY),
            Self::SheetNameTooLong { utf16_len } => {
                write!(formatter, "{MESSAGE_SHEET_NAME_TOO_LONG}: {utf16_len}")
            }
            Self::SheetNameInvalidCharacter { character } => write!(
                formatter,
                "{MESSAGE_SHEET_NAME_INVALID_CHARACTER}: {character:?}"
            ),
            Self::SheetNameApostropheBoundary => {
                formatter.write_str(MESSAGE_SHEET_NAME_APOSTROPHE_BOUNDARY)
            }
            Self::DuplicateSheetId { value } => {
                write!(formatter, "{MESSAGE_DUPLICATE_SHEET_ID}: {value}")
            }
            Self::DuplicateSheetName { name } => {
                write!(formatter, "{MESSAGE_DUPLICATE_SHEET_NAME}: {name}")
            }
            Self::DuplicateCell { row, column } => {
                write!(
                    formatter,
                    "{MESSAGE_DUPLICATE_CELL}: row {row}, column {column}"
                )
            }
            Self::DefinedNameEmpty => formatter.write_str(MESSAGE_DEFINED_NAME_EMPTY),
            Self::DefinedNameTooLong { utf16_len } => {
                write!(formatter, "{MESSAGE_DEFINED_NAME_TOO_LONG}: {utf16_len}")
            }
            Self::DefinedNameControlCharacter { character } => {
                write!(formatter, "{MESSAGE_DEFINED_NAME_CONTROL}: {character:?}")
            }
            Self::DefinedNameUnknownSheet { sheet_id } => {
                write!(
                    formatter,
                    "{MESSAGE_DEFINED_NAME_UNKNOWN_SHEET}: {sheet_id}"
                )
            }
            Self::DuplicateDefinedName { name } => {
                write!(formatter, "{MESSAGE_DUPLICATE_DEFINED_NAME}: {name}")
            }
            Self::NonFiniteNumber => formatter.write_str(MESSAGE_NON_FINITE_NUMBER),
            Self::FormulaEmpty => formatter.write_str(MESSAGE_FORMULA_EMPTY),
            Self::XlsxFormulaHasLeadingEquals => formatter.write_str(MESSAGE_XLSX_FORMULA_EQUALS),
            Self::UserFormulaMissingLeadingEquals => {
                formatter.write_str(MESSAGE_USER_FORMULA_EQUALS)
            }
            Self::SourceIdEmpty => formatter.write_str(MESSAGE_SOURCE_ID_EMPTY),
            Self::DiagnosticCodeInvalid => formatter.write_str(MESSAGE_DIAGNOSTIC_CODE_INVALID),
            Self::ProviderNameEmpty => formatter.write_str(MESSAGE_PROVIDER_NAME_EMPTY),
            Self::ProviderVersionEmpty => formatter.write_str(MESSAGE_PROVIDER_VERSION_EMPTY),
            Self::DiagnosticMessageEmpty => formatter.write_str(MESSAGE_DIAGNOSTIC_MESSAGE_EMPTY),
            Self::UnknownSheetId { value } => {
                write!(formatter, "{MESSAGE_UNKNOWN_SHEET_ID}: {value}")
            }
            Self::CellNotFound {
                sheet_id,
                row,
                column,
            } => write!(
                formatter,
                "{MESSAGE_CELL_NOT_FOUND}: sheet {sheet_id}, row {row}, column {column}"
            ),
            Self::SheetIdExhausted => formatter.write_str(MESSAGE_SHEET_ID_EXHAUSTED),
            Self::LastVisibleSheet => formatter.write_str(MESSAGE_LAST_VISIBLE_SHEET),
            Self::SemanticRevisionExhausted => {
                formatter.write_str(MESSAGE_SEMANTIC_REVISION_EXHAUSTED)
            }
            Self::PresentationRevisionExhausted => {
                formatter.write_str(MESSAGE_PRESENTATION_REVISION_EXHAUSTED)
            }
            Self::PhoneticRangeEmpty { start, end } => {
                write!(formatter, "{MESSAGE_PHONETIC_RANGE_EMPTY}: {start}..{end}")
            }
            Self::PhoneticRangeOutOfBounds {
                end,
                base_utf16_len,
            } => write!(
                formatter,
                "{MESSAGE_PHONETIC_RANGE_OUT_OF_BOUNDS}: {end} > {base_utf16_len}"
            ),
            Self::PhoneticRangeSplitsSurrogate { offset } => {
                write!(
                    formatter,
                    "{MESSAGE_PHONETIC_RANGE_SPLITS_SURROGATE}: {offset}"
                )
            }
            Self::PhoneticRunsOutOfOrder => formatter.write_str(MESSAGE_PHONETIC_RUNS_OUT_OF_ORDER),
            Self::PhoneticTextEmpty => formatter.write_str(MESSAGE_PHONETIC_TEXT_EMPTY),
            Self::PhoneticTextInvalidCharacter { character } => write!(
                formatter,
                "{MESSAGE_PHONETIC_TEXT_INVALID_CHARACTER}: {character:?}"
            ),
            Self::PhoneticsRequireTextCell {
                sheet_id,
                row,
                column,
            } => write!(
                formatter,
                "{MESSAGE_PHONETICS_REQUIRE_TEXT_CELL}: sheet {sheet_id}, row {row}, column {column}"
            ),
            Self::PhoneticFontIdUnsupported { value } => {
                write!(formatter, "{MESSAGE_PHONETIC_FONT_ID_UNSUPPORTED}: {value}")
            }
            Self::AnnotatedTextReplacementRequired {
                sheet_id,
                row,
                column,
            } => write!(
                formatter,
                "{MESSAGE_ANNOTATED_TEXT_REPLACEMENT_REQUIRED}: sheet {sheet_id}, row {row}, column {column}"
            ),
            Self::FrozenRowsOutOfRange { value } => {
                write!(formatter, "{MESSAGE_FROZEN_ROWS_OUT_OF_RANGE}: {value}")
            }
            Self::FrozenColumnsOutOfRange { value } => {
                write!(formatter, "{MESSAGE_FROZEN_COLUMNS_OUT_OF_RANGE}: {value}")
            }
            Self::BuiltInNumberFormatId { value } => {
                write!(formatter, "{MESSAGE_NUMBER_FORMAT_BUILTIN_ID}: {value}")
            }
            Self::CustomNumberFormatId { value } => {
                write!(formatter, "{MESSAGE_NUMBER_FORMAT_CUSTOM_ID}: {value}")
            }
            Self::NumberFormatCodeEmpty => formatter.write_str(MESSAGE_NUMBER_FORMAT_CODE_EMPTY),
            Self::TableIdZero => formatter.write_str(MESSAGE_TABLE_ID_ZERO),
            Self::TableColumnIdZero => formatter.write_str(MESSAGE_TABLE_COLUMN_ID_ZERO),
            Self::TableNameEmpty => formatter.write_str(MESSAGE_TABLE_NAME_EMPTY),
            Self::TableNameTooLong { utf16_len } => {
                write!(formatter, "{MESSAGE_TABLE_NAME_TOO_LONG}: {utf16_len}")
            }
            Self::TableNameInvalidCharacter { character } => write!(
                formatter,
                "{MESSAGE_TABLE_NAME_INVALID_CHARACTER}: {character:?}"
            ),
            Self::TableNameReferenceConflict => {
                formatter.write_str(MESSAGE_TABLE_NAME_REFERENCE_CONFLICT)
            }
            Self::DuplicateTableDisplayName { name } => {
                write!(formatter, "{MESSAGE_DUPLICATE_TABLE_DISPLAY_NAME}: {name}")
            }
            Self::DuplicateTableId { id } => {
                write!(formatter, "{MESSAGE_DUPLICATE_TABLE_ID}: {id}")
            }
            Self::DuplicateTableProgrammaticName { name } => {
                write!(
                    formatter,
                    "{MESSAGE_DUPLICATE_TABLE_PROGRAMMATIC_NAME}: {name}"
                )
            }
            Self::TableDisplayNameConflictsWithDefinedName { name } => {
                write!(
                    formatter,
                    "{MESSAGE_TABLE_DISPLAY_NAME_CONFLICTS_WITH_DEFINED_NAME}: {name}"
                )
            }
            Self::TableColumnsEmpty => formatter.write_str(MESSAGE_TABLE_COLUMNS_EMPTY),
            Self::TableColumnCountMismatch { columns, width } => write!(
                formatter,
                "{MESSAGE_TABLE_COLUMN_COUNT_MISMATCH}: {columns} columns, width {width}"
            ),
            Self::TableColumnNameEmpty => formatter.write_str(MESSAGE_TABLE_COLUMN_NAME_EMPTY),
            Self::TableColumnNameTooLong { utf16_len } => {
                write!(
                    formatter,
                    "{MESSAGE_TABLE_COLUMN_NAME_TOO_LONG}: {utf16_len}"
                )
            }
            Self::TableColumnNameInvalidCharacter { character } => write!(
                formatter,
                "{MESSAGE_TABLE_COLUMN_NAME_INVALID_CHARACTER}: {character:?}"
            ),
            Self::TableColumnNameSpaceBoundary => {
                formatter.write_str(MESSAGE_TABLE_COLUMN_NAME_SPACE_BOUNDARY)
            }
            Self::DuplicateTableColumnName { name } => {
                write!(formatter, "{MESSAGE_DUPLICATE_TABLE_COLUMN_NAME}: {name}")
            }
            Self::DuplicateTableColumnId { id } => {
                write!(formatter, "{MESSAGE_DUPLICATE_TABLE_COLUMN_ID}: {id}")
            }
            Self::OverlappingTables {
                sheet_id,
                first_table_id,
                second_table_id,
            } => write!(
                formatter,
                "{MESSAGE_OVERLAPPING_TABLES}: sheet {sheet_id}, tables {first_table_id} and {second_table_id}"
            ),
            Self::TableRowCountsExceedRange {
                header_row_count,
                totals_row_count,
                height,
            } => write!(
                formatter,
                "{MESSAGE_TABLE_ROW_COUNTS_EXCEED_RANGE}: header {header_row_count}, totals {totals_row_count}, height {height}"
            ),
            Self::InvalidTableTotalsMetadata => {
                formatter.write_str(MESSAGE_INVALID_TABLE_TOTALS_METADATA)
            }
            Self::UnknownTableId { value } => {
                write!(formatter, "{MESSAGE_UNKNOWN_TABLE_ID}: {value}")
            }
            Self::UnknownTableColumnId {
                table_id,
                column_id,
            } => write!(
                formatter,
                "{MESSAGE_UNKNOWN_TABLE_COLUMN_ID}: table {table_id}, column {column_id}"
            ),
            Self::TableDataRowsReversed {
                first_data_row,
                last_data_row,
            } => write!(
                formatter,
                "{MESSAGE_TABLE_DATA_ROWS_REVERSED}: {first_data_row}..{last_data_row}"
            ),
            Self::TableResizeHeaderUnderflow {
                table_id,
                first_data_row,
                header_row_count,
            } => write!(
                formatter,
                "{MESSAGE_TABLE_RESIZE_HEADER_UNDERFLOW}: table {table_id}, first data row {first_data_row}, header rows {header_row_count}"
            ),
            Self::TableMaterializationCollision {
                table_id,
                sheet_id,
                row,
                column,
            } => write!(
                formatter,
                "{MESSAGE_TABLE_MATERIALIZATION_COLLISION}: table {table_id}, sheet {sheet_id}, row {row}, column {column}"
            ),
            Self::UnsupportedTableAuthoringMetadata { table_id } => write!(
                formatter,
                "{MESSAGE_UNSUPPORTED_TABLE_AUTHORING_METADATA}: table {table_id}"
            ),
            Self::FormulaRewriteParseFailed {
                parse_code,
                start,
                end,
                owner,
            } => {
                write!(
                    formatter,
                    "{MESSAGE_FORMULA_REWRITE_PARSE_FAILED}: {parse_code} at {start}..{end}"
                )?;
                if let Some(owner) = owner {
                    write!(formatter, ", owner {owner}")?;
                }
                Ok(())
            }
        }
    }
}

impl Error for ValidationError {}

#[cfg(test)]
mod tests {
    use std::collections::BTreeSet;

    use super::ValidationErrorCode;

    #[test]
    fn validation_error_code_strings_are_complete_stable_and_unique() {
        let cases = [
            (
                ValidationErrorCode::RowOutOfRange,
                "validation.row_out_of_range",
            ),
            (
                ValidationErrorCode::ColumnOutOfRange,
                "validation.column_out_of_range",
            ),
            (
                ValidationErrorCode::CellAddressInvalid,
                "validation.cell_address_invalid",
            ),
            (
                ValidationErrorCode::RangeStartAfterEnd,
                "validation.range_start_after_end",
            ),
            (ValidationErrorCode::SheetIdZero, "validation.sheet_id_zero"),
            (
                ValidationErrorCode::SheetNameEmpty,
                "validation.sheet_name_empty",
            ),
            (
                ValidationErrorCode::SheetNameTooLong,
                "validation.sheet_name_too_long",
            ),
            (
                ValidationErrorCode::SheetNameInvalidCharacter,
                "validation.sheet_name_invalid_character",
            ),
            (
                ValidationErrorCode::SheetNameApostropheBoundary,
                "validation.sheet_name_apostrophe_boundary",
            ),
            (
                ValidationErrorCode::DuplicateSheetId,
                "validation.duplicate_sheet_id",
            ),
            (
                ValidationErrorCode::DuplicateSheetName,
                "validation.duplicate_sheet_name",
            ),
            (
                ValidationErrorCode::DuplicateCell,
                "validation.duplicate_cell",
            ),
            (
                ValidationErrorCode::DefinedNameEmpty,
                "validation.defined_name_empty",
            ),
            (
                ValidationErrorCode::DefinedNameTooLong,
                "validation.defined_name_too_long",
            ),
            (
                ValidationErrorCode::DefinedNameControlCharacter,
                "validation.defined_name_control_character",
            ),
            (
                ValidationErrorCode::DefinedNameUnknownSheet,
                "validation.defined_name_unknown_sheet",
            ),
            (
                ValidationErrorCode::DuplicateDefinedName,
                "validation.duplicate_defined_name",
            ),
            (
                ValidationErrorCode::NonFiniteNumber,
                "validation.non_finite_number",
            ),
            (
                ValidationErrorCode::FormulaEmpty,
                "validation.formula_empty",
            ),
            (
                ValidationErrorCode::XlsxFormulaHasLeadingEquals,
                "validation.xlsx_formula_has_leading_equals",
            ),
            (
                ValidationErrorCode::UserFormulaMissingLeadingEquals,
                "validation.user_formula_missing_leading_equals",
            ),
            (
                ValidationErrorCode::SourceIdEmpty,
                "validation.source_id_empty",
            ),
            (
                ValidationErrorCode::DiagnosticCodeInvalid,
                "validation.diagnostic_code_invalid",
            ),
            (
                ValidationErrorCode::ProviderNameEmpty,
                "validation.provider_name_empty",
            ),
            (
                ValidationErrorCode::ProviderVersionEmpty,
                "validation.provider_version_empty",
            ),
            (
                ValidationErrorCode::DiagnosticMessageEmpty,
                "validation.diagnostic_message_empty",
            ),
            (
                ValidationErrorCode::UnknownSheetId,
                "validation.unknown_sheet_id",
            ),
            (
                ValidationErrorCode::CellNotFound,
                "validation.cell_not_found",
            ),
            (
                ValidationErrorCode::SheetIdExhausted,
                "validation.sheet_id_exhausted",
            ),
            (
                ValidationErrorCode::LastVisibleSheet,
                "validation.last_visible_sheet",
            ),
            (
                ValidationErrorCode::SemanticRevisionExhausted,
                "validation.semantic_revision_exhausted",
            ),
            (
                ValidationErrorCode::PresentationRevisionExhausted,
                "validation.presentation_revision_exhausted",
            ),
            (
                ValidationErrorCode::PhoneticRangeEmpty,
                "validation.phonetic_range_empty",
            ),
            (
                ValidationErrorCode::PhoneticRangeOutOfBounds,
                "validation.phonetic_range_out_of_bounds",
            ),
            (
                ValidationErrorCode::PhoneticRangeSplitsSurrogate,
                "validation.phonetic_range_splits_surrogate",
            ),
            (
                ValidationErrorCode::PhoneticRunsOutOfOrder,
                "validation.phonetic_runs_out_of_order",
            ),
            (
                ValidationErrorCode::PhoneticTextEmpty,
                "validation.phonetic_text_empty",
            ),
            (
                ValidationErrorCode::PhoneticTextInvalidCharacter,
                "validation.phonetic_text_invalid_character",
            ),
            (
                ValidationErrorCode::PhoneticsRequireTextCell,
                "validation.phonetics_require_text_cell",
            ),
            (
                ValidationErrorCode::PhoneticFontIdUnsupported,
                "validation.phonetic_font_id_unsupported",
            ),
            (
                ValidationErrorCode::AnnotatedTextReplacementRequired,
                "validation.annotated_text_replacement_required",
            ),
            (
                ValidationErrorCode::FrozenRowsOutOfRange,
                "validation.frozen_rows_out_of_range",
            ),
            (
                ValidationErrorCode::FrozenColumnsOutOfRange,
                "validation.frozen_columns_out_of_range",
            ),
            (
                ValidationErrorCode::BuiltInNumberFormatId,
                "validation.built_in_number_format_id",
            ),
            (
                ValidationErrorCode::CustomNumberFormatId,
                "validation.custom_number_format_id",
            ),
            (
                ValidationErrorCode::NumberFormatCodeEmpty,
                "validation.number_format_code_empty",
            ),
            (ValidationErrorCode::TableIdZero, "validation.table_id_zero"),
            (
                ValidationErrorCode::TableColumnIdZero,
                "validation.table_column_id_zero",
            ),
            (
                ValidationErrorCode::TableNameEmpty,
                "validation.table_name_empty",
            ),
            (
                ValidationErrorCode::TableNameTooLong,
                "validation.table_name_too_long",
            ),
            (
                ValidationErrorCode::TableNameInvalidCharacter,
                "validation.table_name_invalid_character",
            ),
            (
                ValidationErrorCode::TableNameReferenceConflict,
                "validation.table_name_reference_conflict",
            ),
            (
                ValidationErrorCode::DuplicateTableDisplayName,
                "validation.duplicate_table_display_name",
            ),
            (
                ValidationErrorCode::DuplicateTableId,
                "validation.duplicate_table_id",
            ),
            (
                ValidationErrorCode::DuplicateTableProgrammaticName,
                "validation.duplicate_table_programmatic_name",
            ),
            (
                ValidationErrorCode::TableDisplayNameConflictsWithDefinedName,
                "validation.table_display_name_conflicts_with_defined_name",
            ),
            (
                ValidationErrorCode::TableColumnsEmpty,
                "validation.table_columns_empty",
            ),
            (
                ValidationErrorCode::TableColumnCountMismatch,
                "validation.table_column_count_mismatch",
            ),
            (
                ValidationErrorCode::TableColumnNameEmpty,
                "validation.table_column_name_empty",
            ),
            (
                ValidationErrorCode::TableColumnNameTooLong,
                "validation.table_column_name_too_long",
            ),
            (
                ValidationErrorCode::TableColumnNameInvalidCharacter,
                "validation.table_column_name_invalid_character",
            ),
            (
                ValidationErrorCode::TableColumnNameSpaceBoundary,
                "validation.table_column_name_space_boundary",
            ),
            (
                ValidationErrorCode::DuplicateTableColumnName,
                "validation.duplicate_table_column_name",
            ),
            (
                ValidationErrorCode::DuplicateTableColumnId,
                "validation.duplicate_table_column_id",
            ),
            (
                ValidationErrorCode::OverlappingTables,
                "validation.overlapping_tables",
            ),
            (
                ValidationErrorCode::TableRowCountsExceedRange,
                "validation.table_row_counts_exceed_range",
            ),
            (
                ValidationErrorCode::InvalidTableTotalsMetadata,
                "validation.invalid_table_totals_metadata",
            ),
            (
                ValidationErrorCode::UnknownTableId,
                "validation.unknown_table_id",
            ),
            (
                ValidationErrorCode::UnknownTableColumnId,
                "validation.unknown_table_column_id",
            ),
            (
                ValidationErrorCode::TableDataRowsReversed,
                "validation.table_data_rows_reversed",
            ),
            (
                ValidationErrorCode::TableResizeHeaderUnderflow,
                "validation.table_resize_header_underflow",
            ),
            (
                ValidationErrorCode::TableMaterializationCollision,
                "validation.table_materialization_collision",
            ),
            (
                ValidationErrorCode::UnsupportedTableAuthoringMetadata,
                "validation.unsupported_table_authoring_metadata",
            ),
            (
                ValidationErrorCode::FormulaRewriteParseFailed,
                "validation.formula_rewrite_parse_failed",
            ),
        ];
        let mut seen_codes = BTreeSet::new();

        for (code, expected_text) in &cases {
            assert_eq!(code.as_str(), *expected_text);
            assert!(seen_codes.insert(*expected_text));
        }

        assert_eq!(seen_codes.len(), cases.len());
    }
}