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
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
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
//! Generator Yield Point Analysis
//!
//! DEPYLER-0262: This module analyzes generator functions to identify yield points
//! and plan the state machine transformation needed for proper coroutine execution.
//!
//! ## Problem
//! Current implementation executes the entire function body in state 0 and returns
//! at the first yield, never resuming. This causes:
//! - Unreachable code after yields
//! - Only one value yielded per generator
//! - Loops with yields don't iterate
//!
//! ## Solution
//! Transform the function into a resumable state machine where each yield point
//! becomes a state transition. Similar to async/await lowering.

use depyler_hir::hir::{HirExpr, HirFunction, HirStmt};
use std::collections::HashMap;

/// Represents a single yield point in the generator
#[derive(Debug, Clone, PartialEq)]
pub struct YieldPoint {
    /// State number for this yield point
    pub state_id: usize,
    /// The expression being yielded
    pub yield_expr: HirExpr,
    /// Variables that must be preserved across this yield
    pub live_vars: Vec<String>,
    /// Nesting depth (for loop handling)
    pub depth: usize,
}

/// Analysis result containing all yield points and transformation metadata
#[derive(Debug, Clone)]
pub struct YieldAnalysis {
    /// All yield points found in the function, in execution order
    pub yield_points: Vec<YieldPoint>,
    /// Variables that need to be in state struct (modified between yields)
    pub state_variables: Vec<String>,
    /// Map from state_id to the next statement after the yield
    pub resume_points: HashMap<usize, usize>,
}

impl YieldAnalysis {
    /// Create a new empty analysis
    pub fn new() -> Self {
        Self {
            yield_points: Vec::new(),
            state_variables: Vec::new(),
            resume_points: HashMap::new(),
        }
    }

    /// Analyze a generator function to find all yield points
    ///
    /// This is the entry point for yield point analysis. It walks the function
    /// body and identifies every yield statement, assigning state numbers.
    ///
    /// # Complexity: 3 (create + analyze + finalize)
    pub fn analyze(func: &HirFunction) -> Self {
        let mut analysis = Self::new();
        let mut state_counter = 1; // State 0 is initialization

        // Walk function body and find all yields
        for (idx, stmt) in func.body.iter().enumerate() {
            Self::analyze_stmt(stmt, &mut analysis, &mut state_counter, 0, idx);
        }

        // Finalize analysis (compute live variables, etc.)
        analysis.finalize();
        analysis
    }

    /// Recursively analyze a statement for yield points
    ///
    /// # Complexity: 6 (delegated to helpers)
    fn analyze_stmt(
        stmt: &HirStmt,
        analysis: &mut YieldAnalysis,
        state_counter: &mut usize,
        depth: usize,
        stmt_idx: usize,
    ) {
        match stmt {
            HirStmt::Expr(expr) => {
                Self::analyze_expr_stmt(expr, analysis, state_counter, depth, stmt_idx);
            }
            HirStmt::If {
                then_body,
                else_body,
                ..
            } => {
                Self::analyze_if_stmt(
                    then_body,
                    else_body,
                    analysis,
                    state_counter,
                    depth,
                    stmt_idx,
                );
            }
            HirStmt::While { body, .. } | HirStmt::For { body, .. } => {
                Self::analyze_loop_stmt(body, analysis, state_counter, depth, stmt_idx);
            }
            HirStmt::Try {
                body,
                handlers,
                orelse,
                finalbody,
            } => {
                Self::analyze_try_stmt(
                    body,
                    handlers,
                    orelse,
                    finalbody,
                    analysis,
                    state_counter,
                    (depth, stmt_idx),
                );
            }
            HirStmt::With { body, .. } => {
                Self::analyze_with_stmt(body, analysis, state_counter, depth, stmt_idx);
            }
            _ => {
                // Other statements don't affect control flow for yields
            }
        }
    }

