decy-core 1.0.1

Core transpilation pipeline for C-to-Rust conversion
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
//! NULL Pointer Safety Integration Tests
//!
//! **RED PHASE**: Comprehensive tests for C NULL pointers → Safe Rust
//!
//! This validates that dangerous C NULL pointer patterns are transpiled
//! to safe Rust with proper checking and Option<T> usage.
//!
//! **Pattern**: EXTREME TDD - Test-First Development
//! **Reference**: ISO C99 §6.3.2.3 (Null pointer constant)
//!
//! **Safety Goal**: <50 unsafe blocks per 1000 LOC
//! **Validation**: No NULL dereference, proper checking, Option<T> where possible

use decy_core::transpile;

// ============================================================================
// RED PHASE: NULL Pointer Checks
// ============================================================================

#[test]
fn test_null_pointer_check() {
    // Basic NULL check pattern
    let c_code = r#"
        #include <stdlib.h>

        int main() {
            int* ptr = (int*)malloc(sizeof(int));

            if (ptr == 0) {
                return 1;  // Allocation failed
            }

            *ptr = 42;
            free(ptr);
            return 0;
        }
    "#;

    let result = transpile(c_code).expect("Should transpile");

    assert!(result.contains("fn main"), "Should have main function");

    let unsafe_count = result.matches("unsafe").count();
    assert!(
        unsafe_count <= 4,
        "NULL check should minimize unsafe (found {})",
        unsafe_count
    );
}

#[test]
fn test_null_pointer_comparison() {
    // Compare pointer against NULL
    let c_code = r#"
        int main() {
            int value = 42;
            int* ptr = &value;

            if (ptr != 0) {
                return *ptr;
            }

            return 0;
        }
    "#;

    let result = transpile(c_code).expect("Should transpile");

    assert!(result.contains("fn main"), "Should have main function");

    let unsafe_count = result.matches("unsafe").count();
    assert!(
        unsafe_count <= 3,
        "NULL comparison should minimize unsafe (found {})",
        unsafe_count
    );
}

#[test]
fn test_null_pointer_initialization() {
    // Initialize pointer to NULL
    let c_code = r#"
        int main() {
            int* ptr = 0;  // NULL

            if (ptr == 0) {
                return 1;
            }

            return 0;
        }
    "#;

    let result = transpile(c_code).expect("Should transpile");

    assert!(result.contains("fn main"), "Should have main function");

    let unsafe_count = result.matches("unsafe").count();
    assert!(
        unsafe_count <= 2,
        "NULL initialization should minimize unsafe (found {})",
        unsafe_count
    );
}

// ============================================================================
// RED PHASE: Function Return NULL
// ============================================================================

#[test]
fn test_function_return_null() {
    // Function returns NULL on failure
    let c_code = r#"
        int* create_value(int condition) {
            if (condition == 0) {
                return 0;  // NULL
            }

            int* ptr = (int*)malloc(sizeof(int));
            *ptr = 42;
            return ptr;
        }

        int main() {
            int* value = create_value(1);

            if (value != 0) {
                int result = *value;
                free(value);
                return result;
            }

            return 0;
        }
    "#;

    let result = transpile(c_code).expect("Should transpile");

    assert!(result.contains("fn main"), "Should have main function");
    assert!(
        result.contains("fn create_value"),
        "Should have create_value function"
    );

    let unsafe_count = result.matches("unsafe").count();
    assert!(
        unsafe_count <= 6,
        "Function returning NULL should minimize unsafe (found {})",
        unsafe_count
    );
}

// ============================================================================
// RED PHASE: NULL Pointer in Structs
// ============================================================================

#[test]
fn test_null_pointer_in_struct() {
    // Struct with nullable pointer field
    let c_code = r#"
        struct Node {
            int value;
            struct Node* next;
        };

        int main() {
            struct Node node;
            node.value = 42;
            node.next = 0;  // NULL

            if (node.next == 0) {
                return node.value;
            }

            return 0;
        }
    "#;

    let result = transpile(c_code).expect("Should transpile");

    assert!(result.contains("fn main"), "Should have main function");

    let unsafe_count = result.matches("unsafe").count();
    assert!(
        unsafe_count <= 3,
        "NULL in struct should minimize unsafe (found {})",
        unsafe_count
    );
}

