modulegraph.py 131 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139
  1. """
  2. Find modules used by a script, using bytecode analysis.
  3. Based on the stdlib modulefinder by Thomas Heller and Just van Rossum,
  4. but uses a graph data structure and 2.3 features
  5. XXX: Verify all calls to _import_hook (and variants) to ensure that
  6. imports are done in the right way.
  7. """
  8. #FIXME: To decrease the likelihood of ModuleGraph exceeding the recursion limit
  9. #and hence unpredictably raising fatal exceptions, increase the recursion
  10. #limit at PyInstaller startup (i.e., in the
  11. #PyInstaller.building.build_main.build() function). For details, see:
  12. # https://github.com/pyinstaller/pyinstaller/issues/1919#issuecomment-216016176
  13. import ast
  14. import os
  15. import pkgutil
  16. import sys
  17. import types
  18. import re
  19. from collections import deque, namedtuple, defaultdict
  20. import urllib.request
  21. import warnings
  22. import importlib.util
  23. import importlib.machinery
  24. # The logic in PyInstaller.compat ensures that these are available and
  25. # of correct version.
  26. if sys.version_info >= (3, 10):
  27. import importlib.metadata as importlib_metadata
  28. else:
  29. import importlib_metadata
  30. # The latest version of altgraph at the time of writing (v0.17.4) still
  31. # uses pkg_resources to query its own version. With setuptools >= 80.9.0,
  32. # this triggers deprecation warnings. In 2025-11-30, pkg_resources will be
  33. # removed altogether. Give altgraph just enough of a mocked pkg_resources that
  34. # it can still be imported.
  35. try:
  36. _pkg_resources_not_imported = object()
  37. _old_pkg_resources = sys.modules.get("pkg_resources", _pkg_resources_not_imported)
  38. sys.modules["pkg_resources"] = fake_pkg_resources = types.SimpleNamespace()
  39. fake_pkg_resources.require = lambda name: [importlib_metadata.distribution(name)]
  40. from altgraph.ObjectGraph import ObjectGraph
  41. from altgraph import GraphError
  42. finally:
  43. if _old_pkg_resources is not _pkg_resources_not_imported:
  44. sys.modules["pkg_resources"] = _old_pkg_resources
  45. else:
  46. del sys.modules["pkg_resources"]
  47. from . import util
  48. class BUILTIN_MODULE:
  49. def is_package(fqname):
  50. return False
  51. class NAMESPACE_PACKAGE:
  52. def __init__(self, namespace_dirs):
  53. self.namespace_dirs = namespace_dirs
  54. def is_package(self, fqname):
  55. return True
  56. #FIXME: Leverage this rather than magic numbers below.
  57. ABSOLUTE_OR_RELATIVE_IMPORT_LEVEL = -1
  58. """
  59. Constant instructing the builtin `__import__()` function to attempt both
  60. absolute and relative imports.
  61. """
  62. #FIXME: Leverage this rather than magic numbers below.
  63. ABSOLUTE_IMPORT_LEVEL = 0
  64. """
  65. Constant instructing the builtin `__import__()` function to attempt only
  66. absolute imports.
  67. """
  68. #FIXME: Leverage this rather than magic numbers below.
  69. DEFAULT_IMPORT_LEVEL = ABSOLUTE_IMPORT_LEVEL
  70. """
  71. Constant instructing the builtin `__import__()` function to attempt the default
  72. import style specific to the active Python interpreter.
  73. Specifically, under:
  74. * Python 2, this defaults to attempting both absolute and relative imports.
  75. * Python 3, this defaults to attempting only absolute imports.
  76. """
  77. class InvalidRelativeImportError (ImportError):
  78. pass
  79. def _path_from_importerror(exc, default):
  80. # This is a hack, but sadly enough the necessary information
  81. # isn't available otherwise.
  82. m = re.match(r'^No module named (\S+)$', str(exc))
  83. if m is not None:
  84. return m.group(1)
  85. return default
  86. #FIXME: What is this? Do we actually need this? This appears to provide
  87. #significantly more fine-grained metadata than PyInstaller will ever require.
  88. #It consumes a great deal of space (slots or no slots), since we store an
  89. #instance of this class for each edge of the graph.
  90. class DependencyInfo (namedtuple("DependencyInfo",
  91. ["conditional", "function", "tryexcept", "fromlist"])):
  92. __slots__ = ()
  93. def _merged(self, other):
  94. if (not self.conditional and not self.function and not self.tryexcept) \
  95. or (not other.conditional and not other.function and not other.tryexcept):
  96. return DependencyInfo(
  97. conditional=False,
  98. function=False,
  99. tryexcept=False,
  100. fromlist=self.fromlist and other.fromlist)
  101. else:
  102. return DependencyInfo(
  103. conditional=self.conditional or other.conditional,
  104. function=self.function or other.function,
  105. tryexcept=self.tryexcept or other.tryexcept,
  106. fromlist=self.fromlist and other.fromlist)
  107. #FIXME: Shift the following Node class hierarchy into a new
  108. #"PyInstaller.lib.modulegraph.node" module. This module is much too long.
  109. #FIXME: Refactor "_deferred_imports" from a tuple into a proper lightweight
  110. #class leveraging "__slots__". If not for backward compatibility, we'd just
  111. #leverage a named tuple -- but this should do just as well.
  112. #FIXME: Move the "packagepath" attribute into the "Package" class. Only
  113. #packages define the "__path__" special attribute. The codebase currently
  114. #erroneously tests whether "module.packagepath is not None" to determine
  115. #whether a node is a package or not. However, "isinstance(module, Package)" is
  116. #a significantly more reliable test. Refactor the former into the latter.
  117. class Node:
  118. """
  119. Abstract base class (ABC) of all objects added to a `ModuleGraph`.
  120. Attributes
  121. ----------
  122. code : codeobject
  123. Code object of the pure-Python module corresponding to this graph node
  124. if any _or_ `None` otherwise.
  125. graphident : str
  126. Synonym of `identifier` required by the `ObjectGraph` superclass of the
  127. `ModuleGraph` class. For readability, the `identifier` attribute should
  128. typically be used instead.
  129. filename : str
  130. Absolute path of this graph node's corresponding module, package, or C
  131. extension if any _or_ `None` otherwise.
  132. identifier : str
  133. Fully-qualified name of this graph node's corresponding module,
  134. package, or C extension.
  135. packagepath : str
  136. List of the absolute paths of all directories comprising this graph
  137. node's corresponding package. If this is a:
  138. * Non-namespace package, this list contains exactly one path.
  139. * Namespace package, this list contains one or more paths.
  140. _deferred_imports : list
  141. List of all target modules imported by the source module corresponding
  142. to this graph node whole importations have been deferred for subsequent
  143. processing in between calls to the `_ModuleGraph._scan_code()` and
  144. `_ModuleGraph._process_imports()` methods for this source module _or_
  145. `None` otherwise. Each element of this list is a 3-tuple
  146. `(have_star, _safe_import_hook_args, _safe_import_hook_kwargs)`
  147. collecting the importation of a target module from this source module
  148. for subsequent processing, where:
  149. * `have_star` is a boolean `True` only if this is a `from`-style star
  150. import (e.g., resembling `from {target_module_name} import *`).
  151. * `_safe_import_hook_args` is a (typically non-empty) sequence of all
  152. positional arguments to be passed to the `_safe_import_hook()` method
  153. to add this importation to the graph.
  154. * `_safe_import_hook_kwargs` is a (typically empty) dictionary of all
  155. keyword arguments to be passed to the `_safe_import_hook()` method
  156. to add this importation to the graph.
  157. Unlike functional languages, Python imposes a maximum depth on the
  158. interpreter stack (and hence recursion). On breaching this depth,
  159. Python raises a fatal `RuntimeError` exception. Since `ModuleGraph`
  160. parses imports recursively rather than iteratively, this depth _was_
  161. commonly breached before the introduction of this list. Python
  162. environments installing a large number of modules (e.g., Anaconda) were
  163. particularly susceptible. Why? Because `ModuleGraph` concurrently
  164. descended through both the abstract syntax trees (ASTs) of all source
  165. modules being parsed _and_ the graph of all target modules imported by
  166. these source modules being built. The stack thus consisted of
  167. alternating layers of AST and graph traversal. To unwind such
  168. alternation and effectively halve the stack depth, `ModuleGraph` now
  169. descends through the abstract syntax tree (AST) of each source module
  170. being parsed and adds all importations originating within this module
  171. to this list _before_ descending into the graph of these importations.
  172. See pyinstaller/pyinstaller/#1289 for further details.
  173. _global_attr_names : set
  174. Set of the unqualified names of all global attributes (e.g., classes,
  175. variables) defined in the pure-Python module corresponding to this
  176. graph node if any _or_ the empty set otherwise. This includes the names
  177. of all attributes imported via `from`-style star imports from other
  178. existing modules (e.g., `from {target_module_name} import *`). This
  179. set is principally used to differentiate the non-ignorable importation
  180. of non-existent submodules in a package from the ignorable importation
  181. of existing global attributes defined in that package's pure-Python
  182. `__init__` submodule in `from`-style imports (e.g., `bar` in
  183. `from foo import bar`, which may be either a submodule or attribute of
  184. `foo`), as such imports ambiguously allow both. This set is _not_ used
  185. to differentiate submodules from attributes in `import`-style imports
  186. (e.g., `bar` in `import foo.bar`, which _must_ be a submodule of
  187. `foo`), as such imports unambiguously allow only submodules.
  188. _starimported_ignored_module_names : set
  189. Set of the fully-qualified names of all existing unparsable modules
  190. that the existing parsable module corresponding to this graph node
  191. attempted to perform one or more "star imports" from. If this module
  192. either does _not_ exist or does but is unparsable, this is the empty
  193. set. Equivalently, this set contains each fully-qualified name
  194. `{trg_module_name}` for which:
  195. * This module contains an import statement of the form
  196. `from {trg_module_name} import *`.
  197. * The module whose name is `{trg_module_name}` exists but is _not_
  198. parsable by `ModuleGraph` (e.g., due to _not_ being pure-Python).
  199. **This set is currently defined but otherwise ignored.**
  200. _submodule_basename_to_node : dict
  201. Dictionary mapping from the unqualified name of each submodule
  202. contained by the parent module corresponding to this graph node to that
  203. submodule's graph node. If this dictionary is non-empty, this parent
  204. module is typically but _not_ always a package (e.g., the non-package
  205. `os` module containing the `os.path` submodule).
  206. """
  207. __slots__ = [
  208. 'code',
  209. 'filename',
  210. 'graphident',
  211. 'identifier',
  212. 'packagepath',
  213. '_deferred_imports',
  214. '_global_attr_names',
  215. '_starimported_ignored_module_names',
  216. '_submodule_basename_to_node',
  217. ]
  218. def __init__(self, identifier):
  219. """
  220. Initialize this graph node.
  221. Parameters
  222. ----------
  223. identifier : str
  224. Fully-qualified name of this graph node's corresponding module,
  225. package, or C extension.
  226. """
  227. self.code = None
  228. self.filename = None
  229. self.graphident = identifier
  230. self.identifier = identifier
  231. self.packagepath = None
  232. self._deferred_imports = None
  233. self._global_attr_names = set()
  234. self._starimported_ignored_module_names = set()
  235. self._submodule_basename_to_node = dict()
  236. def is_global_attr(self, attr_name):
  237. """
  238. `True` only if the pure-Python module corresponding to this graph node
  239. defines a global attribute (e.g., class, variable) with the passed
  240. name.
  241. If this module is actually a package, this method instead returns
  242. `True` only if this package's pure-Python `__init__` submodule defines
  243. such a global attribute. In this case, note that this package may still
  244. contain an importable submodule of the same name. Callers should
  245. attempt to import this attribute as a submodule of this package
  246. _before_ assuming this attribute to be an ignorable global. See
  247. "Examples" below for further details.
  248. Parameters
  249. ----------
  250. attr_name : str
  251. Unqualified name of the attribute to be tested.
  252. Returns
  253. ----------
  254. bool
  255. `True` only if this module defines this global attribute.
  256. Examples
  257. ----------
  258. Consider a hypothetical module `foo` containing submodules `bar` and
  259. `__init__` where the latter assigns `bar` to be a global variable
  260. (possibly star-exported via the special `__all__` global variable):
  261. >>> # In "foo.__init__":
  262. >>> bar = 3.1415
  263. Python 2 and 3 both permissively permit this. This method returns
  264. `True` in this case (i.e., when called on the `foo` package's graph
  265. node, passed the attribute name `bar`) despite the importability of the
  266. `foo.bar` submodule.
  267. """
  268. return attr_name in self._global_attr_names
  269. def is_submodule(self, submodule_basename):
  270. """
  271. `True` only if the parent module corresponding to this graph node
  272. contains the submodule with the passed name.
  273. If `True`, this parent module is typically but _not_ always a package
  274. (e.g., the non-package `os` module containing the `os.path` submodule).
  275. Parameters
  276. ----------
  277. submodule_basename : str
  278. Unqualified name of the submodule to be tested.
  279. Returns
  280. ----------
  281. bool
  282. `True` only if this parent module contains this submodule.
  283. """
  284. return submodule_basename in self._submodule_basename_to_node
  285. def add_global_attr(self, attr_name):
  286. """
  287. Record the global attribute (e.g., class, variable) with the passed
  288. name to be defined by the pure-Python module corresponding to this
  289. graph node.
  290. If this module is actually a package, this method instead records this
  291. attribute to be defined by this package's pure-Python `__init__`
  292. submodule.
  293. Parameters
  294. ----------
  295. attr_name : str
  296. Unqualified name of the attribute to be added.
  297. """
  298. self._global_attr_names.add(attr_name)
  299. def add_global_attrs_from_module(self, target_module):
  300. """
  301. Record all global attributes (e.g., classes, variables) defined by the
  302. target module corresponding to the passed graph node to also be defined
  303. by the source module corresponding to this graph node.
  304. If the source module is actually a package, this method instead records
  305. these attributes to be defined by this package's pure-Python `__init__`
  306. submodule.
  307. Parameters
  308. ----------
  309. target_module : Node
  310. Graph node of the target module to import attributes from.
  311. """
  312. self._global_attr_names.update(target_module._global_attr_names)
  313. def add_submodule(self, submodule_basename, submodule_node):
  314. """
  315. Add the submodule with the passed name and previously imported graph
  316. node to the parent module corresponding to this graph node.
  317. This parent module is typically but _not_ always a package (e.g., the
  318. non-package `os` module containing the `os.path` submodule).
  319. Parameters
  320. ----------
  321. submodule_basename : str
  322. Unqualified name of the submodule to add to this parent module.
  323. submodule_node : Node
  324. Graph node of this submodule.
  325. """
  326. self._submodule_basename_to_node[submodule_basename] = submodule_node
  327. def get_submodule(self, submodule_basename):
  328. """
  329. Graph node of the submodule with the passed name in the parent module
  330. corresponding to this graph node.
  331. If this parent module does _not_ contain this submodule, an exception
  332. is raised. Else, this parent module is typically but _not_ always a
  333. package (e.g., the non-package `os` module containing the `os.path`
  334. submodule).
  335. Parameters
  336. ----------
  337. module_basename : str
  338. Unqualified name of the submodule to retrieve.
  339. Returns
  340. ----------
  341. Node
  342. Graph node of this submodule.
  343. """
  344. return self._submodule_basename_to_node[submodule_basename]
  345. def get_submodule_or_none(self, submodule_basename):
  346. """
  347. Graph node of the submodule with the passed unqualified name in the
  348. parent module corresponding to this graph node if this module contains
  349. this submodule _or_ `None`.
  350. This parent module is typically but _not_ always a package (e.g., the
  351. non-package `os` module containing the `os.path` submodule).
  352. Parameters
  353. ----------
  354. submodule_basename : str
  355. Unqualified name of the submodule to retrieve.
  356. Returns
  357. ----------
  358. Node
  359. Graph node of this submodule if this parent module contains this
  360. submodule _or_ `None`.
  361. """
  362. return self._submodule_basename_to_node.get(submodule_basename)
  363. def remove_global_attr_if_found(self, attr_name):
  364. """
  365. Record the global attribute (e.g., class, variable) with the passed
  366. name if previously recorded as defined by the pure-Python module
  367. corresponding to this graph node to be subsequently undefined by the
  368. same module.
  369. If this module is actually a package, this method instead records this
  370. attribute to be undefined by this package's pure-Python `__init__`
  371. submodule.
  372. This method is intended to be called on globals previously defined by
  373. this module that are subsequently undefined via the `del` built-in by
  374. this module, thus "forgetting" or "undoing" these globals.
  375. For safety, there exists no corresponding `remove_global_attr()`
  376. method. While defining this method is trivial, doing so would invite
  377. `KeyError` exceptions on scanning valid Python that lexically deletes a
  378. global in a scope under this module's top level (e.g., in a function)
  379. _before_ defining this global at this top level. Since `ModuleGraph`
  380. cannot and should not (re)implement a full-blown Python interpreter,
  381. ignoring out-of-order deletions is the only sane policy.
  382. Parameters
  383. ----------
  384. attr_name : str
  385. Unqualified name of the attribute to be removed.
  386. """
  387. if self.is_global_attr(attr_name):
  388. self._global_attr_names.remove(attr_name)
  389. def __eq__(self, other):
  390. try:
  391. otherIdent = getattr(other, 'graphident')
  392. except AttributeError:
  393. return False
  394. return self.graphident == otherIdent
  395. def __ne__(self, other):
  396. try:
  397. otherIdent = getattr(other, 'graphident')
  398. except AttributeError:
  399. return True
  400. return self.graphident != otherIdent
  401. def __lt__(self, other):
  402. try:
  403. otherIdent = getattr(other, 'graphident')
  404. except AttributeError:
  405. return NotImplemented
  406. return self.graphident < otherIdent
  407. def __le__(self, other):
  408. try:
  409. otherIdent = getattr(other, 'graphident')
  410. except AttributeError:
  411. return NotImplemented
  412. return self.graphident <= otherIdent
  413. def __gt__(self, other):
  414. try:
  415. otherIdent = getattr(other, 'graphident')
  416. except AttributeError:
  417. return NotImplemented
  418. return self.graphident > otherIdent
  419. def __ge__(self, other):
  420. try:
  421. otherIdent = getattr(other, 'graphident')
  422. except AttributeError:
  423. return NotImplemented
  424. return self.graphident >= otherIdent
  425. def __hash__(self):
  426. return hash(self.graphident)
  427. def infoTuple(self):
  428. return (self.identifier,)
  429. def __repr__(self):
  430. return '%s%r' % (type(self).__name__, self.infoTuple())
  431. class Alias(str):
  432. """
  433. Placeholder aliasing an existing source module to a non-existent target
  434. module (i.e., the desired alias).
  435. For obscure reasons, this class subclasses `str`. Each instance of this
  436. class is the fully-qualified name of the existing source module being
  437. aliased. Unlike the related `AliasNode` class, instances of this class are
  438. _not_ actual nodes and hence _not_ added to the graph; they only facilitate
  439. communication between the `ModuleGraph.alias_module()` and
  440. `ModuleGraph.find_node()` methods.
  441. """
  442. class AliasNode(Node):
  443. """
  444. Graph node representing the aliasing of an existing source module under a
  445. non-existent target module name (i.e., the desired alias).
  446. """
  447. def __init__(self, name, node=None):
  448. """
  449. Initialize this alias.
  450. Parameters
  451. ----------
  452. name : str
  453. Fully-qualified name of the non-existent target module to be
  454. created (as an alias of the existing source module).
  455. node : Node
  456. Graph node of the existing source module being aliased. Optional;
  457. if not provided here, the attributes from referred node should
  458. be copied later using `copyAttributesFromReferredNode` method.
  459. """
  460. super(AliasNode, self).__init__(name)
  461. # Copy attributes from referred node, if provided
  462. self.copyAttributesFromReferredNode(node)
  463. def copyAttributesFromReferredNode(self, node):
  464. """
  465. Copy a subset of attributes from referred node (source module) into this target alias.
  466. """
  467. # FIXME: Why only some? Why not *EVERYTHING* except "graphident", which
  468. # must remain equal to "name" for lookup purposes? This is, after all,
  469. # an alias. The idea is for the two nodes to effectively be the same.
  470. for attr_name in (
  471. 'identifier', 'packagepath',
  472. '_global_attr_names', '_starimported_ignored_module_names',
  473. '_submodule_basename_to_node'):
  474. if hasattr(node, attr_name):
  475. setattr(self, attr_name, getattr(node, attr_name))
  476. def infoTuple(self):
  477. return (self.graphident, self.identifier)
  478. class BadModule(Node):
  479. pass
  480. class ExcludedModule(BadModule):
  481. pass
  482. class MissingModule(BadModule):
  483. pass
  484. class InvalidRelativeImport (BadModule):
  485. def __init__(self, relative_path, from_name):
  486. identifier = relative_path
  487. if relative_path.endswith('.'):
  488. identifier += from_name
  489. else:
  490. identifier += '.' + from_name
  491. super(InvalidRelativeImport, self).__init__(identifier)
  492. self.relative_path = relative_path
  493. self.from_name = from_name
  494. def infoTuple(self):
  495. return (self.relative_path, self.from_name)
  496. class Script(Node):
  497. def __init__(self, filename):
  498. super(Script, self).__init__(filename)
  499. self.filename = filename
  500. def infoTuple(self):
  501. return (self.filename,)
  502. class BaseModule(Node):
  503. def __init__(self, name, filename=None, path=None):
  504. super(BaseModule, self).__init__(name)
  505. self.filename = filename
  506. self.packagepath = path
  507. def infoTuple(self):
  508. return tuple(filter(None, (self.identifier, self.filename, self.packagepath)))
  509. class BuiltinModule(BaseModule):
  510. pass
  511. class SourceModule(BaseModule):
  512. pass
  513. class InvalidSourceModule(SourceModule):
  514. pass
  515. class CompiledModule(BaseModule):
  516. pass
  517. class InvalidCompiledModule(BaseModule):
  518. pass
  519. class Extension(BaseModule):
  520. pass
  521. class Package(BaseModule):
  522. """
  523. Graph node representing a non-namespace package.
  524. """
  525. pass
  526. class ExtensionPackage(Extension, Package):
  527. """
  528. Graph node representing a package where the __init__ module is an extension
  529. module.
  530. """
  531. pass
  532. class NamespacePackage(Package):
  533. """
  534. Graph node representing a namespace package.
  535. """
  536. pass
  537. class RuntimeModule(BaseModule):
  538. """
  539. Graph node representing a non-package Python module dynamically defined at
  540. runtime.
  541. Most modules are statically defined on-disk as standard Python files.
  542. Some modules, however, are dynamically defined in-memory at runtime
  543. (e.g., `gi.repository.Gst`, dynamically defined by the statically
  544. defined `gi.repository.__init__` module).
  545. This node represents such a runtime module. Since this is _not_ a package,
  546. all attempts to import submodules from this module in `from`-style import
  547. statements (e.g., the `queue` submodule in `from six.moves import queue`)
  548. will be silently ignored.
  549. To ensure that the parent package of this module if any is also imported
  550. and added to the graph, this node is typically added to the graph by
  551. calling the `ModuleGraph.add_module()` method.
  552. """
  553. pass
  554. class RuntimePackage(Package):
  555. """
  556. Graph node representing a non-namespace Python package dynamically defined
  557. at runtime.
  558. Most packages are statically defined on-disk as standard subdirectories
  559. containing `__init__.py` files. Some packages, however, are dynamically
  560. defined in-memory at runtime (e.g., `six.moves`, dynamically defined by
  561. the statically defined `six` module).
  562. This node represents such a runtime package. All attributes imported from
  563. this package in `from`-style import statements that are submodules of this
  564. package (e.g., the `queue` submodule in `from six.moves import queue`) will
  565. be imported rather than ignored.
  566. To ensure that the parent package of this package if any is also imported
  567. and added to the graph, this node is typically added to the graph by
  568. calling the `ModuleGraph.add_module()` method.
  569. """
  570. pass
  571. #FIXME: Safely removable. We don't actually use this anywhere. After removing
  572. #this class, remove the corresponding entry from "compat".
  573. class FlatPackage(BaseModule):
  574. def __init__(self, *args, **kwds):
  575. warnings.warn(
  576. "This class will be removed in a future version of modulegraph",
  577. DeprecationWarning)
  578. super(FlatPackage, *args, **kwds)
  579. #FIXME: Safely removable. We don't actually use this anywhere. After removing
  580. #this class, remove the corresponding entry from "compat".
  581. class ArchiveModule(BaseModule):
  582. def __init__(self, *args, **kwds):
  583. warnings.warn(
  584. "This class will be removed in a future version of modulegraph",
  585. DeprecationWarning)
  586. super(FlatPackage, *args, **kwds)
  587. # HTML templates for ModuleGraph generator
  588. header = """\
  589. <!DOCTYPE html>
  590. <html>
  591. <head>
  592. <meta charset="UTF-8">
  593. <title>%(TITLE)s</title>
  594. <style>
  595. .node { padding: 0.5em 0 0.5em; border-top: thin grey dotted; }
  596. .moduletype { font: smaller italic }
  597. .node a { text-decoration: none; color: #006699; }
  598. .node a:visited { text-decoration: none; color: #2f0099; }
  599. </style>
  600. </head>
  601. <body>
  602. <h1>%(TITLE)s</h1>"""
  603. entry = """
  604. <div class="node">
  605. <a name="%(NAME)s"></a>
  606. %(CONTENT)s
  607. </div>"""
  608. contpl = """<tt>%(NAME)s</tt> <span class="moduletype">%(TYPE)s</span>"""
  609. contpl_linked = """\
  610. <a target="code" href="%(URL)s" type="text/plain"><tt>%(NAME)s</tt></a>
  611. <span class="moduletype">%(TYPE)s</span>"""
  612. imports = """\
  613. <div class="import">
  614. %(HEAD)s:
  615. %(LINKS)s
  616. </div>
  617. """
  618. footer = """
  619. </body>
  620. </html>"""
  621. def _ast_names(names):
  622. result = []
  623. for nm in names:
  624. if isinstance(nm, ast.alias):
  625. result.append(nm.name)
  626. else:
  627. result.append(nm)
  628. result = [r for r in result if r != '__main__']
  629. return result
  630. def uniq(seq):
  631. """Remove duplicates from a list, preserving order"""
  632. # Taken from https://stackoverflow.com/questions/480214
  633. seen = set()
  634. seen_add = seen.add
  635. return [x for x in seq if not (x in seen or seen_add(x))]
  636. DEFAULT_IMPORT_LEVEL = 0
  637. class _Visitor(ast.NodeVisitor):
  638. def __init__(self, graph, module):
  639. self._graph = graph
  640. self._module = module
  641. self._level = DEFAULT_IMPORT_LEVEL
  642. self._in_if = [False]
  643. self._in_def = [False]
  644. self._in_tryexcept = [False]
  645. @property
  646. def in_if(self):
  647. return self._in_if[-1]
  648. @property
  649. def in_def(self):
  650. return self._in_def[-1]
  651. @property
  652. def in_tryexcept(self):
  653. return self._in_tryexcept[-1]
  654. def _collect_import(self, name, fromlist, level):
  655. have_star = False
  656. if fromlist is not None:
  657. fromlist = uniq(fromlist)
  658. if '*' in fromlist:
  659. fromlist.remove('*')
  660. have_star = True
  661. # Record this import as originating from this module for subsequent
  662. # handling by the _process_imports() method.
  663. self._module._deferred_imports.append(
  664. (have_star,
  665. (name, self._module, fromlist, level),
  666. {'edge_attr': DependencyInfo(
  667. conditional=self.in_if,
  668. tryexcept=self.in_tryexcept,
  669. function=self.in_def,
  670. fromlist=False)}))
  671. def visit_Import(self, node):
  672. for nm in _ast_names(node.names):
  673. self._collect_import(nm, None, self._level)
  674. def visit_ImportFrom(self, node):
  675. level = node.level if node.level != 0 else self._level
  676. self._collect_import(node.module or '', _ast_names(node.names), level)
  677. def visit_If(self, node):
  678. self._in_if.append(True)
  679. self.generic_visit(node)
  680. self._in_if.pop()
  681. def visit_FunctionDef(self, node):
  682. self._in_def.append(True)
  683. self.generic_visit(node)
  684. self._in_def.pop()
  685. visit_AsyncFunctionDef = visit_FunctionDef
  686. def visit_Try(self, node):
  687. self._in_tryexcept.append(True)
  688. self.generic_visit(node)
  689. self._in_tryexcept.pop()
  690. def visit_TryExcept(self, node):
  691. self._in_tryexcept.append(True)
  692. self.generic_visit(node)
  693. self._in_tryexcept.pop()
  694. def visit_Expression(self, node):
  695. # Expression node's cannot contain import statements or
  696. # other nodes that are relevant for us.
  697. pass
  698. # Expression isn't actually used as such in AST trees,
  699. # therefore define visitors for all kinds of expression nodes.
  700. visit_BoolOp = visit_Expression
  701. visit_BinOp = visit_Expression
  702. visit_UnaryOp = visit_Expression
  703. visit_Lambda = visit_Expression
  704. visit_IfExp = visit_Expression
  705. visit_Dict = visit_Expression
  706. visit_Set = visit_Expression
  707. visit_ListComp = visit_Expression
  708. visit_SetComp = visit_Expression
  709. visit_ListComp = visit_Expression
  710. visit_GeneratorExp = visit_Expression
  711. visit_Compare = visit_Expression
  712. visit_Yield = visit_Expression
  713. visit_YieldFrom = visit_Expression
  714. visit_Await = visit_Expression
  715. visit_Call = visit_Expression
  716. visit_Await = visit_Expression
  717. class ModuleGraph(ObjectGraph):
  718. """
  719. Directed graph whose nodes represent modules and edges represent
  720. dependencies between these modules.
  721. """
  722. def createNode(self, cls, name, *args, **kw):
  723. m = self.find_node(name)
  724. if m is None:
  725. #assert m is None, m
  726. m = super(ModuleGraph, self).createNode(cls, name, *args, **kw)
  727. return m
  728. def __init__(self, path=None, excludes=(), replace_paths=(), implies=(), graph=None, debug=0):
  729. super(ModuleGraph, self).__init__(graph=graph, debug=debug)
  730. if path is None:
  731. path = sys.path
  732. self.path = path
  733. self.lazynodes = {}
  734. # excludes is stronger than implies
  735. self.lazynodes.update(dict(implies))
  736. for m in excludes:
  737. self.lazynodes[m] = None
  738. self.replace_paths = replace_paths
  739. # Maintain own list of package path mappings in the scope of Modulegraph
  740. # object.
  741. self._package_path_map = {}
  742. # Legacy namespace-package paths. Initialized by scan_legacy_namespace_packages.
  743. self._legacy_ns_packages = {}
  744. def scan_legacy_namespace_packages(self):
  745. """
  746. Resolve extra package `__path__` entries for legacy setuptools-based
  747. namespace packages, by reading `namespace_packages.txt` from dist
  748. metadata.
  749. """
  750. legacy_ns_packages = defaultdict(lambda: set())
  751. for dist in importlib_metadata.distributions():
  752. ns_packages = dist.read_text("namespace_packages.txt")
  753. if ns_packages is None:
  754. continue
  755. ns_packages = ns_packages.splitlines()
  756. # Obtain path to dist metadata directory
  757. dist_path = getattr(dist, '_path')
  758. if dist_path is None:
  759. continue
  760. for package_name in ns_packages:
  761. path = os.path.join(
  762. str(dist_path.parent), # might be zipfile.Path if in zipped .egg
  763. *package_name.split('.'),
  764. )
  765. legacy_ns_packages[package_name].add(path)
  766. # Convert into dictionary of lists
  767. self._legacy_ns_packages = {
  768. package_name: list(paths)
  769. for package_name, paths in legacy_ns_packages.items()
  770. }
  771. def implyNodeReference(self, node, other, edge_data=None):
  772. """
  773. Create a reference from the passed source node to the passed other node,
  774. implying the former to depend upon the latter.
  775. While the source node _must_ be an existing graph node, the target node
  776. may be either an existing graph node _or_ a fully-qualified module name.
  777. In the latter case, the module with that name and all parent packages of
  778. that module will be imported _without_ raising exceptions and for each
  779. newly imported module or package:
  780. * A new graph node will be created for that module or package.
  781. * A reference from the passed source node to that module or package will
  782. be created.
  783. This method allows dependencies between Python objects _not_ importable
  784. with standard techniques (e.g., module aliases, C extensions).
  785. Parameters
  786. ----------
  787. node : str
  788. Graph node for this reference's source module or package.
  789. other : {Node, str}
  790. Either a graph node _or_ fully-qualified name for this reference's
  791. target module or package.
  792. """
  793. if isinstance(other, Node):
  794. self._updateReference(node, other, edge_data)
  795. else:
  796. if isinstance(other, tuple):
  797. raise ValueError(other)
  798. others = self._safe_import_hook(other, node, None)
  799. for other in others:
  800. self._updateReference(node, other, edge_data)
  801. def outgoing(self, fromnode):
  802. """
  803. Yield all nodes that `fromnode` dependes on (that is,
  804. all modules that `fromnode` imports.
  805. """
  806. node = self.find_node(fromnode)
  807. out_edges, _ = self.get_edges(node)
  808. return out_edges
  809. getReferences = outgoing
  810. def incoming(self, tonode, collapse_missing_modules=True):
  811. node = self.find_node(tonode)
  812. _, in_edges = self.get_edges(node)
  813. if collapse_missing_modules:
  814. for n in in_edges:
  815. if isinstance(n, MissingModule):
  816. for n in self.incoming(n, False):
  817. yield n
  818. else:
  819. yield n
  820. else:
  821. for n in in_edges:
  822. yield n
  823. getReferers = incoming
  824. def hasEdge(self, fromnode, tonode):
  825. """ Return True iff there is an edge from 'fromnode' to 'tonode' """
  826. fromnode = self.find_node(fromnode)
  827. tonode = self.find_node(tonode)
  828. return self.graph.edge_by_node(fromnode, tonode) is not None
  829. def foldReferences(self, packagenode):
  830. """
  831. Create edges to/from `packagenode` based on the edges to/from all
  832. submodules of that package _and_ then hide the graph nodes
  833. corresponding to those submodules.
  834. """
  835. pkg = self.find_node(packagenode)
  836. for n in self.nodes():
  837. if not n.identifier.startswith(pkg.identifier + '.'):
  838. continue
  839. iter_out, iter_inc = self.get_edges(n)
  840. for other in iter_out:
  841. if other.identifier.startswith(pkg.identifier + '.'):
  842. continue
  843. if not self.hasEdge(pkg, other):
  844. # Ignore circular dependencies
  845. self._updateReference(pkg, other, 'pkg-internal-import')
  846. for other in iter_inc:
  847. if other.identifier.startswith(pkg.identifier + '.'):
  848. # Ignore circular dependencies
  849. continue
  850. if not self.hasEdge(other, pkg):
  851. self._updateReference(other, pkg, 'pkg-import')
  852. self.graph.hide_node(n)
  853. # TODO: unfoldReferences(pkg) that restore the submodule nodes and
  854. # removes 'pkg-import' and 'pkg-internal-import' edges. Care should
  855. # be taken to ensure that references are correct if multiple packages
  856. # are folded and then one of them in unfolded
  857. def _updateReference(self, fromnode, tonode, edge_data):
  858. try:
  859. ed = self.edgeData(fromnode, tonode)
  860. except (KeyError, GraphError): # XXX: Why 'GraphError'
  861. return self.add_edge(fromnode, tonode, edge_data)
  862. if not (isinstance(ed, DependencyInfo) and isinstance(edge_data, DependencyInfo)):
  863. self.updateEdgeData(fromnode, tonode, edge_data)
  864. else:
  865. self.updateEdgeData(fromnode, tonode, ed._merged(edge_data))
  866. def add_edge(self, fromnode, tonode, edge_data='direct'):
  867. """
  868. Create a reference from fromnode to tonode
  869. """
  870. return super(ModuleGraph, self).createReference(fromnode, tonode, edge_data=edge_data)
  871. createReference = add_edge
  872. def find_node(self, name, create_nspkg=True):
  873. """
  874. Graph node uniquely identified by the passed fully-qualified module
  875. name if this module has been added to the graph _or_ `None` otherwise.
  876. If (in order):
  877. . A namespace package with this identifier exists _and_ the passed
  878. `create_nspkg` parameter is `True`, this package will be
  879. instantiated and returned.
  880. . A lazy node with this identifier and:
  881. * No dependencies exists, this node will be instantiated and
  882. returned.
  883. * Dependencies exists, this node and all transitive dependencies of
  884. this node be instantiated and this node returned.
  885. . A non-lazy node with this identifier exists, this node will be
  886. returned as is.
  887. Parameters
  888. ----------
  889. name : str
  890. Fully-qualified name of the module whose graph node is to be found.
  891. create_nspkg : bool
  892. Ignored.
  893. Returns
  894. ----------
  895. Node
  896. Graph node of this module if added to the graph _or_ `None`
  897. otherwise.
  898. """
  899. data = super(ModuleGraph, self).findNode(name)
  900. if data is not None:
  901. return data
  902. if name in self.lazynodes:
  903. deps = self.lazynodes.pop(name)
  904. if deps is None:
  905. # excluded module
  906. m = self.createNode(ExcludedModule, name)
  907. elif isinstance(deps, Alias):
  908. # NOTE: the AliasNode must be created and added to graph
  909. # before trying to create the referred node; that might
  910. # (due to recursive import analysis) lead to another
  911. # attempt to resolve the aliased node (and if there is
  912. # a real node that we are trying to shadow with the alias,
  913. # that will end up added to the graph and prevent the
  914. # alias node from being added).
  915. m = self.createNode(AliasNode, name)
  916. # Create the referred node.
  917. other = self._safe_import_hook(deps, None, None).pop()
  918. # Copy attributes; this used to be done by AliasNode
  919. # constructor, back when referred node was created before
  920. # the AliasNode (and could thus be passed to its constructor).
  921. m.copyAttributesFromReferredNode(other)
  922. self.implyNodeReference(m, other)
  923. else:
  924. m = self._safe_import_hook(name, None, None).pop()
  925. for dep in deps:
  926. self.implyNodeReference(m, dep)
  927. return m
  928. return None
  929. findNode = find_node
  930. iter_graph = ObjectGraph.flatten
  931. def add_script(self, pathname, caller=None):
  932. """
  933. Create a node by path (not module name). It is expected to be a Python
  934. source file, and will be scanned for dependencies.
  935. """
  936. self.msg(2, "run_script", pathname)
  937. pathname = os.path.realpath(pathname)
  938. m = self.find_node(pathname)
  939. if m is not None:
  940. return m
  941. with open(pathname, 'rb') as fp:
  942. contents = fp.read()
  943. contents = importlib.util.decode_source(contents)
  944. co_ast = compile(contents, pathname, 'exec', ast.PyCF_ONLY_AST, True)
  945. co = compile(co_ast, pathname, 'exec', 0, True)
  946. m = self.createNode(Script, pathname)
  947. self._updateReference(caller, m, None)
  948. n = self._scan_code(m, co, co_ast)
  949. self._process_imports(n)
  950. m.code = co
  951. if self.replace_paths:
  952. m.code = self._replace_paths_in_code(m.code)
  953. return m
  954. #FIXME: For safety, the "source_module" parameter should default to the
  955. #root node of the current graph if unpassed. This parameter currently
  956. #defaults to None, thus disconnected modules imported in this manner (e.g.,
  957. #hidden imports imported by depend.analysis.initialize_modgraph()).
  958. def import_hook(
  959. self,
  960. target_module_partname,
  961. source_module=None,
  962. target_attr_names=None,
  963. level=DEFAULT_IMPORT_LEVEL,
  964. edge_attr=None,
  965. ):
  966. """
  967. Import the module with the passed name, all parent packages of this
  968. module, _and_ all submodules and attributes in this module with the
  969. passed names from the previously imported caller module signified by
  970. the passed graph node.
  971. Unlike most import methods (e.g., `_safe_import_hook()`), this method
  972. is designed to be publicly called by both external and internal
  973. callers and hence is public.
  974. Parameters
  975. ----------
  976. target_module_partname : str
  977. Partially-qualified name of the target module to be imported. See
  978. `_safe_import_hook()` for further details.
  979. source_module : Node
  980. Graph node for the previously imported **source module** (i.e.,
  981. module containing the `import` statement triggering the call to
  982. this method) _or_ `None` if this module is to be imported in a
  983. "disconnected" manner. **Passing `None` is _not_ recommended.**
  984. Doing so produces a disconnected graph in which the graph node
  985. created for the module to be imported will be disconnected and
  986. hence unreachable from all other nodes -- which frequently causes
  987. subtle issues in external callers (namely PyInstaller, which
  988. silently ignores unreachable nodes).
  989. target_attr_names : list
  990. List of the unqualified names of all submodules and attributes to
  991. be imported from the module to be imported if this is a "from"-
  992. style import (e.g., `[encode_base64, encode_noop]` for the import
  993. `from email.encoders import encode_base64, encode_noop`) _or_
  994. `None` otherwise.
  995. level : int
  996. Whether to perform an absolute or relative import. See
  997. `_safe_import_hook()` for further details.
  998. Returns
  999. ----------
  1000. list
  1001. List of the graph nodes created for all modules explicitly imported
  1002. by this call, including the passed module and all submodules listed
  1003. in `target_attr_names` _but_ excluding all parent packages
  1004. implicitly imported by this call. If `target_attr_names` is `None`
  1005. or the empty list, this is guaranteed to be a list of one element:
  1006. the graph node created for the passed module.
  1007. Raises
  1008. ----------
  1009. ImportError
  1010. If the target module to be imported is unimportable.
  1011. """
  1012. self.msg(3, "_import_hook", target_module_partname, source_module, source_module, level)
  1013. source_package = self._determine_parent(source_module)
  1014. target_package, target_module_partname = self._find_head_package(
  1015. source_package, target_module_partname, level)
  1016. self.msgin(4, "load_tail", target_package, target_module_partname)
  1017. submodule = target_package
  1018. while target_module_partname:
  1019. i = target_module_partname.find('.')
  1020. if i < 0:
  1021. i = len(target_module_partname)
  1022. head, target_module_partname = target_module_partname[
  1023. :i], target_module_partname[i+1:]
  1024. mname = "%s.%s" % (submodule.identifier, head)
  1025. submodule = self._safe_import_module(head, mname, submodule)
  1026. if submodule is None:
  1027. # FIXME: Why do we no longer return a MissingModule instance?
  1028. # result = self.createNode(MissingModule, mname)
  1029. self.msgout(4, "raise ImportError: No module named", mname)
  1030. raise ImportError("No module named " + repr(mname))
  1031. self.msgout(4, "load_tail ->", submodule)
  1032. target_module = submodule
  1033. target_modules = [target_module]
  1034. # If this is a "from"-style import *AND* this target module is
  1035. # actually a package, import all submodules of this package specified
  1036. # by the "import" half of this import (e.g., the submodules "bar" and
  1037. # "car" of the target package "foo" in "from foo import bar, car").
  1038. #
  1039. # If this target module is a non-package, it could still contain
  1040. # importable submodules (e.g., the non-package `os` module containing
  1041. # the `os.path` submodule). In this case, these submodules are already
  1042. # imported by this target module's pure-Python code. Since our import
  1043. # scanner already detects such imports, these submodules need *NOT* be
  1044. # reimported here.
  1045. if target_attr_names and isinstance(target_module,
  1046. (Package, AliasNode)):
  1047. for target_submodule in self._import_importable_package_submodules(
  1048. target_module, target_attr_names):
  1049. if target_submodule not in target_modules:
  1050. target_modules.append(target_submodule)
  1051. # Add an edge from this source module to each target module.
  1052. for target_module in target_modules:
  1053. self._updateReference(
  1054. source_module, target_module, edge_data=edge_attr)
  1055. return target_modules
  1056. def _determine_parent(self, caller):
  1057. """
  1058. Determine the package containing a node.
  1059. """
  1060. self.msgin(4, "determine_parent", caller)
  1061. parent = None
  1062. if caller:
  1063. pname = caller.identifier
  1064. if isinstance(caller, Package):
  1065. parent = caller
  1066. elif '.' in pname:
  1067. pname = pname[:pname.rfind('.')]
  1068. parent = self.find_node(pname)
  1069. elif caller.packagepath:
  1070. # XXX: I have no idea why this line
  1071. # is necessary.
  1072. parent = self.find_node(pname)
  1073. self.msgout(4, "determine_parent ->", parent)
  1074. return parent
  1075. def _find_head_package(
  1076. self,
  1077. source_package,
  1078. target_module_partname,
  1079. level=DEFAULT_IMPORT_LEVEL):
  1080. """
  1081. Import the target package providing the target module with the passed
  1082. name to be subsequently imported from the previously imported source
  1083. package corresponding to the passed graph node.
  1084. Parameters
  1085. ----------
  1086. source_package : Package
  1087. Graph node for the previously imported **source package** (i.e.,
  1088. package containing the module containing the `import` statement
  1089. triggering the call to this method) _or_ `None` if this module is
  1090. to be imported in a "disconnected" manner. **Passing `None` is
  1091. _not_ recommended.** See the `_import_hook()` method for further
  1092. details.
  1093. target_module_partname : str
  1094. Partially-qualified name of the target module to be imported. See
  1095. `_safe_import_hook()` for further details.
  1096. level : int
  1097. Whether to perform absolute or relative imports. See the
  1098. `_safe_import_hook()` method for further details.
  1099. Returns
  1100. ----------
  1101. (target_package, target_module_tailname)
  1102. 2-tuple describing the imported target package, where:
  1103. * `target_package` is the graph node created for this package.
  1104. * `target_module_tailname` is the unqualified name of the target
  1105. module to be subsequently imported (e.g., `text` when passed a
  1106. `target_module_partname` of `email.mime.text`).
  1107. Raises
  1108. ----------
  1109. ImportError
  1110. If the package to be imported is unimportable.
  1111. """
  1112. self.msgin(4, "find_head_package", source_package, target_module_partname, level)
  1113. #FIXME: Rename all local variable names to something sensible. No,
  1114. #"p_fqdn" is not a sensible name.
  1115. # If this target module is a submodule...
  1116. if '.' in target_module_partname:
  1117. target_module_headname, target_module_tailname = (
  1118. target_module_partname.split('.', 1))
  1119. # Else, this target module is a top-level module.
  1120. else:
  1121. target_module_headname = target_module_partname
  1122. target_module_tailname = ''
  1123. # If attempting both absolute and relative imports...
  1124. if level == ABSOLUTE_OR_RELATIVE_IMPORT_LEVEL:
  1125. if source_package:
  1126. target_package_name = source_package.identifier + '.' + target_module_headname
  1127. else:
  1128. target_package_name = target_module_headname
  1129. # Else if attempting only absolute imports...
  1130. elif level == ABSOLUTE_IMPORT_LEVEL:
  1131. target_package_name = target_module_headname
  1132. # Absolute import, ignore the parent
  1133. source_package = None
  1134. # Else if attempting only relative imports...
  1135. else:
  1136. if source_package is None:
  1137. self.msg(2, "Relative import outside of package")
  1138. raise InvalidRelativeImportError(
  1139. "Relative import outside of package (name=%r, parent=%r, level=%r)" % (
  1140. target_module_partname, source_package, level))
  1141. for i in range(level - 1):
  1142. if '.' not in source_package.identifier:
  1143. self.msg(2, "Relative import outside of package")
  1144. raise InvalidRelativeImportError(
  1145. "Relative import outside of package (name=%r, parent=%r, level=%r)" % (
  1146. target_module_partname, source_package, level))
  1147. p_fqdn = source_package.identifier.rsplit('.', 1)[0]
  1148. new_parent = self.find_node(p_fqdn)
  1149. if new_parent is None:
  1150. #FIXME: Repetition detected. Exterminate. Exterminate.
  1151. self.msg(2, "Relative import outside of package")
  1152. raise InvalidRelativeImportError(
  1153. "Relative import outside of package (name=%r, parent=%r, level=%r)" % (
  1154. target_module_partname, source_package, level))
  1155. assert new_parent is not source_package, (
  1156. new_parent, source_package)
  1157. source_package = new_parent
  1158. if target_module_headname:
  1159. target_package_name = (
  1160. source_package.identifier + '.' + target_module_headname)
  1161. else:
  1162. target_package_name = source_package.identifier
  1163. # Graph node of this target package.
  1164. target_package = self._safe_import_module(
  1165. target_module_headname, target_package_name, source_package)
  1166. # If this target package is *NOT* importable and a source package was
  1167. # passed, attempt to import this target package as an absolute import.
  1168. #
  1169. # ADDENDUM: but do this only if the passed "level" is either
  1170. # ABSOLUTE_IMPORT_LEVEL (0) or ABSOLUTE_OR_RELATIVE_IMPORT_LEVEL (-1).
  1171. # Otherwise, an attempt at relative import of a missing sub-module
  1172. # (from .module import something) might pull in an unrelated
  1173. # but eponymous top-level module, which should not happen.
  1174. if target_package is None and source_package is not None and level <= ABSOLUTE_IMPORT_LEVEL:
  1175. target_package_name = target_module_headname
  1176. source_package = None
  1177. # Graph node for the target package, again.
  1178. target_package = self._safe_import_module(
  1179. target_module_headname, target_package_name, source_package)
  1180. # If this target package is importable, return this package.
  1181. if target_package is not None:
  1182. self.msgout(4, "find_head_package ->", (target_package, target_module_tailname))
  1183. return target_package, target_module_tailname
  1184. # Else, raise an exception.
  1185. self.msgout(4, "raise ImportError: No module named", target_package_name)
  1186. raise ImportError("No module named " + target_package_name)
  1187. #FIXME: Refactor from a generator yielding graph nodes into a non-generator
  1188. #returning a list or tuple of all yielded graph nodes. This method is only
  1189. #called once above and the return value of that call is only iterated over
  1190. #as a list or tuple. There's no demonstrable reason for this to be a
  1191. #generator. Generators are great for their intended purposes (e.g., as
  1192. #continuations). This isn't one of those purposes.
  1193. def _import_importable_package_submodules(self, package, attr_names):
  1194. """
  1195. Generator importing and yielding each importable submodule (of the
  1196. previously imported package corresponding to the passed graph node)
  1197. whose unqualified name is in the passed list.
  1198. Elements of this list that are _not_ importable submodules of this
  1199. package are either:
  1200. * Ignorable attributes (e.g., classes, globals) defined at the top
  1201. level of this package's `__init__` submodule, which will be ignored.
  1202. * Else, unignorable unimportable submodules, in which case an
  1203. exception is raised.
  1204. Parameters
  1205. ----------
  1206. package : Package
  1207. Graph node of the previously imported package containing the
  1208. modules to be imported and yielded.
  1209. attr_names : list
  1210. List of the unqualified names of all attributes of this package to
  1211. attempt to import as submodules. This list will be internally
  1212. converted into a set, safely ignoring any duplicates in this list
  1213. (e.g., reducing the "from"-style import
  1214. `from foo import bar, car, far, bar, car, far` to merely
  1215. `from foo import bar, car, far`).
  1216. Yields
  1217. ----------
  1218. Node
  1219. Graph node created for the currently imported submodule.
  1220. Raises
  1221. ----------
  1222. ImportError
  1223. If any attribute whose name is in `attr_names` is neither:
  1224. * An importable submodule of this package.
  1225. * An ignorable global attribute (e.g., class, variable) defined at
  1226. the top level of this package's `__init__` submodule.
  1227. In this case, this attribute _must_ be an unimportable submodule of
  1228. this package.
  1229. """
  1230. # Ignore duplicate submodule names in the passed list.
  1231. attr_names = set(attr_names)
  1232. self.msgin(4, "_import_importable_package_submodules", package, attr_names)
  1233. #FIXME: This test *SHOULD* be superfluous and hence safely removable.
  1234. #The higher-level _scan_bytecode() and _collect_import() methods
  1235. #already guarantee "*" characters to be removed from fromlists.
  1236. if '*' in attr_names:
  1237. attr_names.update(self._find_all_submodules(package))
  1238. attr_names.remove('*')
  1239. # self.msg(4, '_import_importable_package_submodules (global attrs)', package.identifier, package._global_attr_names)
  1240. # For the name of each attribute to be imported from this package...
  1241. for attr_name in attr_names:
  1242. # self.msg(4, '_import_importable_package_submodules (fromlist attr)', package.identifier, attr_name)
  1243. # Graph node of this attribute if this attribute is a previously
  1244. # imported module or None otherwise.
  1245. submodule = package.get_submodule_or_none(attr_name)
  1246. # If this attribute is *NOT* a previously imported module, attempt
  1247. # to import this attribute as a submodule of this package.
  1248. if submodule is None:
  1249. # Fully-qualified name of this submodule.
  1250. submodule_name = package.identifier + '.' + attr_name
  1251. # Graph node of this submodule if importable or None otherwise.
  1252. submodule = self._safe_import_module(
  1253. attr_name, submodule_name, package)
  1254. # If this submodule is unimportable...
  1255. if submodule is None:
  1256. # If this attribute is a global (e.g., class, variable)
  1257. # defined at the top level of this package's "__init__"
  1258. # submodule, this importation is safely ignorable. Do so
  1259. # and skip to the next attribute.
  1260. #
  1261. # This behaviour is non-conformant with Python behaviour,
  1262. # which is bad, but is required to sanely handle all
  1263. # possible edge cases, which is good. In Python, a global
  1264. # attribute defined at the top level of a package's
  1265. # "__init__" submodule shadows a submodule of the same name
  1266. # in that package. Attempting to import that submodule
  1267. # instead imports that attribute; thus, that submodule is
  1268. # effectively unimportable. In this method and elsewhere,
  1269. # that submodule is tested for first and hence shadows that
  1270. # attribute -- the opposite logic. Attempts to import that
  1271. # attribute are mistakenly seen as attempts to import that
  1272. # submodule! Why?
  1273. #
  1274. # Edge cases. PyInstaller (and by extension ModuleGraph)
  1275. # only cares about module imports. Global attribute imports
  1276. # are parsed only as the means to this ends and are
  1277. # otherwise ignorable. The cost of erroneously shadowing:
  1278. #
  1279. # * Submodules by attributes is significant. Doing so
  1280. # prevents such submodules from being frozen and hence
  1281. # imported at application runtime.
  1282. # * Attributes by submodules is insignificant. Doing so
  1283. # could erroneously freeze such submodules despite their
  1284. # never being imported at application runtime. However,
  1285. # ModuleGraph is incapable of determining with certainty
  1286. # that Python logic in another module other than the
  1287. # "__init__" submodule containing these attributes does
  1288. # *NOT* delete these attributes and hence unshadow these
  1289. # submodules, which would then become importable at
  1290. # runtime and require freezing. Hence, ModuleGraph *MUST*
  1291. # permissively assume submodules of the same name as
  1292. # attributes to be unshadowed elsewhere and require
  1293. # freezing -- even if they do not.
  1294. #
  1295. # It is practically difficult (albeit technically feasible)
  1296. # for ModuleGraph to determine whether or not the target
  1297. # attribute names of "from"-style import statements (e.g.,
  1298. # "bar" and "car" in "from foo import bar, car") refer to
  1299. # non-ignorable submodules or ignorable non-module globals
  1300. # during opcode scanning. Distinguishing these two cases
  1301. # during opcode scanning would require a costly call to the
  1302. # _find_module() method, which would subsequently be
  1303. # repeated during import-graph construction. This could be
  1304. # ameliorated with caching, which itself would require
  1305. # costly space consumption and developer time.
  1306. #
  1307. # Since opcode scanning fails to distinguish these two
  1308. # cases, this and other methods subsequently called at
  1309. # import-graph construction time (e.g.,
  1310. # _safe_import_hook()) must do so. Since submodules of the
  1311. # same name as attributes must assume to be unshadowed
  1312. # elsewhere and require freezing, the only solution is to
  1313. # attempt to import an attribute as a non-ignorable module
  1314. # *BEFORE* assuming an attribute to be an ignorable
  1315. # non-module. Which is what this and other methods do.
  1316. #
  1317. # See Package.is_global_attr() for similar discussion.
  1318. if package.is_global_attr(attr_name):
  1319. self.msg(4, '_import_importable_package_submodules: ignoring from-imported global', package.identifier, attr_name)
  1320. continue
  1321. # Else, this attribute is an unimportable submodule. Since
  1322. # this is *NOT* safely ignorable, raise an exception.
  1323. else:
  1324. raise ImportError("No module named " + submodule_name)
  1325. # Yield this submodule's graph node to the caller.
  1326. yield submodule
  1327. self.msgin(4, "_import_importable_package_submodules ->")
  1328. def _find_all_submodules(self, m):
  1329. if not m.packagepath:
  1330. return
  1331. # 'suffixes' used to be a list hardcoded to [".py", ".pyc", ".pyo"].
  1332. # But we must also collect Python extension modules - although
  1333. # we cannot separate normal dlls from Python extensions.
  1334. for path in m.packagepath:
  1335. try:
  1336. names = os.listdir(path)
  1337. except (os.error, IOError):
  1338. self.msg(2, "can't list directory", path)
  1339. continue
  1340. for name in names:
  1341. for suffix in importlib.machinery.all_suffixes():
  1342. if path.endswith(suffix):
  1343. name = os.path.basename(path)[:-len(suffix)]
  1344. break
  1345. else:
  1346. continue
  1347. if name != '__init__':
  1348. yield name
  1349. def alias_module(self, src_module_name, trg_module_name):
  1350. """
  1351. Alias the source module to the target module with the passed names.
  1352. This method ensures that the next call to findNode() given the target
  1353. module name will resolve this alias. This includes importing and adding
  1354. a graph node for the source module if needed as well as adding a
  1355. reference from the target to source module.
  1356. Parameters
  1357. ----------
  1358. src_module_name : str
  1359. Fully-qualified name of the existing **source module** (i.e., the
  1360. module being aliased).
  1361. trg_module_name : str
  1362. Fully-qualified name of the non-existent **target module** (i.e.,
  1363. the alias to be created).
  1364. """
  1365. self.msg(3, 'alias_module "%s" -> "%s"' % (src_module_name, trg_module_name))
  1366. # print('alias_module "%s" -> "%s"' % (src_module_name, trg_module_name))
  1367. assert isinstance(src_module_name, str), '"%s" not a module name.' % str(src_module_name)
  1368. assert isinstance(trg_module_name, str), '"%s" not a module name.' % str(trg_module_name)
  1369. # If the target module has already been added to the graph as either a
  1370. # non-alias or as a different alias, raise an exception.
  1371. trg_module = self.find_node(trg_module_name)
  1372. if trg_module is not None and not (
  1373. isinstance(trg_module, AliasNode) and
  1374. trg_module.identifier == src_module_name):
  1375. raise ValueError(
  1376. 'Target module "%s" already imported as "%s".' % (
  1377. trg_module_name, trg_module))
  1378. # See findNode() for details.
  1379. self.lazynodes[trg_module_name] = Alias(src_module_name)
  1380. def add_module(self, module):
  1381. """
  1382. Add the passed module node to the graph if not already added.
  1383. If that module has a parent module or package with a previously added
  1384. node, this method also adds a reference from this module node to its
  1385. parent node and adds this module node to its parent node's namespace.
  1386. This high-level method wraps the low-level `addNode()` method, but is
  1387. typically _only_ called by graph hooks adding runtime module nodes. For
  1388. all other node types, the `import_module()` method should be called.
  1389. Parameters
  1390. ----------
  1391. module : BaseModule
  1392. Graph node of the module to be added.
  1393. """
  1394. self.msg(3, 'add_module', module)
  1395. # If no node exists for this module, add such a node.
  1396. module_added = self.find_node(module.identifier)
  1397. if module_added is None:
  1398. self.addNode(module)
  1399. else:
  1400. assert module == module_added, 'New module %r != previous %r.' % (module, module_added)
  1401. # If this module has a previously added parent, reference this module to
  1402. # its parent and add this module to its parent's namespace.
  1403. parent_name, _, module_basename = module.identifier.rpartition('.')
  1404. if parent_name:
  1405. parent = self.find_node(parent_name)
  1406. if parent is None:
  1407. self.msg(4, 'add_module parent not found:', parent_name)
  1408. else:
  1409. self.add_edge(module, parent)
  1410. parent.add_submodule(module_basename, module)
  1411. def append_package_path(self, package_name, directory):
  1412. """
  1413. Modulegraph does a good job at simulating Python's, but it can not
  1414. handle packagepath '__path__' modifications packages make at runtime.
  1415. Therefore there is a mechanism whereby you can register extra paths
  1416. in this map for a package, and it will be honored.
  1417. NOTE: This method has to be called before a package is resolved by
  1418. modulegraph.
  1419. Parameters
  1420. ----------
  1421. module : str
  1422. Fully-qualified module name.
  1423. directory : str
  1424. Absolute or relative path of the directory to append to the
  1425. '__path__' attribute.
  1426. """
  1427. paths = self._package_path_map.setdefault(package_name, [])
  1428. paths.append(directory)
  1429. def _safe_import_module(
  1430. self, module_partname, module_name, parent_module):
  1431. """
  1432. Create a new graph node for the module with the passed name under the
  1433. parent package signified by the passed graph node _without_ raising
  1434. `ImportError` exceptions.
  1435. If this module has already been imported, this module's existing graph
  1436. node will be returned; else if this module is importable, a new graph
  1437. node will be added for this module and returned; else this module is
  1438. unimportable, in which case `None` will be returned. Like the
  1439. `_safe_import_hook()` method, this method does _not_ raise
  1440. `ImportError` exceptions when this module is unimportable.
  1441. Parameters
  1442. ----------
  1443. module_partname : str
  1444. Unqualified name of the module to be imported (e.g., `text`).
  1445. module_name : str
  1446. Fully-qualified name of this module (e.g., `email.mime.text`).
  1447. parent_module : Package
  1448. Graph node of the previously imported parent module containing this
  1449. submodule _or_ `None` if this is a top-level module (i.e.,
  1450. `module_name` contains no `.` delimiters). This parent module is
  1451. typically but _not_ always a package (e.g., the `os.path` submodule
  1452. contained by the `os` module).
  1453. Returns
  1454. ----------
  1455. Node
  1456. Graph node created for this module _or_ `None` if this module is
  1457. unimportable.
  1458. """
  1459. self.msgin(3, "safe_import_module", module_partname, module_name, parent_module)
  1460. # If this module has *NOT* already been imported, do so.
  1461. module = self.find_node(module_name)
  1462. if module is None:
  1463. # List of the absolute paths of all directories to be searched for
  1464. # this module. This effectively defaults to "sys.path".
  1465. search_dirs = None
  1466. # If this module has a parent package...
  1467. if parent_module is not None:
  1468. # ...with a list of the absolute paths of all directories
  1469. # comprising this package, prefer that to "sys.path".
  1470. if parent_module.packagepath is not None:
  1471. search_dirs = parent_module.packagepath
  1472. # Else, something is horribly wrong. Return emptiness.
  1473. else:
  1474. self.msgout(3, "safe_import_module -> None (parent_parent.packagepath is None)")
  1475. return None
  1476. try:
  1477. pathname, loader = self._find_module(
  1478. module_partname, search_dirs, parent_module)
  1479. except ImportError as exc:
  1480. self.msgout(3, "safe_import_module -> None (%r)" % exc)
  1481. return None
  1482. (module, co) = self._load_module(module_name, pathname, loader)
  1483. if co is not None:
  1484. try:
  1485. if isinstance(co, ast.AST):
  1486. co_ast = co
  1487. co = compile(co_ast, pathname, 'exec', 0, True)
  1488. else:
  1489. co_ast = None
  1490. n = self._scan_code(module, co, co_ast)
  1491. self._process_imports(n)
  1492. if self.replace_paths:
  1493. co = self._replace_paths_in_code(co)
  1494. module.code = co
  1495. except SyntaxError:
  1496. self.msg(
  1497. 1, "safe_import_module: SyntaxError in ", pathname,
  1498. )
  1499. cls = InvalidSourceModule
  1500. module = self.createNode(cls, module_name)
  1501. # If this is a submodule rather than top-level module...
  1502. if parent_module is not None:
  1503. self.msg(4, "safe_import_module create reference", module, "->", parent_module)
  1504. # Add an edge from this submodule to its parent module.
  1505. self._updateReference(
  1506. module, parent_module, edge_data=DependencyInfo(
  1507. conditional=False,
  1508. fromlist=False,
  1509. function=False,
  1510. tryexcept=False,
  1511. ))
  1512. # Add this submodule to its parent module.
  1513. parent_module.add_submodule(module_partname, module)
  1514. # Return this module.
  1515. self.msgout(3, "safe_import_module ->", module)
  1516. return module
  1517. def _load_module(self, fqname, pathname, loader):
  1518. from importlib._bootstrap_external import ExtensionFileLoader
  1519. self.msgin(2, "load_module", fqname, pathname,
  1520. loader.__class__.__name__)
  1521. partname = fqname.rpartition(".")[-1]
  1522. if loader.is_package(partname):
  1523. if isinstance(loader, NAMESPACE_PACKAGE):
  1524. # This is a PEP-420 namespace package.
  1525. m = self.createNode(NamespacePackage, fqname)
  1526. m.filename = '-'
  1527. m.packagepath = loader.namespace_dirs[:] # copy for safety
  1528. else:
  1529. # Regular package.
  1530. #
  1531. # NOTE: this might be a legacy setuptools (pkg_resources)
  1532. # based namespace package (with __init__.py, but calling
  1533. # `pkg_resources.declare_namespace(__name__)`). To properly
  1534. # handle the case when such a package is split across
  1535. # multiple locations, we need to resolve the package
  1536. # paths via metadata.
  1537. ns_pkgpaths = self._legacy_ns_packages.get(fqname, [])
  1538. if isinstance(loader, ExtensionFileLoader):
  1539. m = self.createNode(ExtensionPackage, fqname)
  1540. else:
  1541. m = self.createNode(Package, fqname)
  1542. m.filename = pathname
  1543. # PEP-302-compliant loaders return the pathname of the
  1544. # `__init__`-file, not the package directory.
  1545. assert os.path.basename(pathname).startswith('__init__.')
  1546. m.packagepath = [os.path.dirname(pathname)] + ns_pkgpaths
  1547. # As per comment at top of file, simulate runtime packagepath
  1548. # additions
  1549. m.packagepath = m.packagepath + self._package_path_map.get(
  1550. fqname, [])
  1551. if isinstance(m, NamespacePackage):
  1552. return (m, None)
  1553. co = None
  1554. if loader is BUILTIN_MODULE:
  1555. cls = BuiltinModule
  1556. elif isinstance(loader, ExtensionFileLoader):
  1557. cls = Extension
  1558. # Look for accompanying .py or .pyi file, which might allow
  1559. # us to perform basic import analysis for the extension.
  1560. def _co_from_accompanying_source(extension_filename):
  1561. path = os.path.dirname(extension_filename)
  1562. basename = os.path.basename(extension_filename).split('.')[0]
  1563. for ext in {'.py', '.pyi'}:
  1564. src_filename = os.path.join(path, basename + ext)
  1565. if not os.path.isfile(src_filename):
  1566. continue
  1567. try:
  1568. with open(src_filename, 'rb') as fp:
  1569. src = fp.read()
  1570. co = compile(src, src_filename, 'exec', ast.PyCF_ONLY_AST, True)
  1571. return co
  1572. except Exception as e:
  1573. pass
  1574. co = _co_from_accompanying_source(pathname)
  1575. else:
  1576. try:
  1577. src = loader.get_source(partname)
  1578. except (UnicodeDecodeError, SyntaxError) as e:
  1579. # The `UnicodeDecodeError` is typically raised here when the
  1580. # source file contains non-ASCII characters in some local
  1581. # encoding that is different from UTF-8, but fails to
  1582. # declare it via PEP361 encoding header. Python seems to
  1583. # be able to load and run such module, but we cannot retrieve
  1584. # the source for it via the `loader.get_source()`.
  1585. #
  1586. # The `UnicodeDecoreError` in turn triggers a `SyntaxError`
  1587. # when such invalid character appears on the first line of
  1588. # the source file (and interrupts the scan for PEP361
  1589. # encoding header).
  1590. #
  1591. # In such cases, we try to fall back to reading the source
  1592. # as raw data file.
  1593. # If `SyntaxError` was not raised during handling of
  1594. # a `UnicodeDecodeError`, it was likely a genuine syntax
  1595. # error, so re-raise it.
  1596. if isinstance(e, SyntaxError):
  1597. if not isinstance(e.__context__, UnicodeDecodeError):
  1598. raise
  1599. self.msg(2, "load_module: failed to obtain source for "
  1600. f"{partname}: {e}! Falling back to reading as "
  1601. "raw data!")
  1602. path = loader.get_filename(partname)
  1603. src = loader.get_data(path)
  1604. if src is not None:
  1605. try:
  1606. co = compile(src, pathname, 'exec', ast.PyCF_ONLY_AST, True)
  1607. cls = SourceModule
  1608. except SyntaxError:
  1609. co = None
  1610. cls = InvalidSourceModule
  1611. except Exception as exc: # FIXME: more specific?
  1612. cls = InvalidSourceModule
  1613. self.msg(2, "load_module: InvalidSourceModule", pathname,
  1614. exc)
  1615. else:
  1616. # no src available
  1617. try:
  1618. co = loader.get_code(partname)
  1619. cls = (CompiledModule if co is not None
  1620. else InvalidCompiledModule)
  1621. except Exception as exc: # FIXME: more specific?
  1622. self.msg(2, "load_module: InvalidCompiledModule, "
  1623. "Cannot load code", pathname, exc)
  1624. cls = InvalidCompiledModule
  1625. m = self.createNode(cls, fqname)
  1626. m.filename = pathname
  1627. self.msgout(2, "load_module ->", m)
  1628. return (m, co)
  1629. def _safe_import_hook(
  1630. self, target_module_partname, source_module, target_attr_names,
  1631. level=DEFAULT_IMPORT_LEVEL, edge_attr=None):
  1632. """
  1633. Import the module with the passed name and all parent packages of this
  1634. module from the previously imported caller module signified by the
  1635. passed graph node _without_ raising `ImportError` exceptions.
  1636. This method wraps the lowel-level `_import_hook()` method. On catching
  1637. an `ImportError` exception raised by that method, this method creates
  1638. and adds a `MissingNode` instance describing the unimportable module to
  1639. the graph instead.
  1640. Parameters
  1641. ----------
  1642. target_module_partname : str
  1643. Partially-qualified name of the module to be imported. If `level`
  1644. is:
  1645. * `ABSOLUTE_OR_RELATIVE_IMPORT_LEVEL` (e.g., the Python 2 default)
  1646. or a positive integer (e.g., an explicit relative import), the
  1647. fully-qualified name of this module is the concatenation of the
  1648. fully-qualified name of the caller module's package and this
  1649. parameter.
  1650. * `ABSOLUTE_IMPORT_LEVEL` (e.g., the Python 3 default), this name
  1651. is already fully-qualified.
  1652. * A non-negative integer (e.g., `1`), this name is typically the
  1653. empty string. In this case, this is a "from"-style relative
  1654. import (e.g., "from . import bar") and the fully-qualified name
  1655. of this module is dynamically resolved by import machinery.
  1656. source_module : Node
  1657. Graph node for the previously imported **caller module** (i.e.,
  1658. module containing the `import` statement triggering the call to
  1659. this method) _or_ `None` if this module is to be imported in a
  1660. "disconnected" manner. **Passing `None` is _not_ recommended.**
  1661. Doing so produces a disconnected graph in which the graph node
  1662. created for the module to be imported will be disconnected and
  1663. hence unreachable from all other nodes -- which frequently causes
  1664. subtle issues in external callers (e.g., PyInstaller, which
  1665. silently ignores unreachable nodes).
  1666. target_attr_names : list
  1667. List of the unqualified names of all submodules and attributes to
  1668. be imported via a `from`-style import statement from this target
  1669. module if any (e.g., the list `[encode_base64, encode_noop]` for
  1670. the import `from email.encoders import encode_base64, encode_noop`)
  1671. _or_ `None` otherwise. Ignored unless `source_module` is the graph
  1672. node of a package (i.e., is an instance of the `Package` class).
  1673. Why? Because:
  1674. * Consistency. The `_import_importable_package_submodules()`
  1675. method accepts a similar list applicable only to packages.
  1676. * Efficiency. Unlike packages, modules cannot physically contain
  1677. submodules. Hence, any target module imported via a `from`-style
  1678. import statement as an attribute from another target parent
  1679. module must itself have been imported in that target parent
  1680. module. The import statement responsible for that import must
  1681. already have been previously parsed by `ModuleGraph`, in which
  1682. case that target module will already be frozen by PyInstaller.
  1683. These imports are safely ignorable here.
  1684. level : int
  1685. Whether to perform an absolute or relative import. This parameter
  1686. corresponds exactly to the parameter of the same name accepted by
  1687. the `__import__()` built-in: "The default is -1 which indicates
  1688. both absolute and relative imports will be attempted. 0 means only
  1689. perform absolute imports. Positive values for level indicate the
  1690. number of parent directories to search relative to the directory of
  1691. the module calling `__import__()`." Defaults to -1 under Python 2
  1692. and 0 under Python 3. Since this default depends on the major
  1693. version of the current Python interpreter, depending on this
  1694. default can result in unpredictable and non-portable behaviour.
  1695. Callers are strongly recommended to explicitly pass this parameter
  1696. rather than implicitly accept this default.
  1697. Returns
  1698. ----------
  1699. list
  1700. List of the graph nodes created for all modules explicitly imported
  1701. by this call, including the passed module and all submodules listed
  1702. in `target_attr_names` _but_ excluding all parent packages
  1703. implicitly imported by this call. If `target_attr_names` is either
  1704. `None` or the empty list, this is guaranteed to be a list of one
  1705. element: the graph node created for the passed module. As above,
  1706. `MissingNode` instances are created for all unimportable modules.
  1707. """
  1708. self.msg(3, "_safe_import_hook", target_module_partname, source_module, target_attr_names, level)
  1709. def is_swig_candidate():
  1710. return (source_module is not None and
  1711. target_attr_names is None and
  1712. level == ABSOLUTE_IMPORT_LEVEL and
  1713. type(source_module) is SourceModule and
  1714. target_module_partname ==
  1715. '_' + source_module.identifier.rpartition('.')[2])
  1716. def is_swig_wrapper(source_module):
  1717. with open(source_module.filename, 'rb') as fp:
  1718. contents = fp.read()
  1719. contents = importlib.util.decode_source(contents)
  1720. first_line = contents.splitlines()[0] if contents else ''
  1721. self.msg(5, 'SWIG wrapper candidate first line: %r' % (first_line))
  1722. return "automatically generated by SWIG" in first_line
  1723. # List of the graph nodes created for all target modules both
  1724. # imported by and returned from this call, whose:
  1725. #
  1726. # * First element is the graph node for the core target module
  1727. # specified by the "target_module_partname" parameter.
  1728. # * Remaining elements are the graph nodes for all target submodules
  1729. # specified by the "target_attr_names" parameter.
  1730. target_modules = None
  1731. # True if this is a Python 2-style implicit relative import of a
  1732. # SWIG-generated C extension. False if we checked and it is not SWIG.
  1733. # None if we haven't checked yet.
  1734. is_swig_import = None
  1735. # Attempt to import this target module in the customary way.
  1736. try:
  1737. target_modules = self.import_hook(
  1738. target_module_partname, source_module,
  1739. target_attr_names=None, level=level, edge_attr=edge_attr)
  1740. # Failing that, defer to custom module importers handling non-standard
  1741. # import schemes (namely, SWIG).
  1742. except InvalidRelativeImportError:
  1743. self.msgout(2, "Invalid relative import", level,
  1744. target_module_partname, target_attr_names)
  1745. result = []
  1746. for sub in target_attr_names or '*':
  1747. m = self.createNode(InvalidRelativeImport,
  1748. '.' * level + target_module_partname, sub)
  1749. self._updateReference(source_module, m, edge_data=edge_attr)
  1750. result.append(m)
  1751. return result
  1752. except ImportError as msg:
  1753. # If this is an absolute top-level import under Python 3 and if the
  1754. # name to be imported is the caller's name prefixed by "_", this
  1755. # could be a SWIG-generated Python 2-style implicit relative import.
  1756. # SWIG-generated files contain functions named swig_import_helper()
  1757. # importing dynamic libraries residing in the same directory. For
  1758. # example, a SWIG-generated caller module "csr.py" might resemble:
  1759. #
  1760. # # This file was automatically generated by SWIG (http://www.swig.org).
  1761. # ...
  1762. # def swig_import_helper():
  1763. # ...
  1764. # try:
  1765. # fp, pathname, description = imp.find_module('_csr',
  1766. # [dirname(__file__)])
  1767. # except ImportError:
  1768. # import _csr
  1769. # return _csr
  1770. #
  1771. # While there exists no reasonable means for modulegraph to parse
  1772. # the call to imp.find_module(), the subsequent implicit relative
  1773. # import is trivially parsable. This import is prohibited under
  1774. # Python 3, however, and thus parsed only if the caller's file is
  1775. # parsable plaintext (as indicated by a filetype of ".py") and the
  1776. # first line of this file is the above SWIG header comment.
  1777. #
  1778. # The constraint that this library's name be the caller's name
  1779. # prefixed by '_' is explicitly mandated by SWIG and thus a
  1780. # reliable indicator of "SWIG-ness". The SWIG documentation states:
  1781. # "When linking the module, the name of the output file has to match
  1782. # the name of the module prefixed by an underscore."
  1783. #
  1784. # Only source modules (e.g., ".py"-suffixed files) are SWIG import
  1785. # candidates. All other node types are safely ignorable.
  1786. if is_swig_candidate():
  1787. self.msg(
  1788. 4,
  1789. 'SWIG import candidate (name=%r, caller=%r, level=%r)' % (
  1790. target_module_partname, source_module, level))
  1791. is_swig_import = is_swig_wrapper(source_module)
  1792. if is_swig_import:
  1793. # Convert this Python 2-compliant implicit relative
  1794. # import prohibited by Python 3 into a Python
  1795. # 3-compliant explicit relative "from"-style import for
  1796. # the duration of this function call by overwriting the
  1797. # original parameters passed to this call.
  1798. target_attr_names = [target_module_partname]
  1799. target_module_partname = ''
  1800. level = 1
  1801. self.msg(2,
  1802. 'SWIG import (caller=%r, fromlist=%r, level=%r)'
  1803. % (source_module, target_attr_names, level))
  1804. # Import this target SWIG C extension's package.
  1805. try:
  1806. target_modules = self.import_hook(
  1807. target_module_partname, source_module,
  1808. target_attr_names=None,
  1809. level=level,
  1810. edge_attr=edge_attr)
  1811. except ImportError as msg:
  1812. self.msg(2, "SWIG ImportError:", str(msg))
  1813. # If this module remains unimportable...
  1814. if target_modules is None:
  1815. self.msg(2, "ImportError:", str(msg))
  1816. # Add this module as a MissingModule node.
  1817. target_module = self.createNode(
  1818. MissingModule,
  1819. _path_from_importerror(msg, target_module_partname))
  1820. self._updateReference(
  1821. source_module, target_module, edge_data=edge_attr)
  1822. # Initialize this list to this node.
  1823. target_modules = [target_module]
  1824. # Ensure that the above logic imported exactly one target module.
  1825. assert len(target_modules) == 1, (
  1826. 'Expected import_hook() to'
  1827. 'return only one module but received: {}'.format(target_modules))
  1828. # Target module imported above.
  1829. target_module = target_modules[0]
  1830. if isinstance(target_module, MissingModule) \
  1831. and is_swig_import is None and is_swig_candidate() \
  1832. and is_swig_wrapper(source_module):
  1833. # if this possible swig C module was previously imported from
  1834. # a python module other than its corresponding swig python
  1835. # module, then it may have been considered a MissingModule.
  1836. # Try to reimport it now. For details see pull-request #2578
  1837. # and issue #1522.
  1838. #
  1839. # If this module was takes as a SWIG candidate above, but failed
  1840. # to import, this would be a MissingModule, too. Thus check if
  1841. # this was the case (is_swig_import would be not None) to avoid
  1842. # recursion error. If `is_swig_import` is None and we are still a
  1843. # swig candidate then that means we haven't properly imported this
  1844. # swig module yet so do that below.
  1845. #
  1846. # Remove the MissingModule node from the graph so that we can
  1847. # attempt a reimport and avoid collisions. This node should be
  1848. # fine to remove because the proper module will be imported and
  1849. # added to the graph in the next line (call to _safe_import_hook).
  1850. self.removeNode(target_module)
  1851. # Reimport the SWIG C module relative to the wrapper
  1852. target_modules = self._safe_import_hook(
  1853. target_module_partname, source_module,
  1854. target_attr_names=None, level=1, edge_attr=edge_attr)
  1855. # return the output regardless because it would just be
  1856. # duplicating the processing below
  1857. return target_modules
  1858. if isinstance(edge_attr, DependencyInfo):
  1859. edge_attr = edge_attr._replace(fromlist=True)
  1860. # If this is a "from"-style import *AND* this target module is a
  1861. # package, import all attributes listed by the "import" clause of this
  1862. # import that are submodules of this package. If this target module is
  1863. # *NOT* a package, these attributes are always ignorable globals (e.g.,
  1864. # classes, variables) defined at the top level of this module.
  1865. #
  1866. # If this target module is a non-package, it could still contain
  1867. # importable submodules (e.g., the non-package `os` module containing
  1868. # the `os.path` submodule). In this case, these submodules are already
  1869. # imported by this target module's pure-Python code. Since our import
  1870. # scanner already detects these imports, these submodules need *NOT* be
  1871. # reimported here. (Doing so would be harmless but inefficient.)
  1872. if target_attr_names and isinstance(target_module,
  1873. (Package, AliasNode)):
  1874. # For the name of each attribute imported from this target package
  1875. # into this source module...
  1876. for target_submodule_partname in target_attr_names:
  1877. #FIXME: Is this optimization *REALLY* an optimization or at all
  1878. #necessary? The findNode() method called below should already
  1879. #be heavily optimized, in which case this optimization here is
  1880. #premature, senseless, and should be eliminated.
  1881. # If this attribute is a previously imported submodule of this
  1882. # target module, optimize this edge case.
  1883. if target_module.is_submodule(target_submodule_partname):
  1884. # Graph node for this submodule.
  1885. target_submodule = target_module.get_submodule(
  1886. target_submodule_partname)
  1887. #FIXME: What? Shouldn't "target_submodule" *ALWAYS* be
  1888. #non-None here? Assert this to be non-None instead.
  1889. if target_submodule is not None:
  1890. #FIXME: Why does duplication matter? List searches are
  1891. #mildly expensive.
  1892. # If this submodule has not already been added to the
  1893. # list of submodules to be returned, do so.
  1894. if target_submodule not in target_modules:
  1895. self._updateReference(
  1896. source_module,
  1897. target_submodule,
  1898. edge_data=edge_attr)
  1899. target_modules.append(target_submodule)
  1900. continue
  1901. # Fully-qualified name of this submodule.
  1902. target_submodule_name = (
  1903. target_module.identifier + '.' + target_submodule_partname)
  1904. # Graph node of this submodule if previously imported or None.
  1905. target_submodule = self.find_node(target_submodule_name)
  1906. # If this submodule has not been imported, do so as if this
  1907. # submodule were the only attribute listed by the "import"
  1908. # clause of this import (e.g., as "from foo import bar" rather
  1909. # than "from foo import car, far, bar").
  1910. if target_submodule is None:
  1911. # Attempt to import this submodule.
  1912. try:
  1913. # Ignore the list of graph nodes returned by this
  1914. # method. If both this submodule's package and this
  1915. # submodule are importable, this method returns a
  1916. # 2-element list whose second element is this
  1917. # submodule's graph node. However, if this submodule's
  1918. # package is importable but this submodule is not,
  1919. # this submodule is either:
  1920. #
  1921. # * An ignorable global attribute defined at the top
  1922. # level of this package's "__init__" submodule. In
  1923. # this case, this method returns a 1-element list
  1924. # without raising an exception.
  1925. # * A non-ignorable unimportable submodule. In this
  1926. # case, this method raises an "ImportError".
  1927. #
  1928. # While the first two cases are disambiguatable by the
  1929. # length of this list, doing so would render this code
  1930. # dependent on import_hook() details subject to change.
  1931. # Instead, call findNode() to decide the truthiness.
  1932. self.import_hook(
  1933. target_module_partname, source_module,
  1934. target_attr_names=[target_submodule_partname],
  1935. level=level,
  1936. edge_attr=edge_attr)
  1937. # Graph node of this submodule imported by the prior
  1938. # call if importable or None otherwise.
  1939. target_submodule = self.find_node(target_submodule_name)
  1940. # If this submodule does not exist, this *MUST* be an
  1941. # ignorable global attribute defined at the top level
  1942. # of this package's "__init__" submodule.
  1943. if target_submodule is None:
  1944. # Assert this to actually be the case.
  1945. assert target_module.is_global_attr(
  1946. target_submodule_partname), (
  1947. 'No global named {} in {}.__init__'.format(
  1948. target_submodule_partname,
  1949. target_module.identifier))
  1950. # Skip this safely ignorable importation to the
  1951. # next attribute. See similar logic in the body of
  1952. # _import_importable_package_submodules().
  1953. self.msg(4, '_safe_import_hook', 'ignoring imported non-module global', target_module.identifier, target_submodule_partname)
  1954. continue
  1955. # If this is a SWIG C extension, instruct PyInstaller
  1956. # to freeze this extension under its unqualified rather
  1957. # than qualified name (e.g., as "_csr" rather than
  1958. # "scipy.sparse.sparsetools._csr"), permitting the
  1959. # implicit relative import in its parent SWIG module to
  1960. # successfully find this extension.
  1961. if is_swig_import:
  1962. # If a graph node with this name already exists,
  1963. # avoid collisions by emitting an error instead.
  1964. if self.find_node(target_submodule_partname):
  1965. self.msg(
  1966. 2,
  1967. 'SWIG import error: %r basename %r '
  1968. 'already exists' % (
  1969. target_submodule_name,
  1970. target_submodule_partname))
  1971. else:
  1972. self.msg(
  1973. 4,
  1974. 'SWIG import renamed from %r to %r' % (
  1975. target_submodule_name,
  1976. target_submodule_partname))
  1977. target_submodule.identifier = (
  1978. target_submodule_partname)
  1979. # If this submodule is unimportable, add a MissingModule.
  1980. except ImportError as msg:
  1981. self.msg(2, "ImportError:", str(msg))
  1982. target_submodule = self.createNode(
  1983. MissingModule, target_submodule_name)
  1984. # Add this submodule to its package.
  1985. target_module.add_submodule(
  1986. target_submodule_partname, target_submodule)
  1987. if target_submodule is not None:
  1988. self._updateReference(
  1989. target_module, target_submodule, edge_data=edge_attr)
  1990. self._updateReference(
  1991. source_module, target_submodule, edge_data=edge_attr)
  1992. if target_submodule not in target_modules:
  1993. target_modules.append(target_submodule)
  1994. # Return the list of all target modules imported by this call.
  1995. return target_modules
  1996. def _scan_code(
  1997. self,
  1998. module,
  1999. module_code_object,
  2000. module_code_object_ast=None):
  2001. """
  2002. Parse and add all import statements from the passed code object of the
  2003. passed source module to this graph, recursively.
  2004. **This method is at the root of all `ModuleGraph` recursion.**
  2005. Recursion begins here and ends when all import statements in all code
  2006. objects of all modules transitively imported by the source module
  2007. passed to the first call to this method have been added to the graph.
  2008. Specifically, this method:
  2009. 1. If the passed `module_code_object_ast` parameter is non-`None`,
  2010. parses all import statements from this object.
  2011. 2. Else, parses all import statements from the passed
  2012. `module_code_object` parameter.
  2013. 1. For each such import statement:
  2014. 1. Adds to this `ModuleGraph` instance:
  2015. 1. Nodes for all target modules of these imports.
  2016. 1. Directed edges from this source module to these target
  2017. modules.
  2018. 2. Recursively calls this method with these target modules.
  2019. Parameters
  2020. ----------
  2021. module : Node
  2022. Graph node of the module to be parsed.
  2023. module_code_object : PyCodeObject
  2024. Code object providing this module's disassembled Python bytecode.
  2025. Ignored unless `module_code_object_ast` is `None`.
  2026. module_code_object_ast : optional[ast.AST]
  2027. Optional abstract syntax tree (AST) of this module if any or `None`
  2028. otherwise. Defaults to `None`, in which case the passed
  2029. `module_code_object` is parsed instead.
  2030. Returns
  2031. ----------
  2032. module : Node
  2033. Graph node of the module to be parsed.
  2034. """
  2035. # For safety, guard against multiple scans of the same module by
  2036. # resetting this module's list of deferred target imports.
  2037. module._deferred_imports = []
  2038. # Parse all imports from this module *BEFORE* adding these imports to
  2039. # the graph. If an AST is provided, parse that rather than this
  2040. # module's code object.
  2041. if module_code_object_ast is not None:
  2042. # Parse this module's AST for imports.
  2043. self._scan_ast(module, module_code_object_ast)
  2044. # Parse this module's code object for all relevant non-imports
  2045. # (e.g., global variable declarations and undeclarations).
  2046. self._scan_bytecode(
  2047. module, module_code_object, is_scanning_imports=False)
  2048. # Else, parse this module's code object for imports.
  2049. else:
  2050. self._scan_bytecode(
  2051. module, module_code_object, is_scanning_imports=True)
  2052. return module
  2053. def _scan_ast(self, module, module_code_object_ast):
  2054. """
  2055. Parse and add all import statements from the passed abstract syntax
  2056. tree (AST) of the passed source module to this graph, non-recursively.
  2057. Parameters
  2058. ----------
  2059. module : Node
  2060. Graph node of the module to be parsed.
  2061. module_code_object_ast : ast.AST
  2062. Abstract syntax tree (AST) of this module to be parsed.
  2063. """
  2064. visitor = _Visitor(self, module)
  2065. visitor.visit(module_code_object_ast)
  2066. #FIXME: Optimize. Global attributes added by this method are tested by
  2067. #other methods *ONLY* for packages, implying this method should scan and
  2068. #handle opcodes pertaining to global attributes (e.g.,
  2069. #"STORE_NAME", "DELETE_GLOBAL") only if the passed "module"
  2070. #object is an instance of the "Package" class. For all other module types,
  2071. #these opcodes should simply be ignored.
  2072. #
  2073. #After doing so, the "Node._global_attr_names" attribute and all methods
  2074. #using this attribute (e.g., Node.is_global()) should be moved from the
  2075. #"Node" superclass to the "Package" subclass.
  2076. def _scan_bytecode(
  2077. self, module, module_code_object, is_scanning_imports):
  2078. """
  2079. Parse and add all import statements from the passed code object of the
  2080. passed source module to this graph, non-recursively.
  2081. This method parses all reasonably parsable operations (i.e., operations
  2082. that are both syntactically and semantically parsable _without_
  2083. requiring Turing-complete interpretation) directly or indirectly
  2084. involving module importation from this code object. This includes:
  2085. * `IMPORT_NAME`, denoting an import statement. Ignored unless
  2086. the passed `is_scanning_imports` parameter is `True`.
  2087. * `STORE_NAME` and `STORE_GLOBAL`, denoting the
  2088. declaration of a global attribute (e.g., class, variable) in this
  2089. module. This method stores each such declaration for subsequent
  2090. lookup. While global attributes are usually irrelevant to import
  2091. parsing, they remain the only means of distinguishing erroneous
  2092. non-ignorable attempts to import non-existent submodules of a package
  2093. from successful ignorable attempts to import existing global
  2094. attributes of a package's `__init__` submodule (e.g., the `bar` in
  2095. `from foo import bar`, which is either a non-ignorable submodule of
  2096. `foo` or an ignorable global attribute of `foo.__init__`).
  2097. * `DELETE_NAME` and `DELETE_GLOBAL`, denoting the
  2098. undeclaration of a previously declared global attribute in this
  2099. module.
  2100. Since `ModuleGraph` is _not_ intended to replicate the behaviour of a
  2101. full-featured Turing-complete Python interpreter, this method ignores
  2102. operations that are _not_ reasonably parsable from this code object --
  2103. even those directly or indirectly involving module importation. This
  2104. includes:
  2105. * `STORE_ATTR(namei)`, implementing `TOS.name = TOS1`. If `TOS` is the
  2106. name of a target module currently imported into the namespace of the
  2107. passed source module, this opcode would ideally be parsed to add that
  2108. global attribute to that target module. Since this addition only
  2109. conditionally occurs on the importation of this source module and
  2110. execution of the code branch in this module performing this addition,
  2111. however, that global _cannot_ be unconditionally added to that target
  2112. module. In short, only Turing-complete behaviour suffices.
  2113. * `DELETE_ATTR(namei)`, implementing `del TOS.name`. If `TOS` is the
  2114. name of a target module currently imported into the namespace of the
  2115. passed source module, this opcode would ideally be parsed to remove
  2116. that global attribute from that target module. Again, however, only
  2117. Turing-complete behaviour suffices.
  2118. Parameters
  2119. ----------
  2120. module : Node
  2121. Graph node of the module to be parsed.
  2122. module_code_object : PyCodeObject
  2123. Code object of the module to be parsed.
  2124. is_scanning_imports : bool
  2125. `True` only if this method is parsing import statements from
  2126. `IMPORT_NAME` opcodes. If `False`, no import statements will be
  2127. parsed. This parameter is typically:
  2128. * `True` when parsing this module's code object for such imports.
  2129. * `False` when parsing this module's abstract syntax tree (AST)
  2130. (rather than code object) for such imports. In this case, that
  2131. parsing will have already parsed import statements, which this
  2132. parsing must avoid repeating.
  2133. """
  2134. level = None
  2135. fromlist = None
  2136. # 'deque' is a list-like container with fast appends, pops on
  2137. # either end, and automatically discarding elements too much.
  2138. prev_insts = deque(maxlen=2)
  2139. for inst in util.iterate_instructions(module_code_object):
  2140. if not inst:
  2141. continue
  2142. # If this is an import statement originating from this module,
  2143. # parse this import.
  2144. #
  2145. # Note that the related "IMPORT_FROM" opcode need *NOT* be parsed.
  2146. # "IMPORT_NAME" suffices. For further details, see
  2147. # http://probablyprogramming.com/2008/04/14/python-import_name
  2148. if inst.opname == 'IMPORT_NAME':
  2149. # If this method is ignoring import statements, skip to the
  2150. # next opcode.
  2151. if not is_scanning_imports:
  2152. continue
  2153. # Python >=2.5: LOAD_CONST flags, LOAD_CONST names, IMPORT_NAME name
  2154. #
  2155. # Python 3.14 split LOAD_CONST into LOAD_CONST, LOAD_CONST_IMMORTAL,
  2156. # and LOAD_SMALL_INT. The former two can be used to load the names
  2157. # (i.e., the fromlist argument), while LOAD_SMALL_INT can be also used
  2158. # to load the flags (i.e., the level argument). LOAD_CONST_IMMORTAL was
  2159. # subsequently removed in Python 3.15.
  2160. #
  2161. # Python 3.14 also introduced LOAD_COMMON_CONSTANT, which was extended
  2162. # in python 3.15 to cover the None constant.
  2163. if sys.version_info >= (3, 15):
  2164. EXPECTED_OPCODES_LEVEL = {
  2165. 'LOAD_CONST',
  2166. 'LOAD_SMALL_INT',
  2167. }
  2168. EXPECTED_OPCODES_FROMLIST = {
  2169. 'LOAD_CONST',
  2170. 'LOAD_COMMON_CONSTANT',
  2171. }
  2172. elif sys.version_info >= (3, 14):
  2173. EXPECTED_OPCODES_LEVEL = {
  2174. 'LOAD_CONST',
  2175. 'LOAD_CONST_IMMORTAL',
  2176. 'LOAD_SMALL_INT',
  2177. }
  2178. EXPECTED_OPCODES_FROMLIST = {
  2179. 'LOAD_CONST',
  2180. 'LOAD_CONST_IMMORTAL',
  2181. 'LOAD_COMMON_CONSTANT',
  2182. }
  2183. else:
  2184. EXPECTED_OPCODES_LEVEL = {
  2185. 'LOAD_CONST',
  2186. }
  2187. EXPECTED_OPCODES_FROMLIST = {
  2188. 'LOAD_CONST',
  2189. }
  2190. assert prev_insts[-2].opname in EXPECTED_OPCODES_LEVEL, \
  2191. f"Unexpected opcode used to push level argument: {prev_insts[-2].opname}"
  2192. assert prev_insts[-1].opname in EXPECTED_OPCODES_FROMLIST, \
  2193. f"Unexpected opcode used to push fromlist argument: {prev_insts[-1].opname}"
  2194. level = prev_insts[-2].argval
  2195. fromlist = prev_insts[-1].argval
  2196. assert fromlist is None or type(fromlist) is tuple, \
  2197. f"Unexpected type of fromlistargument: {type(fromlist)}"
  2198. target_module_partname = inst.argval
  2199. #FIXME: The exact same logic appears in _collect_import(),
  2200. #which isn't particularly helpful. Instead, defer this logic
  2201. #until later by:
  2202. #
  2203. #* Refactor the "_deferred_imports" list to contain 2-tuples
  2204. # "(_safe_import_hook_args, _safe_import_hook_kwargs)" rather
  2205. # than 3-tuples "(have_star, _safe_import_hook_args,
  2206. # _safe_import_hook_kwargs)".
  2207. #* Stop prepending these tuples by a "have_star" boolean both
  2208. # here, in _collect_import(), and in _process_imports().
  2209. #* Shift the logic below to _process_imports().
  2210. #* Remove the same logic from _collect_import().
  2211. have_star = False
  2212. if fromlist is not None:
  2213. fromlist = uniq(fromlist)
  2214. if '*' in fromlist:
  2215. fromlist.remove('*')
  2216. have_star = True
  2217. # Record this import as originating from this module for
  2218. # subsequent handling by the _process_imports() method.
  2219. module._deferred_imports.append((
  2220. have_star,
  2221. (target_module_partname, module, fromlist, level),
  2222. {}
  2223. ))
  2224. elif inst.opname in ('STORE_NAME', 'STORE_GLOBAL'):
  2225. # If this is the declaration of a global attribute (e.g.,
  2226. # class, variable) in this module, store this declaration for
  2227. # subsequent lookup. See method docstring for further details.
  2228. #
  2229. # Global attributes are usually irrelevant to import parsing, but
  2230. # remain the only means of distinguishing erroneous non-ignorable
  2231. # attempts to import non-existent submodules of a package from
  2232. # successful ignorable attempts to import existing global
  2233. # attributes of a package's "__init__" submodule (e.g., the "bar"
  2234. # in "from foo import bar", which is either a non-ignorable
  2235. # submodule of "foo" or an ignorable global attribute of
  2236. # "foo.__init__").
  2237. name = inst.argval
  2238. module.add_global_attr(name)
  2239. elif inst.opname in ('DELETE_NAME', 'DELETE_GLOBAL'):
  2240. # If this is the undeclaration of a previously declared global
  2241. # attribute (e.g., class, variable) in this module, remove that
  2242. # declaration to prevent subsequent lookup. See method docstring
  2243. # for further details.
  2244. name = inst.argval
  2245. module.remove_global_attr_if_found(name)
  2246. prev_insts.append(inst)
  2247. def _process_imports(self, source_module):
  2248. """
  2249. Graph all target modules whose importations were previously parsed from
  2250. the passed source module by a prior call to the `_scan_code()` method
  2251. and methods call by that method (e.g., `_scan_ast()`,
  2252. `_scan_bytecode()`, `_scan_bytecode_stores()`).
  2253. Parameters
  2254. ----------
  2255. source_module : Node
  2256. Graph node of the source module to graph target imports for.
  2257. """
  2258. # If this source module imported no target modules, noop.
  2259. if not source_module._deferred_imports:
  2260. return
  2261. # For each target module imported by this source module...
  2262. for have_star, import_info, kwargs in source_module._deferred_imports:
  2263. # Graph node of the target module specified by the "from" portion
  2264. # of this "from"-style star import (e.g., an import resembling
  2265. # "from {target_module_name} import *") or ignored otherwise.
  2266. target_modules = self._safe_import_hook(*import_info, **kwargs)
  2267. if not target_modules:
  2268. # If _safe_import_hook suppressed the module, quietly drop it.
  2269. # Do not create an ExcludedModule instance, because that might
  2270. # completely suppress the module whereas it might need to be
  2271. # included due to reference from another module (that does
  2272. # not exclude it via hook).
  2273. continue
  2274. target_module = target_modules[0]
  2275. # If this is a "from"-style star import, process this import.
  2276. if have_star:
  2277. #FIXME: Sadly, the current approach to importing attributes
  2278. #from "from"-style star imports is... simplistic. This should
  2279. #be revised as follows. If this target module is:
  2280. #
  2281. #* A package:
  2282. # * Whose "__init__" submodule defines the "__all__" global
  2283. # attribute, only attributes listed by this attribute should
  2284. # be imported.
  2285. # * Else, *NO* attributes should be imported.
  2286. #* A non-package:
  2287. # * Defining the "__all__" global attribute, only attributes
  2288. # listed by this attribute should be imported.
  2289. # * Else, only public attributes whose names are *NOT*
  2290. # prefixed by "_" should be imported.
  2291. source_module.add_global_attrs_from_module(target_module)
  2292. source_module._starimported_ignored_module_names.update(
  2293. target_module._starimported_ignored_module_names)
  2294. # If this target module has no code object and hence is
  2295. # unparsable, record its name for posterity.
  2296. if target_module.code is None:
  2297. target_module_name = import_info[0]
  2298. source_module._starimported_ignored_module_names.add(
  2299. target_module_name)
  2300. # For safety, prevent these imports from being reprocessed.
  2301. source_module._deferred_imports = None
  2302. def _find_module(self, name, path, parent=None):
  2303. """
  2304. 3-tuple describing the physical location of the module with the passed
  2305. name if this module is physically findable _or_ raise `ImportError`.
  2306. This high-level method wraps the low-level `modulegraph.find_module()`
  2307. function with additional support for graph-based module caching.
  2308. Parameters
  2309. ----------
  2310. name : str
  2311. Fully-qualified name of the Python module to be found.
  2312. path : list
  2313. List of the absolute paths of all directories to search for this
  2314. module _or_ `None` if the default path list `self.path` is to be
  2315. searched.
  2316. parent : Node
  2317. Package containing this module if this module is a submodule of a
  2318. package _or_ `None` if this is a top-level module.
  2319. Returns
  2320. ----------
  2321. (filename, loader)
  2322. See `modulegraph._find_module()` for details.
  2323. Raises
  2324. ----------
  2325. ImportError
  2326. If this module is _not_ found.
  2327. """
  2328. if parent is not None:
  2329. # assert path is not None
  2330. fullname = parent.identifier + '.' + name
  2331. else:
  2332. fullname = name
  2333. node = self.find_node(fullname)
  2334. if node is not None:
  2335. self.msg(3, "find_module: already included?", node)
  2336. raise ImportError(name)
  2337. if path is None:
  2338. if name in sys.builtin_module_names:
  2339. return (None, BUILTIN_MODULE)
  2340. path = self.path
  2341. return self._find_module_path(fullname, name, path)
  2342. def _find_module_path(self, fullname, module_name, search_dirs):
  2343. """
  2344. 3-tuple describing the physical location of the module with the passed
  2345. name if this module is physically findable _or_ raise `ImportError`.
  2346. This low-level function is a variant on the standard `imp.find_module()`
  2347. function with additional support for:
  2348. * Multiple search paths. The passed list of absolute paths will be
  2349. iteratively searched for the first directory containing a file
  2350. corresponding to this module.
  2351. * Compressed (e.g., zipped) packages.
  2352. For efficiency, the higher level `ModuleGraph._find_module()` method
  2353. wraps this function with support for module caching.
  2354. Parameters
  2355. ----------
  2356. module_name : str
  2357. Fully-qualified name of the module to be found.
  2358. search_dirs : list
  2359. List of the absolute paths of all directories to search for this
  2360. module (in order). Searching will halt at the first directory
  2361. containing this module.
  2362. Returns
  2363. ----------
  2364. (filename, loader)
  2365. 2-tuple describing the physical location of this module, where:
  2366. * `filename` is the absolute path of this file.
  2367. * `loader` is the import loader.
  2368. In case of a namespace package, this is a NAMESPACE_PACKAGE
  2369. instance
  2370. Raises
  2371. ----------
  2372. ImportError
  2373. If this module is _not_ found.
  2374. """
  2375. self.msgin(4, "_find_module_path <-", fullname, search_dirs)
  2376. # Top-level 2-tuple to be returned.
  2377. path_data = None
  2378. # List of the absolute paths of all directories comprising the
  2379. # namespace package to which this module belongs if any.
  2380. namespace_dirs = []
  2381. try:
  2382. for search_dir in search_dirs:
  2383. # PEP 302-compliant importer making loaders for this directory.
  2384. importer = pkgutil.get_importer(search_dir)
  2385. # If this directory is not importable, continue.
  2386. if importer is None:
  2387. # self.msg(4, "_find_module_path importer not found", search_dir)
  2388. continue
  2389. # Get the PEP 302-compliant loader object loading this module.
  2390. #
  2391. # If this importer defines the PEP 451-compliant find_spec()
  2392. # method, use that, and obtain loader from spec. This should
  2393. # be available on python >= 3.4.
  2394. if hasattr(importer, 'find_spec'):
  2395. loader = None
  2396. spec = importer.find_spec(module_name)
  2397. if spec is not None:
  2398. loader = spec.loader
  2399. namespace_dirs.extend(spec.submodule_search_locations or [])
  2400. # Else if this importer defines the PEP 302-compliant find_loader()
  2401. # method, use that.
  2402. elif hasattr(importer, 'find_loader'):
  2403. loader, loader_namespace_dirs = importer.find_loader(
  2404. module_name)
  2405. namespace_dirs.extend(loader_namespace_dirs)
  2406. # Else if this importer defines the Python 2-specific
  2407. # find_module() method, fall back to that. Despite the method
  2408. # name, this method returns a loader rather than a module.
  2409. elif hasattr(importer, 'find_module'):
  2410. loader = importer.find_module(module_name)
  2411. # Else, raise an exception.
  2412. else:
  2413. raise ImportError(
  2414. "Module %r importer %r loader unobtainable" % (module_name, importer))
  2415. # If this module is not loadable from this directory, continue.
  2416. if loader is None:
  2417. # self.msg(4, "_find_module_path loader not found", search_dir)
  2418. continue
  2419. # Absolute path of this module. If this module resides in a
  2420. # compressed archive, this is the absolute path of this module
  2421. # after extracting this module from that archive and hence
  2422. # should not exist; else, this path should typically exist.
  2423. pathname = None
  2424. # If this loader defines the PEP 302-compliant get_filename()
  2425. # method, preferably call that method first. Most if not all
  2426. # loaders (including zipimporter objects) define this method.
  2427. if hasattr(loader, 'get_filename'):
  2428. pathname = loader.get_filename(module_name)
  2429. # Else if this loader provides a "path" attribute, defer to that.
  2430. elif hasattr(loader, 'path'):
  2431. pathname = loader.path
  2432. # Else, raise an exception.
  2433. else:
  2434. raise ImportError(
  2435. "Module %r loader %r path unobtainable" % (module_name, loader))
  2436. # If no path was found, this is probably a namespace package. In
  2437. # such case, continue collecting namespace directories.
  2438. if pathname is None:
  2439. self.msg(4, "_find_module_path path not found", pathname)
  2440. continue
  2441. # Return such metadata.
  2442. path_data = (pathname, loader)
  2443. break
  2444. # Else if this is a namespace package, return such metadata.
  2445. else:
  2446. if namespace_dirs:
  2447. path_data = (namespace_dirs[0],
  2448. NAMESPACE_PACKAGE(namespace_dirs))
  2449. except UnicodeDecodeError as exc:
  2450. self.msgout(1, "_find_module_path -> unicode error", exc)
  2451. # Ensure that exceptions are logged, as this function is typically
  2452. # called by the import_module() method which squelches ImportErrors.
  2453. except Exception as exc:
  2454. self.msgout(4, "_find_module_path -> exception", exc)
  2455. raise
  2456. # If this module was not found, raise an exception.
  2457. self.msgout(4, "_find_module_path ->", path_data)
  2458. if path_data is None:
  2459. raise ImportError("No module named " + repr(module_name))
  2460. return path_data
  2461. def create_xref(self, out=None):
  2462. global header, footer, entry, contpl, contpl_linked, imports
  2463. if out is None:
  2464. out = sys.stdout
  2465. scripts = []
  2466. mods = []
  2467. for mod in self.iter_graph():
  2468. name = os.path.basename(mod.graphident)
  2469. if isinstance(mod, Script):
  2470. scripts.append((name, mod))
  2471. else:
  2472. mods.append((name, mod))
  2473. scripts.sort()
  2474. mods.sort()
  2475. scriptnames = [sn for sn, m in scripts]
  2476. scripts.extend(mods)
  2477. mods = scripts
  2478. title = "modulegraph cross reference for " + ', '.join(scriptnames)
  2479. print(header % {"TITLE": title}, file=out)
  2480. def sorted_namelist(mods):
  2481. lst = [os.path.basename(mod.graphident) for mod in mods if mod]
  2482. lst.sort()
  2483. return lst
  2484. for name, m in mods:
  2485. content = ""
  2486. if isinstance(m, BuiltinModule):
  2487. content = contpl % {"NAME": name,
  2488. "TYPE": "<i>(builtin module)</i>"}
  2489. elif isinstance(m, Extension):
  2490. content = contpl % {"NAME": name,
  2491. "TYPE": "<tt>%s</tt>" % m.filename}
  2492. else:
  2493. url = urllib.request.pathname2url(m.filename or "")
  2494. content = contpl_linked % {"NAME": name, "URL": url,
  2495. 'TYPE': m.__class__.__name__}
  2496. oute, ince = map(sorted_namelist, self.get_edges(m))
  2497. if oute:
  2498. links = []
  2499. for n in oute:
  2500. links.append(""" <a href="#%s">%s</a>\n""" % (n, n))
  2501. # #8226 = bullet-point; can't use html-entities since the
  2502. # test-suite uses xml.etree.ElementTree.XMLParser, which
  2503. # does't supprot them.
  2504. links = " &#8226; ".join(links)
  2505. content += imports % {"HEAD": "imports", "LINKS": links}
  2506. if ince:
  2507. links = []
  2508. for n in ince:
  2509. links.append(""" <a href="#%s">%s</a>\n""" % (n, n))
  2510. # #8226 = bullet-point; can't use html-entities since the
  2511. # test-suite uses xml.etree.ElementTree.XMLParser, which
  2512. # does't supprot them.
  2513. links = " &#8226; ".join(links)
  2514. content += imports % {"HEAD": "imported by", "LINKS": links}
  2515. print(entry % {"NAME": name, "CONTENT": content}, file=out)
  2516. print(footer, file=out)
  2517. def itergraphreport(self, name='G', flatpackages=()):
  2518. # XXX: Can this be implemented using Dot()?
  2519. nodes = list(map(self.graph.describe_node, self.graph.iterdfs(self)))
  2520. describe_edge = self.graph.describe_edge
  2521. edges = deque()
  2522. packagenodes = set()
  2523. packageidents = {}
  2524. nodetoident = {}
  2525. inpackages = {}
  2526. mainedges = set()
  2527. # XXX - implement
  2528. flatpackages = dict(flatpackages)
  2529. def nodevisitor(node, data, outgoing, incoming):
  2530. if not isinstance(data, Node):
  2531. return {'label': str(node)}
  2532. #if isinstance(d, (ExcludedModule, MissingModule, BadModule)):
  2533. # return None
  2534. s = '<f0> ' + type(data).__name__
  2535. for i, v in enumerate(data.infoTuple()[:1], 1):
  2536. s += '| <f%d> %s' % (i, v)
  2537. return {'label': s, 'shape': 'record'}
  2538. def edgevisitor(edge, data, head, tail):
  2539. # XXX: This method nonsense, the edge
  2540. # data is never initialized.
  2541. if data == 'orphan':
  2542. return {'style': 'dashed'}
  2543. elif data == 'pkgref':
  2544. return {'style': 'dotted'}
  2545. return {}
  2546. yield 'digraph %s {\ncharset="UTF-8";\n' % (name,)
  2547. attr = dict(rankdir='LR', concentrate='true')
  2548. cpatt = '%s="%s"'
  2549. for item in attr.items():
  2550. yield '\t%s;\n' % (cpatt % item,)
  2551. # find all packages (subgraphs)
  2552. for (node, data, outgoing, incoming) in nodes:
  2553. nodetoident[node] = getattr(data, 'graphident', None)
  2554. if isinstance(data, Package):
  2555. packageidents[data.graphident] = node
  2556. inpackages[node] = set([node])
  2557. packagenodes.add(node)
  2558. # create sets for subgraph, write out descriptions
  2559. for (node, data, outgoing, incoming) in nodes:
  2560. # update edges
  2561. for edge in (describe_edge(e) for e in outgoing):
  2562. edges.append(edge)
  2563. # describe node
  2564. yield '\t"%s" [%s];\n' % (
  2565. node,
  2566. ','.join([
  2567. (cpatt % item) for item in
  2568. nodevisitor(node, data, outgoing, incoming).items()
  2569. ]),
  2570. )
  2571. inside = inpackages.get(node)
  2572. if inside is None:
  2573. inside = inpackages[node] = set()
  2574. ident = nodetoident[node]
  2575. if ident is None:
  2576. continue
  2577. pkgnode = packageidents.get(ident[:ident.rfind('.')])
  2578. if pkgnode is not None:
  2579. inside.add(pkgnode)
  2580. graph = []
  2581. subgraphs = {}
  2582. for key in packagenodes:
  2583. subgraphs[key] = []
  2584. while edges:
  2585. edge, data, head, tail = edges.popleft()
  2586. if ((head, tail)) in mainedges:
  2587. continue
  2588. mainedges.add((head, tail))
  2589. tailpkgs = inpackages[tail]
  2590. common = inpackages[head] & tailpkgs
  2591. if not common and tailpkgs:
  2592. usepkgs = sorted(tailpkgs)
  2593. if len(usepkgs) != 1 or usepkgs[0] != tail:
  2594. edges.append((edge, data, head, usepkgs[0]))
  2595. edges.append((edge, 'pkgref', usepkgs[-1], tail))
  2596. continue
  2597. if common:
  2598. common = common.pop()
  2599. if tail == common:
  2600. edges.append((edge, data, tail, head))
  2601. elif head == common:
  2602. subgraphs[common].append((edge, 'pkgref', head, tail))
  2603. else:
  2604. edges.append((edge, data, common, head))
  2605. edges.append((edge, data, common, tail))
  2606. else:
  2607. graph.append((edge, data, head, tail))
  2608. def do_graph(edges, tabs):
  2609. edgestr = tabs + '"%s" -> "%s" [%s];\n'
  2610. # describe edge
  2611. for (edge, data, head, tail) in edges:
  2612. attribs = edgevisitor(edge, data, head, tail)
  2613. yield edgestr % (
  2614. head,
  2615. tail,
  2616. ','.join([(cpatt % item) for item in attribs.items()]),
  2617. )
  2618. for g, edges in subgraphs.items():
  2619. yield '\tsubgraph "cluster_%s" {\n' % (g,)
  2620. yield '\t\tlabel="%s";\n' % (nodetoident[g],)
  2621. for s in do_graph(edges, '\t\t'):
  2622. yield s
  2623. yield '\t}\n'
  2624. for s in do_graph(graph, '\t'):
  2625. yield s
  2626. yield '}\n'
  2627. def graphreport(self, fileobj=None, flatpackages=()):
  2628. if fileobj is None:
  2629. fileobj = sys.stdout
  2630. fileobj.writelines(self.itergraphreport(flatpackages=flatpackages))
  2631. def report(self):
  2632. """Print a report to stdout, listing the found modules with their
  2633. paths, as well as modules that are missing, or seem to be missing.
  2634. """
  2635. print()
  2636. print("%-15s %-25s %s" % ("Class", "Name", "File"))
  2637. print("%-15s %-25s %s" % ("-----", "----", "----"))
  2638. for m in sorted(self.iter_graph(), key=lambda n: n.graphident):
  2639. if isinstance(m, AliasNode):
  2640. print("%-15s %-25s %s" % (type(m).__name__, m.graphident, m.identifier))
  2641. else:
  2642. print("%-15s %-25s %s" % (type(m).__name__, m.graphident, m.filename or ""))
  2643. def _replace_paths_in_code(self, co):
  2644. new_filename = original_filename = os.path.normpath(co.co_filename)
  2645. for f, r in self.replace_paths:
  2646. f = os.path.join(f, '')
  2647. r = os.path.join(r, '')
  2648. if original_filename.startswith(f):
  2649. new_filename = r + original_filename[len(f):]
  2650. break
  2651. else:
  2652. return co
  2653. consts = list(co.co_consts)
  2654. for i in range(len(consts)):
  2655. if isinstance(consts[i], type(co)):
  2656. consts[i] = self._replace_paths_in_code(consts[i])
  2657. return co.replace(co_consts=tuple(consts), co_filename=new_filename)