wavetools 0.1.2

Command-line tools for digital simulation waveform analysis -- read, filter, and diff FST and VCD files
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
//------------------------------------------------------------------------------
// lib.rs
// Shared waveform library: file opening, hierarchy building, VCD streaming
//
// SPDX-FileCopyrightText: Hudson River Trading
// SPDX-License-Identifier: MIT
//------------------------------------------------------------------------------

mod cat;
mod diff;
#[allow(dead_code, unused_imports, clippy::manual_repeat_n, mismatched_lifetime_syntaxes)]
mod vcd;

pub use cat::{write_signals_wave, write_signals_wave_multi, SignalOutputOptions};
pub use diff::{
    compare_signal_meta, compare_signal_names, diff_wave_sets, diff_waves, open_and_read_wave_sets,
    open_and_read_waves,
};

use fst_reader::{
    is_fst_file, FstArrayType, FstEnumType, FstHierarchyEntry, FstPackType, FstReader,
    FstVarDirection, FstVarType,
};
use std::collections::HashMap;
use std::fs::File;
use std::io::{BufRead, BufReader, Seek, Write};
use std::path::Path;

/// Mapping from signal handle indices to their fully qualified hierarchical names
pub type SignalNames = HashMap<usize, Vec<String>>;

/// Index into a NameTree arena.
pub type NameId = u32;

/// A single node in the hierarchical name tree.
#[derive(Debug)]
struct NameNode {
    segment: String,
    parent: Option<NameId>,
    children: HashMap<String, NameId>,
}

/// Returns true if `s` is a valid SystemVerilog simple identifier.
/// IEEE 1800 rules:
/// 1. Must be non-empty.
/// 2. All characters must be letters, digits, `$`, or `_`.
/// 3. First character must not be a digit or `$`.
fn is_simple_identifier(s: &str) -> bool {
    let mut chars = s.chars();
    match chars.next() {
        Some(c) if c.is_ascii_alphabetic() || c == '_' => {}
        _ => return false,
    }
    chars.all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '$')
}

/// Split a trailing VCD range suffix (e.g., ` [31:0]`, `[5]`) from the base name.
/// Returns `(base, range_suffix)` where `range_suffix` may or may not include a
/// leading space, or `(s, "")` if no range is found.
///
/// Only recognizes numeric ranges (`[digits]` or `[digits:digits]`) to avoid
/// splitting signal names that contain literal brackets.
fn split_range_suffix(s: &str) -> (&str, &str) {
    if !s.ends_with(']') {
        return (s, "");
    }
    // Try " [" first (standard format), then bare "[" (no_range_space format)
    let split_pos = s.rfind(" [").or_else(|| {
        let pos = s.rfind('[')?;
        if pos > 0 { Some(pos) } else { None }
    });
    if let Some(pos) = split_pos {
        // Extract bracket content and verify it's a numeric range
        let bracket_start = s[pos..].find('[').unwrap() + pos + 1;
        let content = &s[bracket_start..s.len() - 1];
        let is_numeric_range = !content.is_empty()
            && content.chars().all(|c| c.is_ascii_digit() || c == ':');
        if is_numeric_range {
            return (&s[..pos], &s[pos..]);
        }
    }
    (s, "")
}

/// Format a single segment for display, escaping non-simple identifiers
/// per the SystemVerilog `%m` convention (leading `\`, trailing space).
///
/// Range suffixes (e.g., ` [31:0]`) are not part of the identifier and are
/// preserved as-is.  Only the base name is tested for escaping.
fn format_segment(s: &str) -> String {
    let (base, range_suffix) = split_range_suffix(s);
    if is_simple_identifier(base) {
        s.to_string()
    } else if range_suffix.is_empty() {
        format!("\\{} ", base)
    } else {
        // The trailing space of the escaped identifier replaces the original
        // space before the range bracket: "\a0.cyc [31:0]"
        format!("\\{} {}", base, &range_suffix[1..])
    }
}

/// Arena-based trie for hierarchical signal names.
///
/// Each node holds one path segment (scope or variable name). Signals share
/// prefix nodes, so `VarEntry` stores a compact `NameId` (u32) instead of a
/// full `String`.
#[derive(Debug)]
pub struct NameTree {
    nodes: Vec<NameNode>,
}

impl NameTree {
    /// Create a new tree with a root node.
    pub fn new() -> Self {
        NameTree {
            nodes: vec![NameNode {
                segment: String::new(),
                parent: None,
                children: HashMap::new(),
            }],
        }
    }

    /// Return the root node id.
    pub fn root(&self) -> NameId {
        0
    }

