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
//! Error classification for convergence loop (Issue #172)
//!
//! Integrates depyler_oracle for ML-based error classification and
//! OracleQueryLoop for pattern-based fix suggestions.

use super::compiler::{CompilationError, CompilationResult};
use depyler_oracle::{ErrorCategory as OracleCategory, Oracle};
#[cfg(feature = "oracle-training")]
use depyler_oracle::{
    ErrorContext, OracleQueryLoop, OracleSuggestion, QueryLoopConfig, RustErrorCode,
};
use std::sync::OnceLock;

/// Lazily initialized Oracle singleton for ML classification
static ORACLE: OnceLock<Option<Oracle>> = OnceLock::new();

/// Get or initialize the Oracle singleton
fn get_oracle() -> Option<&'static Oracle> {
    ORACLE
        .get_or_init(|| {
            #[cfg(feature = "oracle-training")]
            {
                match Oracle::load_or_train() {
                    Ok(oracle) => Some(oracle),
                    Err(e) => {
                        tracing::warn!(
                            "Failed to load oracle: {e}. Using fallback classification."
                        );
                        None
                    }
                }
            }
            #[cfg(not(feature = "oracle-training"))]
            {
                // Without training feature, try loading from disk only
                let path = Oracle::default_model_path();
                if path.exists() {
                    Oracle::load(&path).ok()
                } else {
                    None
                }
            }
        })
        .as_ref()
}

/// Category of compilation error (converge-level taxonomy)
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ErrorCategory {
    /// Gap in transpiler (missing feature, incorrect codegen)
    TranspilerGap,
    /// Gap in model (incorrect pattern matching)
    ModelGap,
    /// User code issue (not transpiler's fault)
    UserError,
    /// Unknown category
    Unknown,
}

/// Map Oracle's specific category to converge's higher-level taxonomy
fn map_oracle_category(oracle_cat: OracleCategory) -> (ErrorCategory, String) {
    match oracle_cat {
        OracleCategory::TypeMismatch => (ErrorCategory::TranspilerGap, "type_inference".into()),
        OracleCategory::BorrowChecker => (ErrorCategory::TranspilerGap, "borrow_checker".into()),
        OracleCategory::MissingImport => (ErrorCategory::TranspilerGap, "missing_import".into()),
        OracleCategory::SyntaxError => (ErrorCategory::TranspilerGap, "syntax".into()),
        OracleCategory::LifetimeError => (ErrorCategory::TranspilerGap, "lifetime".into()),
        OracleCategory::TraitBound => (ErrorCategory::TranspilerGap, "trait_bound".into()),
        OracleCategory::Other => (ErrorCategory::Unknown, "unknown".into()),
    }
}

/// Classification result for a single error
#[derive(Debug, Clone)]
pub struct ErrorClassification {
    /// The original error
    pub error: CompilationError,
    /// Category of the error
    pub category: ErrorCategory,
    /// Subcategory for more specific classification
    pub subcategory: String,
    /// Confidence of classification (0.0-1.0)
    pub confidence: f64,
    /// Suggested fix from Oracle (if available)
    pub suggested_fix: Option<String>,
}

/// Classifier for compilation errors using ML Oracle
pub struct ErrorClassifier {
    /// Optional OracleQueryLoop for pattern-based fixes
    #[cfg(feature = "oracle-training")]
    query_loop: Option<OracleQueryLoop>,
}

impl ErrorClassifier {
    /// Create a new error classifier with Oracle integration
    pub fn new() -> Self {
        #[cfg(feature = "oracle-training")]
        {
            let query_loop = Self::init_query_loop();
            Self { query_loop }
        }
        #[cfg(not(feature = "oracle-training"))]
        {
            Self {}
        }
    }

    /// Initialize OracleQueryLoop with default patterns
    #[cfg(feature = "oracle-training")]
    fn init_query_loop() -> Option<OracleQueryLoop> {
        let config = QueryLoopConfig {
            threshold: 0.7,
            max_suggestions: 3,
            boost_recent: true,
            max_retries: 3,
            llm_fallback: false,
        };
        let mut loop_instance = OracleQueryLoop::with_config(config);

        // Try to load patterns from default path
        let pattern_path = OracleQueryLoop::default_pattern_path();
        if pattern_path.exists() {
            if let Err(e) = loop_instance.load(&pattern_path) {
                tracing::debug!("No patterns loaded: {e}");
            }
        }

        Some(loop_instance)
    }

