depyler 4.1.1

A Python-to-Rust transpiler focusing on energy-efficient, safe code generation with progressive verification
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
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
//! DEPYLER-0380: Compile Command Implementation
//!
//! **EXTREME TDD - GREEN Phase**
//!
//! Single-shot Python-to-Rust compilation:
//! 1. Transpile Python → Rust
//! 2. Create Cargo project structure
//! 3. Build executable binary
//! 4. Return path to binary
//!
//! DEPYLER-1102: Oracle Loop Integration
//! - When E0308 errors occur, extract type constraints
//! - Re-transpile with learned constraints
//! - Automatically retry compilation
//!
//! Complexity: ≤10 per function
//! TDG Score: A (≤2.0)
//! Coverage: ≥85%

use crate::converge::type_constraint_learner::{parse_e0308_constraint, TypeConstraintStore};
use anyhow::{Context, Result};
use depyler_core::DepylerPipeline;
use indicatif::{ProgressBar, ProgressStyle};
use std::collections::HashMap;
use std::fs;
use std::path::{Path, PathBuf};
use std::process::Command;

/// Maximum number of Oracle Loop retry attempts
const MAX_ORACLE_RETRIES: usize = 2;

/// Compile a Python script to a standalone Rust binary
///
/// DEPYLER-1102: Now includes Oracle Loop for automatic E0308 recovery.
/// When compilation fails with type mismatch errors, the system learns
/// constraints from rustc output and retries transpilation.
///
/// # Arguments
/// * `input` - Path to Python file
/// * `output` - Optional output binary path (defaults to input name without extension)
/// * `profile` - Cargo profile (release, debug, etc.)
///
/// # Returns
/// Path to the compiled binary
///
/// Complexity: 9 (within ≤10 target)
pub fn compile_python_to_binary(
    input: &Path,
    output: Option<&Path>,
    profile: Option<&str>,
) -> Result<PathBuf> {
    // Validate input exists
    if !input.exists() {
        anyhow::bail!("Input file not found: {}", input.display());
    }

    // Set up progress bar
    let pb = ProgressBar::new(4);
    pb.set_style(
        ProgressStyle::default_bar()
            .template("[{elapsed_precise}] {bar:40.cyan/blue} {pos}/{len} {msg}")
            .expect("static progress template")
            .progress_chars("█▓▒░ "),
    );

    let python_code = fs::read_to_string(input)
        .with_context(|| format!("Failed to read input file: {}", input.display()))?;

    let cargo_profile = profile.unwrap_or("release");

    // DEPYLER-1102: Oracle Loop - retry compilation with learned constraints
    let mut constraint_store = TypeConstraintStore::new();
    let mut last_error: Option<String> = None;

    for attempt in 0..=MAX_ORACLE_RETRIES {
        // Step 1: Transpile Python → Rust
        pb.set_message(if attempt == 0 {
            "Transpiling Python to Rust...".to_string()
        } else {
            format!("Re-transpiling (attempt {})...", attempt + 1)
        });

        let pipeline = DepylerPipeline::new();

        // DEPYLER-1102: If we have constraints, apply them
        let (rust_code, dependencies) = if constraint_store.stats.constraints_extracted > 0 {
            // Convert constraint store to simple map for the current file
            let input_str = input.to_string_lossy().to_string();
            let constraints_map: HashMap<String, String> = constraint_store
                .variable_constraints
                .iter()
                .filter(|((file, _), _)| file == &input_str)
                .map(|((_, var), constraint)| (var.clone(), constraint.expected_type.clone()))
                .collect();

            pipeline
                .transpile_with_constraints_and_dependencies(&python_code, &constraints_map)
                .context("Failed to transpile with constraints")?
        } else {
            pipeline
                .transpile_with_dependencies(&python_code)
                .context("Failed to transpile Python to Rust")?
        };

        if attempt == 0 {
            pb.inc(1);
        }

        // Step 2: Create Cargo project
        pb.set_message("Creating Cargo project...");
        let (project_dir, is_binary) = create_cargo_project(input, &rust_code, &dependencies)?;

        if attempt == 0 {
            pb.inc(1);
        }

        // Step 3: Build project
        pb.set_message(if is_binary {
            "Building binary...".to_string()
        } else {
            "Building library...".to_string()
        });

        let build_result = build_cargo_project(&project_dir, cargo_profile)?;

        if build_result.success {
            if attempt == 0 {
                pb.inc(1);
            }

            // Step 4: Finalize
            pb.set_message("Finalizing...");
            let result_path = if is_binary {
                finalize_binary(&project_dir, input, output, cargo_profile)?
            } else {
                project_dir.clone()
            };
            pb.inc(1);

            let success_msg = if attempt > 0 {
                format!(
                    "✅ Compilation complete (after {} Oracle Loop retries)!",
                    attempt
                )
            } else if is_binary {
                "✅ Compilation complete!".to_string()
            } else {
                "✅ Library compilation complete!".to_string()
            };
            pb.finish_with_message(success_msg);

            // DEPYLER-1102: Log learned constraints for future improvement
            if constraint_store.stats.constraints_extracted > 0 {
                tracing::info!(
                    "DEPYLER-1102: Oracle Loop learned {} type constraints",
                    constraint_store.stats.constraints_extracted
                );
            }

            return Ok(result_path);
        }

        // Build failed - check if we can learn from E0308 errors
        let new_constraints = extract_e0308_constraints(&build_result.stderr, input);

        if new_constraints.stats.constraints_extracted > 0 && attempt < MAX_ORACLE_RETRIES {
            // We learned something! Log and retry
            tracing::info!(
                "DEPYLER-1102: Extracted {} E0308 constraints, retrying...",
                new_constraints.stats.constraints_extracted
            );

            // Merge constraints
            for (key, constraint) in new_constraints.variable_constraints {
                constraint_store
                    .variable_constraints
                    .insert(key, constraint);
            }
            constraint_store.stats.constraints_extracted +=
                new_constraints.stats.constraints_extracted;

            // Continue to next attempt
            continue;
        }

        // No more constraints to learn or max retries reached
        last_error = Some(build_result.stderr);
        break;
    }

    // All attempts failed
    pb.finish_with_message("❌ Compilation failed");
    anyhow::bail!(
        "Cargo build failed after {} attempts:\n{}",
        MAX_ORACLE_RETRIES + 1,
        last_error.unwrap_or_else(|| "Unknown error".to_string())
    )
}

