ondas 2.1.0

Read-only, format-independent waveform analysis library
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
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
#[cfg(test)]
mod tests;

mod path;

use std::{
    fmt,
    str::FromStr,
    sync::{
        Arc, OnceLock,
        atomic::{AtomicU64, Ordering},
    },
};

use crate::{LookupError, PathError, PathFormatError, Result, SliceError};

/// An owned, immutable sequence of exact hierarchy components.
///
/// Identity is the exact component sequence. Escaping affects only text
/// representations. Paths start at the hierarchy root. Relative paths and the
/// navigation components `.` and `..` are not supported.
///
/// # Accepted text forms
///
/// - Ordinary components: `tb.dut.data`.
/// - SystemVerilog escaped identifiers: `tb.\gen.blk[0] .data`. A leading
///   backslash starts the identifier. Whitespace ends it. Embedded dots and
///   brackets do not split the path.
/// - Ondas quoted components: `tb."name with space".data`,
///   `tb."name.with.dots".data`, or `tb."имя сигнала".data`. These represent names
///   outside SystemVerilog identifier syntax.
///
/// # Quoted components and canonical output
///
/// Each quoted component uses JSON string syntax. Accepted escapes are `\"`,
/// `\\`, `\/`, `\b`, `\f`, `\n`, `\r`, `\t`, and `\uXXXX` with exactly four
/// hexadecimal digits. Unicode surrogate pairs decode to one Unicode scalar.
/// Unpaired surrogates are invalid. Unknown escapes such as `\q`, incomplete
/// escapes, and unescaped `U+0000..=U+001F` characters produce [`PathError`]. These
/// rules apply inside quotes, not to SystemVerilog escaped identifiers.
///
/// [`Display`](fmt::Display) produces canonical Ondas syntax. Parsing that output
/// recovers the same components. Empty components and components containing
/// separators, whitespace, brackets, quotes, backslashes, `U+0000..=U+001F`, or
/// slice-like spelling are quoted. Inside quotes, canonical output uses `\"`
/// and `\\`, the short escapes `\b`, `\f`, `\n`, `\r`, and `\t`, and lowercase
/// `\u00xx` for the remaining `U+0000..=U+001F` characters. All other characters,
/// including `/` and non-ASCII Unicode, are written literally. Output does not
/// normalize Unicode. Thus `tb."a\u000Ab"` canonicalizes to `tb."a\nb"`.
///
/// [`Self::to_verilog`] instead produces lossless SystemVerilog-compatible text
/// or a [`PathFormatError`].
///
/// # Path versus selector
///
/// Brackets do not specify array indices or bit slices here. `tb.mem[0]` may name
/// an actual declaration. Only [`Hierarchy::signal`] interprets an optional
/// trailing `[msb:lsb]` as a projection after exact lookup fails.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct HierarchyPath {
    components: Vec<String>,
}

impl HierarchyPath {
    /// Parses the accepted text forms described on [`HierarchyPath`].
    ///
    /// Returns [`PathError`] with a byte offset for invalid syntax. This parses
    /// exact components, not a signal-slice expression.
    pub fn parse(text: &str) -> std::result::Result<Self, PathError> {
        path::parse(text).map(|components| Self { components })
    }

    /// Builds a path from exact, unescaped hierarchy components.
    ///
    /// Component contents are names, not text to parse or unescape.
    pub fn from_components<I, S>(components: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        Self {
            components: components.into_iter().map(Into::into).collect(),
        }
    }

    /// Returns the exact hierarchy components in order.
    pub fn components(&self) -> impl ExactSizeIterator<Item = &str> + '_ {
        self.components.iter().map(String::as_str)
    }

    /// Returns the number of hierarchy components.
    pub fn len(&self) -> usize {
        self.components.len()
    }

    /// Returns whether the path has no components.
    pub fn is_empty(&self) -> bool {
        self.components.is_empty()
    }

    /// Returns the final component, if any.
    pub fn name(&self) -> Option<&str> {
        self.components.last().map(String::as_str)
    }

    /// Returns the path without its final component, if any.
    pub fn parent(&self) -> Option<Self> {
        self.components.split_last().map(|(_, parent)| Self {
            components: parent.to_vec(),
        })
    }

    /// Returns a new path with one exact component appended, leaving this path unchanged.
    ///
    /// The component is not parsed as a path or selector.
    pub fn join(&self, component: impl Into<String>) -> Self {
        let mut path = self.clone();
        path.components.push(component.into());
        path
    }

    /// Formats the path losslessly using SystemVerilog-compatible spelling.
    ///
    /// Returns [`PathFormatError::NotRepresentable`] if a component cannot be
    /// represented without loss. Ondas quoted syntax remains available through
    /// [`Display`](fmt::Display).
    ///
    /// Every component is escaped, including keywords and simple identifiers.
    pub fn to_verilog(&self) -> std::result::Result<String, PathFormatError> {
        let mut output = String::new();
        for component in &self.components {
            // IEEE 1800-2017 5.6.1: printable ASCII, terminated by whitespace.
            if component.is_empty() || !component.bytes().all(|b| (33..=126).contains(&b)) {
                return Err(PathFormatError::NotRepresentable {
                    component: component.clone(),
                });
            }
            if !output.is_empty() {
                output.push('.');
            }
            output.push('\\');
            output.push_str(component);
            output.push(' ');
        }
        Ok(output)
    }
}

impl FromStr for HierarchyPath {
    type Err = PathError;

    /// Parses a root-based hierarchy path.
    fn from_str(text: &str) -> std::result::Result<Self, Self::Err> {
        Self::parse(text)
    }
}

impl fmt::Display for HierarchyPath {
    /// Formats the path using canonical, round-trippable Ondas syntax.
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        for (index, component) in self.components.iter().enumerate() {
            if index != 0 {
                formatter.write_str(".")?;
            }
            if component.is_empty()
                || component.chars().any(|c| {
                    c.is_whitespace() || c.is_control() || matches!(c, '.' | '[' | ']' | '"' | '\\')
                })
            {
                formatter.write_str(&serde_json::to_string(component).map_err(|_| fmt::Error)?)?;
            } else {
                formatter.write_str(component)?;
            }
        }
        Ok(())
    }
}