    /// Classify a single compilation error using ML Oracle
    pub fn classify(&self, error: &CompilationError) -> ErrorClassification {
        // Try ML classification first
        if let Some(oracle) = get_oracle() {
            if let Ok(result) = oracle.classify_message(&error.message) {
                let (category, subcategory) = map_oracle_category(result.category);
                return ErrorClassification {
                    error: error.clone(),
                    category,
                    subcategory,
                    confidence: result.confidence as f64,
                    suggested_fix: result.suggested_fix,
                };
            }
        }

        // Fallback to rule-based classification
        self.classify_fallback(error)
    }

    /// Fallback rule-based classification (original hardcoded logic)
    fn classify_fallback(&self, error: &CompilationError) -> ErrorClassification {
        let (category, subcategory, confidence) = match error.code.as_str() {
            "E0599" => (ErrorCategory::TranspilerGap, "missing_method".into(), 0.9),
            "E0308" => (ErrorCategory::TranspilerGap, "type_inference".into(), 0.85),
            "E0277" => (ErrorCategory::TranspilerGap, "trait_bound".into(), 0.8),
            "E0425" => (
                ErrorCategory::TranspilerGap,
                "undefined_variable".into(),
                0.75,
            ),
            "E0433" => (ErrorCategory::TranspilerGap, "missing_import".into(), 0.85),
            "E0432" => (
                ErrorCategory::TranspilerGap,
                "unresolved_import".into(),
                0.85,
            ),
            "E0382" => (ErrorCategory::TranspilerGap, "borrow_checker".into(), 0.7),
            "E0502" => (ErrorCategory::TranspilerGap, "borrow_checker".into(), 0.7),
            "E0507" => (ErrorCategory::TranspilerGap, "borrow_checker".into(), 0.7),
            "E0597" => (ErrorCategory::TranspilerGap, "lifetime".into(), 0.7),
            "E0716" => (ErrorCategory::TranspilerGap, "lifetime".into(), 0.7),
            _ => (ErrorCategory::Unknown, "unknown".into(), 0.5),
        };

        ErrorClassification {
            error: error.clone(),
            category,
            subcategory,
            confidence,
            suggested_fix: None,
        }
    }

    /// Get fix suggestions from OracleQueryLoop for an error
    #[cfg(feature = "oracle-training")]
    pub fn get_suggestions(&mut self, error: &CompilationError) -> Vec<OracleSuggestion> {
        let query_loop = match &mut self.query_loop {
            Some(ql) => ql,
            None => return Vec::new(),
        };

        // Parse error code
        let error_code = match error.code.parse::<RustErrorCode>() {
            Ok(code) => code,
            Err(_) => return Vec::new(),
        };

        // Build error context
        let context = ErrorContext {
            file: error.file.clone(),
            line: error.line,
            column: error.column,
            source_snippet: String::new(), // Could extract from file
            surrounding_lines: Vec::new(),
        };

        query_loop.suggest(error_code, &error.message, &context)
    }

    /// Classify all errors from compilation results
    pub fn classify_all(&self, results: &[CompilationResult]) -> Vec<ErrorClassification> {
        results
            .iter()
            .flat_map(|r| r.errors.iter())
            .map(|e| self.classify(e))
            .collect()
    }

