gaia-assembler 0.1.1

Universal assembler framework for Gaia project
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
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
//! JVM (Java Virtual Machine) backend compiler

use crate::{
    adapters::FunctionMapper,
    backends::{Backend, GeneratedFiles},
    config::GaiaConfig,
    instruction::{CoreInstruction, GaiaInstruction},
    program::{GaiaConstant, GaiaFunction, GaiaGlobal, GaiaModule},
    types::{GaiaType, mapping},
};
use gaia_types::{
    helpers::{AbiCompatible, ApiCompatible, Architecture, ArtifactType, CompilationTarget},
    GaiaError, Result,
};
use std::collections::HashMap;

#[cfg(feature = "jvm-assembler")]
use jvm_assembler::{
    formats::class::writer::ClassWriter,
    program::{JvmAccessFlags, JvmField, JvmInstruction, JvmMethod, JvmProgram, JvmVersion, JvmExceptionHandler},
};

#[cfg(not(feature = "jvm-assembler"))]
mod jvm_stub {
    pub struct JvmProgram;
}
#[cfg(not(feature = "jvm-assembler"))]
use jvm_stub::*;

/// JVM Backend implementation
#[derive(Default)]
pub struct JvmBackend {}

impl Backend for JvmBackend {
    fn name(&self) -> &'static str {
        "JVM"
    }

    fn primary_target(&self) -> CompilationTarget {
        CompilationTarget { build: Architecture::JVM, host: AbiCompatible::Unknown, target: ApiCompatible::JvmRuntime(8) }
    }

    fn artifact_type(&self) -> ArtifactType {
        ArtifactType::Bytecode
    }

    fn match_score(&self, target: &CompilationTarget) -> f32 {
        match target.build {
            Architecture::JVM => match target.host {
                // bytecode output, 80% support (primary)
                AbiCompatible::Unknown => 80.0,
                // jasm output, 5% support (disabled)
                AbiCompatible::JavaAssembly => 5.0,
                _ => -100.0,
            },
            _ => -100.0,
        }
    }

    fn generate(&self, program: &GaiaModule, config: &GaiaConfig) -> Result<GeneratedFiles> {
        #[cfg(feature = "jvm-assembler")]
        {
            let mut files = HashMap::new();

            // Convert GaiaModule to JvmProgram (with config and function mapping)
            let jvm_program = convert_gaia_to_jvm(program, config)?;

            match config.target.host {
                AbiCompatible::Unknown => {
                    // Generate .class bytecode file
                    let buffer = Vec::new();
                    let class_writer = ClassWriter::new(buffer);
                    let class_bytes = class_writer.write(&jvm_program).result?;
                    files.insert("main.class".to_string(), class_bytes);
                }
                AbiCompatible::JavaAssembly => {
                    return Err(GaiaError::custom_error("JASM output is currently disabled"));
                }
                _ => return Err(GaiaError::custom_error(&format!("Unsupported host ABI: {:?}", config.target.host))),
            }

            Ok(GeneratedFiles { artifact_type: self.artifact_type(), files, custom: None, diagnostics: vec![] })
        }
        #[cfg(not(feature = "jvm-assembler"))]
        {
            let _ = program;
            let _ = config;
            Err(gaia_types::errors::GaiaError::custom_error("JVM backend not enabled"))
        }
    }
}

impl JvmBackend {
    /// Generate JVM program from Gaia program
    pub fn generate_program(program: &GaiaModule) -> Result<JvmProgram> {
        #[cfg(feature = "jvm-assembler")]
        {
            // Generate with default configuration (maintain backward compatibility)
            let default_config = GaiaConfig::default();
            convert_gaia_to_jvm(program, &default_config)
        }
        #[cfg(not(feature = "jvm-assembler"))]
        {
            let _ = program;
            Err(gaia_types::errors::GaiaError::custom_error("JVM backend not enabled"))
        }
    }
}

#[cfg(feature = "jvm-assembler")]
/// JVM compilation context, carrying function mapping and target information
struct JvmContext {
    function_mapper: FunctionMapper,
    /// Field type mapping (class name, field name) -> descriptor
    field_types: HashMap<(String, String), String>,
}

#[cfg(feature = "jvm-assembler")]
/// Convert GaiaModule to JvmProgram
fn convert_gaia_to_jvm(program: &GaiaModule, config: &GaiaConfig) -> Result<JvmProgram> {
    let mut jvm_program = JvmProgram::new(program.name.clone());

    // Set version information
    jvm_program.version = JvmVersion { major: 52, minor: 0 }; // Java 8

    // Set access flags
    jvm_program.access_flags = JvmAccessFlags::public();

    // Build field type mapping
    let mut field_types = HashMap::new();
    for class in &program.classes {
        for field in &class.fields {
            field_types.insert((class.name.clone(), field.name.clone()), convert_gaia_type_to_jvm_descriptor(&field.ty));
        }
    }
    for global in &program.globals {
        field_types.insert(("Main".to_string(), global.name.clone()), convert_gaia_type_to_jvm_descriptor(&global.ty));
    }

    // Build context (initialize function mapping from config)
    let ctx = JvmContext { function_mapper: FunctionMapper::from_config(&config.setting)?, field_types };

    // Convert functions (with context)
    for function in &program.functions {
        let jvm_method = convert_gaia_function_to_jvm(function, &ctx)?;
        jvm_program.add_method(jvm_method);
    }

    // Convert classes
    for class in &program.classes {
        for field in &class.fields {
            let jvm_field = convert_gaia_field_to_jvm_field(field)?;
            jvm_program.add_field(jvm_field);
        }
        for method in &class.methods {
            let jvm_method = convert_gaia_function_to_jvm(method, &ctx)?;
            jvm_program.add_method(jvm_method);
        }
    }

    // Convert global variables to fields
    for global in &program.globals {
        let jvm_field = convert_gaia_global_to_jvm_field(global)?;
        jvm_program.add_field(jvm_field);
    }

    Ok(jvm_program)
}

