pushkin-compiler 0.2.1

Schema compiler for pushkin: canonical JSON Schema emission and generated bindings
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
//! Parsing + constrained-subset validation of the canonical JSON Schema.
//! The subset is deliberately small in Phase 1: strict objects with string
//! properties (length/format/enum constraints). Everything else is rejected
//! by name with alternatives.

use crate::CompileError;

/// Constructs the Phase 1 subset does not carry, with the alternative named
/// in the rejection (spec §5.1 — never silently dropped).
const UNREPRESENTABLE: &[(&str, &str)] = &[
    ("patternProperties", "declare explicit 'properties' instead"),
    (
        "prefixItems",
        "declare a named object; tuples do not round-trip to SQL",
    ),
    (
        "$ref",
        "inline the definition; cross-schema refs land in a later phase",
    ),
    ("allOf", "flatten the composition into one object"),
    ("anyOf", "split into separate contracts"),
    ("oneOf", "split into separate contracts"),
    ("not", "express the constraint positively"),
];

const SUPPORTED_FORMATS: &[&str] = &["email"];

/// Keywords the parser consumes at the top level. The gate is BIJECTIVE
/// (F26): a keyword outside this set is rejected by name, never
/// tolerated-and-ignored. Tolerating an unconsumed keyword was a silent
/// DROP before the typify swap and, after it, silent cross-target DRIFT
/// — `targets/rust.rs` feeds typify the RAW schema JSON, so a keyword
/// the parser ignores still shapes the Rust binding alone.
const TOP_LEVEL_KEYWORDS: &[&str] = &[
    "$schema",
    "$comment",
    "type",
    "properties",
    "required",
    "additionalProperties",
];

/// Keywords the parser consumes on a STRING property subschema (F26).
const PROPERTY_KEYWORDS: &[&str] = &[
    "type",
    "minLength",
    "maxLength",
    "format",
    "enum",
    "default",
    "pattern",
];

/// Keywords the parser consumes on a scalar (integer/number/boolean)
/// property (R6 step 2). Bijective like `PROPERTY_KEYWORDS`: range
/// keywords, `multipleOf`, string-only keywords, and anything unknown
/// reject by name — a tolerated keyword would reach typify's raw-JSON
/// feed and shape the Rust binding alone (F26).
const SCALAR_KEYWORDS: &[&str] = &["type", "default"];

/// Keywords admitted on an `array` property (R6 step 3). Bijective like
/// `SCALAR_KEYWORDS`: cardinality keywords (`minItems`/`maxItems`/
/// `uniqueItems`) and `default` reject by name.
///
/// Cardinality is excluded because typify has no such constraint on
/// `Vec<T>` — Zod, Pydantic and Postgres could all express it, so
/// admitting it would leave Rust silently under-enforcing what the other
/// three check (F26). `default` is deferred to its own widening step.
const ARRAY_KEYWORDS: &[&str] = &["type", "items"];

/// Keywords admitted on an array's `items` (R6 step 3): the element type
/// and nothing else.
///
/// Constrained elements are the load-bearing exclusion. Zod, Pydantic and
/// Rust can each express a constrained element type; SQL cannot — a
/// per-element `enum` or length bound is not a column constraint, it needs
/// a `CHECK` over `unnest`. Admitting them would enforce the contract in
/// three targets and not the fourth.
const ARRAY_ITEM_KEYWORDS: &[&str] = &["type"];

/// The email regex the authoring pipeline (Zod v4 `z.email()`) emits
/// alongside `format: "email"`. `pattern` is admitted ONLY as this
/// format's companion and ONLY byte-equal to this constant (human
/// decision, recorded §7).
///
/// A future authoring-library bump that changes the emitted regex will
/// fail compile loudly here. That is the DESIGNED behavior, not a bug:
/// the alternative is the silent cross-target drift this gate closes.
/// Remediation is a deliberate constant update in the same PR as the bump.
const AUTHORING_EMAIL_PATTERN: &str = r"^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$";

