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
//! Corpus Analysis Report Command
//!
//! Minimal report implementation focused on testable pure functions.
//! GH-209: Extended with ML clustering and semantic domain analysis.

pub mod advanced_report; // GH-209 Phase 5: Advanced Report Output
pub mod analysis;
pub mod clustering; // GH-209 Phase 2: ML Clustering
pub mod filter;
pub mod graph_analysis; // GH-209 Phase 4: Graph Analysis

use anyhow::Result;
use colored::Colorize;
use std::collections::HashMap;
use std::path::PathBuf;

/// Report command arguments
pub struct ReportArgs {
    pub corpus: Option<PathBuf>,
    pub format: String,
    pub output: Option<PathBuf>,
    pub skip_clean: bool,
    pub target_rate: f64,
    pub filter: Option<String>,
    pub tag: Option<String>,
    pub limit: Option<usize>,
    pub sample: Option<usize>,
    pub bisect: bool,
    pub fail_fast: bool,
}

/// Compilation result for a single file
#[derive(Debug, Clone)]
pub struct CompileResult {
    pub name: String,
    pub success: bool,
    pub error_code: Option<String>,
    pub error_message: Option<String>,
}

/// Error taxonomy entry
#[derive(Debug, Default, Clone)]
pub struct ErrorTaxonomy {
    pub count: usize,
    pub samples: Vec<String>,
}

/// Handle the report command - simplified version
pub fn handle_report_command(args: ReportArgs) -> Result<()> {
    let corpus_path = args.corpus.unwrap_or_else(default_corpus_path);

    println!("Corpus Analysis Report");
    println!("======================");
    println!("Corpus: {}", corpus_path.display());
    println!("Target: {:.0}%", args.target_rate * 100.0);
    println!("Format: {}", args.format);

    // For now, just print status - actual compilation delegated to converge command
    println!("\nUse 'depyler converge' for full compilation analysis.");

    Ok(())
}

/// Find default corpus path
pub fn default_corpus_path() -> PathBuf {
    let candidates = [
        PathBuf::from("/home/noah/src/reprorusted-python-cli/examples"),
        PathBuf::from("../reprorusted-python-cli/examples"),
        PathBuf::from("./examples"),
    ];

    for path in &candidates {
        if path.exists() {
            return path.clone();
        }
    }

    PathBuf::from(".")
}

/// Extract error code and message from cargo output
pub fn extract_error(stderr: &str) -> (String, String) {
    let strip_ansi = |s: &str| -> String {
        let mut result = String::new();
        let mut in_escape = false;
        for c in s.chars() {
            if c == '\x1b' {
                in_escape = true;
            } else if in_escape {
                if c == 'm' {
                    in_escape = false;
                }
            } else {
                result.push(c);
            }
        }
        result
    };

    // Look for error[EXXXX] pattern
    for line in stderr.lines() {
        if let Some(start) = line.find("error[E") {
            if let Some(end) = line[start..].find(']') {
                let code = &line[start + 6..start + end];
                let msg = strip_ansi(line[start + end + 1..].trim());
                return (code.to_string(), msg);
            }
        }
    }

    // Check for transpiler errors
    for line in stderr.lines() {
        if line.starts_with("Error: Failed to transpile") {
            for cause_line in stderr.lines() {
                if cause_line
                    .trim()
                    .starts_with("Expression type not yet supported")
                {
                    return ("TRANSPILE".to_string(), strip_ansi(cause_line.trim()));
                }
                if cause_line.trim().starts_with("Unsupported") {
                    return ("TRANSPILE".to_string(), strip_ansi(cause_line.trim()));
                }
            }
            return ("TRANSPILE".to_string(), strip_ansi(line));
        }
        if line.starts_with("Error:") {
            return ("DEPYLER".to_string(), strip_ansi(line));
        }
    }

    // Fallback
    for line in stderr.lines() {
        let lower = line.to_lowercase();
        if lower.starts_with("error") {
            return ("UNKNOWN".to_string(), strip_ansi(line));
        }
    }

    ("UNKNOWN".to_string(), "Unknown error".to_string())
}

/// Analyze compilation results
pub fn analyze_results(
    results: &[CompileResult],
) -> (usize, usize, HashMap<String, ErrorTaxonomy>) {
    let mut pass = 0;
    let mut fail = 0;
    let mut taxonomy: HashMap<String, ErrorTaxonomy> = HashMap::new();

    for result in results {
        if result.success {
            pass += 1;
        } else {
            fail += 1;

            if let Some(code) = &result.error_code {
                let entry = taxonomy.entry(code.clone()).or_default();
                entry.count += 1;
                if entry.samples.len() < 3 {
                    let sample = format!(
                        "{}: {}",
                        result.name,
                        result.error_message.as_deref().unwrap_or("?")
                    );
                    entry.samples.push(sample);
                }
            }
        }
    }

    (pass, fail, taxonomy)
}

