knx-catalog 0.0.8

Reviewed KNX datapoint-type catalogue as const data
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
//! Declarative row and descriptor types for the catalogue.
//!
//! These types hold the declarative record of each subtype - a
//! restatement where the KNX source is plain, and the reading this
//! catalogue settled on where the source is silent, ambiguous or
//! prints figures that disagree - in a shape a consumer can read
//! without heap allocation or runtime text parsing. The types
//! deliberately distinguish structural dimensions the source
//! distinguishes - fixed fields, fixed arrays, repeated fixed-width
//! groups, genuinely variable length, reserved bits, named bits, special
//! values with distinct kinds - rather than collapsing them into a single
//! width number.

use core::fmt;

use crate::id::DptId;

/// The transmitted width contract of a subtype.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum PayloadWidth {
    /// A fixed width shorter than one octet, transmitted on the low bit
    /// positions of a data octet under the carrier rule for short types.
    Bits(u8),
    /// A fixed width in octets.
    Octets(u16),
    /// A variable octet count, bounded by the transport rather than by the
    /// type.
    Variable,
}

/// An exact decimal number: `num * 10^exp`.
///
/// The source declares ranges and resolutions in decimal; a scaled integer
/// keeps them exact where a binary float would approximate.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub struct Decimal {
    /// The scaled integer value.
    pub num: i64,
    /// The power of ten the value is scaled by.
    pub exp: i8,
}

impl Decimal {
    /// The value scaled to the given exponent, when that scaling fits
    /// an `i128`.
    fn scaled_to(self, exp: i8) -> Option<i128> {
        let shift = u32::try_from(i32::from(self.exp) - i32::from(exp)).ok()?;
        10i128.checked_pow(shift).and_then(|scale| i128::from(self.num).checked_mul(scale))
    }

    /// Compares two decimals by numeric value, exactly, for any
    /// exponent pair: a scaling that cannot be represented is decided
    /// by sign, because the unscalable side's magnitude necessarily
    /// exceeds the other's.
    pub fn value_cmp(self, other: Decimal) -> core::cmp::Ordering {
        use core::cmp::Ordering;
        if self.num == 0 || other.num == 0 || (self.num < 0) != (other.num < 0) {
            return self.num.cmp(&other.num);
        }
        // The side at the minimum exponent scales by 10^0 and always
        // fits, so at most one scaling can overflow - and a nonzero
        // value whose scaling overflows i128 necessarily exceeds the
        // other side's magnitude.
        let exp = self.exp.min(other.exp);
        match (self.scaled_to(exp), other.scaled_to(exp)) {
            (Some(left), Some(right)) => left.cmp(&right),
            (None, _) => {
                if self.num > 0 {
                    Ordering::Greater
                } else {
                    Ordering::Less
                }
            }
            (_, None) => {
                if other.num > 0 {
                    Ordering::Less
                } else {
                    Ordering::Greater
                }
            }
        }
    }

    /// The exact quotient of this value by `divisor`, when the division
    /// is exact, every intermediate fits, and the result fits an `i64`.
    ///
    /// `None` means the value is off the divisor's grid - whether
    /// because the division leaves a remainder or because a scaling
    /// cannot be represented; an unscalable magnitude is off every
    /// field grid, so `None` is the honest answer either way.
    pub fn exact_quotient(self, divisor: Decimal) -> Option<i64> {
        if divisor.num == 0 {
            return None;
        }
        if self.num == 0 {
            // Zero is on every grid whatever the exponents; the
            // scaling below could overflow on the divisor's side.
            return Some(0);
        }
        let exp = self.exp.min(divisor.exp);
        let left = self.scaled_to(exp)?;
        let right = divisor.scaled_to(exp)?;
        if left % right != 0 {
            return None;
        }
        i64::try_from(left / right).ok()
    }

