ocpi-tariffs 0.54.0

OCPI tariff calculations
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
//! Applying [`Edit`]s to the source of a parsed [`json::Document`].
//!
//! Producing the edits and agreeing to apply them are separate steps, which is what lets edits
//! drawn from different kinds of warning be resolved together. A `warning::Set<schema::Warning>`
//! and a `warning::Set<lint::tariff::Warning>` are different types, so no single call can take
//! both; [`Edit`] is the common form each reduces to, and a caller concatenates them before one
//! [`apply`].
//!
//! Applying each set in turn instead would resolve the second against a re-parsed document, where
//! the ids of the first no longer mean the same elements, so two edits landing on one element
//! could not be resolved against each other at all.
//!
//! [`apply`] resolves a whole set of edits against one document in a single pass. Resolving
//! them one at a time would be wrong for the same reason within a set: which span removes an
//! element depends on which of its siblings survive, so removals have to be resolved together.
//! See [`json::Document::removal_spans`].

#[cfg(test)]
mod test_apply;

#[cfg(test)]
mod test_edits;

#[cfg(test)]
mod test_json;

#[cfg(test)]
mod test_lint_warning;

#[cfg(test)]
mod test_price_invariant;

#[cfg(test)]
mod test_schema_warning;

use std::{
    collections::{BTreeMap, BTreeSet},
    fmt,
};

use crate::{datetime, json, lint, schema, string, warning, weekday};

/// The edits that resolve `warnings` against the document they were raised on.
///
/// A [`Fixable`] warning says what edit would resolve it; it does not decide whether that edit
/// is wanted. Filter the [`warning::Set`] before calling this to leave a fix out, with
/// `Set::remove_unexpected_fields` and its siblings.
///
/// Each edit states its [`Meaning`], so a caller can also drop the edits that change what the
/// document means before passing the rest to [`apply`].
///
/// The edits come back in document order, since a [`warning::Set`] is keyed by
/// [`json::ElemId`]. Pass them to [`apply`], which resolves how they interact.
///
/// `edits` does not propose removing the last occurrence of a key that occurs more than once in an
/// object, whichever warning's fix asks for it. Schema warnings and lint warnings both have fixes
/// that remove a field. The last occurrence is the one used, so removing it would result in an
/// earlier field's value being used. The removal is proposed once
/// [`DuplicateField`](schema::Warning::DuplicateField) has been resolved and the earlier fields are
/// gone, so [`tariff::fix`](crate::tariff::fix) takes one more pass over such a document. Filtering
/// the warnings never lets a removal change what a document says.
///
/// `edits` also leaves out a [`Meaning::Changes`] rename whose new key would clash with another
/// key in the object. A rename clashes in three cases:
///
/// - Another rename writes the same key in the same object.
/// - The object still holds a field with that key once the other edits are applied.
/// - Another fix renames the same field.
///
/// The three cases are checked only against the other edits this call returns. A caller
/// that joins the edits of two calls, such as one for each set of warnings, can get two renames
/// that write the same key in one object. [`apply`] then writes that key twice.
///
/// Calling `edits` again on the document [`apply`] returns proposes the rename once the clash is
/// gone. So a [`schema::Warning::MisspelledField`] with one expected name doesn't produce an edit
/// while another field in the same object is nearest to the same name.
pub fn edits<W: Fixable>(
    doc: &json::Document<'_>,
    warnings: &warning::Set<W>,
) -> Result<Vec<Edit>, Error> {
    let mut proposed = proposed_edits(doc, warnings)?;
    let _refused = refuse_clashing_renames(doc, &mut proposed);
    let edits = proposed.into_iter().map(Proposed::into_edit).collect();

    Ok(edits)
}

/// The edits that resolve `warnings`, each beside the id of the warning that proposed it.
///
/// Unlike [`edits`], this keeps every rename whose new key would clash, so a caller joining the
/// edits of several calls can refuse the clashing renames once over all of them, with
/// [`refuse_clashing_renames`].
pub(crate) fn proposed_edits<W: Fixable>(
    doc: &json::Document<'_>,
    warnings: &warning::Set<W>,
) -> Result<Vec<Proposed>, Error> {
    let mut out: Vec<Proposed> = Vec::new();
    let last_of_repeated = doc.last_of_repeated_keys();

    for group in warnings {
        let (element, raised) = group.to_parts();
        let live = doc
            .element(element.id)
            .ok_or(Error::UnknownElement(element.id))?;

        for warning in raised {
            let Some(edit) = warning.fix(live) else {
                continue;
            };

            if let Change::Remove(id) = edit.change
                && last_of_repeated.contains(&id)
            {
                continue;
            }

            out.push(Proposed {
                edit,
                warning: warning.id(),
            });
        }
    }

    Ok(out)
}

/// An [`Edit`] beside the id of the warning whose fix proposed it.
///
/// Only `refuse_clashing_renames` reads the id, to name the warning in each [`Refused`]. So the
/// id stays out of [`Edit`], which callers outside this crate see.
pub(crate) struct Proposed {
    edit: Edit,

    warning: warning::Id,
}

impl Proposed {
    pub(crate) fn into_edit(self) -> Edit {
        self.edit
    }
}

/// A fix that [`tariff::fix`](crate::tariff::fix) proposed for a warning and then
/// refused, so the warning remains in the fixed tariff.
/// [`lint::fix::Fixed::refused`](crate::lint::fix::Fixed::refused) lists them.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Refused {
    /// The path of the field the refused fix would have changed. For a rename, that is
    /// the field whose name the fix would have rewritten.
    pub path: json::Path,

    /// The id of the warning whose fix was refused.
    pub warning: warning::Id,

    /// Why the fix was refused.
    pub reason: Refusal,
}

