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
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
//! A compiled JSON Schema, for the subset alpha2's published schemas use. Any other keyword is
//! refused with its place.

use std::collections::HashMap;
use std::fmt;

use crate::path::Path;
use crate::tree::{Node, Value};

/// An index of a node in a [`Schema`].
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct SchemaId(u32);

impl SchemaId {
    const fn index(self) -> usize {
        self.0 as usize
    }
}

/// The JSON types a schema node allows, as a set.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
pub struct Types(u8);

impl Types {
    /// `null`.
    pub const NULL: Self = Self(1);
    /// `boolean`.
    pub const BOOLEAN: Self = Self(2);
    /// `integer`.
    pub const INTEGER: Self = Self(4);
    /// `number`.
    pub const NUMBER: Self = Self(8);
    /// `string`.
    pub const STRING: Self = Self(16);
    /// `array`.
    pub const ARRAY: Self = Self(32);
    /// `object`.
    pub const OBJECT: Self = Self(64);

    const NAMES: [(Self, &'static str); 7] = [
        (Self::OBJECT, "object"),
        (Self::ARRAY, "array"),
        (Self::STRING, "string"),
        (Self::NUMBER, "number"),
        (Self::INTEGER, "integer"),
        (Self::BOOLEAN, "boolean"),
        (Self::NULL, "null"),
    ];

    fn from_name(name: &str) -> Option<Self> {
        Self::NAMES
            .iter()
            .find(|(_, known)| *known == name)
            .map(|(types, _)| *types)
    }

    /// Whether every type of `other` is in the set.
    #[must_use]
    pub const fn contains(self, other: Self) -> bool {
        self.0 & other.0 == other.0
    }

    /// Whether no type is in the set.
    #[must_use]
    pub const fn is_empty(self) -> bool {
        self.0 == 0
    }

    /// Whether the two sets share a type.
    #[must_use]
    pub const fn intersects(self, other: Self) -> bool {
        self.0 & other.0 != 0
    }

    /// The union of two sets.
    #[must_use]
    pub const fn union(self, other: Self) -> Self {
        Self(self.0 | other.0)
    }

    /// The type of a value; a number is `number`, and also `integer` when spelt as one.
    #[must_use]
    pub fn of(node: &Node) -> Self {
        match &node.value {
            Value::Null => Self::NULL,
            Value::Bool(_) => Self::BOOLEAN,
            Value::Number(number) => {
                if number.as_i128().is_some() {
                    Self::NUMBER.union(Self::INTEGER)
                } else {
                    Self::NUMBER
                }
            }
            Value::Text(_) => Self::STRING,
            Value::List(_) => Self::ARRAY,
            Value::Map(_) => Self::OBJECT,
        }
    }

    /// Whether a value of this JSON kind may stand here; any number may stand where an integer
    /// does, its spelling being judged later.
    #[must_use]
    pub fn admits(self, node: &Node) -> bool {
        match &node.value {
            Value::Number(_) => self.contains(Self::NUMBER) || self.contains(Self::INTEGER),
            _ => self.contains(Self::of(node)),
        }
    }

    /// The type names, as JSON Schema writes them.
    #[must_use]
    pub fn names(self) -> Vec<&'static str> {
        Self::NAMES
            .iter()
            .filter(|(types, _)| self.contains(*types))
            .map(|(_, name)| *name)
            .collect()
    }
}

/// The value formats the walker knows.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Format {
    /// A 32-bit float: any JSON number, read as 32 bits.
    Float,
    /// A 64-bit float.
    Double,
    /// An integer in `i8`.
    Int8,
    /// An integer in `i16`.
    Int16,
    /// An integer in `i32`.
    Int32,
    /// An integer in `i64`.
    Int64,
    /// An integer in `u8`.
    Uint8,
    /// An integer in `u16`.
    Uint16,
    /// An integer in `u32`.
    Uint32,
    /// An integer in `u64`.
    Uint64,
    /// A URI reference; not checked.
    UriReference,
}

