addressToPathname method

String? addressToPathname(
  1. OccurrenceAddress address, {
  2. bool asSignal = false,
})

Convert a OccurrenceAddress back to a /-separated pathname by walking the tree using child indices.

Returns null if the address doesn't resolve in the current tree (e.g. out-of-bounds indices). O(depth).

For signal addresses, the last index is resolved as a signal within the parent occurrence. For pure occurrence addresses, every index is a child.

Set asSignal to true when you know the address points to a signal (the last index is a signal offset rather than a child offset). When false (default), all indices are treated as child offsets.

Implementation

String? addressToPathname(OccurrenceAddress address,
    {bool asSignal = false}) {
  if (address.path.isEmpty) {
    return root.name;
  }

  final indices = address.path;
  final moduleEndIdx = asSignal ? indices.length - 1 : indices.length;

  final walked = indices
      .sublist(0, moduleEndIdx)
      .fold<({List<String> parts, HierarchyOccurrence node})?>((
    parts: [root.name],
    node: root,
  ), (cur, idx) {
    if (cur == null || idx < 0 || idx >= cur.node.children.length) {
      return null;
    }
    final child = cur.node.children[idx];
    return (parts: [...cur.parts, child.name], node: child);
  });
  if (walked == null) {
    return null;
  }

  if (asSignal && indices.isNotEmpty) {
    final sigIdx = indices.last;
    return (sigIdx >= 0 && sigIdx < walked.node.signals.length)
        ? [...walked.parts, walked.node.signals[sigIdx].name]
            .join(hierarchyPathSeparator)
        : null;
  }
  return walked.parts.join(hierarchyPathSeparator);
}