/// Why a proposed fix was refused.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Refusal {
    /// The fix renames a field, and the new name would clash with the name of another
    /// field in the same object. [`edits`] lists the ways two names can clash.
    RenameClashes,
}

impl fmt::Display for Refusal {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::RenameClashes => f.write_str(
                "renaming the field would clash with the name of another field in the same object",
            ),
        }
    }
}

/// A [`Warning`](crate::Warning) that a mechanical edit can resolve.
///
/// An implementation reports what edit would resolve the warning, not whether the edit should
/// be made. Whether a given fix is wanted is the caller's decision, so a caller that does not
/// want one filters the warning out of the set before calling [`edits`].
///
/// An implementation also states whether the document means the same after the edit, as the
/// edit's [`Meaning`]. A caller can drop the edits whose meaning it doesn't want, as well as or in
/// place of filtering the warnings.
///
/// Sealed, because only this crate can build an [`Edit`]: an implementation outside it could
/// return nothing but `None`.
#[expect(
    private_bounds,
    reason = "`Sealed` is crate-private on purpose; that is what seals the trait"
)]
pub trait Fixable: crate::Warning + sealed::Sealed {
    /// The edit that resolves this warning at `element`, or `None` if nothing mechanical can
    /// resolve it.
    fn fix(&self, element: &json::Element<'_>) -> Option<Edit>;
}

/// Seals [`Fixable`] against implementations outside this crate.
pub(crate) mod sealed {
    /// The supertrait of [`Fixable`](super::Fixable) that only this crate can name, and so the
    /// only crate that can implement `Fixable`.
    pub(crate) trait Sealed {}
}

impl sealed::Sealed for schema::Warning {}

impl Fixable for schema::Warning {
    #[expect(
        clippy::match_same_arms,
        reason = "one arm per variant, so a new variant has to state whether it can be fixed"
    )]
    fn fix(&self, element: &json::Element<'_>) -> Option<Edit> {
        match self {
            // A `null` value has no semantic meaning in OCPI. The item can be removed.
            Self::NullField => Some(Edit::remove(element.id(), Meaning::Preserves)),

            // The OCPI spec does not define this field so the fix feature can remove it.
            Self::UnexpectedField => Some(Edit::remove(element.id(), Meaning::Preserves)),

            // Removing the field would delete the only record of what the author meant.
            // Renaming it to the one name in `expected` is a guess at that meaning. After the
            // rename, parsing reads the field, so the rename is a `Meaning::Changes` edit. For a
            // pricing field the rename also changes what a session costs. When `expected` holds
            // several names, only the author can choose between them.
            //
            // The arm proposes the rename whatever else is in the object. The function
            // `refuse_clashing_renames` then refuses it for a pass when the new key would clash
            // with another key in the same object, and `refused_renames` lists the three ways it
            // can clash.
            //
            // A field holding `null` records nothing under either name, so the arm
            // removes it instead, which keeps the meaning. Renaming it would count as a change the
            // caller has to allow, and it could block the rename of a sibling field that is
            // nearest to the same name.
            Self::MisspelledField { expected } => {
                if element.is_null() {
                    return Some(Edit::remove(element.id(), Meaning::Preserves));
                }
                let [name] = expected.as_slice() else {
                    return None;
                };
                Some(Edit::rename(
                    element.id(),
                    Json::string(name),
                    Meaning::Changes,
                ))
            }

            // Rewriting the value to the one variant in `expected` is a guess at what the author
            // meant. After the rewrite, parsing reads the value, so the rewrite is a
            // `Meaning::Changes` edit. For a pricing field, such as a price component's `type` or
            // a restriction's `day_of_week`, the rewrite also changes what a session costs.
            //
            // Parsing drops a price component whose `type` it can't read, and pricing rejects a
            // tariff whose `day_of_week` holds a value parsing can't read. When `expected` holds
            // several variants, only the author can choose between them.
            Self::MisspelledValue {
                expected,
                actual: _,
            } => {
                let [variant] = expected.as_slice() else {
                    return None;
                };
                Some(Edit::replace(
                    element.id(),
                    Json::string(variant),
                    Meaning::Changes,
                ))
            }

            // The warning is anchored on a superseded occurrence: a later one carries the value.
            // Removing this one leaves the document semantically identical.
            Self::DuplicateField => Some(Edit::remove(element.id(), Meaning::Preserves)),

            // A non-spec field is off-spec but used because we can infer what it should have been.
            // Removing it would change how the document prices, so there is no fix action.
            Self::NonSpecField => None,

            // Parsing matches the field by its decoded name, so writing the name without its
            // escapes leaves the document semantically identical.
            Self::FieldNameContainsEscapeCodes => plain_field_name(element),

            // Which field the author meant is unknown, so only the author can rewrite the name. The
            // walk also raises `UnexpectedField` on the field. The fix for that warning removes the
            // field when the caller asks for unexpected fields to be removed.
            Self::FieldNameInvalidEscape => None,

            // Write the variant with the correct case.
            Self::IncorrectCase {
                expected,
                actual: _,
            } => Some(Edit::replace(
                element.id(),
                Json::string(expected),
                Meaning::Preserves,
            )),

            // `expected` is the date or time the library read, written in the spec's form, so the
            // document means the same date or time after the rewrite.
            Self::IncorrectFormat {
                expected,
                actual: _,
            } => Some(Edit::replace(
                element.id(),
                Json::string(expected),
                Meaning::Preserves,
            )),

            // Rounding a number changes what a session costs, so it is not a fix this
            // layer makes on its own. #456 decides that policy and needs `Json::number`, which
            // #454 adds.
            Self::ExcessivePrecision { max: _, scale: _ } => None,

            // All the below issues require intervention from the author.
            Self::MissingField { name: _ }
            | Self::InvalidType {
                expected: _,
                actual: _,
            }
            | Self::StringTooLong { max: _, len: _ }
            | Self::InvalidValue {
                expected: _,
                actual: _,
            }
            | Self::Cardinality => None,
        }
    }
}

