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
//! Pure core functions extracted from lib.rs for EXTREME TDD
//!
//! This module contains pure, side-effect-free functions that can be
//! thoroughly tested with unit tests. The main lib.rs becomes a thin
//! shim that calls these functions.
//!
//! DEPYLER-COVERAGE-95: Extracted for testability

use colored::{ColoredString, Colorize};

/// Rate code complexity and return colored rating string
///
/// # Thresholds
/// - Good: complexity <= 5
/// - Acceptable: complexity <= 10
/// - High: complexity > 10
pub fn complexity_rating(complexity: f64) -> ColoredString {
    if complexity <= 5.0 {
        "Good".green()
    } else if complexity <= 10.0 {
        "Acceptable".yellow()
    } else {
        "High".red()
    }
}

/// Complexity level enum for programmatic use
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ComplexityLevel {
    Good,
    Acceptable,
    High,
}

impl ComplexityLevel {
    /// Get complexity level from numeric value
    pub fn from_value(complexity: f64) -> Self {
        if complexity <= 5.0 {
            ComplexityLevel::Good
        } else if complexity <= 10.0 {
            ComplexityLevel::Acceptable
        } else {
            ComplexityLevel::High
        }
    }

    /// Get string representation
    pub fn as_str(&self) -> &'static str {
        match self {
            ComplexityLevel::Good => "Good",
            ComplexityLevel::Acceptable => "Acceptable",
            ComplexityLevel::High => "High",
        }
    }

    /// Check if complexity is acceptable (Good or Acceptable)
    pub fn is_acceptable(&self) -> bool {
        matches!(self, ComplexityLevel::Good | ComplexityLevel::Acceptable)
    }
}

/// Extract error code from rustc/cargo stderr output
///
/// Returns Some(code) if an error code like E0308 is found, None otherwise
pub fn extract_error_code(error: &str) -> Option<String> {
    // Pattern: error[EXXXX]:
    if let Some(start) = error.find("error[E") {
        let rest = &error[start + 6..]; // After "error["
        if let Some(end) = rest.find(']') {
            return Some(rest[..end].to_string());
        }
    }
    None
}

/// Parse line and column from rustc error output
///
/// Returns Some((line, column)) if found, None otherwise
pub fn parse_error_location(error: &str) -> Option<(usize, usize)> {
    // Pattern: --> path:line:column
    if let Some(arrow_pos) = error.find("-->") {
        let rest = &error[arrow_pos + 3..];
        // Find first colon (after path)
        if let Some(first_colon) = rest.find(':') {
            let after_path = &rest[first_colon + 1..];
            // Find line:column
            if let Some(second_colon) = after_path.find(':') {
                let line_str = &after_path[..second_colon];
                let col_rest = &after_path[second_colon + 1..];
                // Column ends at whitespace or newline
                let col_str: String = col_rest.chars().take_while(|c| c.is_ascii_digit()).collect();

                if let (Ok(line), Ok(col)) = (line_str.trim().parse(), col_str.parse()) {
                    return Some((line, col));
                }
            }
        }
    }
    None
}

/// Error category for classification
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ErrorCategory {
    TypeMismatch,
    BorrowChecker,
    MissingImport,
    UndefinedVariable,
    MethodNotFound,
    TraitBound,
    Syntax,
    Transpiler,
    Unknown,
}

impl ErrorCategory {
    /// Classify error code into category
    pub fn from_code(code: &str) -> Self {
        match code {
            "E0308" => ErrorCategory::TypeMismatch,
            "E0382" | "E0499" | "E0502" | "E0505" | "E0507" | "E0515" => ErrorCategory::BorrowChecker,
            "E0432" | "E0433" => ErrorCategory::MissingImport,
            "E0425" => ErrorCategory::UndefinedVariable,
            "E0599" | "E0609" => ErrorCategory::MethodNotFound,
            "E0277" => ErrorCategory::TraitBound,
            "TRANSPILE" => ErrorCategory::Transpiler,
            _ => ErrorCategory::Unknown,
        }
    }

