Skip to main content

zenkey_model/
contract.rs

1//! The contract model: an authoring file, resolved and linted.
2//!
3//! - **Defaults are expanded first (r3.3 D2):** a field comes from the
4//!   resource, else `[defaults.<kind>]`, else `[defaults]`, else the
5//!   built-in default of r3 §3.3. A default applies only where its field is
6//!   legal, so `[defaults] priority = …` reaches streams and operations
7//!   alike while `[defaults] history = true` skips an `@stream`.
8//! - **Types are resolved** against the contract's [`SchemaSet`].
9//! - **Every lint runs** ([`crate::diag::CODES`]), and the model exists only
10//!   when no error was found.
11//!
12//! Set-level checks (two files, one interface; a requirement naming a
13//! resource its interface lacks) are [`check_set`].
14
15use std::collections::{BTreeMap, BTreeSet};
16use std::path::Path;
17use std::str::FromStr;
18
19use serde_json::Value;
20
21use crate::authoring::{
22    self as a, ContractFile, DefaultsBlock, DefaultsSection, Encoding, Kind, ParamType,
23    ResourceSpec, TypeRef,
24};
25use crate::chunk::is_ident;
26use crate::diag::{Diagnostic, Report};
27use crate::grammar::{IfaceId, KindToken};
28use crate::schema::{Artifact, SchemaSet, TypeId};
29use crate::template::{Segment, Template};
30
31pub use crate::authoring::{
32    Congestion, Fanout, HistoryParams, Priority, Reliability, Replies, RequireCardinality, Serving,
33};
34
35/// A valid contract, every default expanded.
36#[derive(Debug, Clone)]
37pub struct Contract {
38    pub iface: IfaceId,
39    /// Informative; not in the fingerprint.
40    pub minor: Option<u32>,
41    /// Documentation; not in the fingerprint.
42    pub summary: Option<String>,
43    /// The profiles used, sorted.
44    pub uses: Vec<IfaceId>,
45    /// Sorted by (kind token, template).
46    pub resources: Vec<Resource>,
47    pub requires: BTreeMap<String, Requirement>,
48    /// Every schema artifact the contract lists or references, by id.
49    pub artifacts: BTreeMap<String, Artifact>,
50}
51
52impl Contract {
53    /// The resource declared under `token` with this exact template.
54    #[must_use]
55    pub fn resource(&self, token: KindToken, template: &str) -> Option<&Resource> {
56        self.resources
57            .iter()
58            .find(|r| r.token == token && r.template.as_str() == template)
59    }
60
61    /// The layout of a packed type this contract references (core §7.6),
62    /// read from its artifact: `None` for a type of another kind, `Err`
63    /// naming why a packed one has none (an artifact missing, as a bundle
64    /// read without its schemas would leave it, or a declaration with a
65    /// finding).
66    ///
67    /// # Errors
68    /// The reason, in words.
69    pub fn packed_layout(&self, ty: &TypeId) -> Result<Option<crate::packed::Layout>, String> {
70        let TypeId::Packed { name, schema } = ty else {
71            return Ok(None);
72        };
73        match self.artifacts.get(schema).map(|a| &a.data) {
74            Some(crate::schema::ArtifactData::Json(doc)) => {
75                crate::packed::layout_in(doc, name).map(Some)
76            }
77            _ => Err(format!(
78                "packed:{name}: the contract carries no packed artifact {schema}"
79            )),
80        }
81    }
82}
83
84/// One resource, fully explicit.
85#[derive(Debug, Clone)]
86pub struct Resource {
87    pub template: Template,
88    pub kind: Kind,
89    pub token: KindToken,
90    /// Documentation; not in the fingerprint.
91    pub doc: Option<String>,
92    pub params: BTreeMap<String, ParamType>,
93    pub cardinality: Option<u64>,
94    pub epoch: Option<String>,
95    pub optional: bool,
96    /// Sorted, deduplicated (a gate list is an AND).
97    pub gate: Vec<String>,
98    pub deprecated: Option<a::Deprecated>,
99    /// `[defaults]`, then `[defaults.<kind>]`, then the resource's own.
100    pub annotations: BTreeMap<String, Value>,
101    pub body: Body,
102}
103
104#[derive(Debug, Clone)]
105pub enum Body {
106    Data(Data),
107    Operation(Operation),
108}
109
110/// A stream, state or event resource.
111#[derive(Debug, Clone)]
112pub struct Data {
113    pub type_: TypeId,
114    pub attachment: Option<TypeId>,
115    /// Set exactly when the type is a JSON Schema type.
116    pub encoding: Option<Encoding>,
117    /// Set exactly when the attachment is a JSON Schema type.
118    pub attachment_encoding: Option<Encoding>,
119    pub reliability: Reliability,
120    pub congestion: Congestion,
121    pub priority: Priority,
122    pub express: bool,
123    pub history: Option<HistoryParams>,
124    /// A frame resource's `frame` table (core §7.7, 0.83): a plain stream
125    /// with no parameter alone; `None` for every other resource.
126    pub frame: Option<crate::frame::FrameParams>,
127    /// Events only.
128    pub rate: Option<Rate>,
129    /// Events only: how far back a replay GET may reach.
130    pub retention_s: Option<u64>,
131}
132
133/// An operation.
134#[derive(Debug, Clone)]
135pub struct Operation {
136    pub request: TypeId,
137    pub response: TypeId,
138    pub error: Option<TypeId>,
139    pub summary: Option<TypeId>,
140    /// Set exactly when one of the operation's types is a JSON Schema type.
141    pub encoding: Option<Encoding>,
142    pub idempotent: bool,
143    pub fanout: Fanout,
144    pub serving: Serving,
145    pub replies: Replies,
146    pub timeout_ms: Option<u64>,
147    /// A recommendation: replies inherit the caller's QoS.
148    pub priority: Priority,
149}
150
151/// An event's declared rate (r3.3 D3).
152#[derive(Debug, Clone, Copy, PartialEq, Eq)]
153pub enum Rate {
154    /// At most one per hour.
155    Rare,
156    /// At most one per minute.
157    Low,
158    /// At most n per hour.
159    Burst(u32),
160}
161
162impl Rate {
163    /// Reads a rate as the authoring format spells it (§2.6): `rare`,
164    /// `low` or `burst(<n>/h)`, `<n>` from 1 without a leading zero.
165    #[must_use]
166    pub fn parse(s: &str) -> Option<Self> {
167        match s {
168            "rare" => Some(Self::Rare),
169            "low" => Some(Self::Low),
170            _ => {
171                let n = s.strip_prefix("burst(")?.strip_suffix("/h)")?;
172                if n.is_empty()
173                    || !n.bytes().all(|b| b.is_ascii_digit())
174                    || (n.len() > 1 && n.starts_with('0'))
175                {
176                    return None;
177                }
178                n.parse().ok().filter(|n| *n > 0).map(Self::Burst)
179            }
180        }
181    }
182}
183
184impl std::fmt::Display for Rate {
185    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
186        match self {
187            Self::Rare => f.write_str("rare"),
188            Self::Low => f.write_str("low"),
189            Self::Burst(n) => write!(f, "burst({n}/h)"),
190        }
191    }
192}
193
194/// `"7d"` → seconds. Units: `s`, `m`, `h`, `d`, `w`.
195fn parse_duration_s(s: &str) -> Option<u64> {
196    let unit = s.chars().last()?;
197    let n = &s[..s.len() - 1];
198    if n.is_empty() || !n.bytes().all(|b| b.is_ascii_digit()) {
199        return None;
200    }
201    let mul = match unit {
202        's' => 1,
203        'm' => 60,
204        'h' => 3600,
205        'd' => 86_400,
206        'w' => 604_800,
207        _ => return None,
208    };
209    n.parse::<u64>().ok()?.checked_mul(mul).filter(|v| *v > 0)
210}
211
212/// A requirement, resolved.
213#[derive(Debug, Clone)]
214pub struct Requirement {
215    pub interface: IfaceId,
216    /// Sorted; `None` is everything.
217    pub resources: Option<Vec<String>>,
218    pub cardinality: RequireCardinality,
219    pub optional: bool,
220    /// Documentation; not in the fingerprint.
221    pub doc: Option<String>,
222    pub annotations: BTreeMap<String, Value>,
223}
224
225/// The outcome of loading one contract file.
226#[derive(Debug)]
227pub struct Loaded {
228    /// `Some` exactly when the report has no error.
229    pub contract: Option<Contract>,
230    pub report: Report,
231}
232
233/// Loads, resolves and lints one contract file. Schema paths are relative
234/// to the file's directory.
235#[must_use]
236pub fn load_path(path: &Path) -> Loaded {
237    let mut report = Report::default();
238    let text = match std::fs::read_to_string(path) {
239        Ok(t) => t,
240        Err(e) => {
241            report.push(Diagnostic::error(
242                "E000",
243                "file",
244                format!("cannot be read: {e}"),
245            ));
246            return Loaded {
247                contract: None,
248                report,
249            };
250        }
251    };
252    let dir = path.parent().unwrap_or(Path::new("."));
253    let name = path.file_name().and_then(|n| n.to_str());
254    load_str(&text, dir, name)
255}
256
257/// Loads, resolves and lints contract text. `dir` anchors schema paths;
258/// `file_name`, when given, is checked against `<name>.v<major>.toml`.
259#[must_use]
260pub fn load_str(text: &str, dir: &Path, file_name: Option<&str>) -> Loaded {
261    let mut report = Report::default();
262    let parsed = toml::from_str(text).map(|f| (f, crate::toml10::first_beyond_toml10(text)));
263    let file: ContractFile = match parsed {
264        Ok((_, Some((line, what)))) => {
265            report.push(Diagnostic::error(
266                "E000",
267                "file",
268                format!("line {line}: {what} is not TOML 1.0, which a contract is (spec §9.1)"),
269            ));
270            return Loaded {
271                contract: None,
272                report,
273            };
274        }
275        Ok((f, None)) => f,
276        Err(e) => {
277            let msg = e.to_string().trim().replace('\n', " ");
278            report.push(Diagnostic::error("E000", "file", msg));
279            return Loaded {
280                contract: None,
281                report,
282            };
283        }
284    };
285    let contract = resolve(&file, dir, file_name, &mut report);
286    let contract = if report.has_errors() { None } else { contract };
287    if let Some(c) = &contract {
288        crate::canonical::check_contract_restrictions(&crate::canonical::canonical(c), &mut report);
289    }
290    let contract = if report.has_errors() { None } else { contract };
291    Loaded { contract, report }
292}
293
294struct Ctx<'a> {
295    report: &'a mut Report,
296    schemas: SchemaSet,
297    defaults: DefaultsSection,
298    base: DefaultsBlock,
299    /// Each profile `uses` lists, by name, and its major.
300    profiles: BTreeMap<String, u32>,
301    minor: Option<u32>,
302}
303
304fn resolve(
305    file: &ContractFile,
306    dir: &Path,
307    file_name: Option<&str>,
308    report: &mut Report,
309) -> Option<Contract> {
310    let i = &file.interface;
311    let iface = match IfaceId::new(&i.name, i.major) {
312        Ok(id) => Some(id),
313        Err(e) => {
314            report.push(Diagnostic::error("E001", "interface", e.to_string()));
315            None
316        }
317    };
318    if i.minor.is_none() {
319        report.push(Diagnostic::warning(
320            "W104",
321            "interface",
322            "`minor` is missing",
323        ));
324    }
325    if let (Some(id), Some(f)) = (&iface, file_name) {
326        let want = format!("{id}.toml");
327        if f != want {
328            report.push(Diagnostic::warning(
329                "W107",
330                "file",
331                format!("the file is named {f:?}; the convention is {want:?}"),
332            ));
333        }
334    }
335    let mut uses = BTreeSet::new();
336    for u in &i.uses {
337        match IfaceId::from_str(u) {
338            Ok(p) => {
339                uses.insert(p);
340            }
341            Err(_) => report.push(Diagnostic::error(
342                "E002",
343                "interface.uses",
344                format!("{u:?} is not a profile id <name>.v<major>"),
345            )),
346        }
347    }
348    // §9.1 E002 (0.22): an annotation key names its profile without a
349    // major, so one contract cannot use two majors of one profile.
350    let mut majors: BTreeMap<&str, Vec<String>> = BTreeMap::new();
351    for p in &uses {
352        majors.entry(p.name()).or_default().push(p.to_string());
353    }
354    for (name, ids) in majors.iter().filter(|(_, ids)| ids.len() > 1) {
355        report.push(Diagnostic::error(
356            "E002",
357            "interface.uses",
358            format!(
359                "profile {name:?} is listed at more than one major ({}): an annotation key \
360                 names its profile without a major, so a contract uses one major of it",
361                ids.join(", ")
362            ),
363        ));
364    }
365    let profiles = uses
366        .iter()
367        .map(|p| (p.name().to_owned(), p.major()))
368        .collect();
369    let schemas = SchemaSet::load(dir, &file.schemas, report);
370    let defaults = file.defaults.clone().unwrap_or_default();
371    let mut cx = Ctx {
372        report,
373        schemas,
374        base: defaults.base(),
375        defaults,
376        profiles,
377        minor: i.minor,
378    };
379    check_defaults(&mut cx);
380
381    let mut resources = Vec::new();
382    for (raw, spec) in &file.resources {
383        if let Some(r) = resolve_resource(raw, spec, &mut cx) {
384            resources.push(r);
385        }
386    }
387    resources.sort_by(|x: &Resource, y: &Resource| {
388        (x.token.as_str(), x.template.as_str()).cmp(&(y.token.as_str(), y.template.as_str()))
389    });
390    check_shapes(file, cx.report);
391    check_overlaps(&resources, cx.report);
392    // Member keys carry no template (r3.3 D9b), so one interface has at most
393    // one `epoch` template: a second would share its member keys.
394    let mut epochs = file.resources.iter().filter(|(_, s)| s.epoch.is_some());
395    if epochs.next().is_some() {
396        for (raw, _) in epochs {
397            cx.report.push(Diagnostic::error(
398                "E022",
399                at_res(raw),
400                "a second `epoch` template in one interface: member keys carry no template",
401            ));
402        }
403    }
404    for (raw, spec) in &file.resources {
405        if let Some(d) = &spec.deprecated
406            && let Some(to) = &d.replaced_by
407            && (to == raw || !file.resources.contains_key(to))
408        {
409            cx.report.push(Diagnostic::error(
410                "E031",
411                at_res(raw),
412                format!(
413                    "`deprecated.replaced_by` {to:?} names no other template of this interface"
414                ),
415            ));
416        }
417    }
418
419    let mut requires = BTreeMap::new();
420    for (role, req) in &file.requires {
421        if let Some(r) = resolve_requirement(role, req, &mut cx) {
422            requires.insert(role.clone(), r);
423        }
424    }
425
426    Some(Contract {
427        iface: iface?,
428        minor: i.minor,
429        summary: i.summary.clone(),
430        uses: uses.into_iter().collect(),
431        resources,
432        requires,
433        artifacts: cx.schemas.artifacts().clone(),
434    })
435}
436
437/// The key's kind chunk for a resource (r3.3 D3).
438#[must_use]
439pub fn token_of(kind: Kind, explicit: bool) -> KindToken {
440    match (kind, explicit) {
441        (Kind::Stream, false) => KindToken::Stream,
442        (Kind::Stream, true) => KindToken::ExplicitStream,
443        (Kind::State, false) => KindToken::State,
444        (Kind::State, true) => KindToken::ExplicitState,
445        (Kind::Event, _) => KindToken::Events,
446        (Kind::Operation, _) => KindToken::Op,
447    }
448}
449
450fn at_res(raw: &str) -> String {
451    format!("resources.{raw:?}")
452}
453
454const DATA_FIELDS: &[&str] = &[
455    "type",
456    "attachment",
457    "encoding",
458    "attachment_encoding",
459    "reliability",
460    "congestion",
461    "priority",
462    "express",
463];
464const OP_FIELDS: &[&str] = &[
465    "request",
466    "response",
467    "error",
468    "summary",
469    "encoding",
470    "idempotent",
471    "fanout",
472    "serving",
473    "replies",
474    "timeout_ms",
475    "priority",
476];
477
478/// `None` when `field` is legal for the kind; otherwise the code to report.
479fn illegal(kind: Kind, explicit: bool, field: &str) -> Option<&'static str> {
480    let ok = match field {
481        "history" => {
482            return (!(matches!(kind, Kind::Stream | Kind::State) && !explicit)).then_some("E019");
483        }
484        // §7.7 (0.83): a plain stream's, and only one with no parameter,
485        // which `resolve_resource` checks with the template in hand.
486        "frame" => return (!(kind == Kind::Stream && !explicit)).then_some("E046"),
487        "explicit" => matches!(kind, Kind::Stream | Kind::State),
488        "rate" | "retention" => kind == Kind::Event,
489        f if kind == Kind::Operation => OP_FIELDS.contains(&f),
490        f => DATA_FIELDS.contains(&f),
491    };
492    (!ok).then_some("E014")
493}
494
495fn block_fields(b: &DefaultsBlock) -> Vec<&'static str> {
496    let mut v = Vec::new();
497    let mut p = |set: bool, n: &'static str| {
498        if set {
499            v.push(n);
500        }
501    };
502    p(b.encoding.is_some(), "encoding");
503    p(b.attachment_encoding.is_some(), "attachment_encoding");
504    p(b.reliability.is_some(), "reliability");
505    p(b.congestion.is_some(), "congestion");
506    p(b.priority.is_some(), "priority");
507    p(b.express.is_some(), "express");
508    p(b.history.is_some(), "history");
509    p(b.idempotent.is_some(), "idempotent");
510    p(b.fanout.is_some(), "fanout");
511    p(b.serving.is_some(), "serving");
512    p(b.replies.is_some(), "replies");
513    p(b.timeout_ms.is_some(), "timeout_ms");
514    v
515}
516
517fn spec_fields(s: &ResourceSpec) -> Vec<&'static str> {
518    let mut v = Vec::new();
519    let mut p = |set: bool, n: &'static str| {
520        if set {
521            v.push(n);
522        }
523    };
524    p(s.type_.is_some(), "type");
525    p(s.attachment.is_some(), "attachment");
526    p(s.encoding.is_some(), "encoding");
527    p(s.attachment_encoding.is_some(), "attachment_encoding");
528    p(s.explicit.is_some(), "explicit");
529    p(s.reliability.is_some(), "reliability");
530    p(s.congestion.is_some(), "congestion");
531    p(s.priority.is_some(), "priority");
532    p(s.express.is_some(), "express");
533    p(s.history.is_some(), "history");
534    p(s.frame.is_some(), "frame");
535    p(s.rate.is_some(), "rate");
536    p(s.retention.is_some(), "retention");
537    p(s.request.is_some(), "request");
538    p(s.response.is_some(), "response");
539    p(s.error.is_some(), "error");
540    p(s.idempotent.is_some(), "idempotent");
541    p(s.fanout.is_some(), "fanout");
542    p(s.serving.is_some(), "serving");
543    p(s.replies.is_some(), "replies");
544    p(s.summary.is_some(), "summary");
545    p(s.timeout_ms.is_some(), "timeout_ms");
546    v
547}
548
549fn check_defaults(cx: &mut Ctx<'_>) {
550    check_annotations(&cx.base.annotations, "defaults", &cx.profiles, cx.report);
551    check_history(cx.base.history.as_ref(), "defaults", cx.report);
552    for kind in [Kind::Stream, Kind::State, Kind::Event, Kind::Operation] {
553        let Some(b) = cx.defaults.for_kind(kind) else {
554            continue;
555        };
556        let at = format!("defaults.{}", kind.as_str());
557        for f in block_fields(b) {
558            if let Some(code) = illegal(kind, false, f) {
559                cx.report.push(Diagnostic::error(
560                    code,
561                    at.clone(),
562                    format!("`{f}` is not a field of kind = {:?}", kind.as_str()),
563                ));
564            }
565        }
566        check_annotations(&b.annotations, &at, &cx.profiles, cx.report);
567        check_history(b.history.as_ref(), &at, cx.report);
568    }
569}
570
571fn check_history(h: Option<&a::History>, at: &str, report: &mut Report) {
572    if let Some(a::History::Params(p)) = h
573        && p.depth == 0
574    {
575        report.push(Diagnostic::error(
576            "E034",
577            at,
578            "`history.depth` must be at least 1",
579        ));
580    }
581}
582
583/// The annotation vocabularies W105 reads (core §10 point 2, Appendix D):
584/// a profile's published table where it has one, else the interim table
585/// of draft 1 (r3.3 D19), until each profile ships its own (#613).
586/// `freshness.v1` publishes its own (`freshness::VOCABULARY`, core 0.21),
587/// and so does `link.v1` (`link::VOCABULARY`, core 0.29, which drops the
588/// interim `downsample_ms`), `alarms.v1` an empty one
589/// (`alarms::VOCABULARY`, core 0.34, which drops the interim
590/// `severity_default`), `telemetry.v1` the interim row's four keys
591/// (`telemetry::VOCABULARY`, core 0.35), `desired.v1` `target_param`
592/// alone (`desired::VOCABULARY`, core 0.36, which retires the interim
593/// `target`), `redundancy.v1` the interim row's `election`
594/// (`redundancy::VOCABULARY`, core 0.39), `timing.v1` the interim row's
595/// three keys (`timing::VOCABULARY`, core 0.53), and `arbitration.v1` the
596/// interim row's `policy`, read on a requirement (`arbitration::VOCABULARY`,
597/// core 0.54). A later major's own is [`vocabulary`]'s: `telemetry.v2`
598/// adds `series` (`telemetry::VOCABULARY_V2`, #983 T1).
599const VOCABULARIES: &[(&str, &[&str])] = &[
600    (crate::freshness::NAME, crate::freshness::VOCABULARY),
601    (crate::timing::NAME, crate::timing::VOCABULARY),
602    (crate::telemetry::NAME, crate::telemetry::VOCABULARY),
603    (crate::link::NAME, crate::link::VOCABULARY),
604    (crate::arbitration::NAME, crate::arbitration::VOCABULARY),
605    (crate::desired::NAME, crate::desired::VOCABULARY),
606    (crate::alarms::NAME, crate::alarms::VOCABULARY),
607    (
608        "media",
609        &[
610            "tiers",
611            "tier_param",
612            "frame_clock",
613            "control",
614            "receiver_report",
615        ],
616    ),
617    ("views", &["document"]),
618    (crate::redundancy::NAME, crate::redundancy::VOCABULARY),
619];
620
621/// The vocabulary W105 reads for the profile `name` at `major`: a later
622/// major's where it publishes its own, else [`VOCABULARIES`]' row.
623fn vocabulary(name: &str, major: u32) -> Option<&'static [&'static str]> {
624    if name == crate::telemetry::NAME && major == 2 {
625        return Some(crate::telemetry::VOCABULARY_V2);
626    }
627    VOCABULARIES
628        .iter()
629        .find(|(n, _)| *n == name)
630        .map(|(_, keys)| *keys)
631}
632
633fn check_annotations(
634    map: &BTreeMap<String, Value>,
635    at: &str,
636    profiles: &BTreeMap<String, u32>,
637    report: &mut Report,
638) {
639    for (k, v) in map {
640        if has_datetime(v) {
641            report.push(Diagnostic::error(
642                "E020",
643                at,
644                format!("annotation {k:?}: a TOML datetime has no JSON value"),
645            ));
646        }
647        let Some((p, key)) = k.rsplit_once('.') else {
648            report.push(Diagnostic::error(
649                "E020",
650                at,
651                format!("annotation {k:?} is not <profile>.<key>"),
652            ));
653            continue;
654        };
655        if IfaceId::new(p, 1).is_err() || !is_ident(key) {
656            report.push(Diagnostic::error(
657                "E020",
658                at,
659                format!("annotation {k:?} is not <profile>.<key>"),
660            ));
661        } else if !profiles.contains_key(p) {
662            report.push(Diagnostic::error(
663                "E020",
664                at,
665                format!("annotation {k:?}: profile {p:?} is not listed in `uses`"),
666            ));
667        } else if let Some(keys) = vocabulary(p, profiles[p])
668            && !keys.contains(&key)
669        {
670            report.push(Diagnostic::warning(
671                "W105",
672                at,
673                format!("annotation {k:?} is not in {p}'s vocabulary {keys:?}"),
674            ));
675        }
676    }
677}
678
679/// A TOML datetime reaches serde as an object with this private key.
680fn has_datetime(v: &Value) -> bool {
681    match v {
682        Value::Object(m) => m.contains_key(a::DATETIME) || m.values().any(has_datetime),
683        Value::Array(a) => a.iter().any(has_datetime),
684        _ => false,
685    }
686}
687
688fn check_gate(g: &str) -> bool {
689    let Some((kind, name)) = g.split_once(':') else {
690        return false;
691    };
692    let mut cs = name.chars();
693    matches!(kind, "build" | "config" | "capability")
694        && cs
695            .next()
696            .is_some_and(|c| c.is_ascii_lowercase() || c.is_ascii_digit())
697        && cs.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || "_.-".contains(c))
698}
699
700/// resource > `[defaults.<kind>]` > `[defaults]`.
701fn pick<T: Clone>(
702    own: Option<&T>,
703    kind: Option<&DefaultsBlock>,
704    base: &DefaultsBlock,
705    f: impl Fn(&DefaultsBlock) -> Option<&T>,
706) -> Option<T> {
707    own.or_else(|| kind.and_then(&f))
708        .or_else(|| f(base))
709        .cloned()
710}
711
712/// What E013 says to write (core §2.2, 0.57; #937): both spellings, so a
713/// newcomer who meets the error needs no further reading.
714const E013_SPELLINGS: &str =
715    "write a number, the most members one instance will hold, or \"unbounded\"";
716
717#[allow(clippy::too_many_lines)]
718fn resolve_resource(raw: &str, spec: &ResourceSpec, cx: &mut Ctx<'_>) -> Option<Resource> {
719    let at = at_res(raw);
720    let template = match Template::parse(raw) {
721        Ok(t) => t,
722        Err(e) => {
723            cx.report.push(Diagnostic::error("E010", at, e.to_string()));
724            return None;
725        }
726    };
727    let kind = spec.kind;
728    let explicit = spec.explicit.unwrap_or(false);
729    let token = token_of(kind, explicit);
730    let errors_before = cx.report.errors().count();
731    for f in spec_fields(spec) {
732        if let Some(code) = illegal(kind, explicit, f) {
733            let why = match code {
734                "E019" => "`history` is for plain (non-explicit) stream and state resources only"
735                    .to_owned(),
736                "E046" => "`frame` is for a plain (non-explicit) stream resource only".to_owned(),
737                _ => format!("`{f}` is not a field of kind = {:?}", kind.as_str()),
738            };
739            cx.report.push(Diagnostic::error(code, at.clone(), why));
740        } else if f == "frame" && template.has_params() {
741            cx.report.push(Diagnostic::error(
742                "E046",
743                at.clone(),
744                "`frame` on a template with a parameter: a frame resource's fields are concrete",
745            ));
746        }
747    }
748
749    // Parameters.
750    let tparams: Vec<(&str, bool)> = template.params().collect();
751    for (name, rest) in &tparams {
752        match spec.params.get(*name) {
753            None => cx.report.push(Diagnostic::error(
754                "E011",
755                at.clone(),
756                format!("template parameter {name:?} has no entry in `params`"),
757            )),
758            Some(t) => {
759                if (*t == ParamType::Path) != *rest {
760                    cx.report.push(Diagnostic::error(
761                        "E012",
762                        at.clone(),
763                        format!("parameter {name:?}: `path` is the type of a rest parameter {{x...}}, and only of one"),
764                    ));
765                }
766            }
767        }
768    }
769    for name in spec.params.keys() {
770        if !tparams.iter().any(|(n, _)| n == name) {
771            cx.report.push(Diagnostic::error(
772                "E011",
773                at.clone(),
774                format!("`params` declares {name:?}, which the template does not have"),
775            ));
776        }
777    }
778    // `"unbounded"` is 4294967295 from here on (§2.2, 0.57): the contract
779    // carries one integer whichever spelling wrote it.
780    let cardinality = spec.cardinality.map(a::Cardinality::value);
781    match (template.has_params(), cardinality) {
782        (true, None) => cx.report.push(Diagnostic::error(
783            "E013",
784            at.clone(),
785            format!("a templated resource declares its `cardinality`; {E013_SPELLINGS}"),
786        )),
787        (true, Some(0)) => cx.report.push(Diagnostic::error(
788            "E013",
789            at.clone(),
790            format!("`cardinality` is at least 1; {E013_SPELLINGS}"),
791        )),
792        (false, Some(_)) => cx.report.push(Diagnostic::error(
793            "E014",
794            at.clone(),
795            "`cardinality` on a template without parameters",
796        )),
797        _ => {}
798    }
799    let single = |n: &str| {
800        template
801            .segments()
802            .iter()
803            .any(|s| matches!(s, Segment::Param(p) if p == n))
804    };
805    if let Some(e) = &spec.epoch
806        && !single(e)
807    {
808        cx.report.push(Diagnostic::error(
809            "E022",
810            at.clone(),
811            format!("`epoch` {e:?} is not a single-chunk parameter of the template"),
812        ));
813    }
814
815    // Gates.
816    let mut gate: Vec<String> = spec
817        .gate
818        .as_ref()
819        .map(|g| g.items().into_iter().map(str::to_owned).collect())
820        .unwrap_or_default();
821    gate.sort();
822    gate.dedup();
823    if !gate.is_empty() && !spec.optional {
824        cx.report.push(Diagnostic::error(
825            "E016",
826            at.clone(),
827            "`gate` without `optional = true`",
828        ));
829    }
830    for g in &gate {
831        if !check_gate(g) {
832            let hint = if g.starts_with("feature:") {
833                " (draft 0's `feature:` is `build:` in draft 1)"
834            } else {
835                ""
836            };
837            cx.report.push(Diagnostic::error(
838                "E017",
839                at.clone(),
840                format!(
841                    "gate {g:?} is not build:|config:|capability: plus [a-z0-9][a-z0-9_.-]*{hint}"
842                ),
843            ));
844        }
845    }
846    if let Some(d) = &spec.deprecated
847        && let Some(m) = cx.minor
848        && d.since > m
849    {
850        cx.report.push(Diagnostic::error(
851            "E031",
852            at.clone(),
853            format!(
854                "`deprecated.since` = {} is later than the interface minor {m}",
855                d.since
856            ),
857        ));
858    }
859
860    // Annotations: defaults, then the kind's defaults, then the resource's own.
861    check_annotations(&spec.annotations, &at, &cx.profiles, cx.report);
862    let kd = cx.defaults.for_kind(kind).cloned();
863    let kd = kd.as_ref();
864    let mut annotations = cx.base.annotations.clone();
865    if let Some(k) = kd {
866        annotations.extend(k.annotations.clone());
867    }
868    annotations.extend(spec.annotations.clone());
869
870    let body = if kind == Kind::Operation {
871        resolve_op(&at, spec, kd, &tparams, cx)
872    } else {
873        resolve_data(&at, spec, kind, explicit, kd, &template, &annotations, cx)
874    };
875    if cx.report.errors().count() > errors_before {
876        return None;
877    }
878    Some(Resource {
879        template,
880        kind,
881        token,
882        doc: spec.doc.clone(),
883        params: spec.params.clone(),
884        cardinality,
885        epoch: spec.epoch.clone(),
886        optional: spec.optional,
887        gate,
888        deprecated: spec.deprecated.clone(),
889        annotations,
890        body: body?,
891    })
892}
893
894fn resolve_type(
895    r: Option<&TypeRef>,
896    what: &str,
897    at: &str,
898    template: Option<&Template>,
899    cx: &mut Ctx<'_>,
900) -> Option<TypeId> {
901    let t = cx.schemas.resolve(r?, &format!("{at} {what}"), cx.report)?;
902    if let (
903        TypeId::Raw {
904            media_param: Some(p),
905            ..
906        },
907        Some(tpl),
908    ) = (&t, template)
909    {
910        let ok = tpl
911            .segments()
912            .iter()
913            .any(|s| matches!(s, Segment::Param(n) if n == p));
914        if !ok {
915            cx.report.push(Diagnostic::error(
916                "E025",
917                at,
918                format!(
919                    "{what}: `media_param` {p:?} is not a single-chunk parameter of the template"
920                ),
921            ));
922        }
923    }
924    Some(t)
925}
926
927#[allow(clippy::too_many_arguments)]
928fn resolve_data(
929    at: &str,
930    spec: &ResourceSpec,
931    kind: Kind,
932    explicit: bool,
933    kd: Option<&DefaultsBlock>,
934    template: &Template,
935    annotations: &BTreeMap<String, Value>,
936    cx: &mut Ctx<'_>,
937) -> Option<Body> {
938    if spec.type_.is_none() {
939        cx.report.push(Diagnostic::error(
940            "E015",
941            at,
942            format!("kind = {:?} requires `type`", kind.as_str()),
943        ));
944    }
945    let type_ = resolve_type(spec.type_.as_ref(), "type", at, Some(template), cx);
946    let attachment = resolve_type(
947        spec.attachment.as_ref(),
948        "attachment",
949        at,
950        Some(template),
951        cx,
952    );
953    // §7.1 (0.75, narrowed by 0.92): a packed record needs CH's tag, which
954    // an explicit stream's samples and an attachment never carry.
955    if kind == Kind::Stream && explicit && type_.as_ref().is_some_and(TypeId::is_packed) {
956        cx.report.push(Diagnostic::error(
957            "E044",
958            at,
959            "type: a packed type on an explicit stream, whose samples carry no CH for its tag",
960        ));
961    }
962    if attachment.as_ref().is_some_and(TypeId::is_packed) {
963        cx.report.push(Diagnostic::error(
964            "E044",
965            at,
966            "attachment: a packed type as an attachment, which carries no CH for its tag",
967        ));
968    }
969    let base = cx.base.clone();
970    // W103 is judged on resolved types only: a type that is missing (E015)
971    // or does not resolve (E023, E024) says nothing about its kind.
972    let encoding = match &type_ {
973        Some(t) if t.is_json() => Some(
974            pick(spec.encoding.as_ref(), kd, &base, |b| b.encoding.as_ref())
975                .unwrap_or(Encoding::Json),
976        ),
977        Some(_) => {
978            if spec.encoding.is_some() {
979                cx.report.push(Diagnostic::warning(
980                    "W103",
981                    at,
982                    "`encoding` on a protobuf or raw type is ignored",
983                ));
984            }
985            None
986        }
987        None => None,
988    };
989    let attachment_encoding = match &attachment {
990        Some(t) if t.is_json() => Some(
991            pick(spec.attachment_encoding.as_ref(), kd, &base, |b| {
992                b.attachment_encoding.as_ref()
993            })
994            .unwrap_or(Encoding::Json),
995        ),
996        None if spec.attachment.is_some() => None,
997        _ => {
998            if spec.attachment_encoding.is_some() {
999                cx.report.push(Diagnostic::warning(
1000                    "W103",
1001                    at,
1002                    "`attachment_encoding` without a JSON Schema attachment is ignored",
1003                ));
1004            }
1005            None
1006        }
1007    };
1008    let (rel, cong, prio) = match (kind, explicit) {
1009        (Kind::Stream, false) => (Reliability::BestEffort, Congestion::Drop, Priority::Data),
1010        (Kind::Stream, true) => (Reliability::BestEffort, Congestion::Drop, Priority::DataLow),
1011        _ => (Reliability::Reliable, Congestion::Block, Priority::Data),
1012    };
1013    let history = if illegal(kind, explicit, "history").is_none() {
1014        let h = pick(spec.history.as_ref(), kd, &base, |b| b.history.as_ref());
1015        check_history(spec.history.as_ref(), at, cx.report);
1016        match h {
1017            None | Some(a::History::Flag(false)) => None,
1018            Some(a::History::Flag(true)) => Some(HistoryParams {
1019                depth: 1,
1020                miss_detection_ms: None,
1021            }),
1022            Some(a::History::Params(p)) => Some(p),
1023        }
1024    } else {
1025        None
1026    };
1027    let frame = match &spec.frame {
1028        Some(f) if kind == Kind::Stream && !explicit && !template.has_params() => {
1029            resolve_frame(at, f, type_.as_ref(), annotations, cx)
1030        }
1031        _ => None,
1032    };
1033    let (mut rate, mut retention_s) = (None, None);
1034    if kind == Kind::Event {
1035        match &spec.rate {
1036            None => cx.report.push(Diagnostic::error(
1037                "E015",
1038                at,
1039                "kind = \"event\" requires `rate`",
1040            )),
1041            Some(s) => {
1042                rate = Rate::parse(s);
1043                if rate.is_none() {
1044                    cx.report.push(Diagnostic::error(
1045                        "E026",
1046                        at,
1047                        format!("`rate` {s:?} is not \"rare\", \"low\" or \"burst(<n>/h)\""),
1048                    ));
1049                }
1050            }
1051        }
1052        match &spec.retention {
1053            None => cx.report.push(Diagnostic::error(
1054                "E015",
1055                at,
1056                "kind = \"event\" requires `retention`",
1057            )),
1058            Some(s) => {
1059                retention_s = parse_duration_s(s);
1060                if retention_s.is_none() {
1061                    cx.report.push(Diagnostic::error(
1062                        "E026",
1063                        at,
1064                        format!("`retention` {s:?} is not a positive duration <n>s|m|h|d|w"),
1065                    ));
1066                }
1067            }
1068        }
1069    }
1070    Some(Body::Data(Data {
1071        type_: type_?,
1072        attachment,
1073        encoding,
1074        attachment_encoding,
1075        reliability: pick(spec.reliability.as_ref(), kd, &base, |b| {
1076            b.reliability.as_ref()
1077        })
1078        .unwrap_or(rel),
1079        congestion: pick(spec.congestion.as_ref(), kd, &base, |b| {
1080            b.congestion.as_ref()
1081        })
1082        .unwrap_or(cong),
1083        priority: pick(spec.priority.as_ref(), kd, &base, |b| b.priority.as_ref()).unwrap_or(prio),
1084        express: pick(spec.express.as_ref(), kd, &base, |b| b.express.as_ref()).unwrap_or(false),
1085        history,
1086        frame,
1087        rate,
1088        retention_s,
1089    }))
1090}
1091
1092/// A frame resource's `frame` table (core §7.7, §9.2 cascade 8): E048 for
1093/// each value outside §7.7's table; E047 for a type that resolved and is
1094/// not packed, or whose packed declaration has an extension marker; E049
1095/// for a deadband its record type's layout does not take; E050 for the
1096/// timing it cannot keep, once its values are E048's none. `None` on any
1097/// E048, so the resource carries no table.
1098fn resolve_frame(
1099    at: &str,
1100    spec: &a::FrameSpec,
1101    type_: Option<&TypeId>,
1102    annotations: &BTreeMap<String, Value>,
1103    cx: &mut Ctx<'_>,
1104) -> Option<crate::frame::FrameParams> {
1105    let params = match crate::frame::FrameParams::resolve(spec) {
1106        Ok(p) => Some(p),
1107        Err(why) => {
1108            for w in why {
1109                cx.report.push(Diagnostic::error("E048", at, w));
1110            }
1111            None
1112        }
1113    };
1114    // E047 and E049 read the record type: they wait for one that resolves.
1115    match type_ {
1116        Some(t) if !t.is_packed() => cx.report.push(Diagnostic::error(
1117            "E047",
1118            at,
1119            format!("a frame resource's type is {}, not packed", t.kind_str()),
1120        )),
1121        Some(t) => {
1122            if let Some(layout) = cx.schemas.packed_layout(t).cloned() {
1123                if layout
1124                    .items
1125                    .iter()
1126                    .any(|i| matches!(i, crate::packed::Item::Marker))
1127                {
1128                    cx.report.push(Diagnostic::error(
1129                        "E047",
1130                        at,
1131                        "a frame resource's packed type has an extension marker: a delta \
1132                         record's bitmap has one width for every reader",
1133                    ));
1134                }
1135                for name in spec.deadband.keys() {
1136                    match layout.fields().find(|f| &f.name == name) {
1137                        None => cx.report.push(Diagnostic::error(
1138                            "E049",
1139                            at,
1140                            format!("the deadband names {name:?}, no field of the record type"),
1141                        )),
1142                        Some(f) if !crate::frame::takes_deadband(f) => {
1143                            cx.report.push(Diagnostic::error(
1144                                "E049",
1145                                at,
1146                                format!(
1147                                    "the deadband names {name:?}, a {} field: only an int, \
1148                                     fixed or counter takes one",
1149                                    f.kind.as_str()
1150                                ),
1151                            ));
1152                        }
1153                        Some(_) => {}
1154                    }
1155                }
1156            }
1157        }
1158        None => {}
1159    }
1160    let params = params?;
1161    check_frame_timing(at, &params, annotations, cx.report);
1162    check_frame_horizon(at, &params, annotations, cx.report);
1163    Some(params)
1164}
1165
1166/// W108 (core §7.7, `freshness.v1` §2.4): a frame resource whose interval
1167/// is above half its horizon. Its owner puts a frame at least every
1168/// ttl/2, so a cadence it states above that is one it cannot keep. An
1169/// unstated interval, and a horizon that does not read, give none.
1170fn check_frame_horizon(
1171    at: &str,
1172    params: &crate::frame::FrameParams,
1173    annotations: &BTreeMap<String, Value>,
1174    report: &mut Report,
1175) {
1176    let (Some(ttl), Some(interval)) = (
1177        crate::freshness::horizon(Kind::Stream, annotations).ttl(),
1178        params.interval_ms(annotations),
1179    ) else {
1180        return;
1181    };
1182    if u128::from(interval) * 2 > ttl.as_millis() {
1183        report.push(Diagnostic::warning(
1184            "W108",
1185            at,
1186            format!(
1187                "the frame's interval, {interval} ms, is above half its `freshness.ttl_s` = {}: \
1188                 its owner puts a frame at least every ttl/2",
1189                ttl.as_secs()
1190            ),
1191        ));
1192    }
1193}
1194
1195/// E050 (core §7.7, `timing.v1` §2.3): a deadline below the span, each
1196/// deadband whose `max_records` × the frame's interval passes the
1197/// deadline (an unstated interval always), and a lifespan. The `timing.*`
1198/// values are read as `timing.v1` §2.2 reads them: one that does not read
1199/// gives none.
1200fn check_frame_timing(
1201    at: &str,
1202    params: &crate::frame::FrameParams,
1203    annotations: &BTreeMap<String, Value>,
1204    report: &mut Report,
1205) {
1206    let crate::timing::Declaration::Declared(d) =
1207        crate::timing::declaration(Kind::Stream, annotations)
1208    else {
1209        return;
1210    };
1211    let ms = |x: std::time::Duration| u64::try_from(x.as_millis()).unwrap_or(u64::MAX);
1212    if let Some(deadline) = d.deadline.map(ms) {
1213        if let Some(span) = params.span_ms()
1214            && deadline < span
1215        {
1216            report.push(Diagnostic::error(
1217                "E050",
1218                at,
1219                format!(
1220                    "`timing.deadline_ms` = {deadline} is below the frame's span, {span} ms: \
1221                     every frame that keeps its cadence would miss it"
1222                ),
1223            ));
1224        }
1225        let interval = params.interval_ms(annotations);
1226        for (name, db) in &params.deadband {
1227            let fits =
1228                interval.is_some_and(|i| u64::from(db.max_records).saturating_mul(i) <= deadline);
1229            if !fits {
1230                report.push(Diagnostic::error(
1231                    "E050",
1232                    at,
1233                    match interval {
1234                        Some(i) => format!(
1235                            "the deadband on {name:?}: {} records of {i} ms pass \
1236                             `timing.deadline_ms` = {deadline}",
1237                            db.max_records
1238                        ),
1239                        None => format!(
1240                            "the deadband on {name:?} beside `timing.deadline_ms`, and no \
1241                             interval stated: neither a step nor `timing.period_ms`"
1242                        ),
1243                    },
1244                ));
1245            }
1246        }
1247    }
1248    if d.lifespan.is_some() {
1249        report.push(Diagnostic::error(
1250            "E050",
1251            at,
1252            "`timing.lifespan_ms` on a frame resource: a lifespan reads each sample's Zenoh \
1253             timestamp, and a frame's records carry none of their own",
1254        ));
1255    }
1256}
1257
1258fn resolve_op(
1259    at: &str,
1260    spec: &ResourceSpec,
1261    kd: Option<&DefaultsBlock>,
1262    tparams: &[(&str, bool)],
1263    cx: &mut Ctx<'_>,
1264) -> Option<Body> {
1265    for (f, set) in [
1266        ("request", spec.request.is_some()),
1267        ("response", spec.response.is_some()),
1268    ] {
1269        if !set {
1270            cx.report.push(Diagnostic::error(
1271                "E015",
1272                at,
1273                format!("kind = \"operation\" requires `{f}`"),
1274            ));
1275        }
1276    }
1277    let request = resolve_type(spec.request.as_ref(), "request", at, None, cx);
1278    let response = resolve_type(spec.response.as_ref(), "response", at, None, cx);
1279    let error = resolve_type(spec.error.as_ref(), "error", at, None, cx);
1280    let summary = resolve_type(spec.summary.as_ref(), "summary", at, None, cx);
1281    // §7.1 (0.92): an operation's request, response, error and summary may
1282    // each be packed, since §7.5's forms carry the tag in their CH.
1283    let base = cx.base.clone();
1284    let replies =
1285        pick(spec.replies.as_ref(), kd, &base, |b| b.replies.as_ref()).unwrap_or(Replies::One);
1286    if spec.summary.is_some() && replies != Replies::Many {
1287        cx.report.push(Diagnostic::error(
1288            "E033",
1289            at,
1290            "`summary` without `replies = \"many\"`",
1291        ));
1292    }
1293    let idempotent = pick(spec.idempotent.as_ref(), kd, &base, |b| {
1294        b.idempotent.as_ref()
1295    })
1296    .unwrap_or(false);
1297    let serving = pick(spec.serving.as_ref(), kd, &base, |b| b.serving.as_ref())
1298        .unwrap_or(Serving::Exclusive);
1299    if serving == Serving::Replicated && !idempotent {
1300        cx.report.push(Diagnostic::error(
1301            "E018",
1302            at,
1303            "`serving = \"replicated\"` requires `idempotent = true`",
1304        ));
1305    }
1306    if let Some(req) = &request
1307        && let Some(fields) = cx.schemas.field_names(req)
1308    {
1309        let rep: Vec<&str> = tparams
1310            .iter()
1311            .map(|(n, _)| *n)
1312            .filter(|n| fields.iter().any(|f| f == n))
1313            .collect();
1314        if !rep.is_empty() {
1315            cx.report.push(Diagnostic::warning(
1316                "W102",
1317                at,
1318                format!("the request type repeats template parameter(s) {rep:?} (D21)"),
1319            ));
1320        }
1321    }
1322    let any_json = [&request, &response, &error, &summary]
1323        .into_iter()
1324        .any(|t| t.as_ref().is_some_and(TypeId::is_json));
1325    // As for data, W103 waits for every type to resolve.
1326    let unresolved = [
1327        (&spec.request, &request),
1328        (&spec.response, &response),
1329        (&spec.error, &error),
1330        (&spec.summary, &summary),
1331    ]
1332    .iter()
1333    .any(|(written, resolved)| written.is_some() && resolved.is_none())
1334        || request.is_none()
1335        || response.is_none();
1336    let encoding = if any_json {
1337        Some(
1338            pick(spec.encoding.as_ref(), kd, &base, |b| b.encoding.as_ref())
1339                .unwrap_or(Encoding::Json),
1340        )
1341    } else {
1342        if spec.encoding.is_some() && !unresolved {
1343            cx.report.push(Diagnostic::warning(
1344                "W103",
1345                at,
1346                "`encoding` on an operation without JSON Schema types is ignored",
1347            ));
1348        }
1349        None
1350    };
1351    Some(Body::Operation(Operation {
1352        request: request?,
1353        response: response?,
1354        error,
1355        summary,
1356        encoding,
1357        idempotent,
1358        fanout: pick(spec.fanout.as_ref(), kd, &base, |b| b.fanout.as_ref())
1359            .unwrap_or(Fanout::Forbidden),
1360        serving,
1361        replies,
1362        timeout_ms: pick(spec.timeout_ms.as_ref(), kd, &base, |b| {
1363            b.timeout_ms.as_ref()
1364        }),
1365        priority: pick(spec.priority.as_ref(), kd, &base, |b| b.priority.as_ref())
1366            .unwrap_or(Priority::InteractiveHigh),
1367    }))
1368}
1369
1370/// The type a resource is read as, for the overlap lint (W101).
1371fn read_type(r: &Resource) -> (Option<&TypeId>, Option<&TypeId>) {
1372    match &r.body {
1373        Body::Data(d) => (Some(&d.type_), None),
1374        Body::Operation(o) => (Some(&o.request), Some(&o.response)),
1375    }
1376}
1377
1378/// D1: one shape per kind token. Checked over every template that parses,
1379/// whatever else is wrong with its resource, so the codes reported do not
1380/// depend on the order lints run in.
1381fn check_shapes(file: &ContractFile, report: &mut Report) {
1382    let mut shapes: BTreeMap<(KindToken, String), &str> = BTreeMap::new();
1383    for (raw, spec) in &file.resources {
1384        let Ok(t) = Template::parse(raw) else {
1385            continue;
1386        };
1387        let token = token_of(spec.kind, spec.explicit.unwrap_or(false));
1388        let k = (token, t.shape());
1389        if let Some(first) = shapes.get(&k) {
1390            report.push(Diagnostic::error(
1391                "E021",
1392                at_res(raw),
1393                format!(
1394                    "same shape {:?} as {first:?} under the `{}` token",
1395                    t.shape(),
1396                    token.as_str()
1397                ),
1398            ));
1399        } else {
1400            shapes.insert(k, raw);
1401        }
1402    }
1403}
1404
1405/// D1: overlapping templates under one token with different types are
1406/// flagged (W101). Only resolved resources have a type to compare.
1407fn check_overlaps(resources: &[Resource], report: &mut Report) {
1408    for (i, x) in resources.iter().enumerate() {
1409        for y in &resources[i + 1..] {
1410            if x.token == y.token
1411                && x.template.overlaps(&y.template)
1412                && read_type(x) != read_type(y)
1413            {
1414                report.push(Diagnostic::warning(
1415                    "W101",
1416                    at_res(y.template.as_str()),
1417                    format!(
1418                        "overlaps {:?} under `{}` with a different type; a key resolves most-literal-first",
1419                        x.template.as_str(),
1420                        x.token.as_str()
1421                    ),
1422                ));
1423            }
1424        }
1425    }
1426}
1427
1428fn resolve_requirement(role: &str, req: &a::Requirement, cx: &mut Ctx<'_>) -> Option<Requirement> {
1429    let at = format!("requires.{role}");
1430    let before = cx.report.errors().count();
1431    if !is_ident(role) {
1432        cx.report.push(Diagnostic::error(
1433            "E030",
1434            at.clone(),
1435            format!("role {role:?} is not [a-z][a-z0-9_]*"),
1436        ));
1437    }
1438    let iface = IfaceId::from_str(&req.interface);
1439    if iface.is_err() {
1440        cx.report.push(Diagnostic::error(
1441            "E030",
1442            at.clone(),
1443            format!("interface {:?} is not <name>.v<major>", req.interface),
1444        ));
1445    }
1446    let resources = req.resources.as_ref().map(|v| {
1447        let mut v = v.clone();
1448        v.sort();
1449        v.dedup();
1450        v
1451    });
1452    for r in resources.iter().flatten() {
1453        if Template::parse(r).is_err() {
1454            cx.report.push(Diagnostic::error(
1455                "E030",
1456                at.clone(),
1457                format!("resource {r:?} is not a template"),
1458            ));
1459        }
1460    }
1461    if resources.as_ref().is_some_and(Vec::is_empty) {
1462        cx.report.push(Diagnostic::error(
1463            "E030",
1464            at.clone(),
1465            "`resources = []` consumes nothing; omit it to consume everything",
1466        ));
1467    }
1468    check_annotations(&req.annotations, &at, &cx.profiles, cx.report);
1469    if cx.report.errors().count() > before {
1470        return None;
1471    }
1472    Some(Requirement {
1473        interface: iface.ok()?,
1474        resources,
1475        cardinality: req.cardinality.unwrap_or(RequireCardinality::One),
1476        optional: req.optional,
1477        doc: req.doc.clone(),
1478        annotations: req.annotations.clone(),
1479    })
1480}
1481
1482/// Checks across a set of contracts: one file per interface id (E036), and
1483/// every requirement naming resources its interface declares, when that
1484/// interface is in the set (E035). The set is taken in the order given (a
1485/// directory's files in name order): E036 falls on each later declaration,
1486/// and E035 checks against the first (spec §9.2).
1487#[must_use]
1488pub fn check_set(contracts: &[&Contract]) -> Report {
1489    let mut report = Report::default();
1490    let mut by_id: BTreeMap<String, &Contract> = BTreeMap::new();
1491    for c in contracts {
1492        match by_id.entry(c.iface.to_string()) {
1493            std::collections::btree_map::Entry::Occupied(e) => {
1494                report.push(Diagnostic::error(
1495                    "E036",
1496                    "interface",
1497                    format!("{} is declared twice", e.key()),
1498                ));
1499            }
1500            std::collections::btree_map::Entry::Vacant(e) => {
1501                e.insert(c);
1502            }
1503        }
1504    }
1505    for c in contracts {
1506        for (role, req) in &c.requires {
1507            let Some(target) = by_id.get(&req.interface.to_string()) else {
1508                continue;
1509            };
1510            for r in req.resources.iter().flatten() {
1511                if !target.resources.iter().any(|x| x.template.as_str() == r) {
1512                    report.push(Diagnostic::error(
1513                        "E035",
1514                        format!("{}: requires.{role}", c.iface),
1515                        format!("{} declares no resource {r:?}", req.interface),
1516                    ));
1517                }
1518            }
1519        }
1520    }
1521    report
1522}
1523
1524#[cfg(test)]
1525mod tests {
1526    use super::*;
1527
1528    fn codes(src: &str) -> Vec<&'static str> {
1529        load_str(src, Path::new("."), None).report.codes()
1530    }
1531
1532    const HEAD: &str = "[interface]\nname = \"t\"\nmajor = 1\nminor = 0\n";
1533
1534    /// W105 reads the vocabulary of the major a contract uses:
1535    /// `telemetry.v2` adds `series` to `telemetry.v1`'s four keys (#983 T1).
1536    #[test]
1537    fn a_later_major_reads_its_own_vocabulary() {
1538        let src = |major: u32| {
1539            format!(
1540                "[interface]\nname = \"t\"\nmajor = 1\nminor = 0\nuses = [\"telemetry.v{major}\"]\n\
1541                 [resources.\"a\"]\nkind = \"stream\"\ntype = {{ raw = \"image/jpeg\" }}\n\
1542                 annotations = {{ \"telemetry.series\" = {{ n = {{ kind = \"counter\" }} }} }}\n"
1543            )
1544        };
1545        assert_eq!(codes(&src(1)), ["W105"]);
1546        assert!(codes(&src(2)).is_empty(), "{:?}", codes(&src(2)));
1547    }
1548
1549    #[test]
1550    fn rates_and_durations() {
1551        assert_eq!(Rate::parse("burst(12/h)"), Some(Rate::Burst(12)));
1552        for bad in ["burst(0/h)", "burst(012/h)", "burst(/h)", "often"] {
1553            assert_eq!(Rate::parse(bad), None, "{bad}");
1554        }
1555        assert_eq!(parse_duration_s("7d"), Some(604_800));
1556        assert_eq!(parse_duration_s("0s"), None);
1557        assert_eq!(parse_duration_s("7"), None);
1558    }
1559
1560    #[test]
1561    fn defaults_expand_before_resolution() {
1562        let src = format!(
1563            "{HEAD}[defaults.stream]\npriority = \"data_low\"\n\
1564             [resources.\"a\"]\nkind = \"stream\"\ntype = {{ raw = \"image/jpeg\" }}\n\
1565             [resources.\"b\"]\nkind = \"stream\"\ntype = {{ raw = \"image/jpeg\" }}\npriority = \"data_high\"\n"
1566        );
1567        let l = load_str(&src, Path::new("."), None);
1568        let c = l.contract.expect("valid");
1569        let prio = |t: &str| match &c.resource(KindToken::Stream, t).unwrap().body {
1570            Body::Data(d) => d.priority,
1571            Body::Operation(_) => unreachable!(),
1572        };
1573        assert_eq!(prio("a"), Priority::DataLow);
1574        assert_eq!(prio("b"), Priority::DataHigh);
1575    }
1576
1577    #[test]
1578    fn kind_tokens() {
1579        let src = format!(
1580            "{HEAD}[resources.\"a\"]\nkind = \"state\"\nexplicit = true\ntype = {{ raw = \"text/plain\" }}\n\
1581             [resources.\"b\"]\nkind = \"event\"\nrate = \"low\"\nretention = \"7d\"\ntype = {{ raw = \"text/plain\" }}\n"
1582        );
1583        let c = load_str(&src, Path::new("."), None)
1584            .contract
1585            .expect("valid");
1586        assert!(c.resource(KindToken::ExplicitState, "a").is_some());
1587        assert!(c.resource(KindToken::Events, "b").is_some());
1588    }
1589
1590    #[test]
1591    fn lints_have_stable_codes() {
1592        let raw = "type = { raw = \"text/plain\" }";
1593        assert_eq!(
1594            codes(&format!(
1595                "{HEAD}[resources.\"a/{{x}}\"]\nkind = \"stream\"\n{raw}\n"
1596            )),
1597            ["E011", "E013"]
1598        );
1599        assert_eq!(
1600            codes(&format!(
1601                "{HEAD}[resources.\"a\"]\nkind = \"stream\"\n{raw}\ngate = \"feature:x\"\n"
1602            )),
1603            ["E016", "E017"]
1604        );
1605        assert_eq!(
1606            codes(&format!(
1607                "{HEAD}[resources.\"a\"]\nkind = \"stream\"\nexplicit = true\nhistory = true\n{raw}\n"
1608            )),
1609            ["E019"]
1610        );
1611        assert_eq!(
1612            codes(&format!(
1613                "{HEAD}[resources.\"a\"]\nkind = \"event\"\n{raw}\n"
1614            )),
1615            ["E015", "E015"]
1616        );
1617        assert_eq!(
1618            codes(&format!(
1619                "{HEAD}[resources.\"a/{{x}}\"]\nkind = \"stream\"\nparams = {{ x = \"string\" }}\ncardinality = 4\n{raw}\n\
1620                 [resources.\"a/{{y}}\"]\nkind = \"stream\"\nparams = {{ y = \"string\" }}\ncardinality = 4\n{raw}\n"
1621            )),
1622            ["E021"]
1623        );
1624        assert_eq!(
1625            codes(&format!(
1626                "{HEAD}[resources.\"a\"]\nkind = \"stream\"\n{raw}\nannotations = {{ \"freshness.ttl_s\" = 1 }}\n"
1627            )),
1628            ["E020"]
1629        );
1630        assert_eq!(
1631            codes(&format!(
1632                "{HEAD}[resources.\"a\"]\nkind = \"stream\"\ntype = \"json:Nope\"\n"
1633            )),
1634            ["E023"]
1635        );
1636        assert_eq!(codes("[interface]\nname = \"t\"\nmajor = 1\n"), ["W104"]);
1637        assert_eq!(codes("[interface]\nname = \"t\"\n"), ["E000"]);
1638    }
1639
1640    /// `cardinality = "unbounded"` (core §2.2, 0.57; #937): the contract
1641    /// carries 4294967295, so both spellings have one fingerprint; any other
1642    /// string, a negative number or a float is not the format's shape; and
1643    /// E013 says what to write.
1644    #[test]
1645    fn cardinality_unbounded_is_the_no_ceiling_value() {
1646        let src = |card: &str| {
1647            format!(
1648                "{HEAD}[resources.\"a/{{x}}\"]\nkind = \"stream\"\nparams = {{ x = \"string\" }}\n\
1649                 {card}type = {{ raw = \"text/plain\" }}\n"
1650            )
1651        };
1652        let load = |card: &str| load_str(&src(card), Path::new("."), None);
1653        let named = load("cardinality = \"unbounded\"\n")
1654            .contract
1655            .expect("valid");
1656        let number = load("cardinality = 4294967295\n").contract.expect("valid");
1657        let r = named.resource(KindToken::Stream, "a/{x}").unwrap();
1658        assert_eq!(r.cardinality, Some(crate::budget::NO_CEILING));
1659        assert_eq!(
1660            crate::canonical::canonical_bytes(&named),
1661            crate::canonical::canonical_bytes(&number)
1662        );
1663        assert_eq!(
1664            crate::canonical::Fingerprint::of(&named),
1665            crate::canonical::Fingerprint::of(&number)
1666        );
1667        for bad in [
1668            "cardinality = \"Unbounded\"\n",
1669            "cardinality = \"many\"\n",
1670            "cardinality = \"4\"\n",
1671            "cardinality = -1\n",
1672            "cardinality = 4.0\n",
1673        ] {
1674            assert_eq!(codes(&src(bad)), ["E000"], "{bad}");
1675        }
1676        let at_least_one = load("cardinality = 0\n");
1677        for l in [load(""), at_least_one] {
1678            let d = &l.report.0;
1679            assert_eq!(d.len(), 1, "{}", l.report);
1680            assert_eq!(d[0].code, "E013");
1681            assert!(
1682                d[0].message.ends_with(
1683                    "write a number, the most members one instance will hold, or \"unbounded\""
1684                ),
1685                "{}",
1686                d[0].message
1687            );
1688        }
1689        let untemplated = format!(
1690            "{HEAD}[resources.\"a\"]\nkind = \"stream\"\ncardinality = \"unbounded\"\n\
1691             type = {{ raw = \"text/plain\" }}\n"
1692        );
1693        assert_eq!(codes(&untemplated), ["E014"]);
1694    }
1695
1696    /// W103 is judged on resolved types: an unresolved one (E023) says
1697    /// nothing about whether a JSON Schema type takes the encoding.
1698    #[test]
1699    fn w103_waits_for_the_types() {
1700        let op = |types: &str| {
1701            codes(&format!(
1702                "{HEAD}[resources.\"a\"]\nkind = \"operation\"\n{types}\nencoding = \"cbor\"\n"
1703            ))
1704        };
1705        assert_eq!(
1706            codes(&format!(
1707                "{HEAD}[resources.\"a\"]\nkind = \"stream\"\ntype = \"json:Nope\"\nencoding = \"cbor\"\n"
1708            )),
1709            ["E023"]
1710        );
1711        assert_eq!(
1712            codes(&format!(
1713                "{HEAD}[resources.\"a\"]\nkind = \"stream\"\ntype = {{ raw = \"a/b\" }}\nattachment = \"json:Nope\"\nattachment_encoding = \"cbor\"\n"
1714            )),
1715            ["E023"]
1716        );
1717        assert_eq!(
1718            codes(&format!(
1719                "{HEAD}[resources.\"a\"]\nkind = \"stream\"\ntype = {{ raw = \"a/b\" }}\nattachment_encoding = \"cbor\"\n"
1720            )),
1721            ["W103"]
1722        );
1723        let raw = "{ raw = \"a/b\" }";
1724        assert_eq!(op(&format!("request = {raw}\nresponse = {raw}")), ["W103"]);
1725        assert_eq!(
1726            op(&format!(
1727                "request = {raw}\nresponse = {raw}\nerror = \"json:Nope\""
1728            )),
1729            ["E023"]
1730        );
1731    }
1732
1733    /// Under E036, E035 checks a requirement against the first declaration
1734    /// in the order given; the later ones are the duplicates.
1735    #[test]
1736    fn a_set_checks_against_the_first_declaration() {
1737        let load = |src: String| load_str(&src, Path::new("."), None).contract.unwrap();
1738        let decl = |res: &str| {
1739            load(format!(
1740                "[interface]\nname = \"d\"\nmajor = 1\nminor = 0\n\
1741                 [resources.{res}]\nkind = \"stream\"\ntype = {{ raw = \"a/b\" }}\n"
1742            ))
1743        };
1744        let (first, second) = (decl("x"), decl("y"));
1745        let user = load(format!(
1746            "{HEAD}[requires.r]\ninterface = \"d.v1\"\nresources = [\"x\"]\n"
1747        ));
1748        assert_eq!(check_set(&[&first, &second, &user]).codes(), ["E036"]);
1749        assert_eq!(
1750            check_set(&[&second, &first, &user]).codes(),
1751            ["E035", "E036"]
1752        );
1753    }
1754
1755    #[test]
1756    fn same_shape_under_different_tokens_is_fine() {
1757        let raw = "type = { raw = \"text/plain\" }";
1758        let src = format!(
1759            "{HEAD}[resources.\"a/{{x}}\"]\nkind = \"stream\"\nparams = {{ x = \"string\" }}\ncardinality = 2\n{raw}\n\
1760             [resources.\"a/{{y}}\"]\nkind = \"state\"\nparams = {{ y = \"string\" }}\ncardinality = 2\n{raw}\n"
1761        );
1762        assert!(codes(&src).is_empty());
1763    }
1764}