#[cfg(feature = "jvm-assembler")]
/// Convert GaiaFunction to JvmMethod
fn convert_gaia_function_to_jvm(function: &GaiaFunction, ctx: &JvmContext) -> Result<JvmMethod> {
    // Build method descriptor
    let descriptor = build_method_descriptor(&function.signature.params, &Some(function.signature.return_type.clone()));

    let mut method = JvmMethod::new(function.name.clone(), descriptor);

    // Set access flags
    method.access_flags.is_public = true;
    method.access_flags.is_static = true;

    // 跟踪 try-catch-finally 块
    let mut try_blocks: Vec<()> = vec![];
    
    // 处理基本块
    for block in &function.blocks {
        // 为块添加标签
        if !block.label.is_empty() {
            method.add_instruction(JvmInstruction::Label { name: block.label.clone() });
        }
        
        // 收集当前块的指令
        let mut block_instructions = vec![];
        for instruction in &block.instructions {
            block_instructions.push(instruction.clone());
        }
        
        // 应用优化
        let optimized_block_instructions = constant_fold(&block_instructions);
        let optimized_block_instructions = eliminate_dead_code(&optimized_block_instructions);
        
        // 生成 JVM 指令
        for instruction in &optimized_block_instructions {
            match instruction {
                // 处理其他指令
                _ => {
                    let converted = convert_gaia_instruction_to_jvm(instruction, ctx)?;
                    for instr in converted {
                        method.add_instruction(instr);
                    }
                }
            }
        }

        // 处理终止指令
        let mut terminator_instructions = vec![];
        match &block.terminator {
            crate::program::GaiaTerminator::Jump(label) => {
                terminator_instructions.push(JvmInstruction::Goto { target: label.clone() });
            }
            crate::program::GaiaTerminator::Branch { true_label, false_label } => {
                // JVM usually jumps on false condition first, or true jump. Here we use Ifne (if not zero)
                terminator_instructions.push(JvmInstruction::Ifne { target: true_label.clone() });
                terminator_instructions.push(JvmInstruction::Goto { target: false_label.clone() });
            }
            crate::program::GaiaTerminator::Return => {
                // 根据返回类型选择合适的返回指令
                match function.signature.return_type {
                    GaiaType::I32 | GaiaType::U32 | GaiaType::I8 | GaiaType::U8 | GaiaType::I16 | GaiaType::U16 | GaiaType::Bool => {
                        terminator_instructions.push(JvmInstruction::Ireturn);
                    }
                    GaiaType::I64 | GaiaType::U64 => {
                        terminator_instructions.push(JvmInstruction::Lreturn);
                    }
                    GaiaType::F32 => {
                        terminator_instructions.push(JvmInstruction::Freturn);
                    }
                    GaiaType::F64 => {
                        terminator_instructions.push(JvmInstruction::Dreturn);
                    }
                    _ => {
                        terminator_instructions.push(JvmInstruction::Areturn);
                    }
                }
            }
            crate::program::GaiaTerminator::Call { callee, args_count: _, next_block } => {
                // JVM call mapping
                let jvm_target = CompilationTarget {
                    build: Architecture::JVM,
                    host: AbiCompatible::JavaAssembly,
                    target: ApiCompatible::JvmRuntime(8),
                };
                let mapped = ctx.function_mapper.map_function(&jvm_target, callee).unwrap_or(callee.as_str()).to_string();

                terminator_instructions.push(JvmInstruction::Invokestatic {
                    class_name: "Main".to_string(),
                    method_name: mapped,
                    descriptor: "()V".to_string(), // Simplified, actually needs to be determined by function signature
                });
                terminator_instructions.push(JvmInstruction::Goto { target: next_block.clone() });
            }
            crate::program::GaiaTerminator::Halt => {
                // In JVM, Halt can be mapped to System.exit(0)
                terminator_instructions.push(JvmInstruction::Iconst0);
                terminator_instructions.push(JvmInstruction::Invokestatic {
                    class_name: "java/lang/System".to_string(),
                    method_name: "exit".to_string(),
                    descriptor: "(I)V".to_string(),
                });
            }
        }
        
        // 应用 JVM 指令级优化
        let optimized_terminator_instructions = optimize_jvm_instructions(terminator_instructions);
        
        // 添加优化后的终止指令到方法
        for instr in optimized_terminator_instructions {
            method.add_instruction(instr);
        }
    }

    // Calculate stack and local variable sizes
    let (max_stack, max_locals) = calculate_stack_and_locals(function, ctx)?;
    method.max_stack = max_stack;
    method.max_locals = max_locals;

    Ok(method)
}

#[cfg(feature = "jvm-assembler")]
/// Convert GaiaField to JvmField
fn convert_gaia_field_to_jvm_field(field: &crate::program::GaiaField) -> Result<JvmField> {
    let descriptor = convert_gaia_type_to_jvm_descriptor(&field.ty);
    let mut jvm_field = JvmField::new(field.name.clone(), descriptor);

    if field.is_static {
        jvm_field.access_flags.is_static = true;
    }

    match field.visibility {
        crate::program::Visibility::Public => jvm_field.access_flags.is_public = true,
        crate::program::Visibility::Private => jvm_field.access_flags.is_private = true,
        crate::program::Visibility::Protected => jvm_field.access_flags.is_protected = true,
        _ => {}
    }

    Ok(jvm_field)
}

#[cfg(feature = "jvm-assembler")]
/// Convert GaiaGlobal to JvmField
fn convert_gaia_global_to_jvm_field(global: &GaiaGlobal) -> Result<JvmField> {
    let descriptor = convert_gaia_type_to_jvm_descriptor(&global.ty);
    let mut field = JvmField::new(global.name.clone(), descriptor);
    field.access_flags.is_public = true;
    field.access_flags.is_static = true;

    Ok(field)
}

#[cfg(feature = "jvm-assembler")]
/// 执行常量折叠优化
fn constant_fold(instructions: &[GaiaInstruction]) -> Vec<GaiaInstruction> {
    let mut optimized = vec![];
    let mut i = 0;
    
    while i < instructions.len() {
        // 检查是否是二元操作指令
        if i + 2 < instructions.len() {
            if let (GaiaInstruction::Core(CoreInstruction::PushConstant(c1)), 
                   GaiaInstruction::Core(CoreInstruction::PushConstant(c2)),
                   GaiaInstruction::Core(op)) = (&instructions[i], &instructions[i+1], &instructions[i+2]) {
                match op {
                    CoreInstruction::Add(ty) => {
                        if let (Some(result), _) = evaluate_binary_op(c1, c2, |a, b| a + b) {
                            optimized.push(GaiaInstruction::Core(CoreInstruction::PushConstant(result)));
                            i += 3;
                            continue;
                        }
                    }
                    CoreInstruction::Sub(ty) => {
                        if let (Some(result), _) = evaluate_binary_op(c1, c2, |a, b| a - b) {
                            optimized.push(GaiaInstruction::Core(CoreInstruction::PushConstant(result)));
                            i += 3;
                            continue;
                        }
                    }
                    CoreInstruction::Mul(ty) => {
                        if let (Some(result), _) = evaluate_binary_op(c1, c2, |a, b| a * b) {
                            optimized.push(GaiaInstruction::Core(CoreInstruction::PushConstant(result)));
                            i += 3;
                            continue;
                        }
                    }
                    CoreInstruction::Div(ty) => {
                        if let (Some(result), _) = evaluate_binary_op(c1, c2, |a, b| a / b) {
                            optimized.push(GaiaInstruction::Core(CoreInstruction::PushConstant(result)));
                            i += 3;
                            continue;
                        }
                    }
                    CoreInstruction::Rem(ty) => {
                        if let (Some(result), _) = evaluate_binary_op(c1, c2, |a, b| a % b) {
                            optimized.push(GaiaInstruction::Core(CoreInstruction::PushConstant(result)));
                            i += 3;
                            continue;
                        }
                    }
                    CoreInstruction::And(ty) => {
                        if let (Some(result), _) = evaluate_binary_op(c1, c2, |a, b| a & b) {
                            optimized.push(GaiaInstruction::Core(CoreInstruction::PushConstant(result)));
                            i += 3;
                            continue;
                        }
                    }
                    CoreInstruction::Or(ty) => {
                        if let (Some(result), _) = evaluate_binary_op(c1, c2, |a, b| a | b) {
                            optimized.push(GaiaInstruction::Core(CoreInstruction::PushConstant(result)));
                            i += 3;
                            continue;
                        }
                    }
                    CoreInstruction::Xor(ty) => {
                        if let (Some(result), _) = evaluate_binary_op(c1, c2, |a, b| a ^ b) {
                            optimized.push(GaiaInstruction::Core(CoreInstruction::PushConstant(result)));
                            i += 3;
                            continue;
                        }
                    }
                    _ => {}
                }
            }
        }
        
        // 检查是否是一元操作指令
        if i + 1 < instructions.len() {
            if let (GaiaInstruction::Core(CoreInstruction::PushConstant(c)), 
                   GaiaInstruction::Core(op)) = (&instructions[i], &instructions[i+1]) {
                match op {
                    CoreInstruction::Neg(ty) => {
                        if let Some(result) = evaluate_unary_op(c, |a| -a) {
                            optimized.push(GaiaInstruction::Core(CoreInstruction::PushConstant(result)));
                            i += 2;
                            continue;
                        }
                    }
                    CoreInstruction::Not(ty) => {
                        if let Some(result) = evaluate_unary_op(c, |a| !a) {
                            optimized.push(GaiaInstruction::Core(CoreInstruction::PushConstant(result)));
                            i += 2;
                            continue;
                        }
                    }
                    _ => {}
                }
            }
        }
        
        optimized.push(instructions[i].clone());
        i += 1;
    }
    
    optimized
}

