lambdust 0.1.1

A Scheme dialect with gradual typing and effect systems
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
//! Bytecode compiler for Lambdust expressions and programs.

#![allow(dead_code)]

use super::instruction::{Instruction, OpCode, Operand, ConstantPool, ConstantValue, Bytecode};
use crate::ast::{Expr, Program, Literal, Formals, Binding};
use crate::diagnostics::{Result, Error, Spanned};
use crate::utils::SymbolId;
use std::time::Instant;

/// Options for bytecode compilation.
#[derive(Debug, Clone)]
pub struct CompilerOptions {
    /// Enable debug information generation
    pub debug_info: bool,
    /// Enable profiling markers
    pub profiling: bool,
    /// Target stack size for optimization
    pub target_stack_size: usize,
    /// Enable aggressive optimizations
    pub aggressive_optimization: bool,
    /// Maximum number of local variables before spilling to heap
    pub max_local_variables: usize,
}

impl Default for CompilerOptions {
    fn default() -> Self {
        Self {
            debug_info: false,
            profiling: false,
            target_stack_size: 256,
            aggressive_optimization: false,
            max_local_variables: 256,
        }
    }
}

/// Result of bytecode compilation.
#[derive(Debug, Clone)]
pub struct CompilationResult {
    /// Generated bytecode
    pub bytecode: Bytecode,
    /// Constant pool  
    pub constant_pool: ConstantPool,
    /// Compilation statistics
    pub stats: CompilationStats,
}

/// Statistics about compilation process.
#[derive(Debug, Clone)]
pub struct CompilationStats {
    /// Number of expressions compiled
    pub expressions_compiled: usize,
    /// Number of instructions generated
    pub instructions_generated: usize,
    /// Number of constants created
    pub constants_created: usize,
    /// Compilation time in microseconds
    pub compilation_time_us: u64,
    /// Memory usage during compilation (bytes)
    pub memory_usage_bytes: usize,
    /// Number of local variables allocated
    pub local_variables: usize,
    /// Maximum stack depth required
    pub max_stack_depth: usize,
}

/// Local variable information during compilation.
#[derive(Debug, Clone)]
struct LocalVariable {
    /// Variable name
    name: String,
    /// Local index
    index: u16,
    /// Scope depth
    scope_depth: usize,
    /// Whether the variable is mutable
    mutable: bool,
}

/// Compilation context for tracking state during compilation.
#[derive(Debug)]
#[allow(dead_code)]
struct CompilerContext {
    /// Current local variables
    locals: Vec<LocalVariable>,
    /// Current scope depth
    scope_depth: usize,
    /// Current stack depth
    stack_depth: usize,
    /// Maximum stack depth reached
    max_stack_depth: usize,
    /// Loop context stack (for break/continue)
    loop_stack: Vec<LoopContext>,
    /// Function context stack
    function_stack: Vec<FunctionContext>,
}

/// Loop compilation context.
#[derive(Debug, Clone)]
#[allow(dead_code)]
struct LoopContext {
    /// Start of loop (for continue)
    start_label: usize,
    /// End of loop (for break)
    end_label: usize,
}

/// Function compilation context.
#[derive(Debug, Clone)]
#[allow(dead_code)]
struct FunctionContext {
    /// Function name (if any)
    name: Option<String>,
    /// Number of parameters
    param_count: usize,
    /// Return label
    return_label: usize,
}

/// The bytecode compiler.
pub struct BytecodeCompiler {
    /// Compilation options
    options: CompilerOptions,
    /// Compilation statistics
    stats: CompilationStats,
}

impl BytecodeCompiler {
    /// Creates a new bytecode compiler with the given options.
    pub fn new(options: CompilerOptions) -> Self {
        Self {
            options,
            stats: CompilationStats {
                expressions_compiled: 0,
                instructions_generated: 0,
                constants_created: 0,
                compilation_time_us: 0,
                memory_usage_bytes: 0,
                local_variables: 0,
                max_stack_depth: 0,
            },
        }
    }
    