impl Format {
    fn from_name(name: &str) -> Option<Self> {
        Some(match name {
            "float" => Self::Float,
            "double" => Self::Double,
            "int8" => Self::Int8,
            "int16" => Self::Int16,
            "int32" => Self::Int32,
            "int64" => Self::Int64,
            "uint8" => Self::Uint8,
            "uint16" => Self::Uint16,
            "uint32" => Self::Uint32,
            "uint64" => Self::Uint64,
            "uri-reference" => Self::UriReference,
            _ => return None,
        })
    }

    /// The name as JSON Schema writes it.
    #[must_use]
    pub const fn name(self) -> &'static str {
        match self {
            Self::Float => "float",
            Self::Double => "double",
            Self::Int8 => "int8",
            Self::Int16 => "int16",
            Self::Int32 => "int32",
            Self::Int64 => "int64",
            Self::Uint8 => "uint8",
            Self::Uint16 => "uint16",
            Self::Uint32 => "uint32",
            Self::Uint64 => "uint64",
            Self::UriReference => "uri-reference",
        }
    }

    /// The range of an integer format.
    #[must_use]
    pub const fn integer_range(self) -> Option<(i128, i128)> {
        Some(match self {
            Self::Int8 => (i8::MIN as i128, i8::MAX as i128),
            Self::Int16 => (i16::MIN as i128, i16::MAX as i128),
            Self::Int32 => (i32::MIN as i128, i32::MAX as i128),
            Self::Int64 => (i64::MIN as i128, i64::MAX as i128),
            Self::Uint8 => (0, u8::MAX as i128),
            Self::Uint16 => (0, u16::MAX as i128),
            Self::Uint32 => (0, u32::MAX as i128),
            Self::Uint64 => (0, u64::MAX as i128),
            _ => return None,
        })
    }
}

/// What an object allows besides its named properties.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Additional {
    /// Anything.
    Allowed,
    /// Nothing.
    Denied,
    /// Values of this schema.
    Schema(SchemaId),
}

/// Where a definition comes from: its document's topic and its name under `$defs`.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Definition {
    /// The topic of the schema document, as the reference names it (`project`, `compose`).
    pub topic: String,
    /// The name under `$defs`.
    pub name: String,
}

/// One compiled schema node.
#[derive(Clone, Debug, PartialEq, Default)]
pub struct SchemaNode {
    /// Set on the root of a definition.
    pub definition: Option<Definition>,
    /// `false`: no value is allowed.
    pub never: bool,
    /// `type`.
    pub types: Option<Types>,
    /// `const`.
    pub constant: Option<Node>,
    /// `enum`.
    pub choices: Option<Vec<Node>>,
    /// `properties`, in order.
    pub properties: Vec<(String, SchemaId)>,
    /// `required`.
    pub required: Vec<String>,
    /// `additionalProperties`; absent allows anything.
    pub additional: Option<Additional>,
    /// `items`.
    pub items: Option<Additional>,
    /// `prefixItems`.
    pub prefix_items: Vec<SchemaId>,
    /// `minItems`.
    pub min_items: Option<usize>,
    /// `maxItems`.
    pub max_items: Option<usize>,
    /// `maxProperties`.
    pub max_properties: Option<usize>,
    /// `minimum`.
    pub minimum: Option<f64>,
    /// `maximum`.
    pub maximum: Option<f64>,
    /// `minLength`, in characters.
    pub min_length: Option<usize>,
    /// `maxLength`, in characters.
    pub max_length: Option<usize>,
    /// `format`.
    pub format: Option<Format>,
    /// `oneOf` or `anyOf`: the forms a value may take; the first that fits is taken.
    pub forms: Vec<SchemaId>,
    /// The property whose constant tells the forms apart, when every form is an object that has
    /// one with a distinct constant.
    pub tag: Option<String>,
    /// For a union whose forms are not all tagged: a property that, where a form has it, holds
    /// a distinct constant in at least two forms. A value with it picks among those forms; a
    /// value without it among the rest.
    pub partial_tag: Option<String>,
    /// `$ref`, checked as well as the node's own keywords.
    pub reference: Option<SchemaId>,
    /// `pattern`; read, not evaluated.
    pub pattern: Option<String>,
    /// `not`; read, not evaluated.
    pub not: Option<SchemaId>,
    /// `default`.
    pub default: Option<Node>,
    /// `x-` keywords, for packs.
    pub extensions: Vec<(String, Node)>,
}