#[cfg(feature = "jvm-assembler")]
/// 评估二元操作
fn evaluate_binary_op<F>(c1: &GaiaConstant, c2: &GaiaConstant, op: F) -> (Option<GaiaConstant>, GaiaType)
where F: Fn(i64, i64) -> i64 {
    match (c1, c2) {
        (GaiaConstant::I32(a), GaiaConstant::I32(b)) => {
            let result = op(*a as i64, *b as i64);
            (Some(GaiaConstant::I32(result as i32)), GaiaType::I32)
        }
        (GaiaConstant::I64(a), GaiaConstant::I64(b)) => {
            let result = op(*a, *b);
            (Some(GaiaConstant::I64(result)), GaiaType::I64)
        }
        (GaiaConstant::U32(a), GaiaConstant::U32(b)) => {
            let result = op(*a as i64, *b as i64);
            (Some(GaiaConstant::U32(result as u32)), GaiaType::U32)
        }
        (GaiaConstant::U64(a), GaiaConstant::U64(b)) => {
            let result = op(*a as i64, *b as i64);
            (Some(GaiaConstant::U64(result as u64)), GaiaType::U64)
        }
        _ => (None, GaiaType::I32)
    }
}

#[cfg(feature = "jvm-assembler")]
/// 评估一元操作
fn evaluate_unary_op<F>(c: &GaiaConstant, op: F) -> Option<GaiaConstant>
where F: Fn(i64) -> i64 {
    match c {
        GaiaConstant::I32(a) => {
            let result = op(*a as i64);
            Some(GaiaConstant::I32(result as i32))
        }
        GaiaConstant::I64(a) => {
            let result = op(*a);
            Some(GaiaConstant::I64(result))
        }
        GaiaConstant::U32(a) => {
            let result = op(*a as i64);
            Some(GaiaConstant::U32(result as u32))
        }
        GaiaConstant::U64(a) => {
            let result = op(*a as i64);
            Some(GaiaConstant::U64(result as u64))
        }
        GaiaConstant::Bool(a) => {
            Some(GaiaConstant::Bool(!*a))
        }
        _ => None
    }
}

#[cfg(feature = "jvm-assembler")]
/// 执行死代码消除
fn eliminate_dead_code(instructions: &[GaiaInstruction]) -> Vec<GaiaInstruction> {
    let mut optimized = vec![];
    let mut reachable = true;
    let mut i = 0;
    
    while i < instructions.len() {
        match &instructions[i] {
            GaiaInstruction::Core(CoreInstruction::Br(label)) => {
                optimized.push(instructions[i].clone());
                // 标记跳转到的标签为可达
                reachable = false;
                i += 1;
            }
            GaiaInstruction::Core(CoreInstruction::BrTrue(label)) | 
            GaiaInstruction::Core(CoreInstruction::BrFalse(label)) => {
                optimized.push(instructions[i].clone());
                // 条件分支后代码仍然可达
                i += 1;
            }
            GaiaInstruction::Core(CoreInstruction::Ret) => {
                optimized.push(instructions[i].clone());
                // return 后的代码不可达
                reachable = false;
                i += 1;
            }
            GaiaInstruction::Core(CoreInstruction::Label(name)) => {
                // 标签总是可达的
                optimized.push(instructions[i].clone());
                reachable = true;
                i += 1;
            }
            _ => {
                if reachable {
                    optimized.push(instructions[i].clone());
                }
                i += 1;
            }
        }
    }
    
    optimized
}

#[cfg(feature = "jvm-assembler")]
/// 优化 JVM 指令序列
fn optimize_jvm_instructions(instructions: Vec<JvmInstruction>) -> Vec<JvmInstruction> {
    let mut optimized = vec![];
    let mut i = 0;
    
    while i < instructions.len() {
        // 指令选择优化:使用更高效的指令
        match &instructions[i] {
            // 优化常量加载
            JvmInstruction::Bipush { value } if *value >= -1 && *value <= 5 => {
                match *value {
                    -1 => optimized.push(JvmInstruction::IconstM1),
                    0 => optimized.push(JvmInstruction::Iconst0),
                    1 => optimized.push(JvmInstruction::Iconst1),
                    2 => optimized.push(JvmInstruction::Iconst2),
                    3 => optimized.push(JvmInstruction::Iconst3),
                    4 => optimized.push(JvmInstruction::Iconst4),
                    5 => optimized.push(JvmInstruction::Iconst5),
                    _ => optimized.push(instructions[i].clone()),
                }
                i += 1;
                continue;
            }
            
            // 优化局部变量访问
            JvmInstruction::Iload { index } if *index <= 3 => {
                match *index {
                    0 => optimized.push(JvmInstruction::Iload0),
                    1 => optimized.push(JvmInstruction::Iload1),
                    2 => optimized.push(JvmInstruction::Iload2),
                    3 => optimized.push(JvmInstruction::Iload3),
                    _ => optimized.push(instructions[i].clone()),
                }
                i += 1;
                continue;
            }
            
            JvmInstruction::Istore { index } if *index <= 3 => {
                match *index {
                    0 => optimized.push(JvmInstruction::Istore0),
                    1 => optimized.push(JvmInstruction::Istore1),
                    2 => optimized.push(JvmInstruction::Istore2),
                    3 => optimized.push(JvmInstruction::Istore3),
                    _ => optimized.push(instructions[i].clone()),
                }
                i += 1;
                continue;
            }
            
            // 优化冗余指令
            JvmInstruction::Pop => {
                // 检查前一个指令是否是可以直接优化的
                if !optimized.is_empty() {
                    match optimized.last().unwrap() {
                        JvmInstruction::Iconst0 | JvmInstruction::Iconst1 | JvmInstruction::Iconst2 | 
                        JvmInstruction::Iconst3 | JvmInstruction::Iconst4 | JvmInstruction::Iconst5 | 
                        JvmInstruction::IconstM1 | JvmInstruction::AconstNull | 
                        JvmInstruction::Fconst0 | JvmInstruction::Fconst1 | JvmInstruction::Fconst2 | 
                        JvmInstruction::Dconst0 | JvmInstruction::Dconst1 | JvmInstruction::Lconst0 | 
                        JvmInstruction::Lconst1 => {
                            // 如果前一个指令是常量加载,且当前是 Pop,可以直接移除两者
                            optimized.pop();
                            i += 1;
                            continue;
                        }
                        _ => {}
                    }
                }
                optimized.push(instructions[i].clone());
                i += 1;
            }
            
            // 优化连续的相同指令
            _ => {
                if !optimized.is_empty() && optimized.last().unwrap() == &instructions[i] {
                    // 跳过连续的相同指令
                    i += 1;
                    continue;
                }
                optimized.push(instructions[i].clone());
                i += 1;
            }
        }
    }
    
    optimized
}

