depyler-analysis 4.1.1

Analysis, type inference, and optimization passes for the Depyler 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
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
//! Borrowing Shim - pure logic separated from I/O
//!
//! Extracts testable logic from borrowing.rs

use depyler_hir::hir::{ConstGeneric, Type};
use std::collections::HashSet;

/// Analysis result for a single parameter
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum BorrowingPattern {
    /// Parameter should be taken by value (moved)
    Owned,
    /// Parameter can be borrowed immutably
    Borrowed,
    /// Parameter needs mutable borrow
    MutableBorrow,
}

impl BorrowingPattern {
    /// Get the Rust syntax prefix for this pattern
    pub fn prefix(&self) -> &'static str {
        match self {
            Self::Owned => "",
            Self::Borrowed => "&",
            Self::MutableBorrow => "&mut ",
        }
    }

    /// Check if this pattern requires a reference
    pub fn is_reference(&self) -> bool {
        matches!(self, Self::Borrowed | Self::MutableBorrow)
    }

    /// Check if this pattern is mutable
    pub fn is_mutable(&self) -> bool {
        matches!(self, Self::MutableBorrow)
    }
}

/// Check if a type is copyable (doesn't need borrowing)
pub fn is_copyable(ty: &Type) -> bool {
    match ty {
        Type::Int | Type::Float | Type::Bool => true,
        Type::Optional(inner) => is_copyable(inner),
        Type::Tuple(types) if types.len() <= 12 => types.iter().all(is_copyable),
        Type::Custom(name) => is_copy_type_name(name),
        _ => false,
    }
}

/// Check if a type name represents a Copy type
pub fn is_copy_type_name(name: &str) -> bool {
    matches!(
        name,
        "i8" | "i16"
            | "i32"
            | "i64"
            | "i128"
            | "isize"
            | "u8"
            | "u16"
            | "u32"
            | "u64"
            | "u128"
            | "usize"
            | "f32"
            | "f64"
            | "bool"
            | "char"
            | "()"
    )
}

/// Check if a type should be passed by reference for efficiency
pub fn should_pass_by_ref(ty: &Type) -> bool {
    match ty {
        Type::String | Type::List(_) | Type::Dict(_, _) | Type::Set(_) => true,
        Type::Custom(name) => {
            name.starts_with("Vec<")
                || name.starts_with("HashMap<")
                || name.starts_with("HashSet<")
                || name.starts_with("String")
                || name.starts_with("BTreeMap<")
                || name.starts_with("BTreeSet<")
        }
        Type::Tuple(types) if types.len() > 3 => true,
        _ => false,
    }
}

/// Determine borrowing pattern based on usage
pub fn determine_pattern(
    is_mutated: bool,
    is_escaping: bool,
    is_loop_used: bool,
    ty: &Type,
) -> BorrowingPattern {
    if is_escaping {
        // Must be owned if it escapes
        BorrowingPattern::Owned
    } else if is_mutated {
        // Needs mutable borrow if mutated
        BorrowingPattern::MutableBorrow
    } else if is_copyable(ty) {
        // Small Copy types should be passed by value
        BorrowingPattern::Owned
    } else if is_loop_used && should_pass_by_ref(ty) {
        // Loop usage of large types should be borrowed
        BorrowingPattern::Borrowed
    } else if should_pass_by_ref(ty) {
        BorrowingPattern::Borrowed
    } else {
        BorrowingPattern::Owned
    }
}

/// Convert type to Rust string representation
pub fn type_to_rust_string(ty: &Type) -> String {
    match ty {
        Type::Int => "i64".to_string(),
        Type::Float => "f64".to_string(),
        Type::Bool => "bool".to_string(),
        Type::String => "String".to_string(),
        Type::None => "()".to_string(),
        Type::Unknown => "T".to_string(),
        Type::List(inner) => format!("Vec<{}>", type_to_rust_string(inner)),
        Type::Dict(key, value) => {
            format!(
                "HashMap<{}, {}>",
                type_to_rust_string(key),
                type_to_rust_string(value)
            )
        }
        Type::Set(inner) => format!("HashSet<{}>", type_to_rust_string(inner)),
        Type::Optional(inner) => format!("Option<{}>", type_to_rust_string(inner)),
        Type::Tuple(types) => {
            let inner: Vec<_> = types.iter().map(type_to_rust_string).collect();
            format!("({})", inner.join(", "))
        }
        Type::Custom(name) => name.clone(),
        Type::Function { params, ret } => {
            let param_strs: Vec<_> = params.iter().map(type_to_rust_string).collect();
            format!(
                "fn({}) -> {}",
                param_strs.join(", "),
                type_to_rust_string(ret)
            )
        }
        Type::TypeVar(name) => name.clone(),
        Type::UnificationVar(id) => format!("?T{}", id),
        Type::Generic { base, params } => {
            let param_strs: Vec<_> = params.iter().map(type_to_rust_string).collect();
            format!("{}<{}>", base, param_strs.join(", "))
        }
        Type::Union(types) => {
            // Rust doesn't have union types, approximate with enum
            let inner: Vec<_> = types.iter().map(type_to_rust_string).collect();
            format!("Either<{}>", inner.join(", "))
        }
        Type::Array { element_type, size } => {
            let size_str = match size {
                ConstGeneric::Literal(n) => n.to_string(),
                ConstGeneric::Parameter(name) => name.clone(),
                ConstGeneric::Expression(expr) => expr.clone(),
            };
            format!("[{}; {}]", type_to_rust_string(element_type), size_str)
        }
        Type::Final(inner) => type_to_rust_string(inner),
    }
}