    /// A binary floating-point approximation; exact wherever the
    /// scaling power of ten is exactly representable (every catalogued
    /// exponent is).
    ///
    /// A representation conversion only - the exact decimal remains the
    /// recorded fact; a caller doing floating arithmetic opts into the
    /// one rounding step here.
    pub fn to_f64(self) -> f64 {
        let mut scale = 1.0f64;
        for _ in 0..self.exp.unsigned_abs() {
            scale *= 10.0;
        }
        let num = self.num as f64;
        if self.exp >= 0 {
            num * scale
        } else {
            num / scale
        }
    }
}

/// Canonical decimal rendering: the exact value, a `.` only where the
/// exponent is negative, no exponent notation and no trimming.
impl fmt::Display for Decimal {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        if self.exp >= 0 {
            write!(formatter, "{}", self.num)?;
            if self.num != 0 {
                for _ in 0..self.exp {
                    formatter.write_str("0")?;
                }
            }
            return Ok(());
        }
        if self.num < 0 {
            formatter.write_str("-")?;
        }
        let magnitude = self.num.unsigned_abs();
        let places = usize::from(self.exp.unsigned_abs());
        let mut digits = 1usize;
        let mut probe = magnitude;
        while probe >= 10 {
            probe /= 10;
            digits += 1;
        }
        if digits > places {
            // `places < digits <= 20`, so the split power fits u64.
            let split = 10u64.pow(places as u32);
            write!(
                formatter,
                "{}.{:0places$}",
                magnitude / split,
                magnitude % split,
                places = places
            )
        } else {
            formatter.write_str("0.")?;
            for _ in 0..(places - digits) {
                formatter.write_str("0")?;
            }
            write!(formatter, "{magnitude}")
        }
    }
}

/// The declared numeric range of a subtype's value.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum DeclaredRange {
    /// The numeric range the reviewed data records for this field.
    /// Where the source prints one range plainly this restates it;
    /// where the source is silent, ambiguous, or prints figures that
    /// disagree, it is the reading this catalogue settled on, not a
    /// further source statement.
    ///
    /// Whether either direction judges against it follows the field's
    /// carrier, so recording a range is not by itself a bound. On the
    /// unsigned, signed and float carriers it is one: interpretation
    /// refuses a value outside it and so does composition - except
    /// under a linear mapping, which runs the encodable span onto it,
    /// so composition refuses a value outside it and interpretation
    /// produces none to refuse. The binary32 carrier keeps 1
    /// deliberate asymmetry: a NaN is never outside a range on the
    /// interpret side, which reports what the octets carry, and is
    /// always outside one on the compose side, which refuses to
    /// transmit it. No catalogued row exercises that asymmetry - no
    /// catalogued binary32 row records a range at all. On the boolean and
    /// enumerated carriers neither direction reads the range: a
    /// boolean's 2 states and a declared code table are those fields'
    /// whole domains. Generation still reads it there, checking every
    /// code the declared table defines against it; how many rows
    /// record both is a measured count, not a figure repeated here.
    Declared {
        /// The declared minimum.
        min: Decimal,
        /// The declared maximum.
        max: Decimal,
    },
    /// The reviewed data records no range for this field. A recorded
    /// absence, not zero - and, like a recorded range, a fact about
    /// the record rather than a further statement about what the
    /// source prints.
    NotDeclared,
}

/// A declared resolution.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub struct Resolution {
    /// The step value.
    pub value: Decimal,
    /// Whether the recorded step is an approximation. Set where the
    /// source prints the figure as approximate; clear where it prints
    /// an exact one, and clear where the figure is the reading this
    /// catalogue settled on rather than a printed figure.
    pub approximate: bool,
}

/// The kind of special encoded value, as the source distinguishes them.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum SpecialKind {
    /// The encoded value marks the carried data as invalid.
    ValueState,
    /// The encoded value directs the receiver's handling of the
    /// message; the source-assigned disposition rides the kind, so a
    /// receiver-disposition special without one cannot exist.
    ReceiverDisposition(ReceiveDisposition),
    /// The value's meaning depends on a sibling validity flag.
    FlagConditioned,
}