/// Get error description
pub fn error_description(code: &str) -> &'static str {
    match code {
        "E0425" => "Cannot find value in scope",
        "E0412" => "Cannot find type in scope",
        "E0308" => "Mismatched types",
        "E0277" => "Trait not implemented",
        "E0432" => "Unresolved import",
        "E0599" => "Method not found",
        "E0433" => "Failed to resolve path",
        "E0423" => "Expected value, found type",
        "E0369" => "Binary operation not supported",
        "E0255" => "Name already defined",
        "E0618" => "Expected function",
        "E0609" => "No field on type",
        "E0601" => "main function not found",
        "E0573" => "Expected type",
        "TRANSPILE" => "Transpiler limitation",
        "DEPYLER" => "General transpiler error",
        _ => "See rustc --explain",
    }
}

/// Get fix recommendation
pub fn fix_recommendation(code: &str) -> &'static str {
    match code {
        "E0425" => "Declare variables before use",
        "E0412" => "Add generic parameter detection",
        "E0308" => "Standardize numeric types",
        "E0277" => "Add missing trait implementations",
        "E0432" => "Fix import resolution",
        "E0599" => "Check method resolution",
        "E0433" => "Update module path resolution",
        "E0423" => "Fix value/type confusion",
        "E0369" => "Add operator overloading",
        "TRANSPILE" => "Add support in expr_gen.rs",
        "DEPYLER" => "Check error message",
        _ => "Investigate error pattern",
    }
}

/// Generate ASCII bar chart
pub fn ascii_bar(ratio: f64, width: usize) -> String {
    let filled = (ratio.clamp(0.0, 1.0) * width as f64).round() as usize;
    let empty = width.saturating_sub(filled);
    format!(
        "{}{}",
        "â–ˆ".repeat(filled).green(),
        "â–‘".repeat(empty).dimmed()
    )
}

/// Print terminal report
pub fn print_terminal_report(
    total: usize,
    pass: usize,
    fail: usize,
    rate: f64,
    taxonomy: &HashMap<String, ErrorTaxonomy>,
    _target: f64,
) {
    println!();
    println!("{}", "Summary".bold().underline());
    println!("  Total: {}", total);
    println!("  Pass:  {}", pass.to_string().green());
    println!("  Fail:  {}", fail.to_string().red());
    println!("  Rate:  {}", format!("{:.1}%", rate).cyan().bold());

    let andon = if rate >= 80.0 {
        "GREEN".green().bold()
    } else if rate >= 50.0 {
        "YELLOW".yellow().bold()
    } else {
        "RED".red().bold()
    };
    println!("  Status: {}", andon);

    if !taxonomy.is_empty() {
        println!();
        println!("{}", "Error Taxonomy".bold().underline());

        let mut sorted: Vec<_> = taxonomy.iter().collect();
        sorted.sort_by(|a, b| b.1.count.cmp(&a.1.count));

        for (code, entry) in sorted.iter().take(10) {
            let desc = error_description(code);
            println!("  {} ({}) - {}", code.yellow(), entry.count, desc);
        }
    }
}

