use super::*;
fn fixture() -> Hierarchy {
let scopes = vec![
ScopeData {
name: "tb".into(),
name_was_escaped: false,
parent: None,
kind: "module".into(),
definition_name: Some("testbench".into()),
packing: None,
is_hidden: false,
},
ScopeData {
name: "dut".into(),
name_was_escaped: false,
parent: Some(0),
kind: "struct".into(),
definition_name: None,
packing: Some(Packing::Packed),
is_hidden: false,
},
];
let variables = [
("data", Some(0)),
("alias", Some(0)),
("data[7:0]", Some(1)),
("mem[0]", Some(0)),
("no_history", None),
("duplicate", Some(0)),
("duplicate", Some(0)),
("with space", Some(0)),
]
.into_iter()
.map(|(name, signal)| VariableData {
name: name.into(),
reader_name: None,
name_was_escaped: false,
parent: Some(1),
kind: "wire".into(),
direction: Direction::Input,
range: Some(BitRange::new(-16, 15)),
is_constant: true,
type_name: Some("state_t".into()),
signedness: None,
logic_domain: None,
enumeration: Some(EnumerationData {
name: Some("state_t".into()),
variants: vec![("00".into(), "IDLE".into()), ("01".into(), "RUN".into())],
}),
signal,
})
.collect();
Hierarchy::new(
scopes,
variables,
vec![
Encoding::Bits { width: 32 },
Encoding::Bits { width: 8 },
Encoding::Real,
],
)
}
#[test]
fn path_index_is_lazy_and_shared_between_hierarchy_clones() {
let hierarchy = fixture();
let cloned = hierarchy.clone();
assert!(hierarchy.data.variables_by_path.get().is_none());
for variable in hierarchy.variables() {
let _ = variable.path();
}
assert!(hierarchy.data.variables_by_path.get().is_none());
assert_eq!(cloned.variable("tb.dut.data").unwrap().name(), "data");
assert!(hierarchy.data.variables_by_path.get().is_none());
assert_eq!(hierarchy.variable("tb.dut.alias").unwrap().name(), "alias");
let index = hierarchy.data.variables_by_path.get().unwrap();
assert!(std::ptr::eq(
index,
cloned.data.variables_by_path.get().unwrap()
));
assert!(matches!(
hierarchy.variable("tb.dut.duplicate"),
Err(LookupError::Ambiguous { matches: 2, .. })
));
let ambiguous = fixture();
assert!(matches!(
ambiguous.variable("tb.dut.duplicate"),
Err(LookupError::Ambiguous { matches: 2, .. })
));
assert!(ambiguous.data.variables_by_path.get().is_none());
let missing = fixture();
assert!(matches!(
missing.variable("tb.dut.absent"),
Err(LookupError::NotFound { .. })
));
assert!(missing.data.variables_by_path.get().is_none());
assert_eq!(missing.variable("tb.dut.data").unwrap().name(), "data");
assert!(missing.data.variables_by_path.get().is_some());
let exact = fixture();
assert_eq!(exact.signal("tb.dut.data[7:0]").unwrap().width(), Some(8));
assert!(exact.data.variables_by_path.get().is_none());
let fallback = fixture();
assert_eq!(
fallback.signal("tb.dut.data[1:0]").unwrap().width(),
Some(2)
);
assert!(fallback.data.variables_by_path.get().is_some());
}
#[test]
fn hidden_flag_is_local_and_does_not_filter_hierarchy() {
let mut hierarchy = fixture();
Arc::get_mut(&mut hierarchy.data).unwrap().scopes[0].is_hidden = true;
let parent = hierarchy.scope("tb").unwrap();
let child = hierarchy.scope("tb.dut").unwrap();
assert!(parent.is_hidden());
assert!(!child.is_hidden());
assert!(child.parent().unwrap().is_hidden());
assert!(parent.children().next().is_some());
assert!(hierarchy.variable("tb.dut.data").is_ok());
}
#[test]
fn indexed_paths_match_linear_lookup_across_duplicate_scope_paths() {
let mut data = Arc::try_unwrap(fixture().data).ok().unwrap();
for parent in [None, Some(2)] {
data.scopes.push(ScopeData {
name: if parent.is_none() { "tb" } else { "dut" }.into(),
name_was_escaped: false,
parent,
kind: "module".into(),
definition_name: None,
packing: None,
is_hidden: false,
});
}
let variable = data.variables.last_mut().unwrap();
variable.name = "data".into();
variable.parent = Some(3);
let hierarchy = Hierarchy::new(data.scopes, data.variables, data.encodings);
let paths = hierarchy
.variables()
.map(|variable| variable.path())
.chain([
HierarchyPath::from_components([] as [&str; 0]),
HierarchyPath::parse("tb.missing").unwrap(),
]);
for path in paths {
let expected = hierarchy
.variables()
.filter(|variable| variable.path() == path)
.map(|variable| variable.index)
.collect::<Vec<_>>();
match hierarchy.variable_path(&path) {
Ok(variable) => assert_eq!(expected, [variable.index]),
Err(LookupError::NotFound { .. }) => assert!(expected.is_empty()),
Err(LookupError::Ambiguous { matches, .. }) => {
assert!(expected.len() > 1);
assert_eq!(matches, expected.len());
}
Err(error) => panic!("unexpected lookup error: {error}"),
}
}
assert_eq!(
hierarchy
.scopes()
.map(|scope| scope.name())
.collect::<Vec<_>>(),
["tb", "dut", "tb", "dut"]
);
assert_eq!(
hierarchy
.variables()
.map(|variable| variable.name())
.collect::<Vec<_>>(),
[
"data",
"alias",
"data[7:0]",
"mem[0]",
"no_history",
"duplicate",
"duplicate",
"data"
]
);
}
#[test]
fn hierarchy_views_aliases_and_metadata() {
let hierarchy = fixture();
assert_eq!(hierarchy.roots().count(), 1);
assert_eq!(hierarchy.scopes().count(), 2);
assert_eq!(hierarchy.variables().count(), 8);
assert_eq!(hierarchy.signals().count(), 3);
let tb = hierarchy.scope("tb").unwrap();
assert_eq!(tb.name(), "tb");
assert!(tb.parent().is_none());
assert_eq!(tb.kind(), "module");
assert_eq!(tb.definition_name(), Some("testbench"));
assert!(matches!(tb.children().next(), Some(Item::Scope(_))));
let dut = hierarchy.scope("tb.dut").unwrap();
assert_eq!(dut.parent().unwrap().path(), tb.path());
assert_eq!(dut.packing(), Some(Packing::Packed));
assert_eq!(dut.children().count(), 8);
assert!(dut.children().all(|item| matches!(item, Item::Variable(_))));
let data = hierarchy.variable("tb.dut.data").unwrap();
assert_eq!(data.name(), "data");
assert_eq!(data.parent().unwrap().path(), dut.path());
assert_eq!(data.kind(), "wire");
assert_eq!(data.direction(), Direction::Input);
assert!(data.is_constant());
assert_eq!(data.type_name(), Some("state_t"));
assert_eq!(data.range(), Some(BitRange::new(-16, 15)));
assert_eq!(data.range().unwrap().width(), 32);
assert_eq!(data.range().unwrap().msb(), -16);
assert_eq!(data.range().unwrap().lsb(), 15);
let enumeration = data.enumeration().unwrap();
assert_eq!(enumeration.name(), Some("state_t"));
assert_eq!(
enumeration
.variants()
.map(|v| (v.encoded, v.label))
.collect::<Vec<_>>(),
[("00", "IDLE"), ("01", "RUN")]
);
let whole = data.signal().unwrap();
assert_eq!(hierarchy.signal("tb.dut.alias").unwrap(), whole);
let names = |signal| {
hierarchy
.aliases(signal)
.unwrap()
.map(|v| v.name())
.collect::<Vec<_>>()
};
assert_eq!(
names(whole),
names(whole.slice(23, 8).unwrap().slice(7, 0).unwrap())
);
assert_eq!(names(whole).len(), 6);
let clone = hierarchy.clone();
assert_eq!(clone.validate(whole).unwrap(), 0);
drop(hierarchy);
assert_eq!(clone.variable("tb.dut.data").unwrap().name(), "data");
}
#[test]
fn interpretation_belongs_to_declarations_not_shared_histories() {
let cases = [
(
"signed",
Some(0),
Some(Signedness::Signed),
Some(LogicDomain::NineState),
),
(
"unsigned_alias",
Some(0),
Some(Signedness::Unsigned),
Some(LogicDomain::TwoState),
),
(
"four_state_alias",
Some(0),
None,
Some(LogicDomain::FourState),
),
("unknown_alias", Some(0), None, None),
("real", Some(1), None, None),
("string", Some(2), None, None),
("event", Some(3), None, None),
("no_history", None, None, None),
];
let hierarchy = Hierarchy::new(
vec![],
cases
.iter()
.map(|&(name, signal, signedness, logic_domain)| VariableData {
name: name.into(),
reader_name: None,
name_was_escaped: false,
parent: None,
kind: "variable".into(),
direction: Direction::Unknown,
range: None,
is_constant: false,
type_name: None,
signedness,
logic_domain,
enumeration: None,
signal,
})
.collect(),
vec![
Encoding::Bits { width: 8 },
Encoding::Real,
Encoding::String,
Encoding::Event,
],
);
for (name, signal, signedness, logic_domain) in cases {
let variable = hierarchy.variable(name).unwrap();
assert_eq!(variable.signedness(), signedness);
assert_eq!(variable.logic_domain(), logic_domain);
assert_eq!(
variable.signal(),
signal.map(|index| hierarchy.signal_at(index))
);
}
let signal = hierarchy.signal("signed").unwrap();
assert_eq!(signal, hierarchy.signal("unsigned_alias").unwrap());
assert_eq!(signal.encoding(), Encoding::Bits { width: 8 });
assert_eq!(signal.slice(3, 0).unwrap().width(), Some(4));
assert_eq!(hierarchy.aliases(signal).unwrap().count(), 4);
}
#[test]
fn exact_lookup_precedes_selectors() {
let hierarchy = fixture();
let data = hierarchy.signal("tb.dut.data").unwrap();
assert_eq!(
hierarchy.signal("tb.dut.data[7:0]").unwrap(),
hierarchy.signal_at(1)
);
assert_eq!(
hierarchy.signal("tb.dut.data[15:8]").unwrap(),
data.slice(15, 8).unwrap()
);
assert_eq!(
hierarchy.signal("tb.dut.mem[0][7:0]").unwrap(),
data.slice(7, 0).unwrap()
);
assert_eq!(
hierarchy.signal(r#"tb.dut."with space"[7:0]"#).unwrap(),
data.slice(7, 0).unwrap()
);
assert_eq!(
hierarchy
.signal("tb.dut.\\with+punct [7:0]")
.err()
.map(|e| matches!(e, LookupError::NotFound { .. })),
Some(true)
);
assert_eq!(
hierarchy.signal(r#"tb.dut."data[7:0]""#).unwrap(),
hierarchy.signal_at(1)
);
assert!(matches!(
hierarchy.signal("tb.dut.data[0]"),
Err(LookupError::NotFound { .. })
));
assert!(matches!(
hierarchy.signal("tb.dut.duplicate"),
Err(LookupError::Ambiguous { matches: 2, .. })
));
assert!(matches!(
hierarchy.signal("tb.dut.duplicate[7:0]"),
Err(LookupError::Ambiguous { matches: 2, .. })
));
assert!(matches!(
hierarchy.signal("tb.dut.no_history"),
Err(LookupError::NoSignal { .. })
));
assert!(matches!(
hierarchy.signal("tb.dut.no_history[7:0]"),
Err(LookupError::NoSignal { .. })
));
assert!(matches!(
hierarchy.signal("tb.dut.data[32:0]"),
Err(LookupError::InvalidSlice(SliceError::OutOfBounds { .. }))
));
assert!(matches!(
hierarchy.signal("tb.dut.data[0:1]"),
Err(LookupError::InvalidSlice(SliceError::InvalidRange { .. }))
));
for text in [
"tb.dut.data[x:0]",
"tb.dut.data[-1:0]",
"tb.dut.data[4294967296:0]",
] {
assert!(
matches!(hierarchy.signal(text), Err(LookupError::InvalidPath(_))),
"{text}"
);
}
}
#[test]
fn signals_compose_normalize_and_validate() {
let hierarchy = fixture();
let data = hierarchy.signal_at(0);
assert!(!data.is_slice());
assert_eq!(data.slice(31, 0).unwrap(), data);
let slice = data.slice(31, 16).unwrap().slice(7, 0).unwrap();
assert_eq!(slice, data.slice(23, 16).unwrap());
assert_eq!(slice.slice(7, 0).unwrap(), slice);
assert_eq!(slice.base(), data);
assert!(slice.is_slice());
assert_eq!(slice.index(), 0);
assert_eq!(slice.lsb(), 16);
assert_eq!(slice.encoding(), Encoding::Bits { width: 8 });
assert_eq!(slice.width(), Some(8));
assert!(matches!(
slice.slice(8, 0),
Err(SliceError::OutOfBounds { width: 8, .. })
));
assert_eq!(hierarchy.signal_at(2).width(), None);
assert!(matches!(
hierarchy.signal_at(2).slice(0, 0),
Err(SliceError::NotBits)
));
assert!(matches!(
fixture().aliases(slice),
Err(crate::Error::InvalidSignal { .. })
));
assert!(matches!(
fixture().validate(data),
Err(crate::Error::InvalidSignal { .. })
));
assert_eq!(hierarchy.validate(slice).unwrap(), 0);
for invalid in [
Signal {
index: usize::MAX,
..data
},
Signal {
base_encoding: Encoding::Real,
..data
},
Signal {
encoding: Encoding::Real,
..data
},
Signal {
encoding: Encoding::Bits { width: 0 },
..data
},
Signal {
lsb: u32::MAX,
..slice
},
Signal { lsb: 30, ..slice },
Signal {
lsb: 1,
..hierarchy.signal_at(2)
},
] {
assert!(matches!(
hierarchy.validate(invalid),
Err(crate::Error::InvalidSignal { .. })
));
}
}
#[test]
fn root_declarations_duplicate_scopes_and_extreme_ranges() {
let hierarchy = Hierarchy::new(
vec![
ScopeData {
name: "same".into(),
parent: None,
kind: "module".into(),
definition_name: None,
packing: None,
is_hidden: false,
name_was_escaped: false,
},
ScopeData {
name: "same".into(),
parent: None,
kind: "module".into(),
definition_name: None,
packing: None,
is_hidden: false,
name_was_escaped: false,
},
],
vec![VariableData {
name: "root".into(),
reader_name: None,
name_was_escaped: false,
parent: None,
kind: "parameter".into(),
direction: Direction::Unknown,
range: None,
is_constant: true,
type_name: None,
signedness: None,
logic_domain: None,
enumeration: None,
signal: None,
}],
vec![],
);
assert_eq!(hierarchy.roots().count(), 3);
assert!(matches!(
hierarchy.scope("same"),
Err(LookupError::Ambiguous { matches: 2, .. })
));
assert!(matches!(
hierarchy.scope(""),
Err(LookupError::NotFound { .. })
));
let root = hierarchy.variable("root").unwrap();
assert!(root.parent().is_none());
assert_eq!(root.path().to_string(), "root");
assert!(root.signal().is_none());
assert!(root.enumeration().is_none());
assert_eq!(BitRange::new(i64::MIN, i64::MAX - 1).width(), u64::MAX);
}
#[test]
#[should_panic(expected = "range width exceeds u64")]
fn unrepresentable_range_width_panics() {
BitRange::new(i64::MIN, i64::MAX).width();
}
#[test]
fn paths_round_trip_and_keep_exact_components() {
let root = HierarchyPath::parse("").unwrap();
assert!(root.is_empty());
assert_eq!(root.len(), 0);
assert_eq!(root.name(), None);
assert_eq!(root.parent(), None);
assert_eq!(root.to_string(), "");
assert_eq!(root.to_verilog().unwrap(), "");
let path = HierarchyPath::parse(r#"tb.\gen.blk[0] ."имя сигнала"."""#).unwrap();
assert_eq!(
path.components().collect::<Vec<_>>(),
["tb", "gen.blk[0]", "имя сигнала", ""]
);
assert_eq!(path.to_string(), r#"tb."gen.blk[0]"."имя сигнала"."""#);
assert_eq!(HierarchyPath::parse(&path.to_string()).unwrap(), path);
assert_eq!(path.parent().unwrap().join(""), path);
assert!(path.to_verilog().is_err());
let sv = HierarchyPath::from_components(["tb", "gen.blk[0]", "module", "a\\b", "a\"b"]);
assert_eq!(HierarchyPath::parse(&sv.to_verilog().unwrap()).unwrap(), sv);
for name in [
"", ".", "..", "a.b", "[7:0]", "a b", "\\", "\"", "a/b", "é", "\0\u{1f}", "\u{7f}",
] {
let path = HierarchyPath::from_components([name]);
assert_eq!(HierarchyPath::parse(&path.to_string()).unwrap(), path);
}
}
#[test]
fn exact_unicode_paths_do_not_normalize_names() {
let names = ["é", "e\u{301}"];
let hierarchy = Hierarchy::new(
vec![],
names
.iter()
.enumerate()
.map(|(index, name)| VariableData {
name: (*name).into(),
reader_name: None,
name_was_escaped: false,
parent: None,
kind: "wire".into(),
direction: Direction::Unknown,
range: None,
is_constant: false,
type_name: None,
signedness: None,
logic_domain: None,
enumeration: None,
signal: Some(index),
})
.collect(),
vec![Encoding::Bits { width: 1 }; 2],
);
let root = HierarchyPath::from_components(Vec::<String>::new());
let mut resolved = Vec::new();
for name in names {
let path = root.join(name);
assert!(root.is_empty(), "join must not mutate its source");
assert_eq!(path.len(), 1);
assert_eq!(path.components().len(), 1);
assert_eq!(path.parent(), Some(root.clone()));
let parsed: HierarchyPath = path.to_string().parse().unwrap();
assert_eq!(parsed, path);
let declaration = hierarchy.variable_path(&parsed).unwrap();
assert_eq!(declaration.name(), name);
assert_eq!(declaration.path(), path);
resolved.push(hierarchy.signal_path(&parsed).unwrap());
assert!(
matches!(path.to_verilog(), Err(PathFormatError::NotRepresentable { component }) if component == name)
);
}
assert_ne!(resolved[0], resolved[1]);
assert_eq!(hierarchy.signal(r#""\u00e9""#).unwrap(), resolved[0]);
let bad: std::result::Result<HierarchyPath, _> = "é..x".parse();
assert_eq!(bad.unwrap_err().offset, 3);
assert!(
matches!(hierarchy.variable("é..x"), Err(LookupError::InvalidPath(error)) if error.offset == 3)
);
}
#[test]
fn quoted_json_escapes_and_surrogates() {
let path = HierarchyPath::parse(r#""\"\\\/\b\f\n\r\t\u0000\u001f\uD83D\uDE00""#).unwrap();
assert_eq!(path.name(), Some("\"\\/\u{8}\u{c}\n\r\t\0\u{1f}😀"));
assert_eq!(path.to_string(), r#""\"\\/\b\f\n\r\t\u0000\u001f😀""#);
assert_eq!(
HierarchyPath::parse(r#"tb."a\u000Ab""#)
.unwrap()
.to_string(),
r#"tb."a\nb""#
);
}
#[test]
fn path_errors_have_byte_offsets() {
for (text, offset) in [
(".", 0),
("a..b", 2),
("a.", 2),
("é. bad", 3),
("é.a b", 4),
("a\\b", 1),
("\\", 1),
("\\abc", 4),
("\"abc", 4),
("\"a\"b", 3),
("\"é\\q\"", 4),
("\"a\nb\"", 2),
] {
let error = HierarchyPath::parse(text).unwrap_err();
assert_eq!(error.offset, offset, "{text:?}: {error}");
}
for text in [
r#""\uD800""#,
r#""\uDC00""#,
r#""\uD800\u0041""#,
r#""\u12""#,
r#""\uXXXX""#,
r#""\q""#,
"\"a\\",
"a. ",
"a.\\ .b",
] {
let error = HierarchyPath::parse(text).unwrap_err();
assert!(error.offset <= text.len(), "{text:?}: {error}");
}
}