alpha2-diagnose 0.10.0

Format-neutral document diagnostics for alpha2: a document tree, a JSON reader that recovers, a schema walker, advice and fixes.
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
//! Advisors: help lines and fixes added to diagnostics from what the schema says.

use crate::codes::{
    SHAPE_MISSING_FIELD, SHAPE_MISSING_TAG, SHAPE_NOT_INTEGER, SHAPE_NOT_ONE_OF,
    SHAPE_OUT_OF_RANGE, SHAPE_UNKNOWN_FIELD, SHAPE_UNKNOWN_TAG, SHAPE_WRONG_TYPE,
};
use crate::diagnostic::{Diagnostic, Edit, Fix};
use crate::path::{Path, Segment};
use crate::schema::{Schema, SchemaId, Types};
use crate::shape::{Finding, type_words, written};
use crate::suggest::{self, Suggestion};
use crate::tree::{Node, Number, Value};
use crate::write::quote;

/// What an advisor sees besides the diagnostic.
#[derive(Clone, Copy, Debug)]
pub struct Context<'a> {
    /// The schema the document was walked against, if any.
    pub schema: Option<&'a Schema>,
    /// The document as read.
    pub tree: &'a Node,
    /// The schema node of the value (for a field problem, of the object).
    pub at: Option<SchemaId>,
    /// The schema of the object holding that value.
    pub parent: Option<SchemaId>,
}

impl<'a> Context<'a> {
    /// The schema and the node of the value, when the diagnostic came from the walker.
    #[must_use]
    pub fn shape(&self) -> Option<(&'a Schema, SchemaId)> {
        self.schema.zip(self.at)
    }
}