    /// Intern a child segment under `parent`, returning the child's `NameId`.
    /// If the child already exists, returns the existing id.
    pub fn intern(&mut self, parent: NameId, segment: &str) -> NameId {
        if let Some(&id) = self.nodes[parent as usize].children.get(segment) {
            return id;
        }
        let id = self.nodes.len() as NameId;
        self.nodes.push(NameNode {
            segment: segment.to_string(),
            parent: Some(parent),
            children: HashMap::new(),
        });
        self.nodes[parent as usize]
            .children
            .insert(segment.to_string(), id);
        id
    }

    /// Collect path segments from root to `leaf` (excluding the root).
    pub fn segments(&self, leaf: NameId) -> Vec<&str> {
        let mut parts = Vec::new();
        let mut cur = leaf;
        while let Some(parent) = self.nodes[cur as usize].parent {
            parts.push(self.nodes[cur as usize].segment.as_str());
            cur = parent;
        }
        parts.reverse();
        parts
    }

    /// Format the full hierarchical path for display.
    ///
    /// Joins segments with `.`, escaping any non-simple identifiers per
    /// the SystemVerilog `%m` convention (`\name `).
    pub fn format_path(&self, leaf: NameId) -> String {
        let segments = self.segments(leaf);
        segments
            .iter()
            .map(|s| format_segment(s))
            .collect::<Vec<_>>()
            .join(".")
    }

    /// Walk root->leaf by segments, returning the leaf `NameId` if found.
    pub fn find(&self, segments: &[&str]) -> Option<NameId> {
        let mut cur = self.root();
        for seg in segments {
            cur = *self.nodes[cur as usize].children.get(*seg)?;
        }
        Some(cur)
    }
}

impl Default for NameTree {
    fn default() -> Self {
        Self::new()
    }
}

/// Bundles a `SignalMap` with its associated `NameTree`.
#[derive(Debug)]
pub struct WaveHierarchy {
    pub signal_map: SignalMap,
    pub names: NameTree,
}

/// K-way merge of multiple receivers, forwarding items in time order.
///
/// Maintains a head item per receiver and always picks the one with the smallest
/// time (via `get_time`).  Each item is passed to `on_item`; if that returns an
/// error the merge stops and the error is propagated.
pub(crate) fn kway_merge_channels<T>(
    rxs: &[crossbeam_channel::Receiver<T>],
    get_time: impl Fn(&T) -> u64,
    mut on_item: impl FnMut(T) -> std::io::Result<()>,
) -> std::io::Result<()> {
    let mut heads: Vec<Option<T>> = rxs.iter().map(|rx| rx.recv().ok()).collect();
    loop {
        let min_idx = heads
            .iter()
            .enumerate()
            .filter_map(|(i, opt)| opt.as_ref().map(|c| (i, get_time(c))))
            .min_by_key(|&(_, t)| t)
            .map(|(i, _)| i);
        match min_idx {
            Some(idx) => {
                on_item(heads[idx].take().unwrap())?;
                heads[idx] = rxs[idx].recv().ok();
            }
            None => return Ok(()),
        }
    }
}

/// Direction string for signals with no explicit direction
const IMPLICIT_DIRECTION: &str = "implicit";

/// Variable metadata normalized across FST and VCD formats
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct VarMeta {
    /// Canonical type string: "wire", "reg", "integer", "real", etc.
    pub var_type: String,
    /// Bit width
    pub size: u32,
    /// Direction: "implicit", "input", "output", "inout", "buffer", "linkage"
    pub direction: String,
}

/// A single variable declaration: name, metadata, and optional attributes.
/// Aliased signals (same handle/id code) each get their own entry since
/// they can have different declared types.
#[derive(Debug, Clone)]
pub struct VarEntry {
    pub name: NameId,
    pub meta: VarMeta,
    /// Formatted attribute strings (enum tables, array types, etc.)
    pub attrs: Vec<String>,
}

/// Per-handle signal info: one or more variable declarations that share
/// the same underlying signal data (aliases).
#[derive(Debug, Clone)]
pub struct SignalInfo {
    pub vars: Vec<VarEntry>,
}

/// Mapping from signal handle indices to their full info
pub type SignalMap = HashMap<usize, SignalInfo>;

/// Extract just the names from a SignalMap, for use in streaming code
pub fn names_only(map: &SignalMap, tree: &NameTree) -> SignalNames {
    map.iter()
        .map(|(&k, info)| {
            (
                k,
                info.vars.iter().map(|v| tree.format_path(v.name)).collect(),
            )
        })
        .collect()
}