    /// Analyze expression statement for yield
    ///
    /// # Complexity: 2
    #[inline]
    fn analyze_expr_stmt(
        expr: &HirExpr,
        analysis: &mut YieldAnalysis,
        state_counter: &mut usize,
        depth: usize,
        stmt_idx: usize,
    ) {
        if let Some(yield_expr) = Self::extract_yield_expr(expr) {
            let yield_point = YieldPoint {
                state_id: *state_counter,
                yield_expr,
                live_vars: Vec::new(),
                depth,
            };
            analysis.yield_points.push(yield_point);
            analysis.resume_points.insert(*state_counter, stmt_idx + 1);
            *state_counter += 1;
        }
    }

    /// Analyze if statement branches
    ///
    /// # Complexity: 3
    #[inline]
    fn analyze_if_stmt(
        then_body: &[HirStmt],
        else_body: &Option<Vec<HirStmt>>,
        analysis: &mut YieldAnalysis,
        state_counter: &mut usize,
        depth: usize,
        stmt_idx: usize,
    ) {
        for s in then_body {
            Self::analyze_stmt(s, analysis, state_counter, depth, stmt_idx);
        }
        if let Some(else_stmts) = else_body {
            for s in else_stmts {
                Self::analyze_stmt(s, analysis, state_counter, depth, stmt_idx);
            }
        }
    }

    /// Analyze loop body with increased depth
    ///
    /// # Complexity: 2
    #[inline]
    fn analyze_loop_stmt(
        body: &[HirStmt],
        analysis: &mut YieldAnalysis,
        state_counter: &mut usize,
        depth: usize,
        stmt_idx: usize,
    ) {
        for s in body {
            Self::analyze_stmt(s, analysis, state_counter, depth + 1, stmt_idx);
        }
    }

    /// Analyze try/except/else/finally blocks
    ///
    /// # Complexity: 5
    #[inline]
    fn analyze_try_stmt(
        body: &[HirStmt],
        handlers: &[depyler_hir::hir::ExceptHandler],
        orelse: &Option<Vec<HirStmt>>,
        finalbody: &Option<Vec<HirStmt>>,
        analysis: &mut YieldAnalysis,
        state_counter: &mut usize,
        context: (usize, usize), // (depth, stmt_idx)
    ) {
        let (depth, stmt_idx) = context;
        for s in body {
            Self::analyze_stmt(s, analysis, state_counter, depth, stmt_idx);
        }
        for handler in handlers {
            for s in &handler.body {
                Self::analyze_stmt(s, analysis, state_counter, depth, stmt_idx);
            }
        }
        if let Some(else_stmts) = orelse {
            for s in else_stmts {
                Self::analyze_stmt(s, analysis, state_counter, depth, stmt_idx);
            }
        }
        if let Some(finally_stmts) = finalbody {
            for s in finally_stmts {
                Self::analyze_stmt(s, analysis, state_counter, depth, stmt_idx);
            }
        }
    }

    /// Analyze with statement body
    ///
    /// # Complexity: 2
    #[inline]
    fn analyze_with_stmt(
        body: &[HirStmt],
        analysis: &mut YieldAnalysis,
        state_counter: &mut usize,
        depth: usize,
        stmt_idx: usize,
    ) {
        for s in body {
            Self::analyze_stmt(s, analysis, state_counter, depth, stmt_idx);
        }
    }

    /// Extract yield expression if present
    ///
    /// # Complexity: 2 (match + clone)
    fn extract_yield_expr(expr: &HirExpr) -> Option<HirExpr> {
        match expr {
            HirExpr::Yield { value } => value.as_ref().map(|v| *v.clone()),
            _ => None,
        }
    }

    /// Finalize analysis by computing live variables and state variables
    ///
    /// # Complexity: 2 (placeholder for future liveness analysis)
    fn finalize(&mut self) {
        // NOTE: Implement liveness analysis to determine which variables need capturing (tracked in DEPYLER-0424)
        // need to be preserved in the state struct.
        // For now, we'll rely on the existing GeneratorStateInfo analysis.
    }

    /// Check if this function contains any yields
    #[inline]
    pub fn has_yields(&self) -> bool {
        !self.yield_points.is_empty()
    }

    /// Get the number of states needed (including state 0 for initialization)
    #[inline]
    pub fn num_states(&self) -> usize {
        self.yield_points.len() + 1
    }
}

impl Default for YieldAnalysis {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use depyler_hir::hir::*;
    use depyler_annotations::TranspilationAnnotations;
    use smallvec::smallvec;

