heddle-semantic 0.2.1

An AI-native version control system
Documentation
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
// SPDX-License-Identifier: Apache-2.0
//! Call graph and blast radius analysis.
//!
//! Extracts function call relationships from tree-sitter ASTs and computes
//! downstream impact ("blast radius") for changed functions.

use std::{
    collections::{HashMap, HashSet, VecDeque},
    path::PathBuf,
};

use crate::parser::{Language, ParsedFile};

/// A node in the call graph: a function definition.
#[derive(Clone, Debug)]
pub struct CallGraphNode {
    /// File containing this function.
    pub file: PathBuf,
    /// Function name.
    pub name: String,
    /// Line range in the source file.
    pub start_line: usize,
    pub end_line: usize,
}

/// A directed edge: `caller` calls `callee`.
#[derive(Clone, Debug, Eq, Hash, PartialEq, Ord, PartialOrd)]
pub struct FunctionKey {
    pub file: PathBuf,
    pub name: String,
    pub start_line: usize,
}

/// A directed edge: `caller` calls `callee`.
#[derive(Clone, Debug)]
pub struct CallEdge {
    pub caller: FunctionKey,
    pub callee: FunctionKey,
}

/// The call graph for a set of files.
#[derive(Clone, Debug, Default)]
pub struct CallGraph {
    /// Function definitions: name → node.
    pub nodes: HashMap<FunctionKey, CallGraphNode>,
    /// Forward edges: function → set of functions it calls.
    pub calls: HashMap<FunctionKey, HashSet<FunctionKey>>,
    /// Reverse edges: function → set of functions that call it.
    pub called_by: HashMap<FunctionKey, HashSet<FunctionKey>>,
}

/// Blast radius result for a set of changed functions.
#[derive(Clone, Debug)]
pub struct BlastRadius {
    /// The changed functions that triggered the analysis.
    pub changed_functions: Vec<String>,
    /// Downstream functions affected (transitive callers).
    pub affected: Vec<CallGraphNode>,
    /// Total number of affected functions.
    pub affected_count: usize,
}

impl CallGraph {
    /// Build a call graph from a set of files and their contents.
    pub fn build(files: &[(PathBuf, String)]) -> Self {
        let mut graph = CallGraph::default();

        for (path, content) in files {
            let language = Language::from_path(path);
            let Some(parsed) = ParsedFile::parse(content, language) else {
                continue;
            };

            let functions: Vec<_> = parsed
                .extract_functions()
                .into_iter()
                .map(|func| {
                    let key = FunctionKey {
                        file: path.clone(),
                        name: func.name.clone(),
                        start_line: func.start_line,
                    };
                    (key, func)
                })
                .collect();

            for (key, func) in &functions {
                graph.nodes.insert(
                    key.clone(),
                    CallGraphNode {
                        file: path.clone(),
                        name: func.name.clone(),
                        start_line: func.start_line,
                        end_line: func.end_line,
                    },
                );
            }

            let edges = extract_call_edges(&functions, parsed.language);
            for edge in edges {
                graph
                    .calls
                    .entry(edge.caller.clone())
                    .or_default()
                    .insert(edge.callee.clone());
                graph
                    .called_by
                    .entry(edge.callee.clone())
                    .or_default()
                    .insert(edge.caller.clone());
            }
        }

        graph
    }

    /// Return stable function identities for a bare function name.
    pub fn keys_for_name(&self, name: &str) -> Vec<FunctionKey> {
        let mut keys: Vec<_> = self
            .nodes
            .keys()
            .filter(|key| key.name == name)
            .cloned()
            .collect();
        keys.sort();
        keys
    }