/// Adds help and fixes to a diagnostic. A pack registers its own beside the generic ones.
pub trait Advisor {
    /// Adds what it knows; leaves the diagnostic alone otherwise.
    fn advise(&self, diagnostic: &mut Diagnostic, context: &Context<'_>);
}

impl<F: Fn(&mut Diagnostic, &Context<'_>)> Advisor for F {
    fn advise(&self, diagnostic: &mut Diagnostic, context: &Context<'_>) {
        self(diagnostic, context);
    }
}

/// A field that belongs somewhere far from where it was written, which no closeness rule finds.
#[derive(Clone, Copy, Debug)]
pub struct Misplacement {
    /// The definition the field was written in.
    pub definition: &'static str,
    /// The field.
    pub field: &'static str,
    /// Where it belongs and how to write it there.
    pub help: &'static str,
}

/// A table of misplacements, as one advisor on `shape.unknown_field`.
#[derive(Clone, Copy, Debug)]
pub struct Misplacements(pub &'static [Misplacement]);

impl Advisor for Misplacements {
    fn advise(&self, diagnostic: &mut Diagnostic, _: &Context<'_>) {
        if !diagnostic.is(&SHAPE_UNKNOWN_FIELD) {
            return;
        }
        let Some(definition) = diagnostic
            .reference
            .as_ref()
            .map(|reference| reference.definition.clone())
        else {
            return;
        };
        let field = diagnostic.path.last_key().unwrap_or_default().to_owned();
        if let Some(entry) = self
            .0
            .iter()
            .find(|entry| entry.definition == definition && entry.field == field)
        {
            diagnostic.help.push(entry.help.to_owned());
        }
    }
}

/// The generic advisors, in the order they run after a pack's own.
#[must_use]
pub fn generic() -> Vec<&'static dyn Advisor> {
    vec![
        &integer_spelling,
        &same_name,
        &one_level_off,
        &close_name,
        &bare_value,
        &misspelt_tag,
        &missing_field,
        &percent_for_fraction,
    ]
}

/// Runs a pack's advisors, then the generic ones, over every finding.
#[must_use]
pub fn run(
    findings: Vec<Finding>,
    schema: Option<&Schema>,
    tree: &Node,
    advisors: &[&dyn Advisor],
) -> Vec<Diagnostic> {
    let generic = generic();
    let advised: Vec<Diagnostic> = findings
        .into_iter()
        .map(|finding| {
            let mut diagnostic = finding.diagnostic;
            let context = Context {
                schema,
                tree,
                at: finding.schema,
                parent: finding.parent,
            };
            for advisor in advisors.iter().chain(generic.iter()) {
                advisor.advise(&mut diagnostic, &context);
            }
            diagnostic
        })
        .collect();
    without_renamed_missing(advised)
}

fn without_renamed_missing(diagnostics: Vec<Diagnostic>) -> Vec<Diagnostic> {
    let renamed: Vec<(Path, String)> = diagnostics
        .iter()
        .filter(|diagnostic| diagnostic.is(&SHAPE_UNKNOWN_FIELD))
        .flat_map(|diagnostic| &diagnostic.fixes)
        .flat_map(|fix| &fix.edits)
        .filter_map(|edit| match edit {
            Edit::RenameKey { path, to } => Some((path.parent()?, to.clone())),
            _ => None,
        })
        .collect();
    diagnostics
        .into_iter()
        .filter(|diagnostic| {
            !(diagnostic.is(&SHAPE_MISSING_FIELD)
                && diagnostic
                    .datum("field")
                    .and_then(Node::as_str)
                    .is_some_and(|field| {
                        renamed
                            .iter()
                            .any(|(object, to)| *object == diagnostic.path && to == field)
                    }))
        })
        .collect()
}

fn property_names(schema: &Schema, id: SchemaId) -> Vec<&str> {
    let mut names: Vec<&str> = Vec::new();
    for object in schema.objects(id) {
        for (name, _) in &schema.node(object).properties {
            if !names.contains(&name.as_str()) {
                names.push(name);
            }
        }
    }
    names
}

fn property(schema: &Schema, id: SchemaId, name: &str) -> Option<SchemaId> {
    schema
        .objects(id)
        .into_iter()
        .find_map(|object| schema.node(object).property(name))
}

fn field_of(diagnostic: &Diagnostic) -> Option<(Path, String)> {
    let field = diagnostic.path.last_key()?.to_owned();
    Some((diagnostic.path.parent()?, field))
}

/// A union's tag field written under another name (`tpye` for `type`): the rename, as a
/// likely fix, when exactly one field of the object is near the tag's name.
pub fn misspelt_tag(diagnostic: &mut Diagnostic, context: &Context<'_>) {
    if !diagnostic.is(&SHAPE_MISSING_TAG) || diagnostic.has_advice() {
        return;
    }
    let Some(tag) = diagnostic
        .datum("tag")
        .and_then(Node::as_str)
        .map(str::to_owned)
    else {
        return;
    };
    let Some(entries) = context.tree.at(&diagnostic.path).and_then(Node::as_map) else {
        return;
    };
    let keys = entries
        .iter()
        .map(|entry| entry.key.as_str())
        .filter(|key| *key != tag);
    let Suggestion::One(written) = suggest::closest(&tag, keys) else {
        return;
    };
    diagnostic.help.push(format!(
        "{} looks like {} misspelt (a guess)",
        quote(written),
        quote(&tag)
    ));
    diagnostic.fixes.push(Fix::likely(
        format!("rename {} to {}", quote(written), quote(&tag)),
        vec![Edit::RenameKey {
            path: diagnostic.path.key(written),
            to: tag,
        }],
    ));
}

/// `1920.0` in an integer field: the same number spelt as an integer, a certain fix.
pub fn integer_spelling(diagnostic: &mut Diagnostic, _: &Context<'_>) {
    if !diagnostic.is(&SHAPE_NOT_INTEGER) {
        return;
    }
    let Some(whole) = diagnostic
        .datum("whole")
        .and_then(Node::as_str)
        .map(str::to_owned)
    else {
        return;
    };
    let Some(number) = Number::parse(&whole) else {
        return;
    };
    diagnostic.help.push(format!(
        "the value is the integer {whole}; write it without a fraction"
    ));
    diagnostic.fixes.push(Fix::certain(
        format!("write {whole}"),
        vec![Edit::Replace {
            path: diagnostic.path.clone(),
            value: Node::number(number),
        }],
    ));
}

/// A field written in another case or with other separators (`sourceId` for `source_id`): a
/// certain rename when exactly one field of the type matches.
pub fn same_name(diagnostic: &mut Diagnostic, context: &Context<'_>) {
    if !diagnostic.is(&SHAPE_UNKNOWN_FIELD) || diagnostic.has_advice() {
        return;
    }
    let (Some((schema, at)), Some((object, field))) = (context.shape(), field_of(diagnostic))
    else {
        return;
    };
    let names = property_names(schema, at);
    let matches: Vec<&str> = names
        .iter()
        .copied()
        .filter(|name| suggest::same_name(name, &field))
        .collect();
    let [name] = matches.as_slice() else {
        return;
    };
    diagnostic
        .help
        .push(format!("the field is spelt {}", quote(name)));
    let taken = context
        .tree
        .at(&object)
        .and_then(|node| node.get(name))
        .is_some();
    if taken {
        diagnostic.help.push(format!(
            "{} is already given; remove one of the two",
            quote(name)
        ));
    } else {
        diagnostic.fixes.push(Fix::certain(
            format!("rename {} to {}", quote(&field), quote(name)),
            vec![Edit::RenameKey {
                path: diagnostic.path.clone(),
                to: (*name).to_owned(),
            }],
        ));
    }
}

/// A field one level off: a field of a child object (`opacity` on a clip, meaning
/// `visual.opacity`) or of the object above.
pub fn one_level_off(diagnostic: &mut Diagnostic, context: &Context<'_>) {
    if !diagnostic.is(&SHAPE_UNKNOWN_FIELD) || diagnostic.has_advice() {
        return;
    }
    let (Some((schema, at)), Some((object, field))) = (context.shape(), field_of(diagnostic))
    else {
        return;
    };
    let children: Vec<&str> = property_names(schema, at)
        .into_iter()
        .filter(|child| {
            property(schema, at, child)
                .is_some_and(|child_id| property(schema, child_id, &field).is_some())
        })
        .collect();
    if let [child] = children.as_slice() {
        diagnostic.help.push(format!(
            "{} is a field of {}, one level down",
            quote(&field),
            quote(child)
        ));
        let child_path = object.key(*child);
        let to = child_path.key(field.clone());
        let mut edits = Vec::new();
        match context.tree.at(&child_path) {
            Some(node) if node.get(&field).is_some() => return,
            Some(node) if matches!(node.value, Value::Map(_)) => {}
            Some(_) => return,
            None => edits.push(Edit::Insert {
                path: child_path,
                value: Node::map(Vec::<(String, Node)>::new()),
            }),
        }
        edits.push(Edit::Move {
            from: diagnostic.path.clone(),
            to,
        });
        diagnostic.fixes.push(Fix::likely(
            format!("move {} into {}", quote(&field), quote(child)),
            edits,
        ));
        return;
    }
    let Some(parent) = context.parent else {
        return;
    };
    if property(schema, parent, &field).is_none() || !matches!(object.last(), Some(Segment::Key(_)))
    {
        return;
    }
    let Some(above) = object.parent() else {
        return;
    };
    diagnostic
        .help
        .push(format!("{} is a field of the object above", quote(&field)));
    if context
        .tree
        .at(&above)
        .and_then(|node| node.get(&field))
        .is_none()
    {
        diagnostic.fixes.push(Fix::likely(
            format!("move {} up one level", quote(&field)),
            vec![Edit::Move {
                from: diagnostic.path.clone(),
                to: above.key(field),
            }],
        ));
    }
}

/// A close name for an unknown field, kind or value, or the list of known ones.
pub fn close_name(diagnostic: &mut Diagnostic, context: &Context<'_>) {
    if diagnostic.has_advice() {
        return;
    }
    if diagnostic.is(&SHAPE_UNKNOWN_FIELD) {
        let (Some((schema, at)), Some((object, field))) = (context.shape(), field_of(diagnostic))
        else {
            return;
        };
        let present = context.tree.at(&object);
        let names: Vec<&str> = property_names(schema, at)
            .into_iter()
            .filter(|name| present.and_then(|node| node.get(name)).is_none())
            .collect();
        match suggest::closest(&field, names.iter().copied()) {
            Suggestion::One(name) => {
                diagnostic
                    .help
                    .push(format!("did you mean {}?", quote(name)));
                diagnostic.fixes.push(Fix::likely(
                    format!("rename {} to {}", quote(&field), quote(name)),
                    vec![Edit::RenameKey {
                        path: diagnostic.path.clone(),
                        to: name.to_owned(),
                    }],
                ));
            }
            Suggestion::Several(list) => diagnostic.help.push(format!(
                "did you mean one of {}?",
                suggest::listed(list, suggest::MAX_CANDIDATES)
            )),
            Suggestion::None => {
                let all = property_names(schema, at);
                if !all.is_empty() {
                    let owner = diagnostic.reference.as_ref().map_or_else(
                        || "this object".to_owned(),
                        |reference| reference.definition.clone(),
                    );
                    diagnostic.help.push(format!(
                        "{owner} has the fields {}",
                        suggest::listed(all, 24)
                    ));
                }
            }
        }
        return;
    }
    if !(diagnostic.is(&SHAPE_UNKNOWN_TAG) || diagnostic.is(&SHAPE_NOT_ONE_OF)) {
        return;
    }
    let Some(found) = diagnostic
        .datum("found")
        .and_then(Node::as_str)
        .map(str::to_owned)
    else {
        return;
    };
    let allowed: Vec<String> = diagnostic
        .datum("allowed")
        .and_then(Node::as_list)
        .unwrap_or_default()
        .iter()
        .filter_map(|value| value.as_str().map(str::to_owned))
        .collect();
    match suggest::closest(&found, allowed.iter().map(String::as_str)) {
        Suggestion::One(name) => {
            diagnostic
                .help
                .push(format!("did you mean {}?", quote(name)));
            diagnostic.fixes.push(Fix::likely(
                format!("write {}", quote(name)),
                vec![Edit::Replace {
                    path: diagnostic.path.clone(),
                    value: Node::text(name),
                }],
            ));
        }
        Suggestion::Several(list) => diagnostic.help.push(format!(
            "did you mean one of {}?",
            suggest::listed(list, suggest::MAX_CANDIDATES)
        )),
        Suggestion::None => {}
    }
}

fn tagged_unions(schema: &Schema, id: SchemaId) -> Vec<(String, Vec<SchemaId>)> {
    let mut unions = Vec::new();
    for candidate in std::iter::once(schema.resolve(id)).chain(schema.non_null_forms(id)) {
        let node = schema.node(candidate);
        if let Some(tag) = &node.tag
            && !unions
                .iter()
                .any(|(_, forms): &(String, Vec<SchemaId>)| *forms == node.forms)
        {
            unions.push((tag.clone(), node.forms.clone()));
        }
    }
    unions
}

/// A bare value where a tagged object belongs, and exactly one form holds one value of that
/// type: `0.5` for `{"mode": "constant", "value": 0.5}`.
pub fn bare_value(diagnostic: &mut Diagnostic, context: &Context<'_>) {
    if !diagnostic.is(&SHAPE_WRONG_TYPE) || diagnostic.has_advice() {
        return;
    }
    let Some((schema, at)) = context.shape() else {
        return;
    };
    let Some(value) = context.tree.at(&diagnostic.path) else {
        return;
    };
    if matches!(value.value, Value::Map(_) | Value::Null) {
        return;
    }
    let mut wraps = Vec::new();
    for (tag, forms) in tagged_unions(schema, at) {
        for form in forms {
            let form = schema.resolve(form);
            let node = schema.node(form);
            let Some(tag_value) = schema.tag_value(form, &tag) else {
                continue;
            };
            let others: Vec<&(String, SchemaId)> = node
                .properties
                .iter()
                .filter(|(name, _)| *name != tag)
                .collect();
            let fits: Vec<&&(String, SchemaId)> = others
                .iter()
                .filter(|(_, property)| schema.types(*property).admits(value))
                .collect();
            let required_ok = node
                .required
                .iter()
                .all(|name| *name == tag || fits.first().is_some_and(|(fit, _)| fit == name));
            if let [(name, property)] = fits.as_slice()
                && required_ok
            {
                let exact = schema.types(*property).intersects(Types::of(value));
                wraps.push((
                    exact,
                    Node::map([
                        (tag.clone(), tag_value.clone()),
                        (name.clone(), value.clone().without_spans()),
                    ]),
                ));
            }
        }
    }
    if wraps.len() > 1 {
        wraps.retain(|(exact, _)| *exact);
    }
    let [(_, wrapped)] = wraps.as_slice() else {
        return;
    };
    diagnostic.help.push(format!(
        "a bare value is written in its tagged form here: {}",
        written(wrapped)
    ));
    diagnostic.fixes.push(Fix::likely(
        format!("write {}", written(wrapped)),
        vec![Edit::Replace {
            path: diagnostic.path.clone(),
            value: wrapped.clone(),
        }],
    ));
}

/// What a missing field takes: its type as the reference writes it, and its smallest form.
pub fn missing_field(diagnostic: &mut Diagnostic, context: &Context<'_>) {
    if !diagnostic.is(&SHAPE_MISSING_FIELD) || diagnostic.has_advice() {
        return;
    }
    let Some((schema, at)) = context.shape() else {
        return;
    };
    let Some(field) = diagnostic
        .datum("field")
        .and_then(Node::as_str)
        .map(str::to_owned)
    else {
        return;
    };
    let Some(property) = property(schema, at, &field) else {
        return;
    };
    diagnostic.help.push(format!(
        "{} takes {}",
        quote(&field),
        describe(schema, property)
    ));
    if let Some(smallest) = smallest(schema, property, 0) {
        diagnostic
            .help
            .push(format!("its smallest form is {}", written(&smallest)));
    }
}

/// A value over one where the range is 0..=1 and the value reads as a percentage.
pub fn percent_for_fraction(diagnostic: &mut Diagnostic, _: &Context<'_>) {
    if !diagnostic.is(&SHAPE_OUT_OF_RANGE) || diagnostic.has_advice() {
        return;
    }
    let number = |key| {
        diagnostic
            .datum(key)
            .and_then(Node::as_number)
            .map(Number::as_f64)
    };
    let (Some(found), Some(minimum), Some(maximum)) =
        (number("found"), number("minimum"), number("maximum"))
    else {
        return;
    };
    if minimum < 0.0 || (maximum - 1.0).abs() > f64::EPSILON || found <= 1.0 || found > 100.0 {
        return;
    }
    let fraction = Node::float(found / 100.0);
    diagnostic.help.push(format!(
        "the range is a fraction; if {} is a percentage, write {}",
        written(&Node::float(found)),
        written(&fraction)
    ));
    diagnostic.fixes.push(Fix::likely(
        format!("write {}", written(&fraction)),
        vec![Edit::Replace {
            path: diagnostic.path.clone(),
            value: fraction,
        }],
    ));
}

/// A schema node in words, as the reference writes types: a definition by name, constants
/// listed, else the JSON types and format.
#[must_use]
pub fn describe(schema: &Schema, id: SchemaId) -> String {
    if let Some(definition) = schema.definition_of(id) {
        return format!("a {}", definition.name);
    }
    if let Some(constants) = schema.constants(id) {
        let values: Vec<String> = constants.iter().map(|value| written(value)).collect();
        return format!("one of {}", values.join(", "));
    }
    let forms = schema.non_null_forms(id);
    if let [only] = forms.as_slice()
        && *only != schema.resolve(id)
    {
        return format!("{} or null", describe(schema, *only));
    }
    let node = schema.node(schema.resolve(id));
    let mut words = type_words(schema.types(id));
    if let Some(format) = node.format {
        words = format!("{words} ({})", format.name());
    }
    words
}

/// The smallest value a schema node takes: a constant, a default, or the required fields of
/// an object filled in; `None` past a few levels or where no value is plain to give.
#[must_use]
pub fn smallest(schema: &Schema, id: SchemaId, depth: usize) -> Option<Node> {
    if depth > 6 {
        return None;
    }
    let id = schema.resolve(id);
    let node = schema.node(id);
    if let Some(constant) = &node.constant {
        return Some(constant.clone());
    }
    if let Some(choices) = &node.choices {
        return choices.first().cloned();
    }
    if let Some(default) = &node.default {
        return Some(default.clone());
    }
    if let Some(target) = node.reference {
        return smallest(schema, target, depth + 1);
    }
    if let Some(first) = schema.non_null_forms(id).first()
        && *first != id
    {
        return smallest(schema, *first, depth + 1);
    }
    let types = node.types.unwrap_or_else(|| schema.types(id));
    if types.contains(Types::OBJECT) || !node.properties.is_empty() {
        let mut entries = Vec::new();
        for name in &node.required {
            let property = node.property(name)?;
            entries.push((name.clone(), smallest(schema, property, depth + 1)?));
        }
        return Some(Node::map(entries));
    }
    if types.contains(Types::ARRAY) {
        let count = node.min_items.unwrap_or(0);
        if count == 0 {
            return Some(Node::list(Vec::new()));
        }
        let item = match node.items {
            Some(crate::schema::Additional::Schema(item)) => smallest(schema, item, depth + 1)?,
            _ => return None,
        };
        return Some(Node::list(vec![item; count]));
    }
    if types.contains(Types::NUMBER) {
        return Some(
            node.minimum
                .map_or_else(|| Node::integer(0), |minimum| Node::float(minimum.max(0.0))),
        );
    }
    if types.contains(Types::INTEGER) {
        #[expect(
            clippy::cast_possible_truncation,
            reason = "a schema bound is a small whole number"
        )]
        return Some(Node::integer(
            node.minimum
                .map_or(0, |minimum| minimum.max(0.0).ceil() as i64),
        ));
    }
    if types.contains(Types::BOOLEAN) {
        return Some(Node::bool(false));
    }
    if types.contains(Types::STRING) && node.min_length.unwrap_or(0) == 0 {
        return Some(Node::text(""));
    }
    if types.contains(Types::NULL) {
        return Some(Node::null());
    }
    None
}