    /// Get Oracle statistics (if query loop is active)
    #[cfg(feature = "oracle-training")]
    pub fn stats(&self) -> Option<&depyler_oracle::OracleStats> {
        self.query_loop.as_ref().map(|ql| ql.stats())
    }
}

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

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

    #[test]
    fn test_classify_e0599_fallback() {
        let classifier = ErrorClassifier::new();
        let error = CompilationError {
            code: "E0599".to_string(),
            message: "no method named `contains_key`".to_string(),
            file: PathBuf::from("test.rs"),
            line: 10,
            column: 5,
            ..Default::default()
        };

        // Use fallback directly to test rule-based logic
        let classification = classifier.classify_fallback(&error);
        assert_eq!(classification.category, ErrorCategory::TranspilerGap);
        assert_eq!(classification.subcategory, "missing_method");
        assert!(classification.confidence > 0.8);
    }

    #[test]
    fn test_classify_e0308_fallback() {
        let classifier = ErrorClassifier::new();
        let error = CompilationError {
            code: "E0308".to_string(),
            message: "expected `i32`, found `i64`".to_string(),
            file: PathBuf::from("test.rs"),
            line: 20,
            column: 10,
            ..Default::default()
        };

        let classification = classifier.classify_fallback(&error);
        assert_eq!(classification.category, ErrorCategory::TranspilerGap);
        assert_eq!(classification.subcategory, "type_inference");
    }

    #[test]
    fn test_classify_e0277_fallback() {
        let classifier = ErrorClassifier::new();
        let error = CompilationError {
            code: "E0277".to_string(),
            message: "the trait bound `Foo: Clone` is not satisfied".to_string(),
            file: PathBuf::from("test.rs"),
            line: 30,
            column: 15,
            ..Default::default()
        };

        let classification = classifier.classify_fallback(&error);
        assert_eq!(classification.category, ErrorCategory::TranspilerGap);
        assert_eq!(classification.subcategory, "trait_bound");
    }

    #[test]
    fn test_classify_unknown_code() {
        let classifier = ErrorClassifier::new();
        let error = CompilationError {
            code: "E9999".to_string(),
            message: "unknown error".to_string(),
            file: PathBuf::from("test.rs"),
            line: 1,
            column: 1,
            ..Default::default()
        };

        let classification = classifier.classify_fallback(&error);
        assert_eq!(classification.category, ErrorCategory::Unknown);
    }

    #[test]
    fn test_map_oracle_category() {
        assert_eq!(
            map_oracle_category(OracleCategory::TypeMismatch),
            (ErrorCategory::TranspilerGap, "type_inference".into())
        );
        assert_eq!(
            map_oracle_category(OracleCategory::BorrowChecker),
            (ErrorCategory::TranspilerGap, "borrow_checker".into())
        );
        assert_eq!(
            map_oracle_category(OracleCategory::Other),
            (ErrorCategory::Unknown, "unknown".into())
        );
    }

    #[test]
    fn test_classifier_default() {
        let classifier = ErrorClassifier::default();
        // Just verify it creates without panic
        #[cfg(feature = "oracle-training")]
        assert!(classifier.query_loop.is_some());
        let _ = classifier;
    }

    #[test]
    fn test_classify_e0425_undefined_variable() {
        let classifier = ErrorClassifier::new();
        let error = CompilationError {
            code: "E0425".to_string(),
            message: "cannot find value `x` in this scope".to_string(),
            file: PathBuf::from("test.rs"),
            line: 5,
            column: 1,
            ..Default::default()
        };
        let classification = classifier.classify_fallback(&error);
        assert_eq!(classification.category, ErrorCategory::TranspilerGap);
        assert_eq!(classification.subcategory, "undefined_variable");
    }

    #[test]
    fn test_classify_e0433_missing_import() {
        let classifier = ErrorClassifier::new();
        let error = CompilationError {
            code: "E0433".to_string(),
            message: "failed to resolve: use of undeclared crate or module".to_string(),
            file: PathBuf::from("test.rs"),
            line: 1,
            column: 5,
            ..Default::default()
        };
        let classification = classifier.classify_fallback(&error);
        assert_eq!(classification.category, ErrorCategory::TranspilerGap);
        assert_eq!(classification.subcategory, "missing_import");
    }

    #[test]
    fn test_classify_e0432_unresolved_import() {
        let classifier = ErrorClassifier::new();
        let error = CompilationError {
            code: "E0432".to_string(),
            message: "unresolved import `foo`".to_string(),
            file: PathBuf::from("test.rs"),
            line: 2,
            column: 5,
            ..Default::default()
        };
        let classification = classifier.classify_fallback(&error);
        assert_eq!(classification.category, ErrorCategory::TranspilerGap);
        assert_eq!(classification.subcategory, "unresolved_import");
    }

    #[test]
    fn test_classify_e0382_borrow_checker() {
        let classifier = ErrorClassifier::new();
        let error = CompilationError {
            code: "E0382".to_string(),
            message: "borrow of moved value".to_string(),
            file: PathBuf::from("test.rs"),
            line: 10,
            column: 5,
            ..Default::default()
        };
        let classification = classifier.classify_fallback(&error);
        assert_eq!(classification.category, ErrorCategory::TranspilerGap);
        assert_eq!(classification.subcategory, "borrow_checker");
    }

    #[test]
    fn test_classify_e0502_borrow_checker() {
        let classifier = ErrorClassifier::new();
        let error = CompilationError {
            code: "E0502".to_string(),
            message: "cannot borrow as mutable".to_string(),
            file: PathBuf::from("test.rs"),
            line: 15,
            column: 8,
            ..Default::default()
        };
        let classification = classifier.classify_fallback(&error);
        assert_eq!(classification.category, ErrorCategory::TranspilerGap);
        assert_eq!(classification.subcategory, "borrow_checker");
    }

    #[test]
    fn test_classify_e0507_borrow_checker() {
        let classifier = ErrorClassifier::new();
        let error = CompilationError {
            code: "E0507".to_string(),
            message: "cannot move out of borrowed content".to_string(),
            file: PathBuf::from("test.rs"),
            line: 20,
            column: 10,
            ..Default::default()
        };
        let classification = classifier.classify_fallback(&error);
        assert_eq!(classification.category, ErrorCategory::TranspilerGap);
        assert_eq!(classification.subcategory, "borrow_checker");
    }

    #[test]
    fn test_classify_e0597_lifetime() {
        let classifier = ErrorClassifier::new();
        let error = CompilationError {
            code: "E0597".to_string(),
            message: "does not live long enough".to_string(),
            file: PathBuf::from("test.rs"),
            line: 25,
            column: 12,
            ..Default::default()
        };
        let classification = classifier.classify_fallback(&error);
        assert_eq!(classification.category, ErrorCategory::TranspilerGap);
        assert_eq!(classification.subcategory, "lifetime");
    }

    #[test]
    fn test_classify_e0716_lifetime() {
        let classifier = ErrorClassifier::new();
        let error = CompilationError {
            code: "E0716".to_string(),
            message: "temporary value dropped while borrowed".to_string(),
            file: PathBuf::from("test.rs"),
            line: 30,
            column: 5,
            ..Default::default()
        };
        let classification = classifier.classify_fallback(&error);
        assert_eq!(classification.category, ErrorCategory::TranspilerGap);
        assert_eq!(classification.subcategory, "lifetime");
    }

    #[test]
    fn test_classify_all_empty() {
        let classifier = ErrorClassifier::new();
        let results: Vec<CompilationResult> = vec![];
        let classifications = classifier.classify_all(&results);
        assert!(classifications.is_empty());
    }

    #[test]
    fn test_classify_all_with_errors() {
        let classifier = ErrorClassifier::new();
        let results = vec![
            CompilationResult {
                source_file: PathBuf::from("a.py"),
                success: false,
                errors: vec![CompilationError {
                    code: "E0599".to_string(),
                    message: "no method".to_string(),
                    file: PathBuf::from("a.rs"),
                    line: 1,
                    column: 1,
                    ..Default::default()
                }],
                rust_file: None,
            },
            CompilationResult {
                source_file: PathBuf::from("b.py"),
                success: false,
                errors: vec![
                    CompilationError {
                        code: "E0308".to_string(),
                        message: "type mismatch".to_string(),
                        file: PathBuf::from("b.rs"),
                        line: 2,
                        column: 2,
                        ..Default::default()
                    },
                    CompilationError {
                        code: "E0277".to_string(),
                        message: "trait bound".to_string(),
                        file: PathBuf::from("b.rs"),
                        line: 3,
                        column: 3,
                        ..Default::default()
                    },
                ],
                rust_file: None,
            },
        ];
        let classifications = classifier.classify_all(&results);
        assert_eq!(classifications.len(), 3);
    }

    #[test]
    fn test_map_oracle_category_all_variants() {
        assert_eq!(
            map_oracle_category(OracleCategory::MissingImport),
            (ErrorCategory::TranspilerGap, "missing_import".into())
        );
        assert_eq!(
            map_oracle_category(OracleCategory::SyntaxError),
            (ErrorCategory::TranspilerGap, "syntax".into())
        );
        assert_eq!(
            map_oracle_category(OracleCategory::LifetimeError),
            (ErrorCategory::TranspilerGap, "lifetime".into())
        );
        assert_eq!(
            map_oracle_category(OracleCategory::TraitBound),
            (ErrorCategory::TranspilerGap, "trait_bound".into())
        );
    }

    #[test]
    #[cfg(feature = "oracle-training")]
    fn test_get_suggestions_invalid_code() {
        let mut classifier = ErrorClassifier::new();
        let error = CompilationError {
            code: "INVALID".to_string(),
            message: "test".to_string(),
            file: PathBuf::from("test.rs"),
            line: 1,
            column: 1,
            ..Default::default()
        };
        let suggestions = classifier.get_suggestions(&error);
        assert!(suggestions.is_empty());
    }

    #[test]
    #[cfg(feature = "oracle-training")]
    fn test_classifier_stats() {
        let classifier = ErrorClassifier::new();
        let stats = classifier.stats();
        assert!(stats.is_some());
    }
}