    /// Compute the blast radius for a set of changed function names.
    /// Returns all transitive callers (upstream functions that depend on the changed ones).
    pub fn blast_radius(&self, changed_functions: &[String]) -> BlastRadius {
        let mut affected: HashSet<FunctionKey> = HashSet::new();
        let mut queue: VecDeque<FunctionKey> = VecDeque::new();
        let changed_names: HashSet<_> = changed_functions.iter().map(String::as_str).collect();
        let changed_keys: HashSet<_> = self
            .nodes
            .keys()
            .filter(|key| changed_names.contains(key.name.as_str()))
            .cloned()
            .collect();

        for key in &changed_keys {
            queue.push_back(key.clone());
        }

        while let Some(current) = queue.pop_front() {
            if let Some(callers) = self.called_by.get(&current) {
                for caller in callers {
                    if !changed_keys.contains(caller) && affected.insert(caller.clone()) {
                        queue.push_back(caller.clone());
                    }
                }
            }
        }

        let mut affected_nodes: Vec<CallGraphNode> = affected
            .iter()
            .filter_map(|key| self.nodes.get(key).cloned())
            .collect();
        affected_nodes.sort_by(|left, right| {
            left.file
                .cmp(&right.file)
                .then_with(|| left.start_line.cmp(&right.start_line))
                .then_with(|| left.name.cmp(&right.name))
        });
        let count = affected_nodes.len();

        BlastRadius {
            changed_functions: changed_functions.to_vec(),
            affected: affected_nodes,
            affected_count: count,
        }
    }
}

/// Extract call edges from a parsed file by walking function bodies
/// and looking for identifier references that match known patterns.
fn extract_call_edges(
    functions: &[(FunctionKey, crate::parser::FunctionDef)],
    language: Language,
) -> Vec<CallEdge> {
    let mut edges = Vec::new();
    let mut functions_by_name: HashMap<String, Vec<FunctionKey>> = HashMap::new();

    for (key, func) in functions {
        functions_by_name
            .entry(func.name.clone())
            .or_default()
            .push(key.clone());
    }

    for (caller_key, func) in functions {
        let calls = extract_calls_from_text(&func.content, language);
        for callee_name in calls {
            if callee_name == func.name {
                continue;
            }

            if let Some(callees) = functions_by_name.get(&callee_name) {
                for callee_key in callees {
                    edges.push(CallEdge {
                        caller: caller_key.clone(),
                        callee: callee_key.clone(),
                    });
                }
            }
        }
    }

    edges
}

/// Extract function call names from a source text snippet.
/// Simple heuristic: look for `identifier(` patterns.
fn extract_calls_from_text(text: &str, _language: Language) -> Vec<String> {
    let mut calls = HashSet::new();
    let bytes = text.as_bytes();
    let len = bytes.len();
    let mut i = 0;

    while i < len {
        // Find '(' and look backwards for an identifier.
        if bytes[i] == b'(' {
            let end = i;
            // Skip backwards past whitespace.
            let mut j = end;
            while j > 0 && bytes[j - 1] == b' ' {
                j -= 1;
            }
            // Collect identifier characters backwards.
            let ident_end = j;
            while j > 0 && (bytes[j - 1].is_ascii_alphanumeric() || bytes[j - 1] == b'_') {
                j -= 1;
            }
            if j < ident_end {
                let ident = &text[j..ident_end];
                // Filter out language keywords.
                if !is_keyword(ident) && !ident.is_empty() {
                    calls.insert(ident.to_string());
                }
            }
        }
        i += 1;
    }

    calls.into_iter().collect()
}

