aprender-core 0.29.2

Next-generation machine learning library in pure Rust
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
pub(crate) use super::*;

// ==================== Test Helpers (reduce DataTransformation repetition) ====================

/// Build a default CITL instance with RustCompiler for testing
fn test_citl() -> CITL {
    CITL::builder()
        .compiler(RustCompiler::new())
        .build()
        .expect("Should build")
}

/// Build a mutable CITL instance with RustCompiler for testing
fn test_citl_mut() -> CITL {
    test_citl()
}

/// Build a CITL instance with custom max_iterations
fn test_citl_with_max_iter(max_iterations: usize) -> CITL {
    CITL::builder()
        .compiler(RustCompiler::new())
        .max_iterations(max_iterations)
        .build()
        .expect("Should build")
}

/// Create a standard E0308 TypeMismatch error code (most common in tests)
fn e0308() -> ErrorCode {
    ErrorCode::new("E0308", ErrorCategory::TypeMismatch, Difficulty::Easy)
}

/// Create a standard compiler diagnostic for testing
fn test_diagnostic(error_code: ErrorCode, message: &str) -> CompilerDiagnostic {
    CompilerDiagnostic::new(
        error_code,
        DiagnosticSeverity::Error,
        message,
        SourceSpan::default(),
    )
}

// ==================== ErrorCode Tests ====================

#[test]
fn test_error_code_new() {
    let code = e0308();
    assert_eq!(code.code, "E0308");
    assert_eq!(code.category, ErrorCategory::TypeMismatch);
    assert_eq!(code.difficulty, Difficulty::Easy);
}

#[test]
fn test_error_code_from_code() {
    let code = ErrorCode::from_code("E0308");
    assert_eq!(code.code, "E0308");
    assert_eq!(code.category, ErrorCategory::Unknown);
    assert_eq!(code.difficulty, Difficulty::Medium);
}

#[test]
fn test_error_code_display() {
    let code = e0308();
    assert_eq!(format!("{code}"), "E0308");
}

/// Helper: create E0382 Ownership/Medium error code (second most common in tests)
fn e0382() -> ErrorCode {
    ErrorCode::new("E0382", ErrorCategory::Ownership, Difficulty::Medium)
}

#[test]
fn test_error_code_equality() {
    let code1 = e0308();
    let code2 = e0308();
    let code3 = e0382();

    assert_eq!(code1, code2);
    assert_ne!(code1, code3);
}

// ==================== Difficulty Tests ====================

#[test]
fn test_difficulty_score() {
    // Data-driven: (variant, expected_score)
    let cases = [
        (Difficulty::Easy, 0.25),
        (Difficulty::Medium, 0.5),
        (Difficulty::Hard, 0.75),
        (Difficulty::Expert, 1.0),
    ];
    for (diff, expected) in &cases {
        assert!(
            (diff.score() - expected).abs() < f32::EPSILON,
            "{diff:?} score mismatch"
        );
    }
}

#[test]
fn test_difficulty_ordering() {
    assert!(Difficulty::Easy < Difficulty::Medium);
    assert!(Difficulty::Medium < Difficulty::Hard);
    assert!(Difficulty::Hard < Difficulty::Expert);
}

// ==================== ErrorCategory Tests ====================

#[test]
fn test_error_category_variants() {
    let categories = [
        ErrorCategory::TypeMismatch,
        ErrorCategory::TraitBound,
        ErrorCategory::Unresolved,
        ErrorCategory::Ownership,
        ErrorCategory::Borrowing,
        ErrorCategory::Lifetime,
        ErrorCategory::Async,
        ErrorCategory::TypeInference,
        ErrorCategory::MethodNotFound,
        ErrorCategory::Import,
        ErrorCategory::Unknown,
    ];
    assert_eq!(categories.len(), 11);
}

// ==================== Language Tests ====================

#[test]
fn test_language_display() {
    // Data-driven: (variant, expected_display)
    let cases = [
        (Language::Python, "Python"),
        (Language::C, "C"),
        (Language::Ruchy, "Ruchy"),
        (Language::Bash, "Bash"),
        (Language::Rust, "Rust"),
    ];
    for (lang, expected) in &cases {
        assert_eq!(format!("{lang}"), *expected);
    }
}

// ==================== CITLConfig Tests ====================

#[test]
fn test_citl_config_default() {
    let config = CITLConfig::default();
    assert_eq!(config.max_iterations, 10);
    assert!((config.confidence_threshold - 0.7).abs() < f32::EPSILON);
    assert!(config.enable_self_training);
}

// ==================== rust_error_codes Tests ====================

