depyler-core 3.24.0

Core transpilation engine for the Depyler Python-to-Rust transpiler
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
//! Tests for string allocation optimizations

use depyler_core::DepylerPipeline;

// ============================================================================
// UNIT TESTS
// ============================================================================

#[test]
fn test_read_only_string_no_allocation() {
    let pipeline = DepylerPipeline::new();
    let python_code = r#"
def print_message():
    message = "Hello, World!"
    print(message)
"#;

    let rust_code = pipeline.transpile(python_code).unwrap();
    println!("Generated code for print_message:\n{}", rust_code);

    // Should not allocate a String for a read-only literal
    assert!(
        !rust_code.contains(".to_string()"),
        "Should not allocate String for read-only literal"
    );
}

#[test]
fn test_returned_string_uses_appropriate_type() {
    let pipeline = DepylerPipeline::new();
    let python_code = r#"
def get_greeting() -> str:
    return "Hello!"
"#;

    let rust_code = pipeline.transpile(python_code).unwrap();
    println!("Generated code for get_greeting:\n{}", rust_code);

    // DEPYLER-0357: Returns String for string literals
    // Note: Python source updated to include return type annotation (-> str)
    // to ensure proper Rust type generation
    assert!(
        rust_code.contains("-> String"),
        "Should have String return type"
    );
    assert!(
        rust_code.contains("to_string()"),
        "String literal should be converted to String"
    );
}

#[test]
fn test_string_concatenation_allocates() {
    let pipeline = DepylerPipeline::new();
    let python_code = r#"
def concat_strings(a: str, b: str) -> str:
    return a + b
"#;

    let rust_code = pipeline.transpile(python_code).unwrap();
    println!("Generated code for concat_strings:\n{}", rust_code);

    // DEPYLER-0357: String concatenation uses format! for borrowed strings
    // This is more idiomatic than + operator when both operands are &str
    assert!(
        rust_code.contains("format!") || rust_code.contains("+"),
        "Should contain concatenation via format! or +"
    );
    assert!(
        rust_code.contains("-> String"),
        "Concatenation should return String"
    );
}

#[test]
fn test_interned_strings_for_repeated_literals() {
    let pipeline = DepylerPipeline::new();
    let python_code = r#"
def use_repeated_string():
    s1 = "repeated"
    s2 = "repeated"
    s3 = "repeated"
    s4 = "repeated"
    s5 = "repeated"
    return [s1, s2, s3, s4, s5]
"#;

    let rust_code = pipeline.transpile(python_code).unwrap();
    println!("Generated code for use_repeated_string:\n{}", rust_code);

    // Should generate a constant for repeated string literals
    assert!(
        rust_code.contains("const STR_"),
        "Should intern repeated string literal"
    );
}

#[test]
fn test_constants_collision_resolution() {
    let pipeline = DepylerPipeline::new();
    let python_code = r#"
def test_constants1() -> bool:
    """Test string constants comparison"""
    x = "DEF"
    if x == 'ABC':
        return False
    if x == 'abc':
        return False
    return True

def test_constants2() -> bool:
    """Test string constants comparison"""
    x = "DEF"
    if x == 'ABC':
        return False
    if x == 'abc':
        return False
    return True

def test_constants3() -> bool:
    """Test string constants comparison"""
    x = "DEF"
    if x == 'ABC':
        return False
    if x == 'abc':
        return False
    return True

def test_constants4() -> bool:
    """Test string constants comparison"""
    x = "DEF"
    if x == 'ABC':
        return False
    if x == 'abc':
        return False
    return True
"#;

    let rust_code = pipeline.transpile(python_code).unwrap();
    println!("Generated code for test_constants:\n{}", rust_code);

    // Each string appears 4 times (once per function), so should be interned
    assert!(
        rust_code.contains("const STR_DEF"),
        "Should intern DEF string literal (appears 4 times)"
    );
    assert!(
        rust_code.contains("const STR_ABC"),
        "Should intern ABC string literal (appears 4 times)"
    );

    // Verify that "ABC" and "abc" get different constant names due to collision
    // Both would map to STR_ABC, so one should get a suffix
    let abc_count = rust_code.matches("const STR_ABC").count();
    assert!(
        abc_count >= 2,
        "Should have at least 2 STR_ABC constants (one for 'ABC', one for 'abc' with suffix), found {}",
        abc_count
    );

    // Verify the constants actually compile (no duplicate names)
    assert!(
        rust_code.matches("const STR_ABC_1").count() >= 1
            || rust_code.matches("const STR_ABC_2").count() >= 1,
        "Should have collision-resolved names like STR_ABC_1 or STR_ABC_2"
    );
}