// ============================================================================
// RED PHASE: Array of Pointers with NULL
// ============================================================================

#[test]
fn test_null_in_pointer_array() {
    // Array of pointers with NULL sentinel
    let c_code = r#"
        int main() {
            int a = 1, b = 2, c = 3;
            int* array[4] = {&a, &b, &c, 0};  // NULL terminated

            int sum = 0;
            for (int i = 0; array[i] != 0; i++) {
                sum += *array[i];
            }

            return sum;
        }
    "#;

    let result = transpile(c_code).expect("Should transpile");

    assert!(result.contains("fn main"), "Should have main function");

    let unsafe_count = result.matches("unsafe").count();
    assert!(
        unsafe_count <= 6,
        "NULL in array should minimize unsafe (found {})",
        unsafe_count
    );
}

// ============================================================================
// RED PHASE: Defensive NULL Checks
// ============================================================================

#[test]
fn test_defensive_null_check() {
    // Defensive programming with NULL checks
    let c_code = r#"
        int safe_deref(int* ptr) {
            if (ptr == 0) {
                return -1;  // Error code
            }
            return *ptr;
        }

        int main() {
            int value = 42;
            int result = safe_deref(&value);

            return result;
        }
    "#;

    let result = transpile(c_code).expect("Should transpile");

    assert!(result.contains("fn main"), "Should have main function");
    assert!(
        result.contains("fn safe_deref"),
        "Should have safe_deref function"
    );

    let unsafe_count = result.matches("unsafe").count();
    assert!(
        unsafe_count <= 4,
        "Defensive NULL check should minimize unsafe (found {})",
        unsafe_count
    );
}

// ============================================================================
// RED PHASE: NULL Coalescing Pattern
// ============================================================================

#[test]
fn test_null_coalescing() {
    // Use default value if NULL
    let c_code = r#"
        int main() {
            int* ptr = 0;
            int value = (ptr != 0) ? *ptr : 42;

            return value;
        }
    "#;

    let result = transpile(c_code).expect("Should transpile");

    assert!(result.contains("fn main"), "Should have main function");

    let unsafe_count = result.matches("unsafe").count();
    assert!(
        unsafe_count <= 3,
        "NULL coalescing should minimize unsafe (found {})",
        unsafe_count
    );
}

// ============================================================================
// RED PHASE: String NULL Checks
// ============================================================================

#[test]
fn test_string_null_check() {
    // Check string pointer before use
    let c_code = r#"
        #include <string.h>

        int safe_strlen(const char* str) {
            if (str == 0) {
                return 0;
            }
            return strlen(str);
        }

        int main() {
            const char* text = "Hello";
            int len = safe_strlen(text);

            return len;
        }
    "#;

    let result = transpile(c_code).expect("Should transpile");

    assert!(result.contains("fn main"), "Should have main function");

    let unsafe_count = result.matches("unsafe").count();
    assert!(
        unsafe_count <= 4,
        "String NULL check should minimize unsafe (found {})",
        unsafe_count
    );
}

// ============================================================================
// RED PHASE: Multiple NULL Checks
// ============================================================================

#[test]
fn test_multiple_null_checks() {
    // Chain of NULL checks
    let c_code = r#"
        #include <stdlib.h>

        int main() {
            int* a = (int*)malloc(sizeof(int));
            int* b = (int*)malloc(sizeof(int));

            if (a == 0 || b == 0) {
                if (a != 0) free(a);
                if (b != 0) free(b);
                return 1;
            }

            *a = 10;
            *b = 20;
            int result = *a + *b;

            free(a);
            free(b);

            return result;
        }
    "#;

    let result = transpile(c_code).expect("Should transpile");

    assert!(result.contains("fn main"), "Should have main function");

    let unsafe_count = result.matches("unsafe").count();
    assert!(
        unsafe_count <= 8,
        "Multiple NULL checks should minimize unsafe (found {})",
        unsafe_count
    );
}

// ============================================================================
// RED PHASE: NULL Pointer Assignment
// ============================================================================

