Skip to main content

matter_kit/dm/
conformance.rs

1//! Conformance: what the specification says may, must, or must not be present (Core §7.3).
2//!
3//! Every element of every cluster carries one of these, and it is the part of the data model
4//! nobody transcribes correctly by hand. On/Off's `StartUpOnOff` is mandatory *when the
5//! Lighting feature is set* and forbidden otherwise; its `On` command is mandatory *unless*
6//! `OffOnly` is; Level Control's `CurrentFrequency` is mandatory with `FQ` and disallowed
7//! without it. There are several thousand such rules in the 1.6 library, and a device whose
8//! descriptors disagree with them is one that fails certification for a reason no test in the
9//! device's own suite would find.
10//!
11//! # Why it is a tree rather than a flag
12//!
13//! The conformance column is a small language, not a keyword. These are all real:
14//!
15//! ```text
16//! M                         always
17//! [LT]                      optional when Lighting
18//! !OFFONLY                  mandatory unless OffOnly
19//! LT & !DF                  mandatory when Lighting and not DeadFrontBehavior
20//! MSCH | MSFT, [MSSCH]      mandatory when either; otherwise optional when MSSCH
21//! ```
22//!
23//! So an element's conformance is an ordered list of [`Clause`]s — the specification's
24//! "otherwise" chain — each a verdict and the [`Condition`] under which it applies. The first
25//! clause whose condition holds decides, and an element no clause selects is **disallowed**.
26//! That last rule is the one worth stating plainly: `[LT]` does not mean "optional, and by the
27//! way there is a feature"; it means the element may exist only when Lighting does.
28//!
29//! # What this is for
30//!
31//! Two things, and the second is the reason it exists at all.
32//!
33//! A **device can be checked against its own claims**: given the feature map an endpoint
34//! declares, [`spec::Cluster::validate`](crate::dm::spec::Cluster::validate) says whether the attributes, commands and events it serves
35//! are the set the specification permits. A missing mandatory element, or a present disallowed
36//! one, is found at construction rather than by a certification lab.
37//!
38//! And a **client can reason about a peer** without a table of special cases: the same
39//! evaluation over a `FeatureMap` read off the wire says what that node must be able to do.
40
41use crate::im::{AttributeId, ClusterId, CommandId, EventId};
42
43/// What the specification says about an element's presence.
44///
45/// Four of the five are decisions; `Described` is the refusal to make one, and
46/// [`Cluster::validate`](crate::dm::spec::Cluster::validate) is where all five are acted on.
47#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
48pub enum Conformance {
49    /// `M` — the element SHALL be present.
50    Mandatory,
51    /// `O` — the element MAY be present.
52    Optional,
53    /// `P` — provisional. Not certifiable, and may change in a dot revision.
54    ///
55    /// Three lists say what is provisional: Core §2.13, and the Application Cluster and Device
56    /// Library specifications' own. A device *may* serve one, so this behaves as
57    /// [`Optional`](Conformance::Optional) when the `provisional` feature is on — and
58    /// [`Cluster::validate`](crate::dm::spec::Cluster::validate) reports
59    /// [`Defect::Provisional`](crate::dm::spec::Defect::Provisional) when it is not, because a
60    /// certifiable build is the default build.
61    Provisional,
62    /// `D` — deprecated. Present for compatibility with an earlier revision, and not to be
63    /// implemented in anything new.
64    Deprecated,
65    /// `X` — the element SHALL NOT be present.
66    Disallowed,
67    /// `desc` — the rule is prose the XML could not express, so the specification's own words
68    /// decide. Neither permitted nor forbidden mechanically; a validator must not guess.
69    Described,
70}
71
72// There is deliberately no `is_permitted`/`is_required` pair here, convenient as one would look.
73// `Described` is not a boolean in either direction — the specification's own words decide, which
74// is why `Cluster::validate` skips those elements instead of judging them — so a predicate would
75// have to answer `false` for it, and `false` reads as "forbidden". That is a guess in exactly
76// the direction the verdict exists to refuse.
77//
78// An element's conformance is asked through
79// [`Cluster::validate`](crate::dm::spec::Cluster::validate), which has all three answers and a
80// place to put the third.
81
82/// What an element's presence depends on.
83///
84/// Borrowed rather than owned throughout: the whole tree is `const` data generated from the
85/// CSA XML, so a condition is a `&'static Condition` and costs nothing at runtime.
86#[derive(Debug, Clone, Copy, PartialEq, Eq)]
87pub enum Condition {
88    /// Unconditional.
89    Always,
90    /// A feature bit of this cluster's `FeatureMap`.
91    Feature(u8),
92    /// Another attribute of this cluster being present.
93    Attribute(AttributeId),
94    /// A command of this cluster being present.
95    Command(CommandId),
96    /// An event of this cluster being present.
97    Event(EventId),
98    /// Another cluster on the same endpoint — how a device type says "Level Control, if you
99    /// have On/Off".
100    Cluster(ClusterId),
101    /// A named condition the XML does not define in terms of anything else — "Zigbee",
102    /// "Matter", "LargeMessageTransport". A validator cannot evaluate these, so an element
103    /// that depends on one is [`Conformance::Described`] rather than guessed at.
104    Named(&'static str),
105    /// Logical negation.
106    Not(&'static Condition),
107    /// Every term must hold.
108    All(&'static [Condition]),
109    /// Some term must hold.
110    Any(&'static [Condition]),
111    /// Exactly one term must hold. Rare, and the reason `Any` cannot simply be reused.
112    ExactlyOne(&'static [Condition]),
113}
114
115/// What a device says it supports, so a [`Condition`] can be evaluated against it.
116///
117/// A trait rather than a bare feature map because the conditions are not all about features:
118/// an attribute's conformance may depend on another attribute being served, and a device
119/// type's on a cluster being present.
120pub trait Supports {
121    /// The cluster's `FeatureMap`.
122    fn feature_map(&self) -> u32;
123
124    /// Whether the endpoint serves an attribute of this cluster.
125    fn has_attribute(&self, id: AttributeId) -> bool;
126
127    /// Whether the endpoint serves a command of this cluster.
128    fn has_command(&self, id: CommandId) -> bool;
129
130    /// Whether the endpoint serves an event of this cluster.
131    fn has_event(&self, id: EventId) -> bool;
132
133    /// Whether the endpoint serves another cluster.
134    fn has_cluster(&self, id: ClusterId) -> bool;
135
136    /// Whether a named condition holds. The default is "unknown", which is what makes an
137    /// element depending on one [`Conformance::Described`] rather than silently absent.
138    fn named(&self, _name: &str) -> Option<bool> {
139        None
140    }
141}
142
143/// Evaluating a condition has three outcomes, not two.
144#[derive(Debug, Clone, Copy, PartialEq, Eq)]
145enum Truth {
146    True,
147    False,
148    /// A named condition this device cannot answer. It poisons the whole expression: a
149    /// validator that guessed would either demand an element the device is right not to have
150    /// or permit one it must not.
151    Unknown,
152}
153
154impl Truth {
155    const fn not(self) -> Self {
156        match self {
157            Self::True => Self::False,
158            Self::False => Self::True,
159            Self::Unknown => Self::Unknown,
160        }
161    }
162}
163
164impl Condition {
165    /// Evaluates the condition against what a device supports.
166    fn eval<S: Supports + ?Sized>(&self, device: &S) -> Truth {
167        match self {
168            Self::Always => Truth::True,
169            Self::Feature(bit) => {
170                // A bit beyond the map's width is a feature this revision does not define.
171                if *bit >= 32 {
172                    return Truth::False;
173                }
174                if device.feature_map() & (1u32 << *bit) != 0 {
175                    Truth::True
176                } else {
177                    Truth::False
178                }
179            }
180            Self::Attribute(id) => Truth::from(device.has_attribute(*id)),
181            Self::Command(id) => Truth::from(device.has_command(*id)),
182            Self::Event(id) => Truth::from(device.has_event(*id)),
183            Self::Cluster(id) => Truth::from(device.has_cluster(*id)),
184            Self::Named(name) => device.named(name).map_or(Truth::Unknown, Truth::from),
185            Self::Not(inner) => inner.eval(device).not(),
186            Self::All(terms) => {
187                // A single false settles it even with unknowns present, which is why this is
188                // not a fold over booleans.
189                let mut unknown = false;
190                for term in *terms {
191                    match term.eval(device) {
192                        Truth::False => return Truth::False,
193                        Truth::Unknown => unknown = true,
194                        Truth::True => {}
195                    }
196                }
197                if unknown { Truth::Unknown } else { Truth::True }
198            }
199            Self::Any(terms) => {
200                let mut unknown = false;
201                for term in *terms {
202                    match term.eval(device) {
203                        Truth::True => return Truth::True,
204                        Truth::Unknown => unknown = true,
205                        Truth::False => {}
206                    }
207                }
208                if unknown {
209                    Truth::Unknown
210                } else {
211                    Truth::False
212                }
213            }
214            Self::ExactlyOne(terms) => {
215                let mut count = 0usize;
216                for term in *terms {
217                    match term.eval(device) {
218                        Truth::True => count = count.saturating_add(1),
219                        Truth::Unknown => return Truth::Unknown,
220                        Truth::False => {}
221                    }
222                }
223                Truth::from(count == 1)
224            }
225        }
226    }
227}
228
229impl From<bool> for Truth {
230    fn from(value: bool) -> Self {
231        if value { Self::True } else { Self::False }
232    }
233}
234
235/// One branch of a conformance expression: a verdict and when it applies.
236#[derive(Debug, Clone, Copy, PartialEq, Eq)]
237pub struct Clause {
238    /// What the element is when this clause is selected.
239    pub verdict: Conformance,
240    /// When it is selected.
241    pub when: Condition,
242}
243
244impl Clause {
245    /// An unconditional clause.
246    #[must_use]
247    pub const fn always(verdict: Conformance) -> Self {
248        Self {
249            verdict,
250            when: Condition::Always,
251        }
252    }
253}
254
255/// An element's complete conformance — the specification's "otherwise" chain.
256///
257/// The first clause whose condition holds decides. An element no clause selects is
258/// [`Conformance::Disallowed`]: `[LT]` does not mean "optional, and incidentally there is a
259/// feature", it means the element may exist only when Lighting does.
260#[derive(Debug, Clone, Copy, PartialEq, Eq)]
261pub struct Conform {
262    /// The clauses, in the order the specification wrote them.
263    pub clauses: &'static [Clause],
264}
265
266impl Conform {
267    /// `M` — mandatory, unconditionally.
268    pub const MANDATORY: Self = Self {
269        clauses: &[Clause::always(Conformance::Mandatory)],
270    };
271    /// `O` — optional, unconditionally.
272    pub const OPTIONAL: Self = Self {
273        clauses: &[Clause::always(Conformance::Optional)],
274    };
275    /// `X` — disallowed.
276    pub const DISALLOWED: Self = Self {
277        clauses: &[Clause::always(Conformance::Disallowed)],
278    };
279    /// `desc` — the rule is prose.
280    pub const DESCRIBED: Self = Self {
281        clauses: &[Clause::always(Conformance::Described)],
282    };
283
284    /// The verdict for a device that supports what `device` says it does.
285    #[must_use]
286    pub fn verdict<S: Supports + ?Sized>(&self, device: &S) -> Conformance {
287        for clause in self.clauses {
288            match clause.when.eval(device) {
289                Truth::True => return clause.verdict,
290                // An unanswerable condition makes the whole element's status prose, because
291                // the specification's own words are the only thing that can settle it.
292                Truth::Unknown => return Conformance::Described,
293                Truth::False => {}
294            }
295        }
296        // No clause applied. §7.3: an element the conformance does not select SHALL NOT be
297        // present — which is what makes `[LT]` a statement about existence rather than
298        // optionality.
299        Conformance::Disallowed
300    }
301}