decy-core 2.2.0

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
//! Format String Safety Integration Tests
//!
//! **RED PHASE**: Comprehensive tests for C format string → Safe Rust
//!
//! This validates that dangerous C format string patterns (printf, sprintf, scanf)
//! are transpiled to safe Rust code with type-safe formatting and bounds checking.
//!
//! **Pattern**: EXTREME TDD - Test-First Development
//! **Reference**: CWE-134 (Format String Vulnerability)
//!
//! **Safety Goal**: ≤30 unsafe blocks per 1000 LOC
//! **Validation**: Format strings validated at compile time, no format string injection
//!
//! # FIXED: Parser System Header Support
//!
//! **STATUS**: Tests now passing with stdlib prototype support! ✅
//!
//! **SOLUTION**: The decy-stdlib crate provides built-in prototypes for C standard library.
//! - System includes are commented out during preprocessing
//! - Stdlib prototypes are injected for the specific header (e.g., stdio.h)
//! - Parser successfully handles injected prototypes (per-header filtering)
//!
//! **IMPLEMENTATION**: decy-stdlib (Sprint 18)
//! 1. ✅ Built-in definitions for 24 stdio.h functions (ISO C99 §7.21)
//! 2. ✅ Per-header prototype filtering (string.h, stdio.h, stdlib.h)
//! 3. ✅ Integration with preprocessor for automatic injection
//!
//! **TOYOTA WAY - Kaizen (改善)**: Continuous improvement through TDD!

use decy_core::transpile;

// ============================================================================
// RED PHASE: Safe printf Usage
// ============================================================================