impl sealed::Sealed for lint::tariff::Warning {}

impl Fixable for lint::tariff::Warning {
    #[expect(
        clippy::match_same_arms,
        reason = "one arm per variant, so a new variant has to state whether it can be fixed"
    )]
    fn fix(&self, element: &json::Element<'_>) -> Option<Edit> {
        match self {
            // A list of all seven days matches every day, which is what leaving the list out
            // means, so the element matches the same days without it.
            Self::ContainsEntireWeek => Some(Edit::remove(element.id(), Meaning::Preserves)),

            // An object holding no restriction restricts nothing, which is the same as no object.
            Self::RestrictionsEmpty => Some(Edit::remove(element.id(), Meaning::Preserves)),

            // A `min_duration` of `0` allows every session, so the element applies to the same
            // sessions without the field. The removal needs no check of its own on the value: the
            // linter raises this warning only for a bound that lowered to a duration of exactly
            // `0`, and a fractional or negative one never lowers at all.
            Self::MinDurationZeroAllowsEverySession => {
                Some(Edit::remove(element.id(), Meaning::Preserves))
            }

            // Which days a list matches is a question of membership, so neither the order of
            // the days nor a repeat of one changes it.
            Self::DayOfWeekDuplicates | Self::DayOfWeekUnsorted => sorted_day_of_week(element),

            // OCPI reads an empty list the same as no list, so the element matches the same days
            // without it.
            Self::DayOfWeekEmpty => Some(Edit::remove(element.id(), Meaning::Preserves)),

            // `23:59` and the `00:00` the spec asks for do not cover the same day, so
            // rewriting one to the other moves a boundary by a minute.
            Self::EndTimeIsNearEndOfDay => None,

            // A `min_kwh`, `min_power` or `min_current` of `0` excludes a negative value, and the
            // library prices a CDR that reports one. Removing the field would change what the
            // session costs. `MinDurationZeroAllowsEverySession` does get that removal, which is
            // safe only because a duration is never negative.
            Self::MinZeroExcludesOnlyNegative => None,

            // Nothing mechanical resolves these. Two fields disagree and only the author knows
            // which of them is wrong, or the value is unusable and only the author knows what
            // it was meant to be. `Duration` is the one wrapped enum with no fixable variant:
            // a duration that does not parse, is not an int, or overflows is all it reports.
            Self::Duration(_)
            | Self::MinPriceIsGreaterThanMax
            | Self::StartDateTimeIsAfterEndDateTime => None,

            // A bound of midnight restricts nothing. Every time of day is at or after a
            // `start_time` of midnight, and parsing reads an `end_time` of midnight as the end of
            // the day. So the element applies under the same conditions without the field.
            //
            // The linter also raises this warning on an `end_time` of `23:59`, and removing that
            // bound would widen the element's time window by a minute, which is
            // `EndTimeIsNearEndOfDay`'s objection. So the fix reads the time the way parsing a
            // tariff does, and removes the bound only when it reads as midnight. Parsing reads
            // `0:00` as midnight, as it does `00:00`.
            //
            // With both bounds present the linter raises the warning on `start_time` alone, and a
            // fix receives only the element its warning sits on. So one pass of the fixing loop
            // removes `start_time`. The linter then raises the warning on the lone `end_time`,
            // which the next pass removes.
            Self::ContainsEntireDay => {
                let json::Value::String(raw) = element.value() else {
                    return None;
                };

                let time = datetime::parse_time(raw.as_unescaped_str()).ok()?;

                if time != chrono::NaiveTime::MIN {
                    return None;
                }

                Some(Edit::remove(element.id(), Meaning::Preserves))
            }

            // TODO #405 Fixable at this element, not yet written. The warning is raised only
            // once the value has parsed as a valid alpha-3, so the `country::Code` behind it
            // already holds the alpha-2 to write in its place, and the lowering normalizes the
            // two strings to that same `Code` regardless. Needs a crate-visible alpha-3
            // lookup, because `Code::from_alpha_3` is reachable from `country` alone.
            Self::CpoCountryCodeShouldBeAlpha2 => None,

            // Pricing never uses this element, so removing it doesn't change any price. Another
            // element may still match a session, so the tariff still has one after the removal,
            // as OCPI requires.
            Self::ElementExcludesEverySession(lint::tariff::OtherElements::SomeMayMatch) => {
                Some(Edit::remove(element.id(), Meaning::Preserves))
            }

            // No other element may match a session. OCPI requires a tariff to have at least one
            // element, and which one to keep is the author's choice, so `lint --fix` removes
            // nothing.
            Self::ElementExcludesEverySession(lint::tariff::OtherElements::NoneMayMatch) => None,

            // While pricing rejects the tariff, `lint` can't tell whether another element may match
            // a session. Removing this one could leave none, so `lint --fix` removes nothing.
            Self::ElementExcludesEverySession(lint::tariff::OtherElements::TariffRejected) => None,

            // Each of these sits on one restriction field. Removing the field would make the
            // element match more sessions, which is the opposite of what its author meant.
            //
            // Where the element's restrictions do exclude every session, `lint` also raises
            // `ElementExcludesEverySession` on the element, and the fix for that warning can remove
            // the whole element.
            Self::LowerBoundAtOrAboveUpper | Self::MaxZeroNeverMatch | Self::NeverValid => None,

            // TODO #407 The lowering's own warnings, each wrapping an enum that mixes the two
            // cases. A lower-case country, currency or string is `IncorrectCase` and a
            // rewrite; so is a value carrying escape codes that decode. An invalid code, a
            // malformed escape or a number out of range is not. Resolving them means `Fixable`
            // reaching into the wrapped enum, since the wrapper is the wrong altitude for the
            // decision.
            Self::Country(_)
            | Self::Currency(_)
            | Self::DateTime(_)
            | Self::Money(_)
            | Self::Number(_)
            | Self::String(_) => None,
        }
    }
}

