aprender-core 0.29.1

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
426
427
428
429
430
431
432
433
434
435
436
437
pub(crate) use super::*;
pub(crate) use crate::citl::diagnostic::DiagnosticSeverity;
pub(crate) use crate::citl::{Difficulty, ErrorCategory};
// ==================== ErrorEmbedding Tests ====================

#[test]
fn test_error_embedding_new() {
    let vector = vec![0.5; 256];
    let code = ErrorCode::new("E0308", ErrorCategory::TypeMismatch, Difficulty::Easy);
    let embedding = ErrorEmbedding::new(vector.clone(), code, 12345);

    assert_eq!(embedding.dim(), 256);
    assert_eq!(embedding.context_hash, 12345);
}

#[test]
fn test_error_embedding_cosine_similarity() {
    let v1 = vec![1.0, 0.0, 0.0, 0.0];
    let v2 = vec![1.0, 0.0, 0.0, 0.0];
    let v3 = vec![0.0, 1.0, 0.0, 0.0];

    let code = ErrorCode::new("E0308", ErrorCategory::TypeMismatch, Difficulty::Easy);

    let e1 = ErrorEmbedding::new(v1, code.clone(), 0);
    let e2 = ErrorEmbedding::new(v2, code.clone(), 0);
    let e3 = ErrorEmbedding::new(v3, code, 0);

    // Same vectors should have similarity 1.0
    assert!((e1.cosine_similarity(&e2) - 1.0).abs() < 0.001);

    // Orthogonal vectors should have similarity 0.0
    assert!(e1.cosine_similarity(&e3).abs() < 0.001);
}

#[test]
fn test_error_embedding_l2_distance() {
    let v1 = vec![0.0, 0.0];
    let v2 = vec![3.0, 4.0];

    let code = ErrorCode::new("E0308", ErrorCategory::TypeMismatch, Difficulty::Easy);

    let e1 = ErrorEmbedding::new(v1, code.clone(), 0);
    let e2 = ErrorEmbedding::new(v2, code, 0);

    // Distance should be 5.0 (3-4-5 triangle)
    assert!((e1.l2_distance(&e2) - 5.0).abs() < 0.001);
}

// ==================== ErrorEncoder Tests ====================

#[test]
fn test_error_encoder_new() {
    let encoder = ErrorEncoder::new();
    assert_eq!(encoder.dim, 256);
}

#[test]
fn test_error_encoder_with_dim() {
    let encoder = ErrorEncoder::with_dim(128);
    assert_eq!(encoder.dim, 128);
}

#[test]
fn test_error_encoder_encode() {
    let encoder = ErrorEncoder::new();
    let code = ErrorCode::new("E0308", ErrorCategory::TypeMismatch, Difficulty::Easy);
    let span = SourceSpan::single_line("test.rs", 10, 5, 20);
    let diagnostic =
        CompilerDiagnostic::new(code, DiagnosticSeverity::Error, "mismatched types", span);

    let source = "fn main() { let x: i32 = \"hello\"; }";
    let embedding = encoder.encode(&diagnostic, source);

    assert_eq!(embedding.dim(), 256);
    assert_eq!(embedding.error_code.code, "E0308");
}

#[test]
fn test_error_encoder_encode_with_types() {
    let encoder = ErrorEncoder::new();
    let code = ErrorCode::new("E0308", ErrorCategory::TypeMismatch, Difficulty::Easy);
    let span = SourceSpan::single_line("test.rs", 10, 5, 20);
    let diagnostic =
        CompilerDiagnostic::new(code, DiagnosticSeverity::Error, "mismatched types", span)
            .with_expected(crate::citl::diagnostic::TypeInfo::new("i32"))
            .with_found(crate::citl::diagnostic::TypeInfo::new("&str"));

    let source = "fn main() { let x: i32 = \"hello\"; }";
    let embedding = encoder.encode(&diagnostic, source);

    assert_eq!(embedding.dim(), 256);
    // Type features should be populated
    let type_region: f32 = embedding.vector[128..192].iter().sum();
    assert!(type_region > 0.0);
}