    // === YieldPoint tests ===

    #[test]
    fn test_yield_point_new() {
        let yp = YieldPoint {
            state_id: 5,
            yield_expr: HirExpr::Literal(Literal::Int(42)),
            live_vars: vec!["x".to_string(), "y".to_string()],
            depth: 2,
        };
        assert_eq!(yp.state_id, 5);
        assert_eq!(yp.live_vars.len(), 2);
        assert_eq!(yp.depth, 2);
    }

    #[test]
    fn test_yield_point_clone() {
        let yp = YieldPoint {
            state_id: 1,
            yield_expr: HirExpr::Var("x".to_string()),
            live_vars: vec!["x".to_string()],
            depth: 0,
        };
        let cloned = yp.clone();
        assert_eq!(cloned.state_id, yp.state_id);
        assert_eq!(cloned.depth, yp.depth);
    }

    #[test]
    fn test_yield_point_eq() {
        let yp1 = YieldPoint {
            state_id: 1,
            yield_expr: HirExpr::Literal(Literal::Int(1)),
            live_vars: vec![],
            depth: 0,
        };
        let yp2 = YieldPoint {
            state_id: 1,
            yield_expr: HirExpr::Literal(Literal::Int(1)),
            live_vars: vec![],
            depth: 0,
        };
        assert_eq!(yp1, yp2);
    }

    #[test]
    fn test_yield_point_debug() {
        let yp = YieldPoint {
            state_id: 3,
            yield_expr: HirExpr::Literal(Literal::Int(99)),
            live_vars: vec!["z".to_string()],
            depth: 1,
        };
        let debug = format!("{:?}", yp);
        assert!(debug.contains("state_id"));
        assert!(debug.contains("3"));
    }

    // === YieldAnalysis tests ===

    #[test]
    fn test_yield_analysis_new() {
        let analysis = YieldAnalysis::new();
        assert!(analysis.yield_points.is_empty());
        assert!(analysis.state_variables.is_empty());
        assert!(analysis.resume_points.is_empty());
    }

    #[test]
    fn test_yield_analysis_default() {
        let analysis = YieldAnalysis::default();
        assert!(analysis.yield_points.is_empty());
    }

    #[test]
    fn test_yield_analysis_has_yields_empty() {
        let analysis = YieldAnalysis::new();
        assert!(!analysis.has_yields());
    }

    #[test]
    fn test_yield_analysis_has_yields_true() {
        let mut analysis = YieldAnalysis::new();
        analysis.yield_points.push(YieldPoint {
            state_id: 1,
            yield_expr: HirExpr::Literal(Literal::Int(1)),
            live_vars: vec![],
            depth: 0,
        });
        assert!(analysis.has_yields());
    }

    #[test]
    fn test_yield_analysis_num_states_empty() {
        let analysis = YieldAnalysis::new();
        assert_eq!(analysis.num_states(), 1); // Just state 0
    }

    #[test]
    fn test_yield_analysis_num_states_with_yields() {
        let mut analysis = YieldAnalysis::new();
        for i in 1..=5 {
            analysis.yield_points.push(YieldPoint {
                state_id: i,
                yield_expr: HirExpr::Literal(Literal::Int(i as i64)),
                live_vars: vec![],
                depth: 0,
            });
        }
        assert_eq!(analysis.num_states(), 6); // State 0 + 5 yields
    }

    #[test]
    fn test_yield_analysis_clone() {
        let mut analysis = YieldAnalysis::new();
        analysis.yield_points.push(YieldPoint {
            state_id: 1,
            yield_expr: HirExpr::Literal(Literal::Int(1)),
            live_vars: vec!["a".to_string()],
            depth: 0,
        });
        analysis.state_variables.push("x".to_string());
        analysis.resume_points.insert(1, 2);

        let cloned = analysis.clone();
        assert_eq!(cloned.yield_points.len(), 1);
        assert_eq!(cloned.state_variables.len(), 1);
        assert_eq!(cloned.resume_points.len(), 1);
    }

    // === analyze function tests ===