/// An immutable waveform hierarchy that can be cloned.
///
/// [`Scope`] and [`Variable`] are borrowed views. [`Signal`] is a copyable query
/// handle. Clone the hierarchy before retaining views across mutable queries on
/// its [`Waveform`](crate::Waveform). See the example on that type.
///
/// Declarations and histories are distinct. [`Self::variables`] includes aliases.
/// [`Self::signals`] lists whole histories with distinct handles. A reader can
/// leave aliases separate when it cannot establish their shared history.
/// Lookup failures use [`LookupError`], not opening or backend errors.
///
/// Scope and variable equality compares object identity, not paths or metadata.
/// A clone keeps the same objects. An independent open has different objects,
/// even when it reads the same file. Use equality to match a parent returned by
/// traversal with a retained scope. Equal paths can refer to distinct objects.
///
/// ```
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let source = b"$scope module top $end $var wire 1 ! flag $end \
///     $upscope $end $enddefinitions $end #0 1!";
/// let wave = ondas::open_bytes("tree.vcd", source.as_slice().into())?;
/// let hierarchy = wave.hierarchy();
/// let retained = hierarchy.clone();
/// let root = retained.scope("top")?;
/// let flag = hierarchy.variable("top.flag")?;
/// assert!(flag.parent().as_ref() == Some(&root));
/// assert!(flag == retained.variable("top.flag")?);
/// # Ok(())
/// # }
/// ```
#[derive(Clone)]
pub struct Hierarchy {
    // Identity of this logical source. Clones keep it, so views from a clone compare equal.
    source: u64,
    data: Arc<HierarchyData>,
}

pub(crate) struct ScopeData {
    pub(crate) name: String,
    pub(crate) name_was_escaped: bool,
    pub(crate) parent: Option<usize>,
    pub(crate) kind: String,
    pub(crate) definition_name: Option<String>,
    pub(crate) packing: Option<Packing>,
    pub(crate) is_hidden: bool,
}

pub(crate) struct VariableData {
    pub(crate) name: String,
    pub(crate) reader_name: Option<String>,
    pub(crate) name_was_escaped: bool,
    pub(crate) parent: Option<usize>,
    pub(crate) kind: String,
    pub(crate) direction: Direction,
    pub(crate) range: Option<BitRange>,
    pub(crate) is_constant: bool,
    pub(crate) type_name: Option<String>,
    pub(crate) signedness: Option<Signedness>,
    pub(crate) logic_domain: Option<LogicDomain>,
    pub(crate) enumeration: Option<EnumerationData>,
    pub(crate) signal: Option<usize>,
}

pub(crate) struct EnumerationData {
    pub(crate) name: Option<String>,
    // Whole-width logic keys are validated and canonicalized by for_encoding.
    variants: Vec<(String, String)>,
}

impl EnumerationData {
    /// Expose only keys that can be matched to the whole stored bit value.
    pub(crate) fn for_encoding(
        name: Option<String>,
        mut variants: Vec<(String, String)>,
        encoding: Encoding,
    ) -> Option<Self> {
        let Encoding::Bits { width } = encoding else {
            return None;
        };
        if variants.is_empty()
            || !variants.iter().all(|(key, _)| {
                crate::BitsRef::from_ascii(key.as_bytes()).is_some_and(|bits| bits.width() == width)
            })
        {
            return None;
        }
        for (key, _) in &mut variants {
            key.make_ascii_lowercase();
        }
        Some(Self { name, variants })
    }
}

struct HierarchyData {
    scopes: Vec<ScopeData>,
    variables: Vec<VariableData>,
    encodings: Vec<Encoding>,
    children: OnceLock<ChildLinks>,
    declarations_by_name: OnceLock<NameIndex>,
}

struct NameIndex {
    offsets: Vec<usize>,
    declarations: Vec<usize>,
}

struct ChildLinks {
    first: Vec<usize>,
    next: Vec<usize>,
}

impl ChildLinks {
    fn new(scopes: &[ScopeData], variables: &[VariableData]) -> Self {
        let mut first = vec![usize::MAX; scopes.len()];
        let mut next = vec![usize::MAX; scopes.len() + variables.len()];
        // Scope IDs precede variable IDs.
        // Prepending in reverse order keeps scopes before variables and retains
        // declaration order within each kind, without per-parent allocations.
        for (index, variable) in variables.iter().enumerate().rev() {
            if let Some(parent) = variable.parent {
                let child = scopes.len() + index;
                next[child] = std::mem::replace(&mut first[parent], child);
            }
        }
        for (index, scope) in scopes.iter().enumerate().rev() {
            if let Some(parent) = scope.parent {
                next[index] = std::mem::replace(&mut first[parent], index);
            }
        }
        Self { first, next }
    }
}

/// Retained bytes of one vector payload, counted by capacity rather than length.
fn vec_bytes<T>(capacity: usize) -> usize {
    capacity.saturating_mul(std::mem::size_of::<T>())
}

static NEXT_SOURCE: AtomicU64 = AtomicU64::new(1);

fn next_source() -> u64 {
    NEXT_SOURCE
        .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |id| id.checked_add(1))
        .expect("hierarchy source IDs exhausted")
}

/// A scope or variable encountered during hierarchy traversal.
pub enum Item<'h> {
    /// A hierarchy scope.
    Scope(Scope<'h>),
    /// A variable declaration.
    Variable(Variable<'h>),
}

/// A borrowed view of a scope in a hierarchy.
///
/// Equality identifies one scope in one source hierarchy. Views from a
/// [`Hierarchy::clone`] compare equal to the original views. Distinct scopes
/// compare unequal even when their paths and metadata are equal. Views from
/// independent opens compare unequal.
pub struct Scope<'h> {
    hierarchy: &'h Hierarchy,
    index: usize,
}

