genson-core 1.0.3

Core library for JSON schema inference using genson-rs
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
use core::panic;
use std::borrow::{Borrow, Cow};
use std::hash::Hasher;

use crate::dag::{kw, Dag, Id};
use crate::genson_rs::interned::{RowStates, StateId, Strat};
use crate::genson_rs::strategy::base::SchemaStrategy;
use crate::genson_rs::strategy::scalar::TypelessStrategy;
use crate::genson_rs::strategy::BasicSchemaStrategy;
use crate::value::object;
use ordermap::OrderMap;
use serde_json::{json, Value};

/// Fewest schemas merged into one node at once for which going parallel below it pays off.
pub(crate) const PAR_MERGE_MIN: usize = 8;

/// The child absorbs a node's strategies hold back while the node takes a batch of
/// interned states (`absorb_interned_all`), by strategy, in the order of the node's.
#[derive(Default)]
pub(crate) struct Deferred<'a>(Vec<DeferredStrategy<'a>>);

/// The child absorbs one strategy holds back: an object's states for each of its
/// properties (by the property's index), or a list's states for its items.
#[derive(Default)]
pub(crate) enum DeferredStrategy<'a> {
    #[default]
    None,
    Object(Vec<Vec<(&'a RowStates, StateId)>>),
    List(Vec<(&'a RowStates, StateId)>),
}

/// Feed `hasher` a JSON value, as its compact serialisation.
pub(crate) fn hash_value<H: Hasher>(value: &Value, hasher: &mut H) {
    struct Writer<'a, H>(&'a mut H);
    impl<H: Hasher> std::io::Write for Writer<'_, H> {
        fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
            self.0.write(buf);
            Ok(buf.len())
        }
        fn flush(&mut self) -> std::io::Result<()> {
            Ok(())
        }
    }
    serde_json::to_writer(Writer(hasher), value).expect("hashing a Value cannot fail");
}

/// Basic schema generator class. SchemaNode objects can be loaded
/// up with existing schemas and objects before being serialized.
#[derive(Debug, PartialEq)]
pub struct SchemaNode {
    active_strategies: Vec<BasicSchemaStrategy>,
    /// The interned row states absorbed into this node (`absorb_interned`)
    absorbed: Absorbed,
}

/// The interned states a node has absorbed. Absorbing one of them again leaves the node as
/// it is, so this is a record of work not to repeat, and takes no part in comparing nodes.
#[derive(Default)]
struct Absorbed(rustc_hash::FxHashSet<u64>);

impl PartialEq for Absorbed {
    fn eq(&self, _: &Self) -> bool {
        true
    }
}

impl std::fmt::Debug for Absorbed {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "Absorbed({})", self.0.len())
    }
}