/// An FST reader over a buffered file
pub(crate) type FstFileReader = FstReader<BufReader<File>>;

/// Options for formatting variable names
#[derive(Debug, Clone, Default)]
pub struct NameOptions {
    /// Remove space before range brackets (e.g., "dat[3:0]" vs "dat [3:0]")
    pub no_range_space: bool,
}

/// Convert an FST variable type to its canonical VCD string
fn fst_var_type_str(t: FstVarType) -> &'static str {
    match t {
        FstVarType::Event => "event",
        FstVarType::Integer => "integer",
        FstVarType::Parameter => "parameter",
        FstVarType::Real => "real",
        FstVarType::RealParameter => "real_parameter",
        FstVarType::Reg => "reg",
        FstVarType::Supply0 => "supply0",
        FstVarType::Supply1 => "supply1",
        FstVarType::Time => "time",
        FstVarType::Tri => "tri",
        FstVarType::TriAnd => "triand",
        FstVarType::TriOr => "trior",
        FstVarType::TriReg => "trireg",
        FstVarType::Tri0 => "tri0",
        FstVarType::Tri1 => "tri1",
        FstVarType::Wand => "wand",
        FstVarType::Wire => "wire",
        FstVarType::Wor => "wor",
        FstVarType::Port => "port",
        FstVarType::SparseArray => "sparray",
        FstVarType::RealTime => "realtime",
        FstVarType::GenericString => "string",
        FstVarType::Bit => "bit",
        FstVarType::Logic => "logic",
        FstVarType::Int => "int",
        FstVarType::ShortInt => "shortint",
        FstVarType::LongInt => "longint",
        FstVarType::Byte => "byte",
        FstVarType::Enum => "enum",
        FstVarType::ShortReal => "shortreal",
    }
}

/// Convert an FST variable direction to its canonical string
fn fst_direction_str(d: FstVarDirection) -> &'static str {
    match d {
        FstVarDirection::Implicit => IMPLICIT_DIRECTION,
        FstVarDirection::Input => "input",
        FstVarDirection::Output => "output",
        FstVarDirection::InOut => "inout",
        FstVarDirection::Buffer => "buffer",
        FstVarDirection::Linkage => "linkage",
    }
}

/// Build a SignalMap and NameTree from an FST hierarchy
fn build_hierarchy<R: BufRead + Seek>(
    fst_reader: &mut fst_reader::FstReader<R>,
    options: &NameOptions,
) -> Result<(SignalMap, NameTree), String> {
    let mut signal_map: SignalMap = HashMap::new();
    let mut tree = NameTree::new();
    let mut scope_id: NameId = tree.root();
    let mut last_handle: Option<usize> = None;
    let mut enum_tables: HashMap<u64, (String, Vec<(String, String)>)> = HashMap::new();
    let mut enum_names: EnumNameRegistry = HashMap::new();
    let mut conflict_error: Option<String> = None;

    fst_reader
        .read_hierarchy(|entry| match entry {
            FstHierarchyEntry::Scope { name, .. } => {
                scope_id = tree.intern(scope_id, &name);
                last_handle = None;
            }
            FstHierarchyEntry::UpScope => {
                scope_id = tree.nodes[scope_id as usize].parent.unwrap_or(tree.root());
                last_handle = None;
            }
            FstHierarchyEntry::Var {
                tpe,
                direction,
                name,
                length,
                handle,
                ..
            } => {
                let name = if options.no_range_space {
                    name.replace(" [", "[")
                } else {
                    name
                };
                let leaf = tree.intern(scope_id, &name);
                let idx = handle.get_index();
                last_handle = Some(idx);
                // FST stores real sizes in bytes (8); normalize to bits (64)
                // to match VCD convention.
                let size = match tpe {
                    FstVarType::Real | FstVarType::RealParameter | FstVarType::RealTime => 64,
                    _ => length,
                };
                let entry = signal_map.entry(idx).or_insert_with(|| SignalInfo {
                    vars: Vec::new(),
                });
                entry.vars.push(VarEntry {
                    name: leaf,
                    meta: VarMeta {
                        var_type: fst_var_type_str(tpe).to_string(),
                        size,
                        direction: fst_direction_str(direction).to_string(),
                    },
                    attrs: Vec::new(),
                });
            }
            FstHierarchyEntry::EnumTable {
                name,
                handle,
                mapping,
            } => {
                // fst_reader stores mapping as (encoding, value_name);
                // normalize to (value_name, encoding) to match VCD convention.
                let mapping: Vec<(String, String)> =
                    mapping.into_iter().map(|(enc, val)| (val, enc)).collect();
                if conflict_error.is_none() {
                    if let Err(e) = check_enum_conflict(&mut enum_names, &name, &mapping) {
                        conflict_error = Some(e);
                    }
                }
                enum_tables.insert(handle, (name, mapping));
            }
            FstHierarchyEntry::EnumTableRef { handle } => {
                if let Some(var_idx) = last_handle {
                    if let Some((name, mapping)) = enum_tables.get(&handle) {
                        push_attr(&mut signal_map, var_idx, format_enum_attr(name, mapping));
                    }
                }
            }
            FstHierarchyEntry::Array { name, array_type, left, right } => {
                if let Some(var_idx) = last_handle {
                    push_attr(&mut signal_map, var_idx,
                        format_array_attr(&name, array_type, left, right));
                }
            }
            FstHierarchyEntry::Pack { name, pack_type, value } => {
                if let Some(var_idx) = last_handle {
                    push_attr(&mut signal_map, var_idx,
                        format_pack_attr(&name, pack_type, value));
                }
            }
            FstHierarchyEntry::SVEnum { name, enum_type, value } => {
                if let Some(var_idx) = last_handle {
                    push_attr(&mut signal_map, var_idx,
                        format_sv_enum_attr(&name, enum_type, value));
                }
            }
            _ => {}
        })
        .map_err(|e| format!("Failed to read hierarchy: {}", e))?;

    if let Some(e) = conflict_error {
        return Err(e);
    }

    Ok((signal_map, tree))
}