/// A receiver disposition the source assigns to declared data.
///
/// The vocabulary carries exactly the dispositions catalogued rows
/// declare and interpretation returns. Rejection needs no declared
/// data: an undeclared code or pattern already fails closed. The
/// source assigns further dispositions at other layers (refuse the
/// read, truncate, neglect the frame); those are not catalogue data
/// and no row can declare them. A population row declaring a
/// disposition outside this vocabulary is a source question that
/// extends it through review.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum ReceiveDisposition {
    /// Ignore the whole message.
    IgnoreMessage,
    /// Accept the message without acting on it.
    AcceptWithoutAction,
}

/// A special encoded value the reviewed data records beside the
/// field's ordinary domain: singled out by the source where the source
/// singles one out, and the reading this catalogue settled on where a
/// printed reference supplies it instead.
///
/// The kind carries the whole behavioral contract; any human-readable
/// designation is a projection concern derived from it.
#[derive(Debug)]
pub struct SpecialValue {
    /// The encoded value, as transmitted.
    pub raw: u32,
    /// Which kind of special value this is.
    pub kind: SpecialKind,
}

/// One defined code in an enumeration code table.
#[derive(Debug)]
pub struct CodeEntry {
    /// The encoded code.
    pub code: u16,
    /// A short human-readable name for the code. It is not part of the
    /// encoding: match on `code`, never on this text, because a label may
    /// be reworded between releases without the code's meaning changing.
    ///
    /// Some enumerations define their extent by a range rather than by
    /// naming every member - 10.001's `Day` is one - and the labels
    /// between the named anchors are derived from that range.
    pub label: &'static str,
}

/// A band of codes that share one collective meaning.
#[derive(Debug)]
pub struct CodeBand {
    /// The first code of the band, inclusive.
    pub start: u16,
    /// The last code of the band, inclusive.
    pub end: u16,
    /// A short human-readable name for what the whole band means. It is
    /// not part of the encoding: match on the range, never on this text.
    pub label: &'static str,
    /// The receiver disposition the source assigns to the band, where
    /// it states one. What silence does depends on the carrier the band
    /// sits beside: on an enumerated carrier an undeclared band's codes
    /// fail closed, while on an unsigned carrier the band only labels
    /// values the declared range already carries and nothing refuses
    /// (3.007's Step band is the precedent for the second reading).
    pub disposition: Option<ReceiveDisposition>,
}

/// An enumeration code table: a set of defined codes, possibly sparse,
/// with source-stated bands over the remaining code space.
///
/// A code domain is a set, never a range with a default.
#[derive(Debug)]
pub struct CodeTable {
    /// The defined codes.
    pub entries: &'static [CodeEntry],
    /// Source-stated bands over the remaining code space.
    pub bands: &'static [CodeBand],
}

/// A named bit in a bit-set layout.
#[derive(Debug)]
pub struct NamedBit {
    /// The bit position, 0 = least significant.
    pub bit: u8,
    /// A short name for the bit. It is not part of the encoding: match
    /// on `bit`, never on this text.
    pub name: &'static str,
    /// The encoded value at which the named condition holds. The source
    /// states inverted polarities explicitly, so this is per-declaration
    /// data rather than a convention.
    pub active_value: u8,
    /// A declared reference supplying this bit's interpretation
    /// contract, where the source states one. 2.xxx's v bit prints no
    /// encoding of its own - only the delegation to its 1.xxx twin -
    /// so the reference is the bit's whole stated contract, exactly
    /// as a scalar's [`ScalarField::semantics`] is. A records
    /// statement: the generated contract derives nothing from the
    /// target at runtime.
    pub semantics: Option<RefTarget>,
}

/// How a receiver treats declared reserved or unused bits.
///
/// Per-declaration data: the source obliges receivers to check some
/// reserved fields to be zero and to ignore other unused fields.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum ReservedBitRule {
    /// Receivers check the bits are zero.
    CheckZero,
    /// Receivers ignore the bits.
    Ignore,
}