/// DataType wraps around different types of schema data that can be added
/// to a SchemaNode. It wraps references to Value objects and SchemaNode
/// objects so when it gets dropped the underlying data is not dropped.
#[derive(Clone)]
pub enum DataType<'a> {
    /// SchemaNode represents a JSON schema
    Schema(&'a Value),
    /// Object represents a valid JSON object (array, object, string, number, boolean, null)
    Object(super::JsonValue<'a>),
    /// SchemaNode reference
    SchemaNode(&'a SchemaNode),
}

impl Default for SchemaNode {
    fn default() -> Self {
        Self::new()
    }
}

impl SchemaNode {
    pub fn new() -> Self {
        SchemaNode {
            active_strategies: vec![],
            absorbed: Absorbed::default(),
        }
    }

    pub fn is_empty(&self) -> bool {
        self.active_strategies.is_empty()
    }

    /// Whether the node is an object schema and nothing else.
    pub fn is_object(&self) -> bool {
        matches!(
            self.active_strategies.as_slice(),
            [BasicSchemaStrategy::Object(_)]
        )
    }

    /// Call `f(name, node)` on every property node below this one (through objects' values
    /// and lists' items too), walking into a property only when `f` returns true.
    pub(crate) fn visit_properties_mut<F>(&mut self, f: &mut F)
    where
        F: FnMut(&str, &mut SchemaNode) -> bool,
    {
        for strategy in &mut self.active_strategies {
            strategy.visit_properties_mut(f);
        }
    }

    /// Record `key` as an extra keyword of the node's object strategy, unless it has one.
    pub(crate) fn add_object_keyword(&mut self, key: &str, value: Value) {
        for strategy in &mut self.active_strategies {
            if let BasicSchemaStrategy::Object(object) = strategy {
                object.add_extra_keywords(&json!({ key: value }));
                return;
            }
        }
    }

    pub fn add_schema(&mut self, data: DataType) -> &mut Self {
        let schema: Cow<Value> = match data {
            DataType::SchemaNode(node) => Cow::Owned(node.to_schema()),
            DataType::Schema(schema) => Cow::Borrowed(schema),
            _ => panic!("Invalid schema type"),
        };

        // Common case: no `anyOf` / type array to split, so skip `get_subschemas` (which
        // allocates a Vec per node visited).
        if !SchemaNode::needs_splitting(&schema) {
            let active_strategy = self.get_or_create_strategy_for_schema(&schema);
            SchemaNode::add_schema_or_object_to_strategy(
                active_strategy,
                DataType::Schema(&schema),
            );
            return self;
        }

        for subschema in SchemaNode::get_subschemas(&schema) {
            let active_strategy = self.get_or_create_strategy_for_schema(&subschema);
            SchemaNode::add_schema_or_object_to_strategy(
                active_strategy,
                DataType::Schema(&subschema),
            );
        }
        self
    }

    /// Merge `other` into this node, with the same result as
    /// `self.add_schema(DataType::Schema(&other.to_schema()))`: its subtrees are moved in, or
    /// merged node by node, rather than written out as a schema and read back. The one
    /// difference: an object that saw no key in all of its values limits `required` to
    /// nothing, where its schema, which has no `required`, would not limit it at all.
    pub fn absorb(&mut self, other: SchemaNode) {
        let mut strategies = other.active_strategies;
        match strategies.len() {
            // An empty node's schema is `{}`, which only ever adds a typeless strategy
            0 => self.absorb_strategy(BasicSchemaStrategy::Typeless(TypelessStrategy::new())),
            // One strategy is already in schema order
            1 => self.absorb_strategy(strategies.pop().unwrap()),
            _ => Self::schema_order(strategies)
                .into_iter()
                .for_each(|strategy| self.absorb_strategy(strategy)),
        }
    }

    /// A node holding `node` as `SchemaNode::new()` plus `add_schema(node.to_schema())` builds it:
    /// the same schema, with each strategy's extra keywords recording the keys it has.
    pub(crate) fn round_tripped(node: SchemaNode) -> SchemaNode {
        let mut fresh = SchemaNode::new();
        fresh.absorb(node);
        fresh
    }

    /// The strategies in the order `to_schema` lists them: those whose schema has more than a
    /// `type` first, as they stand, then the bare types in the type list's (sorted) order.
    fn schema_order<S: Borrow<BasicSchemaStrategy>>(strategies: Vec<S>) -> Vec<S> {
        let (mut bare, mut ordered): (Vec<_>, Vec<_>) = strategies
            .into_iter()
            .partition(|strategy| strategy.borrow().bare_type().is_some());
        bare.sort_by_key(|strategy| strategy.borrow().bare_type());
        ordered.extend(bare);
        ordered
    }

    /// `absorb` each of `others` in turn. When there are enough of them, and they are all
    /// objects (or all lists) merging into one of the same, the merge goes parallel below
    /// this node: across the properties, or through the items.
    pub fn absorb_all(&mut self, mut others: Vec<SchemaNode>) {
        let sole_kind = |node: &SchemaNode| match node.active_strategies.as_slice() {
            [strategy @ (BasicSchemaStrategy::Object(_) | BasicSchemaStrategy::List(_))] => {
                Some(std::mem::discriminant(strategy))
            }
            _ => None,
        };
        let kind = others.first().and_then(sole_kind);
        let parallel = others.len() >= PAR_MERGE_MIN
            && kind.is_some()
            && others.iter().all(|other| sole_kind(other) == kind)
            && (self.is_empty() || sole_kind(self) == kind);
        if !parallel {
            others.into_iter().for_each(|other| self.absorb(other));
            return;
        }
        if self.is_empty() {
            let created = others[0].active_strategies[0].new_of_same_kind();
            self.active_strategies.reserve_exact(1);
            self.active_strategies.push(created);
        }
        let strategies = others
            .iter_mut()
            .filter_map(|other| other.active_strategies.pop());
        match &mut self.active_strategies[0] {
            BasicSchemaStrategy::Object(own) => own.absorb_all(
                strategies
                    .filter_map(|strategy| match strategy {
                        BasicSchemaStrategy::Object(object) => Some(object),
                        _ => None,
                    })
                    .collect(),
            ),
            BasicSchemaStrategy::List(own) => own.absorb_all(
                strategies
                    .filter_map(|strategy| match strategy {
                        BasicSchemaStrategy::List(list) => Some(list),
                        _ => None,
                    })
                    .collect(),
            ),
            _ => unreachable!("only objects and lists merge in parallel"),
        }
    }

    /// Feed `hasher` what identifies `to_schema`'s output, without building it, so that
    /// nodes with equal schemas hash equal.
    pub fn hash_schema<H: Hasher>(&self, hasher: &mut H) {
        // One typed strategy is already in schema order: feed what the loop below would,
        // without collecting the strategies
        if let [strategy] = self.active_strategies.as_slice() {
            if !matches!(strategy, BasicSchemaStrategy::Typeless(_)) {
                hasher.write_usize(1);
                strategy.hash_schema(hasher);
                return;
            }
        }
        // A typeless strategy without keywords writes `{}`, as no strategy at all does
        let written = self.active_strategies.iter().filter(|strategy| {
            !matches!(strategy, BasicSchemaStrategy::Typeless(t) if t.to_schema() == json!({}))
        });
        let ordered = Self::schema_order(written.collect());
        hasher.write_usize(ordered.len());
        for strategy in ordered {
            strategy.hash_schema(hasher);
        }
    }

    /// `absorb` of the node an interned row state stands for: the same result, read from
    /// the state. A state this node has absorbed before is skipped, as absorbing it again
    /// would change nothing.
    pub(crate) fn absorb_interned(&mut self, rows: &RowStates, state: StateId) {
        if !self.absorbed.0.insert(rows.identity(state)) {
            return;
        }
        let strats = rows.strats(state);
        match strats.len() {
            0 => self.absorb_strategy(BasicSchemaStrategy::Typeless(TypelessStrategy::new())),
            1 => self.absorb_interned_strategy(rows, strats[0]),
            _ => {
                for strat in rows.schema_order(strats) {
                    self.absorb_interned_strategy(rows, strat);
                }
            }
        }
    }

    /// `absorb_interned` of each of `states` in turn: the same node. The node takes all of
    /// them first, its strategies holding back their children's states, and then each child
    /// takes its own in their order (an object's children on their own threads); a node
    /// reads nothing of its children's, nor they of each other's.
    pub(crate) fn absorb_interned_all(&mut self, states: &[(&RowStates, StateId)]) {
        if let [(rows, state)] = states {
            return self.absorb_interned(rows, *state);
        }
        let mut deferred = Deferred::default();
        for &(rows, state) in states {
            self.absorb_interned_deferred(rows, state, &mut deferred);
        }
        self.absorb_deferred(deferred);
    }

    /// `absorb_interned`, with the strategies' child absorbs added to `deferred` (to be
    /// made by `absorb_deferred`).
    pub(crate) fn absorb_interned_deferred<'a>(
        &mut self,
        rows: &'a RowStates,
        state: StateId,
        deferred: &mut Deferred<'a>,
    ) {
        if !self.absorbed.0.insert(rows.identity(state)) {
            return;
        }
        let strats = rows.strats(state);
        match strats.len() {
            0 => self.absorb_strategy(BasicSchemaStrategy::Typeless(TypelessStrategy::new())),
            1 => self.absorb_interned_strategy_deferred(rows, strats[0], deferred),
            _ => {
                for strat in rows.schema_order(strats) {
                    self.absorb_interned_strategy_deferred(rows, strat, deferred);
                }
            }
        }
    }

    /// `absorb_interned_strategy`, with the child absorbs added to `deferred`.
    fn absorb_interned_strategy_deferred<'a>(
        &mut self,
        rows: &'a RowStates,
        strat: Strat,
        deferred: &mut Deferred<'a>,
    ) {
        let at = match self
            .active_strategies
            .iter()
            .position(|existing| existing.same_kind_as_interned(strat))
        {
            Some(at) => at,
            None => {
                let mut created = BasicSchemaStrategy::new_of_interned_kind(strat);
                if let Some(BasicSchemaStrategy::Typeless(typeless)) = self.active_strategies.last()
                {
                    created.add_schema(&typeless.to_schema());
                    self.active_strategies.pop();
                }
                if self.active_strategies.is_empty() {
                    self.active_strategies.reserve_exact(1);
                }
                self.active_strategies.push(created);
                self.active_strategies.len() - 1
            }
        };
        // A slot for each strategy: a typeless one holds back nothing, and a strategy that
        // replaced one takes its slot
        deferred
            .0
            .resize_with(self.active_strategies.len(), Default::default);
        self.active_strategies[at].absorb_interned_deferred(rows, strat, &mut deferred.0[at]);
    }

    /// The child absorbs `absorb_interned_deferred` held back.
    pub(crate) fn absorb_deferred(&mut self, deferred: Deferred) {
        for (strategy, deferred) in self.active_strategies.iter_mut().zip(deferred.0) {
            strategy.absorb_deferred(deferred);
        }
    }

    /// `absorb_strategy` of the strategy an interned one stands for.
    fn absorb_interned_strategy(&mut self, rows: &RowStates, strat: Strat) {
        if let Some(existing) = self
            .active_strategies
            .iter_mut()
            .find(|existing| existing.same_kind_as_interned(strat))
        {
            existing.absorb_interned(rows, strat);
            return;
        }
        let mut created = BasicSchemaStrategy::new_of_interned_kind(strat);
        if let Some(BasicSchemaStrategy::Typeless(typeless)) = self.active_strategies.last() {
            created.add_schema(&typeless.to_schema());
            self.active_strategies.pop();
        }
        created.absorb_interned(rows, strat);
        if self.active_strategies.is_empty() {
            self.active_strategies.reserve_exact(1);
        }
        self.active_strategies.push(created);
    }

    /// As `add_schema` with the one subschema `strategy` writes: merged into the strategy of
    /// the same kind, or added the way `create_strategy_for_kind` adds one.
    fn absorb_strategy(&mut self, strategy: BasicSchemaStrategy) {
        if let Some(existing) = self
            .active_strategies
            .iter_mut()
            .find(|existing| existing.same_kind(&strategy))
        {
            existing.absorb(strategy);
            return;
        }
        if let BasicSchemaStrategy::Typeless(typeless) = strategy {
            // A typeless schema matches no new strategy, so it goes to the first one
            if self.active_strategies.is_empty() {
                self.active_strategies
                    .push(BasicSchemaStrategy::Typeless(TypelessStrategy::new()));
            }
            self.active_strategies[0].add_schema(&typeless.to_schema());
            return;
        }
        let mut created = strategy.new_of_same_kind();
        if let Some(BasicSchemaStrategy::Typeless(typeless)) = self.active_strategies.last() {
            created.add_schema(&typeless.to_schema());
            self.active_strategies.pop();
        }
        created.absorb(strategy);
        if self.active_strategies.is_empty() {
            self.active_strategies.reserve_exact(1);
        }
        self.active_strategies.push(created);
    }

    fn needs_splitting(schema: &Value) -> bool {
        match schema {
            Value::Object(obj) => {
                matches!(obj.get("anyOf"), Some(Value::Array(_)))
                    || matches!(obj.get("type"), Some(Value::Array(_)))
            }
            _ => false,
        }
    }

    /// Merge `schemas` in order like repeated `add_schema`, going parallel below this node
    /// (across properties, and through arrays into their items) when there are enough of them
    /// to be worth it.
    pub fn add_schemas_par(&mut self, schemas: &[&Value]) {
        if schemas.len() >= PAR_MERGE_MIN
            && (self.add_object_schemas_par(schemas) || self.add_list_schemas_par(schemas))
        {
            return;
        }
        for schema in schemas {
            self.add_schema(DataType::Schema(schema));
        }
    }

    /// Like `add_object_schemas_par` for plain array schemas whose `items` is an object schema.
    fn add_list_schemas_par(&mut self, schemas: &[&Value]) -> bool {
        let plain_lists = schemas.iter().all(|schema| {
            schema["type"] == "array"
                && schema["items"].is_object()
                && !SchemaNode::needs_splitting(schema)
        });
        if !plain_lists {
            return false;
        }
        match self.active_strategies.as_slice() {
            [] => {
                self.get_or_create_strategy_for_schema(schemas[0]);
            }
            [BasicSchemaStrategy::List(_)] => {}
            _ => return false,
        }
        match self.active_strategies.first_mut() {
            Some(BasicSchemaStrategy::List(strategy)) => {
                let items: Vec<&Value> = schemas.iter().map(|schema| &schema["items"]).collect();
                strategy.add_item_schemas_par(&items);
                true
            }
            _ => false,
        }
    }

    /// Merge `schemas` in order like repeated `add_schema`, but in parallel across the
    /// properties when they are all plain object schemas merging into an object node. Returns
    /// false, having merged nothing, when they are not.
    pub fn add_object_schemas_par(&mut self, schemas: &[&Value]) -> bool {
        if schemas.is_empty() {
            return true;
        }
        let plain_objects = schemas
            .iter()
            .all(|schema| schema["type"] == "object" && !SchemaNode::needs_splitting(schema));
        if !plain_objects {
            return false;
        }
        match self.active_strategies.as_slice() {
            [] => {
                self.get_or_create_strategy_for_schema(schemas[0]);
            }
            [BasicSchemaStrategy::Object(_)] => {}
            _ => return false,
        }
        match self.active_strategies.first_mut() {
            Some(BasicSchemaStrategy::Object(strategy)) => {
                strategy.add_schemas_par(schemas);
                true
            }
            _ => false,
        }
    }

    /// Add multiple schemas at once with optimized batch processing
    pub fn add_schemas(&mut self, schemas: &[&Value]) -> &mut Self {
        // Store owned subschemas to avoid lifetime issues
        let mut all_subschemas: Vec<Cow<Value>> = Vec::new();
        // Map strategy index to indices into all_subschemas
        let mut schema_groups: OrderMap<usize, Vec<usize>> = OrderMap::new();

        for schema in schemas {
            // Get all subschemas (handles anyOf, type arrays, etc.)
            for subschema in SchemaNode::get_subschemas(schema) {
                // Find or create strategy for this subschema
                let strategy_idx =
                    if let Some(idx) = self.get_strategy_for_kind(DataType::Schema(&subschema)) {
                        idx
                    } else {
                        // Create new strategy
                        if let Some(_strategy) =
                            self.create_strategy_for_kind(DataType::Schema(&subschema))
                        {
                            self.active_strategies.len() - 1
                        } else {
                            continue; // Skip if can't create strategy
                        }
                    };

                let subschema_idx = all_subschemas.len();
                all_subschemas.push(subschema);

                schema_groups
                    .entry(strategy_idx)
                    .or_default()
                    .push(subschema_idx);
            }
        }

        // Batch process schemas for each strategy
        for (strategy_idx, subschema_indices) in schema_groups {
            if let Some(strategy) = self.active_strategies.get_mut(strategy_idx) {
                // Gather references to the subschemas for this strategy
                let schema_refs: Vec<&Value> = subschema_indices
                    .iter()
                    .map(|&idx| all_subschemas[idx].as_ref())
                    .collect();
                strategy.add_schemas(&schema_refs);
            }
        }

        self
    }

    fn get_subschemas(schema: &Value) -> Vec<Cow<'_, Value>> {
        if let Value::Object(obj) = schema {
            if let Some(Value::Array(anyof)) = obj.get("anyOf") {
                return anyof.iter().flat_map(SchemaNode::get_subschemas).collect();
            } else if let Some(Value::Array(types)) = obj.get("type") {
                return types
                    .iter()
                    .map(|t| {
                        let mut new_schema = obj.clone();
                        new_schema["type"] = t.clone();
                        Cow::Owned(Value::Object(new_schema))
                    })
                    .collect();
            } else {
                return vec![Cow::Borrowed(schema)];
            }
        }
        vec![Cow::Borrowed(schema)]
    }

    /// Modify the schema to accomodate the object.
    pub fn add_object(&mut self, data: DataType) -> &mut Self {
        let object = match data {
            DataType::Object(obj) => obj,
            _ => panic!("Invalid object type"),
        };

        let active_strategy = self.get_or_create_strategy_for_object(object);
        SchemaNode::add_schema_or_object_to_strategy(active_strategy, DataType::Object(object));
        self
    }

    /// Convert the current schema node to a JSON schema
    /// `to_schema` as a DAG.
    pub(crate) fn to_dag(&self, dag: &mut Dag) -> Id {
        // A node of one strategy (most are) is that strategy's schema
        if let [strategy] = self.active_strategies.as_slice() {
            let schema = strategy.to_dag(dag);
            if dag.as_object(schema).is_none() {
                panic!("Invalid schema type for strategy {:?}", strategy);
            }
            return schema;
        }
        // Scalar schemas (only a type) apart, so they collapse into one type or a type list
        let start = dag.items.len();
        let mut scalar_schemas: Vec<Id> = vec![];
        for strategy in &self.active_strategies {
            let schema = strategy.to_dag(dag);
            let Some(keywords) = dag.as_object(schema) else {
                panic!("Invalid schema type for strategy {:?}", strategy);
            };
            if keywords.len() == 1 && keywords.first().is_some_and(|(k, _)| k == kw::TYPE) {
                scalar_schemas.push(schema);
            } else {
                dag.items.push(schema);
            }
        }
        if scalar_schemas.len() == 1 {
            dag.items.push(scalar_schemas[0]);
        } else if !scalar_schemas.is_empty() {
            let mut types: Vec<&str> = scalar_schemas
                .iter()
                .map(|&schema| {
                    let js_type = dag.get(schema, kw::TYPE).and_then(|t| dag.as_sym(t));
                    dag.name(js_type.unwrap())
                })
                .collect();
            types.sort();
            types.dedup();
            if types.len() == 1 {
                dag.items.push(scalar_schemas[0]);
            } else {
                let types: Vec<String> = types.into_iter().map(str::to_string).collect();
                let types: Vec<Id> = types.iter().map(|t| dag.str(t)).collect();
                let types = dag.array(&types);
                let schema = dag.object(&[(kw::TYPE, types)]);
                dag.items.push(schema);
            }
        }
        match dag.items.len() - start {
            1 => dag.items.pop().unwrap(),
            0 => dag.object(&[]),
            _ => {
                let any_of = dag.array_from(start);
                dag.object(&[(kw::ANY_OF, any_of)])
            }
        }
    }

    pub fn to_schema(&self) -> Value {
        // Scalar strategies produce `{"type": t}`; keep those apart so they can be
        // collapsed into one entry (a single type, or a sorted type list) at the end.
        let mut scalar_schemas: Vec<Value> = vec![];
        let mut generated_schemas: Vec<Value> = vec![];

        self.active_strategies.iter().for_each(|strategy| {
            let generated_schema: Value = strategy.to_schema();
            if let Value::Object(ref schema) = generated_schema {
                // if schema is scalar type
                if schema.keys().len() == 1 && schema.contains_key("type") {
                    scalar_schemas.push(generated_schema);
                } else {
                    generated_schemas.push(generated_schema);
                }
            } else {
                panic!("Invalid schema type for strategy {:?}", strategy);
            }
        });

        if scalar_schemas.len() == 1 {
            generated_schemas.push(scalar_schemas.swap_remove(0));
        } else if !scalar_schemas.is_empty() {
            let mut scalar_type_list: Vec<&str> = scalar_schemas
                .iter()
                .map(|schema| schema["type"].as_str().unwrap())
                .collect();
            scalar_type_list.sort();
            scalar_type_list.dedup();
            if scalar_type_list.len() == 1 {
                generated_schemas.push(scalar_schemas.swap_remove(0));
            } else {
                generated_schemas.push(json!({"type": scalar_type_list}));
            }
        }

        if generated_schemas.len() == 1 {
            generated_schemas.swap_remove(0)
        } else if !generated_schemas.is_empty() {
            object([("anyOf", Value::Array(generated_schemas))])
        } else {
            json!({})
        }
    }

    /// Get the current active strategy for the object, if not found create a new one.
    fn get_or_create_strategy_for_object(
        &mut self,
        object: super::JsonValue,
    ) -> &mut BasicSchemaStrategy {
        if let Some(idx) = self.get_strategy_for_kind(DataType::Object(object)) {
            return &mut self.active_strategies[idx];
        }
        if let Some(strategy) = self.create_strategy_for_kind(DataType::Object(object)) {
            return strategy;
        }
        panic!("Could not find matching schema type for object: {object:?}")
    }

    /// Get the current active strategy for the schema, if not found create a new one.
    fn get_or_create_strategy_for_schema(&mut self, schema: &Value) -> &mut BasicSchemaStrategy {
        if let Some(idx) = self.get_strategy_for_kind(DataType::Schema(schema)) {
            return &mut self.active_strategies[idx];
        }
        if let Some(strategy) = self.create_strategy_for_kind(DataType::Schema(schema)) {
            return strategy;
        }
        panic!("Could not find matching schema type for schema: {schema}")
    }

    /// Get the strategy that matches the schema or object and return its index.
    fn get_strategy_for_kind(&self, schema_or_object: DataType) -> Option<usize> {
        self.active_strategies.iter().position(|strategy| {
            SchemaNode::strategy_does_match_schema_or_object(strategy, &schema_or_object)
        })
    }

    fn create_strategy_for_kind(
        &mut self,
        schema_or_object: DataType,
    ) -> Option<&mut BasicSchemaStrategy> {
        if let Some(mut strategy) =
            SchemaNode::create_strategy_for_schema_or_object(&schema_or_object)
        {
            if let Some(BasicSchemaStrategy::Typeless(typeless)) = self.active_strategies.last() {
                // if the last strategy is a typeless strategy, incorporate it into the newly created strategy
                SchemaNode::add_schema_or_object_to_strategy(
                    &mut strategy,
                    DataType::Schema(&typeless.to_schema()),
                );
                self.active_strategies.pop();
            }
            // Most nodes only ever hold one strategy, and a strategy is a few hundred bytes,
            // so don't let the first push reserve room for four
            if self.active_strategies.is_empty() {
                self.active_strategies.reserve_exact(1);
            }
            self.active_strategies.push(strategy);
            return Some(self.active_strategies.last_mut().unwrap());
        }
        // if no matching strategy found, create a typeless strategy and append to the active strategies
        // list if it's currently empty
        // ??: don't really understand the significance of typeless strategy yet
        else if let DataType::Schema(schema) = schema_or_object {
            if TypelessStrategy::match_schema(schema) {
                if self.active_strategies.is_empty() {
                    self.active_strategies
                        .push(BasicSchemaStrategy::Typeless(TypelessStrategy::new()));
                }
                let first_strategy = self.active_strategies.first_mut().unwrap();
                return Some(first_strategy);
            }
        }
        None
    }

    fn strategy_does_match_schema_or_object(
        strategy: &BasicSchemaStrategy,
        schema_or_object: &DataType,
    ) -> bool {
        match schema_or_object {
            DataType::Object(obj) => strategy.match_object(*obj),
            DataType::Schema(schema) => strategy.match_schema(schema),
            _ => false,
        }
    }

    /// Create a strategy for a schema or object based on which strategy it matches.
    fn create_strategy_for_schema_or_object(
        schema_or_object: &DataType,
    ) -> Option<BasicSchemaStrategy> {
        match schema_or_object {
            DataType::Object(obj) => BasicSchemaStrategy::new_for_object(*obj),
            DataType::Schema(schema) => BasicSchemaStrategy::new_for_schema(schema),
            _ => None,
        }
    }

    fn add_schema_or_object_to_strategy(
        strategy: &mut BasicSchemaStrategy,
        schema_or_object: DataType,
    ) {
        match schema_or_object {
            DataType::Object(obj) => strategy.add_object(obj),
            DataType::Schema(schema) => strategy.add_schema(schema),
            _ => (),
        }
    }
}

#[cfg(test)]
mod tests {
    include!("../tests/node.rs");
}