    /// Compiles a program to bytecode.
    pub fn compile_program(&mut self, program: &Program) -> Result<CompilationResult> {
        let start_time = Instant::now();
        
        let mut bytecode = Bytecode::new();
        let mut constant_pool = ConstantPool::new();
        let mut context = CompilerContext {
            locals: Vec::new(),
            scope_depth: 0,
            stack_depth: 0,
            max_stack_depth: 0,
            loop_stack: Vec::new(),
            function_stack: Vec::new(),
        };
        
        // Compile each expression in sequence
        for expr in &program.expressions {
            self.compile_expression_internal(&expr.inner, &mut bytecode, &mut constant_pool, &mut context)?;
            // Pop result if not the last expression
            if expr != program.expressions.last().unwrap() {
                bytecode.add_instruction(Instruction::new(OpCode::Pop));
                context.stack_depth = context.stack_depth.saturating_sub(1);
            }
        }
        
        // Add halt instruction
        bytecode.add_instruction(Instruction::new(OpCode::Halt));
        
        // Update bytecode metadata
        bytecode.constants = constant_pool.clone();
        bytecode.local_count = context.locals.len();
        bytecode.max_stack_depth = context.max_stack_depth;
        
        // Update statistics
        self.stats.expressions_compiled += program.expressions.len();
        self.stats.instructions_generated += bytecode.instructions.len();
        self.stats.constants_created += constant_pool.len();
        self.stats.compilation_time_us += start_time.elapsed().as_micros() as u64;
        self.stats.memory_usage_bytes += bytecode.estimated_size();
        self.stats.local_variables = context.locals.len();
        self.stats.max_stack_depth = context.max_stack_depth;
        
        Ok(CompilationResult {
            bytecode,
            constant_pool,
            stats: self.stats.clone(),
        })
    }
    
    /// Compiles a single expression to bytecode.
    pub fn compile_expression(&mut self, expr: &Expr) -> Result<CompilationResult> {
        let start_time = Instant::now();
        
        let mut bytecode = Bytecode::new();
        let mut constant_pool = ConstantPool::new();
        let mut context = CompilerContext {
            locals: Vec::new(),
            scope_depth: 0,
            stack_depth: 0,
            max_stack_depth: 0,
            loop_stack: Vec::new(),
            function_stack: Vec::new(),
        };
        
        self.compile_expression_internal(expr, &mut bytecode, &mut constant_pool, &mut context)?;
        
        // Add halt instruction
        bytecode.add_instruction(Instruction::new(OpCode::Halt));
        
        // Update bytecode metadata  
        bytecode.constants = constant_pool.clone();
        bytecode.local_count = context.locals.len();
        bytecode.max_stack_depth = context.max_stack_depth;
        
        // Update statistics
        self.stats.expressions_compiled += 1;
        self.stats.instructions_generated += bytecode.instructions.len();
        self.stats.constants_created += constant_pool.len();
        self.stats.compilation_time_us += start_time.elapsed().as_micros() as u64;
        self.stats.memory_usage_bytes += bytecode.estimated_size();
        self.stats.local_variables = context.locals.len();
        self.stats.max_stack_depth = context.max_stack_depth;
        
        Ok(CompilationResult {
            bytecode,
            constant_pool,
            stats: self.stats.clone(),
        })
    }
    
    /// Internal expression compilation implementation.
    fn compile_expression_internal(
        &mut self,
        expr: &Expr,
        bytecode: &mut Bytecode,
        constant_pool: &mut ConstantPool,
        context: &mut CompilerContext,
    ) -> Result<()> {
        match expr {
            Expr::Literal(literal) => {
                self.compile_literal(literal, bytecode, constant_pool, context)
            }
            
            Expr::Symbol(symbol) => {
                let symbol_id = crate::utils::intern_symbol(symbol);
                self.compile_symbol_reference(symbol_id, bytecode, constant_pool, context)
            }
            
            Expr::Application { operator, operands } => {
                self.compile_application(operator, operands, bytecode, constant_pool, context)
            }
            
            Expr::Lambda { formals, body, metadata: _ } => {
                self.compile_lambda(formals, body, bytecode, constant_pool, context)
            }
            
            Expr::Define { name, value, metadata: _ } => {
                self.compile_define(name, value, bytecode, constant_pool, context)
            }
            
            Expr::Set { name, value } => {
                self.compile_set(name, value, bytecode, constant_pool, context)
            }
            
            Expr::If { test, consequent, alternative } => {
                self.compile_if(test, consequent, alternative.as_deref(), bytecode, constant_pool, context)
            }
            
            Expr::Begin(expressions) => {
                self.compile_begin(expressions, bytecode, constant_pool, context)
            }
            
            Expr::Let { bindings, body } => {
                self.compile_let(bindings, body, bytecode, constant_pool, context)
            }
            
            Expr::LetRec { bindings, body } => {
                self.compile_letrec(bindings, body, bytecode, constant_pool, context)
            }
            
            Expr::Quote(quoted) => {
                self.compile_quote(quoted, bytecode, constant_pool, context)
            }
            
            _ => Err(Box::new(Error::compilation_error(format!("Unsupported expression type: {expr:?}")))),
        }
    }
    