fn is_keyword(s: &str) -> bool {
    matches!(
        s,
        "if" | "else"
            | "for"
            | "while"
            | "match"
            | "return"
            | "let"
            | "mut"
            | "fn"
            | "pub"
            | "struct"
            | "enum"
            | "impl"
            | "trait"
            | "use"
            | "mod"
            | "type"
            | "where"
            | "async"
            | "await"
            | "loop"
            | "break"
            | "continue"
            | "self"
            | "Self"
            | "super"
            | "crate"
            | "as"
            | "in"
            | "ref"
            | "move"
            | "dyn"
            | "unsafe"
            | "extern"
            | "const"
            | "static"
            | "true"
            | "false"
            | "Some"
            | "None"
            | "Ok"
            | "Err"
            // Common control flow in other languages
            | "def"
            | "class"
            | "import"
            | "from"
            | "try"
            | "catch"
            | "throw"
            | "new"
            | "var"
            | "function"
            | "switch"
            | "case"
            | "default"
            | "typeof"
            | "instanceof"
            | "void"
            | "delete"
    )
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_basic_call_graph() {
        let files = vec![(
            PathBuf::from("test.rs"),
            concat!(
                "fn main() {\n",
                "    let x = helper();\n",
                "    process(x);\n",
                "}\n\n",
                "fn helper() -> i32 {\n",
                "    42\n",
                "}\n\n",
                "fn process(x: i32) {\n",
                "    output(x);\n",
                "}\n\n",
                "fn output(x: i32) {\n",
                "    println!(\"{}\", x);\n",
                "}\n",
            )
            .to_string(),
        )];

        let graph = CallGraph::build(&files);
        assert_eq!(graph.nodes.len(), 4); // main, helper, process, output

        // main calls helper and process.
        let main_key = graph.keys_for_name("main").pop().unwrap();
        let helper_key = graph.keys_for_name("helper").pop().unwrap();
        let process_key = graph.keys_for_name("process").pop().unwrap();
        let output_key = graph.keys_for_name("output").pop().unwrap();
        let main_calls = graph.calls.get(&main_key).unwrap();
        assert!(main_calls.contains(&helper_key));
        assert!(main_calls.contains(&process_key));

        // process calls output.
        let proc_calls = graph.calls.get(&process_key).unwrap();
        assert!(proc_calls.contains(&output_key));
    }

    #[test]
    fn test_blast_radius() {
        let files = vec![(
            PathBuf::from("test.rs"),
            concat!(
                "fn main() {\n    run();\n}\n\n",
                "fn run() {\n    compute();\n}\n\n",
                "fn compute() {\n    42\n}\n\n",
                "fn unrelated() {\n    99\n}\n",
            )
            .to_string(),
        )];

        let graph = CallGraph::build(&files);
        let blast = graph.blast_radius(&["compute".to_string()]);

        // compute is called by run, run is called by main.
        assert_eq!(blast.affected_count, 2);
        let names: HashSet<_> = blast.affected.iter().map(|n| n.name.as_str()).collect();
        assert!(names.contains("run"));
        assert!(names.contains("main"));
        // unrelated is not affected.
        assert!(!names.contains("unrelated"));
    }

    #[test]
    fn test_no_blast_radius_for_leaf() {
        let files = vec![(
            PathBuf::from("test.rs"),
            "fn leaf() {\n    42\n}\n".to_string(),
        )];

        let graph = CallGraph::build(&files);
        let blast = graph.blast_radius(&["leaf".to_string()]);
        assert_eq!(blast.affected_count, 0);
    }

    #[test]
    fn test_duplicate_function_names_stay_isolated_by_file() {
        let files = vec![
            (
                PathBuf::from("a.rs"),
                concat!(
                    "fn run() {\n    target();\n}\n\n",
                    "fn target() {\n    42\n}\n",
                )
                .to_string(),
            ),
            (
                PathBuf::from("b.rs"),
                concat!(
                    "fn run() {\n    other();\n}\n\n",
                    "fn other() {\n    99\n}\n",
                )
                .to_string(),
            ),
        ];

        let graph = CallGraph::build(&files);
        let run_keys = graph.keys_for_name("run");
        assert_eq!(run_keys.len(), 2);

        let blast = graph.blast_radius(&["target".to_string()]);
        assert_eq!(blast.affected_count, 1);
        assert_eq!(blast.affected[0].file, PathBuf::from("a.rs"));
        assert_eq!(blast.affected[0].name, "run");
    }
}