Repository navigation
Expand file tree
/
Copy pathcall_graph_analyzer.py
More file actions
1156 lines (981 loc) · 45.1 KB
/
Copy pathcall_graph_analyzer.py
File metadata and controls
1156 lines (981 loc) · 45.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Call Graph Analyzer
Central orchestrator for multi-language call graph analysis.
Coordinates language-specific analyzers to build comprehensive call graphs
across different programming languages in a repository.
"""
import logging
import re
import signal
import threading
import time
import traceback
from collections import defaultdict
from contextlib import contextmanager
from pathlib import Path
from codewiki.src.be.dependency_analyzer.models.core import CallRelationship, Node
from codewiki.src.be.dependency_analyzer.utils.external_symbols import (
CPP_STANDARD_HEADERS,
is_external_symbol,
is_macro_name,
)
from codewiki.src.be.dependency_analyzer.utils.patterns import CODE_EXTENSIONS
from codewiki.src.be.dependency_analyzer.utils.security import safe_open_text
logger = logging.getLogger(__name__)
class TimeoutError(BaseException):
"""Raised when file parsing exceeds timeout.
A ``BaseException`` on purpose: the language analyzers wrap many small
steps in ``except Exception`` blocks. If the alarm fired inside one of
them, the error was swallowed, the alarm was already spent, and a slow
file (e.g. a multi-megabyte vendored JS bundle) ran forever. Only
``_analyze_code_file`` catches it.
"""
@contextmanager
def timeout(seconds):
"""Context manager for timeout on file parsing.
SIGALRM only exists on Unix and can only be installed from the main
thread. Anywhere else (Windows, worker threads such as the MCP server's
``asyncio.to_thread`` pool) the body runs without a timeout instead of
failing -- previously ``signal.signal`` raised from a worker thread and
the per-file ``except Exception`` silently skipped every file.
"""
if not hasattr(signal, "SIGALRM") or threading.current_thread() is not threading.main_thread():
yield
return
def signal_handler(signum, frame):
raise TimeoutError(f"File parsing exceeded {seconds}s timeout")
old_handler = signal.signal(signal.SIGALRM, signal_handler)
signal.alarm(seconds)
try:
yield
finally:
signal.alarm(0)
signal.signal(signal.SIGALRM, old_handler)
class CallGraphAnalyzer:
def __init__(self):
"""Initialize the call graph analyzer."""
self.functions: dict[str, Node] = {}
self._dart_directives: dict[str, list] = {}
self._dart_visible: dict[str, set[str]] = {}
self._dart_library_members: dict[str, set[str]] = {}
self._dart_unscoped = False
self.call_relationships: list[CallRelationship] = []
self._python_project_modules: set = set()
self._python_external_import_roots: set = set()
logger.debug("CallGraphAnalyzer initialized.")
def analyze_code_files(self, code_files: list[dict], base_dir: str) -> dict:
"""
Complete analysis: Analyze all files to build complete call graph with all nodes.
This approach:
1. Analyzes all code files
2. Extracts all functions and relationships
3. Builds complete call graph
4. Returns all nodes and relationships
"""
logger.debug(f"Starting analysis of {len(code_files)} files")
logger.info(f"📊 Parsing {len(code_files)} source files (this may take a few minutes)...")
self.functions = {}
self.call_relationships = []
code_files = self._route_contextual_headers(code_files, base_dir)
self._python_project_modules = self._collect_python_modules(code_files)
self._python_external_import_roots = set()
self._dart_directives = {}
self._dart_visible = {}
self._dart_library_members = {}
self._dart_unscoped = False
files_analyzed = 0
files_failed = 0
start_time = time.time()
for idx, file_info in enumerate(code_files, 1):
file_path = file_info["path"]
try:
# Log progress every file with elapsed time
if idx % max(1, len(code_files) // 10) == 0 or idx <= 5:
elapsed = time.time() - start_time
rate = idx / elapsed if elapsed > 0 else 0
remaining = (len(code_files) - idx) / rate if rate > 0 else 0
logger.info(
f" [{idx}/{len(code_files)}] {file_path} ({elapsed:.1f}s elapsed, ~{remaining:.1f}s remaining)"
)
self._analyze_code_file(base_dir, file_info)
files_analyzed += 1
except Exception as e: # noqa: BLE001 — one unparsable file must not abort the sweep
files_failed += 1
logger.warning(
f" ⚠️ [{idx}/{len(code_files)}] Failed to analyze {file_path}: {str(e)[:100]}"
)
elapsed_time = time.time() - start_time
logger.info(
f"✓ Analysis complete: {files_analyzed}/{len(code_files)} files analyzed, "
f"{files_failed} failed, {len(self.functions)} functions, {len(self.call_relationships)} relationships ({elapsed_time:.1f}s)"
)
if self._dart_directives:
self._build_dart_scopes(base_dir)
logger.debug("Resolving call relationships")
self._resolve_call_relationships()
self._deduplicate_relationships()
viz_data = self._generate_visualization_data()
return {
"call_graph": {
"total_functions": len(self.functions),
"total_calls": len(self.call_relationships),
"languages_found": list({f.get("language") for f in code_files}),
"files_analyzed": files_analyzed,
"analysis_approach": "complete_unlimited",
},
"functions": [func.model_dump() for func in self.functions.values()],
"relationships": [rel.model_dump() for rel in self.call_relationships],
"visualization": viz_data,
}
def extract_code_files(self, file_tree: dict) -> list[dict]:
"""
Extract code files from file tree structure.
Filters files based on supported extensions and excludes test/config files.
Args:
file_tree: Nested dictionary representing file structure
Returns:
List of code file information dictionaries
"""
code_files = []
def traverse(tree):
if tree["type"] == "file":
ext = tree.get("extension", "").lower()
if ext in CODE_EXTENSIONS:
name = tree["name"].lower()
if not any(skip in name for skip in []):
code_files.append(
{
"path": tree["path"],
"name": tree["name"],
"extension": ext,
"language": CODE_EXTENSIONS[ext],
}
)
elif tree["type"] == "directory" and tree.get("children"):
for child in tree["children"]:
traverse(child)
traverse(file_tree)
return code_files
def _route_contextual_headers(self, code_files: list[dict], base_dir: str) -> list[dict]:
"""Route ambiguous .h headers per file.
A header is parsed as C++ when its own content shows C++ signals, or
when the repository is C++-only (so even a signal-free header cannot be
C). In a mixed C/C++ repository, a plain C header stays routed as C.
"""
cpp_extensions = {".cpp", ".cc", ".cxx", ".c++", ".hpp", ".hxx", ".h++"}
has_cpp_files = any(
file_info.get("extension", "").lower() in cpp_extensions
or file_info.get("language") == "cpp"
for file_info in code_files
)
has_c_files = any(
file_info.get("extension", "").lower() == ".c" for file_info in code_files
)
routed_files = []
for file_info in code_files:
routed = dict(file_info)
if routed.get("extension", "").lower() == ".h" and (
self._header_has_cpp_signal(base_dir, routed["path"])
or has_cpp_files
and not has_c_files
):
routed["language"] = "cpp"
routed_files.append(routed)
return routed_files
def _header_has_cpp_signal(self, base_dir: str, relative_path: str) -> bool:
base = Path(base_dir)
try:
content = safe_open_text(base, base / relative_path)
except Exception: # noqa: BLE001 — unreadable file simply is not an entry point
return False
if re.search(
r"\b(?:namespace\s+[A-Za-z_{:]|class\s+[A-Za-z_]|template\s*<"
r"|typename\b|(?:public|private|protected)\s*:)",
content,
):
return True
if "::" in content:
return True
for header in CPP_STANDARD_HEADERS:
if f"#include <{header}>" in content:
return True
return False
def _analyze_code_file(self, repo_dir: str, file_info: dict):
"""
Analyze a single code file based on its language.
Routes to appropriate language-specific analyzer.
Args:
repo_dir: Repository directory path
file_info: File information dictionary
"""
base = Path(repo_dir)
file_path = base / file_info["path"]
try:
# Add timeout protection (30 seconds per file max)
with timeout(30):
content = safe_open_text(base, file_path)
language = file_info["language"]
if language == "python":
self._analyze_python_file(file_path, content, repo_dir)
elif language == "javascript":
self._analyze_javascript_file(file_path, content, repo_dir)
elif language == "typescript":
self._analyze_typescript_file(file_path, content, repo_dir)
elif language == "java":
self._analyze_java_file(file_path, content, repo_dir)
elif language == "kotlin":
self._analyze_kotlin_file(file_path, content, repo_dir)
elif language == "csharp":
self._analyze_csharp_file(file_path, content, repo_dir)
elif language == "c":
self._analyze_c_file(file_path, content, repo_dir)
elif language == "cpp":
self._analyze_cpp_file(file_path, content, repo_dir)
elif language == "php":
self._analyze_php_file(file_path, content, repo_dir)
elif language == "ruby":
self._analyze_ruby_file(file_path, content, repo_dir)
elif language == "scala":
self._analyze_scala_file(file_path, content, repo_dir)
elif language == "rust":
self._analyze_rust_file(file_path, content, repo_dir)
elif language == "dart":
self._analyze_dart_file(file_path, content, repo_dir)
# else:
# logger.warning(
# f"Unsupported language for call graph analysis: {language} for file {file_path}"
# )
except TimeoutError as e:
logger.warning(f"⏱️ Timeout analyzing {file_path}: {e!s}")
except Exception as e: # noqa: BLE001 — per-file analysis is best-effort
logger.debug(f"Error analyzing {file_path}: {e!s}")
logger.debug(f"Traceback: {traceback.format_exc()}")
def _analyze_python_file(self, file_path: str, content: str, base_dir: str):
"""
Analyze Python file using Python AST analyzer.
Args:
file_path: Relative path to the Python file
content: File content string
base_dir: Repository base directory path
"""
from codewiki.src.be.dependency_analyzer.analyzers.python import analyze_python_file
try:
functions, relationships, external_import_roots = analyze_python_file(
file_path,
content,
repo_path=base_dir,
project_modules=self._python_project_modules,
)
for func in functions:
func_id = func.id if func.id else f"{file_path}:{func.name}"
self.functions[func_id] = func
self.call_relationships.extend(relationships)
self._python_external_import_roots.update(external_import_roots)
except Exception:
logger.exception(f"Failed to analyze Python file {file_path}")
@staticmethod
def _collect_python_modules(code_files: list[dict]) -> set:
"""Dotted module paths for every Python file in the repository."""
modules = set()
for file_info in code_files:
if file_info.get("language") != "python":
continue
path = file_info["path"]
for ext in (".py", ".pyx"):
if path.endswith(ext):
path = path[: -len(ext)]
break
module = path.replace("/", ".").replace("\\", ".")
module = module.removesuffix(".__init__")
if module:
modules.add(module)
return modules
def _analyze_javascript_file(self, file_path: str, content: str, repo_dir: str):
"""
Analyze JavaScript file using tree-sitter based AST analyzer
Args:
file_path: Relative path to the JavaScript file
content: File content string
repo_dir: Repository base directory
"""
try:
from codewiki.src.be.dependency_analyzer.analyzers.javascript import (
analyze_javascript_file_treesitter,
)
functions, relationships = analyze_javascript_file_treesitter(
file_path, content, repo_path=repo_dir
)
for func in functions:
func_id = func.id if func.id else f"{file_path}:{func.name}"
self.functions[func_id] = func
self.call_relationships.extend(relationships)
except Exception:
logger.exception(f"Failed to analyze JavaScript file {file_path}")
def _analyze_typescript_file(self, file_path: str, content: str, repo_dir: str):
"""
Analyze TypeScript file using tree-sitter based AST analyzer
Args:
file_path: Relative path to the TypeScript file
content: File content string
"""
try:
from codewiki.src.be.dependency_analyzer.analyzers.typescript import (
analyze_typescript_file_treesitter,
)
functions, relationships = analyze_typescript_file_treesitter(
file_path, content, repo_path=repo_dir
)
for func in functions:
func_id = func.id if func.id else f"{file_path}:{func.name}"
self.functions[func_id] = func
self.call_relationships.extend(relationships)
except Exception:
logger.exception(f"Failed to analyze TypeScript file {file_path}")
def _analyze_c_file(self, file_path: str, content: str, repo_dir: str):
"""
Analyze C file using tree-sitter based analyzer.
Args:
file_path: Relative path to the C file
content: File content string
repo_dir: Repository base directory
"""
from codewiki.src.be.dependency_analyzer.analyzers.c import analyze_c_file
functions, relationships = analyze_c_file(file_path, content, repo_path=repo_dir)
for func in functions:
func_id = func.id if func.id else f"{file_path}:{func.name}"
self.functions[func_id] = func
self.call_relationships.extend(relationships)
def _analyze_cpp_file(self, file_path: str, content: str, repo_dir: str):
"""
Analyze C++ file using tree-sitter based analyzer.
Args:
file_path: Relative path to the C++ file
content: File content string
"""
from codewiki.src.be.dependency_analyzer.analyzers.cpp import analyze_cpp_file
functions, relationships = analyze_cpp_file(file_path, content, repo_path=repo_dir)
for func in functions:
func_id = func.id if func.id else f"{file_path}:{func.name}"
self.functions[func_id] = func
self.call_relationships.extend(relationships)
def _analyze_java_file(self, file_path: str, content: str, repo_dir: str):
"""
Analyze Java file using tree-sitter based analyzer.
Args:
file_path: Relative path to the Java file
content: File content string
repo_dir: Repository base directory
"""
from codewiki.src.be.dependency_analyzer.analyzers.java import analyze_java_file
try:
functions, relationships = analyze_java_file(file_path, content, repo_path=repo_dir)
for func in functions:
func_id = func.id if func.id else f"{file_path}:{func.name}"
self.functions[func_id] = func
self.call_relationships.extend(relationships)
except Exception:
logger.exception(f"Failed to analyze Java file {file_path}")
def _analyze_kotlin_file(self, file_path: str, content: str, repo_dir: str):
"""
Analyze Kotlin file using tree-sitter based analyzer.
Args:
file_path: Relative path to the Kotlin file
content: File content string
repo_dir: Repository base directory
"""
from codewiki.src.be.dependency_analyzer.analyzers.kotlin import analyze_kotlin_file
try:
functions, relationships = analyze_kotlin_file(file_path, content, repo_path=repo_dir)
for func in functions:
func_id = func.id if func.id else f"{file_path}:{func.name}"
self.functions[func_id] = func
self.call_relationships.extend(relationships)
except Exception:
logger.exception(f"Failed to analyze Kotlin file {file_path}")
def _analyze_csharp_file(self, file_path: str, content: str, repo_dir: str):
"""
Analyze C# file using tree-sitter based analyzer.
Args:
file_path: Relative path to the C# file
content: File content string
repo_dir: Repository base directory
"""
from codewiki.src.be.dependency_analyzer.analyzers.csharp import analyze_csharp_file
try:
functions, relationships = analyze_csharp_file(file_path, content, repo_path=repo_dir)
for func in functions:
func_id = func.id if func.id else f"{file_path}:{func.name}"
self.functions[func_id] = func
self.call_relationships.extend(relationships)
except Exception:
logger.exception(f"Failed to analyze C# file {file_path}")
def _analyze_php_file(self, file_path: str, content: str, repo_dir: str):
"""
Analyze PHP file using tree-sitter based analyzer.
Args:
file_path: Relative path to the PHP file
content: File content string
repo_dir: Repository base directory
"""
from codewiki.src.be.dependency_analyzer.analyzers.php import analyze_php_file
try:
functions, relationships = analyze_php_file(file_path, content, repo_path=repo_dir)
for func in functions:
func_id = func.id if func.id else f"{file_path}:{func.name}"
self.functions[func_id] = func
self.call_relationships.extend(relationships)
except Exception:
logger.exception(f"Failed to analyze PHP file {file_path}")
def _analyze_ruby_file(self, file_path: str, content: str, repo_dir: str):
"""
Analyze Ruby file using tree-sitter based analyzer.
Args:
file_path: Relative path to the Ruby file
content: File content string
repo_dir: Repository base directory
"""
from codewiki.src.be.dependency_analyzer.analyzers.ruby import analyze_ruby_file
try:
functions, relationships = analyze_ruby_file(file_path, content, repo_path=repo_dir)
for func in functions:
func_id = func.id if func.id else f"{file_path}:{func.name}"
self.functions[func_id] = func
self.call_relationships.extend(relationships)
except Exception:
logger.exception(f"Failed to analyze Ruby file {file_path}")
def _analyze_scala_file(self, file_path: str, content: str, repo_dir: str):
"""
Analyze Scala file using tree-sitter based analyzer.
Args:
file_path: Relative path to the Scala file
content: File content string
repo_dir: Repository base directory
"""
from codewiki.src.be.dependency_analyzer.analyzers.scala import analyze_scala_file
try:
functions, relationships = analyze_scala_file(file_path, content, repo_path=repo_dir)
for func in functions:
func_id = func.id if func.id else f"{file_path}:{func.name}"
self.functions[func_id] = func
self.call_relationships.extend(relationships)
except Exception:
logger.exception(f"Failed to analyze Scala file {file_path}")
def _analyze_rust_file(self, file_path: str, content: str, repo_dir: str):
"""
Analyze Rust file using tree-sitter based analyzer.
Args:
file_path: Relative path to the Rust file
content: File content string
repo_dir: Repository base directory
"""
from codewiki.src.be.dependency_analyzer.analyzers.rust import analyze_rust_file
try:
functions, relationships = analyze_rust_file(file_path, content, repo_path=repo_dir)
for func in functions:
func_id = func.id if func.id else f"{file_path}:{func.name}"
self.functions[func_id] = func
self.call_relationships.extend(relationships)
except Exception:
logger.exception(f"Failed to analyze Rust file {file_path}")
def _analyze_dart_file(self, file_path: str, content: str, repo_dir: str):
"""
Analyze Dart file using tree-sitter based analyzer.
Besides components and relationships, records the file's
import/export/part directives for Dart scope-aware resolution.
Args:
file_path: Path to the Dart file
content: File content string
repo_dir: Repository base directory
"""
from codewiki.src.be.dependency_analyzer.analyzers.dart import TreeSitterDartAnalyzer
try:
analyzer = TreeSitterDartAnalyzer(str(file_path), content, repo_path=repo_dir)
for func in analyzer.nodes:
func_id = func.id if func.id else f"{file_path}:{func.name}"
self.functions[func_id] = func
self.call_relationships.extend(analyzer.call_relationships)
self._dart_directives[analyzer.relative_path] = analyzer.directives
except Exception:
logger.exception(f"Failed to analyze Dart file {file_path}")
def _build_dart_scopes(self, base_dir: str) -> None:
"""Resolve recorded Dart directives into per-file visibility scopes."""
from codewiki.src.be.dependency_analyzer.analyzers.dart_imports import (
DartPackageResolver,
build_scopes,
)
files = set(self._dart_directives)
resolver = DartPackageResolver.from_files(base_dir, files)
scopes = build_scopes(self._dart_directives, resolver, files)
self._dart_library_members = scopes.library_members
if resolver.packages:
self._dart_visible = scopes.visible
return
# Without a pubspec.yaml (e.g. only `lib/` was analyzed) `package:`
# imports resolve to nothing, and scoping would drop nearly every
# cross-file edge. Match names across all Dart files instead.
self._dart_unscoped = True
logger.warning(
"No pubspec.yaml found for the analyzed Dart files; `package:` imports "
"cannot be resolved, so Dart calls are matched by name across Dart files."
)
def _dart_scope_candidates(
self, func_ids: list[str], scope: set[str] | None, caller_file: str | None = None
) -> list[str]:
from codewiki.src.be.dependency_analyzer.analyzers.dart_imports import (
is_private_dart_name,
)
own_library = self._dart_library_members.get(caller_file, set()) if caller_file else set()
candidates: list[str] = []
for func_id in func_ids:
func = self.functions.get(func_id)
if func_id in candidates or func is None:
continue
func_file = Path(func.relative_path).as_posix()
if scope is not None and func_file not in scope:
continue
# A `_`-prefixed segment in the target (`_Ticker.tick`) is private
# to its library, whatever the callee's own spelling.
if is_private_dart_name(func.name) and func_file not in own_library:
continue
candidates.append(func_id)
return candidates
def _resolve_dart_callee(
self, callee: str, caller: Node, lang_indexes: dict | None
) -> str | None:
"""Prefer definitions the caller's library can see (imports, parts,
re-exports); library-private names only resolve inside the library."""
from codewiki.src.be.dependency_analyzer.analyzers.dart_imports import (
is_private_dart_name,
)
if not lang_indexes or "::" in callee:
return None
caller_file = Path(caller.relative_path).as_posix()
scope: set[str] | None
if is_private_dart_name(callee):
scope = self._dart_library_members.get(caller_file, {caller_file})
elif self._dart_unscoped:
scope = None # any Dart file
else:
scope = self._dart_visible.get(caller_file)
if not scope:
return None
keys = [callee]
if "." in callee:
keys.append(callee.split(".")[0])
for key in keys:
# Exact names first: an imported `helper()` must not turn ambiguous
# because some visible class also has a `helper` method.
for index in ("exact", "simple"):
candidates = self._dart_scope_candidates(
lang_indexes[index].get(key, []), scope, caller_file
)
if len(candidates) == 1:
return candidates[0]
if candidates:
break
from codewiki.src.be.dependency_analyzer.analyzers.dart_flutter import (
RIVERPOD_NOTIFIER_TYPE,
RIVERPOD_PROVIDER_TYPE,
provider_alias_candidates,
)
# riverpod_generator providers live in ignored *.g.dart files: map
# `fooProvider` to the @riverpod declaration it was generated from.
for alias in provider_alias_candidates(callee):
candidates = [
func_id
for func_id in self._dart_scope_candidates(
lang_indexes["exact"].get(alias, []), scope, caller_file
)
if self.functions[func_id].node_type
in (RIVERPOD_PROVIDER_TYPE, RIVERPOD_NOTIFIER_TYPE)
and self.functions[func_id].name == alias
]
if len(candidates) == 1:
return candidates[0]
return None
def _resolve_call_relationships(self):
"""
Resolve function call relationships across all languages.
Attempts to match function calls to actual function definitions,
handling cross-language calls where possible.
"""
for func_info in self.functions.values():
if not func_info.language:
file_ext = Path(func_info.file_path).suffix.lower()
func_info.language = CODE_EXTENSIONS.get(file_ext)
indexes = self._build_resolution_indexes()
resolved_count = 0
for relationship in self.call_relationships:
if relationship.is_resolved and relationship.callee in self.functions:
continue
resolved_id = self._resolve_callee(relationship, indexes)
if resolved_id:
relationship.callee = resolved_id
relationship.is_resolved = True
resolved_count += 1
dotted_packages = self._dotted_project_packages()
self.call_relationships = [
relationship
for relationship in self.call_relationships
if relationship.is_resolved
or not self._is_unresolvable_dart(relationship)
and not self._is_external_callee(
self._caller_language(relationship.caller),
relationship.callee,
dotted_packages,
)
]
def _is_unresolvable_dart(self, relationship: CallRelationship) -> bool:
"""A Dart caller's callee that Dart resolution rejected is external or
invisible; drop it so ast_parser's name-only fallback cannot bind it
to an unrelated component."""
caller = self.functions.get(relationship.caller)
return caller is not None and caller.language == "dart"
def _dotted_project_packages(self) -> dict[str, set]:
"""Project packages/namespaces, partitioned by language. Java and C#
share the namespace-origin rule: a dotted callee qualified to a package
with no prefix relation to any project package came from a third-party
import."""
packages: dict[str, set] = defaultdict(set)
for func_info in self.functions.values():
if func_info.language in ("java", "csharp"):
package = self._dotted_package_for_node(func_info)
if package:
packages[func_info.language].add(package)
return packages
def _is_external_callee(
self, language: str | None, callee: str, dotted_packages: dict[str, set]
) -> bool:
"""Classify a still-unresolved callee as external, after project
resolution has had its chance.
Rules are generic, not name lists: prefix/standard-library knowledge in
is_external_symbol, the C/C++ ALL_CAPS macro convention (macros are
never components, so such calls can never resolve), and Java package
origin — a dotted name qualified to a package with no prefix relation
to any project package came from a third-party import.
"""
if is_external_symbol(language, callee):
return True
if language in ("c", "cpp") and is_macro_name(callee):
return True
if language in ("java", "csharp") and "." in callee and dotted_packages.get(language):
package = callee.rsplit(".", 1)[0]
if not any(
package == project
or package.startswith(project + ".")
or project.startswith(package + ".")
for project in dotted_packages[language]
):
return True
if language == "python" and "." in callee:
return self._is_external_python_callee(callee)
if language == "dart":
from codewiki.src.be.dependency_analyzer.analyzers.dart_imports import (
is_private_dart_name,
)
# A library-private name that did not resolve inside its library
# can never be a component elsewhere; dropping it keeps the
# name-based fallback from binding another library's `_Body`.
if is_private_dart_name(callee):
return True
return False
def _is_external_python_callee(self, callee: str) -> bool:
"""Classify a still-unresolved dotted Python callee.
A callee whose dotted prefix aligns with a project module is an
honest project gap, never external. Otherwise the import-origin rule
(head was imported from outside the project) and the core-object
method rule (a tail like ``append``/``endswith`` on an unknowable
receiver can never be a project component) apply.
"""
from codewiki.src.be.dependency_analyzer.analyzers.python import is_project_import
from codewiki.src.be.dependency_analyzer.utils.external_symbols import (
PYTHON_OBJECT_METHODS,
)
parts = callee.split(".")
if self._python_project_modules:
for end in range(len(parts) - 1, 0, -1):
if is_project_import(".".join(parts[:end]), self._python_project_modules):
return False
if parts[0] in self._python_external_import_roots:
return True
return parts[-1] in PYTHON_OBJECT_METHODS
def _build_resolution_indexes(self) -> dict[str, dict]:
"""Build exact/simple-name lookup indexes, both globally and per
language. Resolution prefers the caller's own language partition: a
name that is unique within the caller's language resolves even when
another language defines the same name, and names made ambiguous only
by foreign-language components keep resolving as before."""
def make() -> dict[str, dict[str, list[str]]]:
return {"exact": defaultdict(list), "simple": defaultdict(list)}
global_indexes = make()
by_lang: dict[str, dict[str, dict[str, list[str]]]] = defaultdict(make)
def add(index: dict[str, list[str]], key: str | None, func_id: str) -> None:
if key and func_id not in index[key]:
index[key].append(func_id)
for func_id, func_info in self.functions.items():
targets = [global_indexes]
if func_info.language:
targets.append(by_lang[func_info.language])
exact_keys = [
func_id,
func_info.component_id,
func_info.qualified_name,
func_info.name,
]
names = {func_info.name}
if func_info.component_id:
names.add(func_info.component_id.split("::")[-1])
if func_info.qualified_name:
names.add(func_info.qualified_name.split(".")[-1])
parts = func_info.qualified_name.split(".")
if len(parts) >= 2:
names.add(".".join(parts[-2:]))
for target in targets:
for key in exact_keys:
add(target["exact"], key, func_id)
for name in names:
add(target["simple"], name, func_id)
if name and "." in name:
add(target["simple"], name.split(".")[-1], func_id)
return {
"exact": global_indexes["exact"],
"simple": global_indexes["simple"],
"by_lang": dict(by_lang),
}
def _resolve_callee(
self, relationship: CallRelationship, indexes: dict[str, dict]
) -> str | None:
caller = self.functions.get(relationship.caller)
caller_language = caller.language if caller else None
lang_indexes = indexes["by_lang"].get(caller_language) if caller_language else None
if caller_language == "dart" and caller is not None:
# Dart resolution is authoritative: it never falls back to name
# guessing in other languages or invisible libraries.
return self._resolve_dart_callee(relationship.callee, caller, lang_indexes)
if lang_indexes:
match = self._resolve_callee_in(
relationship, lang_indexes["exact"], lang_indexes["simple"]
)
if match:
return match
return self._resolve_callee_in(relationship, indexes["exact"], indexes["simple"])
def _resolve_callee_in(
self,
relationship: CallRelationship,
exact: dict[str, list[str]],
simple: dict[str, list[str]],
) -> str | None:
callee_name = relationship.callee
exact_match = self._unique_match(exact, callee_name)
if exact_match:
return exact_match
if "::" in callee_name:
suffix = callee_name.split("::")[-1]
exact_match = self._unique_match(exact, suffix)
if exact_match:
return exact_match
simple_match = self._unique_match(simple, suffix)
if simple_match:
return simple_match
if "." in callee_name:
simple_match = self._unique_match(simple, callee_name)
if simple_match:
return simple_match
tail_match = self._unique_match(simple, callee_name.split(".")[-1])
if tail_match:
return tail_match
caller = self.functions.get(relationship.caller)
if caller and caller.language in ("java", "csharp") and "." not in callee_name:
package = self._dotted_package_for_node(caller)
if package:
same_package_match = self._unique_match(exact, f"{package}.{callee_name}")
if same_package_match:
return same_package_match
return self._unique_match(simple, callee_name)
def _unique_match(self, index: dict[str, list[str]], key: str) -> str | None:
matches = index.get(key, [])
return matches[0] if len(matches) == 1 else None
def _dotted_package_for_node(self, node: Node) -> str:
"""The package (Java) / namespace (C#) a node lives in, derived from its
dotted qualified name. Both languages share the same shape: a type's
package is its qualified name minus the type, a method's is minus
``Type.method``."""
qualified_name = node.qualified_name or ""
parts = qualified_name.split(".")
if len(parts) < 2:
return ""
if node.component_type == "method" and len(parts) >= 3:
return ".".join(parts[:-2])
return ".".join(parts[:-1])
def _caller_language(self, caller_id: str) -> str | None:
caller = self.functions.get(caller_id)
if caller and caller.language:
return caller.language
if caller:
return CODE_EXTENSIONS.get(Path(caller.file_path).suffix.lower())
return None
def _deduplicate_relationships(self):
"""
Deduplicate call relationships based on caller-callee pairs.
Removes duplicate relationships while preserving the first occurrence.
This helps eliminate noise from multiple calls to the same function.
"""
seen = set()
unique_relationships = []
for rel in self.call_relationships:
key = (rel.caller, rel.callee)
if key not in seen:
seen.add(key)
unique_relationships.append(rel)
self.call_relationships = unique_relationships
def _generate_visualization_data(self) -> dict:
"""
Generate visualization data for graph rendering.
Creates Cytoscape.js compatible graph data with nodes and edges.
Returns:
Dict: Visualization data with cytoscape elements and summary
"""
cytoscape_elements = []
for func_id, func_info in self.functions.items():
node_classes = []
if func_info.node_type == "method":