    /// Compiles a literal value.
    fn compile_literal(
        &mut self,
        literal: &Literal,
        bytecode: &mut Bytecode,
        constant_pool: &mut ConstantPool,
        context: &mut CompilerContext,
    ) -> Result<()> {
        let constant_value = match literal {
            Literal::ExactInteger(i) => ConstantValue::Number(*i as f64),
            Literal::InexactReal(f) => ConstantValue::Number(*f),
            Literal::Number(f) => ConstantValue::Number(*f),
            Literal::Rational { numerator, denominator } => {
                // Convert rational to float for now
                ConstantValue::Number(*numerator as f64 / *denominator as f64)
            }
            Literal::Complex { real, imaginary } => {
                // For now, just use the real part (TODO: proper complex number support)
                if *imaginary != 0.0 {
                    return Err(Box::new(Error::compilation_error("Complex literals not yet fully supported in bytecode".to_string())));
                }
                ConstantValue::Number(*real)
            }
            Literal::String(s) => ConstantValue::String(s.clone()),
            Literal::Boolean(b) => ConstantValue::Boolean(*b),
            Literal::Character(c) => ConstantValue::String(c.to_string()), // Store as string for simplicity
            Literal::Bytevector(_bytes) => {
                // Create a special constant for bytevectors
                return Err(Box::new(Error::compilation_error("Bytevector literals not yet supported in bytecode".to_string())));
            }
            Literal::Nil => {
                // Use a special nil constant or empty list representation
                ConstantValue::String("()".to_string()) // Simple representation for now
            }
            Literal::Unspecified => {
                // Unspecified values are typically not literals but we handle them anyway
                ConstantValue::String("#<unspecified>".to_string())
            }
        };
        
        let const_index = constant_pool.add_constant(constant_value);
        bytecode.add_instruction(Instruction::with_operand(OpCode::LoadConst, Operand::ConstIndex(const_index)));
        
        self.push_stack(context);
        Ok(())
    }
    
    /// Compiles a symbol reference.
    fn compile_symbol_reference(
        &mut self,
        symbol: SymbolId,
        bytecode: &mut Bytecode,
        _constant_pool: &mut ConstantPool,
        context: &mut CompilerContext,
    ) -> Result<()> {
        // Try to find as local variable first
        if let Some(local) = self.find_local(symbol, context) {
            bytecode.add_instruction(Instruction::with_operand(OpCode::LoadLocal, Operand::LocalIndex(local.index)));
        } else {
            // Load as global variable
            bytecode.add_instruction(Instruction::with_operand(OpCode::LoadGlobal, Operand::Symbol(symbol)));
        }
        
        self.push_stack(context);
        Ok(())
    }
    
    /// Compiles a function application.
    fn compile_application(
        &mut self,
        operator: &Spanned<Expr>,
        operands: &[Spanned<Expr>],
        bytecode: &mut Bytecode,
        constant_pool: &mut ConstantPool,
        context: &mut CompilerContext,
    ) -> Result<()> {
        // Check for special forms that can be optimized
        if let Expr::Symbol(symbol) = &operator.inner {
            let symbol_id = crate::utils::intern_symbol(symbol);
            if let Some(builtin_op) = self.get_builtin_operation(symbol_id) {
                return self.compile_builtin_operation(builtin_op, operands, bytecode, constant_pool, context);
            }
        }
        
        // Compile operands (arguments) first
        for operand in operands {
            self.compile_expression_internal(&operand.inner, bytecode, constant_pool, context)?;
        }
        
        // Compile operator (function)
        self.compile_expression_internal(&operator.inner, bytecode, constant_pool, context)?;
        
        // Generate call instruction
        let arg_count = operands.len() as u32;
        bytecode.add_instruction(Instruction::with_operand(OpCode::Call, Operand::U32(arg_count)));
        
        // Adjust stack depth (arguments + function are consumed, result is pushed)
        context.stack_depth = context.stack_depth.saturating_sub(operands.len() + 1);
        self.push_stack(context);
        
        Ok(())
    }
    