/// The edit that puts a `day_of_week` list in spec order and drops its repeats.
///
/// Returns `None` unless every item is a day this can name, so a list holding anything else is
/// left exactly as the author wrote it. The schema accepts a day in any case, and the match
/// here is exact, so a lower-case list is one of the lists that keeps its warning.
fn sorted_day_of_week(element: &json::Element<'_>) -> Option<Edit> {
    let items = element.value().as_array()?;
    let mut days: Vec<weekday::Weekday> = Vec::with_capacity(items.len());

    for item in items {
        let json::Value::String(raw) = item.value() else {
            return None;
        };

        days.push(weekday::Weekday::from_canonical(raw.as_unescaped_str())?);
    }

    days.sort_unstable();
    days.dedup();

    let names: Vec<&str> = days.iter().map(|day| day.canonical()).collect();

    Some(Edit::replace(
        element.id(),
        Json::string_array(&names),
        Meaning::Preserves,
    ))
}

/// Removes every rename that would change what the document means and whose new key
/// would clash with another key in the same object. The doc of `refused_renames` lists the ways
/// a key can clash.
///
/// `fix::edits` runs this on the edits for one set of warnings. `lint::fix::pass_edits` runs it
/// on the schema warnings' edits and the lint warnings' edits joined, because a rename from
/// one set can write the same key as a rename from the other.
///
/// Returns a [`Refused`] for each rename it removes, naming the field the rename would
/// have rewritten and the warning that proposed it.
pub(crate) fn refuse_clashing_renames(
    doc: &json::Document<'_>,
    proposed: &mut Vec<Proposed>,
) -> Vec<Refused> {
    let refused_values = refused_renames(doc, proposed);
    let extracted = proposed.extract_if(.., |proposed| {
        let Change::Rename { elem, key: _ } = &proposed.edit.change else {
            return false;
        };
        proposed.edit.meaning == Meaning::Changes && refused_values.contains(elem)
    });

    let mut refused = Vec::new();

    for Proposed { edit, warning } in extracted {
        let Change::Rename { elem, key: _ } = edit.change else {
            continue;
        };
        let Some(element) = doc.element(elem) else {
            continue;
        };

        refused.push(Refused {
            path: element.path(),
            warning,
            reason: Refusal::RenameClashes,
        });
    }

    refused
}

/// Finds the renames that `refuse_clashing_renames` refuses for this pass. Returns the id of each
/// refused rename's value, because a rename is anchored on the value of the field it renames.
///
/// Only a rename marked `Meaning::Changes` is ever refused. A rename that keeps the meaning,
/// such as the fix for an escaped field name, always goes ahead.
///
/// The checks below ignore any field that this pass removes, because that field's key is gone
/// once the pass is applied.
///
/// - **Another rename writes the same key in the same object.** Two misspelled fields can both be
///   nearest to one absent field, as `dayOfWeek` and `DayOfWeek` are to `day_of_week`. Applying
///   both renames would repeat the key. Nothing says which of the two the author meant, so
///   both are refused. A `Meaning::Preserves` rename is never refused, so when one shares the
///   key with a `Changes` rename, only the `Changes` rename is refused.
/// - **The object keeps a field with that key.** A `null` field counts as absent in the schema
///   walk, so `dayOfWeek` is reported as a misspelling beside `"day_of_week": null`. When the pass
///   doesn't remove that `null`, the rename would write a key the object still holds, and parsing
///   would read the later of the two.
/// - **The same value has another rename.** A name both escaped and misspelled, such as
///   `"day\u004ffWeek"`, gets the escape fix's rename as well. [`apply`] rejects two renames of
///   one key that write different text. The escape fix's rename goes first, and the next pass
///   proposes the misspelling's rename on its own.
fn refused_renames(doc: &json::Document<'_>, proposed: &[Proposed]) -> BTreeSet<json::ElemId> {
    let mut removed: BTreeSet<json::ElemId> = BTreeSet::new();
    let mut renames_of_value: BTreeMap<json::ElemId, usize> = BTreeMap::new();
    let mut renames_by_key: BTreeMap<(json::ElemId, &str), usize> = BTreeMap::new();

    for Proposed { edit, warning: _ } in proposed {
        match &edit.change {
            Change::Remove(elem) => {
                removed.insert(*elem);
            }
            Change::Rename { elem, key: _ } => {
                let count = renames_of_value.entry(*elem).or_default();
                *count = count.saturating_add(1);
            }
            Change::Replace { elem: _, json: _ } => {}
        }
    }

    // The renames that would change what the document means. Each one comes as the id of
    // the renamed field's value, the id of the object holding that field and the new key. A
    // rename of a field that this pass removes is left out.
    let mut changing: Vec<(json::ElemId, json::ElemId, &Json)> = Vec::new();

    for Proposed { edit, warning: _ } in proposed {
        let Change::Rename { elem, key } = &edit.change else {
            continue;
        };
        if removed.contains(elem) {
            continue;
        }
        let Some(object) = doc.object_of_field(*elem) else {
            continue;
        };

        let count = renames_by_key.entry((object, key.as_str())).or_default();
        *count = count.saturating_add(1);

        if edit.meaning == Meaning::Changes {
            changing.push((*elem, object, key));
        }
    }

    let mut refused = BTreeSet::new();

    for (elem, object, key) in changing {
        let shares_key = renames_by_key
            .get(&(object, key.as_str()))
            .map(|count| *count > 1)
            .unwrap_or(false);
        let renamed_twice = renames_of_value
            .get(&elem)
            .map(|count| *count > 1)
            .unwrap_or(false);
        if shares_key || renamed_twice {
            refused.insert(elem);
            continue;
        }

        // One scan per rename would make this quadratic in the object's size.
        // The check above leaves at most one rename per key.
        // Each such key is a name the schema lists for the object.
        // So the schema caps the scans per object, not the input.
        let Some(fields) = doc
            .element(object)
            .and_then(json::Element::as_object_fields)
        else {
            continue;
        };

        // A schema name needs no escapes, so the text between the key's quotes is the
        // name the rename writes.
        let name = key.as_str().trim_matches('"');

        let key_kept = fields.iter().any(|field| {
            let value = field.element().id();
            let field_key = field.element().key().map(json::RawStr::to_key);

            value != elem
                && !removed.contains(&value)
                && field_key.is_some_and(|field_key| field_key.name() == Some(name))
        });
        if key_kept {
            refused.insert(elem);
        }
    }

    refused
}

