decy-hir 2.2.0

High-level Intermediate Representation for C-to-Rust transpilation
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
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
//! High-level Intermediate Representation for C-to-Rust transpilation.
//!
//! The HIR is a Rust-oriented representation that bridges C AST and Rust code generation.
//!
//! # Examples
//!
//! ```
//! use decy_hir::{HirFunction, HirType, HirParameter};
//!
//! // Create a simple HIR function
//! let func = HirFunction::new(
//!     "main".to_string(),
//!     HirType::Int,
//!     vec![],
//! );
//!
//! assert_eq!(func.name(), "main");
//! assert_eq!(func.return_type(), &HirType::Int);
//! ```

#![warn(missing_docs)]
#![warn(clippy::all)]
#![deny(unsafe_code)]

#[macro_use]
#[allow(unused_macros)]
mod generated_contracts;

/// Represents a C type in HIR.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum HirType {
    /// void type
    Void,
    /// C99 _Bool type (maps to bool in Rust)
    Bool,
    /// int type (maps to i32 in Rust)
    Int,
    /// unsigned int type (maps to u32 in Rust) - DECY-158
    UnsignedInt,
    /// float type (maps to f32 in Rust)
    Float,
    /// double type (maps to f64 in Rust)
    Double,
    /// char type (maps to u8 in Rust)
    Char,
    /// signed char type (maps to i8 in Rust) - DECY-250
    SignedChar,
    /// Pointer to another type
    Pointer(Box<HirType>),
    /// Boxed type (Rust `Box<T>`)
    Box(Box<HirType>),
    /// Vec type (Rust `Vec<T>`)
    Vec(Box<HirType>),
    /// Option type (Rust `Option<T>`) - for NULL pointer handling
    Option(Box<HirType>),
    /// Reference type (Rust `&T` or `&mut T`)
    Reference {
        /// Inner type
        inner: Box<HirType>,
        /// Whether the reference is mutable
        mutable: bool,
    },
    /// Struct type (by name)
    Struct(String),
    /// Enum type (by name)
    Enum(String),
    /// Union type with named fields
    Union(Vec<(String, HirType)>),
    /// Array type with optional size (fixed-size or unsized)
    Array {
        /// Element type
        element_type: Box<HirType>,
        /// Optional size (None for unsized arrays like function parameters)
        size: Option<usize>,
    },
    /// Function pointer type (Rust `fn` type)
    FunctionPointer {
        /// Parameter types
        param_types: Vec<HirType>,
        /// Return type
        return_type: Box<HirType>,
    },
    /// String literal type (maps to &str in Rust)
    StringLiteral,
    /// Owned string type (maps to String in Rust)
    OwnedString,
    /// String reference type (maps to &str in Rust)
    StringReference,
    /// Type alias (typedef) - preserves the alias name for codegen
    /// DECY-172: Used for size_t, ssize_t, ptrdiff_t, etc.
    TypeAlias(String),
}

impl HirType {
    /// Convert from parser AST type to HIR type.
    ///
    /// # Examples
    ///
    /// ```
    /// use decy_hir::HirType;
    /// use decy_parser::parser::Type;
    ///
    /// let hir_type = HirType::from_ast_type(&Type::Int);
    /// assert_eq!(hir_type, HirType::Int);
    /// ```
    pub fn from_ast_type(ast_type: &decy_parser::parser::Type) -> Self {
        contract_pre_parse!();
        use decy_parser::parser::Type;
        match ast_type {
            Type::Void => HirType::Void,
            Type::Bool => HirType::Bool,
            Type::Int => HirType::Int,
            Type::UnsignedInt => HirType::UnsignedInt, // DECY-158
            Type::Float => HirType::Float,
            Type::Double => HirType::Double,
            Type::Char => HirType::Char,
            Type::SignedChar => HirType::SignedChar, // DECY-250
            Type::Pointer(inner) => HirType::Pointer(Box::new(HirType::from_ast_type(inner))),
            Type::Struct(name) => HirType::Struct(name.clone()),
            Type::FunctionPointer { param_types, return_type } => HirType::FunctionPointer {
                param_types: param_types.iter().map(HirType::from_ast_type).collect(),
                return_type: Box::new(HirType::from_ast_type(return_type)),
            },
            Type::Array { element_type, size } => HirType::Array {
                element_type: Box::new(HirType::from_ast_type(element_type)),
                size: size.map(|s| s as usize),
            },
            // DECY-172: Preserve type aliases like size_t, ssize_t, ptrdiff_t
            Type::TypeAlias(name) => HirType::TypeAlias(name.clone()),
        }
    }
}

/// Represents a struct field in HIR.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct HirStructField {
    name: String,
    field_type: HirType,
}

impl HirStructField {
    /// Create a new struct field.
    pub fn new(name: String, field_type: HirType) -> Self {
        Self { name, field_type }
    }

    /// Get the field name.
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Get the field type.
    pub fn field_type(&self) -> &HirType {
        &self.field_type
    }
}

/// Represents a struct definition in HIR.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct HirStruct {
    name: String,
    fields: Vec<HirStructField>,
}

impl HirStruct {
    /// Create a new struct.
    pub fn new(name: String, fields: Vec<HirStructField>) -> Self {
        Self { name, fields }
    }

    /// Get the struct name.
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Get the struct fields.
    pub fn fields(&self) -> &[HirStructField] {
        &self.fields
    }
}

/// C++ operator kind in HIR (DECY-208).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum HirCxxOperatorKind {
    /// operator+ -> impl Add
    Add,
    /// operator- -> impl Sub
    Sub,
    /// operator* -> impl Mul
    Mul,
    /// operator/ -> impl Div
    Div,
    /// operator% -> impl Rem
    Rem,
    /// operator== -> impl PartialEq
    Equal,
    /// operator!= (derived from PartialEq)
    NotEqual,
    /// operator< -> impl PartialOrd
    Less,
    /// operator[] -> impl Index
    Index,
    /// operator+= -> impl AddAssign
    AddAssign,
    /// operator-= -> impl SubAssign
    SubAssign,
}

/// Represents a C++ method in HIR (DECY-200).
#[derive(Debug, Clone, PartialEq)]
pub struct HirMethod {
    /// The function definition
    function: HirFunction,
    /// Whether this is a const method (maps to &self vs &mut self)
    is_const: bool,
    /// Whether this is static (associated function, no self)
    is_static: bool,
    /// Whether this is virtual (maps to dyn Trait dispatch)
    is_virtual: bool,
    /// Overloaded operator kind (DECY-208)
    operator_kind: Option<HirCxxOperatorKind>,
}