/// Create a Cargo project with the transpiled Rust code
///
/// DEPYLER-0384: Now accepts dependencies for automatic Cargo.toml generation
/// DEPYLER-0763: Returns (project_dir, is_binary) - is_binary is true if code has main()
///
/// Complexity: 4 (within ≤10 target)
fn create_cargo_project(
    input: &Path,
    rust_code: &str,
    dependencies: &[depyler_core::cargo_toml_gen::Dependency],
) -> Result<(PathBuf, bool)> {
    let project_name = input
        .file_stem()
        .and_then(|s| s.to_str())
        .unwrap_or("output");

    let temp_dir = std::env::temp_dir();
    let project_dir = temp_dir.join(format!("depyler_{}", project_name));

    // Create project structure
    // DEPYLER-0763: Clean existing src directory to avoid stale files
    // (e.g., leftover main.rs when switching to lib.rs)
    let src_dir = project_dir.join("src");
    if src_dir.exists() {
        fs::remove_dir_all(&src_dir).ok(); // Ignore errors - might not exist
    }
    fs::create_dir_all(&src_dir).context("Failed to create src directory")?;

    // DEPYLER-0763: Check if code has fn main() to determine crate type
    // Libraries (no main) should be compiled as --crate-type lib to avoid E0601
    // CLIs with argparse/main functions should be compiled as binaries
    let has_main = rust_code.contains("fn main()") || rust_code.contains("pub fn main()");
    let (rs_filename, cargo_toml) = if has_main {
        // Binary: uses [[bin]] section
        let toml = depyler_core::cargo_toml_gen::generate_cargo_toml(
            project_name,
            "src/main.rs",
            dependencies,
        );
        ("src/main.rs", toml)
    } else {
        // Library: uses [lib] section - avoids E0601 "main function not found"
        // Must use generate_cargo_toml_lib directly (not _auto which only does lib for test_*)
        let toml = depyler_core::cargo_toml_gen::generate_cargo_toml_lib(
            project_name,
            "src/lib.rs",
            dependencies,
        );
        ("src/lib.rs", toml)
    };
    fs::write(project_dir.join("Cargo.toml"), cargo_toml).context("Failed to write Cargo.toml")?;

    // Write source file (main.rs or lib.rs based on crate type)
    fs::write(project_dir.join(rs_filename), rust_code)
        .with_context(|| format!("Failed to write {}", rs_filename))?;

    // DEPYLER-0763: Return whether this is a binary (has main) so caller knows what to finalize
    Ok((project_dir, has_main))
}

