rsbinder-aidl 0.6.1

This is a AIDL compiler for rsbinder.
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
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
// Copyright 2022 Jeff Kim <hiking90@gmail.com>
// SPDX-License-Identifier: Apache-2.0

// #![allow(clippy::missing_const_for_fn)]

use std::cell::RefCell;
use std::collections::HashMap;

use crate::error::{pest_error_to_diagnostic, AidlError, ParseError};

use convert_case::{Case, Casing};

use pest::Parser;
#[derive(pest_derive::Parser)]
#[grammar = "aidl.pest"]
pub struct AIDLParser;

use crate::const_expr::{ConstExpr, ValueType};
use crate::type_generator;
use crate::Namespace;

#[derive(Debug, Clone)]
pub enum SymbolType {
    EnumMember,
    InterfaceConstant,
    // Future expansion: ParcelableDefault, Variable, etc.
}

#[derive(Debug, Clone)]
pub struct Symbol {
    #[allow(dead_code)]
    pub name: String,
    pub value: crate::const_expr::ConstExpr,
    #[allow(dead_code)]
    pub symbol_type: SymbolType,
    #[allow(dead_code)]
    pub namespace: Option<String>,
}

thread_local! {
    static DECLARATION_MAP: RefCell<HashMap<Namespace, Declaration>> = RefCell::new(HashMap::new());
    #[allow(clippy::missing_const_for_thread_local)]
    static NAMESPACE_STACK: RefCell<Vec<Namespace>> = RefCell::new(Vec::new());
    static DOCUMENT: RefCell<Document> = RefCell::new(Document::new());

    // Universal Symbol Table - supports all types of named constants
    static SYMBOL_TABLE: RefCell<HashMap<String, Symbol>> = RefCell::new(HashMap::new());

    // Filename and source text of the source currently being parsed (used for error message generation)
    #[allow(clippy::missing_const_for_thread_local)]
    static CURRENT_SOURCE_NAME: RefCell<String> = RefCell::new(String::new());
    #[allow(clippy::missing_const_for_thread_local)]
    static CURRENT_SOURCE_TEXT: RefCell<String> = RefCell::new(String::new());
}

/// Helper that creates a ParseError using the same thread-local source info as SourceGuard.
fn make_parse_error(message: impl Into<String>, start: usize, end: usize) -> AidlError {
    let filename = CURRENT_SOURCE_NAME.with(|name| name.borrow().clone());
    let source = CURRENT_SOURCE_TEXT.with(|text| text.borrow().clone());
    AidlError::from(ParseError {
        src: miette::NamedSource::new(filename, source),
        span: miette::SourceSpan::new(start.into(), end - start),
        message: message.into(),
        help: None,
    })
}

/// Context struct holding the filename and source text of a file to be parsed.
/// Passed to `parse_document()` so that file information is included in error diagnostics.
#[derive(Debug, Clone)]
pub struct SourceContext {
    pub filename: String,
    pub source: String,
}

impl SourceContext {
    pub fn new(filename: impl Into<String>, source: impl Into<String>) -> Self {
        Self {
            filename: filename.into(),
            source: source.into(),
        }
    }
}

/// RAII guard: sets the thread-local source context on creation and clears it
/// automatically on drop, ensuring cleanup on both error-return and panic paths.
pub struct SourceGuard;

impl SourceGuard {
    pub fn new(filename: &str, source: &str) -> Self {
        CURRENT_SOURCE_NAME.with(|name| *name.borrow_mut() = filename.to_string());
        CURRENT_SOURCE_TEXT.with(|text| *text.borrow_mut() = source.to_string());
        SourceGuard
    }
}

impl Drop for SourceGuard {
    fn drop(&mut self) {
        CURRENT_SOURCE_NAME.with(|name| name.borrow_mut().clear());
        CURRENT_SOURCE_TEXT.with(|text| text.borrow_mut().clear());
    }
}

/// Returns the filename of the currently active source context.
pub fn current_source_name() -> String {
    CURRENT_SOURCE_NAME.with(|name| name.borrow().clone())
}

/// Returns the source text of the currently active source context.
pub fn current_source_text() -> String {
    CURRENT_SOURCE_TEXT.with(|text| text.borrow().clone())
}

pub struct NamespaceGuard();

impl NamespaceGuard {
    pub fn new(ns: &Namespace) -> Self {
        NAMESPACE_STACK.with(|vec| {
            vec.borrow_mut().push(ns.clone());
        });
        Self()
    }
}

impl Drop for NamespaceGuard {
    fn drop(&mut self) {
        NAMESPACE_STACK.with(|vec| {
            vec.borrow_mut().pop();
        });
    }
}

pub fn current_namespace() -> Namespace {
    NAMESPACE_STACK.with(|stack| stack.borrow().last().cloned().unwrap_or_default())
}

pub fn set_current_document(document: &Document) {
    DOCUMENT.with(|doc| {
        let mut doc = doc.borrow_mut();

        doc.package = document.package.clone();
        doc.imports = document.imports.clone();
    })
}

fn make_ns_candidate(ns: &Namespace, name: &Namespace) -> Vec<Namespace> {
    let mut res = Vec::new();

    let mut curr_ns = ns.clone();
    curr_ns.push_ns(name);
    res.push(curr_ns.clone());

    if name.ns.len() > 1 {
        curr_ns.pop(); // Remove the last name in case of IntEnum.Foo. Removed the Foo.
        res.push(curr_ns);
    }

    res
}

#[derive(Debug)]
pub struct LookupDecl {
    pub decl: Declaration,
    pub ns: Namespace,
    pub name: Namespace,
}

pub fn lookup_decl_from_name(name: &str, style: &str) -> Option<LookupDecl> {
    let mut namespace = Namespace::new(name, style);

    let mut ns_vec = Vec::new();

    // 1, check if the type exists in the current namespace.
    let mut curr_ns = current_namespace();
    ns_vec.append(&mut make_ns_candidate(&curr_ns, &namespace));

    curr_ns.pop(); // For parent namespace
    ns_vec.append(&mut make_ns_candidate(&curr_ns, &namespace));

    // 2. check if the type exists in the imports from the current document.
    DOCUMENT.with(|curr_doc| {
        let curr_doc = curr_doc.borrow();

        if let Some(package) = &curr_doc.package {
            let package_ns = Namespace::new(package, Namespace::AIDL);
            ns_vec.append(&mut make_ns_candidate(&package_ns, &namespace));
        }

        if let Some(imported) = curr_doc.imports.get(&namespace.ns[0]) {
            let mut new_ns = Namespace::new(imported, Namespace::AIDL);
            new_ns.ns.extend_from_slice(&namespace.ns[1..]);
            ns_vec.push(new_ns);
        }
    });

    let (decl, ns) = DECLARATION_MAP.with(|hashmap| {
        for ns in &ns_vec {
            if let Some(decl) = hashmap.borrow().get(ns) {
                return Some((decl.clone(), ns.clone()));
            }
        }

        let curr_ns = current_namespace();
        if let Some(decl) = hashmap.borrow().get(&curr_ns) {
            return Some((decl.clone(), curr_ns));
        }

        None
    })?;

    // leave max 2 items because the other items are for name space.
    if namespace.ns.len() > 2 {
        namespace.ns.drain(0..namespace.ns.len() - 2);
    }

    Some(LookupDecl {
        decl,
        ns,
        name: namespace,
    })
}