    /// Compiles a lambda expression.
    fn compile_lambda(
        &mut self,
        formals: &Formals,
        body: &[Spanned<Expr>],
        bytecode: &mut Bytecode,
        constant_pool: &mut ConstantPool,
        context: &mut CompilerContext,
    ) -> Result<()> {
        // Create a new bytecode for the lambda body
        let mut lambda_bytecode = Bytecode::new();
        let mut lambda_context = CompilerContext {
            locals: Vec::new(),
            scope_depth: 0,
            stack_depth: 0,
            max_stack_depth: 0,
            loop_stack: Vec::new(),
            function_stack: Vec::new(),
        };
        
        // Add parameters as local variables
        let _param_count = match formals {
            Formals::Fixed(params) => {
                for (i, param) in params.iter().enumerate() {
                    let local = LocalVariable {
                        name: param.clone(),
                        index: i as u16,
                        scope_depth: 0,
                        mutable: false,
                    };
                    lambda_context.locals.push(local);
                }
                params.len()
            }
            Formals::Variable(param) => {
                let local = LocalVariable {
                    name: param.clone(),
                    index: 0,
                    scope_depth: 0,
                    mutable: false,
                };
                lambda_context.locals.push(local);
                1
            }
            Formals::Mixed { fixed, rest } => {
                for (i, param) in fixed.iter().enumerate() {
                    let local = LocalVariable {
                        name: param.clone(),
                        index: i as u16,
                        scope_depth: 0,
                        mutable: false,
                    };
                    lambda_context.locals.push(local);
                }
                // Add rest parameter
                let rest_local = LocalVariable {
                    name: rest.clone(),
                    index: fixed.len() as u16,
                    scope_depth: 0,
                    mutable: false,
                };
                lambda_context.locals.push(rest_local);
                fixed.len() + 1
            }
            Formals::Keyword { fixed, rest, keywords: _ } => {
                for (i, param) in fixed.iter().enumerate() {
                    let local = LocalVariable {
                        name: param.clone(),
                        index: i as u16,
                        scope_depth: 0,
                        mutable: false,
                    };
                    lambda_context.locals.push(local);
                }
                let mut count = fixed.len();
                if let Some(rest) = rest {
                    let rest_local = LocalVariable {
                        name: rest.clone(),
                        index: count as u16,
                        scope_depth: 0,
                        mutable: false,
                    };
                    lambda_context.locals.push(rest_local);
                    count += 1;
                }
                // TODO: Handle keyword parameters properly
                count
            }
        };
        
        // Compile lambda body
        for (i, expr) in body.iter().enumerate() {
            self.compile_expression_internal(&expr.inner, &mut lambda_bytecode, constant_pool, &mut lambda_context)?;
            // Pop intermediate results except for the last expression
            if i < body.len() - 1 {
                lambda_bytecode.add_instruction(Instruction::new(OpCode::Pop));
                lambda_context.stack_depth = lambda_context.stack_depth.saturating_sub(1);
            }
        }
        
        // Add return instruction
        lambda_bytecode.add_instruction(Instruction::new(OpCode::Return));
        
        // Store lambda bytecode in constant pool
        let lambda_const = ConstantValue::Bytecode(lambda_bytecode.instructions);
        let const_index = constant_pool.add_constant(lambda_const);
        
        // Generate make closure instruction
        bytecode.add_instruction(Instruction::with_operand(OpCode::MakeClosure, Operand::ConstIndex(const_index)));
        
        self.push_stack(context);
        Ok(())
    }
    
    /// Compiles a define expression.
    fn compile_define(
        &mut self,
        name: &str,
        value: &Spanned<Expr>,
        bytecode: &mut Bytecode,
        constant_pool: &mut ConstantPool,
        context: &mut CompilerContext,
    ) -> Result<()> {
        // Compile the value
        self.compile_expression_internal(&value.inner, bytecode, constant_pool, context)?;
        
        // Store as global (simplified - would need proper symbol handling)
        let symbol_id = crate::utils::intern_symbol(name).id();
        bytecode.add_instruction(Instruction::with_operand(OpCode::StoreGlobal, Operand::Symbol(SymbolId::new(symbol_id))));
        
        // Pop the value from stack
        self.pop_stack(context);
        
        // Push unspecified as result
        let unspec_const = constant_pool.add_constant(ConstantValue::Boolean(false)); // Use false as unspecified placeholder
        bytecode.add_instruction(Instruction::with_operand(OpCode::LoadConst, Operand::ConstIndex(unspec_const)));
        self.push_stack(context);
        
        Ok(())
    }
    