    #[test]
    fn test_analyze_empty_function() {
        let func = HirFunction {
            name: "empty".to_string(),
            params: smallvec![],
            ret_type: Type::None,
            body: vec![],
            properties: FunctionProperties::default(),
            annotations: TranspilationAnnotations::default(),
            docstring: None,
        };

        let analysis = YieldAnalysis::analyze(&func);
        assert!(!analysis.has_yields());
        assert_eq!(analysis.num_states(), 1);
    }

    #[test]
    fn test_analyze_non_generator_function() {
        let func = HirFunction {
            name: "regular".to_string(),
            params: smallvec![],
            ret_type: Type::Int,
            body: vec![HirStmt::Return(Some(HirExpr::Literal(Literal::Int(42))))],
            properties: FunctionProperties::default(),
            annotations: TranspilationAnnotations::default(),
            docstring: None,
        };

        let analysis = YieldAnalysis::analyze(&func);
        assert!(!analysis.has_yields());
    }

    #[test]
    fn test_analyze_yield_in_if_then() {
        let func = HirFunction {
            name: "if_yield".to_string(),
            params: smallvec![],
            ret_type: Type::Int,
            body: vec![HirStmt::If {
                condition: HirExpr::Var("cond".to_string()),
                then_body: vec![HirStmt::Expr(HirExpr::Yield {
                    value: Some(Box::new(HirExpr::Literal(Literal::Int(1)))),
                })],
                else_body: None,
            }],
            properties: FunctionProperties {
                is_generator: true,
                ..Default::default()
            },
            annotations: TranspilationAnnotations::default(),
            docstring: None,
        };

        let analysis = YieldAnalysis::analyze(&func);
        assert_eq!(analysis.yield_points.len(), 1);
    }

    #[test]
    fn test_analyze_yield_in_if_else() {
        let func = HirFunction {
            name: "if_else_yield".to_string(),
            params: smallvec![],
            ret_type: Type::Int,
            body: vec![HirStmt::If {
                condition: HirExpr::Var("cond".to_string()),
                then_body: vec![HirStmt::Expr(HirExpr::Yield {
                    value: Some(Box::new(HirExpr::Literal(Literal::Int(1)))),
                })],
                else_body: Some(vec![HirStmt::Expr(HirExpr::Yield {
                    value: Some(Box::new(HirExpr::Literal(Literal::Int(2)))),
                })]),
            }],
            properties: FunctionProperties {
                is_generator: true,
                ..Default::default()
            },
            annotations: TranspilationAnnotations::default(),
            docstring: None,
        };

        let analysis = YieldAnalysis::analyze(&func);
        assert_eq!(analysis.yield_points.len(), 2);
    }

    #[test]
    fn test_analyze_yield_in_for_loop() {
        let func = HirFunction {
            name: "for_yield".to_string(),
            params: smallvec![],
            ret_type: Type::Int,
            body: vec![HirStmt::For {
                target: AssignTarget::Symbol("i".to_string()),
                iter: HirExpr::Var("range".to_string()),
                body: vec![HirStmt::Expr(HirExpr::Yield {
                    value: Some(Box::new(HirExpr::Var("i".to_string()))),
                })],
            }],
            properties: FunctionProperties {
                is_generator: true,
                ..Default::default()
            },
            annotations: TranspilationAnnotations::default(),
            docstring: None,
        };

        let analysis = YieldAnalysis::analyze(&func);
        assert_eq!(analysis.yield_points.len(), 1);
        assert_eq!(analysis.yield_points[0].depth, 1); // Inside loop = depth 1
    }

    #[test]
    fn test_analyze_yield_in_nested_loops() {
        let func = HirFunction {
            name: "nested_yield".to_string(),
            params: smallvec![],
            ret_type: Type::Int,
            body: vec![HirStmt::While {
                condition: HirExpr::Literal(Literal::Bool(true)),
                body: vec![HirStmt::For {
                    target: AssignTarget::Symbol("i".to_string()),
                    iter: HirExpr::Var("items".to_string()),
                    body: vec![HirStmt::Expr(HirExpr::Yield {
                        value: Some(Box::new(HirExpr::Var("i".to_string()))),
                    })],
                }],
            }],
            properties: FunctionProperties {
                is_generator: true,
                ..Default::default()
            },
            annotations: TranspilationAnnotations::default(),
            docstring: None,
        };

        let analysis = YieldAnalysis::analyze(&func);
        assert_eq!(analysis.yield_points.len(), 1);
        assert_eq!(analysis.yield_points[0].depth, 2); // Nested = depth 2
    }

