Skip to main content

zenkey_model/
schema.rs

1//! Schema artifacts and type resolution (r3 §3.9, r3.3 D5–D7).
2//!
3//! - **Protobuf:** every listed `.proto` file is compiled on its own with
4//!   `protox` into a `FileDescriptorSet` that includes its imports, without
5//!   source info. That set is the file's artifact. A message type resolves
6//!   to the listed file that defines it. The well-known types
7//!   (`google.protobuf.*`) are always available; one that no listed file
8//!   defines is compiled on demand and becomes an artifact of its own.
9//! - **JSON Schema:** every listed file is one artifact, hashed over its
10//!   JCS form. `json:<Name>` names a `$defs` entry that is unique across
11//!   the listed files; `json:<stem>#<Name>` names one in the file whose stem
12//!   is `<stem>`. A cross-file `$ref` may point only at listed files, and
13//!   in a bundle it resolves by the file stem of its path, so stems are
14//!   unique per contract, and so are ids: two listed files with one JCS
15//!   form would be one artifact under one name (spec §9.4, 0.6).
16//! - **Packed** (core §7.6, §9.4, 0.75): every listed file is one
17//!   artifact, read and hashed as a JSON Schema file is. `packed:<Name>`
18//!   names a `types` entry unique across the listed packed files, and
19//!   `packed:<stem>#<Name>` one in the file of that stem. Its declarations
20//!   are linted by [`crate::packed`] (E038 to E045).
21//! - **Raw:** a media type (`image/jpeg`) or family (`video/*`), with no
22//!   artifact.
23//!
24//! An artifact's id is `sha256:<hex>` of its bytes (protobuf) or of its JCS
25//! form (JSON Schema). A type's identity is (kind, name, artifact id).
26
27use std::collections::{BTreeMap, BTreeSet};
28use std::fmt::Write as _;
29use std::path::{Component, Path, PathBuf};
30
31use base64::Engine as _;
32use prost_reflect::DescriptorPool;
33use serde_json::Value;
34use sha2::{Digest, Sha256};
35
36use crate::authoring::{RawType, SchemasSection, TypeRef};
37use crate::diag::{Diagnostic, Report};
38
39/// A schema artifact's kind, by MCAP's spellings.
40#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
41pub enum SchemaKind {
42    Protobuf,
43    JsonSchema,
44    /// A packed file (core §7.6): strict JSON, carried as
45    /// [`ArtifactData::Json`].
46    Packed,
47}
48
49impl SchemaKind {
50    #[must_use]
51    pub fn as_str(self) -> &'static str {
52        match self {
53            Self::Protobuf => "protobuf",
54            Self::JsonSchema => "jsonschema",
55            Self::Packed => "packed",
56        }
57    }
58}
59
60/// One schema artifact, as a bundle carries it.
61#[derive(Debug, Clone, PartialEq)]
62pub struct Artifact {
63    pub kind: SchemaKind,
64    /// The protobuf file name (include-relative, as imports spell it) or
65    /// the JSON Schema file stem.
66    pub name: String,
67    pub data: ArtifactData,
68}
69
70#[derive(Debug, Clone, PartialEq)]
71pub enum ArtifactData {
72    /// An encoded `FileDescriptorSet`.
73    Protobuf(Vec<u8>),
74    /// A JSON Schema document, or a packed one.
75    Json(Value),
76}
77
78impl Artifact {
79    /// `sha256:<hex>` over the artifact's bytes, or its JCS form.
80    #[must_use]
81    pub fn id(&self) -> String {
82        match &self.data {
83            ArtifactData::Protobuf(b) => sha256_id(b),
84            ArtifactData::Json(v) => sha256_id(&jcs(v)),
85        }
86    }
87
88    /// The `data` member of the artifact's bundle entry: base64 of a
89    /// descriptor set, or the JSON Schema document itself.
90    #[must_use]
91    pub fn data_value(&self) -> Value {
92        match &self.data {
93            ArtifactData::Protobuf(b) => {
94                Value::String(base64::engine::general_purpose::STANDARD.encode(b))
95            }
96            ArtifactData::Json(v) => v.clone(),
97        }
98    }
99}
100
101/// A resolved type identity.
102#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
103pub enum TypeId {
104    Protobuf {
105        name: String,
106        schema: String,
107    },
108    JsonSchema {
109        name: String,
110        schema: String,
111    },
112    /// A packed type (core §7.6): a `types` entry of a packed artifact.
113    Packed {
114        name: String,
115        schema: String,
116    },
117    Raw {
118        media_type: String,
119        media_param: Option<String>,
120    },
121}
122
123impl TypeId {
124    #[must_use]
125    pub fn kind_str(&self) -> &'static str {
126        match self {
127            Self::Protobuf { .. } => "protobuf",
128            Self::JsonSchema { .. } => "jsonschema",
129            Self::Packed { .. } => "packed",
130            Self::Raw { .. } => "raw",
131        }
132    }
133    #[must_use]
134    pub fn is_json(&self) -> bool {
135        matches!(self, Self::JsonSchema { .. })
136    }
137    #[must_use]
138    pub fn is_packed(&self) -> bool {
139        matches!(self, Self::Packed { .. })
140    }
141}
142
143struct ProtoFile {
144    /// The include-relative name (`nav/v2/nav.proto`).
145    name: String,
146    pool: DescriptorPool,
147    artifact: String,
148}
149
150struct JsonFile {
151    stem: String,
152    doc: Value,
153    artifact: String,
154}
155
156struct PackedFile {
157    stem: String,
158    doc: crate::packed::PackedDoc,
159    artifact: String,
160}
161
162/// A type whose layout tag is 0, in a packed file with no E028: E051's
163/// candidate (core §9.2, cascade 7), until the contract's resources say
164/// whether a profile derives it (§7.6, [`SchemaSet::report_tag_zero`]).
165struct TagZero {
166    stem: String,
167    name: String,
168    at: String,
169}
170
171/// The compiled schemas of one contract.
172pub struct SchemaSet {
173    artifacts: BTreeMap<String, Artifact>,
174    proto: Vec<ProtoFile>,
175    json: Vec<JsonFile>,
176    packed: Vec<PackedFile>,
177    /// E051's candidates, in the order the files list them.
178    tag_zero: Vec<TagZero>,
179    /// Set when a listed file failed to load, so unresolved references of
180    /// that kind are not reported twice.
181    proto_failed: bool,
182    json_failed: bool,
183    packed_failed: bool,
184}
185
186/// The well-known types, by the file that defines them.
187const WELL_KNOWN: &[(&str, &[&str])] = &[
188    ("google/protobuf/any.proto", &["Any"]),
189    ("google/protobuf/duration.proto", &["Duration"]),
190    ("google/protobuf/empty.proto", &["Empty"]),
191    ("google/protobuf/field_mask.proto", &["FieldMask"]),
192    (
193        "google/protobuf/struct.proto",
194        &["Struct", "Value", "ListValue"],
195    ),
196    ("google/protobuf/timestamp.proto", &["Timestamp"]),
197    (
198        "google/protobuf/wrappers.proto",
199        &[
200            "DoubleValue",
201            "FloatValue",
202            "Int64Value",
203            "UInt64Value",
204            "Int32Value",
205            "UInt32Value",
206            "BoolValue",
207            "StringValue",
208            "BytesValue",
209        ],
210    ),
211];
212
213impl SchemaSet {
214    /// Loads and compiles every listed schema file, relative to `dir`.
215    /// E051 waits for the contract's resources:
216    /// [`SchemaSet::report_tag_zero`].
217    pub fn load(dir: &Path, sec: &SchemasSection, report: &mut Report) -> Self {
218        let mut set = Self {
219            artifacts: BTreeMap::new(),
220            proto: Vec::new(),
221            json: Vec::new(),
222            packed: Vec::new(),
223            tag_zero: Vec::new(),
224            proto_failed: false,
225            json_failed: false,
226            packed_failed: false,
227        };
228        set.load_proto(dir, sec, report);
229        set.load_json(dir, sec, report);
230        set.load_packed(dir, sec, report);
231        set
232    }
233
234    /// Packed files (core §7.6, §9.4): read as JSON Schema files are, then
235    /// linted by [`crate::packed::PackedDoc::read`]. A stem is unique among
236    /// the packed files, and an id among the JSON Schema and packed files,
237    /// both E024.
238    fn load_packed(&mut self, dir: &Path, sec: &SchemasSection, report: &mut Report) {
239        for f in &sec.packed {
240            let at = format!("schemas.packed {f:?}");
241            let doc = match std::fs::read_to_string(dir.join(f)) {
242                Ok(text) => match crate::strict::parse_json(&text) {
243                    Ok(v) => v,
244                    Err(e) => {
245                        report.push(Diagnostic::error(
246                            "E029",
247                            at,
248                            format!("is not valid JSON: {e}"),
249                        ));
250                        self.packed_failed = true;
251                        continue;
252                    }
253                },
254                Err(e) => {
255                    report.push(Diagnostic::error(
256                        "E029",
257                        at,
258                        format!("cannot be read: {e}"),
259                    ));
260                    self.packed_failed = true;
261                    continue;
262                }
263            };
264            let unsafe_number = unsafe_integer(&doc);
265            if let Some(n) = &unsafe_number {
266                report.push(Diagnostic::error(
267                    "E028",
268                    at.clone(),
269                    format!("{n} is outside ±(2^53−1), so the artifact has no portable id"),
270                ));
271            }
272            let stem = file_stem(f);
273            if self.packed.iter().any(|p| p.stem == stem) {
274                report.push(Diagnostic::error(
275                    "E024",
276                    at,
277                    format!(
278                        "a second listed packed file has the stem {stem:?}; stems are unique per contract"
279                    ),
280                ));
281                continue;
282            }
283            let art = Artifact {
284                kind: SchemaKind::Packed,
285                name: stem.clone(),
286                data: ArtifactData::Json(doc.clone()),
287            };
288            let id = art.id();
289            let taken = self
290                .json
291                .iter()
292                .map(|j| (&j.artifact, &j.stem))
293                .chain(self.packed.iter().map(|p| (&p.artifact, &p.stem)))
294                .find(|(a, _)| **a == id);
295            if let Some((_, first)) = taken {
296                report.push(Diagnostic::error(
297                    "E024",
298                    at,
299                    format!("the same document as {first:?} (one id); list it once"),
300                ));
301                continue;
302            }
303            let read = crate::packed::PackedDoc::read(&doc);
304            for x in &read.findings {
305                let place = if x.at.is_empty() {
306                    at.clone()
307                } else {
308                    format!("{at} {}", x.at)
309                };
310                report.push(Diagnostic::error(x.code, place, x.message.clone()));
311            }
312            // E051 (core §9.2, cascade 7; #1152): a type whose layout tag is
313            // 0, the tag a record of any other kind carries (§7.5), read in
314            // every type with a layout, named by a resource or not. A file
315            // with E028 has no form every implementation hashes alike. A
316            // type a profile derives is set aside (§7.6), which the
317            // resources tell: `report_tag_zero`.
318            if unsafe_number.is_none() {
319                for (name, layout) in &read.types {
320                    if layout.as_ref().is_some_and(|l| l.tag() == 0) {
321                        self.tag_zero.push(TagZero {
322                            stem: stem.clone(),
323                            name: name.clone(),
324                            at: format!("{at} types.{name}"),
325                        });
326                    }
327                }
328            }
329            self.artifacts.insert(id.clone(), art);
330            self.packed.push(PackedFile {
331                stem,
332                doc: read,
333                artifact: id,
334            });
335        }
336    }
337
338    /// The layout of a packed type this set resolved, when its declaration
339    /// has no finding.
340    #[must_use]
341    pub fn packed_layout(&self, t: &TypeId) -> Option<&crate::packed::Layout> {
342        let TypeId::Packed { name, schema } = t else {
343            return None;
344        };
345        self.packed
346            .iter()
347            .find(|p| &p.artifact == schema)?
348            .doc
349            .types
350            .get(name)?
351            .as_ref()
352    }
353
354    fn load_proto(&mut self, dir: &Path, sec: &SchemasSection, report: &mut Report) {
355        if sec.protobuf.is_empty() {
356            return;
357        }
358        let includes: Vec<PathBuf> = match &sec.proto_include {
359            Some(v) => v.iter().map(|p| dir.join(p)).collect(),
360            None if dir.join("proto").is_dir() => vec![dir.join("proto")],
361            None => vec![dir.to_path_buf()],
362        };
363        for f in &sec.protobuf {
364            let at = format!("schemas.protobuf {f:?}");
365            let compiled = protox::Compiler::new(&includes).and_then(|mut c| {
366                c.include_imports(true).include_source_info(false);
367                c.open_file(dir.join(f))?;
368                Ok(c)
369            });
370            let c = match compiled {
371                Ok(c) => c,
372                Err(e) => {
373                    report.push(Diagnostic::error(
374                        "E029",
375                        at,
376                        format!("does not compile: {e}"),
377                    ));
378                    self.proto_failed = true;
379                    continue;
380                }
381            };
382            let Some(name) = c
383                .files()
384                .find(|m| !m.is_import())
385                .map(|m| m.name().to_owned())
386            else {
387                report.push(Diagnostic::error("E029", at, "compiled to no file"));
388                self.proto_failed = true;
389                continue;
390            };
391            let art = Artifact {
392                kind: SchemaKind::Protobuf,
393                name: name.clone(),
394                data: ArtifactData::Protobuf(c.encode_file_descriptor_set()),
395            };
396            let id = art.id();
397            self.artifacts.insert(id.clone(), art);
398            self.proto.push(ProtoFile {
399                name,
400                pool: c.descriptor_pool(),
401                artifact: id,
402            });
403        }
404    }
405
406    fn load_json(&mut self, dir: &Path, sec: &SchemasSection, report: &mut Report) {
407        let mut paths = Vec::new();
408        for f in &sec.jsonschema {
409            let at = format!("schemas.jsonschema {f:?}");
410            let path = dir.join(f);
411            let doc = match std::fs::read_to_string(&path) {
412                Ok(text) => match crate::strict::parse_json(&text) {
413                    Ok(v) => v,
414                    Err(e) => {
415                        report.push(Diagnostic::error(
416                            "E029",
417                            at,
418                            format!("is not valid JSON: {e}"),
419                        ));
420                        self.json_failed = true;
421                        continue;
422                    }
423                },
424                Err(e) => {
425                    report.push(Diagnostic::error(
426                        "E029",
427                        at,
428                        format!("cannot be read: {e}"),
429                    ));
430                    self.json_failed = true;
431                    continue;
432                }
433            };
434            if let Some(n) = unsafe_integer(&doc) {
435                report.push(Diagnostic::error(
436                    "E028",
437                    at.clone(),
438                    format!("{n} is outside ±(2^53−1), so the artifact has no portable id"),
439                ));
440            }
441            let mut refused = std::collections::BTreeSet::new();
442            refused_keywords(&doc, &mut refused);
443            for k in refused {
444                report.push(Diagnostic::error(
445                    "E037",
446                    at.clone(),
447                    format!("keyword {k:?} is outside the zk2 JSON Schema subset"),
448                ));
449            }
450            let stem = file_stem(f);
451            if self.json.iter().any(|j| j.stem == stem) {
452                report.push(Diagnostic::error(
453                    "E024",
454                    at,
455                    format!(
456                        "a second listed file has the stem {stem:?}; stems are unique per contract"
457                    ),
458                ));
459                continue;
460            }
461            let art = Artifact {
462                kind: SchemaKind::JsonSchema,
463                name: stem.clone(),
464                data: ArtifactData::Json(doc.clone()),
465            };
466            let id = art.id();
467            // One id, one name (spec §9.4, 0.6): a later file with an earlier
468            // one's JCS bytes would share its id, and the canonical form
469            // could list it under one name only, so a bundle `$ref` naming
470            // the other stem would resolve to nothing.
471            if let Some(first) = self.json.iter().find(|j| j.artifact == id) {
472                report.push(Diagnostic::error(
473                    "E024",
474                    at,
475                    format!(
476                        "the same document as {:?} (one id); list it once",
477                        first.stem
478                    ),
479                ));
480                continue;
481            }
482            self.artifacts.insert(id.clone(), art);
483            self.json.push(JsonFile {
484                stem,
485                doc,
486                artifact: id,
487            });
488            paths.push((f.clone(), normalize(&path)));
489        }
490        // Cross-file `$ref`s: listed files only, existing definitions only.
491        for (i, (f, path)) in paths.iter().enumerate() {
492            let mut refs = Vec::new();
493            collect_refs(&self.json[i].doc, &mut refs);
494            for r in refs {
495                let at = format!("schemas.jsonschema {f:?}");
496                let (file_part, pointer) = r.split_once('#').unwrap_or((r.as_str(), ""));
497                let target = if file_part.is_empty() {
498                    Some(i)
499                } else if file_part.contains(':') {
500                    None
501                } else {
502                    let p = normalize(&path.parent().unwrap_or(Path::new("")).join(file_part));
503                    paths.iter().position(|(_, q)| *q == p)
504                };
505                let Some(t) = target else {
506                    report.push(Diagnostic::error(
507                        "E032",
508                        at,
509                        format!("$ref {r:?} points outside the listed files"),
510                    ));
511                    continue;
512                };
513                if !pointer.is_empty() && self.json[t].doc.pointer(pointer).is_none() {
514                    report.push(Diagnostic::error(
515                        "E032",
516                        at,
517                        format!("$ref {r:?} points at a missing definition"),
518                    ));
519                }
520            }
521        }
522    }
523
524    /// Resolves a type reference, reporting E023/E024 at `at`.
525    pub fn resolve(&mut self, r: &TypeRef, at: &str, report: &mut Report) -> Option<TypeId> {
526        match r {
527            TypeRef::Raw(raw) => resolve_raw(raw, at, report),
528            TypeRef::Named(s) => {
529                if let Some(rest) = s.strip_prefix("json:") {
530                    self.resolve_json(s, rest, at, report)
531                } else if let Some(rest) = s.strip_prefix("packed:") {
532                    self.resolve_packed(s, rest, at, report)
533                } else {
534                    self.resolve_proto(s, at, report)
535                }
536            }
537        }
538    }
539
540    fn resolve_json(
541        &self,
542        full: &str,
543        rest: &str,
544        at: &str,
545        report: &mut Report,
546    ) -> Option<TypeId> {
547        let (stem, name) = match rest.split_once('#') {
548            Some((stem, name)) => (Some(stem), name),
549            None => (None, rest),
550        };
551        let has = |j: &JsonFile| j.doc.get("$defs").and_then(|d| d.get(name)).is_some();
552        let found: Vec<&JsonFile> = self
553            .json
554            .iter()
555            .filter(|j| stem.is_none_or(|s| j.stem == s) && has(j))
556            .collect();
557        match found.as_slice() {
558            [j] => Some(TypeId::JsonSchema {
559                name: name.to_owned(),
560                schema: j.artifact.clone(),
561            }),
562            [] => {
563                if !self.json_failed {
564                    report.push(Diagnostic::error(
565                        "E023",
566                        at,
567                        format!("{full:?}: no listed JSON Schema file defines $defs/{name}"),
568                    ));
569                }
570                None
571            }
572            many => {
573                let stems: Vec<&str> = many.iter().map(|j| j.stem.as_str()).collect();
574                report.push(Diagnostic::error(
575                    "E024",
576                    at,
577                    format!("{full:?} is defined in {stems:?}; qualify it as json:<stem>#{name}"),
578                ));
579                None
580            }
581        }
582    }
583
584    fn resolve_packed(
585        &self,
586        full: &str,
587        rest: &str,
588        at: &str,
589        report: &mut Report,
590    ) -> Option<TypeId> {
591        let (stem, name) = match rest.split_once('#') {
592            Some((stem, name)) => (Some(stem), name),
593            None => (None, rest),
594        };
595        let found: Vec<&PackedFile> = self
596            .packed
597            .iter()
598            .filter(|p| stem.is_none_or(|s| p.stem == s) && p.doc.types.contains_key(name))
599            .collect();
600        match found.as_slice() {
601            [p] => Some(TypeId::Packed {
602                name: name.to_owned(),
603                schema: p.artifact.clone(),
604            }),
605            [] => {
606                if !self.packed_failed {
607                    report.push(Diagnostic::error(
608                        "E023",
609                        at,
610                        format!("{full:?}: no listed packed file defines types/{name}"),
611                    ));
612                }
613                None
614            }
615            many => {
616                let stems: Vec<&str> = many.iter().map(|p| p.stem.as_str()).collect();
617                report.push(Diagnostic::error(
618                    "E024",
619                    at,
620                    format!("{full:?} is defined in {stems:?}; qualify it as packed:<stem>#{name}"),
621                ));
622                None
623            }
624        }
625    }
626
627    fn resolve_proto(&mut self, name: &str, at: &str, report: &mut Report) -> Option<TypeId> {
628        let found: Vec<&ProtoFile> = self
629            .proto
630            .iter()
631            .filter(|p| {
632                p.pool
633                    .get_message_by_name(name)
634                    .is_some_and(|m| m.parent_file().name() == p.name)
635            })
636            .collect();
637        match found.as_slice() {
638            [p] => {
639                return Some(TypeId::Protobuf {
640                    name: name.to_owned(),
641                    schema: p.artifact.clone(),
642                });
643            }
644            [] => {}
645            _ => {
646                report.push(Diagnostic::error(
647                    "E023",
648                    at,
649                    format!("{name:?} is defined by more than one listed .proto file"),
650                ));
651                return None;
652            }
653        }
654        if let Some(short) = name.strip_prefix("google.protobuf.")
655            && let Some((file, _)) = WELL_KNOWN.iter().find(|(_, ms)| ms.contains(&short))
656        {
657            return self.well_known(file, name);
658        }
659        if !self.proto_failed {
660            let hint = if self
661                .proto
662                .iter()
663                .any(|p| p.pool.get_message_by_name(name).is_some())
664            {
665                " (it is defined by an imported file: list that file)"
666            } else {
667                ""
668            };
669            report.push(Diagnostic::error(
670                "E023",
671                at,
672                format!("{name:?}: no listed .proto file defines this message{hint}"),
673            ));
674        }
675        None
676    }
677
678    fn well_known(&mut self, file: &str, name: &str) -> Option<TypeId> {
679        if let Some(p) = self.proto.iter().find(|p| p.name == file) {
680            return Some(TypeId::Protobuf {
681                name: name.to_owned(),
682                schema: p.artifact.clone(),
683            });
684        }
685        let mut c = protox::Compiler::new::<_, &Path>([]).ok()?;
686        c.include_imports(true).include_source_info(false);
687        c.open_file(file).ok()?;
688        let art = Artifact {
689            kind: SchemaKind::Protobuf,
690            name: file.to_owned(),
691            data: ArtifactData::Protobuf(c.encode_file_descriptor_set()),
692        };
693        let id = art.id();
694        self.artifacts.insert(id.clone(), art);
695        self.proto.push(ProtoFile {
696            name: file.to_owned(),
697            pool: c.descriptor_pool(),
698            artifact: id.clone(),
699        });
700        Some(TypeId::Protobuf {
701            name: name.to_owned(),
702            schema: id,
703        })
704    }
705
706    /// The top-level field names of a message or object type, for the D21
707    /// lint. `None` for raw types, or when the shape is not plain.
708    #[must_use]
709    pub fn field_names(&self, t: &TypeId) -> Option<Vec<String>> {
710        match t {
711            TypeId::Protobuf { name, schema } => {
712                let p = self.proto.iter().find(|p| &p.artifact == schema)?;
713                let m = p.pool.get_message_by_name(name)?;
714                Some(m.fields().map(|f| f.name().to_owned()).collect())
715            }
716            TypeId::JsonSchema { name, schema } => {
717                let j = self.json.iter().find(|j| &j.artifact == schema)?;
718                let props = j
719                    .doc
720                    .get("$defs")?
721                    .get(name)?
722                    .get("properties")?
723                    .as_object()?;
724                Some(props.keys().cloned().collect())
725            }
726            TypeId::Packed { .. } | TypeId::Raw { .. } => None,
727        }
728    }
729
730    /// Every artifact, by id.
731    #[must_use]
732    pub fn artifacts(&self) -> &BTreeMap<String, Artifact> {
733        &self.artifacts
734    }
735
736    /// Whether a listed packed file, with no E028, defines a type whose
737    /// layout tag is 0: E051's candidates, before a profile's derivation
738    /// sets any aside.
739    #[must_use]
740    pub fn has_tag_zero(&self) -> bool {
741        !self.tag_zero.is_empty()
742    }
743
744    /// E051 (core §9.2, cascade 7), per type: each type of a listed packed
745    /// file with no E028 whose layout tag is 0, named by a resource or not,
746    /// "but a type a profile derives (§7.6)". `derived` holds those, each
747    /// `(stem, name)`: the contract's loader asks the profiles that derive
748    /// types (`config.v2`'s `Record` and each `Set<T>`, config.v2 §3,
749    /// [`crate::config::v2::derived_types`]).
750    pub fn report_tag_zero(&self, derived: &BTreeSet<(String, String)>, report: &mut Report) {
751        for t in &self.tag_zero {
752            if derived.contains(&(t.stem.clone(), t.name.clone())) {
753                continue;
754            }
755            report.push(Diagnostic::error(
756                "E051",
757                t.at.clone(),
758                "its layout form has the tag 0, the tag of a record of any other kind, so a \
759                 tool holding no type would sniff its records (core §7.6): swap two of its \
760                 fields of different forms, move a bound, or add a reserved code or a marker; \
761                 a rename keeps the tag"
762                    .to_owned(),
763            ));
764        }
765    }
766}
767
768fn resolve_raw(raw: &RawType, at: &str, report: &mut Report) -> Option<TypeId> {
769    if !is_media_type(&raw.raw) {
770        report.push(Diagnostic::error(
771            "E023",
772            at,
773            format!(
774                "{:?} is not a lowercase media type <type>/<subtype> or family <type>/*",
775                raw.raw
776            ),
777        ));
778        return None;
779    }
780    Some(TypeId::Raw {
781        media_type: raw.raw.clone(),
782        media_param: raw.media_param.clone(),
783    })
784}
785
786fn is_media_type(s: &str) -> bool {
787    let tok = |t: &str| {
788        let mut cs = t.chars();
789        cs.next()
790            .is_some_and(|c| c.is_ascii_lowercase() || c.is_ascii_digit())
791            && cs.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || "!#$&-^_.+".contains(c))
792    };
793    match s.split_once('/') {
794        Some((t, sub)) => tok(t) && (sub == "*" || tok(sub)),
795        None => false,
796    }
797}
798
799fn file_stem(f: &str) -> String {
800    let base = f.rsplit('/').next().unwrap_or(f);
801    base.strip_suffix(".json").unwrap_or(base).to_owned()
802}
803
804/// Lexically normalizes a path (`.` and `..` folded), without touching the
805/// filesystem.
806fn normalize(p: &Path) -> PathBuf {
807    let mut out = PathBuf::new();
808    for c in p.components() {
809        match c {
810            Component::CurDir => {}
811            Component::ParentDir => {
812                if !out.pop() {
813                    out.push("..");
814                }
815            }
816            other => out.push(other),
817        }
818    }
819    out
820}
821
822/// Visits every schema object at a schema position (spec §7.3): the
823/// document root; each value of `properties` and `$defs`; each element of
824/// `prefixItems`, `oneOf` and `anyOf`; the value of `items` and
825/// `additionalProperties`. The value of a refused keyword is not a schema
826/// position, and neither is data (`enum`, `const`, `default`, `examples`):
827/// a `$ref` or a keyword written there is not one.
828pub(crate) fn visit_schemas<'a>(
829    schema: &'a Value,
830    f: &mut dyn FnMut(&'a serde_json::Map<String, Value>),
831) {
832    let Value::Object(m) = schema else { return };
833    f(m);
834    for (k, v) in m {
835        match (k.as_str(), v) {
836            ("properties" | "$defs", Value::Object(subs)) => {
837                subs.values().for_each(|s| visit_schemas(s, f));
838            }
839            ("prefixItems" | "oneOf" | "anyOf", Value::Array(subs)) => {
840                subs.iter().for_each(|s| visit_schemas(s, f));
841            }
842            ("items" | "additionalProperties", sub) => visit_schemas(sub, f),
843            _ => {}
844        }
845    }
846}
847
848/// Every `$ref` at a schema position, in document order.
849fn collect_refs(v: &Value, out: &mut Vec<String>) {
850    visit_schemas(v, &mut |m| {
851        if let Some(Value::String(r)) = m.get("$ref") {
852            out.push(r.clone());
853        }
854    });
855}
856
857/// RFC 8785 (JCS) bytes of a JSON value.
858///
859/// # Panics
860/// Never for a `serde_json::Value`, which always serializes.
861#[must_use]
862pub fn jcs(v: &Value) -> Vec<u8> {
863    serde_json_canonicalizer::to_vec(v).expect("a serde_json::Value always serializes")
864}
865
866/// `sha256:<lowercase hex>` of some bytes.
867#[must_use]
868pub fn sha256_id(bytes: &[u8]) -> String {
869    let digest = Sha256::digest(bytes);
870    let mut s = String::with_capacity(71);
871    s.push_str("sha256:");
872    for b in digest {
873        let _ = write!(s, "{b:02x}");
874    }
875    s
876}
877
878/// The first number outside ±(2^53−1) in a JSON document, if any: an
879/// integer, or a float JCS writes as one
880/// ([`crate::canonical::outside_safe_range`]). JCS implementations disagree
881/// beyond it (Python's `rfc8785` raises).
882pub(crate) fn unsafe_integer(v: &Value) -> Option<String> {
883    match v {
884        Value::Number(n) => crate::canonical::outside_safe_range(n).then(|| n.to_string()),
885        Value::Array(a) => a.iter().find_map(unsafe_integer),
886        Value::Object(m) => m.values().find_map(unsafe_integer),
887        _ => None,
888    }
889}
890
891/// The zk2 JSON Schema subset (spec `core.md` §7.3): the keywords a schema
892/// may use. Annotations are carried and ignored.
893const SUBSET: &[&str] = &[
894    "type",
895    "properties",
896    "required",
897    "additionalProperties",
898    "items",
899    "prefixItems",
900    "enum",
901    "const",
902    "minimum",
903    "maximum",
904    "exclusiveMinimum",
905    "exclusiveMaximum",
906    "minLength",
907    "maxLength",
908    "minItems",
909    "maxItems",
910    "$ref",
911    "oneOf",
912    "anyOf",
913];
914const ANNOTATIONS: &[&str] = &[
915    "$schema",
916    "$id",
917    "$defs",
918    "$comment",
919    "title",
920    "description",
921    "default",
922    "examples",
923    "format",
924    "deprecated",
925    "readOnly",
926    "writeOnly",
927];
928
929/// Every keyword outside the subset at a schema position of a JSON Schema
930/// document ([`visit_schemas`]: never property names, which are data, and
931/// never inside a refused keyword, whose content is not walked).
932fn refused_keywords(schema: &Value, out: &mut std::collections::BTreeSet<String>) {
933    visit_schemas(schema, &mut |m| {
934        for k in m.keys() {
935            if !SUBSET.contains(&k.as_str()) && !ANNOTATIONS.contains(&k.as_str()) {
936                out.insert(k.clone());
937            }
938        }
939    });
940}
941
942#[cfg(test)]
943mod tests {
944    use super::*;
945
946    #[test]
947    fn media_types() {
948        for ok in [
949            "image/jpeg",
950            "video/*",
951            "application/vnd.foo+cbor",
952            "audio/l16",
953        ] {
954            assert!(is_media_type(ok), "{ok}");
955        }
956        for bad in ["image", "Image/jpeg", "*/*", "image/", "image/jpeg; q=1"] {
957            assert!(!is_media_type(bad), "{bad}");
958        }
959    }
960
961    #[test]
962    fn well_known_types_compile_on_demand() {
963        let mut report = Report::default();
964        let mut set = SchemaSet::load(Path::new("."), &SchemasSection::default(), &mut report);
965        let t = set
966            .resolve(
967                &TypeRef::Named("google.protobuf.Empty".into()),
968                "x",
969                &mut report,
970            )
971            .unwrap();
972        assert!(report.0.is_empty(), "{report}");
973        let TypeId::Protobuf { schema, .. } = t else {
974            panic!()
975        };
976        assert_eq!(set.artifacts()[&schema].name, "google/protobuf/empty.proto");
977        assert!(
978            set.resolve(
979                &TypeRef::Named("google.protobuf.Nope".into()),
980                "x",
981                &mut report
982            )
983            .is_none()
984        );
985        assert_eq!(report.codes(), ["E023"]);
986    }
987
988    /// Spec §9.4 (0.6, F-62): a later listed file with an earlier one's id
989    /// (equal JCS bytes, whatever the file bytes) is E024 and not loaded, so
990    /// every name a `$ref` can use stays one artifact's in the bundle.
991    #[test]
992    fn a_listed_file_with_a_taken_id_is_e024() {
993        let dir = std::env::temp_dir().join(format!("zk2-schema-ids-{}", std::process::id()));
994        std::fs::create_dir_all(&dir).unwrap();
995        std::fs::write(
996            dir.join("a.json"),
997            r#"{"$defs": {"X": {"type": "string"}}}"#,
998        )
999        .unwrap();
1000        std::fs::write(
1001            dir.join("b.json"),
1002            "{\"$defs\":{\"X\":{\"type\":\"string\"}}}\n",
1003        )
1004        .unwrap();
1005        std::fs::write(
1006            dir.join("c.json"),
1007            r#"{"$defs": {"Y": {"$ref": "a.json#/$defs/X"}}}"#,
1008        )
1009        .unwrap();
1010        let sec = SchemasSection {
1011            jsonschema: vec!["a.json".into(), "b.json".into(), "c.json".into()],
1012            ..SchemasSection::default()
1013        };
1014        let mut report = Report::default();
1015        let set = SchemaSet::load(&dir, &sec, &mut report);
1016        std::fs::remove_dir_all(&dir).unwrap();
1017        assert_eq!(report.codes(), ["E024"], "{report}");
1018        let names: Vec<&str> = set.artifacts().values().map(|a| a.name.as_str()).collect();
1019        assert_eq!(names.len(), 2);
1020        assert!(names.contains(&"a") && names.contains(&"c"), "{names:?}");
1021    }
1022
1023    #[test]
1024    fn normalize_folds_dots() {
1025        assert_eq!(
1026            normalize(Path::new("a/./b/../c.json")),
1027            PathBuf::from("a/c.json")
1028        );
1029        assert_eq!(normalize(Path::new("../x")), PathBuf::from("../x"));
1030    }
1031}