codegraphcontext-rust 0.9.24__cp314-cp314-win_amd64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (112) hide show
  1. codegraphcontext/__init__.py +2 -0
  2. codegraphcontext/__main__.py +5 -0
  3. codegraphcontext/_cgc_rust.cp314-win_amd64.pyd +4 -0
  4. codegraphcontext/cli/__init__.py +1 -0
  5. codegraphcontext/cli/cli_helpers.py +774 -0
  6. codegraphcontext/cli/config_manager.py +1051 -0
  7. codegraphcontext/cli/entry.py +21 -0
  8. codegraphcontext/cli/main.py +2386 -0
  9. codegraphcontext/cli/registry_commands.py +404 -0
  10. codegraphcontext/cli/setup_macos.py +93 -0
  11. codegraphcontext/cli/setup_wizard.py +991 -0
  12. codegraphcontext/cli/visualizer.py +50 -0
  13. codegraphcontext/core/__init__.py +165 -0
  14. codegraphcontext/core/bundle_registry.py +181 -0
  15. codegraphcontext/core/cgc_bundle.py +858 -0
  16. codegraphcontext/core/cgcignore.py +118 -0
  17. codegraphcontext/core/database.py +273 -0
  18. codegraphcontext/core/database_falkordb.py +480 -0
  19. codegraphcontext/core/database_falkordb_remote.py +199 -0
  20. codegraphcontext/core/database_kuzu.py +636 -0
  21. codegraphcontext/core/falkor_worker.py +132 -0
  22. codegraphcontext/core/jobs.py +132 -0
  23. codegraphcontext/core/watcher.py +260 -0
  24. codegraphcontext/prompts.py +125 -0
  25. codegraphcontext/server.py +471 -0
  26. codegraphcontext/tool_definitions.py +220 -0
  27. codegraphcontext/tools/__init__.py +0 -0
  28. codegraphcontext/tools/advanced_language_query_tool.py +103 -0
  29. codegraphcontext/tools/code_finder.py +1160 -0
  30. codegraphcontext/tools/graph_builder.py +337 -0
  31. codegraphcontext/tools/handlers/analysis_handlers.py +114 -0
  32. codegraphcontext/tools/handlers/indexing_handlers.py +116 -0
  33. codegraphcontext/tools/handlers/management_handlers.py +339 -0
  34. codegraphcontext/tools/handlers/query_handlers.py +83 -0
  35. codegraphcontext/tools/handlers/watcher_handlers.py +83 -0
  36. codegraphcontext/tools/indexing/__init__.py +1 -0
  37. codegraphcontext/tools/indexing/angular_routes.py +396 -0
  38. codegraphcontext/tools/indexing/cgc_wiki_cli.py +1334 -0
  39. codegraphcontext/tools/indexing/constants.py +70 -0
  40. codegraphcontext/tools/indexing/context_generator.py +461 -0
  41. codegraphcontext/tools/indexing/discovery.py +64 -0
  42. codegraphcontext/tools/indexing/engine.py +114 -0
  43. codegraphcontext/tools/indexing/execution_flows.py +355 -0
  44. codegraphcontext/tools/indexing/module_grouping.py +551 -0
  45. codegraphcontext/tools/indexing/noise_filter.py +131 -0
  46. codegraphcontext/tools/indexing/op_param_extraction.py +287 -0
  47. codegraphcontext/tools/indexing/persistence/__init__.py +3 -0
  48. codegraphcontext/tools/indexing/persistence/duckdb_writer.py +1116 -0
  49. codegraphcontext/tools/indexing/persistence/parquet_loader.py +643 -0
  50. codegraphcontext/tools/indexing/persistence/writer.py +1562 -0
  51. codegraphcontext/tools/indexing/pipeline.py +171 -0
  52. codegraphcontext/tools/indexing/pre_scan.py +105 -0
  53. codegraphcontext/tools/indexing/rationale_extraction.py +154 -0
  54. codegraphcontext/tools/indexing/resolution/__init__.py +8 -0
  55. codegraphcontext/tools/indexing/resolution/calls.py +253 -0
  56. codegraphcontext/tools/indexing/resolution/inheritance.py +91 -0
  57. codegraphcontext/tools/indexing/route_extraction.py +659 -0
  58. codegraphcontext/tools/indexing/sanitize.py +41 -0
  59. codegraphcontext/tools/indexing/schema.py +79 -0
  60. codegraphcontext/tools/indexing/schema_contract.py +44 -0
  61. codegraphcontext/tools/indexing/scip_pipeline.py +140 -0
  62. codegraphcontext/tools/languages/c.py +563 -0
  63. codegraphcontext/tools/languages/cpp.py +616 -0
  64. codegraphcontext/tools/languages/csharp.py +551 -0
  65. codegraphcontext/tools/languages/dart.py +378 -0
  66. codegraphcontext/tools/languages/elixir.py +460 -0
  67. codegraphcontext/tools/languages/go.py +499 -0
  68. codegraphcontext/tools/languages/haskell.py +426 -0
  69. codegraphcontext/tools/languages/java.py +500 -0
  70. codegraphcontext/tools/languages/javascript.py +589 -0
  71. codegraphcontext/tools/languages/kotlin.py +640 -0
  72. codegraphcontext/tools/languages/perl.py +260 -0
  73. codegraphcontext/tools/languages/php.py +519 -0
  74. codegraphcontext/tools/languages/python.py +578 -0
  75. codegraphcontext/tools/languages/ruby.py +537 -0
  76. codegraphcontext/tools/languages/rust.py +295 -0
  77. codegraphcontext/tools/languages/scala.py +519 -0
  78. codegraphcontext/tools/languages/swift.py +491 -0
  79. codegraphcontext/tools/languages/typescript.py +606 -0
  80. codegraphcontext/tools/languages/typescriptjsx.py +151 -0
  81. codegraphcontext/tools/package_resolver.py +472 -0
  82. codegraphcontext/tools/query_tool_languages/c_toolkit.py +5 -0
  83. codegraphcontext/tools/query_tool_languages/cpp_toolkit.py +87 -0
  84. codegraphcontext/tools/query_tool_languages/csharp_toolkit.py +5 -0
  85. codegraphcontext/tools/query_tool_languages/dart_toolkit.py +5 -0
  86. codegraphcontext/tools/query_tool_languages/go_toolkit.py +5 -0
  87. codegraphcontext/tools/query_tool_languages/haskell_toolkit.py +5 -0
  88. codegraphcontext/tools/query_tool_languages/java_toolkit.py +5 -0
  89. codegraphcontext/tools/query_tool_languages/javascript_toolkit.py +5 -0
  90. codegraphcontext/tools/query_tool_languages/perl_toolkit.py +5 -0
  91. codegraphcontext/tools/query_tool_languages/python_toolkit.py +5 -0
  92. codegraphcontext/tools/query_tool_languages/ruby_toolkit.py +5 -0
  93. codegraphcontext/tools/query_tool_languages/rust_toolkit.py +5 -0
  94. codegraphcontext/tools/query_tool_languages/scala_toolkit.py +5 -0
  95. codegraphcontext/tools/query_tool_languages/swift_toolkit.py +5 -0
  96. codegraphcontext/tools/query_tool_languages/typescript_toolkit.py +5 -0
  97. codegraphcontext/tools/scip_indexer.py +467 -0
  98. codegraphcontext/tools/scip_pb2.py +2455 -0
  99. codegraphcontext/tools/system.py +133 -0
  100. codegraphcontext/tools/tree_sitter_parser.py +103 -0
  101. codegraphcontext/utils/debug_log.py +90 -0
  102. codegraphcontext/utils/path_ignore.py +55 -0
  103. codegraphcontext/utils/repo_path.py +27 -0
  104. codegraphcontext/utils/tree_sitter_manager.py +285 -0
  105. codegraphcontext/utils/visualize_graph.py +0 -0
  106. codegraphcontext/viz/server.py +282 -0
  107. codegraphcontext_rust-0.9.24.dist-info/METADATA +543 -0
  108. codegraphcontext_rust-0.9.24.dist-info/RECORD +112 -0
  109. codegraphcontext_rust-0.9.24.dist-info/WHEEL +4 -0
  110. codegraphcontext_rust-0.9.24.dist-info/entry_points.txt +4 -0
  111. codegraphcontext_rust-0.9.24.dist-info/licenses/LICENSE +21 -0
  112. codegraphcontext_rust-0.9.24.dist-info/sboms/cgc-python.cyclonedx.json +2302 -0
