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 (Core §2.13). Not certifiable, and may change in a 1.6.x revision,
54 /// so this crate treats it as optional but gates it behind the `provisional` feature.
55 Provisional,
56 /// `D` — deprecated. Present for compatibility with an earlier revision, and not to be
57 /// implemented in anything new.
58 Deprecated,
59 /// `X` — the element SHALL NOT be present.
60 Disallowed,
61 /// `desc` — the rule is prose the XML could not express, so the specification's own words
62 /// decide. Neither permitted nor forbidden mechanically; a validator must not guess.
63 Described,
64}
65
66// There is deliberately no `is_permitted`/`is_required` pair here, convenient as one would look.
67// `Described` is not a boolean in either direction — the specification's own words decide, which
68// is why `Cluster::validate` skips those elements instead of judging them — so a predicate would
69// have to answer `false` for it, and `false` reads as "forbidden". That is a guess in exactly
70// the direction the verdict exists to refuse.
71//
72// An element's conformance is asked through
73// [`Cluster::validate`](crate::dm::spec::Cluster::validate), which has all three answers and a
74// place to put the third.
75
76/// What an element's presence depends on.
77///
78/// Borrowed rather than owned throughout: the whole tree is `const` data generated from the
79/// CSA XML, so a condition is a `&'static Condition` and costs nothing at runtime.
80#[derive(Debug, Clone, Copy, PartialEq, Eq)]
81pub enum Condition {
82 /// Unconditional.
83 Always,
84 /// A feature bit of this cluster's `FeatureMap`.
85 Feature(u8),
86 /// Another attribute of this cluster being present.
87 Attribute(AttributeId),
88 /// A command of this cluster being present.
89 Command(CommandId),
90 /// An event of this cluster being present.
91 Event(EventId),
92 /// Another cluster on the same endpoint — how a device type says "Level Control, if you
93 /// have On/Off".
94 Cluster(ClusterId),
95 /// A named condition the XML does not define in terms of anything else — "Zigbee",
96 /// "Matter", "LargeMessageTransport". A validator cannot evaluate these, so an element
97 /// that depends on one is [`Conformance::Described`] rather than guessed at.
98 Named(&'static str),
99 /// Logical negation.
100 Not(&'static Condition),
101 /// Every term must hold.
102 All(&'static [Condition]),
103 /// Some term must hold.
104 Any(&'static [Condition]),
105 /// Exactly one term must hold. Rare, and the reason `Any` cannot simply be reused.
106 ExactlyOne(&'static [Condition]),
107}
108
109/// What a device says it supports, so a [`Condition`] can be evaluated against it.
110///
111/// A trait rather than a bare feature map because the conditions are not all about features:
112/// an attribute's conformance may depend on another attribute being served, and a device
113/// type's on a cluster being present.
114pub trait Supports {
115 /// The cluster's `FeatureMap`.
116 fn feature_map(&self) -> u32;
117
118 /// Whether the endpoint serves an attribute of this cluster.
119 fn has_attribute(&self, id: AttributeId) -> bool;
120
121 /// Whether the endpoint serves a command of this cluster.
122 fn has_command(&self, id: CommandId) -> bool;
123
124 /// Whether the endpoint serves an event of this cluster.
125 fn has_event(&self, id: EventId) -> bool;
126
127 /// Whether the endpoint serves another cluster.
128 fn has_cluster(&self, id: ClusterId) -> bool;
129
130 /// Whether a named condition holds. The default is "unknown", which is what makes an
131 /// element depending on one [`Conformance::Described`] rather than silently absent.
132 fn named(&self, _name: &str) -> Option<bool> {
133 None
134 }
135}
136
137/// Evaluating a condition has three outcomes, not two.
138#[derive(Debug, Clone, Copy, PartialEq, Eq)]
139enum Truth {
140 True,
141 False,
142 /// A named condition this device cannot answer. It poisons the whole expression: a
143 /// validator that guessed would either demand an element the device is right not to have
144 /// or permit one it must not.
145 Unknown,
146}
147
148impl Truth {
149 const fn not(self) -> Self {
150 match self {
151 Self::True => Self::False,
152 Self::False => Self::True,
153 Self::Unknown => Self::Unknown,
154 }
155 }
156}
157
158impl Condition {
159 /// Evaluates the condition against what a device supports.
160 fn eval<S: Supports + ?Sized>(&self, device: &S) -> Truth {
161 match self {
162 Self::Always => Truth::True,
163 Self::Feature(bit) => {
164 // A bit beyond the map's width is a feature this revision does not define.
165 if *bit >= 32 {
166 return Truth::False;
167 }
168 if device.feature_map() & (1u32 << *bit) != 0 {
169 Truth::True
170 } else {
171 Truth::False
172 }
173 }
174 Self::Attribute(id) => Truth::from(device.has_attribute(*id)),
175 Self::Command(id) => Truth::from(device.has_command(*id)),
176 Self::Event(id) => Truth::from(device.has_event(*id)),
177 Self::Cluster(id) => Truth::from(device.has_cluster(*id)),
178 Self::Named(name) => device.named(name).map_or(Truth::Unknown, Truth::from),
179 Self::Not(inner) => inner.eval(device).not(),
180 Self::All(terms) => {
181 // A single false settles it even with unknowns present, which is why this is
182 // not a fold over booleans.
183 let mut unknown = false;
184 for term in *terms {
185 match term.eval(device) {
186 Truth::False => return Truth::False,
187 Truth::Unknown => unknown = true,
188 Truth::True => {}
189 }
190 }
191 if unknown { Truth::Unknown } else { Truth::True }
192 }
193 Self::Any(terms) => {
194 let mut unknown = false;
195 for term in *terms {
196 match term.eval(device) {
197 Truth::True => return Truth::True,
198 Truth::Unknown => unknown = true,
199 Truth::False => {}
200 }
201 }
202 if unknown {
203 Truth::Unknown
204 } else {
205 Truth::False
206 }
207 }
208 Self::ExactlyOne(terms) => {
209 let mut count = 0usize;
210 for term in *terms {
211 match term.eval(device) {
212 Truth::True => count = count.saturating_add(1),
213 Truth::Unknown => return Truth::Unknown,
214 Truth::False => {}
215 }
216 }
217 Truth::from(count == 1)
218 }
219 }
220 }
221}
222
223impl From<bool> for Truth {
224 fn from(value: bool) -> Self {
225 if value { Self::True } else { Self::False }
226 }
227}
228
229/// One branch of a conformance expression: a verdict and when it applies.
230#[derive(Debug, Clone, Copy, PartialEq, Eq)]
231pub struct Clause {
232 /// What the element is when this clause is selected.
233 pub verdict: Conformance,
234 /// When it is selected.
235 pub when: Condition,
236}
237
238impl Clause {
239 /// An unconditional clause.
240 #[must_use]
241 pub const fn always(verdict: Conformance) -> Self {
242 Self {
243 verdict,
244 when: Condition::Always,
245 }
246 }
247}
248
249/// An element's complete conformance — the specification's "otherwise" chain.
250///
251/// The first clause whose condition holds decides. An element no clause selects is
252/// [`Conformance::Disallowed`]: `[LT]` does not mean "optional, and incidentally there is a
253/// feature", it means the element may exist only when Lighting does.
254#[derive(Debug, Clone, Copy, PartialEq, Eq)]
255pub struct Conform {
256 /// The clauses, in the order the specification wrote them.
257 pub clauses: &'static [Clause],
258}
259
260impl Conform {
261 /// `M` — mandatory, unconditionally.
262 pub const MANDATORY: Self = Self {
263 clauses: &[Clause::always(Conformance::Mandatory)],
264 };
265 /// `O` — optional, unconditionally.
266 pub const OPTIONAL: Self = Self {
267 clauses: &[Clause::always(Conformance::Optional)],
268 };
269 /// `X` — disallowed.
270 pub const DISALLOWED: Self = Self {
271 clauses: &[Clause::always(Conformance::Disallowed)],
272 };
273 /// `desc` — the rule is prose.
274 pub const DESCRIBED: Self = Self {
275 clauses: &[Clause::always(Conformance::Described)],
276 };
277
278 /// The verdict for a device that supports what `device` says it does.
279 #[must_use]
280 pub fn verdict<S: Supports + ?Sized>(&self, device: &S) -> Conformance {
281 for clause in self.clauses {
282 match clause.when.eval(device) {
283 Truth::True => return clause.verdict,
284 // An unanswerable condition makes the whole element's status prose, because
285 // the specification's own words are the only thing that can settle it.
286 Truth::Unknown => return Conformance::Described,
287 Truth::False => {}
288 }
289 }
290 // No clause applied. §7.3: an element the conformance does not select SHALL NOT be
291 // present — which is what makes `[LT]` a statement about existence rather than
292 // optionality.
293 Conformance::Disallowed
294 }
295}