#[test]
fn test_error_encoder_similar_errors_similar_embeddings() {
    let encoder = ErrorEncoder::new();

    // Two similar type mismatch errors
    let code = ErrorCode::new("E0308", ErrorCategory::TypeMismatch, Difficulty::Easy);
    let span1 = SourceSpan::single_line("test.rs", 10, 5, 20);
    let span2 = SourceSpan::single_line("test.rs", 20, 5, 20);

    let diag1 = CompilerDiagnostic::new(
        code.clone(),
        DiagnosticSeverity::Error,
        "mismatched types",
        span1,
    );
    let diag2 = CompilerDiagnostic::new(code, DiagnosticSeverity::Error, "mismatched types", span2);

    let source1 = "fn main() { let x: i32 = \"hello\"; }";
    let source2 = "fn foo() { let y: i32 = \"world\"; }";

    let e1 = encoder.encode(&diag1, source1);
    let e2 = encoder.encode(&diag2, source2);

    // Same error type should have high similarity
    let similarity = e1.cosine_similarity(&e2);
    assert!(
        similarity > 0.5,
        "Similar errors should have similarity > 0.5, got {similarity}"
    );
}

#[test]
fn test_error_encoder_different_errors_different_embeddings() {
    let encoder = ErrorEncoder::new();

    let code1 = ErrorCode::new("E0308", ErrorCategory::TypeMismatch, Difficulty::Easy);
    let code2 = ErrorCode::new("E0382", ErrorCategory::Ownership, Difficulty::Medium);
    let span = SourceSpan::single_line("test.rs", 10, 5, 20);

    let diag1 = CompilerDiagnostic::new(
        code1,
        DiagnosticSeverity::Error,
        "mismatched types",
        span.clone(),
    );
    let diag2 = CompilerDiagnostic::new(
        code2,
        DiagnosticSeverity::Error,
        "borrow of moved value",
        span,
    );

    let source = "fn main() {}";

    let e1 = encoder.encode(&diag1, source);
    let e2 = encoder.encode(&diag2, source);

    // Different error types should have lower similarity
    let similarity = e1.cosine_similarity(&e2);
    assert!(
        similarity < 0.9,
        "Different errors should have similarity < 0.9, got {similarity}"
    );
}

// ==================== ProgramFeedbackGraph Tests ====================

#[test]
fn test_program_feedback_graph_new() {
    let graph = ProgramFeedbackGraph::new();
    assert_eq!(graph.num_nodes(), 0);
    assert_eq!(graph.num_edges(), 0);
}

#[test]
fn test_program_feedback_graph_add_node() {
    let mut graph = ProgramFeedbackGraph::new();
    let features = vec![1.0, 2.0, 3.0];
    let idx = graph.add_node(NodeType::Ast, features);

    assert_eq!(idx, 0);
    assert_eq!(graph.num_nodes(), 1);
}

#[test]
fn test_program_feedback_graph_add_edge() {
    let mut graph = ProgramFeedbackGraph::new();
    graph.add_node(NodeType::Ast, vec![1.0]);
    graph.add_node(NodeType::Diagnostic, vec![2.0]);
    graph.add_edge(0, 1, EdgeType::DiagnosticRefers);

    assert_eq!(graph.num_edges(), 1);
    assert_eq!(graph.edges[0], (0, 1));
    assert_eq!(graph.edge_types[0], EdgeType::DiagnosticRefers);
}

#[test]
fn test_program_feedback_graph_complex() {
    let mut graph = ProgramFeedbackGraph::new();

    // Add AST nodes
    let ast1 = graph.add_node(NodeType::Ast, vec![1.0, 0.0]);
    let ast2 = graph.add_node(NodeType::Ast, vec![0.0, 1.0]);

    // Add diagnostic node
    let diag = graph.add_node(NodeType::Diagnostic, vec![1.0, 1.0]);

    // Add type nodes
    let expected = graph.add_node(NodeType::ExpectedType, vec![1.0, 0.0]);
    let found = graph.add_node(NodeType::FoundType, vec![0.0, 1.0]);

    // Add edges
    graph.add_edge(ast1, ast2, EdgeType::AstChild);
    graph.add_edge(diag, ast2, EdgeType::DiagnosticRefers);
    graph.add_edge(diag, expected, EdgeType::Expects);
    graph.add_edge(diag, found, EdgeType::Found);

    assert_eq!(graph.num_nodes(), 5);
    assert_eq!(graph.num_edges(), 4);
}