/// A bit-set layout with named positions and reserved bits.
///
/// Bit positions are anchored to the bit-group field node that
/// references this descriptor, not to the whole payload: bit 0 is the
/// group's last transmitted bit, so a group of N bits spans positions
/// N-1..0 whether or not it ends on an octet boundary. The group's
/// placement in the payload is the field tree's data; this descriptor
/// never restates it.
#[derive(Debug)]
pub struct BitSet {
    /// The named bits.
    pub named: &'static [NamedBit],
    /// Mask of bits the sender transmits as zero.
    pub reserved_mask: u32,
    /// The receiver rule for the reserved bits.
    pub reserved_rule: ReservedBitRule,
}

/// The numeric carrier of a scalar field, as the notation symbol
/// declares it.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Carrier {
    /// A single-bit boolean (`B1` as a lone value field).
    Boolean,
    /// An enumeration code (`N`); the field carries a code table.
    Enumerated,
    /// An unsigned integer (`U`).
    Unsigned,
    /// A two's complement signed integer (`V`).
    Signed,
    /// The KNX 2-octet float (`F16`).
    Float16,
    /// IEEE binary32 (`F32`).
    Float32,
}

impl Carrier {
    /// All `Carrier` variants in declaration order; the canonical
    /// single source for a consumer that must answer for every one.
    pub const ALL: [Carrier; 6] = [
        Carrier::Boolean,
        Carrier::Enumerated,
        Carrier::Unsigned,
        Carrier::Signed,
        Carrier::Float16,
        Carrier::Float32,
    ];
}

/// A declared value-to-field mapping of an integer scalar field.
///
/// The DPT specification form's encoding conventions distinguish how a
/// field value relates to the value it carries, and the relationship is
/// a per-field fact: one subtype can hold fields of different mapping
/// kinds. The reviewed data declares the kind explicitly and generation
/// fails when a declared kind contradicts the field's printed
/// resolution or range, so no consumer ever re-derives it.
///
/// The declared range's domain follows the kind: identity, offset,
/// century and interval-exponential ranges bound the FIELD value
/// (19.001's Year prints 0..255), by this catalogue's own convention
/// for all 4; resolution and linear ranges bound the mapped VALUE
/// (7.003's 0..655350 ms, 5.001's 0..100 percent).
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Mapping {
    /// The field value is the value, at a resolution of 1 in the unit
    /// the source declares (or dimensionless).
    Identity,
    /// The field's encodable span maps onto the declared range by an
    /// exact ratio; the printed resolution is approximate (5.001:
    /// 100 percent encodes as 255, so the ratio is 100/255).
    Linear,
    /// The value is the field times the declared exact resolution
    /// factor, in the unit the source declares (7.003: field x 10 ms); the encode
    /// direction divides, and only exact multiples of the factor are
    /// encodable. The factor is the field's declared resolution -
    /// guaranteed present and exact by generation, never restated here.
    Resolution,
    /// The value is the field plus a declared base (19.001: the year is
    /// the field plus 1900).
    Offset {
        /// The base added to the field value.
        base: i32,
    },
    /// The date century rule (11.001): field values 90 through 99 read
    /// as the years 1990 through 1999, values 0 through 89 as 2000
    /// through 2089.
    Century,
    /// The field's value is the step code itself; the code additionally
    /// declares an interval count of 2 to the power of the code minus 1
    /// (3.007: step codes 1 through 7 subdivide the controlled range
    /// into 1 through 64 intervals). Access reads and writes the code;
    /// the recorded exponential relation is data for a consumer that
    /// needs interval counts, and none exists yet.
    IntervalExponential,
}