    /// Compiles a set! expression.
    fn compile_set(
        &mut self,
        name: &str,
        value: &Spanned<Expr>,
        bytecode: &mut Bytecode,
        constant_pool: &mut ConstantPool,
        context: &mut CompilerContext,
    ) -> Result<()> {
        // Compile the value
        self.compile_expression_internal(&value.inner, bytecode, constant_pool, context)?;
        
        // Try to find as local variable first
        let symbol_id = crate::utils::intern_symbol(name).id();
        if let Some(local) = self.find_local(SymbolId::new(symbol_id), context) {
            if !local.mutable {
                return Err(Box::new(Error::compilation_error(format!("Cannot assign to immutable variable: {name}"))));
            }
            bytecode.add_instruction(Instruction::with_operand(OpCode::StoreLocal, Operand::LocalIndex(local.index)));
        } else {
            // Store as global
            bytecode.add_instruction(Instruction::with_operand(OpCode::StoreGlobal, Operand::Symbol(SymbolId::new(symbol_id))));
        }
        
        // Pop the value from stack
        self.pop_stack(context);
        
        // Push unspecified as result
        let unspec_const = constant_pool.add_constant(ConstantValue::Boolean(false));
        bytecode.add_instruction(Instruction::with_operand(OpCode::LoadConst, Operand::ConstIndex(unspec_const)));
        self.push_stack(context);
        
        Ok(())
    }
    
    /// Compiles an if expression.
    fn compile_if(
        &mut self,
        condition: &Spanned<Expr>,
        consequent: &Spanned<Expr>,
        alternative: Option<&Spanned<Expr>>,
        bytecode: &mut Bytecode,
        constant_pool: &mut ConstantPool,
        context: &mut CompilerContext,
    ) -> Result<()> {
        // Compile condition
        self.compile_expression_internal(&condition.inner, bytecode, constant_pool, context)?;
        
        // Jump if false to alternative/end
        let false_jump = bytecode.instructions.len();
        bytecode.add_instruction(Instruction::with_operand(OpCode::JumpIfFalse, Operand::JumpOffset(0))); // Will be patched
        self.pop_stack(context); // Condition is consumed
        
        // Compile consequent
        self.compile_expression_internal(&consequent.inner, bytecode, constant_pool, context)?;
        
        // Jump over alternative
        let end_jump = bytecode.instructions.len();
        bytecode.add_instruction(Instruction::with_operand(OpCode::Jump, Operand::JumpOffset(0))); // Will be patched
        
        // Patch false jump to point here
        let alternative_start = bytecode.instructions.len();
        if let Operand::JumpOffset(offset) = &mut bytecode.instructions[false_jump].operand {
            *offset = (alternative_start as i32) - (false_jump as i32);
        }
        
        // Pop consequent result if we're jumping to alternative
        self.pop_stack(context);
        
        // Compile alternative (or push unspecified)
        if let Some(alt) = alternative {
            self.compile_expression_internal(&alt.inner, bytecode, constant_pool, context)?;
        } else {
            // Push unspecified
            let unspec_const = constant_pool.add_constant(ConstantValue::Boolean(false));
            bytecode.add_instruction(Instruction::with_operand(OpCode::LoadConst, Operand::ConstIndex(unspec_const)));
            self.push_stack(context);
        }
        
        // Patch end jump
        let end_pos = bytecode.instructions.len();
        if let Operand::JumpOffset(offset) = &mut bytecode.instructions[end_jump].operand {
            *offset = (end_pos as i32) - (end_jump as i32);
        }
        
        Ok(())
    }
    
    /// Compiles a begin expression.
    fn compile_begin(
        &mut self,
        expressions: &[Spanned<Expr>],
        bytecode: &mut Bytecode,
        constant_pool: &mut ConstantPool,
        context: &mut CompilerContext,
    ) -> Result<()> {
        if expressions.is_empty() {
            // Push unspecified for empty begin
            let unspec_const = constant_pool.add_constant(ConstantValue::Boolean(false));
            bytecode.add_instruction(Instruction::with_operand(OpCode::LoadConst, Operand::ConstIndex(unspec_const)));
            self.push_stack(context);
            return Ok(());
        }
        
        for (i, expr) in expressions.iter().enumerate() {
            self.compile_expression_internal(&expr.inner, bytecode, constant_pool, context)?;
            
            // Pop intermediate results except for the last expression
            if i < expressions.len() - 1 {
                bytecode.add_instruction(Instruction::new(OpCode::Pop));
                self.pop_stack(context);
            }
        }
        
        Ok(())
    }
    