    #[test]
    fn test_analyze_yield_in_try_body() {
        let func = HirFunction {
            name: "try_yield".to_string(),
            params: smallvec![],
            ret_type: Type::Int,
            body: vec![HirStmt::Try {
                body: vec![HirStmt::Expr(HirExpr::Yield {
                    value: Some(Box::new(HirExpr::Literal(Literal::Int(1)))),
                })],
                handlers: vec![],
                orelse: None,
                finalbody: None,
            }],
            properties: FunctionProperties {
                is_generator: true,
                ..Default::default()
            },
            annotations: TranspilationAnnotations::default(),
            docstring: None,
        };

        let analysis = YieldAnalysis::analyze(&func);
        assert_eq!(analysis.yield_points.len(), 1);
    }

    #[test]
    fn test_analyze_yield_in_except_handler() {
        let func = HirFunction {
            name: "except_yield".to_string(),
            params: smallvec![],
            ret_type: Type::Int,
            body: vec![HirStmt::Try {
                body: vec![],
                handlers: vec![ExceptHandler {
                    exception_type: Some("Exception".to_string()),
                    name: Some("e".to_string()),
                    body: vec![HirStmt::Expr(HirExpr::Yield {
                        value: Some(Box::new(HirExpr::Literal(Literal::Int(99)))),
                    })],
                }],
                orelse: None,
                finalbody: None,
            }],
            properties: FunctionProperties {
                is_generator: true,
                ..Default::default()
            },
            annotations: TranspilationAnnotations::default(),
            docstring: None,
        };

        let analysis = YieldAnalysis::analyze(&func);
        assert_eq!(analysis.yield_points.len(), 1);
    }

    #[test]
    fn test_analyze_yield_in_finally() {
        let func = HirFunction {
            name: "finally_yield".to_string(),
            params: smallvec![],
            ret_type: Type::Int,
            body: vec![HirStmt::Try {
                body: vec![],
                handlers: vec![],
                orelse: None,
                finalbody: Some(vec![HirStmt::Expr(HirExpr::Yield {
                    value: Some(Box::new(HirExpr::Literal(Literal::Int(0)))),
                })]),
            }],
            properties: FunctionProperties {
                is_generator: true,
                ..Default::default()
            },
            annotations: TranspilationAnnotations::default(),
            docstring: None,
        };

        let analysis = YieldAnalysis::analyze(&func);
        assert_eq!(analysis.yield_points.len(), 1);
    }

    #[test]
    fn test_analyze_yield_in_with() {
        let func = HirFunction {
            name: "with_yield".to_string(),
            params: smallvec![],
            ret_type: Type::Int,
            body: vec![HirStmt::With {
                context: HirExpr::Var("ctx".to_string()),
                target: Some("f".to_string()),
                body: vec![HirStmt::Expr(HirExpr::Yield {
                    value: Some(Box::new(HirExpr::Var("f".to_string()))),
                })],
                is_async: false,
            }],
            properties: FunctionProperties {
                is_generator: true,
                ..Default::default()
            },
            annotations: TranspilationAnnotations::default(),
            docstring: None,
        };

        let analysis = YieldAnalysis::analyze(&func);
        assert_eq!(analysis.yield_points.len(), 1);
    }

    #[test]
    fn test_resume_points_tracking() {
        let func = HirFunction {
            name: "resume".to_string(),
            params: smallvec![],
            ret_type: Type::Int,
            body: vec![
                HirStmt::Expr(HirExpr::Yield {
                    value: Some(Box::new(HirExpr::Literal(Literal::Int(1)))),
                }),
                HirStmt::Expr(HirExpr::Yield {
                    value: Some(Box::new(HirExpr::Literal(Literal::Int(2)))),
                }),
            ],
            properties: FunctionProperties {
                is_generator: true,
                ..Default::default()
            },
            annotations: TranspilationAnnotations::default(),
            docstring: None,
        };

        let analysis = YieldAnalysis::analyze(&func);
        assert_eq!(analysis.resume_points.len(), 2);
        // Resume after first yield (index 0) should be statement index 1
        assert_eq!(analysis.resume_points.get(&1), Some(&1));
        // Resume after second yield (index 1) should be statement index 2
        assert_eq!(analysis.resume_points.get(&2), Some(&2));
    }