/// A scalar field's declarative record.
///
/// Resolution, range, codes and specials attach here because they are
/// per-field facts: multi-field rows (251.600's 4 colour components,
/// 204.001's main value) are only expressible at this level, and a
/// per-field absence is recorded rather than erased by a row-level
/// hoist. Each is a restatement where the source is plain and the
/// reading this catalogue settled on where it is not.
#[derive(Debug)]
pub struct ScalarField {
    /// The carrier the notation symbol declares.
    pub carrier: Carrier,
    /// The field width in bits.
    pub bits: u8,
    /// A declared reference supplying this field's interpretation
    /// contract, where the source states one.
    pub semantics: Option<RefTarget>,
    /// The resolution the reviewed data records for this field, where
    /// it records one: a restatement where the source prints a figure,
    /// and the reading this catalogue settled on where it does not.
    pub resolution: Option<Resolution>,
    /// The declared value-to-field mapping. Present on every unsigned
    /// and signed integer carrier; absent on boolean, enumerated and
    /// float carriers, whose relationship is owned by the code table or
    /// the float format itself.
    pub mapping: Option<Mapping>,
    /// The declared numeric range.
    pub range: DeclaredRange,
    /// The enumeration code table, for fields that declare one.
    pub codes: Option<&'static CodeTable>,
    /// Special encoded values of this field.
    pub specials: &'static [SpecialValue],
    /// The Z8 main-value designation: true on the one top-level
    /// scalar the Z8 control octet couples with, on a row that
    /// declares MORE than one top-level scalar (the source designates
    /// the field per row). A single-scalar
    /// Z8 row's sole scalar is the main by construction and carries
    /// no designation; every non-Z8 field is false.
    pub main: bool,
}

/// The shape of one field in a subtype's declared encoding.
///
/// Recursion appears exactly where the source structure requires it: a
/// repeated group and an embedded record contain fields; everything
/// else is flat. Print-level octet groupings are not nesting and are
/// flattened.
#[derive(Debug)]
pub enum FieldShape {
    /// A value-carrying scalar.
    Scalar(ScalarField),
    /// Reserved bits: a declared `r` field, or unused carrier bits of
    /// the declared width that the format string leaves uncovered - two
    /// categories the source equates while assigning them different
    /// receiver rules per declaration. Senders transmit zero either way.
    Reserved {
        /// The reserved width in bits.
        bits: u8,
        /// The receiver rule; check-zero where the source is silent.
        rule: ReservedBitRule,
    },
    /// A named-bit group. Positions in the descriptor anchor to this
    /// group.
    BitGroup {
        /// The group width in bits.
        bits: u8,
        /// The bit-set descriptor.
        set: &'static BitSet,
    },
    /// A fixed-width character array with 8-bit elements.
    CharArray {
        /// The element count.
        count: u16,
        /// The declared fill value for unused trailing positions, where
        /// the source declares one.
        pad: Option<u8>,
        /// The declared character contract, as a schema token.
        repertoire: TextRepertoire,
    },
    /// A fixed-width container holding a terminator-delimited character
    /// sequence: at most `octets - 1` content octets, then the mandatory
    /// terminator, then zero fill.
    CharTerminated {
        /// The container width in octets, the terminator included.
        octets: u16,
        /// The declared terminator value.
        terminator: u8,
        /// The declared character contract, as a schema token.
        repertoire: TextRepertoire,
    },
    /// A variable-length character sequence with 8-bit elements and a
    /// terminator that is part of the format.
    CharVariable {
        /// The declared terminator value.
        terminator: u8,
        /// The declared character contract, as a schema token.
        repertoire: TextRepertoire,
    },
    /// The service-selected Z8 status/command octet. A row containing
    /// this field requires service-selected context; a standalone
    /// status-only Z8 layout (21.001) is a bit group instead, which is
    /// per-subtype data.
    Z8Control,
    /// An embedded record declared same-as another subtype. The fields
    /// are this row's own declared instantiation; per-subtype
    /// divergences in the embedded layout are data, never options.
    Embed {
        /// The subtype whose record is embedded.
        of: DptId,
        /// The embedded fields, in transmission order.
        fields: &'static [FieldNode],
    },
    /// A field group repeated a declared number of times.
    Repeat {
        /// The declared repetition count.
        count: u16,
        /// The declared base contract of the group, where the source
        /// states one.
        base: Option<RefTarget>,
        /// The group fields, in transmission order.
        group: &'static [FieldNode],
    },
}