/// Write all variable names from the hierarchy to a writer
pub fn write_names<W: Write>(
    writer: &mut W,
    handle_to_names: &SignalNames,
    sort: bool,
) -> std::io::Result<()> {
    let mut entries: Vec<String> = handle_to_names
        .values()
        .flat_map(|names| names.iter().cloned())
        .collect();

    if sort {
        entries.sort();
    }

    for entry in entries {
        writeln!(writer, "{}", entry)?;
    }
    Ok(())
}

// -- VCD / unified API -------------------------------------------------------

/// A streaming VCD reader that yields signal changes on demand
///
/// Wraps a `vcd::Parser` and the id-to-handle mapping built from the header.
/// Changes are read lazily -- nothing is buffered beyond the parser's own
/// internal line buffer.
pub struct VcdData {
    parser: vcd::Parser<BufReader<File>>,
    id_to_idx: HashMap<vcd::IdCode, usize>,
    current_time: u64,
}

/// A reader backed by either an FST file (streamed via callbacks) or a VCD
/// file (streamed via an iterator-style parser)
pub enum WaveReader {
    Fst(Box<FstFileReader>),
    Vcd(VcdData),
}

/// Convert a VCD scalar Value to its character representation
fn vcd_value_char(v: vcd::Value) -> char {
    match v {
        vcd::Value::V0 => '0',
        vcd::Value::V1 => '1',
        vcd::Value::X => 'x',
        vcd::Value::Z => 'z',
    }
}

/// Read the next signal change from a VCD parser, skipping non-change commands
pub(crate) fn next_vcd_change(vcd_data: &mut VcdData) -> Option<(u64, usize, String)> {
    while let Some(Ok(cmd)) = vcd_data.parser.next() {
        match cmd {
            vcd::Command::Timestamp(t) => {
                vcd_data.current_time = t;
            }
            vcd::Command::ChangeScalar(id, val) => {
                if let Some(&idx) = vcd_data.id_to_idx.get(&id) {
                    return Some((vcd_data.current_time, idx, vcd_value_char(val).to_string()));
                }
            }
            vcd::Command::ChangeVector(id, ref vec) => {
                if let Some(&idx) = vcd_data.id_to_idx.get(&id) {
                    let s: String = vec.iter().map(vcd_value_char).collect();
                    return Some((vcd_data.current_time, idx, s));
                }
            }
            vcd::Command::ChangeReal(id, val) => {
                if let Some(&idx) = vcd_data.id_to_idx.get(&id) {
                    return Some((vcd_data.current_time, idx, val.to_string()));
                }
            }
            vcd::Command::ChangeString(id, ref s) => {
                if let Some(&idx) = vcd_data.id_to_idx.get(&id) {
                    return Some((vcd_data.current_time, idx, s.clone()));
                }
            }
            _ => {}
        }
    }
    None
}

/// Registry of enum table definitions, keyed by handle ID.
/// Each entry stores the table name and its (value_name, encoding) pairs.
type EnumTableRegistry = HashMap<i64, (String, Vec<(String, String)>)>;

/// Registry of fully qualified enum names (containing "::") to their mappings,
/// used to detect conflicting definitions from combined trace data.
type EnumNameRegistry = HashMap<String, Vec<(String, String)>>;