impl HirMethod {
    /// Create a new HIR method.
    pub fn new(function: HirFunction, is_const: bool, is_static: bool, is_virtual: bool) -> Self {
        Self { function, is_const, is_static, is_virtual, operator_kind: None }
    }

    /// Get the underlying function.
    pub fn function(&self) -> &HirFunction {
        &self.function
    }

    /// Whether this method takes &self (const) vs &mut self.
    pub fn is_const(&self) -> bool {
        self.is_const
    }

    /// Whether this is an associated function (no self parameter).
    pub fn is_static(&self) -> bool {
        self.is_static
    }

    /// Whether this method is virtual (trait dispatch candidate).
    pub fn is_virtual(&self) -> bool {
        self.is_virtual
    }

    /// Get the operator kind if this is an overloaded operator (DECY-208).
    pub fn operator_kind(&self) -> Option<HirCxxOperatorKind> {
        self.operator_kind
    }
}

/// Represents a C++ class in HIR (DECY-200).
///
/// Maps to Rust: `struct Name { fields }` + `impl Name { methods }` +
/// optionally `impl Drop for Name { fn drop() }`.
#[derive(Debug, Clone, PartialEq)]
pub struct HirClass {
    name: String,
    fields: Vec<HirStructField>,
    methods: Vec<HirMethod>,
    constructor_params: Vec<HirParameter>,
    has_destructor: bool,
    /// Base class name for single inheritance (DECY-209)
    base_class: Option<String>,
}

impl HirClass {
    /// Create a new HIR class.
    pub fn new(name: String) -> Self {
        Self {
            name,
            fields: Vec::new(),
            methods: Vec::new(),
            constructor_params: Vec::new(),
            has_destructor: false,
            base_class: None,
        }
    }

    /// Convert from parser AST class to HIR class.
    pub fn from_ast_class(ast_class: &decy_parser::parser::Class) -> Self {
        contract_pre_class_to_struct!();
        let fields = ast_class
            .fields
            .iter()
            .map(|f| HirStructField::new(f.name().to_string(), HirType::from_ast_type(&f.field_type)))
            .collect();

        let methods = ast_class
            .methods
            .iter()
            .map(|m| {
                let mut method = HirMethod::new(
                    HirFunction::from_ast_function(&m.function),
                    m.is_const,
                    m.is_static,
                    m.is_virtual,
                );
                method.operator_kind = m.operator_kind.map(|op| {
                    use decy_parser::parser::CxxOperatorKind as P;
                    match op {
                        P::Add => HirCxxOperatorKind::Add,
                        P::Sub => HirCxxOperatorKind::Sub,
                        P::Mul => HirCxxOperatorKind::Mul,
                        P::Div => HirCxxOperatorKind::Div,
                        P::Rem => HirCxxOperatorKind::Rem,
                        P::Equal | P::NotEqual => HirCxxOperatorKind::Equal,
                        P::Less | P::LessEqual | P::Greater | P::GreaterEqual => {
                            HirCxxOperatorKind::Less
                        }
                        P::Index => HirCxxOperatorKind::Index,
                        P::AddAssign => HirCxxOperatorKind::AddAssign,
                        P::SubAssign => HirCxxOperatorKind::SubAssign,
                        P::Shl | P::Shr => HirCxxOperatorKind::Add, // fallback
                    }
                });
                method
            })
            .collect();

        let constructor_params = ast_class
            .constructor_params
            .iter()
            .map(HirParameter::from_ast_parameter)
            .collect();

        Self {
            name: ast_class.name.clone(),
            fields,
            methods,
            constructor_params,
            has_destructor: ast_class.has_destructor,
            base_class: ast_class.base_class.clone(),
        }
    }

    /// Get the class name.
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Get the class fields.
    pub fn fields(&self) -> &[HirStructField] {
        &self.fields
    }

    /// Get the class methods.
    pub fn methods(&self) -> &[HirMethod] {
        &self.methods
    }

    /// Get constructor parameters.
    pub fn constructor_params(&self) -> &[HirParameter] {
        &self.constructor_params
    }

    /// Whether this class has a destructor (needs Drop impl).
    pub fn has_destructor(&self) -> bool {
        self.has_destructor
    }

    /// Get the base class name (DECY-209).
    pub fn base_class(&self) -> Option<&str> {
        self.base_class.as_deref()
    }
}

/// Represents a C++ namespace in HIR (DECY-201).
///
/// Maps to Rust `mod` block. Contains functions, structs, classes, and
/// nested namespaces.
#[derive(Debug, Clone, PartialEq)]
pub struct HirNamespace {
    name: String,
    functions: Vec<HirFunction>,
    structs: Vec<HirStruct>,
    classes: Vec<HirClass>,
    namespaces: Vec<HirNamespace>,
}

impl HirNamespace {
    /// Create a new HIR namespace.
    pub fn new(name: String) -> Self {
        Self {
            name,
            functions: Vec::new(),
            structs: Vec::new(),
            classes: Vec::new(),
            namespaces: Vec::new(),
        }
    }

    /// Convert from parser AST namespace to HIR namespace.
    pub fn from_ast_namespace(ast_ns: &decy_parser::parser::Namespace) -> Self {
        Self {
            name: ast_ns.name.clone(),
            functions: ast_ns.functions.iter().map(HirFunction::from_ast_function).collect(),
            structs: ast_ns
                .structs
                .iter()
                .map(|s| {
                    HirStruct::new(
                        s.name().to_string(),
                        s.fields()
                            .iter()
                            .map(|f| {
                                HirStructField::new(
                                    f.name().to_string(),
                                    HirType::from_ast_type(&f.field_type),
                                )
                            })
                            .collect(),
                    )
                })
                .collect(),
            classes: ast_ns.classes.iter().map(HirClass::from_ast_class).collect(),
            namespaces: ast_ns.namespaces.iter().map(HirNamespace::from_ast_namespace).collect(),
        }
    }

    /// Get the namespace name.
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Get the functions in this namespace.
    pub fn functions(&self) -> &[HirFunction] {
        &self.functions
    }

    /// Get the structs in this namespace.
    pub fn structs(&self) -> &[HirStruct] {
        &self.structs
    }

    /// Get the classes in this namespace.
    pub fn classes(&self) -> &[HirClass] {
        &self.classes
    }

    /// Get nested namespaces.
    pub fn namespaces(&self) -> &[HirNamespace] {
        &self.namespaces
    }
}

/// Represents an enum variant in HIR.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct HirEnumVariant {
    name: String,
    value: Option<i32>,
}

impl HirEnumVariant {
    /// Create a new enum variant.
    pub fn new(name: String, value: Option<i32>) -> Self {
        Self { name, value }
    }