/// A borrowed view of a variable declaration in a hierarchy.
///
/// Equality identifies one declaration in one source hierarchy. Views from a
/// [`Hierarchy::clone`] compare equal to the original views. Alias declarations
/// compare unequal even when they share a [`Signal`]. Equal paths or metadata do
/// not make declarations equal. Views from independent opens compare unequal.
pub struct Variable<'h> {
    hierarchy: &'h Hierarchy,
    index: usize,
}

impl PartialEq<Scope<'_>> for Scope<'_> {
    fn eq(&self, other: &Scope<'_>) -> bool {
        self.hierarchy.source == other.hierarchy.source && self.index == other.index
    }
}

impl Eq for Scope<'_> {}

impl PartialEq<Variable<'_>> for Variable<'_> {
    fn eq(&self, other: &Variable<'_>) -> bool {
        self.hierarchy.source == other.hierarchy.source && self.index == other.index
    }
}

impl Eq for Variable<'_> {}

/// An opaque source or computed waveform signal with an optional bit projection.
///
/// A handle can have [`Encoding::Unsupported`]. Value queries then return
/// [`Error::UnsupportedSignal`](crate::Error::UnsupportedSignal).
///
/// Whole aliases compare equal when the reader establishes their shared history.
/// Otherwise, declarations have separate handles. Unequal handles do not prove
/// independent histories. Distinct histories have distinct whole handles.
/// Handles belong to their source hierarchy and waveform.
/// Using one with another source returns [`Error::InvalidSignal`](crate::Error::InvalidSignal).
/// Backend-local identifiers and projection representation are not public contracts.
///
/// [`Waveform::concat`](crate::Waveform::concat) creates computed bit signals.
/// Identical ordered definitions in one waveform share a handle. A computed
/// signal has no source declaration. Its definition belongs to the waveform;
/// copying a handle does not keep that waveform alive.
///
/// A projection has its own observed history. Only changes to the selected bits
/// appear in traces and scans. For projected samples, `changed_at` identifies the
/// last change of the projected value, not unrelated activity in its base signal.
/// It is `None` if the backend cannot establish that time reliably.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Signal {
    source: u64,
    index: usize,
    computed: bool,
    base_encoding: Encoding,
    encoding: Encoding,
    lsb: u32,
}

impl Hierarchy {
    // Reader adaptation supplies normalized kinds, valid indices, and acyclic scope parents.
    pub(crate) fn new(
        scopes: Vec<ScopeData>,
        variables: Vec<VariableData>,
        encodings: Vec<Encoding>,
    ) -> Self {
        Self {
            source: next_source(),
            data: Arc::new(HierarchyData {
                scopes,
                variables,
                encodings,
                children: OnceLock::new(),
                declarations_by_name: OnceLock::new(),
            }),
        }
    }

    // Bytes this hierarchy retains, including the lookup tables that are built on first use.
    // A reader that parks validated declarations needs a byte bound, and the lazy tables are a
    // deterministic function of the declarations, so they are counted before they exist.
    pub(crate) fn validated_bytes(&self) -> usize {
        let data = &self.data;
        let scopes = data.scopes.len();
        let variables = data.variables.len();
        let mut bytes = std::mem::size_of::<HierarchyData>();
        bytes = bytes.saturating_add(vec_bytes::<ScopeData>(data.scopes.capacity()));
        for scope in &data.scopes {
            bytes = bytes.saturating_add(scope.name.capacity());
            bytes = bytes.saturating_add(scope.kind.capacity());
            bytes = bytes.saturating_add(
                scope
                    .definition_name
                    .as_ref()
                    .map_or(0, |name| name.capacity()),
            );
        }
        bytes = bytes.saturating_add(vec_bytes::<VariableData>(data.variables.capacity()));
        for variable in &data.variables {
            bytes = bytes.saturating_add(variable.name.capacity());
            bytes = bytes.saturating_add(variable.kind.capacity());
            bytes = bytes.saturating_add(
                variable
                    .reader_name
                    .as_ref()
                    .map_or(0, |name| name.capacity()),
            );
            bytes = bytes.saturating_add(
                variable
                    .type_name
                    .as_ref()
                    .map_or(0, |name| name.capacity()),
            );
            if let Some(enumeration) = &variable.enumeration {
                bytes = bytes.saturating_add(std::mem::size_of::<EnumerationData>());
                bytes = bytes
                    .saturating_add(enumeration.name.as_ref().map_or(0, |name| name.capacity()));
                bytes = bytes.saturating_add(vec_bytes::<(String, String)>(
                    enumeration.variants.capacity(),
                ));
                for (key, label) in &enumeration.variants {
                    bytes = bytes.saturating_add(key.capacity());
                    bytes = bytes.saturating_add(label.capacity());
                }
            }
        }
        bytes = bytes.saturating_add(vec_bytes::<Encoding>(data.encodings.capacity()));
        // Children links keep one entry per scope and one per declaration; the name index keeps
        // one offset per scope plus two, and one declaration index per declaration.
        let child_entries = scopes.saturating_mul(2).saturating_add(variables);
        let name_entries = scopes
            .saturating_mul(2)
            .saturating_add(variables)
            .saturating_add(2);
        let words = std::mem::size_of::<usize>();
        bytes = bytes.saturating_add(child_entries.saturating_mul(words));
        bytes = bytes.saturating_add(name_entries.saturating_mul(words));
        bytes
    }

    // A reader may retain immutable declaration data across sequential logical opens. Every
    // open still needs its own source identity so handles from an earlier open are rejected.
    pub(crate) fn reopened(&self) -> Self {
        Self {
            source: next_source(),
            data: Arc::clone(&self.data),
        }
    }

    pub(crate) fn signal_at(&self, index: usize) -> Signal {
        let encoding = self.data.encodings[index];
        Signal {
            source: self.source,
            index,
            computed: false,
            base_encoding: encoding,
            encoding,
            lsb: 0,
        }
    }