/// Format enum mapping pairs as "k=v k=v ..." for display.
fn format_mapping(mapping: &[(String, String)]) -> String {
    mapping.iter().map(|(k, v)| format!("{}={}", k, v)).collect::<Vec<_>>().join(" ")
}

/// Check whether a fully qualified enum definition conflicts with a previous one.
/// Returns `Err` if the name was seen before with a different mapping.
fn check_enum_conflict(
    enum_names: &mut EnumNameRegistry,
    name: &str,
    mapping: &[(String, String)],
) -> Result<(), String> {
    if !name.contains("::") {
        return Ok(());
    }
    match enum_names.entry(name.to_string()) {
        std::collections::hash_map::Entry::Occupied(e) => {
            if e.get() != mapping {
                return Err(format!(
                    "conflicting enum definitions for '{}': [{}] vs [{}]",
                    name,
                    format_mapping(e.get()),
                    format_mapping(mapping),
                ));
            }
        }
        std::collections::hash_map::Entry::Vacant(e) => {
            e.insert(mapping.to_vec());
        }
    }
    Ok(())
}

/// Parse a VCD enum table definition from the name field of a `misc 07` attribute.
/// Format: `<name> <count> <val1> ... <valN> <enc1> ... <encN>`
/// Returns the table name and key=value pairs matching the FST enum format.
fn parse_vcd_enum_table(name: &str) -> Option<(String, Vec<(String, String)>)> {
    let parts: Vec<&str> = name.split_whitespace().collect();
    if parts.len() < 2 {
        return None;
    }
    let table_name = parts[0].to_string();
    let count: usize = parts[1].parse().ok()?;
    if parts.len() < 2 + count * 2 {
        return None;
    }
    let values = &parts[2..2 + count];
    let encodings = &parts[2 + count..2 + count * 2];
    let mapping: Vec<(String, String)> = values
        .iter()
        .zip(encodings.iter())
        .map(|(v, e)| (v.to_string(), e.to_string()))
        .collect();
    Some((table_name, mapping))
}

/// Format an enum table as a string matching the FST enum attr format.
fn format_enum_attr(name: &str, mapping: &[(String, String)]) -> String {
    format!("enum {}: {}", name, format_mapping(mapping))
}

/// Format an FST array attribute to match VCD output.
/// VCD format: "array <subtype>: <name> <arg>"
fn format_array_attr(name: &str, array_type: FstArrayType, left: i32, right: i32) -> String {
    let subtype = match array_type {
        FstArrayType::None => "none",
        FstArrayType::Unpacked => "unpacked",
        FstArrayType::Packed => "packed",
        FstArrayType::Sparse => "sparse",
    };
    let arg = ((left as i64) << 32) | (right as u32 as i64);
    format!("array {}: {} {}", subtype, name, arg)
}

/// Format an FST pack attribute to match VCD output.
/// VCD format: "class <subtype>: <name> <value>"
fn format_pack_attr(name: &str, pack_type: FstPackType, value: u64) -> String {
    let subtype = match pack_type {
        FstPackType::None => "none",
        FstPackType::Unpacked => "unpacked",
        FstPackType::Packed => "packed",
        FstPackType::TaggedPacked => "tagged_packed",
    };
    format!("class {}: {} {}", subtype, name, value)
}

/// Format an FST SV enum attribute to match VCD output.
/// VCD format: "enum <subtype>: <name> <value>"
fn format_sv_enum_attr(name: &str, enum_type: FstEnumType, value: u64) -> String {
    let subtype = match enum_type {
        FstEnumType::Integer => "integer",
        FstEnumType::Bit => "bit",
        FstEnumType::Logic => "logic",
        FstEnumType::Int => "int",
        FstEnumType::ShortInt => "shortint",
        FstEnumType::LongInt => "longint",
        FstEnumType::Byte => "byte",
        FstEnumType::UnsignedInteger => "unsigned_integer",
        FstEnumType::UnsignedBit => "unsigned_bit",
        FstEnumType::UnsignedLogic => "unsigned_logic",
        FstEnumType::UnsignedInt => "unsigned_int",
        FstEnumType::UnsignedShortInt => "unsigned_shortint",
        FstEnumType::UnsignedLongInt => "unsigned_longint",
        FstEnumType::UnsignedByte => "unsigned_byte",
        FstEnumType::Reg => "reg",
        FstEnumType::Time => "time",
    };
    format!("enum {}: {} {}", subtype, name, value)
}

