Skip to main content

arbor_graph/
heuristics.rs

1//! Heuristics for detecting runtime edges and framework patterns
2//!
3//! Real codebases aren't clean. This module provides best-effort detection of:
4//! - Dynamic/callback calls
5//! - Framework-specific patterns (Flutter widgets, etc.)
6//! - Possible runtime dependencies
7
8use arbor_core::{CodeNode, NodeKind};
9
10/// Types of uncertain edges
11#[derive(Debug, Clone, PartialEq, Eq)]
12pub enum UncertainEdgeKind {
13    /// Callback or closure passed as argument
14    Callback,
15    /// Dynamic dispatch (trait objects, interfaces)
16    DynamicDispatch,
17    /// Framework widget tree (Flutter, React, etc.)
18    WidgetTree,
19    /// Event handler registration
20    EventHandler,
21    /// Dependency injection
22    DependencyInjection,
23    /// Reflection or runtime lookup
24    Reflection,
25}
26
27/// Android activities and the two iOS delegate classes, plus Hilt entry annotations.
28///
29/// Suffixes like `Service`, `Provider`, and `Application` are ordinary type names
30/// in Java and Kotlin, so they are not entry points. `@AndroidEntryPoint` and
31/// `@HiltAndroidApp` are, when the parser recorded them on the signature.
32fn is_mobile_component(node: &CodeNode) -> bool {
33    if node.kind != NodeKind::Class {
34        return false;
35    }
36    let name = node.name.to_lowercase();
37    let file = node.file.replace('\\', "/").to_lowercase();
38    let jvm = file.ends_with(".kt") || file.ends_with(".kts") || file.ends_with(".java");
39    if jvm && name.ends_with("activity") {
40        return true;
41    }
42    if file.ends_with(".swift") && (name == "appdelegate" || name == "scenedelegate") {
43        return true;
44    }
45    if jvm {
46        if let Some(signature) = node.signature.as_deref() {
47            let signature = signature.to_lowercase();
48            if signature.contains("@androidentrypoint") || signature.contains("@hiltandroidapp") {
49                return true;
50            }
51        }
52    }
53    false
54}
55
56impl std::fmt::Display for UncertainEdgeKind {
57    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
58        match self {
59            UncertainEdgeKind::Callback => write!(f, "callback"),
60            UncertainEdgeKind::DynamicDispatch => write!(f, "dynamic dispatch"),
61            UncertainEdgeKind::WidgetTree => write!(f, "widget tree"),
62            UncertainEdgeKind::EventHandler => write!(f, "event handler"),
63            UncertainEdgeKind::DependencyInjection => write!(f, "dependency injection"),
64            UncertainEdgeKind::Reflection => write!(f, "reflection"),
65        }
66    }
67}
68
69/// An edge that might exist at runtime but cannot be proven statically
70#[derive(Debug, Clone)]
71pub struct UncertainEdge {
72    pub from: String,
73    pub to: String,
74    pub kind: UncertainEdgeKind,
75    pub confidence: f32, // 0.0 to 1.0
76    pub reason: String,
77}
78
79/// Pattern matchers for different frameworks and languages
80pub struct HeuristicsMatcher;
81
82impl HeuristicsMatcher {
83    /// Check if a node looks like a Flutter widget
84    pub fn is_flutter_widget(node: &CodeNode) -> bool {
85        // Widget classes typically extend StatelessWidget or StatefulWidget
86        node.kind == NodeKind::Class
87            && (node.name.ends_with("Widget")
88                || node.name.ends_with("State")
89                || node.name.ends_with("Page")
90                || node.name.ends_with("Screen")
91                || node.name.ends_with("View"))
92    }
93
94    /// Check if a node looks like a React component
95    pub fn is_react_component(node: &CodeNode) -> bool {
96        (node.kind == NodeKind::Function || node.kind == NodeKind::Class)
97            && node.file.ends_with(".tsx")
98            && node.name.chars().next().is_some_and(|c| c.is_uppercase())
99    }
100
101    /// Check if a node looks like an event handler
102    pub fn is_event_handler(node: &CodeNode) -> bool {
103        let name_lower = node.name.to_lowercase();
104        (node.kind == NodeKind::Function || node.kind == NodeKind::Method)
105            && (name_lower.starts_with("on")
106                || name_lower.starts_with("handle")
107                || name_lower.ends_with("handler")
108                || name_lower.ends_with("callback")
109                || name_lower.ends_with("listener"))
110    }
111
112    /// Check if a node looks like a callback parameter
113    pub fn is_callback_style(node: &CodeNode) -> bool {
114        let name_lower = node.name.to_lowercase();
115        name_lower.ends_with("fn")
116            || name_lower.ends_with("callback")
117            || name_lower.ends_with("handler")
118            || name_lower.starts_with("on_")
119    }
120
121    /// Check if a node looks like a factory or provider (DI pattern)
122    pub fn is_dependency_injection(node: &CodeNode) -> bool {
123        let name_lower = node.name.to_lowercase();
124        name_lower.ends_with("factory")
125            || name_lower.ends_with("provider")
126            || name_lower.ends_with("injector")
127            || name_lower.ends_with("container")
128            || name_lower.contains("singleton")
129    }
130
131    /// Check if a node is likely a production entry point.
132    ///
133    /// Entry points are the outermost functions that receive external requests —
134    /// HTTP handlers, CLI commands, cron jobs, webhook receivers, main functions.
135    /// They're the roots of execution trees; if a changed function reaches one,
136    /// it means the change can affect real production traffic.
137    pub fn is_likely_entry_point(node: &CodeNode) -> bool {
138        if is_mobile_component(node) {
139            return true;
140        }
141        if !matches!(node.kind, NodeKind::Function | NodeKind::Method) {
142            return false;
143        }
144        let name = node.name.to_lowercase();
145        let file = node.file.to_lowercase();
146
147        // Main / program entry
148        if node.name == "main" || node.name == "__main__" {
149            return true;
150        }
151
152        // HTTP route handlers (Express, Gin, axum, FastAPI, Flask, Django, Rails)
153        if name.ends_with("_view")
154            || name.ends_with("_handler")
155            || name.ends_with("_controller")
156            || name.ends_with("_endpoint")
157            || name.starts_with("handle_")
158            || name.starts_with("get_")
159            || name.starts_with("post_")
160            || name.starts_with("put_")
161            || name.starts_with("delete_")
162            || name.starts_with("patch_")
163        {
164            // Only count as entry point if in a routes/views/handlers/controllers file
165            if file.contains("route")
166                || file.contains("view")
167                || file.contains("handler")
168                || file.contains("controller")
169                || file.contains("endpoint")
170                || file.contains("api")
171            {
172                return true;
173            }
174        }
175
176        // Webhook / event receivers
177        if name.contains("webhook")
178            || name.contains("receive")
179            || name.contains("subscribe")
180            || name.starts_with("on_")
181            || (name.starts_with("handle") && !file.contains("test"))
182        {
183            return true;
184        }
185
186        // Background jobs / cron / workers
187        if (name.contains("job")
188            || name.contains("task")
189            || name.contains("worker")
190            || name.contains("cron")
191            || name.ends_with("_run")
192            || name == "run"
193            || name == "execute"
194            || name == "process")
195            && (file.contains("job")
196                || file.contains("task")
197                || file.contains("worker")
198                || file.contains("cron")
199                || file.contains("celery")
200                || file.contains("sidekiq")
201                || file.contains("background"))
202        {
203            return true;
204        }
205
206        // CLI command handlers
207        if name.contains("command") || name.ends_with("_cmd") || name == "cli" || name == "invoke" {
208            return true;
209        }
210
211        false
212    }
213
214    /// Infer uncertain edges from node patterns
215    pub fn infer_uncertain_edges(nodes: &[&CodeNode]) -> Vec<UncertainEdge> {
216        let mut edges = Vec::new();
217
218        for node in nodes {
219            // Event handlers likely connected to event sources
220            if Self::is_event_handler(node) {
221                edges.push(UncertainEdge {
222                    from: "event_source".to_string(),
223                    to: node.id.clone(),
224                    kind: UncertainEdgeKind::EventHandler,
225                    confidence: 0.7,
226                    reason: format!("'{}' looks like an event handler", node.name),
227                });
228            }
229
230            // Callbacks likely invoked dynamically
231            if Self::is_callback_style(node) {
232                edges.push(UncertainEdge {
233                    from: "caller".to_string(),
234                    to: node.id.clone(),
235                    kind: UncertainEdgeKind::Callback,
236                    confidence: 0.6,
237                    reason: format!("'{}' is likely passed as a callback", node.name),
238                });
239            }
240
241            // Flutter widgets part of widget tree
242            if Self::is_flutter_widget(node) {
243                edges.push(UncertainEdge {
244                    from: "parent_widget".to_string(),
245                    to: node.id.clone(),
246                    kind: UncertainEdgeKind::WidgetTree,
247                    confidence: 0.8,
248                    reason: format!("'{}' is a Flutter widget in the widget tree", node.name),
249                });
250            }
251        }
252
253        edges
254    }
255}
256
257/// Warnings about analysis limitations
258#[derive(Debug, Clone)]
259pub struct AnalysisWarning {
260    pub message: String,
261    pub suggestion: String,
262}
263
264impl AnalysisWarning {
265    pub fn new(message: impl Into<String>, suggestion: impl Into<String>) -> Self {
266        Self {
267            message: message.into(),
268            suggestion: suggestion.into(),
269        }
270    }
271}
272
273/// Check for common patterns that limit static analysis accuracy
274pub fn detect_analysis_limitations(nodes: &[&CodeNode]) -> Vec<AnalysisWarning> {
275    let mut warnings = Vec::new();
276
277    let callback_count = nodes
278        .iter()
279        .filter(|n| HeuristicsMatcher::is_callback_style(n))
280        .count();
281    if callback_count > 5 {
282        warnings.push(AnalysisWarning::new(
283            format!("Found {} callback-style nodes", callback_count),
284            "Callbacks may be invoked dynamically. Verify runtime behavior.",
285        ));
286    }
287
288    let event_handler_count = nodes
289        .iter()
290        .filter(|n| HeuristicsMatcher::is_event_handler(n))
291        .count();
292    if event_handler_count > 3 {
293        warnings.push(AnalysisWarning::new(
294            format!("Found {} event handlers", event_handler_count),
295            "Event handlers are connected at runtime. Check event sources.",
296        ));
297    }
298
299    let widget_count = nodes
300        .iter()
301        .filter(|n| HeuristicsMatcher::is_flutter_widget(n))
302        .count();
303    if widget_count > 0 {
304        warnings.push(AnalysisWarning::new(
305            format!("Detected {} Flutter widgets", widget_count),
306            "Widget tree hierarchy is determined at runtime.",
307        ));
308    }
309
310    warnings
311}
312
313#[cfg(test)]
314mod tests {
315    use super::*;
316
317    #[test]
318    fn test_flutter_widget_detection() {
319        let widget = CodeNode::new("HomeWidget", "HomeWidget", NodeKind::Class, "home.dart");
320        assert!(HeuristicsMatcher::is_flutter_widget(&widget));
321
322        let state = CodeNode::new("HomeState", "HomeState", NodeKind::Class, "home.dart");
323        assert!(HeuristicsMatcher::is_flutter_widget(&state));
324
325        let non_widget = CodeNode::new(
326            "UserService",
327            "UserService",
328            NodeKind::Class,
329            "service.dart",
330        );
331        assert!(!HeuristicsMatcher::is_flutter_widget(&non_widget));
332    }
333
334    #[test]
335    fn test_event_handler_detection() {
336        let handler = CodeNode::new("onClick", "onClick", NodeKind::Function, "button.ts");
337        assert!(HeuristicsMatcher::is_event_handler(&handler));
338
339        let handler2 = CodeNode::new(
340            "handleSubmit",
341            "handleSubmit",
342            NodeKind::Function,
343            "form.ts",
344        );
345        assert!(HeuristicsMatcher::is_event_handler(&handler2));
346
347        let non_handler = CodeNode::new("calculate", "calculate", NodeKind::Function, "math.ts");
348        assert!(!HeuristicsMatcher::is_event_handler(&non_handler));
349    }
350
351    #[test]
352    fn test_react_component_detection() {
353        let component = CodeNode::new(
354            "UserProfile",
355            "UserProfile",
356            NodeKind::Function,
357            "profile.tsx",
358        );
359        assert!(HeuristicsMatcher::is_react_component(&component));
360
361        let non_component = CodeNode::new("helper", "helper", NodeKind::Function, "utils.tsx");
362        assert!(!HeuristicsMatcher::is_react_component(&non_component));
363
364        // Not a .tsx file -> not a React component
365        let wrong_ext = CodeNode::new(
366            "UserProfile",
367            "UserProfile",
368            NodeKind::Function,
369            "profile.rs",
370        );
371        assert!(!HeuristicsMatcher::is_react_component(&wrong_ext));
372
373        // Class in .tsx is also a React component
374        let class_comp = CodeNode::new("AppContainer", "AppContainer", NodeKind::Class, "app.tsx");
375        assert!(HeuristicsMatcher::is_react_component(&class_comp));
376    }
377
378    #[test]
379    fn test_callback_style_detection() {
380        let callback = CodeNode::new(
381            "on_click_handler",
382            "on_click_handler",
383            NodeKind::Function,
384            "a.rs",
385        );
386        assert!(HeuristicsMatcher::is_callback_style(&callback));
387
388        let callback_fn = CodeNode::new("sortFn", "sortFn", NodeKind::Function, "a.ts");
389        assert!(HeuristicsMatcher::is_callback_style(&callback_fn));
390
391        let regular = CodeNode::new("process_data", "process_data", NodeKind::Function, "a.rs");
392        assert!(!HeuristicsMatcher::is_callback_style(&regular));
393    }
394
395    #[test]
396    fn test_dependency_injection_detection() {
397        let factory = CodeNode::new("UserFactory", "UserFactory", NodeKind::Class, "factory.ts");
398        assert!(HeuristicsMatcher::is_dependency_injection(&factory));
399
400        let provider = CodeNode::new("AuthProvider", "AuthProvider", NodeKind::Class, "auth.ts");
401        assert!(HeuristicsMatcher::is_dependency_injection(&provider));
402
403        let regular = CodeNode::new("UserService", "UserService", NodeKind::Class, "service.ts");
404        assert!(!HeuristicsMatcher::is_dependency_injection(&regular));
405    }
406
407    #[test]
408    fn test_infer_uncertain_edges_from_patterns() {
409        let handler = CodeNode::new("onClick", "onClick", NodeKind::Function, "button.ts");
410        let widget = CodeNode::new("HomeWidget", "HomeWidget", NodeKind::Class, "home.dart");
411        let regular = CodeNode::new("calculate", "calculate", NodeKind::Function, "math.ts");
412
413        let nodes: Vec<&CodeNode> = vec![&handler, &widget, &regular];
414        let edges = HeuristicsMatcher::infer_uncertain_edges(&nodes);
415
416        // Should have edges for handler (EventHandler) and widget (WidgetTree)
417        assert!(edges
418            .iter()
419            .any(|e| matches!(e.kind, UncertainEdgeKind::EventHandler)));
420        assert!(edges
421            .iter()
422            .any(|e| matches!(e.kind, UncertainEdgeKind::WidgetTree)));
423        // Regular function shouldn't produce uncertain edges
424        assert!(!edges.iter().any(|e| e.to == regular.id));
425    }
426
427    #[test]
428    fn test_detect_analysis_limitations_callbacks() {
429        // Create 6+ callback-style nodes to trigger the warning
430        let nodes: Vec<CodeNode> = (0..7)
431            .map(|i| {
432                CodeNode::new(
433                    format!("on_event_{}", i),
434                    format!("on_event_{}", i),
435                    NodeKind::Function,
436                    "events.ts",
437                )
438            })
439            .collect();
440        let node_refs: Vec<&CodeNode> = nodes.iter().collect();
441
442        let warnings = detect_analysis_limitations(&node_refs);
443        assert!(!warnings.is_empty());
444        assert!(warnings.iter().any(|w| w.message.contains("callback")));
445    }
446
447    #[test]
448    fn test_detect_analysis_limitations_flutter_widgets() {
449        let widgets: Vec<CodeNode> = vec![CodeNode::new(
450            "HomeWidget",
451            "HomeWidget",
452            NodeKind::Class,
453            "home.dart",
454        )];
455        let node_refs: Vec<&CodeNode> = widgets.iter().collect();
456
457        let warnings = detect_analysis_limitations(&node_refs);
458        assert!(warnings.iter().any(|w| w.message.contains("Flutter")));
459    }
460
461    #[test]
462    fn test_uncertain_edge_kind_display() {
463        assert_eq!(UncertainEdgeKind::Callback.to_string(), "callback");
464        assert_eq!(
465            UncertainEdgeKind::DynamicDispatch.to_string(),
466            "dynamic dispatch"
467        );
468        assert_eq!(UncertainEdgeKind::WidgetTree.to_string(), "widget tree");
469        assert_eq!(UncertainEdgeKind::EventHandler.to_string(), "event handler");
470        assert_eq!(
471            UncertainEdgeKind::DependencyInjection.to_string(),
472            "dependency injection"
473        );
474        assert_eq!(UncertainEdgeKind::Reflection.to_string(), "reflection");
475    }
476
477    #[test]
478    fn android_activity_is_an_entry_point_and_a_service_is_not() {
479        let activity = CodeNode::new(
480            "MainActivity",
481            "MainActivity",
482            NodeKind::Class,
483            "app/src/main/java/com/example/MainActivity.kt",
484        );
485        assert!(HeuristicsMatcher::is_likely_entry_point(&activity));
486
487        let service = CodeNode::new(
488            "UserService",
489            "UserService",
490            NodeKind::Class,
491            "src/main/java/com/example/UserService.java",
492        );
493        assert!(!HeuristicsMatcher::is_likely_entry_point(&service));
494
495        let controller = CodeNode::new(
496            "ProfileViewController",
497            "ProfileViewController",
498            NodeKind::Class,
499            "ios/ProfileViewController.swift",
500        );
501        assert!(!HeuristicsMatcher::is_likely_entry_point(&controller));
502
503        let delegate = CodeNode::new(
504            "AppDelegate",
505            "AppDelegate",
506            NodeKind::Class,
507            "ios/AppDelegate.swift",
508        );
509        assert!(HeuristicsMatcher::is_likely_entry_point(&delegate));
510    }
511
512    #[test]
513    fn hilt_annotation_marks_the_annotated_class_only() {
514        let app = CodeNode::new(
515            "MyApplication",
516            "MyApplication",
517            NodeKind::Class,
518            "app/src/main/java/com/example/MyApplication.kt",
519        )
520        .with_signature("@HiltAndroidApp open class MyApplication : Application()");
521        assert!(HeuristicsMatcher::is_likely_entry_point(&app));
522
523        let plain = CodeNode::new(
524            "MyApplication",
525            "MyApplication",
526            NodeKind::Class,
527            "app/src/main/java/com/example/MyApplication.kt",
528        );
529        assert!(!HeuristicsMatcher::is_likely_entry_point(&plain));
530    }
531
532    #[test]
533    fn test_no_warnings_for_clean_code() {
534        let nodes: Vec<CodeNode> = vec![
535            CodeNode::new("main", "main", NodeKind::Function, "main.rs"),
536            CodeNode::new("helper", "helper", NodeKind::Function, "utils.rs"),
537        ];
538        let node_refs: Vec<&CodeNode> = nodes.iter().collect();
539
540        let warnings = detect_analysis_limitations(&node_refs);
541        assert!(warnings.is_empty());
542    }
543}