decy-analyzer 2.2.0

Static analysis and type inference for C code
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
//! Tests for output parameter detection.
//!
//! These tests verify that we can detect C output parameters and transform them
//! to idiomatic Rust return values.

use decy_analyzer::output_params::{OutputParamDetector, ParameterKind};
use decy_hir::{BinaryOperator, HirExpression, HirFunction, HirParameter, HirStatement, HirType};

/// Helper: Create a simple function for testing
fn create_test_function(
    name: &str,
    params: Vec<HirParameter>,
    return_type: HirType,
    body: Vec<HirStatement>,
) -> HirFunction {
    HirFunction::new_with_body(name.to_string(), return_type, params, body)
}

/// Helper: Create a pointer parameter
fn create_pointer_param(name: &str) -> HirParameter {
    HirParameter::new(name.to_string(), HirType::Pointer(Box::new(HirType::Int)))
}

/// Helper: Create a char pointer parameter (for strings)
fn create_char_pointer_param(name: &str) -> HirParameter {
    HirParameter::new(name.to_string(), HirType::Pointer(Box::new(HirType::Char)))
}

// ============================================================================
// TEST 1: Basic output parameter detection (write-before-read)
// ============================================================================

#[test]
fn test_detect_simple_output_parameter() {
    // C code:
    // int parse(const char* input, int* result) {
    //     *result = 42;  // Write before read
    //     return 0;      // Success
    // }

    let func = create_test_function(
        "parse",
        vec![create_char_pointer_param("input"), create_pointer_param("result")],
        HirType::Int,
        vec![
            // *result = 42
            HirStatement::DerefAssignment {
                target: HirExpression::Variable("result".to_string()),
                value: HirExpression::IntLiteral(42),
            },
            // return 0
            HirStatement::Return(Some(HirExpression::IntLiteral(0))),
        ],
    );

    let detector = OutputParamDetector::new();
    let output_params = detector.detect(&func);

    assert_eq!(output_params.len(), 1);
    assert_eq!(output_params[0].name, "result");
    assert_eq!(output_params[0].kind, ParameterKind::Output);
    assert!(output_params[0].is_fallible);
}

// ============================================================================
// TEST 2: Distinguish input parameters (read-before-write)
// ============================================================================

#[test]
fn test_input_parameter_not_detected_as_output() {
    // C code:
    // int increment(int* value) {
    //     int old = *value;  // Read before write
    //     *value = old + 1;
    //     return 0;
    // }

    let func = create_test_function(
        "increment",
        vec![create_pointer_param("value")],
        HirType::Int,
        vec![
            // int old = *value
            HirStatement::VariableDeclaration {
                name: "old".to_string(),
                var_type: HirType::Int,
                initializer: Some(HirExpression::Dereference(Box::new(HirExpression::Variable(
                    "value".to_string(),
                )))),
            },
            // *value = old + 1
            HirStatement::DerefAssignment {
                target: HirExpression::Variable("value".to_string()),
                value: HirExpression::BinaryOp {
                    op: BinaryOperator::Add,
                    left: Box::new(HirExpression::Variable("old".to_string())),
                    right: Box::new(HirExpression::IntLiteral(1)),
                },
            },
            HirStatement::Return(Some(HirExpression::IntLiteral(0))),
        ],
    );

    let detector = OutputParamDetector::new();
    let output_params = detector.detect(&func);

    // Should be classified as input-output, not pure output
    assert_eq!(output_params.len(), 0);
}

// ============================================================================
// TEST 3: Multiple output parameters
// ============================================================================

