repotoire 0.3.112

Graph-powered code analysis CLI. 114 detectors for security, architecture, and code quality.
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
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
//! Unreachable Code Detector
//!
//! Graph-aware detection of unreachable code:
//! 1. Code after return/throw/exit (source pattern)
//! 2. Functions with zero callers in the call graph (dead functions)

use crate::detectors::base::{Detector, DetectorConfig};
use crate::graph::GraphStore;
use crate::models::{Finding, Severity};
use anyhow::Result;
use regex::Regex;
use std::collections::HashSet;
use std::path::PathBuf;
use std::sync::OnceLock;
use tracing::{debug, info};

static RETURN_PATTERN: OnceLock<Regex> = OnceLock::new();

fn return_pattern() -> &'static Regex {
    RETURN_PATTERN.get_or_init(|| {
        Regex::new(
            r"^\s*(return\b|throw\b|raise\b|exit\(|sys\.exit|process\.exit|break;|continue;)",
        )
        .expect("valid regex")
    })
}

/// Entry point patterns - these functions are called externally
const ENTRY_POINT_PATTERNS: &[&str] = &[
    "main",
    "test_",
    "setup",
    "teardown",
    "run",
    "start",
    "init",
    "handle",
    "on_",
    "get_",
    "post_",
    "put_",
    "delete_",
    "patch_",
    "__init__",
    "__new__",
    "__call__",
    "__enter__",
    "__exit__",
    "configure",
    "register",
    "setup_",
    "create_app",
    // Rust trait methods (called via trait dispatch, not visible in call graph)
    "detect",
    "name",
    "description",
    "category",
    "config",
    "new",
    "default",
    "from",
    "into",
    "try_from",
    "try_into",
    "clone",
    "fmt",
    "eq",
    "cmp",
    "hash",
    "drop",
    "deref",
    "serialize",
    "deserialize",
    "build",
    "parse",
    "validate",
    // Builder pattern methods (called on builder instances, not tracked in graph)
    "with_",
    "set_",
    "add_",
    "find",
    "calculate",
    "analyze",
    // Callback/handler patterns (called via function pointers)
    "_cb", // callback suffix
    "_callback",
    "_handler",
    "_hook",
    "_fn",
    // Common interpreter/runtime prefixes (called via dispatch tables)
    // CPython: Py_, PyObject_, PyList_, etc.
    "py_",
    "pyobject_",
    "pylist_",
    "pydict_",
    "pytuple_",
    "pyset_",
    "_py", // internal CPython
    // Lua: lua_, luaL_, luaV_, etc.
    "lua_",
    "lual_",
    "luav_",
    "luac_",
    "luad_",
    "luag_",
    "luah_",
    // Ruby: rb_, RUBY_
    "rb_",
    "ruby_",
    // V8/JavaScript engines
    "v8_",
    "js_",
    // GLib/GTK
    "g_",
    "gtk_",
    "gdk_",
    // libuv
    "uv_",
    "uv__",
    // React/UI framework patterns (exported for external use)
    "use",       // React hooks: useEffect, useState, useCallback, useMemo
    "render",    // React render functions
    "component", // React components
    "create",    // Factory functions: createElement, createContext
    "provide",   // Provider components
    "consume",   // Consumer components
    "forward",   // forwardRef
    "memo",      // React.memo
    "lazy",      // React.lazy
    "suspense",  // Suspense-related
    // Compiler visitor patterns (called via dispatch)
    "visit",     // Visitor pattern: visitNode, visitExpression
    "enter",     // AST traversal: enterBlock
    "exit",      // AST traversal: exitBlock
    "transform", // AST transforms
    "emit",      // Code emission
    "infer",     // Type inference
    "check",     // Type checking
    "validate",  // Validation passes
    "lower",     // IR lowering
    "optimize",  // Optimization passes
    "analyze",   // Analysis passes
];