/// The edit that writes the name of the field holding `element` without escapes. The edit
/// rewrites only the name and leaves the field's value as written.
///
/// Returns `None` when `element` isn't the value of an object field, or when JSON can't write the
/// decoded name without an escape.
fn plain_field_name(element: &json::Element<'_>) -> Option<Edit> {
    let raw = element.key()?;
    let json::Key::Decoded(name) = raw.to_key() else {
        return None;
    };
    let key = Json::string(&name);

    // JSON can write a `"` or a `\` in a name only as an escape. The walk raises the
    // warning for any escape, so it would raise the warning again on the renamed field. The next
    // pass would propose a rename to the name the field already has, and the fixing loop would
    // repeat it until it reached its limit.
    if key.as_str().contains('\\') {
        return None;
    }

    Some(Edit::rename(element.id(), key, Meaning::Preserves))
}

/// Apply `edits` to the source of `doc` and return the edited JSON.
///
/// The output is re-parsed before it is returned. Since every replacement payload is one JSON
/// value by construction, and a value is legal wherever another one was, this should not be able
/// to fail; it is kept as a backstop on the splicing, and on the payload builders in a release
/// build where their own assertion is compiled out.
///
/// Edits interact, and the rules are not symmetric:
///
/// | Case | Outcome |
/// |---|---|
/// | Two removals of the same element | Removed once |
/// | A removal of an element inside another removed element | The ancestor's span covers it |
/// | A replacement of an element that is also removed | The removal wins |
/// | A replacement of an element inside a removed element | The removal wins |
/// | Two replacements of the same element, same text | Replaced once |
/// | Two replacements of the same element, differing text | [`Error::Duplicate`] |
/// | A replacement of an element inside another replaced element | [`Error::Conflict`] |
/// | A removal of an element inside a replaced element | [`Error::Conflict`] |
/// | Two renames of the same field, same text | Renamed once |
/// | Two renames of the same field, differing text | [`Error::Duplicate`] |
///
/// A rename rewrites a field's key, and `apply` treats it as a replacement of the key.
/// The fixes for [`schema::Warning::FieldNameContainsEscapeCodes`] and
/// [`schema::Warning::MisspelledField`] both propose renames. A rename and a replacement of the
/// same field both apply, because the key and the value don't overlap.
///
/// A removal makes any edit inside it redundant, because the bytes go away either way. Nothing an
/// inner edit intended is lost. A replacement doesn't make an inner edit redundant. Its payload was
/// written without knowledge of the inner edit, so applying it would discard that edit silently.
///
/// Two replacements asking for the same text are one edit proposed twice, not a disagreement:
/// a `day_of_week` list can be both unsorted and repeating, and the same sorted list resolves
/// either warning. Only replacements that disagree about the text are an error.
pub fn apply(doc: &json::Document<'_>, edits: &[Edit]) -> Result<String, Error> {
    let splices = resolve(doc, edits)?;
    let edited = splice(doc.source(), &splices)?;

    check_parses(&edited)?;

    Ok(edited)
}

/// A single change to one element of a document.
///
/// Opaque, and produced only by [`edits`]. Which edit resolves a warning is this crate's
/// decision. A caller decides which edits to apply in two ways. It can filter the
/// [`warning::Set`] before calling [`edits`], which leaves out every edit for the warnings it
/// removed. An `Edit` doesn't record which warning asked for it, so that is the only way to choose
/// by warning. A caller can also leave out the edits whose [`Edit::meaning`] it doesn't want.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Edit {
    change: Change,
    meaning: Meaning,
}

impl Edit {
    /// Remove the element from its parent, along with the separator that joined it to its
    /// siblings.
    pub(crate) fn remove(elem: json::ElemId, meaning: Meaning) -> Self {
        Self {
            change: Change::Remove(elem),
            meaning,
        }
    }

    /// Replace the element's value with `json`, leaving an object field's key in place.
    pub(crate) fn replace(elem: json::ElemId, json: Json, meaning: Meaning) -> Self {
        Self {
            change: Change::Replace { elem, json },
            meaning,
        }
    }