#[test]
fn test_rust_error_codes_contains_common_errors() {
    let codes = rust_error_codes();

    // Most common errors from depyler data
    assert!(codes.contains_key("E0308")); // 20.9%
    assert!(codes.contains_key("E0599")); // 17.9%
    assert!(codes.contains_key("E0433")); // 16.4%
    assert!(codes.contains_key("E0432")); // 14.1%
    assert!(codes.contains_key("E0277")); // 11.0%
    assert!(codes.contains_key("E0425")); // 8.2%
    assert!(codes.contains_key("E0282")); // 7.0%
}

/// Helper: assert an error code has the expected category and difficulty
fn assert_error_code(codes: &std::collections::HashMap<String, ErrorCode>, code: &str, cat: ErrorCategory, diff: Difficulty) {
    let ec = codes.get(code).unwrap_or_else(|| panic!("{code} not found"));
    assert_eq!(ec.category, cat, "{code} category mismatch");
    assert_eq!(ec.difficulty, diff, "{code} difficulty mismatch");
}

#[test]
fn test_rust_error_codes_categories_and_difficulties() {
    let codes = rust_error_codes();

    // Data-driven: (code, expected_category, expected_difficulty)
    let expectations: &[(&str, ErrorCategory, Difficulty)] = &[
        ("E0308", ErrorCategory::TypeMismatch, Difficulty::Easy),
        ("E0425", ErrorCategory::Unresolved, Difficulty::Easy),
        ("E0382", ErrorCategory::Ownership, Difficulty::Medium),
        ("E0502", ErrorCategory::Borrowing, Difficulty::Medium),
        ("E0597", ErrorCategory::Lifetime, Difficulty::Hard),
        ("E0277", ErrorCategory::TraitBound, Difficulty::Hard),
        ("E0373", ErrorCategory::Async, Difficulty::Expert),
    ];

    for (code, cat, diff) in expectations {
        assert_error_code(&codes, code, *cat, *diff);
    }
}

// ==================== CITLBuilder Tests ====================

#[test]
fn test_citl_builder_without_compiler_fails() {
    let result = CITL::builder().build();
    assert!(result.is_err());
    if let Err(CITLError::ConfigurationError { message }) = result {
        assert!(message.contains("Compiler interface is required"));
    } else {
        panic!("Expected ConfigurationError");
    }
}

#[test]
fn test_citl_builder_with_compiler_succeeds() {
    let _citl = test_citl();
}

#[test]
fn test_citl_builder_max_iterations() {
    let citl = test_citl_with_max_iter(20);
    assert_eq!(citl.config.max_iterations, 20);
}

#[test]
fn test_citl_builder_confidence_threshold() {
    let citl = CITL::builder()
        .compiler(RustCompiler::new())
        .confidence_threshold(0.9)
        .build()
        .expect("Should build");
    assert!((citl.config.confidence_threshold - 0.9).abs() < f32::EPSILON);
}

// ==================== Iterative Fix Loop Tests ====================

#[test]
fn test_suggested_fix_creation() {
    let fix = SuggestedFix::new(
        "expr.to_string()".to_string(),
        0.85,
        "Convert to String".to_string(),
    );
    assert_eq!(fix.replacement, "expr.to_string()");
    assert!((fix.confidence - 0.85).abs() < f32::EPSILON);
    assert_eq!(fix.description, "Convert to String");
}

#[test]
fn test_fix_result_success() {
    let result = FixResult::success("fixed code".to_string(), 1);
    assert!(result.is_success());
    assert_eq!(result.iterations, 1);
    assert!(result.fixed_source.is_some());
}

#[test]
fn test_fix_result_failure() {
    let result = FixResult::failure(5, vec!["E0308".to_string()]);
    assert!(!result.is_success());
    assert_eq!(result.iterations, 5);
    assert!(result.fixed_source.is_none());
    assert_eq!(result.remaining_errors.len(), 1);
}

#[test]
fn test_suggest_fix_for_valid_code_returns_none() {
    let citl = test_citl();

    let code = "pub fn add(a: i32, b: i32) -> i32 { a + b }";
    let result = citl.compile(code).expect("Should compile");

    // Valid code should have no errors to fix
    assert!(result.is_success());
}