impl SchemaNode {
    /// The schema of a named property.
    #[must_use]
    pub fn property(&self, name: &str) -> Option<SchemaId> {
        self.properties
            .iter()
            .find(|(known, _)| known == name)
            .map(|(_, id)| *id)
    }
}

/// Why a schema could not be compiled.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct SchemaError {
    /// Where in the schema document, under the root name `schema`.
    pub path: Path,
    /// What is wrong.
    pub message: String,
}

impl fmt::Display for SchemaError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(formatter, "{}: {}", self.path, self.message)
    }
}

impl std::error::Error for SchemaError {}

/// A compiled schema.
#[derive(Clone, Debug)]
pub struct Schema {
    nodes: Vec<SchemaNode>,
    root: SchemaId,
    definitions: HashMap<String, SchemaId>,
}

/// A schema document another one refers to by its `$id`.
#[derive(Clone, Copy, Debug)]
pub struct Import<'a> {
    /// The document.
    pub tree: &'a Node,
    /// Its topic in the reference.
    pub topic: &'a str,
}

struct Document<'a> {
    tree: &'a Node,
    topic: &'a str,
    id: Option<&'a str>,
}

struct Compiler<'a> {
    documents: Vec<Document<'a>>,
    nodes: Vec<SchemaNode>,
    definitions: HashMap<(usize, String), SchemaId>,
    pending: Vec<(usize, String, SchemaId)>,
}

impl Schema {
    /// Compiles a schema document. `topic` names it in the reference.
    ///
    /// # Errors
    /// [`SchemaError`] at the first keyword outside the supported set, or a malformed one.
    pub fn compile(tree: &Node, topic: &str) -> Result<Self, SchemaError> {
        Self::compile_with(tree, topic, &[])
    }

