fossil-mcp 0.1.7

Multi-language static analysis toolkit with MCP server. Detects dead code, code clones, and AI scaffolding.
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
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
//! BDD-based context-sensitive dead code detection.
//!
//! Behavior-Driven Detection (BDD) uses common behavioral patterns to identify
//! functions that appear dead but are actually alive due to:
//! - Callback registration (setTimeout, addEventListener, etc.)
//! - Dynamic dispatch (reflection, plugin systems, factories)
//! - Middleware/decorator patterns
//! - Setup/teardown lifecycle methods
//! - Configuration-driven selection
//! - Lazy initialization

use crate::core::CodeNode;
use regex::Regex;
use std::sync::OnceLock;

#[cfg(test)]
use crate::core::NodeKind;

/// Behavior markers that indicate a function is actually in use despite
/// appearing unreachable in static analysis.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum BehaviorMarker {
    /// Function is passed as callback (setTimeout, fetch, promise.then, etc.)
    CallbackHandler,
    /// Function is middleware (Express, Django, etc.)
    Middleware,
    /// Function is lifecycle method (setUp, tearDown, beforeEach, etc.)
    LifecycleMethod,
    /// Function is registered in a registry/plugin system
    PluginRegistration,
    /// Function is used via lazy loading/factory pattern
    LazyLoading,
    /// Function is exported for external consumption
    PublicExport,
    /// Function is used in dynamic dispatch (reflection, factory selection)
    DynamicDispatch,
    /// Function matches common event handler pattern
    EventHandler,
    /// Function is used as a constructor in factory
    FactoryMethod,
    /// Function is used in configuration/dependency injection
    ConfigDriven,
}

/// Detects behavior markers that indicate code is alive despite appearing dead.
pub struct BddContextDetector;

impl BddContextDetector {
    /// Check if a node has any behavior markers indicating it's actually alive.
    pub fn detect_markers(node: &CodeNode) -> Vec<BehaviorMarker> {
        let mut markers = Vec::new();

        // Check callback handler patterns
        if Self::is_callback_handler(node) {
            markers.push(BehaviorMarker::CallbackHandler);
        }

        // Check middleware patterns
        if Self::is_middleware(node) {
            markers.push(BehaviorMarker::Middleware);
        }

        // Check lifecycle methods
        if Self::is_lifecycle_method(node) {
            markers.push(BehaviorMarker::LifecycleMethod);
        }

        // Check event handler patterns
        if Self::is_event_handler(node) {
            markers.push(BehaviorMarker::EventHandler);
        }

        // Check if exported for external consumption
        if Self::is_public_export(node) {
            markers.push(BehaviorMarker::PublicExport);
        }

        // Check plugin/registry patterns
        if Self::is_plugin_registration(node) {
            markers.push(BehaviorMarker::PluginRegistration);
        }

        // Check factory patterns
        if Self::is_factory_method(node) {
            markers.push(BehaviorMarker::FactoryMethod);
        }

        // Check config-driven patterns (Zustand, Redux, serialization)
        if Self::is_config_driven(node) {
            markers.push(BehaviorMarker::ConfigDriven);
        }

        markers
    }

    /// Check if function name suggests it's a callback handler
    fn is_callback_handler(node: &CodeNode) -> bool {
        let name_lower = node.name.to_lowercase();

        // Common callback handler patterns
        callback_patterns().is_match(&name_lower)
            || node
                .attributes
                .iter()
                .any(|attr| callback_attr_patterns().is_match(attr))
    }

    /// Check if function is a middleware
    fn is_middleware(node: &CodeNode) -> bool {
        let name_lower = node.name.to_lowercase();

        middleware_patterns().is_match(&name_lower)
            || node
                .attributes
                .iter()
                .any(|attr| middleware_attr_patterns().is_match(attr))
    }

    /// Check if function is a lifecycle/setup/teardown method
    fn is_lifecycle_method(node: &CodeNode) -> bool {
        let name_lower = node.name.to_lowercase();

        lifecycle_patterns().is_match(&name_lower)
            || node
                .attributes
                .iter()
                .any(|attr| lifecycle_attr_patterns().is_match(attr))
    }