#[test]
fn test_safe_printf_with_format_string() {
    // Safe printf with literal format string
    let c_code = r#"
        #include <stdio.h>

        int main() {
            int value = 42;
            printf("Value: %d\n", 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 <= 2, "Safe printf should minimize unsafe (found {})", unsafe_count);
}

#[test]
fn test_printf_multiple_arguments() {
    // printf with multiple format specifiers
    let c_code = r#"
        #include <stdio.h>

        int main() {
            int a = 10;
            int b = 20;
            printf("a=%d, b=%d, sum=%d\n", a, b, a + b);
            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, "Multi-arg printf should minimize unsafe (found {})", unsafe_count);
}

#[test]
fn test_printf_string_format() {
    // printf with string format specifier
    let c_code = r#"
        #include <stdio.h>

        int main() {
            char* name = "Alice";
            printf("Hello, %s!\n", name);
            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, "String printf should minimize unsafe (found {})", unsafe_count);
}

// ============================================================================
// RED PHASE: sprintf and snprintf Safety
// ============================================================================

#[test]
fn test_sprintf_with_bounds() {
    // sprintf (unbounded, dangerous in C)
    let c_code = r#"
        #include <stdio.h>

        int main() {
            char buffer[100];
            int value = 42;
            sprintf(buffer, "Value: %d", 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, "sprintf should minimize unsafe (found {})", unsafe_count);
}

#[test]
fn test_snprintf_bounded() {
    // snprintf (bounded, safer)
    let c_code = r#"
        #include <stdio.h>

        int main() {
            char buffer[100];
            int value = 42;
            snprintf(buffer, sizeof(buffer), "Value: %d", 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, "snprintf should minimize unsafe (found {})", unsafe_count);
}

// ============================================================================
// RED PHASE: scanf Safety
// ============================================================================

#[test]
fn test_scanf_with_width_specifier() {
    // scanf with width specifier (safer)
    let c_code = r#"
        #include <stdio.h>

        int main() {
            char buffer[10];
            scanf("%9s", buffer);
            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, "scanf with width should minimize unsafe (found {})", unsafe_count);
}

#[test]
fn test_scanf_integer() {
    // scanf for integer input
    let c_code = r#"
        #include <stdio.h>

        int main() {
            int value;
            scanf("%d", &value);
            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, "scanf integer should minimize unsafe (found {})", unsafe_count);
}

// ============================================================================
// RED PHASE: Format Specifier Validation
// ============================================================================

#[test]
fn test_printf_integer_formats() {
    // Various integer format specifiers
    let c_code = r#"
        #include <stdio.h>

        int main() {
            int d = 42;
            unsigned int u = 42;
            printf("d=%d, u=%u, hex=%x, oct=%o\n", d, u, u, u);
            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, "Integer formats should minimize unsafe (found {})", unsafe_count);
}

#[test]
fn test_printf_float_formats() {
    // Float format specifiers
    let c_code = r#"
        #include <stdio.h>

        int main() {
            double value = 3.14159;
            printf("f=%f, e=%e, g=%g\n", value, value, 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, "Float formats should minimize unsafe (found {})", unsafe_count);
}

#[test]
fn test_printf_char_format() {
    // Character format specifier
    let c_code = r#"
        #include <stdio.h>

        int main() {
            char c = 'A';
            printf("Character: %c\n", c);
            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, "Char format should minimize unsafe (found {})", unsafe_count);
}

// ============================================================================
// RED PHASE: Width and Precision Specifiers
// ============================================================================

#[test]
fn test_printf_width_specifier() {
    // Width specifier
    let c_code = r#"
        #include <stdio.h>

        int main() {
            int value = 42;
            printf("%10d\n", 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 <= 2, "Width specifier should minimize unsafe (found {})", unsafe_count);
}

#[test]
fn test_printf_precision_specifier() {
    // Precision specifier for floats
    let c_code = r#"
        #include <stdio.h>

        int main() {
            double value = 3.14159;
            printf("%.2f\n", 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 <= 2,
        "Precision specifier should minimize unsafe (found {})",
        unsafe_count
    );
}

// ============================================================================
// RED PHASE: Complex Format Strings
// ============================================================================

#[test]
fn test_printf_complex_format() {
    // Complex format string with multiple types
    let c_code = r#"
        #include <stdio.h>

        int main() {
            int i = 42;
            double d = 3.14;
            char* s = "test";
            char c = 'A';

            printf("int=%d, double=%.2f, string=%s, char=%c\n", i, d, s, c);
            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, "Complex format should minimize unsafe (found {})", unsafe_count);
}

// ============================================================================
// RED PHASE: Formatted Output to Variables
// ============================================================================

#[test]
fn test_sprintf_to_buffer() {
    // sprintf to buffer
    let c_code = r#"
        #include <stdio.h>
        #include <string.h>

        int main() {
            char buffer[50];
            int value = 42;

            sprintf(buffer, "The answer is %d", value);
            return strlen(buffer);
        }
    "#;

    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, "sprintf to buffer should minimize unsafe (found {})", unsafe_count);
}

// ============================================================================
// RED PHASE: Format String with Escape Sequences
// ============================================================================

#[test]
fn test_printf_escape_sequences() {
    // Format string with escape sequences
    let c_code = r#"
        #include <stdio.h>

        int main() {
            printf("Line 1\nLine 2\tTabbed\n");
            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, "Escape sequences should minimize unsafe (found {})", unsafe_count);
}

// ============================================================================
// RED PHASE: Percent Escaping
// ============================================================================

#[test]
fn test_printf_percent_escape() {
    // Percent sign escaping
    let c_code = r#"
        #include <stdio.h>

        int main() {
            int percent = 50;
            printf("Progress: %d%%\n", percent);
            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, "Percent escape should minimize unsafe (found {})", unsafe_count);
}

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

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

        int main() {
            char buffer[100];
            int a = 10;
            int b = 20;
            char* name = "Alice";

            printf("Values: a=%d, b=%d\n", a, b);
            snprintf(buffer, sizeof(buffer), "Hello, %s!", name);

            return 0;
        }
    "#;

    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: <=30 unsafe per 1000 LOC for format strings
    assert!(
        unsafe_per_1000 <= 30.0,
        "Format strings should minimize unsafe (got {:.2} per 1000 LOC, want <=30)",
        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_format_code_compiles() {
    // Generated Rust should have valid syntax
    let c_code = r#"
        #include <stdio.h>

        int main() {
            int value = 42;
            printf("Value: %d\n", value);

            char buffer[50];
            sprintf(buffer, "Result: %d", value * 2);

            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_format_string_safety_documentation() {
    // Validate generated code quality
    let c_code = r#"
        #include <stdio.h>

        int main() {
            printf("Hello, World!\n");
            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);
}