jonesy 0.7.11

Jonesy is here to help you not panic!
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
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
//! Detection heuristics for panic analysis.
//!
//! Jonesy uses a layered set of heuristics to achieve two core tasks:
//!
//! 1. **Source code ownership** — Distinguishing user/crate code from standard library
//!    and dependency code in DWARF debug info and symbol tables.
//! 2. **Panic cause classification** — Identifying _what kind_ of panic a call path
//!    leads to (e.g., `unwrap()` on `None` vs. index out of bounds).
//!
//! This module consolidates the pattern constants and classification functions used
//! throughout the crate, serving as the single reference for how detection works.
//!
//! # Source Code Ownership
//!
//! DWARF debug info includes file paths for every source line. When the compiler
//! inlines stdlib code (e.g., `Option::unwrap()`), the line table contains paths
//! from the Rust toolchain (like `/rustc/.../option.rs`). Jonesy must distinguish
//! these from user code to report only panic points the developer controls.
//!
//! Three complementary functions handle this:
//!
//! - [`is_dependency_path`] — Checks if a file path belongs to a dependency or
//!   the standard library. Uses known path prefixes (`.cargo/registry/`, `/rustc/`,
//!   `.rustup/toolchains/`, etc.).
//!
//! - [`is_stdlib_function`] — Checks if a demangled function name belongs to the
//!   standard library by namespace (`core::`, `std::`, `alloc::`), including trait
//!   impl forms like `<core::option::Option<T>>::unwrap`.
//!
//! - `matches_crate_pattern_validated` (in [`crate::sym`]) — Positive matching:
//!   checks if a path belongs to the user's crate based on `src/` patterns derived
//!   from `Cargo.toml`. For single-crate projects, validates against an allowlist
//!   of actual source files to prevent false positives from dependencies that use
//!   relative `src/` paths in their DWARF info.
//!
//! # Panic Entry Points
//!
//! Analysis begins by finding _entry points_ — the low-level functions that the
//! Rust panic runtime calls. The entry points differ between binary and library
//! analysis:
//!
//! - **Binary analysis** uses [`PANIC_SYMBOL_PATTERNS`] to find symbols like
//!   `rust_panic$` in the binary's symbol table, then traces backwards through
//!   the call graph to find user code that reaches them.
//!
//! - **Library analysis** (rlib/staticlib) cannot trace from a single entry point
//!   because library object files are not fully linked. Instead, it uses
//!   [`LIBRARY_PANIC_PATTERNS`] to match demangled relocation targets against
//!   known panic-related functions.
//!
//! - **Abort paths** — Some panics (like OOM via `alloc_error_handler`) go through
//!   `std::process::abort()` instead of the normal panic runtime. These are
//!   matched by [`ABORT_SYMBOL_PATTERNS`].
//!
//! # Panic Cause Classification
//!
//! Once a panic path is found, jonesy classifies _why_ it panics. This happens
//! in [`detect_panic_cause`] by matching against the
//! function name at the panic site. The classification uses a priority order:
//!
//! 1. **Exact symbol match** — e.g., `panic_bounds_check` → bounds error
//! 2. **Domain detection** — e.g., `core::fmt::` prefix → formatting error
//! 3. **Contextual disambiguation** — e.g., `unwrap_failed` in `option.rs`
//!    vs. `result.rs` distinguishes `JP006` from `JP007`
//! 4. **Fallback** — `PanicCause::Unknown` when no heuristic matches
//!
//! # Direct vs. Indirect Panics
//!
//! [`is_panic_triggering_function`] determines whether a function in the call
//! chain _directly_ triggers a panic (like `unwrap()`, `assert!()`, `panic!()`)
//! or merely calls something that might panic internally. This distinction
//! controls the help message: direct panics suggest alternatives (e.g., "use
//! `if let`"), while indirect panics note the intermediate function.

// ---------------------------------------------------------------------------
// Panic entry point patterns
// ---------------------------------------------------------------------------

/// Symbol patterns for finding panic entry points in **binaries**.
///
/// These are searched in the binary's symbol table (via `nm`-style lookup).
/// The first match found becomes the root of the call-graph trace.
///
/// | Pattern              | Purpose                                     |
/// |----------------------|---------------------------------------------|
/// | `rust_panic$`        | Main Rust panic entry point                 |
/// | `panic_fmt$`         | Core panic formatting (fallback entry)      |
/// | `panic_display`      | Panic display helper                        |
/// | `slice_index_fail`   | Vec/slice index-out-of-bounds panics        |
/// | `str_index_overflow` | String slice boundary violation panics      |
///
/// The `$` suffix in some patterns is significant — it anchors the match to
/// the end of the symbol name to avoid matching functions that merely contain
/// the substring.
pub const PANIC_SYMBOL_PATTERNS: &[&str] = &[
    "rust_panic$",
    "panic_fmt$",
    "panic_display",
    "slice_index_fail",
    "str_index_overflow",
];

/// Symbol patterns for **abort-based** error paths.
///
/// Some error conditions (notably OOM via `alloc_error_handler`) go through
/// `std::process::abort()` instead of the normal panic/unwind machinery.
/// These are traced separately to catch panics that would otherwise be missed.
pub const ABORT_SYMBOL_PATTERNS: &[&str] = &["std::process::abort"];