/// Push an attribute string onto the last VarEntry for a given handle.
fn push_attr(signal_map: &mut SignalMap, handle: usize, attr: String) {
    if let Some(info) = signal_map.get_mut(&handle) {
        if let Some(var_entry) = info.vars.last_mut() {
            var_entry.attrs.push(attr);
        }
    }
}

/// Walk the VCD scope item tree and populate hierarchy maps.
/// `scope_id` is the current position in the NameTree.
#[allow(clippy::too_many_arguments)]
fn walk_vcd_items(
    items: &[vcd::ScopeItem],
    scope_id: NameId,
    tree: &mut NameTree,
    signal_map: &mut SignalMap,
    id_to_idx: &mut HashMap<vcd::IdCode, usize>,
    enum_tables: &mut EnumTableRegistry,
    enum_names: &mut EnumNameRegistry,
    options: &NameOptions,
) -> Result<(), String> {
    let mut last_idx: Option<usize> = None;
    for item in items {
        match item {
            vcd::ScopeItem::Scope(scope) => {
                let child_id = tree.intern(scope_id, &scope.identifier);
                walk_vcd_items(
                    &scope.items,
                    child_id,
                    tree,
                    signal_map,
                    id_to_idx,
                    enum_tables,
                    enum_names,
                    options,
                )?;
                last_idx = None;
            }
            vcd::ScopeItem::Var(var) => {
                let next_idx = id_to_idx.len();
                let idx = *id_to_idx.entry(var.code).or_insert(next_idx);
                last_idx = Some(idx);

                let ref_name = if options.no_range_space {
                    var.reference.replace(" [", "[")
                } else {
                    var.reference.clone()
                };
                let name = match &var.index {
                    Some(vcd::ReferenceIndex::BitSelect(n)) => {
                        format!("{} [{}]", ref_name, n)
                    }
                    Some(vcd::ReferenceIndex::Range(hi, lo)) => {
                        if options.no_range_space {
                            format!("{}[{}:{}]", ref_name, hi, lo)
                        } else {
                            format!("{} [{}:{}]", ref_name, hi, lo)
                        }
                    }
                    None => ref_name,
                };
                let leaf = tree.intern(scope_id, &name);
                let entry = signal_map.entry(idx).or_insert_with(|| SignalInfo {
                    vars: Vec::new(),
                });
                entry.vars.push(VarEntry {
                    name: leaf,
                    meta: VarMeta {
                        var_type: var.var_type.to_string(),
                        size: var.size,
                        direction: IMPLICIT_DIRECTION.to_string(),
                    },
                    attrs: Vec::new(),
                });
            }
            vcd::ScopeItem::Attribute(attr) => {
                // For misc 07 (enum table): distinguish definitions from references.
                // Definitions have a non-empty, non-"" name with the full enum details.
                // References have "" as the name and the handle as arg.
                let is_enum_table = attr.attr_type == vcd::AttributeType::Misc
                    && attr.subtype == "07";
                if is_enum_table {
                    let name_trimmed = attr.name.trim_matches('"');
                    if !name_trimmed.is_empty() {
                        // Enum table definition -- register it and attach to current signal
                        if let Some(parsed) = parse_vcd_enum_table(&attr.name) {
                            check_enum_conflict(enum_names, &parsed.0, &parsed.1)?;
                            enum_tables.insert(attr.arg, parsed.clone());
                            if let Some(idx) = last_idx {
                                push_attr(signal_map, idx, format_enum_attr(&parsed.0, &parsed.1));
                            }
                        }
                    } else {
                        // Enum table reference -- resolve from registry
                        if let Some(idx) = last_idx {
                            if let Some((name, mapping)) = enum_tables.get(&attr.arg) {
                                push_attr(signal_map, idx, format_enum_attr(name, mapping));
                            }
                        }
                    }
                } else if let Some(idx) = last_idx {
                    let attr_str = format!("{} {}: {} {}", attr.attr_type, attr.subtype, attr.name, attr.arg);
                    push_attr(signal_map, idx, attr_str);
                }
            }
            _ => {}
        }
    }
    Ok(())
}

/// Build hierarchy from a parsed VCD header
fn build_vcd_hierarchy(
    header: &vcd::Header,
    options: &NameOptions,
) -> Result<(SignalMap, HashMap<vcd::IdCode, usize>, NameTree), String> {
    let mut signal_map: SignalMap = HashMap::new();
    let mut id_to_idx: HashMap<vcd::IdCode, usize> = HashMap::new();
    let mut tree = NameTree::new();
    let mut enum_tables: EnumTableRegistry = HashMap::new();
    let mut enum_names: EnumNameRegistry = HashMap::new();
    walk_vcd_items(
        &header.items,
        tree.root(),
        &mut tree,
        &mut signal_map,
        &mut id_to_idx,
        &mut enum_tables,
        &mut enum_names,
        options,
    )?;
    Ok((signal_map, id_to_idx, tree))
}

