jsoncompat 0.4.1

JSON Schema and OpenAPI Compatibility Checker
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
//! Conditional (`if`/`then`/`else`) subset helpers.
//!
//! This module keeps guard/branch reasoning together; callers still control
//! where these rules sit in the overall proof pipeline.

use super::*;

pub(super) fn optional_sup_conditional_branch_contains(
    sub: &SchemaNode,
    sup_branch: Option<&SchemaNode>,
    context: &mut SubschemaCheckContext,
    mode: ExplanationMode,
) -> bool {
    match sup_branch {
        None => true,
        Some(branch) => analyze_subschema_with_context(sub, branch, context, mode).is_subschema,
    }
}

pub(super) fn optional_conditional_branch_subsumed(
    sub_branch: Option<&SchemaNode>,
    sup_branch: Option<&SchemaNode>,
    context: &mut SubschemaCheckContext,
    mode: ExplanationMode,
) -> bool {
    match (sub_branch, sup_branch) {
        (_, None) => true,
        (Some(sub), Some(sup)) => {
            analyze_subschema_with_context(sub, sup, context, mode).is_subschema
        }
        (None, Some(sup)) => schema_is_trivially_universal(sup),
    }
}

pub(super) enum LiveConditionalBranch<'a> {
    /// The selected branch is absent, which is the JSON Schema `true` schema.
    Universal,
    Schema(&'a SchemaNode),
}

/// Return the only live branch for a conditional with a syntactically constant
/// guard.  Keep this deliberately narrow: recognizing literal/unconstrained
/// true and literal false is enough for common normalized schemas, while
/// avoiding general emptiness/complement reasoning in a normalization helper.
pub(super) fn constant_guard_conditional_branch<'a>(
    if_schema: &SchemaNode,
    then_branch: Option<&'a SchemaNode>,
    else_branch: Option<&'a SchemaNode>,
) -> Option<LiveConditionalBranch<'a>> {
    let selected = if schema_is_trivially_universal(if_schema) {
        then_branch
    } else if matches!(if_schema.kind(), SchemaNodeKind::BoolSchema(false)) {
        else_branch
    } else {
        return None;
    };

    Some(match selected {
        Some(branch) => LiveConditionalBranch::Schema(branch),
        None => LiveConditionalBranch::Universal,
    })
}

pub(super) fn explain_identical_conditional_failure(
    sub_then: Option<&SchemaNode>,
    sup_then: Option<&SchemaNode>,
    sub_else: Option<&SchemaNode>,
    sup_else: Option<&SchemaNode>,
    context: &mut SubschemaCheckContext,
) -> Option<SubschemaExplanation> {
    if !optional_conditional_branch_subsumed(
        sub_then,
        sup_then,
        context,
        ExplanationMode::VerdictOnly,
    ) {
        return explain_optional_conditional_branch_failure(sub_then, sup_then, context)
            .map(|detail| detail.under_conditional_branch("then"));
    }
    if !optional_conditional_branch_subsumed(
        sub_else,
        sup_else,
        context,
        ExplanationMode::VerdictOnly,
    ) {
        return explain_optional_conditional_branch_failure(sub_else, sup_else, context)
            .map(|detail| detail.under_conditional_branch("else"));
    }
    None
}

pub(super) fn explain_optional_conditional_branch_failure(
    sub_branch: Option<&SchemaNode>,
    sup_branch: Option<&SchemaNode>,
    context: &mut SubschemaCheckContext,
) -> Option<SubschemaExplanation> {
    match (sub_branch, sup_branch) {
        (Some(sub), Some(sup)) => explain_subschema_failure_with_context(sub, sup, context),
        (None, Some(_)) => Some(SubschemaExplanation::new(
            "unconstrained conditional branch is not contained by the comparison target branch",
        )),
        _ => None,
    }
}

/// Prove a finite conditional branch is contained by `sup` after restricting it
/// to the side of the guard on which the branch can actually run.  The finite
/// value list is an upper bound for the branch language; values that are
/// definitely rejected by the branch, definitely rejected by the guard (then
/// side), or definitely accepted by the guard (else side) can be ignored.
pub(super) fn finite_conditional_branch_values_fit_target(
    if_schema: &SchemaNode,
    branch: &SchemaNode,
    sup: &SchemaNode,
    then_side: bool,
    context: &mut SubschemaCheckContext,
) -> bool {
    let Some(values) = finite_schema_value_superset(branch) else {
        return false;
    };
    values.iter().all(|value| {
        if context.schema_definitely_rejects_value(branch, value) {
            return true;
        }
        let can_reach_side = if then_side {
            !context.schema_definitely_rejects_value(if_schema, value)
        } else {
            !context.superset_contains_value(if_schema, value)
        };
        !can_reach_side || context.superset_contains_value(sup, value)
    })
}