    pub(crate) fn validate(&self, signal: Signal) -> Result<usize> {
        let encoding = (!signal.computed)
            .then(|| self.data.encodings.get(signal.index).copied())
            .flatten();
        self.validate_encoding(signal, encoding)
    }

    pub(crate) fn computed_signal(&self, index: usize, width: u32) -> Signal {
        let encoding = Encoding::Bits { width };
        Signal {
            source: self.source,
            index,
            computed: true,
            base_encoding: encoding,
            encoding,
            lsb: 0,
        }
    }

    pub(crate) fn validate_encoding(
        &self,
        signal: Signal,
        encoding: Option<Encoding>,
    ) -> Result<usize> {
        let valid = signal.source == self.source
            && encoding == Some(signal.base_encoding)
            && match (signal.base_encoding, signal.encoding) {
                (Encoding::Bits { width: base }, Encoding::Bits { width }) => {
                    (width > 0 || signal == signal.base())
                        && signal.lsb.checked_add(width).is_some_and(|end| end <= base)
                }
                (base, current) => base == current && signal.lsb == 0,
            };
        if valid {
            Ok(signal.index)
        } else {
            Err(crate::Error::InvalidSignal { signal })
        }
    }

    fn children_of(&self, parent: usize) -> impl Iterator<Item = Item<'_>> + '_ {
        let links = self
            .data
            .children
            .get_or_init(|| ChildLinks::new(&self.data.scopes, &self.data.variables));
        let scopes = self.data.scopes.len();
        let mut next = links.first[parent];
        std::iter::from_fn(move || {
            let index = next;
            if index == usize::MAX {
                return None;
            }
            next = links.next[index];
            Some(if index < scopes {
                Item::Scope(Scope {
                    hierarchy: self,
                    index,
                })
            } else {
                Item::Variable(Variable {
                    hierarchy: self,
                    index: index - scopes,
                })
            })
        })
    }

    fn scope_path_at(&self, mut index: Option<usize>) -> HierarchyPath {
        let mut components = Vec::new();
        while let Some(current) = index {
            let scope = &self.data.scopes[current];
            components.push(scope.name.clone());
            index = scope.parent;
        }
        components.reverse();
        HierarchyPath { components }
    }

    /// Iterates over root scopes and variables.
    pub fn roots(&self) -> impl Iterator<Item = Item<'_>> + '_ {
        self.scopes()
            .filter(|scope| scope.data().parent.is_none())
            .map(Item::Scope)
            .chain(
                self.variables()
                    .filter(|variable| variable.data().parent.is_none())
                    .map(Item::Variable),
            )
    }

    /// Iterates over all scopes in the hierarchy.
    pub fn scopes(&self) -> impl Iterator<Item = Scope<'_>> + '_ {
        (0..self.data.scopes.len()).map(|index| Scope {
            hierarchy: self,
            index,
        })
    }

    /// Iterates over all declarations, including signal aliases.
    pub fn variables(&self) -> impl Iterator<Item = Variable<'_>> + '_ {
        (0..self.data.variables.len()).map(|index| Variable {
            hierarchy: self,
            index,
        })
    }