/// Serde's opening words for a field a type does not take.
const SERDE_UNKNOWN_FIELD: &str = "unknown field `";

/// Serde's opening words for a kind or value a type does not take.
const SERDE_UNKNOWN_VARIANT: &str = "unknown variant `";

/// A refusal in serde's words for an unknown field or value, moved to that key or value below
/// its path and advised as the walker would; kept as it is when that is not found exactly once.
#[must_use]
pub fn serde_refusal(diagnostic: Diagnostic, tree: &Node) -> Diagnostic {
    if let Some((field, expected)) = quoted_after(&diagnostic.message, SERDE_UNKNOWN_FIELD) {
        return unknown_field_refusal(diagnostic, tree, &field, &expected);
    }
    if let Some((value, expected)) = quoted_after(&diagnostic.message, SERDE_UNKNOWN_VARIANT) {
        return unknown_variant_refusal(diagnostic, tree, &value, &expected);
    }
    diagnostic
}

fn unknown_field_refusal(
    mut diagnostic: Diagnostic,
    tree: &Node,
    field: &str,
    expected: &[String],
) -> Diagnostic {
    let Some((path, key_span)) = tree
        .at(&diagnostic.path)
        .and_then(|object| below(object, &diagnostic.path, |key, _| key == Some(field)))
    else {
        return diagnostic;
    };
    let present: Vec<&str> = path
        .parent()
        .and_then(|object| tree.at(&object))
        .and_then(Node::as_map)
        .map(|entries| entries.iter().map(|entry| entry.key.as_str()).collect())
        .unwrap_or_default();
    diagnostic.path = path;
    diagnostic.span = key_span.or(diagnostic.span);
    let free: Vec<&str> = expected
        .iter()
        .map(String::as_str)
        .filter(|name| !present.contains(name))
        .collect();
    let same: Vec<&str> = free
        .iter()
        .copied()
        .filter(|name| suggest::same_name(name, field))
        .collect();
    let at = diagnostic.path.clone();
    let rename = |to: &str| Edit::RenameKey {
        path: at.clone(),
        to: to.to_owned(),
    };
    if let [name] = same.as_slice() {
        let fix = Fix::certain(
            format!("rename {} to {}", quote(field), quote(name)),
            vec![rename(name)],
        );
        diagnostic
            .help
            .push(format!("the field is spelt {}", quote(name)));
        diagnostic.fixes.push(fix);
        return diagnostic;
    }
    let fix = |name: &str| {
        Fix::likely(
            format!("rename {} to {}", quote(field), quote(name)),
            vec![rename(name)],
        )
    };
    suggest_close(&mut diagnostic, field, &free, fix);
    diagnostic
}