/// Demangled symbol patterns for finding panic targets in **library** analysis.
///
/// Library analysis (rlib/staticlib) works differently from binary analysis:
/// object files contain relocations to external symbols but have no linked
/// call graph. This list defines the demangled names that indicate a
/// relocation target is panic-related.
///
/// The list is checked with `contains()` matching, so `"core::panicking::panic"`
/// also matches `core::panicking::panic_fmt` etc. Order does not matter.
///
/// # Categories
///
/// **Direct panic functions** — the low-level panic entry points:
/// - `core::panicking::panic`, `panic_fmt`, `panic_display`
/// - `panic_in_cleanup` (panic during drop), `panic_cannot_unwind`
/// - `panic_const` (compile-time overflow checks)
/// - `panic_bounds_check`, `panic_nounwind_fmt`
/// - `assert_failed` (assert/debug_assert macros)
/// - `std::panicking::begin_panic` / `begin_panic_fmt`
///
/// **Option panic functions** — called when unwrapping `None`:
/// - `core::option::Option<T>::unwrap`, `::expect`
/// - `core::option::unwrap_failed` (internal panic function)
///
/// **Result panic functions** — called when unwrapping `Err`:
/// - `core::result::Result<T, E>::unwrap`, `::expect`
/// - `core::result::Result<T, E>::unwrap_err`, `::expect_err`
/// - `core::result::unwrap_failed` (internal panic function)
///
/// # Additional dynamic patterns
///
/// At runtime, the library analysis also matches:
/// - Any symbol containing `core::panicking::` (catches future additions)
/// - `std::panicking::*` except `set_hook`/`take_hook` (which configures
///   the panic-handler, not trigger panics)
pub const LIBRARY_PANIC_PATTERNS: &[&str] = &[
    // Direct panic functions
    "core::panicking::panic",
    "core::panicking::panic_fmt",
    "core::panicking::panic_display",
    "core::panicking::panic_in_cleanup",
    "core::panicking::panic_const",
    "core::panicking::panic_bounds_check",
    "core::panicking::panic_nounwind_fmt",
    "core::panicking::panic_cannot_unwind",
    "core::panicking::assert_failed",
    "std::panicking::begin_panic",
    "std::panicking::begin_panic_fmt",
    // Option panic functions
    "core::option::Option<T>::unwrap",
    "core::option::Option<T>::expect",
    "core::option::unwrap_failed",
    // Result panic functions
    "core::result::Result<T,E>::unwrap",
    "core::result::Result<T,E>::expect",
    "core::result::Result<T,E>::unwrap_err",
    "core::result::Result<T,E>::expect_err",
    "core::result::unwrap_failed",
];

// ---------------------------------------------------------------------------
// Source code ownership heuristics
// ---------------------------------------------------------------------------

/// Check if a file path belongs to a dependency or the standard library.
///
/// Returns `true` if the path should **not** be reported as user code. This is
/// used in both binary and library analysis to filter DWARF line table entries
/// that point into inlined stdlib code.
///
/// # Path categories detected
///
/// | Pattern                      | Source                                    |
/// |------------------------------|-------------------------------------------|
/// | `.cargo/registry/`           | Crates.io dependencies (Unix)             |
/// | `.cargo\registry\`           | Crates.io dependencies (Windows)          |
/// | `/rustc/`                    | Compiler-generated paths (includes hash)  |
/// | `/.rustup/toolchains/`       | Toolchain stdlib source                   |
/// | `/rustlib/src/`              | Stdlib source in sysroot                  |
/// | `/rust/deps/` (prefix)       | Rust CI dependency paths                  |
/// | `library/` (prefix)          | Relative stdlib paths in DWARF            |
/// | `/__/`                       | Generated code boundaries (e.g., objc2)   |
/// | `__` (prefix)                | Generated code (macro-generated modules)  |
/// | `src/__` (prefix)            | Generated code in src directory            |
///
/// # Why both file paths and function names?
///
/// DWARF line tables use file paths while symbol tables use function names.
/// A call to `opt.unwrap()` may be inlined, leaving only the stdlib file path
/// (`option.rs`) in the line table — there is no function boundary to check.
/// Conversely, a function like `core::option::unwrap_failed` appears only in
/// the symbol table. Both checks are needed for complete coverage.
pub fn is_dependency_path(file_path: &str) -> bool {
    // Cargo registry dependencies (absolute paths)
    if file_path.contains(".cargo/registry/") || file_path.contains(".cargo\\registry\\") {
        return true;
    }

    // Rust stdlib and compiler-generated paths
    if file_path.contains("/rustc/")
        || file_path.contains("/.rustup/toolchains/")
        || file_path.contains("/rustlib/src/")
        || file_path.starts_with("/rust/deps/")
        || file_path.starts_with("library/")
    {
        return true;
    }

    // Internal/generated paths from dependencies (common patterns)
    // These use relative src/ paths that would match the "src/" pattern for single-crate projects
    // The __ prefixes are used by macro-generated code in crates like objc2
    // Use segment-boundary checks to avoid false positives on user dirs like /Users/__myuser__/
    if file_path.contains("/__/") || file_path.starts_with("__") || file_path.starts_with("src/__")
    {
        return true;
    }

    false
}