    /// Iterates over whole signals with distinct handles in the hierarchy.
    ///
    /// Aliases share a handle only when the reader establishes their shared history.
    pub fn signals(&self) -> impl Iterator<Item = Signal> + '_ {
        (0..self.data.encodings.len()).map(|index| self.signal_at(index))
    }

    /// Parses and resolves an exact scope path.
    pub fn scope(&self, text: &str) -> std::result::Result<Scope<'_>, LookupError> {
        self.scope_path(&HierarchyPath::parse(text)?)
    }

    /// Parses and resolves an exact variable path.
    pub fn variable(&self, text: &str) -> std::result::Result<Variable<'_>, LookupError> {
        self.variable_path(&HierarchyPath::parse(text)?)
    }

    /// Resolves an exact variable path first, then an optional trailing bit slice.
    ///
    /// The lookup first treats the entire selector as an exact variable path. If
    /// that variable is not found, one trailing `[msb:lsb]` can specify a
    /// [`Signal::slice`]. An actual variable named `data[7:0]` therefore takes
    /// priority over slicing `data`. `[n]` is never a slice. Select one bit with `[n:n]`.
    ///
    /// For example, `tb.mem[0]` names a whole signal, while `tb.mem[0][7:0]`
    /// can slice it. Use [`Self::signal_path`] followed by [`Signal::slice`] to
    /// avoid ambiguity. This is not an expression language or a dynamic index.
    ///
    /// Returns [`LookupError`] for invalid syntax, missing or ambiguous metadata,
    /// a declaration without a history, or an invalid slice.
    pub fn signal(&self, selector: &str) -> std::result::Result<Signal, LookupError> {
        let exact = HierarchyPath::parse(selector)
            .map_err(LookupError::from)
            .and_then(|path| self.signal_path(&path));
        if !matches!(
            &exact,
            Err(LookupError::NotFound { .. } | LookupError::InvalidPath(_))
        ) {
            return exact;
        }
        if let Some((path, msb, lsb)) = path::selector(selector)? {
            return Ok(self.signal_path(&path)?.slice(msb, lsb)?);
        }
        exact
    }

    /// Resolves an already parsed exact scope path.
    ///
    /// Returns [`LookupError::Ambiguous`] when distinct scopes share the path.
    /// Those scopes remain accessible through [`Self::scopes`] and [`Scope::children`].
    pub fn scope_path(&self, path: &HierarchyPath) -> std::result::Result<Scope<'_>, LookupError> {
        let mut matches = self
            .scopes()
            .filter(|scope| Some(scope.name()) == path.name() && scope.path() == *path);
        let first = matches.next();
        match (first, matches.count()) {
            (None, _) => Err(LookupError::NotFound { path: path.clone() }),
            (Some(scope), 0) => Ok(scope),
            (_, remaining) => Err(LookupError::Ambiguous {
                path: path.clone(),
                matches: remaining + 1,
            }),
        }
    }

    /// Resolves an already parsed exact variable path.
    pub fn variable_path(
        &self,
        path: &HierarchyPath,
    ) -> std::result::Result<Variable<'_>, LookupError> {
        let Some((name, scopes)) = path.components.split_last() else {
            return Err(LookupError::NotFound { path: path.clone() });
        };
        // The common warm path has one scope candidate per component. Follow it
        // without building a frontier vector. A second candidate can still hold
        // the target in another branch, so hand that case to the full frontier
        // search instead of reporting an early ambiguity.
        let mut parent = None;
        for name in scopes {
            let mut candidates = self
                .declarations_named(parent, name)
                .iter()
                .copied()
                .filter(|index| *index < self.data.scopes.len());
            let Some(first) = candidates.next() else {
                return Err(LookupError::NotFound { path: path.clone() });
            };
            if candidates.next().is_some() {
                return self.variable_path_frontier(path);
            }
            parent = Some(first);
        }
        let mut matches = self
            .declarations_named(parent, name)
            .iter()
            .copied()
            .filter_map(|index| index.checked_sub(self.data.scopes.len()))
            .map(|index| Variable {
                hierarchy: self,
                index,
            });
        let first = matches.next();
        match (first, matches.count()) {
            (None, _) => Err(LookupError::NotFound { path: path.clone() }),
            (Some(variable), 0) => Ok(variable),
            (_, remaining) => Err(LookupError::Ambiguous {
                path: path.clone(),
                matches: remaining + 1,
            }),
        }
    }

    /// Complete frontier search for a path with several scope branches.
    fn variable_path_frontier(
        &self,
        path: &HierarchyPath,
    ) -> std::result::Result<Variable<'_>, LookupError> {
        let Some((name, scopes)) = path.components.split_last() else {
            return Err(LookupError::NotFound { path: path.clone() });
        };
        let mut parents = vec![None];
        for name in scopes {
            parents = parents
                .into_iter()
                .flat_map(|parent| self.declarations_named(parent, name))
                .copied()
                .filter(|index| *index < self.data.scopes.len())
                .map(Some)
                .collect();
            if parents.is_empty() {
                return Err(LookupError::NotFound { path: path.clone() });
            }
        }
        let mut matches = parents
            .into_iter()
            .flat_map(|parent| self.declarations_named(parent, name))
            .filter_map(|index| index.checked_sub(self.data.scopes.len()))
            .map(|index| Variable {
                hierarchy: self,
                index,
            });
        let first = matches.next();
        match (first, matches.count()) {
            (None, _) => Err(LookupError::NotFound { path: path.clone() }),
            (Some(variable), 0) => Ok(variable),
            (_, remaining) => Err(LookupError::Ambiguous {
                path: path.clone(),
                matches: remaining + 1,
            }),
        }
    }

    fn declaration_key(&self, index: usize) -> (Option<usize>, &str) {
        if index < self.data.scopes.len() {
            let scope = &self.data.scopes[index];
            (scope.parent, &scope.name)
        } else {
            let variable = &self.data.variables[index - self.data.scopes.len()];
            (variable.parent, &variable.name)
        }
    }

    fn declarations_named(&self, parent: Option<usize>, name: &str) -> &[usize] {
        // Keep only declaration indices. Full paths duplicate every ancestor's
        // name for each variable and are unnecessary for component lookup.
        let index = self.data.declarations_by_name.get_or_init(|| {
            let root = self.data.scopes.len();
            let count = root + self.data.variables.len();
            let mut offsets = vec![0; root + 2];
            for item in 0..count {
                let parent = self.declaration_key(item).0.unwrap_or(root);
                offsets[parent + 1] += 1;
            }
            for parent in 1..offsets.len() {
                offsets[parent] += offsets[parent - 1];
            }
            let mut next = offsets[..offsets.len() - 1].to_vec();
            let mut declarations = vec![0; count];
            for item in 0..count {
                let parent = self.declaration_key(item).0.unwrap_or(root);
                declarations[next[parent]] = item;
                next[parent] += 1;
            }
            for range in offsets.windows(2) {
                declarations[range[0]..range[1]].sort_unstable_by(|a, b| {
                    self.declaration_key(*a).1.cmp(self.declaration_key(*b).1)
                });
            }
            NameIndex {
                offsets,
                declarations,
            }
        });
        let parent = parent.unwrap_or(self.data.scopes.len());
        let index = &index.declarations[index.offsets[parent]..index.offsets[parent + 1]];
        let start = index.partition_point(|item| self.declaration_key(*item).1 < name);
        let count = index[start..].partition_point(|item| self.declaration_key(*item).1 == name);
        &index[start..start + count]
    }

    /// Resolves an already parsed exact variable path to a whole signal.
    ///
    /// Never interprets brackets as a slice. Returns [`LookupError::NoSignal`]
    /// when the declaration exists but has no queryable history.
    pub fn signal_path(&self, path: &HierarchyPath) -> std::result::Result<Signal, LookupError> {
        self.variable_path(path)?
            .signal()
            .ok_or_else(|| LookupError::NoSignal { path: path.clone() })
    }

    /// Iterates over declarations that share a signal valid for this hierarchy.
    ///
    /// This includes the reader's confirmed aliases. Unknown alias relationships
    /// remain separate and do not appear in this iterator.
    ///
    /// For a sliced handle, returns the declarations of its base whole signal,
    /// ignoring the projection. Slicing does not create declarations. Whole,
    /// sliced, and repeatedly sliced handles with the same base return the same
    /// declarations. They retain their original metadata and declaration ranges.
    ///
    /// Computed signals and their slices have no source declarations, so their
    /// iterator is empty. They do not inherit aliases from their operands.
    ///
    /// A handle from another hierarchy or waveform produces
    /// [`Error::InvalidSignal`](crate::Error::InvalidSignal).
    pub fn aliases(&self, signal: Signal) -> Result<impl Iterator<Item = Variable<'_>> + '_> {
        if signal.computed {
            self.validate_encoding(signal, Some(signal.base_encoding))?;
        }
        let index = if signal.computed {
            None
        } else {
            Some(self.validate(signal)?)
        };
        Ok(self
            .variables()
            .filter(move |variable| index.is_some() && variable.data().signal == index))
    }
}