/// Print JSON report
pub fn print_json_report(
    total: usize,
    pass: usize,
    fail: usize,
    rate: f64,
    taxonomy: &HashMap<String, ErrorTaxonomy>,
    target: f64,
) -> Result<()> {
    let errors: Vec<_> = taxonomy
        .iter()
        .map(|(code, entry)| {
            serde_json::json!({
                "code": code,
                "count": entry.count,
                "description": error_description(code),
                "samples": entry.samples,
            })
        })
        .collect();

    let report = serde_json::json!({
        "summary": {
            "total": total,
            "pass": pass,
            "fail": fail,
            "rate": rate,
            "target": target * 100.0,
            "status": if rate >= 80.0 { "GREEN" } else if rate >= 50.0 { "YELLOW" } else { "RED" }
        },
        "errors": errors
    });

    println!("{}", serde_json::to_string_pretty(&report)?);
    Ok(())
}

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

    #[test]
    fn test_extract_error_rust_error_code() {
        let stderr = "error[E0425]: cannot find value `x` in this scope";
        let (code, msg) = extract_error(stderr);
        assert_eq!(code, "E0425");
        assert!(msg.contains("cannot find value"));
    }

    #[test]
    fn test_extract_error_transpile() {
        let stderr =
            "Error: Failed to transpile\nCaused by:\n  Expression type not yet supported: Lambda";
        let (code, msg) = extract_error(stderr);
        assert_eq!(code, "TRANSPILE");
        assert!(msg.contains("Expression type not yet supported"));
    }

    #[test]
    fn test_extract_error_unsupported() {
        let stderr = "Error: Failed to transpile\nCaused by:\n  Unsupported syntax";
        let (code, msg) = extract_error(stderr);
        assert_eq!(code, "TRANSPILE");
        assert!(msg.contains("Unsupported"));
    }

    #[test]
    fn test_extract_error_depyler() {
        let stderr = "Error: Something went wrong";
        let (code, _msg) = extract_error(stderr);
        assert_eq!(code, "DEPYLER");
    }

    #[test]
    fn test_extract_error_unknown() {
        let stderr = "some random output";
        let (code, _) = extract_error(stderr);
        assert_eq!(code, "UNKNOWN");
    }

    #[test]
    fn test_extract_error_strips_ansi() {
        let stderr = "error[E0308]: \x1b[31mmismatched types\x1b[0m";
        let (code, msg) = extract_error(stderr);
        assert_eq!(code, "E0308");
        assert!(!msg.contains("\x1b"));
    }

    #[test]
    fn test_extract_error_empty() {
        let (code, _) = extract_error("");
        assert_eq!(code, "UNKNOWN");
    }

    #[test]
    fn test_extract_error_whitespace() {
        let (code, _) = extract_error("   \n\t  ");
        assert_eq!(code, "UNKNOWN");
    }

    #[test]
    fn test_analyze_results_all_pass() {
        let results = vec![
            CompileResult {
                name: "a".into(),
                success: true,
                error_code: None,
                error_message: None,
            },
            CompileResult {
                name: "b".into(),
                success: true,
                error_code: None,
                error_message: None,
            },
        ];
        let (pass, fail, taxonomy) = analyze_results(&results);
        assert_eq!(pass, 2);
        assert_eq!(fail, 0);
        assert!(taxonomy.is_empty());
    }

    #[test]
    fn test_analyze_results_with_failures() {
        let results = vec![
            CompileResult {
                name: "a".into(),
                success: true,
                error_code: None,
                error_message: None,
            },
            CompileResult {
                name: "b".into(),
                success: false,
                error_code: Some("E0425".into()),
                error_message: Some("not found".into()),
            },
            CompileResult {
                name: "c".into(),
                success: false,
                error_code: Some("E0425".into()),
                error_message: Some("not found".into()),
            },
            CompileResult {
                name: "d".into(),
                success: false,
                error_code: Some("E0308".into()),
                error_message: Some("type mismatch".into()),
            },
        ];
        let (pass, fail, taxonomy) = analyze_results(&results);
        assert_eq!(pass, 1);
        assert_eq!(fail, 3);
        assert_eq!(taxonomy.get("E0425").unwrap().count, 2);
        assert_eq!(taxonomy.get("E0308").unwrap().count, 1);
    }

    #[test]
    fn test_analyze_results_samples_limited() {
        let results: Vec<_> = (0..10)
            .map(|i| CompileResult {
                name: format!("file{}", i),
                success: false,
                error_code: Some("E0425".into()),
                error_message: Some(format!("error {}", i)),
            })
            .collect();
        let (_, _, taxonomy) = analyze_results(&results);
        assert_eq!(taxonomy.get("E0425").unwrap().count, 10);
        assert_eq!(taxonomy.get("E0425").unwrap().samples.len(), 3);
    }

    #[test]
    fn test_analyze_results_empty() {
        let results: Vec<CompileResult> = vec![];
        let (pass, fail, taxonomy) = analyze_results(&results);
        assert_eq!(pass, 0);
        assert_eq!(fail, 0);
        assert!(taxonomy.is_empty());
    }

    #[test]
    fn test_error_description_known_codes() {
        assert!(error_description("E0425").contains("find"));
        assert!(error_description("E0308").contains("type"));
        assert!(error_description("E0277").contains("Trait"));
        assert!(error_description("TRANSPILE").contains("Transpiler"));
    }

    #[test]
    fn test_error_description_unknown() {
        assert!(error_description("E9999").contains("rustc"));
    }

    #[test]
    fn test_fix_recommendation_known_codes() {
        assert!(!fix_recommendation("E0425").is_empty());
        assert!(!fix_recommendation("E0308").is_empty());
        assert!(!fix_recommendation("TRANSPILE").is_empty());
    }

    #[test]
    fn test_fix_recommendation_unknown() {
        let rec = fix_recommendation("UNKNOWN_CODE");
        assert!(!rec.is_empty());
    }

    #[test]
    fn test_ascii_bar_full() {
        let bar = ascii_bar(1.0, 10);
        assert!(bar.contains("â–ˆ"));
    }

    #[test]
    fn test_ascii_bar_empty() {
        let bar = ascii_bar(0.0, 10);
        assert!(bar.contains("â–‘"));
    }

    #[test]
    fn test_ascii_bar_half() {
        let bar = ascii_bar(0.5, 10);
        assert!(!bar.is_empty());
    }

    #[test]
    fn test_ascii_bar_clamps() {
        let bar1 = ascii_bar(-0.5, 10);
        let bar2 = ascii_bar(1.5, 10);
        assert!(!bar1.is_empty());
        assert!(!bar2.is_empty());
    }

    #[test]
    fn test_default_corpus_path() {
        let path = default_corpus_path();
        assert!(!path.as_os_str().is_empty());
    }

    #[test]
    fn test_report_args_defaults() {
        let args = ReportArgs {
            corpus: None,
            format: "terminal".into(),
            output: None,
            skip_clean: false,
            target_rate: 0.8,
            filter: None,
            tag: None,
            limit: None,
            sample: None,
            bisect: false,
            fail_fast: false,
        };
        assert_eq!(args.target_rate, 0.8);
        assert!(!args.bisect);
    }

    #[test]
    fn test_print_terminal_report() {
        let taxonomy = HashMap::new();
        print_terminal_report(10, 8, 2, 80.0, &taxonomy, 0.8);
    }

    #[test]
    fn test_print_terminal_report_with_errors() {
        let mut taxonomy = HashMap::new();
        taxonomy.insert(
            "E0425".to_string(),
            ErrorTaxonomy {
                count: 5,
                samples: vec!["sample1: error".to_string()],
            },
        );
        print_terminal_report(10, 2, 8, 20.0, &taxonomy, 0.8);
    }

    #[test]
    fn test_print_terminal_report_yellow_status() {
        let taxonomy = HashMap::new();
        print_terminal_report(100, 60, 40, 60.0, &taxonomy, 0.8);
    }

    #[test]
    fn test_print_terminal_report_green_status() {
        let taxonomy = HashMap::new();
        print_terminal_report(100, 85, 15, 85.0, &taxonomy, 0.8);
    }

    #[test]
    fn test_print_json_report() {
        let taxonomy = HashMap::new();
        let result = print_json_report(0, 0, 0, 0.0, &taxonomy, 0.8);
        assert!(result.is_ok());
    }

    #[test]
    fn test_print_json_report_with_data() {
        let mut taxonomy = HashMap::new();
        taxonomy.insert(
            "E0425".to_string(),
            ErrorTaxonomy {
                count: 2,
                samples: vec!["sample: error".to_string()],
            },
        );
        let result = print_json_report(2, 1, 1, 50.0, &taxonomy, 0.8);
        assert!(result.is_ok());
    }

    #[test]
    fn test_compile_result_debug() {
        let result = CompileResult {
            name: "test".to_string(),
            success: true,
            error_code: None,
            error_message: None,
        };
        let debug_str = format!("{:?}", result);
        assert!(debug_str.contains("test"));
    }

    #[test]
    fn test_error_taxonomy_default() {
        let taxonomy = ErrorTaxonomy::default();
        assert_eq!(taxonomy.count, 0);
        assert!(taxonomy.samples.is_empty());
    }

    #[test]
    fn test_handle_report_command() {
        let args = ReportArgs {
            corpus: Some(PathBuf::from("/tmp")),
            format: "text".into(),
            output: None,
            skip_clean: false,
            target_rate: 0.8,
            filter: None,
            tag: None,
            limit: None,
            sample: None,
            bisect: false,
            fail_fast: false,
        };
        let result = handle_report_command(args);
        assert!(result.is_ok());
    }

    #[test]
    fn test_handle_report_command_default_corpus() {
        let args = ReportArgs {
            corpus: None,
            format: "json".into(),
            output: None,
            skip_clean: true,
            target_rate: 0.9,
            filter: Some("test".into()),
            tag: Some("Dict".into()),
            limit: Some(10),
            sample: Some(5),
            bisect: false,
            fail_fast: true,
        };
        let result = handle_report_command(args);
        assert!(result.is_ok());
    }
}