/// Check if a demangled function name belongs to the standard library.
///
/// Returns `true` for functions in the `core`, `std`, or `alloc` crates.
/// Handles multiple name formats that arise from Rust's name mangling:
///
/// | Format                       | Example                                  |
/// |------------------------------|------------------------------------------|
/// | Direct namespace             | `core::option::Option::unwrap`           |
/// | Generic bounds               | `<core::option::Option<T>>::unwrap`      |
/// | Trait impl with space        | `<Foo as core::fmt::Display>::fmt`       |
/// | Nested module reference      | `mycrate::core::panicking::panic`        |
///
/// This function is used during library analysis to skip stdlib callers
/// and report only user-code panic sources.
pub fn is_stdlib_function(name: &str) -> bool {
    name.starts_with("core::")
        || name.starts_with("std::")
        || name.starts_with("alloc::")
        || name.starts_with("<core::")
        || name.starts_with("<std::")
        || name.starts_with("<alloc::")
        || name.contains(" core::")
        || name.contains(" std::")
        || name.contains(" alloc::")
        || name.contains("::core::")
        || name.contains("::std::")
        || name.contains("::alloc::")
}

/// Paths in DWARF that indicate standard library source code.
///
/// Used to identify when a file path points to Rust standard library source.
///
/// These cover both the modern Rust source layout (`/library/core/src/`) and
/// the legacy layout (`/src/libcore/`).
pub const STDLIB_SOURCE_PREFIXES: &[&str] = &[
    "/rustc/",
    // Modern layout (absolute)
    "/library/core/src/",
    "/library/std/src/",
    "/library/alloc/src/",
    // Modern layout (relative — DWARF sometimes omits leading slash)
    "library/core/src/",
    "library/std/src/",
    "library/alloc/src/",
    // Legacy layout
    "/src/libstd/",
    "/src/libcore/",
    "/src/liballoc/",
];

/// Check if a file path points to standard library source code.
///
/// This is a narrower check than [`is_dependency_path`] — it specifically
/// identifies Rust stdlib source files, not all dependencies.
pub fn is_stdlib_source(file_path: &str) -> bool {
    STDLIB_SOURCE_PREFIXES
        .iter()
        .any(|prefix| file_path.contains(prefix))
}

// ---------------------------------------------------------------------------
// Direct vs. indirect panic classification
// ---------------------------------------------------------------------------

/// Check if a function name represents a **direct** panic-triggering function.
///
/// Direct panic functions are those that _immediately_ cause a panic when called
/// (e.g., `unwrap()`, `assert!()`, `panic!()`). Indirect functions are user code
/// that calls something that eventually panics.
///
/// This distinction is used for help messages:
/// - **Direct**: "Use `if let`, `match`, or `unwrap_or` instead"
/// - **Indirect**: "This calls `foo()` which may panic internally"
///
/// # Patterns matched
///
/// **Unwrap/expect variants:**
/// - `unwrap_failed`, `expect_failed` — internal panic functions
/// - `unwrap` (excluding `unwrap_or*`) — `Option::unwrap()` / `Result::unwrap()`
/// - `expect` with `Option` or `Result` — `.expect("msg")`
///
/// **Panic runtime functions:**
/// - `panic_fmt`, `panic_display` — explicit `panic!()` macro
/// - `panic_bounds_check` — array/slice index out of bounds
/// - `panic_const_*` — compile-time overflow/division checks
/// - `panic_in_cleanup`, `panic_cannot_unwind`, `panic_nounwind`
/// - `panic_misaligned_pointer`, `panic_invalid_enum`
///
/// **Assert macros:**
/// - `assert_failed` — `assert!()`, `assert_eq!()`, `assert_ne!()`
///
/// **Capacity/allocation:**
/// - `capacity_overflow` — `Vec::with_capacity(usize::MAX)`
/// - `handle_alloc_error` — OOM handler
///
/// **String/slice errors:**
/// - `slice_error_fail`, `str_index_overflow_fail`
/// - `index<`, `::index<`, `Index::index` — Index trait implementations
pub fn is_panic_triggering_function(func_name: &str) -> bool {
    // Unwrap/expect variants
    func_name.contains("unwrap_failed")
        || func_name.contains("expect_failed")
        // Direct unwrap/expect calls (before they reach _failed)
        || (func_name.contains("unwrap") && !func_name.contains("unwrap_or"))
        || (func_name.contains("expect") && func_name.contains("Option"))
        || (func_name.contains("expect") && func_name.contains("Result"))
        // Panic functions
        || func_name.contains("panic_fmt")
        || func_name.contains("panic_display")
        || func_name.contains("panic_bounds_check")
        || func_name.contains("panic_const_")
        || func_name.contains("panic_in_cleanup")
        || func_name.contains("panic_cannot_unwind")
        || func_name.contains("panic_nounwind")
        || func_name.contains("panic_misaligned_pointer")
        || func_name.contains("panic_invalid_enum")
        // Assert
        || func_name.contains("assert_failed")
        // Capacity/allocation
        || func_name.contains("capacity_overflow")
        || func_name.contains("handle_alloc_error")
        // String/slice errors
        || func_name.contains("slice_error_fail")
        || func_name.contains("str_index_overflow_fail")
        // Index trait - direct bounds check
        // Matches both simple names ("index<T>") and fully qualified demangled
        // linkage names ("<impl Index<I> for str>::index")
        || func_name.starts_with("index<")
        || func_name.contains("::index<")
        || func_name.contains("Index::index")
        || func_name.contains(">::index")
}

