Skip to main content

matter_kit/dm/
spec.rs

1//! What the specification says a cluster is (Core §7.3, and the Application Cluster library).
2//!
3//! [`meta`](crate::dm::meta) describes what *this device serves*: the attributes its handler
4//! answers, the commands it accepts. This module describes what the **specification defines**:
5//! every element the cluster has, its conformance, its access, its qualities — the whole
6//! table, whether or not any device implements all of it.
7//!
8//! The two are different things and the gap between them is where certification failures
9//! live. A device whose `ClusterDescriptor` omits a mandatory attribute, or serves one its
10//! feature map disallows, is conformant-looking and wrong; nothing in its own test suite
11//! finds it, because its own tests only exercise what it does implement.
12//! [`Cluster::validate`] is that check, and it is the reason these tables are generated from
13//! the CSA XML rather than transcribed.
14//!
15//! Everything here is `&'static` const data. A device that names one cluster links one
16//! cluster's table; the rest are dropped by the linker exactly as any other unreferenced
17//! const is.
18
19use crate::dm::conformance::{Conform, Conformance, Supports};
20use crate::dm::meta::{
21    AttributeDescriptor, ClusterDescriptor, CommandDescriptor, EventDescriptor, EventPriority,
22    Reporting,
23};
24use crate::dm::{Access, AttributeQualities};
25use crate::im::{AttributeId, ClusterId, CommandId, EventId};
26
27/// One bit of a cluster's `FeatureMap` (§7.13.2).
28#[derive(Debug, Clone, Copy)]
29pub struct Feature {
30    /// Which bit.
31    pub bit: u8,
32    /// The short code the conformance expressions name it by — "LT", "OFFONLY".
33    pub code: &'static str,
34    /// The readable name — "Lighting".
35    pub name: &'static str,
36    /// When the feature itself may be claimed. Features have conformance too: On/Off's
37    /// `Lighting` is optional *only when* `OffOnly` is absent.
38    pub conform: Conform,
39}
40
41/// One attribute, as the specification defines it.
42#[derive(Debug, Clone, Copy)]
43pub struct Attribute {
44    /// Its id.
45    pub id: AttributeId,
46    /// Its name in the specification — "StartUpOnOff".
47    pub name: &'static str,
48    /// The specification's type name, verbatim — "uint16", "StartUpOnOffEnum",
49    /// `list[TargetStruct]`. Kept as text because what a Rust program does with it is the
50    /// handler's business; the generated Rust type lives in the cluster's own module.
51    ///
52    /// **Empty** for the handful of attributes the specification lists with no type at all —
53    /// General Diagnostics' `DoNotUse`, Door Lock's `SecurityLevel`. Every one of them is
54    /// deprecated or disallowed: there is nothing to say what they were, and the conformance
55    /// already says they must not be there.
56    pub kind: &'static str,
57    /// §7.6's access column.
58    pub access: Access,
59    /// §7.12's qualities, minus the reporting policy.
60    pub qualities: AttributeQualities,
61    /// Whether and how changes are reported.
62    pub reporting: Reporting,
63    /// When the attribute may or must be present.
64    pub conform: Conform,
65}
66
67/// One command.
68#[derive(Debug, Clone, Copy)]
69pub struct Command {
70    /// Its id.
71    pub id: CommandId,
72    /// Its name in the specification — "OffWithEffect".
73    pub name: &'static str,
74    /// Whether the client sends it to the server, or the reverse. A response command is
75    /// `to_client`, and a server's *accepted* command list must not contain one.
76    pub to_server: bool,
77    /// The command that answers it, if the answer is not a bare status.
78    pub response: Option<CommandId>,
79    /// The privilege an invoke needs, and whether it must be Timed.
80    pub access: Access,
81    /// When the command may or must be present.
82    pub conform: Conform,
83}
84
85/// One event.
86#[derive(Debug, Clone, Copy)]
87pub struct Event {
88    /// Its id.
89    pub id: EventId,
90    /// Its name in the specification — "StateChanged".
91    pub name: &'static str,
92    /// Which ring of the event store it goes in (§7.14.2).
93    pub priority: EventPriority,
94    /// The privilege a read needs.
95    pub access: Access,
96    /// When the event may or must be present.
97    pub conform: Conform,
98}
99
100/// A whole cluster, as the specification defines it.
101#[derive(Debug, Clone, Copy)]
102pub struct Cluster {
103    /// Its id.
104    pub id: ClusterId,
105    /// The readable name — "On/Off".
106    pub name: &'static str,
107    /// The highest revision in the cluster's revision history, which is what
108    /// `ClusterRevision` must report (§7.13.1).
109    pub revision: u16,
110    /// The PICS code, for the certification declaration a test harness reads.
111    pub pics: &'static str,
112    /// Whether this cluster is a base or is derived from another — the Mode Base family and
113    /// the Resource Monitoring clusters are one element set behind many ids.
114    pub derived_from: Option<&'static str>,
115    /// Its `FeatureMap` bits.
116    pub features: &'static [Feature],
117    /// Every attribute it defines, sorted by id.
118    pub attributes: &'static [Attribute],
119    /// Every command, accepted and generated, sorted by id.
120    pub commands: &'static [Command],
121    /// Every event, sorted by id.
122    pub events: &'static [Event],
123}
124
125/// Something a device's configuration got wrong.
126///
127/// `#[non_exhaustive]` because the list has grown twice — `ResponseAccepted` and then
128/// `Provisional`, each because a rule turned out not to be checked anywhere — and a `match` in
129/// an integrator's build should not break the next time the specification gives this crate a
130/// reason to notice something new.
131#[derive(Debug, Clone, Copy, PartialEq, Eq)]
132#[non_exhaustive]
133pub enum Defect {
134    /// A mandatory element the device does not serve.
135    Missing(Element),
136    /// An element the device serves that its feature map disallows.
137    Disallowed(Element),
138    /// A feature bit the device claims that this cluster revision does not define.
139    UnknownFeature(u8),
140    /// The descriptor's `ClusterRevision` is not the one the specification defines.
141    WrongRevision {
142        /// What the device reports.
143        found: u16,
144        /// What the specification says.
145        expected: u16,
146    },
147    /// A response command in the accepted list, which is a command the server sends.
148    ResponseAccepted(CommandId),
149    /// An element the specification marks provisional, on a build that did not ask for them.
150    ///
151    /// Core §2.13 — and the Application Cluster and Device Library specifications' own lists —
152    /// mark a mechanism provisional when it is "not certifiable and may change". Serving one is
153    /// a deliberate act, and the `provisional` Cargo feature is where the deliberation goes; a
154    /// build without it that furnishes a `P` element is a node that cannot be certified for a
155    /// reason nobody chose.
156    Provisional(Element),
157}
158
159/// Which element a [`Defect`] is about.
160#[derive(Debug, Clone, Copy, PartialEq, Eq)]
161pub enum Element {
162    /// An attribute.
163    Attribute(AttributeId),
164    /// A command.
165    Command(CommandId),
166    /// An event.
167    Event(EventId),
168}
169
170/// A device's cluster instance, seen as a set of supported things.
171///
172/// This is the bridge between [`meta::ClusterDescriptor`](crate::dm::ClusterDescriptor) — what
173/// a device serves — and [`Conform`] — what the specification allows.
174struct Instance<'a> {
175    descriptor: &'a ClusterDescriptor<'a>,
176}
177
178impl Supports for Instance<'_> {
179    fn feature_map(&self) -> u32 {
180        self.descriptor.feature_map
181    }
182
183    fn has_attribute(&self, id: AttributeId) -> bool {
184        self.descriptor.attributes.iter().any(|a| a.id == id)
185    }
186
187    fn has_command(&self, id: CommandId) -> bool {
188        self.descriptor.accepted_commands.iter().any(|c| c.id == id) || self.generates(id)
189    }
190
191    fn has_event(&self, id: EventId) -> bool {
192        self.descriptor.events.iter().any(|e| e.id == id)
193    }
194
195    fn has_cluster(&self, _id: ClusterId) -> bool {
196        // A cluster's own conformance never refers to another cluster; a device type's does,
197        // and that check has the endpoint to answer it with.
198        false
199    }
200}
201
202impl Instance<'_> {
203    /// Whether the server sends this command.
204    ///
205    /// §7.13.5's `GeneratedCommandList` is *synthesised*: "For each client request command in
206    /// this list that mandates a response from the server, the response command SHALL be
207    /// indicated in the GeneratedCommandList", so most responses are declared once, on the
208    /// request, through [`CommandDescriptor::response`](crate::dm::CommandDescriptor). Asking
209    /// only about the explicit list would find none of them and call every response command
210    /// missing.
211    fn generates(&self, id: CommandId) -> bool {
212        self.descriptor.generated_command_ids().any(|c| c == id)
213    }
214}
215
216impl Cluster {
217    /// The feature bits this revision defines, as a mask.
218    #[must_use]
219    pub fn feature_mask(&self) -> u32 {
220        let mut mask = 0u32;
221        for feature in self.features {
222            if feature.bit < 32 {
223                mask |= 1u32 << feature.bit;
224            }
225        }
226        mask
227    }
228
229    /// The feature whose code is `code`, if this cluster has one.
230    #[must_use]
231    pub fn feature(&self, code: &str) -> Option<&Feature> {
232        self.features.iter().find(|f| f.code == code)
233    }
234
235    /// Checks a device's descriptor against the specification, reporting each defect to
236    /// `found`.
237    ///
238    /// Four kinds of mistake, and the first two are the ones a device makes by accident:
239    ///
240    /// * a **mandatory element missing** — the feature map claims `Lighting` and the
241    ///   descriptor has no `StartUpOnOff`;
242    /// * a **disallowed element present** — `StartUpOnOff` served without `Lighting`, which a
243    ///   commissioner reads as a device that does not know what it is;
244    /// * a feature bit this revision does not define;
245    /// * a `ClusterRevision` that is not the specification's.
246    ///
247    /// Elements whose conformance is [prose](Conformance::Described) are skipped in both
248    /// directions. The specification could not express the rule mechanically, so neither can
249    /// this — and guessing would produce exactly the confident-and-wrong answer that makes a
250    /// validator worth ignoring.
251    ///
252    /// A fifth is reported only on a build without the `provisional` feature: an element the
253    /// specification marks `P`, or a cluster one of the three provisional *lists* names
254    /// ([`PROVISIONAL_CLUSTERS`]).
255    pub fn validate(&self, descriptor: &ClusterDescriptor<'_>, mut found: impl FnMut(Defect)) {
256        // A cluster the Application Cluster specification calls provisional in prose. The data
257        // model does not always mark its elements `P` — `content_control` and `temperature_alarm`
258        // carry no provisional conformance at all — so serving one would otherwise be a
259        // perfectly conformant way to build a node that cannot be certified.
260        #[cfg(not(feature = "provisional"))]
261        if PROVISIONAL_CLUSTERS.iter().any(|(id, _)| *id == self.id) {
262            for attribute in descriptor.attributes {
263                found(Defect::Provisional(Element::Attribute(attribute.id)));
264            }
265        }
266        if descriptor.revision != self.revision {
267            found(Defect::WrongRevision {
268                found: descriptor.revision,
269                expected: self.revision,
270            });
271        }
272        let undefined = descriptor.feature_map & !self.feature_mask();
273        for bit in 0..32u8 {
274            if undefined & (1u32 << bit) != 0 {
275                found(Defect::UnknownFeature(bit));
276            }
277        }
278
279        let instance = Instance { descriptor };
280
281        for attribute in self.attributes {
282            let verdict = attribute.conform.verdict(&instance);
283            let present = instance.has_attribute(attribute.id);
284            check(
285                verdict,
286                present,
287                Element::Attribute(attribute.id),
288                &mut found,
289            );
290        }
291        for command in self.commands {
292            let verdict = command.conform.verdict(&instance);
293            if command.to_server {
294                let present = descriptor
295                    .accepted_commands
296                    .iter()
297                    .any(|c| c.id == command.id);
298                check(verdict, present, Element::Command(command.id), &mut found);
299            } else {
300                // A response command belongs in the *generated* list. Accepting one would
301                // advertise that a client may invoke this server's own reply.
302                //
303                // Only when the id is unambiguous. Matter scopes command ids **by
304                // direction**, and four clusters in the 1.6 library reuse one across both —
305                // Groups' `AddGroup` and `AddGroupResponse` are each `0x00`. Finding that id
306                // in the accepted list there means the *request* is accepted, which is exactly
307                // right, and reporting it would make every conformant Groups server look
308                // broken.
309                let shared = self
310                    .commands
311                    .iter()
312                    .any(|other| other.to_server && other.id == command.id);
313                if !shared
314                    && descriptor
315                        .accepted_commands
316                        .iter()
317                        .any(|c| c.id == command.id)
318                {
319                    found(Defect::ResponseAccepted(command.id));
320                }
321                let present = instance.generates(command.id);
322                check(verdict, present, Element::Command(command.id), &mut found);
323            }
324        }
325        for event in self.events {
326            let verdict = event.conform.verdict(&instance);
327            let present = instance.has_event(event.id);
328            check(verdict, present, Element::Event(event.id), &mut found);
329        }
330    }
331
332    /// Whether a descriptor has no defects at all.
333    #[must_use]
334    pub fn is_valid(&self, descriptor: &ClusterDescriptor<'_>) -> bool {
335        let mut ok = true;
336        self.validate(descriptor, |_| ok = false);
337        ok
338    }
339}
340
341/// Clusters a specification calls provisional **in prose** rather than in its conformance column.
342///
343/// Core §2.13 is a list of mechanisms and the data model marks their elements `P`, so
344/// [`Conformance::Provisional`] carries them. The Application Cluster and Device Library
345/// specifications keep lists of their own, in a paragraph — and the model does not always mark
346/// what those paragraphs name. `content_control` and `temperature_alarm` come out of the
347/// generator with no provisional conformance at all, so without this table a default build could
348/// serve either and every check here would call it conformant.
349///
350/// Hand-written, because prose is, which puts it in the same class as the rest of the
351/// hand-written specification surface and under the same drift check. Each entry cites the
352/// sentence it comes from.
353pub const PROVISIONAL_CLUSTERS: &[(ClusterId, &str)] = &[
354    // App §1.1's list: "Support for Content Control Cluster is provisional."
355    (0x050F, "App §1.1 — Content Control"),
356    // "Support for the Temperature Alarm Cluster is provisional."
357    (0x0064, "App §1.1 — Temperature Alarm"),
358    // "Support for the Ambient Context Sensing Cluster is provisional." The model does mark this
359    // one, and it is here so that the list is the whole list rather than the part that was
360    // missing — a reader checking the paragraph against this table should find every line.
361    (0x0431, "App §1.1 — Ambient Context Sensing"),
362];
363
364/// What the prose lists name and a cluster id cannot express.
365///
366/// Two things, stated so that [`PROVISIONAL_CLUSTERS`] reads as partial rather than complete.
367/// Dishwasher Alarm's five provisional *alarm bits* are values inside a bitmap attribute rather
368/// than elements of a cluster, so no conformance verdict reaches them; the check belongs in that
369/// cluster's write path. The Device Library's two device types belong to
370/// [`DeviceType::validate`](crate::dm::device::DeviceType::validate).
371///
372/// App §1.1's other two — Level Control's `Frequency` and Microwave Oven Control's
373/// `PowerInWatts` — need nothing here: the data model marks both `P` itself.
374pub const PROVISIONAL_NOT_EXPRESSIBLE: &str =
375    "App §1.1: Dishwasher Alarm's five alarm bits; DL §1.1: two device types";
376
377fn check(verdict: Conformance, present: bool, element: Element, found: &mut impl FnMut(Defect)) {
378    match verdict {
379        Conformance::Mandatory if !present => found(Defect::Missing(element)),
380        Conformance::Disallowed if present => found(Defect::Disallowed(element)),
381        // "Provisional means off" is the crate's ninth rule, and this is the only place it can
382        // be enforced rather than asserted. The `provisional` feature gates the modules whose
383        // *whole* subject is provisional — the Groupcast cluster — but most provisional elements
384        // sit inside a cluster that is otherwise certifiable, and for those the feature has
385        // nothing to gate. So the verdict does the work: a `P` element a device furnishes is a
386        // defect unless the build asked for provisional mechanisms.
387        #[cfg(not(feature = "provisional"))]
388        Conformance::Provisional if present => found(Defect::Provisional(element)),
389        _ => {}
390    }
391}
392
393// --- Building a descriptor from the specification ------------------------------------------
394
395/// The optional elements a device chooses to serve.
396///
397/// Conformance says what a device *may* have, and "may" is not derivable — an optional
398/// attribute is present because the product decided to implement it. So a device supplies its
399/// feature map, which settles the mandatory and disallowed elements, and this, which settles
400/// the rest.
401#[derive(Debug, Clone, Copy, Default)]
402pub struct Optional<'a> {
403    /// Optional attributes the device serves.
404    pub attributes: &'a [AttributeId],
405    /// Optional commands it accepts or generates.
406    pub commands: &'a [CommandId],
407    /// Optional events it may emit.
408    pub events: &'a [EventId],
409}
410
411impl Optional<'_> {
412    /// A device that implements nothing optional.
413    pub const NONE: Self = Self {
414        attributes: &[],
415        commands: &[],
416        events: &[],
417    };
418}
419
420/// A [`ClusterDescriptor`] derived from the specification's own tables.
421///
422/// The tables say which elements a feature map makes mandatory and which it forbids, so a
423/// device that states its features and its optional choices does not need to write the lists
424/// out — and cannot get them wrong. That is the failure this exists for: a hand-written
425/// descriptor whose element list does not move when its feature map does still *advertises*
426/// the elements, and a client reading `AttributeList` believes it.
427///
428/// `A`, `C`, `G` and `E` bound what the *device holds* — the attributes, accepted commands,
429/// generated commands and events conformance selected, not the size of the specification's
430/// table. Sizing one too small is [`NoSpace`](crate::ErrorCode::NoSpace), at construction,
431/// once.
432///
433/// ```
434/// use matter_kit::clusters::generated::on_off;
435/// use matter_kit::dm::spec::{Conforming, Optional};
436///
437/// // A plain On/Off server: no Lighting, so none of its four attributes.
438/// let plain = Conforming::<8, 8, 4, 4>::new(&on_off::CLUSTER, 0, &Optional::NONE)?;
439/// assert_eq!(plain.descriptor().attributes.len(), 1);
440///
441/// // The same cluster with Lighting: `StartUpOnOff` and its three companions appear, and so
442/// // do three more commands, without a line of it being written down anywhere.
443/// let lighting =
444///     Conforming::<8, 8, 4, 4>::new(&on_off::CLUSTER, on_off::feature::LIGHTING, &Optional::NONE)?;
445/// assert_eq!(lighting.descriptor().attributes.len(), 5);
446/// assert_eq!(lighting.descriptor().accepted_commands.len(), 6);
447/// # Ok::<(), matter_kit::Error>(())
448/// ```
449#[derive(Debug)]
450pub struct Conforming<const A: usize, const C: usize, const G: usize, const E: usize> {
451    id: ClusterId,
452    revision: u16,
453    feature_map: u32,
454    attributes: heapless::Vec<AttributeDescriptor, A>,
455    accepted: heapless::Vec<CommandDescriptor, C>,
456    generated: heapless::Vec<CommandId, G>,
457    events: heapless::Vec<EventDescriptor, E>,
458}
459
460/// Which entries of a specification table have been chosen, by position.
461///
462/// A bitset rather than a list of ids, because an id does not identify an entry: Matter scopes
463/// command ids by direction, and Groups, Scenes, Door Lock and Commodity Tariff each define a
464/// request and a response that share one.
465#[derive(Debug, Clone, Copy, PartialEq, Eq)]
466struct Chosen<const N: usize> {
467    bits: [bool; N],
468}
469
470impl<const N: usize> Chosen<N> {
471    const fn new() -> Self {
472        Self { bits: [false; N] }
473    }
474
475    /// Marks an entry chosen, or fails when the table is longer than the caller sized for.
476    fn set(&mut self, index: usize) -> crate::error::Result<()> {
477        match self.bits.get_mut(index) {
478            Some(slot) => {
479                *slot = true;
480                Ok(())
481            }
482            None => Err(crate::Error::new(crate::ErrorCode::NoSpace)),
483        }
484    }
485
486    fn has(&self, index: usize) -> bool {
487        self.bits.get(index).copied().unwrap_or(false)
488    }
489}
490
491/// What a candidate element set looks like to a conformance expression.
492struct Candidate<'a> {
493    feature_map: u32,
494    spec: &'a Cluster,
495    attributes: &'a Chosen<MAX_ELEMENTS>,
496    commands: &'a Chosen<MAX_ELEMENTS>,
497    events: &'a Chosen<MAX_ELEMENTS>,
498}
499
500impl Supports for Candidate<'_> {
501    fn feature_map(&self) -> u32 {
502        self.feature_map
503    }
504    fn has_attribute(&self, id: AttributeId) -> bool {
505        self.spec
506            .attributes
507            .iter()
508            .enumerate()
509            .any(|(index, a)| a.id == id && self.attributes.has(index))
510    }
511    /// A condition names a command by id alone, which is direction-agnostic, so this answers
512    /// "some chosen command has this id". No cluster that reuses an id across directions
513    /// conditions on a command, so the two readings never differ in the 1.6 library.
514    fn has_command(&self, id: CommandId) -> bool {
515        self.spec
516            .commands
517            .iter()
518            .enumerate()
519            .any(|(index, c)| c.id == id && self.commands.has(index))
520    }
521    fn has_event(&self, id: EventId) -> bool {
522        self.spec
523            .events
524            .iter()
525            .enumerate()
526            .any(|(index, e)| e.id == id && self.events.has(index))
527    }
528    fn has_cluster(&self, _id: ClusterId) -> bool {
529        false
530    }
531}
532
533/// How many times the element set may be recomputed before giving up.
534///
535/// An element's conformance may name another element, so the answer depends on the set being
536/// computed — `Attribute(x)` is true or false according to whether `x` ended up present. The
537/// dependencies in the 1.6 library are one deep, so this settles on the second pass; the
538/// margin is for a future revision, and the cap is because the specification does not promise
539/// such a system has a unique solution at all.
540const ROUNDS: usize = 8;
541
542/// How many elements of one kind a cluster may define.
543///
544/// The working set during the fixed-point search, which is sized by the *specification's*
545/// table rather than by what the caller chose to serve — so `A`, `C`, `G` and `E` keep meaning
546/// "how much the device holds" rather than "how big the cluster is". The largest tables in the
547/// 1.6 library are 65 attributes, 28 commands and 17 events; this leaves room for a revision
548/// that grows them.
549const MAX_ELEMENTS: usize = 128;
550
551impl<const A: usize, const C: usize, const G: usize, const E: usize> Conforming<A, C, G, E> {
552    /// Derives the descriptor for an instance of `spec` with this feature map.
553    ///
554    /// Returns [`InvalidArgument`](crate::ErrorCode::InvalidArgument) for a feature bit the cluster does not define —
555    /// a device claiming one is describing a cluster that does not exist — and
556    /// [`NoSpace`](crate::ErrorCode::NoSpace) when a const parameter is too small for what conformance
557    /// selected.
558    pub fn new(
559        spec: &'static Cluster,
560        feature_map: u32,
561        optional: &Optional<'_>,
562    ) -> crate::error::Result<Self> {
563        if feature_map & !spec.feature_mask() != 0 {
564            crate::error::bail!(InvalidArgument)
565        }
566
567        // Iterate to a fixed point. Each round decides every element against the previous
568        // round's set, which is what lets an attribute whose conformance names another
569        // attribute settle.
570        // Selection is by *position* in the specification's tables, never by id. Matter
571        // scopes command ids by direction, and Groups, Scenes, Door Lock and Commodity Tariff
572        // each define a request and a response sharing one — so a set of ids would silently
573        // merge them and serve whichever the filter happened to match first.
574        let mut attributes = Chosen::<MAX_ELEMENTS>::new();
575        let mut commands = Chosen::<MAX_ELEMENTS>::new();
576        let mut events = Chosen::<MAX_ELEMENTS>::new();
577        for round in 0..ROUNDS {
578            let candidate = Candidate {
579                feature_map,
580                spec,
581                attributes: &attributes,
582                commands: &commands,
583                events: &events,
584            };
585            let mut next_attributes = Chosen::<MAX_ELEMENTS>::new();
586            let mut next_commands = Chosen::<MAX_ELEMENTS>::new();
587            let mut next_events = Chosen::<MAX_ELEMENTS>::new();
588
589            for (index, attribute) in spec.attributes.iter().enumerate() {
590                if selected(
591                    attribute.conform.verdict(&candidate),
592                    optional.attributes.contains(&attribute.id),
593                ) {
594                    next_attributes.set(index)?;
595                }
596            }
597            for (index, command) in spec.commands.iter().enumerate() {
598                if selected(
599                    command.conform.verdict(&candidate),
600                    optional.commands.contains(&command.id),
601                ) {
602                    next_commands.set(index)?;
603                }
604            }
605            for (index, event) in spec.events.iter().enumerate() {
606                if selected(
607                    event.conform.verdict(&candidate),
608                    optional.events.contains(&event.id),
609                ) {
610                    next_events.set(index)?;
611                }
612            }
613
614            let settled =
615                next_attributes == attributes && next_commands == commands && next_events == events;
616            attributes = next_attributes;
617            commands = next_commands;
618            events = next_events;
619            if settled {
620                break;
621            }
622            if round == ROUNDS - 1 {
623                // The conformance did not settle. Better to refuse than to ship whichever
624                // half of an oscillation the loop happened to stop on.
625                crate::error::bail!(InvalidState)
626            }
627        }
628
629        let mut this = Self {
630            id: spec.id,
631            revision: spec.revision,
632            feature_map,
633            attributes: heapless::Vec::new(),
634            accepted: heapless::Vec::new(),
635            generated: heapless::Vec::new(),
636            events: heapless::Vec::new(),
637        };
638        for (_, attribute) in spec
639            .attributes
640            .iter()
641            .enumerate()
642            .filter(|(index, _)| attributes.has(*index))
643        {
644            this.attributes
645                .push(AttributeDescriptor {
646                    id: attribute.id,
647                    access: attribute.access,
648                    reporting: attribute.reporting,
649                    qualities: attribute.qualities,
650                })
651                .map_err(|_| crate::Error::new(crate::ErrorCode::NoSpace))?;
652        }
653        for (_, command) in spec
654            .commands
655            .iter()
656            .enumerate()
657            .filter(|(index, _)| commands.has(*index))
658        {
659            if command.to_server {
660                this.accepted
661                    .push(CommandDescriptor {
662                        id: command.id,
663                        access: command.access,
664                        // Left `None`: §7.13.5's list is synthesised from it, and the
665                        // responses are already selected in their own right below. Declaring
666                        // them here as well would list each one twice.
667                        response: None,
668                    })
669                    .map_err(|_| crate::Error::new(crate::ErrorCode::NoSpace))?;
670            } else {
671                this.generated
672                    .push(command.id)
673                    .map_err(|_| crate::Error::new(crate::ErrorCode::NoSpace))?;
674            }
675        }
676        for (_, event) in spec
677            .events
678            .iter()
679            .enumerate()
680            .filter(|(index, _)| events.has(*index))
681        {
682            this.events
683                .push(EventDescriptor {
684                    id: event.id,
685                    access: event.access,
686                    priority: event.priority,
687                })
688                .map_err(|_| crate::Error::new(crate::ErrorCode::NoSpace))?;
689        }
690        Ok(this)
691    }
692
693    /// The descriptor, borrowed from this storage.
694    #[must_use]
695    pub fn descriptor(&self) -> ClusterDescriptor<'_> {
696        ClusterDescriptor {
697            id: self.id,
698            revision: self.revision,
699            feature_map: self.feature_map,
700            attributes: &self.attributes,
701            accepted_commands: &self.accepted,
702            generated_commands: &self.generated,
703            events: &self.events,
704        }
705    }
706}
707
708/// Whether an element with this verdict is served.
709///
710/// `Provisional` and `Deprecated` are treated as optional *here*: neither is forbidden, and both
711/// are a decision the product makes rather than one the conformance makes for it. Whether the
712/// product was allowed to make that decision is [`check`]'s question, not this one — a `P`
713/// element furnished by a build without the `provisional` feature is a [`Defect::Provisional`].
714/// `Described` is *not* selected — the specification could not express the rule, so a device
715/// that needs the element names it in [`Optional`] and takes responsibility for reading the
716/// prose.
717const fn selected(verdict: Conformance, chosen: bool) -> bool {
718    match verdict {
719        Conformance::Mandatory => true,
720        Conformance::Optional
721        | Conformance::Provisional
722        | Conformance::Deprecated
723        | Conformance::Described => chosen,
724        Conformance::Disallowed => false,
725    }
726}