/// Write all signal attributes from the hierarchy to a writer
pub fn write_attrs<W: Write>(
    writer: &mut W,
    signal_map: &SignalMap,
    tree: &NameTree,
    sort: bool,
) -> std::io::Result<()> {
    let mut entries: Vec<(String, &VarMeta, &[String])> = signal_map
        .values()
        .flat_map(|info| {
            info.vars
                .iter()
                .map(|v| (tree.format_path(v.name), &v.meta, v.attrs.as_slice()))
        })
        .collect();

    if sort {
        entries.sort_by(|(a, _, _), (b, _, _)| a.cmp(b));
    }

    for (name, meta, attrs) in entries {
        if meta.direction != IMPLICIT_DIRECTION {
            writeln!(writer, "{}  {}  {}  {}", name, meta.var_type, meta.size, meta.direction)?;
        } else {
            writeln!(writer, "{}  {}  {}", name, meta.var_type, meta.size)?;
        }
        for attr in attrs {
            writeln!(writer, "  {}", attr)?;
        }
    }
    Ok(())
}

/// Merge multiple SignalMaps and NameTrees into one with remapped handles.
///
/// Each file's handles are offset so they don't collide. Returns the merged map,
/// merged tree, and per-file handle offsets. Errors if any signal name appears in
/// more than one file (duplicate signal) or if qualified enum definitions conflict
/// across files.
pub fn merge_signal_maps(
    maps: &[(&SignalMap, &NameTree, &str)],
) -> Result<(SignalMap, NameTree, Vec<usize>), String> {
    if maps.len() == 1 {
        // Single file -- clone the map but also rebuild the tree so NameIds
        // remain valid.  For single-file case, NameIds don't need remapping.
        let (map, tree, _) = maps[0];
        return Ok((map.clone(), clone_name_tree(tree), vec![0]));
    }

    let mut merged = SignalMap::new();
    let mut merged_tree = NameTree::new();
    let mut offsets = Vec::with_capacity(maps.len());
    let mut next_handle: usize = 0;
    let mut seen_names: HashMap<String, &str> = HashMap::new();
    let mut enum_names: EnumNameRegistry = HashMap::new();

    for &(map, tree, path) in maps {
        offsets.push(next_handle);
        for (&handle, info) in map {
            let new_handle = handle + next_handle;
            let mut new_vars = Vec::with_capacity(info.vars.len());
            for var in &info.vars {
                let flat_name = tree.format_path(var.name);
                if let Some(&prev_path) = seen_names.get(&flat_name) {
                    return Err(format!(
                        "duplicate signal '{}' found in both {} and {}",
                        flat_name, prev_path, path,
                    ));
                }
                seen_names.insert(flat_name, path);

                // Re-intern segments into merged tree
                let segments = tree.segments(var.name);
                let mut cur = merged_tree.root();
                for seg in &segments {
                    cur = merged_tree.intern(cur, seg);
                }

                // Check cross-file enum conflicts for qualified names
                for attr in &var.attrs {
                    if let Some(rest) = attr.strip_prefix("enum ") {
                        if let Some(colon_pos) = rest.find(':') {
                            let enum_name = rest[..colon_pos].trim();
                            if enum_name.contains("::") {
                                let mapping: Vec<(String, String)> = rest[colon_pos + 1..]
                                    .split_whitespace()
                                    .filter_map(|pair| {
                                        let (k, v) = pair.split_once('=')?;
                                        Some((k.to_string(), v.to_string()))
                                    })
                                    .collect();
                                check_enum_conflict(&mut enum_names, enum_name, &mapping)?;
                            }
                        }
                    }
                }
                new_vars.push(VarEntry {
                    name: cur,
                    meta: var.meta.clone(),
                    attrs: var.attrs.clone(),
                });
            }
            merged.insert(new_handle, SignalInfo { vars: new_vars });
        }
        let max_handle = map.keys().max().copied().unwrap_or(0);
        next_handle += max_handle + 1;
    }

    Ok((merged, merged_tree, offsets))
}

/// Clone a NameTree (the single-file shortcut avoids re-interning).
fn clone_name_tree(tree: &NameTree) -> NameTree {
    NameTree {
        nodes: tree
            .nodes
            .iter()
            .map(|n| NameNode {
                segment: n.segment.clone(),
                parent: n.parent,
                children: n.children.clone(),
            })
            .collect(),
    }
}