    /// Get human-readable name
    pub fn as_str(&self) -> &'static str {
        match self {
            ErrorCategory::TypeMismatch => "Type Mismatch",
            ErrorCategory::BorrowChecker => "Borrow Checker",
            ErrorCategory::MissingImport => "Missing Import",
            ErrorCategory::UndefinedVariable => "Undefined Variable",
            ErrorCategory::MethodNotFound => "Method Not Found",
            ErrorCategory::TraitBound => "Trait Bound",
            ErrorCategory::Syntax => "Syntax Error",
            ErrorCategory::Transpiler => "Transpiler Error",
            ErrorCategory::Unknown => "Unknown",
        }
    }
}

/// Quality validation result
#[derive(Debug, Clone)]
pub struct QualityCheck {
    pub tdg_ok: bool,
    pub complexity_ok: bool,
    pub coverage_ok: bool,
}

impl QualityCheck {
    /// Check if all quality gates pass
    pub fn all_passed(&self) -> bool {
        self.tdg_ok && self.complexity_ok && self.coverage_ok
    }

    /// Count passing checks
    pub fn passing_count(&self) -> usize {
        [self.tdg_ok, self.complexity_ok, self.coverage_ok]
            .iter()
            .filter(|&&x| x)
            .count()
    }

    /// Count failing checks
    pub fn failing_count(&self) -> usize {
        3 - self.passing_count()
    }
}

/// Validate TDG (Technical Debt Grade) score
pub fn validate_tdg(tdg: f64, min: f64, max: f64) -> bool {
    tdg >= min && tdg <= max
}

/// Validate complexity score
pub fn validate_complexity(complexity: f64, max: u32) -> bool {
    complexity <= max as f64
}

/// Validate coverage percentage
pub fn validate_coverage(coverage: f64, min: u32) -> bool {
    coverage >= min as f64
}

/// Format file size in human-readable format
pub fn format_file_size(bytes: usize) -> String {
    const KB: usize = 1024;
    const MB: usize = KB * 1024;
    const GB: usize = MB * 1024;

    if bytes >= GB {
        format!("{:.2} GB", bytes as f64 / GB as f64)
    } else if bytes >= MB {
        format!("{:.2} MB", bytes as f64 / MB as f64)
    } else if bytes >= KB {
        format!("{:.2} KB", bytes as f64 / KB as f64)
    } else {
        format!("{} bytes", bytes)
    }
}

/// Format duration in human-readable format
pub fn format_duration_secs(secs: f64) -> String {
    if secs < 0.001 {
        format!("{:.0} μs", secs * 1_000_000.0)
    } else if secs < 1.0 {
        format!("{:.0} ms", secs * 1000.0)
    } else if secs < 60.0 {
        format!("{:.2} s", secs)
    } else if secs < 3600.0 {
        let mins = (secs / 60.0).floor();
        let remaining = secs - (mins * 60.0);
        format!("{}m {:.0}s", mins as u32, remaining)
    } else {
        let hours = (secs / 3600.0).floor();
        let remaining_mins = ((secs - (hours * 3600.0)) / 60.0).floor();
        format!("{}h {}m", hours as u32, remaining_mins as u32)
    }
}

/// Calculate percentage safely
pub fn calculate_percentage(part: usize, total: usize) -> f64 {
    if total == 0 {
        0.0
    } else {
        (part as f64 / total as f64) * 100.0
    }
}

/// Truncate string to max length with ellipsis
pub fn truncate_with_ellipsis(s: &str, max_len: usize) -> String {
    if s.len() <= max_len {
        s.to_string()
    } else if max_len <= 3 {
        s.chars().take(max_len).collect()
    } else {
        let truncated: String = s.chars().take(max_len - 3).collect();
        format!("{}...", truncated)
    }
}