/// Paths that indicate entry points or dispatch-table code
const ENTRY_POINT_PATHS: &[&str] = &[
    // Direct entry points
    "/cli/",
    "/cmd/",
    "/main",
    "/handlers/",
    "/routes/",
    "/views/",
    "/api/",
    "/endpoints/",
    "/__main__",
    "/tests/",
    "_test.",
    // Dispatch table patterns (functions called via pointers, not direct calls)
    "/jets/",       // JIT/dispatch tables (interpreters)
    "/opcodes/",    // Opcode handlers
    "/callbacks/",  // Callback functions
    "/hooks/",      // Hook functions
    "/vtable/",     // Virtual table implementations
    "/impls/",      // Trait/interface implementations
    "/builtins/",   // Built-in functions
    "/intrinsics/", // Compiler intrinsics
    "/primitives/", // Primitive operations
    "/ops/",        // Operation implementations
    "/ffi/",        // FFI bindings
    "/bindings/",   // Language bindings
    "/wasm/",       // WebAssembly exports
    // Vendored/third-party code (shouldn't flag external code)
    "/ext/",          // External dependencies
    "/vendor/",       // Vendored code
    "/third_party/",  // Third-party libraries
    "/thirdparty/",   // Third-party libraries (alt)
    "/external/",     // External dependencies
    "/deps/",         // Dependencies
    "/node_modules/", // npm packages
    // Framework source code (exports are API surface, not dead code)
    "/packages/react",     // React monorepo packages
    "/packages/shared",    // React shared utilities
    "/packages/scheduler", // React scheduler
    "/packages/use-",      // React hooks packages
    "/reconciler/",        // React reconciler internals
    "/scheduler/",         // Scheduler internals
    "/forks/",             // React platform forks
    "/fiber/",             // React Fiber internals
];

pub struct UnreachableCodeDetector {
    repository_path: PathBuf,
    max_findings: usize,
}

impl UnreachableCodeDetector {
    pub fn new(repository_path: impl Into<PathBuf>) -> Self {
        Self {
            repository_path: repository_path.into(),
            max_findings: 50,
        }
    }

    /// Check if function is likely an entry point (called externally)
    fn is_entry_point(&self, func_name: &str, file_path: &str) -> bool {
        let name_lower = func_name.to_lowercase();

        // Check name patterns
        if ENTRY_POINT_PATTERNS
            .iter()
            .any(|p| name_lower.starts_with(p) || name_lower == *p || name_lower.ends_with(p))
        {
            return true;
        }

        // Check path patterns
        if ENTRY_POINT_PATHS.iter().any(|p| file_path.contains(p)) {
            return true;
        }

        // Exported functions (capitalized in Go, pub in Rust implied by graph)
        if func_name
            .chars()
            .next()
            .map(|c| c.is_uppercase())
            .unwrap_or(false)
        {
            return true;
        }

        // Detect runtime/interpreter naming convention: short_prefix + underscore + name
        // Examples: u3r_word, Py_Initialize, lua_pushnil, rb_str_new
        // Pattern: 2-4 alphanumeric chars followed by underscore
        if Self::has_runtime_prefix(func_name) {
            return true;
        }

        false
    }

    /// Detect common runtime/interpreter naming patterns
    /// Pattern: 2-4 alphanumeric prefix + underscore (e.g., u3r_, Py_, lua_, rb_)
    fn has_runtime_prefix(func_name: &str) -> bool {
        // Find first underscore
        if let Some(underscore_pos) = func_name.find('_') {
            // Prefix must be 2-4 characters
            if (2..=4).contains(&underscore_pos) {
                let prefix = &func_name[..underscore_pos];
                // Prefix must be alphanumeric (allow mixed case for Py_, Rb_, etc.)
                if prefix.chars().all(|c| c.is_alphanumeric()) {
                    // Additional check: avoid false positives from common words
                    let prefix_lower = prefix.to_lowercase();
                    const COMMON_WORDS: &[&str] = &[
                        "get", "set", "is", "do", "can", "has", "new", "old", "add", "del", "pop",
                        "put", "run", "try", "end", "use", "for", "the", "and", "not", "dead",
                        "live", "test", "mock", "fake", "stub", "temp", "tmp", "foo", "bar", "baz",
                        "qux", "call", "read", "load", "save", "send", "recv",
                    ];
                    if !COMMON_WORDS.contains(&prefix_lower.as_str()) {
                        return true;
                    }
                }
            }
        }
        false
    }