    /// Compiles a let expression.
    fn compile_let(
        &mut self,
        bindings: &[Binding],
        body: &[Spanned<Expr>],
        bytecode: &mut Bytecode,
        constant_pool: &mut ConstantPool,
        context: &mut CompilerContext,
    ) -> Result<()> {
        // Enter new scope
        self.enter_scope(context);
        
        // Compile binding values and create local variables
        for binding in bindings {
            // Compile the value
            self.compile_expression_internal(&binding.value.inner, bytecode, constant_pool, context)?;
            
            // Create local variable
            let local_index = context.locals.len() as u16;
            let local = LocalVariable {
                name: binding.name.clone(),
                index: local_index,
                scope_depth: context.scope_depth,
                mutable: false,
            };
            context.locals.push(local);
            
            // Store in local slot (the value is already on stack)
            bytecode.add_instruction(Instruction::with_operand(OpCode::StoreLocal, Operand::LocalIndex(local_index)));
            self.pop_stack(context); // Value is consumed by store
        }
        
        // Compile body
        self.compile_begin(body, bytecode, constant_pool, context)?;
        
        // Exit scope
        self.exit_scope(context);
        
        Ok(())
    }
    
    /// Compiles a letrec expression.
    fn compile_letrec(
        &mut self,
        bindings: &[Binding],
        body: &[Spanned<Expr>],
        bytecode: &mut Bytecode,
        constant_pool: &mut ConstantPool,
        context: &mut CompilerContext,
    ) -> Result<()> {
        // Enter new scope
        self.enter_scope(context);
        
        // Create local variables for all bindings first (with unspecified values)
        let unspec_const = constant_pool.add_constant(ConstantValue::Boolean(false));
        for binding in bindings {
            // Push unspecified value
            bytecode.add_instruction(Instruction::with_operand(OpCode::LoadConst, Operand::ConstIndex(unspec_const)));
            self.push_stack(context);
            
            // Create local variable
            let local_index = context.locals.len() as u16;
            let local = LocalVariable {
                name: binding.name.clone(),
                index: local_index,
                scope_depth: context.scope_depth,
                mutable: true, // letrec bindings are mutable during initialization
            };
            context.locals.push(local);
            
            // Store unspecified value
            bytecode.add_instruction(Instruction::with_operand(OpCode::StoreLocal, Operand::LocalIndex(local_index)));
            self.pop_stack(context);
        }
        
        // Now compile actual values and assign them
        for binding in bindings {
            self.compile_expression_internal(&binding.value.inner, bytecode, constant_pool, context)?;
            
            // Find the local variable
            if let Some(local) = self.find_local_by_name(&binding.name, context) {
                bytecode.add_instruction(Instruction::with_operand(OpCode::StoreLocal, Operand::LocalIndex(local.index)));
                self.pop_stack(context);
            } else {
                return Err(Box::new(Error::compilation_error(format!("Internal error: letrec binding not found: {}", binding.name))));
            }
        }
        
        // Compile body
        self.compile_begin(body, bytecode, constant_pool, context)?;
        
        // Exit scope
        self.exit_scope(context);
        
        Ok(())
    }
    
    /// Compiles a quote expression.
    fn compile_quote(
        &mut self,
        quoted: &Expr,
        bytecode: &mut Bytecode,
        constant_pool: &mut ConstantPool,
        context: &mut CompilerContext,
    ) -> Result<()> {
        // For now, only support literal quotes
        match quoted {
            Expr::Literal(literal) => {
                self.compile_literal(literal, bytecode, constant_pool, context)
            }
            Expr::Symbol(symbol) => {
                // Quote a symbol - store it as a constant
                let symbol_id = crate::utils::intern_symbol(symbol);
                let const_value = ConstantValue::Symbol(symbol_id);
                let const_index = constant_pool.add_constant(const_value);
                bytecode.add_instruction(Instruction::with_operand(OpCode::LoadConst, Operand::ConstIndex(const_index)));
                self.push_stack(context);
                Ok(())
            }
            _ => {
                Err(Box::new(Error::compilation_error("Complex quoted expressions not yet supported in bytecode".to_string())))
            }
        }
    }
    