#[derive(Debug, Clone, PartialEq)]
pub enum PropertyKind {
    String {
        min_length: Option<u64>,
        max_length: Option<u64>,
        format: Option<String>,
        enum_values: Option<Vec<String>>,
        default: Option<String>,
    },
    Integer {
        default: Option<i64>,
    },
    Number {
        default: Option<f64>,
    },
    Boolean {
        default: Option<bool>,
    },
    /// R6 step 3: an array of bare scalars. The element is an
    /// `ArrayElement`, not a boxed `PropertyKind`, so the type itself
    /// cannot express a nested array, an array of objects, or a
    /// constrained element — D1's admitted shape is structural rather
    /// than merely validated.
    Array {
        element: ArrayElement,
    },
}

/// The element type of an admitted array (R6 step 3). Deliberately a
/// closed enum of the four scalars with no payload: a constrained or
/// compound element is unrepresentable here by construction, so a future
/// widening step must widen this type on purpose rather than by accident.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ArrayElement {
    String,
    Integer,
    Number,
    Boolean,
}

impl PropertyKind {
    /// Whether the property carries a declared default (any type).
    #[must_use]
    pub fn has_default(&self) -> bool {
        match self {
            Self::String { default, .. } => default.is_some(),
            Self::Integer { default } => default.is_some(),
            Self::Number { default } => default.is_some(),
            Self::Boolean { default } => default.is_some(),
            // D1 admits no array default in this step; the front gate
            // rejects `default` on an array property by name.
            Self::Array { .. } => false,
        }
    }
}

#[derive(Debug, Clone, PartialEq)]
pub struct Property {
    pub name: String,
    pub kind: PropertyKind,
    pub required: bool,
}

#[derive(Debug, Clone)]
pub struct ContractSchema {
    pub contract_name: String,
    pub properties: Vec<Property>,
}

pub fn parse(contract_name: &str, schema_json: &str) -> Result<ContractSchema, CompileError> {
    let value: serde_json::Value =
        serde_json::from_str(schema_json).map_err(|error| CompileError::InvalidSchema {
            message: error.to_string(),
        })?;

    require_identifier("contract name", contract_name)?;
    reject_unrepresentable(&value)?;
    reject_unknown_top_level_keywords(&value)?;
    require_strict_object(&value)?;

    let required = required_names(&value)?;
    let properties = parse_properties(&value, &required)?;

    Ok(ContractSchema {
        contract_name: contract_name.to_owned(),
        properties,
    })
}

/// Walks the schema keyword-aware: keys of a schema object are keywords and
/// are matched against the unrepresentable list, but the keys of a
/// `properties` map are user-defined property NAMES — data, not structure —
/// so only their values (subschemas) are walked (S1).
fn reject_unrepresentable(value: &serde_json::Value) -> Result<(), CompileError> {
    match value {
        serde_json::Value::Object(map) => {
            for (key, child) in map {
                if let Some((construct, alternative)) = UNREPRESENTABLE
                    .iter()
                    .find(|(construct, _)| *construct == key)
                {
                    return Err(CompileError::Unrepresentable {
                        construct: (*construct).to_owned(),
                        alternatives: (*alternative).to_owned(),
                    });
                }
                if key == "properties" {
                    if let Some(properties) = child.as_object() {
                        for subschema in properties.values() {
                            reject_unrepresentable(subschema)?;
                        }
                        continue;
                    }
                }
                reject_unrepresentable(child)?;
            }
        }
        serde_json::Value::Array(entries) => {
            for entry in entries {
                reject_unrepresentable(entry)?;
            }
        }
        _ => {}
    }
    Ok(())
}