    /// Get the variant name.
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Get the variant value.
    pub fn value(&self) -> Option<i32> {
        self.value
    }
}

/// Represents an enum definition in HIR.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct HirEnum {
    name: String,
    variants: Vec<HirEnumVariant>,
}

impl HirEnum {
    /// Create a new enum.
    pub fn new(name: String, variants: Vec<HirEnumVariant>) -> Self {
        Self { name, variants }
    }

    /// Get the enum name.
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Get the enum variants.
    pub fn variants(&self) -> &[HirEnumVariant] {
        &self.variants
    }
}

/// Represents a typedef (type alias) in HIR.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct HirTypedef {
    name: String,
    underlying_type: HirType,
}

impl HirTypedef {
    /// Create a new typedef.
    ///
    /// # Examples
    ///
    /// ```
    /// use decy_hir::{HirTypedef, HirType};
    ///
    /// let typedef = HirTypedef::new("Integer".to_string(), HirType::Int);
    /// assert_eq!(typedef.name(), "Integer");
    /// assert_eq!(typedef.underlying_type(), &HirType::Int);
    /// ```
    pub fn new(name: String, underlying_type: HirType) -> Self {
        Self { name, underlying_type }
    }

    /// Get the typedef name.
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Get the underlying type.
    pub fn underlying_type(&self) -> &HirType {
        &self.underlying_type
    }
}

/// Represents a constant declaration in HIR (from C #define or const).
///
/// # Examples
///
/// ```
/// use decy_hir::{HirConstant, HirType, HirExpression};
///
/// let constant = HirConstant::new(
///     "MAX".to_string(),
///     HirType::Int,
///     HirExpression::IntLiteral(100),
/// );
/// assert_eq!(constant.name(), "MAX");
/// assert_eq!(constant.const_type(), &HirType::Int);
/// ```
#[derive(Debug, Clone, PartialEq)]
pub struct HirConstant {
    name: String,
    const_type: HirType,
    value: HirExpression,
}

impl HirConstant {
    /// Create a new constant.
    ///
    /// # Examples
    ///
    /// ```
    /// use decy_hir::{HirConstant, HirType, HirExpression};
    ///
    /// let constant = HirConstant::new(
    ///     "PI".to_string(),
    ///     HirType::Float,
    ///     HirExpression::IntLiteral(3), // Simplified for example
    /// );
    /// assert_eq!(constant.name(), "PI");
    /// ```
    pub fn new(name: String, const_type: HirType, value: HirExpression) -> Self {
        Self { name, const_type, value }
    }

    /// Get the constant name.
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Get the constant type.
    pub fn const_type(&self) -> &HirType {
        &self.const_type
    }

    /// Get the constant value expression.
    pub fn value(&self) -> &HirExpression {
        &self.value
    }
}

/// Represents a C macro definition in HIR.
///
/// C macros come in two forms:
/// - Object-like: `#define MAX 100` (simple text substitution)
/// - Function-like: `#define SQR(x) ((x) * (x))` (macro with parameters)
///
/// In Rust, these typically become:
/// - Object-like → `const` declarations
/// - Function-like → `fn` (inline functions) or `macro_rules!` (if truly necessary)
///
/// # Examples
///
/// ```
/// use decy_hir::{HirMacroDefinition, HirType, HirExpression};
///
/// // Object-like macro: #define MAX 100
/// let macro_def = HirMacroDefinition::new_object_like(
///     "MAX".to_string(),
///     "100".to_string(),
/// );
/// assert_eq!(macro_def.name(), "MAX");
/// assert!(!macro_def.is_function_like());
///
/// // Function-like macro: #define SQR(x) ((x) * (x))
/// let macro_def2 = HirMacroDefinition::new_function_like(
///     "SQR".to_string(),
///     vec!["x".to_string()],
///     "((x) * (x))".to_string(),
/// );
/// assert_eq!(macro_def2.name(), "SQR");
/// assert!(macro_def2.is_function_like());
/// assert_eq!(macro_def2.parameters(), &["x"]);
/// ```
///
/// Reference: K&R §4.11, ISO C99 §6.10.3
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct HirMacroDefinition {
    /// Macro name (e.g., "MAX", "SQR")
    name: String,
    /// Parameters for function-like macros (empty for object-like macros)
    parameters: Vec<String>,
    /// Macro body as a token string (unparsed)
    /// This will be expanded during codegen
    body: String,
}

impl HirMacroDefinition {
    /// Create a new object-like macro (no parameters).
    ///
    /// # Examples
    ///
    /// ```
    /// use decy_hir::HirMacroDefinition;
    ///
    /// // #define MAX 100
    /// let macro_def = HirMacroDefinition::new_object_like(
    ///     "MAX".to_string(),
    ///     "100".to_string(),
    /// );
    /// assert_eq!(macro_def.name(), "MAX");
    /// assert!(!macro_def.is_function_like());
    /// ```
    pub fn new_object_like(name: String, body: String) -> Self {
        Self { name, parameters: vec![], body }
    }

    /// Create a new function-like macro (with parameters).
    ///
    /// # Examples
    ///
    /// ```
    /// use decy_hir::HirMacroDefinition;
    ///
    /// // #define SQR(x) ((x) * (x))
    /// let macro_def = HirMacroDefinition::new_function_like(
    ///     "SQR".to_string(),
    ///     vec!["x".to_string()],
    ///     "((x) * (x))".to_string(),
    /// );
    /// assert_eq!(macro_def.name(), "SQR");
    /// assert!(macro_def.is_function_like());
    /// assert_eq!(macro_def.parameters(), &["x"]);
    /// ```
    pub fn new_function_like(name: String, parameters: Vec<String>, body: String) -> Self {
        Self { name, parameters, body }
    }

    /// Get the macro name.
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Get the macro parameters (empty for object-like macros).
    pub fn parameters(&self) -> &[String] {
        &self.parameters
    }

    /// Get the macro body (unparsed token string).
    pub fn body(&self) -> &str {
        &self.body
    }

    /// Check if this is a function-like macro (has parameters).
    pub fn is_function_like(&self) -> bool {
        !self.parameters.is_empty()
    }

    /// Check if this is an object-like macro (no parameters).
    pub fn is_object_like(&self) -> bool {
        self.parameters.is_empty()
    }
}

/// Represents a function parameter in HIR.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct HirParameter {
    name: String,
    param_type: HirType,
    /// DECY-135: Whether the pointee type is const (for pointer params like `const char*`)
    is_pointee_const: bool,
}