    /// Check if function is exported (has export keyword or is in module.exports)
    fn is_exported_function(file_path: &str, func_name: &str, line_start: u32) -> bool {
        let path = std::path::Path::new(file_path);
        let func_pattern = func_name.split("::").last().unwrap_or(func_name);

        if let Some(content) = crate::cache::global_cache().get_content(path) {
            let lines: Vec<&str> = content.lines().collect();

            // Check the function declaration line and a few lines before
            let start = (line_start as usize).saturating_sub(3);
            let end = (line_start as usize + 2).min(lines.len());

            for i in start..end {
                if i < lines.len() {
                    let line = lines[i];

                    // JS/TS export patterns - must be on the actual function line
                    if line.contains("export ")
                        && (line.contains("function")
                            || line.contains("const")
                            || line.contains("=>"))
                    {
                        return true;
                    }
                    if line.contains("export default") {
                        return true;
                    }
                }
            }

            // Check for export statements anywhere in file (re-exports)
            for line in &lines {
                // module.exports = { funcName } or module.exports.funcName
                if line.contains("module.exports") && line.contains(func_pattern) {
                    return true;
                }
                // exports.funcName =
                if line.contains(&format!("exports.{}", func_pattern)) {
                    return true;
                }
                // export { funcName } or export { funcName as alias }
                if (line.contains("export {") || line.contains("export{"))
                    && line.contains(func_pattern)
                {
                    return true;
                }
                // export default funcName
                if line.contains("export default") && line.contains(func_pattern) {
                    return true;
                }
            }

            // Rust: Check for pub fn at the declaration
            if file_path.ends_with(".rs") {
                let start_idx = (line_start as usize).saturating_sub(1);
                if start_idx < lines.len() {
                    let line = lines[start_idx];
                    if line.contains("pub fn") || line.contains("pub async fn") {
                        return true;
                    }
                }
            }

            // Go: Capitalized = exported (checked in is_entry_point already)
            if file_path.ends_with(".go") {
                if let Some(c) = func_pattern.chars().next() {
                    if c.is_uppercase() {
                        return true;
                    }
                }
            }

            // Python: Check for __all__ declaration containing the function name
            if file_path.ends_with(".py") {
                for line in &lines {
                    // __all__ = ['func1', 'func2'] or __all__ = ["func1", "func2"]
                    if line.contains("__all__") && line.contains(func_pattern) {
                        return true;
                    }
                }
            }
        }
        false
    }

