goiaba 0.0.3

Experimental Go parser and compiler
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
// Copyright 2025-present Raphael Amorim. All rights reserved.
// Use of this source code is governed by a BSD-3-Clause
// license that can be found in the LICENSE file.

use crate::parser::ast::{TypeSpec, Spec};
use crate::parser::FuncTypeKey;
use crate::parser::Token;
use crate::parser::parse_str;
use std::collections::HashMap;
use wasm_encoder::{
    CodeSection, ExportKind, ExportSection, Function, FunctionSection, Instruction,
    Module as WasmModule, TypeSection, ValType, MemorySection, MemoryType,
};

// Import your internal parser types
use crate::parser::{
    ast::{BasicLit, Decl, Expr, File, FuncDecl, Stmt, GenDecl},
    objects::{AstObjects, IdentKey, SpecKey},
};
use std::rc::Rc;

fn extract_export_name(source: &str, func_name: &str) -> Option<String> {
    let lines: Vec<&str> = source.lines().collect();

    // Find the function definition line
    for (i, line) in lines.iter().enumerate() {
        if line.contains(&format!("func {}", func_name)) {
            // Look backwards from the function definition for export comment
            for j in (0..i).rev() {
                let check_line = lines[j].trim();
                if check_line.starts_with("//export ") {
                    let export_name = check_line.strip_prefix("//export ").unwrap().trim();
                    if !export_name.is_empty() {
                        return Some(export_name.to_string());
                    }
                }
                // Stop if we hit a non-comment, non-empty line
                if !check_line.is_empty() && !check_line.starts_with("//") {
                    break;
                }
            }
            break;
        }
    }
    None
}

// Define our WASM-specific AST structures
#[derive(Debug, Clone)]
pub enum WasmExpr {
    Integer(i32),
    Variable(String),
    Binary(WasmBinaryOp, Box<WasmExpr>, Box<WasmExpr>),
    Unary(WasmUnaryOp, Box<WasmExpr>),
    Call(String, Vec<WasmExpr>),
    Assign(String, Box<WasmExpr>),
    StructLiteral(String, Vec<(String, WasmExpr)>), // struct_name, field_values
    FieldAccess(Box<WasmExpr>, String),              // object.field
    FieldAssign(Box<WasmExpr>, String, Box<WasmExpr>), // object.field = value
    AddressOf(Box<WasmExpr>),                        // &expr
    Dereference(Box<WasmExpr>),                      // *expr
}

#[derive(Debug, Clone)]
pub enum WasmUnaryOp {
    Neg,
    Not,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum WasmBinaryOp {
    Add,
    Sub,
    Mul,
    Div,
    Rem,      // Modulo/remainder
    Lt,
    Gt,
    LtEq,
    GtEq,
    Eq,
    NotEq,
    And,      // Bitwise AND
    Or,       // Bitwise OR  
    Xor,      // Bitwise XOR
    Shl,      // Left shift
    Shr,      // Right shift
    LogicalOr, // Logical OR (||)
    LogicalAnd, // Logical AND (&&)
}

#[derive(Debug, Clone)]
pub enum WasmStatement {
    ExprStmt(WasmExpr),
    VarDecl(String, WasmExpr),
    Return(Option<WasmExpr>),
    Block(Vec<WasmStatement>),
    If(WasmExpr, Vec<WasmStatement>, Option<Vec<WasmStatement>>),
    Loop(Vec<WasmStatement>),
    Break,
    StructDecl(String, Vec<(String, WasmType)>), // struct_name, fields
}

#[derive(Debug, Clone)]
pub struct WasmFunctionDef {
    pub name: String,
    pub export_name: Option<String>,
    pub params: Vec<(String, WasmType)>,
    pub return_type: Option<WasmType>,
    pub body: Vec<WasmStatement>,
}

#[derive(Debug, Clone, PartialEq)]
pub enum WasmType {
    Int,
    Float,
    Void,
    Struct(String),              // Named struct type
    Pointer(Box<WasmType>),      // Pointer to type
}

// Struct definition storage
#[derive(Debug, Clone)]
pub struct WasmStructDef {
    pub name: String,
    pub fields: Vec<(String, WasmType)>,
    pub field_offsets: HashMap<String, u32>, // Field name -> byte offset
    pub size: u32,                           // Total struct size in bytes
}

#[derive(Debug)]
pub struct WasmProgram {
    pub functions: Vec<WasmFunctionDef>,
    pub structs: Vec<WasmStructDef>,
}

// Translator from Go AST to WASM AST
pub struct GoToWasmTranslator {
    struct_defs: HashMap<String, WasmStructDef>,
}

impl GoToWasmTranslator {
    pub fn new() -> Self {
        Self {
            struct_defs: HashMap::new(),
        }
    }