    /// Compiles a schema document whose `$ref`s may name definitions of `imports` by their
    /// `$id`.
    ///
    /// # Errors
    /// [`SchemaError`] at the first keyword outside the supported set, a malformed one, or a
    /// reference that names nothing.
    pub fn compile_with(
        tree: &Node,
        topic: &str,
        imports: &[Import<'_>],
    ) -> Result<Self, SchemaError> {
        let documents = std::iter::once((tree, topic))
            .chain(imports.iter().map(|import| (import.tree, import.topic)))
            .map(|(tree, topic)| Document {
                tree,
                topic,
                id: tree.get("$id").and_then(Node::as_str),
            })
            .collect();
        let mut compiler = Compiler {
            documents,
            nodes: Vec::new(),
            definitions: HashMap::new(),
            pending: Vec::new(),
        };
        let path = Path::root("schema");
        if let Some(definitions) = tree.get("$defs") {
            let entries = definitions.as_map().ok_or_else(|| SchemaError {
                path: path.key("$defs"),
                message: "`$defs` is not an object".into(),
            })?;
            for entry in entries {
                compiler.definition(0, &entry.key);
            }
        }
        let root = compiler.reserve();
        compiler.compile_into(0, tree, &path, root, true)?;
        while let Some((document, name, id)) = compiler.pending.pop() {
            let path = Path::root("schema").key("$defs").key(name.clone());
            let body = compiler.documents[document]
                .tree
                .get("$defs")
                .and_then(|definitions| definitions.get(&name))
                .ok_or_else(|| SchemaError {
                    path: path.clone(),
                    message: format!("no definition {name}"),
                })?;
            compiler.compile_into(document, body, &path, id, false)?;
            compiler.nodes[id.index()].definition = Some(Definition {
                topic: compiler.documents[document].topic.to_owned(),
                name: name.clone(),
            });
        }
        let definitions = compiler
            .definitions
            .iter()
            .filter(|((document, _), _)| *document == 0)
            .map(|((_, name), id)| (name.clone(), *id))
            .collect();
        let schema = Self {
            nodes: compiler.nodes,
            root,
            definitions,
        };
        Ok(schema.find_tags())
    }

    /// The root node.
    #[must_use]
    pub const fn root(&self) -> SchemaId {
        self.root
    }

    /// A node.
    ///
    /// # Panics
    /// When `id` is of another schema and out of range.
    #[must_use]
    pub fn node(&self, id: SchemaId) -> &SchemaNode {
        &self.nodes[id.index()]
    }

    /// A definition of the root document, by name.
    #[must_use]
    pub fn definition(&self, name: &str) -> Option<SchemaId> {
        self.definitions.get(name).copied()
    }

    /// The node a chain of bare `$ref`s ends at.
    #[must_use]
    pub fn resolve(&self, mut id: SchemaId) -> SchemaId {
        for _ in 0..64 {
            let node = self.node(id);
            match node.reference {
                Some(target) if node.is_bare_reference() => id = target,
                _ => break,
            }
        }
        id
    }

    /// The forms of a union, the nullable `anyOf [T, null]` seen through to `T`; a node without
    /// forms is its own one form.
    #[must_use]
    pub fn non_null_forms(&self, id: SchemaId) -> Vec<SchemaId> {
        let id = self.resolve(id);
        let node = self.node(id);
        if node.forms.is_empty() {
            return vec![id];
        }
        node.forms
            .iter()
            .map(|form| self.resolve(*form))
            .filter(|form| self.node(*form).types != Some(Types::NULL))
            .collect()
    }

    /// The object schemas a value at `id` may be: `id` itself, or the forms of a union.
    #[must_use]
    pub fn objects(&self, id: SchemaId) -> Vec<SchemaId> {
        self.non_null_forms(id)
            .into_iter()
            .filter(|form| {
                let node = self.node(*form);
                !node.properties.is_empty()
                    || node
                        .types
                        .is_some_and(|types| types.contains(Types::OBJECT))
            })
            .collect()
    }

    /// The name of the definition `id` is the root of, through bare references.
    #[must_use]
    pub fn definition_of(&self, id: SchemaId) -> Option<&Definition> {
        let mut id = id;
        for _ in 0..64 {
            let node = self.node(id);
            if let Some(definition) = &node.definition {
                return Some(definition);
            }
            match node.reference {
                Some(target) if node.is_bare_reference() => id = target,
                _ => return None,
            }
        }
        None
    }

    /// The JSON types a value at `id` may have, through references and forms.
    #[must_use]
    pub fn types(&self, id: SchemaId) -> Types {
        self.types_at(id, 0)
    }

    fn types_at(&self, id: SchemaId, depth: usize) -> Types {
        let node = self.node(id);
        if depth > 16 || node.never {
            return Types::default();
        }
        if let Some(target) = node.reference {
            return self.types_at(target, depth + 1);
        }
        if let Some(types) = node.types {
            return types;
        }
        if let Some(constant) = &node.constant {
            return Types::of(constant);
        }
        if let Some(choices) = &node.choices {
            return choices.iter().fold(Types::default(), |types, choice| {
                types.union(Types::of(choice))
            });
        }
        if !node.forms.is_empty() {
            return node.forms.iter().fold(Types::default(), |types, form| {
                types.union(self.types_at(*form, depth + 1))
            });
        }
        if !node.properties.is_empty() {
            return Types::OBJECT;
        }
        Types(0x7F)
    }

    /// The constant values a value at `id` may take, when it may take only constants.
    #[must_use]
    pub fn constants(&self, id: SchemaId) -> Option<Vec<&Node>> {
        let id = self.resolve(id);
        let node = self.node(id);
        if let Some(constant) = &node.constant {
            return Some(vec![constant]);
        }
        if let Some(choices) = &node.choices {
            return Some(choices.iter().collect());
        }
        if node.forms.is_empty() {
            return None;
        }
        let mut all = Vec::new();
        for form in &node.forms {
            all.extend(self.constants(*form)?);
        }
        Some(all)
    }

    /// Whether `node` is one of the constants of `id`, when `id` takes only constants; the
    /// same answer as [`constants`](Self::constants) without collecting them.
    #[must_use]
    pub fn constant_match(&self, id: SchemaId, node: &Node) -> Option<bool> {
        let id = self.resolve(id);
        let rule = self.node(id);
        if let Some(constant) = &rule.constant {
            return Some(constant.same_value(node));
        }
        if let Some(choices) = &rule.choices {
            return Some(choices.iter().any(|choice| choice.same_value(node)));
        }
        if rule.forms.is_empty() {
            return None;
        }
        let mut found = false;
        for form in &rule.forms {
            found |= self.constant_match(*form, node)?;
        }
        Some(found)
    }

    /// The constant of the tag property in one form of a tagged union.
    #[must_use]
    pub fn tag_value(&self, form: SchemaId, tag: &str) -> Option<&Node> {
        let property = self.node(self.resolve(form)).property(tag)?;
        let property = self.node(self.resolve(property));
        property.constant.as_ref().or_else(|| {
            property
                .choices
                .as_ref()
                .filter(|choices| choices.len() == 1)?
                .first()
        })
    }

    fn find_tags(mut self) -> Self {
        let tags: Vec<Option<String>> = (0..self.nodes.len())
            .map(|index| self.tag_of(&self.nodes[index]))
            .collect();
        let partial: Vec<Option<String>> = (0..self.nodes.len())
            .map(|index| {
                if tags[index].is_some() {
                    None
                } else {
                    self.partial_tag_of(&self.nodes[index])
                }
            })
            .collect();
        for ((node, tag), partial) in self.nodes.iter_mut().zip(tags).zip(partial) {
            node.tag = tag;
            node.partial_tag = partial;
        }
        self
    }

    fn partial_tag_of(&self, node: &SchemaNode) -> Option<String> {
        if node.forms.len() < 2 {
            return None;
        }
        let forms: Vec<SchemaId> = node.forms.iter().map(|form| self.resolve(*form)).collect();
        let mut names: Vec<&str> = forms
            .iter()
            .flat_map(|form| {
                self.node(*form)
                    .properties
                    .iter()
                    .map(|(name, _)| name.as_str())
            })
            .collect();
        names.sort_unstable();
        names.dedup();
        names.sort_by_key(|name| {
            ["type", "op", "kind", "mode", "shape"]
                .iter()
                .position(|preferred| preferred == name)
                .unwrap_or(usize::MAX)
        });
        names
            .into_iter()
            .find(|name| {
                let mut seen: Vec<&Node> = Vec::new();
                for form in &forms {
                    if self.node(*form).property(name).is_none() {
                        continue;
                    }
                    match self.tag_value(*form, name) {
                        Some(value) if !seen.iter().any(|known| known.same_value(value)) => {
                            seen.push(value);
                        }
                        Some(_) => return false,
                        None => {}
                    }
                }
                seen.len() >= 2
            })
            .map(str::to_owned)
    }

    fn tag_of(&self, node: &SchemaNode) -> Option<String> {
        if node.forms.len() < 2 {
            return None;
        }
        let forms: Vec<SchemaId> = node.forms.iter().map(|form| self.resolve(*form)).collect();
        let first = self.node(forms[0]);
        let mut candidates: Vec<&str> = first
            .properties
            .iter()
            .map(|(name, _)| name.as_str())
            .filter(|name| {
                let mut seen: Vec<&Node> = Vec::new();
                forms.iter().all(|form| match self.tag_value(*form, name) {
                    Some(value) if !seen.iter().any(|known| known.same_value(value)) => {
                        seen.push(value);
                        true
                    }
                    _ => false,
                })
            })
            .collect();
        candidates.sort_by_key(|name| {
            ["type", "op", "kind", "mode", "shape"]
                .iter()
                .position(|preferred| preferred == name)
                .unwrap_or(usize::MAX)
        });
        candidates.first().map(|name| (*name).to_owned())
    }
}

impl SchemaNode {
    /// Whether the node is only a `$ref`, nothing else to check.
    #[must_use]
    pub fn is_bare_reference(&self) -> bool {
        self.reference.is_some()
            && !self.never
            && self.types.is_none()
            && self.constant.is_none()
            && self.choices.is_none()
            && self.properties.is_empty()
            && self.required.is_empty()
            && self.additional.is_none()
            && self.items.is_none()
            && self.prefix_items.is_empty()
            && self.min_items.is_none()
            && self.max_items.is_none()
            && self.max_properties.is_none()
            && self.minimum.is_none()
            && self.maximum.is_none()
            && self.min_length.is_none()
            && self.max_length.is_none()
            && self.format.is_none()
            && self.forms.is_empty()
    }
}

fn bound(node: &mut SchemaNode, key: &str, value: &Node, at: &Path) -> Result<(), SchemaError> {
    match key {
        "minItems" => node.min_items = Some(count(value, at)?),
        "maxItems" => node.max_items = Some(count(value, at)?),
        "maxProperties" => node.max_properties = Some(count(value, at)?),
        "minLength" => node.min_length = Some(count(value, at)?),
        "maxLength" => node.max_length = Some(count(value, at)?),
        "minimum" => node.minimum = Some(number(value, at)?),
        _ => node.maximum = Some(number(value, at)?),
    }
    Ok(())
}

fn types(value: &Node, at: &Path) -> Result<Types, SchemaError> {
    let names: Vec<&Node> = match &value.value {
        Value::Text(_) => vec![value],
        Value::List(items) => items.iter().collect(),
        _ => return Err(error(at, "expected a type name or a list of them")),
    };
    let mut types = Types::default();
    for name in names {
        let known = name
            .as_str()
            .and_then(Types::from_name)
            .ok_or_else(|| error(at, "unknown type name"))?;
        types = types.union(known);
    }
    Ok(types)
}

fn error(path: &Path, message: impl Into<String>) -> SchemaError {
    SchemaError {
        path: path.clone(),
        message: message.into(),
    }
}

fn count(node: &Node, path: &Path) -> Result<usize, SchemaError> {
    node.as_number()
        .and_then(crate::tree::Number::as_i128)
        .and_then(|value| usize::try_from(value).ok())
        .ok_or_else(|| error(path, "expected a non-negative integer"))
}

fn number(node: &Node, path: &Path) -> Result<f64, SchemaError> {
    node.as_number()
        .map(crate::tree::Number::as_f64)
        .filter(|value| value.is_finite())
        .ok_or_else(|| error(path, "expected a number"))
}

impl Compiler<'_> {
    fn reserve(&mut self) -> SchemaId {
        let id = SchemaId(u32::try_from(self.nodes.len()).unwrap_or(u32::MAX));
        self.nodes.push(SchemaNode::default());
        id
    }

