decy-verify 2.2.0

Safety property verification for transpiled Rust code
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
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
//! Safety property verification for transpiled Rust code.
//!
//! Verifies memory safety, type safety, and other Rust safety guarantees.
//!
//! # Unsafe Code Auditing
//!
//! This module provides comprehensive auditing of unsafe blocks in generated Rust code:
//! - Detection and counting of all unsafe blocks
//! - Confidence scoring for elimination potential
//! - Suggestions for safer alternatives
//! - Unsafe density metrics (<5 per 1000 LOC target)
//!
//! # Example
//!
//! ```no_run
//! use decy_verify::{UnsafeAuditor, audit_rust_code};
//!
//! let rust_code = r#"
//!     fn example() {
//!         unsafe {
//!             let ptr = std::ptr::null_mut();
//!         }
//!     }
//! "#;
//!
//! let report = audit_rust_code(rust_code).expect("Failed to audit");
//! println!("Unsafe blocks found: {}", report.unsafe_blocks.len());
//! println!("Unsafe density: {:.2}%", report.unsafe_density_percent);
//! ```

#![warn(missing_docs)]
#![warn(clippy::all)]
#![deny(unsafe_code)]

pub mod diff_test;
pub mod lock_verify;

use anyhow::{Context, Result};
use syn::{visit::Visit, Block, Expr, ExprUnsafe, ItemFn};

/// Represents a single unsafe block found in Rust code
#[derive(Debug, Clone, PartialEq)]
pub struct UnsafeBlock {
    /// Line number where the unsafe block starts
    pub line: usize,
    /// Confidence score (0-100) that this block could be eliminated
    pub confidence: u8,
    /// Pattern detected (e.g., "raw_pointer_deref", "transmute", etc.)
    pub pattern: UnsafePattern,
    /// Suggestion for safer alternative
    pub suggestion: String,
}

/// Categories of unsafe patterns
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum UnsafePattern {
    /// Raw pointer dereference (*ptr)
    RawPointerDeref,
    /// Type transmutation
    Transmute,
    /// Inline assembly
    Assembly,
    /// FFI call
    FfiCall,
    /// Union field access
    UnionAccess,
    /// Mutable static access
    MutableStatic,
    /// Other unsafe operation
    Other,
}

/// Report summarizing unsafe code in a Rust file
#[derive(Debug, Clone)]
pub struct UnsafeAuditReport {
    /// Total lines of code
    pub total_lines: usize,
    /// Lines inside unsafe blocks
    pub unsafe_lines: usize,
    /// Unsafe density as percentage
    pub unsafe_density_percent: f64,
    /// List of all unsafe blocks found
    pub unsafe_blocks: Vec<UnsafeBlock>,
    /// Average confidence score across all blocks
    pub average_confidence: f64,
}

impl UnsafeAuditReport {
    /// Create a new audit report
    pub fn new(total_lines: usize, unsafe_lines: usize, unsafe_blocks: Vec<UnsafeBlock>) -> Self {
        let unsafe_density_percent =
            if total_lines > 0 { (unsafe_lines as f64 / total_lines as f64) * 100.0 } else { 0.0 };

        let average_confidence = if !unsafe_blocks.is_empty() {
            unsafe_blocks.iter().map(|b| b.confidence as f64).sum::<f64>()
                / unsafe_blocks.len() as f64
        } else {
            0.0
        };

        Self {
            total_lines,
            unsafe_lines,
            unsafe_density_percent,
            unsafe_blocks,
            average_confidence,
        }
    }

    /// Check if unsafe density meets the <5% target
    pub fn meets_density_target(&self) -> bool {
        self.unsafe_density_percent < 5.0
    }

    /// Get blocks with high confidence for elimination (≥70)
    pub fn high_confidence_blocks(&self) -> Vec<&UnsafeBlock> {
        self.unsafe_blocks.iter().filter(|b| b.confidence >= 70).collect()
    }
}

/// Main auditor for analyzing unsafe code
pub struct UnsafeAuditor {
    unsafe_blocks: Vec<UnsafeBlock>,
    total_lines: usize,
    unsafe_lines: usize,
    source_code: String,
}

impl UnsafeAuditor {
    /// Create a new auditor
    pub fn new() -> Self {
        Self {
            unsafe_blocks: Vec::new(),
            total_lines: 0,
            unsafe_lines: 0,
            source_code: String::new(),
        }
    }

