codeatlas-viz 0.2.2__tar.gz

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 (26) hide show
  1. codeatlas_viz-0.2.2/LICENSE +21 -0
  2. codeatlas_viz-0.2.2/PKG-INFO +146 -0
  3. codeatlas_viz-0.2.2/README.md +119 -0
  4. codeatlas_viz-0.2.2/pyproject.toml +48 -0
  5. codeatlas_viz-0.2.2/setup.cfg +4 -0
  6. codeatlas_viz-0.2.2/src/codeatlas/__init__.py +15 -0
  7. codeatlas_viz-0.2.2/src/codeatlas/analyzers/__init__.py +72 -0
  8. codeatlas_viz-0.2.2/src/codeatlas/analyzers/base.py +20 -0
  9. codeatlas_viz-0.2.2/src/codeatlas/analyzers/c_family_analyzer.py +208 -0
  10. codeatlas_viz-0.2.2/src/codeatlas/analyzers/js_analyzer.py +207 -0
  11. codeatlas_viz-0.2.2/src/codeatlas/analyzers/python_analyzer.py +130 -0
  12. codeatlas_viz-0.2.2/src/codeatlas/cli.py +134 -0
  13. codeatlas_viz-0.2.2/src/codeatlas/models.py +276 -0
  14. codeatlas_viz-0.2.2/src/codeatlas/scanner.py +335 -0
  15. codeatlas_viz-0.2.2/src/codeatlas/server.py +208 -0
  16. codeatlas_viz-0.2.2/src/codeatlas/web/assets/index-WkvacVWK.js +4 -0
  17. codeatlas_viz-0.2.2/src/codeatlas/web/assets/index-vVc60hrc.css +1 -0
  18. codeatlas_viz-0.2.2/src/codeatlas/web/index.html +13 -0
  19. codeatlas_viz-0.2.2/src/codeatlas_viz.egg-info/PKG-INFO +146 -0
  20. codeatlas_viz-0.2.2/src/codeatlas_viz.egg-info/SOURCES.txt +24 -0
  21. codeatlas_viz-0.2.2/src/codeatlas_viz.egg-info/dependency_links.txt +1 -0
  22. codeatlas_viz-0.2.2/src/codeatlas_viz.egg-info/entry_points.txt +2 -0
  23. codeatlas_viz-0.2.2/src/codeatlas_viz.egg-info/requires.txt +3 -0
  24. codeatlas_viz-0.2.2/src/codeatlas_viz.egg-info/top_level.txt +1 -0
  25. codeatlas_viz-0.2.2/tests/test_analyzers.py +278 -0
  26. codeatlas_viz-0.2.2/tests/test_scanner_and_server.py +269 -0
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 kutyfuty
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,146 @@
1
+ Metadata-Version: 2.4
2
+ Name: codeatlas-viz
3
+ Version: 0.2.2
4
+ Summary: Zero-config local codebase architecture & call-graph visualizer with an interactive Svelte UI.
5
+ Author: kutyfuty
6
+ License: MIT
7
+ Project-URL: Homepage, https://github.com/kutyfuty/codeatlas
8
+ Project-URL: Repository, https://github.com/kutyfuty/codeatlas
9
+ Project-URL: Issues, https://github.com/kutyfuty/codeatlas/issues
10
+ Keywords: cli,call-graph,ast,architecture,visualizer,developer-tools,svelte
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Environment :: Console
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: License :: OSI Approved :: MIT License
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3.10
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Topic :: Software Development :: Code Generators
20
+ Classifier: Topic :: Software Development :: Documentation
21
+ Requires-Python: >=3.10
22
+ Description-Content-Type: text/markdown
23
+ License-File: LICENSE
24
+ Provides-Extra: dev
25
+ Requires-Dist: pytest>=8.0; extra == "dev"
26
+ Dynamic: license-file
27
+
28
+ # CodeAtlas
29
+
30
+ **Zero-config local codebase architecture & call-graph visualizer.**
31
+
32
+ Inspect functions, classes, call-graph hubs, unreferenced ("dead") code, circular dependencies, and shortest call paths in your terminal or browser—with zero cloud uploads, zero configuration files, and zero runtime dependencies for the CLI.
33
+
34
+ ![CodeAtlas interactive Svelte call-graph demo](docs/demo.gif)
35
+
36
+ <details>
37
+ <summary>More screenshots (Overview, Focus 1-hop, File-level Graph)</summary>
38
+
39
+ | Symbol Graph & Path Finder | Focus 1-Hop Isolation | File Dependency Map |
40
+ |---|---|---|
41
+ | ![CodeAtlas Symbol Graph](docs/demo-ui.png) | ![CodeAtlas Focus 1-Hop](docs/demo-focus.png) | ![CodeAtlas File Graph](docs/demo-files.png) |
42
+
43
+ </details>
44
+
45
+ ---
46
+
47
+ ## Key Features
48
+
49
+ - **Zero Runtime Dependencies:** Pure Python standard-library CLI (`pip` / `pipx` ready).
50
+ - **Multi-Language Analysis (9 Languages):**
51
+ - **Python:** Full `ast` parsing for classes, methods, nested functions, docstrings, relative imports, and import aliases.
52
+ - **JavaScript / TypeScript / Svelte:** Structural analysis of functions, arrow functions, ES6 classes, methods, getters/setters, class arrow properties, and `<script>` blocks.
53
+ - **Go / Rust / Java / C / C++:** Structural parsing of structs, traits/impl blocks, receiver methods, classes, and member call sites.
54
+ - **Architectural Health Score & Standalone HTML Report:**
55
+ - Computes a `0–100` repository health score based on circular dependency and dead-code ratios.
56
+ - Export self-contained single-file `.html` architecture reports (`codeatlas export . --format html -o report.html`).
57
+ - **Interactive Svelte 5 Web UI (`codeatlas serve`):**
58
+ - Switch between **Symbol-Level** and **File-Level** dependency graphs.
59
+ - **Hubs, Circular Dependencies (`Cycles`), and Unreferenced (`Dead`)** tabs.
60
+ - **Shortest Call-Path Finder (BFS):** Highlight the exact call chain (`A → ... → B`) between any two symbols.
61
+ - **Focus 1-Hop Mode:** Isolate callers and callees of the selected symbol.
62
+ - **Live Source Preview:** Inspect exact source lines directly in the side panel.
63
+ - **One-Click Exports:** Download `.svg` or `.mmd` (Mermaid) diagrams directly from the toolbar.
64
+ - **Fast & Scalable:** Iterative Tarjan strongly-connected-components (SCC) cycle detection, precompiled `.gitignore` matching, and automatic minified bundle filtering.
65
+
66
+ ---
67
+
68
+ ## Architecture Overview
69
+
70
+ ```mermaid
71
+ flowchart LR
72
+ CLI["cli.py (main)"] --> Scanner["scanner.py (scan_directory)"]
73
+ CLI --> Server["server.py (serve_graph)"]
74
+ Scanner --> AnalyzerRegistry["analyzers/__init__.py (analyze_file)"]
75
+ AnalyzerRegistry --> PyAnalyzer["python_analyzer.py (analyze_python)"]
76
+ AnalyzerRegistry --> JsAnalyzer["js_analyzer.py (analyze_js)"]
77
+ Scanner --> GraphModel["models.py (CodeGraph)"]
78
+ Server --> WebUI["Svelte 5 Web UI (/api/graph & /api/file)"]
79
+ ```
80
+
81
+ ---
82
+
83
+ ## Installation
84
+
85
+ ```bash
86
+ # Run directly with pipx / uvx (once published to PyPI)
87
+ pipx install codeatlas-viz
88
+
89
+ # Or install from source
90
+ git clone https://github.com/kutyfuty/codeatlas.git
91
+ cd codeatlas
92
+ pip install -e .
93
+ ```
94
+
95
+ ## Usage
96
+
97
+ ### 1. Terminal Summary (`scan`)
98
+
99
+ ```bash
100
+ codeatlas .
101
+ # or explicitly:
102
+ codeatlas scan /path/to/repo
103
+ ```
104
+
105
+ ### 2. Interactive Web UI (`serve`)
106
+
107
+ ```bash
108
+ codeatlas serve .
109
+ # Custom port / without auto-opening browser:
110
+ codeatlas serve /path/to/repo --port 4173 --no-open
111
+ ```
112
+
113
+ ### 3. Export Graph (`export`)
114
+
115
+ ```bash
116
+ # Export as self-contained single-file HTML report
117
+ codeatlas export . --format html -o report.html
118
+
119
+ # Export as GitHub-flavored Markdown summary (great for PR comments / CI)
120
+ codeatlas export . --format markdown -o SUMMARY.md
121
+
122
+ # Export as Mermaid flowchart
123
+ codeatlas export . --format mermaid -o architecture.mmd
124
+
125
+ # Export full graph analytics as JSON
126
+ codeatlas export . --format json -o graph.json
127
+ ```
128
+
129
+ ---
130
+
131
+ ## Development & Testing
132
+
133
+ ```bash
134
+ # Backend tests
135
+ pip install -e ".[dev]"
136
+ pytest -v
137
+
138
+ # Rebuild Svelte static bundle (outputs to src/codeatlas/web/)
139
+ cd frontend
140
+ npm install
141
+ npm run build
142
+ ```
143
+
144
+ ## License
145
+
146
+ [MIT](LICENSE)
@@ -0,0 +1,119 @@
1
+ # CodeAtlas
2
+
3
+ **Zero-config local codebase architecture & call-graph visualizer.**
4
+
5
+ Inspect functions, classes, call-graph hubs, unreferenced ("dead") code, circular dependencies, and shortest call paths in your terminal or browser—with zero cloud uploads, zero configuration files, and zero runtime dependencies for the CLI.
6
+
7
+ ![CodeAtlas interactive Svelte call-graph demo](docs/demo.gif)
8
+
9
+ <details>
10
+ <summary>More screenshots (Overview, Focus 1-hop, File-level Graph)</summary>
11
+
12
+ | Symbol Graph & Path Finder | Focus 1-Hop Isolation | File Dependency Map |
13
+ |---|---|---|
14
+ | ![CodeAtlas Symbol Graph](docs/demo-ui.png) | ![CodeAtlas Focus 1-Hop](docs/demo-focus.png) | ![CodeAtlas File Graph](docs/demo-files.png) |
15
+
16
+ </details>
17
+
18
+ ---
19
+
20
+ ## Key Features
21
+
22
+ - **Zero Runtime Dependencies:** Pure Python standard-library CLI (`pip` / `pipx` ready).
23
+ - **Multi-Language Analysis (9 Languages):**
24
+ - **Python:** Full `ast` parsing for classes, methods, nested functions, docstrings, relative imports, and import aliases.
25
+ - **JavaScript / TypeScript / Svelte:** Structural analysis of functions, arrow functions, ES6 classes, methods, getters/setters, class arrow properties, and `<script>` blocks.
26
+ - **Go / Rust / Java / C / C++:** Structural parsing of structs, traits/impl blocks, receiver methods, classes, and member call sites.
27
+ - **Architectural Health Score & Standalone HTML Report:**
28
+ - Computes a `0–100` repository health score based on circular dependency and dead-code ratios.
29
+ - Export self-contained single-file `.html` architecture reports (`codeatlas export . --format html -o report.html`).
30
+ - **Interactive Svelte 5 Web UI (`codeatlas serve`):**
31
+ - Switch between **Symbol-Level** and **File-Level** dependency graphs.
32
+ - **Hubs, Circular Dependencies (`Cycles`), and Unreferenced (`Dead`)** tabs.
33
+ - **Shortest Call-Path Finder (BFS):** Highlight the exact call chain (`A → ... → B`) between any two symbols.
34
+ - **Focus 1-Hop Mode:** Isolate callers and callees of the selected symbol.
35
+ - **Live Source Preview:** Inspect exact source lines directly in the side panel.
36
+ - **One-Click Exports:** Download `.svg` or `.mmd` (Mermaid) diagrams directly from the toolbar.
37
+ - **Fast & Scalable:** Iterative Tarjan strongly-connected-components (SCC) cycle detection, precompiled `.gitignore` matching, and automatic minified bundle filtering.
38
+
39
+ ---
40
+
41
+ ## Architecture Overview
42
+
43
+ ```mermaid
44
+ flowchart LR
45
+ CLI["cli.py (main)"] --> Scanner["scanner.py (scan_directory)"]
46
+ CLI --> Server["server.py (serve_graph)"]
47
+ Scanner --> AnalyzerRegistry["analyzers/__init__.py (analyze_file)"]
48
+ AnalyzerRegistry --> PyAnalyzer["python_analyzer.py (analyze_python)"]
49
+ AnalyzerRegistry --> JsAnalyzer["js_analyzer.py (analyze_js)"]
50
+ Scanner --> GraphModel["models.py (CodeGraph)"]
51
+ Server --> WebUI["Svelte 5 Web UI (/api/graph & /api/file)"]
52
+ ```
53
+
54
+ ---
55
+
56
+ ## Installation
57
+
58
+ ```bash
59
+ # Run directly with pipx / uvx (once published to PyPI)
60
+ pipx install codeatlas-viz
61
+
62
+ # Or install from source
63
+ git clone https://github.com/kutyfuty/codeatlas.git
64
+ cd codeatlas
65
+ pip install -e .
66
+ ```
67
+
68
+ ## Usage
69
+
70
+ ### 1. Terminal Summary (`scan`)
71
+
72
+ ```bash
73
+ codeatlas .
74
+ # or explicitly:
75
+ codeatlas scan /path/to/repo
76
+ ```
77
+
78
+ ### 2. Interactive Web UI (`serve`)
79
+
80
+ ```bash
81
+ codeatlas serve .
82
+ # Custom port / without auto-opening browser:
83
+ codeatlas serve /path/to/repo --port 4173 --no-open
84
+ ```
85
+
86
+ ### 3. Export Graph (`export`)
87
+
88
+ ```bash
89
+ # Export as self-contained single-file HTML report
90
+ codeatlas export . --format html -o report.html
91
+
92
+ # Export as GitHub-flavored Markdown summary (great for PR comments / CI)
93
+ codeatlas export . --format markdown -o SUMMARY.md
94
+
95
+ # Export as Mermaid flowchart
96
+ codeatlas export . --format mermaid -o architecture.mmd
97
+
98
+ # Export full graph analytics as JSON
99
+ codeatlas export . --format json -o graph.json
100
+ ```
101
+
102
+ ---
103
+
104
+ ## Development & Testing
105
+
106
+ ```bash
107
+ # Backend tests
108
+ pip install -e ".[dev]"
109
+ pytest -v
110
+
111
+ # Rebuild Svelte static bundle (outputs to src/codeatlas/web/)
112
+ cd frontend
113
+ npm install
114
+ npm run build
115
+ ```
116
+
117
+ ## License
118
+
119
+ [MIT](LICENSE)
@@ -0,0 +1,48 @@
1
+ [build-system]
2
+ requires = ["setuptools>=68.0", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "codeatlas-viz"
7
+ version = "0.2.2"
8
+ description = "Zero-config local codebase architecture & call-graph visualizer with an interactive Svelte UI."
9
+ readme = "README.md"
10
+ license = {text = "MIT"}
11
+ requires-python = ">=3.10"
12
+ authors = [
13
+ {name = "kutyfuty"}
14
+ ]
15
+ keywords = ["cli", "call-graph", "ast", "architecture", "visualizer", "developer-tools", "svelte"]
16
+ classifiers = [
17
+ "Development Status :: 3 - Alpha",
18
+ "Environment :: Console",
19
+ "Intended Audience :: Developers",
20
+ "License :: OSI Approved :: MIT License",
21
+ "Programming Language :: Python :: 3",
22
+ "Programming Language :: Python :: 3.10",
23
+ "Programming Language :: Python :: 3.11",
24
+ "Programming Language :: Python :: 3.12",
25
+ "Topic :: Software Development :: Code Generators",
26
+ "Topic :: Software Development :: Documentation",
27
+ ]
28
+ dependencies = []
29
+
30
+ [project.urls]
31
+ Homepage = "https://github.com/kutyfuty/codeatlas"
32
+ Repository = "https://github.com/kutyfuty/codeatlas"
33
+ Issues = "https://github.com/kutyfuty/codeatlas/issues"
34
+
35
+ [project.optional-dependencies]
36
+ dev = ["pytest>=8.0"]
37
+
38
+ [project.scripts]
39
+ codeatlas = "codeatlas.cli:main"
40
+
41
+ [tool.setuptools.packages.find]
42
+ where = ["src"]
43
+
44
+ [tool.setuptools.package-data]
45
+ codeatlas = ["web/*", "web/**/*"]
46
+
47
+ [tool.pytest.ini_options]
48
+ testpaths = ["tests"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,15 @@
1
+ """CodeAtlas: Zero-config local codebase architecture & call-graph visualizer."""
2
+
3
+ from .models import CallEdge, CodeGraph, FileSummary, SymbolNode
4
+ from .scanner import scan_directory
5
+
6
+ __version__ = "0.2.2"
7
+
8
+ __all__ = [
9
+ "__version__",
10
+ "CallEdge",
11
+ "CodeGraph",
12
+ "FileSummary",
13
+ "SymbolNode",
14
+ "scan_directory",
15
+ ]
@@ -0,0 +1,72 @@
1
+ """Language analyzer registry."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from pathlib import Path
6
+
7
+ from .base import ParsedFile
8
+ from .c_family_analyzer import analyze_c_family
9
+ from .js_analyzer import analyze_js
10
+ from .python_analyzer import analyze_python
11
+
12
+ EXTENSION_LANGUAGE: dict[str, str] = {
13
+ ".py": "python",
14
+ ".js": "javascript",
15
+ ".jsx": "javascript",
16
+ ".mjs": "javascript",
17
+ ".ts": "typescript",
18
+ ".tsx": "typescript",
19
+ ".svelte": "svelte",
20
+ ".go": "go",
21
+ ".rs": "rust",
22
+ ".java": "java",
23
+ ".c": "c",
24
+ ".h": "c",
25
+ ".cpp": "cpp",
26
+ ".cc": "cpp",
27
+ ".cxx": "cpp",
28
+ ".hpp": "cpp",
29
+ }
30
+
31
+ _C_FAMILY_LANGS = frozenset({"go", "rust", "java", "c", "cpp"})
32
+ _MINIFIABLE_LANGS = frozenset({"javascript", "typescript"})
33
+
34
+
35
+ def _looks_minified_source(source: str, lang: str) -> bool:
36
+ """Detect minified JS/TS bundles from already-loaded source without re-opening the file."""
37
+ if lang not in _MINIFIABLE_LANGS:
38
+ return False
39
+ pos = 0
40
+ for _ in range(10):
41
+ nl = source.find("\n", pos)
42
+ line_len = (len(source) - pos) if nl == -1 else (nl - pos)
43
+ if line_len > 700:
44
+ return True
45
+ if nl == -1:
46
+ break
47
+ pos = nl + 1
48
+ return False
49
+
50
+
51
+ def analyze_file(path: Path, rel_path: str) -> tuple[str, int, ParsedFile] | None:
52
+ """Analyze a source file if its extension is supported."""
53
+ lang = EXTENSION_LANGUAGE.get(path.suffix.lower())
54
+ if not lang:
55
+ return None
56
+
57
+ try:
58
+ source = path.read_text(encoding="utf-8", errors="replace")
59
+ except OSError:
60
+ return None
61
+
62
+ if _looks_minified_source(source, lang):
63
+ return None
64
+
65
+ line_count = source.count("\n") + (1 if source else 0)
66
+ if lang == "python":
67
+ parsed = analyze_python(source, rel_path)
68
+ elif lang in _C_FAMILY_LANGS:
69
+ parsed = analyze_c_family(source, rel_path, language=lang)
70
+ else:
71
+ parsed = analyze_js(source, rel_path, language=lang)
72
+ return lang, line_count, parsed
@@ -0,0 +1,20 @@
1
+ """Shared analyzer types."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass, field
6
+
7
+ from ..models import SymbolNode
8
+
9
+
10
+ @dataclass(slots=True)
11
+ class ParsedFile:
12
+ """Intermediate representation produced by a language analyzer."""
13
+
14
+ symbols: list[SymbolNode] = field(default_factory=list)
15
+ # Maps caller symbol ID -> list of raw callee names referenced inside it.
16
+ raw_calls: dict[str, list[str]] = field(default_factory=dict)
17
+ # Imported module/file hints to help disambiguate cross-file calls.
18
+ imports: list[str] = field(default_factory=list)
19
+ # Maps local alias -> original imported symbol name (e.g. "vt" -> "verify_token").
20
+ aliases: dict[str, str] = field(default_factory=dict)
@@ -0,0 +1,208 @@
1
+ """Structural analyzer for Go, Rust, Java, and C/C++ source files."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+
7
+ from ..models import SymbolNode
8
+ from .base import ParsedFile
9
+ from .js_analyzer import (
10
+ _build_line_index,
11
+ _find_matching_brace,
12
+ _line_at,
13
+ _strip_comments_and_strings,
14
+ )
15
+
16
+ _C_FAMILY_KEYWORDS = frozenset({
17
+ "if", "else", "for", "while", "do", "switch", "case", "catch", "finally",
18
+ "try", "return", "throw", "sizeof", "alignof", "typeof", "new", "delete",
19
+ "class", "struct", "enum", "union", "interface", "impl", "trait", "fn",
20
+ "func", "pub", "private", "protected", "public", "static", "const",
21
+ "virtual", "override", "synchronized", "match", "loop", "where", "defer",
22
+ "go", "select", "chan", "package", "import", "use", "mod", "crate",
23
+ "super", "self", "this", "main", "printf", "println", "fmt", "std",
24
+ })
25
+
26
+ # Go: func (r *Recv) Name(args) [ret] { OR func Name(args) [ret] {
27
+ _GO_FUNC_RE = re.compile(
28
+ r"""(?:^|\n)\s*func\s+(?:\(\s*[A-Za-z_]\w*\s+\*?([A-Za-z_]\w*)\s*\)\s+)?([A-Za-z_]\w*)\s*(?:\[[^\]]*\])?\s*\([^)]*\)[^{;]*\{""",
29
+ )
30
+ _GO_IMPORT_RE = re.compile(r'"([^"]+)"')
31
+
32
+ # Rust: [pub] [async] [unsafe] fn name[<T>](args) [-> Ret] [where ...] {
33
+ _RUST_STRUCT_IMPL_RE = re.compile(
34
+ r"""(?:^|\n)\s*(?:pub(?:\([^)]*\))?\s+)?(?:struct|enum|trait|impl(?:\s*<[^>]*>)?(?:\s+[A-Za-z_][\w:<>]*\s+for)?)\s+([A-Za-z_]\w*)[^{;]*\{""",
35
+ )
36
+ _RUST_FN_RE = re.compile(
37
+ r"""(?:^|\n)\s*(?:pub(?:\([^)]*\))?\s+)?(?:const\s+)?(?:async\s+)?(?:unsafe\s+)?fn\s+([A-Za-z_]\w*)\s*(?:<[^>]*>)?\s*\([^)]*\)[^{;]*\{""",
38
+ )
39
+ _RUST_USE_RE = re.compile(r"""(?:^|\n)\s*use\s+([A-Za-z_][\w:]*)\s*;""")
40
+
41
+ # Java / C / C++ classes & functions/methods (no nested quantifiers to avoid ReDoS)
42
+ _CLASS_STRUCT_RE = re.compile(
43
+ r"""(?:^|[\n;{}])\s*(?:(?:public|private|protected|abstract|final|static)\s+)*(?:class|struct|interface)\s+([A-Za-z_]\w*)[^{;]*\{""",
44
+ )
45
+ _CFAMILY_FUNC_RE = re.compile(
46
+ r"""(?:^|[\n;{}])\s*(?:(?:public|private|protected|static|final|virtual|inline|explicit|constexpr|synchronized|native|async)\s+)*(?:[A-Za-z_~][\w:<>,*&]*\s+)+([A-Za-z_~][\w:]*(?:::[A-Za-z_~]\w*)?)\s*\([^;{}]*\)\s*(?:const\s*)?(?:noexcept\s*)?(?:override\s*)?(?:throws\s+[A-Za-z0-9_.,\s]+)?\{""",
47
+ )
48
+ _JAVA_IMPORT_RE = re.compile(r"""(?:^|\n)\s*import\s+(?:static\s+)?([A-Za-z_][\w.]*)\s*;""")
49
+ _CPP_INCLUDE_RE = re.compile(r"""#\s*include\s*[<"]([^>"]+)[>"]""")
50
+
51
+ _CALL_RE = re.compile(r"""(?<![.\w:])([A-Za-z_]\w*)\s*\(""")
52
+ _MEMBER_CALL_RE = re.compile(r"""(?:\.|->|::)([A-Za-z_]\w*)\s*\(""")
53
+
54
+
55
+ def _extract_calls(body: str) -> list[str]:
56
+ calls = [
57
+ m.group(1)
58
+ for m in _CALL_RE.finditer(body)
59
+ if m.group(1) not in _C_FAMILY_KEYWORDS
60
+ ]
61
+ calls.extend(
62
+ m.group(1)
63
+ for m in _MEMBER_CALL_RE.finditer(body)
64
+ if m.group(1) not in _C_FAMILY_KEYWORDS
65
+ )
66
+ return calls
67
+
68
+
69
+ def _innermost_parent(pos: int, spans: list[tuple[int, int, str]]) -> str | None:
70
+ """Return the innermost enclosing class/impl name for pos."""
71
+ best_span = None
72
+ best_name = None
73
+ for ob, cb, cname in spans:
74
+ if ob < pos < cb:
75
+ size = cb - ob
76
+ if best_span is None or size < best_span:
77
+ best_span = size
78
+ best_name = cname
79
+ return best_name
80
+
81
+
82
+ def _inside_any_span(pos: int, spans: list[tuple[int, int]]) -> bool:
83
+ return any(ob < pos < cb for ob, cb in spans)
84
+
85
+
86
+ def analyze_c_family(source: str, rel_path: str, language: str) -> ParsedFile:
87
+ """Analyze Go, Rust, Java, or C/C++ source code into symbols and call sites."""
88
+ imports: list[str] = []
89
+ if language == "go":
90
+ imports.extend(_GO_IMPORT_RE.findall(source))
91
+ elif language == "rust":
92
+ imports.extend(m.replace("::", "/") for m in _RUST_USE_RE.findall(source))
93
+ elif language == "java":
94
+ imports.extend(_JAVA_IMPORT_RE.findall(source))
95
+ elif language in {"c", "cpp"}:
96
+ imports.extend(_CPP_INCLUDE_RE.findall(source))
97
+
98
+ clean = _strip_comments_and_strings(source)
99
+ newlines = _build_line_index(clean)
100
+
101
+ symbols: list[SymbolNode] = []
102
+ raw_calls: dict[str, list[str]] = {}
103
+ seen_ids: set[str] = set()
104
+
105
+ def register(
106
+ name: str,
107
+ kind: str,
108
+ decl_start: int,
109
+ open_brace: int,
110
+ parent: str | None = None,
111
+ ) -> int:
112
+ close_idx = _find_matching_brace(clean, open_brace)
113
+ qname = f"{parent}.{name}" if parent else name
114
+ sym_id = f"{rel_path}::{qname}"
115
+ if sym_id in seen_ids:
116
+ return close_idx
117
+ seen_ids.add(sym_id)
118
+
119
+ symbols.append(
120
+ SymbolNode(
121
+ id=sym_id,
122
+ name=name,
123
+ kind=kind,
124
+ file=rel_path,
125
+ language=language,
126
+ start_line=_line_at(newlines, decl_start),
127
+ end_line=_line_at(newlines, close_idx),
128
+ parent=parent,
129
+ )
130
+ )
131
+ if kind != "class":
132
+ raw_calls[sym_id] = _extract_calls(clean[open_brace + 1 : close_idx])
133
+ return close_idx
134
+
135
+ if language == "go":
136
+ for m in _GO_FUNC_RE.finditer(clean):
137
+ recv, name = m.group(1), m.group(2)
138
+ kind = "method" if recv else "function"
139
+ register(name, kind, m.start(2), m.end() - 1, parent=recv)
140
+
141
+ elif language == "rust":
142
+ impl_spans: list[tuple[int, int, str]] = []
143
+ for m in _RUST_STRUCT_IMPL_RE.finditer(clean):
144
+ cname = m.group(1)
145
+ open_b = m.end() - 1
146
+ close_b = _find_matching_brace(clean, open_b)
147
+ register(cname, "class", m.start(1), open_b)
148
+ impl_spans.append((open_b, close_b, cname))
149
+
150
+ fn_spans: list[tuple[int, int]] = []
151
+ for m in _RUST_FN_RE.finditer(clean):
152
+ fn_name = m.group(1)
153
+ pos = m.start(1)
154
+ if _inside_any_span(pos, fn_spans):
155
+ continue
156
+ parent = _innermost_parent(pos, impl_spans)
157
+ open_b = m.end() - 1
158
+ close_b = register(
159
+ fn_name,
160
+ "method" if parent else "function",
161
+ pos,
162
+ open_b,
163
+ parent=parent,
164
+ )
165
+ fn_spans.append((open_b, close_b))
166
+
167
+ else:
168
+ # Java, C, C++
169
+ class_spans: list[tuple[int, int, str]] = []
170
+ for m in _CLASS_STRUCT_RE.finditer(clean):
171
+ cname = m.group(1)
172
+ if cname in _C_FAMILY_KEYWORDS:
173
+ continue
174
+ open_b = m.end() - 1
175
+ close_b = register(cname, "class", m.start(1), open_b)
176
+ class_spans.append((open_b, close_b, cname))
177
+
178
+ fn_spans = []
179
+ for m in _CFAMILY_FUNC_RE.finditer(clean):
180
+ raw_name = m.group(1)
181
+ pos = m.start(1)
182
+ if _inside_any_span(pos, fn_spans):
183
+ continue
184
+
185
+ parent: str | None = None
186
+ fname = raw_name
187
+ if "::" in raw_name:
188
+ parts = raw_name.split("::")
189
+ parent = parts[-2]
190
+ fname = parts[-1]
191
+ else:
192
+ parent = _innermost_parent(pos, class_spans)
193
+
194
+ if fname in _C_FAMILY_KEYWORDS:
195
+ continue
196
+
197
+ open_b = m.end() - 1
198
+ close_b = register(
199
+ fname,
200
+ "method" if parent else "function",
201
+ pos,
202
+ open_b,
203
+ parent=parent,
204
+ )
205
+ fn_spans.append((open_b, close_b))
206
+
207
+ symbols.sort(key=lambda s: s.start_line)
208
+ return ParsedFile(symbols=symbols, raw_calls=raw_calls, imports=imports)