/// One field of a subtype's declared encoding, in transmission order
/// (most significant, first transmitted, first).
#[derive(Debug)]
pub struct FieldNode {
    /// A short name for the field. It identifies the field within its
    /// subtype and is not part of the encoding.
    pub name: &'static str,
    /// The field's shape and declared facts.
    pub shape: FieldShape,
}

/// What the gating flag's active state declares about its target.
///
/// The source states both polarities: 251.600's mask bits and 235.001's
/// validity bits declare the component valid, while 19.001's "No ..."
/// flags declare the gated fields not valid. The sense is recorded per
/// edge because it cannot be derived from a bit name.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum ValiditySense {
    /// The target is valid exactly when the flag is in its active
    /// state.
    AssertsValid,
    /// The target is not valid when the flag is in its active state.
    AssertsInvalid,
}

/// A validity association the reviewed data records: a named flag bit
/// gates a field (or another named bit) of the same row.
///
/// Source-declared where the defining clause declares one, and the
/// reading this catalogue settled on where the clause reaches its flags
/// through a reference instead. The reviewed data records no per-edge
/// provenance column; the kind is assigned per ROW, in the 2 paragraphs
/// below, and every per-row count is pinned by a test - so the totals
/// live where they are measured, not here - a moving figure restated
/// in prose goes stale the commit the set grows. Per row, the counts
/// below are fixed facts of each clause.
///
/// The clause-declared rows: 19.001 carries 8, 251.600 carries 4,
/// and 235.001 and 235.002 carry 2 each - each row's own field table
/// names the gating flag, its polarity and what it gates. The
/// structured compound rows whose own bit tables print a validity
/// declaration are clause-declared the same way, 1 edge per printed
/// declaration - a growing membership, so it is not enumerated here;
/// the per-row counts are pinned by tests.
///
/// The remainder rest on a reference. 265.001 and 247.600 carry 8 each,
/// under 2 same-shaped readings: 265.001 declares no validity association of
/// its own at all: its clause reaches 19.001 through a same-as cell in
/// the column that states how a field's value relates to its coded
/// value, and whether such a cell carries the named row's whole
/// definition or only its field encodings is a question the source
/// leaves open. Answering it broadly - so that the edges come across
/// with the layout - is a decision recorded for this catalogue rather
/// than a printed fact. 247.600's clause hands its octets 12 to 5 -
/// the whole date-and-time block, flags included - to 19.001 through
/// one see-cell, and its edges come across under the same broad
/// reading (its flag octets re-package 19.001's B16 as B8 plus B1r7,
/// so the layout could not come across as an instantiation - the
/// contract did). The DateTime-carrying register variants take the
/// SAME same-as reading for their date-and-time portion: each
/// carries 19.001's 8 flag edges through its embedded record,
/// exactly as 265.001 does. And every register-family row (277.1200,
/// its instantiation-count variants, and the DateTime variants
/// alike) carries its `E` and `T` pair under a qualified delegation:
/// the
/// family clause prints the validity octet's bit geometry and no bit
/// label, polarity or per-bit meaning at all, handing the repeated
/// record to 235.001 under a qualifier whose extension is printed as
/// prose with no encoding - so the pair is read off the delegation
/// target, and whether the referenced meanings survive the qualifier
/// stays an open reading. A DateTime register variant therefore
/// carries both classes: the 8 date-and-time edges and the pair.
///
/// The flag's active state is its declared `active_value`; the sense
/// says what that state means for the target. The value-level
/// consequences of an invalid target are semantic-layer concerns.
/// Within a repeated group, the association binds per instance - and
/// that is why both ends live in one scope: an association binding per
/// instance has no reading where one end sits outside the group, so an
/// edge whose flag and target are declared on opposite sides of a
/// repeated group is refused where the row is bound rather than
/// resolved per payload.
#[derive(Debug)]
pub struct ValidityEdge {
    /// The gating flag: a named bit in one of the row's bit groups.
    pub flag: &'static str,
    /// The gated target: a field name, or a named bit of the same row.
    pub target: &'static str,
    /// What the flag's active state declares about the target.
    pub sense: ValiditySense,
}