impl HirParameter {
    /// Create a new HIR parameter.
    ///
    /// # Examples
    ///
    /// ```
    /// use decy_hir::{HirParameter, HirType};
    ///
    /// let param = HirParameter::new("x".to_string(), HirType::Int);
    /// assert_eq!(param.name(), "x");
    /// ```
    pub fn new(name: String, param_type: HirType) -> Self {
        Self { name, param_type, is_pointee_const: false }
    }

    /// Get the parameter name.
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Get the parameter type.
    pub fn param_type(&self) -> &HirType {
        &self.param_type
    }

    /// DECY-135: Check if this parameter has a const-qualified pointee.
    pub fn is_pointee_const(&self) -> bool {
        self.is_pointee_const
    }

    /// DECY-135: Check if this is a const char* parameter (should become &str).
    pub fn is_const_char_pointer(&self) -> bool {
        self.is_pointee_const
            && matches!(self.param_type, HirType::Pointer(ref inner) if **inner == HirType::Char)
    }

    /// Convert from parser AST parameter to HIR parameter.
    pub fn from_ast_parameter(ast_param: &decy_parser::parser::Parameter) -> Self {
        contract_pre_parse!();
        Self {
            name: ast_param.name.clone(),
            param_type: HirType::from_ast_type(&ast_param.param_type),
            is_pointee_const: ast_param.is_pointee_const,
        }
    }

    /// DECY-135: Create a new parameter with a transformed type but preserving is_pointee_const.
    /// Use this when transforming parameter types (e.g., pointer to reference) to maintain
    /// const char* → &str transformation capability.
    pub fn with_type(&self, new_type: HirType) -> Self {
        Self {
            name: self.name.clone(),
            param_type: new_type,
            is_pointee_const: self.is_pointee_const,
        }
    }
}

/// CUDA function qualifier (DECY-199).
///
/// Preserved from AST through HIR for codegen to emit appropriate
/// attributes or FFI wrappers.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum HirCudaQualifier {
    /// `__global__` - kernel entry point
    Global,
    /// `__device__` - device-only function
    Device,
    /// `__host__` - host-only function
    Host,
    /// `__host__ __device__` - dual function
    HostDevice,
}

/// Represents a function in HIR.
#[derive(Debug, Clone, PartialEq)]
pub struct HirFunction {
    name: String,
    return_type: HirType,
    parameters: Vec<HirParameter>,
    body: Option<Vec<HirStatement>>,
    /// CUDA qualifier (DECY-199), None for plain C/C++ functions
    cuda_qualifier: Option<HirCudaQualifier>,
}

impl HirFunction {
    /// Create a new HIR function.
    ///
    /// # Examples
    ///
    /// ```
    /// use decy_hir::{HirFunction, HirType, HirParameter};
    ///
    /// let func = HirFunction::new(
    ///     "add".to_string(),
    ///     HirType::Int,
    ///     vec![
    ///         HirParameter::new("a".to_string(), HirType::Int),
    ///         HirParameter::new("b".to_string(), HirType::Int),
    ///     ],
    /// );
    ///
    /// assert_eq!(func.name(), "add");
    /// assert_eq!(func.parameters().len(), 2);
    /// ```
    pub fn new(name: String, return_type: HirType, parameters: Vec<HirParameter>) -> Self {
        Self { name, return_type, parameters, body: None, cuda_qualifier: None }
    }

    /// Get the function name.
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Get the return type.
    pub fn return_type(&self) -> &HirType {
        &self.return_type
    }

    /// Get the parameters.
    pub fn parameters(&self) -> &[HirParameter] {
        &self.parameters
    }

    /// Convert from parser AST function to HIR function.
    ///
    /// # Examples
    ///
    /// ```
    /// use decy_hir::HirFunction;
    /// use decy_parser::parser::{Function, Type, Parameter};
    ///
    /// let ast_func = Function::new(
    ///     "test".to_string(),
    ///     Type::Void,
    ///     vec![],
    /// );
    ///
    /// let hir_func = HirFunction::from_ast_function(&ast_func);
    /// assert_eq!(hir_func.name(), "test");
    /// ```
    pub fn from_ast_function(ast_func: &decy_parser::parser::Function) -> Self {
        let body = if ast_func.body.is_empty() {
            None
        } else {
            Some(ast_func.body.iter().map(HirStatement::from_ast_statement).collect())
        };

        let cuda_qualifier = ast_func.cuda_qualifier.map(|q| match q {
            decy_parser::parser::CudaQualifier::Global => HirCudaQualifier::Global,
            decy_parser::parser::CudaQualifier::Device => HirCudaQualifier::Device,
            decy_parser::parser::CudaQualifier::Host => HirCudaQualifier::Host,
            decy_parser::parser::CudaQualifier::HostDevice => HirCudaQualifier::HostDevice,
        });

        Self {
            name: ast_func.name.clone(),
            return_type: HirType::from_ast_type(&ast_func.return_type),
            parameters: ast_func.parameters.iter().map(HirParameter::from_ast_parameter).collect(),
            body,
            cuda_qualifier,
        }
    }

    /// Create a new HIR function with a body.
    ///
    /// # Examples
    ///
    /// ```
    /// use decy_hir::{HirFunction, HirType, HirStatement, HirExpression};
    ///
    /// let func = HirFunction::new_with_body(
    ///     "test".to_string(),
    ///     HirType::Int,
    ///     vec![],
    ///     vec![
    ///         HirStatement::VariableDeclaration {
    ///             name: "x".to_string(),
    ///             var_type: HirType::Int,
    ///             initializer: Some(HirExpression::IntLiteral(5)),
    ///         },
    ///         HirStatement::Return(Some(HirExpression::Variable("x".to_string()))),
    ///     ],
    /// );
    ///
    /// assert_eq!(func.name(), "test");
    /// assert_eq!(func.body().len(), 2);
    /// ```
    pub fn new_with_body(
        name: String,
        return_type: HirType,
        parameters: Vec<HirParameter>,
        body: Vec<HirStatement>,
    ) -> Self {
        Self { name, return_type, parameters, body: Some(body), cuda_qualifier: None }
    }

    /// Get the function body.
    pub fn body(&self) -> &[HirStatement] {
        self.body.as_deref().unwrap_or(&[])
    }

    /// DECY-190: Check if this function has a body (is a definition, not just a declaration).
    /// Returns true for definitions, false for forward declarations/prototypes.
    pub fn has_body(&self) -> bool {
        self.body.is_some()
    }

    /// Get the CUDA qualifier (DECY-199).
    pub fn cuda_qualifier(&self) -> Option<HirCudaQualifier> {
        self.cuda_qualifier
    }

    /// Set the CUDA qualifier (DECY-221: preserve through transformations).
    pub fn set_cuda_qualifier(&mut self, qualifier: Option<HirCudaQualifier>) {
        contract_pre_qualifier_preservation!();
        self.cuda_qualifier = qualifier;
    }
}