/// Build result containing success status and any errors
#[derive(Debug)]
pub struct BuildResult {
    /// Whether the build succeeded
    pub success: bool,
    /// Raw stderr output for error parsing
    pub stderr: String,
}

/// Build the Cargo project
///
/// DEPYLER-0380-FIX: Explicitly set target-dir to avoid inheriting parent project's
/// .cargo/config.toml target-dir setting which would cause builds to go to wrong location.
///
/// DEPYLER-1102: Returns BuildResult instead of bailing to allow Oracle Loop retry.
///
/// Complexity: 3 (within ≤10 target)
fn build_cargo_project(project_dir: &Path, profile: &str) -> Result<BuildResult> {
    let mut cmd = Command::new("cargo");
    cmd.arg("build")
        .arg("--manifest-path")
        .arg(project_dir.join("Cargo.toml"))
        // Explicitly set target directory to project's own target dir
        // This prevents inheriting the parent project's .cargo/config.toml target-dir
        .arg("--target-dir")
        .arg(project_dir.join("target"));

    if profile == "release" {
        cmd.arg("--release");
    }

    let output = cmd.output().context("Failed to run cargo build")?;
    let stderr = String::from_utf8_lossy(&output.stderr).to_string();

    Ok(BuildResult {
        success: output.status.success(),
        stderr,
    })
}

/// Parse E0308 errors from cargo build output and extract type constraints
///
/// DEPYLER-1102: Extracts "expected X, found Y" patterns for oracle learning.
///
/// Complexity: 5 (within ≤10 target)
fn extract_e0308_constraints(stderr: &str, source_file: &Path) -> TypeConstraintStore {
    let mut store = TypeConstraintStore::new();

    // Parse each line looking for E0308 errors
    for line in stderr.lines() {
        if line.contains("error[E0308]") {
            // Extract the error message part
            if let Some(msg_start) = line.find("]: ") {
                let message = &line[msg_start + 3..];
                if let Some(constraint) = parse_e0308_constraint(message, source_file, 0) {
                    store.add_constraint(constraint);
                }
            }
        }
    }

    // Also look for context lines with expected/found
    for line in stderr.lines() {
        if (line.contains("expected `") && line.contains("found `"))
            || line.contains("expected type")
        {
            if let Some(constraint) = parse_e0308_constraint(line, source_file, 0) {
                store.add_constraint(constraint);
            }
        }
    }

    store
}