    pub fn translate_program(go_program: &File, objs: &AstObjects, source: &str) -> WasmProgram {
        let mut translator = Self::new();
        let mut functions = Vec::new();
        let mut structs = Vec::new();

        // First pass: collect struct definitions
        for decl in &go_program.decls {
            if let Decl::Gen(gen_decl) = decl {
                for spec_key in &gen_decl.specs {
                    if let Spec::Type(type_spec) = &objs.specs[*spec_key] {
                        if let Some(struct_def) = translator.translate_struct_definition(type_spec, objs) {
                            translator.struct_defs.insert(struct_def.name.clone(), struct_def.clone());
                            structs.push(struct_def);
                        }
                    }
                }
            }
        }

        // Second pass: translate functions with struct context
        for decl in &go_program.decls {
            if let Decl::Func(func_decl_key) = decl {
                let func_decl = &objs.fdecls[*func_decl_key];
                functions.push(translator.translate_function(func_decl, objs, source));
            }
        }

        WasmProgram { functions, structs }
    }

    fn translate_struct_definition(&mut self, type_spec: &TypeSpec, objs: &AstObjects) -> Option<WasmStructDef> {
        let struct_name = objs.idents[type_spec.name].name.clone();
        
        if let Expr::Struct(struct_type) = &type_spec.typ {
            let mut fields = Vec::new();
            let mut field_offsets = HashMap::new();
            let mut current_offset = 0u32;

            for field_key in &struct_type.fields.list {
                let field = &objs.fields[*field_key];
                let field_type = Self::go_type_to_wasm_type(&field.typ, objs);
                let field_size = Self::get_type_size(&field_type);

                // Handle named fields
                if !field.names.is_empty() {
                    for name_key in &field.names {
                        let field_name = objs.idents[*name_key].name.clone();
                        field_offsets.insert(field_name.clone(), current_offset);
                        fields.push((field_name, field_type.clone()));
                        current_offset += field_size;
                    }
                } else {
                    // Anonymous field - generate a name based on type
                    let field_name = format!("field_{}", fields.len());
                    field_offsets.insert(field_name.clone(), current_offset);
                    fields.push((field_name, field_type.clone()));
                    current_offset += field_size;
                }
            }

            return Some(WasmStructDef {
                name: struct_name,
                fields,
                field_offsets,
                size: current_offset,
            });
        }

        None
    }

    fn get_type_size(wasm_type: &WasmType) -> u32 {
        match wasm_type {
            WasmType::Int => 4,        // 32-bit integers
            WasmType::Float => 4,      // 32-bit floats
            WasmType::Void => 0,
            WasmType::Pointer(_) => 4, // 32-bit pointers
            WasmType::Struct(_struct_name) => {
                // For now, return a default size - this would need proper struct resolution
                // In a complete implementation, you'd look up the struct definition
                16 // Default struct size
            }
        }
    }

    // Updated translate_function with proper signature extraction
    fn translate_function(&self, go_func: &FuncDecl, objs: &AstObjects, source: &str) -> WasmFunctionDef {
        // Extract function name - resolve IdentKey to get the actual name
        let func_name = objs.idents[go_func.name].name.clone();

        // Extract function signature from the type
        let (params, return_type) = Self::extract_function_signature(&go_func.typ, objs);

        // Extract function body using filtered translation
        let body = if let Some(ref body_block) = go_func.body {
            self.translate_statements(&body_block.list, objs)
        } else {
            Vec::new()
        };

        // Extract export name from comments
        let export_name = extract_export_name(source, &func_name);

        WasmFunctionDef {
            name: func_name,
            export_name,
            params,
            return_type,
            body,
        }
    }

    // Helper function to extract function parameters and return type
    fn extract_function_signature(
        func_type_key: &FuncTypeKey,
        objs: &AstObjects,
    ) -> (Vec<(String, WasmType)>, Option<WasmType>) {
        let func_type = &objs.ftypes[*func_type_key];

        // Extract parameters
        let mut params = Vec::new();
        for field_key in &func_type.params.list {
            let field = &objs.fields[*field_key];

            // Get the parameter type
            let param_type = Self::go_type_to_wasm_type(&field.typ, objs);

            // If field has names, use them; otherwise generate parameter names
            if !field.names.is_empty() {
                for name_key in &field.names {
                    let param_name = objs.idents[*name_key].name.clone();
                    params.push((param_name, param_type.clone()));
                }
            } else {
                // Anonymous parameter - generate a name
                params.push((format!("param_{}", params.len()), param_type));
            }
        }

        // Extract return type
        let return_type = if let Some(ref results) = func_type.results {
            if !results.list.is_empty() {
                let return_field = &objs.fields[results.list[0]];
                Some(Self::go_type_to_wasm_type(&return_field.typ, objs))
            } else {
                None
            }
        } else {
            None
        };

        (params, return_type)
    }