@@ -0,0 +1,171 @@
1
+ """Orchestrates full-repo indexing (Tree-sitter path)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import time
7
+ from datetime import datetime
8
+ from pathlib import Path
9
+ from typing import Any, Callable, Dict, List, Optional
10
+
11
+ from ...core.jobs import JobManager, JobStatus
12
+ from ...utils.debug_log import debug_log, error_logger, info_logger
13
+ from .discovery import discover_files_to_index
14
+ from .persistence.writer import GraphWriter
15
+ from .pre_scan import pre_scan_for_imports
16
+ from .resolution.calls import build_function_call_groups
17
+ from .resolution.inheritance import build_inheritance_and_csharp_files
18
+
19
+ # Try to load Rust engine for accelerated parsing
20
+ try:
21
+ from .engine import (
22
+ RUST_AVAILABLE,
23
+ _RUST_SUPPORTED_LANGS,
24
+ _rust_parse_files_parallel,
25
+ _rust_pre_scan,
26
+ _rust_parse_and_prescan,
27
+ _rust_resolve_calls,
28
+ _rust_resolve_inheritance,
29
+ )
30
+ except ImportError:
31
+ RUST_AVAILABLE = False
32
+
33
+
34
+ async def run_tree_sitter_index_async(
35
+ path: Path,
36
+ is_dependency: bool,
37
+ job_id: Optional[str],
38
+ cgcignore_path: Optional[str],
39
+ writer: GraphWriter,
40
+ job_manager: JobManager,
41
+ parsers: Dict[str, str],
42
+ get_parser: Callable[[str], Any],
43
+ parse_file: Callable[[Path, Path, bool], Dict[str, Any]],
44
+ add_minimal_file_node: Callable[[Path, Path, bool], None],
45
+ ) -> None:
46
+ """Parse all discovered files, write symbols, then inheritance + CALLS.
47
+
48
+ When the Rust engine is available, files with supported languages are
49
+ parsed in parallel via Rust for significant speedup. Unsupported
50
+ languages (e.g. Kotlin, Perl) fall back to the Python parser.
51
+ """
52
+ if job_id:
53
+ job_manager.update_job(job_id, status=JobStatus.RUNNING)
54
+
55
+ writer.add_repository_to_graph(path, is_dependency)
56
+ repo_name = path.name
57
+
58
+ files, _ignore_root = discover_files_to_index(path, cgcignore_path)
59
+
60
+ if job_id:
61
+ job_manager.update_job(job_id, total_files=len(files))
62
+
63
+ all_file_data: List[Dict[str, Any]] = []
64
+ resolved_repo_path_str = str(path.resolve()) if path.is_dir() else str(path.parent.resolve())
65
+ repo_path_resolved = path.resolve() if path.is_dir() else path.parent.resolve()
66
+
67
+ # --- Combined pre-scan + parsing phase ---
68
+ if RUST_AVAILABLE:
69
+ # Split files into Rust-supported and fallback
70
+ rust_files = []
71
+ fallback_files = []
72
+ for file in files:
73
+ if not file.is_file():
74
+ continue
75
+ lang = parsers.get(file.suffix)
76
+ if lang and lang in _RUST_SUPPORTED_LANGS and file.suffix != ".ipynb":
77
+ rust_files.append((file, lang))
78
+ else:
79
+ fallback_files.append(file)
80
+
81
+ # Combined parse + pre-scan in one parallel pass (saves ~12% time)
82
+ imports_map = {}
83
+ if rust_files:
84
+ info_logger(f"Rust combined parse+prescan for {len(rust_files)} files...")
85
+ t_parse = time.time()
86
+ specs = [(str(f), lang, is_dependency) for f, lang in rust_files]
87
+ rust_results, imports_map = _rust_parse_and_prescan(specs, index_source=True)
88
+ info_logger(f"Rust parse+prescan done in {time.time() - t_parse:.1f}s "
89
+ f"({len(imports_map)} symbols)")
90
+
91
+ for file_data in rust_results:
92
+ if "error" not in file_data:
93
+ file_data["repo_path"] = str(repo_path_resolved)
94
+ writer.add_file_to_graph(file_data, repo_name, imports_map, repo_path_str=resolved_repo_path_str)
95
+ all_file_data.append(file_data)
96
+
97
+ if job_id:
98
+ job_manager.update_job(job_id, processed_files=len(rust_files))
99
+
100
+ # Fallback for unsupported files (.ipynb, Perl, etc.)
101
+ processed_count = len(rust_files)
102
+ for file in fallback_files:
103
+ if job_id:
104
+ job_manager.update_job(job_id, current_file=str(file))
105
+ file_data = parse_file(repo_path_resolved, file, is_dependency)
106
+ if "error" not in file_data:
107
+ writer.add_file_to_graph(file_data, repo_name, imports_map, repo_path_str=resolved_repo_path_str)
108
+ all_file_data.append(file_data)
109
+ elif not file_data.get("unsupported"):
110
+ add_minimal_file_node(file, repo_path_resolved, is_dependency)
111
+ processed_count += 1
112
+
113
+ if job_id:
114
+ job_manager.update_job(job_id, processed_files=processed_count)
115
+ if processed_count % 50 == 0:
116
+ await asyncio.sleep(0)
117
+ else:
118
+ # Original Python-only path: separate pre-scan
119
+ debug_log("Starting pre-scan to build imports map...")
120
+ imports_map = pre_scan_for_imports(files, parsers.keys(), get_parser)
121
+ debug_log(f"Pre-scan complete. Found {len(imports_map)} definitions.")
122
+ processed_count = 0
123
+ for file in files:
124
+ if not file.is_file():
125
+ continue
126
+ if job_id:
127
+ job_manager.update_job(job_id, current_file=str(file))
128
+ repo_path = path.resolve() if path.is_dir() else file.parent.resolve()
129
+ file_data = parse_file(repo_path, file, is_dependency)
130
+ if "error" not in file_data:
131
+ writer.add_file_to_graph(file_data, repo_name, imports_map, repo_path_str=resolved_repo_path_str)
132
+ all_file_data.append(file_data)
133
+ elif not file_data.get("unsupported"):
134
+ add_minimal_file_node(file, repo_path, is_dependency)
135
+ processed_count += 1
136
+
137
+ if job_id:
138
+ job_manager.update_job(job_id, processed_files=processed_count)
139
+ if processed_count % 50 == 0:
140
+ await asyncio.sleep(0)
141
+
142
+ info_logger(
143
+ f"File processing complete. {len(all_file_data)} files parsed. "
144
+ f"Starting post-processing phase (inheritance + function calls)..."
145
+ )
146
+
147
+ # --- Post-processing phase ---
148
+ t0 = time.time()
149
+
150
+ if RUST_AVAILABLE:
151
+ info_logger(f"[INHERITS] Rust-accelerated inheritance resolution ({len(all_file_data)} files)...")
152
+ inheritance_batch, csharp_files = _rust_resolve_inheritance(all_file_data, imports_map)
153
+ else:
154
+ info_logger(f"[INHERITS] Resolving inheritance links across {len(all_file_data)} files...")
155
+ inheritance_batch, csharp_files = build_inheritance_and_csharp_files(all_file_data, imports_map)
156
+ writer.write_inheritance_links(inheritance_batch, csharp_files, imports_map)
157
+ t1 = time.time()
158
+ info_logger(f"Inheritance links created in {t1 - t0:.1f}s. Starting function calls...")
159
+
160
+ if RUST_AVAILABLE:
161
+ from ...cli.config_manager import get_config_value
162
+ skip_external = (get_config_value("SKIP_EXTERNAL_RESOLUTION") or "false").lower() == "true"
163
+ groups = _rust_resolve_calls(all_file_data, imports_map, skip_external)
164
+ else:
165
+ groups = build_function_call_groups(all_file_data, imports_map, None)
166
+ writer.write_function_call_groups(*groups)
167
+ t2 = time.time()
168
+ info_logger(f"Function calls created in {t2 - t1:.1f}s. Total post-processing: {t2 - t0:.1f}s")
169
+
170
+ if job_id:
171
+ job_manager.update_job(job_id, status=JobStatus.COMPLETED, end_time=datetime.now())
@@ -0,0 +1,105 @@
1
+ """Build global imports_map via language-specific pre-scan (registry dispatch)."""
2
+
3
+ from pathlib import Path
4
+ from typing import Any, Callable, Dict, List, Optional
5
+
6
+ # (extension -> callable(files, get_parser_for_ext) -> dict updates)
7
+ _PreScanFn = Callable[[List[Path], Callable[[str], Any]], dict]
8
+
9
+
10
+ def _register_prescans() -> Dict[str, _PreScanFn]:
11
+ from ..languages import python as python_lang_module
12
+ from ..languages import javascript as js_lang_module
13
+ from ..languages import go as go_lang_module
14
+ from ..languages import typescript as ts_lang_module
15
+ from ..languages import typescriptjsx as tsx_lang_module
16
+ from ..languages import cpp as cpp_lang_module
17
+ from ..languages import rust as rust_lang_module
18
+ from ..languages import c as c_lang_module
19
+ from ..languages import java as java_lang_module
20
+ from ..languages import ruby as ruby_lang_module
21
+ from ..languages import csharp as csharp_lang_module
22
+ from ..languages import kotlin as kotlin_lang_module
23
+ from ..languages import scala as scala_lang_module
24
+ from ..languages import swift as swift_lang_module
25
+ from ..languages import dart as dart_lang_module
26
+ from ..languages import perl as perl_lang_module
27
+ from ..languages import php as php_lang_module
28
+ from ..languages import haskell as haskell_lang_module
29
+ from ..languages import elixir as elixir_lang_module
30
+
31
+ def make_py(ext: str) -> _PreScanFn:
32
+ def scan(files: List[Path], gp: Callable[[str], Any]) -> dict:
33
+ return python_lang_module.pre_scan_python(files, gp(ext))
34
+
35
+ return scan
36
+
37
+ def make_js(ext: str) -> _PreScanFn:
38
+ def scan(files: List[Path], gp: Callable[[str], Any]) -> dict:
39
+ return js_lang_module.pre_scan_javascript(files, gp(ext))
40
+
41
+ return scan
42
+
43
+ return {
44
+ ".py": make_py(".py"),
45
+ ".ipynb": make_py(".ipynb"),
46
+ ".js": make_js(".js"),
47
+ ".jsx": make_js(".jsx"),
48
+ ".mjs": make_js(".mjs"),
49
+ ".cjs": make_js(".cjs"),
50
+ ".go": lambda files, gp: go_lang_module.pre_scan_go(files, gp(".go")),
51
+ ".ts": lambda files, gp: ts_lang_module.pre_scan_typescript(files, gp(".ts")),
52
+ ".tsx": lambda files, gp: tsx_lang_module.pre_scan_typescript(files, gp(".tsx")),
53
+ ".cpp": lambda files, gp: cpp_lang_module.pre_scan_cpp(files, gp(".cpp")),
54
+ ".h": lambda files, gp: cpp_lang_module.pre_scan_cpp(files, gp(".h")),
55
+ ".hpp": lambda files, gp: cpp_lang_module.pre_scan_cpp(files, gp(".hpp")),
56
+ ".hh": lambda files, gp: cpp_lang_module.pre_scan_cpp(files, gp(".hh")),
57
+ ".rs": lambda files, gp: rust_lang_module.pre_scan_rust(files, gp(".rs")),
58
+ ".c": lambda files, gp: c_lang_module.pre_scan_c(files, gp(".c")),
59
+ ".java": lambda files, gp: java_lang_module.pre_scan_java(files, gp(".java")),
60
+ ".rb": lambda files, gp: ruby_lang_module.pre_scan_ruby(files, gp(".rb")),
61
+ ".cs": lambda files, gp: csharp_lang_module.pre_scan_csharp(files, gp(".cs")),
62
+ ".kt": lambda files, gp: kotlin_lang_module.pre_scan_kotlin(files, gp(".kt")),
63
+ ".scala": lambda files, gp: scala_lang_module.pre_scan_scala(files, gp(".scala")),
64
+ ".sc": lambda files, gp: scala_lang_module.pre_scan_scala(files, gp(".sc")),
65
+ ".swift": lambda files, gp: swift_lang_module.pre_scan_swift(files, gp(".swift")),
66
+ ".dart": lambda files, gp: dart_lang_module.pre_scan_dart(files, gp(".dart")),
67
+ ".pl": lambda files, gp: perl_lang_module.pre_scan_perl(files, gp(".pl")),
68
+ ".pm": lambda files, gp: perl_lang_module.pre_scan_perl(files, gp(".pm")),
69
+ ".php": lambda files, gp: php_lang_module.pre_scan_php(files, gp(".php")),
70
+ ".hs": lambda files, gp: haskell_lang_module.pre_scan_haskell(files, gp(".hs")),
71
+ ".ex": lambda files, gp: elixir_lang_module.pre_scan_elixir(files, gp(".ex")),
72
+ ".exs": lambda files, gp: elixir_lang_module.pre_scan_elixir(files, gp(".exs")),
73
+ }
74
+
75
+
76
+ _PRESCAN_REGISTRY: Optional[Dict[str, _PreScanFn]] = None
77
+
78
+
79
+ def _get_registry() -> Dict[str, _PreScanFn]:
80
+ global _PRESCAN_REGISTRY
81
+ if _PRESCAN_REGISTRY is None:
82
+ _PRESCAN_REGISTRY = _register_prescans()
83
+ return _PRESCAN_REGISTRY
84
+
85
+
86
+ def pre_scan_for_imports(
87
+ files: List[Path],
88
+ parsers_keys: Any,
89
+ get_parser: Callable[[str], Any],
90
+ ) -> dict:
91
+ """Dispatch pre-scan by file extension; *parsers_keys* is the set of supported extensions (e.g. graph_builder.parsers.keys())."""
92
+ imports_map: dict = {}
93
+ files_by_ext: Dict[str, List[Path]] = {}
94
+ for file in files:
95
+ if file.suffix in parsers_keys:
96
+ ext = file.suffix
97
+ files_by_ext.setdefault(ext, []).append(file)
98
+
99
+ registry = _get_registry()
100
+ for ext, file_list in files_by_ext.items():
101
+ scanner = registry.get(ext)
102
+ if scanner:
103
+ imports_map.update(scanner(file_list, get_parser))
104
+
105
+ return imports_map
@@ -0,0 +1,154 @@
1
+ """Extract design rationale from source code comments.
2
+
3
+ Captures: NOTE, WHY, HACK, TODO, FIXME, IMPORTANT, WARNING, SAFETY,
4
+ WORKAROUND, ASSUMPTION, CONSTRAINT, DECISION, TRADE-OFF comments.
5
+
6
+ These explain "why" code was written a certain way — the most valuable
7
+ information for documentation that pure AST parsing misses.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import logging
13
+ import os
14
+ import re
15
+ from pathlib import Path
16
+ from typing import Any, Dict, List
17
+
18
+ logger = logging.getLogger(__name__)
19
+
20
+ # Patterns that indicate design rationale in comments
21
+ _RATIONALE_PATTERN = re.compile(
22
+ r'(?:^|\s)(?://|#|/\*\*?|\*)\s*' # comment prefix: //, #, /*, *, /**
23
+ r'(NOTE|WHY|HACK|TODO|FIXME|IMPORTANT|WARNING|SAFETY|'
24
+ r'WORKAROUND|ASSUMPTION|CONSTRAINT|DECISION|TRADE.?OFF|'
25
+ r'REVIEW|OPTIMIZE|DEPRECATED|BREAKING|MIGRATION|'
26
+ r'CONTEXT|REASON|RATIONALE|EXPLAIN|CAVEAT|GOTCHA|PITFALL)'
27
+ r'\s*:?\s*(.+)',
28
+ re.IGNORECASE | re.MULTILINE,
29
+ )
30
+
31
+ # Language extensions that support comments
32
+ _COMMENT_LANGS = {
33
+ '.py', '.js', '.jsx', '.ts', '.tsx', '.java', '.go', '.rs',
34
+ '.rb', '.php', '.cs', '.kt', '.scala', '.swift', '.c', '.cpp',
35
+ '.h', '.hpp', '.m', '.dart', '.ex', '.exs', '.hs', '.pl',
36
+ }
37
+
38
+
39
+ def extract_rationales(
40
+ parsed_results: List[Dict[str, Any]],
41
+ repo_path: str,
42
+ ) -> List[Dict[str, Any]]:
43
+ """Extract design rationale comments from source files.
44
+
45
+ Returns list of:
46
+ {
47
+ tag: str (NOTE, WHY, HACK, TODO, etc.),
48
+ text: str (the rationale text),
49
+ file: str (relative path),
50
+ line: int,
51
+ context: str (nearby function/class name),
52
+ }
53
+ """
54
+ rationales: List[Dict[str, Any]] = []
55
+
56
+ for file_data in parsed_results:
57
+ if "error" in file_data:
58
+ continue
59
+
60
+ file_path = file_data.get("path", "")
61
+ ext = Path(file_path).suffix.lower()
62
+
63
+ if ext not in _COMMENT_LANGS:
64
+ continue
65
+
66
+ if not os.path.exists(file_path):
67
+ continue
68
+
69
+ try:
70
+ rel_path = os.path.relpath(file_path, repo_path)
71
+ except ValueError:
72
+ rel_path = Path(file_path).name
73
+
74
+ # Build line → function context map
75
+ # Functions are applied outermost-first (by start line, then longest
76
+ # span first), so a nested function overrides its enclosing one and
77
+ # the result doesn't depend on the order the parser listed them in.
78
+ # The parser reports `end_line` (not `body_end_line`); without it every
79
+ # function spanned 50 lines and overlapping ranges were won by
80
+ # whichever came last.
81
+ func_context: Dict[int, str] = {}
82
+ spans = []
83
+ for fn in file_data.get("functions", []):
84
+ start = fn.get("line_number", 0)
85
+ end = fn.get("end_line") or fn.get("body_end_line") or start + 50
86
+ name = fn.get("name", "")
87
+ ctx = fn.get("class_context", "")
88
+ spans.append((start, -end, f"{ctx}.{name}" if ctx else name))
89
+ for start, neg_end, full_name in sorted(spans):
90
+ for line in range(start, -neg_end + 1):
91
+ func_context[line] = full_name
92
+
93
+ # Scan source for rationale comments
94
+ try:
95
+ with open(file_path, "r", encoding="utf-8", errors="replace") as fh:
96
+ for line_no, line in enumerate(fh, 1):
97
+ for m in _RATIONALE_PATTERN.finditer(line):
98
+ tag = m.group(1).upper()
99
+ text = m.group(2).strip()
100
+
101
+ # Decode unicode escapes:
102
+ # 1. \u0111\u00e3 (with backslash) → đã
103
+ # 2. u0111u00e3 (literal, no backslash) → đã
104
+ if "\\u" in text:
105
+ try:
106
+ text = text.encode("utf-8").decode("unicode_escape").encode("latin-1").decode("utf-8")
107
+ except (UnicodeDecodeError, UnicodeEncodeError):
108
+ pass
109
+ elif re.search(r'u[0-9a-fA-F]{4}', text):
110
+ # Multi-pass: greedily replace uXXXX sequences
111
+ # that decode to non-ASCII chars (Vietnamese, Latin Extended)
112
+ def _decode_u(m):
113
+ cp = int(m.group(1), 16)
114
+ # Only replace if codepoint is non-ASCII (> 0x7F)
115
+ # This avoids mangling ASCII like "url", "use"
116
+ if cp > 0x7F:
117
+ return chr(cp)
118
+ return m.group(0)
119
+ try:
120
+ text = re.sub(
121
+ r'u([0-9a-fA-F]{4})',
122
+ _decode_u,
123
+ text,
124
+ )
125
+ except (ValueError, OverflowError):
126
+ pass
127
+
128
+ # Skip very short or empty rationales
129
+ if len(text) < 5:
130
+ continue
131
+
132
+ # Find nearest function context
133
+ context = func_context.get(line_no, "")
134
+ if not context:
135
+ # Check lines above
136
+ for delta in range(1, 10):
137
+ context = func_context.get(line_no - delta, "")
138
+ if context:
139
+ break
140
+
141
+ rationales.append({
142
+ "tag": tag,
143
+ "text": text,
144
+ "file": rel_path,
145
+ "line": line_no,
146
+ "context": context,
147
+ })
148
+ except OSError:
149
+ continue
150
+
151
+ # Sort by file + line
152
+ rationales.sort(key=lambda r: (r["file"], r["line"]))
153
+ logger.info("Extracted %d rationale comments", len(rationales))
154
+ return rationales
@@ -0,0 +1,8 @@
1
+ from .calls import build_function_call_groups, resolve_function_call
2
+ from .inheritance import build_inheritance_and_csharp_files
3
+
4
+ __all__ = [
5
+ "build_function_call_groups",
6
+ "resolve_function_call",
7
+ "build_inheritance_and_csharp_files",
8
+ ]