#[test]
fn test_null_pointer_assignment() {
    // Set pointer to NULL after free
    let c_code = r#"
        #include <stdlib.h>

        int main() {
            int* ptr = (int*)malloc(sizeof(int));

            if (ptr != 0) {
                *ptr = 42;
                free(ptr);
                ptr = 0;  // Set to NULL after free
            }

            if (ptr == 0) {
                return 1;  // Success
            }

            return 0;
        }
    "#;

    let result = transpile(c_code).expect("Should transpile");

    assert!(result.contains("fn main"), "Should have main function");

    let unsafe_count = result.matches("unsafe").count();
    assert!(
        unsafe_count <= 5,
        "NULL assignment should minimize unsafe (found {})",
        unsafe_count
    );
}

// ============================================================================
// RED PHASE: Conditional NULL Dereference
// ============================================================================

#[test]
fn test_conditional_null_dereference() {
    // Only dereference if not NULL
    let c_code = r#"
        int main() {
            int value = 42;
            int* ptr = &value;
            int result = 0;

            if (ptr != 0 && *ptr > 0) {
                result = *ptr;
            }

            return result;
        }
    "#;

    let result = transpile(c_code).expect("Should transpile");

    assert!(result.contains("fn main"), "Should have main function");

    let unsafe_count = result.matches("unsafe").count();
    assert!(
        unsafe_count <= 4,
        "Conditional dereference should minimize unsafe (found {})",
        unsafe_count
    );
}

// ============================================================================
// RED PHASE: Unsafe Density Target
// ============================================================================

#[test]
fn test_unsafe_block_count_target() {
    // CRITICAL: Validate overall unsafe minimization for NULL checks
    let c_code = r#"
        #include <stdlib.h>

        int* allocate_array(int size) {
            if (size <= 0) {
                return 0;  // NULL
            }
            return (int*)malloc(sizeof(int) * size);
        }

        int main() {
            int* array = allocate_array(10);

            if (array == 0) {
                return 1;  // Allocation failed
            }

            // Initialize array
            for (int i = 0; i < 10; i++) {
                array[i] = i;
            }

            // Sum array
            int sum = 0;
            for (int i = 0; i < 10; i++) {
                sum += array[i];
            }

            free(array);
            return sum;
        }
    "#;

    let result = transpile(c_code).expect("Should transpile");

    // Count unsafe blocks and calculate density
    let unsafe_count = result.matches("unsafe").count();
    let lines_of_code = result.lines().count();

    let unsafe_per_1000 = if lines_of_code > 0 {
        (unsafe_count as f64 / lines_of_code as f64) * 1000.0
    } else {
        0.0
    };

    // Target: <=100 unsafe per 1000 LOC for NULL checks
    assert!(
        unsafe_per_1000 <= 100.0,
        "NULL checks should minimize unsafe (got {:.2} per 1000 LOC, want <=100)",
        unsafe_per_1000
    );

    // Should have main function
    assert!(result.contains("fn main"), "Should generate main function");
}

// ============================================================================
// RED PHASE: Compilation and Correctness
// ============================================================================

#[test]
fn test_transpiled_null_checks_compile() {
    // Generated Rust should have valid syntax
    let c_code = r#"
        #include <stdlib.h>

        int main() {
            int* ptr = (int*)malloc(sizeof(int));

            if (ptr != 0) {
                *ptr = 42;
                free(ptr);
            }

            return 0;
        }
    "#;

    let result = transpile(c_code).expect("Should transpile");

    // Basic syntax validation
    assert!(!result.is_empty(), "Should generate non-empty code");
    assert!(result.contains("fn main"), "Should have main function");

    // Should not have obvious syntax errors
    let open_braces = result.matches('{').count();
    let close_braces = result.matches('}').count();
    assert_eq!(
        open_braces, close_braces,
        "Braces should be balanced: {} open, {} close",
        open_braces, close_braces
    );
}

#[test]
fn test_null_safety_documentation() {
    // Validate generated code quality
    let c_code = r#"
        int main() {
            int* ptr = 0;

            if (ptr == 0) {
                return 1;
            }

            return 0;
        }
    "#;

    let result = transpile(c_code).expect("Should transpile");

    // Generated code should be reasonable
    assert!(result.contains("fn main"), "Should have main function");

    // If unsafe blocks exist, they should be minimal
    let unsafe_count = result.matches("unsafe").count();
    assert!(
        unsafe_count < 10,
        "Should have minimal unsafe blocks (found {})",
        unsafe_count
    );
}