/// Unary operators for expressions.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum UnaryOperator {
    /// Unary minus (-x)
    Minus,
    /// Logical NOT (!x)
    LogicalNot,
    /// Bitwise NOT (~x)
    BitwiseNot,
    /// Address-of (&x)
    AddressOf,
    /// Post-increment (x++)
    /// Returns old value, then increments
    /// Reference: ISO C99 §6.5.2.4, K&R §2.8
    PostIncrement,
    /// Post-decrement (x--)
    /// Returns old value, then decrements
    /// Reference: ISO C99 §6.5.2.4, K&R §2.8
    PostDecrement,
    /// Pre-increment (++x)
    /// Increments first, then returns new value
    /// Reference: ISO C99 §6.5.3.1, K&R §2.8
    PreIncrement,
    /// Pre-decrement (--x)
    /// Decrements first, then returns new value
    /// Reference: ISO C99 §6.5.3.1, K&R §2.8
    PreDecrement,
}

/// Binary operators for expressions.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BinaryOperator {
    /// Addition (+)
    Add,
    /// Subtraction (-)
    Subtract,
    /// Multiplication (*)
    Multiply,
    /// Division (/)
    Divide,
    /// Modulo (%)
    Modulo,
    /// Equality (==)
    Equal,
    /// Inequality (!=)
    NotEqual,
    /// Less than (<)
    LessThan,
    /// Greater than (>)
    GreaterThan,
    /// Less than or equal (<=)
    LessEqual,
    /// Greater than or equal (>=)
    GreaterEqual,
    /// Logical AND (&&)
    LogicalAnd,
    /// Logical OR (||)
    LogicalOr,
    /// Left shift (<<)
    LeftShift,
    /// Right shift (>>)
    RightShift,
    /// Bitwise AND (&)
    BitwiseAnd,
    /// Bitwise OR (|)
    BitwiseOr,
    /// Bitwise XOR (^)
    BitwiseXor,
    /// Assignment (=) - for embedded assignments like (c=getchar())
    Assign,
    /// Comma operator (,) - DECY-224: for multi-expression statements
    Comma,
}

/// Represents an expression in HIR.
#[derive(Debug, Clone, PartialEq)]
pub enum HirExpression {
    /// Integer literal
    IntLiteral(i32),
    /// Float literal (stored as string to preserve precision)
    FloatLiteral(String),
    /// String literal (C: "hello" → Rust: "hello")
    StringLiteral(String),
    /// Character literal (C: 'a', '\0', '\n' → Rust: b'a', 0, b'\n')
    CharLiteral(i8),
    /// Variable reference
    Variable(String),
    /// Binary operation (left op right)
    BinaryOp {
        /// The operator
        op: BinaryOperator,
        /// Left operand
        left: Box<HirExpression>,
        /// Right operand
        right: Box<HirExpression>,
    },
    /// Dereference operation (*ptr)
    Dereference(Box<HirExpression>),
    /// Address-of operation (&x)
    AddressOf(Box<HirExpression>),
    /// Unary operation (-x, !x)
    UnaryOp {
        /// The operator
        op: UnaryOperator,
        /// Operand
        operand: Box<HirExpression>,
    },
    /// Post-increment expression (x++)
    /// C semantics: returns old value, then increments
    /// Rust: { let tmp = x; x += 1; tmp }
    PostIncrement {
        /// The operand to increment
        operand: Box<HirExpression>,
    },
    /// Pre-increment expression (++x)
    /// C semantics: increments first, then returns new value
    /// Rust: { x += 1; x }
    PreIncrement {
        /// The operand to increment
        operand: Box<HirExpression>,
    },
    /// Post-decrement expression (x--)
    /// C semantics: returns old value, then decrements
    /// Rust: { let tmp = x; x -= 1; tmp }
    PostDecrement {
        /// The operand to decrement
        operand: Box<HirExpression>,
    },
    /// Pre-decrement expression (--x)
    /// C semantics: decrements first, then returns new value
    /// Rust: { x -= 1; x }
    PreDecrement {
        /// The operand to decrement
        operand: Box<HirExpression>,
    },
    /// Function call (function_name(args...))
    FunctionCall {
        /// Function name
        function: String,
        /// Arguments
        arguments: Vec<HirExpression>,
    },
    /// Field access (obj.field)
    FieldAccess {
        /// Object expression
        object: Box<HirExpression>,
        /// Field name
        field: String,
    },
    /// Pointer field access (ptr->field)
    PointerFieldAccess {
        /// Pointer expression
        pointer: Box<HirExpression>,
        /// Field name
        field: String,
    },
    /// Array indexing
    ArrayIndex {
        /// Array expression
        array: Box<HirExpression>,
        /// Index expression
        index: Box<HirExpression>,
    },
    /// Safe slice indexing (DECY-069)
    /// Represents safe, bounds-checked array access: `arr[index]`
    /// Generated when pointer arithmetic can be transformed to safe indexing.
    /// Unlike ArrayIndex (which may use unsafe), SliceIndex guarantees zero unsafe blocks.
    SliceIndex {
        /// Slice/array expression
        slice: Box<HirExpression>,
        /// Index expression
        index: Box<HirExpression>,
        /// Element type (for codegen type inference)
        element_type: HirType,
    },
    /// Sizeof expression (sizeof(T) → `std::mem::size_of::<T>()`)
    Sizeof {
        /// Type name as a string (e.g., "int", "struct Data")
        type_name: String,
    },
    /// NULL literal (NULL → None)
    NullLiteral,
    /// NULL check expression (p != NULL → is_some(), p == NULL → is_none())
    IsNotNull(Box<HirExpression>),
    /// calloc(count, sizeof(T)) → vec![0; count]
    Calloc {
        /// Number of elements to allocate
        count: Box<HirExpression>,
        /// Element type
        element_type: Box<HirType>,
    },
    /// malloc(size) → Box::new(default) or Vec::with_capacity(n)
    Malloc {
        /// Size expression (typically sizeof(T) or n * sizeof(T))
        size: Box<HirExpression>,
    },
    /// realloc(ptr, new_size) → Vec::resize or Vec::reserve
    Realloc {
        /// Pointer to reallocate
        pointer: Box<HirExpression>,
        /// New size expression (typically n * sizeof(T))
        new_size: Box<HirExpression>,
    },
    /// String method call (e.g., s.len(), s.to_string(), s.clone_into(&mut dst))
    StringMethodCall {
        /// Receiver expression (e.g., s in s.len())
        receiver: Box<HirExpression>,
        /// Method name (e.g., "len", "to_string", "clone_into")
        method: String,
        /// Arguments to the method call
        arguments: Vec<HirExpression>,
    },
    /// Cast expression (C: (int)x → Rust: x as i32)
    ///
    /// Represents a C-style cast that converts an expression to a target type.
    /// Maps to Rust `as` operator for safe casts, or `transmute` for unsafe casts.
    ///
    /// # Sprint 19 Feature (DECY-059)
    ///
    /// Added in Sprint 19 to support C cast expressions.
    Cast {
        /// Target type to cast to
        target_type: HirType,
        /// Expression being cast
        expr: Box<HirExpression>,
    },
    /// Compound literal (C: (struct Point){10, 20} → Rust: Point { x: 10, y: 20 })
    ///
    /// C99 compound literals create anonymous objects of a specified type.
    /// Used for inline struct/array initialization.
    ///
    /// # Sprint 19 Feature (DECY-060)
    ///
    /// Added in Sprint 19 to support C99 compound literals.
    CompoundLiteral {
        /// Type of the compound literal (struct Point, int[], etc.)
        literal_type: HirType,
        /// Initializer expressions (values for struct fields or array elements)
        initializers: Vec<HirExpression>,
    },
    /// Ternary/Conditional expression (C: cond ? then_val : else_val)
    ///
    /// The C ternary operator evaluates the condition and returns either
    /// the then_val or else_val based on whether condition is truthy.
    ///
    /// Maps to Rust's `if cond { then_val } else { else_val }` expression.
    ///
    /// # DECY-192
    ///
    /// Added to support K&R Chapter 2.11 Conditional Expressions.
    Ternary {
        /// Condition expression (evaluated as boolean)
        condition: Box<HirExpression>,
        /// Value if condition is true
        then_expr: Box<HirExpression>,
        /// Value if condition is false
        else_expr: Box<HirExpression>,
    },
    /// C++ new expression: `new T(args)` -> `Box::new(T::new(args))` (DECY-207)
    CxxNew {
        /// Type being allocated
        allocated_type: HirType,
        /// Constructor arguments (empty for default construction)
        arguments: Vec<HirExpression>,
    },
    /// C++ delete expression: `delete ptr` -> `drop(ptr)` (DECY-207)
    CxxDelete {
        /// Expression being deleted
        operand: Box<HirExpression>,
    },
}