#[cfg(feature = "jvm-assembler")]
/// Convert GaiaInstruction to JvmInstruction
fn convert_gaia_instruction_to_jvm(instruction: &GaiaInstruction, ctx: &JvmContext) -> Result<Vec<JvmInstruction>> {
    match instruction {
        GaiaInstruction::Core(core) => {

            
            match core {
                CoreInstruction::PushConstant(constant) => match constant {
                    GaiaConstant::I8(value) => Ok(vec![JvmInstruction::Bipush { value: *value }]),
                    GaiaConstant::U8(value) => Ok(vec![JvmInstruction::Bipush { value: *value as i8 }]),
                    GaiaConstant::I16(value) => Ok(vec![JvmInstruction::Sipush { value: *value }]),
                    GaiaConstant::U16(value) => Ok(vec![JvmInstruction::Sipush { value: *value as i16 }]),
                    GaiaConstant::I32(value) => match *value {
                        0 => Ok(vec![JvmInstruction::Iconst0]),
                        1 => Ok(vec![JvmInstruction::Iconst1]),
                        2 => Ok(vec![JvmInstruction::Iconst2]),
                        3 => Ok(vec![JvmInstruction::Iconst3]),
                        4 => Ok(vec![JvmInstruction::Iconst4]),
                        5 => Ok(vec![JvmInstruction::Iconst5]),
                        -1 => Ok(vec![JvmInstruction::IconstM1]),
                        _ if *value >= -128 && *value <= 127 => Ok(vec![JvmInstruction::Bipush { value: *value as i8 }]),
                        _ if *value >= -32768 && *value <= 32767 => Ok(vec![JvmInstruction::Sipush { value: *value as i16 }]),
                        _ => Ok(vec![JvmInstruction::Ldc { symbol: value.to_string() }]),
                    },
                    GaiaConstant::U32(value) => Ok(vec![JvmInstruction::Ldc { symbol: value.to_string() }]),
                    GaiaConstant::I64(value) => Ok(vec![JvmInstruction::Ldc2W { symbol: value.to_string() }]),
                    GaiaConstant::U64(value) => Ok(vec![JvmInstruction::Ldc2W { symbol: value.to_string() }]),
                    GaiaConstant::F32(value) => match *value {
                        0.0 => Ok(vec![JvmInstruction::Fconst0]),
                        1.0 => Ok(vec![JvmInstruction::Fconst1]),
                        2.0 => Ok(vec![JvmInstruction::Fconst2]),
                        _ => Ok(vec![JvmInstruction::Ldc { symbol: value.to_string() }]),
                    },
                    GaiaConstant::F64(value) => match *value {
                        0.0 => Ok(vec![JvmInstruction::Dconst0]),
                        1.0 => Ok(vec![JvmInstruction::Dconst1]),
                        _ => Ok(vec![JvmInstruction::Ldc2W { symbol: value.to_string() }]),
                    },
                    GaiaConstant::String(value) => Ok(vec![JvmInstruction::Ldc { symbol: value.clone() }]),
                    GaiaConstant::Bool(value) => Ok(vec![if *value { JvmInstruction::Iconst1 } else { JvmInstruction::Iconst0 }]),
                    GaiaConstant::Null => Ok(vec![JvmInstruction::AconstNull]),
                    _ => Err(GaiaError::custom_error("Unsupported constant type for JVM")),
                },
                CoreInstruction::Load(gaia_type) => {
                    // 添加错误处理
                    Err(GaiaError::custom_error(&format!("JVM indirect load not supported for type: {:?}", gaia_type)))
                },
                CoreInstruction::Store(gaia_type) => {
                    // 添加错误处理
                    Err(GaiaError::custom_error(&format!("JVM indirect store not supported for type: {:?}", gaia_type)))
                },
                CoreInstruction::Add(ty) => Ok(vec![match ty {
                    GaiaType::I32 | GaiaType::U32 | GaiaType::Bool | GaiaType::I8 | GaiaType::U8 | GaiaType::I16 | GaiaType::U16 => JvmInstruction::Iadd,
                    GaiaType::I64 | GaiaType::U64 => JvmInstruction::Ladd,
                    GaiaType::F32 => JvmInstruction::Fadd,
                    GaiaType::F64 => JvmInstruction::Dadd,
                    _ => JvmInstruction::Iadd,
                }]),
                CoreInstruction::Sub(ty) => Ok(vec![match ty {
                    GaiaType::I32 | GaiaType::U32 | GaiaType::Bool | GaiaType::I8 | GaiaType::U8 | GaiaType::I16 | GaiaType::U16 => JvmInstruction::Isub,
                    GaiaType::I64 | GaiaType::U64 => JvmInstruction::Lsub,
                    GaiaType::F32 => JvmInstruction::Fsub,
                    GaiaType::F64 => JvmInstruction::Dsub,
                    _ => JvmInstruction::Isub,
                }]),
                CoreInstruction::Mul(ty) => Ok(vec![match ty {
                    GaiaType::I32 | GaiaType::U32 | GaiaType::Bool | GaiaType::I8 | GaiaType::U8 | GaiaType::I16 | GaiaType::U16 => JvmInstruction::Imul,
                    GaiaType::I64 | GaiaType::U64 => JvmInstruction::Lmul,
                    GaiaType::F32 => JvmInstruction::Fmul,
                    GaiaType::F64 => JvmInstruction::Dmul,
                    _ => JvmInstruction::Imul,
                }]),
                CoreInstruction::Div(ty) => Ok(vec![match ty {
                    GaiaType::I32 | GaiaType::U32 | GaiaType::Bool | GaiaType::I8 | GaiaType::U8 | GaiaType::I16 | GaiaType::U16 => JvmInstruction::Idiv,
                    GaiaType::I64 | GaiaType::U64 => JvmInstruction::Ldiv,
                    GaiaType::F32 => JvmInstruction::Fdiv,
                    GaiaType::F64 => JvmInstruction::Ddiv,
                    _ => JvmInstruction::Idiv,
                }]),
                CoreInstruction::Rem(ty) => Ok(vec![match ty {
                    GaiaType::I32 | GaiaType::U32 | GaiaType::Bool | GaiaType::I8 | GaiaType::U8 | GaiaType::I16 | GaiaType::U16 => JvmInstruction::Irem,
                    GaiaType::I64 | GaiaType::U64 => JvmInstruction::Lrem,
                    GaiaType::F32 => JvmInstruction::Frem,
                    GaiaType::F64 => JvmInstruction::Drem,
                    _ => JvmInstruction::Irem,
                }]),
                CoreInstruction::Pop => Ok(vec![JvmInstruction::Pop]),
                CoreInstruction::Ret => Ok(vec![JvmInstruction::Return]),
                CoreInstruction::Br(label) => Ok(vec![JvmInstruction::Goto { target: label.clone() }]),
                CoreInstruction::BrTrue(label) => Ok(vec![JvmInstruction::Ifne { target: label.clone() }]),
                CoreInstruction::BrFalse(label) => Ok(vec![JvmInstruction::Ifeq { target: label.clone() }]),
                CoreInstruction::Label(name) => Ok(vec![JvmInstruction::Label { name: name.clone() }]),
                CoreInstruction::Call(name, arg_count) => {
                    let jvm_target = gaia_types::helpers::CompilationTarget {
                        build: gaia_types::helpers::Architecture::JVM,
                        host: gaia_types::helpers::AbiCompatible::JavaAssembly,
                        target: gaia_types::helpers::ApiCompatible::JvmRuntime(8),
                    };
                    let mapped = ctx.function_mapper.map_function(&jvm_target, name).unwrap_or(name);
                    
                    // 改进方法调用处理,支持完整的方法签名
                    // 尝试从函数映射中获取方法签名信息
                    let mut descriptor = "()V".to_string();
                    
                    // 对于标准库方法,使用预定义的描述符
                    if name.starts_with("java/") || name.starts_with("java.lang/") {
                        // 标准库方法调用
                        let parts: Vec<&str> = name.split('.').collect();
                        if parts.len() >= 2 {
                            let class_name = parts[0..parts.len()-1].join("/");
                            let method_name = parts[parts.len()-1];
                            
                            // 根据方法名和参数数量生成更准确的描述符
                            descriptor = match (class_name.as_str(), method_name, *arg_count) {
                                ("java/lang/System", "exit", 1) => "(I)V".to_string(),
                                ("java/lang/System", "currentTimeMillis", 0) => "()J".to_string(),
                                ("java/lang/System", "arraycopy", 5) => "(Ljava/lang/Object;ILjava/lang/Object;II)V".to_string(),
                                ("java/lang/String", "valueOf", 1) => "(I)Ljava/lang/String;".to_string(),
                                ("java/lang/Integer", "parseInt", 1) => "(Ljava/lang/String;)I".to_string(),
                                _ => format!("({})V", "I".repeat(*arg_count)),
                            };
                            
                            Ok(vec![JvmInstruction::Invokestatic {
                                class_name,
                                method_name: method_name.to_string(),
                                descriptor,
                            }])
                        } else {
                            Ok(vec![JvmInstruction::Invokestatic {
                                class_name: "Main".to_string(),
                                method_name: mapped.to_string(),
                                descriptor,
                            }])
                        }
                    } else {
                        // 普通方法调用,尝试从函数映射中获取签名
                        // 暂时使用基于参数数量的描述符,后续可以通过更复杂的分析获取准确签名
                        descriptor = format!("({})V", "I".repeat(*arg_count));
                        
                        // 添加边界情况检查
                        if *arg_count > 255 {
                            return Err(GaiaError::custom_error("Too many arguments for JVM method call"));
                        }
                        
                        Ok(vec![JvmInstruction::Invokestatic {
                            class_name: "Main".to_string(),
                            method_name: mapped.to_string(),
                            descriptor,
                        }])
                    }
                },
                CoreInstruction::LoadLocal(index, ty) => {
                    // 添加边界情况检查
                    if *index > 65535 {
                        return Err(GaiaError::custom_error("Local variable index out of range for JVM"));
                    }
                    Ok(vec![match ty {
                        GaiaType::I32
                        | GaiaType::U32
                        | GaiaType::Bool
                        | GaiaType::I8
                        | GaiaType::U8
                        | GaiaType::I16
                        | GaiaType::U16 => JvmInstruction::Iload { index: *index as u16 },
                        GaiaType::I64 | GaiaType::U64 => JvmInstruction::Lload { index: *index as u16 },
                        GaiaType::F32 => JvmInstruction::Fload { index: *index as u16 },
                        GaiaType::F64 => JvmInstruction::Dload { index: *index as u16 },
                        _ => JvmInstruction::Aload { index: *index as u16 },
                    }])
                },
                CoreInstruction::StoreLocal(index, ty) => {
                    // 添加边界情况检查
                    if *index > 65535 {
                        return Err(GaiaError::custom_error("Local variable index out of range for JVM"));
                    }
                    Ok(vec![match ty {
                        GaiaType::I32
                        | GaiaType::U32
                        | GaiaType::Bool
                        | GaiaType::I8
                        | GaiaType::U8
                        | GaiaType::I16
                        | GaiaType::U16 => JvmInstruction::Istore { index: *index as u16 },
                        GaiaType::I64 | GaiaType::U64 => JvmInstruction::Lstore { index: *index as u16 },
                        GaiaType::F32 => JvmInstruction::Fstore { index: *index as u16 },
                        GaiaType::F64 => JvmInstruction::Dstore { index: *index as u16 },
                        _ => JvmInstruction::Astore { index: *index as u16 },
                    }])
                },
                CoreInstruction::LoadArg(index, ty) => {
                    // 添加边界情况检查
                    if *index > 65535 {
                        return Err(GaiaError::custom_error("Argument index out of range for JVM"));
                    }
                    Ok(vec![match ty {
                        GaiaType::I32
                        | GaiaType::U32
                        | GaiaType::Bool
                        | GaiaType::I8
                        | GaiaType::U8
                        | GaiaType::I16
                        | GaiaType::U16 => JvmInstruction::Iload { index: *index as u16 },
                        GaiaType::I64 | GaiaType::U64 => JvmInstruction::Lload { index: *index as u16 },
                        GaiaType::F32 => JvmInstruction::Fload { index: *index as u16 },
                        GaiaType::F64 => JvmInstruction::Dload { index: *index as u16 },
                        _ => JvmInstruction::Aload { index: *index as u16 },
                    }])
                },
                CoreInstruction::StoreArg(index, ty) => {
                    // 添加边界情况检查
                    if *index > 65535 {
                        return Err(GaiaError::custom_error("Argument index out of range for JVM"));
                    }
                    Ok(vec![match ty {
                        GaiaType::I32
                        | GaiaType::U32
                        | GaiaType::Bool
                        | GaiaType::I8
                        | GaiaType::U8
                        | GaiaType::I16
                        | GaiaType::U16 => JvmInstruction::Istore { index: *index as u16 },
                        GaiaType::I64 | GaiaType::U64 => JvmInstruction::Lstore { index: *index as u16 },
                        GaiaType::F32 => JvmInstruction::Fstore { index: *index as u16 },
                        GaiaType::F64 => JvmInstruction::Dstore { index: *index as u16 },
                        _ => JvmInstruction::Astore { index: *index as u16 },
                    }])
                },
                CoreInstruction::New(type_name) => Ok(vec![
                    JvmInstruction::New { class_name: type_name.replace('.', "/") },
                    JvmInstruction::Dup,
                    JvmInstruction::Invokespecial {
                        class_name: type_name.replace('.', "/"),
                        method_name: "<init>".to_string(),
                        descriptor: "()V".to_string(),
                    },
                ]),
                CoreInstruction::LoadField(type_name, field_name) => {
                    let descriptor = ctx
                        .field_types
                        .get(&(type_name.clone(), field_name.clone()))
                        .cloned()
                        .unwrap_or_else(|| "Ljava/lang/Object;".to_string());
                    Ok(vec![JvmInstruction::Getfield {
                        class_name: type_name.replace('.', "/"),
                        field_name: field_name.to_string(),
                        descriptor,
                    }])
                }
                CoreInstruction::StoreField(type_name, field_name) => {
                    let descriptor = ctx
                        .field_types
                        .get(&(type_name.clone(), field_name.clone()))
                        .cloned()
                        .unwrap_or_else(|| "Ljava/lang/Object;".to_string());
                    Ok(vec![JvmInstruction::Putfield {
                        class_name: type_name.replace('.', "/"),
                        field_name: field_name.to_string(),
                        descriptor,
                    }])
                }
                CoreInstruction::LoadElement(ty) => {
                    // 添加数组索引边界检查
                    let mut instructions = vec![];
                    
                    // 保存数组引用
                    instructions.push(JvmInstruction::Dup);
                    // 加载数组长度
                    instructions.push(JvmInstruction::Arraylength);
                    // 交换数组引用和长度
                    instructions.push(JvmInstruction::Swap);
                    // 交换索引和长度
                    instructions.push(JvmInstruction::Swap);
                    // 比较索引和长度
                    instructions.push(JvmInstruction::Lcmp);
                    // 如果索引 >= 长度,抛出数组越界异常
                    instructions.push(JvmInstruction::Ifge { target: "array_index_out_of_bounds".to_string() });
                    // 正常的元素加载
                    instructions.push(match ty {
                        GaiaType::I32 | GaiaType::U32 => JvmInstruction::Iaload,
                        GaiaType::I64 | GaiaType::U64 => JvmInstruction::Laload,
                        GaiaType::F32 => JvmInstruction::Faload,
                        GaiaType::F64 => JvmInstruction::Daload,
                        GaiaType::I8 | GaiaType::U8 | GaiaType::Bool => JvmInstruction::Baload,
                        GaiaType::I16 | GaiaType::U16 => JvmInstruction::Saload,
                        _ => JvmInstruction::Aaload,
                    });
                    // 数组越界异常处理
                    instructions.push(JvmInstruction::Label { name: "array_index_out_of_bounds".to_string() });
                    instructions.push(JvmInstruction::New { class_name: "java/lang/ArrayIndexOutOfBoundsException".to_string() });
                    instructions.push(JvmInstruction::Dup);
                    instructions.push(JvmInstruction::Invokespecial { class_name: "java/lang/ArrayIndexOutOfBoundsException".to_string(), method_name: "<init>".to_string(), descriptor: "()V".to_string() });
                    instructions.push(JvmInstruction::Athrow);
                    
                    Ok(instructions)
                },
                CoreInstruction::StoreElement(ty) => {
                    // 添加数组索引边界检查
                    let mut instructions = vec![];
                    
                    // 保存数组引用和值
                    instructions.push(JvmInstruction::Dup2);
                    // 加载数组长度
                    instructions.push(JvmInstruction::Arraylength);
                    // 交换数组引用和长度
                    instructions.push(JvmInstruction::Swap);
                    // 交换值和长度
                    instructions.push(JvmInstruction::Swap);
                    // 交换索引和长度
                    instructions.push(JvmInstruction::Swap);
                    // 比较索引和长度
                    instructions.push(JvmInstruction::Lcmp);
                    // 如果索引 >= 长度,抛出数组越界异常
                    instructions.push(JvmInstruction::Ifge { target: "array_index_out_of_bounds_store".to_string() });
                    // 正常的元素存储
                    instructions.push(match ty {
                        GaiaType::I32 | GaiaType::U32 => JvmInstruction::Iastore,
                        GaiaType::I64 | GaiaType::U64 => JvmInstruction::Lastore,
                        GaiaType::F32 => JvmInstruction::Fastore,
                        GaiaType::F64 => JvmInstruction::Dastore,
                        GaiaType::I8 | GaiaType::U8 | GaiaType::Bool => JvmInstruction::Bastore,
                        GaiaType::I16 | GaiaType::U16 => JvmInstruction::Sastore,
                        _ => JvmInstruction::Aastore,
                    });
                    // 数组越界异常处理
                    instructions.push(JvmInstruction::Label { name: "array_index_out_of_bounds_store".to_string() });
                    instructions.push(JvmInstruction::New { class_name: "java/lang/ArrayIndexOutOfBoundsException".to_string() });
                    instructions.push(JvmInstruction::Dup);
                    instructions.push(JvmInstruction::Invokespecial { class_name: "java/lang/ArrayIndexOutOfBoundsException".to_string(), method_name: "<init>".to_string(), descriptor: "()V".to_string() });
                    instructions.push(JvmInstruction::Athrow);
                    
                    Ok(instructions)
                },
                CoreInstruction::Cmp(condition, ty) => Ok(vec![match ty {
                    GaiaType::I32 | GaiaType::U32 | GaiaType::Bool | GaiaType::I8 | GaiaType::U8 | GaiaType::I16 | GaiaType::U16 => JvmInstruction::Lcmp,
                    GaiaType::I64 | GaiaType::U64 => JvmInstruction::Lcmp,
                    GaiaType::F32 => JvmInstruction::Fcmpg,
                    GaiaType::F64 => JvmInstruction::Dcmpg,
                    _ => JvmInstruction::Lcmp,
                }]),
                CoreInstruction::Gep { base_type, indices } => Err(GaiaError::not_implemented("JVM GEP")),
                CoreInstruction::NewArray(ty, is_length_on_stack) => {
                    // 实现 NewArray 指令
                    let instructions = match ty {
                        GaiaType::I8 | GaiaType::U8 | GaiaType::Bool => vec![JvmInstruction::Newarray { type_code: 4 }], // T_BYTE
                        GaiaType::I16 | GaiaType::U16 => vec![JvmInstruction::Newarray { type_code: 5 }], // T_SHORT
                        GaiaType::I32 | GaiaType::U32 => vec![JvmInstruction::Newarray { type_code: 6 }], // T_INT
                        GaiaType::I64 | GaiaType::U64 => vec![JvmInstruction::Newarray { type_code: 7 }], // T_LONG
                        GaiaType::F32 => vec![JvmInstruction::Newarray { type_code: 8 }], // T_FLOAT
                        GaiaType::F64 => vec![JvmInstruction::Newarray { type_code: 9 }], // T_DOUBLE
                        GaiaType::Object | GaiaType::String => {
                            vec![JvmInstruction::Anewarray { class_name: ty.to_string().replace('.', "/") }]
                        },
                        _ => vec![JvmInstruction::Newarray { type_code: 6 }], // 默认使用 int 数组
                    };
                    Ok(instructions)
                },
                CoreInstruction::ArrayLength => Ok(vec![JvmInstruction::Arraylength]),
                CoreInstruction::ArrayPush => {
                    // ArrayPush 指令实现 - 对于 JVM,我们需要先获取数组长度,然后将元素添加到末尾
                    // 这里假设数组引用在栈顶,值在栈顶下方
                    Ok(vec![
                        JvmInstruction::Dup, // 复制数组引用
                        JvmInstruction::Arraylength, // 获取数组长度
                        JvmInstruction::Swap, // 交换数组引用和长度
                        JvmInstruction::Swap, // 交换值和长度
                        JvmInstruction::Iastore, // 存储元素到数组末尾
                    ])
                },
                CoreInstruction::Cast { from, to, kind } => {
                    // 实现类型转换指令
                    let mut instructions = vec![];
                    match (from, to) {
                        // 整数类型之间的转换
                        (GaiaType::I8, GaiaType::I16) | (GaiaType::U8, GaiaType::I16) | (GaiaType::I8, GaiaType::I32) | (GaiaType::U8, GaiaType::I32) | (GaiaType::I16, GaiaType::I32) | (GaiaType::U16, GaiaType::I32) => {
                            // 对于这些转换,JVM 会自动处理,不需要额外指令
                        }
                        (GaiaType::I8, GaiaType::I64) | (GaiaType::U8, GaiaType::I64) | (GaiaType::I16, GaiaType::I64) | (GaiaType::U16, GaiaType::I64) | (GaiaType::I32, GaiaType::I64) | (GaiaType::U32, GaiaType::I64) => {
                            instructions.push(JvmInstruction::I2l);
                        }
                        (GaiaType::I8, GaiaType::F32) | (GaiaType::U8, GaiaType::F32) | (GaiaType::I16, GaiaType::F32) | (GaiaType::U16, GaiaType::F32) | (GaiaType::I32, GaiaType::F32) | (GaiaType::U32, GaiaType::F32) => {
                            instructions.push(JvmInstruction::I2f);
                        }
                        (GaiaType::I8, GaiaType::F64) | (GaiaType::U8, GaiaType::F64) | (GaiaType::I16, GaiaType::F64) | (GaiaType::U16, GaiaType::F64) | (GaiaType::I32, GaiaType::F64) | (GaiaType::U32, GaiaType::F64) => {
                            instructions.push(JvmInstruction::I2d);
                        }
                        (GaiaType::I64, GaiaType::I32) => {
                            instructions.push(JvmInstruction::L2i);
                        }
                        (GaiaType::I64, GaiaType::F32) => {
                            instructions.push(JvmInstruction::L2f);
                        }
                        (GaiaType::I64, GaiaType::F64) => {
                            instructions.push(JvmInstruction::L2d);
                        }
                        (GaiaType::F32, GaiaType::I32) => {
                            instructions.push(JvmInstruction::F2i);
                        }
                        (GaiaType::F32, GaiaType::I64) => {
                            instructions.push(JvmInstruction::F2l);
                        }
                        (GaiaType::F32, GaiaType::F64) => {
                            instructions.push(JvmInstruction::F2d);
                        }
                        (GaiaType::F64, GaiaType::I32) => {
                            instructions.push(JvmInstruction::D2i);
                        }
                        (GaiaType::F64, GaiaType::I64) => {
                            instructions.push(JvmInstruction::D2l);
                        }
                        (GaiaType::F64, GaiaType::F32) => {
                            instructions.push(JvmInstruction::D2f);
                        }
                        // 引用类型之间的转换
                        (_, GaiaType::Object) | (_, GaiaType::String) => {
                            instructions.push(JvmInstruction::Checkcast { class_name: to.to_string().replace('.', "/") });
                        }
                        _ => {
                            // 其他类型转换暂不支持
                        }
                    }
                    Ok(instructions)
                },
                CoreInstruction::And(ty) => Ok(vec![match ty {
                    GaiaType::I32 | GaiaType::U32 | GaiaType::Bool | GaiaType::I8 | GaiaType::U8 | GaiaType::I16 | GaiaType::U16 => JvmInstruction::Iand,
                    GaiaType::I64 | GaiaType::U64 => JvmInstruction::Land,
                    _ => JvmInstruction::Iand,
                }]),
                CoreInstruction::Or(ty) => Ok(vec![match ty {
                    GaiaType::I32 | GaiaType::U32 | GaiaType::Bool | GaiaType::I8 | GaiaType::U8 | GaiaType::I16 | GaiaType::U16 => JvmInstruction::Ior,
                    GaiaType::I64 | GaiaType::U64 => JvmInstruction::Lor,
                    _ => JvmInstruction::Ior,
                }]),
                CoreInstruction::Xor(ty) => Ok(vec![match ty {
                    GaiaType::I32 | GaiaType::U32 | GaiaType::Bool | GaiaType::I8 | GaiaType::U8 | GaiaType::I16 | GaiaType::U16 => JvmInstruction::Ixor,
                    GaiaType::I64 | GaiaType::U64 => JvmInstruction::Lxor,
                    _ => JvmInstruction::Ixor,
                }]),
                CoreInstruction::Shl(ty) => Ok(vec![match ty {
                    GaiaType::I32 | GaiaType::U32 | GaiaType::Bool | GaiaType::I8 | GaiaType::U8 | GaiaType::I16 | GaiaType::U16 => JvmInstruction::Ishl,
                    GaiaType::I64 | GaiaType::U64 => JvmInstruction::Lshl,
                    _ => JvmInstruction::Ishl,
                }]),
                CoreInstruction::Shr(ty) => Ok(vec![match ty {
                    GaiaType::I32 | GaiaType::U32 | GaiaType::Bool | GaiaType::I8 | GaiaType::U8 | GaiaType::I16 | GaiaType::U16 => JvmInstruction::Ishr,
                    GaiaType::I64 | GaiaType::U64 => JvmInstruction::Lshr,
                    _ => JvmInstruction::Ishr,
                }]),
                CoreInstruction::Neg(ty) => Ok(vec![match ty {
                    GaiaType::I32 | GaiaType::U32 | GaiaType::Bool | GaiaType::I8 | GaiaType::U8 | GaiaType::I16 | GaiaType::U16 => JvmInstruction::Ineg,
                    GaiaType::I64 | GaiaType::U64 => JvmInstruction::Lneg,
                    GaiaType::F32 => JvmInstruction::Fneg,
                    GaiaType::F64 => JvmInstruction::Dneg,
                    _ => JvmInstruction::Ineg,
                }]),
                CoreInstruction::Not(ty) => Ok(vec![match ty {
                    GaiaType::I32 | GaiaType::U32 | GaiaType::Bool | GaiaType::I8 | GaiaType::U8 | GaiaType::I16 | GaiaType::U16 => JvmInstruction::Ixor,
                    GaiaType::I64 | GaiaType::U64 => JvmInstruction::Lxor,
                    _ => JvmInstruction::Ixor,
                }]),
                CoreInstruction::CallIndirect(arg_count) => Err(GaiaError::not_implemented("JVM CallIndirect")),
                CoreInstruction::Alloca(ty, count) => {
                    // 在 JVM 中,局部变量是在方法的局部变量表中分配的
                    // 这里我们不需要生成实际的指令,因为局部变量的分配是在方法级别的
                    // 我们只需要确保在 calculate_stack_and_locals 中计算了正确的 max_locals
                    Ok(vec![])
                },
                CoreInstruction::Throw => Ok(vec![JvmInstruction::Athrow]),

                _ => Ok(vec![]),
            }
        },
        _ => Ok(vec![]),
    }
}