impl<'h> Scope<'h> {
    fn data(&self) -> &'h ScopeData {
        &self.hierarchy.data.scopes[self.index]
    }

    /// Returns the scope's exact local name.
    pub fn name(&self) -> &'h str {
        &self.data().name
    }

    /// Returns the scope's owned, root-based path.
    pub fn path(&self) -> HierarchyPath {
        self.hierarchy.scope_path_at(Some(self.index))
    }

    /// Returns the containing scope, or `None` for a root scope.
    pub fn parent(&self) -> Option<Scope<'h>> {
        self.data().parent.map(|index| Scope {
            hierarchy: self.hierarchy,
            index,
        })
    }

    /// Iterates over the scope's direct child scopes and variables.
    pub fn children(&self) -> impl Iterator<Item = Item<'h>> + '_ {
        self.hierarchy.children_of(self.index)
    }

    /// Returns the canonical lower-case scope kind.
    ///
    /// Common kinds are normalized. Unknown vendor kinds retain a namespaced
    /// spelling. They are not forced into a closed enum.
    pub fn kind(&self) -> &'h str {
        &self.data().kind
    }

    /// Returns whether the reader supplied a Verilog escape marker for this name.
    ///
    /// The marker is excluded from [`Self::name`] and path identity. Add one
    /// backslash before the name and terminate it with whitespace to form an
    /// escaped Verilog identifier.
    /// Terminating whitespace is not retained. Merged scopes retain the first
    /// declaration's spelling. This records available reader syntax, not whether
    /// the name needs escaping as a path. A reader that supplies logical names
    /// directly may not retain the source spelling and returns `false`.
    pub fn name_was_escaped(&self) -> bool {
        self.data().name_was_escaped
    }

    /// Returns whether the source explicitly marks this scope as hidden.
    ///
    /// Hidden scopes and their contents remain accessible. This flag is local
    /// to the scope and is not inherited. To hide a subtree, also check
    /// its ancestors. Returns `false` when the backend has no hidden-scope flag.
    pub fn is_hidden(&self) -> bool {
        self.data().is_hidden
    }

    /// Returns the defining module, entity, or equivalent name when available.
    pub fn definition_name(&self) -> Option<&'h str> {
        self.data().definition_name.as_deref()
    }

    /// Returns the scope's packing metadata when applicable.
    pub fn packing(&self) -> Option<Packing> {
        self.data().packing
    }
}

/// Separates a reader-provided Verilog escape marker from logical identity.
pub(crate) fn normalize_name(mut name: String) -> (String, bool) {
    let escaped = name.starts_with('\\');
    if escaped {
        name.remove(0);
    }
    (name, escaped)
}

impl<'h> Variable<'h> {
    fn data(&self) -> &'h VariableData {
        &self.hierarchy.data.variables[self.index]
    }

    /// Returns the declaration's exact logical local name.
    ///
    /// Recognized Verilog escape syntax is excluded. Literal backslashes,
    /// brackets, dots and whitespace remain component data. Use this name for
    /// lookup; do not parse [`Self::reader_name`] to construct a path.
    pub fn name(&self) -> &'h str {
        &self.data().name
    }

    /// Returns the reader-provided local declaration spelling, if retained.
    ///
    /// This diagnostic spelling can include escape syntax and printed ranges.
    /// FSDB retains callback spelling. WLF retains recognized escaped spelling.
    /// WLF spelling includes the terminating whitespace.
    /// Merged duplicate declarations retain the first spelling; aliases retain
    /// their own. Availability is optional. This text does not define identity
    /// or lookup. Use [`Self::name`] and [`Self::path`] for ordinary addressing.
    pub fn reader_name(&self) -> Option<&'h str> {
        self.data().reader_name.as_deref()
    }

    /// Returns whether the reader supplied a Verilog escape marker for this name.
    ///
    /// The recognized marker is excluded from [`Self::name`]. Prefix the name
    /// with one backslash and terminate it with whitespace to form an escaped
    /// Verilog identifier. The name omits a separately printed declared range;
    /// an attached suffix on an escaped identifier remains literal.
    /// This flag does not affect identity or lookup. Merged repeated
    /// declarations retain the first spelling. Aliases retain their own flags.
    /// A reader that supplies logical names directly may not retain the source
    /// spelling and returns `false`. The flag does not prove that an unescaped
    /// identifier appeared in the original HDL.
    pub fn name_was_escaped(&self) -> bool {
        self.data().name_was_escaped
    }

    /// Returns the declaration's owned, root-based path.
    pub fn path(&self) -> HierarchyPath {
        self.hierarchy
            .scope_path_at(self.data().parent)
            .join(self.name())
    }

    /// Returns the containing scope, if any.
    pub fn parent(&self) -> Option<Scope<'h>> {
        self.data().parent.map(|index| Scope {
            hierarchy: self.hierarchy,
            index,
        })
    }

    /// Returns the declaration's whole signal handle, if it has one.
    ///
    /// Aliases return equal handles when the reader establishes their shared history.
    /// Otherwise, the declarations have separate handles. A declaration can exist
    /// without a waveform signal. An unsupported encoding still has a
    /// handle, but value queries return [`Error::UnsupportedSignal`](crate::Error::UnsupportedSignal).
    pub fn signal(&self) -> Option<Signal> {
        self.data()
            .signal
            .map(|index| self.hierarchy.signal_at(index))
    }

    /// Returns the canonical lower-case declaration kind.
    ///
    /// Common kinds are normalized. Unknown vendor kinds retain a namespaced
    /// spelling. Kind is separate from constancy and value encoding.
    pub fn kind(&self) -> &'h str {
        &self.data().kind
    }

    /// Returns the declaration's direction metadata.
    pub fn direction(&self) -> Direction {
        self.data().direction
    }

    /// Returns the original HDL declaration range, if present.
    pub fn range(&self) -> Option<BitRange> {
        self.data().range
    }

    /// Returns whether the declaration denotes a constant value.
    ///
    /// This is independent of kind and encoding. A parameter or generic may
    /// carry bits, a real value, or a string.
    pub fn is_constant(&self) -> bool {
        self.data().is_constant
    }

    /// Returns the declared type name when available.
    pub fn type_name(&self) -> Option<&'h str> {
        self.data().type_name.as_deref()
    }

    /// Returns known signed or unsigned interpretation of this declaration.
    ///
    /// `None` means unavailable or not applicable, for example for a real, string
    /// or event. It does not mean unsigned. This metadata is independent of shared
    /// [`Signal`] identity and is never inferred from observed values or names.
    /// Reading it does not load value histories.
    pub fn signedness(&self) -> Option<Signedness> {
        self.data().signedness
    }

    /// Returns the declaration's known logic domain, not the states observed so far.
    ///
    /// `None` means unavailable or not applicable. An observed `0`/`1` value
    /// does not establish a two-state domain. Aliases may have different metadata
    /// while sharing a [`Signal`]. Reading it does not load value histories.
    pub fn logic_domain(&self) -> Option<LogicDomain> {
        self.data().logic_domain
    }

    /// Returns enumeration metadata whose keys match the whole signal's bits.
    ///
    /// `None` means the reader cannot supply this mapping. It does not prove
    /// that the source declaration is not an enum. Keys describe the whole
    /// signal, not a slice. The reader does not pad, reverse or reinterpret keys
    /// to fit a declaration.
    pub fn enumeration(&self) -> Option<Enumeration<'h>> {
        self.data()
            .enumeration
            .as_ref()
            .map(|data| Enumeration { data })
    }
}

