waspy 0.9.0

A Python interpreter written in Rust, designed for WebAssembly.
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
use crate::compiler::context::CompilationContext;
use crate::compiler::expression::{emit_expr, emit_integer_power_operation};
use crate::ir::{IRBody, IRFunction, IROp, IRStatement, IRType, MemoryLayout};
use wasm_encoder::{BlockType, Function, Instruction, MemArg, ValType};

/// Compile an IR function into a WebAssembly function
pub fn compile_function(
    ir_func: &IRFunction,
    ctx: &mut CompilationContext,
    memory_layout: &MemoryLayout,
) -> Function {
    ctx.locals_map.clear();
    ctx.local_count = 0;

    for param in &ir_func.params {
        ctx.add_local(&param.name, param.param_type.clone());
    }

    // Scan for variable declarations to allocate locals
    scan_and_allocate_locals(&ir_func.body, ctx);

    // Determine local types for WebAssembly
    let mut locals = Vec::new();
    let num_params = ir_func.params.len() as u32;

    // Group locals by type
    let mut i32_count = 0;
    let mut f64_count = 0;

    // Count locals by type (excluding parameters)
    for i in num_params..ctx.local_count {
        match get_local_type_by_index(ctx, i) {
            IRType::Float => f64_count += 1,
            _ => i32_count += 1,
        }
    }

    // Add locals to function signature
    if i32_count > 0 {
        locals.push((i32_count, ValType::I32));
    }
    if f64_count > 0 {
        locals.push((f64_count, ValType::F64));
    }

    let mut func = Function::new(locals);

    // Compile the function body
    compile_body(&ir_func.body, &mut func, ctx, memory_layout);

    // Add default return value if no explicit return
    match ir_func.return_type {
        IRType::Float => {
            func.instruction(&Instruction::F64Const(0.0_f64.into()));
        }
        IRType::None => {
            func.instruction(&Instruction::I32Const(0));
        }
        _ => {
            func.instruction(&Instruction::I32Const(0));
        }
    }

    func.instruction(&Instruction::End);

    func
}

/// Get the type of a local variable by its index
fn get_local_type_by_index(ctx: &CompilationContext, index: u32) -> IRType {
    for local_info in ctx.locals_map.values() {
        if local_info.index == index {
            return local_info.var_type.clone();
        }
    }
    IRType::Int // Default to i32
}

/// Scan the function body for variable declarations and allocate local variables
pub fn scan_and_allocate_locals(body: &IRBody, ctx: &mut CompilationContext) {
    for stmt in &body.statements {
        match stmt {
            IRStatement::Assign {
                target, var_type, ..
            } => {
                if ctx.get_local_index(target).is_none() {
                    let var_type = var_type.clone().unwrap_or(IRType::Unknown);
                    ctx.add_local(target, var_type);
                }
            }
            IRStatement::TupleUnpack { targets, .. } => {
                for target in targets {
                    if ctx.get_local_index(target).is_none() {
                        ctx.add_local(target, IRType::Unknown);
                    }
                }
            }
            IRStatement::If {
                then_body,
                else_body,
                ..
            } => {
                scan_and_allocate_locals(then_body, ctx);
                if let Some(else_body) = else_body {
                    scan_and_allocate_locals(else_body, ctx);
                }
            }
            IRStatement::While { body, .. } => {
                scan_and_allocate_locals(body, ctx);
            }
            IRStatement::For {
                target,
                body,
                else_body,
                ..
            } => {
                // Allocate the loop variable
                if ctx.get_local_index(target).is_none() {
                    ctx.add_local(target, IRType::Unknown);
                }
                scan_and_allocate_locals(body, ctx);
                if let Some(else_body) = else_body {
                    scan_and_allocate_locals(else_body, ctx);
                }
            }
            IRStatement::TryExcept {
                try_body,
                except_handlers,
                finally_body,
            } => {
                scan_and_allocate_locals(try_body, ctx);

                for handler in except_handlers {
                    // Allocate exception variable if it exists
                    if let Some(name) = &handler.name {
                        if ctx.get_local_index(name).is_none() {
                            ctx.add_local(name, IRType::Unknown);
                        }
                    }
                    scan_and_allocate_locals(&handler.body, ctx);
                }

                if let Some(finally_body) = finally_body {
                    scan_and_allocate_locals(finally_body, ctx);
                }
            }
            IRStatement::With {
                optional_vars,
                body,
                ..
            } => {
                // Allocate context variable if it exists
                if let Some(name) = optional_vars {
                    if ctx.get_local_index(name).is_none() {
                        ctx.add_local(name, IRType::Unknown);
                    }
                }
                scan_and_allocate_locals(body, ctx);
            }
            _ => {}
        }
    }
}