    // Helper function to convert Go types to WASM types
    fn go_type_to_wasm_type(go_type: &Expr, objs: &AstObjects) -> WasmType {
        match go_type {
            Expr::Ident(ident_key) => {
                let type_name = &objs.idents[*ident_key].name;
                match type_name.as_str() {
                    "int" | "int32" | "int64" => WasmType::Int,
                    "float32" | "float64" => WasmType::Float,
                    _ => WasmType::Int, // Default to int for unknown types
                }
            }
            // Handle other type expressions as needed
            _ => WasmType::Int, // Default fallback
        }
    }

    // Helper to translate binary operators using pattern matching
    fn translate_binary_op(go_op: &Token) -> WasmBinaryOp {
        match go_op {
            Token::ADD => WasmBinaryOp::Add,
            Token::SUB => WasmBinaryOp::Sub,
            Token::MUL => WasmBinaryOp::Mul,
            Token::QUO => WasmBinaryOp::Div,
            Token::REM => WasmBinaryOp::Rem,        // %
            Token::LSS => WasmBinaryOp::Lt,
            Token::GTR => WasmBinaryOp::Gt,
            Token::LEQ => WasmBinaryOp::LtEq,
            Token::GEQ => WasmBinaryOp::GtEq,
            Token::EQL => WasmBinaryOp::Eq,
            Token::NEQ => WasmBinaryOp::NotEq,
            Token::AND => WasmBinaryOp::And,        // &
            Token::OR => WasmBinaryOp::Or,          // |
            Token::XOR => WasmBinaryOp::Xor,        // ^
            Token::SHL => WasmBinaryOp::Shl,        // <<
            Token::SHR => WasmBinaryOp::Shr,        // >>
            Token::LOR => WasmBinaryOp::LogicalOr,  // ||
            Token::LAND => WasmBinaryOp::LogicalAnd, // &&
            _ => {
                // Handle string-based operators as fallback
                let op_str = format!("{:?}", go_op);
                match op_str.as_str() {
                    "%" => WasmBinaryOp::Rem,
                    "&" => WasmBinaryOp::And,
                    "|" => WasmBinaryOp::Or,
                    "^" => WasmBinaryOp::Xor,
                    "<<" => WasmBinaryOp::Shl,
                    ">>" => WasmBinaryOp::Shr,
                    "||" => WasmBinaryOp::LogicalOr,
                    "&&" => WasmBinaryOp::LogicalAnd,
                    _ => {
                        println!("Warning: Unknown binary operator: {:?}", go_op);
                        WasmBinaryOp::Add // Default fallback
                    }
                }
            }
        }
    }

    // Helper to translate unary operators using pattern matching
    fn translate_unary_op(go_op: &Token) -> WasmUnaryOp {
        match go_op {
            Token::SUB => WasmUnaryOp::Neg,
            Token::NOT => WasmUnaryOp::Not,
            _ => {
                println!("Warning: Unknown unary operator: {:?}", go_op);
                WasmUnaryOp::Neg // Default fallback
            }
        }
    }

    // Helper function to filter and translate statements
    fn translate_statements(&self, go_stmts: &[Stmt], objs: &AstObjects) -> Vec<WasmStatement> {
        go_stmts
            .iter()
            .filter_map(|stmt| self.translate_statement_optional(stmt, objs))
            .collect()
    }