fn make_const_expr(const_expr: Option<&ConstExpr>, lookup_decl: &LookupDecl) -> ConstExpr {
    if let Some(expr) = const_expr {
        expr.clone()
    } else {
        let ns = current_namespace().relative_mod(&lookup_decl.ns);

        let name = if !ns.is_empty() {
            format!(
                "{}{}{}",
                ns,
                Namespace::RUST,
                lookup_decl.name.to_string(Namespace::RUST)
            )
        } else {
            lookup_decl.name.to_string(Namespace::RUST)
        };
        ConstExpr::new(ValueType::Name(name))
    }
}

fn lookup_name_from_decl(decl: &Declaration, lookup_decl: &LookupDecl) -> Option<ConstExpr> {
    let lookup_ident = lookup_decl.name.ns.last().unwrap().to_owned();
    match decl {
        Declaration::Variable(decl) => {
            if decl.identifier == lookup_ident {
                Some(make_const_expr(decl.const_expr.as_ref(), lookup_decl))
            } else {
                None
            }
        }
        Declaration::Interface(ref decl) => {
            for var in &decl.constant_list {
                if var.identifier == lookup_ident {
                    return Some(make_const_expr(var.const_expr.as_ref(), lookup_decl));
                }
            }
            lookup_name_members(&decl.members, lookup_decl)
        }

        Declaration::Parcelable(ref decl) => lookup_name_members(&decl.members, lookup_decl),

        Declaration::Enum(ref decl) => {
            for enumerator in &decl.enumerator_list {
                if enumerator.identifier == lookup_ident {
                    return Some(make_const_expr(None, lookup_decl));
                }
            }
            lookup_name_members(&decl.members, lookup_decl)
        }

        Declaration::Union(ref decl) => lookup_name_members(&decl.members, lookup_decl),
    }
}

fn lookup_name_members(members: &Vec<Declaration>, lookup_decl: &LookupDecl) -> Option<ConstExpr> {
    for decl in members {
        if let Some(expr) = lookup_name_from_decl(decl, lookup_decl) {
            return Some(expr);
        }
    }
    None
}

// Universal symbol registration - supports all types of named constants
pub fn register_symbol(
    name: &str,
    value: ConstExpr,
    symbol_type: SymbolType,
    namespace: Option<&str>,
) {
    let symbol = Symbol {
        name: name.to_string(),
        value,
        symbol_type,
        namespace: namespace.map(|s| s.to_string()),
    };

    SYMBOL_TABLE.with(|table| {
        let mut table = table.borrow_mut();

        // Register with simple name
        table.insert(name.to_string(), symbol.clone());

        // Also register with qualified name if namespace is provided
        if let Some(ns) = namespace {
            let qualified_name = format!("{}.{}", ns, name);
            table.insert(qualified_name, symbol);
        }
    });
}

// Note: register_enum_member removed as it's not used
// Use register_symbol directly with SymbolType::EnumMember

// Enhanced name resolution with universal symbol table
pub fn name_to_const_expr(name: &str) -> Option<ConstExpr> {
    // First, try to resolve from universal symbol table (exact match)
    let symbol_result =
        SYMBOL_TABLE.with(|table| table.borrow().get(name).map(|symbol| symbol.value.clone()));

    if symbol_result.is_some() {
        return symbol_result;
    }

    // For dotted names, try namespace-aware declaration lookup before variant stripping.
    // This ensures that qualified names like "ParcelableWithNested.Status.OK"
    // are resolved with full namespace context rather than being stripped to
    // shorter variants that may lose parent type information.
    if name.contains('.') {
        if let Some(lookup_decl) = lookup_decl_from_name(name, Namespace::AIDL) {
            if let Some(expr) = lookup_name_from_decl(&lookup_decl.decl, &lookup_decl) {
                return Some(expr);
            }
        }
    }

    // Try alternative name formats for cross-references
    let alternative_formats = generate_name_variants(name);
    for variant in alternative_formats {
        let variant_result = SYMBOL_TABLE.with(|table| {
            table
                .borrow()
                .get(&variant)
                .map(|symbol| symbol.value.clone())
        });
        if variant_result.is_some() {
            return variant_result;
        }
    }

    // Fallback to original resolution
    if let Some(lookup_decl) = lookup_decl_from_name(name, Namespace::AIDL) {
        return lookup_name_from_decl(&lookup_decl.decl, &lookup_decl);
    }

    None
}

// Generate possible name variants for flexible resolution
fn generate_name_variants(name: &str) -> Vec<String> {
    let mut variants = Vec::new();

    // Handle dot notation: "A.B.C" -> ["A.B.C", "B.C", "C"]
    // Try progressively shorter prefixes to find the best qualified match
    if name.contains('.') {
        let parts: Vec<&str> = name.split('.').collect();
        for i in 0..parts.len() {
            variants.push(parts[i..].join("."));
        }
    } else {
        // For simple names, try with current namespace context
        let current_ns = current_namespace().to_string(crate::Namespace::AIDL);

        if !current_ns.is_empty() {
            variants.push(format!("{}.{}", current_ns, name));
        }
        variants.push(name.to_string());
    }

    variants
}

#[derive(Debug)]
pub struct Document {
    pub package: Option<String>,
    pub imports: HashMap<String, String>,
    pub decls: Vec<Declaration>,
}

impl Document {
    fn new() -> Self {
        Self {
            package: None,
            imports: HashMap::new(),
            decls: Vec::new(),
        }
    }
}

#[derive(Debug, Default, Clone)]
pub struct VariableDecl {
    pub constant: bool,
    pub annotation_list: Vec<Annotation>,
    pub r#type: Type,
    pub identifier: String,
    pub const_expr: Option<ConstExpr>,
}

impl VariableDecl {
    pub fn identifier(&self) -> String {
        self.identifier.to_owned()
    }

    pub fn const_identifier(&self) -> String {
        self.identifier.to_uppercase()
    }

    pub fn union_identifier(&self) -> String {
        self.identifier.to_case(Case::UpperCamel)
    }

    pub fn member_init(&self) -> String {
        "Default::default()".into()
    }
}

#[derive(Debug, Default, Clone)]
pub struct InterfaceDecl {
    pub namespace: Namespace,
    pub annotation_list: Vec<Annotation>,
    pub oneway: bool,
    pub name: String,
    pub name_span: Option<(usize, usize)>,
    pub method_list: Vec<MethodDecl>,
    pub constant_list: Vec<VariableDecl>,
    pub members: Vec<Declaration>,
}