// ==================== NodeType and EdgeType Tests ====================

#[test]
fn test_node_types() {
    let types = [
        NodeType::Ast,
        NodeType::Diagnostic,
        NodeType::ExpectedType,
        NodeType::FoundType,
        NodeType::Suggestion,
    ];
    assert_eq!(types.len(), 5);
}

#[test]
fn test_edge_types() {
    let types = [
        EdgeType::AstChild,
        EdgeType::DataFlow,
        EdgeType::ControlFlow,
        EdgeType::DiagnosticRefers,
        EdgeType::Expects,
        EdgeType::Found,
    ];
    assert_eq!(types.len(), 6);
}

// ==================== GNNErrorEncoder Tests ====================

#[test]
fn test_gnn_encoder_new() {
    let encoder = GNNErrorEncoder::new(64, 256);
    assert_eq!(encoder.output_dim(), 256);
}

#[test]
fn test_gnn_encoder_default_config() {
    let encoder = GNNErrorEncoder::default_config();
    assert_eq!(encoder.output_dim(), 256);
}

#[test]
fn test_gnn_encoder_default_trait() {
    let encoder = GNNErrorEncoder::default();
    assert_eq!(encoder.output_dim(), 256);
}

#[test]
fn test_gnn_encoder_build_graph() {
    let encoder = GNNErrorEncoder::new(32, 128);
    let code = ErrorCode::new("E0308", ErrorCategory::TypeMismatch, Difficulty::Easy);
    let span = SourceSpan::single_line("test.rs", 10, 5, 20);
    let diagnostic =
        CompilerDiagnostic::new(code, DiagnosticSeverity::Error, "mismatched types", span);

    let source = "fn main() { let x: i32 = \"hello\"; }";
    let graph = encoder.build_graph(&diagnostic, source);

    // Should have at least 1 node (diagnostic)
    assert!(graph.num_nodes() >= 1);
    // Should have diagnostic node
    assert!(graph.node_types.contains(&NodeType::Diagnostic));
}

#[test]
fn test_gnn_encoder_build_graph_with_types() {
    let encoder = GNNErrorEncoder::new(32, 128);
    let code = ErrorCode::new("E0308", ErrorCategory::TypeMismatch, Difficulty::Easy);
    let span = SourceSpan::single_line("test.rs", 10, 5, 20);
    let diagnostic =
        CompilerDiagnostic::new(code, DiagnosticSeverity::Error, "mismatched types", span)
            .with_expected(crate::citl::diagnostic::TypeInfo::new("i32"))
            .with_found(crate::citl::diagnostic::TypeInfo::new("&str"));

    let source = "fn main() { let x: i32 = \"hello\"; }";
    let graph = encoder.build_graph(&diagnostic, source);

    // Should have expected and found type nodes
    assert!(graph.node_types.contains(&NodeType::ExpectedType));
    assert!(graph.node_types.contains(&NodeType::FoundType));
    // Should have edges to type nodes
    assert!(graph.num_edges() >= 2);
}

#[test]
fn test_gnn_encoder_encode_graph() {
    let encoder = GNNErrorEncoder::new(32, 128);
    let code = ErrorCode::new("E0308", ErrorCategory::TypeMismatch, Difficulty::Easy);
    let span = SourceSpan::single_line("test.rs", 10, 5, 20);
    let diagnostic =
        CompilerDiagnostic::new(code, DiagnosticSeverity::Error, "mismatched types", span);

    let source = "fn main() { let x: i32 = \"hello\"; }";
    let graph = encoder.build_graph(&diagnostic, source);
    let embedding = encoder.encode_graph(&graph);

    // Should produce correct dimension
    assert_eq!(embedding.dim(), 128);
    // Should be normalized (unit length)
    let norm: f32 = embedding.vector.iter().map(|x| x * x).sum::<f32>().sqrt();
    assert!(
        (norm - 1.0).abs() < 0.01,
        "Embedding should be normalized, got norm {}",
        norm
    );
}