/// F26: the top-level counterpart to the property allowlist. Runs AFTER
/// `reject_unrepresentable` so the named constructs keep their
/// `Unrepresentable` variant and their specific alternatives.
///
/// `parse` has already parsed the document, and a non-object top level is
/// rejected by `require_strict_object`; the empty-map case simply finds
/// no unknown key.
fn reject_unknown_top_level_keywords(value: &serde_json::Value) -> Result<(), CompileError> {
    for key in value.as_object().into_iter().flatten().map(|(key, _)| key) {
        if !TOP_LEVEL_KEYWORDS.contains(&key.as_str()) {
            return Err(CompileError::Unrepresentable {
                construct: format!("top-level keyword '{key}'"),
                alternatives: format!(
                    "the subset carries {}; annotation keywords are not \
                     emitted to any target, so carrying them would drift \
                     the bindings — remove it, or propose it as a \
                     widening step",
                    TOP_LEVEL_KEYWORDS.join(", ")
                ),
            });
        }
    }
    Ok(())
}

/// F26: a property keyword the parser does not consume would reach
/// typify through the raw-JSON feed and shape the Rust binding ONLY.
///
/// Called from `parse_string_property` after its `type` check, so `spec`
/// is always an object here.
fn reject_unknown_property_keywords(
    name: &str,
    spec: &serde_json::Value,
) -> Result<(), CompileError> {
    for key in spec.as_object().into_iter().flatten().map(|(key, _)| key) {
        if !PROPERTY_KEYWORDS.contains(&key.as_str()) {
            return Err(CompileError::Unrepresentable {
                construct: format!("keyword '{key}' on property '{name}'"),
                alternatives: format!(
                    "the subset carries {}; remove it, or propose it as a \
                     widening step",
                    PROPERTY_KEYWORDS.join(", ")
                ),
            });
        }
    }
    Ok(())
}

/// F26(b), human decision: `pattern` is admitted ONLY as the email
/// format's companion, byte-equal to what the authoring pipeline emits.
/// Zod/Pydantic/SQL carry no pattern handling, so any other pattern
/// would be enforced in Rust alone — the exact drift this closes.
fn validate_pattern(
    name: &str,
    spec: &serde_json::Value,
    format: Option<&str>,
) -> Result<(), CompileError> {
    let Some(value) = spec.get("pattern") else {
        return Ok(());
    };
    let Some(pattern) = value.as_str() else {
        return Err(invalid_property_keyword(name, "'pattern' must be a string"));
    };
    if format == Some("email") && pattern == AUTHORING_EMAIL_PATTERN {
        return Ok(());
    }
    Err(CompileError::Unrepresentable {
        construct: format!("'pattern' on property '{name}'"),
        alternatives: "format 'email', or propose pattern support as a widening step".to_owned(),
    })
}

fn require_strict_object(value: &serde_json::Value) -> Result<(), CompileError> {
    if value.get("type").and_then(serde_json::Value::as_str) != Some("object") {
        return Err(CompileError::InvalidSchema {
            message: "top-level schema must be an object type".to_owned(),
        });
    }
    if value.get("additionalProperties") != Some(&serde_json::Value::Bool(false)) {
        return Err(CompileError::InvalidSchema {
            message: "additionalProperties must be false (strictness is mandatory, charter N2)"
                .to_owned(),
        });
    }
    Ok(())
}

fn required_names(value: &serde_json::Value) -> Result<Vec<String>, CompileError> {
    let Some(required) = value.get("required") else {
        return Ok(Vec::new());
    };
    let Some(entries) = required.as_array() else {
        return Err(invalid_keyword("required", "must be an array of strings"));
    };
    entries
        .iter()
        .map(|entry| {
            entry
                .as_str()
                .map(str::to_owned)
                .ok_or_else(|| invalid_keyword("required", "entries must all be strings"))
        })
        .collect()
}