fn unknown_variant_refusal(
    mut diagnostic: Diagnostic,
    tree: &Node,
    value: &str,
    expected: &[String],
) -> Diagnostic {
    let Some((path, _)) = tree.at(&diagnostic.path).and_then(|object| {
        below(object, &diagnostic.path, |_, node| {
            node.as_str() == Some(value)
        })
    }) else {
        return diagnostic;
    };
    diagnostic.span = tree
        .at(&path)
        .and_then(|node| node.span)
        .or(diagnostic.span);
    diagnostic.path = path;
    let names: Vec<&str> = expected.iter().map(String::as_str).collect();
    let at = diagnostic.path.clone();
    let fix = |name: &str| {
        Fix::likely(
            format!("write {}", quote(name)),
            vec![Edit::Replace {
                path: at.clone(),
                value: Node::text(name),
            }],
        )
    };
    suggest_close(&mut diagnostic, value, &names, fix);
    diagnostic
}

fn suggest_close(
    diagnostic: &mut Diagnostic,
    written: &str,
    names: &[&str],
    fix: impl Fn(&str) -> Fix,
) {
    match suggest::closest(written, names.iter().copied()) {
        Suggestion::One(name) => {
            diagnostic
                .help
                .push(format!("did you mean {}?", quote(name)));
            diagnostic.fixes.push(fix(name));
        }
        Suggestion::Several(list) => diagnostic.help.push(format!(
            "did you mean one of {}?",
            suggest::listed(list, suggest::MAX_CANDIDATES)
        )),
        Suggestion::None => {}
    }
}