    /// Replace the key of the object field whose value is `elem` with `key`, leaving the value in
    /// place.
    pub(crate) fn rename(elem: json::ElemId, key: Json, meaning: Meaning) -> Self {
        Self {
            change: Change::Rename { elem, key },
            meaning,
        }
    }

    /// Whether the document means the same under OCPI after this edit.
    pub fn meaning(&self) -> Meaning {
        self.meaning
    }
}

/// Whether a document means the same under OCPI after an [`Edit`].
///
/// The answer is about what the document says, not about what a session costs. Removing a `null`
/// element is [`Meaning::Preserves`], because a `null` has no meaning in OCPI, even when the
/// tariff can't be priced until the `null` is gone. An edit that supplies what the author probably
/// meant is [`Meaning::Changes`], because the document as written doesn't say it.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Meaning {
    /// The document means the same under OCPI after the edit.
    Preserves,

    /// The document means something else under OCPI after the edit.
    Changes,
}

/// What an [`Edit`] does to its element.
#[derive(Clone, Debug, Eq, PartialEq)]
enum Change {
    /// Remove the element from its parent, along with the separator that joined it to its
    /// siblings.
    Remove(json::ElemId),

    /// Replace the element's value with `json`, leaving an object field's key in place.
    Replace {
        /// The element whose value is rewritten.
        elem: json::ElemId,

        /// The value taking its place.
        json: Json,
    },

    /// Replace the key of the object field whose value is `elem`, leaving the value in place.
    Rename {
        /// The value of the field whose key is rewritten.
        elem: json::ElemId,

        /// The key to write, as a quoted JSON string such as `"min_kwh"`.
        key: Json,
    },
}

/// One JSON value represented as a `String`.
///
/// The text is spliced in place of an element's own span or of a field's quoted key, so it stands
/// in for exactly one value: it contains no `"key":` prefix and no comma. It doesn't matter which
/// value is used when the replacement target is an element, as any JSON value is a valid
/// replacement from a JSON spec point-of-view. When the target is a key, the text has to be a
/// quoted JSON string, so every rename is given text built by `Json::string`.
///
/// There is no constructor that takes JSON source. Each one takes the content to write and builds
/// the text itself, escaping what it writes, so a `Json` is one valid JSON value by construction.
/// What that does *not* promise is that it is the right value for where it lands: it is not
/// checked against the OCPI schema for that position, so [`apply`] will happily write a number
/// where an array was.
#[derive(Clone, Debug, Eq, PartialEq)]
pub(crate) struct Json(String);

impl Json {
    /// A JSON array holding each of `values` as a JSON string.
    ///
    /// The quoting and escaping happen here, so a caller passes the string content it wants
    /// written rather than JSON source: a value holding a quote or a backslash arrives in the
    /// document as that same one character.
    pub(crate) fn string_array(values: &[&str]) -> Self {
        let mut json = String::from("[");

        for (index, value) in values.iter().enumerate() {
            if index > 0 {
                json.push_str(", ");
            }

            push_json_string(&mut json, value);
        }

        json.push(']');

        Self::built(json)
    }

    /// A JSON string.
    ///
    /// `value` is quoted and escaped, so a caller passes the string content it wants
    /// written rather than JSON source.
    pub(crate) fn string(value: &str) -> Self {
        let mut json = String::new();

        push_json_string(&mut json, value);

        Self::built(json)
    }

    /// The text this value will be written as, exactly as it was built.
    pub fn as_str(&self) -> &str {
        &self.0
    }

    /// Take text built by a constructor above, holding it to being a single JSON value.
    ///
    /// Every constructor ends here, so the check covers all of them. It is a `debug_assert`
    /// rather than a returned error because the producer is always this crate. Text that is not
    /// one JSON value is a bug in the constructor that built it, not something a caller passed in
    /// or can act on. A release build still cannot write a corrupt document, since [`apply`]
    /// re-parses the whole result and reports [`Error::Internal`]; what the assertion adds is the
    /// producer's own stack rather than that after-the-fact report.
    fn built(text: String) -> Self {
        debug_assert!(
            is_one_json_value(&text),
            "`fix` built text that is not a single JSON value: `{text}`"
        );

        Self(text)
    }

    /// Take `text` verbatim, for tests needing a payload shape no constructor above builds.
    #[cfg(test)]
    fn raw(text: &str) -> Self {
        Self::built(text.to_owned())
    }
}

impl fmt::Display for Json {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.0)
    }
}