    /// Analyze Rust source code and generate an audit report
    pub fn audit(&mut self, rust_code: &str) -> Result<UnsafeAuditReport> {
        // Store source code for line counting
        self.source_code = rust_code.to_string();

        // Count total lines
        self.total_lines = rust_code.lines().count();

        // Parse the Rust code
        let syntax_tree = syn::parse_file(rust_code).context("Failed to parse Rust code")?;

        // Visit the AST to find unsafe blocks
        self.visit_file(&syntax_tree);

        Ok(UnsafeAuditReport::new(self.total_lines, self.unsafe_lines, self.unsafe_blocks.clone()))
    }

    /// Detect the pattern type and assign confidence score
    fn analyze_unsafe_block(&self, unsafe_block: &ExprUnsafe) -> (UnsafePattern, u8, String) {
        // Convert block to string for pattern matching
        let block_str = quote::quote!(#unsafe_block).to_string();

        // Detect patterns and assign confidence scores
        let (pattern, confidence, suggestion) = if block_str.contains("std :: ptr ::")
            || block_str.contains("* ptr")
            || block_str.contains("null_mut")
            || block_str.contains("null()")
        {
            (
                UnsafePattern::RawPointerDeref,
                85,
                "Consider using Box<T>, &T, or &mut T with proper lifetimes".to_string(),
            )
        } else if block_str.contains("transmute") {
            (
                UnsafePattern::Transmute,
                40,
                "Consider safe alternatives like From/Into traits or checked conversions"
                    .to_string(),
            )
        } else if block_str.contains("asm!") || block_str.contains("global_asm!") {
            (
                UnsafePattern::Assembly,
                15,
                "No safe alternative - inline assembly required for platform-specific operations"
                    .to_string(),
            )
        } else if block_str.contains("extern") {
            (
                UnsafePattern::FfiCall,
                30,
                "Consider creating a safe wrapper around FFI calls".to_string(),
            )
        } else {
            (
                UnsafePattern::Other,
                50,
                "Review if this unsafe block can be eliminated or replaced with safe alternatives"
                    .to_string(),
            )
        };

        (pattern, confidence, suggestion)
    }

    /// Count lines in an unsafe block
    fn count_block_lines(&self, block: &Block) -> usize {
        // Rough approximation: count statements and add braces
        block.stmts.len() + 2
    }
}

impl Default for UnsafeAuditor {
    fn default() -> Self {
        Self::new()
    }
}

impl<'ast> Visit<'ast> for UnsafeAuditor {
    /// Visit expressions to find unsafe blocks
    fn visit_expr(&mut self, expr: &'ast Expr) {
        if let Expr::Unsafe(unsafe_expr) = expr {
            // Found an unsafe block!
            let (pattern, confidence, suggestion) = self.analyze_unsafe_block(unsafe_expr);

            // Count lines in this unsafe block
            let block_lines = self.count_block_lines(&unsafe_expr.block);
            self.unsafe_lines += block_lines;

            // Get line number (approximation using span start)
            let line = 0; // syn doesn't provide easy line number access without proc_macro2 spans

            self.unsafe_blocks.push(UnsafeBlock { line, confidence, pattern, suggestion });
        }

        // Continue visiting nested expressions
        syn::visit::visit_expr(self, expr);
    }