#[test]
fn test_gnn_encoder_encode_convenience() {
    let encoder = GNNErrorEncoder::new(32, 128);
    let code = ErrorCode::new("E0308", ErrorCategory::TypeMismatch, Difficulty::Easy);
    let span = SourceSpan::single_line("test.rs", 10, 5, 20);
    let diagnostic =
        CompilerDiagnostic::new(code, DiagnosticSeverity::Error, "mismatched types", span);

    let source = "fn main() { let x: i32 = \"hello\"; }";
    let embedding = encoder.encode(&diagnostic, source);

    assert_eq!(embedding.dim(), 128);
}

#[test]
fn test_gnn_encoder_empty_graph() {
    let encoder = GNNErrorEncoder::new(32, 128);
    let graph = ProgramFeedbackGraph::new();
    let embedding = encoder.encode_graph(&graph);

    // Should return zero embedding for empty graph
    assert_eq!(embedding.dim(), 128);
    assert!(embedding.vector.iter().all(|&x| x == 0.0));
}

#[test]
fn test_gnn_encoder_similar_errors_similar_embeddings() {
    let encoder = GNNErrorEncoder::new(32, 128);

    // Two similar type mismatch errors
    let code = ErrorCode::new("E0308", ErrorCategory::TypeMismatch, Difficulty::Easy);
    let span1 = SourceSpan::single_line("test.rs", 10, 5, 20);
    let span2 = SourceSpan::single_line("test.rs", 20, 5, 20);

    let diag1 = CompilerDiagnostic::new(
        code.clone(),
        DiagnosticSeverity::Error,
        "mismatched types",
        span1,
    );
    let diag2 = CompilerDiagnostic::new(code, DiagnosticSeverity::Error, "mismatched types", span2);

    let source1 = "fn main() { let x: i32 = \"hello\"; }";
    let source2 = "fn foo() { let y: i32 = \"world\"; }";

    let e1 = encoder.encode(&diag1, source1);
    let e2 = encoder.encode(&diag2, source2);

    // Same error type should have non-negative similarity
    let similarity = e1.cosine_similarity(&e2);
    assert!(
        similarity > 0.0,
        "Similar errors should have positive similarity, got {}",
        similarity
    );
}

#[test]
fn test_gnn_encoder_different_categories() {
    let encoder = GNNErrorEncoder::new(32, 128);

    let code1 = ErrorCode::new("E0308", ErrorCategory::TypeMismatch, Difficulty::Easy);
    let code2 = ErrorCode::new("E0382", ErrorCategory::Ownership, Difficulty::Medium);
    let span = SourceSpan::single_line("test.rs", 10, 5, 20);

    let diag1 = CompilerDiagnostic::new(
        code1,
        DiagnosticSeverity::Error,
        "mismatched types",
        span.clone(),
    );
    let diag2 = CompilerDiagnostic::new(
        code2,
        DiagnosticSeverity::Error,
        "borrow of moved value",
        span,
    );

    let source = "fn main() { let x = 5; }";

    let e1 = encoder.encode(&diag1, source);
    let e2 = encoder.encode(&diag2, source);

    // Should produce different embeddings
    let diff: f32 = e1
        .vector
        .iter()
        .zip(e2.vector.iter())
        .map(|(a, b)| (a - b).abs())
        .sum();
    assert!(
        diff > 0.1,
        "Different error categories should have different embeddings"
    );
}

#[test]
fn test_gnn_encoder_tokenize_rust() {
    let tokens = GNNErrorEncoder::tokenize_rust("let x: i32 = 5;");
    assert!(!tokens.is_empty());
    assert!(tokens.contains(&"let".to_string()));
}

#[test]
fn test_gnn_encoder_tokenize_rust_complex() {
    let tokens = GNNErrorEncoder::tokenize_rust("fn foo<T: Clone>(x: &mut T) -> Result<(), Error>");
    assert!(tokens.contains(&"fn".to_string()));
    // Should capture punctuation
    assert!(tokens.iter().any(|t| t.contains('<') || t == "<"));
}

#[path = "tests_gnn_encoder.rs"]
mod tests_gnn_encoder;