impl InterfaceDecl {
    pub fn pre_process(&mut self) {
        for decl in &mut self.constant_list {
            decl.const_expr = decl
                .const_expr
                .as_ref()
                .map(|expr| expr.calculate().unwrap_or_else(|_| expr.clone()));
        }
    }
}

#[derive(Debug, Default, Clone)]
pub struct ParcelableDecl {
    pub annotation_list: Vec<Annotation>,
    pub namespace: Namespace,
    pub name: String,
    pub type_params: Vec<String>,
    pub cpp_header: String,
    pub members: Vec<Declaration>,
    // pub name_dict: Option<HashMap<String, ConstExpr>>,
}

impl ParcelableDecl {
    pub fn pre_process(&mut self) {
        for decl in &mut self.members {
            if let Declaration::Variable(decl) = decl {
                decl.const_expr = decl
                    .const_expr
                    .as_ref()
                    .map(|expr| expr.calculate().unwrap_or_else(|_| expr.clone()));
            }
        }
    }
}

#[derive(Debug, Default, Clone)]
pub enum Direction {
    #[default]
    None,
    In,
    Out,
    Inout,
}

#[derive(Debug, Default, Clone)]
pub struct Arg {
    pub direction: Direction,
    pub direction_span: Option<(usize, usize)>,
    pub r#type: Type,
    pub identifier: String,
}

impl Arg {
    pub fn to_generator(&self) -> Result<type_generator::TypeGenerator, crate::error::AidlError> {
        let generator = type_generator::TypeGenerator::new_with_type(&self.r#type)?;

        Ok(generator
            .direction_at(&self.direction, self.direction_span)?
            .identifier(&self.identifier))
    }

    // fn arg_identifier(&self) -> String {
    //     format!("_arg_{}", self.identifier)
    // }

    // pub fn to_string(&self, is_nullable: bool) -> (String, String, String, String) {
    //     let param = self.arg_identifier();
    //     let mut type_cast = self.r#type.type_cast();
    //     let type_cloned = type_cast.clone();
    //     type_cast.set_fn_nullable(is_nullable);
    //     let def_arg = type_cast.fn_def_arg(&self.direction);
    //     let arg = format!("{}: {}",
    //         param.clone(), def_arg);
    //     (param, arg, def_arg, type_cloned.return_type())
    // }

    pub fn is_mutable(&self) -> bool {
        match self.direction {
            Direction::Inout | Direction::Out => true,
            Direction::In => false,
            _ => false,
        }
    }
}

#[derive(Debug, Default, Clone)]
pub struct MethodDecl {
    pub annotation_list: Vec<Annotation>,
    pub oneway: bool,
    pub r#type: Type,
    pub identifier: String,
    pub identifier_span: Option<(usize, usize)>,
    pub arg_list: Vec<Arg>,
    pub intvalue: Option<i64>,
    pub intvalue_span: Option<(usize, usize)>,
}

#[derive(Debug, Clone)]
pub enum Declaration {
    Parcelable(ParcelableDecl),
    Interface(InterfaceDecl),
    Enum(EnumDecl),
    Union(UnionDecl),
    Variable(VariableDecl),
}

impl Declaration {
    pub fn is_variable(&self) -> Option<&VariableDecl> {
        if let Declaration::Variable(decl) = self {
            Some(decl)
        } else {
            None
        }
    }

    pub fn namespace(&self) -> &Namespace {
        match self {
            Declaration::Parcelable(decl) => &decl.namespace,
            Declaration::Interface(decl) => &decl.namespace,
            Declaration::Enum(decl) => &decl.namespace,
            Declaration::Union(decl) => &decl.namespace,
            _ => unreachable!(),
        }
    }

    pub fn set_namespace(&mut self, namespace: Namespace) {
        match self {
            Declaration::Parcelable(decl) => decl.namespace = namespace,
            Declaration::Interface(decl) => decl.namespace = namespace,
            Declaration::Enum(decl) => decl.namespace = namespace,
            Declaration::Union(decl) => decl.namespace = namespace,
            _ => unreachable!(),
        }
    }

    pub fn name(&self) -> &str {
        match self {
            Declaration::Parcelable(decl) => &decl.name,
            Declaration::Interface(decl) => &decl.name,
            Declaration::Enum(decl) => &decl.name,
            Declaration::Union(decl) => &decl.name,
            _ => unreachable!(),
        }
    }