    fn translate_expression(&self, go_expr: &Expr, objs: &AstObjects) -> WasmExpr {
        match go_expr {
            Expr::BasicLit(lit) => {
                match &lit.token {
                    Token::INT(lit_val) => {
                        let value_str: &String = lit_val.as_ref();
                        WasmExpr::Integer(value_str.parse::<i32>().unwrap_or(0))
                    }
                    Token::CHAR(lit_val) => {
                        let value_str: &String = lit_val.as_ref();
                        WasmExpr::Integer(value_str.chars().next().unwrap_or('0') as i32)
                    }
                    _ => WasmExpr::Integer(0)
                }
            }
            Expr::Ident(ident_key) => {
                let ident_name = objs.idents[*ident_key].name.clone();
                WasmExpr::Variable(ident_name)
            }
            Expr::Paren(paren_expr) => {
                self.translate_expression(&paren_expr.expr, objs)
            }
            Expr::Binary(binary_expr) => {
                let left = self.translate_expression(&binary_expr.expr_a, objs);
                let right = self.translate_expression(&binary_expr.expr_b, objs);
                let op = Self::translate_binary_op(&binary_expr.op);
                WasmExpr::Binary(op, Box::new(left), Box::new(right))
            }
            Expr::Call(call_expr) => {
                let func_name = if let Expr::Ident(func_ident) = &call_expr.func {
                    objs.idents[*func_ident].name.clone()
                } else {
                    "unknown".to_string()
                };
                let args = call_expr
                    .args
                    .iter()
                    .map(|arg| self.translate_expression(arg, objs))
                    .collect();
                WasmExpr::Call(func_name, args)
            }
            Expr::Unary(unary_expr) => {
                let operand = self.translate_expression(&unary_expr.expr, objs);
                let op = Self::translate_unary_op(&unary_expr.op);
                
                // Handle address-of and dereference operators
                match unary_expr.op {
                    Token::AND => WasmExpr::AddressOf(Box::new(operand)),
                    Token::MUL => WasmExpr::Dereference(Box::new(operand)),
                    _ => WasmExpr::Unary(op, Box::new(operand)),
                }
            }
            // Enhanced struct field access
            Expr::Selector(selector_expr) => {
                let object = self.translate_expression(&selector_expr.expr, objs);
                let field_name = objs.idents[selector_expr.sel].name.clone();
                WasmExpr::FieldAccess(Box::new(object), field_name)
            }
            // Enhanced composite literal support for structs
            Expr::CompositeLit(composite_lit) => {
                // Determine the struct type
                let struct_name = if let Some(Expr::Ident(type_ident)) = &composite_lit.typ {
                    objs.idents[*type_ident].name.clone()
                } else {
                    "unknown".to_string()
                };

                // Parse field assignments from the element list
                let mut field_values = Vec::new();
                
                for element in &composite_lit.elts {
                    match element {
                        // Key-value pairs: field: value
                        Expr::KeyValue(kv_expr) => {
                            if let Expr::Ident(key_ident) = &kv_expr.key {
                                let field_name = objs.idents[*key_ident].name.clone();
                                let field_value = self.translate_expression(&kv_expr.val, objs);
                                field_values.push((field_name, field_value));
                            }
                        }
                        // Direct values (positional initialization)
                        _ => {
                            let field_name = format!("field_{}", field_values.len());
                            let field_value = self.translate_expression(element, objs);
                            field_values.push((field_name, field_value));
                        }
                    }
                }

                WasmExpr::StructLiteral(struct_name, field_values)
            }
            _ => {
                println!("Warning: Unsupported expression type for struct support: {:?}", go_expr);
                WasmExpr::Integer(0)
            }
        }
    }
    