// ============================================================================
// EXTREME TDD: Comprehensive Unit Tests
// ============================================================================

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

    // ========== complexity_rating tests ==========

    #[test]
    fn test_complexity_rating_good_zero() {
        let rating = complexity_rating(0.0);
        assert!(rating.to_string().contains("Good"));
    }

    #[test]
    fn test_complexity_rating_good_mid() {
        let rating = complexity_rating(3.0);
        assert!(rating.to_string().contains("Good"));
    }

    #[test]
    fn test_complexity_rating_good_boundary() {
        let rating = complexity_rating(5.0);
        assert!(rating.to_string().contains("Good"));
    }

    #[test]
    fn test_complexity_rating_acceptable_low() {
        let rating = complexity_rating(5.1);
        assert!(rating.to_string().contains("Acceptable"));
    }

    #[test]
    fn test_complexity_rating_acceptable_mid() {
        let rating = complexity_rating(7.5);
        assert!(rating.to_string().contains("Acceptable"));
    }

    #[test]
    fn test_complexity_rating_acceptable_boundary() {
        let rating = complexity_rating(10.0);
        assert!(rating.to_string().contains("Acceptable"));
    }

    #[test]
    fn test_complexity_rating_high_low() {
        let rating = complexity_rating(10.1);
        assert!(rating.to_string().contains("High"));
    }

    #[test]
    fn test_complexity_rating_high_mid() {
        let rating = complexity_rating(15.0);
        assert!(rating.to_string().contains("High"));
    }

    #[test]
    fn test_complexity_rating_high_extreme() {
        let rating = complexity_rating(100.0);
        assert!(rating.to_string().contains("High"));
    }

    // ========== ComplexityLevel tests ==========

    #[test]
    fn test_complexity_level_good() {
        assert_eq!(ComplexityLevel::from_value(0.0), ComplexityLevel::Good);
        assert_eq!(ComplexityLevel::from_value(3.0), ComplexityLevel::Good);
        assert_eq!(ComplexityLevel::from_value(5.0), ComplexityLevel::Good);
    }

    #[test]
    fn test_complexity_level_acceptable() {
        assert_eq!(ComplexityLevel::from_value(5.1), ComplexityLevel::Acceptable);
        assert_eq!(ComplexityLevel::from_value(7.5), ComplexityLevel::Acceptable);
        assert_eq!(ComplexityLevel::from_value(10.0), ComplexityLevel::Acceptable);
    }

    #[test]
    fn test_complexity_level_high() {
        assert_eq!(ComplexityLevel::from_value(10.1), ComplexityLevel::High);
        assert_eq!(ComplexityLevel::from_value(15.0), ComplexityLevel::High);
        assert_eq!(ComplexityLevel::from_value(100.0), ComplexityLevel::High);
    }

    #[test]
    fn test_complexity_level_as_str() {
        assert_eq!(ComplexityLevel::Good.as_str(), "Good");
        assert_eq!(ComplexityLevel::Acceptable.as_str(), "Acceptable");
        assert_eq!(ComplexityLevel::High.as_str(), "High");
    }

    #[test]
    fn test_complexity_level_is_acceptable() {
        assert!(ComplexityLevel::Good.is_acceptable());
        assert!(ComplexityLevel::Acceptable.is_acceptable());
        assert!(!ComplexityLevel::High.is_acceptable());
    }

    // ========== extract_error_code tests ==========

    #[test]
    fn test_extract_error_code_e0308() {
        assert_eq!(
            extract_error_code("error[E0308]: mismatched types"),
            Some("E0308".to_string())
        );
    }

    #[test]
    fn test_extract_error_code_e0425() {
        assert_eq!(
            extract_error_code("error[E0425]: cannot find value"),
            Some("E0425".to_string())
        );
    }

    #[test]
    fn test_extract_error_code_e0277() {
        assert_eq!(
            extract_error_code("error[E0277]: trait bound not satisfied"),
            Some("E0277".to_string())
        );
    }

    #[test]
    fn test_extract_error_code_not_found() {
        assert_eq!(extract_error_code("warning: unused variable"), None);
    }

    #[test]
    fn test_extract_error_code_malformed() {
        assert_eq!(extract_error_code("error[E0308 no bracket"), None);
    }

    #[test]
    fn test_extract_error_code_empty() {
        assert_eq!(extract_error_code(""), None);
    }

    #[test]
    fn test_extract_error_code_multiline() {
        let error = "compiling...\nerror[E0599]: no method found\n   --> src/main.rs";
        assert_eq!(extract_error_code(error), Some("E0599".to_string()));
    }

    // ========== parse_error_location tests ==========

    #[test]
    fn test_parse_error_location_found() {
        let error = "  --> src/main.rs:42:15";
        assert_eq!(parse_error_location(error), Some((42, 15)));
    }

    #[test]
    fn test_parse_error_location_line_only() {
        let error = "  --> src/main.rs:100:1";
        assert_eq!(parse_error_location(error), Some((100, 1)));
    }

    #[test]
    fn test_parse_error_location_not_found() {
        let error = "error: something went wrong";
        assert_eq!(parse_error_location(error), None);
    }

    #[test]
    fn test_parse_error_location_empty() {
        assert_eq!(parse_error_location(""), None);
    }

    // ========== ErrorCategory tests ==========

    #[test]
    fn test_error_category_type_mismatch() {
        assert_eq!(ErrorCategory::from_code("E0308"), ErrorCategory::TypeMismatch);
    }

    #[test]
    fn test_error_category_borrow_checker() {
        assert_eq!(ErrorCategory::from_code("E0382"), ErrorCategory::BorrowChecker);
        assert_eq!(ErrorCategory::from_code("E0499"), ErrorCategory::BorrowChecker);
        assert_eq!(ErrorCategory::from_code("E0502"), ErrorCategory::BorrowChecker);
        assert_eq!(ErrorCategory::from_code("E0505"), ErrorCategory::BorrowChecker);
        assert_eq!(ErrorCategory::from_code("E0507"), ErrorCategory::BorrowChecker);
    }

    #[test]
    fn test_error_category_missing_import() {
        assert_eq!(ErrorCategory::from_code("E0432"), ErrorCategory::MissingImport);
        assert_eq!(ErrorCategory::from_code("E0433"), ErrorCategory::MissingImport);
    }

    #[test]
    fn test_error_category_undefined_variable() {
        assert_eq!(ErrorCategory::from_code("E0425"), ErrorCategory::UndefinedVariable);
    }

    #[test]
    fn test_error_category_method_not_found() {
        assert_eq!(ErrorCategory::from_code("E0599"), ErrorCategory::MethodNotFound);
        assert_eq!(ErrorCategory::from_code("E0609"), ErrorCategory::MethodNotFound);
    }

    #[test]
    fn test_error_category_trait_bound() {
        assert_eq!(ErrorCategory::from_code("E0277"), ErrorCategory::TraitBound);
    }

    #[test]
    fn test_error_category_transpiler() {
        assert_eq!(ErrorCategory::from_code("TRANSPILE"), ErrorCategory::Transpiler);
    }

    #[test]
    fn test_error_category_unknown() {
        assert_eq!(ErrorCategory::from_code("E9999"), ErrorCategory::Unknown);
        assert_eq!(ErrorCategory::from_code("RANDOM"), ErrorCategory::Unknown);
    }

    #[test]
    fn test_error_category_as_str() {
        assert_eq!(ErrorCategory::TypeMismatch.as_str(), "Type Mismatch");
        assert_eq!(ErrorCategory::BorrowChecker.as_str(), "Borrow Checker");
        assert_eq!(ErrorCategory::Unknown.as_str(), "Unknown");
    }

    // ========== QualityCheck tests ==========

    #[test]
    fn test_quality_check_all_pass() {
        let check = QualityCheck {
            tdg_ok: true,
            complexity_ok: true,
            coverage_ok: true,
        };
        assert!(check.all_passed());
        assert_eq!(check.passing_count(), 3);
        assert_eq!(check.failing_count(), 0);
    }

    #[test]
    fn test_quality_check_none_pass() {
        let check = QualityCheck {
            tdg_ok: false,
            complexity_ok: false,
            coverage_ok: false,
        };
        assert!(!check.all_passed());
        assert_eq!(check.passing_count(), 0);
        assert_eq!(check.failing_count(), 3);
    }

    #[test]
    fn test_quality_check_some_pass() {
        let check = QualityCheck {
            tdg_ok: true,
            complexity_ok: false,
            coverage_ok: true,
        };
        assert!(!check.all_passed());
        assert_eq!(check.passing_count(), 2);
        assert_eq!(check.failing_count(), 1);
    }

    // ========== validate_tdg tests ==========

    #[test]
    fn test_validate_tdg_in_range() {
        assert!(validate_tdg(1.5, 0.0, 2.0));
        assert!(validate_tdg(0.0, 0.0, 2.0));
        assert!(validate_tdg(2.0, 0.0, 2.0));
    }

    #[test]
    fn test_validate_tdg_out_of_range() {
        assert!(!validate_tdg(-0.1, 0.0, 2.0));
        assert!(!validate_tdg(2.1, 0.0, 2.0));
    }

    // ========== validate_complexity tests ==========

    #[test]
    fn test_validate_complexity_pass() {
        assert!(validate_complexity(5.0, 10));
        assert!(validate_complexity(10.0, 10));
    }

    #[test]
    fn test_validate_complexity_fail() {
        assert!(!validate_complexity(10.1, 10));
        assert!(!validate_complexity(15.0, 10));
    }

    // ========== validate_coverage tests ==========

    #[test]
    fn test_validate_coverage_pass() {
        assert!(validate_coverage(80.0, 80));
        assert!(validate_coverage(95.0, 80));
    }

    #[test]
    fn test_validate_coverage_fail() {
        assert!(!validate_coverage(79.9, 80));
        assert!(!validate_coverage(50.0, 80));
    }

    // ========== format_file_size tests ==========

    #[test]
    fn test_format_file_size_bytes() {
        assert_eq!(format_file_size(0), "0 bytes");
        assert_eq!(format_file_size(512), "512 bytes");
        assert_eq!(format_file_size(1023), "1023 bytes");
    }

    #[test]
    fn test_format_file_size_kb() {
        assert_eq!(format_file_size(1024), "1.00 KB");
        assert_eq!(format_file_size(2048), "2.00 KB");
        assert!(format_file_size(1536).contains("KB"));
    }

    #[test]
    fn test_format_file_size_mb() {
        assert_eq!(format_file_size(1024 * 1024), "1.00 MB");
        assert!(format_file_size(5 * 1024 * 1024).contains("MB"));
    }

    #[test]
    fn test_format_file_size_gb() {
        assert_eq!(format_file_size(1024 * 1024 * 1024), "1.00 GB");
    }

    // ========== format_duration_secs tests ==========

    #[test]
    fn test_format_duration_microseconds() {
        assert!(format_duration_secs(0.0001).contains("μs"));
        assert!(format_duration_secs(0.0005).contains("μs"));
    }

    #[test]
    fn test_format_duration_milliseconds() {
        assert!(format_duration_secs(0.001).contains("ms"));
        assert!(format_duration_secs(0.5).contains("ms"));
    }

    #[test]
    fn test_format_duration_seconds() {
        assert!(format_duration_secs(1.0).contains(" s"));
        assert!(format_duration_secs(30.5).contains(" s"));
    }

    #[test]
    fn test_format_duration_minutes() {
        let formatted = format_duration_secs(90.0);
        assert!(formatted.contains("m"));
    }

    #[test]
    fn test_format_duration_hours() {
        let formatted = format_duration_secs(3700.0);
        assert!(formatted.contains("h"));
    }

    // ========== calculate_percentage tests ==========

    #[test]
    fn test_calculate_percentage_zero() {
        assert_eq!(calculate_percentage(0, 0), 0.0);
        assert_eq!(calculate_percentage(0, 100), 0.0);
    }

    #[test]
    fn test_calculate_percentage_full() {
        assert_eq!(calculate_percentage(100, 100), 100.0);
    }

    #[test]
    fn test_calculate_percentage_half() {
        assert_eq!(calculate_percentage(50, 100), 50.0);
    }

    #[test]
    fn test_calculate_percentage_various() {
        assert!((calculate_percentage(1, 4) - 25.0).abs() < 0.01);
        assert!((calculate_percentage(3, 4) - 75.0).abs() < 0.01);
    }

    // ========== truncate_with_ellipsis tests ==========

    #[test]
    fn test_truncate_short_string() {
        assert_eq!(truncate_with_ellipsis("hello", 10), "hello");
    }

    #[test]
    fn test_truncate_exact_length() {
        assert_eq!(truncate_with_ellipsis("hello", 5), "hello");
    }

    #[test]
    fn test_truncate_long_string() {
        assert_eq!(truncate_with_ellipsis("hello world", 8), "hello...");
    }

    #[test]
    fn test_truncate_very_short_max() {
        assert_eq!(truncate_with_ellipsis("hello", 2), "he");
        assert_eq!(truncate_with_ellipsis("hello", 3), "hel");
    }

    #[test]
    fn test_truncate_empty() {
        assert_eq!(truncate_with_ellipsis("", 5), "");
    }

    #[test]
    fn test_truncate_zero_max() {
        assert_eq!(truncate_with_ellipsis("hello", 0), "");
    }
}