/// Represents a single case in a switch statement.
#[derive(Debug, Clone, PartialEq)]
pub struct SwitchCase {
    /// Case value expression (None for default case)
    pub value: Option<HirExpression>,
    /// Statements to execute for this case
    pub body: Vec<HirStatement>,
}

/// Represents a statement in HIR.
#[derive(Debug, Clone, PartialEq)]
pub enum HirStatement {
    /// Variable declaration with optional initializer
    VariableDeclaration {
        /// Variable name
        name: String,
        /// Variable type
        var_type: HirType,
        /// Optional initializer expression
        initializer: Option<HirExpression>,
    },
    /// Return statement with optional value
    Return(Option<HirExpression>),
    /// If statement with condition, then-block, and optional else-block
    If {
        /// Condition expression
        condition: HirExpression,
        /// Then block (statements to execute if condition is true)
        then_block: Vec<HirStatement>,
        /// Else block (optional statements to execute if condition is false)
        else_block: Option<Vec<HirStatement>>,
    },
    /// While loop with condition and body
    While {
        /// Loop condition
        condition: HirExpression,
        /// Loop body (statements to execute while condition is true)
        body: Vec<HirStatement>,
    },
    /// Break statement (exit loop)
    Break,
    /// Continue statement (skip to next iteration)
    Continue,
    /// Assignment statement (target = value)
    Assignment {
        /// Target variable name
        target: String,
        /// Value expression to assign
        value: HirExpression,
    },
    /// For loop with optional init, condition, optional increment, and body
    For {
        /// Initialization statements (e.g., int i = 0, j = 10) - DECY-224
        init: Vec<HirStatement>,
        /// Loop condition expression (None = infinite loop, e.g. `for(;;)`)
        condition: Option<HirExpression>,
        /// Increment statements (e.g., i++, j--) - DECY-224
        increment: Vec<HirStatement>,
        /// Loop body (statements to execute while condition is true)
        body: Vec<HirStatement>,
    },
    /// Switch statement with condition, cases, and optional default case
    Switch {
        /// Condition expression to match against
        condition: HirExpression,
        /// List of case statements
        cases: Vec<SwitchCase>,
        /// Optional default case body
        default_case: Option<Vec<HirStatement>>,
    },
    /// Pointer dereference assignment (*ptr = value)
    DerefAssignment {
        /// Target expression to dereference
        target: HirExpression,
        /// Value expression to assign
        value: HirExpression,
    },
    /// Array index assignment
    ArrayIndexAssignment {
        /// Array expression
        array: Box<HirExpression>,
        /// Index expression
        index: Box<HirExpression>,
        /// Value expression to assign
        value: HirExpression,
    },
    /// Field assignment (ptr->field = value or obj.field = value)
    FieldAssignment {
        /// Object/pointer expression
        object: HirExpression,
        /// Field name
        field: String,
        /// Value expression to assign
        value: HirExpression,
    },
    /// Free statement (free(ptr) → automatic drop via RAII)
    Free {
        /// Pointer expression to free
        pointer: HirExpression,
    },
    /// Expression statement (e.g., printf("Hello");, free(ptr);, i++;)
    ///
    /// Represents an expression used as a statement, typically for side effects.
    /// Common in C for function calls whose return values are discarded.
    ///
    /// # DECY-065
    ///
    /// Added to fix bug where function call statements (like printf) were being
    /// converted to Break placeholder, causing them to disappear during transpilation.
    Expression(HirExpression),
    /// Inline assembly statement (C: asm("...") or __asm__("..."))
    ///
    /// C inline assembly cannot be automatically transpiled to safe Rust.
    /// This variant preserves the assembly text for manual review.
    ///
    /// # DECY-197
    ///
    /// Added to handle inline assembly in C code. The codegen emits a
    /// review-required comment rather than attempting automatic translation.
    InlineAsm {
        /// The raw assembly text from the C source
        text: String,
        /// Whether the assembly might be translatable to Rust intrinsics
        translatable: bool,
    },
}