    /// Find functions with zero callers using the call graph
    fn find_dead_functions(&self, graph: &dyn crate::graph::GraphQuery) -> Vec<Finding> {
        let mut findings = Vec::new();
        let functions = graph.get_functions();

        // Build set of all called functions
        let called_functions: HashSet<String> = graph
            .get_calls()
            .into_iter()
            .map(|(_, callee)| callee)
            .collect();

        // First pass: find directly dead functions
        let mut directly_dead: HashSet<String> = HashSet::new();

        for func in &functions {
            // Skip if it's called somewhere
            if called_functions.contains(&func.qualified_name) {
                continue;
            }

            // Skip entry points
            if self.is_entry_point(&func.name, &func.file_path) {
                continue;
            }

            // Skip exported functions (called externally)
            if Self::is_exported_function(&func.file_path, &func.qualified_name, func.line_start) {
                continue;
            }

            // Skip functions whose address is taken (callbacks, dispatch tables, etc.)
            // These are invoked indirectly via function pointers, not direct calls
            if func.get_bool("address_taken").unwrap_or(false) {
                continue;
            }

            // Skip test files for this check
            if func.file_path.contains("/test")
                || func.file_path.contains("_test.")
                || func.file_path.contains("/tests/")
                || func.file_path.contains("conftest")
                || func.file_path.contains("type_check")
            {
                continue;
            }

            // Skip scripts/build tools (developer utilities, not production code)
            if func.file_path.contains("/scripts/")
                || func.file_path.contains("/tools/")
                || func.file_path.contains("/build/")
            {
                continue;
            }

            // Skip non-production paths entirely
            if crate::detectors::content_classifier::is_non_production_path(&func.file_path) {
                continue;
            }

            // Skip framework internal paths (exports used externally)
            if func.file_path.contains("packages/react")
                || func.file_path.contains("/react-dom/")
                || func.file_path.contains("/react-server/")
                || func.file_path.contains("/reconciler/")
                || func.file_path.contains("/scheduler/")
                || func.file_path.contains("/shared/")
                || func.file_path.contains("/forks/")
            {
                continue;
            }

            // Skip bundled/generated code: path check (semantic) + content check (additional)
            if crate::detectors::content_classifier::is_likely_bundled_path(&func.file_path) {
                continue;
            }
            if let Some(content) =
                crate::cache::global_cache().get_content(std::path::Path::new(&func.file_path))
            {
                if crate::detectors::content_classifier::is_bundled_code(&content)
                    || crate::detectors::content_classifier::is_minified_code(&content)
                    || crate::detectors::content_classifier::is_fixture_code(
                        &func.file_path,
                        &content,
                    )
                {
                    continue;
                }
            }

            // Skip CLI-related functions (often entry points)
            if func.file_path.contains("/cli")
                || func.name.contains("locate")
                || func.name.contains("app")
                || func.name.contains("create")
            {
                continue;
            }

            // Skip private/internal functions (underscore prefix)
            if func.name.starts_with('_') && !func.name.starts_with("__") {
                continue;
            }

            // Skip constructors (always called when class is instantiated)
            if func.name == "constructor" || func.name == "__init__" || func.name == "new" {
                continue;
            }

            // Skip dev-only functions (conditional compilation)
            let name_lower = func.name.to_lowercase();
            if name_lower.ends_with("dev")
                || name_lower.contains("indev")
                || name_lower.starts_with("warn")
                || name_lower.starts_with("debug")
            {
                continue;
            }

            // Double-check with get_callers for accuracy
            let callers = graph.get_callers(&func.qualified_name);
            if !callers.is_empty() {
                continue;
            }

            // Check if method is called via self.method() in same file (Rust parser limitation)
            if let Some(content) =
                crate::cache::global_cache().get_content(std::path::Path::new(&func.file_path))
            {
                let self_call = format!("self.{}(", func.name);
                if content.contains(&self_call) {
                    continue;
                }
            }

            directly_dead.insert(func.qualified_name.clone());
        }

        // Second pass: find transitively dead functions
        // (functions only called by dead functions)
        let transitively_dead = self.find_transitively_dead(graph, &directly_dead);

        // Create findings for directly dead functions
        for func in &functions {
            if !directly_dead.contains(&func.qualified_name) {
                continue;
            }

            // Check how many functions this dead function calls (impact)
            let callees = graph.get_callees(&func.qualified_name);
            let dead_callees: Vec<_> = callees
                .iter()
                .filter(|c| transitively_dead.contains(&c.qualified_name))
                .collect();

            let cascade_note = if !dead_callees.is_empty() {
                format!(
                    "\n\n⚠️ **Cascade**: Removing this also removes {} transitively dead function(s):\n{}",
                    dead_callees.len(),
                    dead_callees.iter().take(3).map(|c| format!("  - {}", c.name)).collect::<Vec<_>>().join("\n")
                )
            } else {
                String::new()
            };

            debug!("Dead function found: {} in {}", func.name, func.file_path);

            findings.push(Finding {
                id: String::new(),
                detector: "UnreachableCodeDetector".to_string(),
                severity: if !dead_callees.is_empty() {
                    Severity::High
                } else {
                    Severity::Medium
                },
                title: format!("Dead function: {}", func.name),
                description: format!(
                    "Function '{}' has **zero callers** in the codebase.\n\n\
                     This function is never called and may be dead code that can be removed.{}",
                    func.name, cascade_note
                ),
                affected_files: vec![func.file_path.clone().into()],
                line_start: Some(func.line_start),
                line_end: Some(func.line_end),
                suggested_fix: Some(
                    "Options:\n\
                     1. Remove the dead function\n\
                     2. If it's an entry point, add it to exports or ensure it's registered\n\
                     3. If it's a callback, ensure it's passed to the caller"
                        .to_string(),
                ),
                estimated_effort: Some(if !dead_callees.is_empty() {
                    "15 minutes".to_string()
                } else {
                    "10 minutes".to_string()
                }),
                category: Some("dead-code".to_string()),
                cwe_id: Some("CWE-561".to_string()),
                why_it_matters: Some(
                    "Dead functions add maintenance burden without providing value. \
                     They can confuse developers and increase cognitive load."
                        .to_string(),
                ),
                ..Default::default()
            });
        }

        // Create separate findings for transitively dead (lower severity - removing root will fix)
        for func in &functions {
            if !transitively_dead.contains(&func.qualified_name) {
                continue;
            }
            if directly_dead.contains(&func.qualified_name) {
                continue; // Already reported
            }

            // Find which dead function(s) call this one
            let dead_callers: Vec<_> = graph
                .get_callers(&func.qualified_name)
                .into_iter()
                .filter(|c| {
                    directly_dead.contains(&c.qualified_name)
                        || transitively_dead.contains(&c.qualified_name)
                })
                .collect();

            findings.push(Finding {
                id: String::new(),
                detector: "UnreachableCodeDetector".to_string(),
                severity: Severity::Low, // Lower - fixing root dead function will resolve this
                title: format!("Transitively dead: {}", func.name),
                description: format!(
                    "Function '{}' is only called by dead function(s):\n{}\n\n\
                     Removing the dead callers will make this removable too.",
                    func.name,
                    dead_callers
                        .iter()
                        .take(3)
                        .map(|c| format!("  - {}", c.name))
                        .collect::<Vec<_>>()
                        .join("\n")
                ),
                affected_files: vec![func.file_path.clone().into()],
                line_start: Some(func.line_start),
                line_end: Some(func.line_end),
                suggested_fix: Some(
                    "This function will become removable after its dead callers are removed."
                        .to_string(),
                ),
                estimated_effort: Some("5 minutes".to_string()),
                category: Some("dead-code".to_string()),
                cwe_id: Some("CWE-561".to_string()),
                why_it_matters: Some(
                    "Transitively dead code is only reachable through other dead code.".to_string(),
                ),
                ..Default::default()
            });
        }

        findings
    }