fn parse_properties(
    value: &serde_json::Value,
    required: &[String],
) -> Result<Vec<Property>, CompileError> {
    let Some(map) = value
        .get("properties")
        .and_then(serde_json::Value::as_object)
    else {
        return Err(CompileError::InvalidSchema {
            message: "schema declares no properties".to_owned(),
        });
    };
    let mut properties = Vec::new();
    for (name, spec) in map {
        require_identifier("property name", name)?;
        let kind = parse_property(name, spec)?;
        let required = required.contains(name);
        reject_required_with_default(name, &kind, required)?;
        reject_non_required_array(name, &kind, required)?;
        properties.push(Property {
            name: name.clone(),
            kind,
            required,
        });
    }
    Ok(properties)
}

/// `required` means the caller MUST send the key; `default` means fill it
/// when omitted — emitted together every target silently demotes the field
/// to optional (S5 human decision, option a: loud rejection, never a quiet
/// winner).
fn reject_required_with_default(
    name: &str,
    kind: &PropertyKind,
    required: bool,
) -> Result<(), CompileError> {
    if required && kind.has_default() {
        return Err(CompileError::InvalidSchema {
            message: format!(
                "property '{name}' is both required and has a default; \
                 choose one: required (caller must send it) or \
                 default (caller may omit it)"
            ),
        });
    }
    Ok(())
}

/// R6 step 3 / charter Addendum A (D8): an array property must be `required`.
///
/// typify emits a bare `Vec<T>` whether or not the property is required —
/// byte-identical output for both — so an absent key and `[]` are
/// indistinguishable in the Rust binding. Zod (`.optional()`), Pydantic
/// (`Optional[list[T]] = None`) and SQL (nullable column) all preserve the
/// difference, so admitting optional arrays would enforce the contract in
/// three targets and silently lose it in the fourth.
///
/// Narrowing the step is the ruled remedy: every alternative shapes typify's
/// feed or post-processes its output, which is the second normalization path
/// F26 refused. Optional arrays are deferred to their own widening step.
fn reject_non_required_array(
    name: &str,
    kind: &PropertyKind,
    required: bool,
) -> Result<(), CompileError> {
    if !required && matches!(kind, PropertyKind::Array { .. }) {
        return Err(CompileError::InvalidSchema {
            message: format!(
                "array property '{name}' must be required; mark it required, \
                 or propose optional arrays as their own widening step"
            ),
        });
    }
    Ok(())
}

/// Names are emitted verbatim into TS, Python, Rust, and SQL identifiers
/// (S2): only `^[A-Za-z_][A-Za-z0-9_]*$` is portable across all four
/// without renaming machinery, which is out of scope by decision.
fn require_identifier(role: &str, name: &str) -> Result<(), CompileError> {
    let mut chars = name.chars();
    let valid = chars
        .next()
        .is_some_and(|first| first.is_ascii_alphabetic() || first == '_')
        && chars.all(|rest| rest.is_ascii_alphanumeric() || rest == '_');
    if valid {
        return Ok(());
    }
    Err(CompileError::InvalidSchema {
        message: format!(
            "{role} '{name}' is not a portable identifier; \
             names must match [A-Za-z_][A-Za-z0-9_]* to emit into all targets"
        ),
    })
}

fn parse_property(name: &str, spec: &serde_json::Value) -> Result<PropertyKind, CompileError> {
    match spec.get("type").and_then(serde_json::Value::as_str) {
        Some("string") => parse_string_property(name, spec),
        Some(scalar @ ("integer" | "number" | "boolean")) => {
            parse_scalar_property(name, spec, scalar)
        }
        Some("array") => parse_array_property(name, spec),
        other => Err(CompileError::Unrepresentable {
            construct: format!("property '{name}' of type {other:?}"),
            alternatives: "the subset carries string, integer, number, and boolean \
                           properties, and arrays of those scalars; objects land in \
                           a later widening step"
                .to_owned(),
        }),
    }
}