    pub fn members_mut(&mut self) -> &mut Vec<Declaration> {
        match self {
            Declaration::Parcelable(decl) => &mut decl.members,
            Declaration::Interface(decl) => &mut decl.members,
            Declaration::Enum(decl) => &mut decl.members,
            Declaration::Union(decl) => &mut decl.members,
            _ => unreachable!(),
        }
    }
}

#[derive(Debug, Clone)]
pub struct Parameter {
    identifier: String,
    const_expr: ConstExpr,
}

#[derive(Debug, Default, Clone)]
pub struct Annotation {
    pub annotation: String,
    pub const_expr: Option<ConstExpr>,
    pub parameter_list: Vec<Parameter>,
    pub annotation_span: Option<(usize, usize)>,
}

#[derive(Debug, Clone)]
pub enum Generic {
    Type1 {
        type_args1: Vec<Type>,
        non_array_type: NonArrayType,
        type_args2: Vec<Type>,
    },
    Type2 {
        non_array_type: NonArrayType,
        type_args: Vec<Type>,
    },
    Type3 {
        type_args: Vec<Type>,
    },
}

// fn generic_type_args_to_string(args: &[Type]) -> String {
//     let mut args_str = String::new();

//     args.iter().for_each(|t| {
//         let mut cast = t.type_cast();
//         cast.set_generic(true);

//         args_str.push_str(", ");
//         args_str.push_str(&cast.member_type());
//     });

//     args_str[2..].into()
// }

impl Generic {
    pub fn to_value_type(&self) -> Result<ValueType, crate::error::AidlError> {
        let generator = match self {
            Generic::Type1 {
                type_args1,
                non_array_type: _,
                type_args2: _,
            } => type_generator::TypeGenerator::new_with_type(&type_args1[0])?,
            Generic::Type2 {
                non_array_type,
                type_args: _,
            } => type_generator::TypeGenerator::new(non_array_type)?,
            Generic::Type3 { type_args } => {
                type_generator::TypeGenerator::new_with_type(&type_args[0])?
            }
        };

        Ok(generator.value_type)
    }
}

#[derive(Debug, Default, Clone)]
pub struct NonArrayType {
    pub name: String,
    pub generic: Option<Box<Generic>>,
    pub name_span: Option<(usize, usize)>,
}

#[derive(Debug, Default, Clone)]
pub struct ArrayType {
    pub const_expr: Option<ConstExpr>,
}

#[derive(Debug, Default, Clone)]
pub struct Type {
    pub annotation_list: Vec<Annotation>,
    pub non_array_type: NonArrayType,
    pub array_types: Vec<ArrayType>,
}

impl Type {
    pub fn to_generator(&self) -> Result<type_generator::TypeGenerator, crate::error::AidlError> {
        type_generator::TypeGenerator::new_with_type(self)
    }
}

#[derive(PartialEq)]
pub enum AnnotationType {
    IsNullable,
    JavaOnly,
    RustDerive,
    VintfStability,
}

pub fn check_annotation_list(
    annotation_list: &Vec<Annotation>,
    query_type: AnnotationType,
) -> (bool, String) {
    for annotation in annotation_list {
        match query_type {
            AnnotationType::VintfStability if annotation.annotation == "@VintfStability" => {
                return (true, "".to_owned())
            }
            AnnotationType::IsNullable if annotation.annotation == "@nullable" => {
                return (true, "".to_owned())
            }
            AnnotationType::JavaOnly if annotation.annotation.starts_with("@JavaOnly") => {
                return (true, "".to_owned())
            }
            AnnotationType::RustDerive if annotation.annotation == "@RustDerive" => {
                let mut derives = Vec::new();

                for param in &annotation.parameter_list {
                    if param.const_expr.to_bool().unwrap_or(false) {
                        derives.push(param.identifier.to_owned())
                    }
                }

                return (true, derives.join(","));
            }
            _ => {}
        }
    }

    (false, "".to_owned())
}

pub fn get_descriptor_from_annotation_list(annotation_list: &Vec<Annotation>) -> Option<String> {
    for annotation in annotation_list {
        if annotation.annotation == "@Descriptor" {
            for param in &annotation.parameter_list {
                if param.identifier == "value" {
                    return Some(param.const_expr.to_value_string());
                }
            }
        }
    }

    None
}

pub fn get_backing_type(
    annotation_list: &Vec<Annotation>,
    name_span: Option<(usize, usize)>,
) -> Result<type_generator::TypeGenerator, crate::error::AidlError> {
    // parse "@Backing(type="byte")"
    for annotation in annotation_list {
        if annotation.annotation == "@Backing" {
            for param in &annotation.parameter_list {
                if param.identifier == "type" {
                    return type_generator::TypeGenerator::new(&NonArrayType {
                        // The cstr is enclosed in quotes.
                        name: param.const_expr.to_value_string().trim_matches('"').into(),
                        generic: None,
                        name_span,
                    });
                }
            }
        }
    }

    type_generator::TypeGenerator::new(&NonArrayType {
        // The cstr is enclosed in quotes.
        name: "byte".into(),
        generic: None,
        name_span: None,
    })
}

fn parse_unary(mut pairs: pest::iterators::Pairs<Rule>) -> Result<ConstExpr, AidlError> {
    let operator = pairs.next().unwrap().as_str().to_owned();
    let factor = parse_factor(pairs.next().unwrap().into_inner().next().unwrap())?;
    Ok(ConstExpr::new_unary(&operator, factor))
}

fn parse_intvalue(arg_value: &str, span: (usize, usize)) -> Result<ConstExpr, AidlError> {
    let mut is_u8 = false;
    let mut is_long = false;

    let (value, radix) = if arg_value.starts_with("0x") || arg_value.starts_with("0X") {
        (&arg_value[2..], 16)
    } else {
        (arg_value, 10)
    };

    let value = if value.ends_with('l') || value.ends_with('L') {
        is_long = true;
        &value[..value.len() - 1]
    } else if let Some(stripped) = value.strip_suffix("u8") {
        is_u8 = true;
        stripped
    } else {
        value
    };

    if radix == 16 {
        if is_u8 {
            let parsed_value = u8::from_str_radix(value, radix).map_err(|err| {
                make_parse_error(
                    format!("invalid u8 hex literal '{arg_value}': {err}"),
                    span.0,
                    span.1,
                )
            })?;
            Ok(ConstExpr::new(ValueType::Byte(parsed_value as _)))
        } else if !is_long {
            if let Ok(parsed_value) = u32::from_str_radix(value, radix) {
                Ok(ConstExpr::new(ValueType::Int32(parsed_value as i32 as _)))
            } else {
                let parsed_value = u64::from_str_radix(value, radix).map_err(|err| {
                    make_parse_error(
                        format!("invalid hex literal '{arg_value}': {err}"),
                        span.0,
                        span.1,
                    )
                })?;
                Ok(ConstExpr::new(ValueType::Int64(parsed_value as i64 as _)))
            }
        } else {
            let parsed_value = u64::from_str_radix(value, radix).map_err(|err| {
                make_parse_error(
                    format!("invalid hex literal '{arg_value}': {err}"),
                    span.0,
                    span.1,
                )
            })?;
            Ok(ConstExpr::new(ValueType::Int64(parsed_value as i64 as _)))
        }
    } else {
        let parsed_value = i64::from_str_radix(value, radix).map_err(|err| {
            make_parse_error(
                format!("invalid integer literal '{arg_value}': {err}"),
                span.0,
                span.1,
            )
        })?;
        if is_u8 {
            if parsed_value > u8::MAX.into() || parsed_value < 0 {
                return Err(make_parse_error(
                    format!("u8 literal overflow: {parsed_value} is out of range (0..=255)"),
                    span.0,
                    span.1,
                ));
            }
            Ok(ConstExpr::new(ValueType::Byte(parsed_value as i8 as _)))
        } else if is_long {
            Ok(ConstExpr::new(ValueType::Int64(parsed_value as _)))
        } else if parsed_value <= i8::MAX.into() && parsed_value >= i8::MIN.into() {
            Ok(ConstExpr::new(ValueType::Byte(parsed_value as i8 as _)))
        } else if parsed_value <= i32::MAX.into() && parsed_value >= i32::MIN.into() {
            Ok(ConstExpr::new(ValueType::Int32(parsed_value as i32 as _)))
        } else {
            Ok(ConstExpr::new(ValueType::Int64(parsed_value as _)))
        }
    }
}

fn parse_value(pair: pest::iterators::Pair<Rule>) -> Result<ConstExpr, AidlError> {
    match pair.as_rule() {
        Rule::qualified_name => Ok(ConstExpr::new(ValueType::Name(pair.as_str().into()))),
        Rule::HEXVALUE | Rule::INTVALUE => {
            let span = pair.as_span();
            parse_intvalue(pair.as_str(), (span.start(), span.end()))
        }
        Rule::FLOATVALUE => {
            let span = pair.as_span();
            let value = pair.as_str();
            let value = if let Some(stripped) = value.strip_suffix('f') {
                stripped
            } else {
                value
            };
            let f = value.parse::<f64>().map_err(|_| {
                make_parse_error(
                    format!("invalid float literal: {}", pair.as_str()),
                    span.start(),
                    span.end(),
                )
            })?;
            Ok(ConstExpr::new(ValueType::Double(f as _)))
        }
        Rule::TRUE_LITERAL => Ok(ConstExpr::new(ValueType::Bool(true))),
        Rule::FALSE_LITERAL => Ok(ConstExpr::new(ValueType::Bool(false))),
        _ => unreachable!("Unexpected rule in parse_value(): {}", pair),
    }
}

fn parse_factor(pair: pest::iterators::Pair<Rule>) -> Result<ConstExpr, AidlError> {
    // println!("parse_factor {:?}", pair);
    match pair.as_rule() {
        Rule::expression => parse_expression(pair.clone().into_inner()),
        Rule::unary => parse_unary(pair.into_inner()),
        Rule::value => parse_value(pair.into_inner().next().unwrap()),
        _ => unreachable!("Unexpected rule in parse_factor(): {}", pair),
    }
}

fn parse_expression_term(pair: pest::iterators::Pair<Rule>) -> Result<ConstExpr, AidlError> {
    match pair.as_rule() {
        Rule::equality
        | Rule::comparison
        | Rule::bitwise_or
        | Rule::bitwise_xor
        | Rule::bitwise_and
        | Rule::shift
        | Rule::arith
        | Rule::logical_or
        | Rule::logical_and => parse_expression(pair.clone().into_inner()),
        Rule::factor => parse_factor(pair.into_inner().next().unwrap()),
        _ => unreachable!("Unexpected rule in Rule::parse_expression_into: {}", pair),
    }
}

fn parse_expression(mut pairs: pest::iterators::Pairs<Rule>) -> Result<ConstExpr, AidlError> {
    let mut lhs = parse_expression_term(pairs.next().unwrap())?;

    while let Some(pair) = pairs.next() {
        let op = pair.as_str().to_owned();
        let rhs = parse_expression_term(pairs.next().unwrap())?;

        lhs = ConstExpr::new_expr(lhs, &op, rhs)
    }

    Ok(lhs)
}

fn parse_string_term(pair: pest::iterators::Pair<Rule>) -> ConstExpr {
    match pair.as_rule() {
        Rule::C_STR => {
            let string = pair.as_str();
            ConstExpr::new(ValueType::String(string[1..string.len() - 1].into()))
        }
        Rule::qualified_name => ConstExpr::new(ValueType::Name(pair.as_str().into())),
        _ => unreachable!("Unexpected rule in Rule::parse_string_term: {}", pair),
    }
}

fn parse_string_expr(pairs: pest::iterators::Pairs<Rule>) -> Result<ConstExpr, AidlError> {
    let mut expr: Option<ConstExpr> = None;

    for pair in pairs {
        match pair.as_rule() {
            Rule::string_term => {
                let term = parse_string_term(pair.into_inner().next().unwrap());
                expr = match expr {
                    Some(expr) => Some(ConstExpr::new_expr(expr, "+", term)),
                    None => Some(term),
                }
            }
            _ => unreachable!("Unexpected rule in Rule::parse_string_expr: {}", pair),
        }
    }

    Ok(expr.expect("internal: empty string_expr"))
}

fn parse_const_expr(pair: pest::iterators::Pair<Rule>) -> Result<ConstExpr, AidlError> {
    match pair.as_rule() {
        Rule::constant_value_list => {
            let mut value_list = Vec::new();
            for pair in pair.into_inner() {
                match pair.as_rule() {
                    Rule::const_expr => {
                        value_list.push(parse_const_expr(pair.into_inner().next().unwrap())?);
                    }
                    _ => unreachable!("Unexpected rule in Rule::constant_value_list: {}", pair),
                }
            }
            Ok(ConstExpr::new(ValueType::Array(value_list)))
        }

        Rule::CHARVALUE => {
            let mut found = false;
            let mut has_backslash = false;
            for ch in pair.as_str().chars() {
                if !found && ch == '\'' {
                    found = true;
                } else if found {
                    if !has_backslash && ch == '\\' {
                        has_backslash = true;
                    } else {
                        return Ok(ConstExpr::new(ValueType::Char(ch)));
                    }
                }
            }
            unreachable!()
        }

        Rule::expression => parse_expression(pair.clone().into_inner()),

        Rule::string_expr => parse_string_expr(pair.into_inner()),

        _ => unreachable!("Unexpected rule in parse_const_expr(): {}", pair),
    }
}

fn parse_parameter(pairs: pest::iterators::Pairs<Rule>) -> Result<Parameter, AidlError> {
    let mut parameter = Parameter {
        identifier: "".to_string(),
        const_expr: ConstExpr::default(),
    };

    for pair in pairs {
        match pair.as_rule() {
            Rule::identifier => {
                parameter.identifier = pair.as_str().into();
            }
            Rule::const_expr => {
                parameter.const_expr = parse_const_expr(pair.into_inner().next().unwrap())?;
            }
            _ => unreachable!("Unexpected rule in parse_parameter(): {}", pair),
        }
    }

    Ok(parameter)
}

fn parse_parameter_list(pairs: pest::iterators::Pairs<Rule>) -> Result<Vec<Parameter>, AidlError> {
    let mut list = Vec::new();
    for pair in pairs {
        list.push(parse_parameter(pair.into_inner())?);
    }

    Ok(list)
}

fn parse_annotation(pairs: pest::iterators::Pairs<Rule>) -> Result<Annotation, AidlError> {
    let mut annotation = Annotation::default();
    for pair in pairs {
        match pair.as_rule() {
            Rule::ANNOTATION => {
                let span = pair.as_span();
                annotation.annotation = pair.as_str().into();
                annotation.annotation_span = Some((span.start(), span.end()));
            }

            Rule::const_expr => {
                annotation.const_expr = Some(parse_const_expr(pair.into_inner().next().unwrap())?);
            }

            Rule::parameter_list => {
                annotation.parameter_list = parse_parameter_list(pair.into_inner())?;
            }

            _ => unreachable!("Unexpected rule in parse_annotation(): {}", pair),
        }
    }

    Ok(annotation)
}

fn parse_annotation_list(
    pairs: pest::iterators::Pairs<Rule>,
) -> Result<Vec<Annotation>, AidlError> {
    let mut annotation_list = Vec::new();
    for pair in pairs {
        annotation_list.push(parse_annotation(pair.into_inner())?);
    }

    Ok(annotation_list)
}

fn parse_type_args(pairs: pest::iterators::Pairs<Rule>) -> Result<Vec<Type>, AidlError> {
    let mut res = Vec::new();

    for pair in pairs {
        match pair.as_rule() {
            Rule::r#type => res.push(parse_type(pair.into_inner())?),
            _ => unreachable!("Unexpected rule in parse_type_args(): {}", pair),
        }
    }

    Ok(res)
}

fn parse_non_array_type(pairs: pest::iterators::Pairs<Rule>) -> Result<NonArrayType, AidlError> {
    let mut non_array_type = NonArrayType::default();

    for pair in pairs {
        match pair.as_rule() {
            Rule::qualified_name => {
                let span = pair.as_span();
                non_array_type.name = pair.as_str().into();
                non_array_type.name_span = Some((span.start(), span.end()));
            }
            Rule::generic_type1 => {
                let mut pairs = pair.into_inner();
                let generic = Generic::Type1 {
                    type_args1: parse_type_args(pairs.next().unwrap().into_inner())?,
                    non_array_type: parse_non_array_type(pairs.next().unwrap().into_inner())?,
                    type_args2: parse_type_args(pairs.next().unwrap().into_inner())?,
                };

                non_array_type.generic = Some(Box::new(generic));
            }

            Rule::generic_type2 => {
                let mut pairs = pair.into_inner();
                let generic = Generic::Type2 {
                    non_array_type: parse_non_array_type(pairs.next().unwrap().into_inner())?,
                    type_args: parse_type_args(pairs.next().unwrap().into_inner())?,
                };

                non_array_type.generic = Some(Box::new(generic));
            }
            Rule::generic_type3 => {
                let mut pairs = pair.into_inner();
                let generic = Generic::Type3 {
                    type_args: parse_type_args(pairs.next().unwrap().into_inner())?,
                };

                non_array_type.generic = Some(Box::new(generic));
            }
            _ => {
                unreachable!();
            }
        }
    }

    Ok(non_array_type)
}

fn parse_array_type(pairs: pest::iterators::Pairs<Rule>) -> Result<ArrayType, AidlError> {
    let mut array_type = ArrayType::default();

    for pair in pairs {
        match pair.as_rule() {
            Rule::const_expr => {
                array_type.const_expr = Some(parse_const_expr(pair.into_inner().next().unwrap())?);
            }
            _ => unreachable!("Unexpected rule in parse_array_type(): {}", pair),
        }
    }

    Ok(array_type)
}

fn parse_type(pairs: pest::iterators::Pairs<Rule>) -> Result<Type, AidlError> {
    let mut r#type = Type::default();

    for pair in pairs {
        match pair.as_rule() {
            Rule::annotation_list => {
                r#type.annotation_list = parse_annotation_list(pair.into_inner())?;
            }
            Rule::non_array_type => {
                r#type.non_array_type = parse_non_array_type(pair.into_inner())?;
            }
            Rule::array_type => {
                r#type
                    .array_types
                    .push(parse_array_type(pair.into_inner())?);
            }
            _ => {
                unreachable!("Unexpected rule in parse_type(): {}", pair);
            }
        }
    }

    Ok(r#type)
}

fn parse_variable_decl(
    pairs: pest::iterators::Pairs<Rule>,
    constant: bool,
) -> Result<VariableDecl, AidlError> {
    let mut decl = VariableDecl {
        constant,
        ..Default::default()
    };

    for pair in pairs {
        match pair.as_rule() {
            Rule::annotation_list => {
                decl.annotation_list = parse_annotation_list(pair.into_inner())?;
            }
            Rule::r#type => {
                decl.r#type = parse_type(pair.into_inner())?;
            }
            Rule::identifier => {
                decl.identifier = pair.as_str().into();
            }
            Rule::const_expr => match pair.into_inner().next() {
                Some(pair) => decl.const_expr = Some(parse_const_expr(pair)?),
                None => decl.const_expr = None,
            },
            _ => unreachable!(
                "Unexpected rule in parse_variable_decl(): {}\t{}",
                pair,
                pair.as_str()
            ),
        }
    }

    Ok(decl)
}

fn parse_arg(pairs: pest::iterators::Pairs<Rule>) -> Result<Arg, AidlError> {
    let mut arg = Arg::default();

    for pair in pairs {
        match pair.as_rule() {
            Rule::direction => {
                let span = pair.as_span();
                arg.direction = match pair.as_str() {
                    "in" => Direction::In,
                    "out" => Direction::Out,
                    "inout" => Direction::Inout,
                    _ => {
                        return Err(make_parse_error(
                            format!("unsupported direction: {}", pair.as_str()),
                            span.start(),
                            span.end(),
                        ));
                    }
                };
                arg.direction_span = Some((span.start(), span.end()));
            }
            Rule::r#type => {
                arg.r#type = parse_type(pair.into_inner())?;
            }
            Rule::identifier => {
                arg.identifier = pair.as_str().into();
            }
            _ => unreachable!("Unexpected rule in parse_arg(): {}", pair),
        }
    }

