depyler-core 3.22.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
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
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
//! Collection constructor code generation
//!
//! This module handles Python collection constructors: set(), frozenset(), dict(),
//! list(), deque(), Counter()
//!
//! Extracted from expr_gen.rs as part of DEPYLER-REFACTOR-001 (God File split)
//!
//! # DEPYLER-REFACTOR-001 Traceability
//! - Original location: expr_gen.rs lines 1816-1951, 2330-2381
//! - Extraction date: 2025-11-25
//! - Tests: tests/refactor_collection_constructors_test.rs

use crate::rust_gen::context::CodeGenContext;
use anyhow::{bail, Result};
use syn::parse_quote;

/// Convert Python set() constructor to Rust HashSet
///
/// - `set()` → `HashSet::<i32>::new()` (DEPYLER-0409: default type for inference)
/// - `set(iterable)` → `iterable.into_iter().collect::<HashSet<_>>()`
///
/// # Complexity: 4
pub fn convert_set_constructor(ctx: &mut CodeGenContext, args: &[syn::Expr]) -> Result<syn::Expr> {
    ctx.needs_hashset = true;
    if args.is_empty() {
        // Empty set: set()
        // DEPYLER-0409: Use default type i32 to avoid "type annotations needed" error
        // DEPYLER-0831: Use fully-qualified path for E0412 resolution
        Ok(parse_quote! { std::collections::HashSet::<i32>::new() })
    } else if args.len() == 1 {
        // Set from iterable: set([1, 2, 3])
        let arg = &args[0];
        // DEPYLER-0797: Check if arg is a tuple - tuples don't implement IntoIterator in Rust
        // Convert tuple to vec! for iteration
        // DEPYLER-0831: Use fully-qualified path for E0412 resolution
        if let syn::Expr::Tuple(tuple) = arg {
            let elems = &tuple.elems;
            Ok(parse_quote! {
                vec![#elems].into_iter().collect::<std::collections::HashSet<_>>()
            })
        } else {
            Ok(parse_quote! {
                #arg.into_iter().collect::<std::collections::HashSet<_>>()
            })
        }
    } else {
        bail!("set() takes at most 1 argument ({} given)", args.len())
    }
}

/// Convert Python frozenset() constructor to Rust Arc<HashSet>
///
/// - `frozenset()` → `Arc::new(HashSet::<i32>::new())`
/// - `frozenset(iterable)` → `Arc::new(iterable.into_iter().collect::<HashSet<_>>())`
///
/// # Complexity: 4
pub fn convert_frozenset_constructor(
    ctx: &mut CodeGenContext,
    args: &[syn::Expr],
) -> Result<syn::Expr> {
    ctx.needs_hashset = true;
    if args.is_empty() {
        // Empty frozenset: frozenset()
        // DEPYLER-0409: Use default type i32 for empty sets
        // DEPYLER-0831: Use fully-qualified path for E0412 resolution
        Ok(parse_quote! { std::sync::Arc::new(std::collections::HashSet::<i32>::new()) })
    } else if args.len() == 1 {
        // Frozenset from iterable: frozenset([1, 2, 3])
        let arg = &args[0];
        // DEPYLER-0797: Check if arg is a tuple - tuples don't implement IntoIterator in Rust
        // Convert tuple to vec! for iteration
        // DEPYLER-0831: Use fully-qualified path for E0412 resolution
        if let syn::Expr::Tuple(tuple) = arg {
            let elems = &tuple.elems;
            Ok(parse_quote! {
                std::sync::Arc::new(vec![#elems].into_iter().collect::<std::collections::HashSet<_>>())
            })
        } else {
            Ok(parse_quote! {
                std::sync::Arc::new(#arg.into_iter().collect::<std::collections::HashSet<_>>())
            })
        }
    } else {
        bail!(
            "frozenset() takes at most 1 argument ({} given)",
            args.len()
        )
    }
}

/// Convert Python Counter() to Rust HashMap with fold counting
///
/// DEPYLER-0171: Counter(iterable) counts elements
///
/// - `Counter()` → `HashMap::new()`
/// - `Counter(iterable)` → fold with entry().or_insert()
///
/// # Complexity: 4
pub fn convert_counter_builtin(ctx: &mut CodeGenContext, args: &[syn::Expr]) -> Result<syn::Expr> {
    ctx.needs_hashmap = true;
    if args.is_empty() {
        Ok(parse_quote! { HashMap::new() })
    } else if args.len() == 1 {
        let arg = &args[0];
        Ok(parse_quote! {
            #arg.into_iter().fold(HashMap::new(), |mut acc, item| {
                *acc.entry(item).or_insert(0) += 1;
                acc
            })
        })
    } else {
        bail!("Counter() takes at most 1 argument ({} given)", args.len())
    }
}

/// Convert Python defaultdict() to Rust HashMap
///
/// DEPYLER-0556: defaultdict(factory) creates HashMap with default values
///
/// - `defaultdict(int)` → `HashMap::new()` (use entry API for default 0)
/// - `defaultdict(list)` → `HashMap::new()` (use entry API for default vec)
/// - `defaultdict()` → `HashMap::new()`
///
/// Note: Python's defaultdict auto-creates missing values. In Rust, we use
/// the entry API: `map.entry(key).or_insert_with(factory)` or `.or_default()`
///
/// # Complexity: 3
pub fn convert_defaultdict_builtin(
    ctx: &mut CodeGenContext,
    _args: &[syn::Expr],
) -> Result<syn::Expr> {
    ctx.needs_hashmap = true;
    // defaultdict(int), defaultdict(list), defaultdict(str), defaultdict()
    // All translate to HashMap::new() since Rust uses entry API for defaults
    Ok(parse_quote! { HashMap::new() })
}

/// Convert Python dict() constructor to Rust HashMap
///
/// DEPYLER-0172: dict() converts mapping/iterable to HashMap
///
/// - `dict()` → `HashMap::new()`
/// - `dict(mapping)` → `mapping.into_iter().collect::<HashMap<_, _>>()`
///
/// # Complexity: 4
pub fn convert_dict_builtin(ctx: &mut CodeGenContext, args: &[syn::Expr]) -> Result<syn::Expr> {
    ctx.needs_hashmap = true;
    if args.is_empty() {
        Ok(parse_quote! { std::collections::HashMap::new() })
    } else if args.len() == 1 {
        let arg = &args[0];
        Ok(parse_quote! {
            #arg.into_iter().collect::<std::collections::HashMap<_, _>>()
        })
    } else {
        bail!("dict() takes at most 1 argument ({} given)", args.len())
    }
}

/// Convert Python deque() to Rust VecDeque
///
/// DEPYLER-0173: deque(iterable) creates VecDeque from iterable
/// DEPYLER-1165: In NASA mode, wrap elements in DepylerValue for heterogeneous deques
///
/// - `deque()` → `VecDeque::new()`
/// - `deque(iterable)` → `VecDeque::from(iterable)`
/// - In NASA mode: `deque([1,2,3])` → `VecDeque::from(vec![1,2,3].into_iter().map(DepylerValue::from).collect::<Vec<_>>())`
///
/// # Complexity: 6
pub fn convert_deque_builtin(ctx: &mut CodeGenContext, args: &[syn::Expr]) -> Result<syn::Expr> {
    ctx.needs_vecdeque = true;
    if args.is_empty() {
        Ok(parse_quote! { VecDeque::new() })
    } else if args.len() == 1 {
        let arg = &args[0];
        // DEPYLER-1165: In NASA mode, wrap iterable elements in DepylerValue
        if ctx.type_mapper.nasa_mode {
            ctx.needs_depyler_value_enum = true;
            Ok(parse_quote! {
                VecDeque::from(#arg.into_iter().map(DepylerValue::from).collect::<Vec<_>>())
            })
        } else {
            Ok(parse_quote! {
                VecDeque::from(#arg)
            })
        }
    } else {
        bail!("deque() takes at most 1 argument ({} given)", args.len())
    }
}

/// Check if expression already ends with .collect()
///
/// # Complexity: 2
pub fn already_collected(expr: &syn::Expr) -> bool {
    if let syn::Expr::MethodCall(method_call) = expr {
        method_call.method == "collect"
    } else {
        false
    }
}

/// Check if expression is a range (0..5, start..end, etc.)
///
/// # Complexity: 1
pub fn is_range_expr(expr: &syn::Expr) -> bool {
    matches!(expr, syn::Expr::Range(_))
}

/// Check if expression is an iterator-producing expression
///
/// # Complexity: 4
pub fn is_iterator_expr(expr: &syn::Expr) -> bool {
    if let syn::Expr::MethodCall(method_call) = expr {
        let method_name = method_call.method.to_string();
        matches!(
            method_name.as_str(),
            "iter"
                | "iter_mut"
                | "into_iter"
                | "zip"
                | "map"
                | "filter"
                | "enumerate"
                | "chain"
                | "flat_map"
                | "take"
                | "skip"
                | "collect"
        )
    } else {
        false
    }
}

/// Check if expression is a CSV reader variable
///
/// DEPYLER-0452: Uses heuristic name-based detection
///
/// # Complexity: 4
pub fn is_csv_reader_var(expr: &syn::Expr) -> bool {
    if let syn::Expr::Path(path) = expr {
        if let Some(ident) = path.path.get_ident() {
            let var_name = ident.to_string();
            return var_name == "reader"
                || var_name.contains("csv")
                || var_name.ends_with("_reader")
                || var_name.starts_with("reader_");
        }
    }
    false
}

/// Convert Python list() to Rust Vec with smart handling
///
/// DEPYLER-0174: list(iterable) converts iterable to Vec
///
/// Handles special cases:
/// - Empty: `list()` → `Vec::new()`
/// - Already collected: return as-is
/// - Range: `list(range(5))` → `(0..5).collect::<Vec<_>>()`
/// - Iterator: `list(iter)` → `iter.collect::<Vec<_>>()`
/// - CSV reader: special handling for DictReader
/// - Default: `list(x)` → `x.into_iter().collect::<Vec<_>>()`
///
/// # Complexity: 9 (within limit)
pub fn convert_list_builtin(ctx: &mut CodeGenContext, args: &[syn::Expr]) -> Result<syn::Expr> {
    if args.is_empty() {
        return Ok(parse_quote! { Vec::new() });
    }

    if args.len() != 1 {
        bail!("list() takes at most 1 argument ({} given)", args.len());
    }

    let arg = &args[0];

    // DEPYLER-0177: Check if expression already collected
    if already_collected(arg) {
        return Ok(arg.clone());
    }

    // DEPYLER-0179: range(5) → (0..5).collect()
    if is_range_expr(arg) {
        return Ok(parse_quote! {
            (#arg).collect::<Vec<_>>()
        });
    }

    // DEPYLER-0176: zip(), enumerate() return iterators
    if is_iterator_expr(arg) {
        return Ok(parse_quote! {
            #arg.collect::<Vec<_>>()
        });
    }

    // DEPYLER-0452: CSV DictReader → use deserialize()
    if is_csv_reader_var(arg) {
        ctx.needs_csv = true;
        return Ok(parse_quote! {
            #arg.deserialize::<HashMap<String, String>>().collect::<Vec<_>>()
        });
    }

    // Regular iterable → collect to Vec
    Ok(parse_quote! {
        #arg.into_iter().collect::<Vec<_>>()
    })
}

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

    fn make_ctx() -> CodeGenContext<'static> {
        CodeGenContext::default()
    }

    #[test]
    fn test_already_collected_true() {
        let expr: syn::Expr = parse_quote! { items.collect::<Vec<_>>() };
        assert!(already_collected(&expr));
    }

    #[test]
    fn test_already_collected_false() {
        let expr: syn::Expr = parse_quote! { items.iter() };
        assert!(!already_collected(&expr));
    }

    #[test]
    fn test_is_range_expr_true() {
        let expr: syn::Expr = parse_quote! { 0..5 };
        assert!(is_range_expr(&expr));
    }

    #[test]
    fn test_is_range_expr_false() {
        let expr: syn::Expr = parse_quote! { vec![1, 2, 3] };
        assert!(!is_range_expr(&expr));
    }

    #[test]
    fn test_is_iterator_expr_zip() {
        let expr: syn::Expr = parse_quote! { a.iter().zip(b.iter()) };
        assert!(is_iterator_expr(&expr));
    }

    #[test]
    fn test_is_iterator_expr_map() {
        let expr: syn::Expr = parse_quote! { items.map(|x| x + 1) };
        assert!(is_iterator_expr(&expr));
    }

    #[test]
    fn test_is_csv_reader_var_true() {
        let expr: syn::Expr = parse_quote! { reader };
        assert!(is_csv_reader_var(&expr));

        let expr2: syn::Expr = parse_quote! { csv_reader };
        assert!(is_csv_reader_var(&expr2));
    }

    #[test]
    fn test_is_csv_reader_var_false() {
        let expr: syn::Expr = parse_quote! { items };
        assert!(!is_csv_reader_var(&expr));
    }

    // ========== convert_set_constructor tests ==========

    #[test]
    fn test_convert_set_constructor_empty() {
        let mut ctx = make_ctx();
        let result = convert_set_constructor(&mut ctx, &[]).unwrap();
        let code = quote::quote!(#result).to_string();
        assert!(code.contains("HashSet"));
        assert!(code.contains("new"));
        assert!(ctx.needs_hashset);
    }

    #[test]
    fn test_convert_set_constructor_with_iterable() {
        let mut ctx = make_ctx();
        let arg: syn::Expr = parse_quote! { items };
        let result = convert_set_constructor(&mut ctx, &[arg]).unwrap();
        let code = quote::quote!(#result).to_string();
        assert!(code.contains("collect"));
        assert!(code.contains("HashSet"));
    }

    #[test]
    fn test_convert_set_constructor_with_tuple() {
        let mut ctx = make_ctx();
        let arg: syn::Expr = parse_quote! { (1, 2, 3) };
        let result = convert_set_constructor(&mut ctx, &[arg]).unwrap();
        let code = quote::quote!(#result).to_string();
        // Tuple is converted via vec![elements] pattern
        assert!(code.contains("collect"));
        assert!(code.contains("HashSet"));
    }

    #[test]
    fn test_convert_set_constructor_too_many_args() {
        let mut ctx = make_ctx();
        let arg1: syn::Expr = parse_quote! { a };
        let arg2: syn::Expr = parse_quote! { b };
        let result = convert_set_constructor(&mut ctx, &[arg1, arg2]);
        assert!(result.is_err());
    }

    // ========== convert_frozenset_constructor tests ==========

    #[test]
    fn test_convert_frozenset_constructor_empty() {
        let mut ctx = make_ctx();
        let result = convert_frozenset_constructor(&mut ctx, &[]).unwrap();
        let code = quote::quote!(#result).to_string();
        assert!(code.contains("Arc"));
        assert!(code.contains("HashSet"));
        assert!(ctx.needs_hashset);
    }

    #[test]
    fn test_convert_frozenset_constructor_with_iterable() {
        let mut ctx = make_ctx();
        let arg: syn::Expr = parse_quote! { items };
        let result = convert_frozenset_constructor(&mut ctx, &[arg]).unwrap();
        let code = quote::quote!(#result).to_string();
        assert!(code.contains("Arc"));
        assert!(code.contains("collect"));
    }

    #[test]
    fn test_convert_frozenset_constructor_with_tuple() {
        let mut ctx = make_ctx();
        let arg: syn::Expr = parse_quote! { (1, 2, 3) };
        let result = convert_frozenset_constructor(&mut ctx, &[arg]).unwrap();
        let code = quote::quote!(#result).to_string();
        // Tuple converted via vec![elements] pattern wrapped in Arc
        assert!(code.contains("collect"));
        assert!(code.contains("Arc"));
    }

    #[test]
    fn test_convert_frozenset_constructor_too_many_args() {
        let mut ctx = make_ctx();
        let arg1: syn::Expr = parse_quote! { a };
        let arg2: syn::Expr = parse_quote! { b };
        let result = convert_frozenset_constructor(&mut ctx, &[arg1, arg2]);
        assert!(result.is_err());
    }

    // ========== convert_counter_builtin tests ==========

    #[test]
    fn test_convert_counter_builtin_empty() {
        let mut ctx = make_ctx();
        let result = convert_counter_builtin(&mut ctx, &[]).unwrap();
        let code = quote::quote!(#result).to_string();
        assert!(code.contains("HashMap :: new"));
        assert!(ctx.needs_hashmap);
    }

    #[test]
    fn test_convert_counter_builtin_with_iterable() {
        let mut ctx = make_ctx();
        let arg: syn::Expr = parse_quote! { items };
        let result = convert_counter_builtin(&mut ctx, &[arg]).unwrap();
        let code = quote::quote!(#result).to_string();
        assert!(code.contains("fold"));
        assert!(code.contains("entry"));
        assert!(code.contains("or_insert"));
    }

    #[test]
    fn test_convert_counter_builtin_too_many_args() {
        let mut ctx = make_ctx();
        let arg1: syn::Expr = parse_quote! { a };
        let arg2: syn::Expr = parse_quote! { b };
        let result = convert_counter_builtin(&mut ctx, &[arg1, arg2]);
        assert!(result.is_err());
    }

    // ========== convert_defaultdict_builtin tests ==========

    #[test]
    fn test_convert_defaultdict_builtin_empty() {
        let mut ctx = make_ctx();
        let result = convert_defaultdict_builtin(&mut ctx, &[]).unwrap();
        let code = quote::quote!(#result).to_string();
        assert!(code.contains("HashMap :: new"));
        assert!(ctx.needs_hashmap);
    }

    #[test]
    fn test_convert_defaultdict_builtin_with_factory() {
        let mut ctx = make_ctx();
        let arg: syn::Expr = parse_quote! { int };
        let result = convert_defaultdict_builtin(&mut ctx, &[arg]).unwrap();
        let code = quote::quote!(#result).to_string();
        // Always generates HashMap::new()
        assert!(code.contains("HashMap :: new"));
    }

    // ========== convert_dict_builtin tests ==========

    #[test]
    fn test_convert_dict_builtin_empty() {
        let mut ctx = make_ctx();
        let result = convert_dict_builtin(&mut ctx, &[]).unwrap();
        let code = quote::quote!(#result).to_string();
        assert!(code.contains("HashMap"));
        assert!(code.contains("new"));
        assert!(ctx.needs_hashmap);
    }

    #[test]
    fn test_convert_dict_builtin_with_mapping() {
        let mut ctx = make_ctx();
        let arg: syn::Expr = parse_quote! { items };
        let result = convert_dict_builtin(&mut ctx, &[arg]).unwrap();
        let code = quote::quote!(#result).to_string();
        assert!(code.contains("collect"));
        assert!(code.contains("HashMap"));
    }

    #[test]
    fn test_convert_dict_builtin_too_many_args() {
        let mut ctx = make_ctx();
        let arg1: syn::Expr = parse_quote! { a };
        let arg2: syn::Expr = parse_quote! { b };
        let result = convert_dict_builtin(&mut ctx, &[arg1, arg2]);
        assert!(result.is_err());
    }

    // ========== convert_deque_builtin tests ==========

    #[test]
    fn test_convert_deque_builtin_empty() {
        let mut ctx = make_ctx();
        let result = convert_deque_builtin(&mut ctx, &[]).unwrap();
        let code = quote::quote!(#result).to_string();
        assert!(code.contains("VecDeque"));
        assert!(code.contains("new"));
        assert!(ctx.needs_vecdeque);
    }

    #[test]
    fn test_convert_deque_builtin_with_iterable() {
        let mut ctx = make_ctx();
        let arg: syn::Expr = parse_quote! { items };
        let result = convert_deque_builtin(&mut ctx, &[arg]).unwrap();
        let code = quote::quote!(#result).to_string();
        assert!(code.contains("VecDeque"));
        assert!(code.contains("from"));
    }

    #[test]
    fn test_convert_deque_builtin_too_many_args() {
        let mut ctx = make_ctx();
        let arg1: syn::Expr = parse_quote! { a };
        let arg2: syn::Expr = parse_quote! { b };
        let result = convert_deque_builtin(&mut ctx, &[arg1, arg2]);
        assert!(result.is_err());
    }

    // ========== convert_list_builtin tests ==========

    #[test]
    fn test_convert_list_builtin_empty() {
        let mut ctx = make_ctx();
        let result = convert_list_builtin(&mut ctx, &[]).unwrap();
        let code = quote::quote!(#result).to_string();
        assert!(code.contains("Vec :: new"));
    }

    #[test]
    fn test_convert_list_builtin_with_iterable() {
        let mut ctx = make_ctx();
        let arg: syn::Expr = parse_quote! { items };
        let result = convert_list_builtin(&mut ctx, &[arg]).unwrap();
        let code = quote::quote!(#result).to_string();
        assert!(code.contains("collect"));
        assert!(code.contains("Vec"));
    }

    #[test]
    fn test_convert_list_builtin_with_range() {
        let mut ctx = make_ctx();
        let arg: syn::Expr = parse_quote! { 0..10 };
        let result = convert_list_builtin(&mut ctx, &[arg]).unwrap();
        let code = quote::quote!(#result).to_string();
        assert!(code.contains("collect"));
    }

    #[test]
    fn test_convert_list_builtin_already_collected() {
        let mut ctx = make_ctx();
        let arg: syn::Expr = parse_quote! { items.iter().collect::<Vec<_>>() };
        let result = convert_list_builtin(&mut ctx, &[arg.clone()]).unwrap();
        // Should return the same expression
        let code = quote::quote!(#result).to_string();
        assert!(code.contains("collect"));
    }

    #[test]
    fn test_convert_list_builtin_with_iterator() {
        let mut ctx = make_ctx();
        let arg: syn::Expr = parse_quote! { items.iter().filter(|x| *x > 0) };
        let result = convert_list_builtin(&mut ctx, &[arg]).unwrap();
        let code = quote::quote!(#result).to_string();
        assert!(code.contains("filter"));
        assert!(code.contains("collect"));
    }

    #[test]
    fn test_convert_list_builtin_with_csv_reader() {
        let mut ctx = make_ctx();
        let arg: syn::Expr = parse_quote! { reader };
        let result = convert_list_builtin(&mut ctx, &[arg]).unwrap();
        let code = quote::quote!(#result).to_string();
        assert!(code.contains("deserialize"));
        assert!(ctx.needs_csv);
    }

    #[test]
    fn test_convert_list_builtin_too_many_args() {
        let mut ctx = make_ctx();
        let arg1: syn::Expr = parse_quote! { a };
        let arg2: syn::Expr = parse_quote! { b };
        let result = convert_list_builtin(&mut ctx, &[arg1, arg2]);
        assert!(result.is_err());
    }

    // ========== Additional iterator detection tests ==========

    #[test]
    fn test_is_iterator_expr_enumerate() {
        let expr: syn::Expr = parse_quote! { items.enumerate() };
        assert!(is_iterator_expr(&expr));
    }

    #[test]
    fn test_is_iterator_expr_chain() {
        let expr: syn::Expr = parse_quote! { a.chain(b) };
        assert!(is_iterator_expr(&expr));
    }

    #[test]
    fn test_is_iterator_expr_take() {
        let expr: syn::Expr = parse_quote! { items.take(5) };
        assert!(is_iterator_expr(&expr));
    }

    #[test]
    fn test_is_iterator_expr_skip() {
        let expr: syn::Expr = parse_quote! { items.skip(5) };
        assert!(is_iterator_expr(&expr));
    }

    #[test]
    fn test_is_iterator_expr_flat_map() {
        let expr: syn::Expr = parse_quote! { items.flat_map(|x| x) };
        assert!(is_iterator_expr(&expr));
    }

    #[test]
    fn test_is_iterator_expr_iter() {
        let expr: syn::Expr = parse_quote! { items.iter() };
        assert!(is_iterator_expr(&expr));
    }

    #[test]
    fn test_is_iterator_expr_into_iter() {
        let expr: syn::Expr = parse_quote! { items.into_iter() };
        assert!(is_iterator_expr(&expr));
    }

    #[test]
    fn test_is_iterator_expr_non_iterator() {
        let expr: syn::Expr = parse_quote! { items.push(1) };
        assert!(!is_iterator_expr(&expr));
    }

    // ========== CSV reader detection tests ==========

    #[test]
    fn test_is_csv_reader_var_ends_with_reader() {
        let expr: syn::Expr = parse_quote! { csv_file_reader };
        assert!(is_csv_reader_var(&expr));
    }

    #[test]
    fn test_is_csv_reader_var_starts_with_reader() {
        let expr: syn::Expr = parse_quote! { reader_csv };
        assert!(is_csv_reader_var(&expr));
    }

    #[test]
    fn test_is_csv_reader_var_method_call() {
        // Method call is not a path expression
        let expr: syn::Expr = parse_quote! { file.reader() };
        assert!(!is_csv_reader_var(&expr));
    }

    // ========== Range expression tests ==========

    #[test]
    fn test_is_range_expr_inclusive() {
        let expr: syn::Expr = parse_quote! { 0..=5 };
        assert!(is_range_expr(&expr));
    }

    #[test]
    fn test_is_range_expr_half_open() {
        let expr: syn::Expr = parse_quote! { start..end };
        assert!(is_range_expr(&expr));
    }

    // ========== Edge case tests ==========

    #[test]
    fn test_already_collected_nested() {
        let expr: syn::Expr = parse_quote! { a.iter().filter(|x| true).collect::<Vec<_>>() };
        assert!(already_collected(&expr));
    }

    #[test]
    fn test_already_collected_literal() {
        let expr: syn::Expr = parse_quote! { 42 };
        assert!(!already_collected(&expr));
    }
}