fn quoted_after(message: &str, opening: &str) -> Option<(String, Vec<String>)> {
    let start = message.find(opening)? + opening.len();
    let (name, rest) = message[start..].split_once('`')?;
    let expected = rest
        .split_once("expected")
        .map(|(_, list)| {
            list.split('`')
                .skip(1)
                .step_by(2)
                .map(str::to_owned)
                .collect()
        })
        .unwrap_or_default();
    Some((name.to_owned(), expected))
}

/// The one key or value below `object` (at `at`) that `wanted` takes, nearest level first, with
/// the place of its key or value; none when the nearest level that has one has several.
pub fn below(
    object: &Node,
    at: &Path,
    wanted: impl Fn(Option<&str>, &Node) -> bool,
) -> Option<(Path, Option<crate::Span>)> {
    let mut level = vec![(object, at.clone())];
    while !level.is_empty() {
        let mut found = Vec::new();
        let mut next = Vec::new();
        for (node, path) in level {
            match &node.value {
                Value::Map(entries) => {
                    for entry in entries {
                        let inner = path.key(entry.key.clone());
                        if wanted(Some(&entry.key), &entry.value) {
                            found.push((inner.clone(), entry.key_span));
                        }
                        next.push((&entry.value, inner));
                    }
                }
                Value::List(items) => {
                    for (index, item) in items.iter().enumerate() {
                        let inner = path.index(index);
                        if wanted(None, item) {
                            found.push((inner.clone(), item.span));
                        }
                        next.push((item, inner));
                    }
                }
                _ => {}
            }
        }
        match found.len() {
            0 => level = next,
            1 => return found.pop(),
            _ => return None,
        }
    }
    None
}

#[cfg(test)]
#[path = "advise_tests.rs"]
mod tests;