    /// Find functions that are transitively dead (only called by dead functions)
    fn find_transitively_dead(
        &self,
        graph: &dyn crate::graph::GraphQuery,
        directly_dead: &HashSet<String>,
    ) -> HashSet<String> {
        let mut transitively_dead: HashSet<String> = HashSet::new();
        let mut changed = true;
        let mut iterations = 0;

        // Iterate until no new dead functions found
        while changed && iterations < 10 {
            changed = false;
            iterations += 1;

            for func in graph.get_functions() {
                // Skip if already marked dead
                if directly_dead.contains(&func.qualified_name)
                    || transitively_dead.contains(&func.qualified_name)
                {
                    continue;
                }

                // Skip entry points
                if self.is_entry_point(&func.name, &func.file_path) {
                    continue;
                }

                // Get all callers
                let callers = graph.get_callers(&func.qualified_name);
                if callers.is_empty() {
                    continue; // Would have been caught as directly dead
                }

                // Check if ALL callers are dead
                let all_callers_dead = callers.iter().all(|c| {
                    directly_dead.contains(&c.qualified_name)
                        || transitively_dead.contains(&c.qualified_name)
                });

                if all_callers_dead {
                    transitively_dead.insert(func.qualified_name.clone());
                    changed = true;
                }
            }
        }

        debug!(
            "Found {} transitively dead functions",
            transitively_dead.len()
        );
        transitively_dead
    }