    fn definition(&mut self, document: usize, name: &str) -> SchemaId {
        if let Some(id) = self.definitions.get(&(document, name.to_owned())) {
            return *id;
        }
        let id = self.reserve();
        self.definitions.insert((document, name.to_owned()), id);
        self.pending.push((document, name.to_owned(), id));
        id
    }

    fn reference(
        &mut self,
        document: usize,
        target: &str,
        path: &Path,
    ) -> Result<SchemaId, SchemaError> {
        let (base, fragment) = target.split_once('#').unwrap_or((target, ""));
        let document = if base.is_empty() {
            document
        } else {
            self.documents
                .iter()
                .position(|known| known.id == Some(base))
                .ok_or_else(|| error(path, format!("`$ref` names {base}, which is not given")))?
        };
        let name = fragment
            .strip_prefix("/$defs/")
            .filter(|name| !name.contains('/'))
            .ok_or_else(|| {
                error(
                    path,
                    format!("`$ref` {target} is not of the form #/$defs/Name"),
                )
            })?;
        let exists = self.documents[document]
            .tree
            .get("$defs")
            .and_then(|definitions| definitions.get(name))
            .is_some();
        if !exists {
            return Err(error(
                path,
                format!("`$ref` names {target}, which is not defined"),
            ));
        }
        Ok(self.definition(document, name))
    }