#[test]
fn test_multiple_output_parameters() {
    // C code:
    // int parse_coords(const char* input, int* x, int* y) {
    //     *x = 10;
    //     *y = 20;
    //     return 0;
    // }

    let func = create_test_function(
        "parse_coords",
        vec![
            create_char_pointer_param("input"),
            create_pointer_param("x"),
            create_pointer_param("y"),
        ],
        HirType::Int,
        vec![
            HirStatement::DerefAssignment {
                target: HirExpression::Variable("x".to_string()),
                value: HirExpression::IntLiteral(10),
            },
            HirStatement::DerefAssignment {
                target: HirExpression::Variable("y".to_string()),
                value: HirExpression::IntLiteral(20),
            },
            HirStatement::Return(Some(HirExpression::IntLiteral(0))),
        ],
    );

    let detector = OutputParamDetector::new();
    let output_params = detector.detect(&func);

    assert_eq!(output_params.len(), 2);

    let x_param = output_params.iter().find(|p| p.name == "x").unwrap();
    let y_param = output_params.iter().find(|p| p.name == "y").unwrap();

    assert_eq!(x_param.kind, ParameterKind::Output);
    assert_eq!(y_param.kind, ParameterKind::Output);
}

// ============================================================================
// TEST 4: Fallible operations (return value indicates success/failure)
// ============================================================================

#[test]
fn test_fallible_operation_detection() {
    // C code:
    // int try_parse(const char* input, int* result) {
    //     if (input == NULL) return -1;  // Error
    //     *result = 42;
    //     return 0;  // Success
    // }

    let func = create_test_function(
        "try_parse",
        vec![create_char_pointer_param("input"), create_pointer_param("result")],
        HirType::Int,
        vec![
            HirStatement::If {
                condition: HirExpression::BinaryOp {
                    op: BinaryOperator::Equal,
                    left: Box::new(HirExpression::Variable("input".to_string())),
                    right: Box::new(HirExpression::NullLiteral),
                },
                then_block: vec![HirStatement::Return(Some(HirExpression::IntLiteral(-1)))],
                else_block: None,
            },
            HirStatement::DerefAssignment {
                target: HirExpression::Variable("result".to_string()),
                value: HirExpression::IntLiteral(42),
            },
            HirStatement::Return(Some(HirExpression::IntLiteral(0))),
        ],
    );

    let detector = OutputParamDetector::new();
    let output_params = detector.detect(&func);

    assert_eq!(output_params.len(), 1);
    assert_eq!(output_params[0].name, "result");
    assert!(output_params[0].is_fallible, "Should detect fallible operation");
}

// ============================================================================
// TEST 5: Non-fallible operation (void return type)
// ============================================================================

#[test]
fn test_non_fallible_operation() {
    // C code:
    // void get_default(int* result) {
    //     *result = 42;
    // }

    let func = create_test_function(
        "get_default",
        vec![create_pointer_param("result")],
        HirType::Void,
        vec![HirStatement::DerefAssignment {
            target: HirExpression::Variable("result".to_string()),
            value: HirExpression::IntLiteral(42),
        }],
    );

    let detector = OutputParamDetector::new();
    let output_params = detector.detect(&func);

    assert_eq!(output_params.len(), 1);
    assert_eq!(output_params[0].name, "result");
    assert!(!output_params[0].is_fallible, "Void return is not fallible");
}

// ============================================================================
// TEST 6: Output parameter not written
// ============================================================================

#[test]
fn test_parameter_not_written_not_detected() {
    // C code:
    // int no_op(int* result) {
    //     return 0;  // Parameter never written
    // }

    let func = create_test_function(
        "no_op",
        vec![create_pointer_param("result")],
        HirType::Int,
        vec![HirStatement::Return(Some(HirExpression::IntLiteral(0)))],
    );

    let detector = OutputParamDetector::new();
    let output_params = detector.detect(&func);

    assert_eq!(output_params.len(), 0, "Unwritten parameter should not be detected");
}

// ============================================================================
// TEST 7: Conditional write (still an output parameter)
// ============================================================================

#[test]
fn test_conditional_write_detected_as_output() {
    // C code:
    // int maybe_write(int flag, int* result) {
    //     if (flag) {
    //         *result = 42;
    //     }
    //     return 0;
    // }

    let func = create_test_function(
        "maybe_write",
        vec![HirParameter::new("flag".to_string(), HirType::Int), create_pointer_param("result")],
        HirType::Int,
        vec![
            HirStatement::If {
                condition: HirExpression::Variable("flag".to_string()),
                then_block: vec![HirStatement::DerefAssignment {
                    target: HirExpression::Variable("result".to_string()),
                    value: HirExpression::IntLiteral(42),
                }],
                else_block: None,
            },
            HirStatement::Return(Some(HirExpression::IntLiteral(0))),
        ],
    );

    let detector = OutputParamDetector::new();
    let output_params = detector.detect(&func);

    assert_eq!(output_params.len(), 1);
    assert_eq!(output_params[0].name, "result");
}