    /// Find code after return/throw statements using source scanning
    fn find_code_after_return(&self) -> Vec<Finding> {
        let mut findings = Vec::new();
        let walker = ignore::WalkBuilder::new(&self.repository_path)
            .hidden(false)
            .git_ignore(true)
            .build();

        for entry in walker.filter_map(|e| e.ok()) {
            if findings.len() >= self.max_findings {
                break;
            }

            let path = entry.path();
            if !path.is_file() {
                continue;
            }

            let ext = path.extension().and_then(|e| e.to_str()).unwrap_or("");
            // Skip Rust - compiler catches this
            if ext == "rs" {
                continue;
            }
            if !matches!(
                ext,
                "py" | "js" | "ts" | "jsx" | "tsx" | "java" | "go" | "rb" | "php"
            ) {
                continue;
            }

            let rel_path = path.strip_prefix(&self.repository_path).unwrap_or(path);

            if let Some(content) = crate::cache::global_cache().get_content(path) {
                let lines: Vec<&str> = content.lines().collect();

                for i in 0..lines.len().saturating_sub(1) {
                    let line = lines[i];
                    let next = lines[i + 1].trim();

                    // Skip if next line is empty, closing brace, or comment
                    if next.is_empty()
                        || next == "}"
                        || next == "]"
                        || next == ")"  // Closing paren (multi-line calls)
                        || next.starts_with("//")
                        || next.starts_with("#")
                        || next.starts_with("else")
                        || next.starts_with("elif")
                        || next.starts_with("except")
                        || next.starts_with("catch")
                        || next.starts_with("finally")
                        || next.starts_with("case")
                        || next.starts_with("default")
                        || next.starts_with(")")  // Multi-line function call closing
                        || next.starts_with("ctx")  // Common continuation pattern
                        || next.starts_with("param")
                    // Common continuation pattern
                    {
                        continue;
                    }

                    // Skip if current line is inside a multi-line statement
                    if line.trim().ends_with(",") || line.trim().ends_with("(") {
                        continue;
                    }

                    if return_pattern().is_match(line)
                        && !line.contains("if")
                        && !line.contains("?")
                    {
                        let curr_indent = line.len() - line.trim_start().len();
                        let next_indent = lines[i + 1].len() - next.len();

                        if next_indent >= curr_indent && !next.starts_with("}") {
                            findings.push(Finding {
                                id: String::new(),
                                detector: "UnreachableCodeDetector".to_string(),
                                severity: Severity::Medium,
                                title: "Unreachable code after return".to_string(),
                                description: format!(
                                    "Code after return/throw/exit will never execute:\n```\n{}\n{}\n```",
                                    line.trim(), next
                                ),
                                affected_files: vec![rel_path.to_path_buf()],
                                line_start: Some((i + 2) as u32),
                                line_end: Some((i + 2) as u32),
                                suggested_fix: Some(
                                    "Remove unreachable code or fix control flow logic.".to_string()
                                ),
                                estimated_effort: Some("10 minutes".to_string()),
                                category: Some("dead-code".to_string()),
                                cwe_id: Some("CWE-561".to_string()),
                                why_it_matters: Some(
                                    "Unreachable code indicates logic errors and adds confusion."
                                        .to_string()
                                ),
                                ..Default::default()
                            });
                        }
                    }
                }
            }
        }

        findings
    }
}

impl Detector for UnreachableCodeDetector {
    fn name(&self) -> &'static str {
        "UnreachableCodeDetector"
    }

    fn description(&self) -> &'static str {
        "Detects unreachable code and dead functions"
    }

    fn category(&self) -> &'static str {
        "dead-code"
    }

    fn detect(&self, graph: &dyn crate::graph::GraphQuery) -> Result<Vec<Finding>> {
        let mut findings = Vec::new();

        // Graph-based: find functions with zero callers
        findings.extend(self.find_dead_functions(graph));

        // Source-based: find code after return/throw
        findings.extend(self.find_code_after_return());

        info!("UnreachableCodeDetector found {} findings", findings.len());
        Ok(findings)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::graph::{CodeEdge, CodeNode, GraphStore};

    #[test]
    fn test_is_entry_point() {
        let detector = UnreachableCodeDetector::new(".");

        assert!(detector.is_entry_point("main", "src/main.py"));
        assert!(detector.is_entry_point("test_something", "tests/test_foo.py"));
        assert!(detector.is_entry_point("handle_request", "handlers/api.py"));
        assert!(detector.is_entry_point("GetUser", "api/user.go")); // Capitalized = exported
        assert!(!detector.is_entry_point("helper_func", "src/utils.py"));
    }

    #[test]
    fn test_find_dead_functions() {
        let graph = GraphStore::in_memory();

        // Add a dead function (no callers)
        graph.add_node(
            CodeNode::function("dead_func", "src/utils.py")
                .with_qualified_name("utils::dead_func")
                .with_lines(10, 20),
        );

        // Add a live function with a caller
        graph.add_node(
            CodeNode::function("live_func", "src/utils.py")
                .with_qualified_name("utils::live_func")
                .with_lines(30, 40),
        );
        graph.add_node(
            CodeNode::function("caller", "src/main.py")
                .with_qualified_name("main::caller")
                .with_lines(1, 10),
        );
        graph.add_edge_by_name("main::caller", "utils::live_func", CodeEdge::calls());

        let detector = UnreachableCodeDetector::new(".");
        let findings = detector.find_dead_functions(&graph);

        assert_eq!(findings.len(), 1);
        assert!(findings[0].title.contains("dead_func"));
    }
}