    /// Check if function matches event handler naming conventions
    fn is_event_handler(node: &CodeNode) -> bool {
        let name_lower = node.name.to_lowercase();

        // on* pattern (onClick, onChange, onSubmit, etc.)
        // Must have uppercase letter after 'on'
        (node.name.starts_with("on")
            && node.name.len() > 2
            && node.name.chars().nth(2).is_some_and(|c| c.is_uppercase()))
            // Lowercase DOM/SSE event handlers (onopen, onmessage, onerror, onclose, etc.)
            || matches!(
                node.name.as_str(),
                "onopen" | "onmessage" | "onerror" | "onclose" | "onabort"
                    | "onconnect" | "ondisconnect" | "ontimeout" | "ondata"
                    | "onprogress" | "onload" | "onready" | "oncomplete"
            )
            // handle* pattern (handleClick, handleChange, etc.)
            || name_lower.starts_with("handle")
            // *listener pattern (messageListener, errorListener, etc.)
            || name_lower.ends_with("listener")
            // Swift delegate method patterns (called by frameworks, not user code)
            || Self::is_swift_delegate_method(node)
            // Check attributes
            || node
                .attributes
                .iter()
                .any(|attr| event_attr_patterns().is_match(attr))
    }

    /// Swift delegate methods follow naming conventions like `Did`, `Will`, `Should`
    /// (e.g., `applicationDidFinishLaunching`, `locationManagerDidChangeAuthorization`).
    /// These are called by Apple frameworks via protocol conformance, not directly.
    fn is_swift_delegate_method(node: &CodeNode) -> bool {
        if node.language != crate::core::Language::Swift {
            return false;
        }
        let name = &node.name;
        // Cocoa delegate naming conventions: contains Did/Will/Should
        name.contains("Did")
            || name.contains("Will")
            || name.contains("Should")
            // Common delegate prefixes for specific Apple frameworks
            || name.starts_with("locationManager")
            || name.starts_with("webView")
            || name.starts_with("tableView")
            || name.starts_with("collectionView")
            || name.starts_with("photoOutput")
            || name.starts_with("audioPlayer")
            || name.starts_with("urlSession")
            || name.starts_with("mapView")
    }

    /// Check if function is exported for external use
    fn is_public_export(node: &CodeNode) -> bool {
        node.name.starts_with("export")
            || node.attributes.iter().any(|attr| {
                attr.contains("export")
                    || attr.contains("public")
                    || attr.contains("@api")
                    || attr.contains("@public")
            })
    }

    /// Check if function is registered in a plugin/registry system
    fn is_plugin_registration(node: &CodeNode) -> bool {
        let name_lower = node.name.to_lowercase();

        plugin_patterns().is_match(&name_lower)
            || node.attributes.iter().any(|attr| {
                plugin_attr_patterns().is_match(attr)
                    || attr.contains("register")
                    || attr.contains("plugin")
            })
    }

    /// Check if function is invoked via configuration or framework wiring
    /// (Zustand persist options, Redux middleware, serialization hooks, etc.)
    fn is_config_driven(node: &CodeNode) -> bool {
        matches!(
            node.name.as_str(),
            "migrate"
                | "serialize"
                | "deserialize"
                | "transform"
                | "validate"
                | "sanitize"
                | "comparator"
                | "reducer"
                | "partialize"
                | "onRehydrateStorage"
                | "onFinishHydration"
                | "getStorage"
                | "setStorage"
        )
    }

    /// Check if function is a factory method
    fn is_factory_method(node: &CodeNode) -> bool {
        let name_lower = node.name.to_lowercase();

        factory_patterns().is_match(&name_lower)
    }
}

// ============================================================================
// Compiled regex patterns (lazily initialized)
// ============================================================================

fn callback_patterns() -> &'static Regex {
    static INSTANCE: OnceLock<Regex> = OnceLock::new();
    INSTANCE.get_or_init(|| {
        Regex::new(
            r"(?ix)
            (callback|handler|onload|onsuccess|onerror|onchange|onclick|
             onsubmit|onblur|onfocus|onmouseenter|onmouseleave|
             then|catch|finally|resolve|reject)
            ",
        )
        .unwrap()
    })
}

fn callback_attr_patterns() -> &'static Regex {
    static INSTANCE: OnceLock<Regex> = OnceLock::new();
    INSTANCE.get_or_init(|| Regex::new(r"(?i)(callback|handler|listener|async|promise)").unwrap())
}

fn middleware_patterns() -> &'static Regex {
    static INSTANCE: OnceLock<Regex> = OnceLock::new();
    INSTANCE.get_or_init(|| {
        Regex::new(
            r"(?ix)
            (middleware|interceptor|filter|validator|authenticator|
             authorization|permission|check|guard|protect)
            ",
        )
        .unwrap()
    })
}