#[cfg(feature = "jvm-assembler")]
/// Convert GaiaType to JVM descriptor
fn convert_gaia_type_to_jvm_descriptor(ty: &GaiaType) -> String {
    mapping::map_gaia_type_to_jvm_descriptor(ty)
}

#[cfg(feature = "jvm-assembler")]
/// Calculate stack and local variable sizes for JVM method
fn calculate_stack_and_locals(function: &GaiaFunction, _ctx: &JvmContext) -> Result<(u16, u16)> {
    // 更准确的栈大小计算实现
    let mut max_stack: i32 = 0;
    let mut current_stack: i32 = 0;
    let mut max_locals: u16 = 0;
    
    // 计算参数占用的局部变量空间
    for (i, param) in function.signature.params.iter().enumerate() {
        let size = match param {
            GaiaType::I64 | GaiaType::U64 | GaiaType::F64 => 2u16,
            _ => 1u16,
        };
        max_locals += size;
    }
    
    // 分析指令的栈操作
    for block in &function.blocks {
        for instruction in &block.instructions {
            match instruction {
                GaiaInstruction::Core(core) => match core {
                    CoreInstruction::PushConstant(constant) => {
                        match constant {
                            GaiaConstant::I64(_) | GaiaConstant::U64(_) | GaiaConstant::F64(_) => {
                                current_stack += 2;
                            }
                            _ => {
                                current_stack += 1;
                            }
                        }
                        if current_stack > max_stack {
                            max_stack = current_stack;
                        }
                    }
                    CoreInstruction::Add(ty) | CoreInstruction::Sub(ty) | CoreInstruction::Mul(ty) | CoreInstruction::Div(ty) | CoreInstruction::Rem(ty) => {
                        match ty {
                            GaiaType::I64 | GaiaType::U64 | GaiaType::F64 => {
                                current_stack -= 1; // 2 个操作数入栈,1 个结果出栈,净减少 1
                            }
                            _ => {
                                current_stack -= 1; // 2 个操作数入栈,1 个结果出栈,净减少 1
                            }
                        }
                    }
                    CoreInstruction::Pop => {
                        current_stack -= 1;
                    }
                    CoreInstruction::Dup => {
                        current_stack += 1;
                        if current_stack > max_stack {
                            max_stack = current_stack;
                        }
                    }
                    CoreInstruction::LoadLocal(_, ty) | CoreInstruction::LoadArg(_, ty) => {
                        match ty {
                            GaiaType::I64 | GaiaType::U64 | GaiaType::F64 => {
                                current_stack += 2;
                            }
                            _ => {
                                current_stack += 1;
                            }
                        }
                        if current_stack > max_stack {
                            max_stack = current_stack;
                        }
                    }
                    CoreInstruction::StoreLocal(index, ty) | CoreInstruction::StoreArg(index, ty) => {
                        match ty {
                            GaiaType::I64 | GaiaType::U64 | GaiaType::F64 => {
                                current_stack -= 2;
                                let local_index = *index as u16;
                                if local_index + 1 > max_locals {
                                    max_locals = local_index + 2;
                                }
                            }
                            _ => {
                                current_stack -= 1;
                                let local_index = *index as u16;
                                if local_index > max_locals {
                                    max_locals = local_index + 1;
                                }
                            }
                        }
                    }
                    CoreInstruction::New(_) => {
                        current_stack += 1; // new 指令创建对象并压入栈
                        if current_stack > max_stack {
                            max_stack = current_stack;
                        }
                    }
                    CoreInstruction::LoadField(_, _) => {
                        current_stack += 1; // 加载字段值并压入栈
                        if current_stack > max_stack {
                            max_stack = current_stack;
                        }
                    }
                    CoreInstruction::StoreField(_, _) => {
                        current_stack -= 1; // 存储字段值,从栈中弹出
                    }
                    CoreInstruction::LoadElement(ty) => {
                        match ty {
                            GaiaType::I64 | GaiaType::U64 | GaiaType::F64 => {
                                current_stack += 1; // 数组引用和索引入栈,元素出栈,净增加 1
                            }
                            _ => {
                                current_stack += 1; // 数组引用和索引入栈,元素出栈,净增加 1
                            }
                        }
                        if current_stack > max_stack {
                            max_stack = current_stack;
                        }
                    }
                    CoreInstruction::StoreElement(ty) => {
                        match ty {
                            GaiaType::I64 | GaiaType::U64 | GaiaType::F64 => {
                                current_stack -= 2; // 数组引用、索引和值入栈,净减少 2
                            }
                            _ => {
                                current_stack -= 2; // 数组引用、索引和值入栈,净减少 2
                            }
                        }
                    }
                    CoreInstruction::Call(_, arg_count) => {
                        // 方法调用会弹出参数并压入返回值
                        current_stack -= *arg_count as i32;
                        // 假设返回值为 1 个单位大小
                        current_stack += 1;
                        if current_stack > max_stack {
                            max_stack = current_stack;
                        }
                    }
                    CoreInstruction::NewArray(_, _) => {
                        // NewArray 指令消耗一个长度值,产生一个数组引用
                        current_stack -= 1; // 消耗长度
                        current_stack += 1; // 产生数组引用
                        // 净变化为 0,但需要确保栈大小足够
                    }
                    CoreInstruction::ArrayLength => {
                        // ArrayLength 指令消耗一个数组引用,产生一个长度值
                        current_stack -= 1; // 消耗数组引用
                        current_stack += 1; // 产生长度值
                        // 净变化为 0
                    }
                    CoreInstruction::ArrayPush => {
                        // ArrayPush 指令消耗数组引用和值,不产生结果
                        current_stack -= 2; // 消耗数组引用和值
                    }
                    CoreInstruction::Throw => {
                        // Throw 指令消耗一个异常对象引用
                        current_stack -= 1;
                    }

                    CoreInstruction::Br(_) | CoreInstruction::BrTrue(_) | CoreInstruction::BrFalse(_) | CoreInstruction::Label(_) => {
                        // 控制流指令不影响栈大小
                    }
                    CoreInstruction::Ret => {
                        // Return 指令清空栈
                        current_stack = 0;
                    }
                    _ => {
                        // 其他指令暂不处理
                    }
                },
                _ => {
                    // 其他类型的指令暂不处理
                }
            }
        }
    }
    
    // 确保栈大小不为负数
    if max_stack < 0 {
        max_stack = 0;
    }
    
    // 添加一些安全余量
    max_stack = std::cmp::max(max_stack, 4);
    max_locals = std::cmp::max(max_locals, 4u16);
    
    Ok((max_stack as u16, max_locals as u16))
}

#[cfg(feature = "jvm-assembler")]
/// Build JVM method descriptor from Gaia types
fn build_method_descriptor(params: &[GaiaType], return_type: &Option<GaiaType>) -> String {
    let mut descriptor = "(".to_string();
    for param in params {
        descriptor.push_str(&convert_gaia_type_to_jvm_descriptor(param));
    }
    descriptor.push(')');
    if let Some(ret) = return_type {
        descriptor.push_str(&convert_gaia_type_to_jvm_descriptor(ret));
    }
    else {
        descriptor.push('V');
    }
    descriptor
}