    /// Compiles built-in operations that can be optimized.
    fn compile_builtin_operation(
        &mut self,
        op: BuiltinOperation,
        operands: &[Spanned<Expr>],
        bytecode: &mut Bytecode,
        constant_pool: &mut ConstantPool,
        context: &mut CompilerContext,
    ) -> Result<()> {
        match op {
            BuiltinOperation::Add => {
                // Compile all operands
                for operand in operands {
                    self.compile_expression_internal(&operand.inner, bytecode, constant_pool, context)?;
                }
                
                // Generate add instructions (fold left)
                for _ in 1..operands.len() {
                    bytecode.add_instruction(Instruction::new(OpCode::Add));
                    context.stack_depth = context.stack_depth.saturating_sub(1); // Two operands become one
                }
                
                // Handle empty case
                if operands.is_empty() {
                    let zero_const = constant_pool.add_constant(ConstantValue::Number(0.0));
                    bytecode.add_instruction(Instruction::with_operand(OpCode::LoadConst, Operand::ConstIndex(zero_const)));
                    self.push_stack(context);
                }
                
                Ok(())
            }
            
            BuiltinOperation::Subtract => {
                if operands.is_empty() {
                    return Err(Box::new(Error::compilation_error("- requires at least one argument".to_string())));
                }
                
                // Compile first operand
                self.compile_expression_internal(&operands[0].inner, bytecode, constant_pool, context)?;
                
                if operands.len() == 1 {
                    // Negate single argument
                    bytecode.add_instruction(Instruction::new(OpCode::Neg));
                } else {
                    // Subtract remaining arguments
                    for operand in &operands[1..] {
                        self.compile_expression_internal(&operand.inner, bytecode, constant_pool, context)?;
                        bytecode.add_instruction(Instruction::new(OpCode::Sub));
                        context.stack_depth = context.stack_depth.saturating_sub(1);
                    }
                }
                
                Ok(())
            }
            
            BuiltinOperation::Multiply => {
                // Similar to add
                for operand in operands {
                    self.compile_expression_internal(&operand.inner, bytecode, constant_pool, context)?;
                }
                
                for _ in 1..operands.len() {
                    bytecode.add_instruction(Instruction::new(OpCode::Mul));
                    context.stack_depth = context.stack_depth.saturating_sub(1);
                }
                
                if operands.is_empty() {
                    let one_const = constant_pool.add_constant(ConstantValue::Number(1.0));
                    bytecode.add_instruction(Instruction::with_operand(OpCode::LoadConst, Operand::ConstIndex(one_const)));
                    self.push_stack(context);
                }
                
                Ok(())
            }
            
            BuiltinOperation::Equal => {
                if operands.len() != 2 {
                    return Err(Box::new(Error::compilation_error("= requires exactly 2 arguments".to_string())));
                }
                
                self.compile_expression_internal(&operands[0].inner, bytecode, constant_pool, context)?;
                self.compile_expression_internal(&operands[1].inner, bytecode, constant_pool, context)?;
                bytecode.add_instruction(Instruction::new(OpCode::Eq));
                context.stack_depth = context.stack_depth.saturating_sub(1);
                
                Ok(())
            }
            
            BuiltinOperation::Cons => {
                if operands.len() != 2 {
                    return Err(Box::new(Error::compilation_error("cons requires exactly 2 arguments".to_string())));
                }
                
                self.compile_expression_internal(&operands[0].inner, bytecode, constant_pool, context)?;
                self.compile_expression_internal(&operands[1].inner, bytecode, constant_pool, context)?;
                bytecode.add_instruction(Instruction::new(OpCode::Cons));
                context.stack_depth = context.stack_depth.saturating_sub(1);
                
                Ok(())
            }
            
            BuiltinOperation::Car => {
                if operands.len() != 1 {
                    return Err(Box::new(Error::compilation_error("car requires exactly 1 argument".to_string())));
                }
                
                self.compile_expression_internal(&operands[0].inner, bytecode, constant_pool, context)?;
                bytecode.add_instruction(Instruction::new(OpCode::Car));
                
                Ok(())
            }
            
            BuiltinOperation::Cdr => {
                if operands.len() != 1 {
                    return Err(Box::new(Error::compilation_error("cdr requires exactly 1 argument".to_string())));
                }
                
                self.compile_expression_internal(&operands[0].inner, bytecode, constant_pool, context)?;
                bytecode.add_instruction(Instruction::new(OpCode::Cdr));
                
                Ok(())
            }
        }
    }
    