    fn compile(
        &mut self,
        document: usize,
        tree: &Node,
        path: &Path,
    ) -> Result<SchemaId, SchemaError> {
        let id = self.reserve();
        self.compile_into(document, tree, path, id, false)?;
        Ok(id)
    }

    fn compile_list(
        &mut self,
        document: usize,
        tree: &Node,
        path: &Path,
    ) -> Result<Vec<SchemaId>, SchemaError> {
        let items = tree
            .as_list()
            .ok_or_else(|| error(path, "expected an array of schemas"))?;
        items
            .iter()
            .enumerate()
            .map(|(index, item)| self.compile(document, item, &path.index(index)))
            .collect()
    }

    fn compile_into(
        &mut self,
        document: usize,
        tree: &Node,
        path: &Path,
        id: SchemaId,
        root: bool,
    ) -> Result<(), SchemaError> {
        let mut node = SchemaNode::default();
        match &tree.value {
            Value::Bool(true) => {}
            Value::Bool(false) => node.never = true,
            Value::Map(entries) => {
                for entry in entries {
                    let at = path.key(entry.key.clone());
                    self.keyword(document, &mut node, &entry.key, &entry.value, &at, root)?;
                }
            }
            _ => return Err(error(path, "a schema is an object or a boolean")),
        }
        let definition = self.nodes[id.index()].definition.take();
        node.definition = definition;
        self.nodes[id.index()] = node;
        Ok(())
    }