/// Dual finite proof for the `then` side: when the guard itself has a finite
/// value superset, enumerate that instead of the branch.  This catches cases
/// like `if: {enum:[1,"a"]}, then: {type: integer}` where the branch is not
/// finite on its own, but the reachable intersection is.  Values that the
/// guard or branch evaluator can soundly reject are ignored; any uncertain
/// value is kept, making the check conservative.
pub(super) fn finite_conditional_then_guard_values_fit_target(
    if_schema: &SchemaNode,
    then_branch: &SchemaNode,
    sup: &SchemaNode,
    context: &mut SubschemaCheckContext,
) -> bool {
    let Some(values) = finite_schema_value_superset(if_schema) else {
        return false;
    };
    values.iter().all(|value| {
        if context.schema_definitely_rejects_value(if_schema, value)
            || context.schema_definitely_rejects_value(then_branch, value)
        {
            return true;
        }
        context.superset_contains_value(sup, value)
    })
}

/// Enumerate a finite guard domain to prove an implicit `then` branch fits a target.
/// This is the missing-branch analogue of `finite_conditional_then_guard_values_fit_target`.
pub(super) fn finite_guard_values_fit_target(
    if_schema: &SchemaNode,
    sup: &SchemaNode,
    context: &mut SubschemaCheckContext,
) -> bool {
    let Some(values) = finite_schema_value_superset(if_schema) else {
        return false;
    };
    values.iter().all(|value| {
        if context.schema_definitely_rejects_value(if_schema, value) {
            return true;
        }
        context.superset_contains_value(sup, value)
    })
}

/// If the guard is `not A`, its else-side domain is contained in `A`.
/// Proving `A <= sup` is therefore enough for any else branch (including an
/// implicit/universal one) to fit the target.
pub(super) fn negated_guard_complement_subsumed_by_target(
    if_schema: &SchemaNode,
    sup: &SchemaNode,
    context: &mut SubschemaCheckContext,
) -> bool {
    let SchemaNodeKind::Not(negated) = if_schema.kind() else {
        return false;
    };
    analyze_subschema_with_context(negated, sup, context, ExplanationMode::VerdictOnly).is_subschema
}

/// Finite fallback for an implicit/universal else side of a negated guard.
/// This is useful when `A <= sup` is too hard structurally but `A` has a small
/// enumerable superset.
pub(super) fn finite_negated_guard_complement_values_fit_target(
    if_schema: &SchemaNode,
    sup: &SchemaNode,
    context: &mut SubschemaCheckContext,
) -> bool {
    let SchemaNodeKind::Not(negated) = if_schema.kind() else {
        return false;
    };
    let Some(values) = finite_schema_value_superset(negated) else {
        return false;
    };
    values.iter().all(|value| {
        if context.schema_definitely_rejects_value(negated, value)
            || context.superset_contains_value(if_schema, value)
        {
            return true;
        }
        context.superset_contains_value(sup, value)
    })
}

/// Finite fallback for an explicit else branch under a negated guard; enumerate
/// the complement side (`A` in `not A`) and filter by the branch.
pub(super) fn finite_conditional_else_negated_guard_values_fit_target(
    if_schema: &SchemaNode,
    else_branch: &SchemaNode,
    sup: &SchemaNode,
    context: &mut SubschemaCheckContext,
) -> bool {
    let SchemaNodeKind::Not(negated) = if_schema.kind() else {
        return false;
    };
    let Some(values) = finite_schema_value_superset(negated) else {
        return false;
    };
    values.iter().all(|value| {
        if context.schema_definitely_rejects_value(negated, value)
            || context.schema_definitely_rejects_value(else_branch, value)
            || context.superset_contains_value(if_schema, value)
        {
            return true;
        }
        context.superset_contains_value(sup, value)
    })
}