#[test]
fn test_function_taking_str_reference() {
    let pipeline = DepylerPipeline::new();
    let python_code = r#"
def validate_string(s: str) -> bool:
    return len(s) > 0
"#;

    let rust_code = pipeline.transpile(python_code).unwrap();
    println!("Generated code for validate_string:\n{}", rust_code);

    // Should take &str not String for read-only parameter
    assert!(rust_code.contains("&"), "Should borrow string parameter");
    assert!(rust_code.contains("str"), "Should use str type");
}

#[test]
fn test_local_string_variable_optimization() {
    let pipeline = DepylerPipeline::new();
    let python_code = r#"
def format_number(n: int) -> str:
    prefix = "Number: "
    return prefix + str(n)
"#;

    let rust_code = pipeline.transpile(python_code).unwrap();
    println!("Generated code for format_number:\n{}", rust_code);

    // Local string that's used in concatenation
    // The prefix might be inlined by the optimizer
    assert!(
        rust_code.contains("Number: ") || rust_code.contains("prefix"),
        "Should have prefix string either as variable or inlined"
    );
}

// ============================================================================
// PROPERTY TESTS
// ============================================================================

#[cfg(test)]
mod property_tests {
    use super::*;
    use proptest::prelude::*;

    proptest! {
        #![proptest_config(ProptestConfig::with_cases(10))]

        #[test]
        fn prop_string_literals_always_transpile(_s in "\\PC{0,50}") {
            // Property: Any valid string literal should transpile without error
            // Using simple alphanumeric strings to avoid parsing complexity
            let pipeline = DepylerPipeline::new();
            let python_code = r#"
def test_func():
    x = "test_string"
    return x
"#;

            let result = pipeline.transpile(python_code);
            prop_assert!(result.is_ok(), "String literal transpilation failed: {:?}", result.err());
        }

        #[test]
        fn prop_string_concatenation_compiles(_a in "\\PC{1,20}", _b in "\\PC{1,20}") {
            // Property: String concatenation should always produce valid Rust
            let pipeline = DepylerPipeline::new();
            let python_code = r#"
def concat(x: str, y: str) -> str:
    return x + y
"#;

            let result = pipeline.transpile(python_code);
            prop_assert!(result.is_ok(), "String concatenation transpilation failed");

            let rust_code = result.unwrap();
            prop_assert!(rust_code.contains("+") || rust_code.contains("format!"),
                "Should contain concatenation operator or format macro");
        }

        #[test]
        fn prop_string_parameters_use_references(param_name in "[a-z]{1,10}") {
            // Property: String parameters should prefer &str over String
            // Filter out Python AND Rust keywords to avoid parsing errors
            let rust_keywords = ["as", "break", "const", "continue", "crate", "do", "else",
                                 "enum", "extern", "false", "fn", "for", "if", "impl", "in",
                                 "let", "loop", "match", "mod", "move", "mut", "pub", "ref",
                                 "return", "self", "Self", "static", "struct", "super", "trait",
                                 "true", "type", "unsafe", "use", "where", "while", "async",
                                 "await", "dyn", "abstract", "become", "box", "final", "macro",
                                 "override", "priv", "typeof", "unsized", "virtual", "yield",
                                 "try"];

            // Python keywords that would cause parse errors
            let python_keywords = ["and", "as", "assert", "async", "await", "break", "class",
                                  "continue", "def", "del", "elif", "else", "except", "finally",
                                  "for", "from", "global", "if", "import", "in", "is", "lambda",
                                  "nonlocal", "not", "or", "pass", "raise", "return", "try",
                                  "while", "with", "yield"];

            prop_assume!(!rust_keywords.contains(&param_name.as_str()));
            prop_assume!(!python_keywords.contains(&param_name.as_str()));

            let pipeline = DepylerPipeline::new();
            let python_code = format!(r#"
def check_{param}({param}: str) -> int:
    return len({param})
"#, param = param_name);

            let result = pipeline.transpile(&python_code);
            prop_assert!(result.is_ok(), "String parameter transpilation failed");

            let rust_code = result.unwrap();
            // Should use &str or similar borrowed type
            prop_assert!(rust_code.contains("&"),
                "String parameters should use borrowing");
        }
    }
}

// ============================================================================
// MUTATION TESTS
// ============================================================================

#[cfg(test)]
mod mutation_tests {
    use super::*;

