144144 _resolve_lua_import_target ,
145145 _probe_python_module_candidate ,
146146 _resolve_python_module_path ,
147+ _resolve_python_namespace_dir ,
147148 _resolve_tsconfig_alias ,
148149 _resolve_workspace_import ,
149150 _source_key ,
@@ -181,8 +182,12 @@ def _raise_recursion_limit() -> None:
181182 sys .setrecursionlimit (_RECURSION_LIMIT )
182183
183184
184- def _safe_extract (extractor : Callable , path : Path ) -> dict :
185+ def _safe_extract (
186+ extractor : Callable , path : Path , * , scan_root : Path | None = None
187+ ) -> dict :
185188 try :
189+ if extractor is extract_python :
190+ return extractor (path , root = scan_root )
186191 return extractor (path )
187192 except RecursionError :
188193 print (f" warning: skipped { path } (recursion limit exceeded)" , file = sys .stderr , flush = True )
@@ -436,15 +441,51 @@ def _resolve_name(node, source: bytes, config: LanguageConfig) -> str | None:
436441
437442# ── Import handlers ───────────────────────────────────────────────────────────
438443
439- def _import_python (node , source : bytes , file_nid : str , stem : str , edges : list , str_path : str , scope_stack : list [str ] | None = None ) -> None :
444+ def _import_python (
445+ node , source : bytes , file_nid : str , stem : str , edges : list , str_path : str ,
446+ scope_stack : list [str ] | None = None , scan_root : Path | None = None ,
447+ ) -> None :
440448 t = node .type
449+ current_path = Path (str_path )
450+ try :
451+ current_path = current_path .resolve ()
452+ except OSError :
453+ pass
454+ root = Path (scan_root ) if scan_root is not None else current_path .parent
455+ try :
456+ root = root .resolve ()
457+ except OSError :
458+ pass
441459 if t == "import_statement" :
442460 for child in node .children :
443461 if child .type in ("dotted_name" , "aliased_import" ):
444462 raw = _read_text (child , source )
445463 raw_module , _ , raw_alias = raw .partition (" as " )
446464 module_name = raw_module .strip ().lstrip ("." )
447- tgt_nid = _make_id (module_name )
465+ target_path = _resolve_python_module_path (
466+ module_name , current_path , root , level = 0
467+ )
468+ # The importer-relative resolver can find a module under one
469+ # nested sys.path root even when the scan contains another file
470+ # with the same dotted name under a different root. Keep those
471+ # cases for the root-wide alias pass, which refuses ambiguous
472+ # aliases; use a direct scan-root hit here.
473+ root_target = _resolve_python_module_path (
474+ module_name , root , root , level = 0
475+ )
476+ if root_target is None or target_path != root_target :
477+ target_path = None
478+ if target_path is not None :
479+ try :
480+ if target_path .resolve () == current_path :
481+ target_path = None
482+ except OSError :
483+ pass
484+ tgt_nid = (
485+ _make_id (str (target_path ))
486+ if target_path is not None
487+ else _make_id (module_name )
488+ )
448489 edge = {
449490 "source" : file_nid ,
450491 "target" : tgt_nid ,
@@ -455,6 +496,8 @@ def _import_python(node, source: bytes, file_nid: str, stem: str, edges: list, s
455496 "source_location" : f"L{ node .start_point [0 ] + 1 } " ,
456497 "weight" : 1.0 ,
457498 }
499+ if target_path is not None :
500+ edge ["target_file" ] = str (target_path )
458501 if raw_alias :
459502 # `import pkg.mod as alias` binds the local name `alias`, not
460503 # `mod`'s own stem, to the module -- stash it so the cross-file
@@ -471,55 +514,35 @@ def _import_python(node, source: bytes, file_nid: str, stem: str, edges: list, s
471514 # Relative import - resolve to full path so IDs match file node IDs
472515 dots = len (raw ) - len (raw .lstrip ("." ))
473516 module_name = raw .lstrip ("." )
474- base = Path (str_path ).parent
475- for _ in range (dots - 1 ):
476- base = base .parent
477- # A relative import can name a subpackage (a directory with an
478- # __init__.py), not a module file. Probing the candidate on disk
479- # (mirroring the companion `imports` edge's
480- # _resolve_python_module_path) resolves `graphs` -> graphs/__init__.py
481- # instead of a nonexistent graphs.py: without it the target keeps an
482- # absolute-path-derived slug that the target_file stamp below can't
483- # heal, so it dangles per-checkout (#2455).
484- candidate = base / module_name .replace ("." , "/" ) if module_name else base
485- resolved = _probe_python_module_candidate (candidate )
486- if resolved is not None :
487- target_path = resolved
488- else :
517+ target_path = _resolve_python_module_path (
518+ module_name , current_path , root , level = dots
519+ )
520+ if target_path is None :
521+ base = current_path .parent
522+ for _ in range (dots - 1 ):
523+ base = base .parent
489524 rel = (module_name .replace ("." , "/" ) + ".py" ) if module_name else "__init__.py"
490525 target_path = base / rel
491526 tgt_nid = _make_id (str (target_path ))
492527 else :
493- # Absolute imports need the same package/file probing as the
494- # relative arm. Keeping the dotted-name slug here makes
495- # ``from pkg.sub import thing`` point at ``pkg_sub`` even when
496- # the real node is ``pkg_sub_init``; the symbol-resolution pass
497- # may add a second, correct edge, but it cannot repair this
498- # malformed file-level edge (#3723). Search upward from the
499- # importer and only probe non-package ancestors, mirroring the
500- # resolver's sys.path-root rule without requiring the scan root
501- # at per-file extraction time.
502- module_rel = raw .replace ("." , "/" )
503- current_path = Path (str_path )
504- try :
505- current_path = current_path .resolve ()
506- except OSError :
507- pass
508- for ancestor in (current_path .parent , * current_path .parent .parents ):
509- if (ancestor / "__init__.py" ).is_file ():
510- continue
511- resolved = _probe_python_module_candidate (ancestor / module_rel )
512- if resolved is not None :
513- try :
514- if resolved .resolve () == current_path :
515- # An external import can share the importing
516- # file's basename; never turn that coincidence
517- # into a self-loop.
518- continue
519- except OSError :
520- pass
521- target_path = resolved
522- break
528+ # Use the shared scan-root-aware resolver for absolute imports.
529+ # It stops at the corpus boundary and handles package roots the
530+ # same way as symbol resolution. A namespace package has no file
531+ # node of its own; the corpus pass will emit edges to any
532+ # imported submodules that exist on disk.
533+ target_path = _resolve_python_module_path (raw , current_path , root , level = 0 )
534+ if target_path is None and _resolve_python_namespace_dir (
535+ raw , current_path , root , level = 0
536+ ) is not None :
537+ return
538+ if target_path is not None :
539+ try :
540+ if target_path .resolve () == current_path :
541+ # Do not turn an import of the current file into a
542+ # self-loop.
543+ target_path = None
544+ except OSError :
545+ pass
523546 tgt_nid = _make_id (str (target_path )) if target_path is not None else _make_id (raw )
524547 edge = {
525548 "source" : file_nid ,
@@ -1726,9 +1749,9 @@ def placeholder(match: "re.Match[bytes]") -> bytes:
17261749
17271750# ── Public API ────────────────────────────────────────────────────────────────
17281751
1729- def extract_python (path : Path ) -> dict :
1752+ def extract_python (path : Path , * , root : Path | None = None ) -> dict :
17301753 """Extract classes, functions, and imports from a .py file via tree-sitter AST."""
1731- result = _extract_generic (path , _PYTHON_CONFIG )
1754+ result = _extract_generic (path , _PYTHON_CONFIG , scan_root = root )
17321755 if "error" not in result :
17331756 _extract_python_rationale (path , result )
17341757 return result
@@ -6629,7 +6652,7 @@ def _safe_extract_with_xaml_root(extractor, path: Path, root: Path) -> dict:
66296652 previous_root = _XAML_ACTIVE_EXTRACT_ROOT
66306653 _XAML_ACTIVE_EXTRACT_ROOT = root .resolve ()
66316654 try :
6632- return _safe_extract (extractor , path )
6655+ return _safe_extract (extractor , path , scan_root = root )
66336656 finally :
66346657 _XAML_ACTIVE_EXTRACT_ROOT = previous_root
66356658
0 commit comments