    // Improve the assignment handling to deal with complex left-hand sides
    fn translate_statement_optional(&self, go_stmt: &Stmt, objs: &AstObjects) -> Option<WasmStatement> {
        match go_stmt {
            Stmt::Empty(_) => None,
            Stmt::Expr(expr) => Some(WasmStatement::ExprStmt(self.translate_expression(expr, objs))),
            Stmt::Assign(assign_key) => {
                let assign_stmt = &objs.a_stmts[*assign_key];

                if !assign_stmt.lhs.is_empty() && !assign_stmt.rhs.is_empty() {
                    // Handle field assignments
                    if let Expr::Selector(selector_expr) = &assign_stmt.lhs[0] {
                        let object = self.translate_expression(&selector_expr.expr, objs);
                        let field_name = objs.idents[selector_expr.sel].name.clone();
                        let value = self.translate_expression(&assign_stmt.rhs[0], objs);
                        
                        return Some(WasmStatement::ExprStmt(
                            WasmExpr::FieldAssign(Box::new(object), field_name, Box::new(value))
                        ));
                    }
                    
                    // Handle simple variable assignment
                    if let Expr::Ident(var_key) = &assign_stmt.lhs[0] {
                        let var_name = objs.idents[*var_key].name.clone();
                        let value_expr = self.translate_expression(&assign_stmt.rhs[0], objs);

                        match assign_stmt.token {
                            Token::ASSIGN | Token::DEFINE => {
                                Some(WasmStatement::VarDecl(var_name, value_expr))
                            }
                            _ => {
                                println!("Warning: Unsupported assignment operator: {:?}", assign_stmt.token);
                                Some(WasmStatement::VarDecl(var_name, value_expr))
                            }
                        }
                    } else {
                        None
                    }
                } else {
                    None
                }
            }
            Stmt::Return(return_stmt) => {
                let return_expr = if !return_stmt.results.is_empty() {
                    Some(self.translate_expression(&return_stmt.results[0], objs))
                } else {
                    None
                };
                Some(WasmStatement::Return(return_expr))
            }
            Stmt::Block(block) => {
                let statements = self.translate_statements(&block.list, objs);
                Some(WasmStatement::Block(statements))
            }
            Stmt::If(if_stmt) => {
                let condition = self.translate_expression(&if_stmt.cond, objs);
                let if_statements = self.translate_statements(&if_stmt.body.list, objs);
                let else_statements = if let Some(ref else_stmt) = if_stmt.els {
                    match else_stmt {
                        Stmt::Block(else_block) => {
                            Some(self.translate_statements(&else_block.list, objs))
                        }
                        _ => Some(vec![self.translate_statement_optional(else_stmt, objs)?]),
                    }
                } else {
                    None
                };
                Some(WasmStatement::If(condition, if_statements, else_statements))
            }
            Stmt::IncDec(inc_dec) => {
                if let Expr::Ident(var_key) = &inc_dec.expr {
                    let var_name = objs.idents[*var_key].name.clone();
                    let operation = match inc_dec.token {
                        Token::INC => WasmBinaryOp::Add,
                        Token::DEC => WasmBinaryOp::Sub,
                        _ => {
                            println!("Warning: Unknown increment/decrement operator: {:?}", inc_dec.token);
                            WasmBinaryOp::Add
                        }
                    };

                    let increment_expr = WasmExpr::Binary(
                        operation,
                        Box::new(WasmExpr::Variable(var_name.clone())),
                        Box::new(WasmExpr::Integer(1)),
                    );

                    Some(WasmStatement::VarDecl(var_name, increment_expr))
                } else {
                    println!("Warning: Skipping complex increment/decrement");
                    None
                }
            }
            Stmt::For(for_stmt) => {
                let mut loop_body = Vec::new();
                
                // Add condition check at start of loop (if present)
                if let Some(ref condition) = for_stmt.cond {
                    // If condition is false, break out of loop
                    let negated_condition = WasmExpr::Unary(
                        WasmUnaryOp::Not, 
                        Box::new(self.translate_expression(condition, objs))
                    );
                    loop_body.push(WasmStatement::If(
                        negated_condition,
                        vec![WasmStatement::Break],
                        None
                    ));
                }
                
                // Add the main body statements
                let body_statements = self.translate_statements(&for_stmt.body.list, objs);
                loop_body.extend(body_statements);
                
                // Add post statement (if present) 
                if let Some(ref post_stmt) = for_stmt.post {
                    if let Some(post_wasm) = self.translate_statement_optional(post_stmt, objs) {
                        loop_body.push(post_wasm);
                    }
                }
                
                // Wrap everything in a block that includes init + loop
                let mut statements = Vec::new();
                
                // Add init statement (if present)
                if let Some(ref init_stmt) = for_stmt.init {
                    if let Some(init_wasm) = self.translate_statement_optional(init_stmt, objs) {
                        statements.push(init_wasm);
                    }
                }
                
                // Add the loop
                statements.push(WasmStatement::Loop(loop_body));
                
                Some(WasmStatement::Block(statements))
            }
            _ => {
                println!("Warning: Skipping unsupported statement type: {:?}", go_stmt);
                None
            }
        }
    }
}

// WASM Compiler (keeping the same implementation)
pub struct WasmCompiler {
    types: TypeSection,
    functions: FunctionSection,
    exports: ExportSection,
    codes: CodeSection,
    function_types: HashMap<String, u32>,
    function_indices: HashMap<String, u32>,
    variables: HashMap<String, u32>,
    next_local_index: u32,
    current_func_index: u32,
    struct_definitions: HashMap<String, WasmStructDef>,
    memory_offset: u32, // Current offset in linear memory
    heap_pointer: u32,  // Current heap allocation pointer
}

impl WasmCompiler {
    pub fn new() -> Self {
        Self {
            types: TypeSection::new(),
            functions: FunctionSection::new(),
            exports: ExportSection::new(),
            codes: CodeSection::new(),
            function_types: HashMap::new(),
            function_indices: HashMap::new(),
            variables: HashMap::new(),
            next_local_index: 0,
            current_func_index: 0,
            struct_definitions: HashMap::new(),
            memory_offset: 0,
            heap_pointer: 1024, // Start heap after some reserved space
        }
    }

    pub fn compile_program(&mut self, program: &WasmProgram) -> Vec<u8> {
        // Store struct definitions
        for struct_def in &program.structs {
            self.struct_definitions.insert(struct_def.name.clone(), struct_def.clone());
        }

        // First pass: register all function signatures
        for func in &program.functions {
            let param_types: Vec<ValType> = func
                .params
                .iter()
                .map(|(_, ty)| match ty {
                    WasmType::Int => ValType::I32,
                    WasmType::Float => ValType::F32,
                    WasmType::Void => panic!("Void cannot be a parameter type"),
                    WasmType::Struct(_) => ValType::I32, // Treat structs as pointers
                    WasmType::Pointer(_) => ValType::I32,
                })
                .collect();

            let return_types: Vec<ValType> = match &func.return_type {
                Some(WasmType::Int) => vec![ValType::I32],
                Some(WasmType::Float) => vec![ValType::F32],
                Some(WasmType::Struct(_)) => vec![ValType::I32], // Return as pointer
                Some(WasmType::Pointer(_)) => vec![ValType::I32],
                Some(WasmType::Void) | None => vec![],
            };

            let type_index = self.types.len();
            self.types.ty().function(param_types, return_types);
            self.function_types.insert(func.name.clone(), type_index);
            self.function_indices
                .insert(func.name.clone(), self.current_func_index);
            self.current_func_index += 1;
        }

        // Reset function index for compilation
        self.current_func_index = 0;

        // Second pass: compile function bodies
        for func in &program.functions {
            self.compile_function(func);
        }

        let mut module = WasmModule::new();
        
        // Add sections in the correct order according to WebAssembly specification:
        // 1. Type section
        module.section(&self.types);
        
        // 2. Function section
        module.section(&self.functions);
        
        // 3. Memory section (for struct storage)
        let mut memory_section = MemorySection::new();
        memory_section.memory(MemoryType {
            minimum: 1, // At least 1 page (64KB)
            maximum: None,
            memory64: false,
            shared: false,
            page_size_log2: None,
        });
        module.section(&memory_section);
        
        // 4. Export section
        module.section(&self.exports);
        
        // 5. Code section (must come last)
        module.section(&self.codes);

        module.finish()
    }