    #[test]
    fn test_yield_none_value() {
        let func = HirFunction {
            name: "yield_none".to_string(),
            params: smallvec![],
            ret_type: Type::None,
            body: vec![HirStmt::Expr(HirExpr::Yield { value: None })],
            properties: FunctionProperties {
                is_generator: true,
                ..Default::default()
            },
            annotations: TranspilationAnnotations::default(),
            docstring: None,
        };

        let analysis = YieldAnalysis::analyze(&func);
        // yield without value is not extracted (returns None from extract_yield_expr)
        // because extract_yield_expr returns value.as_ref().map(...)
        assert_eq!(analysis.yield_points.len(), 0);
    }

    // === Original tests ===

    #[test]
    #[allow(non_snake_case)]
    fn test_depyler_0262_simple_yield_detection() {
        // Test: Single yield in function body
        let func = HirFunction {
            name: "simple".to_string(),
            params: smallvec![],
            ret_type: Type::Int,
            body: vec![HirStmt::Expr(HirExpr::Yield {
                value: Some(Box::new(HirExpr::Literal(Literal::Int(42)))),
            })],
            properties: FunctionProperties {
                is_generator: true,
                ..Default::default()
            },
            annotations: TranspilationAnnotations::default(),
            docstring: None,
        };

        let analysis = YieldAnalysis::analyze(&func);

        assert_eq!(analysis.yield_points.len(), 1, "Should find 1 yield");
        assert_eq!(analysis.yield_points[0].state_id, 1);
        assert_eq!(analysis.num_states(), 2); // State 0 + 1 yield
    }

    #[test]
    #[allow(non_snake_case)]
    fn test_depyler_0262_loop_with_yield() {
        // Test: Yield inside a while loop (the main bug scenario)
        let func = HirFunction {
            name: "counter".to_string(),
            params: smallvec![],
            ret_type: Type::Int,
            body: vec![HirStmt::While {
                condition: HirExpr::Literal(Literal::Bool(true)),
                body: vec![HirStmt::Expr(HirExpr::Yield {
                    value: Some(Box::new(HirExpr::Var("i".to_string()))),
                })],
            }],
            properties: FunctionProperties {
                is_generator: true,
                ..Default::default()
            },
            annotations: TranspilationAnnotations::default(),
            docstring: None,
        };

        let analysis = YieldAnalysis::analyze(&func);

        assert_eq!(analysis.yield_points.len(), 1);
        assert_eq!(analysis.yield_points[0].depth, 1, "Yield is at depth 1");
    }

    #[test]
    #[allow(non_snake_case)]
    fn test_depyler_0262_multiple_yields() {
        // Test: Multiple sequential yields
        let func = HirFunction {
            name: "multi".to_string(),
            params: smallvec![],
            ret_type: Type::Int,
            body: vec![
                HirStmt::Expr(HirExpr::Yield {
                    value: Some(Box::new(HirExpr::Literal(Literal::Int(1)))),
                }),
                HirStmt::Expr(HirExpr::Yield {
                    value: Some(Box::new(HirExpr::Literal(Literal::Int(2)))),
                }),
                HirStmt::Expr(HirExpr::Yield {
                    value: Some(Box::new(HirExpr::Literal(Literal::Int(3)))),
                }),
            ],
            properties: FunctionProperties {
                is_generator: true,
                ..Default::default()
            },
            annotations: TranspilationAnnotations::default(),
            docstring: None,
        };

        let analysis = YieldAnalysis::analyze(&func);

        assert_eq!(analysis.yield_points.len(), 3);
        assert_eq!(analysis.yield_points[0].state_id, 1);
        assert_eq!(analysis.yield_points[1].state_id, 2);
        assert_eq!(analysis.yield_points[2].state_id, 3);
        assert_eq!(analysis.num_states(), 4); // State 0 + 3 yields
    }