/// Generate parameter signature with borrowing pattern
pub fn generate_param_signature(name: &str, ty: &Type, pattern: &BorrowingPattern) -> String {
    let type_str = type_to_rust_string(ty);
    match pattern {
        BorrowingPattern::Owned => format!("{}: {}", name, type_str),
        BorrowingPattern::Borrowed => format!("{}: &{}", name, type_str),
        BorrowingPattern::MutableBorrow => format!("{}: &mut {}", name, type_str),
    }
}

/// Parameter usage tracking
#[derive(Debug, Default)]
pub struct ParamUsage {
    pub is_mutated: bool,
    pub is_escaping: bool,
    pub is_loop_used: bool,
    pub is_read: bool,
}

impl ParamUsage {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn mark_mutated(&mut self) {
        self.is_mutated = true;
    }

    pub fn mark_escaping(&mut self) {
        self.is_escaping = true;
    }

    pub fn mark_loop_used(&mut self) {
        self.is_loop_used = true;
    }

    pub fn mark_read(&mut self) {
        self.is_read = true;
    }

    pub fn get_pattern(&self, ty: &Type) -> BorrowingPattern {
        determine_pattern(self.is_mutated, self.is_escaping, self.is_loop_used, ty)
    }
}

/// Collect all variable names from a set of identifiers
pub fn collect_param_names(params: &[String]) -> HashSet<String> {
    params.iter().cloned().collect()
}

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

    #[test]
    fn test_borrowing_pattern_prefix() {
        assert_eq!(BorrowingPattern::Owned.prefix(), "");
        assert_eq!(BorrowingPattern::Borrowed.prefix(), "&");
        assert_eq!(BorrowingPattern::MutableBorrow.prefix(), "&mut ");
    }

    #[test]
    fn test_borrowing_pattern_is_reference() {
        assert!(!BorrowingPattern::Owned.is_reference());
        assert!(BorrowingPattern::Borrowed.is_reference());
        assert!(BorrowingPattern::MutableBorrow.is_reference());
    }

    #[test]
    fn test_borrowing_pattern_is_mutable() {
        assert!(!BorrowingPattern::Owned.is_mutable());
        assert!(!BorrowingPattern::Borrowed.is_mutable());
        assert!(BorrowingPattern::MutableBorrow.is_mutable());
    }

    #[test]
    fn test_is_copyable_primitives() {
        assert!(is_copyable(&Type::Int));
        assert!(is_copyable(&Type::Float));
        assert!(is_copyable(&Type::Bool));
    }

    #[test]
    fn test_is_copyable_non_primitives() {
        assert!(!is_copyable(&Type::String));
        assert!(!is_copyable(&Type::List(Box::new(Type::Int))));
        assert!(!is_copyable(&Type::Dict(
            Box::new(Type::String),
            Box::new(Type::Int)
        )));
    }

    #[test]
    fn test_is_copyable_optional() {
        assert!(is_copyable(&Type::Optional(Box::new(Type::Int))));
        assert!(!is_copyable(&Type::Optional(Box::new(Type::String))));
    }

    #[test]
    fn test_is_copyable_tuple() {
        let small_copy_tuple = Type::Tuple(vec![Type::Int, Type::Bool]);
        assert!(is_copyable(&small_copy_tuple));

        let small_non_copy_tuple = Type::Tuple(vec![Type::Int, Type::String]);
        assert!(!is_copyable(&small_non_copy_tuple));
    }

    #[test]
    fn test_is_copy_type_name() {
        assert!(is_copy_type_name("i32"));
        assert!(is_copy_type_name("u64"));
        assert!(is_copy_type_name("f64"));
        assert!(is_copy_type_name("bool"));
        assert!(is_copy_type_name("char"));
        assert!(is_copy_type_name("()"));
        assert!(!is_copy_type_name("String"));
        assert!(!is_copy_type_name("Vec"));
    }

    #[test]
    fn test_should_pass_by_ref() {
        assert!(should_pass_by_ref(&Type::String));
        assert!(should_pass_by_ref(&Type::List(Box::new(Type::Int))));
        assert!(should_pass_by_ref(&Type::Dict(
            Box::new(Type::String),
            Box::new(Type::Int)
        )));
        assert!(should_pass_by_ref(&Type::Set(Box::new(Type::Int))));
        assert!(!should_pass_by_ref(&Type::Int));
        assert!(!should_pass_by_ref(&Type::Bool));
    }

    #[test]
    fn test_should_pass_by_ref_custom() {
        assert!(should_pass_by_ref(&Type::Custom("Vec<i32>".to_string())));
        assert!(should_pass_by_ref(&Type::Custom(
            "HashMap<String, i32>".to_string()
        )));
        assert!(should_pass_by_ref(&Type::Custom("String".to_string())));
        assert!(!should_pass_by_ref(&Type::Custom("i32".to_string())));
    }

    #[test]
    fn test_should_pass_by_ref_large_tuple() {
        let large_tuple = Type::Tuple(vec![Type::Int; 5]);
        assert!(should_pass_by_ref(&large_tuple));

        let small_tuple = Type::Tuple(vec![Type::Int; 2]);
        assert!(!should_pass_by_ref(&small_tuple));
    }

    #[test]
    fn test_determine_pattern_escaping() {
        let pattern = determine_pattern(false, true, false, &Type::String);
        assert_eq!(pattern, BorrowingPattern::Owned);
    }

    #[test]
    fn test_determine_pattern_mutated() {
        let pattern = determine_pattern(true, false, false, &Type::String);
        assert_eq!(pattern, BorrowingPattern::MutableBorrow);
    }

    #[test]
    fn test_determine_pattern_copyable() {
        let pattern = determine_pattern(false, false, false, &Type::Int);
        assert_eq!(pattern, BorrowingPattern::Owned);
    }

    #[test]
    fn test_determine_pattern_borrowed() {
        let pattern = determine_pattern(false, false, false, &Type::String);
        assert_eq!(pattern, BorrowingPattern::Borrowed);
    }

    #[test]
    fn test_determine_pattern_loop_used() {
        let pattern = determine_pattern(false, false, true, &Type::String);
        assert_eq!(pattern, BorrowingPattern::Borrowed);
    }

    #[test]
    fn test_type_to_rust_string_primitives() {
        assert_eq!(type_to_rust_string(&Type::Int), "i64");
        assert_eq!(type_to_rust_string(&Type::Float), "f64");
        assert_eq!(type_to_rust_string(&Type::Bool), "bool");
        assert_eq!(type_to_rust_string(&Type::String), "String");
        assert_eq!(type_to_rust_string(&Type::None), "()");
        assert_eq!(type_to_rust_string(&Type::Unknown), "T");
    }

    #[test]
    fn test_type_to_rust_string_containers() {
        assert_eq!(
            type_to_rust_string(&Type::List(Box::new(Type::Int))),
            "Vec<i64>"
        );
        assert_eq!(
            type_to_rust_string(&Type::Dict(Box::new(Type::String), Box::new(Type::Int))),
            "HashMap<String, i64>"
        );
        assert_eq!(
            type_to_rust_string(&Type::Set(Box::new(Type::Int))),
            "HashSet<i64>"
        );
    }

    #[test]
    fn test_type_to_rust_string_optional() {
        assert_eq!(
            type_to_rust_string(&Type::Optional(Box::new(Type::Int))),
            "Option<i64>"
        );
    }

    #[test]
    fn test_type_to_rust_string_tuple() {
        let tuple = Type::Tuple(vec![Type::Int, Type::String, Type::Bool]);
        assert_eq!(type_to_rust_string(&tuple), "(i64, String, bool)");
    }

    #[test]
    fn test_type_to_rust_string_function() {
        let func = Type::Function {
            params: vec![Type::Int, Type::String],
            ret: Box::new(Type::Bool),
        };
        assert_eq!(type_to_rust_string(&func), "fn(i64, String) -> bool");
    }

    #[test]
    fn test_type_to_rust_string_typevar() {
        assert_eq!(type_to_rust_string(&Type::TypeVar("T".to_string())), "T");
        assert_eq!(type_to_rust_string(&Type::TypeVar("U".to_string())), "U");
    }

    #[test]
    fn test_type_to_rust_string_unification_var() {
        assert_eq!(type_to_rust_string(&Type::UnificationVar(0)), "?T0");
        assert_eq!(type_to_rust_string(&Type::UnificationVar(42)), "?T42");
    }

    #[test]
    fn test_type_to_rust_string_generic() {
        let generic = Type::Generic {
            base: "Result".to_string(),
            params: vec![Type::Int, Type::String],
        };
        assert_eq!(type_to_rust_string(&generic), "Result<i64, String>");
    }

    #[test]
    fn test_type_to_rust_string_union() {
        let union = Type::Union(vec![Type::Int, Type::String]);
        assert_eq!(type_to_rust_string(&union), "Either<i64, String>");
    }

    #[test]
    fn test_type_to_rust_string_array() {
        let array = Type::Array {
            element_type: Box::new(Type::Int),
            size: ConstGeneric::Literal(10),
        };
        assert_eq!(type_to_rust_string(&array), "[i64; 10]");

        let array_param = Type::Array {
            element_type: Box::new(Type::Float),
            size: ConstGeneric::Parameter("N".to_string()),
        };
        assert_eq!(type_to_rust_string(&array_param), "[f64; N]");

        let array_expr = Type::Array {
            element_type: Box::new(Type::Bool),
            size: ConstGeneric::Expression("N + 1".to_string()),
        };
        assert_eq!(type_to_rust_string(&array_expr), "[bool; N + 1]");
    }

    #[test]
    fn test_type_to_rust_string_final() {
        let final_type = Type::Final(Box::new(Type::Int));
        assert_eq!(type_to_rust_string(&final_type), "i64");
    }

    #[test]
    fn test_generate_param_signature() {
        assert_eq!(
            generate_param_signature("x", &Type::Int, &BorrowingPattern::Owned),
            "x: i64"
        );
        assert_eq!(
            generate_param_signature("s", &Type::String, &BorrowingPattern::Borrowed),
            "s: &String"
        );
        assert_eq!(
            generate_param_signature(
                "v",
                &Type::List(Box::new(Type::Int)),
                &BorrowingPattern::MutableBorrow
            ),
            "v: &mut Vec<i64>"
        );
    }

    #[test]
    fn test_param_usage_new() {
        let usage = ParamUsage::new();
        assert!(!usage.is_mutated);
        assert!(!usage.is_escaping);
        assert!(!usage.is_loop_used);
        assert!(!usage.is_read);
    }

    #[test]
    fn test_param_usage_mark_mutated() {
        let mut usage = ParamUsage::new();
        usage.mark_mutated();
        assert!(usage.is_mutated);
    }

    #[test]
    fn test_param_usage_mark_escaping() {
        let mut usage = ParamUsage::new();
        usage.mark_escaping();
        assert!(usage.is_escaping);
    }

    #[test]
    fn test_param_usage_mark_loop_used() {
        let mut usage = ParamUsage::new();
        usage.mark_loop_used();
        assert!(usage.is_loop_used);
    }

    #[test]
    fn test_param_usage_mark_read() {
        let mut usage = ParamUsage::new();
        usage.mark_read();
        assert!(usage.is_read);
    }

    #[test]
    fn test_param_usage_get_pattern() {
        let mut usage = ParamUsage::new();
        assert_eq!(usage.get_pattern(&Type::String), BorrowingPattern::Borrowed);

        usage.mark_mutated();
        assert_eq!(
            usage.get_pattern(&Type::String),
            BorrowingPattern::MutableBorrow
        );

        let mut escaping_usage = ParamUsage::new();
        escaping_usage.mark_escaping();
        assert_eq!(
            escaping_usage.get_pattern(&Type::String),
            BorrowingPattern::Owned
        );
    }

    #[test]
    fn test_collect_param_names() {
        let params = vec!["a".to_string(), "b".to_string(), "c".to_string()];
        let names = collect_param_names(&params);
        assert!(names.contains("a"));
        assert!(names.contains("b"));
        assert!(names.contains("c"));
        assert_eq!(names.len(), 3);
    }

    #[test]
    fn test_collect_param_names_empty() {
        let params: Vec<String> = vec![];
        let names = collect_param_names(&params);
        assert!(names.is_empty());
    }
}