    /// Gets builtin operation for a symbol, if any.
    fn get_builtin_operation(&self, _symbol: SymbolId) -> Option<BuiltinOperation> {
        // This would need proper symbol name lookup
        // For now, return None to use general application
        None
    }
    
    /// Finds a local variable by symbol ID.
    fn find_local(&self, _symbol: SymbolId, _context: &CompilerContext) -> Option<&LocalVariable> {
        // This would need proper symbol name lookup
        // For now, return None
        None
    }
    
    /// Finds a local variable by name.
    fn find_local_by_name<'a>(&self, name: &str, context: &'a CompilerContext) -> Option<&'a LocalVariable> {
        context.locals.iter().rev().find(|local| local.name == name)
    }
    
    /// Enters a new lexical scope.
    fn enter_scope(&self, context: &mut CompilerContext) {
        context.scope_depth += 1;
    }
    
    /// Exits the current lexical scope.
    fn exit_scope(&self, context: &mut CompilerContext) {
        context.scope_depth = context.scope_depth.saturating_sub(1);
        
        // Remove locals from the exited scope
        context.locals.retain(|local| local.scope_depth <= context.scope_depth);
    }
    
    /// Updates stack depth for a push operation.
    fn push_stack(&self, context: &mut CompilerContext) {
        context.stack_depth += 1;
        context.max_stack_depth = context.max_stack_depth.max(context.stack_depth);
    }
    
    /// Updates stack depth for a pop operation.
    fn pop_stack(&self, context: &mut CompilerContext) {
        context.stack_depth = context.stack_depth.saturating_sub(1);
    }
    
    /// Gets compilation statistics.
    pub fn get_stats(&self) -> super::CompilerStats {
        super::CompilerStats {
            expressions_compiled: self.stats.expressions_compiled,
            instructions_generated: self.stats.instructions_generated,
            constants_count: self.stats.constants_created,
            compilation_time_us: self.stats.compilation_time_us,
            memory_usage_bytes: self.stats.memory_usage_bytes,
        }
    }
}

/// Built-in operations that can be compiled to optimized bytecode.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum BuiltinOperation {
    Add,
    Subtract,
    Multiply,
    Equal,
    Cons,
    Car,
    Cdr,
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::ast::Literal;
    
    #[test]
    fn test_compile_literal() {
        let mut compiler = BytecodeCompiler::new(CompilerOptions::default());
        let expr = Expr::Literal(Literal::Number(42.0));
        
        let result = compiler.compile_expression(&expr).unwrap();
        
        assert!(result.bytecode.instructions.len() > 0);
        assert_eq!(result.constant_pool.len(), 1);
        
        // Should have LoadConst and Halt instructions
        assert_eq!(result.bytecode.instructions[0].opcode, OpCode::LoadConst);
        assert_eq!(result.bytecode.instructions[1].opcode, OpCode::Halt);
    }
    
    #[test]
    fn test_compile_begin() {
        let mut compiler = BytecodeCompiler::new(CompilerOptions::default());
        let expressions = vec![
            Spanned::new(Expr::Literal(Literal::Number(1.0)), (0..0).into()),
            Spanned::new(Expr::Literal(Literal::Number(2.0)), (0..0).into()),
        ];
        let expr = Expr::Begin(expressions);
        
        let result = compiler.compile_expression(&expr).unwrap();
        
        // Should compile both expressions but only keep the last result
        assert!(result.bytecode.instructions.len() >= 4); // LoadConst, Pop, LoadConst, Halt
        assert_eq!(result.constant_pool.len(), 2);
    }
    
    #[test]
    fn test_compiler_stats() {
        let mut compiler = BytecodeCompiler::new(CompilerOptions::default());
        let expr = Expr::Literal(Literal::String("hello".to_string()));
        
        let _result = compiler.compile_expression(&expr).unwrap();
        let stats = compiler.get_stats();
        
        assert_eq!(stats.expressions_compiled, 1);
        assert!(stats.instructions_generated > 0);
        assert!(stats.constants_count > 0);
        assert!(stats.compilation_time_us > 0);
    }
}