    // === Additional edge case tests ===

    #[test]
    fn test_extract_yield_expr_with_value() {
        let expr = HirExpr::Yield {
            value: Some(Box::new(HirExpr::Literal(Literal::Int(42)))),
        };
        let result = YieldAnalysis::extract_yield_expr(&expr);
        assert!(result.is_some());
        if let Some(HirExpr::Literal(Literal::Int(n))) = result {
            assert_eq!(n, 42);
        } else {
            panic!("Expected Int literal");
        }
    }

    #[test]
    fn test_extract_yield_expr_without_value() {
        let expr = HirExpr::Yield { value: None };
        let result = YieldAnalysis::extract_yield_expr(&expr);
        assert!(result.is_none());
    }

    #[test]
    fn test_extract_yield_expr_not_yield() {
        let expr = HirExpr::Literal(Literal::Int(42));
        let result = YieldAnalysis::extract_yield_expr(&expr);
        assert!(result.is_none());
    }

    #[test]
    fn test_analyze_yield_in_try_else() {
        let func = HirFunction {
            name: "try_else_yield".to_string(),
            params: smallvec![],
            ret_type: Type::Int,
            body: vec![HirStmt::Try {
                body: vec![],
                handlers: vec![],
                orelse: Some(vec![HirStmt::Expr(HirExpr::Yield {
                    value: Some(Box::new(HirExpr::Literal(Literal::Int(77)))),
                })]),
                finalbody: None,
            }],
            properties: FunctionProperties {
                is_generator: true,
                ..Default::default()
            },
            annotations: TranspilationAnnotations::default(),
            docstring: None,
        };

        let analysis = YieldAnalysis::analyze(&func);
        assert_eq!(analysis.yield_points.len(), 1);
    }

    #[test]
    fn test_analyze_all_try_blocks_with_yields() {
        let func = HirFunction {
            name: "try_all_yield".to_string(),
            params: smallvec![],
            ret_type: Type::Int,
            body: vec![HirStmt::Try {
                body: vec![HirStmt::Expr(HirExpr::Yield {
                    value: Some(Box::new(HirExpr::Literal(Literal::Int(1)))),
                })],
                handlers: vec![ExceptHandler {
                    exception_type: Some("Exception".to_string()),
                    name: None,
                    body: vec![HirStmt::Expr(HirExpr::Yield {
                        value: Some(Box::new(HirExpr::Literal(Literal::Int(2)))),
                    })],
                }],
                orelse: Some(vec![HirStmt::Expr(HirExpr::Yield {
                    value: Some(Box::new(HirExpr::Literal(Literal::Int(3)))),
                })]),
                finalbody: Some(vec![HirStmt::Expr(HirExpr::Yield {
                    value: Some(Box::new(HirExpr::Literal(Literal::Int(4)))),
                })]),
            }],
            properties: FunctionProperties {
                is_generator: true,
                ..Default::default()
            },
            annotations: TranspilationAnnotations::default(),
            docstring: None,
        };

        let analysis = YieldAnalysis::analyze(&func);
        assert_eq!(analysis.yield_points.len(), 4);
    }

    #[test]
    fn test_yield_analysis_debug() {
        let analysis = YieldAnalysis::new();
        let debug = format!("{:?}", analysis);
        assert!(debug.contains("yield_points"));
        assert!(debug.contains("state_variables"));
        assert!(debug.contains("resume_points"));
    }

    #[test]
    fn test_yield_point_different_state_ids() {
        let yp1 = YieldPoint {
            state_id: 1,
            yield_expr: HirExpr::Literal(Literal::Int(1)),
            live_vars: vec![],
            depth: 0,
        };
        let yp2 = YieldPoint {
            state_id: 2,
            yield_expr: HirExpr::Literal(Literal::Int(1)),
            live_vars: vec![],
            depth: 0,
        };
        assert_ne!(yp1, yp2);
    }

    #[test]
    fn test_yield_point_different_depths() {
        let yp1 = YieldPoint {
            state_id: 1,
            yield_expr: HirExpr::Literal(Literal::Int(1)),
            live_vars: vec![],
            depth: 0,
        };
        let yp2 = YieldPoint {
            state_id: 1,
            yield_expr: HirExpr::Literal(Literal::Int(1)),
            live_vars: vec![],
            depth: 1,
        };
        assert_ne!(yp1, yp2);
    }