    /// Visit items to find unsafe functions
    fn visit_item_fn(&mut self, func: &'ast ItemFn) {
        // Check if function is marked unsafe
        if func.sig.unsafety.is_some() {
            // Unsafe function - count the entire body as unsafe
            let body_lines = self.count_block_lines(&func.block);
            self.unsafe_lines += body_lines;

            self.unsafe_blocks.push(UnsafeBlock {
                line: 0,
                confidence: 60,
                pattern: UnsafePattern::Other,
                suggestion: "Unsafe function - review if entire function needs to be unsafe or just specific blocks".to_string(),
            });
        }

        // Continue visiting the function body
        syn::visit::visit_item_fn(self, func);
    }
}

/// Convenience function to audit Rust code
///
/// # Example
///
/// ```
/// use decy_verify::audit_rust_code;
///
/// let code = "fn safe_function() { let x = 42; }";
/// let report = audit_rust_code(code).expect("Audit failed");
/// assert_eq!(report.unsafe_blocks.len(), 0);
/// ```
pub fn audit_rust_code(rust_code: &str) -> Result<UnsafeAuditReport> {
    let mut auditor = UnsafeAuditor::new();
    auditor.audit(rust_code)
}

/// A structured compilation error from rustc
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CompilationError {
    /// Error code (e.g., "E0308")
    pub code: Option<String>,
    /// Error message
    pub message: String,
}

/// Result of compiling generated Rust code
#[derive(Debug, Clone)]
pub struct CompilationResult {
    /// Whether compilation succeeded
    pub success: bool,
    /// Errors found during compilation
    pub errors: Vec<CompilationError>,
    /// Warnings found during compilation
    pub warnings: Vec<String>,
}

/// Verify that generated Rust code compiles by invoking rustc.
///
/// Uses `rustc --emit=metadata --edition=2021` for fast type-checking
/// without full code generation.
///
/// # Example
///
/// ```no_run
/// use decy_verify::verify_compilation;
///
/// let result = verify_compilation("fn main() {}").expect("rustc failed to run");
/// assert!(result.success);
/// ```
pub fn verify_compilation(rust_code: &str) -> Result<CompilationResult> {
    use std::process::Command;
    use std::time::{SystemTime, UNIX_EPOCH};

    let unique_id = SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_nanos()).unwrap_or(0);
    let temp_dir = std::env::temp_dir();
    let temp_file = temp_dir.join(format!("decy_verify_{}.rs", unique_id));
    let temp_output = temp_dir.join(format!("decy_verify_{}.rmeta", unique_id));

    std::fs::write(&temp_file, rust_code)
        .context("Failed to write temp file for compilation check")?;

    let output = Command::new("rustc")
        .arg("--emit=metadata")
        .arg("--edition=2021")
        .arg("-o")
        .arg(&temp_output)
        .arg(&temp_file)
        .output()
        .context("Failed to run rustc — is it installed?")?;

    // Remove scratch files
    let _ = std::fs::remove_file(&temp_file);
    let _ = std::fs::remove_file(&temp_output);

    let stderr = String::from_utf8_lossy(&output.stderr);