/// R6 step 3: an array of bare scalars. `items` is required and admits
/// exactly one keyword, `type`; the array itself admits only `type` and
/// `items` (F26 bijectivity — see `ARRAY_KEYWORDS`/`ARRAY_ITEM_KEYWORDS`).
fn parse_array_property(
    name: &str,
    spec: &serde_json::Value,
) -> Result<PropertyKind, CompileError> {
    for key in spec.as_object().into_iter().flatten().map(|(key, _)| key) {
        if !ARRAY_KEYWORDS.contains(&key.as_str()) {
            return Err(CompileError::Unrepresentable {
                construct: format!("keyword '{key}' on array property '{name}'"),
                alternatives: format!(
                    "the array widening step carries {}; remove it, or propose \
                     it as a widening step",
                    ARRAY_KEYWORDS.join(", ")
                ),
            });
        }
    }

    let Some(items) = spec.get("items") else {
        return Err(CompileError::Unrepresentable {
            construct: format!("array property '{name}' without 'items'"),
            alternatives: format!(
                "an array needs an element type: {}; write \
                 {{\"type\": \"array\", \"items\": {{\"type\": \"string\"}}}}",
                ARRAY_KEYWORDS.join(", ")
            ),
        });
    };

    for key in items.as_object().into_iter().flatten().map(|(key, _)| key) {
        if !ARRAY_ITEM_KEYWORDS.contains(&key.as_str()) {
            return Err(CompileError::Unrepresentable {
                construct: format!("keyword '{key}' on the items of array property '{name}'"),
                alternatives: format!(
                    "array items carry {} only — a per-element constraint is not \
                     a SQL column constraint, so admitting it would enforce the \
                     contract in three targets and not the fourth",
                    ARRAY_ITEM_KEYWORDS.join(", ")
                ),
            });
        }
    }

    let element = match items.get("type").and_then(serde_json::Value::as_str) {
        Some("string") => ArrayElement::String,
        Some("integer") => ArrayElement::Integer,
        Some("number") => ArrayElement::Number,
        Some("boolean") => ArrayElement::Boolean,
        other => {
            return Err(CompileError::Unrepresentable {
                construct: format!("array property '{name}' with items of type {other:?}"),
                alternatives: "array items carry string, integer, number, or boolean; \
                               nested arrays and arrays of objects land in a later \
                               widening step"
                    .to_owned(),
            });
        }
    };

    Ok(PropertyKind::Array { element })
}

/// R6 step 2: bare scalars with an optional TYPED default; every other
/// keyword rejects by name against `SCALAR_KEYWORDS` (F26 bijectivity).
fn parse_scalar_property(
    name: &str,
    spec: &serde_json::Value,
    scalar: &str,
) -> Result<PropertyKind, CompileError> {
    for key in spec.as_object().into_iter().flatten().map(|(key, _)| key) {
        if !SCALAR_KEYWORDS.contains(&key.as_str()) {
            return Err(CompileError::Unrepresentable {
                construct: format!("keyword '{key}' on {scalar} property '{name}'"),
                alternatives: format!(
                    "the scalar widening step carries {}; remove it, or \
                     propose it as a widening step",
                    SCALAR_KEYWORDS.join(", ")
                ),
            });
        }
    }
    let default = spec.get("default");
    match scalar {
        "integer" => {
            let parsed = typed_default(name, default, scalar, serde_json::Value::as_i64)?;
            if let Some(val) = parsed {
                // 2^53 - 1 is the largest integer that survives a round-trip
                // through an IEEE 754 double without change.  Zod's `.default(…)`
                // emits an IEEE double, so a schema default beyond this emits a
                // different value in TS — the silent-lossy class this project
                // rejects by policy.
                let max_safe = 9_007_199_254_740_991_i64;
                let min_safe = -9_007_199_254_740_991_i64;
                if val > max_safe || val < min_safe {
                    return Err(CompileError::InvalidSchema {
                        message: format!(
                            "integer default {val} on property '{name}' exceeds the \
                             safe range for JavaScript number binding (±2^53-1); \
                             the Zod target would emit a different value"
                        ),
                    });
                }
            }
            Ok(PropertyKind::Integer { default: parsed })
        }
        "number" => Ok(PropertyKind::Number {
            default: typed_default(name, default, scalar, serde_json::Value::as_f64)?,
        }),
        _ => Ok(PropertyKind::Boolean {
            default: typed_default(name, default, scalar, serde_json::Value::as_bool)?,
        }),
    }
}

