99import concurrent .futures
1010import hashlib
1111import multiprocessing
12+ from collections import Counter
1213from collections .abc import Callable , Iterable , Mapping , Sequence
1314from dataclasses import dataclass , field , replace
1415from pathlib import Path
8889 TemplateCallsAnalysis ,
8990 build_module_graph ,
9091 discover_sources ,
92+ name_modules ,
9193 project_symbol ,
9294)
9395from coretrace_python .ir import PYIR_SCHEMA_VERSION
@@ -371,7 +373,11 @@ def analyze_project(
371373 strongly connected components of the module graph, imports first; with ``jobs``
372374 above one the components of a wave are analysed in that many processes (§29).
373375 ``advisory_files`` add to the ``advisories.json`` at ``root``; ``policy_file``
374- replaces the ``coretrace-policy.toml`` there."""
376+ replaces the ``coretrace-policy.toml`` there.
377+
378+ Every module is known by the name ``name_modules`` gives its file: its import name,
379+ or its path from the root when another file has that import name. Such files carry
380+ an ``ambiguous-module`` note and are covered as ``ambiguous``."""
375381
376382 if jobs < 1 :
377383 raise ValueError ("jobs must be at least 1" )
@@ -398,18 +404,18 @@ def analyze_project(
398404 files : dict [str , SourceFile ] = {}
399405 unreadable : list [tuple [Path , str ]] = []
400406 coverage : list [FileCoverage ] = []
401- discovered = discover_sources (root , sources , unreadable )
407+ named = name_modules ( root , discover_sources (root , sources , unreadable ) )
402408 for path , reason in unreadable :
403409 findings .append (_note ("syntax-error" , f"{ path } : { reason } " , sources .add_source (str (path ), "" ), 1 ))
404410 coverage .append (FileCoverage (str (path ), "unreadable" , 0 , 0 ))
405- for source in discovered :
411+ for name , source in named . items () :
406412 try :
407- modules [source . module_name ] = build_hir (source )
413+ modules [name ] = build_hir (source )
408414 except (ParseError , HIRBuildError ) as error :
409415 findings .append (_note ("syntax-error" , str (error ), source , 1 ))
410416 coverage .append (FileCoverage (str (source .source_id ), "syntax-error" , 0 , 0 ))
411417 continue
412- files [source . module_name ] = source
418+ files [name ] = source
413419
414420 managers = {name : _register_all (module ) for name , module in modules .items ()}
415421 probe = next (iter (managers .values ()), None ) or _register_all (build_hir (sources .add_source ("<empty>" , "" )))
@@ -439,6 +445,8 @@ def analyze_project(
439445 graph = build_module_graph (
440446 {name : files [name ] for name in analysable }, {name : modules [name ] for name in analysable }, imports
441447 )
448+ shared = _shared_names (graph )
449+ findings .extend (_ambiguity_notes (graph , shared , root ))
442450 routes : dict [SymbolId , EntryPoint ] = {}
443451 for name in sorted (analysable ):
444452 for symbol , registered in _routes_of (analysable [name ]).items ():
@@ -515,15 +523,16 @@ def analyze_project(
515523 if pool is not None :
516524 pool .shutdown ()
517525
518- index = _seed (results , graph , frozenset () )
526+ index = _index (results , { name : name for name in results } )
519527 call_graphs : dict [str , CallGraph ] = {}
520528 functions : dict [str , tuple [ModuleFunction , ...]] = {}
521529 for name in sorted (analysable ):
522530 entry = results [name ]
523531 findings .extend (entry .findings )
524532 unsupported = sum (1 for f in entry .findings if f .rule_id == "unsupported-syntax" )
533+ status = "ambiguous" if files [name ].module_name in shared else "analysed"
525534 coverage .append (
526- FileCoverage (str (files [name ].source_id ), "analysed" , len (entry .functions ), len (entry .functions ) - unsupported )
535+ FileCoverage (str (files [name ].source_id ), status , len (entry .functions ), len (entry .functions ) - unsupported )
527536 )
528537 functions [name ] = entry .functions
529538 sites : dict [str , list [CallSite ]] = {function .name : [] for function in entry .functions }
@@ -645,24 +654,76 @@ def _advisory_paths(root: Path, advisory_files: Sequence[Path]) -> tuple[Path, .
645654 return (* ([default ] if default .is_file () else []), * advisory_files )
646655
647656
657+ def _shared_names (graph : ModuleGraph ) -> dict [str , list [str ]]:
658+ """The import names several analysable files have, each with those files' modules."""
659+
660+ by_name : dict [str , list [str ]] = {}
661+ for name in graph .modules :
662+ by_name .setdefault (graph .source (name ).module_name , []).append (name )
663+ return {import_name : names for import_name , names in by_name .items () if len (names ) > 1 }
664+
665+
666+ def _ambiguity_notes (graph : ModuleGraph , shared : Mapping [str , list [str ]], root : Path ) -> list [Finding ]:
667+ """One note on each file whose import name another file shares, since a symbol of
668+ that name may denote a function of either, and one on each importer whose import of
669+ such a name no root resolved, since calls through it are not followed."""
670+
671+ def located (name : str ) -> str :
672+ return _located (_path_of (graph .source (name )), root )
673+
674+ notes : list [Finding ] = []
675+ for import_name , names in sorted (shared .items ()):
676+ for name in names :
677+ others = ", " .join (located (other ) for other in names if other != name )
678+ message = (
679+ f"{ located (name )} is the module '{ import_name } ' like { others } : a symbol "
680+ f"python.{ import_name } .* may name a function of either, and an import of "
681+ f"'{ import_name } ' resolves only from its own root"
682+ )
683+ notes .append (_note ("ambiguous-module" , message , graph .source (name ), 1 ))
684+ for name in graph .modules :
685+ for import_name in sorted (graph .unresolved (name )):
686+ candidates = " or " .join (located (other ) for other in shared [import_name ])
687+ message = f"'{ import_name } ' imported here is { candidates } : calls into it are not followed"
688+ notes .append (_note ("ambiguous-module" , message , graph .source (name ), 1 ))
689+ return notes
690+
691+
648692def _seed (results : Mapping [str , CachedModule ], graph : ModuleGraph , component : frozenset [str ]) -> SummaryIndex :
649693 """The summaries a component starts from: those of every module it imports,
650- transitively, all final by the time its wave runs; the whole index for no component."""
651-
652- if component :
653- wanted : set [str ] = set ()
654- pending = list (component )
655- while pending :
656- for imported in graph .imports (pending .pop ()):
657- if imported in results and imported not in wanted :
658- wanted .add (imported )
659- pending .append (imported )
660- else :
661- wanted = set (results )
694+ transitively, all final by the time its wave runs, each under the import name the
695+ component's code refers to it by. Of several files with one import name, only the
696+ one a member imports directly, resolved in its own root, goes under that name: the
697+ others are reached through summaries that inline them already, and a name no
698+ member's root resolved is followed into neither file."""
699+
700+ wanted : set [str ] = set ()
701+ pending = list (component )
702+ while pending :
703+ for imported in graph .imports (pending .pop ()):
704+ if imported in results and imported not in wanted :
705+ wanted .add (imported )
706+ pending .append (imported )
707+ direct = {imported for member in component for imported in graph .imports (member )}
708+ by_import : dict [str , list [str ]] = {}
709+ for name in wanted :
710+ by_import .setdefault (graph .source (name ).module_name , []).append (name )
711+ names : dict [str , str ] = {}
712+ for import_name , modules in by_import .items ():
713+ chosen = modules if len (modules ) == 1 else [name for name in modules if name in direct ]
714+ if len (chosen ) == 1 :
715+ names [chosen [0 ]] = import_name
716+ return _index (results , names )
717+
718+
719+ def _index (results : Mapping [str , CachedModule ], names : Mapping [str , str ]) -> SummaryIndex :
720+ """The summaries of the modules in ``names``, each function under the project symbol
721+ of the module name given for its module."""
722+
662723 return SummaryIndex (
663724 {
664- project_symbol (name , function ): summary
665- for name in sorted (wanted )
725+ project_symbol (module , function ): summary
726+ for name , module in sorted (names . items () )
666727 for function , summary in results [name ].summaries .items ()
667728 }
668729 )
@@ -675,8 +736,12 @@ def _analyse_managers(
675736 affected : Affected ,
676737) -> dict [str , CachedModule ]:
677738 """Analyse one component: iterate its summaries to a fixpoint over ``seed`` (§21),
678- then extract what the rest of the run needs from each module."""
739+ then extract what the rest of the run needs from each module. Each member registers
740+ its functions under its import name, what the others' code refers to it by; a name
741+ two members share, a cycle across roots, is registered by neither."""
679742
743+ counts = Counter (manager .module .name for manager in managers .values ())
744+ names = {name : manager .module .name for name , manager in managers .items () if counts [manager .module .name ] == 1 }
680745 index = seed
681746 for manager in managers .values ():
682747 manager .provide (ProjectSummaries , index )
@@ -685,9 +750,9 @@ def _analyse_managers(
685750 {
686751 ** seed .summaries ,
687752 ** {
688- project_symbol (name , function ): summary
689- for name , manager in managers .items ()
690- for function , summary in _summaries_of (manager ).items ()
753+ project_symbol (module , function ): summary
754+ for name , module in names .items ()
755+ for function , summary in _summaries_of (managers [ name ] ).items ()
691756 },
692757 }
693758 )
@@ -702,8 +767,9 @@ def _analyse_managers(
702767
703768@dataclass (frozen = True )
704769class _Batch :
705- """One component handed to a worker process: it rebuilds the configuration from the
706- project root and the plugin roots, so only paths and the imported summaries travel."""
770+ """One component handed to a worker process, its files under the engine's module
771+ names: it rebuilds the configuration from the project root and the plugin roots, so
772+ only paths and the imported summaries travel."""
707773
708774 root : Path
709775 plugin_roots : tuple [Path , ...]
0 commit comments