pub(super) fn conditional_branches_subsumed_by(
    if_schema: &SchemaNode,
    then_branch: Option<&SchemaNode>,
    else_branch: Option<&SchemaNode>,
    sup: &SchemaNode,
    context: &mut SubschemaCheckContext,
    mode: ExplanationMode,
) -> bool {
    fn then_branch_is_vacuous(
        if_schema: &SchemaNode,
        then_branch: &SchemaNode,
        context: &mut SubschemaCheckContext,
    ) -> bool {
        // The then side admits only values satisfying both the guard and the
        // branch.  Any sound disjointness fact for those two schemas makes the
        // side empty; false is merely conservative.
        let then_mask = possible_json_type_mask(then_branch);
        then_mask == 0
            || schemas_definitely_disjoint_for_partition(then_branch, then_mask, if_schema, context)
            || schema_definitely_excludes_schema(then_branch, if_schema, context)
            || schema_definitely_excludes_schema(if_schema, then_branch, context)
    }

    fn else_branch_is_vacuous(
        if_schema: &SchemaNode,
        else_branch: &SchemaNode,
        context: &mut SubschemaCheckContext,
    ) -> bool {
        // The else side admits only values that fail the guard.  If the branch
        // itself is a subset of the guard, no value can take that side.
        analyze_subschema_with_context(
            else_branch,
            if_schema,
            context,
            ExplanationMode::VerdictOnly,
        )
        .is_subschema
    }

    match (then_branch, else_branch) {
        (Some(then_branch), Some(else_branch)) => {
            (analyze_subschema_with_context(then_branch, sup, context, mode).is_subschema
                || then_branch_is_vacuous(if_schema, then_branch, context)
                || analyze_subschema_with_context(
                    if_schema,
                    sup,
                    context,
                    ExplanationMode::VerdictOnly,
                )
                .is_subschema
                || finite_conditional_branch_values_fit_target(
                    if_schema,
                    then_branch,
                    sup,
                    true,
                    context,
                )
                || finite_conditional_then_guard_values_fit_target(
                    if_schema,
                    then_branch,
                    sup,
                    context,
                ))
                && (analyze_subschema_with_context(else_branch, sup, context, mode).is_subschema
                    || else_branch_is_vacuous(if_schema, else_branch, context)
                    || branch_covers_guard_complement(if_schema, sup, context)
                    || negated_guard_complement_subsumed_by_target(if_schema, sup, context)
                    || finite_conditional_branch_values_fit_target(
                        if_schema,
                        else_branch,
                        sup,
                        false,
                        context,
                    )
                    || finite_conditional_else_negated_guard_values_fit_target(
                        if_schema,
                        else_branch,
                        sup,
                        context,
                    ))
        }
        (None, Some(else_branch)) => {
            // With no `then`, every value satisfying the guard is accepted on
            // that side.  It is therefore enough for the guard language itself
            // to be contained by the target, plus the usual proof for the
            // explicit else side.
            analyze_subschema_with_context(if_schema, sup, context, mode).is_subschema
                && (analyze_subschema_with_context(else_branch, sup, context, mode).is_subschema
                    || else_branch_is_vacuous(if_schema, else_branch, context)
                    || branch_covers_guard_complement(if_schema, sup, context)
                    || negated_guard_complement_subsumed_by_target(if_schema, sup, context)
                    || finite_conditional_branch_values_fit_target(
                        if_schema,
                        else_branch,
                        sup,
                        false,
                        context,
                    )
                    || finite_conditional_else_negated_guard_values_fit_target(
                        if_schema,
                        else_branch,
                        sup,
                        context,
                    ))
        }
        (Some(then_branch), None) => {
            // With no `else`, values failing the guard are unconstrained.  The
            // cheap sound special case is a universal guard, which leaves no
            // else side at all (or a universal target, as before).
            (schema_is_trivially_universal(sup)
                || schema_is_trivially_universal(if_schema)
                || branch_covers_guard_complement(if_schema, sup, context)
                || negated_guard_complement_subsumed_by_target(if_schema, sup, context)
                || finite_negated_guard_complement_values_fit_target(if_schema, sup, context))
                && (analyze_subschema_with_context(then_branch, sup, context, mode).is_subschema
                    || then_branch_is_vacuous(if_schema, then_branch, context)
                    || analyze_subschema_with_context(
                        if_schema,
                        sup,
                        context,
                        ExplanationMode::VerdictOnly,
                    )
                    .is_subschema
                    || finite_conditional_branch_values_fit_target(
                        if_schema,
                        then_branch,
                        sup,
                        true,
                        context,
                    )
                    || finite_conditional_then_guard_values_fit_target(
                        if_schema,
                        then_branch,
                        sup,
                        context,
                    ))
        }
        (None, None) => schema_is_trivially_universal(sup),
    }
}