    if output.status.success() {
        let warnings: Vec<String> =
            stderr.lines().filter(|l| l.contains("warning")).map(|l| l.to_string()).collect();
        Ok(CompilationResult { success: true, errors: vec![], warnings })
    } else {
        let mut errors = Vec::new();
        for line in stderr.lines() {
            if line.starts_with("error") {
                // Extract error code like E0308 from "error[E0308]: ..."
                let code = line
                    .find('[')
                    .and_then(|start| line.find(']').map(|end| (start, end)))
                    .map(|(start, end)| line[start + 1..end].to_string());
                errors.push(CompilationError { code, message: line.to_string() });
            }
        }
        Ok(CompilationResult { success: false, errors, warnings: vec![] })
    }
}

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

    // RED PHASE: These tests will FAIL
    // Testing unsafe block detection

    #[test]
    fn test_no_unsafe_blocks() {
        // RED: This should pass (no unsafe blocks)
        let code = r#"
            fn safe_function() {
                let x = 42;
                println!("{}", x);
            }
        "#;

        let report = audit_rust_code(code).expect("Audit failed");
        assert_eq!(report.unsafe_blocks.len(), 0);
        assert_eq!(report.unsafe_lines, 0);
        assert!(report.meets_density_target());
    }

    #[test]
    fn test_single_unsafe_block() {
        // RED: This will FAIL - we don't detect unsafe blocks yet
        let code = r#"
            fn with_unsafe() {
                unsafe {
                    let ptr = std::ptr::null_mut::<i32>();
                    *ptr = 42;
                }
            }
        "#;

        let report = audit_rust_code(code).expect("Audit failed");
        assert_eq!(report.unsafe_blocks.len(), 1, "Should detect one unsafe block");
        assert!(report.unsafe_lines > 0, "Should count unsafe lines");
    }

    #[test]
    fn test_multiple_unsafe_blocks() {
        // RED: This will FAIL
        let code = r#"
            fn multiple_unsafe() {
                unsafe {
                    let ptr1 = std::ptr::null_mut::<i32>();
                }

                let safe_code = 42;

                unsafe {
                    let ptr2 = std::ptr::null_mut::<f64>();
                }
            }
        "#;

        let report = audit_rust_code(code).expect("Audit failed");
        assert_eq!(report.unsafe_blocks.len(), 2, "Should detect two unsafe blocks");
    }

    #[test]
    fn test_unsafe_density_calculation() {
        // RED: This will FAIL
        let code = r#"
fn example() {
    let x = 1;
    let y = 2;
    unsafe {
        let ptr = std::ptr::null_mut::<i32>();
    }
    let z = 3;
}
"#;
        let report = audit_rust_code(code).expect("Audit failed");

        // Total lines: 9, unsafe lines: 3 (lines 5-7)
        // Density should be around 33%
        assert!(report.unsafe_density_percent > 20.0);
        assert!(report.unsafe_density_percent < 50.0);
    }

    #[test]
    fn test_nested_unsafe_blocks() {
        // RED: This will FAIL
        let code = r#"
            fn nested() {
                unsafe {
                    let ptr = std::ptr::null_mut::<i32>();
                    unsafe {
                        *ptr = 42;
                    }
                }
            }
        "#;

        let report = audit_rust_code(code).expect("Audit failed");
        // Should detect nested blocks (implementation choice: count as 2 or 1)
        assert!(!report.unsafe_blocks.is_empty(), "Should detect unsafe blocks");
    }

    #[test]
    fn test_unsafe_in_different_items() {
        // RED: This will FAIL
        let code = r#"
            fn func1() {
                unsafe { let x = 1; }
            }

            fn func2() {
                unsafe { let y = 2; }
            }

            impl MyStruct {
                fn method(&self) {
                    unsafe { let z = 3; }
                }
            }

            struct MyStruct;
        "#;

        let report = audit_rust_code(code).expect("Audit failed");
        assert_eq!(report.unsafe_blocks.len(), 3, "Should detect unsafe in all items");
    }

    #[test]
    fn test_confidence_scoring() {
        // RED: This will FAIL - confidence scoring not implemented
        let code = r#"
            fn with_pointer() {
                unsafe {
                    let ptr = std::ptr::null_mut::<i32>();
                    *ptr = 42;
                }
            }
        "#;

        let report = audit_rust_code(code).expect("Audit failed");
        assert_eq!(report.unsafe_blocks.len(), 1);

        let block = &report.unsafe_blocks[0];
        assert!(block.confidence > 0, "Should have non-zero confidence");
        assert!(block.confidence <= 100, "Confidence should be 0-100");
    }

    #[test]
    fn test_pattern_detection_raw_pointer() {
        // RED: This will FAIL - pattern detection not implemented
        let code = r#"
            fn deref_pointer() {
                unsafe {
                    let ptr = std::ptr::null_mut::<i32>();
                    *ptr = 42;
                }
            }
        "#;

        let report = audit_rust_code(code).expect("Audit failed");
        assert_eq!(report.unsafe_blocks.len(), 1);
        assert_eq!(report.unsafe_blocks[0].pattern, UnsafePattern::RawPointerDeref);
    }

    #[test]
    fn test_suggestion_generation() {
        // RED: This will FAIL - suggestions not implemented
        let code = r#"
            fn with_unsafe() {
                unsafe {
                    let ptr = std::ptr::null_mut::<i32>();
                }
            }
        "#;

        let report = audit_rust_code(code).expect("Audit failed");
        assert_eq!(report.unsafe_blocks.len(), 1);
        assert!(!report.unsafe_blocks[0].suggestion.is_empty(), "Should provide a suggestion");
    }

    #[test]
    fn test_high_confidence_blocks() {
        // RED: This will FAIL
        let code = r#"
            fn example() {
                unsafe { let x = 1; }
                unsafe { let y = 2; }
            }
        "#;

        let report = audit_rust_code(code).expect("Audit failed");
        // Assuming we'll score some blocks as high confidence
        // This tests the filtering logic
        let high_conf = report.high_confidence_blocks();
        assert!(high_conf.len() <= report.unsafe_blocks.len());
    }

    #[test]
    fn test_average_confidence() {
        // RED: This will FAIL
        let code = r#"
            fn example() {
                unsafe { let x = 1; }
            }
        "#;

        let report = audit_rust_code(code).expect("Audit failed");
        assert!(report.average_confidence >= 0.0);
        assert!(report.average_confidence <= 100.0);
    }

    #[test]
    fn test_empty_code() {
        // This should pass (edge case)
        let code = "";
        let report = audit_rust_code(code).expect("Audit failed");
        assert_eq!(report.unsafe_blocks.len(), 0);
        assert_eq!(report.total_lines, 0);
    }

    #[test]
    fn test_invalid_rust_code() {
        // Should return error, not panic
        let code = "fn incomplete(";
        let result = audit_rust_code(code);
        assert!(result.is_err(), "Should return error for invalid code");
    }

    #[test]
    fn test_unsafe_fn() {
        // RED: This will FAIL - unsafe fn detection
        let code = r#"
            unsafe fn dangerous_function() {
                let x = 42;
            }
        "#;

        let report = audit_rust_code(code).expect("Audit failed");
        // Should detect unsafe function (entire function body is unsafe context)
        assert!(!report.unsafe_blocks.is_empty() || report.unsafe_lines > 0);
    }

    #[test]
    fn test_verify_compilation_valid_code() {
        let result = verify_compilation("fn main() {}").expect("rustc failed to run");
        assert!(result.success, "Valid Rust should compile");
        assert!(result.errors.is_empty());
    }

    #[test]
    fn test_verify_compilation_type_error() {
        let result =
            verify_compilation("fn main() { let x: i32 = \"bad\"; }").expect("rustc failed to run");
        assert!(!result.success, "Type error should fail compilation");
        assert!(!result.errors.is_empty(), "Should have at least one error");
        // E0308 is the mismatched types error
        let has_e0308 = result.errors.iter().any(|e| e.code.as_deref() == Some("E0308"));
        assert!(has_e0308, "Should contain E0308 error code");
    }

    #[test]
    fn test_verify_compilation_missing_function() {
        let result =
            verify_compilation("fn main() { undefined_function(); }").expect("rustc failed to run");
        assert!(!result.success);
        assert!(!result.errors.is_empty());
    }

    // ========================================================================
    // Pattern detection: transmute, assembly, FFI, Other
    // ========================================================================

    #[test]
    fn test_pattern_detection_transmute() {
        let code = r#"
            fn with_transmute() {
                unsafe {
                    let x: u32 = std::mem::transmute(1.0f32);
                }
            }
        "#;
        let report = audit_rust_code(code).expect("Audit failed");
        assert_eq!(report.unsafe_blocks.len(), 1);
        assert_eq!(report.unsafe_blocks[0].pattern, UnsafePattern::Transmute);
        assert_eq!(report.unsafe_blocks[0].confidence, 40);
        assert!(report.unsafe_blocks[0].suggestion.contains("From/Into"));
    }

    #[test]
    fn test_pattern_detection_assembly() {
        // The auditor uses quote! to stringify the unsafe block, then searches for "asm!"
        // core::arch::asm! macro invocation appears in the stringified form
        let code = r#"
            fn with_asm() {
                unsafe {
                    std::arch::asm!("nop");
                }
            }
        "#;
        let report = audit_rust_code(code).expect("Audit failed");
        assert_eq!(report.unsafe_blocks.len(), 1);
        // The stringified block contains "asm!" so it should match Assembly
        // If the macro doesn't appear in stringified form, it may fall through to Other
        let pattern = &report.unsafe_blocks[0].pattern;
        assert!(
            *pattern == UnsafePattern::Assembly || *pattern == UnsafePattern::Other,
            "Expected Assembly or Other, got {:?}",
            pattern
        );
    }

    #[test]
    fn test_pattern_detection_ffi() {
        let code = r#"
            fn with_ffi() {
                unsafe {
                    extern "C" {
                        fn puts(s: *const u8) -> i32;
                    }
                }
            }
        "#;
        let report = audit_rust_code(code).expect("Audit failed");
        assert_eq!(report.unsafe_blocks.len(), 1);
        assert_eq!(report.unsafe_blocks[0].pattern, UnsafePattern::FfiCall);
        assert_eq!(report.unsafe_blocks[0].confidence, 30);
        assert!(report.unsafe_blocks[0].suggestion.contains("safe wrapper"));
    }

    #[test]
    fn test_pattern_detection_other() {
        let code = r#"
            fn with_other_unsafe() {
                unsafe {
                    let v: Vec<i32> = Vec::new();
                    let _ = v.len();
                }
            }
        "#;
        let report = audit_rust_code(code).expect("Audit failed");
        assert_eq!(report.unsafe_blocks.len(), 1);
        assert_eq!(report.unsafe_blocks[0].pattern, UnsafePattern::Other);
        assert_eq!(report.unsafe_blocks[0].confidence, 50);
        assert!(report.unsafe_blocks[0].suggestion.contains("Review"));
    }

    // ========================================================================
    // meets_density_target + high_confidence_blocks
    // ========================================================================

    #[test]
    fn test_meets_density_target_low_density() {
        let report = UnsafeAuditReport::new(100, 3, vec![]);
        assert!(report.meets_density_target());
        assert!(report.unsafe_density_percent < 5.0);
    }

    #[test]
    fn test_meets_density_target_high_density() {
        let report = UnsafeAuditReport::new(100, 10, vec![]);
        assert!(!report.meets_density_target());
        assert!(report.unsafe_density_percent >= 5.0);
    }

    #[test]
    fn test_meets_density_target_zero_lines() {
        let report = UnsafeAuditReport::new(0, 0, vec![]);
        assert!(report.meets_density_target());
        assert!((report.unsafe_density_percent - 0.0).abs() < 0.001);
    }

    #[test]
    fn test_high_confidence_blocks_filtering() {
        let blocks = vec![
            UnsafeBlock {
                line: 1,
                confidence: 85,
                pattern: UnsafePattern::RawPointerDeref,
                suggestion: "Use Box".to_string(),
            },
            UnsafeBlock {
                line: 10,
                confidence: 40,
                pattern: UnsafePattern::Transmute,
                suggestion: "Use From".to_string(),
            },
            UnsafeBlock {
                line: 20,
                confidence: 70,
                pattern: UnsafePattern::Other,
                suggestion: "Review".to_string(),
            },
        ];
        let report = UnsafeAuditReport::new(100, 10, blocks);
        let high = report.high_confidence_blocks();
        assert_eq!(high.len(), 2); // confidence 85 and 70
        assert!(high.iter().all(|b| b.confidence >= 70));
    }

    #[test]
    fn test_high_confidence_blocks_empty() {
        let report = UnsafeAuditReport::new(100, 0, vec![]);
        assert!(report.high_confidence_blocks().is_empty());
    }

    // ========================================================================
    // UnsafeAuditor default + unsafe fn detection
    // ========================================================================

    #[test]
    fn test_unsafe_auditor_default() {
        let auditor = UnsafeAuditor::default();
        assert_eq!(auditor.total_lines, 0);
        assert_eq!(auditor.unsafe_lines, 0);
        assert!(auditor.unsafe_blocks.is_empty());
    }

    #[test]
    fn test_unsafe_fn_detection_body_lines() {
        let code = r#"
            unsafe fn dangerous() {
                let x = 1;
                let y = 2;
                let z = 3;
            }
        "#;
        let report = audit_rust_code(code).expect("Audit failed");
        assert!(!report.unsafe_blocks.is_empty());
        let block = &report.unsafe_blocks[0];
        assert_eq!(block.confidence, 60);
        assert_eq!(block.pattern, UnsafePattern::Other);
        assert!(block.suggestion.contains("Unsafe function"));
    }

    // ========================================================================
    // verify_compilation: warnings path + edge cases
    // ========================================================================

    #[test]
    fn test_verify_compilation_with_warnings() {
        let code = "#[warn(unused_variables)] fn main() { let x = 42; }";
        let result = verify_compilation(code).expect("rustc failed to run");
        assert!(result.success);
        // May or may not have warnings depending on rustc config
    }

    #[test]
    fn test_verify_compilation_multiple_errors() {
        let code = "fn main() { undefined_a(); undefined_b(); }";
        let result = verify_compilation(code).expect("rustc failed to run");
        assert!(!result.success);
        assert!(!result.errors.is_empty());
    }

    #[test]
    fn test_compilation_error_without_code() {
        // Error lines without [EXXXX] format
        let code = "this is not valid rust at all";
        let result = verify_compilation(code).expect("rustc failed to run");
        assert!(!result.success);
        // Should have errors, some may lack error codes
        assert!(!result.errors.is_empty());
    }

    #[test]
    fn test_average_confidence_calculation() {
        let blocks = vec![
            UnsafeBlock {
                line: 0,
                confidence: 80,
                pattern: UnsafePattern::RawPointerDeref,
                suggestion: "s".to_string(),
            },
            UnsafeBlock {
                line: 0,
                confidence: 40,
                pattern: UnsafePattern::Transmute,
                suggestion: "s".to_string(),
            },
        ];
        let report = UnsafeAuditReport::new(100, 10, blocks);
        assert!((report.average_confidence - 60.0).abs() < 0.001);
    }

    #[test]
    fn test_average_confidence_no_blocks() {
        let report = UnsafeAuditReport::new(100, 0, vec![]);
        assert!((report.average_confidence - 0.0).abs() < 0.001);
    }
}

#[cfg(test)]
#[path = "lock_verify_tests.rs"]
mod lock_verify_tests;