/// A source-declared relation between fields of one row.
///
/// The vocabulary is closed over the relations the reviewed rows
/// declare; a new source-declared relation form extends it through
/// review, never through a generic escape hatch. A rule's operands
/// all live in one scope - the row's top scope, or one repeated
/// group, where the relation binds every instance independently
/// (instance i's trigger obliges instance i's targets alone), the
/// same per-instance reading a [`ValidityEdge`] takes.
#[derive(Debug)]
pub enum CrossFieldRule {
    /// When the trigger field carries the stated value, every target
    /// field shall be zero (19.001: hour 24 obliges zero minutes and
    /// seconds). A violating message gets the stated receiver
    /// disposition; an encoder rejects what it cannot ignore.
    ZeroWhen {
        /// The field whose value conditions the rule.
        trigger: &'static str,
        /// The trigger's raw field value that activates the rule.
        value: u64,
        /// The fields obliged to be zero while the rule is active.
        targets: &'static [&'static str],
        /// The receiver disposition the source assigns to a violation.
        disposition: ReceiveDisposition,
    },
}

/// The target of a source-declared reference.
///
/// The source references both specific subtypes and whole families; a
/// family-level reference is not collapsed onto an arbitrary subtype.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum RefTarget {
    /// A specific subtype.
    Subtype(DptId),
    /// A whole main-number family.
    Family(u16),
}