// ============================================================================
// TEST 8: Non-pointer parameter (should not be detected)
// ============================================================================

#[test]
fn test_non_pointer_not_detected() {
    // C code:
    // int add(int a, int b) {
    //     return a + b;
    // }

    let func = create_test_function(
        "add",
        vec![
            HirParameter::new("a".to_string(), HirType::Int),
            HirParameter::new("b".to_string(), HirType::Int),
        ],
        HirType::Int,
        vec![HirStatement::Return(Some(HirExpression::BinaryOp {
            op: BinaryOperator::Add,
            left: Box::new(HirExpression::Variable("a".to_string())),
            right: Box::new(HirExpression::Variable("b".to_string())),
        }))],
    );

    let detector = OutputParamDetector::new();
    let output_params = detector.detect(&func);

    assert_eq!(output_params.len(), 0, "Non-pointer parameters should not be detected");
}

// ============================================================================
// TEST 9: Pointer parameter read but never written
// ============================================================================

#[test]
fn test_pointer_read_only_not_output() {
    // C code:
    // int read_value(int* ptr) {
    //     return *ptr;
    // }

    let func = create_test_function(
        "read_value",
        vec![create_pointer_param("ptr")],
        HirType::Int,
        vec![HirStatement::Return(Some(HirExpression::Dereference(Box::new(
            HirExpression::Variable("ptr".to_string()),
        ))))],
    );

    let detector = OutputParamDetector::new();
    let output_params = detector.detect(&func);

    assert_eq!(output_params.len(), 0, "Read-only pointer should not be output");
}

// ============================================================================
// TEST 10: Double pointer (common for handles/resources)
// ============================================================================

#[test]
fn test_double_pointer_output() {
    // C code:
    // int create_object(Object** obj) {
    //     *obj = malloc(sizeof(Object));
    //     return 0;
    // }

    let func = create_test_function(
        "create_object",
        vec![HirParameter::new(
            "obj".to_string(),
            HirType::Pointer(Box::new(HirType::Pointer(Box::new(HirType::Struct(
                "Object".to_string(),
            ))))),
        )],
        HirType::Int,
        vec![
            HirStatement::DerefAssignment {
                target: HirExpression::Variable("obj".to_string()),
                value: HirExpression::Malloc {
                    size: Box::new(HirExpression::Sizeof { type_name: "Object".to_string() }),
                },
            },
            HirStatement::Return(Some(HirExpression::IntLiteral(0))),
        ],
    );

    let detector = OutputParamDetector::new();
    let output_params = detector.detect(&func);

    assert_eq!(output_params.len(), 1);
    assert_eq!(output_params[0].name, "obj");
    assert_eq!(output_params[0].kind, ParameterKind::Output);
}

#[test]
fn test_output_param_detector_default() {
    let detector = OutputParamDetector::default();
    let func = create_test_function("empty", vec![], HirType::Void, vec![]);
    let params = detector.detect(&func);
    assert!(params.is_empty());
}

#[test]
fn test_detect_no_parameters() {
    let func =
        create_test_function("noop", vec![], HirType::Void, vec![HirStatement::Return(None)]);
    let detector = OutputParamDetector::new();
    assert!(detector.detect(&func).is_empty());
}

#[test]
fn test_detect_non_pointer_only_params() {
    let func = create_test_function(
        "add",
        vec![
            HirParameter::new("a".to_string(), HirType::Int),
            HirParameter::new("b".to_string(), HirType::Int),
        ],
        HirType::Int,
        vec![HirStatement::Return(Some(HirExpression::BinaryOp {
            op: decy_hir::BinaryOperator::Add,
            left: Box::new(HirExpression::Variable("a".to_string())),
            right: Box::new(HirExpression::Variable("b".to_string())),
        }))],
    );
    let detector = OutputParamDetector::new();
    assert!(detector.detect(&func).is_empty());
}