impl HirStatement {
    /// Convert from parser AST statement to HIR statement.
    pub fn from_ast_statement(ast_stmt: &decy_parser::parser::Statement) -> Self {
        use decy_parser::parser::Statement;
        match ast_stmt {
            Statement::VariableDeclaration { name, var_type, initializer } => {
                HirStatement::VariableDeclaration {
                    name: name.clone(),
                    var_type: HirType::from_ast_type(var_type),
                    initializer: initializer.as_ref().map(HirExpression::from_ast_expression),
                }
            }
            Statement::Return(expr) => {
                HirStatement::Return(expr.as_ref().map(HirExpression::from_ast_expression))
            }
            Statement::Assignment { target, value } => HirStatement::Assignment {
                target: target.clone(),
                value: HirExpression::from_ast_expression(value),
            },
            Statement::If { condition, then_block, else_block } => HirStatement::If {
                condition: HirExpression::from_ast_expression(condition),
                then_block: then_block.iter().map(HirStatement::from_ast_statement).collect(),
                else_block: else_block
                    .as_ref()
                    .map(|block| block.iter().map(HirStatement::from_ast_statement).collect()),
            },
            Statement::For { init, condition, increment, body } => HirStatement::For {
                // DECY-224: Support multiple init statements
                init: init.iter().map(HirStatement::from_ast_statement).collect(),
                condition: condition.as_ref().map(HirExpression::from_ast_expression),
                // DECY-224: Support multiple increment statements
                increment: increment.iter().map(HirStatement::from_ast_statement).collect(),
                body: body.iter().map(HirStatement::from_ast_statement).collect(),
            },
            Statement::While { condition, body } => HirStatement::While {
                condition: HirExpression::from_ast_expression(condition),
                body: body.iter().map(HirStatement::from_ast_statement).collect(),
            },
            Statement::DerefAssignment { target, value } => HirStatement::DerefAssignment {
                target: HirExpression::from_ast_expression(target),
                value: HirExpression::from_ast_expression(value),
            },
            Statement::ArrayIndexAssignment { array, index, value } => {
                HirStatement::ArrayIndexAssignment {
                    array: Box::new(HirExpression::from_ast_expression(array)),
                    index: Box::new(HirExpression::from_ast_expression(index)),
                    value: HirExpression::from_ast_expression(value),
                }
            }
            Statement::FieldAssignment { object, field, value } => HirStatement::FieldAssignment {
                object: HirExpression::from_ast_expression(object),
                field: field.clone(),
                value: HirExpression::from_ast_expression(value),
            },
            Statement::Break => HirStatement::Break,
            Statement::Continue => HirStatement::Continue,
            // Increment/decrement statements are converted to assignments
            // ptr++ becomes ptr = ptr + 1
            Statement::PostIncrement { target } | Statement::PreIncrement { target } => {
                HirStatement::Assignment {
                    target: target.clone(),
                    value: HirExpression::BinaryOp {
                        op: BinaryOperator::Add,
                        left: Box::new(HirExpression::Variable(target.clone())),
                        right: Box::new(HirExpression::IntLiteral(1)),
                    },
                }
            }
            // ptr-- becomes ptr = ptr - 1
            Statement::PostDecrement { target } | Statement::PreDecrement { target } => {
                HirStatement::Assignment {
                    target: target.clone(),
                    value: HirExpression::BinaryOp {
                        op: BinaryOperator::Subtract,
                        left: Box::new(HirExpression::Variable(target.clone())),
                        right: Box::new(HirExpression::IntLiteral(1)),
                    },
                }
            }
            // Compound assignments like ptr += offset become ptr = ptr + offset
            Statement::CompoundAssignment { target, op, value } => HirStatement::Assignment {
                target: target.clone(),
                value: HirExpression::BinaryOp {
                    op: convert_binary_operator(*op),
                    left: Box::new(HirExpression::Variable(target.clone())),
                    right: Box::new(HirExpression::from_ast_expression(value)),
                },
            },
            // DECY-185: Compound assignments to complex targets like *ptr *= 2, sb->capacity *= 2
            // These become DerefAssignment with a BinaryOp value
            Statement::DerefCompoundAssignment { target, op, value } => {
                let hir_target = HirExpression::from_ast_expression(target);
                HirStatement::DerefAssignment {
                    target: hir_target.clone(),
                    value: HirExpression::BinaryOp {
                        op: convert_binary_operator(*op),
                        left: Box::new(hir_target),
                        right: Box::new(HirExpression::from_ast_expression(value)),
                    },
                }
            }
            // Switch statement - convert cases and default
            Statement::Switch { condition, cases, default_case } => HirStatement::Switch {
                condition: HirExpression::from_ast_expression(condition),
                cases: cases
                    .iter()
                    .map(|case| SwitchCase {
                        value: case.value.as_ref().map(HirExpression::from_ast_expression),
                        body: case.body.iter().map(HirStatement::from_ast_statement).collect(),
                    })
                    .collect(),
                default_case: default_case
                    .as_ref()
                    .map(|block| block.iter().map(HirStatement::from_ast_statement).collect()),
            },
            // Function call statement - convert to expression statement
            // DECY-065: Now properly supported with HirStatement::Expression variant
            Statement::FunctionCall { function, arguments } => {
                HirStatement::Expression(HirExpression::FunctionCall {
                    function: function.clone(),
                    arguments: arguments.iter().map(HirExpression::from_ast_expression).collect(),
                })
            }
        }
    }
}