fn middleware_attr_patterns() -> &'static Regex {
    static INSTANCE: OnceLock<Regex> = OnceLock::new();
    INSTANCE.get_or_init(|| {
        Regex::new(
            r"(?i)
            (@middleware|@interceptor|@filter|@guard|@route|@post|@get|@put|@delete|
             @patch|@use)
            ",
        )
        .unwrap()
    })
}

fn lifecycle_patterns() -> &'static Regex {
    static INSTANCE: OnceLock<Regex> = OnceLock::new();
    INSTANCE.get_or_init(|| {
        Regex::new(
            r"(?ix)
            (setup|teardown|setdown|cleanup|initialize|init|mount|unmount|
             install|uninstall|enable|disable|start|stop|configure|
             beforeeach|aftereach|beforeall|afterall|before|after)
            ",
        )
        .unwrap()
    })
}

fn lifecycle_attr_patterns() -> &'static Regex {
    static INSTANCE: OnceLock<Regex> = OnceLock::new();
    INSTANCE.get_or_init(|| {
        Regex::new(
            r"(?i)
            (@setup|@teardown|@beforeeach|@aftereach|@beforeall|@afterall|
             @lifecycle|@hook)
            ",
        )
        .unwrap()
    })
}

fn event_attr_patterns() -> &'static Regex {
    static INSTANCE: OnceLock<Regex> = OnceLock::new();
    INSTANCE.get_or_init(|| Regex::new(r"(?i)(@event|@listener|@subscribe|@on|@emit)").unwrap())
}

fn plugin_patterns() -> &'static Regex {
    static INSTANCE: OnceLock<Regex> = OnceLock::new();
    INSTANCE.get_or_init(|| {
        Regex::new(
            r"(?ix)
            (plugin|extension|addon|provider|factory|builder|creator|
             register|install|use|apply)
            ",
        )
        .unwrap()
    })
}

fn plugin_attr_patterns() -> &'static Regex {
    static INSTANCE: OnceLock<Regex> = OnceLock::new();
    INSTANCE.get_or_init(|| {
        Regex::new(r"(?i)(@plugin|@provider|@injectable|@factory|@register)").unwrap()
    })
}