    Ok(arg)
}

fn parse_method_decl(pairs: pest::iterators::Pairs<Rule>) -> Result<MethodDecl, AidlError> {
    let mut decl = MethodDecl::default();

    for pair in pairs {
        match pair.as_rule() {
            Rule::annotation_list => {
                decl.annotation_list = parse_annotation_list(pair.into_inner())?;
            }
            Rule::ONEWAY => {
                decl.oneway = true;
            }
            Rule::r#type => {
                decl.r#type = parse_type(pair.into_inner())?;
            }
            Rule::identifier => {
                let span = pair.as_span();
                decl.identifier = pair.as_str().into();
                decl.identifier_span = Some((span.start(), span.end()));
            }
            Rule::arg_list => {
                for pair in pair.into_inner() {
                    match pair.as_rule() {
                        Rule::arg => {
                            decl.arg_list.push(parse_arg(pair.into_inner())?);
                        }
                        _ => unreachable!(
                            "Unexpected rule in parse_method_decl(): {}, \"{}\"",
                            pair,
                            pair.as_str()
                        ),
                    }
                }
            }
            Rule::INTVALUE => {
                let span = pair.as_span();
                let expr = parse_intvalue(pair.as_str(), (span.start(), span.end()))?
                    .calculate()
                    .map_err(|e| make_parse_error(e.message, span.start(), span.end()))?;
                decl.intvalue = Some(match expr.value {
                    ValueType::Byte(v) => v as _,
                    ValueType::Int32(v) => v as _,
                    ValueType::Int64(v) => v,
                    _ => unreachable!(
                        "Unexpected Expression in parse_method_decl(): {}, \"{}\"",
                        pair,
                        pair.as_str()
                    ),
                });
                decl.intvalue_span = Some((span.start(), span.end()));
            }
            _ => unreachable!(
                "Unexpected rule in parse_method_decl(): {}, \"{}\"",
                pair,
                pair.as_str()
            ),
        }
    }

    Ok(decl)
}

