[ILibraryView] don't fail on nested dangling ref

This commit is contained in:
Jan Petykiewicz 2026-03-30 23:34:31 -07:00
commit d03fafcaf6
2 changed files with 21 additions and 2 deletions

View file

@ -294,8 +294,9 @@ class ILibraryView(Mapping[str, 'Pattern'], metaclass=ABCMeta):
def flatten_single(name: str) -> None: def flatten_single(name: str) -> None:
flattened[name] = None flattened[name] = None
pat = self[name].deepcopy() pat = self[name].deepcopy()
refs_by_target = tuple((target, tuple(refs)) for target, refs in pat.refs.items())
for target in pat.refs: for target, refs in refs_by_target:
if target is None: if target is None:
continue continue
if dangling_ok and target not in self: if dangling_ok and target not in self:
@ -310,7 +311,7 @@ class ILibraryView(Mapping[str, 'Pattern'], metaclass=ABCMeta):
if target_pat.is_empty() and not ports_only: # avoid some extra allocations if target_pat.is_empty() and not ports_only: # avoid some extra allocations
continue continue
for ref in pat.refs[target]: for ref in refs:
if flatten_ports and ref.repetition is not None and target_pat.ports: if flatten_ports and ref.repetition is not None and target_pat.ports:
raise PatternError( raise PatternError(
f'Cannot flatten ports from repeated ref to {target!r}; ' f'Cannot flatten ports from repeated ref to {target!r}; '

View file

@ -166,6 +166,24 @@ def test_library_flatten_repeated_ref_with_ports_raises() -> None:
lib.flatten("parent", flatten_ports=True) lib.flatten("parent", flatten_ports=True)
def test_library_flatten_dangling_ok_nested_preserves_dangling_refs() -> None:
lib = Library()
child = Pattern()
child.ref("missing")
lib["child"] = child
parent = Pattern()
parent.ref("child")
lib["parent"] = parent
flat = lib.flatten("parent", dangling_ok=True)
assert set(flat["child"].refs) == {"missing"}
assert flat["child"].has_refs()
assert set(flat["parent"].refs) == {"missing"}
assert flat["parent"].has_refs()
def test_lazy_library() -> None: def test_lazy_library() -> None:
lib = LazyLibrary() lib = LazyLibrary()
called = 0 called = 0