    fn compile_function(&mut self, func: &WasmFunctionDef) {
        // Reset state for this function
        self.variables.clear();
        self.next_local_index = 0;

        // Register parameters as local variables
        let mut locals = Vec::new();
        for (i, (name, _)) in func.params.iter().enumerate() {
            self.variables.insert(name.clone(), i as u32);
            self.next_local_index += 1;
        }

        // Get function type index
        let type_index = *self.function_types.get(&func.name).unwrap();

        // Add function to function section
        self.functions.function(type_index);

        // Export if needed
        if let Some(export_name) = &func.export_name {
            self.exports
                .export(export_name, ExportKind::Func, self.current_func_index);
        }

        // Collect local variable declarations
        self.collect_variable_declarations(&func.body, &mut locals);

        // Create function with locals
        let mut f = Function::new(locals);

        // Reset next_local_index to account for parameters only
        self.next_local_index = func.params.len() as u32;

        // Compile function body
        for stmt in &func.body {
            self.compile_statement_with_indexing(stmt, &mut f);
        }

        // Ensure function ends properly
        f.instruction(&Instruction::End);
        self.codes.function(&f);

        self.current_func_index += 1;
    }

    fn collect_variable_declarations(
        &mut self,
        statements: &[WasmStatement],
        locals: &mut Vec<(u32, ValType)>,
    ) {
        for stmt in statements {
            match stmt {
                WasmStatement::VarDecl(_, _) => {
                    locals.push((1, ValType::I32));
                }
                WasmStatement::Block(block_stmts) => {
                    self.collect_variable_declarations(block_stmts, locals);
                }
                WasmStatement::If(_, if_stmts, else_stmts) => {
                    self.collect_variable_declarations(if_stmts, locals);
                    if let Some(else_statements) = else_stmts {
                        self.collect_variable_declarations(else_statements, locals);
                    }
                }
                WasmStatement::Loop(loop_stmts) => {
                    self.collect_variable_declarations(loop_stmts, locals);
                }
                WasmStatement::StructDecl(_, _) => {
                    // Struct declarations don't need local variables
                }
                _ => {}
            }
        }
    }

    fn compile_statement_with_indexing(&mut self, stmt: &WasmStatement, f: &mut Function) {
        match stmt {
            WasmStatement::ExprStmt(expr) => {
                self.compile_expression(expr, f, &mut Vec::new());
                f.instruction(&Instruction::Drop); // Drop expression result
            }
            WasmStatement::VarDecl(name, init_expr) => {
                self.compile_expression(init_expr, f, &mut Vec::new());
                
                let local_idx = if let Some(&existing_idx) = self.variables.get(name) {
                    existing_idx
                } else {
                    let idx = self.next_local_index;
                    self.variables.insert(name.clone(), idx);
                    self.next_local_index += 1;
                    idx
                };
                
                f.instruction(&Instruction::LocalSet(local_idx));
            }
            WasmStatement::Return(expr_opt) => {
                if let Some(expr) = expr_opt {
                    self.compile_expression(expr, f, &mut Vec::new());
                }
                f.instruction(&Instruction::Return);
            }
            WasmStatement::Block(stmts) => {
                // Just compile each statement in sequence
                for s in stmts {
                    self.compile_statement_with_indexing(s, f);
                }
            }
            WasmStatement::If(condition, if_stmts, else_stmts) => {
                self.compile_expression(condition, f, &mut Vec::new());
                f.instruction(&Instruction::If(wasm_encoder::BlockType::Empty));
                
                for stmt in if_stmts {
                    self.compile_statement_with_indexing(stmt, f);
                }
                
                if let Some(else_statements) = else_stmts {
                    f.instruction(&Instruction::Else);
                    for stmt in else_statements {
                        self.compile_statement_with_indexing(stmt, f);
                    }
                }
                
                f.instruction(&Instruction::End);
            }
            WasmStatement::Loop(body_stmts) => {
                // Simple loop: block { loop { body; br 0 } }
                f.instruction(&Instruction::Block(wasm_encoder::BlockType::Empty));
                f.instruction(&Instruction::Loop(wasm_encoder::BlockType::Empty));
                
                for stmt in body_stmts {
                    if let WasmStatement::If(condition, if_stmts, _) = stmt {
                        if if_stmts.iter().any(|s| matches!(s, WasmStatement::Break)) {
                            // This is a break condition
                            self.compile_expression(condition, f, &mut Vec::new());
                            f.instruction(&Instruction::BrIf(1)); // Break out of loop
                            continue;
                        }
                    }
                    
                    self.compile_statement_with_indexing(stmt, f);
                }
                
                f.instruction(&Instruction::Br(0)); // Continue loop
                f.instruction(&Instruction::End);   // End loop
                f.instruction(&Instruction::End);   // End block
            }
            WasmStatement::Break => {
                f.instruction(&Instruction::Br(1)); // Break out of loop
            }
            WasmStatement::StructDecl(_, _) => {
                // Struct declarations are compile-time constructs, no runtime code needed
            }
        }
    }

