@@ -1935,25 +1935,31 @@ def _resolve_cross_file_imports(
19351935 if src_path .stem not in bare_to_qualified :
19361936 bare_to_qualified [src_path .stem ] = fq_stem
19371937
1938- # Pass 2: for each file, find `from .X import A, B, C` and resolve
1938+ # Pass 2: for each file, find `from .X import A, B, C`, then attribute the
1939+ # `uses` edge to the specific local symbol (class OR function) whose body
1940+ # actually references the imported name — not to every class that merely
1941+ # shares the file (#2652). The edge is anchored at the real reference, not
1942+ # the import line, so `source_location` points at genuine corroboration.
19391943 new_edges : list [dict ] = []
1940- stem_to_path : dict [str , Path ] = {_file_stem (p ): p for p in paths }
19411944
19421945 for file_result , path in zip (per_file , paths ):
1943- stem = _file_stem (path )
19441946 str_path = str (path )
19451947
1946- # Find all classes defined in this file (the importers).
1947- # Excludes rationale nodes whose labels happen not to end in ")" or ".py"
1948- # but which must never be treated as importing entities (#563).
1949- local_classes = [
1950- n ["id" ] for n in file_result .get ("nodes" , [])
1951- if n .get ("source_file" ) == str_path
1952- and not n ["label" ].endswith ((")" , ".py" ))
1953- and n ["id" ] != _make_id (stem ) # exclude file-level node
1954- and n .get ("file_type" ) != "rationale"
1955- ]
1956- if not local_classes :
1948+ # Map each local symbol (class or function) to its node id, keyed by the
1949+ # bare symbol name. Function labels end in "()"; the file node ends in
1950+ # ".py"; rationale nodes never import (#563). First writer wins on a
1951+ # name collision (inherently ambiguous within a file).
1952+ name_to_nid : dict [str , str ] = {}
1953+ for n in file_result .get ("nodes" , []):
1954+ if n .get ("source_file" ) != str_path or n .get ("file_type" ) == "rationale" :
1955+ continue
1956+ label = n .get ("label" , "" )
1957+ if not label or label .endswith (".py" ):
1958+ continue
1959+ sym_name = label [:- 2 ] if label .endswith ("()" ) else label
1960+ if sym_name and sym_name not in name_to_nid :
1961+ name_to_nid [sym_name ] = n ["id" ]
1962+ if not name_to_nid :
19571963 continue
19581964
19591965 # Parse imports from this file
@@ -1963,75 +1969,103 @@ def _resolve_cross_file_imports(
19631969 except Exception :
19641970 continue
19651971
1966- def walk_imports (node ) -> None :
1967- if node .type == "import_from_statement" :
1968- # Find the module name - handles both absolute and relative imports.
1969- # Relative: `from .models import X` → relative_import → dotted_name
1970- # Absolute: `from models import X` → module_name field
1971- # target_fq is the directory-qualified stem used as the key in
1972- # stem_to_entities. Relative imports are resolved exactly via the
1973- # importing file's directory; absolute imports fall back to the
1974- # bare-stem secondary index (first-writer-wins when names collide).
1975- target_fq : str | None = None
1976- for child in node .children :
1977- if child .type == "relative_import" :
1978- for sub in child .children :
1979- if sub .type == "dotted_name" :
1980- raw = source [sub .start_byte :sub .end_byte ].decode ("utf-8" , errors = "replace" )
1981- bare = raw .split ("." )[- 1 ]
1982- # Resolve relative import to exact qualified stem.
1983- candidate = path .parent / f"{ bare } .py"
1984- target_fq = _file_stem (candidate )
1985- break
1986- break
1987- if child .type == "dotted_name" and target_fq is None :
1988- raw = source [child .start_byte :child .end_byte ].decode ("utf-8" , errors = "replace" )
1989- bare = raw .split ("." )[- 1 ]
1990- target_fq = bare_to_qualified .get (bare )
1972+ # local_name -> target node id (local_name honours `import X as Y`, so a
1973+ # reference to the alias in the body still attributes correctly).
1974+ import_targets : dict [str , str ] = {}
1975+ # referenced name -> {source symbol nid: first reference line}
1976+ ref_sources : dict [str , dict [str , int ]] = {}
1977+
1978+ def _text (n ) -> str :
1979+ return source [n .start_byte :n .end_byte ].decode ("utf-8" , errors = "replace" )
1980+
1981+ def resolve_import (node ) -> None :
1982+ # Find the module name - handles both absolute and relative imports.
1983+ # Relative: `from .models import X` → relative_import → dotted_name
1984+ # Absolute: `from models import X` → module_name field
1985+ # target_fq is the directory-qualified stem used as the key in
1986+ # stem_to_entities. Relative imports are resolved exactly via the
1987+ # importing file's directory; absolute imports fall back to the
1988+ # bare-stem secondary index (first-writer-wins when names collide).
1989+ target_fq : str | None = None
1990+ for child in node .children :
1991+ if child .type == "relative_import" :
1992+ for sub in child .children :
1993+ if sub .type == "dotted_name" :
1994+ bare = _text (sub ).split ("." )[- 1 ]
1995+ candidate = path .parent / f"{ bare } .py"
1996+ target_fq = _file_stem (candidate )
1997+ break
1998+ break
1999+ if child .type == "dotted_name" and target_fq is None :
2000+ bare = _text (child ).split ("." )[- 1 ]
2001+ target_fq = bare_to_qualified .get (bare )
19912002
1992- if not target_fq or target_fq not in stem_to_entities :
1993- return
2003+ if not target_fq or target_fq not in stem_to_entities :
2004+ return
19942005
1995- # Collect imported names: dotted_name children of import_from_statement
1996- # that come AFTER the 'import' keyword token.
1997- imported_names : list [str ] = []
1998- past_import_kw = False
1999- for child in node .children :
2000- if child .type == "import" :
2001- past_import_kw = True
2002- continue
2003- if not past_import_kw :
2004- continue
2005- if child .type == "dotted_name" :
2006- imported_names .append (
2007- source [child .start_byte :child .end_byte ].decode ("utf-8" , errors = "replace" )
2008- )
2009- elif child .type == "aliased_import" :
2010- # `import X as Y` - take the original name
2011- name_node = child .child_by_field_name ("name" )
2012- if name_node :
2013- imported_names .append (
2014- source [name_node .start_byte :name_node .end_byte ].decode ("utf-8" , errors = "replace" )
2015- )
2006+ # Imported names come AFTER the 'import' keyword token. For
2007+ # `import X as Y` the target is found via X but the body uses Y.
2008+ past_import_kw = False
2009+ for child in node .children :
2010+ if child .type == "import" :
2011+ past_import_kw = True
2012+ continue
2013+ if not past_import_kw :
2014+ continue
2015+ imported_name : str | None = None
2016+ local_name : str | None = None
2017+ if child .type == "dotted_name" :
2018+ imported_name = local_name = _text (child )
2019+ elif child .type == "aliased_import" :
2020+ name_node = child .child_by_field_name ("name" )
2021+ alias_node = child .child_by_field_name ("alias" )
2022+ if name_node is not None :
2023+ imported_name = _text (name_node )
2024+ local_name = _text (alias_node ) if alias_node is not None else imported_name
2025+ if not imported_name or not local_name :
2026+ continue
2027+ tgt_nid = stem_to_entities [target_fq ].get (imported_name )
2028+ if tgt_nid :
2029+ import_targets [local_name ] = tgt_nid
20162030
2017- line = node .start_point [0 ] + 1
2018- for name in imported_names :
2019- tgt_nid = stem_to_entities [target_fq ].get (name )
2020- if tgt_nid :
2021- for src_class_nid in local_classes :
2022- new_edges .append ({
2023- "source" : src_class_nid ,
2024- "target" : tgt_nid ,
2025- "relation" : "uses" ,
2026- "confidence" : "INFERRED" ,
2027- "source_file" : str_path ,
2028- "source_location" : f"L{ line } " ,
2029- "weight" : 0.8 ,
2030- })
2031+ def visit (node , current_nid : str | None ) -> None :
2032+ # Identifiers inside an import statement are the import itself, not a
2033+ # real use — resolve the import here and don't descend into it.
2034+ if node .type == "import_from_statement" :
2035+ resolve_import (node )
2036+ return
2037+ # Attribute references to the top-level symbol that contains them: a
2038+ # class is a unit (a reference inside one of its methods counts for
2039+ # the class, matching the documented DigestAuth->Response edge), and
2040+ # a module-level function is its own source. Only set at module scope
2041+ # (current_nid is None) so nested defs never override the container.
2042+ if current_nid is None and node .type in ("class_definition" , "function_definition" ):
2043+ name_node = node .child_by_field_name ("name" )
2044+ if name_node is not None :
2045+ mapped = name_to_nid .get (_text (name_node ))
2046+ if mapped is not None :
2047+ current_nid = mapped
2048+ if node .type == "identifier" and current_nid is not None :
2049+ slot = ref_sources .setdefault (_text (node ), {})
2050+ slot .setdefault (current_nid , node .start_point [0 ] + 1 )
20312051 for child in node .children :
2032- walk_imports (child )
2052+ visit (child , current_nid )
2053+
2054+ visit (tree .root_node , None )
20332055
2034- walk_imports (tree .root_node )
2056+ for name , tgt_nid in import_targets .items ():
2057+ for src_nid , line in ref_sources .get (name , {}).items ():
2058+ if src_nid == tgt_nid :
2059+ continue
2060+ new_edges .append ({
2061+ "source" : src_nid ,
2062+ "target" : tgt_nid ,
2063+ "relation" : "uses" ,
2064+ "confidence" : "INFERRED" ,
2065+ "source_file" : str_path ,
2066+ "source_location" : f"L{ line } " ,
2067+ "weight" : 0.8 ,
2068+ })
20352069
20362070 return new_edges
20372071
0 commit comments