/// Copy the built binary to the final location
///
/// Complexity: 4 (within ≤10 target)
fn finalize_binary(
    project_dir: &Path,
    input: &Path,
    output: Option<&Path>,
    profile: &str,
) -> Result<PathBuf> {
    let project_name = input
        .file_stem()
        .and_then(|s| s.to_str())
        .unwrap_or("output");

    // Determine binary location in target directory
    let profile_dir = if profile == "release" {
        "release"
    } else {
        "debug"
    };
    let binary_name = if cfg!(windows) {
        format!("{}.exe", project_name)
    } else {
        project_name.to_string()
    };
    let built_binary = project_dir
        .join("target")
        .join(profile_dir)
        .join(&binary_name);

    // Determine output location
    let output_path = if let Some(out) = output {
        out.to_path_buf()
    } else {
        input.with_file_name(&binary_name)
    };

    // Copy binary
    fs::copy(&built_binary, &output_path).with_context(|| {
        format!(
            "Failed to copy binary from {} to {}",
            built_binary.display(),
            output_path.display()
        )
    })?;

    // Make executable on Unix
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        let mut perms = fs::metadata(&output_path)?.permissions();
        perms.set_mode(0o755);
        fs::set_permissions(&output_path, perms)?;
    }

    Ok(output_path)
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;
    use tempfile::TempDir;

    #[test]
    fn test_create_cargo_project_binary() {
        let rust_code = r#"fn main() { println!("test"); }"#;
        let temp = TempDir::new().unwrap();
        let input = temp.path().join("test.py");
        fs::write(&input, "").unwrap();

        // DEPYLER-0384: Empty dependencies list for basic test
        let dependencies = vec![];
        // DEPYLER-0763: Now returns (project_dir, is_binary)
        let (project_dir, is_binary) =
            create_cargo_project(&input, rust_code, &dependencies).unwrap();

        assert!(
            is_binary,
            "Code with fn main() should be detected as binary"
        );
        assert!(project_dir.join("Cargo.toml").exists());
        assert!(project_dir.join("src/main.rs").exists());

        let main_content = fs::read_to_string(project_dir.join("src/main.rs")).unwrap();
        assert!(main_content.contains("test"));

        // DEPYLER-0384: Verify Cargo.toml has package section
        let cargo_content = fs::read_to_string(project_dir.join("Cargo.toml")).unwrap();
        assert!(cargo_content.contains("[package]"));
        assert!(cargo_content.contains("name = \"test\""));
    }

    #[test]
    fn test_create_cargo_project_pub_main() {
        // Test pub fn main() detection
        let rust_code = r#"pub fn main() { println!("public main"); }"#;
        let temp = TempDir::new().unwrap();
        let input = temp.path().join("pub_main.py");
        fs::write(&input, "").unwrap();

        let dependencies = vec![];
        let (_, is_binary) = create_cargo_project(&input, rust_code, &dependencies).unwrap();

        assert!(
            is_binary,
            "Code with pub fn main() should be detected as binary"
        );
    }

    #[test]
    fn test_create_cargo_project_library() {
        // DEPYLER-0763: Test library detection (no main function)
        let rust_code = r#"pub fn greet(name: &str) -> String { format!("Hello, {}!", name) }"#;
        let temp = TempDir::new().unwrap();
        let input = temp.path().join("mylib.py");
        fs::write(&input, "").unwrap();

        let dependencies = vec![];
        let (project_dir, is_binary) =
            create_cargo_project(&input, rust_code, &dependencies).unwrap();

        assert!(
            !is_binary,
            "Code without fn main() should be detected as library"
        );
        assert!(project_dir.join("Cargo.toml").exists());
        assert!(project_dir.join("src/lib.rs").exists());
        assert!(
            !project_dir.join("src/main.rs").exists(),
            "Library should not have main.rs"
        );

        // Verify Cargo.toml has [lib] section instead of [[bin]]
        let cargo_content = fs::read_to_string(project_dir.join("Cargo.toml")).unwrap();
        assert!(
            cargo_content.contains("[lib]"),
            "Library should have [lib] section"
        );
        assert!(
            !cargo_content.contains("[[bin]]"),
            "Library should not have [[bin]] section"
        );
    }

    #[test]
    fn test_create_cargo_project_with_dependencies() {
        use depyler_core::cargo_toml_gen::Dependency;

        let rust_code = r#"fn main() { println!("test"); }"#;
        let temp = TempDir::new().unwrap();
        let input = temp.path().join("test_deps.py");
        fs::write(&input, "").unwrap();

        let dependencies = vec![
            Dependency {
                crate_name: "serde".to_string(),
                version: "1.0".to_string(),
                features: vec!["derive".to_string()],
            },
            Dependency {
                crate_name: "regex".to_string(),
                version: "1.0".to_string(),
                features: vec![],
            },
        ];

        let (project_dir, _) = create_cargo_project(&input, rust_code, &dependencies).unwrap();

        let cargo_content = fs::read_to_string(project_dir.join("Cargo.toml")).unwrap();
        assert!(cargo_content.contains("serde"));
        assert!(cargo_content.contains("regex"));
    }

    #[test]
    fn test_create_cargo_project_cleanup_existing() {
        // Test that existing src directory is cleaned up
        let rust_code = r#"fn main() { println!("new"); }"#;
        let temp = TempDir::new().unwrap();
        let input = temp.path().join("cleanup_test.py");
        fs::write(&input, "").unwrap();

        let dependencies = vec![];

        // First call creates project with main.rs
        let (project_dir, _) = create_cargo_project(&input, rust_code, &dependencies).unwrap();
        assert!(project_dir.join("src/main.rs").exists());

        // Create a stale file that should be cleaned up
        fs::write(project_dir.join("src/stale.rs"), "stale content").unwrap();

        // Second call should clean up stale files
        let lib_code = r#"pub fn greet() -> &'static str { "hello" }"#;
        let (project_dir2, _) = create_cargo_project(&input, lib_code, &dependencies).unwrap();

        assert_eq!(project_dir, project_dir2);
        assert!(
            !project_dir.join("src/stale.rs").exists(),
            "Stale files should be cleaned"
        );
        assert!(
            !project_dir.join("src/main.rs").exists(),
            "main.rs should be removed for library"
        );
        assert!(
            project_dir.join("src/lib.rs").exists(),
            "lib.rs should exist"
        );
    }

    #[test]
    fn test_compile_nonexistent_file() {
        let result =
            compile_python_to_binary(Path::new("/nonexistent/file.py"), None, Some("release"));
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("not found"));
    }

    #[test]
    fn test_build_cargo_project_release() {
        // Create a simple valid Rust project
        let temp = TempDir::new().unwrap();
        let project_dir = temp.path().to_path_buf();
        let src_dir = project_dir.join("src");
        fs::create_dir_all(&src_dir).unwrap();

        // Write a simple main.rs
        fs::write(
            src_dir.join("main.rs"),
            r#"fn main() { println!("test"); }"#,
        )
        .unwrap();

        // Write Cargo.toml
        let cargo_toml = r#"
[package]
name = "test_build"
version = "0.1.0"
edition = "2021"
"#;
        fs::write(project_dir.join("Cargo.toml"), cargo_toml).unwrap();

        // Build should succeed
        let result = build_cargo_project(&project_dir, "release");
        assert!(result.is_ok());

        // Binary should exist
        assert!(project_dir.join("target/release/test_build").exists());
    }

    #[test]
    fn test_build_cargo_project_debug() {
        let temp = TempDir::new().unwrap();
        let project_dir = temp.path().to_path_buf();
        let src_dir = project_dir.join("src");
        fs::create_dir_all(&src_dir).unwrap();

        fs::write(src_dir.join("main.rs"), r#"fn main() { }"#).unwrap();

        let cargo_toml = r#"
[package]
name = "test_debug"
version = "0.1.0"
edition = "2021"
"#;
        fs::write(project_dir.join("Cargo.toml"), cargo_toml).unwrap();

        // Debug build
        let result = build_cargo_project(&project_dir, "debug");
        assert!(result.is_ok());

        // Debug binary should exist
        assert!(project_dir.join("target/debug/test_debug").exists());
    }

    #[test]
    fn test_build_cargo_project_invalid_code() {
        let temp = TempDir::new().unwrap();
        let project_dir = temp.path().to_path_buf();
        let src_dir = project_dir.join("src");
        fs::create_dir_all(&src_dir).unwrap();

        // Invalid Rust code
        fs::write(src_dir.join("main.rs"), "this is not valid rust").unwrap();

        let cargo_toml = r#"
[package]
name = "test_invalid"
version = "0.1.0"
edition = "2021"
"#;
        fs::write(project_dir.join("Cargo.toml"), cargo_toml).unwrap();

        // DEPYLER-1102: Now returns BuildResult instead of error
        let result = build_cargo_project(&project_dir, "release").unwrap();
        assert!(!result.success, "Invalid code should fail to compile");
        assert!(!result.stderr.is_empty(), "Should have error output");
    }

    // DEPYLER-1102: Tests for Oracle Loop E0308 constraint extraction

    #[test]
    fn test_extract_e0308_constraints_basic() {
        let source = Path::new("test.py");
        let stderr = r#"
error[E0308]: mismatched types
  --> src/main.rs:10:5
   |
10 |     x
   |     ^ expected `String`, found `i64`
"#;
        let store = extract_e0308_constraints(stderr, source);
        assert!(
            store.stats.constraints_extracted > 0,
            "Should extract E0308 constraint"
        );
    }

    #[test]
    fn test_extract_e0308_constraints_multiple() {
        let source = Path::new("test.py");
        let stderr = r#"
error[E0308]: mismatched types
   --> src/main.rs:10:5
    |
10  |     x
    |     ^ expected `String`, found `i64`

error[E0308]: mismatched types
   --> src/main.rs:20:5
    |
20  |     y
    |     ^ expected `f64`, found `bool`
"#;
        let store = extract_e0308_constraints(stderr, source);
        assert!(
            store.stats.constraints_extracted >= 2,
            "Should extract multiple E0308 constraints"
        );
    }

    #[test]
    fn test_extract_e0308_constraints_no_e0308() {
        let source = Path::new("test.py");
        let stderr = r#"
error[E0425]: cannot find value `foo` in this scope
  --> src/main.rs:5:5
   |
5  |     foo
   |     ^^^ not found in this scope
"#;
        let store = extract_e0308_constraints(stderr, source);
        assert_eq!(
            store.stats.constraints_extracted, 0,
            "Should not extract non-E0308 errors"
        );
    }

    #[test]
    fn test_build_result_success_true() {
        let temp = TempDir::new().unwrap();
        let project_dir = temp.path().to_path_buf();
        let src_dir = project_dir.join("src");
        fs::create_dir_all(&src_dir).unwrap();

        // Valid Rust code
        fs::write(src_dir.join("main.rs"), r#"fn main() {}"#).unwrap();

        let cargo_toml = r#"
[package]
name = "test_valid"
version = "0.1.0"
edition = "2021"
"#;
        fs::write(project_dir.join("Cargo.toml"), cargo_toml).unwrap();

        let result = build_cargo_project(&project_dir, "release").unwrap();
        assert!(result.success, "Valid code should compile successfully");
    }

    #[test]
    fn test_finalize_binary_default_output() {
        let temp = TempDir::new().unwrap();
        let project_dir = temp.path().join("project");
        let target_release = project_dir.join("target/release");
        fs::create_dir_all(&target_release).unwrap();

        // Create fake binary
        fs::write(target_release.join("test_final"), "binary content").unwrap();

        let input = temp.path().join("test_final.py");
        fs::write(&input, "").unwrap();

        let result = finalize_binary(&project_dir, &input, None, "release");
        assert!(result.is_ok());

        let output_path = result.unwrap();
        assert!(output_path.exists());
        assert!(output_path.to_string_lossy().contains("test_final"));
    }

    #[test]
    fn test_finalize_binary_custom_output() {
        let temp = TempDir::new().unwrap();
        let project_dir = temp.path().join("project");
        let target_release = project_dir.join("target/release");
        fs::create_dir_all(&target_release).unwrap();

        // Create fake binary
        fs::write(target_release.join("custom_name"), "binary content").unwrap();

        let input = temp.path().join("custom_name.py");
        fs::write(&input, "").unwrap();

        let custom_output = temp.path().join("my_custom_binary");
        let result = finalize_binary(&project_dir, &input, Some(&custom_output), "release");
        assert!(result.is_ok());

        let output_path = result.unwrap();
        assert_eq!(output_path, custom_output);
        assert!(output_path.exists());
    }

    #[test]
    fn test_finalize_binary_debug_profile() {
        let temp = TempDir::new().unwrap();
        let project_dir = temp.path().join("project");
        let target_debug = project_dir.join("target/debug");
        fs::create_dir_all(&target_debug).unwrap();

        // Create fake binary in debug folder
        fs::write(target_debug.join("debug_test"), "binary content").unwrap();

        let input = temp.path().join("debug_test.py");
        fs::write(&input, "").unwrap();

        let result = finalize_binary(&project_dir, &input, None, "debug");
        assert!(result.is_ok());
    }

    // ========================================================================
    // Session 11 - Deep Coverage Tests
    // ========================================================================

    #[cfg(unix)]
    #[test]
    fn test_finalize_binary_unix_permissions() {
        use std::os::unix::fs::PermissionsExt;

        let temp = TempDir::new().unwrap();
        let project_dir = temp.path().join("project");
        let target_release = project_dir.join("target/release");
        fs::create_dir_all(&target_release).unwrap();

        fs::write(target_release.join("perm_test"), "binary content").unwrap();

        let input = temp.path().join("perm_test.py");
        fs::write(&input, "").unwrap();

        let output_path = finalize_binary(&project_dir, &input, None, "release").unwrap();
        let perms = fs::metadata(&output_path).unwrap().permissions();
        assert_eq!(perms.mode() & 0o777, 0o755);
    }

    #[test]
    fn test_extract_e0308_constraints_empty_stderr() {
        let source = Path::new("test.py");
        let store = extract_e0308_constraints("", source);
        assert_eq!(store.stats.constraints_extracted, 0);
    }

    #[test]
    fn test_extract_e0308_constraints_only_warnings() {
        let source = Path::new("test.py");
        let stderr = "warning: unused variable `x`\nwarning: dead code\n";
        let store = extract_e0308_constraints(stderr, source);
        assert_eq!(store.stats.constraints_extracted, 0);
    }

    #[test]
    fn test_build_result_fields() {
        let temp = TempDir::new().unwrap();
        let project_dir = temp.path().to_path_buf();
        let src_dir = project_dir.join("src");
        fs::create_dir_all(&src_dir).unwrap();

        // Invalid code for stderr capture
        fs::write(src_dir.join("main.rs"), "fn main() { let x: i32 = \"oops\"; }").unwrap();
        let cargo_toml = "[package]\nname = \"test_fields\"\nversion = \"0.1.0\"\nedition = \"2021\"\n";
        fs::write(project_dir.join("Cargo.toml"), cargo_toml).unwrap();

        let result = build_cargo_project(&project_dir, "release").unwrap();
        assert!(!result.success);
        // stderr should contain error info
        assert!(!result.stderr.is_empty());
    }

    #[test]
    fn test_create_cargo_project_sanitizes_name() {
        let rust_code = r#"pub fn greet() -> &'static str { "hello" }"#;
        let temp = TempDir::new().unwrap();
        // File name with hyphens should be converted to underscores
        let input = temp.path().join("my-cool-lib.py");
        fs::write(&input, "").unwrap();

        let dependencies = vec![];
        let (project_dir, _) = create_cargo_project(&input, rust_code, &dependencies).unwrap();

        let cargo_content = fs::read_to_string(project_dir.join("Cargo.toml")).unwrap();
        // Cargo name should use underscores
        assert!(cargo_content.contains("my_cool_lib") || cargo_content.contains("my-cool-lib"));
    }

    #[test]
    fn test_compile_nonexistent_error_message() {
        let result = compile_python_to_binary(
            Path::new("/absolutely/nonexistent/file.py"),
            None,
            Some("release"),
        );
        assert!(result.is_err());
        let err_msg = result.unwrap_err().to_string();
        assert!(err_msg.contains("not found"));
        assert!(err_msg.contains("nonexistent"));
    }

    #[test]
    fn test_compile_with_none_profile_defaults_release() {
        // Verify that None profile doesn't cause errors
        let result = compile_python_to_binary(
            Path::new("/nonexistent/file.py"),
            None,
            None, // should default to "release"
        );
        // Fails because file doesn't exist, but profile handling works
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("not found"));
    }
}