pub(super) fn schemas_obviously_equivalent(a: &SchemaNode, b: &SchemaNode) -> bool {
    use SchemaNodeKind::*;
    match (a.kind(), b.kind()) {
        (Const(x), Const(y)) => json_values_equal(x, y),
        (Const(x), Enum(ys)) | (Enum(ys), Const(x)) => {
            ys.len() == 1 && ys.iter().any(|y| json_values_equal(x, y))
        }
        (Enum(xs), Enum(ys)) => {
            xs.len() == ys.len()
                && xs
                    .iter()
                    .all(|x| ys.iter().any(|y| json_values_equal(x, y)))
        }
        (BoolSchema(x), BoolSchema(y)) => x == y,
        (Any, Any) => true,
        (Null { enumeration: None }, Null { enumeration: None }) => true,
        (Boolean { enumeration: None }, Boolean { enumeration: None }) => true,
        (
            String {
                enumeration: None,
                length: al,
                pattern: ap,
                format: af,
            },
            String {
                enumeration: None,
                length: bl,
                pattern: bp,
                format: bf,
            },
        ) => al == bl && ap == bp && af == bf,
        (
            Number {
                enumeration: None,
                bounds: ab,
                multiple_of: am,
            },
            Number {
                enumeration: None,
                bounds: bb,
                multiple_of: bm,
            },
        ) => ab == bb && am == bm,
        (
            Integer {
                enumeration: None,
                bounds: ab,
                multiple_of: am,
            },
            Integer {
                enumeration: None,
                bounds: bb,
                multiple_of: bm,
            },
        ) => ab == bb && am == bm,
        _ => false,
    }
}

/// Compare two conditionals with an identical guard, taking account of
/// branches that are impossible on their guard side. Missing branches are the
/// JSON Schema `true` schema. For the guarded side, it is enough for the
/// superset branch to cover the guard; for the else side, a recognized
/// complement-cover branch can cover every value outside the guard.
pub(super) fn same_guard_conditional_branches_subsumed(
    guard: &SchemaNode,
    sub_then: Option<&SchemaNode>,
    sub_else: Option<&SchemaNode>,
    sup_then: Option<&SchemaNode>,
    sup_else: Option<&SchemaNode>,
    context: &mut SubschemaCheckContext,
    mode: ExplanationMode,
) -> bool {
    let then_empty = |branch: &SchemaNode, context: &mut SubschemaCheckContext| {
        let mask = possible_json_type_mask(branch);
        mask == 0
            || schemas_definitely_disjoint_for_partition(branch, mask, guard, context)
            || schema_definitely_excludes_schema(branch, guard, context)
            || schema_definitely_excludes_schema(guard, branch, context)
    };
    let else_empty = |branch: &SchemaNode, context: &mut SubschemaCheckContext| {
        analyze_subschema_with_context(branch, guard, context, ExplanationMode::VerdictOnly)
            .is_subschema
    };

    let then_ok = match (sub_then, sup_then) {
        (_, None) => true,
        (Some(sub_branch), Some(sup_branch)) => {
            then_empty(sub_branch, context)
                || analyze_subschema_with_context(sub_branch, sup_branch, context, mode)
                    .is_subschema
                || analyze_subschema_with_context(
                    guard,
                    sup_branch,
                    context,
                    ExplanationMode::VerdictOnly,
                )
                .is_subschema
                || finite_conditional_branch_values_fit_target(
                    guard, sub_branch, sup_branch, true, context,
                )
                || finite_conditional_then_guard_values_fit_target(
                    guard, sub_branch, sup_branch, context,
                )
        }
        (None, Some(sup_branch)) => {
            analyze_subschema_with_context(guard, sup_branch, context, ExplanationMode::VerdictOnly)
                .is_subschema
                || finite_guard_values_fit_target(guard, sup_branch, context)
        }
    };
    if !then_ok {
        return false;
    }

    match (sub_else, sup_else) {
        (_, None) => true,
        (Some(sub_branch), Some(sup_branch)) => {
            else_empty(sub_branch, context)
                || analyze_subschema_with_context(sub_branch, sup_branch, context, mode)
                    .is_subschema
                || branch_covers_guard_complement(guard, sup_branch, context)
                || finite_conditional_branch_values_fit_target(
                    guard, sub_branch, sup_branch, false, context,
                )
                || finite_conditional_else_negated_guard_values_fit_target(
                    guard, sub_branch, sup_branch, context,
                )
        }
        (None, Some(sup_branch)) => {
            branch_covers_guard_complement(guard, sup_branch, context)
                || negated_guard_complement_subsumed_by_target(guard, sup_branch, context)
                || finite_negated_guard_complement_values_fit_target(guard, sup_branch, context)
        }
    }
}

