tryFromPathname static method

OccurrenceAddress? tryFromPathname(
  1. String pathname,
  2. HierarchyOccurrence root, {
  3. bool occurrencesOnly = false,
})

Resolve a pathname string (e.g. "Top/counter/clk" or "Top.counter.clk") to a OccurrenceAddress by walking root.

Supports both / hierarchy paths and dot-separated signal identifiers commonly produced by VCD/FST waveform files. If the first segment matches root's instance name or definition name, it is skipped — the root occurrence is always at the empty address.

The last segment is first tried as a signal name within the current occurrence; if that fails it is tried as a child occurrence name. Set occurrencesOnly to look up only child occurrences. This mirrors the pathname convention where a signal path has one more segment than its parent module path.

Returns null if any segment cannot be resolved.

final addr = OccurrenceAddress.tryFromPathname('Top/cpu/clk', root);
if (addr != null) {
  final signal = service.signalByAddress(addr);
}

Implementation

static OccurrenceAddress? tryFromPathname(
  String pathname,
  HierarchyOccurrence root, {
  bool occurrencesOnly = false,
}) {
  final rootAddr = root.address ?? OccurrenceAddress.root;
  final parts = pathname
      .replaceAll('.', hierarchyPathSeparator)
      .split(hierarchyPathSeparator)
      .where((s) => s.isNotEmpty)
      .toList();

  // The hierarchy root retains the waveform instance name while the
  // schematic displays the module definition. Accept either as a prefix.
  final isRootPrefix = parts.isNotEmpty &&
      (parts.first == root.name || parts.first == root.definition);
  final start = isRootPrefix ? 1 : 0;

  ({HierarchyOccurrence node, OccurrenceAddress addr})? step(
    ({HierarchyOccurrence node, OccurrenceAddress addr})? cur,
    (int, String) part,
  ) {
    if (cur == null) {
      return null;
    }
    final (index, segment) = part;
    if (!occurrencesOnly && index == parts.length - 1) {
      final si = cur.node.signalIndexByName(segment);
      if (si >= 0) {
        return (node: cur.node, addr: cur.addr.signal(si));
      }
    }
    final ci = cur.node.childIndexByName(segment);
    return ci >= 0
        ? (node: cur.node.children[ci], addr: cur.addr.child(ci))
        : null;
  }

  return parts.indexed
      .skip(start)
      .fold<({HierarchyOccurrence node, OccurrenceAddress addr})?>(
    (node: root, addr: rootAddr),
    step,
  )?.addr;
}