#[cfg(test)]
mod tests;
mod path;
use std::{
collections::HashMap,
fmt,
str::FromStr,
sync::{
Arc, OnceLock,
atomic::{AtomicU64, Ordering},
},
};
use crate::{LookupError, PathError, PathFormatError, Result, SliceError};
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct HierarchyPath {
components: Vec<String>,
}
impl HierarchyPath {
pub fn parse(text: &str) -> std::result::Result<Self, PathError> {
path::parse(text).map(|components| Self { components })
}
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(),
}
}
pub fn components(&self) -> impl ExactSizeIterator<Item = &str> + '_ {
self.components.iter().map(String::as_str)
}
pub fn len(&self) -> usize {
self.components.len()
}
pub fn is_empty(&self) -> bool {
self.components.is_empty()
}
pub fn name(&self) -> Option<&str> {
self.components.last().map(String::as_str)
}
pub fn parent(&self) -> Option<Self> {
self.components.split_last().map(|(_, parent)| Self {
components: parent.to_vec(),
})
}
pub fn join(&self, component: impl Into<String>) -> Self {
let mut path = self.clone();
path.components.push(component.into());
path
}
pub fn to_verilog(&self) -> std::result::Result<String, PathFormatError> {
let mut output = String::new();
for component in &self.components {
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;
fn from_str(text: &str) -> std::result::Result<Self, Self::Err> {
Self::parse(text)
}
}
impl fmt::Display for HierarchyPath {
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(())
}
}
#[derive(Clone)]
pub struct Hierarchy {
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>,
pub(crate) variants: Vec<(String, String)>,
}
struct HierarchyData {
source: u64,
scopes: Vec<ScopeData>,
variables: Vec<VariableData>,
encodings: Vec<Encoding>,
first_variable_lookup: OnceLock<()>,
variables_by_path: OnceLock<HashMap<HierarchyPath, (usize, usize)>>,
}
static NEXT_SOURCE: AtomicU64 = AtomicU64::new(1);
pub enum Item<'h> {
Scope(Scope<'h>),
Variable(Variable<'h>),
}
pub struct Scope<'h> {
hierarchy: &'h Hierarchy,
index: usize,
}
pub struct Variable<'h> {
hierarchy: &'h Hierarchy,
index: usize,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Signal {
source: u64,
index: usize,
base_encoding: Encoding,
encoding: Encoding,
lsb: u32,
}
impl Hierarchy {
pub(crate) fn new(
scopes: Vec<ScopeData>,
variables: Vec<VariableData>,
encodings: Vec<Encoding>,
) -> Self {
let source = NEXT_SOURCE
.fetch_update(Ordering::Relaxed, Ordering::Relaxed, |id| id.checked_add(1))
.expect("hierarchy source IDs exhausted");
Self {
data: Arc::new(HierarchyData {
source,
scopes,
variables,
encodings,
first_variable_lookup: OnceLock::new(),
variables_by_path: OnceLock::new(),
}),
}
}
pub(crate) fn signal_at(&self, index: usize) -> Signal {
let encoding = self.data.encodings[index];
Signal {
source: self.data.source,
index,
base_encoding: encoding,
encoding,
lsb: 0,
}
}
pub(crate) fn validate(&self, signal: Signal) -> Result<usize> {
let valid = signal.source == self.data.source
&& self.data.encodings.get(signal.index) == 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: Option<usize>) -> impl Iterator<Item = Item<'_>> + '_ {
self.scopes()
.filter(move |scope| scope.data().parent == parent)
.map(Item::Scope)
.chain(
self.variables()
.filter(move |variable| variable.data().parent == parent)
.map(Item::Variable),
)
}
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 }
}
pub fn roots(&self) -> impl Iterator<Item = Item<'_>> + '_ {
self.children_of(None)
}
pub fn scopes(&self) -> impl Iterator<Item = Scope<'_>> + '_ {
(0..self.data.scopes.len()).map(|index| Scope {
hierarchy: self,
index,
})
}
pub fn variables(&self) -> impl Iterator<Item = Variable<'_>> + '_ {
(0..self.data.variables.len()).map(|index| Variable {
hierarchy: self,
index,
})
}
pub fn signals(&self) -> impl Iterator<Item = Signal> + '_ {
(0..self.data.encodings.len()).map(|index| self.signal_at(index))
}
pub fn scope(&self, text: &str) -> std::result::Result<Scope<'_>, LookupError> {
self.scope_path(&HierarchyPath::parse(text)?)
}
pub fn variable(&self, text: &str) -> std::result::Result<Variable<'_>, LookupError> {
self.variable_path(&HierarchyPath::parse(text)?)
}
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
}
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,
}),
}
}
pub fn variable_path(
&self,
path: &HierarchyPath,
) -> std::result::Result<Variable<'_>, LookupError> {
if self.data.variables_by_path.get().is_none()
&& self.data.first_variable_lookup.set(()).is_ok()
{
let mut matches = self.variables().filter(|variable| {
Some(variable.name()) == path.name() && variable.path() == *path
});
let first = matches.next();
return 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,
}),
};
}
let variables_by_path = self.data.variables_by_path.get_or_init(|| {
let mut index = HashMap::with_capacity(self.data.variables.len());
for variable in self.variables() {
let entry = index.entry(variable.path()).or_insert((variable.index, 0));
entry.1 += 1;
}
index
});
match variables_by_path.get(path) {
None => Err(LookupError::NotFound { path: path.clone() }),
Some(&(index, 1)) => Ok(Variable {
hierarchy: self,
index,
}),
Some(&(_, matches)) => Err(LookupError::Ambiguous {
path: path.clone(),
matches,
}),
}
}
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() })
}
pub fn aliases(&self, signal: Signal) -> Result<impl Iterator<Item = Variable<'_>> + '_> {
let index = self.validate(signal)?;
Ok(self
.variables()
.filter(move |variable| variable.data().signal == Some(index)))
}
}
impl<'h> Scope<'h> {
fn data(&self) -> &'h ScopeData {
&self.hierarchy.data.scopes[self.index]
}
pub fn name(&self) -> &'h str {
&self.data().name
}
pub fn path(&self) -> HierarchyPath {
self.hierarchy.scope_path_at(Some(self.index))
}
pub fn parent(&self) -> Option<Scope<'h>> {
self.data().parent.map(|index| Scope {
hierarchy: self.hierarchy,
index,
})
}
pub fn children(&self) -> impl Iterator<Item = Item<'h>> + '_ {
self.hierarchy.children_of(Some(self.index))
}
pub fn kind(&self) -> &'h str {
&self.data().kind
}
pub fn name_was_escaped(&self) -> bool {
self.data().name_was_escaped
}
pub fn is_hidden(&self) -> bool {
self.data().is_hidden
}
pub fn definition_name(&self) -> Option<&'h str> {
self.data().definition_name.as_deref()
}
pub fn packing(&self) -> Option<Packing> {
self.data().packing
}
}
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]
}
pub fn name(&self) -> &'h str {
&self.data().name
}
pub fn reader_name(&self) -> Option<&'h str> {
self.data().reader_name.as_deref()
}
pub fn name_was_escaped(&self) -> bool {
self.data().name_was_escaped
}
pub fn path(&self) -> HierarchyPath {
self.hierarchy
.scope_path_at(self.data().parent)
.join(self.name())
}
pub fn parent(&self) -> Option<Scope<'h>> {
self.data().parent.map(|index| Scope {
hierarchy: self.hierarchy,
index,
})
}
pub fn signal(&self) -> Option<Signal> {
self.data()
.signal
.map(|index| self.hierarchy.signal_at(index))
}
pub fn kind(&self) -> &'h str {
&self.data().kind
}
pub fn direction(&self) -> Direction {
self.data().direction
}
pub fn range(&self) -> Option<BitRange> {
self.data().range
}
pub fn is_constant(&self) -> bool {
self.data().is_constant
}
pub fn type_name(&self) -> Option<&'h str> {
self.data().type_name.as_deref()
}
pub fn signedness(&self) -> Option<Signedness> {
self.data().signedness
}
pub fn logic_domain(&self) -> Option<LogicDomain> {
self.data().logic_domain
}
pub fn enumeration(&self) -> Option<Enumeration<'h>> {
self.data()
.enumeration
.as_ref()
.map(|data| Enumeration { data })
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum Signedness {
Signed,
Unsigned,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum LogicDomain {
TwoState,
FourState,
NineState,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum Direction {
Unknown,
Implicit,
Input,
Output,
InOut,
Buffer,
Linkage,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum Packing {
Packed,
Unpacked,
Sparse,
TaggedPacked,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct BitRange {
msb: i64,
lsb: i64,
}
impl BitRange {
pub const fn new(msb: i64, lsb: i64) -> Self {
Self { msb, lsb }
}
pub const fn msb(self) -> i64 {
self.msb
}
pub const fn lsb(self) -> i64 {
self.lsb
}
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"),
}
}
}
pub struct Enumeration<'h> {
data: &'h EnumerationData,
}
impl<'h> Enumeration<'h> {
pub fn name(&self) -> Option<&'h str> {
self.data.name.as_deref()
}
pub fn variants(&self) -> impl Iterator<Item = EnumerationVariant<'h>> + '_ {
self.data
.variants
.iter()
.map(|(encoded, label)| EnumerationVariant { encoded, label })
}
}
pub struct EnumerationVariant<'h> {
pub encoded: &'h str,
pub label: &'h str,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Encoding {
Bits {
width: u32,
},
Real,
String,
Event,
Unsupported,
}
impl Signal {
pub(crate) fn index(self) -> usize {
self.index
}
pub(crate) fn lsb(self) -> u32 {
self.lsb
}
pub fn encoding(self) -> Encoding {
self.encoding
}
pub fn width(self) -> Option<u32> {
match self.encoding {
Encoding::Bits { width } => Some(width),
_ => None,
}
}
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
})
}
pub fn base(self) -> Self {
Self {
encoding: self.base_encoding,
lsb: 0,
..self
}
}
pub fn is_slice(self) -> bool {
self != self.base()
}
}