fn typed_default<T>(
    name: &str,
    value: Option<&serde_json::Value>,
    scalar: &str,
    extract: impl Fn(&serde_json::Value) -> Option<T>,
) -> Result<Option<T>, CompileError> {
    let Some(value) = value else {
        return Ok(None);
    };
    extract(value).map(Some).ok_or_else(|| {
        invalid_property_keyword(
            name,
            &format!("'default' must be a {scalar} for a {scalar} property"),
        )
    })
}

fn parse_string_property(
    name: &str,
    spec: &serde_json::Value,
) -> Result<PropertyKind, CompileError> {
    let type_name = spec.get("type").and_then(serde_json::Value::as_str);
    if type_name != Some("string") {
        return Err(CompileError::Unrepresentable {
            construct: format!("property '{name}' of type {type_name:?}"),
            alternatives: "Phase 1 subset carries string properties; widen in a later phase"
                .to_owned(),
        });
    }
    reject_unknown_property_keywords(name, spec)?;
    let format = parse_format(name, spec)?;
    validate_pattern(name, spec, format.as_deref())?;
    let enum_values = parse_enum(name, spec)?;
    let default = parse_default(name, spec)?;
    if let (Some(values), Some(value)) = (&enum_values, &default) {
        if !values.contains(value) {
            return Err(invalid_property_keyword(
                name,
                "'default' must be one of the declared 'enum' values",
            ));
        }
    }
    Ok(PropertyKind::String {
        min_length: spec.get("minLength").and_then(serde_json::Value::as_u64),
        max_length: spec.get("maxLength").and_then(serde_json::Value::as_u64),
        format,
        enum_values,
        default,
    })
}

fn parse_format(name: &str, spec: &serde_json::Value) -> Result<Option<String>, CompileError> {
    let Some(value) = spec.get("format") else {
        return Ok(None);
    };
    let Some(format) = value.as_str() else {
        return Err(invalid_keyword("format", "must be a string"));
    };
    if !SUPPORTED_FORMATS.contains(&format) {
        return Err(CompileError::Unrepresentable {
            construct: format!("format '{format}' on property '{name}'"),
            alternatives: "format 'email', or omit 'format'".to_owned(),
        });
    }
    Ok(Some(format.to_owned()))
}

fn parse_enum(name: &str, spec: &serde_json::Value) -> Result<Option<Vec<String>>, CompileError> {
    let Some(value) = spec.get("enum") else {
        return Ok(None);
    };
    let Some(entries) = value.as_array() else {
        return Err(invalid_property_keyword(name, "'enum' must be an array"));
    };
    entries
        .iter()
        .map(|entry| {
            entry
                .as_str()
                .map(str::to_owned)
                .ok_or_else(|| invalid_property_keyword(name, "'enum' entries must all be strings"))
        })
        .collect::<Result<Vec<_>, _>>()
        .map(Some)
}

fn parse_default(name: &str, spec: &serde_json::Value) -> Result<Option<String>, CompileError> {
    let Some(value) = spec.get("default") else {
        return Ok(None);
    };
    value.as_str().map(str::to_owned).map(Some).ok_or_else(|| {
        invalid_property_keyword(name, "'default' must be a string for a string property")
    })
}

fn invalid_keyword(keyword: &str, detail: &str) -> CompileError {
    CompileError::InvalidSchema {
        message: format!("'{keyword}' {detail}"),
    }
}

fn invalid_property_keyword(name: &str, detail: &str) -> CompileError {
    CompileError::InvalidSchema {
        message: format!("property '{name}' keyword {detail}"),
    }
}