/// Write `value` into `json` as a quoted JSON string.
fn push_json_string(json: &mut String, value: &str) {
    json.push('"');

    for c in value.chars() {
        match c {
            '"' => json.push_str(r#"\""#),
            '\\' => json.push_str(r"\\"),
            '\n' => json.push_str(r"\n"),
            '\r' => json.push_str(r"\r"),
            '\t' => json.push_str(r"\t"),
            '\u{8}' => json.push_str(r"\b"),
            '\u{c}' => json.push_str(r"\f"),

            // JSON forbids a literal control character inside a string, and the ones above are
            // the only control characters with a shorthand, so the rest need the `\u` form.
            c if c < ' ' => {
                let code = u32::from(c);

                json.push_str(r"\u00");
                json.push(hex_digit(code >> 4));
                json.push(hex_digit(code & 0xf));
            }

            c => json.push(c),
        }
    }

    json.push('"');
}

/// The lower-case hex digit for `nibble`, which every caller here has already masked to one.
fn hex_digit(nibble: u32) -> char {
    char::from_digit(nibble, 16).unwrap_or('0')
}

/// Whether `text` is exactly one JSON value, which is what a replacement has room for.
fn is_one_json_value(text: &str) -> bool {
    let Ok(checked) = string::ReasonableLen::new(text) else {
        return false;
    };

    json::parse(checked).is_ok()
}

/// Why a set of [`Edit`]s could not be applied.
///
/// Most of these say the edits asked for something contradictory, or named an element that is
/// not there, and the caller can act on them. [`Error::Internal`] and [`Error::OverlappingSpans`]
/// are different in kind: no set of edits can ask for either, so reaching one is a bug in this
/// module rather than anything the caller did. They are returned rather than panicked on because
/// the caller is about to write the result over someone's tariff, and refusing to is better than
/// crashing in their process or, worse, handing back JSON that has been corrupted.
#[derive(Debug, Eq, PartialEq)]
pub enum Error {
    /// More than one replacement, or more than one rename, targets this element, and they disagree
    /// about the text.
    Duplicate(json::ElemId),

    /// Applying `outer` would silently discard the edit to `inner`, which sits inside it.
    Conflict {
        /// The replaced element.
        outer: json::ElemId,

        /// The element edited inside it.
        inner: json::ElemId,
    },

    /// The document has no element with this id.
    UnknownElement(json::ElemId),

    /// The edits were made from a different document than the one they are applied to. An edit
    /// renames the field holding this element, but in this document the element is the root or an
    /// item of an array, so it has no key.
    NotAField(json::ElemId),

    /// The removals could not be resolved to spans.
    Removal(json::RemovalError),

    /// Splicing produced source that is no longer valid JSON, which is a bug in this module.
    ///
    /// A replacement carries a payload that is one JSON value by construction, and a value is
    /// legal wherever another value was, so no payload should cause this. What is left is the
    /// removal spans and the splice itself, so reaching this means one of those is wrong - or, in
    /// a release build, that a payload builder is, since its own assertion is compiled out.
    Internal(json::Error),

    /// The spliced source exceeds the maximum size deemed reasonable.
    ///
    /// A caller can reach this: replacements longer than what they stand in for can take a
    /// document that was within the limit past it. This is the only size bound in the module, and
    /// it is on the whole output, since a bound on one payload would not catch that.
    OutputTooLarge,

    /// Two resolved spans overlap, so erasing both would corrupt the output. No set of edits
    /// should reach this; it means resolution itself is wrong.
    OverlappingSpans {
        /// The span that starts first.
        first: json::Span,

        /// The span that starts inside it.
        second: json::Span,
    },
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Duplicate(id) => {
                write!(f, "More than one edit rewrites the element with id `{id}`.")
            }
            Self::Conflict { outer, inner } => write!(
                f,
                "Replacing the element with id `{outer}` would discard the edit to the element with id `{inner}` inside it."
            ),
            Self::UnknownElement(id) => write!(f, "The document has no element with id `{id}`."),
            Self::NotAField(id) => write!(
                f,
                "The edits were made from a different document than the one they are applied to. The element with id `{id}` is the root or an item of an array, so it has no key to rename."
            ),
            Self::Removal(error) => write!(f, "{error}"),
            Self::Internal(error) => write!(
                f,
                "The edits spliced into JSON that does not parse, which is a bug in `fix`: {error}"
            ),
            Self::OutputTooLarge => write!(
                f,
                "The edited JSON exceeds the reasonable maximum `{} MB`.",
                string::ReasonableLen::FACTOR
            ),
            Self::OverlappingSpans { first, second } => write!(
                f,
                "The spans `{first:?}` and `{second:?}` overlap, so the edits can not both be applied."
            ),
        }
    }
}

impl std::error::Error for Error {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::Removal(error) => Some(error),
            Self::Internal(error) => Some(error),
            Self::Duplicate(_)
            | Self::Conflict { outer: _, inner: _ }
            | Self::UnknownElement(_)
            | Self::NotAField(_)
            | Self::OutputTooLarge
            | Self::OverlappingSpans {
                first: _,
                second: _,
            } => None,
        }
    }
}

/// One resolved edit: the span of source it covers and the text that takes its place.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
struct Splice<'edit> {
    span: json::Span,

    /// Empty for a removal.
    text: &'edit str,
}

/// A replacement that has been resolved to the span it rewrites.
#[derive(Clone, Copy, Debug)]
struct Replacement<'edit> {
    elem: json::ElemId,
    span: json::Span,
    text: &'edit str,
}

/// Resolve `edits` into the spans to rewrite, sorted by start offset.
fn resolve<'edit>(
    doc: &json::Document<'_>,
    edits: &'edit [Edit],
) -> Result<Vec<Splice<'edit>>, Error> {
    let mut removals: BTreeSet<json::ElemId> = BTreeSet::new();
    let mut replacements: BTreeMap<json::ElemId, &'edit str> = BTreeMap::new();
    let mut renames: BTreeMap<json::ElemId, &'edit str> = BTreeMap::new();

    for edit in edits {
        match &edit.change {
            Change::Remove(id) => {
                removals.insert(*id);
            }
            Change::Replace { elem, json } => {
                let earlier = replacements.insert(*elem, json.as_str());

                if earlier.is_some_and(|earlier| earlier != json.as_str()) {
                    return Err(Error::Duplicate(*elem));
                }
            }
            // A rename and a replacement of the same field share the id of the field's value, but
            // they rewrite different spans. Sharing the `replacements` map would make the two
            // collide as a `Duplicate`, so renames are kept in a map of their own. Only two renames
            // with different keys are a `Duplicate`.
            Change::Rename { elem, key } => {
                let earlier = renames.insert(*elem, key.as_str());

                if earlier.is_some_and(|earlier| earlier != key.as_str()) {
                    return Err(Error::Duplicate(*elem));
                }
            }
        }
    }

    let removed = doc.removal_spans(&removals).map_err(Error::Removal)?;
    let replaced = resolve_replacements(doc, &replacements, &renames, &removals, &removed)?;

    check_no_removal_inside_a_replacement(doc, &removals, &replaced)?;

    let mut splices: Vec<Splice<'edit>> = Vec::new();

    for span in removed {
        splices.push(Splice { span, text: "" });
    }

    for replacement in replaced {
        splices.push(Splice {
            span: replacement.span,
            text: replacement.text,
        });
    }

    splices.sort_by_key(|splice| splice.span);

    Ok(splices)
}