/// Known signedness of a variable declaration, independent of stored bit values.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum Signedness {
    /// A signed interpretation.
    Signed,
    /// An unsigned interpretation.
    Unsigned,
}

/// Known logic domain of a variable declaration.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum LogicDomain {
    /// Logic zero and one.
    TwoState,
    /// Logic zero, one, unknown and high impedance.
    FourState,
    /// The full nine-state domain represented by [`Logic`](crate::Logic).
    NineState,
}

/// Direction metadata for a variable declaration.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum Direction {
    /// The direction is unavailable or unrecognized.
    Unknown,
    /// The declaration has an implicit direction.
    Implicit,
    /// An input declaration.
    Input,
    /// An output declaration.
    Output,
    /// A bidirectional declaration.
    InOut,
    /// A VHDL buffer declaration.
    Buffer,
    /// A VHDL linkage declaration.
    Linkage,
}

/// Packing metadata for a hierarchy scope.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum Packing {
    /// A packed representation.
    Packed,
    /// An unpacked representation.
    Unpacked,
    /// A sparse representation.
    Sparse,
    /// A tagged packed representation.
    TaggedPacked,
}

/// The original index range of an HDL declaration.
///
/// The range may ascend or descend and may use arbitrary HDL indices. It preserves
/// declaration indices, independently of the normalized positions used by
/// [`Signal::slice`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct BitRange {
    msb: i64,
    lsb: i64,
}

impl BitRange {
    /// Creates a declaration range preserving the supplied index order.
    pub const fn new(msb: i64, lsb: i64) -> Self {
        Self { msb, lsb }
    }

    /// Returns the declaration's `msb` index.
    pub const fn msb(self) -> i64 {
        self.msb
    }

    /// Returns the declaration's `lsb` index.
    pub const fn lsb(self) -> i64 {
        self.lsb
    }

    /// Returns the inclusive width of the range.
    ///
    /// # Panics
    ///
    /// Panics when the full `i64::MIN..=i64::MAX` span cannot fit in `u64`.
    pub const fn width(self) -> u64 {
        match self.msb.abs_diff(self.lsb).checked_add(1) {
            Some(width) => width,
            None => panic!("range width exceeds u64"),
        }
    }

    /// Selects an inclusive HDL index range from a bit-vector signal.
    ///
    /// This range must have the signal's current width. Its right endpoint maps
    /// to normalized position zero. Requested indices must lie inside the range
    /// and follow its direction. This also accepts a caller-defined range for a
    /// computed value; it does not verify the range's declaration provenance.
    /// Use [`Variable::range`] for source declaration indices. Absent metadata
    /// does not imply a range. [`Signal::slice`] always uses normalized positions.
    ///
    /// Width, bounds and direction failures return distinct [`SliceError`]
    /// variants. Extreme endpoints return an error without arithmetic overflow.
    /// Handle ownership is checked when the result is used with a waveform.
    ///
    /// ```
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let input = b"$var wire 8 ! data [0:7] $end $enddefinitions $end #0 b10110010 !";
    /// let wave = ondas::open_bytes("range.vcd", input.as_slice().into())?;
    /// let variable = wave.hierarchy().variable("data")?;
    /// let signal = variable.signal().unwrap();
    /// assert_eq!(variable.range().unwrap().slice(signal, 2, 5)?, signal.slice(5, 2)?);
    /// # Ok(())
    /// # }
    /// ```
    pub fn slice(
        self,
        signal: Signal,
        msb: i64,
        lsb: i64,
    ) -> std::result::Result<Signal, SliceError> {
        let width = signal.width().ok_or(SliceError::NotBits)?;
        if i128::from(self.msb).abs_diff(i128::from(self.lsb)) + 1 != u128::from(width) {
            return Err(SliceError::HdlRangeWidthMismatch { range: self, width });
        }
        let low = self.msb.min(self.lsb);
        let high = self.msb.max(self.lsb);
        if !(low..=high).contains(&msb) || !(low..=high).contains(&lsb) {
            return Err(SliceError::HdlOutOfBounds {
                range: self,
                msb,
                lsb,
            });
        }
        let position = |index: i64| index.abs_diff(self.lsb) as u32;
        let (left, right) = (position(msb), position(lsb));
        if left < right {
            return Err(SliceError::HdlDirectionMismatch {
                range: self,
                msb,
                lsb,
            });
        }
        signal.slice(left, right)
    }
}