#[test]
fn test_suggest_fix_returns_suggestion_for_error() {
    let mut citl = test_citl_mut();

    // Add a pattern for E0308 type mismatch
    let error_code = e0308();
    let fix = FixTemplate::new("$expr.to_string()", "Convert to String");
    let embedding = ErrorEmbedding::new(vec![0.0; 256], error_code.clone(), 12345);
    citl.pattern_library.add_pattern(embedding, fix);

    // Now suggest_fix should find this pattern for similar errors
    let diag = test_diagnostic(error_code, "mismatched types");

    let suggestion = citl.suggest_fix(&diag, "let x: String = 42;");
    // Should find a suggestion (may or may not match well depending on embedding)
    // The key is that it doesn't panic and returns Some when pattern exists
    assert!(suggestion.is_some() || !citl.pattern_library.is_empty());
}

#[test]
fn test_apply_fix_simple_replacement() {
    let citl = test_citl();

    let source = "let x = 42;";
    let fix = SuggestedFix::new("42_i32".to_string(), 0.9, "Add type suffix".to_string())
        .with_span(8, 10); // Position of "42"

    let result = citl.apply_fix(source, &fix);
    assert_eq!(result, "let x = 42_i32;");
}

#[test]
fn test_apply_fix_preserves_surrounding_code() {
    let citl = test_citl();

    let source = "fn foo() { let x = bar(); }";
    let fix = SuggestedFix::new(
        "bar().unwrap()".to_string(),
        0.8,
        "Unwrap Result".to_string(),
    )
    .with_span(19, 24); // Position of "bar()"

    let result = citl.apply_fix(source, &fix);
    assert_eq!(result, "fn foo() { let x = bar().unwrap(); }");
}

#[test]
fn test_fix_all_valid_code_returns_immediately() {
    let mut citl = test_citl_mut();

    let code = "pub fn add(a: i32, b: i32) -> i32 { a + b }";
    let result = citl.fix_all(code);

    assert!(result.is_success());
    assert_eq!(result.iterations, 0); // No iterations needed
}

#[test]
fn test_fix_all_respects_max_iterations() {
    let mut citl = test_citl_with_max_iter(3);

    // Code with unfixable error (no patterns available)
    let code = "fn main() { let x: String = 42; }";
    let result = citl.fix_all(code);

    // Should stop after max_iterations
    assert!(!result.is_success());
    assert!(result.iterations <= 3);
}

#[test]
fn test_fix_result_tracks_applied_fixes() {
    let result = FixResult::success("fixed".to_string(), 2)
        .with_applied_fix("Fix 1".to_string())
        .with_applied_fix("Fix 2".to_string());

    assert_eq!(result.applied_fixes.len(), 2);
    assert_eq!(result.applied_fixes[0], "Fix 1");
    assert_eq!(result.applied_fixes[1], "Fix 2");
}

// ==================== Integration Tests (Real Compilation) ====================

#[test]
fn test_integration_compile_and_detect_type_error() {
    // Test that we can compile code and detect E0308 type errors
    let compiler = RustCompiler::new();
    let code = "pub fn foo() -> String { 42 }";
    let result = compiler.compile(code, &CompileOptions::default());

    assert!(result.is_ok());
    let compilation = result.expect("Should return result");

    assert!(
        !compilation.is_success(),
        "Code with type error should not compile"
    );
    assert!(compilation.error_count() > 0);

    // Check that we got an E0308 error
    let errors = compilation.errors();
    assert!(!errors.is_empty());
    // E0308 is "mismatched types"
    assert!(
        errors.iter().any(|e| e.code.code == "E0308"),
        "Should have E0308 error"
    );
}

#[test]
fn test_integration_valid_code_compiles() {
    // Test that valid code compiles successfully
    let compiler = RustCompiler::new();
    let code = r#"
pub fn add(a: i32, b: i32) -> i32 {
    a + b
}

pub fn greet(name: &str) -> String {
    format!("Hello, {}!", name)
}
"#;
    let result = compiler.compile(code, &CompileOptions::default());

    assert!(result.is_ok());
    let compilation = result.expect("Should return result");
    assert!(compilation.is_success(), "Valid code should compile");
    assert_eq!(compilation.error_count(), 0);
}

#[test]
fn test_integration_encoder_produces_embeddings() {
    // Test that the error encoder produces valid embeddings
    let encoder = ErrorEncoder::new();
    let diag = test_diagnostic(
        e0308(),
        "mismatched types: expected `String`, found `i32`",
    );

    let source_code = "pub fn foo() -> String { 42 }";
    let embedding = encoder.encode(&diag, source_code);
    assert!(!embedding.vector.is_empty());

    // Embedding should have non-zero values
    let sum: f32 = embedding.vector.iter().sum();
    assert!(sum.abs() > 0.0, "Embedding should have non-zero values");
}

#[path = "tests_pattern_workflow.rs"]
mod tests_pattern_workflow;
#[path = "tests_template_instantiation.rs"]
mod tests_template_instantiation;