impl HirExpression {
    /// Convert from parser AST expression to HIR expression.
    pub fn from_ast_expression(ast_expr: &decy_parser::parser::Expression) -> Self {
        use decy_parser::parser::Expression;
        match ast_expr {
            Expression::IntLiteral(value) => HirExpression::IntLiteral(*value),
            Expression::FloatLiteral(value) => HirExpression::FloatLiteral(value.clone()),
            Expression::StringLiteral(value) => HirExpression::StringLiteral(value.clone()),
            Expression::CharLiteral(value) => HirExpression::CharLiteral(*value),
            Expression::Variable(name) => HirExpression::Variable(name.clone()),
            Expression::BinaryOp { op, left, right } => HirExpression::BinaryOp {
                op: convert_binary_operator(*op),
                left: Box::new(HirExpression::from_ast_expression(left)),
                right: Box::new(HirExpression::from_ast_expression(right)),
            },
            Expression::FunctionCall { function, arguments } => HirExpression::FunctionCall {
                function: function.clone(),
                arguments: arguments.iter().map(HirExpression::from_ast_expression).collect(),
            },
            Expression::Dereference(inner) => {
                HirExpression::Dereference(Box::new(HirExpression::from_ast_expression(inner)))
            }
            Expression::UnaryOp { op, operand } => HirExpression::UnaryOp {
                op: convert_unary_operator(*op),
                operand: Box::new(HirExpression::from_ast_expression(operand)),
            },
            Expression::ArrayIndex { array, index } => HirExpression::ArrayIndex {
                array: Box::new(HirExpression::from_ast_expression(array)),
                index: Box::new(HirExpression::from_ast_expression(index)),
            },
            Expression::FieldAccess { object, field } => HirExpression::FieldAccess {
                object: Box::new(HirExpression::from_ast_expression(object)),
                field: field.clone(),
            },
            Expression::PointerFieldAccess { pointer, field } => {
                HirExpression::PointerFieldAccess {
                    pointer: Box::new(HirExpression::from_ast_expression(pointer)),
                    field: field.clone(),
                }
            }
            // DECY-139: Increment/decrement expressions in expression context
            // Properly preserve the increment/decrement for codegen to emit correct Rust
            Expression::PostIncrement { operand } => HirExpression::PostIncrement {
                operand: Box::new(HirExpression::from_ast_expression(operand)),
            },
            Expression::PreIncrement { operand } => HirExpression::PreIncrement {
                operand: Box::new(HirExpression::from_ast_expression(operand)),
            },
            Expression::PostDecrement { operand } => HirExpression::PostDecrement {
                operand: Box::new(HirExpression::from_ast_expression(operand)),
            },
            Expression::PreDecrement { operand } => HirExpression::PreDecrement {
                operand: Box::new(HirExpression::from_ast_expression(operand)),
            },
            Expression::Sizeof { type_name } => {
                HirExpression::Sizeof { type_name: type_name.clone() }
            }
            Expression::Cast { target_type, expr } => HirExpression::Cast {
                target_type: HirType::from_ast_type(target_type),
                expr: Box::new(HirExpression::from_ast_expression(expr)),
            },
            Expression::CompoundLiteral { literal_type, initializers } => {
                HirExpression::CompoundLiteral {
                    literal_type: HirType::from_ast_type(literal_type),
                    initializers: initializers
                        .iter()
                        .map(HirExpression::from_ast_expression)
                        .collect(),
                }
            }
            // DECY-192: Ternary/conditional expression
            Expression::Ternary { condition, then_expr, else_expr } => HirExpression::Ternary {
                condition: Box::new(HirExpression::from_ast_expression(condition)),
                then_expr: Box::new(HirExpression::from_ast_expression(then_expr)),
                else_expr: Box::new(HirExpression::from_ast_expression(else_expr)),
            },
            // DECY-207: C++ new expression
            Expression::CxxNew { type_name, arguments } => HirExpression::CxxNew {
                allocated_type: HirType::Struct(type_name.clone()),
                arguments: arguments.iter().map(HirExpression::from_ast_expression).collect(),
            },
            // DECY-207: C++ delete expression
            Expression::CxxDelete { operand } => HirExpression::CxxDelete {
                operand: Box::new(HirExpression::from_ast_expression(operand)),
            },
            // DECY-226: C++ nullptr -> NullLiteral
            Expression::NullLiteral => HirExpression::NullLiteral,
            // DECY-226: C++ bool literal
            Expression::BoolLiteral(val) => {
                if *val { HirExpression::IntLiteral(1) } else { HirExpression::IntLiteral(0) }
            }
        }
    }
}

/// Convert parser UnaryOperator to HIR UnaryOperator
fn convert_unary_operator(op: decy_parser::parser::UnaryOperator) -> UnaryOperator {
    use decy_parser::parser::UnaryOperator as ParserOp;
    match op {
        ParserOp::Minus => UnaryOperator::Minus,
        ParserOp::LogicalNot => UnaryOperator::LogicalNot,
        ParserOp::BitwiseNot => UnaryOperator::BitwiseNot,
        ParserOp::AddressOf => UnaryOperator::AddressOf,
    }
}

/// Convert parser BinaryOperator to HIR BinaryOperator
fn convert_binary_operator(op: decy_parser::parser::BinaryOperator) -> BinaryOperator {
    use decy_parser::parser::BinaryOperator as ParserOp;
    match op {
        ParserOp::Add => BinaryOperator::Add,
        ParserOp::Subtract => BinaryOperator::Subtract,
        ParserOp::Multiply => BinaryOperator::Multiply,
        ParserOp::Divide => BinaryOperator::Divide,
        ParserOp::Modulo => BinaryOperator::Modulo,
        ParserOp::Equal => BinaryOperator::Equal,
        ParserOp::NotEqual => BinaryOperator::NotEqual,
        ParserOp::LessThan => BinaryOperator::LessThan,
        ParserOp::GreaterThan => BinaryOperator::GreaterThan,
        ParserOp::LessEqual => BinaryOperator::LessEqual,
        ParserOp::GreaterEqual => BinaryOperator::GreaterEqual,
        ParserOp::LogicalAnd => BinaryOperator::LogicalAnd,
        ParserOp::LogicalOr => BinaryOperator::LogicalOr,
        // DECY-137: Bitwise and shift operators
        ParserOp::LeftShift => BinaryOperator::LeftShift,
        ParserOp::RightShift => BinaryOperator::RightShift,
        ParserOp::BitwiseAnd => BinaryOperator::BitwiseAnd,
        ParserOp::BitwiseOr => BinaryOperator::BitwiseOr,
        ParserOp::BitwiseXor => BinaryOperator::BitwiseXor,
        // DECY-195: Assignment operator for embedded assignments
        ParserOp::Assign => BinaryOperator::Assign,
        // DECY-224: Comma operator for multi-expression statements
        ParserOp::Comma => BinaryOperator::Comma,
    }
}

#[cfg(test)]
#[path = "hir_tests.rs"]
mod hir_tests;

#[cfg(test)]
#[path = "property_tests.rs"]
mod property_tests;

#[cfg(test)]
#[path = "statement_tests.rs"]
mod statement_tests;

#[cfg(test)]
#[path = "struct_tests.rs"]
mod struct_tests;

#[cfg(test)]
#[path = "array_indexing_tests.rs"]
mod array_indexing_tests;

#[cfg(test)]
#[path = "slice_index_tests.rs"]
mod slice_index_tests; // DECY-069

#[cfg(test)]
#[path = "for_loop_tests.rs"]
mod for_loop_tests;

#[cfg(test)]
#[path = "typedef_tests.rs"]
mod typedef_tests;

#[cfg(test)]
#[path = "typedef_property_tests.rs"]
mod typedef_property_tests;

#[cfg(test)]
#[path = "function_pointer_tests.rs"]
mod function_pointer_tests;

#[cfg(test)]
#[path = "string_tests.rs"]
mod string_tests;

#[cfg(test)]
#[path = "string_property_tests.rs"]
mod string_property_tests;

#[cfg(test)]
#[path = "switch_tests.rs"]
mod switch_tests;

#[cfg(test)]
#[path = "macro_definition_tests.rs"]
mod macro_definition_tests;

#[cfg(test)]
#[path = "coverage_tests.rs"]
mod coverage_tests;