fn parse_interface_members(
    pairs: pest::iterators::Pairs<Rule>,
    interface: &mut InterfaceDecl,
) -> Result<(), AidlError> {
    for pair in pairs {
        match pair.as_rule() {
            Rule::method_decl => {
                interface
                    .method_list
                    .push(parse_method_decl(pair.into_inner())?);
            }

            Rule::constant_decl => {
                interface
                    .constant_list
                    .push(parse_variable_decl(pair.into_inner(), true)?);
            }

            Rule::interface_members => {
                parse_interface_members(pair.into_inner(), interface)?;
            }

            Rule::decl => {
                interface
                    .members
                    .append(&mut parse_decl(pair.into_inner())?);
            }

            _ => unreachable!("Unexpected rule in parse_interface_members(): {}", pair),
        }
    }
    Ok(())
}

fn parse_interface_decl(
    annotation_list: Vec<Annotation>,
    pairs: pest::iterators::Pairs<Rule>,
) -> Result<Declaration, AidlError> {
    let mut interface = InterfaceDecl {
        annotation_list,
        ..Default::default()
    };

    for pair in pairs {
        match pair.as_rule() {
            Rule::ONEWAY => {
                interface.oneway = true;
            }

            Rule::qualified_name => {
                let span = pair.as_span();
                interface.name = pair.as_str().into();
                interface.name_span = Some((span.start(), span.end()));
            }

            Rule::interface_members => {
                parse_interface_members(pair.into_inner(), &mut interface)?;
            }

            _ => unreachable!("Unexpected rule in parse_interface_decl(): {}", pair),
        }
    }

    Ok(Declaration::Interface(interface))
}