/// File path filter for library analysis DWARF entries.
///
/// Used in library (rlib/staticlib) analysis to filter out DWARF file entries
/// that point to stdlib or dependency code. This is applied when processing
/// `CallerInfo` from the `LibraryCallGraph` to ensure only user code paths
/// are reported.
///
/// This is a superset of the checks in [`is_dependency_path`], also covering
/// additional paths that appear in library DWARF info (e.g., `/rust/` CI paths,
/// `/deps/` subdirectories).
pub fn is_library_dependency_path(file_path: &str) -> bool {
    is_dependency_path(file_path) || file_path.starts_with("/rust/") || file_path.contains("/deps/")
}

// ---------------------------------------------------------------------------
// Panic cause classification
// ---------------------------------------------------------------------------

use crate::panic_cause::PanicCause;

/// Detect panic cause from a function name in the call chain.
///
/// Walks the priority order described in the module docs:
///
/// 1. Exact symbol match (`panic_bounds_check`, `unwrap_failed`, …)
/// 2. Domain detection (`core::fmt::`, `capacity_overflow`, …)
/// 3. Contextual disambiguation (file path for Option vs Result)
/// 4. Collection internals (`hashbrown::raw::`, `std::collections::hash::`)
/// 5. Fallback → `None` (unknown)
///
/// The optional `file_path` helps distinguish Option vs Result for unwrap/expect.
pub fn detect_panic_cause(func_name: &str, file_path: Option<&str>) -> Option<PanicCause> {
    // Check for drop/cleanup panic paths first
    if func_name.contains("panic_in_cleanup") {
        return Some(PanicCause::PanicInDrop);
    }
    if func_name.contains("panic_cannot_unwind") || func_name.contains("panic_nounwind") {
        return Some(PanicCause::CannotUnwind);
    }

    // Check for specific panic functions
    if func_name.contains("panic_bounds_check") {
        return Some(PanicCause::BoundsCheck);
    }
    if func_name.contains("panic_const_add_overflow") {
        return Some(PanicCause::ArithmeticOverflow("addition".to_string()));
    }
    if func_name.contains("panic_const_sub_overflow") {
        return Some(PanicCause::ArithmeticOverflow("subtraction".to_string()));
    }
    if func_name.contains("panic_const_mul_overflow") {
        return Some(PanicCause::ArithmeticOverflow("multiplication".to_string()));
    }
    if func_name.contains("panic_const_div_overflow") {
        return Some(PanicCause::ArithmeticOverflow("division".to_string()));
    }
    if func_name.contains("panic_const_rem_overflow") {
        return Some(PanicCause::ArithmeticOverflow("remainder".to_string()));
    }
    if func_name.contains("panic_const_neg_overflow") {
        return Some(PanicCause::ArithmeticOverflow("negation".to_string()));
    }
    if func_name.contains("panic_const_shl_overflow") {
        return Some(PanicCause::ShiftOverflow("left".to_string()));
    }
    if func_name.contains("panic_const_shr_overflow") {
        return Some(PanicCause::ShiftOverflow("right".to_string()));
    }
    if func_name.contains("panic_const_div_by_zero") {
        return Some(PanicCause::DivisionByZero);
    }
    if func_name.contains("panic_const_rem_by_zero") {
        return Some(PanicCause::DivisionByZero);
    }
    // unwrap/expect detection - distinguish Option vs Result by file path or function name
    // Check for Result::expect first (it calls unwrap_failed internally)
    if func_name.contains("Result") && func_name.contains("expect") {
        return Some(PanicCause::ExpectErr);
    }
    if func_name.contains("unwrap_failed") {
        // Check file path first (most reliable), then fall back to function name
        // Note: file_path may be the crate source file (not stdlib) when called from
        // rlib analysis, so always check func_name as fallback
        let is_result = file_path
            .filter(|f| {
                f.contains("result.rs")
                    || f.contains("core/result")
                    || f.contains("option.rs")
                    || f.contains("core/option")
            })
            .map(|f| f.contains("result.rs") || f.contains("core/result"))
            .unwrap_or_else(|| func_name.contains("result"));
        if is_result {
            // core::result::unwrap_failed - used by Result::unwrap()
            // (Result::expect is detected above via the caller)
            return Some(PanicCause::UnwrapErr);
        } else {
            // core::option::unwrap_failed
            return Some(PanicCause::UnwrapNone);
        }
    }
    if func_name.contains("expect_failed") {
        // Only Option has expect_failed; Result::expect() uses unwrap_failed
        return Some(PanicCause::ExpectNone);
    }
    // Assert macros - both assert!() and debug_assert!() compile to the same
    // assert_failed function, so we cannot distinguish them at the binary level.
    if func_name.contains("assert_failed") {
        return Some(PanicCause::AssertFailed);
    }
    // panic_display is explicit panic! with a simple message
    if func_name.contains("panic_display") {
        return Some(PanicCause::ExplicitPanic);
    }
    // Check for unreachable/unimplemented/todo patterns
    if func_name.contains("unreachable") && func_name.contains("panic") {
        return Some(PanicCause::Unreachable);
    }

    // ============================================================
    // Stdlib domain detection - detect panics from specific domains
    // ============================================================

    // Formatting domain (core::fmt::, alloc::fmt::)
    // These functions are in the call chain when format!/write!/Display/Debug panic
    if func_name.contains("core::fmt::") || func_name.contains("alloc::fmt::") {
        return Some(PanicCause::FormattingError);
    }
    if func_name.contains("format_inner") || func_name.contains("write_fmt") {
        return Some(PanicCause::FormattingError);
    }
    // Display/Debug trait formatting
    if func_name.contains("::fmt") && (func_name.contains("Display") || func_name.contains("Debug"))
    {
        return Some(PanicCause::FormattingError);
    }

    // Capacity/allocation domain
    if func_name.contains("capacity_overflow") {
        return Some(PanicCause::CapacityOverflow);
    }
    if func_name.contains("handle_alloc_error")
        || func_name.contains("alloc_error_handler")
        || func_name.contains("alloc_error_hook")
    {
        return Some(PanicCause::OutOfMemory);
    }
    if func_name.contains("raw_vec") && func_name.contains("grow") {
        return Some(PanicCause::CapacityOverflow);
    }
    // hashbrown (HashMap/HashSet internals) allocation error
    if func_name.contains("hashbrown") && func_name.contains("alloc_err") {
        return Some(PanicCause::OutOfMemory);
    }

    // String/slice domain
    if func_name.contains("slice_error_fail") {
        return Some(PanicCause::StringSliceError);
    }
    if func_name.contains("str_index_overflow_fail") {
        return Some(PanicCause::StringSliceError);
    }
    if func_name.contains("slice_start_index_overflow")
        || func_name.contains("slice_end_index_overflow")
    {
        return Some(PanicCause::StringSliceError);
    }

    // Bounds checking domain - detect from Index trait implementations
    // These are called from user code when indexing slices/vecs
    // Matches both simple names ("index<T, usize>") and fully qualified demangled
    // linkage names ("<impl Index<I> for str>::index")
    if func_name.starts_with("index<")
        || func_name.contains("::index<")
        || func_name.contains("Index::index")
        || func_name.contains(">::index")
    {
        // Check if it's HashMap/BTreeMap indexing (key not found panic)
        let is_map_op = func_name.contains("HashMap")
            || func_name.contains("BTreeMap")
            || func_name.contains("hash::map")
            || func_name.contains("btree::map");
        if is_map_op {
            return Some(PanicCause::KeyNotFound);
        }

        // Check if it's for str (string slice) vs array/vec (bounds check)
        // String slicing can be detected via:
        // 1. Function name containing str:: or core::str::
        // 2. File path matching known stdlib string module paths
        let is_string_op = func_name.contains("str::") || func_name.contains("core::str::");
        let is_string_file = file_path
            .map(|f| {
                // Normalize path separators for cross-platform matching
                let normalized = f.replace('\\', "/");
                // Only match known stdlib string module paths to avoid false positives
                // from user directories named "str"
                normalized.contains("/library/core/src/str/")
                    || normalized.contains("/library/std/src/str/")
                    || normalized.contains("/src/libcore/str/")
            })
            .unwrap_or(false);
        if is_string_op || is_string_file {
            return Some(PanicCause::StringSliceError);
        }
        return Some(PanicCause::BoundsCheck);
    }

    // Invalid enum discriminant - happens with unsafe enum transmutes or memory corruption
    if func_name.contains("panic_invalid_enum_construction") {
        return Some(PanicCause::InvalidEnum);
    }

    // Misaligned pointer dereference - unsafe code dereferencing misaligned pointers
    if func_name.contains("panic_misaligned_pointer_dereference") {
        return Some(PanicCause::MisalignedPointer);
    }

    // ============================================================
    // Collection internals - hashbrown raw table operations
    // ============================================================
    // hashbrown::raw:: contains the low-level hash table allocation/layout/capacity
    // functions. When these appear on a panic path, it indicates a capacity overflow
    // or allocation failure during HashMap/HashSet operations.
    // This is more specific than the CannotUnwind cause that gets detected earlier
    // from panic_nounwind_fmt on the allocator error path.
    if func_name.contains("hashbrown::raw::") {
        return Some(PanicCause::CapacityOverflow);
    }

    // std::collections::hash HashMap/HashSet creation and allocation functions
    // may panic through hasher initialization (thread-local storage) or internal
    // allocation. When no more specific cause is detected from the panic path,
    // classify as capacity overflow since that's the most actionable cause.
    if func_name.contains("std::collections::hash::") {
        return Some(PanicCause::CapacityOverflow);
    }

    // panic_fmt is the core panic function - if we reach here without a more
    // specific match, leave cause as None (unknown) to avoid incorrect labeling.
    None
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

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

    // -- is_dependency_path tests --

    #[test]
    fn test_cargo_registry_unix() {
        assert!(is_dependency_path(
            "/home/user/.cargo/registry/src/crates.io/serde-1.0/src/lib.rs"
        ));
    }

    #[test]
    fn test_cargo_registry_windows() {
        assert!(is_dependency_path(
            "C:\\Users\\user\\.cargo\\registry\\src\\crates.io\\serde-1.0\\src\\lib.rs"
        ));
    }

    #[test]
    fn test_rustc_path() {
        assert!(is_dependency_path(
            "/rustc/abc123/library/core/src/option.rs"
        ));
    }

    #[test]
    fn test_rustup_toolchain() {
        assert!(is_dependency_path(
            "/Users/user/.rustup/toolchains/stable-aarch64-apple-darwin/lib/rustlib/src/rust/library/core/src/option.rs"
        ));
    }

    #[test]
    fn test_rustlib_src() {
        assert!(is_dependency_path("/usr/lib/rustlib/src/rust/core.rs"));
    }

    #[test]
    fn test_relative_library_path() {
        assert!(is_dependency_path("library/core/src/option.rs"));
    }

    #[test]
    fn test_generated_code_boundary() {
        assert!(is_dependency_path("src/__generated/bindings.rs"));
        assert!(is_dependency_path("__objc2/src/lib.rs"));
        assert!(is_dependency_path("some/path/__/generated.rs"));
    }

    #[test]
    fn test_user_code_not_dependency() {
        assert!(!is_dependency_path("src/main.rs"));
        assert!(!is_dependency_path("src/lib.rs"));
        assert!(!is_dependency_path("/Users/user/project/src/module/mod.rs"));
        assert!(!is_dependency_path("examples/demo/src/main.rs"));
    }

    // -- is_stdlib_function tests --

    #[test]
    fn test_stdlib_direct_namespace() {
        assert!(is_stdlib_function("core::option::Option::unwrap"));
        assert!(is_stdlib_function("std::io::Read::read"));
        assert!(is_stdlib_function("alloc::vec::Vec::push"));
    }

    #[test]
    fn test_stdlib_generic_bounds() {
        assert!(is_stdlib_function("<core::option::Option<T>>::unwrap"));
        assert!(is_stdlib_function("<std::vec::Vec<T>>::push"));
    }

    #[test]
    fn test_stdlib_trait_impl() {
        assert!(is_stdlib_function("<MyStruct as core::fmt::Display>::fmt"));
    }

    #[test]
    fn test_user_function_not_stdlib() {
        assert!(!is_stdlib_function("my_crate::module::function"));
        assert!(!is_stdlib_function("cause_an_unwrap"));
    }

    // -- is_panic_triggering_function tests --

    #[test]
    fn test_unwrap_variants() {
        assert!(is_panic_triggering_function("unwrap_failed"));
        assert!(is_panic_triggering_function("expect_failed"));
        assert!(is_panic_triggering_function(
            "core::option::Option<i32>::unwrap"
        ));
        assert!(!is_panic_triggering_function("unwrap_or_default"));
    }

    #[test]
    fn test_panic_functions() {
        assert!(is_panic_triggering_function("panic_fmt"));
        assert!(is_panic_triggering_function("panic_bounds_check"));
        assert!(is_panic_triggering_function("panic_const_add_overflow"));
        assert!(is_panic_triggering_function("panic_misaligned_pointer"));
    }

    #[test]
    fn test_user_function_not_triggering() {
        assert!(!is_panic_triggering_function("my_function"));
        assert!(!is_panic_triggering_function("process_data"));
    }

    // -- is_stdlib_source tests --

    #[test]
    fn test_stdlib_source_paths() {
        assert!(is_stdlib_source("/rustc/abc123/library/core/src/option.rs"));
        assert!(is_stdlib_source("/library/core/src/panicking.rs"));
        assert!(is_stdlib_source("/library/std/src/io/mod.rs"));
        // Relative paths (DWARF sometimes omits leading slash)
        assert!(is_stdlib_source("library/core/src/panicking.rs"));
        assert!(is_stdlib_source("library/std/src/io/mod.rs"));
        assert!(is_stdlib_source("library/alloc/src/vec/mod.rs"));
        // User code and dependencies should not match
        assert!(!is_stdlib_source("src/main.rs"));
        assert!(!is_stdlib_source(
            "/Users/user/.cargo/registry/src/serde/lib.rs"
        ));
    }

    // -- is_library_dependency_path tests --

    #[test]
    fn test_library_dependency_paths() {
        // Inherits all is_dependency_path checks
        assert!(is_library_dependency_path("/rustc/abc/core.rs"));
        assert!(is_library_dependency_path("library/core/src/option.rs"));
        assert!(is_library_dependency_path(
            "/home/user/.cargo/registry/serde.rs"
        ));
        assert!(is_library_dependency_path(
            "/home/user/.rustup/toolchains/stable/lib.rs"
        ));
        // Additional library-specific checks
        assert!(is_library_dependency_path("/rust/deps/std/src/lib.rs"));
        assert!(is_library_dependency_path("target/debug/deps/serde.rs"));
        // User code should not be filtered
        assert!(!is_library_dependency_path("src/main.rs"));
        assert!(!is_library_dependency_path("src/arch/arm64/mod.rs"));
        assert!(!is_library_dependency_path("src/raw/mod.rs"));
    }

    // -- pattern constant tests --

    #[test]
    fn test_panic_symbol_patterns_cover_key_entry_points() {
        assert!(PANIC_SYMBOL_PATTERNS.iter().any(|p| p.contains("panic")));
        assert!(PANIC_SYMBOL_PATTERNS.iter().any(|p| p.contains("slice")));
    }

    #[test]
    fn test_library_panic_patterns_comprehensive() {
        assert!(LIBRARY_PANIC_PATTERNS.iter().any(|p| p.contains("panic")));
        assert!(LIBRARY_PANIC_PATTERNS.iter().any(|p| p.contains("unwrap")));
        assert!(LIBRARY_PANIC_PATTERNS.iter().any(|p| p.contains("expect")));
        assert!(LIBRARY_PANIC_PATTERNS.iter().any(|p| p.contains("option")));
        assert!(LIBRARY_PANIC_PATTERNS.iter().any(|p| p.contains("result")));
    }

    // -- detect_panic_cause tests --

    #[test]
    fn test_detect_panic_cause_bounds_check() {
        assert_eq!(
            detect_panic_cause("panic_bounds_check", None),
            Some(PanicCause::BoundsCheck)
        );
    }

    #[test]
    fn test_detect_panic_cause_arithmetic_overflow() {
        assert_eq!(
            detect_panic_cause("panic_const_add_overflow", None),
            Some(PanicCause::ArithmeticOverflow("addition".to_string()))
        );
        assert_eq!(
            detect_panic_cause("panic_const_sub_overflow", None),
            Some(PanicCause::ArithmeticOverflow("subtraction".to_string()))
        );
        assert_eq!(
            detect_panic_cause("panic_const_mul_overflow", None),
            Some(PanicCause::ArithmeticOverflow("multiplication".to_string()))
        );
    }

    #[test]
    fn test_detect_panic_cause_shift_overflow() {
        assert_eq!(
            detect_panic_cause("panic_const_shl_overflow", None),
            Some(PanicCause::ShiftOverflow("left".to_string()))
        );
        assert_eq!(
            detect_panic_cause("panic_const_shr_overflow", None),
            Some(PanicCause::ShiftOverflow("right".to_string()))
        );
    }

    #[test]
    fn test_detect_panic_cause_division_by_zero() {
        assert_eq!(
            detect_panic_cause("panic_const_div_by_zero", None),
            Some(PanicCause::DivisionByZero)
        );
        assert_eq!(
            detect_panic_cause("panic_const_rem_by_zero", None),
            Some(PanicCause::DivisionByZero)
        );
    }

    #[test]
    fn test_detect_panic_cause_unwrap_failed_option() {
        assert_eq!(
            detect_panic_cause("unwrap_failed", Some("option.rs")),
            Some(PanicCause::UnwrapNone)
        );
    }

    #[test]
    fn test_detect_panic_cause_unwrap_failed_result() {
        assert_eq!(
            detect_panic_cause("unwrap_failed", Some("result.rs")),
            Some(PanicCause::UnwrapErr)
        );
        assert_eq!(
            detect_panic_cause("unwrap_failed", Some("core/result/mod.rs")),
            Some(PanicCause::UnwrapErr)
        );
    }

    #[test]
    fn test_detect_panic_cause_expect_failed() {
        assert_eq!(
            detect_panic_cause("expect_failed", None),
            Some(PanicCause::ExpectNone)
        );
    }

    #[test]
    fn test_detect_panic_cause_result_expect() {
        assert_eq!(
            detect_panic_cause("Result::expect", None),
            Some(PanicCause::ExpectErr)
        );
    }

    #[test]
    fn test_detect_panic_cause_assert_failed() {
        assert_eq!(
            detect_panic_cause("assert_failed", None),
            Some(PanicCause::AssertFailed)
        );
        assert_eq!(
            detect_panic_cause("assert_failed", Some("src/main.rs")),
            Some(PanicCause::AssertFailed)
        );
    }

    #[test]
    fn test_assert_failed_always_assert_regardless_of_path() {
        assert_eq!(
            detect_panic_cause(
                "assert_failed",
                Some("/rustc/abc123/library/std/src/time.rs")
            ),
            Some(PanicCause::AssertFailed)
        );
        assert_eq!(
            detect_panic_cause("assert_failed", Some("/library/core/src/num/mod.rs")),
            Some(PanicCause::AssertFailed)
        );
        assert_eq!(
            detect_panic_cause("assert_failed", Some("src/main.rs")),
            Some(PanicCause::AssertFailed)
        );
    }

    #[test]
    fn test_assert_in_user_path_with_library() {
        assert_eq!(
            detect_panic_cause("assert_failed", Some("/home/me/library/app/src/main.rs")),
            Some(PanicCause::AssertFailed)
        );
        assert_eq!(
            detect_panic_cause("assert_failed", Some("/projects/library/core/lib.rs")),
            Some(PanicCause::AssertFailed)
        );
    }

    #[test]
    fn test_detect_panic_cause_panic_display() {
        assert_eq!(
            detect_panic_cause("panic_display", None),
            Some(PanicCause::ExplicitPanic)
        );
    }

    #[test]
    fn test_detect_panic_cause_panic_in_cleanup() {
        assert_eq!(
            detect_panic_cause("panic_in_cleanup", None),
            Some(PanicCause::PanicInDrop)
        );
    }

    #[test]
    fn test_detect_panic_cause_panic_cannot_unwind() {
        assert_eq!(
            detect_panic_cause("panic_cannot_unwind", None),
            Some(PanicCause::CannotUnwind)
        );
        assert_eq!(
            detect_panic_cause("panic_nounwind", None),
            Some(PanicCause::CannotUnwind)
        );
    }

    #[test]
    fn test_detect_panic_cause_formatting() {
        assert_eq!(
            detect_panic_cause("core::fmt::write", None),
            Some(PanicCause::FormattingError)
        );
        assert_eq!(
            detect_panic_cause("write_fmt", None),
            Some(PanicCause::FormattingError)
        );
    }

    #[test]
    fn test_detect_panic_cause_capacity_overflow() {
        assert_eq!(
            detect_panic_cause("capacity_overflow", None),
            Some(PanicCause::CapacityOverflow)
        );
    }

    #[test]
    fn test_detect_panic_cause_out_of_memory() {
        assert_eq!(
            detect_panic_cause("handle_alloc_error", None),
            Some(PanicCause::OutOfMemory)
        );
    }

    #[test]
    fn test_detect_panic_cause_string_slice_error() {
        assert_eq!(
            detect_panic_cause("slice_error_fail", None),
            Some(PanicCause::StringSliceError)
        );
        assert_eq!(
            detect_panic_cause("str_index_overflow_fail", None),
            Some(PanicCause::StringSliceError)
        );
    }

    #[test]
    fn test_detect_panic_cause_index_bounds() {
        assert_eq!(
            detect_panic_cause("index<T, usize>", None),
            Some(PanicCause::BoundsCheck)
        );
        assert_eq!(
            detect_panic_cause("Index::index", None),
            Some(PanicCause::BoundsCheck)
        );
    }

    #[test]
    fn test_detect_panic_cause_index_string() {
        assert_eq!(
            detect_panic_cause("index<Range>", Some("/library/core/src/str/mod.rs")),
            Some(PanicCause::StringSliceError)
        );
        assert_eq!(
            detect_panic_cause("str::index<Range>", None),
            Some(PanicCause::StringSliceError)
        );
    }

    #[test]
    fn test_detect_panic_cause_invalid_enum() {
        assert_eq!(
            detect_panic_cause("panic_invalid_enum_construction", None),
            Some(PanicCause::InvalidEnum)
        );
    }

    #[test]
    fn test_detect_panic_cause_misaligned_pointer() {
        assert_eq!(
            detect_panic_cause("panic_misaligned_pointer_dereference", None),
            Some(PanicCause::MisalignedPointer)
        );
    }

    #[test]
    fn test_detect_panic_cause_hashbrown_raw() {
        assert_eq!(
            detect_panic_cause("hashbrown::raw::TableLayout::calculate_layout_for", None),
            Some(PanicCause::CapacityOverflow)
        );
        assert_eq!(
            detect_panic_cause(
                "hashbrown::raw::RawTableInner::fallible_with_capacity",
                None
            ),
            Some(PanicCause::CapacityOverflow)
        );
        assert_eq!(
            detect_panic_cause("hashbrown::raw::RawTableInner::new_uninitialized", None),
            Some(PanicCause::CapacityOverflow)
        );
    }

    #[test]
    fn test_detect_panic_cause_std_collections_hash() {
        assert_eq!(
            detect_panic_cause(
                "std::collections::hash::map::HashMap<K,V>::new",
                Some("/rustc/abc/library/std/src/collections/hash/map.rs")
            ),
            Some(PanicCause::CapacityOverflow)
        );
        assert_eq!(
            detect_panic_cause(
                "std::collections::hash::set::HashSet<T>::with_capacity",
                Some("/rustc/abc/library/std/src/collections/hash/set.rs")
            ),
            Some(PanicCause::CapacityOverflow)
        );
    }

    #[test]
    fn test_detect_hashbrown_specific_causes_take_priority() {
        assert_eq!(
            detect_panic_cause("hashbrown::raw::Fallibility::capacity_overflow", None),
            Some(PanicCause::CapacityOverflow)
        );
        assert_eq!(
            detect_panic_cause("hashbrown::raw::Fallibility::alloc_err", None),
            Some(PanicCause::OutOfMemory)
        );
    }

    #[test]
    fn test_detect_panic_cause_unknown() {
        assert_eq!(detect_panic_cause("some_random_function", None), None);
    }

    #[test]
    fn test_detect_panic_cause_unreachable() {
        assert_eq!(
            detect_panic_cause("unreachable_panic_handler", None),
            Some(PanicCause::Unreachable)
        );
    }

    #[test]
    fn test_detect_panic_cause_raw_vec_grow() {
        assert_eq!(
            detect_panic_cause("raw_vec::grow", None),
            Some(PanicCause::CapacityOverflow)
        );
    }

    #[test]
    fn test_detect_panic_cause_display_fmt() {
        assert_eq!(
            detect_panic_cause("Display::fmt", None),
            Some(PanicCause::FormattingError)
        );
        assert_eq!(
            detect_panic_cause("Debug::fmt", None),
            Some(PanicCause::FormattingError)
        );
    }
}