/// Borrowed enumeration metadata for a variable declaration.
///
/// Each key is a [`BitsRef`](crate::BitsRef) with the whole signal's bit width.
/// Bit zero is the least-significant bit, as in a queried bit value. Match the
/// complete bit value with the key. Signedness and the HDL declaration range do
/// not change this comparison. All nine logic states can occur in keys; their
/// presence does not establish the declaration's domain.
/// A slice does not carry a projected enumeration.
///
/// Labels retain reader-provided spelling. They are not string sample values
/// and are not restricted to ASCII. Order, duplicate keys and duplicate labels
/// are preserved. A value need not have a label; a key can have multiple labels.
/// This metadata does not change the signal's encoding.
///
/// Compare keys with queried [`Bits`](crate::Bits) or [`BitsRef`](crate::BitsRef)
/// values using `==`. Equality checks the complete width and every logic state
/// without formatting text or copying the bit payload.
///
/// ```no_run
/// use ondas::{Sample, Time, Value};
/// # fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let mut wave = ondas::open("dump.fst")?;
/// let hierarchy = wave.hierarchy().clone();
/// let variable = hierarchy.variable("top.state")?;
/// if let (Some(signal), Some(table)) = (variable.signal(), variable.enumeration()) {
///     if let Sample::Value { value: Value::Bits(bits), .. } = wave.sample(signal, Time::ZERO)? {
///         for variant in table.variants() {
///             if variant.encoded == bits {
///                 println!("{}", variant.label);
///             }
///         }
///     }
/// }
/// # Ok(())
/// # }
/// ```
pub struct Enumeration<'h> {
    data: &'h EnumerationData,
}

impl<'h> Enumeration<'h> {
    /// Returns the enumeration type name when available.
    pub fn name(&self) -> Option<&'h str> {
        self.data.name.as_deref()
    }

    /// Iterates over borrowed whole-value bits and their reader-provided labels.
    pub fn variants(&self) -> impl Iterator<Item = EnumerationVariant<'h>> + '_ {
        self.data
            .variants
            .iter()
            .map(|(encoded, label)| EnumerationVariant {
                encoded: crate::BitsRef::from_validated_ascii(encoded.as_bytes()),
                label,
            })
    }
}

/// An encoded enumeration value and its source label.
pub struct EnumerationVariant<'h> {
    /// The whole signal's bit value, borrowed from hierarchy storage.
    ///
    /// The view remains valid for the hierarchy borrow. Use
    /// [`BitsRef::to_owned`](crate::BitsRef::to_owned) to retain an independent copy,
    /// or [`Display`](std::fmt::Display) to format it as an MSB-first logic string.
    pub encoded: crate::BitsRef<'h>,
    /// The corresponding reader-provided enumeration label spelling.
    pub label: &'h str,
}

/// The value encoding of a signal.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Encoding {
    /// A bit-vector encoding.
    Bits {
        /// The bit-vector width.
        width: u32,
    },
    /// A real-number encoding.
    Real,
    /// A string encoding.
    String,
    /// An event occurrence encoding.
    Event,
    /// An encoding visible in the hierarchy but unsupported for queries.
    Unsupported,
}

impl Signal {
    pub(crate) fn is_computed(self) -> bool {
        self.computed
    }
    pub(crate) fn index(self) -> usize {
        self.index
    }

    pub(crate) fn lsb(self) -> u32 {
        self.lsb
    }

    /// Returns the signal's value encoding.
    pub fn encoding(self) -> Encoding {
        self.encoding
    }

    /// Returns the current bit width for bit-vector signals, or `None` otherwise.
    ///
    /// For a slice, this is the projected width, not the base signal's width.
    pub fn width(self) -> Option<u32> {
        match self.encoding {
            Encoding::Bits { width } => Some(width),
            _ => None,
        }
    }

    /// Selects an inclusive normalized range from the current bit-vector value.
    ///
    /// Index zero is the least-significant, rightmost bit of the current value.
    /// These positions need not match [`Variable::range`]. The bounds must satisfy
    /// `msb >= lsb` and `msb < current_width`. Non-bit encodings return [`SliceError::NotBits`],
    /// reversed bounds return [`SliceError::InvalidRange`], and bounds outside
    /// the current width return [`SliceError::OutOfBounds`].
    ///
    /// Repeated slices compose relative to the current projection:
    /// `data.slice(31, 16)?.slice(7, 0)?` selects original bits `[23:16]`.
    /// [`Self::base`] removes the projection. Selecting the full current width
    /// returns the same handle. A full-width slice of a whole signal is whole.
    ///
    /// The resulting history filters out changes that leave the projected value
    /// unchanged. For base values `00000000` at tick 10, `00000001` at tick 20,
    /// and `10100001` at tick 30, slice `[7:4]` changes at 10 and 30, not 20.
    /// Its sample `changed_at` is the last projected change time, or `None` when
    /// that time cannot be determined reliably. It is not another bit's change time.
    /// Multiple slices of one base remain separate public selection entries.
    pub fn slice(self, msb: u32, lsb: u32) -> std::result::Result<Self, SliceError> {
        let width = self.width().ok_or(SliceError::NotBits)?;
        if msb < lsb {
            return Err(SliceError::InvalidRange { msb, lsb });
        }
        if msb >= width {
            return Err(SliceError::OutOfBounds { width, msb, lsb });
        }
        Ok(Self {
            encoding: Encoding::Bits {
                width: msb - lsb + 1,
            },
            lsb: self.lsb + lsb,
            ..self
        })
    }

    /// Returns the complete underlying signal without a bit projection.
    pub fn base(self) -> Self {
        Self {
            encoding: self.base_encoding,
            lsb: 0,
            ..self
        }
    }

    /// Returns whether this handle represents a bit projection.
    pub fn is_slice(self) -> bool {
        self != self.base()
    }
}