stubgen.py 74 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994
  1. #!/usr/bin/env python3
  2. """Generator of dynamically typed draft stubs for arbitrary modules.
  3. The logic of this script can be split in three steps:
  4. * parsing options and finding sources:
  5. - use runtime imports be default (to find also C modules)
  6. - or use mypy's mechanisms, if importing is prohibited
  7. * (optionally) semantically analysing the sources using mypy (as a single set)
  8. * emitting the stubs text:
  9. - for Python modules: from ASTs using StubGenerator
  10. - for C modules using runtime introspection and (optionally) Sphinx docs
  11. During first and third steps some problematic files can be skipped, but any
  12. blocking error during second step will cause the whole program to stop.
  13. Basic usage:
  14. $ stubgen foo.py bar.py some_directory
  15. => Generate out/foo.pyi, out/bar.pyi, and stubs for some_directory (recursively).
  16. $ stubgen -m urllib.parse
  17. => Generate out/urllib/parse.pyi.
  18. $ stubgen -p urllib
  19. => Generate stubs for whole urlib package (recursively).
  20. For C modules, you can get more precise function signatures by parsing .rst (Sphinx)
  21. documentation for extra information. For this, use the --doc-dir option:
  22. $ stubgen --doc-dir <DIR>/Python-3.4.2/Doc/library -m curses
  23. Note: The generated stubs should be verified manually.
  24. TODO:
  25. - maybe use .rst docs also for Python modules
  26. - maybe export more imported names if there is no __all__ (this affects ssl.SSLError, for example)
  27. - a quick and dirty heuristic would be to turn this on if a module has something like
  28. 'from x import y as _y'
  29. - we don't seem to always detect properties ('closed' in 'io', for example)
  30. """
  31. from __future__ import annotations
  32. import argparse
  33. import glob
  34. import keyword
  35. import os
  36. import os.path
  37. import sys
  38. import traceback
  39. from collections import defaultdict
  40. from typing import Final, Iterable, Mapping
  41. import mypy.build
  42. import mypy.mixedtraverser
  43. import mypy.parse
  44. import mypy.traverser
  45. import mypy.util
  46. from mypy.build import build
  47. from mypy.errors import CompileError, Errors
  48. from mypy.find_sources import InvalidSourceList, create_source_list
  49. from mypy.modulefinder import (
  50. BuildSource,
  51. FindModuleCache,
  52. ModuleNotFoundReason,
  53. SearchPaths,
  54. default_lib_path,
  55. )
  56. from mypy.moduleinspect import ModuleInspect
  57. from mypy.nodes import (
  58. ARG_NAMED,
  59. ARG_POS,
  60. ARG_STAR,
  61. ARG_STAR2,
  62. IS_ABSTRACT,
  63. NOT_ABSTRACT,
  64. AssignmentStmt,
  65. Block,
  66. BytesExpr,
  67. CallExpr,
  68. ClassDef,
  69. ComparisonExpr,
  70. ComplexExpr,
  71. Decorator,
  72. DictExpr,
  73. EllipsisExpr,
  74. Expression,
  75. FloatExpr,
  76. FuncBase,
  77. FuncDef,
  78. IfStmt,
  79. Import,
  80. ImportAll,
  81. ImportFrom,
  82. IndexExpr,
  83. IntExpr,
  84. ListExpr,
  85. MemberExpr,
  86. MypyFile,
  87. NameExpr,
  88. OpExpr,
  89. OverloadedFuncDef,
  90. Statement,
  91. StrExpr,
  92. TupleExpr,
  93. TypeInfo,
  94. UnaryExpr,
  95. Var,
  96. )
  97. from mypy.options import Options as MypyOptions
  98. from mypy.stubdoc import Sig, find_unique_signatures, parse_all_signatures
  99. from mypy.stubgenc import (
  100. DocstringSignatureGenerator,
  101. ExternalSignatureGenerator,
  102. FallbackSignatureGenerator,
  103. SignatureGenerator,
  104. generate_stub_for_c_module,
  105. )
  106. from mypy.stubutil import (
  107. CantImport,
  108. common_dir_prefix,
  109. fail_missing,
  110. find_module_path_and_all_py3,
  111. generate_guarded,
  112. remove_misplaced_type_comments,
  113. report_missing,
  114. walk_packages,
  115. )
  116. from mypy.traverser import (
  117. all_yield_expressions,
  118. has_return_statement,
  119. has_yield_expression,
  120. has_yield_from_expression,
  121. )
  122. from mypy.types import (
  123. OVERLOAD_NAMES,
  124. TPDICT_NAMES,
  125. TYPED_NAMEDTUPLE_NAMES,
  126. AnyType,
  127. CallableType,
  128. Instance,
  129. NoneType,
  130. TupleType,
  131. Type,
  132. TypeList,
  133. TypeStrVisitor,
  134. UnboundType,
  135. UnionType,
  136. get_proper_type,
  137. )
  138. from mypy.visitor import NodeVisitor
  139. TYPING_MODULE_NAMES: Final = ("typing", "typing_extensions")
  140. # Common ways of naming package containing vendored modules.
  141. VENDOR_PACKAGES: Final = ["packages", "vendor", "vendored", "_vendor", "_vendored_packages"]
  142. # Avoid some file names that are unnecessary or likely to cause trouble (\n for end of path).
  143. BLACKLIST: Final = [
  144. "/six.py\n", # Likely vendored six; too dynamic for us to handle
  145. "/vendored/", # Vendored packages
  146. "/vendor/", # Vendored packages
  147. "/_vendor/",
  148. "/_vendored_packages/",
  149. ]
  150. # Special-cased names that are implicitly exported from the stub (from m import y as y).
  151. EXTRA_EXPORTED: Final = {
  152. "pyasn1_modules.rfc2437.univ",
  153. "pyasn1_modules.rfc2459.char",
  154. "pyasn1_modules.rfc2459.univ",
  155. }
  156. # These names should be omitted from generated stubs.
  157. IGNORED_DUNDERS: Final = {
  158. "__all__",
  159. "__author__",
  160. "__version__",
  161. "__about__",
  162. "__copyright__",
  163. "__email__",
  164. "__license__",
  165. "__summary__",
  166. "__title__",
  167. "__uri__",
  168. "__str__",
  169. "__repr__",
  170. "__getstate__",
  171. "__setstate__",
  172. "__slots__",
  173. }
  174. # These methods are expected to always return a non-trivial value.
  175. METHODS_WITH_RETURN_VALUE: Final = {
  176. "__ne__",
  177. "__eq__",
  178. "__lt__",
  179. "__le__",
  180. "__gt__",
  181. "__ge__",
  182. "__hash__",
  183. "__iter__",
  184. }
  185. # These magic methods always return the same type.
  186. KNOWN_MAGIC_METHODS_RETURN_TYPES: Final = {
  187. "__len__": "int",
  188. "__length_hint__": "int",
  189. "__init__": "None",
  190. "__del__": "None",
  191. "__bool__": "bool",
  192. "__bytes__": "bytes",
  193. "__format__": "str",
  194. "__contains__": "bool",
  195. "__complex__": "complex",
  196. "__int__": "int",
  197. "__float__": "float",
  198. "__index__": "int",
  199. }
  200. class Options:
  201. """Represents stubgen options.
  202. This class is mutable to simplify testing.
  203. """
  204. def __init__(
  205. self,
  206. pyversion: tuple[int, int],
  207. no_import: bool,
  208. doc_dir: str,
  209. search_path: list[str],
  210. interpreter: str,
  211. parse_only: bool,
  212. ignore_errors: bool,
  213. include_private: bool,
  214. output_dir: str,
  215. modules: list[str],
  216. packages: list[str],
  217. files: list[str],
  218. verbose: bool,
  219. quiet: bool,
  220. export_less: bool,
  221. ) -> None:
  222. # See parse_options for descriptions of the flags.
  223. self.pyversion = pyversion
  224. self.no_import = no_import
  225. self.doc_dir = doc_dir
  226. self.search_path = search_path
  227. self.interpreter = interpreter
  228. self.decointerpreter = interpreter
  229. self.parse_only = parse_only
  230. self.ignore_errors = ignore_errors
  231. self.include_private = include_private
  232. self.output_dir = output_dir
  233. self.modules = modules
  234. self.packages = packages
  235. self.files = files
  236. self.verbose = verbose
  237. self.quiet = quiet
  238. self.export_less = export_less
  239. class StubSource:
  240. """A single source for stub: can be a Python or C module.
  241. A simple extension of BuildSource that also carries the AST and
  242. the value of __all__ detected at runtime.
  243. """
  244. def __init__(
  245. self, module: str, path: str | None = None, runtime_all: list[str] | None = None
  246. ) -> None:
  247. self.source = BuildSource(path, module, None)
  248. self.runtime_all = runtime_all
  249. self.ast: MypyFile | None = None
  250. @property
  251. def module(self) -> str:
  252. return self.source.module
  253. @property
  254. def path(self) -> str | None:
  255. return self.source.path
  256. # What was generated previously in the stub file. We keep track of these to generate
  257. # nicely formatted output (add empty line between non-empty classes, for example).
  258. EMPTY: Final = "EMPTY"
  259. FUNC: Final = "FUNC"
  260. CLASS: Final = "CLASS"
  261. EMPTY_CLASS: Final = "EMPTY_CLASS"
  262. VAR: Final = "VAR"
  263. NOT_IN_ALL: Final = "NOT_IN_ALL"
  264. # Indicates that we failed to generate a reasonable output
  265. # for a given node. These should be manually replaced by a user.
  266. ERROR_MARKER: Final = "<ERROR>"
  267. class AnnotationPrinter(TypeStrVisitor):
  268. """Visitor used to print existing annotations in a file.
  269. The main difference from TypeStrVisitor is a better treatment of
  270. unbound types.
  271. Notes:
  272. * This visitor doesn't add imports necessary for annotations, this is done separately
  273. by ImportTracker.
  274. * It can print all kinds of types, but the generated strings may not be valid (notably
  275. callable types) since it prints the same string that reveal_type() does.
  276. * For Instance types it prints the fully qualified names.
  277. """
  278. # TODO: Generate valid string representation for callable types.
  279. # TODO: Use short names for Instances.
  280. def __init__(self, stubgen: StubGenerator) -> None:
  281. super().__init__(options=mypy.options.Options())
  282. self.stubgen = stubgen
  283. def visit_any(self, t: AnyType) -> str:
  284. s = super().visit_any(t)
  285. self.stubgen.import_tracker.require_name(s)
  286. return s
  287. def visit_unbound_type(self, t: UnboundType) -> str:
  288. s = t.name
  289. self.stubgen.import_tracker.require_name(s)
  290. if t.args:
  291. s += f"[{self.args_str(t.args)}]"
  292. return s
  293. def visit_none_type(self, t: NoneType) -> str:
  294. return "None"
  295. def visit_type_list(self, t: TypeList) -> str:
  296. return f"[{self.list_str(t.items)}]"
  297. def visit_union_type(self, t: UnionType) -> str:
  298. return " | ".join([item.accept(self) for item in t.items])
  299. def args_str(self, args: Iterable[Type]) -> str:
  300. """Convert an array of arguments to strings and join the results with commas.
  301. The main difference from list_str is the preservation of quotes for string
  302. arguments
  303. """
  304. types = ["builtins.bytes", "builtins.str"]
  305. res = []
  306. for arg in args:
  307. arg_str = arg.accept(self)
  308. if isinstance(arg, UnboundType) and arg.original_str_fallback in types:
  309. res.append(f"'{arg_str}'")
  310. else:
  311. res.append(arg_str)
  312. return ", ".join(res)
  313. class AliasPrinter(NodeVisitor[str]):
  314. """Visitor used to collect type aliases _and_ type variable definitions.
  315. Visit r.h.s of the definition to get the string representation of type alias.
  316. """
  317. def __init__(self, stubgen: StubGenerator) -> None:
  318. self.stubgen = stubgen
  319. super().__init__()
  320. def visit_call_expr(self, node: CallExpr) -> str:
  321. # Call expressions are not usually types, but we also treat `X = TypeVar(...)` as a
  322. # type alias that has to be preserved (even if TypeVar is not the same as an alias)
  323. callee = node.callee.accept(self)
  324. args = []
  325. for name, arg, kind in zip(node.arg_names, node.args, node.arg_kinds):
  326. if kind == ARG_POS:
  327. args.append(arg.accept(self))
  328. elif kind == ARG_STAR:
  329. args.append("*" + arg.accept(self))
  330. elif kind == ARG_STAR2:
  331. args.append("**" + arg.accept(self))
  332. elif kind == ARG_NAMED:
  333. args.append(f"{name}={arg.accept(self)}")
  334. else:
  335. raise ValueError(f"Unknown argument kind {kind} in call")
  336. return f"{callee}({', '.join(args)})"
  337. def visit_name_expr(self, node: NameExpr) -> str:
  338. self.stubgen.import_tracker.require_name(node.name)
  339. return node.name
  340. def visit_member_expr(self, o: MemberExpr) -> str:
  341. node: Expression = o
  342. trailer = ""
  343. while isinstance(node, MemberExpr):
  344. trailer = "." + node.name + trailer
  345. node = node.expr
  346. if not isinstance(node, NameExpr):
  347. return ERROR_MARKER
  348. self.stubgen.import_tracker.require_name(node.name)
  349. return node.name + trailer
  350. def visit_str_expr(self, node: StrExpr) -> str:
  351. return repr(node.value)
  352. def visit_index_expr(self, node: IndexExpr) -> str:
  353. base = node.base.accept(self)
  354. index = node.index.accept(self)
  355. if len(index) > 2 and index.startswith("(") and index.endswith(")"):
  356. index = index[1:-1]
  357. return f"{base}[{index}]"
  358. def visit_tuple_expr(self, node: TupleExpr) -> str:
  359. return f"({', '.join(n.accept(self) for n in node.items)})"
  360. def visit_list_expr(self, node: ListExpr) -> str:
  361. return f"[{', '.join(n.accept(self) for n in node.items)}]"
  362. def visit_dict_expr(self, o: DictExpr) -> str:
  363. dict_items = []
  364. for key, value in o.items:
  365. # This is currently only used for TypedDict where all keys are strings.
  366. assert isinstance(key, StrExpr)
  367. dict_items.append(f"{key.accept(self)}: {value.accept(self)}")
  368. return f"{{{', '.join(dict_items)}}}"
  369. def visit_ellipsis(self, node: EllipsisExpr) -> str:
  370. return "..."
  371. def visit_op_expr(self, o: OpExpr) -> str:
  372. return f"{o.left.accept(self)} {o.op} {o.right.accept(self)}"
  373. class ImportTracker:
  374. """Record necessary imports during stub generation."""
  375. def __init__(self) -> None:
  376. # module_for['foo'] has the module name where 'foo' was imported from, or None if
  377. # 'foo' is a module imported directly; examples
  378. # 'from pkg.m import f as foo' ==> module_for['foo'] == 'pkg.m'
  379. # 'from m import f' ==> module_for['f'] == 'm'
  380. # 'import m' ==> module_for['m'] == None
  381. # 'import pkg.m' ==> module_for['pkg.m'] == None
  382. # ==> module_for['pkg'] == None
  383. self.module_for: dict[str, str | None] = {}
  384. # direct_imports['foo'] is the module path used when the name 'foo' was added to the
  385. # namespace.
  386. # import foo.bar.baz ==> direct_imports['foo'] == 'foo.bar.baz'
  387. # ==> direct_imports['foo.bar'] == 'foo.bar.baz'
  388. # ==> direct_imports['foo.bar.baz'] == 'foo.bar.baz'
  389. self.direct_imports: dict[str, str] = {}
  390. # reverse_alias['foo'] is the name that 'foo' had originally when imported with an
  391. # alias; examples
  392. # 'import numpy as np' ==> reverse_alias['np'] == 'numpy'
  393. # 'import foo.bar as bar' ==> reverse_alias['bar'] == 'foo.bar'
  394. # 'from decimal import Decimal as D' ==> reverse_alias['D'] == 'Decimal'
  395. self.reverse_alias: dict[str, str] = {}
  396. # required_names is the set of names that are actually used in a type annotation
  397. self.required_names: set[str] = set()
  398. # Names that should be reexported if they come from another module
  399. self.reexports: set[str] = set()
  400. def add_import_from(self, module: str, names: list[tuple[str, str | None]]) -> None:
  401. for name, alias in names:
  402. if alias:
  403. # 'from {module} import {name} as {alias}'
  404. self.module_for[alias] = module
  405. self.reverse_alias[alias] = name
  406. else:
  407. # 'from {module} import {name}'
  408. self.module_for[name] = module
  409. self.reverse_alias.pop(name, None)
  410. self.direct_imports.pop(alias or name, None)
  411. def add_import(self, module: str, alias: str | None = None) -> None:
  412. if alias:
  413. # 'import {module} as {alias}'
  414. self.module_for[alias] = None
  415. self.reverse_alias[alias] = module
  416. else:
  417. # 'import {module}'
  418. name = module
  419. # add module and its parent packages
  420. while name:
  421. self.module_for[name] = None
  422. self.direct_imports[name] = module
  423. self.reverse_alias.pop(name, None)
  424. name = name.rpartition(".")[0]
  425. def require_name(self, name: str) -> None:
  426. self.required_names.add(name.split(".")[0])
  427. def reexport(self, name: str) -> None:
  428. """Mark a given non qualified name as needed in __all__.
  429. This means that in case it comes from a module, it should be
  430. imported with an alias even is the alias is the same as the name.
  431. """
  432. self.require_name(name)
  433. self.reexports.add(name)
  434. def import_lines(self) -> list[str]:
  435. """The list of required import lines (as strings with python code)."""
  436. result = []
  437. # To summarize multiple names imported from a same module, we collect those
  438. # in the `module_map` dictionary, mapping a module path to the list of names that should
  439. # be imported from it. the names can also be alias in the form 'original as alias'
  440. module_map: Mapping[str, list[str]] = defaultdict(list)
  441. for name in sorted(self.required_names):
  442. # If we haven't seen this name in an import statement, ignore it
  443. if name not in self.module_for:
  444. continue
  445. m = self.module_for[name]
  446. if m is not None:
  447. # This name was found in a from ... import ...
  448. # Collect the name in the module_map
  449. if name in self.reverse_alias:
  450. name = f"{self.reverse_alias[name]} as {name}"
  451. elif name in self.reexports:
  452. name = f"{name} as {name}"
  453. module_map[m].append(name)
  454. else:
  455. # This name was found in an import ...
  456. # We can already generate the import line
  457. if name in self.reverse_alias:
  458. source = self.reverse_alias[name]
  459. result.append(f"import {source} as {name}\n")
  460. elif name in self.reexports:
  461. assert "." not in name # Because reexports only has nonqualified names
  462. result.append(f"import {name} as {name}\n")
  463. else:
  464. result.append(f"import {self.direct_imports[name]}\n")
  465. # Now generate all the from ... import ... lines collected in module_map
  466. for module, names in sorted(module_map.items()):
  467. result.append(f"from {module} import {', '.join(sorted(names))}\n")
  468. return result
  469. def find_defined_names(file: MypyFile) -> set[str]:
  470. finder = DefinitionFinder()
  471. file.accept(finder)
  472. return finder.names
  473. class DefinitionFinder(mypy.traverser.TraverserVisitor):
  474. """Find names of things defined at the top level of a module."""
  475. # TODO: Assignment statements etc.
  476. def __init__(self) -> None:
  477. # Short names of things defined at the top level.
  478. self.names: set[str] = set()
  479. def visit_class_def(self, o: ClassDef) -> None:
  480. # Don't recurse into classes, as we only keep track of top-level definitions.
  481. self.names.add(o.name)
  482. def visit_func_def(self, o: FuncDef) -> None:
  483. # Don't recurse, as we only keep track of top-level definitions.
  484. self.names.add(o.name)
  485. def find_referenced_names(file: MypyFile) -> set[str]:
  486. finder = ReferenceFinder()
  487. file.accept(finder)
  488. return finder.refs
  489. class ReferenceFinder(mypy.mixedtraverser.MixedTraverserVisitor):
  490. """Find all name references (both local and global)."""
  491. # TODO: Filter out local variable and class attribute references
  492. def __init__(self) -> None:
  493. # Short names of things defined at the top level.
  494. self.refs: set[str] = set()
  495. def visit_block(self, block: Block) -> None:
  496. if not block.is_unreachable:
  497. super().visit_block(block)
  498. def visit_name_expr(self, e: NameExpr) -> None:
  499. self.refs.add(e.name)
  500. def visit_instance(self, t: Instance) -> None:
  501. self.add_ref(t.type.fullname)
  502. super().visit_instance(t)
  503. def visit_unbound_type(self, t: UnboundType) -> None:
  504. if t.name:
  505. self.add_ref(t.name)
  506. def visit_tuple_type(self, t: TupleType) -> None:
  507. # Ignore fallback
  508. for item in t.items:
  509. item.accept(self)
  510. def visit_callable_type(self, t: CallableType) -> None:
  511. # Ignore fallback
  512. for arg in t.arg_types:
  513. arg.accept(self)
  514. t.ret_type.accept(self)
  515. def add_ref(self, fullname: str) -> None:
  516. self.refs.add(fullname.split(".")[-1])
  517. class StubGenerator(mypy.traverser.TraverserVisitor):
  518. """Generate stub text from a mypy AST."""
  519. def __init__(
  520. self,
  521. _all_: list[str] | None,
  522. include_private: bool = False,
  523. analyzed: bool = False,
  524. export_less: bool = False,
  525. ) -> None:
  526. # Best known value of __all__.
  527. self._all_ = _all_
  528. self._output: list[str] = []
  529. self._decorators: list[str] = []
  530. self._import_lines: list[str] = []
  531. # Current indent level (indent is hardcoded to 4 spaces).
  532. self._indent = ""
  533. # Stack of defined variables (per scope).
  534. self._vars: list[list[str]] = [[]]
  535. # What was generated previously in the stub file.
  536. self._state = EMPTY
  537. self._toplevel_names: list[str] = []
  538. self._include_private = include_private
  539. self.import_tracker = ImportTracker()
  540. # Was the tree semantically analysed before?
  541. self.analyzed = analyzed
  542. # Disable implicit exports of package-internal imports?
  543. self.export_less = export_less
  544. # Add imports that could be implicitly generated
  545. self.import_tracker.add_import_from("typing", [("NamedTuple", None)])
  546. # Names in __all__ are required
  547. for name in _all_ or ():
  548. if name not in IGNORED_DUNDERS:
  549. self.import_tracker.reexport(name)
  550. self.defined_names: set[str] = set()
  551. # Short names of methods defined in the body of the current class
  552. self.method_names: set[str] = set()
  553. def visit_mypy_file(self, o: MypyFile) -> None:
  554. self.module = o.fullname # Current module being processed
  555. self.path = o.path
  556. self.defined_names = find_defined_names(o)
  557. self.referenced_names = find_referenced_names(o)
  558. known_imports = {
  559. "_typeshed": ["Incomplete"],
  560. "typing": ["Any", "TypeVar", "NamedTuple"],
  561. "collections.abc": ["Generator"],
  562. "typing_extensions": ["TypedDict", "ParamSpec", "TypeVarTuple"],
  563. }
  564. for pkg, imports in known_imports.items():
  565. for t in imports:
  566. if t not in self.defined_names:
  567. alias = None
  568. else:
  569. alias = "_" + t
  570. self.import_tracker.add_import_from(pkg, [(t, alias)])
  571. super().visit_mypy_file(o)
  572. undefined_names = [name for name in self._all_ or [] if name not in self._toplevel_names]
  573. if undefined_names:
  574. if self._state != EMPTY:
  575. self.add("\n")
  576. self.add("# Names in __all__ with no definition:\n")
  577. for name in sorted(undefined_names):
  578. self.add(f"# {name}\n")
  579. def visit_overloaded_func_def(self, o: OverloadedFuncDef) -> None:
  580. """@property with setters and getters, @overload chain and some others."""
  581. overload_chain = False
  582. for item in o.items:
  583. if not isinstance(item, Decorator):
  584. continue
  585. if self.is_private_name(item.func.name, item.func.fullname):
  586. continue
  587. self.process_decorator(item)
  588. if not overload_chain:
  589. self.visit_func_def(item.func)
  590. if item.func.is_overload:
  591. overload_chain = True
  592. elif item.func.is_overload:
  593. self.visit_func_def(item.func)
  594. else:
  595. # skip the overload implementation and clear the decorator we just processed
  596. self.clear_decorators()
  597. def visit_func_def(self, o: FuncDef) -> None:
  598. if (
  599. self.is_private_name(o.name, o.fullname)
  600. or self.is_not_in_all(o.name)
  601. or (self.is_recorded_name(o.name) and not o.is_overload)
  602. ):
  603. self.clear_decorators()
  604. return
  605. if not self._indent and self._state not in (EMPTY, FUNC) and not o.is_awaitable_coroutine:
  606. self.add("\n")
  607. if not self.is_top_level():
  608. self_inits = find_self_initializers(o)
  609. for init, value in self_inits:
  610. if init in self.method_names:
  611. # Can't have both an attribute and a method/property with the same name.
  612. continue
  613. init_code = self.get_init(init, value)
  614. if init_code:
  615. self.add(init_code)
  616. # dump decorators, just before "def ..."
  617. for s in self._decorators:
  618. self.add(s)
  619. self.clear_decorators()
  620. self.add(f"{self._indent}{'async ' if o.is_coroutine else ''}def {o.name}(")
  621. self.record_name(o.name)
  622. args: list[str] = []
  623. for i, arg_ in enumerate(o.arguments):
  624. var = arg_.variable
  625. kind = arg_.kind
  626. name = var.name
  627. annotated_type = (
  628. o.unanalyzed_type.arg_types[i]
  629. if isinstance(o.unanalyzed_type, CallableType)
  630. else None
  631. )
  632. # I think the name check is incorrect: there are libraries which
  633. # name their 0th argument other than self/cls
  634. is_self_arg = i == 0 and name == "self"
  635. is_cls_arg = i == 0 and name == "cls"
  636. annotation = ""
  637. if annotated_type and not is_self_arg and not is_cls_arg:
  638. # Luckily, an argument explicitly annotated with "Any" has
  639. # type "UnboundType" and will not match.
  640. if not isinstance(get_proper_type(annotated_type), AnyType):
  641. annotation = f": {self.print_annotation(annotated_type)}"
  642. if kind.is_named() and not any(arg.startswith("*") for arg in args):
  643. args.append("*")
  644. if arg_.initializer:
  645. if not annotation:
  646. typename = self.get_str_type_of_node(arg_.initializer, True, False)
  647. if typename == "":
  648. annotation = "=..."
  649. else:
  650. annotation = f": {typename} = ..."
  651. else:
  652. annotation += " = ..."
  653. arg = name + annotation
  654. elif kind == ARG_STAR:
  655. arg = f"*{name}{annotation}"
  656. elif kind == ARG_STAR2:
  657. arg = f"**{name}{annotation}"
  658. else:
  659. arg = name + annotation
  660. args.append(arg)
  661. retname = None
  662. if o.name != "__init__" and isinstance(o.unanalyzed_type, CallableType):
  663. if isinstance(get_proper_type(o.unanalyzed_type.ret_type), AnyType):
  664. # Luckily, a return type explicitly annotated with "Any" has
  665. # type "UnboundType" and will enter the else branch.
  666. retname = None # implicit Any
  667. else:
  668. retname = self.print_annotation(o.unanalyzed_type.ret_type)
  669. elif o.abstract_status == IS_ABSTRACT or o.name in METHODS_WITH_RETURN_VALUE:
  670. # Always assume abstract methods return Any unless explicitly annotated. Also
  671. # some dunder methods should not have a None return type.
  672. retname = None # implicit Any
  673. elif o.name in KNOWN_MAGIC_METHODS_RETURN_TYPES:
  674. retname = KNOWN_MAGIC_METHODS_RETURN_TYPES[o.name]
  675. elif has_yield_expression(o) or has_yield_from_expression(o):
  676. self.add_typing_import("Generator")
  677. yield_name = "None"
  678. send_name = "None"
  679. return_name = "None"
  680. if has_yield_from_expression(o):
  681. self.add_typing_import("Incomplete")
  682. yield_name = send_name = self.typing_name("Incomplete")
  683. else:
  684. for expr, in_assignment in all_yield_expressions(o):
  685. if expr.expr is not None and not self.is_none_expr(expr.expr):
  686. self.add_typing_import("Incomplete")
  687. yield_name = self.typing_name("Incomplete")
  688. if in_assignment:
  689. self.add_typing_import("Incomplete")
  690. send_name = self.typing_name("Incomplete")
  691. if has_return_statement(o):
  692. self.add_typing_import("Incomplete")
  693. return_name = self.typing_name("Incomplete")
  694. generator_name = self.typing_name("Generator")
  695. retname = f"{generator_name}[{yield_name}, {send_name}, {return_name}]"
  696. elif not has_return_statement(o) and o.abstract_status == NOT_ABSTRACT:
  697. retname = "None"
  698. retfield = ""
  699. if retname is not None:
  700. retfield = " -> " + retname
  701. self.add(", ".join(args))
  702. self.add(f"){retfield}: ...\n")
  703. self._state = FUNC
  704. def is_none_expr(self, expr: Expression) -> bool:
  705. return isinstance(expr, NameExpr) and expr.name == "None"
  706. def visit_decorator(self, o: Decorator) -> None:
  707. if self.is_private_name(o.func.name, o.func.fullname):
  708. return
  709. self.process_decorator(o)
  710. self.visit_func_def(o.func)
  711. def process_decorator(self, o: Decorator) -> None:
  712. """Process a series of decorators.
  713. Only preserve certain special decorators such as @abstractmethod.
  714. """
  715. for decorator in o.original_decorators:
  716. if not isinstance(decorator, (NameExpr, MemberExpr)):
  717. continue
  718. qualname = get_qualified_name(decorator)
  719. fullname = self.get_fullname(decorator)
  720. if fullname in (
  721. "builtins.property",
  722. "builtins.staticmethod",
  723. "builtins.classmethod",
  724. "functools.cached_property",
  725. ):
  726. self.add_decorator(qualname, require_name=True)
  727. elif fullname in (
  728. "asyncio.coroutine",
  729. "asyncio.coroutines.coroutine",
  730. "types.coroutine",
  731. ):
  732. o.func.is_awaitable_coroutine = True
  733. self.add_decorator(qualname, require_name=True)
  734. elif fullname == "abc.abstractmethod":
  735. self.add_decorator(qualname, require_name=True)
  736. o.func.abstract_status = IS_ABSTRACT
  737. elif fullname in (
  738. "abc.abstractproperty",
  739. "abc.abstractstaticmethod",
  740. "abc.abstractclassmethod",
  741. ):
  742. abc_module = qualname.rpartition(".")[0]
  743. if not abc_module:
  744. self.import_tracker.add_import("abc")
  745. builtin_decorator_replacement = fullname[len("abc.abstract") :]
  746. self.add_decorator(builtin_decorator_replacement, require_name=False)
  747. self.add_decorator(f"{abc_module or 'abc'}.abstractmethod", require_name=True)
  748. o.func.abstract_status = IS_ABSTRACT
  749. elif fullname in OVERLOAD_NAMES:
  750. self.add_decorator(qualname, require_name=True)
  751. o.func.is_overload = True
  752. elif qualname.endswith(".setter"):
  753. self.add_decorator(qualname, require_name=False)
  754. def get_fullname(self, expr: Expression) -> str:
  755. """Return the full name resolving imports and import aliases."""
  756. if (
  757. self.analyzed
  758. and isinstance(expr, (NameExpr, MemberExpr))
  759. and expr.fullname
  760. and not (isinstance(expr.node, Var) and expr.node.is_suppressed_import)
  761. ):
  762. return expr.fullname
  763. name = get_qualified_name(expr)
  764. if "." not in name:
  765. real_module = self.import_tracker.module_for.get(name)
  766. real_short = self.import_tracker.reverse_alias.get(name, name)
  767. if real_module is None and real_short not in self.defined_names:
  768. real_module = "builtins" # not imported and not defined, must be a builtin
  769. else:
  770. name_module, real_short = name.split(".", 1)
  771. real_module = self.import_tracker.reverse_alias.get(name_module, name_module)
  772. resolved_name = real_short if real_module is None else f"{real_module}.{real_short}"
  773. return resolved_name
  774. def visit_class_def(self, o: ClassDef) -> None:
  775. self.method_names = find_method_names(o.defs.body)
  776. sep: int | None = None
  777. if not self._indent and self._state != EMPTY:
  778. sep = len(self._output)
  779. self.add("\n")
  780. self.add(f"{self._indent}class {o.name}")
  781. self.record_name(o.name)
  782. base_types = self.get_base_types(o)
  783. if base_types:
  784. for base in base_types:
  785. self.import_tracker.require_name(base)
  786. if isinstance(o.metaclass, (NameExpr, MemberExpr)):
  787. meta = o.metaclass.accept(AliasPrinter(self))
  788. base_types.append("metaclass=" + meta)
  789. elif self.analyzed and o.info.is_abstract and not o.info.is_protocol:
  790. base_types.append("metaclass=abc.ABCMeta")
  791. self.import_tracker.add_import("abc")
  792. self.import_tracker.require_name("abc")
  793. if base_types:
  794. self.add(f"({', '.join(base_types)})")
  795. self.add(":\n")
  796. n = len(self._output)
  797. self._indent += " "
  798. self._vars.append([])
  799. super().visit_class_def(o)
  800. self._indent = self._indent[:-4]
  801. self._vars.pop()
  802. self._vars[-1].append(o.name)
  803. if len(self._output) == n:
  804. if self._state == EMPTY_CLASS and sep is not None:
  805. self._output[sep] = ""
  806. self._output[-1] = self._output[-1][:-1] + " ...\n"
  807. self._state = EMPTY_CLASS
  808. else:
  809. self._state = CLASS
  810. self.method_names = set()
  811. def get_base_types(self, cdef: ClassDef) -> list[str]:
  812. """Get list of base classes for a class."""
  813. base_types: list[str] = []
  814. p = AliasPrinter(self)
  815. for base in cdef.base_type_exprs + cdef.removed_base_type_exprs:
  816. if isinstance(base, (NameExpr, MemberExpr)):
  817. if self.get_fullname(base) != "builtins.object":
  818. base_types.append(get_qualified_name(base))
  819. elif isinstance(base, IndexExpr):
  820. base_types.append(base.accept(p))
  821. elif isinstance(base, CallExpr):
  822. # namedtuple(typename, fields), NamedTuple(typename, fields) calls can
  823. # be used as a base class. The first argument is a string literal that
  824. # is usually the same as the class name.
  825. #
  826. # Note:
  827. # A call-based named tuple as a base class cannot be safely converted to
  828. # a class-based NamedTuple definition because class attributes defined
  829. # in the body of the class inheriting from the named tuple call are not
  830. # namedtuple fields at runtime.
  831. if self.is_namedtuple(base):
  832. nt_fields = self._get_namedtuple_fields(base)
  833. assert isinstance(base.args[0], StrExpr)
  834. typename = base.args[0].value
  835. if nt_fields is not None:
  836. fields_str = ", ".join(f"({f!r}, {t})" for f, t in nt_fields)
  837. namedtuple_name = self.typing_name("NamedTuple")
  838. base_types.append(f"{namedtuple_name}({typename!r}, [{fields_str}])")
  839. self.add_typing_import("NamedTuple")
  840. else:
  841. # Invalid namedtuple() call, cannot determine fields
  842. base_types.append(self.typing_name("Incomplete"))
  843. elif self.is_typed_namedtuple(base):
  844. base_types.append(base.accept(p))
  845. else:
  846. # At this point, we don't know what the base class is, so we
  847. # just use Incomplete as the base class.
  848. base_types.append(self.typing_name("Incomplete"))
  849. self.add_typing_import("Incomplete")
  850. for name, value in cdef.keywords.items():
  851. if name == "metaclass":
  852. continue # handled separately
  853. base_types.append(f"{name}={value.accept(p)}")
  854. return base_types
  855. def visit_block(self, o: Block) -> None:
  856. # Unreachable statements may be partially uninitialized and that may
  857. # cause trouble.
  858. if not o.is_unreachable:
  859. super().visit_block(o)
  860. def visit_assignment_stmt(self, o: AssignmentStmt) -> None:
  861. foundl = []
  862. for lvalue in o.lvalues:
  863. if isinstance(lvalue, NameExpr) and isinstance(o.rvalue, CallExpr):
  864. if self.is_namedtuple(o.rvalue) or self.is_typed_namedtuple(o.rvalue):
  865. self.process_namedtuple(lvalue, o.rvalue)
  866. foundl.append(False) # state is updated in process_namedtuple
  867. continue
  868. if self.is_typeddict(o.rvalue):
  869. self.process_typeddict(lvalue, o.rvalue)
  870. foundl.append(False) # state is updated in process_typeddict
  871. continue
  872. if (
  873. isinstance(lvalue, NameExpr)
  874. and not self.is_private_name(lvalue.name)
  875. # it is never an alias with explicit annotation
  876. and not o.unanalyzed_type
  877. and self.is_alias_expression(o.rvalue)
  878. ):
  879. self.process_typealias(lvalue, o.rvalue)
  880. continue
  881. if isinstance(lvalue, (TupleExpr, ListExpr)):
  882. items = lvalue.items
  883. if isinstance(o.unanalyzed_type, TupleType): # type: ignore[misc]
  884. annotations: Iterable[Type | None] = o.unanalyzed_type.items
  885. else:
  886. annotations = [None] * len(items)
  887. else:
  888. items = [lvalue]
  889. annotations = [o.unanalyzed_type]
  890. sep = False
  891. found = False
  892. for item, annotation in zip(items, annotations):
  893. if isinstance(item, NameExpr):
  894. init = self.get_init(item.name, o.rvalue, annotation)
  895. if init:
  896. found = True
  897. if not sep and not self._indent and self._state not in (EMPTY, VAR):
  898. init = "\n" + init
  899. sep = True
  900. self.add(init)
  901. self.record_name(item.name)
  902. foundl.append(found)
  903. if all(foundl):
  904. self._state = VAR
  905. def is_namedtuple(self, expr: CallExpr) -> bool:
  906. return self.get_fullname(expr.callee) == "collections.namedtuple"
  907. def is_typed_namedtuple(self, expr: CallExpr) -> bool:
  908. return self.get_fullname(expr.callee) in TYPED_NAMEDTUPLE_NAMES
  909. def _get_namedtuple_fields(self, call: CallExpr) -> list[tuple[str, str]] | None:
  910. if self.is_namedtuple(call):
  911. fields_arg = call.args[1]
  912. if isinstance(fields_arg, StrExpr):
  913. field_names = fields_arg.value.replace(",", " ").split()
  914. elif isinstance(fields_arg, (ListExpr, TupleExpr)):
  915. field_names = []
  916. for field in fields_arg.items:
  917. if not isinstance(field, StrExpr):
  918. return None
  919. field_names.append(field.value)
  920. else:
  921. return None # Invalid namedtuple fields type
  922. if field_names:
  923. self.add_typing_import("Incomplete")
  924. incomplete = self.typing_name("Incomplete")
  925. return [(field_name, incomplete) for field_name in field_names]
  926. elif self.is_typed_namedtuple(call):
  927. fields_arg = call.args[1]
  928. if not isinstance(fields_arg, (ListExpr, TupleExpr)):
  929. return None
  930. fields: list[tuple[str, str]] = []
  931. p = AliasPrinter(self)
  932. for field in fields_arg.items:
  933. if not (isinstance(field, TupleExpr) and len(field.items) == 2):
  934. return None
  935. field_name, field_type = field.items
  936. if not isinstance(field_name, StrExpr):
  937. return None
  938. fields.append((field_name.value, field_type.accept(p)))
  939. return fields
  940. else:
  941. return None # Not a named tuple call
  942. def process_namedtuple(self, lvalue: NameExpr, rvalue: CallExpr) -> None:
  943. if self._state == CLASS:
  944. self.add("\n")
  945. if not isinstance(rvalue.args[0], StrExpr):
  946. self.annotate_as_incomplete(lvalue)
  947. return
  948. fields = self._get_namedtuple_fields(rvalue)
  949. if fields is None:
  950. self.annotate_as_incomplete(lvalue)
  951. return
  952. self.add_typing_import("NamedTuple")
  953. bases = self.typing_name("NamedTuple")
  954. # TODO: Add support for generic NamedTuples. Requires `Generic` as base class.
  955. class_def = f"{self._indent}class {lvalue.name}({bases}):"
  956. if len(fields) == 0:
  957. self.add(f"{class_def} ...\n")
  958. self._state = EMPTY_CLASS
  959. else:
  960. if self._state not in (EMPTY, CLASS):
  961. self.add("\n")
  962. self.add(f"{class_def}\n")
  963. for f_name, f_type in fields:
  964. self.add(f"{self._indent} {f_name}: {f_type}\n")
  965. self._state = CLASS
  966. def is_typeddict(self, expr: CallExpr) -> bool:
  967. return self.get_fullname(expr.callee) in TPDICT_NAMES
  968. def process_typeddict(self, lvalue: NameExpr, rvalue: CallExpr) -> None:
  969. if self._state == CLASS:
  970. self.add("\n")
  971. if not isinstance(rvalue.args[0], StrExpr):
  972. self.annotate_as_incomplete(lvalue)
  973. return
  974. items: list[tuple[str, Expression]] = []
  975. total: Expression | None = None
  976. if len(rvalue.args) > 1 and rvalue.arg_kinds[1] == ARG_POS:
  977. if not isinstance(rvalue.args[1], DictExpr):
  978. self.annotate_as_incomplete(lvalue)
  979. return
  980. for attr_name, attr_type in rvalue.args[1].items:
  981. if not isinstance(attr_name, StrExpr):
  982. self.annotate_as_incomplete(lvalue)
  983. return
  984. items.append((attr_name.value, attr_type))
  985. if len(rvalue.args) > 2:
  986. if rvalue.arg_kinds[2] != ARG_NAMED or rvalue.arg_names[2] != "total":
  987. self.annotate_as_incomplete(lvalue)
  988. return
  989. total = rvalue.args[2]
  990. else:
  991. for arg_name, arg in zip(rvalue.arg_names[1:], rvalue.args[1:]):
  992. if not isinstance(arg_name, str):
  993. self.annotate_as_incomplete(lvalue)
  994. return
  995. if arg_name == "total":
  996. total = arg
  997. else:
  998. items.append((arg_name, arg))
  999. self.add_typing_import("TypedDict")
  1000. p = AliasPrinter(self)
  1001. if any(not key.isidentifier() or keyword.iskeyword(key) for key, _ in items):
  1002. # Keep the call syntax if there are non-identifier or reserved keyword keys.
  1003. self.add(f"{self._indent}{lvalue.name} = {rvalue.accept(p)}\n")
  1004. self._state = VAR
  1005. else:
  1006. bases = self.typing_name("TypedDict")
  1007. # TODO: Add support for generic TypedDicts. Requires `Generic` as base class.
  1008. if total is not None:
  1009. bases += f", total={total.accept(p)}"
  1010. class_def = f"{self._indent}class {lvalue.name}({bases}):"
  1011. if len(items) == 0:
  1012. self.add(f"{class_def} ...\n")
  1013. self._state = EMPTY_CLASS
  1014. else:
  1015. if self._state not in (EMPTY, CLASS):
  1016. self.add("\n")
  1017. self.add(f"{class_def}\n")
  1018. for key, key_type in items:
  1019. self.add(f"{self._indent} {key}: {key_type.accept(p)}\n")
  1020. self._state = CLASS
  1021. def annotate_as_incomplete(self, lvalue: NameExpr) -> None:
  1022. self.add_typing_import("Incomplete")
  1023. self.add(f"{self._indent}{lvalue.name}: {self.typing_name('Incomplete')}\n")
  1024. self._state = VAR
  1025. def is_alias_expression(self, expr: Expression, top_level: bool = True) -> bool:
  1026. """Return True for things that look like target for an alias.
  1027. Used to know if assignments look like type aliases, function alias,
  1028. or module alias.
  1029. """
  1030. # Assignment of TypeVar(...) and other typevar-likes are passed through
  1031. if isinstance(expr, CallExpr) and self.get_fullname(expr.callee) in (
  1032. "typing.TypeVar",
  1033. "typing_extensions.TypeVar",
  1034. "typing.ParamSpec",
  1035. "typing_extensions.ParamSpec",
  1036. "typing.TypeVarTuple",
  1037. "typing_extensions.TypeVarTuple",
  1038. ):
  1039. return True
  1040. elif isinstance(expr, EllipsisExpr):
  1041. return not top_level
  1042. elif isinstance(expr, NameExpr):
  1043. if expr.name in ("True", "False"):
  1044. return False
  1045. elif expr.name == "None":
  1046. return not top_level
  1047. else:
  1048. return not self.is_private_name(expr.name)
  1049. elif isinstance(expr, MemberExpr) and self.analyzed:
  1050. # Also add function and module aliases.
  1051. return (
  1052. top_level
  1053. and isinstance(expr.node, (FuncDef, Decorator, MypyFile))
  1054. or isinstance(expr.node, TypeInfo)
  1055. ) and not self.is_private_member(expr.node.fullname)
  1056. elif (
  1057. isinstance(expr, IndexExpr)
  1058. and isinstance(expr.base, NameExpr)
  1059. and not self.is_private_name(expr.base.name)
  1060. ):
  1061. if isinstance(expr.index, TupleExpr):
  1062. indices = expr.index.items
  1063. else:
  1064. indices = [expr.index]
  1065. if expr.base.name == "Callable" and len(indices) == 2:
  1066. args, ret = indices
  1067. if isinstance(args, EllipsisExpr):
  1068. indices = [ret]
  1069. elif isinstance(args, ListExpr):
  1070. indices = args.items + [ret]
  1071. else:
  1072. return False
  1073. return all(self.is_alias_expression(i, top_level=False) for i in indices)
  1074. else:
  1075. return False
  1076. def process_typealias(self, lvalue: NameExpr, rvalue: Expression) -> None:
  1077. p = AliasPrinter(self)
  1078. self.add(f"{self._indent}{lvalue.name} = {rvalue.accept(p)}\n")
  1079. self.record_name(lvalue.name)
  1080. self._vars[-1].append(lvalue.name)
  1081. def visit_if_stmt(self, o: IfStmt) -> None:
  1082. # Ignore if __name__ == '__main__'.
  1083. expr = o.expr[0]
  1084. if (
  1085. isinstance(expr, ComparisonExpr)
  1086. and isinstance(expr.operands[0], NameExpr)
  1087. and isinstance(expr.operands[1], StrExpr)
  1088. and expr.operands[0].name == "__name__"
  1089. and "__main__" in expr.operands[1].value
  1090. ):
  1091. return
  1092. super().visit_if_stmt(o)
  1093. def visit_import_all(self, o: ImportAll) -> None:
  1094. self.add_import_line(f"from {'.' * o.relative}{o.id} import *\n")
  1095. def visit_import_from(self, o: ImportFrom) -> None:
  1096. exported_names: set[str] = set()
  1097. import_names = []
  1098. module, relative = translate_module_name(o.id, o.relative)
  1099. if self.module:
  1100. full_module, ok = mypy.util.correct_relative_import(
  1101. self.module, relative, module, self.path.endswith(".__init__.py")
  1102. )
  1103. if not ok:
  1104. full_module = module
  1105. else:
  1106. full_module = module
  1107. if module == "__future__":
  1108. return # Not preserved
  1109. for name, as_name in o.names:
  1110. if name == "six":
  1111. # Vendored six -- translate into plain 'import six'.
  1112. self.visit_import(Import([("six", None)]))
  1113. continue
  1114. exported = False
  1115. if as_name is None and self.module and (self.module + "." + name) in EXTRA_EXPORTED:
  1116. # Special case certain names that should be exported, against our general rules.
  1117. exported = True
  1118. is_private = self.is_private_name(name, full_module + "." + name)
  1119. if (
  1120. as_name is None
  1121. and name not in self.referenced_names
  1122. and (not self._all_ or name in IGNORED_DUNDERS)
  1123. and not is_private
  1124. and module not in ("abc", "asyncio") + TYPING_MODULE_NAMES
  1125. ):
  1126. # An imported name that is never referenced in the module is assumed to be
  1127. # exported, unless there is an explicit __all__. Note that we need to special
  1128. # case 'abc' since some references are deleted during semantic analysis.
  1129. exported = True
  1130. top_level = full_module.split(".")[0]
  1131. if (
  1132. as_name is None
  1133. and not self.export_less
  1134. and (not self._all_ or name in IGNORED_DUNDERS)
  1135. and self.module
  1136. and not is_private
  1137. and top_level in (self.module.split(".")[0], "_" + self.module.split(".")[0])
  1138. ):
  1139. # Export imports from the same package, since we can't reliably tell whether they
  1140. # are part of the public API.
  1141. exported = True
  1142. if exported:
  1143. self.import_tracker.reexport(name)
  1144. as_name = name
  1145. import_names.append((name, as_name))
  1146. self.import_tracker.add_import_from("." * relative + module, import_names)
  1147. self._vars[-1].extend(alias or name for name, alias in import_names)
  1148. for name, alias in import_names:
  1149. self.record_name(alias or name)
  1150. if self._all_:
  1151. # Include "import from"s that import names defined in __all__.
  1152. names = [
  1153. name
  1154. for name, alias in o.names
  1155. if name in self._all_ and alias is None and name not in IGNORED_DUNDERS
  1156. ]
  1157. exported_names.update(names)
  1158. def visit_import(self, o: Import) -> None:
  1159. for id, as_id in o.ids:
  1160. self.import_tracker.add_import(id, as_id)
  1161. if as_id is None:
  1162. target_name = id.split(".")[0]
  1163. else:
  1164. target_name = as_id
  1165. self._vars[-1].append(target_name)
  1166. self.record_name(target_name)
  1167. def get_init(
  1168. self, lvalue: str, rvalue: Expression, annotation: Type | None = None
  1169. ) -> str | None:
  1170. """Return initializer for a variable.
  1171. Return None if we've generated one already or if the variable is internal.
  1172. """
  1173. if lvalue in self._vars[-1]:
  1174. # We've generated an initializer already for this variable.
  1175. return None
  1176. # TODO: Only do this at module top level.
  1177. if self.is_private_name(lvalue) or self.is_not_in_all(lvalue):
  1178. return None
  1179. self._vars[-1].append(lvalue)
  1180. if annotation is not None:
  1181. typename = self.print_annotation(annotation)
  1182. if (
  1183. isinstance(annotation, UnboundType)
  1184. and not annotation.args
  1185. and annotation.name == "Final"
  1186. and self.import_tracker.module_for.get("Final") in TYPING_MODULE_NAMES
  1187. ):
  1188. # Final without type argument is invalid in stubs.
  1189. final_arg = self.get_str_type_of_node(rvalue)
  1190. typename += f"[{final_arg}]"
  1191. else:
  1192. typename = self.get_str_type_of_node(rvalue)
  1193. return f"{self._indent}{lvalue}: {typename}\n"
  1194. def add(self, string: str) -> None:
  1195. """Add text to generated stub."""
  1196. self._output.append(string)
  1197. def add_decorator(self, name: str, require_name: bool = False) -> None:
  1198. if require_name:
  1199. self.import_tracker.require_name(name)
  1200. if not self._indent and self._state not in (EMPTY, FUNC):
  1201. self._decorators.append("\n")
  1202. self._decorators.append(f"{self._indent}@{name}\n")
  1203. def clear_decorators(self) -> None:
  1204. self._decorators.clear()
  1205. def typing_name(self, name: str) -> str:
  1206. if name in self.defined_names:
  1207. # Avoid name clash between name from typing and a name defined in stub.
  1208. return "_" + name
  1209. else:
  1210. return name
  1211. def add_typing_import(self, name: str) -> None:
  1212. """Add a name to be imported for typing, unless it's imported already.
  1213. The import will be internal to the stub.
  1214. """
  1215. name = self.typing_name(name)
  1216. self.import_tracker.require_name(name)
  1217. def add_import_line(self, line: str) -> None:
  1218. """Add a line of text to the import section, unless it's already there."""
  1219. if line not in self._import_lines:
  1220. self._import_lines.append(line)
  1221. def output(self) -> str:
  1222. """Return the text for the stub."""
  1223. imports = ""
  1224. if self._import_lines:
  1225. imports += "".join(self._import_lines)
  1226. imports += "".join(self.import_tracker.import_lines())
  1227. if imports and self._output:
  1228. imports += "\n"
  1229. return imports + "".join(self._output)
  1230. def is_not_in_all(self, name: str) -> bool:
  1231. if self.is_private_name(name):
  1232. return False
  1233. if self._all_:
  1234. return self.is_top_level() and name not in self._all_
  1235. return False
  1236. def is_private_name(self, name: str, fullname: str | None = None) -> bool:
  1237. if self._include_private:
  1238. return False
  1239. if fullname in EXTRA_EXPORTED:
  1240. return False
  1241. return name.startswith("_") and (not name.endswith("__") or name in IGNORED_DUNDERS)
  1242. def is_private_member(self, fullname: str) -> bool:
  1243. parts = fullname.split(".")
  1244. return any(self.is_private_name(part) for part in parts)
  1245. def get_str_type_of_node(
  1246. self, rvalue: Expression, can_infer_optional: bool = False, can_be_any: bool = True
  1247. ) -> str:
  1248. rvalue = self.maybe_unwrap_unary_expr(rvalue)
  1249. if isinstance(rvalue, IntExpr):
  1250. return "int"
  1251. if isinstance(rvalue, StrExpr):
  1252. return "str"
  1253. if isinstance(rvalue, BytesExpr):
  1254. return "bytes"
  1255. if isinstance(rvalue, FloatExpr):
  1256. return "float"
  1257. if isinstance(rvalue, ComplexExpr): # 1j
  1258. return "complex"
  1259. if isinstance(rvalue, OpExpr) and rvalue.op in ("-", "+"): # -1j + 1
  1260. if isinstance(self.maybe_unwrap_unary_expr(rvalue.left), ComplexExpr) or isinstance(
  1261. self.maybe_unwrap_unary_expr(rvalue.right), ComplexExpr
  1262. ):
  1263. return "complex"
  1264. if isinstance(rvalue, NameExpr) and rvalue.name in ("True", "False"):
  1265. return "bool"
  1266. if can_infer_optional and isinstance(rvalue, NameExpr) and rvalue.name == "None":
  1267. self.add_typing_import("Incomplete")
  1268. return f"{self.typing_name('Incomplete')} | None"
  1269. if can_be_any:
  1270. self.add_typing_import("Incomplete")
  1271. return self.typing_name("Incomplete")
  1272. else:
  1273. return ""
  1274. def maybe_unwrap_unary_expr(self, expr: Expression) -> Expression:
  1275. """Unwrap (possibly nested) unary expressions.
  1276. But, some unary expressions can change the type of expression.
  1277. While we want to preserve it. For example, `~True` is `int`.
  1278. So, we only allow a subset of unary expressions to be unwrapped.
  1279. """
  1280. if not isinstance(expr, UnaryExpr):
  1281. return expr
  1282. # First, try to unwrap `[+-]+ (int|float|complex)` expr:
  1283. math_ops = ("+", "-")
  1284. if expr.op in math_ops:
  1285. while isinstance(expr, UnaryExpr):
  1286. if expr.op not in math_ops or not isinstance(
  1287. expr.expr, (IntExpr, FloatExpr, ComplexExpr, UnaryExpr)
  1288. ):
  1289. break
  1290. expr = expr.expr
  1291. return expr
  1292. # Next, try `not bool` expr:
  1293. if expr.op == "not":
  1294. while isinstance(expr, UnaryExpr):
  1295. if expr.op != "not" or not isinstance(expr.expr, (NameExpr, UnaryExpr)):
  1296. break
  1297. if isinstance(expr.expr, NameExpr) and expr.expr.name not in ("True", "False"):
  1298. break
  1299. expr = expr.expr
  1300. return expr
  1301. # This is some other unary expr, we cannot do anything with it (yet?).
  1302. return expr
  1303. def print_annotation(self, t: Type) -> str:
  1304. printer = AnnotationPrinter(self)
  1305. return t.accept(printer)
  1306. def is_top_level(self) -> bool:
  1307. """Are we processing the top level of a file?"""
  1308. return self._indent == ""
  1309. def record_name(self, name: str) -> None:
  1310. """Mark a name as defined.
  1311. This only does anything if at the top level of a module.
  1312. """
  1313. if self.is_top_level():
  1314. self._toplevel_names.append(name)
  1315. def is_recorded_name(self, name: str) -> bool:
  1316. """Has this name been recorded previously?"""
  1317. return self.is_top_level() and name in self._toplevel_names
  1318. def find_method_names(defs: list[Statement]) -> set[str]:
  1319. # TODO: Traverse into nested definitions
  1320. result = set()
  1321. for defn in defs:
  1322. if isinstance(defn, FuncDef):
  1323. result.add(defn.name)
  1324. elif isinstance(defn, Decorator):
  1325. result.add(defn.func.name)
  1326. elif isinstance(defn, OverloadedFuncDef):
  1327. for item in defn.items:
  1328. result.update(find_method_names([item]))
  1329. return result
  1330. class SelfTraverser(mypy.traverser.TraverserVisitor):
  1331. def __init__(self) -> None:
  1332. self.results: list[tuple[str, Expression]] = []
  1333. def visit_assignment_stmt(self, o: AssignmentStmt) -> None:
  1334. lvalue = o.lvalues[0]
  1335. if (
  1336. isinstance(lvalue, MemberExpr)
  1337. and isinstance(lvalue.expr, NameExpr)
  1338. and lvalue.expr.name == "self"
  1339. ):
  1340. self.results.append((lvalue.name, o.rvalue))
  1341. def find_self_initializers(fdef: FuncBase) -> list[tuple[str, Expression]]:
  1342. """Find attribute initializers in a method.
  1343. Return a list of pairs (attribute name, r.h.s. expression).
  1344. """
  1345. traverser = SelfTraverser()
  1346. fdef.accept(traverser)
  1347. return traverser.results
  1348. def get_qualified_name(o: Expression) -> str:
  1349. if isinstance(o, NameExpr):
  1350. return o.name
  1351. elif isinstance(o, MemberExpr):
  1352. return f"{get_qualified_name(o.expr)}.{o.name}"
  1353. else:
  1354. return ERROR_MARKER
  1355. def remove_blacklisted_modules(modules: list[StubSource]) -> list[StubSource]:
  1356. return [
  1357. module for module in modules if module.path is None or not is_blacklisted_path(module.path)
  1358. ]
  1359. def is_blacklisted_path(path: str) -> bool:
  1360. return any(substr in (normalize_path_separators(path) + "\n") for substr in BLACKLIST)
  1361. def normalize_path_separators(path: str) -> str:
  1362. if sys.platform == "win32":
  1363. return path.replace("\\", "/")
  1364. return path
  1365. def collect_build_targets(
  1366. options: Options, mypy_opts: MypyOptions
  1367. ) -> tuple[list[StubSource], list[StubSource]]:
  1368. """Collect files for which we need to generate stubs.
  1369. Return list of Python modules and C modules.
  1370. """
  1371. if options.packages or options.modules:
  1372. if options.no_import:
  1373. py_modules = find_module_paths_using_search(
  1374. options.modules, options.packages, options.search_path, options.pyversion
  1375. )
  1376. c_modules: list[StubSource] = []
  1377. else:
  1378. # Using imports is the default, since we can also find C modules.
  1379. py_modules, c_modules = find_module_paths_using_imports(
  1380. options.modules, options.packages, options.verbose, options.quiet
  1381. )
  1382. else:
  1383. # Use mypy native source collection for files and directories.
  1384. try:
  1385. source_list = create_source_list(options.files, mypy_opts)
  1386. except InvalidSourceList as e:
  1387. raise SystemExit(str(e)) from e
  1388. py_modules = [StubSource(m.module, m.path) for m in source_list]
  1389. c_modules = []
  1390. py_modules = remove_blacklisted_modules(py_modules)
  1391. return py_modules, c_modules
  1392. def find_module_paths_using_imports(
  1393. modules: list[str], packages: list[str], verbose: bool, quiet: bool
  1394. ) -> tuple[list[StubSource], list[StubSource]]:
  1395. """Find path and runtime value of __all__ (if possible) for modules and packages.
  1396. This function uses runtime Python imports to get the information.
  1397. """
  1398. with ModuleInspect() as inspect:
  1399. py_modules: list[StubSource] = []
  1400. c_modules: list[StubSource] = []
  1401. found = list(walk_packages(inspect, packages, verbose))
  1402. modules = modules + found
  1403. modules = [
  1404. mod for mod in modules if not is_non_library_module(mod)
  1405. ] # We don't want to run any tests or scripts
  1406. for mod in modules:
  1407. try:
  1408. result = find_module_path_and_all_py3(inspect, mod, verbose)
  1409. except CantImport as e:
  1410. tb = traceback.format_exc()
  1411. if verbose:
  1412. sys.stdout.write(tb)
  1413. if not quiet:
  1414. report_missing(mod, e.message, tb)
  1415. continue
  1416. if not result:
  1417. c_modules.append(StubSource(mod))
  1418. else:
  1419. path, runtime_all = result
  1420. py_modules.append(StubSource(mod, path, runtime_all))
  1421. return py_modules, c_modules
  1422. def is_non_library_module(module: str) -> bool:
  1423. """Does module look like a test module or a script?"""
  1424. if module.endswith(
  1425. (
  1426. ".tests",
  1427. ".test",
  1428. ".testing",
  1429. "_tests",
  1430. "_test_suite",
  1431. "test_util",
  1432. "test_utils",
  1433. "test_base",
  1434. ".__main__",
  1435. ".conftest", # Used by pytest
  1436. ".setup", # Typically an install script
  1437. )
  1438. ):
  1439. return True
  1440. if module.split(".")[-1].startswith("test_"):
  1441. return True
  1442. if (
  1443. ".tests." in module
  1444. or ".test." in module
  1445. or ".testing." in module
  1446. or ".SelfTest." in module
  1447. ):
  1448. return True
  1449. return False
  1450. def translate_module_name(module: str, relative: int) -> tuple[str, int]:
  1451. for pkg in VENDOR_PACKAGES:
  1452. for alt in "six.moves", "six":
  1453. substr = f"{pkg}.{alt}"
  1454. if module.endswith("." + substr) or (module == substr and relative):
  1455. return alt, 0
  1456. if "." + substr + "." in module:
  1457. return alt + "." + module.partition("." + substr + ".")[2], 0
  1458. return module, relative
  1459. def find_module_paths_using_search(
  1460. modules: list[str], packages: list[str], search_path: list[str], pyversion: tuple[int, int]
  1461. ) -> list[StubSource]:
  1462. """Find sources for modules and packages requested.
  1463. This function just looks for source files at the file system level.
  1464. This is used if user passes --no-import, and will not find C modules.
  1465. Exit if some of the modules or packages can't be found.
  1466. """
  1467. result: list[StubSource] = []
  1468. typeshed_path = default_lib_path(mypy.build.default_data_dir(), pyversion, None)
  1469. search_paths = SearchPaths((".",) + tuple(search_path), (), (), tuple(typeshed_path))
  1470. cache = FindModuleCache(search_paths, fscache=None, options=None)
  1471. for module in modules:
  1472. m_result = cache.find_module(module)
  1473. if isinstance(m_result, ModuleNotFoundReason):
  1474. fail_missing(module, m_result)
  1475. module_path = None
  1476. else:
  1477. module_path = m_result
  1478. result.append(StubSource(module, module_path))
  1479. for package in packages:
  1480. p_result = cache.find_modules_recursive(package)
  1481. if p_result:
  1482. fail_missing(package, ModuleNotFoundReason.NOT_FOUND)
  1483. sources = [StubSource(m.module, m.path) for m in p_result]
  1484. result.extend(sources)
  1485. result = [m for m in result if not is_non_library_module(m.module)]
  1486. return result
  1487. def mypy_options(stubgen_options: Options) -> MypyOptions:
  1488. """Generate mypy options using the flag passed by user."""
  1489. options = MypyOptions()
  1490. options.follow_imports = "skip"
  1491. options.incremental = False
  1492. options.ignore_errors = True
  1493. options.semantic_analysis_only = True
  1494. options.python_version = stubgen_options.pyversion
  1495. options.show_traceback = True
  1496. options.transform_source = remove_misplaced_type_comments
  1497. options.preserve_asts = True
  1498. # Override cache_dir if provided in the environment
  1499. environ_cache_dir = os.getenv("MYPY_CACHE_DIR", "")
  1500. if environ_cache_dir.strip():
  1501. options.cache_dir = environ_cache_dir
  1502. options.cache_dir = os.path.expanduser(options.cache_dir)
  1503. return options
  1504. def parse_source_file(mod: StubSource, mypy_options: MypyOptions) -> None:
  1505. """Parse a source file.
  1506. On success, store AST in the corresponding attribute of the stub source.
  1507. If there are syntax errors, print them and exit.
  1508. """
  1509. assert mod.path is not None, "Not found module was not skipped"
  1510. with open(mod.path, "rb") as f:
  1511. data = f.read()
  1512. source = mypy.util.decode_python_encoding(data)
  1513. errors = Errors(mypy_options)
  1514. mod.ast = mypy.parse.parse(
  1515. source, fnam=mod.path, module=mod.module, errors=errors, options=mypy_options
  1516. )
  1517. mod.ast._fullname = mod.module
  1518. if errors.is_blockers():
  1519. # Syntax error!
  1520. for m in errors.new_messages():
  1521. sys.stderr.write(f"{m}\n")
  1522. sys.exit(1)
  1523. def generate_asts_for_modules(
  1524. py_modules: list[StubSource], parse_only: bool, mypy_options: MypyOptions, verbose: bool
  1525. ) -> None:
  1526. """Use mypy to parse (and optionally analyze) source files."""
  1527. if not py_modules:
  1528. return # Nothing to do here, but there may be C modules
  1529. if verbose:
  1530. print(f"Processing {len(py_modules)} files...")
  1531. if parse_only:
  1532. for mod in py_modules:
  1533. parse_source_file(mod, mypy_options)
  1534. return
  1535. # Perform full semantic analysis of the source set.
  1536. try:
  1537. res = build([module.source for module in py_modules], mypy_options)
  1538. except CompileError as e:
  1539. raise SystemExit(f"Critical error during semantic analysis: {e}") from e
  1540. for mod in py_modules:
  1541. mod.ast = res.graph[mod.module].tree
  1542. # Use statically inferred __all__ if there is no runtime one.
  1543. if mod.runtime_all is None:
  1544. mod.runtime_all = res.manager.semantic_analyzer.export_map[mod.module]
  1545. def generate_stub_from_ast(
  1546. mod: StubSource,
  1547. target: str,
  1548. parse_only: bool = False,
  1549. include_private: bool = False,
  1550. export_less: bool = False,
  1551. ) -> None:
  1552. """Use analysed (or just parsed) AST to generate type stub for single file.
  1553. If directory for target doesn't exist it will created. Existing stub
  1554. will be overwritten.
  1555. """
  1556. gen = StubGenerator(
  1557. mod.runtime_all,
  1558. include_private=include_private,
  1559. analyzed=not parse_only,
  1560. export_less=export_less,
  1561. )
  1562. assert mod.ast is not None, "This function must be used only with analyzed modules"
  1563. mod.ast.accept(gen)
  1564. # Write output to file.
  1565. subdir = os.path.dirname(target)
  1566. if subdir and not os.path.isdir(subdir):
  1567. os.makedirs(subdir)
  1568. with open(target, "w") as file:
  1569. file.write("".join(gen.output()))
  1570. def get_sig_generators(options: Options) -> list[SignatureGenerator]:
  1571. sig_generators: list[SignatureGenerator] = [
  1572. DocstringSignatureGenerator(),
  1573. FallbackSignatureGenerator(),
  1574. ]
  1575. if options.doc_dir:
  1576. # Collect info from docs (if given). Always check these first.
  1577. sigs, class_sigs = collect_docs_signatures(options.doc_dir)
  1578. sig_generators.insert(0, ExternalSignatureGenerator(sigs, class_sigs))
  1579. return sig_generators
  1580. def collect_docs_signatures(doc_dir: str) -> tuple[dict[str, str], dict[str, str]]:
  1581. """Gather all function and class signatures in the docs.
  1582. Return a tuple (function signatures, class signatures).
  1583. Currently only used for C modules.
  1584. """
  1585. all_sigs: list[Sig] = []
  1586. all_class_sigs: list[Sig] = []
  1587. for path in glob.glob(f"{doc_dir}/*.rst"):
  1588. with open(path) as f:
  1589. loc_sigs, loc_class_sigs = parse_all_signatures(f.readlines())
  1590. all_sigs += loc_sigs
  1591. all_class_sigs += loc_class_sigs
  1592. sigs = dict(find_unique_signatures(all_sigs))
  1593. class_sigs = dict(find_unique_signatures(all_class_sigs))
  1594. return sigs, class_sigs
  1595. def generate_stubs(options: Options) -> None:
  1596. """Main entry point for the program."""
  1597. mypy_opts = mypy_options(options)
  1598. py_modules, c_modules = collect_build_targets(options, mypy_opts)
  1599. sig_generators = get_sig_generators(options)
  1600. # Use parsed sources to generate stubs for Python modules.
  1601. generate_asts_for_modules(py_modules, options.parse_only, mypy_opts, options.verbose)
  1602. files = []
  1603. for mod in py_modules:
  1604. assert mod.path is not None, "Not found module was not skipped"
  1605. target = mod.module.replace(".", "/")
  1606. if os.path.basename(mod.path) == "__init__.py":
  1607. target += "/__init__.pyi"
  1608. else:
  1609. target += ".pyi"
  1610. target = os.path.join(options.output_dir, target)
  1611. files.append(target)
  1612. with generate_guarded(mod.module, target, options.ignore_errors, options.verbose):
  1613. generate_stub_from_ast(
  1614. mod, target, options.parse_only, options.include_private, options.export_less
  1615. )
  1616. # Separately analyse C modules using different logic.
  1617. all_modules = sorted(m.module for m in (py_modules + c_modules))
  1618. for mod in c_modules:
  1619. if any(py_mod.module.startswith(mod.module + ".") for py_mod in py_modules + c_modules):
  1620. target = mod.module.replace(".", "/") + "/__init__.pyi"
  1621. else:
  1622. target = mod.module.replace(".", "/") + ".pyi"
  1623. target = os.path.join(options.output_dir, target)
  1624. files.append(target)
  1625. with generate_guarded(mod.module, target, options.ignore_errors, options.verbose):
  1626. generate_stub_for_c_module(
  1627. mod.module, target, known_modules=all_modules, sig_generators=sig_generators
  1628. )
  1629. num_modules = len(py_modules) + len(c_modules)
  1630. if not options.quiet and num_modules > 0:
  1631. print("Processed %d modules" % num_modules)
  1632. if len(files) == 1:
  1633. print(f"Generated {files[0]}")
  1634. else:
  1635. print(f"Generated files under {common_dir_prefix(files)}" + os.sep)
  1636. HEADER = """%(prog)s [-h] [more options, see -h]
  1637. [-m MODULE] [-p PACKAGE] [files ...]"""
  1638. DESCRIPTION = """
  1639. Generate draft stubs for modules.
  1640. Stubs are generated in directory ./out, to avoid overriding files with
  1641. manual changes. This directory is assumed to exist.
  1642. """
  1643. def parse_options(args: list[str]) -> Options:
  1644. parser = argparse.ArgumentParser(prog="stubgen", usage=HEADER, description=DESCRIPTION)
  1645. parser.add_argument(
  1646. "--ignore-errors",
  1647. action="store_true",
  1648. help="ignore errors when trying to generate stubs for modules",
  1649. )
  1650. parser.add_argument(
  1651. "--no-import",
  1652. action="store_true",
  1653. help="don't import the modules, just parse and analyze them "
  1654. "(doesn't work with C extension modules and might not "
  1655. "respect __all__)",
  1656. )
  1657. parser.add_argument(
  1658. "--parse-only",
  1659. action="store_true",
  1660. help="don't perform semantic analysis of sources, just parse them "
  1661. "(only applies to Python modules, might affect quality of stubs)",
  1662. )
  1663. parser.add_argument(
  1664. "--include-private",
  1665. action="store_true",
  1666. help="generate stubs for objects and members considered private "
  1667. "(single leading underscore and no trailing underscores)",
  1668. )
  1669. parser.add_argument(
  1670. "--export-less",
  1671. action="store_true",
  1672. help="don't implicitly export all names imported from other modules in the same package",
  1673. )
  1674. parser.add_argument("-v", "--verbose", action="store_true", help="show more verbose messages")
  1675. parser.add_argument("-q", "--quiet", action="store_true", help="show fewer messages")
  1676. parser.add_argument(
  1677. "--doc-dir",
  1678. metavar="PATH",
  1679. default="",
  1680. help="use .rst documentation in PATH (this may result in "
  1681. "better stubs in some cases; consider setting this to "
  1682. "DIR/Python-X.Y.Z/Doc/library)",
  1683. )
  1684. parser.add_argument(
  1685. "--search-path",
  1686. metavar="PATH",
  1687. default="",
  1688. help="specify module search directories, separated by ':' "
  1689. "(currently only used if --no-import is given)",
  1690. )
  1691. parser.add_argument(
  1692. "-o",
  1693. "--output",
  1694. metavar="PATH",
  1695. dest="output_dir",
  1696. default="out",
  1697. help="change the output directory [default: %(default)s]",
  1698. )
  1699. parser.add_argument(
  1700. "-m",
  1701. "--module",
  1702. action="append",
  1703. metavar="MODULE",
  1704. dest="modules",
  1705. default=[],
  1706. help="generate stub for module; can repeat for more modules",
  1707. )
  1708. parser.add_argument(
  1709. "-p",
  1710. "--package",
  1711. action="append",
  1712. metavar="PACKAGE",
  1713. dest="packages",
  1714. default=[],
  1715. help="generate stubs for package recursively; can be repeated",
  1716. )
  1717. parser.add_argument(
  1718. metavar="files",
  1719. nargs="*",
  1720. dest="files",
  1721. help="generate stubs for given files or directories",
  1722. )
  1723. ns = parser.parse_args(args)
  1724. pyversion = sys.version_info[:2]
  1725. ns.interpreter = sys.executable
  1726. if ns.modules + ns.packages and ns.files:
  1727. parser.error("May only specify one of: modules/packages or files.")
  1728. if ns.quiet and ns.verbose:
  1729. parser.error("Cannot specify both quiet and verbose messages")
  1730. # Create the output folder if it doesn't already exist.
  1731. if not os.path.exists(ns.output_dir):
  1732. os.makedirs(ns.output_dir)
  1733. return Options(
  1734. pyversion=pyversion,
  1735. no_import=ns.no_import,
  1736. doc_dir=ns.doc_dir,
  1737. search_path=ns.search_path.split(":"),
  1738. interpreter=ns.interpreter,
  1739. ignore_errors=ns.ignore_errors,
  1740. parse_only=ns.parse_only,
  1741. include_private=ns.include_private,
  1742. output_dir=ns.output_dir,
  1743. modules=ns.modules,
  1744. packages=ns.packages,
  1745. files=ns.files,
  1746. verbose=ns.verbose,
  1747. quiet=ns.quiet,
  1748. export_less=ns.export_less,
  1749. )
  1750. def main(args: list[str] | None = None) -> None:
  1751. mypy.util.check_python_version("stubgen")
  1752. # Make sure that the current directory is in sys.path so that
  1753. # stubgen can be run on packages in the current directory.
  1754. if not ("" in sys.path or "." in sys.path):
  1755. sys.path.insert(0, "")
  1756. options = parse_options(sys.argv[1:] if args is None else args)
  1757. generate_stubs(options)
  1758. if __name__ == "__main__":
  1759. main()