66across different programming languages in a repository.
77"""
88
9- from typing import Dict , List
9+ from typing import Dict , List , Optional
1010import logging
1111import traceback
1212import time
1313import signal
14+ import re
15+ from collections import defaultdict
1416from pathlib import Path
1517from contextlib import contextmanager
1618from codewiki .src .be .dependency_analyzer .models .core import Node , CallRelationship
1719from codewiki .src .be .dependency_analyzer .utils .patterns import CODE_EXTENSIONS
1820from codewiki .src .be .dependency_analyzer .utils .security import safe_open_text
21+ from codewiki .src .be .dependency_analyzer .utils .external_symbols import (
22+ CPP_STANDARD_HEADERS ,
23+ is_external_symbol ,
24+ )
1925
2026logger = logging .getLogger (__name__ )
2127
@@ -69,6 +75,7 @@ def analyze_code_files(self, code_files: List[Dict], base_dir: str) -> Dict:
6975
7076 self .functions = {}
7177 self .call_relationships = []
78+ code_files = self ._route_contextual_headers (code_files , base_dir )
7279
7380 files_analyzed = 0
7481 files_failed = 0
@@ -149,6 +156,40 @@ def traverse(tree):
149156 traverse (file_tree )
150157 return code_files
151158
159+ def _route_contextual_headers (self , code_files : List [Dict ], base_dir : str ) -> List [Dict ]:
160+ """Route ambiguous .h headers as C++ when repo or file content indicates C++."""
161+ cpp_extensions = {".cpp" , ".cc" , ".cxx" , ".c++" , ".hpp" , ".hxx" , ".h++" }
162+ has_cpp_files = any (
163+ file_info .get ("extension" , "" ).lower () in cpp_extensions
164+ or file_info .get ("language" ) == "cpp"
165+ for file_info in code_files
166+ )
167+
168+ routed_files = []
169+ for file_info in code_files :
170+ routed = dict (file_info )
171+ if routed .get ("extension" , "" ).lower () == ".h" :
172+ if has_cpp_files or self ._header_has_cpp_signal (base_dir , routed ["path" ]):
173+ routed ["language" ] = "cpp"
174+ routed_files .append (routed )
175+ return routed_files
176+
177+ def _header_has_cpp_signal (self , base_dir : str , relative_path : str ) -> bool :
178+ base = Path (base_dir )
179+ try :
180+ content = safe_open_text (base , base / relative_path )
181+ except Exception :
182+ return False
183+
184+ if re .search (r"\b(namespace|class|template|typename|public|private|protected)\b" , content ):
185+ return True
186+ if "::" in content or "std::" in content :
187+ return True
188+ for header in CPP_STANDARD_HEADERS :
189+ if f"#include <{ header } >" in content :
190+ return True
191+ return False
192+
152193 def _analyze_code_file (self , repo_dir : str , file_info : Dict ):
153194 """
154195 Analyze a single code file based on its language.
@@ -406,42 +447,120 @@ def _resolve_call_relationships(self):
406447 Attempts to match function calls to actual function definitions,
407448 handling cross-language calls where possible.
408449 """
409- func_lookup = {}
450+ indexes = self . _build_resolution_indexes ()
410451 for func_id , func_info in self .functions .items ():
411- func_lookup [func_id ] = func_id
412- func_lookup [func_info .name ] = func_id
413- if func_info .component_id :
414- func_lookup [func_info .component_id ] = func_id
415- # Extract short name: handle both new (path::Name) and legacy (path.Name) formats
416- if "::" in func_info .component_id :
417- method_name = func_info .component_id .split ("::" )[- 1 ]
418- else :
419- method_name = func_info .component_id .split ("." )[- 1 ]
420- if method_name not in func_lookup :
421- func_lookup [method_name ] = func_id
452+ if not func_info .language :
453+ file_ext = Path (func_info .file_path ).suffix .lower ()
454+ func_info .language = CODE_EXTENSIONS .get (file_ext )
422455
423456 resolved_count = 0
424457 for relationship in self .call_relationships :
425- callee_name = relationship .callee
458+ if relationship .is_resolved and relationship .callee in self .functions :
459+ continue
426460
427- if callee_name in func_lookup :
428- relationship .callee = func_lookup [callee_name ]
461+ resolved_id = self ._resolve_callee (relationship , indexes )
462+ if resolved_id :
463+ relationship .callee = resolved_id
429464 relationship .is_resolved = True
430465 resolved_count += 1
431- elif "::" in callee_name or "." in callee_name :
432- if callee_name in func_lookup :
433- relationship .callee = func_lookup [callee_name ]
434- relationship .is_resolved = True
435- resolved_count += 1
436- else :
437- if "::" in callee_name :
438- method_name = callee_name .split ("::" )[- 1 ]
439- else :
440- method_name = callee_name .split ("." )[- 1 ]
441- if method_name in func_lookup :
442- relationship .callee = func_lookup [method_name ]
443- relationship .is_resolved = True
444- resolved_count += 1
466+
467+ self .call_relationships = [
468+ relationship
469+ for relationship in self .call_relationships
470+ if relationship .is_resolved
471+ or not is_external_symbol (
472+ self ._caller_language (relationship .caller ),
473+ relationship .callee ,
474+ )
475+ ]
476+
477+ def _build_resolution_indexes (self ) -> Dict [str , Dict [str , List [str ]]]:
478+ exact : Dict [str , List [str ]] = defaultdict (list )
479+ simple : Dict [str , List [str ]] = defaultdict (list )
480+
481+ def add (index : Dict [str , List [str ]], key : Optional [str ], func_id : str ) -> None :
482+ if key and func_id not in index [key ]:
483+ index [key ].append (func_id )
484+
485+ for func_id , func_info in self .functions .items ():
486+ add (exact , func_id , func_id )
487+ add (exact , func_info .component_id , func_id )
488+ add (exact , func_info .qualified_name , func_id )
489+ add (exact , func_info .name , func_id )
490+
491+ names = {func_info .name }
492+ if func_info .component_id :
493+ names .add (func_info .component_id .split ("::" )[- 1 ])
494+ if func_info .qualified_name :
495+ names .add (func_info .qualified_name .split ("." )[- 1 ])
496+ parts = func_info .qualified_name .split ("." )
497+ if len (parts ) >= 2 :
498+ names .add ("." .join (parts [- 2 :]))
499+
500+ for name in names :
501+ add (simple , name , func_id )
502+ if name and "." in name :
503+ add (simple , name .split ("." )[- 1 ], func_id )
504+
505+ return {"exact" : exact , "simple" : simple }
506+
507+ def _resolve_callee (self , relationship : CallRelationship , indexes : Dict [str , Dict [str , List [str ]]]) -> Optional [str ]:
508+ callee_name = relationship .callee
509+
510+ exact_match = self ._unique_match (indexes ["exact" ], callee_name )
511+ if exact_match :
512+ return exact_match
513+
514+ if "::" in callee_name :
515+ suffix = callee_name .split ("::" )[- 1 ]
516+ exact_match = self ._unique_match (indexes ["exact" ], suffix )
517+ if exact_match :
518+ return exact_match
519+ simple_match = self ._unique_match (indexes ["simple" ], suffix )
520+ if simple_match :
521+ return simple_match
522+
523+ if "." in callee_name :
524+ exact_match = self ._unique_match (indexes ["exact" ], callee_name )
525+ if exact_match :
526+ return exact_match
527+ simple_match = self ._unique_match (indexes ["simple" ], callee_name )
528+ if simple_match :
529+ return simple_match
530+ tail_match = self ._unique_match (indexes ["simple" ], callee_name .split ("." )[- 1 ])
531+ if tail_match :
532+ return tail_match
533+
534+ caller = self .functions .get (relationship .caller )
535+ if caller and caller .language == "java" and "." not in callee_name :
536+ package = self ._java_package_for_node (caller )
537+ if package :
538+ same_package_match = self ._unique_match (indexes ["exact" ], f"{ package } .{ callee_name } " )
539+ if same_package_match :
540+ return same_package_match
541+
542+ return self ._unique_match (indexes ["simple" ], callee_name )
543+
544+ def _unique_match (self , index : Dict [str , List [str ]], key : str ) -> Optional [str ]:
545+ matches = index .get (key , [])
546+ return matches [0 ] if len (matches ) == 1 else None
547+
548+ def _java_package_for_node (self , node : Node ) -> str :
549+ qualified_name = node .qualified_name or ""
550+ parts = qualified_name .split ("." )
551+ if len (parts ) < 2 :
552+ return ""
553+ if node .component_type == "method" and len (parts ) >= 3 :
554+ return "." .join (parts [:- 2 ])
555+ return "." .join (parts [:- 1 ])
556+
557+ def _caller_language (self , caller_id : str ) -> Optional [str ]:
558+ caller = self .functions .get (caller_id )
559+ if caller and caller .language :
560+ return caller .language
561+ if caller :
562+ return CODE_EXTENSIONS .get (Path (caller .file_path ).suffix .lower ())
563+ return None
445564
446565 def _deduplicate_relationships (self ):
447566 """
@@ -480,15 +599,16 @@ def _generate_visualization_data(self) -> Dict:
480599 node_classes .append ("node-function" )
481600
482601 file_ext = Path (func_info .file_path ).suffix .lower ()
602+ language = func_info .language or CODE_EXTENSIONS .get (file_ext , "unknown" )
483603 if file_ext == ".py" :
484604 node_classes .append ("lang-python" )
485605 elif file_ext == ".js" :
486606 node_classes .append ("lang-javascript" )
487607 elif file_ext == ".ts" :
488608 node_classes .append ("lang-typescript" )
489- elif file_ext in [ ".c" , ".h" ] :
609+ elif language == "c" :
490610 node_classes .append ("lang-c" )
491- elif file_ext in [".cpp" , ".cc" , ".cxx" , ".hpp" , ".hxx" ]:
611+ elif language == "cpp" or file_ext in [".cpp" , ".cc" , ".cxx" , ".c++" , ". hpp" , ".hxx" , ".h++ " ]:
492612 node_classes .append ("lang-cpp" )
493613 elif file_ext in [".kt" , ".kts" ]:
494614 node_classes .append ("lang-kotlin" )
@@ -502,7 +622,7 @@ def _generate_visualization_data(self) -> Dict:
502622 "label" : func_info .name ,
503623 "file" : func_info .file_path ,
504624 "type" : func_info .node_type or "function" ,
505- "language" : CODE_EXTENSIONS . get ( file_ext , "unknown" ) ,
625+ "language" : language ,
506626 },
507627 "classes" : " " .join (node_classes ),
508628 }
@@ -616,4 +736,3 @@ def _select_most_connected_nodes(self, target_count: int):
616736 for rel in self .call_relationships
617737 if rel .caller in selected_func_ids and rel .callee in selected_func_ids
618738 ]
619-
0 commit comments