fn factory_patterns() -> &'static Regex {
    static INSTANCE: OnceLock<Regex> = OnceLock::new();
    INSTANCE.get_or_init(|| {
        Regex::new(
            r"(?ix)
            (create|make|build|factory|builder|constructor|new|instantiate|
             produce|generate|create_.*|make_.*)
            ",
        )
        .unwrap()
    })
}

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

    fn make_node(name: &str, attrs: Vec<&str>) -> CodeNode {
        CodeNode {
            id: crate::core::NodeId::from_u32(1),
            name: name.to_string(),
            full_name: format!("test.{}", name),
            kind: NodeKind::Function,
            location: crate::core::SourceLocation {
                file: "test.rs".to_string(),
                line_start: 1,
                line_end: 10,
                column_start: 0,
                column_end: 0,
            },
            language: crate::core::Language::Rust,
            visibility: crate::core::Visibility::Public,
            lines_of_code: 5,
            parent_id: None,
            is_async: false,
            is_test: false,
            is_generated: false,
            attributes: attrs.iter().map(|s| s.to_string()).collect(),
            documentation: None,
        }
    }

    #[test]
    fn test_callback_handler_detection() {
        let node = make_node("onSuccess", vec![]);
        assert!(BddContextDetector::is_callback_handler(&node));

        let node = make_node("onClick", vec![]);
        assert!(BddContextDetector::is_event_handler(&node));

        let node = make_node("thenHandler", vec![]);
        assert!(BddContextDetector::is_callback_handler(&node));
    }

    #[test]
    fn test_middleware_detection() {
        let node = make_node("authMiddleware", vec![]);
        assert!(BddContextDetector::is_middleware(&node));

        let node = make_node("validator", vec!["@middleware"]);
        assert!(BddContextDetector::is_middleware(&node));
    }

    #[test]
    fn test_lifecycle_detection() {
        let node = make_node("setUp", vec![]);
        assert!(BddContextDetector::is_lifecycle_method(&node));

        let node = make_node("beforeEach", vec![]);
        assert!(BddContextDetector::is_lifecycle_method(&node));

        let node = make_node("tearDown", vec![]);
        assert!(BddContextDetector::is_lifecycle_method(&node));
    }

    #[test]
    fn test_factory_detection() {
        let node = make_node("createUser", vec![]);
        assert!(BddContextDetector::is_factory_method(&node));

        let node = make_node("buildConfig", vec![]);
        assert!(BddContextDetector::is_factory_method(&node));
    }

    #[test]
    fn test_public_export_detection() {
        let node = make_node("exportData", vec![]);
        assert!(BddContextDetector::is_public_export(&node));

        let node = make_node("normalFunction", vec!["@api"]);
        assert!(BddContextDetector::is_public_export(&node));
    }

    #[test]
    fn test_lowercase_event_handler_detection() {
        for name in &[
            "onopen",
            "onmessage",
            "onerror",
            "onclose",
            "onload",
            "onprogress",
        ] {
            let node = make_node(name, vec![]);
            assert!(
                BddContextDetector::is_event_handler(&node),
                "'{}' should be detected as event handler",
                name
            );
        }
    }

    #[test]
    fn test_config_driven_detection() {
        for name in &[
            "migrate",
            "serialize",
            "deserialize",
            "partialize",
            "onRehydrateStorage",
            "reducer",
        ] {
            let node = make_node(name, vec![]);
            assert!(
                BddContextDetector::is_config_driven(&node),
                "'{}' should be detected as config-driven",
                name
            );
        }
    }

    #[test]
    fn test_config_driven_in_detect_markers() {
        let node = make_node("migrate", vec![]);
        let markers = BddContextDetector::detect_markers(&node);
        assert!(
            markers.contains(&BehaviorMarker::ConfigDriven),
            "migrate should have ConfigDriven marker. Markers: {:?}",
            markers
        );
    }

    fn make_swift_node(name: &str, attrs: Vec<&str>) -> CodeNode {
        CodeNode {
            id: crate::core::NodeId::from_u32(1),
            name: name.to_string(),
            full_name: format!("test.{}", name),
            kind: NodeKind::Function,
            location: crate::core::SourceLocation {
                file: "test.swift".to_string(),
                line_start: 1,
                line_end: 10,
                column_start: 0,
                column_end: 0,
            },
            language: crate::core::Language::Swift,
            visibility: crate::core::Visibility::Public,
            lines_of_code: 5,
            parent_id: None,
            is_async: false,
            is_test: false,
            is_generated: false,
            attributes: attrs.iter().map(|s| s.to_string()).collect(),
            documentation: None,
        }
    }

    #[test]
    fn test_swift_delegate_method_detection() {
        // Did/Will/Should patterns
        for name in &[
            "applicationDidFinishLaunching",
            "applicationWillTerminate",
            "applicationShouldTerminate",
            "locationManagerDidChangeAuthorization",
            "windowDidLoad",
            "scrollViewDidScroll",
        ] {
            let node = make_swift_node(name, vec![]);
            assert!(
                BddContextDetector::is_event_handler(&node),
                "Swift delegate method '{}' should be detected as event handler",
                name
            );
        }
    }

    #[test]
    fn test_swift_framework_delegate_prefixes() {
        for name in &[
            "locationManagerDidUpdateLocations",
            "webViewDidFinishNavigation",
            "tableViewDidSelectRow",
            "collectionViewDidSelectItem",
            "urlSessionDidBecomeInvalid",
            "mapViewDidChangeVisibleRegion",
        ] {
            let node = make_swift_node(name, vec![]);
            assert!(
                BddContextDetector::is_event_handler(&node),
                "Swift delegate '{}' should be detected",
                name
            );
        }
    }

    #[test]
    fn test_non_swift_did_not_delegate() {
        // "Did" in a non-Swift node should NOT trigger the Swift delegate check
        let node = make_node("applicationDidFinishLaunching", vec![]);
        // This is a Rust node (from make_node), not Swift, so it should NOT
        // match the Swift delegate pattern — but it may match other patterns
        // because "handle" is a substring. The point is that it doesn't hit
        // is_swift_delegate_method specifically.
        assert!(
            !BddContextDetector::is_swift_delegate_method(&node),
            "Rust node should NOT be detected as Swift delegate"
        );
    }

    #[test]
    fn test_multiple_markers() {
        let node = make_node("handleUserClick", vec!["@event"]);
        let markers = BddContextDetector::detect_markers(&node);
        assert!(!markers.is_empty());
    }
}