fn parse_parcelable_members(
    pairs: pest::iterators::Pairs<Rule>,
) -> Result<Vec<Declaration>, AidlError> {
    let mut res = Vec::new();

    for pair in pairs {
        match pair.as_rule() {
            Rule::variable_decl => {
                res.push(Declaration::Variable(parse_variable_decl(
                    pair.into_inner(),
                    false,
                )?));
            }
            Rule::constant_decl => {
                res.push(Declaration::Variable(parse_variable_decl(
                    pair.into_inner(),
                    true,
                )?));
            }
            Rule::decl => res.append(&mut parse_decl(pair.into_inner())?),
            _ => unreachable!("Unexpected rule in parse_parcelable_members(): {}", pair),
        }
    }

    Ok(res)
}

fn parse_optional_type_params(pairs: pest::iterators::Pairs<Rule>) -> Vec<String> {
    let mut res = Vec::new();

    for pair in pairs {
        match pair.as_rule() {
            Rule::identifier => res.push(pair.as_str().into()),
            _ => unreachable!("Unexpected rule in parse_optional_type_params(): {}", pair),
        }
    }

    res
}

fn parse_parcelable_decl(
    annotation_list: Vec<Annotation>,
    pairs: pest::iterators::Pairs<Rule>,
) -> Result<Declaration, AidlError> {
    let mut parcelable = ParcelableDecl {
        annotation_list,
        ..Default::default()
    };

    for pair in pairs {
        match pair.as_rule() {
            Rule::qualified_name => {
                parcelable.name = pair.as_str().into();
            }

            Rule::optional_type_params => {
                parcelable.type_params = parse_optional_type_params(pair.into_inner());
            }

            Rule::parcelable_members => {
                parcelable
                    .members
                    .append(&mut parse_parcelable_members(pair.into_inner())?);
            }

            Rule::C_STR => {
                parcelable.cpp_header = pair.as_str().into();
            }

            _ => unreachable!("Unexpected rule in parse_parcelable_decl(): {}", pair),
        }
    }

    Ok(Declaration::Parcelable(parcelable))
}

#[derive(Debug, Default, Clone)]
pub struct Enumerator {
    pub identifier: String,
    pub const_expr: Option<ConstExpr>,
}

#[derive(Debug, Default, Clone)]
pub struct EnumDecl {
    pub namespace: Namespace,
    pub annotation_list: Vec<Annotation>,
    pub name: String,
    pub name_span: Option<(usize, usize)>,
    pub enumerator_list: Vec<Enumerator>,
    pub members: Vec<Declaration>,
}

fn parse_enumerator(pairs: pest::iterators::Pairs<Rule>) -> Result<Enumerator, AidlError> {
    let mut res = Enumerator::default();

    for pair in pairs {
        match pair.as_rule() {
            Rule::identifier => {
                res.identifier = pair.as_str().into();
            }
            Rule::const_expr => {
                res.const_expr = Some(parse_const_expr(pair.into_inner().next().unwrap())?);
            }
            _ => unreachable!("Unexpected rule in parse_enumerator(): {}", pair),
        }
    }

    Ok(res)
}

fn parse_enum_decl(
    annotation_list: Vec<Annotation>,
    pairs: pest::iterators::Pairs<Rule>,
) -> Result<Declaration, AidlError> {
    let mut enum_decl = EnumDecl {
        annotation_list: annotation_list.clone(),
        ..Default::default()
    };

    for pair in pairs {
        match pair.as_rule() {
            Rule::qualified_name => {
                let span = pair.as_span();
                enum_decl.name = pair.as_str().into();
                enum_decl.name_span = Some((span.start(), span.end()));
            }
            Rule::enumerator => enum_decl
                .enumerator_list
                .push(parse_enumerator(pair.into_inner())?),
            _ => unreachable!("Unexpected rule in parse_enum_decl(): {}", pair),
        }
    }

    Ok(Declaration::Enum(enum_decl))
}

#[derive(Debug, Default, Clone)]
pub struct UnionDecl {
    pub namespace: Namespace,
    pub annotation_list: Vec<Annotation>,
    pub name: String,
    pub name_span: Option<(usize, usize)>,
    pub type_params: Vec<String>,
    pub members: Vec<Declaration>,
}

fn parse_union_decl(
    annotation_list: Vec<Annotation>,
    pairs: pest::iterators::Pairs<Rule>,
) -> Result<Declaration, AidlError> {
    let mut union_decl = UnionDecl {
        annotation_list,
        ..Default::default()
    };

    for pair in pairs {
        match pair.as_rule() {
            Rule::qualified_name => {
                let span = pair.as_span();
                union_decl.name = pair.as_str().into();
                union_decl.name_span = Some((span.start(), span.end()));
            }
            Rule::optional_type_params => {
                union_decl.type_params = parse_optional_type_params(pair.into_inner());
            }
            Rule::parcelable_members => {
                union_decl.members = parse_parcelable_members(pair.into_inner())?;
            }
            _ => unreachable!("Unexpected rule in parse_union_decl(): {}", pair),
        }
    }
    Ok(Declaration::Union(union_decl))
}

fn parse_decl(pairs: pest::iterators::Pairs<Rule>) -> Result<Vec<Declaration>, AidlError> {
    let mut annotation_list = Vec::new();
    let mut declarations = Vec::new();

    for pair in pairs {
        match pair.as_rule() {
            Rule::annotation_list => {
                annotation_list = parse_annotation_list(pair.into_inner())?;
            }
            Rule::interface_decl => {
                declarations.push(parse_interface_decl(
                    annotation_list.clone(),
                    pair.into_inner(),
                )?);
            }

            Rule::parcelable_decl => {
                declarations.push(parse_parcelable_decl(
                    annotation_list.clone(),
                    pair.into_inner(),
                )?);
            }
            Rule::enum_decl => {
                declarations.push(parse_enum_decl(annotation_list.clone(), pair.into_inner())?);
            }
            Rule::union_decl => {
                declarations.push(parse_union_decl(
                    annotation_list.clone(),
                    pair.into_inner(),
                )?);
            }

            _ => unreachable!("Unexpected rule in parse_decl(): {}", pair),
        };
    }

    Ok(declarations)
}