    fn compile_expression(&mut self, expr: &WasmExpr, f: &mut Function, _locals: &mut Vec<(u32, ValType)>) {
        match expr {
            WasmExpr::Integer(value) => {
                f.instruction(&Instruction::I32Const(*value));
            }
            WasmExpr::Variable(name) => {
                if let Some(&idx) = self.variables.get(name) {
                    f.instruction(&Instruction::LocalGet(idx));
                } else {
                    // Variable doesn't exist - just push 0
                    f.instruction(&Instruction::I32Const(0));
                }
            }
            WasmExpr::Binary(op, left, right) => {
                // Compile left and right operands
                self.compile_expression(left, f, _locals);
                self.compile_expression(right, f, _locals);
                
                // Apply the operation
                match op {
                    WasmBinaryOp::Add => { f.instruction(&Instruction::I32Add); },
                    WasmBinaryOp::Sub => { f.instruction(&Instruction::I32Sub); },
                    WasmBinaryOp::Mul => { f.instruction(&Instruction::I32Mul); },
                    WasmBinaryOp::Div => { f.instruction(&Instruction::I32DivS); },
                    WasmBinaryOp::Rem => { f.instruction(&Instruction::I32RemS); },
                    WasmBinaryOp::Lt => { f.instruction(&Instruction::I32LtS); },
                    WasmBinaryOp::Gt => { f.instruction(&Instruction::I32GtS); },
                    WasmBinaryOp::LtEq => { f.instruction(&Instruction::I32LeS); },
                    WasmBinaryOp::GtEq => { f.instruction(&Instruction::I32GeS); },
                    WasmBinaryOp::Eq => { f.instruction(&Instruction::I32Eq); },
                    WasmBinaryOp::NotEq => { f.instruction(&Instruction::I32Ne); },
                    WasmBinaryOp::And => { f.instruction(&Instruction::I32And); },
                    WasmBinaryOp::Or => { f.instruction(&Instruction::I32Or); },
                    WasmBinaryOp::Xor => { f.instruction(&Instruction::I32Xor); },
                    WasmBinaryOp::Shl => { f.instruction(&Instruction::I32Shl); },
                    WasmBinaryOp::Shr => { f.instruction(&Instruction::I32ShrS); },
                    WasmBinaryOp::LogicalOr => {
                        // Simple: a || b becomes (a | b) != 0
                        f.instruction(&Instruction::I32Or);
                        f.instruction(&Instruction::I32Const(0));
                        f.instruction(&Instruction::I32Ne);
                    }
                    WasmBinaryOp::LogicalAnd => {
                        // Simple: a && b becomes (a & b) != 0
                        f.instruction(&Instruction::I32And);
                        f.instruction(&Instruction::I32Const(0));
                        f.instruction(&Instruction::I32Ne);
                    }
                }
            }
            WasmExpr::Call(func_name, args) => {
                // Compile arguments
                for arg in args {
                    self.compile_expression(arg, f, _locals);
                }
                
                // Call function
                if let Some(&func_idx) = self.function_indices.get(func_name) {
                    f.instruction(&Instruction::Call(func_idx));
                } else {
                    // Unknown function - drop args and push 0
                    for _ in 0..args.len() {
                        f.instruction(&Instruction::Drop);
                    }
                    f.instruction(&Instruction::I32Const(0));
                }
            }
            WasmExpr::Assign(name, value) => {
                // Compile value and store in variable
                self.compile_expression(value, f, _locals);
                if let Some(&idx) = self.variables.get(name) {
                    f.instruction(&Instruction::LocalTee(idx)); // Store and keep value on stack
                } else {
                    // Create new variable
                    let idx = self.next_local_index;
                    self.variables.insert(name.clone(), idx);
                    self.next_local_index += 1;
                    f.instruction(&Instruction::LocalTee(idx));
                }
            }
            WasmExpr::Unary(op, operand) => {
                match op {
                    WasmUnaryOp::Neg => {
                        // Negation: 0 - operand
                        f.instruction(&Instruction::I32Const(0));
                        self.compile_expression(operand, f, _locals);
                        f.instruction(&Instruction::I32Sub);
                    }
                    WasmUnaryOp::Not => {
                        // Logical not: operand == 0
                        self.compile_expression(operand, f, _locals);
                        f.instruction(&Instruction::I32Eqz);
                    }
                }
            }
            WasmExpr::StructLiteral(struct_name, field_values) => {
                // Allocate memory for struct
                if let Some(struct_def) = self.struct_definitions.get(struct_name).cloned() {
                    // Push heap pointer (where struct will be stored)
                    f.instruction(&Instruction::I32Const(self.heap_pointer as i32));
                    
                    // Initialize each field
                    for (field_name, field_expr) in field_values {
                        if let Some(&offset) = struct_def.field_offsets.get(field_name) {
                            // Calculate field address: struct_base + offset
                            f.instruction(&Instruction::I32Const(self.heap_pointer as i32));
                            f.instruction(&Instruction::I32Const(offset as i32));
                            f.instruction(&Instruction::I32Add);
                            
                            // Compile field value
                            self.compile_expression(field_expr, f, _locals);
                            
                            // Store field value at calculated address
                            f.instruction(&Instruction::I32Store(wasm_encoder::MemArg {
                                offset: 0,
                                align: 2, // 4-byte alignment
                                memory_index: 0,
                            }));
                        }
                    }
                    
                    // Return struct pointer
                    f.instruction(&Instruction::I32Const(self.heap_pointer as i32));
                    
                    // Update heap pointer
                    self.heap_pointer += struct_def.size;
                } else {
                    // Unknown struct type
                    f.instruction(&Instruction::I32Const(0));
                }
            }
            WasmExpr::FieldAccess(object_expr, _field_name) => {
                // Compile object expression to get struct pointer
                self.compile_expression(object_expr, f, _locals);
                
                // For now, we'll need to determine the struct type and field offset
                // This is simplified - a complete implementation would track types
                let field_offset = 0; // Placeholder - would need proper type analysis
                
                // Calculate field address and load value
                f.instruction(&Instruction::I32Const(field_offset));
                f.instruction(&Instruction::I32Add);
                f.instruction(&Instruction::I32Load(wasm_encoder::MemArg {
                    offset: 0,
                    align: 2,
                    memory_index: 0,
                }));
            }
            WasmExpr::FieldAssign(object_expr, _field_name, value_expr) => {
                // Calculate field address
                self.compile_expression(object_expr, f, _locals);
                let field_offset = 0; // Placeholder
                f.instruction(&Instruction::I32Const(field_offset));
                f.instruction(&Instruction::I32Add);
                
                // Compile value to store
                self.compile_expression(value_expr, f, _locals);
                
                // Store value at field address
                f.instruction(&Instruction::I32Store(wasm_encoder::MemArg {
                    offset: 0,
                    align: 2,
                    memory_index: 0,
                }));
            }
            WasmExpr::AddressOf(expr) => {
                // For variables, return their memory address
                // This is simplified - proper implementation would need address tracking
                match expr.as_ref() {
                    WasmExpr::Variable(_var_name) => {
                        // Return a mock address for the variable
                        f.instruction(&Instruction::I32Const(self.heap_pointer as i32));
                        self.heap_pointer += 4; // Reserve space
                    }
                    _ => {
                        self.compile_expression(expr, f, _locals);
                        // For now, just return the value itself
                    }
                }
            }
            WasmExpr::Dereference(expr) => {
                // Load value from address
                self.compile_expression(expr, f, _locals);
                f.instruction(&Instruction::I32Load(wasm_encoder::MemArg {
                    offset: 0,
                    align: 2,
                    memory_index: 0,
                }));
            }
        }
    }
}

// Update the high-level compile function
pub fn compile_str(go_source: &str) -> Result<Vec<u8>, Box<dyn std::error::Error>> {
    // Parse the Go source code using the simple parser function
    let (ast_objects, go_program) =
        parse_str(go_source).map_err(|e| format!("Parse error: {}", e))?;

    // Translate Go AST to WASM AST
    let wasm_program = GoToWasmTranslator::translate_program(&go_program, &ast_objects, go_source);

    // Compile WASM AST to WASM bytecode
    let mut compiler = WasmCompiler::new();
    let wasm_bytes = compiler.compile_program(&wasm_program);

    Ok(wasm_bytes)
}

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

    #[test]
    fn test_simple_function_compilation() {
        let go_source = r#"
            package main
            
            func add(x int, y int) int {
                return x + y
            }
        "#;

        let result = compile_str(go_source);
        assert!(result.is_ok(), "Failed to compile: {:?}", result.err());

        let wasm_bytes = result.unwrap();
        assert!(!wasm_bytes.is_empty(), "Generated WASM should not be empty");
    }
}