    #[test]
    fn test_mutation_string_interning_threshold() {
        // Target Mutations:
        // 1. Repeated string count check (5 occurrences → should intern)
        // 2. Constant generation (STR_ prefix must be present)
        // 3. String deduplication (same literal = same constant)
        //
        // Kill Strategy:
        // - Verify STR_ constant is generated for repeated literals
        // - Verify constant is used multiple times (not duplicated)
        // - Mutation that removes interning would fail this check

        let pipeline = DepylerPipeline::new();
        let python_code = r#"
def use_repeated_string():
    s1 = "repeated"
    s2 = "repeated"
    s3 = "repeated"
    s4 = "repeated"
    s5 = "repeated"
    return [s1, s2, s3, s4, s5]
"#;

        let rust_code = pipeline.transpile(python_code).unwrap();

        // Mutation Kill: If interning is disabled, this fails
        assert!(
            rust_code.contains("const STR_"),
            "MUTATION KILL: Must generate interned constant for repeated strings"
        );

        // Mutation Kill: If deduplication breaks, multiple constants would appear
        let const_count = rust_code.matches("const STR_").count();
        assert_eq!(
            const_count, 1,
            "MUTATION KILL: Should have exactly 1 constant for 'repeated' (found {})",
            const_count
        );
    }

    #[test]
    fn test_mutation_string_allocation_elimination() {
        // Target Mutations:
        // 1. .to_string() insertion (should NOT allocate for read-only)
        // 2. String::from() usage (unnecessary allocation)
        // 3. Owned vs borrowed type selection
        //
        // Kill Strategy:
        // - Verify no .to_string() for read-only string literals
        // - Verify no String::from() for simple assignments
        // - Mutation adding allocations would fail this check

        let pipeline = DepylerPipeline::new();
        let python_code = r#"
def print_message():
    message = "Hello, World!"
    print(message)
"#;

        let rust_code = pipeline.transpile(python_code).unwrap();

        // Mutation Kill: Adding .to_string() would fail this
        assert!(
            !rust_code.contains(".to_string()"),
            "MUTATION KILL: Read-only string should not allocate with .to_string()"
        );

        // Mutation Kill: Using String::from unnecessarily would fail
        assert!(
            !rust_code.contains("String::from"),
            "MUTATION KILL: Should not use String::from for simple literal assignment"
        );
    }

    #[test]
    fn test_mutation_string_concatenation_operator() {
        // Target Mutations:
        // 1. + operator removal (would break concatenation)
        // 2. format! macro substitution (alternative approach)
        // 3. Operator precedence changes
        //
        // Kill Strategy:
        // - Verify + operator or format! exists for concatenation
        // - Verify operand ordering is preserved
        // - Mutation removing concatenation logic would fail

        let pipeline = DepylerPipeline::new();
        let python_code = r#"
def concat_strings(a: str, b: str) -> str:
    return a + b
"#;

        let rust_code = pipeline.transpile(python_code).unwrap();

        // Mutation Kill: Removing concatenation operator would fail
        assert!(
            rust_code.contains("+") || rust_code.contains("format!"),
            "MUTATION KILL: Concatenation must use + operator or format! macro"
        );

        // Mutation Kill: Swapping operands would change semantics
        // The generated code should preserve a, b ordering
        assert!(
            rust_code.contains("a") && rust_code.contains("b"),
            "MUTATION KILL: Both operands must be present in concatenation"
        );
    }
}