    fn keyword(
        &mut self,
        document: usize,
        node: &mut SchemaNode,
        key: &str,
        value: &Node,
        at: &Path,
        root: bool,
    ) -> Result<(), SchemaError> {
        match key {
            "$ref" => {
                let target = value
                    .as_str()
                    .ok_or_else(|| error(at, "expected a string"))?;
                node.reference = Some(self.reference(document, target, at)?);
            }
            "$defs" if root => {}
            "type" => node.types = Some(types(value, at)?),
            "properties" => {
                let entries = value
                    .as_map()
                    .ok_or_else(|| error(at, "expected an object"))?;
                for entry in entries {
                    let schema =
                        self.compile(document, &entry.value, &at.key(entry.key.clone()))?;
                    node.properties.push((entry.key.clone(), schema));
                }
            }
            "required" => {
                let names = value
                    .as_list()
                    .ok_or_else(|| error(at, "expected an array"))?;
                for name in names {
                    let name = name.as_str().ok_or_else(|| error(at, "expected strings"))?;
                    node.required.push(name.to_owned());
                }
            }
            "additionalProperties" | "items" => {
                let rule = match value.value {
                    Value::Bool(true) => Additional::Allowed,
                    Value::Bool(false) => Additional::Denied,
                    _ => Additional::Schema(self.compile(document, value, at)?),
                };
                if key == "items" {
                    node.items = Some(rule);
                } else {
                    node.additional = Some(rule);
                }
            }
            "prefixItems" => node.prefix_items = self.compile_list(document, value, at)?,
            "oneOf" | "anyOf" => {
                if !node.forms.is_empty() {
                    return Err(error(at, "both `oneOf` and `anyOf`"));
                }
                node.forms = self.compile_list(document, value, at)?;
            }
            "enum" => {
                let choices = value
                    .as_list()
                    .ok_or_else(|| error(at, "expected an array"))?;
                node.choices = Some(
                    choices
                        .iter()
                        .map(|choice| choice.clone().without_spans())
                        .collect(),
                );
            }
            "const" => node.constant = Some(value.clone().without_spans()),
            "default" => node.default = Some(value.clone().without_spans()),
            "minItems" | "maxItems" | "maxProperties" | "minLength" | "maxLength" | "minimum"
            | "maximum" => bound(node, key, value, at)?,
            "format" => {
                let name = value
                    .as_str()
                    .ok_or_else(|| error(at, "expected a string"))?;
                node.format = Some(
                    Format::from_name(name)
                        .ok_or_else(|| error(at, format!("unsupported format {name}")))?,
                );
            }
            "pattern" => {
                node.pattern = Some(
                    value
                        .as_str()
                        .ok_or_else(|| error(at, "expected a string"))?
                        .to_owned(),
                );
            }
            "not" => node.not = Some(self.compile(document, value, at)?),
            "description" | "title" | "$id" | "$schema" => {}
            _ if key.starts_with("x-") => node
                .extensions
                .push((key.to_owned(), value.clone().without_spans())),
            _ => return Err(error(at, format!("unsupported schema keyword {key}"))),
        }
        Ok(())
    }
}