/// Emits [`TextRepertoire`] and its `ALL` census from ONE variant
/// list, so a variant cannot exist outside the census: the
/// variant-live-census-short state is not expressible, on stable and
/// on this workspace's MSRV alike. A `macro_rules!` list, following
/// the tree's own precedent, not a derive.
macro_rules! text_repertoires {
    (
        $(#[$enum_doc:meta])*
        pub enum TextRepertoire { $( $(#[$member_doc:meta])* $member:ident, )+ }
    ) => {
        $(#[$enum_doc])*
        #[derive(Clone, Copy, PartialEq, Eq, Debug)]
        pub enum TextRepertoire { $( $(#[$member_doc])* $member, )+ }

        impl TextRepertoire {
            /// The census the vocabulary tests loop over, emitted from
            /// the same variant list as the enum itself - a member
            /// cannot exist outside it by construction. The guard test
            /// beside `carrier_all` still pins the census's SIZE, so a
            /// vocabulary change stays a loudly reviewed number.
            pub const ALL: [TextRepertoire; text_repertoires!(@count $($member)+)] =
                [ $(TextRepertoire::$member,)+ ];
        }
    };
    (@count $head:ident $($rest:ident)*) => { 1usize + text_repertoires!(@count $($rest)*) };
    (@count) => { 0usize };
}

text_repertoires! {
    /// The declared character contract of a character field, carried as a
    /// datum of the schema rather than decided by a reader.
    ///
    /// The reviewed data declares a repertoire by reference, or - on
    /// the 3 defining rows 4.001, 4.002 and 28.001 - by the recorded
    /// `self` token; the generator maps either declaration to this
    /// token when it emits the field, so the vocabulary is closed
    /// exactly once - here. A
    /// reader matching on this enum answers for every member or does not
    /// compile, which is what makes a half-added repertoire unbuildable
    /// rather than silently withdrawn: while the reference was
    /// re-interpreted in a hand-written library arm instead, a repertoire
    /// the generator admitted and the arm did not know registered for
    /// encode, published 0 composable items, and sealed a zeroed payload
    /// with no refusal at any gate.
    pub enum TextRepertoire {
        /// The ASCII repertoire, referenced as DPT 4.001: 0x00..=0x7F,
        /// the most significant bit always 0 per the defining clause.
        Ascii,
        /// The ISO-8859-1 octet repertoire, referenced as DPT 4.002.
        Iso8859_1,
        /// The UTF-8 repertoire, referenced as DPT 28.001.
        Utf8,
    }
}

/// Whether a Z8 command's main value carries data.
///
/// The command table's own column: under some commands the main value
/// is valid, under others it is don't care (the source's term) - the
/// receiver reads no data from it.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Z8MainValue {
    /// The main value field carries the datapoint value.
    Valid,
    /// The main value field carries no data under this command.
    DontCare,
}

/// One command of the Z8 command enumeration.
#[derive(Debug)]
pub struct Z8Command {
    /// The encoded command value.
    pub code: u8,
    /// A short name for the command. It is not part of the encoding:
    /// match on `code`, never on this text.
    pub label: &'static str,
    /// Whether the main value carries data under this command.
    pub main_value: Z8MainValue,
}

/// The standardised Z8 status/command contract, declared once.
///
/// A general clause defines the Z8 octet for every Z8-bearing subtype:
/// read as STATUS it is the DPT_StatusGen bit set, read as COMMAND it
/// is this command enumeration, and the reading is selected by the
/// Application Layer service, never by payload content. Under a set
/// Fault status bit the main value field carries failure information
/// whose codes this descriptor also names.
#[derive(Debug)]
pub struct Z8Descriptor {
    /// The status-reading bit set (the DPT_StatusGen layout).
    pub status: &'static BitSet,
    /// The command enumeration, sorted by code.
    pub commands: &'static [Z8Command],
    /// The failure-information codes the main value carries when the
    /// status Fault bit is set.
    pub fault_info: &'static CodeTable,
}

/// The operation context a subtype's interpretation requires.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum ContextRequirement {
    /// No context beyond the payload.
    None,
    /// The Application Layer service selects the reading; there is no
    /// payload-derivable answer.
    ServiceSelected,
}

/// The transport restriction the source states for this type.
///
/// The variants rest on different source statements; they are not
/// degrees of one rule, and a refusal names the rule the source
/// actually states.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum GroupTransport {
    /// No source-stated restriction.
    Eligible,
    /// The source declares the row not available for standard group
    /// communication: for Z8-bearing rows by constraint, and for the
    /// structured HVAC subtype range by the identifier-allocation
    /// table's LTE-only cell.
    Forbidden,
    /// The source does not allow this DPT for runtime communication and
    /// confines it to parameters and diagnostic data, or to what a
    /// Functional Block specification designates as such.
    ParametersAndDiagnosticsOnly,
}

/// One catalogued datapoint subtype: its declarative record - a
/// restatement where the KNX source is plain, and the reading this
/// catalogue settled on where the source is silent, ambiguous or prints
/// figures that disagree.
///
/// Per-field facts - resolutions, ranges, code tables, named bits,
/// specials, reserved declarations - live on the field nodes that own
/// them.
#[derive(Debug)]
pub struct SubtypeRow {
    /// The identifier.
    pub id: DptId,
    /// The official name.
    pub name: &'static str,
    /// The width contract, as the source declares it. The generator
    /// checks it equals the width the field tree computes.
    pub width: PayloadWidth,
    /// The declared field decomposition, in transmission order.
    pub fields: &'static [FieldNode],
    /// The validity associations the reviewed data records between the
    /// row's flags and its fields: source-declared where the clause
    /// declares them, and read off a reference where the clause reaches
    /// its flags through one instead - the 265.001 same-as class and
    /// the register family's qualified delegation; every count is
    /// pinned by a test.
    pub validity: &'static [ValidityEdge],
    /// Source-declared relations between the row's fields.
    pub cross_field: &'static [CrossFieldRule],
    /// The operation context interpretation requires.
    pub context: ContextRequirement,
    /// Group-transport eligibility as the source states it.
    pub group_transport: GroupTransport,
}