/// Return true for the small, sound class of conditionals that accept every
/// instance. Missing conditional branches are JSON Schema `true`; for an
/// explicit `then` branch, proving `if <= then` makes the guarded side
/// vacuous as a restriction. We deliberately only treat the else side as
/// covered when it is absent or syntactically universal, avoiding general
/// complement reasoning here.
pub(super) fn conditional_is_known_universal(
    if_schema: &SchemaNode,
    then_branch: Option<&SchemaNode>,
    else_branch: Option<&SchemaNode>,
    context: &mut SubschemaCheckContext,
) -> bool {
    let then_covers_guard = match then_branch {
        None => true,
        Some(then_branch) => {
            schema_is_trivially_universal(then_branch)
                || analyze_subschema_with_context(
                    if_schema,
                    then_branch,
                    context,
                    ExplanationMode::VerdictOnly,
                )
                .is_subschema
        }
    };
    if !then_covers_guard {
        return false;
    }

    match else_branch {
        None => true,
        Some(else_branch) => branch_covers_guard_complement(if_schema, else_branch, context),
    }
}

/// Prove that a conditional else branch accepts every value outside `if_schema`.
/// A branch `not E` has that property whenever `E <= if_schema`: anything that
/// misses the guard cannot be in `E`, so it satisfies `not E`.  This also works
/// through an anyOf containing such a complement branch.  Keep the recognizer
/// deliberately small; failure is conservative.
pub(super) fn branch_covers_guard_complement(
    if_schema: &SchemaNode,
    branch: &SchemaNode,
    context: &mut SubschemaCheckContext,
) -> bool {
    if schema_is_trivially_universal(branch) {
        return true;
    }
    match branch.kind() {
        SchemaNodeKind::Not(excluded) => {
            analyze_subschema_with_context(
                excluded,
                if_schema,
                context,
                ExplanationMode::VerdictOnly,
            )
            .is_subschema
        }
        SchemaNodeKind::AnyOf(children) => children
            .iter()
            .any(|child| branch_covers_guard_complement(if_schema, child, context)),
        _ => false,
    }
}

pub(super) fn superset_conditional_contains(
    sub: &SchemaNode,
    sup: &SchemaNode,
    sup_if: &SchemaNode,
    sup_then: Option<&SchemaNode>,
    sup_else: Option<&SchemaNode>,
    context: &mut SubschemaCheckContext,
) -> bool {
    let covered_by_then = optional_sup_conditional_branch_contains(
        sub,
        sup_then,
        context,
        ExplanationMode::VerdictOnly,
    );
    let covered_by_else = optional_sup_conditional_branch_contains(
        sub,
        sup_else,
        context,
        ExplanationMode::VerdictOnly,
    );
    let unconditional_branch_cover = covered_by_then && covered_by_else;

    let condition_always_true =
        analyze_subschema_with_context(sub, sup_if, context, ExplanationMode::VerdictOnly)
            .is_subschema;
    let sub_mask = possible_json_type_mask(sub);
    let condition_always_false = sub_mask == 0
        || schemas_definitely_disjoint_for_partition(sub, sub_mask, sup_if, context)
        || schema_definitely_excludes_schema(sub, sup_if, context);
    let guarded_branch_cover =
        (condition_always_true && covered_by_then) || (condition_always_false && covered_by_else);

    let branchwise_subset_cover = if let SchemaNodeKind::IfThenElse {
        if_schema,
        then_schema,
        else_schema,
    } = sub.kind()
    {
        conditional_branches_subsumed_by(
            if_schema,
            then_schema.as_ref(),
            else_schema.as_ref(),
            sup,
            context,
            ExplanationMode::VerdictOnly,
        )
    } else {
        false
    };

    unconditional_branch_cover || guarded_branch_cover || branchwise_subset_cover
}