forked from python/mypy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmro.py
62 lines (51 loc) · 1.95 KB
/
mro.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
from __future__ import annotations
from typing import Callable
from mypy.nodes import TypeInfo
from mypy.types import Instance
from mypy.typestate import type_state
def calculate_mro(info: TypeInfo, obj_type: Callable[[], Instance] | None = None) -> None:
"""Calculate and set mro (method resolution order).
Raise MroError if cannot determine mro.
"""
mro = linearize_hierarchy(info, obj_type)
assert mro, f"Could not produce a MRO at all for {info}"
info.mro = mro
# The property of falling back to Any is inherited.
info.fallback_to_any = any(baseinfo.fallback_to_any for baseinfo in info.mro)
type_state.reset_all_subtype_caches_for(info)
class MroError(Exception):
"""Raised if a consistent mro cannot be determined for a class."""
def linearize_hierarchy(
info: TypeInfo, obj_type: Callable[[], Instance] | None = None
) -> list[TypeInfo]:
# TODO describe
if info.mro:
return info.mro
bases = info.direct_base_classes()
if not bases and info.fullname != "builtins.object" and obj_type is not None:
# Probably an error, add a dummy `object` base class,
# otherwise MRO calculation may spuriously fail.
bases = [obj_type().type]
lin_bases = []
for base in bases:
assert base is not None, f"Cannot linearize bases for {info.fullname} {bases}"
lin_bases.append(linearize_hierarchy(base, obj_type))
lin_bases.append(bases)
return [info] + merge(lin_bases)
def merge(seqs: list[list[TypeInfo]]) -> list[TypeInfo]:
seqs = [s.copy() for s in seqs]
result: list[TypeInfo] = []
while True:
seqs = [s for s in seqs if s]
if not seqs:
return result
for seq in seqs:
head = seq[0]
if not [s for s in seqs if head in s[1:]]:
break
else:
raise MroError()
result.append(head)
for s in seqs:
if s[0] is head:
del s[0]