/// Resolve each replacement and each rename to its span, dropping each one that a removal makes
/// redundant. A removal erases the span of every edit inside the removed element, so such an edit
/// would change nothing.
///
/// A rename becomes a replacement of the span of the field's key. The checks that follow treat it
/// like any other replacement. So replacing an element that contains the field is a conflict, just
/// as replacing an element that contains another replacement is.
fn resolve_replacements<'edit>(
    doc: &json::Document<'_>,
    replacements: &BTreeMap<json::ElemId, &'edit str>,
    renames: &BTreeMap<json::ElemId, &'edit str>,
    removals: &BTreeSet<json::ElemId>,
    removed: &[json::Span],
) -> Result<Vec<Replacement<'edit>>, Error> {
    let mut resolved: Vec<Replacement<'edit>> = Vec::new();

    for (elem, text) in renames {
        if removals.contains(elem) {
            continue;
        }

        doc.element(*elem).ok_or(Error::UnknownElement(*elem))?;
        let span = doc.key_span(*elem).ok_or(Error::NotAField(*elem))?;

        if removed.iter().any(|erased| contains(*erased, span)) {
            continue;
        }

        resolved.push(Replacement {
            elem: *elem,
            span,
            text,
        });
    }

    for (elem, text) in replacements {
        if removals.contains(elem) {
            continue;
        }

        let element = doc.element(*elem).ok_or(Error::UnknownElement(*elem))?;
        let span = element.span();

        if removed.iter().any(|erased| contains(*erased, span)) {
            continue;
        }

        resolved.push(Replacement {
            elem: *elem,
            span,
            text,
        });
    }

    resolved.sort_by_key(|replacement| replacement.span);

    check_no_nested_replacement(&resolved)?;

    Ok(resolved)
}

/// Reject a replacement that sits inside another replacement.
///
/// Element spans nest or are disjoint, and no two elements share a start offset, so sorting
/// by span puts an enclosing replacement before the one it encloses.
fn check_no_nested_replacement(replaced: &[Replacement<'_>]) -> Result<(), Error> {
    let mut outer: Option<Replacement<'_>> = None;

    for replacement in replaced {
        if let Some(open) = outer
            && replacement.span.start < open.span.end
        {
            return Err(Error::Conflict {
                outer: open.elem,
                inner: replacement.elem,
            });
        }

        outer = Some(*replacement);
    }

    Ok(())
}

/// Reject a removal that sits inside a replacement.
fn check_no_removal_inside_a_replacement(
    doc: &json::Document<'_>,
    removals: &BTreeSet<json::ElemId>,
    replaced: &[Replacement<'_>],
) -> Result<(), Error> {
    for id in removals {
        let element = doc.element(*id).ok_or(Error::UnknownElement(*id))?;
        let span = element.span();
        let enclosing = replaced
            .iter()
            .find(|replacement| contains(replacement.span, span));

        if let Some(replacement) = enclosing {
            return Err(Error::Conflict {
                outer: replacement.elem,
                inner: *id,
            });
        }
    }

    Ok(())
}

/// Rewrite `source` by replacing each span with its text.
fn splice(source: &str, splices: &[Splice<'_>]) -> Result<String, Error> {
    let mut out = String::with_capacity(source.len());
    let mut pos: u32 = 0;

    for splice in splices {
        if splice.span.start < pos {
            let previous = splices
                .iter()
                .find(|earlier| earlier.span.end == pos)
                .map(|earlier| earlier.span)
                .unwrap_or_default();

            return Err(Error::OverlappingSpans {
                first: previous,
                second: splice.span,
            });
        }

        out.push_str(slice(source, pos, splice.span.start));
        out.push_str(splice.text);
        pos = splice.span.end;
    }

    out.push_str(slice(source, pos, source_len(source)));

    Ok(out)
}

/// Return true if `outer` covers every byte of `inner`.
fn contains(outer: json::Span, inner: json::Span) -> bool {
    inner.start >= outer.start && inner.end <= outer.end
}

/// Re-parse edited JSON, so a corrupted splice is reported rather than written.
fn check_parses(json: &str) -> Result<(), Error> {
    let json = string::ReasonableLen::new(json).map_err(|_e| Error::OutputTooLarge)?;

    json::parse(json).map_err(Error::Internal)?;

    Ok(())
}

/// The byte range `start..end` of `source`.
///
/// Every span comes from the parser that read `source`, so it always lands on a character
/// boundary; an out of range span yields an empty `&str` rather than a panic.
fn slice(source: &str, start: u32, end: u32) -> &str {
    let Ok(start) = usize::try_from(start) else {
        return "";
    };
    let Ok(end) = usize::try_from(end) else {
        return "";
    };

    source.get(start..end).unwrap_or("")
}

/// The length of `source` as a span offset.
fn source_len(source: &str) -> u32 {
    u32::try_from(source.len()).unwrap_or(u32::MAX)
}