deps.py 49 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137
  1. """Generate fine-grained dependencies for AST nodes, for use in the daemon mode.
  2. Dependencies are stored in a map from *triggers* to *sets of affected locations*.
  3. A trigger is a string that represents a program property that has changed, such
  4. as the signature of a specific function. Triggers are written as '<...>' (angle
  5. brackets). When a program property changes, we determine the relevant trigger(s)
  6. and all affected locations. The latter are stale and will have to be reprocessed.
  7. An affected location is a string than can refer to a *target* (a non-nested
  8. function or method, or a module top level), a class, or a trigger (for
  9. recursively triggering other triggers).
  10. Here's an example representation of a simple dependency map (in format
  11. "<trigger> -> locations"):
  12. <m.A.g> -> m.f
  13. <m.A> -> <m.f>, m.A, m.f
  14. Assuming 'A' is a class, this means that
  15. 1) if a property of 'm.A.g', such as the signature, is changed, we need
  16. to process target (function) 'm.f'
  17. 2) if the MRO or other significant property of class 'm.A' changes, we
  18. need to process target 'm.f', the entire class 'm.A', and locations
  19. triggered by trigger '<m.f>' (this explanation is a bit simplified;
  20. see below for more details).
  21. The triggers to fire are determined using mypy.server.astdiff.
  22. Examples of triggers:
  23. * '<mod.x>' represents a module attribute/function/class. If any externally
  24. visible property of 'x' changes, this gets fired. For changes within
  25. classes, only "big" changes cause the class to be triggered (such as a
  26. change in MRO). Smaller changes, such as changes to some attributes, don't
  27. trigger the entire class.
  28. * '<mod.Cls.x>' represents the type and kind of attribute/method 'x' of
  29. class 'mod.Cls'. This can also refer to an attribute inherited from a
  30. base class (relevant if it's accessed through a value of type 'Cls'
  31. instead of the base class type).
  32. * '<package.mod>' represents the existence of module 'package.mod'. This
  33. gets triggered if 'package.mod' is created or deleted, or if it gets
  34. changed into something other than a module.
  35. Examples of locations:
  36. * 'mod' is the top level of module 'mod' (doesn't include any function bodies,
  37. but includes class bodies not nested within a function).
  38. * 'mod.f' is function 'f' in module 'mod' (module-level variables aren't separate
  39. locations but are included in the module top level). Functions also include
  40. any nested functions and classes -- such nested definitions aren't separate
  41. locations, for simplicity of implementation.
  42. * 'mod.Cls.f' is method 'f' of 'mod.Cls'. Non-method attributes aren't locations.
  43. * 'mod.Cls' represents each method in class 'mod.Cls' + the top-level of the
  44. module 'mod'. (To simplify the implementation, there is no location that only
  45. includes the body of a class without the entire surrounding module top level.)
  46. * Trigger '<...>' as a location is an indirect way of referring to to all
  47. locations triggered by the trigger. These indirect locations keep the
  48. dependency map smaller and easier to manage.
  49. Triggers can be triggered by program changes such as these:
  50. * Addition or deletion of an attribute (or module).
  51. * Change of the kind of thing a name represents (such as a change from a function
  52. to a class).
  53. * Change of the static type of a name.
  54. Changes in the body of a function that aren't reflected in the signature don't
  55. cause the function to be triggered. More generally, we trigger only on changes
  56. that may affect type checking results outside the module that contains the
  57. change.
  58. We don't generate dependencies from builtins and certain other stdlib modules,
  59. since these change very rarely, and they would just increase the size of the
  60. dependency map significantly without significant benefit.
  61. Test cases for this module live in 'test-data/unit/deps*.test'.
  62. """
  63. from __future__ import annotations
  64. from collections import defaultdict
  65. from typing import List
  66. from mypy.nodes import (
  67. GDEF,
  68. LDEF,
  69. MDEF,
  70. AssertTypeExpr,
  71. AssignmentStmt,
  72. AwaitExpr,
  73. Block,
  74. CallExpr,
  75. CastExpr,
  76. ClassDef,
  77. ComparisonExpr,
  78. Decorator,
  79. DelStmt,
  80. DictionaryComprehension,
  81. EnumCallExpr,
  82. Expression,
  83. ForStmt,
  84. FuncBase,
  85. FuncDef,
  86. GeneratorExpr,
  87. Import,
  88. ImportAll,
  89. ImportFrom,
  90. IndexExpr,
  91. MemberExpr,
  92. MypyFile,
  93. NamedTupleExpr,
  94. NameExpr,
  95. NewTypeExpr,
  96. Node,
  97. OperatorAssignmentStmt,
  98. OpExpr,
  99. OverloadedFuncDef,
  100. RefExpr,
  101. StarExpr,
  102. SuperExpr,
  103. TupleExpr,
  104. TypeAliasExpr,
  105. TypeApplication,
  106. TypedDictExpr,
  107. TypeInfo,
  108. TypeVarExpr,
  109. UnaryExpr,
  110. Var,
  111. WithStmt,
  112. YieldFromExpr,
  113. )
  114. from mypy.operators import (
  115. op_methods,
  116. ops_with_inplace_method,
  117. reverse_op_methods,
  118. unary_op_methods,
  119. )
  120. from mypy.options import Options
  121. from mypy.scope import Scope
  122. from mypy.server.trigger import make_trigger, make_wildcard_trigger
  123. from mypy.traverser import TraverserVisitor
  124. from mypy.typeops import bind_self
  125. from mypy.types import (
  126. AnyType,
  127. CallableType,
  128. DeletedType,
  129. ErasedType,
  130. FunctionLike,
  131. Instance,
  132. LiteralType,
  133. NoneType,
  134. Overloaded,
  135. Parameters,
  136. ParamSpecType,
  137. PartialType,
  138. ProperType,
  139. TupleType,
  140. Type,
  141. TypeAliasType,
  142. TypedDictType,
  143. TypeOfAny,
  144. TypeType,
  145. TypeVarTupleType,
  146. TypeVarType,
  147. TypeVisitor,
  148. UnboundType,
  149. UninhabitedType,
  150. UnionType,
  151. UnpackType,
  152. get_proper_type,
  153. )
  154. from mypy.typestate import type_state
  155. from mypy.util import correct_relative_import
  156. def get_dependencies(
  157. target: MypyFile,
  158. type_map: dict[Expression, Type],
  159. python_version: tuple[int, int],
  160. options: Options,
  161. ) -> dict[str, set[str]]:
  162. """Get all dependencies of a node, recursively."""
  163. visitor = DependencyVisitor(type_map, python_version, target.alias_deps, options)
  164. target.accept(visitor)
  165. return visitor.map
  166. def get_dependencies_of_target(
  167. module_id: str,
  168. module_tree: MypyFile,
  169. target: Node,
  170. type_map: dict[Expression, Type],
  171. python_version: tuple[int, int],
  172. ) -> dict[str, set[str]]:
  173. """Get dependencies of a target -- don't recursive into nested targets."""
  174. # TODO: Add tests for this function.
  175. visitor = DependencyVisitor(type_map, python_version, module_tree.alias_deps)
  176. with visitor.scope.module_scope(module_id):
  177. if isinstance(target, MypyFile):
  178. # Only get dependencies of the top-level of the module. Don't recurse into
  179. # functions.
  180. for defn in target.defs:
  181. # TODO: Recurse into top-level statements and class bodies but skip functions.
  182. if not isinstance(defn, (ClassDef, Decorator, FuncDef, OverloadedFuncDef)):
  183. defn.accept(visitor)
  184. elif isinstance(target, FuncBase) and target.info:
  185. # It's a method.
  186. # TODO: Methods in nested classes.
  187. with visitor.scope.class_scope(target.info):
  188. target.accept(visitor)
  189. else:
  190. target.accept(visitor)
  191. return visitor.map
  192. class DependencyVisitor(TraverserVisitor):
  193. def __init__(
  194. self,
  195. type_map: dict[Expression, Type],
  196. python_version: tuple[int, int],
  197. alias_deps: defaultdict[str, set[str]],
  198. options: Options | None = None,
  199. ) -> None:
  200. self.scope = Scope()
  201. self.type_map = type_map
  202. # This attribute holds a mapping from target to names of type aliases
  203. # it depends on. These need to be processed specially, since they are
  204. # only present in expanded form in symbol tables. For example, after:
  205. # A = List[int]
  206. # x: A
  207. # The module symbol table will just have a Var `x` with type `List[int]`,
  208. # and the dependency of `x` on `A` is lost. Therefore the alias dependencies
  209. # are preserved at alias expansion points in `semanal.py`, stored as an attribute
  210. # on MypyFile, and then passed here.
  211. self.alias_deps = alias_deps
  212. self.map: dict[str, set[str]] = {}
  213. self.is_class = False
  214. self.is_package_init_file = False
  215. self.options = options
  216. def visit_mypy_file(self, o: MypyFile) -> None:
  217. with self.scope.module_scope(o.fullname):
  218. self.is_package_init_file = o.is_package_init_file()
  219. self.add_type_alias_deps(self.scope.current_target())
  220. for trigger, targets in o.plugin_deps.items():
  221. self.map.setdefault(trigger, set()).update(targets)
  222. super().visit_mypy_file(o)
  223. def visit_func_def(self, o: FuncDef) -> None:
  224. with self.scope.function_scope(o):
  225. target = self.scope.current_target()
  226. if o.type:
  227. if self.is_class and isinstance(o.type, FunctionLike):
  228. signature: Type = bind_self(o.type)
  229. else:
  230. signature = o.type
  231. for trigger in self.get_type_triggers(signature):
  232. self.add_dependency(trigger)
  233. self.add_dependency(trigger, target=make_trigger(target))
  234. if o.info:
  235. for base in non_trivial_bases(o.info):
  236. # Base class __init__/__new__ doesn't generate a logical
  237. # dependency since the override can be incompatible.
  238. if not self.use_logical_deps() or o.name not in ("__init__", "__new__"):
  239. self.add_dependency(make_trigger(base.fullname + "." + o.name))
  240. self.add_type_alias_deps(self.scope.current_target())
  241. super().visit_func_def(o)
  242. variants = set(o.expanded) - {o}
  243. for ex in variants:
  244. if isinstance(ex, FuncDef):
  245. super().visit_func_def(ex)
  246. def visit_decorator(self, o: Decorator) -> None:
  247. if not self.use_logical_deps():
  248. # We don't need to recheck outer scope for an overload, only overload itself.
  249. # Also if any decorator is nested, it is not externally visible, so we don't need to
  250. # generate dependency.
  251. if not o.func.is_overload and self.scope.current_function_name() is None:
  252. self.add_dependency(make_trigger(o.func.fullname))
  253. else:
  254. # Add logical dependencies from decorators to the function. For example,
  255. # if we have
  256. # @dec
  257. # def func(): ...
  258. # then if `dec` is unannotated, then it will "spoil" `func` and consequently
  259. # all call sites, making them all `Any`.
  260. for d in o.decorators:
  261. tname: str | None = None
  262. if isinstance(d, RefExpr) and d.fullname:
  263. tname = d.fullname
  264. if isinstance(d, CallExpr) and isinstance(d.callee, RefExpr) and d.callee.fullname:
  265. tname = d.callee.fullname
  266. if tname is not None:
  267. self.add_dependency(make_trigger(tname), make_trigger(o.func.fullname))
  268. super().visit_decorator(o)
  269. def visit_class_def(self, o: ClassDef) -> None:
  270. with self.scope.class_scope(o.info):
  271. target = self.scope.current_full_target()
  272. self.add_dependency(make_trigger(target), target)
  273. old_is_class = self.is_class
  274. self.is_class = True
  275. # Add dependencies to type variables of a generic class.
  276. for tv in o.type_vars:
  277. self.add_dependency(make_trigger(tv.fullname), target)
  278. self.process_type_info(o.info)
  279. super().visit_class_def(o)
  280. self.is_class = old_is_class
  281. def visit_newtype_expr(self, o: NewTypeExpr) -> None:
  282. if o.info:
  283. with self.scope.class_scope(o.info):
  284. self.process_type_info(o.info)
  285. def process_type_info(self, info: TypeInfo) -> None:
  286. target = self.scope.current_full_target()
  287. for base in info.bases:
  288. self.add_type_dependencies(base, target=target)
  289. if info.tuple_type:
  290. self.add_type_dependencies(info.tuple_type, target=make_trigger(target))
  291. if info.typeddict_type:
  292. self.add_type_dependencies(info.typeddict_type, target=make_trigger(target))
  293. if info.declared_metaclass:
  294. self.add_type_dependencies(info.declared_metaclass, target=make_trigger(target))
  295. if info.is_protocol:
  296. for base_info in info.mro[:-1]:
  297. # We add dependencies from whole MRO to cover explicit subprotocols.
  298. # For example:
  299. #
  300. # class Super(Protocol):
  301. # x: int
  302. # class Sub(Super, Protocol):
  303. # y: int
  304. #
  305. # In this example we add <Super[wildcard]> -> <Sub>, to invalidate Sub if
  306. # a new member is added to Super.
  307. self.add_dependency(
  308. make_wildcard_trigger(base_info.fullname), target=make_trigger(target)
  309. )
  310. # More protocol dependencies are collected in type_state._snapshot_protocol_deps
  311. # after a full run or update is finished.
  312. self.add_type_alias_deps(self.scope.current_target())
  313. for name, node in info.names.items():
  314. if isinstance(node.node, Var):
  315. # Recheck Liskov if needed, self definitions are checked in the defining method
  316. if node.node.is_initialized_in_class and has_user_bases(info):
  317. self.add_dependency(make_trigger(info.fullname + "." + name))
  318. for base_info in non_trivial_bases(info):
  319. # If the type of an attribute changes in a base class, we make references
  320. # to the attribute in the subclass stale.
  321. self.add_dependency(
  322. make_trigger(base_info.fullname + "." + name),
  323. target=make_trigger(info.fullname + "." + name),
  324. )
  325. for base_info in non_trivial_bases(info):
  326. for name, node in base_info.names.items():
  327. if self.use_logical_deps():
  328. # Skip logical dependency if an attribute is not overridden. For example,
  329. # in case of:
  330. # class Base:
  331. # x = 1
  332. # y = 2
  333. # class Sub(Base):
  334. # x = 3
  335. # we skip <Base.y> -> <Child.y>, because even if `y` is unannotated it
  336. # doesn't affect precision of Liskov checking.
  337. if name not in info.names:
  338. continue
  339. # __init__ and __new__ can be overridden with different signatures, so no
  340. # logical dependency.
  341. if name in ("__init__", "__new__"):
  342. continue
  343. self.add_dependency(
  344. make_trigger(base_info.fullname + "." + name),
  345. target=make_trigger(info.fullname + "." + name),
  346. )
  347. if not self.use_logical_deps():
  348. # These dependencies are only useful for propagating changes --
  349. # they aren't logical dependencies since __init__ and __new__ can be
  350. # overridden with a different signature.
  351. self.add_dependency(
  352. make_trigger(base_info.fullname + ".__init__"),
  353. target=make_trigger(info.fullname + ".__init__"),
  354. )
  355. self.add_dependency(
  356. make_trigger(base_info.fullname + ".__new__"),
  357. target=make_trigger(info.fullname + ".__new__"),
  358. )
  359. # If the set of abstract attributes change, this may invalidate class
  360. # instantiation, or change the generated error message, since Python checks
  361. # class abstract status when creating an instance.
  362. self.add_dependency(
  363. make_trigger(base_info.fullname + ".(abstract)"),
  364. target=make_trigger(info.fullname + ".__init__"),
  365. )
  366. # If the base class abstract attributes change, subclass abstract
  367. # attributes need to be recalculated.
  368. self.add_dependency(make_trigger(base_info.fullname + ".(abstract)"))
  369. def visit_import(self, o: Import) -> None:
  370. for id, as_id in o.ids:
  371. self.add_dependency(make_trigger(id), self.scope.current_target())
  372. def visit_import_from(self, o: ImportFrom) -> None:
  373. if self.use_logical_deps():
  374. # Just importing a name doesn't create a logical dependency.
  375. return
  376. module_id, _ = correct_relative_import(
  377. self.scope.current_module_id(), o.relative, o.id, self.is_package_init_file
  378. )
  379. self.add_dependency(make_trigger(module_id)) # needed if module is added/removed
  380. for name, as_name in o.names:
  381. self.add_dependency(make_trigger(module_id + "." + name))
  382. def visit_import_all(self, o: ImportAll) -> None:
  383. module_id, _ = correct_relative_import(
  384. self.scope.current_module_id(), o.relative, o.id, self.is_package_init_file
  385. )
  386. # The current target needs to be rechecked if anything "significant" changes in the
  387. # target module namespace (as the imported definitions will need to be updated).
  388. self.add_dependency(make_wildcard_trigger(module_id))
  389. def visit_block(self, o: Block) -> None:
  390. if not o.is_unreachable:
  391. super().visit_block(o)
  392. def visit_assignment_stmt(self, o: AssignmentStmt) -> None:
  393. rvalue = o.rvalue
  394. if isinstance(rvalue, CallExpr) and isinstance(rvalue.analyzed, TypeVarExpr):
  395. analyzed = rvalue.analyzed
  396. self.add_type_dependencies(
  397. analyzed.upper_bound, target=make_trigger(analyzed.fullname)
  398. )
  399. for val in analyzed.values:
  400. self.add_type_dependencies(val, target=make_trigger(analyzed.fullname))
  401. # We need to re-analyze the definition if bound or value is deleted.
  402. super().visit_call_expr(rvalue)
  403. elif isinstance(rvalue, CallExpr) and isinstance(rvalue.analyzed, NamedTupleExpr):
  404. # Depend on types of named tuple items.
  405. info = rvalue.analyzed.info
  406. prefix = f"{self.scope.current_full_target()}.{info.name}"
  407. for name, symnode in info.names.items():
  408. if not name.startswith("_") and isinstance(symnode.node, Var):
  409. typ = symnode.node.type
  410. if typ:
  411. self.add_type_dependencies(typ)
  412. self.add_type_dependencies(typ, target=make_trigger(prefix))
  413. attr_target = make_trigger(f"{prefix}.{name}")
  414. self.add_type_dependencies(typ, target=attr_target)
  415. elif isinstance(rvalue, CallExpr) and isinstance(rvalue.analyzed, TypedDictExpr):
  416. # Depend on the underlying typeddict type
  417. info = rvalue.analyzed.info
  418. assert info.typeddict_type is not None
  419. prefix = f"{self.scope.current_full_target()}.{info.name}"
  420. self.add_type_dependencies(info.typeddict_type, target=make_trigger(prefix))
  421. elif isinstance(rvalue, CallExpr) and isinstance(rvalue.analyzed, EnumCallExpr):
  422. # Enum values are currently not checked, but for future we add the deps on them
  423. for name, symnode in rvalue.analyzed.info.names.items():
  424. if isinstance(symnode.node, Var) and symnode.node.type:
  425. self.add_type_dependencies(symnode.node.type)
  426. elif o.is_alias_def:
  427. assert len(o.lvalues) == 1
  428. lvalue = o.lvalues[0]
  429. assert isinstance(lvalue, NameExpr)
  430. typ = get_proper_type(self.type_map.get(lvalue))
  431. if isinstance(typ, FunctionLike) and typ.is_type_obj():
  432. class_name = typ.type_object().fullname
  433. self.add_dependency(make_trigger(class_name + ".__init__"))
  434. self.add_dependency(make_trigger(class_name + ".__new__"))
  435. if isinstance(rvalue, IndexExpr) and isinstance(rvalue.analyzed, TypeAliasExpr):
  436. self.add_type_dependencies(rvalue.analyzed.type)
  437. elif typ:
  438. self.add_type_dependencies(typ)
  439. else:
  440. # Normal assignment
  441. super().visit_assignment_stmt(o)
  442. for lvalue in o.lvalues:
  443. self.process_lvalue(lvalue)
  444. items = o.lvalues + [rvalue]
  445. for i in range(len(items) - 1):
  446. lvalue = items[i]
  447. rvalue = items[i + 1]
  448. if isinstance(lvalue, TupleExpr):
  449. self.add_attribute_dependency_for_expr(rvalue, "__iter__")
  450. if o.type:
  451. self.add_type_dependencies(o.type)
  452. if self.use_logical_deps() and o.unanalyzed_type is None:
  453. # Special case: for definitions without an explicit type like this:
  454. # x = func(...)
  455. # we add a logical dependency <func> -> <x>, because if `func` is not annotated,
  456. # then it will make all points of use of `x` unchecked.
  457. if (
  458. isinstance(rvalue, CallExpr)
  459. and isinstance(rvalue.callee, RefExpr)
  460. and rvalue.callee.fullname
  461. ):
  462. fname: str | None = None
  463. if isinstance(rvalue.callee.node, TypeInfo):
  464. # use actual __init__ as a dependency source
  465. init = rvalue.callee.node.get("__init__")
  466. if init and isinstance(init.node, FuncBase):
  467. fname = init.node.fullname
  468. else:
  469. fname = rvalue.callee.fullname
  470. if not fname:
  471. return
  472. for lv in o.lvalues:
  473. if isinstance(lv, RefExpr) and lv.fullname and lv.is_new_def:
  474. if lv.kind == LDEF:
  475. return # local definitions don't generate logical deps
  476. self.add_dependency(make_trigger(fname), make_trigger(lv.fullname))
  477. def process_lvalue(self, lvalue: Expression) -> None:
  478. """Generate additional dependencies for an lvalue."""
  479. if isinstance(lvalue, IndexExpr):
  480. self.add_operator_method_dependency(lvalue.base, "__setitem__")
  481. elif isinstance(lvalue, NameExpr):
  482. if lvalue.kind in (MDEF, GDEF):
  483. # Assignment to an attribute in the class body, or direct assignment to a
  484. # global variable.
  485. lvalue_type = self.get_non_partial_lvalue_type(lvalue)
  486. type_triggers = self.get_type_triggers(lvalue_type)
  487. attr_trigger = make_trigger(f"{self.scope.current_full_target()}.{lvalue.name}")
  488. for type_trigger in type_triggers:
  489. self.add_dependency(type_trigger, attr_trigger)
  490. elif isinstance(lvalue, MemberExpr):
  491. if self.is_self_member_ref(lvalue) and lvalue.is_new_def:
  492. node = lvalue.node
  493. if isinstance(node, Var):
  494. info = node.info
  495. if info and has_user_bases(info):
  496. # Recheck Liskov for self definitions
  497. self.add_dependency(make_trigger(info.fullname + "." + lvalue.name))
  498. if lvalue.kind is None:
  499. # Reference to a non-module attribute
  500. if lvalue.expr not in self.type_map:
  501. # Unreachable assignment -> not checked so no dependencies to generate.
  502. return
  503. object_type = self.type_map[lvalue.expr]
  504. lvalue_type = self.get_non_partial_lvalue_type(lvalue)
  505. type_triggers = self.get_type_triggers(lvalue_type)
  506. for attr_trigger in self.attribute_triggers(object_type, lvalue.name):
  507. for type_trigger in type_triggers:
  508. self.add_dependency(type_trigger, attr_trigger)
  509. elif isinstance(lvalue, TupleExpr):
  510. for item in lvalue.items:
  511. self.process_lvalue(item)
  512. elif isinstance(lvalue, StarExpr):
  513. self.process_lvalue(lvalue.expr)
  514. def is_self_member_ref(self, memberexpr: MemberExpr) -> bool:
  515. """Does memberexpr to refer to an attribute of self?"""
  516. if not isinstance(memberexpr.expr, NameExpr):
  517. return False
  518. node = memberexpr.expr.node
  519. return isinstance(node, Var) and node.is_self
  520. def get_non_partial_lvalue_type(self, lvalue: RefExpr) -> Type:
  521. if lvalue not in self.type_map:
  522. # Likely a block considered unreachable during type checking.
  523. return UninhabitedType()
  524. lvalue_type = get_proper_type(self.type_map[lvalue])
  525. if isinstance(lvalue_type, PartialType):
  526. if isinstance(lvalue.node, Var):
  527. if lvalue.node.type:
  528. lvalue_type = get_proper_type(lvalue.node.type)
  529. else:
  530. lvalue_type = UninhabitedType()
  531. else:
  532. # Probably a secondary, non-definition assignment that doesn't
  533. # result in a non-partial type. We won't be able to infer any
  534. # dependencies from this so just return something. (The first,
  535. # definition assignment with a partial type is handled
  536. # differently, in the semantic analyzer.)
  537. assert not lvalue.is_new_def
  538. return UninhabitedType()
  539. return lvalue_type
  540. def visit_operator_assignment_stmt(self, o: OperatorAssignmentStmt) -> None:
  541. super().visit_operator_assignment_stmt(o)
  542. self.process_lvalue(o.lvalue)
  543. method = op_methods[o.op]
  544. self.add_attribute_dependency_for_expr(o.lvalue, method)
  545. if o.op in ops_with_inplace_method:
  546. inplace_method = "__i" + method[2:]
  547. self.add_attribute_dependency_for_expr(o.lvalue, inplace_method)
  548. def visit_for_stmt(self, o: ForStmt) -> None:
  549. super().visit_for_stmt(o)
  550. if not o.is_async:
  551. # __getitem__ is only used if __iter__ is missing but for simplicity we
  552. # just always depend on both.
  553. self.add_attribute_dependency_for_expr(o.expr, "__iter__")
  554. self.add_attribute_dependency_for_expr(o.expr, "__getitem__")
  555. if o.inferred_iterator_type:
  556. self.add_attribute_dependency(o.inferred_iterator_type, "__next__")
  557. else:
  558. self.add_attribute_dependency_for_expr(o.expr, "__aiter__")
  559. if o.inferred_iterator_type:
  560. self.add_attribute_dependency(o.inferred_iterator_type, "__anext__")
  561. self.process_lvalue(o.index)
  562. if isinstance(o.index, TupleExpr):
  563. # Process multiple assignment to index variables.
  564. item_type = o.inferred_item_type
  565. if item_type:
  566. # This is similar to above.
  567. self.add_attribute_dependency(item_type, "__iter__")
  568. self.add_attribute_dependency(item_type, "__getitem__")
  569. if o.index_type:
  570. self.add_type_dependencies(o.index_type)
  571. def visit_with_stmt(self, o: WithStmt) -> None:
  572. super().visit_with_stmt(o)
  573. for e in o.expr:
  574. if not o.is_async:
  575. self.add_attribute_dependency_for_expr(e, "__enter__")
  576. self.add_attribute_dependency_for_expr(e, "__exit__")
  577. else:
  578. self.add_attribute_dependency_for_expr(e, "__aenter__")
  579. self.add_attribute_dependency_for_expr(e, "__aexit__")
  580. for typ in o.analyzed_types:
  581. self.add_type_dependencies(typ)
  582. def visit_del_stmt(self, o: DelStmt) -> None:
  583. super().visit_del_stmt(o)
  584. if isinstance(o.expr, IndexExpr):
  585. self.add_attribute_dependency_for_expr(o.expr.base, "__delitem__")
  586. # Expressions
  587. def process_global_ref_expr(self, o: RefExpr) -> None:
  588. if o.fullname:
  589. self.add_dependency(make_trigger(o.fullname))
  590. # If this is a reference to a type, generate a dependency to its
  591. # constructor.
  592. # IDEA: Avoid generating spurious dependencies for except statements,
  593. # class attribute references, etc., if performance is a problem.
  594. typ = get_proper_type(self.type_map.get(o))
  595. if isinstance(typ, FunctionLike) and typ.is_type_obj():
  596. class_name = typ.type_object().fullname
  597. self.add_dependency(make_trigger(class_name + ".__init__"))
  598. self.add_dependency(make_trigger(class_name + ".__new__"))
  599. def visit_name_expr(self, o: NameExpr) -> None:
  600. if o.kind == LDEF:
  601. # We don't track dependencies to local variables, since they
  602. # aren't externally visible.
  603. return
  604. if o.kind == MDEF:
  605. # Direct reference to member is only possible in the scope that
  606. # defined the name, so no dependency is required.
  607. return
  608. self.process_global_ref_expr(o)
  609. def visit_member_expr(self, e: MemberExpr) -> None:
  610. if isinstance(e.expr, RefExpr) and isinstance(e.expr.node, TypeInfo):
  611. # Special case class attribute so that we don't depend on "__init__".
  612. self.add_dependency(make_trigger(e.expr.node.fullname))
  613. else:
  614. super().visit_member_expr(e)
  615. if e.kind is not None:
  616. # Reference to a module attribute
  617. self.process_global_ref_expr(e)
  618. else:
  619. # Reference to a non-module (or missing) attribute
  620. if e.expr not in self.type_map:
  621. # No type available -- this happens for unreachable code. Since it's unreachable,
  622. # it wasn't type checked and we don't need to generate dependencies.
  623. return
  624. if isinstance(e.expr, RefExpr) and isinstance(e.expr.node, MypyFile):
  625. # Special case: reference to a missing module attribute.
  626. self.add_dependency(make_trigger(e.expr.node.fullname + "." + e.name))
  627. return
  628. typ = get_proper_type(self.type_map[e.expr])
  629. self.add_attribute_dependency(typ, e.name)
  630. if self.use_logical_deps() and isinstance(typ, AnyType):
  631. name = self.get_unimported_fullname(e, typ)
  632. if name is not None:
  633. # Generate a logical dependency from an unimported
  634. # definition (which comes from a missing module).
  635. # Example:
  636. # import missing # "missing" not in build
  637. #
  638. # def g() -> None:
  639. # missing.f() # Generate dependency from "missing.f"
  640. self.add_dependency(make_trigger(name))
  641. def get_unimported_fullname(self, e: MemberExpr, typ: AnyType) -> str | None:
  642. """If e refers to an unimported definition, infer the fullname of this.
  643. Return None if e doesn't refer to an unimported definition or if we can't
  644. determine the name.
  645. """
  646. suffix = ""
  647. # Unwrap nested member expression to handle cases like "a.b.c.d" where
  648. # "a.b" is a known reference to an unimported module. Find the base
  649. # reference to an unimported module (such as "a.b") and the name suffix
  650. # (such as "c.d") needed to build a full name.
  651. while typ.type_of_any == TypeOfAny.from_another_any and isinstance(e.expr, MemberExpr):
  652. suffix = "." + e.name + suffix
  653. e = e.expr
  654. if e.expr not in self.type_map:
  655. return None
  656. obj_type = get_proper_type(self.type_map[e.expr])
  657. if not isinstance(obj_type, AnyType):
  658. # Can't find the base reference to the unimported module.
  659. return None
  660. typ = obj_type
  661. if typ.type_of_any == TypeOfAny.from_unimported_type and typ.missing_import_name:
  662. # Infer the full name of the unimported definition.
  663. return typ.missing_import_name + "." + e.name + suffix
  664. return None
  665. def visit_super_expr(self, e: SuperExpr) -> None:
  666. # Arguments in "super(C, self)" won't generate useful logical deps.
  667. if not self.use_logical_deps():
  668. super().visit_super_expr(e)
  669. if e.info is not None:
  670. name = e.name
  671. for base in non_trivial_bases(e.info):
  672. self.add_dependency(make_trigger(base.fullname + "." + name))
  673. if name in base.names:
  674. # No need to depend on further base classes, since we found
  675. # the target. This is safe since if the target gets
  676. # deleted or modified, we'll trigger it.
  677. break
  678. def visit_call_expr(self, e: CallExpr) -> None:
  679. if isinstance(e.callee, RefExpr) and e.callee.fullname == "builtins.isinstance":
  680. self.process_isinstance_call(e)
  681. else:
  682. super().visit_call_expr(e)
  683. typ = self.type_map.get(e.callee)
  684. if typ is not None:
  685. typ = get_proper_type(typ)
  686. if not isinstance(typ, FunctionLike):
  687. self.add_attribute_dependency(typ, "__call__")
  688. def process_isinstance_call(self, e: CallExpr) -> None:
  689. """Process "isinstance(...)" in a way to avoid some extra dependencies."""
  690. if len(e.args) == 2:
  691. arg = e.args[1]
  692. if (
  693. isinstance(arg, RefExpr)
  694. and arg.kind == GDEF
  695. and isinstance(arg.node, TypeInfo)
  696. and arg.fullname
  697. ):
  698. # Special case to avoid redundant dependencies from "__init__".
  699. self.add_dependency(make_trigger(arg.fullname))
  700. return
  701. # In uncommon cases generate normal dependencies. These will include
  702. # spurious dependencies, but the performance impact is small.
  703. super().visit_call_expr(e)
  704. def visit_cast_expr(self, e: CastExpr) -> None:
  705. super().visit_cast_expr(e)
  706. self.add_type_dependencies(e.type)
  707. def visit_assert_type_expr(self, e: AssertTypeExpr) -> None:
  708. super().visit_assert_type_expr(e)
  709. self.add_type_dependencies(e.type)
  710. def visit_type_application(self, e: TypeApplication) -> None:
  711. super().visit_type_application(e)
  712. for typ in e.types:
  713. self.add_type_dependencies(typ)
  714. def visit_index_expr(self, e: IndexExpr) -> None:
  715. super().visit_index_expr(e)
  716. self.add_operator_method_dependency(e.base, "__getitem__")
  717. def visit_unary_expr(self, e: UnaryExpr) -> None:
  718. super().visit_unary_expr(e)
  719. if e.op not in unary_op_methods:
  720. return
  721. method = unary_op_methods[e.op]
  722. self.add_operator_method_dependency(e.expr, method)
  723. def visit_op_expr(self, e: OpExpr) -> None:
  724. super().visit_op_expr(e)
  725. self.process_binary_op(e.op, e.left, e.right)
  726. def visit_comparison_expr(self, e: ComparisonExpr) -> None:
  727. super().visit_comparison_expr(e)
  728. for i, op in enumerate(e.operators):
  729. left = e.operands[i]
  730. right = e.operands[i + 1]
  731. self.process_binary_op(op, left, right)
  732. def process_binary_op(self, op: str, left: Expression, right: Expression) -> None:
  733. method = op_methods.get(op)
  734. if method:
  735. if op == "in":
  736. self.add_operator_method_dependency(right, method)
  737. else:
  738. self.add_operator_method_dependency(left, method)
  739. rev_method = reverse_op_methods.get(method)
  740. if rev_method:
  741. self.add_operator_method_dependency(right, rev_method)
  742. def add_operator_method_dependency(self, e: Expression, method: str) -> None:
  743. typ = get_proper_type(self.type_map.get(e))
  744. if typ is not None:
  745. self.add_operator_method_dependency_for_type(typ, method)
  746. def add_operator_method_dependency_for_type(self, typ: ProperType, method: str) -> None:
  747. # Note that operator methods can't be (non-metaclass) methods of type objects
  748. # (that is, TypeType objects or Callables representing a type).
  749. if isinstance(typ, TypeVarType):
  750. typ = get_proper_type(typ.upper_bound)
  751. if isinstance(typ, TupleType):
  752. typ = typ.partial_fallback
  753. if isinstance(typ, Instance):
  754. trigger = make_trigger(typ.type.fullname + "." + method)
  755. self.add_dependency(trigger)
  756. elif isinstance(typ, UnionType):
  757. for item in typ.items:
  758. self.add_operator_method_dependency_for_type(get_proper_type(item), method)
  759. elif isinstance(typ, FunctionLike) and typ.is_type_obj():
  760. self.add_operator_method_dependency_for_type(typ.fallback, method)
  761. elif isinstance(typ, TypeType):
  762. if isinstance(typ.item, Instance) and typ.item.type.metaclass_type is not None:
  763. self.add_operator_method_dependency_for_type(typ.item.type.metaclass_type, method)
  764. def visit_generator_expr(self, e: GeneratorExpr) -> None:
  765. super().visit_generator_expr(e)
  766. for seq in e.sequences:
  767. self.add_iter_dependency(seq)
  768. def visit_dictionary_comprehension(self, e: DictionaryComprehension) -> None:
  769. super().visit_dictionary_comprehension(e)
  770. for seq in e.sequences:
  771. self.add_iter_dependency(seq)
  772. def visit_star_expr(self, e: StarExpr) -> None:
  773. super().visit_star_expr(e)
  774. self.add_iter_dependency(e.expr)
  775. def visit_yield_from_expr(self, e: YieldFromExpr) -> None:
  776. super().visit_yield_from_expr(e)
  777. self.add_iter_dependency(e.expr)
  778. def visit_await_expr(self, e: AwaitExpr) -> None:
  779. super().visit_await_expr(e)
  780. self.add_attribute_dependency_for_expr(e.expr, "__await__")
  781. # Helpers
  782. def add_type_alias_deps(self, target: str) -> None:
  783. # Type aliases are special, because some of the dependencies are calculated
  784. # in semanal.py, before they are expanded.
  785. if target in self.alias_deps:
  786. for alias in self.alias_deps[target]:
  787. self.add_dependency(make_trigger(alias))
  788. def add_dependency(self, trigger: str, target: str | None = None) -> None:
  789. """Add dependency from trigger to a target.
  790. If the target is not given explicitly, use the current target.
  791. """
  792. if trigger.startswith(
  793. ("<builtins.", "<typing.", "<mypy_extensions.", "<typing_extensions.")
  794. ):
  795. # Don't track dependencies to certain library modules to keep the size of
  796. # the dependencies manageable. These dependencies should only
  797. # change on mypy version updates, which will require a full rebuild
  798. # anyway.
  799. return
  800. if target is None:
  801. target = self.scope.current_target()
  802. self.map.setdefault(trigger, set()).add(target)
  803. def add_type_dependencies(self, typ: Type, target: str | None = None) -> None:
  804. """Add dependencies to all components of a type.
  805. Args:
  806. target: If not None, override the default (current) target of the
  807. generated dependency.
  808. """
  809. for trigger in self.get_type_triggers(typ):
  810. self.add_dependency(trigger, target)
  811. def add_attribute_dependency(self, typ: Type, name: str) -> None:
  812. """Add dependencies for accessing a named attribute of a type."""
  813. targets = self.attribute_triggers(typ, name)
  814. for target in targets:
  815. self.add_dependency(target)
  816. def attribute_triggers(self, typ: Type, name: str) -> list[str]:
  817. """Return all triggers associated with the attribute of a type."""
  818. typ = get_proper_type(typ)
  819. if isinstance(typ, TypeVarType):
  820. typ = get_proper_type(typ.upper_bound)
  821. if isinstance(typ, TupleType):
  822. typ = typ.partial_fallback
  823. if isinstance(typ, Instance):
  824. member = f"{typ.type.fullname}.{name}"
  825. return [make_trigger(member)]
  826. elif isinstance(typ, FunctionLike) and typ.is_type_obj():
  827. member = f"{typ.type_object().fullname}.{name}"
  828. triggers = [make_trigger(member)]
  829. triggers.extend(self.attribute_triggers(typ.fallback, name))
  830. return triggers
  831. elif isinstance(typ, UnionType):
  832. targets = []
  833. for item in typ.items:
  834. targets.extend(self.attribute_triggers(item, name))
  835. return targets
  836. elif isinstance(typ, TypeType):
  837. triggers = self.attribute_triggers(typ.item, name)
  838. if isinstance(typ.item, Instance) and typ.item.type.metaclass_type is not None:
  839. triggers.append(
  840. make_trigger(f"{typ.item.type.metaclass_type.type.fullname}.{name}")
  841. )
  842. return triggers
  843. else:
  844. return []
  845. def add_attribute_dependency_for_expr(self, e: Expression, name: str) -> None:
  846. typ = self.type_map.get(e)
  847. if typ is not None:
  848. self.add_attribute_dependency(typ, name)
  849. def add_iter_dependency(self, node: Expression) -> None:
  850. typ = self.type_map.get(node)
  851. if typ:
  852. self.add_attribute_dependency(typ, "__iter__")
  853. def use_logical_deps(self) -> bool:
  854. return self.options is not None and self.options.logical_deps
  855. def get_type_triggers(self, typ: Type) -> list[str]:
  856. return get_type_triggers(typ, self.use_logical_deps())
  857. def get_type_triggers(
  858. typ: Type, use_logical_deps: bool, seen_aliases: set[TypeAliasType] | None = None
  859. ) -> list[str]:
  860. """Return all triggers that correspond to a type becoming stale."""
  861. return typ.accept(TypeTriggersVisitor(use_logical_deps, seen_aliases))
  862. class TypeTriggersVisitor(TypeVisitor[List[str]]):
  863. def __init__(
  864. self, use_logical_deps: bool, seen_aliases: set[TypeAliasType] | None = None
  865. ) -> None:
  866. self.deps: list[str] = []
  867. self.seen_aliases: set[TypeAliasType] = seen_aliases or set()
  868. self.use_logical_deps = use_logical_deps
  869. def get_type_triggers(self, typ: Type) -> list[str]:
  870. return get_type_triggers(typ, self.use_logical_deps, self.seen_aliases)
  871. def visit_instance(self, typ: Instance) -> list[str]:
  872. trigger = make_trigger(typ.type.fullname)
  873. triggers = [trigger]
  874. for arg in typ.args:
  875. triggers.extend(self.get_type_triggers(arg))
  876. if typ.last_known_value:
  877. triggers.extend(self.get_type_triggers(typ.last_known_value))
  878. if typ.extra_attrs and typ.extra_attrs.mod_name:
  879. # Module as type effectively depends on all module attributes, use wildcard.
  880. triggers.append(make_wildcard_trigger(typ.extra_attrs.mod_name))
  881. return triggers
  882. def visit_type_alias_type(self, typ: TypeAliasType) -> list[str]:
  883. if typ in self.seen_aliases:
  884. return []
  885. self.seen_aliases.add(typ)
  886. assert typ.alias is not None
  887. trigger = make_trigger(typ.alias.fullname)
  888. triggers = [trigger]
  889. for arg in typ.args:
  890. triggers.extend(self.get_type_triggers(arg))
  891. # TODO: Now that type aliases are its own kind of types we can simplify
  892. # the logic to rely on intermediate dependencies (like for instance types).
  893. triggers.extend(self.get_type_triggers(typ.alias.target))
  894. return triggers
  895. def visit_any(self, typ: AnyType) -> list[str]:
  896. if typ.missing_import_name is not None:
  897. return [make_trigger(typ.missing_import_name)]
  898. return []
  899. def visit_none_type(self, typ: NoneType) -> list[str]:
  900. return []
  901. def visit_callable_type(self, typ: CallableType) -> list[str]:
  902. triggers = []
  903. for arg in typ.arg_types:
  904. triggers.extend(self.get_type_triggers(arg))
  905. triggers.extend(self.get_type_triggers(typ.ret_type))
  906. # fallback is a metaclass type for class objects, and is
  907. # processed separately.
  908. return triggers
  909. def visit_overloaded(self, typ: Overloaded) -> list[str]:
  910. triggers = []
  911. for item in typ.items:
  912. triggers.extend(self.get_type_triggers(item))
  913. return triggers
  914. def visit_erased_type(self, t: ErasedType) -> list[str]:
  915. # This type should exist only temporarily during type inference
  916. assert False, "Should not see an erased type here"
  917. def visit_deleted_type(self, typ: DeletedType) -> list[str]:
  918. return []
  919. def visit_partial_type(self, typ: PartialType) -> list[str]:
  920. assert False, "Should not see a partial type here"
  921. def visit_tuple_type(self, typ: TupleType) -> list[str]:
  922. triggers = []
  923. for item in typ.items:
  924. triggers.extend(self.get_type_triggers(item))
  925. triggers.extend(self.get_type_triggers(typ.partial_fallback))
  926. return triggers
  927. def visit_type_type(self, typ: TypeType) -> list[str]:
  928. triggers = self.get_type_triggers(typ.item)
  929. if not self.use_logical_deps:
  930. old_triggers = triggers.copy()
  931. for trigger in old_triggers:
  932. triggers.append(trigger.rstrip(">") + ".__init__>")
  933. triggers.append(trigger.rstrip(">") + ".__new__>")
  934. return triggers
  935. def visit_type_var(self, typ: TypeVarType) -> list[str]:
  936. triggers = []
  937. if typ.fullname:
  938. triggers.append(make_trigger(typ.fullname))
  939. if typ.upper_bound:
  940. triggers.extend(self.get_type_triggers(typ.upper_bound))
  941. if typ.default:
  942. triggers.extend(self.get_type_triggers(typ.default))
  943. for val in typ.values:
  944. triggers.extend(self.get_type_triggers(val))
  945. return triggers
  946. def visit_param_spec(self, typ: ParamSpecType) -> list[str]:
  947. triggers = []
  948. if typ.fullname:
  949. triggers.append(make_trigger(typ.fullname))
  950. if typ.upper_bound:
  951. triggers.extend(self.get_type_triggers(typ.upper_bound))
  952. if typ.default:
  953. triggers.extend(self.get_type_triggers(typ.default))
  954. triggers.extend(self.get_type_triggers(typ.upper_bound))
  955. return triggers
  956. def visit_type_var_tuple(self, typ: TypeVarTupleType) -> list[str]:
  957. triggers = []
  958. if typ.fullname:
  959. triggers.append(make_trigger(typ.fullname))
  960. if typ.upper_bound:
  961. triggers.extend(self.get_type_triggers(typ.upper_bound))
  962. if typ.default:
  963. triggers.extend(self.get_type_triggers(typ.default))
  964. triggers.extend(self.get_type_triggers(typ.upper_bound))
  965. return triggers
  966. def visit_unpack_type(self, typ: UnpackType) -> list[str]:
  967. return typ.type.accept(self)
  968. def visit_parameters(self, typ: Parameters) -> list[str]:
  969. triggers = []
  970. for arg in typ.arg_types:
  971. triggers.extend(self.get_type_triggers(arg))
  972. return triggers
  973. def visit_typeddict_type(self, typ: TypedDictType) -> list[str]:
  974. triggers = []
  975. for item in typ.items.values():
  976. triggers.extend(self.get_type_triggers(item))
  977. triggers.extend(self.get_type_triggers(typ.fallback))
  978. return triggers
  979. def visit_literal_type(self, typ: LiteralType) -> list[str]:
  980. return self.get_type_triggers(typ.fallback)
  981. def visit_unbound_type(self, typ: UnboundType) -> list[str]:
  982. return []
  983. def visit_uninhabited_type(self, typ: UninhabitedType) -> list[str]:
  984. return []
  985. def visit_union_type(self, typ: UnionType) -> list[str]:
  986. triggers = []
  987. for item in typ.items:
  988. triggers.extend(self.get_type_triggers(item))
  989. return triggers
  990. def merge_dependencies(new_deps: dict[str, set[str]], deps: dict[str, set[str]]) -> None:
  991. for trigger, targets in new_deps.items():
  992. deps.setdefault(trigger, set()).update(targets)
  993. def non_trivial_bases(info: TypeInfo) -> list[TypeInfo]:
  994. return [base for base in info.mro[1:] if base.fullname != "builtins.object"]
  995. def has_user_bases(info: TypeInfo) -> bool:
  996. return any(base.module_name not in ("builtins", "typing", "enum") for base in info.mro[1:])
  997. def dump_all_dependencies(
  998. modules: dict[str, MypyFile],
  999. type_map: dict[Expression, Type],
  1000. python_version: tuple[int, int],
  1001. options: Options,
  1002. ) -> None:
  1003. """Generate dependencies for all interesting modules and print them to stdout."""
  1004. all_deps: dict[str, set[str]] = {}
  1005. for id, node in modules.items():
  1006. # Uncomment for debugging:
  1007. # print('processing', id)
  1008. if id in ("builtins", "typing") or "/typeshed/" in node.path:
  1009. continue
  1010. assert id == node.fullname
  1011. deps = get_dependencies(node, type_map, python_version, options)
  1012. for trigger, targets in deps.items():
  1013. all_deps.setdefault(trigger, set()).update(targets)
  1014. type_state.add_all_protocol_deps(all_deps)
  1015. for trigger, targets in sorted(all_deps.items(), key=lambda x: x[0]):
  1016. print(trigger)
  1017. for target in sorted(targets):
  1018. print(f" {target}")