    #[test]
    fn test_analyze_while_loop() {
        let func = HirFunction {
            name: "while_yield".to_string(),
            params: smallvec![],
            ret_type: Type::Int,
            body: vec![HirStmt::While {
                condition: HirExpr::Var("running".to_string()),
                body: vec![HirStmt::Expr(HirExpr::Yield {
                    value: Some(Box::new(HirExpr::Literal(Literal::Int(1)))),
                })],
            }],
            properties: FunctionProperties {
                is_generator: true,
                ..Default::default()
            },
            annotations: TranspilationAnnotations::default(),
            docstring: None,
        };

        let analysis = YieldAnalysis::analyze(&func);
        assert_eq!(analysis.yield_points.len(), 1);
        assert_eq!(analysis.yield_points[0].depth, 1);
    }

    #[test]
    fn test_analyze_other_statements() {
        // Test that non-yield statements don't affect analysis
        let func = HirFunction {
            name: "mixed".to_string(),
            params: smallvec![],
            ret_type: Type::Int,
            body: vec![
                HirStmt::Assign {
                    target: AssignTarget::Symbol("x".to_string()),
                    value: HirExpr::Literal(Literal::Int(1)),
                    type_annotation: None,
                },
                HirStmt::Return(Some(HirExpr::Var("x".to_string()))),
            ],
            properties: FunctionProperties::default(),
            annotations: TranspilationAnnotations::default(),
            docstring: None,
        };

        let analysis = YieldAnalysis::analyze(&func);
        assert!(!analysis.has_yields());
    }

    #[test]
    fn test_finalize_method() {
        let mut analysis = YieldAnalysis::new();
        analysis.yield_points.push(YieldPoint {
            state_id: 1,
            yield_expr: HirExpr::Literal(Literal::Int(1)),
            live_vars: vec![],
            depth: 0,
        });
        analysis.finalize();
        // Currently finalize is a placeholder, just ensure it doesn't crash
        assert_eq!(analysis.yield_points.len(), 1);
    }

    #[test]
    fn test_multiple_handlers_with_yields() {
        let func = HirFunction {
            name: "multi_handler".to_string(),
            params: smallvec![],
            ret_type: Type::Int,
            body: vec![HirStmt::Try {
                body: vec![],
                handlers: vec![
                    ExceptHandler {
                        exception_type: Some("ValueError".to_string()),
                        name: None,
                        body: vec![HirStmt::Expr(HirExpr::Yield {
                            value: Some(Box::new(HirExpr::Literal(Literal::Int(1)))),
                        })],
                    },
                    ExceptHandler {
                        exception_type: Some("TypeError".to_string()),
                        name: None,
                        body: vec![HirStmt::Expr(HirExpr::Yield {
                            value: Some(Box::new(HirExpr::Literal(Literal::Int(2)))),
                        })],
                    },
                ],
                orelse: None,
                finalbody: None,
            }],
            properties: FunctionProperties {
                is_generator: true,
                ..Default::default()
            },
            annotations: TranspilationAnnotations::default(),
            docstring: None,
        };

        let analysis = YieldAnalysis::analyze(&func);
        assert_eq!(analysis.yield_points.len(), 2);
    }

    #[test]
    fn test_yield_expr_variable() {
        let func = HirFunction {
            name: "yield_var".to_string(),
            params: smallvec![],
            ret_type: Type::Int,
            body: vec![HirStmt::Expr(HirExpr::Yield {
                value: Some(Box::new(HirExpr::Var("result".to_string()))),
            })],
            properties: FunctionProperties {
                is_generator: true,
                ..Default::default()
            },
            annotations: TranspilationAnnotations::default(),
            docstring: None,
        };

        let analysis = YieldAnalysis::analyze(&func);
        assert_eq!(analysis.yield_points.len(), 1);
        if let HirExpr::Var(name) = &analysis.yield_points[0].yield_expr {
            assert_eq!(name, "result");
        } else {
            panic!("Expected Var expression");
        }
    }
}