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
// DagBuilder relationship processing: edges, imports, inheritance, and helper methods
impl DagBuilder {
fn process_relationships(&mut self, file: &FileContext) {
// The module node for the file itself is created during node collection
// (pass 1) so that imports can resolve against it here in pass 2.
let file_module_id = self.normalize_path(&file.path);
for item in &file.items {
self.process_single_relationship(item, &file_module_id);
}
}
fn process_single_relationship(&mut self, item: &AstItem, file_module_id: &str) {
match item {
AstItem::Use { path, line: _ } => {
self.process_use_import(path, file_module_id);
}
AstItem::Import {
module,
items,
alias: _,
line: _,
} => {
self.process_language_import(module, items, file_module_id);
}
AstItem::Impl {
type_name,
trait_name,
..
} => {
self.process_impl_relationship(type_name, trait_name);
}
_ => {}
}
}
fn process_use_import(&mut self, path: &str, file_module_id: &str) {
// Create import edges from the file module to imported items
if let Some(target_id) = self.resolve_import_path(path) {
self.add_edge(Edge {
from: file_module_id.to_string(),
to: target_id,
edge_type: EdgeType::Imports,
weight: 1,
});
}
}
fn process_language_import(
&mut self,
module: &str,
items: &[String],
file_module_id: &str,
) {
// Handle language-specific imports (Python, JavaScript, etc.)
// Create import edge to the module
if let Some(target_id) = self.resolve_import_path(module) {
self.add_edge(Edge {
from: file_module_id.to_string(),
to: target_id.clone(),
edge_type: EdgeType::Imports,
weight: 1,
});
}
// Also create edges for specific imported items
for item in items {
let full_path = format!("{module}.{item}");
if let Some(target_id) = self.resolve_import_path(&full_path) {
self.add_edge(Edge {
from: file_module_id.to_string(),
to: target_id,
edge_type: EdgeType::Imports,
weight: 1,
});
}
}
}
fn process_impl_relationship(
&mut self,
type_name: &str,
trait_name: &Option<String>,
) {
// Create inheritance edges for trait implementations
if let (Some(trait_name), Some(struct_id)) =
(trait_name.as_ref(), self.type_map.get(type_name))
{
if let Some(trait_id) = self.type_map.get(trait_name) {
self.add_edge(Edge {
from: struct_id.clone(),
to: trait_id.clone(),
edge_type: EdgeType::Inherits,
weight: 1,
});
}
}
}
fn add_node(&mut self, node: NodeInfo) {
self.graph.add_node(node);
}
fn add_edge(&mut self, edge: Edge) {
self.graph.add_edge(edge);
}
/// Enrich node with semantic naming and metadata
fn enrich_node(&self, mut node: NodeInfo) -> NodeInfo {
// Apply semantic naming
let semantic_name = self.namer.get_semantic_name(&node.id, &node);
if semantic_name != node.id && !semantic_name.is_empty() {
node.label = semantic_name;
}
// Add comprehensive metadata as specified in the bug report
node.metadata
.insert("file_path".to_string(), node.file_path.clone());
node.metadata.insert(
"module_path".to_string(),
self.path_to_module(&node.file_path),
);
node.metadata
.insert("display_name".to_string(), node.label.clone());
node.metadata
.insert("node_type".to_string(), format!("{:?}", node.node_type));
node.metadata
.insert("line_number".to_string(), node.line_number.to_string());
node.metadata
.insert("complexity".to_string(), node.complexity.to_string());
// Add language-specific metadata
let language = detect_language_from_path(&node.file_path);
node.metadata
.insert("language".to_string(), language.to_string());
node
}
fn normalize_path(&self, path: &str) -> String {
// Convert file path to a module-like identifier
path.trim_start_matches("./")
.trim_start_matches('/')
.trim_end_matches(".rs")
.trim_end_matches(".ts")
.trim_end_matches(".py")
.trim_end_matches(".js")
.trim_end_matches(".tsx")
.trim_end_matches(".jsx")
.replace(['/', '.', '-'], "_")
}
fn path_to_module(&self, path: &str) -> String {
// Convert file path to module notation using semantic namer
let ext = std::path::Path::new(path)
.extension()
.and_then(|e| e.to_str())
.unwrap_or("");
let language = SemanticNamer::detect_language(ext);
// Use the semantic namer's path_to_module logic indirectly
let clean_path = path
.trim_start_matches("./")
.trim_start_matches('/')
.trim_start_matches("src/")
.trim_start_matches("lib/")
.trim_start_matches("app/");
let without_ext = std::path::Path::new(clean_path)
.with_extension("")
.to_string_lossy()
.into_owned();
let separator = match language {
"rust" => "::",
"python" => ".",
"typescript" | "javascript" => ".",
"go" => "/",
"java" => ".",
_ => "::",
};
without_ext.replace(['/', '\\'], separator)
}
fn extract_module_name(&self, path: &str) -> String {
// Extract just the file name without extension
std::path::Path::new(path)
.file_stem()
.and_then(|s| s.to_str())
.unwrap_or(path)
.to_string()
}
/// Resolve a `use`/import path to a node that actually exists in the graph.
///
/// Defect #653: the old version ended with
/// `Some(import_path.replace("::", "_"))` — an id for a node that was never
/// created — so `finalize_graph` dropped every one of those edges and
/// `analyze dag` reported "0 edges" on every project. Unresolvable (i.e.
/// external) imports now return None instead of an invented target.
fn resolve_import_path(&self, import_path: &str) -> Option<String> {
// Direct hit on a declared symbol (rare, but cheap to check).
if let Some(type_id) = self.type_map.get(import_path) {
return Some(type_id.clone());
}
if let Some(func_id) = self.function_map.get(import_path) {
return Some(func_id.clone());
}
let (segments, intra_crate) = normalize_import_segments(import_path);
if segments.is_empty() {
return None;
}
// Longest-prefix match against the module paths of analyzed files:
// "crate::services::dag_builder::DagBuilder" -> module "services::dag_builder".
if let Some(module_id) = self.resolve_module_prefix(&segments) {
return Some(module_id);
}
// Intra-crate paths may name an item defined in a file we did analyze even
// when the module path itself does not match; external crates never do.
if intra_crate {
if let Some(last) = segments.last() {
if let Some(type_id) = self.type_map.get(*last) {
return Some(type_id.clone());
}
if let Some(func_id) = self.function_map.get(*last) {
return Some(func_id.clone());
}
}
}
None
}
/// Find the analyzed file whose module path matches the longest prefix of
/// `segments`. Ambiguous matches resolve to nothing rather than to a guess.
fn resolve_module_prefix(&self, segments: &[&str]) -> Option<String> {
for len in (1..=segments.len()).rev() {
let key = segments[..len].join("::");
if let Some(candidates) = self.module_map.get(&key) {
if candidates.len() == 1 {
return Some(candidates[0].clone());
}
return None; // ambiguous — do not invent an edge
}
}
None
}
}
/// Split a file path into module path segments: `src/utils/helpers.rs` ->
/// ["src", "utils", "helpers"], `src/utils/mod.rs` -> ["src", "utils"].
fn module_path_segments(file_path: &str) -> Vec<String> {
let trimmed = file_path.trim_start_matches("./").trim_start_matches('/');
let path = std::path::Path::new(trimmed);
let mut segments: Vec<String> = path
.parent()
.map(|parent| {
parent
.components()
.filter_map(|c| c.as_os_str().to_str())
.filter(|s| !s.is_empty() && *s != "." && *s != "..")
.map(std::string::ToString::to_string)
.collect()
})
.unwrap_or_default();
// `foo/mod.rs` IS module `foo`, so it contributes no extra segment.
if let Some(stem) = path.file_stem().and_then(|s| s.to_str()) {
if stem != "mod" {
segments.push(stem.to_string());
}
}
segments
}
/// Strip `crate::`/`self::`/`super::`/glob decorations from an import path and
/// report whether the path was crate-relative.
fn normalize_import_segments(import_path: &str) -> (Vec<&str>, bool) {
let mut segments: Vec<&str> = import_path
.split("::")
.filter(|s| !s.is_empty() && *s != "*")
.collect();
let mut intra_crate = false;
while let Some(first) = segments.first() {
if matches!(*first, "crate" | "$crate" | "self" | "super") {
intra_crate = true;
segments.remove(0);
} else {
break;
}
}
(segments, intra_crate)
}
/// Detect programming language from file path extension
fn detect_language_from_path(file_path: &str) -> &'static str {
let ext = std::path::Path::new(file_path)
.extension()
.and_then(|e| e.to_str())
.unwrap_or("");
match ext {
"rs" => "rust",
"ts" | "tsx" => "typescript",
"js" | "jsx" => "javascript",
"py" => "python",
"go" => "go",
"java" => "java",
_ => "unknown",
}
}