pub fn calculate_namespace(decl: &mut Declaration, mut namespace: Namespace) {
    if decl.is_variable().is_some() {
        return;
    }

    namespace.push(decl.name());

    decl.set_namespace(namespace.clone());

    DECLARATION_MAP.with(|hashmap| {
        hashmap.borrow_mut().insert(namespace.clone(), decl.clone());
    });

    for decl in decl.members_mut() {
        calculate_namespace(decl, namespace.clone());
    }
}

pub fn parse_document(ctx: &SourceContext) -> Result<Document, AidlError> {
    let _guard = SourceGuard::new(&ctx.filename, &ctx.source);
    let mut document = Document::new();

    match AIDLParser::parse(Rule::document, &ctx.source) {
        Ok(pairs) => {
            for pair in pairs {
                match pair.as_rule() {
                    Rule::package => {
                        document.package = Some(pair.into_inner().next().unwrap().as_str().into());
                    }

                    Rule::imports => {
                        for pair in pair.into_inner() {
                            let import = pair.as_str().to_string();
                            let key = match import.rfind('.') {
                                Some(idx) => &import[(idx + 1)..],
                                None => &import,
                            };
                            document.imports.insert(key.into(), import);
                        }
                    }

                    Rule::decl => {
                        document.decls.append(&mut parse_decl(pair.into_inner())?);
                    }

                    Rule::EOI => {}

                    _ => {
                        unreachable!("Unexpected rule in parse_document(): {}", pair)
                    }
                }
            }

            // println!("{:?}", document);
        }
        Err(err) => {
            return Err(pest_error_to_diagnostic(err, &ctx.filename, &ctx.source).into());
        }
    }

    let namespace = if let Some(ref package) = document.package {
        Namespace::new(package, Namespace::AIDL)
    } else {
        Namespace::default()
    };

    for decl in &mut document.decls {
        calculate_namespace(decl, namespace.clone());
    }

    Ok(document)
}

pub fn reset() {
    DECLARATION_MAP.with(|hashmap| {
        hashmap.borrow_mut().clear();
    });
    NAMESPACE_STACK.with(|stack| {
        stack.borrow_mut().clear();
    });
    DOCUMENT.with(|doc| {
        *doc.borrow_mut() = Document::new();
    });
    SYMBOL_TABLE.with(|table| {
        table.borrow_mut().clear();
    });
}

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

    #[test]
    fn test_parse_string_expr() -> Result<(), Box<dyn Error>> {
        let mut res =
            AIDLParser::parse(Rule::string_expr, r##""Hello" + " World""##).map_err(|err| {
                println!("{err}");
                err
            })?;

        let expr = parse_string_expr(res.next().unwrap().into_inner())?;
        assert_eq!(
            expr,
            ConstExpr::new_expr(
                ConstExpr::new(ValueType::String("Hello".into())),
                "+",
                ConstExpr::new(ValueType::String(" World".into()))
            )
        );

        Ok(())
    }

    #[test]
    fn test_parse_expression() -> Result<(), Box<dyn Error>> {
        let mut res =
            AIDLParser::parse(Rule::expression, r##"1 + -3 * 2 << 2 | 4"##).map_err(|err| {
                println!("{err}");
                err
            })?;

        let expr = parse_expression(res.next().unwrap().into_inner())?;
        // assert_eq!(
        //     expr.clone(),
        //     // Expression::Expr {
        //     //     as_str: "1 + -3 * 2 << 2 | 4".into(),
        //     //     lhs: Box::new(Expression::Expr {
        //     //         as_str: "1 + -3 * 2 << 2 | 4".into(),
        //     //         lhs: Box::new(Expression::Expr {
        //     //             as_str: "1 + -3 * 2 << 2 | 4".into(),
        //     //             lhs: Box::new(Expression::Int8(1)),
        //     //             operator: "+".to_string(),
        //     //             rhs: Box::new(Expression::Expr {
        //     //                 as_str: "1 + -3 * 2 << 2 | 4".into(),
        //     //                 lhs: Box::new(Expression::Unary {
        //     //                     operator: "-".to_string(),
        //     //                     expr: Box::new(Expression::Int8(3))
        //     //                 }),
        //     //                 operator: "*".to_string(),
        //     //                 rhs: Box::new(Expression::Int8(2))
        //     //             })
        //     //         }),
        //     //         operator: "<<".to_string(),
        //     //         rhs: Box::new(Expression::Int8(2))
        //     //     }),
        //     //     operator: "|".to_string(),
        //     //     rhs: Box::new(Expression::Int8(4))
        //     // },
        //     ConstExpr::default(),
        // );

        assert_eq!(
            expr.calculate().unwrap(),
            ConstExpr::new(ValueType::Int64(-20))
        );

        Ok(())
    }

    #[test]
    fn test_namespace_guard() {
        let _ns_1 = NamespaceGuard::new(&Namespace::new("1.1", Namespace::AIDL));
        {
            assert_eq!(current_namespace(), Namespace::new("1.1", Namespace::AIDL));
            let _ns_2 = NamespaceGuard::new(&Namespace::new("2.2", Namespace::AIDL));
            {
                assert_eq!(current_namespace(), Namespace::new("2.2", Namespace::AIDL));
                let _ns_3 = NamespaceGuard::new(&Namespace::new("3.3", Namespace::AIDL));
                assert_eq!(current_namespace(), Namespace::new("3.3", Namespace::AIDL));
            }
            assert_eq!(current_namespace(), Namespace::new("2.2", Namespace::AIDL));
        }
    }

    // 1.1n: thread-local state is cleared after SourceGuard is dropped
    #[test]
    fn test_source_guard_cleanup_on_drop() {
        {
            let _guard = SourceGuard::new("test.aidl", "source text");
            assert_eq!(current_source_name(), "test.aidl");
            assert_eq!(current_source_text(), "source text");
        }
        // After drop, thread-locals should be cleared
        assert_eq!(current_source_name(), "");
        assert_eq!(current_source_text(), "");
    }

    // 1.1o: thread-local state is cleared even when a panic occurs inside SourceGuard
    #[test]
    fn test_source_guard_cleanup_on_panic() {
        let result = std::panic::catch_unwind(|| {
            let _guard = SourceGuard::new("panic.aidl", "panic source");
            panic!("intentional panic to test cleanup");
        });
        assert!(result.is_err());
        assert_eq!(current_source_name(), "");
        assert_eq!(current_source_text(), "");
    }
}