/// Compile a function body into WebAssembly instructions
pub fn compile_body(
    body: &IRBody,
    func: &mut Function,
    ctx: &mut CompilationContext,
    memory_layout: &MemoryLayout,
) {
    for stmt in &body.statements {
        match stmt {
            IRStatement::Return(expr_opt) => {
                if let Some(expr) = expr_opt {
                    emit_expr(expr, func, ctx, memory_layout, None);
                } else {
                    func.instruction(&Instruction::I32Const(0));
                }
                func.instruction(&Instruction::Return);
            }
            IRStatement::Assign {
                target,
                value,
                var_type,
            } => {
                // Get the expected type for the assignment
                let expected_type = var_type
                    .as_ref()
                    .cloned()
                    .or_else(|| ctx.get_local_info(target).map(|info| info.var_type.clone()));

                // Emit code for the value
                emit_expr(value, func, ctx, memory_layout, expected_type.as_ref());

                if let Some(local_idx) = ctx.get_local_index(target) {
                    func.instruction(&Instruction::LocalSet(local_idx));
                } else {
                    // Handle the case where the variable is not found in the context
                    panic!("Variable {target} not found in context");
                }
            }
            IRStatement::TupleUnpack { targets, value } => {
                // Emit code for the value (should be a tuple)
                let _tuple_type = emit_expr(value, func, ctx, memory_layout, None);

                // Load tuple length
                func.instruction(&Instruction::LocalSet(ctx.temp_local));
                func.instruction(&Instruction::LocalGet(ctx.temp_local));
                func.instruction(&Instruction::I32Load(MemArg {
                    offset: 0,
                    align: 2,
                    memory_index: 0,
                }));

                // Verify that number of targets matches tuple length
                func.instruction(&Instruction::I32Const(targets.len() as i32));
                func.instruction(&Instruction::I32Ne);
                func.instruction(&Instruction::If(BlockType::Empty));
                // Error case: tuple size mismatch - for now just continue
                func.instruction(&Instruction::End);

                // Extract each element from the tuple and assign to target variables
                for (i, target) in targets.iter().enumerate() {
                    // Load tuple pointer
                    func.instruction(&Instruction::LocalGet(ctx.temp_local));

                    // Add offset to get element (4 + i*4)
                    func.instruction(&Instruction::I32Const(4 + (i as i32) * 4));
                    func.instruction(&Instruction::I32Add);

                    // Load element value
                    func.instruction(&Instruction::I32Load(MemArg {
                        offset: 0,
                        align: 2,
                        memory_index: 0,
                    }));

                    // Store in target variable
                    if let Some(local_idx) = ctx.get_local_index(target) {
                        func.instruction(&Instruction::LocalSet(local_idx));
                    } else {
                        panic!("Variable {target} not found in context");
                    }
                }
            }
            IRStatement::If {
                condition,
                then_body,
                else_body,
            } => {
                // Emit condition code, ensuring it returns a boolean
                emit_expr(condition, func, ctx, memory_layout, Some(&IRType::Bool));

                // If-else block with no result value
                func.instruction(&Instruction::If(BlockType::Empty));

                // branch
                compile_body(then_body, func, ctx, memory_layout);

                if let Some(else_body) = else_body {
                    func.instruction(&Instruction::Else);
                    // branch
                    compile_body(else_body, func, ctx, memory_layout);
                }

                func.instruction(&Instruction::End);
            }

            IRStatement::Raise { exception } => {
                // Mark exception as raised by setting exception flag
                // Try to get existing exception flag variable if in a try block
                let exception_flag_idx = ctx
                    .get_local_index("__exception_flag")
                    .unwrap_or_else(|| ctx.add_local("__exception_flag", IRType::Int));
                let exception_type_idx = ctx
                    .get_local_index("__exception_type")
                    .unwrap_or_else(|| ctx.add_local("__exception_type", IRType::Int));

                if let Some(exc_expr) = exception {
                    // Evaluate exception expression to get exception code/type
                    emit_expr(exc_expr, func, ctx, memory_layout, None);
                    // Store as exception type code
                    func.instruction(&Instruction::LocalSet(exception_type_idx));
                } else {
                    // Generic exception code
                    func.instruction(&Instruction::I32Const(0));
                    func.instruction(&Instruction::LocalSet(exception_type_idx));
                }

                // Set exception flag to 1
                func.instruction(&Instruction::I32Const(1));
                func.instruction(&Instruction::LocalSet(exception_flag_idx));
            }

            IRStatement::While { condition, body } => {
                // Loop block
                func.instruction(&Instruction::Block(BlockType::Empty));
                func.instruction(&Instruction::Loop(BlockType::Empty));

                // Condition check
                emit_expr(condition, func, ctx, memory_layout, Some(&IRType::Bool));
                func.instruction(&Instruction::BrIf(1));

                // Loop body
                compile_body(body, func, ctx, memory_layout);

                // Jump back to the start of the loop
                func.instruction(&Instruction::Br(0));

                // End of loop and block
                func.instruction(&Instruction::End);
                func.instruction(&Instruction::End);
            }
            IRStatement::Expression(expr) => {
                emit_expr(expr, func, ctx, memory_layout, None);
                func.instruction(&Instruction::Drop);
            }
            IRStatement::AttributeAssign {
                object,
                attribute,
                value,
            } => {
                // Emit code for the object (get reference)
                let obj_type = emit_expr(object, func, ctx, memory_layout, None);

                // Store the object reference temporarily
                func.instruction(&Instruction::LocalSet(ctx.temp_local));

                // Emit code for the value
                emit_expr(value, func, ctx, memory_layout, None);

                // Store the value temporarily
                func.instruction(&Instruction::LocalSet(ctx.temp_local + 1));

                // Load the object reference
                func.instruction(&Instruction::LocalGet(ctx.temp_local));

                // Check if object is a custom class
                if let crate::ir::IRType::Class(class_name) = &obj_type {
                    if let Some(class_info) = ctx.get_class_info(class_name) {
                        if let Some(&field_offset) = class_info.field_offsets.get(attribute) {
                            // Stack: object_ptr
                            // Load the value to store
                            func.instruction(&Instruction::LocalGet(ctx.temp_local + 1));
                            // Store value at object_ptr + field_offset
                            func.instruction(&Instruction::I32Store(MemArg {
                                offset: field_offset,
                                align: 2,
                                memory_index: 0,
                            }));
                            return;
                        }
                    }
                }

                // Fallback: drop everything
                func.instruction(&Instruction::Drop); // Drop object pointer
                func.instruction(&Instruction::Drop); // Drop value
            }

            IRStatement::AugAssign { target, value, op } => {
                // Get the local index
                if let Some(local_idx) = ctx.get_local_index(target) {
                    // Load the current value
                    func.instruction(&Instruction::LocalGet(local_idx));

                    // Emit code for the value to add/multiply/etc.
                    emit_expr(value, func, ctx, memory_layout, None);

                    // Apply the operation (add, multiply, etc.)
                    match op {
                        IROp::Add => {
                            func.instruction(&Instruction::I32Add);
                        }
                        IROp::Sub => {
                            func.instruction(&Instruction::I32Sub);
                        }
                        IROp::Mul => {
                            func.instruction(&Instruction::I32Mul);
                        }
                        IROp::Div => {
                            func.instruction(&Instruction::I32DivS);
                        }
                        IROp::Mod => {
                            func.instruction(&Instruction::I32RemS);
                        }
                        IROp::FloorDiv => {
                            func.instruction(&Instruction::I32DivS);
                        }
                        IROp::Pow => {
                            emit_integer_power_operation(func);
                        }
                        // Handle other operations with placeholder implementations
                        _ => {
                            // Default for unimplemented operations
                            func.instruction(&Instruction::Drop);
                            func.instruction(&Instruction::Drop);
                            func.instruction(&Instruction::I32Const(0));
                        }
                    }

                    // Store the result back
                    func.instruction(&Instruction::LocalSet(local_idx));
                } else {
                    // Variable not found
                    panic!("Variable {target} not found in context");
                }
            }

            IRStatement::AttributeAugAssign {
                object,
                attribute: _, // Ignore the attribute field for now
                value,
                op: _, // Ignore the operation for now
            } => {
                // This is a simplified implementation that doesn't actually perform the operation
                // It's just a placeholder to get the code to compile

                // Emit code for the object (get reference)
                emit_expr(object, func, ctx, memory_layout, None);

                // Emit code for the value
                emit_expr(value, func, ctx, memory_layout, None);

                // For now, just drop the values - we don't have a proper object system
                func.instruction(&Instruction::Drop);
                func.instruction(&Instruction::Drop);
            }

            IRStatement::For {
                target,
                iterable,
                body,
                else_body: _,
            } => {
                // Proper for loop implementation that iterates over lists
                // Allocate locals for loop variables:
                // - iterator_ptr: pointer to the list/iterable
                // - loop_counter: current index in the list
                // - list_length: length of the list

                let iterator_ptr_idx = ctx.add_local("__iter_ptr", IRType::Unknown);
                let loop_counter_idx = ctx.add_local("__iter_idx", IRType::Int);
                let list_length_idx = ctx.add_local("__iter_len", IRType::Int);
                let target_idx = ctx
                    .get_local_index(target)
                    .expect("Target variable not found");

                // Evaluate the iterable (should return a pointer to list or value)
                let iterable_type = emit_expr(iterable, func, ctx, memory_layout, None);

                match iterable_type {
                    IRType::List(_) | IRType::String => {
                        // Store the pointer to the list/string
                        func.instruction(&Instruction::LocalSet(iterator_ptr_idx));

                        // Get list length: load from memory at ptr+0
                        func.instruction(&Instruction::LocalGet(iterator_ptr_idx));
                        func.instruction(&Instruction::I32Load(MemArg {
                            offset: 0,
                            align: 2,
                            memory_index: 0,
                        }));
                        func.instruction(&Instruction::LocalSet(list_length_idx));

                        // Initialize loop counter to 0
                        func.instruction(&Instruction::I32Const(0));
                        func.instruction(&Instruction::LocalSet(loop_counter_idx));

                        // Loop structure
                        func.instruction(&Instruction::Block(BlockType::Empty));
                        func.instruction(&Instruction::Loop(BlockType::Empty));

                        // Check if counter >= length
                        func.instruction(&Instruction::LocalGet(loop_counter_idx));
                        func.instruction(&Instruction::LocalGet(list_length_idx));
                        func.instruction(&Instruction::I32GeS);
                        func.instruction(&Instruction::BrIf(1)); // Break if true

                        // Load element from list[counter]
                        // Memory: [length:i32][elem0:i32][elem1:i32]...
                        // Element at index i is at offset 4 + (i * 4)
                        func.instruction(&Instruction::LocalGet(iterator_ptr_idx));
                        func.instruction(&Instruction::LocalGet(loop_counter_idx));
                        func.instruction(&Instruction::I32Const(4));
                        func.instruction(&Instruction::I32Mul);
                        func.instruction(&Instruction::I32Add);
                        func.instruction(&Instruction::I32Load(MemArg {
                            offset: 0,
                            align: 2,
                            memory_index: 0,
                        }));

                        // Store element in target variable
                        func.instruction(&Instruction::LocalSet(target_idx));

                        // Execute the loop body
                        compile_body(body, func, ctx, memory_layout);

                        // Increment counter
                        func.instruction(&Instruction::LocalGet(loop_counter_idx));
                        func.instruction(&Instruction::I32Const(1));
                        func.instruction(&Instruction::I32Add);
                        func.instruction(&Instruction::LocalSet(loop_counter_idx));

                        // Loop back
                        func.instruction(&Instruction::Br(0));

                        // End of loop
                        func.instruction(&Instruction::End);
                        func.instruction(&Instruction::End);
                    }
                    IRType::Range => {
                        // Range object layout: [start:i32][stop:i32][step:i32][current:i32]
                        func.instruction(&Instruction::LocalSet(iterator_ptr_idx));

                        // Load start value into target
                        func.instruction(&Instruction::LocalGet(iterator_ptr_idx));
                        func.instruction(&Instruction::I32Load(MemArg {
                            offset: 0,
                            align: 2,
                            memory_index: 0,
                        }));
                        func.instruction(&Instruction::LocalSet(target_idx));

                        // Initialize loop counter to 0
                        func.instruction(&Instruction::I32Const(0));
                        func.instruction(&Instruction::LocalSet(loop_counter_idx));

                        // Loop structure
                        func.instruction(&Instruction::Block(BlockType::Empty));
                        func.instruction(&Instruction::Loop(BlockType::Empty));

                        // Load stop and step for comparison
                        func.instruction(&Instruction::LocalGet(iterator_ptr_idx));
                        func.instruction(&Instruction::I32Load(MemArg {
                            offset: 4,
                            align: 2,
                            memory_index: 0,
                        }));
                        func.instruction(&Instruction::LocalSet(list_length_idx));

                        // Check if current >= stop
                        func.instruction(&Instruction::LocalGet(target_idx));
                        func.instruction(&Instruction::LocalGet(list_length_idx));
                        func.instruction(&Instruction::I32GeS);
                        func.instruction(&Instruction::BrIf(1)); // Break if true

                        // Execute the loop body
                        compile_body(body, func, ctx, memory_layout);

                        // Increment by step
                        func.instruction(&Instruction::LocalGet(target_idx));
                        func.instruction(&Instruction::LocalGet(iterator_ptr_idx));
                        func.instruction(&Instruction::I32Load(MemArg {
                            offset: 8,
                            align: 2,
                            memory_index: 0,
                        }));
                        func.instruction(&Instruction::I32Add);
                        func.instruction(&Instruction::LocalSet(target_idx));

                        // Loop back
                        func.instruction(&Instruction::Br(0));

                        // End of loop
                        func.instruction(&Instruction::End);
                        func.instruction(&Instruction::End);
                    }
                    _ => {
                        // For non-list iterables, fall back to simple counting
                        // Treat the value as a count (integer)
                        func.instruction(&Instruction::LocalSet(target_idx));

                        // Simple loop: counter from 1 to value
                        func.instruction(&Instruction::Block(BlockType::Empty));
                        func.instruction(&Instruction::Loop(BlockType::Empty));

                        func.instruction(&Instruction::LocalGet(target_idx));
                        func.instruction(&Instruction::I32Const(0));
                        func.instruction(&Instruction::I32LeS);
                        func.instruction(&Instruction::BrIf(1));

                        // Execute body
                        compile_body(body, func, ctx, memory_layout);

                        // Decrement
                        func.instruction(&Instruction::LocalGet(target_idx));
                        func.instruction(&Instruction::I32Const(1));
                        func.instruction(&Instruction::I32Sub);
                        func.instruction(&Instruction::LocalSet(target_idx));

                        func.instruction(&Instruction::Br(0));
                        func.instruction(&Instruction::End);
                        func.instruction(&Instruction::End);
                    }
                }
            }

            IRStatement::TryExcept {
                try_body,
                except_handlers,
                finally_body,
            } => {
                // Implement exception handling with a global exception state
                // We use a special local variable to track if an exception was raised
                let exception_flag_idx = ctx.add_local("__exception_flag", IRType::Int);
                let exception_type_idx = ctx.add_local("__exception_type", IRType::Int);

                // Initialize exception flag to 0 (no exception)
                func.instruction(&Instruction::I32Const(0));
                func.instruction(&Instruction::LocalSet(exception_flag_idx));

                // Execute the try block
                compile_body(try_body, func, ctx, memory_layout);

                // Check if an exception was raised
                func.instruction(&Instruction::LocalGet(exception_flag_idx));
                func.instruction(&Instruction::I32Const(0));
                func.instruction(&Instruction::I32Eq);

                // If no exception (flag == 0), skip all except handlers and go to finally
                func.instruction(&Instruction::If(BlockType::Empty));

                // If an exception occurred, check handlers
                func.instruction(&Instruction::Else);

                // Try to match exception handlers
                for (idx, handler) in except_handlers.iter().enumerate() {
                    let is_last = idx == except_handlers.len() - 1;

                    // Check if this handler matches the exception type
                    // For now, match any exception if no type is specified, or match by type
                    if handler.exception_type.is_none() {
                        // Bare except: catches all exceptions
                        if let Some(var_name) = &handler.name {
                            let handler_var_idx = ctx
                                .get_local_index(var_name)
                                .unwrap_or_else(|| ctx.add_local(var_name, IRType::Unknown));
                            // Store exception type in the handler variable
                            func.instruction(&Instruction::LocalGet(exception_type_idx));
                            func.instruction(&Instruction::LocalSet(handler_var_idx));
                        }

                        // Execute handler body
                        compile_body(&handler.body, func, ctx, memory_layout);

                        // Clear exception flag
                        func.instruction(&Instruction::I32Const(0));
                        func.instruction(&Instruction::LocalSet(exception_flag_idx));
                    } else if let Some(exc_type) = &handler.exception_type {
                        // Typed exception handler
                        // Map exception type names to codes
                        let exc_code = match exc_type.as_str() {
                            "ZeroDivisionError" => 1,
                            "ValueError" => 2,
                            "TypeError" => 3,
                            "KeyError" => 4,
                            "IndexError" => 5,
                            "AttributeError" => 6,
                            "RuntimeError" => 7,
                            _ => 99, // Unknown exception type
                        };

                        func.instruction(&Instruction::Block(BlockType::Empty));

                        // Check if exception type matches
                        func.instruction(&Instruction::LocalGet(exception_type_idx));
                        func.instruction(&Instruction::I32Const(exc_code));
                        func.instruction(&Instruction::I32Eq);
                        func.instruction(&Instruction::I32Eqz);
                        func.instruction(&Instruction::BrIf(0)); // Branch to next handler if no match

                        if let Some(var_name) = &handler.name {
                            let handler_var_idx = ctx
                                .get_local_index(var_name)
                                .unwrap_or_else(|| ctx.add_local(var_name, IRType::Unknown));
                            func.instruction(&Instruction::LocalGet(exception_type_idx));
                            func.instruction(&Instruction::LocalSet(handler_var_idx));
                        }

                        // Execute handler body
                        compile_body(&handler.body, func, ctx, memory_layout);

                        // Clear exception flag and skip remaining handlers
                        func.instruction(&Instruction::I32Const(0));
                        func.instruction(&Instruction::LocalSet(exception_flag_idx));

                        func.instruction(&Instruction::End);
                    }

                    if is_last && handler.exception_type.is_some() {
                        // Add final block for unmatched exceptions
                        func.instruction(&Instruction::Block(BlockType::Empty));
                        // If we reach here and exception_flag is still set, no handler matched
                        func.instruction(&Instruction::End);
                    }
                }

                // End of exception handling
                func.instruction(&Instruction::End);
                func.instruction(&Instruction::End);

                // If there's a finally block, always execute it
                if let Some(finally_body) = finally_body {
                    compile_body(finally_body, func, ctx, memory_layout);
                }
            }

            IRStatement::With {
                context_expr,
                optional_vars,
                body,
            } => {
                // Context manager implementation
                // with expr as var: body
                // This requires calling __enter__ on the context manager and __exit__ after

                let context_var_idx = ctx.add_local("__context_mgr", IRType::Unknown);
                let exception_flag_idx = ctx
                    .get_local_index("__exception_flag")
                    .unwrap_or_else(|| ctx.add_local("__exception_flag", IRType::Int));

                // Evaluate context expression
                let ctx_type = emit_expr(context_expr, func, ctx, memory_layout, None);

                // Store context manager
                func.instruction(&Instruction::LocalSet(context_var_idx));

                // If optional_vars is provided, assign it the context manager value
                if let Some(var_name) = optional_vars {
                    let var_idx = ctx
                        .get_local_index(var_name)
                        .unwrap_or_else(|| ctx.add_local(var_name, ctx_type));
                    func.instruction(&Instruction::LocalGet(context_var_idx));
                    func.instruction(&Instruction::LocalSet(var_idx));
                }

                // Initialize exception flag for the with block
                let pre_exception_flag_idx = ctx.add_local("__pre_exception_flag", IRType::Int);
                func.instruction(&Instruction::LocalGet(exception_flag_idx));
                func.instruction(&Instruction::LocalSet(pre_exception_flag_idx));
                func.instruction(&Instruction::I32Const(0));
                func.instruction(&Instruction::LocalSet(exception_flag_idx));

                // Execute the body (may raise exceptions)
                compile_body(body, func, ctx, memory_layout);

                // Check if exception was raised
                func.instruction(&Instruction::LocalGet(exception_flag_idx));
                func.instruction(&Instruction::I32Const(0));
                func.instruction(&Instruction::I32Eq);
                func.instruction(&Instruction::If(BlockType::Empty));

                // No exception: normal exit
                // Restore pre-with exception state
                func.instruction(&Instruction::LocalGet(pre_exception_flag_idx));
                func.instruction(&Instruction::LocalSet(exception_flag_idx));

                func.instruction(&Instruction::Else);

                // Exception occurred: still need to run __exit__ with exception info
                // Restore pre-with exception state and re-raise if needed
                func.instruction(&Instruction::LocalGet(pre_exception_flag_idx));
                func.instruction(&Instruction::LocalSet(exception_flag_idx));

                func.instruction(&Instruction::End);
            }

            IRStatement::DynamicImport {
                target,
                module_name,
            } => {
                // Emit code to evaluate the module name expression
                emit_expr(module_name, func, ctx, memory_layout, None);

                // Get the target local index or create one if it doesn't exist
                let local_idx = ctx
                    .get_local_index(target)
                    .unwrap_or_else(|| ctx.add_local(target, IRType::Unknown));

                // Store the result (currently just a placeholder) in the target variable
                func.instruction(&Instruction::LocalSet(local_idx));
            }

            IRStatement::IndexAssign {
                container,
                index,
                value,
            } => {
                // Get container type to determine storage strategy
                let container_type = emit_expr(container, func, ctx, memory_layout, None);

                // Save container pointer
                func.instruction(&Instruction::LocalSet(ctx.temp_local));

                // Emit index expression
                emit_expr(index, func, ctx, memory_layout, Some(&IRType::Int));

                // Save index
                func.instruction(&Instruction::LocalSet(ctx.temp_local + 1));

                // Emit value expression
                let value_type = emit_expr(value, func, ctx, memory_layout, None);

                // Save value
                func.instruction(&Instruction::LocalSet(ctx.temp_local + 2));

                match container_type {
                    IRType::List(_) => {
                        // Calculate address: container_ptr + 4 + (index * 4)
                        func.instruction(&Instruction::LocalGet(ctx.temp_local)); // container_ptr
                        func.instruction(&Instruction::LocalGet(ctx.temp_local + 1)); // index
                        func.instruction(&Instruction::I32Const(4));
                        func.instruction(&Instruction::I32Mul); // index * 4
                        func.instruction(&Instruction::I32Const(4)); // skip length field
                        func.instruction(&Instruction::I32Add); // + 4
                        func.instruction(&Instruction::I32Add); // container_ptr + 4 + (index * 4)

                        // Restore value
                        func.instruction(&Instruction::LocalGet(ctx.temp_local + 2));

                        // Store based on value type
                        match value_type {
                            IRType::Float => {
                                func.instruction(&Instruction::F64Store(MemArg {
                                    offset: 0,
                                    align: 3,
                                    memory_index: 0,
                                }));
                            }
                            _ => {
                                func.instruction(&Instruction::I32Store(MemArg {
                                    offset: 0,
                                    align: 2,
                                    memory_index: 0,
                                }));
                            }
                        }
                    }
                    IRType::Dict(_key_type, _value_type) => {
                        // Dictionary assignment (linear search and update)
                        // For now, just store at a fixed offset after the entries
                        // TODO: Implement proper hash table or linear probe storage
                        func.instruction(&Instruction::LocalGet(ctx.temp_local)); // dict_ptr
                        func.instruction(&Instruction::LocalGet(ctx.temp_local + 1)); // key
                        func.instruction(&Instruction::LocalGet(ctx.temp_local + 2)); // value

                        // Just drop the values for now - proper implementation would search/update
                        func.instruction(&Instruction::Drop);
                        func.instruction(&Instruction::Drop);
                        func.instruction(&Instruction::Drop);
                    }
                    IRType::String => {
                        // String indexing is read-only in Python, assignment not directly supported
                        func.instruction(&Instruction::Drop);
                    }
                    _ => {
                        // Unknown container type
                        func.instruction(&Instruction::Drop);
                    }
                }
            }

            IRStatement::Yield { value } => {
                // Emit the yielded value expression
                if let Some(val) = value {
                    emit_expr(val, func, ctx, memory_layout, None);
                } else {
                    // yield without a value yields None
                    func.instruction(&Instruction::I32Const(0));
                }

                // For generator support, the yielded value would be stored
                // in a generator state and execution would be paused.
                // For now, this is a placeholder that just drops the value.
                func.instruction(&Instruction::Drop);
            }

            IRStatement::ImportModule { module_name, alias } => {
                // Create a variable to hold the imported module
                let var_name = alias.as_ref().unwrap_or(module_name);
                let _local_idx = ctx.add_local(var_name, IRType::Module(module_name.clone()));

                // For now, store a dummy module reference
                // Full implementation would load and execute the module
                func.instruction(&Instruction::I32Const(0));
                func.instruction(&Instruction::LocalSet(_local_idx));
            }
        }
    }
}