Link each Go interface method to the methods of every type that satisfies the interface.
(
per_file: list[dict],
all_nodes: list[dict],
all_edges: list[dict],
)
| 61 | |
| 62 | |
| 63 | def resolve_go_interface_dispatch( |
| 64 | per_file: list[dict], |
| 65 | all_nodes: list[dict], |
| 66 | all_edges: list[dict], |
| 67 | ) -> None: |
| 68 | """Link each Go interface method to the methods of every type that satisfies the interface.""" |
| 69 | interfaces = {n.get("id"): n for n in all_nodes if _is_go_interface(n) and declared_in(n, _GO_SUFFIXES)} |
| 70 | if not interfaces: |
| 71 | return |
| 72 | node_by_id = {n.get("id"): n for n in all_nodes} |
| 73 | |
| 74 | method_names: dict[str, set[str]] = {} |
| 75 | embeds: dict[str, set[str]] = {} |
| 76 | type_set_constrained: set[str] = set() |
| 77 | for e in all_edges: |
| 78 | rel, source = e.get("relation"), e.get("source") |
| 79 | if rel == "method": |
| 80 | mnode = node_by_id.get(e.get("target")) |
| 81 | if mnode is not None and declared_in(mnode, _GO_SUFFIXES) and method_label(mnode): |
| 82 | method_names.setdefault(source, set()).add(method_label(mnode)) |
| 83 | elif source in interfaces and rel == "embeds": |
| 84 | embeds.setdefault(source, set()).add(e.get("target")) |
| 85 | elif source in interfaces and rel == "references" and e.get("context") == "type_constraint": |
| 86 | type_set_constrained.add(source) |
| 87 | |
| 88 | def required(iface: str, visiting: frozenset[str] = frozenset()) -> set[str] | None: |
| 89 | # None: the method set is not fully known (an embedded interface outside |
| 90 | # the corpus, or an embedding cycle, which Go rejects anyway). |
| 91 | names = set(method_names.get(iface, ())) |
| 92 | for embedded in embeds.get(iface, ()): |
| 93 | if embedded not in interfaces or embedded in visiting: |
| 94 | return None |
| 95 | inner = required(embedded, visiting | {iface}) |
| 96 | if inner is None: |
| 97 | return None |
| 98 | names |= inner |
| 99 | return names |
| 100 | |
| 101 | candidates = { |
| 102 | owner: names for owner, names in method_names.items() |
| 103 | if owner not in interfaces and declared_in(node_by_id.get(owner), _GO_SUFFIXES) |
| 104 | } |
| 105 | inferred: list[dict] = [] |
| 106 | for iface, iface_node in interfaces.items(): |
| 107 | if iface in type_set_constrained or not method_names.get(iface): |
| 108 | continue |
| 109 | needed = required(iface) |
| 110 | if not needed: |
| 111 | continue |
| 112 | package = PurePath(str(iface_node.get("source_file"))).parent |
| 113 | same_package_only = any(not name[:1].isupper() for name in needed) |
| 114 | impls = [ |
| 115 | owner for owner, names in candidates.items() |
| 116 | if needed <= names |
| 117 | and (not same_package_only |
| 118 | or PurePath(str(node_by_id[owner].get("source_file"))).parent == package) |
| 119 | ] |
| 120 | if 0 < len(impls) <= _MAX_IMPLICIT_IMPLEMENTERS: |