/// Open multiple waveform files and merge their hierarchies.
///
/// Each file is opened with the given format (or auto-detected if `None`).
/// Returns readers, the merged WaveHierarchy, and per-file handle offsets.
/// Errors if any signal name appears in multiple files.
pub fn open_wave_files(
    paths: &[&Path],
    options: &NameOptions,
    format: Option<WaveFormat>,
) -> Result<(Vec<WaveReader>, WaveHierarchy, Vec<usize>), String> {
    let mut readers = Vec::with_capacity(paths.len());
    let mut hierarchies = Vec::with_capacity(paths.len());

    for &path in paths {
        let (reader, hier) = open_wave_file_with_format(path, options, format)?;
        readers.push(reader);
        hierarchies.push(hier);
    }

    let maps_with_paths: Vec<(&SignalMap, &NameTree, &str)> = hierarchies
        .iter()
        .zip(paths.iter())
        .map(|(h, p)| (&h.signal_map, &h.names, p.to_str().unwrap_or("<unknown>")))
        .collect();

    let (merged_map, merged_tree, offsets) = merge_signal_maps(&maps_with_paths)?;
    Ok((
        readers,
        WaveHierarchy {
            signal_map: merged_map,
            names: merged_tree,
        },
        offsets,
    ))
}

/// Open a file as FST format
fn open_as_fst(
    buf: BufReader<File>,
    path: &Path,
    options: &NameOptions,
) -> Result<(WaveReader, WaveHierarchy), String> {
    let mut fst_reader = fst_reader::FstReader::open(buf)
        .map_err(|e| format!("Failed to open FST file {}: {}", path.display(), e))?;
    let (signal_map, tree) = build_hierarchy(&mut fst_reader, options)
        .map_err(|e| format!("Failed to read hierarchy from {}: {}", path.display(), e))?;
    Ok((
        WaveReader::Fst(Box::new(fst_reader)),
        WaveHierarchy {
            signal_map,
            names: tree,
        },
    ))
}

/// Open a file as VCD format
fn open_as_vcd(
    buf: BufReader<File>,
    path: &Path,
    options: &NameOptions,
) -> Result<(WaveReader, WaveHierarchy), String> {
    let mut parser = vcd::Parser::new(buf).with_gtkwave_extensions(true);
    let header = parser
        .parse_header()
        .map_err(|e| format!("Failed to parse VCD file {}: {}", path.display(), e))?;
    let (signal_map, id_to_idx, tree) = build_vcd_hierarchy(&header, options)?;
    let vcd_data = VcdData {
        parser,
        id_to_idx,
        current_time: 0,
    };
    Ok((
        WaveReader::Vcd(vcd_data),
        WaveHierarchy {
            signal_map,
            names: tree,
        },
    ))
}

/// Waveform file formats that can be forced via `--format`
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum WaveFormat {
    Fst,
    Vcd,
}

/// Open a waveform file (FST or VCD) and build its hierarchy
///
/// Format is detected from file contents: FST is checked first via magic bytes,
/// then VCD is attempted. Returns an error if neither format can parse the file.
pub fn open_wave_file(
    path: &Path,
    options: &NameOptions,
) -> Result<(WaveReader, WaveHierarchy), String> {
    open_wave_file_with_format(path, options, None)
}

/// Open a waveform file, optionally forcing a specific format.
///
/// When `format` is `None`, the format is auto-detected from file contents.
/// When `format` is `Some(WaveFormat::Fst)` or `Some(WaveFormat::Vcd)`, that
/// format is used directly and the error message reflects the specific format.
pub fn open_wave_file_with_format(
    path: &Path,
    options: &NameOptions,
    format: Option<WaveFormat>,
) -> Result<(WaveReader, WaveHierarchy), String> {
    let f = File::open(path).map_err(|e| format!("Failed to open {}: {}", path.display(), e))?;

    match format {
        Some(WaveFormat::Fst) => {
            let buf = BufReader::new(f);
            open_as_fst(buf, path, options)
        }
        Some(WaveFormat::Vcd) => {
            let buf = BufReader::new(f);
            open_as_vcd(buf, path, options)
        }
        None => {
            let mut buf = BufReader::new(f);
            if is_fst_file(&mut buf) {
                return open_as_fst(buf, path, options);
            }
            // Not FST -- try VCD.
            buf.seek(std::io::SeekFrom::Start(0))
                .map_err(|e| format!("Failed to seek in {}: {}", path.display(), e))?;
            open_as_vcd(buf, path, options)
        }
    }
}