aboutsummaryrefslogtreecommitdiff
path: root/aidl_unittest.cpp
blob: 98744c26430d17320bac56c57f7858ace24e8de5 (plain)
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
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
/*
 * Copyright (C) 2015, The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "aidl.h"

#include <android-base/format.h>
#include <android-base/stringprintf.h>
#include <gmock/gmock.h>
#include <gtest/gtest.h>

#include <map>
#include <memory>
#include <set>
#include <string>
#include <vector>

#include "aidl_checkapi.h"
#include "aidl_dumpapi.h"
#include "aidl_language.h"
#include "aidl_to_cpp.h"
#include "aidl_to_java.h"
#include "aidl_to_ndk.h"
#include "comments.h"
#include "logging.h"
#include "options.h"
#include "tests/fake_io_delegate.h"

using android::aidl::internals::parse_preprocessed_file;
using android::aidl::test::FakeIoDelegate;
using android::base::StringPrintf;
using std::map;
using std::set;
using std::string;
using std::unique_ptr;
using std::vector;
using testing::HasSubstr;
using testing::TestParamInfo;
using testing::internal::CaptureStderr;
using testing::internal::GetCapturedStderr;

namespace android {
namespace aidl {
namespace {

const char kExpectedDepFileContents[] =
R"(place/for/output/p/IFoo.java : \
  p/IFoo.aidl

p/IFoo.aidl :
)";

const char kExpectedNinjaDepFileContents[] =
R"(place/for/output/p/IFoo.java : \
  p/IFoo.aidl
)";

const char kExpectedParcelableDeclarationDepFileContents[] =
    R"( : \
  p/Foo.aidl

p/Foo.aidl :
)";

const char kExpectedStructuredParcelableDepFileContents[] =
    R"(place/for/output/p/Foo.java : \
  p/Foo.aidl

p/Foo.aidl :
)";

}  // namespace

class AidlTest : public ::testing::TestWithParam<Options::Language> {
 protected:
  AidlDefinedType* Parse(const string& path, const string& contents, AidlTypenames& typenames_,
                         Options::Language lang, AidlError* error = nullptr,
                         const vector<string> additional_arguments = {}) {
    io_delegate_.SetFileContents(path, contents);
    vector<string> args;
    args.emplace_back("aidl");
    args.emplace_back("--lang=" + to_string(lang));
    for (const string& s : additional_arguments) {
      args.emplace_back(s);
    }
    for (const string& f : preprocessed_files_) {
      args.emplace_back("--preprocessed=" + f);
    }
    for (const string& i : import_paths_) {
      args.emplace_back("--include=" + i);
    }
    args.emplace_back(path);
    Options options = Options::From(args);
    vector<string> imported_files;
    ImportResolver import_resolver{io_delegate_, path, import_paths_, {}};
    AidlError actual_error = ::android::aidl::internals::load_and_validate_aidl(
        path, options, io_delegate_, &typenames_, &imported_files);

    if (error != nullptr) {
      *error = actual_error;
    }

    if (actual_error != AidlError::OK) {
      return nullptr;
    }

    const auto& defined_types = typenames_.MainDocument().DefinedTypes();
    EXPECT_EQ(1ul, defined_types.size());

    return defined_types.front().get();
  }

  Options::Language GetLanguage() { return GetParam(); }

  FakeIoDelegate io_delegate_;
  vector<string> preprocessed_files_;
  set<string> import_paths_;
  AidlTypenames typenames_;
};

// Instantiate the AidlTest parameterized suite, calling all of the TEST_P
// tests with each of the supported languages as a parameter.
INSTANTIATE_TEST_SUITE_P(AidlTestSuite, AidlTest,
                         testing::Values(Options::Language::CPP, Options::Language::JAVA,
                                         Options::Language::NDK, Options::Language::RUST),
                         [](const testing::TestParamInfo<Options::Language>& info) {
                           return to_string(info.param);
                         });

TEST_P(AidlTest, AcceptMissingPackage) {
  EXPECT_NE(nullptr, Parse("IFoo.aidl", "interface IFoo { }", typenames_, GetLanguage()));
}

TEST_P(AidlTest, EndsInSingleLineComment) {
  EXPECT_NE(nullptr, Parse("IFoo.aidl", "interface IFoo { } // foo", typenames_, GetLanguage()));
}

TEST_P(AidlTest, InterfaceRequiresCorrectPath) {
  const string expected_stderr =
      "ERROR: a/Foo.aidl:1.11-21: IBar should be declared in a file called a/IBar.aidl\n";
  const std::string file_contents = "package a; interface IBar {}";
  CaptureStderr();
  EXPECT_EQ(nullptr, Parse("a/Foo.aidl", file_contents, typenames_, GetLanguage()));
  EXPECT_EQ(expected_stderr, GetCapturedStderr()) << file_contents;
}

TEST_P(AidlTest, ParcelableRequiresCorrectPath) {
  const string expected_stderr =
      "ERROR: a/Foo.aidl:1.11-21: Bar should be declared in a file called a/Bar.aidl\n";
  const std::string file_contents = "package a; interface Bar {}";
  CaptureStderr();
  EXPECT_EQ(nullptr, Parse("a/Foo.aidl", file_contents, typenames_, GetLanguage()));
  EXPECT_EQ(expected_stderr, GetCapturedStderr()) << file_contents;
}

TEST_P(AidlTest, UnstructuredParcelableRequiresCorrectPath) {
  const string expected_stderr =
      "ERROR: a/Foo.aidl:1.22-26: Bar should be declared in a file called a/Bar.aidl\n";
  const std::string file_contents = "package a; parcelable Bar cpp_header \"anything.h\";";
  CaptureStderr();
  EXPECT_EQ(nullptr, Parse("a/Foo.aidl", file_contents, typenames_, GetLanguage()));
  EXPECT_EQ(expected_stderr, GetCapturedStderr()) << file_contents;
}

TEST_P(AidlTest, EnumRequiresCorrectPath) {
  const string expected_stderr =
      "ERROR: a/Foo.aidl:1.16-20: Bar should be declared in a file called a/Bar.aidl\n";
  const std::string file_contents = "package a; enum Bar { A, }";
  CaptureStderr();
  EXPECT_EQ(nullptr, Parse("a/Foo.aidl", file_contents, typenames_, GetLanguage()));
  EXPECT_EQ(expected_stderr, GetCapturedStderr()) << file_contents;
}

TEST_P(AidlTest, RejectsArraysOfBinders) {
  import_paths_.emplace("");
  io_delegate_.SetFileContents("bar/IBar.aidl",
                               "package bar; interface IBar {}");
  const string path = "foo/IFoo.aidl";
  const string contents =
      "package foo;\n"
      "import bar.IBar;\n"
      "interface IFoo { void f(in IBar[] input); }";
  const string expected_stderr = "ERROR: foo/IFoo.aidl:3.27-32: Binder type cannot be an array\n";
  CaptureStderr();
  EXPECT_EQ(nullptr, Parse(path, contents, typenames_, GetLanguage()));
  EXPECT_EQ(expected_stderr, GetCapturedStderr());
}

TEST_P(AidlTest, SupportOnlyOutParameters) {
  const string interface_list = "package a; interface IBar { void f(out List<String> bar); }";
  EXPECT_NE(nullptr, Parse("a/IBar.aidl", interface_list, typenames_, GetLanguage()));
}

TEST_P(AidlTest, RejectOutParametersForIBinder) {
  const string interface_ibinder = "package a; interface IBaz { void f(out IBinder bar); }";
  const string expected_ibinder_stderr =
      "ERROR: a/IBaz.aidl:1.47-51: 'bar' can't be an out parameter because IBinder can only be an "
      "in parameter.\n";
  CaptureStderr();
  EXPECT_EQ(nullptr, Parse("a/IBaz.aidl", interface_ibinder, typenames_, GetLanguage()));
  EXPECT_EQ(expected_ibinder_stderr, GetCapturedStderr());
}

TEST_P(AidlTest, RejectsOutParametersInOnewayInterface) {
  const string oneway_interface = "package a; oneway interface IBar { void f(out int[] bar); }";
  const string expected_stderr =
      "ERROR: a/IBar.aidl:1.40-42: oneway method 'f' cannot have out parameters\n";
  CaptureStderr();
  EXPECT_EQ(nullptr, Parse("a/IBar.aidl", oneway_interface, typenames_, GetLanguage()));
  EXPECT_EQ(expected_stderr, GetCapturedStderr());
}

TEST_P(AidlTest, RejectsOutParametersInOnewayMethod) {
  const string oneway_method = "package a; interface IBar { oneway void f(out int[] bar); }";
  const string expected_stderr =
      "ERROR: a/IBar.aidl:1.40-42: oneway method 'f' cannot have out parameters\n";
  CaptureStderr();
  EXPECT_EQ(nullptr, Parse("a/IBar.aidl", oneway_method, typenames_, GetLanguage()));
  EXPECT_EQ(expected_stderr, GetCapturedStderr());
}

TEST_P(AidlTest, RejectsOnewayNonVoidReturn) {
  const string oneway_method = "package a; interface IFoo { oneway int f(); }";
  const string expected_stderr =
      "ERROR: a/IFoo.aidl:1.39-41: oneway method 'f' cannot return a value\n";
  CaptureStderr();
  EXPECT_EQ(nullptr, Parse("a/IFoo.aidl", oneway_method, typenames_, GetLanguage()));
  EXPECT_EQ(expected_stderr, GetCapturedStderr());
}

TEST_P(AidlTest, RejectsNullablePrimitive) {
  const string oneway_method = "package a; interface IFoo { @nullable int f(); }";
  const string expected_stderr =
      "ERROR: a/IFoo.aidl:1.38-42: Primitive type cannot get nullable annotation\n";
  CaptureStderr();
  EXPECT_EQ(nullptr, Parse("a/IFoo.aidl", oneway_method, typenames_, GetLanguage()));
  EXPECT_EQ(expected_stderr, GetCapturedStderr());
}

TEST_P(AidlTest, AcceptNullableList) {
  const string oneway_method = "package a; interface IFoo { @nullable List<String> f(); }";
  const string expected_stderr = "";
  CaptureStderr();
  EXPECT_NE(nullptr, Parse("a/IFoo.aidl", oneway_method, typenames_, GetLanguage()));
  EXPECT_EQ(expected_stderr, GetCapturedStderr());
}

TEST_P(AidlTest, RejectsDuplicatedArgumentNames) {
  const string method = "package a; interface IFoo { void f(int a, int a); }";
  const string expected_stderr =
      "ERROR: a/IFoo.aidl:1.33-35: method 'f' has duplicate argument name 'a'\n";
  CaptureStderr();
  EXPECT_EQ(nullptr, Parse("a/IFoo.aidl", method, typenames_, GetLanguage()));
  EXPECT_EQ(expected_stderr, GetCapturedStderr());
}

TEST_P(AidlTest, RejectsDuplicatedFieldNames) {
  const string method = "package a; parcelable Foo { int a; String a; }";
  const string expected_stderr = "ERROR: a/Foo.aidl:1.42-44: 'Foo' has duplicate field name 'a'\n";
  CaptureStderr();
  EXPECT_EQ(nullptr, Parse("a/Foo.aidl", method, typenames_, GetLanguage()));
  EXPECT_EQ(expected_stderr, GetCapturedStderr());
}

TEST_P(AidlTest, RejectsRepeatedAnnotations) {
  const string method = R"(@Hide @Hide parcelable Foo {})";
  const string expected_stderr =
      "ERROR: Foo.aidl:1.23-27: 'Hide' is repeated, but not allowed. Previous location: "
      "Foo.aidl:1.1-6\n";
  CaptureStderr();
  EXPECT_EQ(nullptr, Parse("Foo.aidl", method, typenames_, GetLanguage()));
  EXPECT_EQ(expected_stderr, GetCapturedStderr());
}

TEST_P(AidlTest, AcceptsEmptyParcelable) {
  CaptureStderr();
  EXPECT_NE(nullptr, Parse("Foo.aidl", "parcelable Foo {}", typenames_, GetLanguage()));
  EXPECT_EQ("", GetCapturedStderr());
}

TEST_P(AidlTest, RejectsDuplicatedAnnotationParams) {
  const string method = "package a; interface IFoo { @UnsupportedAppUsage(foo=1, foo=2)void f(); }";
  const string expected_stderr = "ERROR: a/IFoo.aidl:1.56-62: Trying to redefine parameter foo.\n";
  CaptureStderr();
  EXPECT_EQ(nullptr, Parse("a/IFoo.aidl", method, typenames_, GetLanguage()));
  EXPECT_EQ(expected_stderr, GetCapturedStderr());
}

TEST_P(AidlTest, RejectUnsupportedInterfaceAnnotations) {
  AidlError error;
  const string method = "package a; @nullable interface IFoo { int f(); }";
  CaptureStderr();
  EXPECT_EQ(nullptr, Parse("a/IFoo.aidl", method, typenames_, GetLanguage(), &error));
  EXPECT_THAT(GetCapturedStderr(), HasSubstr("@nullable is not available."));
  EXPECT_EQ(AidlError::BAD_TYPE, error);
}

TEST_P(AidlTest, RejectUnsupportedTypeAnnotations) {
  AidlError error;
  const string method = "package a; interface IFoo { @JavaOnlyStableParcelable int f(); }";
  CaptureStderr();
  EXPECT_EQ(nullptr, Parse("a/IFoo.aidl", method, typenames_, GetLanguage(), &error));
  EXPECT_THAT(GetCapturedStderr(), HasSubstr("@JavaOnlyStableParcelable is not available."));
  EXPECT_EQ(AidlError::BAD_TYPE, error);
}

TEST_P(AidlTest, RejectUnsupportedParcelableAnnotations) {
  AidlError error;
  const string method = "package a; @nullable parcelable IFoo cpp_header \"IFoo.h\";";
  CaptureStderr();
  EXPECT_EQ(nullptr, Parse("a/IFoo.aidl", method, typenames_, GetLanguage(), &error));
  EXPECT_THAT(GetCapturedStderr(), HasSubstr("@nullable is not available."));
  EXPECT_EQ(AidlError::BAD_TYPE, error);
}

TEST_P(AidlTest, RejectUnsupportedParcelableDefineAnnotations) {
  AidlError error;
  const string method = "package a; @nullable parcelable IFoo { String a; String b; }";
  CaptureStderr();
  EXPECT_EQ(nullptr, Parse("a/IFoo.aidl", method, typenames_, GetLanguage(), &error));
  EXPECT_THAT(GetCapturedStderr(), HasSubstr("@nullable is not available."));
  EXPECT_EQ(AidlError::BAD_TYPE, error);
}

TEST_P(AidlTest, ParsesNonNullableAnnotation) {
  auto parse_result =
      Parse("a/IFoo.aidl", "package a; interface IFoo { String f(); }", typenames_, GetLanguage());
  ASSERT_NE(nullptr, parse_result);
  const AidlInterface* interface = parse_result->AsInterface();
  ASSERT_NE(nullptr, interface);
  ASSERT_FALSE(interface->GetMethods().empty());
  EXPECT_FALSE(interface->GetMethods()[0]->GetType().IsNullable());
}

TEST_P(AidlTest, ParsesNullableAnnotation) {
  auto parse_result = Parse("a/IFoo.aidl", "package a; interface IFoo { @nullable String f(); }",
                            typenames_, GetLanguage());
  ASSERT_NE(nullptr, parse_result);
  const AidlInterface* interface = parse_result->AsInterface();
  ASSERT_NE(nullptr, interface);
  ASSERT_FALSE(interface->GetMethods().empty());
  EXPECT_TRUE(interface->GetMethods()[0]->GetType().IsNullable());
}

TEST_P(AidlTest, ParsesNonUtf8Annotations) {
  auto parse_result =
      Parse("a/IFoo.aidl", "package a; interface IFoo { String f(); }", typenames_, GetLanguage());
  ASSERT_NE(nullptr, parse_result);
  const AidlInterface* interface = parse_result->AsInterface();
  ASSERT_NE(nullptr, interface);
  ASSERT_FALSE(interface->GetMethods().empty());
  EXPECT_FALSE(interface->GetMethods()[0]->GetType().IsUtf8InCpp());
}

TEST_P(AidlTest, ParsesUtf8Annotations) {
  auto parse_result = Parse("a/IFoo.aidl", "package a; interface IFoo { @utf8InCpp String f(); }",
                            typenames_, GetLanguage());
  ASSERT_NE(nullptr, parse_result);
  const AidlInterface* interface = parse_result->AsInterface();
  ASSERT_NE(nullptr, interface);
  ASSERT_FALSE(interface->GetMethods().empty());
  EXPECT_TRUE(interface->GetMethods()[0]->GetType().IsUtf8InCpp());
}

TEST_P(AidlTest, VintfRequiresStructuredAndStability) {
  AidlError error;
  const string expected_stderr =
      "ERROR: IFoo.aidl:1.16-26: Must compile @VintfStability type w/ aidl_interface 'stability: "
      "\"vintf\"'\n"
      "ERROR: IFoo.aidl:1.16-26: Must compile @VintfStability type w/ aidl_interface "
      "--structured\n";
  CaptureStderr();
  ASSERT_EQ(nullptr, Parse("IFoo.aidl", "@VintfStability interface IFoo {}", typenames_,
                           GetLanguage(), &error));
  EXPECT_EQ(expected_stderr, GetCapturedStderr());
  ASSERT_EQ(AidlError::NOT_STRUCTURED, error);
}

TEST_P(AidlTest, VintfRequiresStructured) {
  AidlError error;
  const string expected_stderr =
      "ERROR: IFoo.aidl:1.16-26: Must compile @VintfStability type w/ aidl_interface "
      "--structured\n";
  CaptureStderr();
  ASSERT_EQ(nullptr, Parse("IFoo.aidl", "@VintfStability interface IFoo {}", typenames_,
                           GetLanguage(), &error, {"--stability", "vintf"}));
  EXPECT_EQ(expected_stderr, GetCapturedStderr());
  ASSERT_EQ(AidlError::NOT_STRUCTURED, error);
}

TEST_P(AidlTest, VintfRequiresSpecifiedStability) {
  AidlError error;
  const string expected_stderr =
      "ERROR: IFoo.aidl:1.16-26: Must compile @VintfStability type w/ aidl_interface 'stability: "
      "\"vintf\"'\n";
  CaptureStderr();
  ASSERT_EQ(nullptr, Parse("IFoo.aidl", "@VintfStability interface IFoo {}", typenames_,
                           GetLanguage(), &error, {"--structured"}));
  EXPECT_EQ(expected_stderr, GetCapturedStderr());
  ASSERT_EQ(AidlError::NOT_STRUCTURED, error);
}

TEST_P(AidlTest, ParsesStabilityAnnotations) {
  AidlError error;
  auto parse_result = Parse("IFoo.aidl", "@VintfStability interface IFoo {}", typenames_,
                            GetLanguage(), &error, {"--structured", "--stability", "vintf"});
  ASSERT_EQ(AidlError::OK, error);
  ASSERT_NE(nullptr, parse_result);
  const AidlInterface* interface = parse_result->AsInterface();
  ASSERT_NE(nullptr, interface);
  ASSERT_TRUE(interface->IsVintfStability());
}

TEST_F(AidlTest, ParsesJavaOnlyStableParcelable) {
  Options java_options = Options::From("aidl -o out --structured a/Foo.aidl");
  Options cpp_options = Options::From("aidl --lang=cpp -o out -h out/include a/Foo.aidl");
  Options cpp_structured_options =
      Options::From("aidl --lang=cpp --structured -o out -h out/include a/Foo.aidl");
  Options rust_options = Options::From("aidl --lang=rust -o out --structured a/Foo.aidl");
  io_delegate_.SetFileContents(
      "a/Foo.aidl",
      StringPrintf("package a; @JavaOnlyStableParcelable parcelable Foo cpp_header \"Foo.h\" ;"));

  EXPECT_EQ(0, ::android::aidl::compile_aidl(java_options, io_delegate_));
  EXPECT_EQ(0, ::android::aidl::compile_aidl(cpp_options, io_delegate_));
  const string expected_stderr =
      "ERROR: a/Foo.aidl:1.48-52: Cannot declared parcelable in a --structured interface. "
      "Parcelable must be defined in AIDL directly.\n";
  CaptureStderr();
  EXPECT_NE(0, ::android::aidl::compile_aidl(cpp_structured_options, io_delegate_));
  EXPECT_EQ(expected_stderr, GetCapturedStderr());

  CaptureStderr();
  EXPECT_NE(0, ::android::aidl::compile_aidl(rust_options, io_delegate_));
  EXPECT_EQ(expected_stderr, GetCapturedStderr());
}

TEST_F(AidlTest, ParcelableSupportJavaDeriveToString) {
  io_delegate_.SetFileContents("a/Foo.aidl", R"(package a;
    @JavaDerive(toString=true) parcelable Foo { int a; float b; })");
  Options java_options = Options::From("aidl --lang=java -o out a/Foo.aidl");
  EXPECT_EQ(0, ::android::aidl::compile_aidl(java_options, io_delegate_));

  string java_out;
  EXPECT_TRUE(io_delegate_.GetWrittenContents("out/a/Foo.java", &java_out));
  EXPECT_THAT(java_out, testing::HasSubstr("public String toString() {"));

  // Other backends shouldn't be bothered
  Options cpp_options = Options::From("aidl --lang=cpp -o out -h out a/Foo.aidl");
  EXPECT_EQ(0, ::android::aidl::compile_aidl(cpp_options, io_delegate_));

  Options ndk_options = Options::From("aidl --lang=ndk -o out -h out a/Foo.aidl");
  EXPECT_EQ(0, ::android::aidl::compile_aidl(ndk_options, io_delegate_));
}

TEST_F(AidlTest, UnionSupportJavaDeriveToString) {
  io_delegate_.SetFileContents("a/Foo.aidl", R"(package a;
    @JavaDerive(toString=true) union Foo { int a; int[] b; })");
  CaptureStderr();
  Options java_options = Options::From("aidl --lang=java -o out a/Foo.aidl");
  EXPECT_EQ(0, ::android::aidl::compile_aidl(java_options, io_delegate_));
  EXPECT_EQ("", GetCapturedStderr());

  const string expected_to_string_method = R"--(
  @Override
  public String toString() {
    switch (_tag) {
    case a: return "a.Foo.a(" + (getA()) + ")";
    case b: return "a.Foo.b(" + (java.util.Arrays.toString(getB())) + ")";
    }
    throw new IllegalStateException("unknown field: " + _tag);
  }
)--";

  string java_out;
  EXPECT_TRUE(io_delegate_.GetWrittenContents("out/a/Foo.java", &java_out));
  EXPECT_THAT(java_out, testing::HasSubstr(expected_to_string_method));
}

TEST_F(AidlTest, ParcelableSupportJavaDeriveEquals) {
  io_delegate_.SetFileContents("a/Foo.aidl", R"(package a;
    @JavaDerive(equals=true) parcelable Foo { int a; float b; })");
  CaptureStderr();
  Options java_options = Options::From("aidl --lang=java -o out a/Foo.aidl");
  EXPECT_EQ(0, ::android::aidl::compile_aidl(java_options, io_delegate_));
  EXPECT_EQ("", GetCapturedStderr());

  const std::string expected = R"--(
  @Override
  public boolean equals(Object other) {
    if (this == other) return true;
    if (other == null) return false;
    if (!(other instanceof Foo)) return false;
    Foo that = (Foo)other;
    if (!java.util.Objects.deepEquals(a, that.a)) return false;
    if (!java.util.Objects.deepEquals(b, that.b)) return false;
    return true;
  }

  @Override
  public int hashCode() {
    return java.util.Arrays.deepHashCode(java.util.Arrays.asList(a, b).toArray());
  }
)--";

  string java_out;
  EXPECT_TRUE(io_delegate_.GetWrittenContents("out/a/Foo.java", &java_out));
  EXPECT_THAT(java_out, testing::HasSubstr(expected));
}

TEST_F(AidlTest, UnionSupportJavaDeriveEquals) {
  io_delegate_.SetFileContents("a/Foo.aidl", R"(package a;
    @JavaDerive(equals=true) union Foo { int a; int[] b; })");
  CaptureStderr();
  Options java_options = Options::From("aidl --lang=java -o out a/Foo.aidl");
  EXPECT_EQ(0, ::android::aidl::compile_aidl(java_options, io_delegate_));
  EXPECT_EQ("", GetCapturedStderr());

  const std::string expected = R"--(
  @Override
  public boolean equals(Object other) {
    if (this == other) return true;
    if (other == null) return false;
    if (!(other instanceof Foo)) return false;
    Foo that = (Foo)other;
    if (_tag != that._tag) return false;
    if (!java.util.Objects.deepEquals(_value, that._value)) return false;
    return true;
  }

  @Override
  public int hashCode() {
    return java.util.Arrays.deepHashCode(java.util.Arrays.asList(_tag, _value).toArray());
  }
)--";

  string java_out;
  EXPECT_TRUE(io_delegate_.GetWrittenContents("out/a/Foo.java", &java_out));
  EXPECT_THAT(java_out, testing::HasSubstr(expected));
}

TEST_F(AidlTest, RejectsJavaDeriveAnnotation) {
  {
    io_delegate_.SetFileContents("a/Foo.aidl",
                                 "package a; @JavaDerive(blah=true) parcelable Foo{}");
    Options java_options = Options::From("aidl --lang=java -o out a/Foo.aidl");
    CaptureStderr();
    EXPECT_NE(0, ::android::aidl::compile_aidl(java_options, io_delegate_));
    const std::string expected_stderr =
        "ERROR: a/Foo.aidl:1.11-34: Parameter blah not supported for annotation JavaDerive.";
    EXPECT_THAT(GetCapturedStderr(),
                HasSubstr("Parameter blah not supported for annotation JavaDerive."));
  }

  {
    io_delegate_.SetFileContents("a/IFoo.aidl", "package a; @JavaDerive interface IFoo{}");
    Options java_options = Options::From("aidl --lang=java -o out a/IFoo.aidl");
    CaptureStderr();
    EXPECT_NE(0, ::android::aidl::compile_aidl(java_options, io_delegate_));
    EXPECT_THAT(GetCapturedStderr(), HasSubstr("@JavaDerive is not available."));
  }

  {
    io_delegate_.SetFileContents("a/IFoo.aidl", "package a; @JavaDerive enum IFoo { A=1, }");
    Options java_options = Options::From("aidl --lang=java -o out a/IFoo.aidl");
    CaptureStderr();
    EXPECT_NE(0, ::android::aidl::compile_aidl(java_options, io_delegate_));
    EXPECT_THAT(GetCapturedStderr(), HasSubstr("@JavaDerive is not available."));
  }
}

TEST_P(AidlTest, ParseDescriptorAnnotation) {
  AidlError error;
  auto parse_result = Parse("IFoo.aidl", R"(@Descriptor(value="IBar") interface IFoo{})",
                            typenames_, GetLanguage(), &error, {"--structured"});
  ASSERT_EQ(AidlError::OK, error);
  ASSERT_NE(nullptr, parse_result);
  const AidlInterface* interface = parse_result->AsInterface();
  ASSERT_NE(nullptr, interface);
  ASSERT_EQ("IBar", interface->GetDescriptor());
}

TEST_P(AidlTest, AcceptsOnewayMethod) {
  const string oneway_method = "package a; interface IFoo { oneway void f(int a); }";
  EXPECT_NE(nullptr, Parse("a/IFoo.aidl", oneway_method, typenames_, GetLanguage()));
}

TEST_P(AidlTest, AcceptsOnewayInterface) {
  const string oneway_interface = "package a; oneway interface IBar { void f(int a); }";
  EXPECT_NE(nullptr, Parse("a/IBar.aidl", oneway_interface, typenames_, GetLanguage()));
}

TEST_P(AidlTest, AcceptsAnnotatedOnewayMethod) {
  const string oneway_method =
      "package a; interface IFoo { @UnsupportedAppUsage oneway void f(int a); }";
  EXPECT_NE(nullptr, Parse("a/IFoo.aidl", oneway_method, typenames_, GetLanguage()));
}

TEST_P(AidlTest, AnnotationsInMultiplePlaces) {
  const string oneway_method =
      "package a; interface IFoo { @UnsupportedAppUsage oneway @Hide void f(int a); }";
  const AidlDefinedType* defined = Parse("a/IFoo.aidl", oneway_method, typenames_, GetLanguage());
  ASSERT_NE(nullptr, defined);
  const AidlInterface* iface = defined->AsInterface();
  ASSERT_NE(nullptr, iface);

  const auto& methods = iface->GetMethods();
  ASSERT_EQ(1u, methods.size());
  const auto& method = methods[0];
  const AidlTypeSpecifier& ret_type = method->GetType();

  // TODO(b/151102494): these annotations should be on the method
  ASSERT_NE(nullptr, ret_type.UnsupportedAppUsage());
  ASSERT_TRUE(ret_type.IsHide());
}

TEST_P(AidlTest, WritesComments) {
  string foo_interface =
      R"(package a;
        /* foo */
        interface IFoo {
          /* i */
          int i();
          // j
          @nullable String j();
          // k1
          /* k2 */
          @UnsupportedAppUsage oneway void k(int a);
        })";

  CaptureStderr();
  auto parse_result = Parse("a/IFoo.aidl", foo_interface, typenames_, GetLanguage());
  EXPECT_NE(nullptr, parse_result);
  EXPECT_EQ("", GetCapturedStderr());

  EXPECT_EQ((Comments{{"/* foo */"}}), parse_result->GetComments());

  const AidlInterface* interface = parse_result->AsInterface();
  EXPECT_EQ((Comments{{"/* i */"}}), interface->GetMethods()[0]->GetComments());
  EXPECT_EQ((Comments{{"// j\n"}}), interface->GetMethods()[1]->GetComments());
  EXPECT_EQ((Comments{{"// k1\n"}, {"/* k2 */"}}), interface->GetMethods()[2]->GetComments());
}

TEST_P(AidlTest, CppHeaderCanBeIdentifierAsWell) {
  io_delegate_.SetFileContents("p/cpp_header.aidl",
                               R"(package p;
         parcelable cpp_header cpp_header "bar/header";)");
  import_paths_.emplace("");
  const string input_path = "p/IFoo.aidl";
  const string input = R"(package p;
                          import p.cpp_header;
                          interface IFoo {
                            // get bar
                            cpp_header get();
                          })";

  auto parse_result = Parse(input_path, input, typenames_, GetLanguage());
  EXPECT_NE(nullptr, parse_result);
  const AidlInterface* interface = parse_result->AsInterface();
  EXPECT_EQ((Comments{{"// get bar\n"}}), interface->GetMethods()[0]->GetComments());
}

TEST_F(AidlTest, ParsesPreprocessedFile) {
  string simple_content = "parcelable a.Foo;\ninterface b.IBar;";
  io_delegate_.SetFileContents("path", simple_content);
  EXPECT_FALSE(typenames_.ResolveTypename("a.Foo").is_resolved);
  EXPECT_TRUE(parse_preprocessed_file(io_delegate_, "path", &typenames_));
  EXPECT_TRUE(typenames_.ResolveTypename("a.Foo").is_resolved);
  EXPECT_TRUE(typenames_.ResolveTypename("b.IBar").is_resolved);
}

TEST_F(AidlTest, ParsesPreprocessedFileWithWhitespace) {
  string simple_content = "parcelable    a.Foo;\n  interface b.IBar  ;\t";
  io_delegate_.SetFileContents("path", simple_content);

  EXPECT_FALSE(typenames_.ResolveTypename("a.Foo").is_resolved);
  EXPECT_TRUE(parse_preprocessed_file(io_delegate_, "path", &typenames_));
  EXPECT_TRUE(typenames_.ResolveTypename("a.Foo").is_resolved);
  EXPECT_TRUE(typenames_.ResolveTypename("b.IBar").is_resolved);
}

TEST_P(AidlTest, PreferImportToPreprocessed) {
  io_delegate_.SetFileContents("preprocessed", "interface another.IBar;");
  io_delegate_.SetFileContents("one/IBar.aidl", "package one; "
                                                "interface IBar {}");
  preprocessed_files_.push_back("preprocessed");
  import_paths_.emplace("");
  auto parse_result = Parse("p/IFoo.aidl", "package p; import one.IBar; interface IFoo {}",
                            typenames_, GetLanguage());
  EXPECT_NE(nullptr, parse_result);

  // We expect to know about both kinds of IBar
  EXPECT_TRUE(typenames_.ResolveTypename("one.IBar").is_resolved);
  EXPECT_TRUE(typenames_.ResolveTypename("another.IBar").is_resolved);
  // But if we request just "IBar" we should get our imported one.
  AidlTypeSpecifier ambiguous_type(AIDL_LOCATION_HERE, "IBar", false, nullptr, {});
  ambiguous_type.Resolve(typenames_);
  EXPECT_EQ("one.IBar", ambiguous_type.GetName());
}

// Special case of PreferImportToPreprocessed. Imported type should be preferred
// even when the preprocessed file already has the same type.
TEST_P(AidlTest, B147918827) {
  io_delegate_.SetFileContents("preprocessed", "interface another.IBar;\ninterface one.IBar;");
  io_delegate_.SetFileContents("one/IBar.aidl",
                               "package one; "
                               "interface IBar {}");
  preprocessed_files_.push_back("preprocessed");
  import_paths_.emplace("");
  auto parse_result = Parse("p/IFoo.aidl", "package p; import one.IBar; interface IFoo {}",
                            typenames_, GetLanguage());
  EXPECT_NE(nullptr, parse_result);

  // We expect to know about both kinds of IBar
  EXPECT_TRUE(typenames_.ResolveTypename("one.IBar").is_resolved);
  EXPECT_TRUE(typenames_.ResolveTypename("another.IBar").is_resolved);
  // But if we request just "IBar" we should get our imported one.
  AidlTypeSpecifier ambiguous_type(AIDL_LOCATION_HERE, "IBar", false, nullptr, {});
  ambiguous_type.Resolve(typenames_);
  EXPECT_EQ("one.IBar", ambiguous_type.GetName());
}

TEST_F(AidlTest, WritePreprocessedFile) {
  io_delegate_.SetFileContents("p/Outer.aidl",
                               "package p; parcelable Outer.Inner;");
  io_delegate_.SetFileContents("one/IBar.aidl", "package one; import p.Outer;"
                                                "interface IBar {}");

  vector<string> args {
    "aidl",
    "--preprocess",
    "preprocessed",
    "p/Outer.aidl",
    "one/IBar.aidl"};
  Options options = Options::From(args);
  EXPECT_TRUE(::android::aidl::preprocess_aidl(options, io_delegate_));

  string output;
  EXPECT_TRUE(io_delegate_.GetWrittenContents("preprocessed", &output));
  EXPECT_EQ("parcelable p.Outer.Inner;\ninterface one.IBar;\n", output);
}

TEST_P(AidlTest, SupportDeprecated) {
  struct TestCase {
    std::string output_file;
    std::string annotation;
  };

  auto CheckDeprecated = [&](const std::string& filename, const std::string& contents,
                             std::vector<std::pair<Options::Language, TestCase>> expectations) {
    io_delegate_.SetFileContents(filename, contents);

    auto options = Options::From("aidl --lang=" + to_string(GetLanguage()) + " " + filename +
                                 " --out=out --header_out=out");
    EXPECT_EQ(0, ::android::aidl::compile_aidl(options, io_delegate_));
    for (const auto& [lang, test_case] : expectations) {
      if (lang != GetLanguage()) continue;
      string output;
      EXPECT_TRUE(io_delegate_.GetWrittenContents(test_case.output_file, &output));
      EXPECT_THAT(output, HasSubstr(test_case.annotation));
    }
  };

  // Emit escaped string for notes
  CheckDeprecated(
      "IFoo.aidl",
      R"(interface IFoo {
           /**
            * @note asdf
            * @deprecated a really long deprecation message
            *
            *    which is really long
            * @param foo bar
            */
           List<String> foo();
        })",
      {
          {Options::Language::JAVA, {"out/IFoo.java", "@Deprecated"}},
          {Options::Language::CPP,
           {"out/IFoo.h",
            R"(__attribute__((deprecated("a really long deprecation message which is really long"))))"}},
          {Options::Language::NDK,
           {"out/aidl/IFoo.h",
            R"(__attribute__((deprecated("a really long deprecation message which is really long"))))"}},
          {Options::Language::RUST,
           {"out/IFoo.rs",
            R"(#[deprecated = "a really long deprecation message which is really long"])"}},
      });

  // In AIDL @deprecated can be in block comments as well as javadoc style
  CheckDeprecated(
      "IFoo.aidl",
      "interface IFoo {\n"
      "  /* @deprecated use bar() */\n"
      "  List<String> foo();\n"
      "}",
      {
          {Options::Language::JAVA, {"out/IFoo.java", "@Deprecated"}},
          {Options::Language::JAVA, {"out/IFoo.java", "/** @deprecated use bar() */"}},
          {Options::Language::CPP, {"out/IFoo.h", "__attribute__((deprecated(\"use bar()\")))"}},
          {Options::Language::NDK,
           {"out/aidl/IFoo.h", "__attribute__((deprecated(\"use bar()\")))"}},
          {Options::Language::RUST, {"out/IFoo.rs", "#[deprecated = \"use bar()\"]"}},
      });

  // but not in line comments
  auto parsed = Parse("IFoo.aidl", "// @deprecated\ninterface IFoo {}", typenames_, GetLanguage());
  EXPECT_FALSE(parsed->IsDeprecated());

  // parcelable
  CheckDeprecated("Foo.aidl",
                  "parcelable Foo {\n"
                  "  /** @deprecated use bar*/\n"
                  "  int foo = 0;\n"
                  "}",
                  {
                      {Options::Language::JAVA, {"out/Foo.java", "@Deprecated"}},
                      {Options::Language::CPP, {"out/Foo.h", "__attribute__((deprecated"}},
                      {Options::Language::NDK, {"out/aidl/Foo.h", "__attribute__((deprecated"}},
                      {Options::Language::RUST, {"out/Foo.rs", "#[deprecated"}},
                  });

  // interface constants
  CheckDeprecated("IFoo.aidl",
                  "interface IFoo {\n"
                  "  /** @deprecated use bar*/\n"
                  "  const int FOO = 0;\n"
                  "}",
                  {
                      {Options::Language::JAVA, {"out/IFoo.java", "@Deprecated"}},
                      {Options::Language::CPP, {"out/IFoo.h", "__attribute__((deprecated"}},
                      {Options::Language::NDK, {"out/aidl/IFoo.h", "__attribute__((deprecated"}},
                      {Options::Language::RUST, {"out/IFoo.rs", "#[deprecated"}},
                  });

  // union fields
  CheckDeprecated("Foo.aidl",
                  "union Foo {\n"
                  "  int bar = 0;\n"
                  "  /** @deprecated use bar*/\n"
                  "  int foo;\n"
                  "}",
                  {
                      {Options::Language::JAVA, {"out/Foo.java", "@Deprecated"}},
                      {Options::Language::CPP, {"out/Foo.h", "__attribute__((deprecated"}},
                      {Options::Language::NDK, {"out/aidl/Foo.h", "__attribute__((deprecated"}},
                      {Options::Language::RUST, {"out/Foo.rs", "#[deprecated"}},
                  });

  CheckDeprecated("Foo.aidl",
                  "/** @deprecated use Bar */\n"
                  "parcelable Foo {}",
                  {
                      {Options::Language::JAVA, {"out/Foo.java", "@Deprecated"}},
                      {Options::Language::CPP, {"out/Foo.h", "__attribute__((deprecated"}},
                      {Options::Language::NDK, {"out/aidl/Foo.h", "__attribute__((deprecated"}},
                      {Options::Language::RUST, {"out/Foo.rs", "#[deprecated"}},
                  });

  CheckDeprecated("Foo.aidl",
                  "/** @deprecated use Bar */\n"
                  "union Foo { int foo = 0; }",
                  {
                      {Options::Language::JAVA, {"out/Foo.java", "@Deprecated"}},
                      {Options::Language::CPP, {"out/Foo.h", "__attribute__((deprecated"}},
                      {Options::Language::NDK, {"out/aidl/Foo.h", "__attribute__((deprecated"}},
                      {Options::Language::RUST, {"out/Foo.rs", "#[deprecated"}},
                  });

  CheckDeprecated("IFoo.aidl",
                  "/** @deprecated use IBar */\n"
                  "interface IFoo {}",
                  {
                      {Options::Language::JAVA, {"out/IFoo.java", "@Deprecated"}},
                      {Options::Language::CPP, {"out/IFoo.h", "__attribute__((deprecated"}},
                      {Options::Language::NDK, {"out/aidl/IFoo.h", "__attribute__((deprecated"}},
                      {Options::Language::RUST, {"out/IFoo.rs", "#[deprecated"}},
                  });

  CheckDeprecated("Foo.aidl",
                  "/** @deprecated use IBar */\n"
                  "enum Foo { FOO }",
                  {
                      {Options::Language::JAVA, {"out/Foo.java", "@Deprecated"}},
                      {Options::Language::CPP, {"out/Foo.h", "__attribute__((deprecated"}},
                      {Options::Language::NDK, {"out/aidl/Foo.h", "__attribute__((deprecated"}},
                      // TODO(b/177860423) support "deprecated" in Rust enum
                      // {Options::Language::RUST, {"out/Foo.rs", "#[deprecated"}},
                  });
}

TEST_P(AidlTest, RequireOuterClass) {
  const string expected_stderr = "ERROR: p/IFoo.aidl:1.54-60: Failed to resolve 'Inner'\n";
  io_delegate_.SetFileContents("p/Outer.aidl",
                               "package p; parcelable Outer.Inner;");
  import_paths_.emplace("");
  CaptureStderr();
  EXPECT_EQ(nullptr, Parse("p/IFoo.aidl",
                           "package p; import p.Outer; interface IFoo { void f(in Inner c); }",
                           typenames_, GetLanguage()));
  EXPECT_EQ(expected_stderr, GetCapturedStderr());
}

TEST_P(AidlTest, ParseCompoundParcelableFromPreprocess) {
  io_delegate_.SetFileContents("preprocessed",
                               "parcelable p.Outer.Inner;");
  preprocessed_files_.push_back("preprocessed");
  auto parse_result = Parse("p/IFoo.aidl", "package p; interface IFoo { void f(in Inner c); }",
                            typenames_, GetLanguage());
  // TODO(wiley): This should actually return nullptr because we require
  //              the outer class name.  However, for legacy reasons,
  //              this behavior must be maintained.  b/17415692
  EXPECT_NE(nullptr, parse_result);
}

TEST_F(AidlTest, FailOnParcelable) {
  const string expected_foo_stderr =
      "ERROR: p/IFoo.aidl:1.22-27: Refusing to generate code with unstructured parcelables. "
      "Declared parcelables should be in their own file and/or cannot be used with --structured "
      "interfaces.\n";
  io_delegate_.SetFileContents("p/IFoo.aidl", "package p; parcelable IFoo;");

  // By default, we shouldn't fail on parcelable.
  Options options1 = Options::From("aidl p/IFoo.aidl");
  CaptureStderr();
  EXPECT_EQ(0, ::android::aidl::compile_aidl(options1, io_delegate_));
  EXPECT_EQ("", GetCapturedStderr());

  // -b considers this an error
  Options options2 = Options::From("aidl -b p/IFoo.aidl");
  CaptureStderr();
  EXPECT_NE(0, ::android::aidl::compile_aidl(options2, io_delegate_));
  EXPECT_EQ(expected_foo_stderr, GetCapturedStderr());

  const string expected_bar_stderr =
      "ERROR: p/IBar.aidl:1.22-26: Refusing to generate code with unstructured parcelables. "
      "Declared parcelables should be in their own file and/or cannot be used with --structured "
      "interfaces.\n";
  io_delegate_.SetFileContents("p/IBar.aidl", "package p; parcelable Foo; interface IBar{}");

  // With '-b' option, a parcelable and an interface should fail.
  Options options3 = Options::From("aidl p/IBar.aidl");
  CaptureStderr();
  EXPECT_EQ(0, ::android::aidl::compile_aidl(options3, io_delegate_));
  EXPECT_EQ("", GetCapturedStderr());
  Options options4 = Options::From("aidl -b p/IBar.aidl");
  CaptureStderr();
  EXPECT_NE(0, ::android::aidl::compile_aidl(options4, io_delegate_));
  EXPECT_EQ(expected_bar_stderr, GetCapturedStderr());
}

TEST_P(AidlTest, StructuredFailOnUnstructuredParcelable) {
  const string expected_stderr =
      "ERROR: ./o/WhoKnowsWhat.aidl:1.22-35: o.WhoKnowsWhat is not structured, but this is a "
      "structured interface.\n";
  io_delegate_.SetFileContents("o/WhoKnowsWhat.aidl", "package o; parcelable WhoKnowsWhat;");
  import_paths_.emplace("");
  AidlError error;
  CaptureStderr();
  EXPECT_EQ(
      nullptr,
      Parse("p/IFoo.aidl",
            "package p; import o.WhoKnowsWhat; interface IFoo { void f(in WhoKnowsWhat thisIs); }",
            typenames_, GetLanguage(), &error, {"--structured"}));
  EXPECT_EQ(expected_stderr, GetCapturedStderr());
  EXPECT_EQ(AidlError::NOT_STRUCTURED, error);
}

TEST_P(AidlTest, FailOnDuplicateConstantNames) {
  AidlError error;
  const string expected_stderr =
      "ERROR: p/IFoo.aidl:4.34-45: Found duplicate constant name 'DUPLICATED'\n";
  CaptureStderr();
  EXPECT_EQ(nullptr, Parse("p/IFoo.aidl",
                           R"(package p;
                      interface IFoo {
                        const String DUPLICATED = "d";
                        const int DUPLICATED = 1;
                      }
                   )",
                           typenames_, GetLanguage(), &error));
  EXPECT_EQ(expected_stderr, GetCapturedStderr());
  EXPECT_EQ(AidlError::BAD_TYPE, error);
}

TEST_P(AidlTest, FailOnTooBigConstant) {
  AidlError error;
  const string expected_stderr =
      "ERROR: p/IFoo.aidl:3.48-52: Invalid type specifier for an int32 literal: byte\n";
  CaptureStderr();
  EXPECT_EQ(nullptr, Parse("p/IFoo.aidl",
                           R"(package p;
                      interface IFoo {
                        const byte type2small = 256;
                      }
                   )",
                           typenames_, GetLanguage(), &error));
  EXPECT_EQ(expected_stderr, GetCapturedStderr());
  EXPECT_EQ(AidlError::BAD_TYPE, error);
}

TEST_F(AidlTest, BoolConstantsEvaluatesToIntegers) {
  io_delegate_.SetFileContents("a/Foo.aidl", "package a; parcelable Foo { const int y = true; }");
  CaptureStderr();
  auto options = Options::From("aidl --lang java -o out a/Foo.aidl");
  EXPECT_EQ(0, aidl::compile_aidl(options, io_delegate_));
  EXPECT_EQ("", GetCapturedStderr());
  string code;
  EXPECT_TRUE(io_delegate_.GetWrittenContents("out/a/Foo.java", &code));
  EXPECT_THAT(code, testing::HasSubstr("public static final int y = 1;"));
}

TEST_F(AidlTest, AidlConstantValue_EvaluatedValue) {
  using Ptr = unique_ptr<AidlConstantValue>;
  const AidlLocation& loc = AIDL_LOCATION_HERE;

  EXPECT_EQ('c', Ptr(AidlConstantValue::Character(loc, 'c'))->EvaluatedValue<char>());
  EXPECT_EQ("abc", Ptr(AidlConstantValue::String(loc, "\"abc\""))->EvaluatedValue<string>());
  EXPECT_FLOAT_EQ(1.0f, Ptr(AidlConstantValue::Floating(loc, "1.0f"))->EvaluatedValue<float>());
  EXPECT_EQ(true, Ptr(AidlConstantValue::Boolean(loc, true))->EvaluatedValue<bool>());

  AidlBinaryConstExpression one_plus_one(loc, Ptr(AidlConstantValue::Integral(loc, "1")), "+",
                                         Ptr(AidlConstantValue::Integral(loc, "1")));
  EXPECT_EQ(2, one_plus_one.EvaluatedValue<int32_t>());

  auto values = unique_ptr<vector<Ptr>>{new vector<Ptr>};
  values->emplace_back(AidlConstantValue::String(loc, "\"hello\""));
  values->emplace_back(AidlConstantValue::String(loc, "\"world\""));
  vector<string> expected{"hello", "world"};
  EXPECT_EQ(
      expected,
      Ptr(AidlConstantValue::Array(loc, std::move(values)))->EvaluatedValue<vector<string>>());
}

TEST_P(AidlTest, FailOnManyDefinedTypes) {
  AidlError error;
  const string expected_stderr =
      "ERROR: p/IFoo.aidl:3.33-38: You must declare only one type per file.\n";
  CaptureStderr();
  EXPECT_EQ(nullptr, Parse("p/IFoo.aidl",
                           R"(package p;
                      interface IFoo {}
                      parcelable IBar {}
                      parcelable StructuredParcelable {}
                      interface IBaz {}
                  )",
                           typenames_, GetLanguage(), &error));
  EXPECT_EQ(expected_stderr, GetCapturedStderr());
  // Parse success is important for clear error handling even if the cases aren't
  // actually supported in code generation.
  EXPECT_EQ(AidlError::BAD_TYPE, error);
}

TEST_P(AidlTest, FailOnNoDefinedTypes) {
  AidlError error;
  const string expected_stderr = "ERROR: p/IFoo.aidl:1.11-11: syntax error, unexpected $end\n";
  CaptureStderr();
  EXPECT_EQ(nullptr, Parse("p/IFoo.aidl", R"(package p;)", typenames_, GetLanguage(), &error));
  EXPECT_EQ(expected_stderr, GetCapturedStderr());
  EXPECT_EQ(AidlError::PARSE_ERROR, error);
}

TEST_P(AidlTest, FailOnEmptyListWithComma) {
  AidlError error;
  const string expected_stderr =
      "ERROR: p/Foo.aidl:1.45-47: syntax error, unexpected ',', expecting '}'\n";
  CaptureStderr();
  EXPECT_EQ(nullptr, Parse("p/Foo.aidl", R"(package p; parcelable Foo { uint64_t[] a = { , }; })",
                           typenames_, GetLanguage(), &error));
  EXPECT_EQ(expected_stderr, GetCapturedStderr());
  EXPECT_EQ(AidlError::PARSE_ERROR, error);
}

TEST_P(AidlTest, FailOnMalformedConstHexValue) {
  AidlError error;
  const string expected_stderr =
      "ERROR: p/IFoo.aidl:3.50-71: Could not parse hexvalue: 0xffffffffffffffffff\n";
  CaptureStderr();
  EXPECT_EQ(nullptr, Parse("p/IFoo.aidl",
                           R"(package p;
                      interface IFoo {
                        const int BAD_HEX_VALUE = 0xffffffffffffffffff;
                      }
                   )",
                           typenames_, GetLanguage(), &error));
  EXPECT_EQ(expected_stderr, GetCapturedStderr());
  EXPECT_EQ(AidlError::PARSE_ERROR, error);
}

TEST_P(AidlTest, FailOnMalformedQualifiedNameAsIdentifier) {
  AidlError error;
  const string expected_stderr =
      "ERROR: p/IFoo.aidl:1.25-26: syntax error, unexpected ';', expecting identifier or "
      "cpp_header (which can also be used as an identifier)\n";
  CaptureStderr();
  // Notice the trailing dot(.) in the name, which isn't a correct name
  EXPECT_EQ(nullptr, Parse("p/IFoo.aidl", R"(package p; parcelable A.; )", typenames_,
                           GetLanguage(), &error));
  EXPECT_EQ(expected_stderr, GetCapturedStderr());
  EXPECT_EQ(AidlError::PARSE_ERROR, error);
}

TEST_P(AidlTest, FailOnMalformedQualifiedNameAsPackage) {
  AidlError error;
  const string expected_stderr =
      "ERROR: p/IFoo.aidl:1.11-12: syntax error, unexpected ';', expecting identifier or "
      "cpp_header (which can also be used as an identifier)\n";
  CaptureStderr();
  // Notice the trailing dot(.) in the package name
  EXPECT_EQ(nullptr, Parse("p/IFoo.aidl", R"(package p.; parcelable A; )", typenames_,
                           GetLanguage(), &error));
  EXPECT_EQ(expected_stderr, GetCapturedStderr());
  EXPECT_EQ(AidlError::PARSE_ERROR, error);
}

TEST_P(AidlTest, ParsePositiveConstHexValue) {
  AidlError error;
  auto parse_result = Parse("p/IFoo.aidl",
                            R"(package p;
              interface IFoo {
                const int POSITIVE_HEX_VALUE = 0xf5;
              }
           )",
                            typenames_, GetLanguage(), &error);
  EXPECT_NE(nullptr, parse_result);
  const AidlInterface* interface = parse_result->AsInterface();
  ASSERT_NE(nullptr, interface);
  const auto& cpp_constants = interface->GetConstantDeclarations();
  EXPECT_EQ((size_t)1, cpp_constants.size());
  EXPECT_EQ("POSITIVE_HEX_VALUE", cpp_constants[0]->GetName());
  EXPECT_TRUE(cpp_constants[0]->CheckValid(typenames_));
  EXPECT_EQ("245", cpp_constants[0]->ValueString(cpp::ConstantValueDecorator));
}

TEST_P(AidlTest, ParseNegativeConstHexValue) {
  AidlError error;
  auto parse_result = Parse("p/IFoo.aidl",
                            R"(package p;
              interface IFoo {
                const int NEGATIVE_HEX_VALUE = 0xffffffff;
              }
           )",
                            typenames_, GetLanguage(), &error);
  ASSERT_NE(nullptr, parse_result);
  const AidlInterface* interface = parse_result->AsInterface();
  ASSERT_NE(nullptr, interface);
  const auto& cpp_constants = interface->GetConstantDeclarations();
  EXPECT_EQ((size_t)1, cpp_constants.size());
  EXPECT_EQ("NEGATIVE_HEX_VALUE", cpp_constants[0]->GetName());
  EXPECT_EQ(true, cpp_constants[0]->CheckValid(typenames_));
  EXPECT_EQ("-1", cpp_constants[0]->ValueString(cpp::ConstantValueDecorator));
}

TEST_P(AidlTest, UnderstandsNestedParcelables) {
  io_delegate_.SetFileContents(
      "p/Outer.aidl",
      "package p; parcelable Outer.Inner cpp_header \"baz/header\";");
  import_paths_.emplace("");
  const string input_path = "p/IFoo.aidl";
  const string input = "package p; import p.Outer; interface IFoo"
                       " { Outer.Inner get(); }";

  auto parse_result = Parse(input_path, input, typenames_, GetLanguage());
  EXPECT_NE(nullptr, parse_result);

  EXPECT_TRUE(typenames_.ResolveTypename("p.Outer.Inner").is_resolved);
  // C++ uses "::" instead of "." to refer to a inner class.
  AidlTypeSpecifier nested_type(AIDL_LOCATION_HERE, "p.Outer.Inner", false, nullptr, {});
  EXPECT_EQ("::p::Outer::Inner", cpp::CppNameOf(nested_type, typenames_));
}

TEST_P(AidlTest, UnderstandsNativeParcelables) {
  io_delegate_.SetFileContents(
      "p/Bar.aidl",
      "package p; parcelable Bar cpp_header \"baz/header\";");
  import_paths_.emplace("");
  const string input_path = "p/IFoo.aidl";
  const string input = "package p; import p.Bar; interface IFoo { }";
  auto parse_result = Parse(input_path, input, typenames_, GetLanguage());
  EXPECT_NE(nullptr, parse_result);
  EXPECT_TRUE(typenames_.ResolveTypename("p.Bar").is_resolved);
  AidlTypeSpecifier native_type(AIDL_LOCATION_HERE, "p.Bar", false, nullptr, {});
  native_type.Resolve(typenames_);

  EXPECT_EQ("p.Bar", java::InstantiableJavaSignatureOf(native_type, typenames_));
  // C++ understands C++ specific stuff
  EXPECT_EQ("::p::Bar", cpp::CppNameOf(native_type, typenames_));
  set<string> headers;
  cpp::AddHeaders(native_type, typenames_, &headers);
  EXPECT_EQ(1u, headers.size());
  EXPECT_EQ(1u, headers.count("baz/header"));
}

TEST_F(AidlTest, WritesCorrectDependencyFile) {
  // While the in tree build system always gives us an output file name,
  // other android tools take advantage of our ability to infer the intended
  // file name.  This test makes sure we handle this correctly.
  vector<string> args = {
    "aidl",
    "-d dep/file/path",
    "-o place/for/output",
    "p/IFoo.aidl"};
  Options options = Options::From(args);
  io_delegate_.SetFileContents(options.InputFiles().front(), "package p; interface IFoo {}");
  EXPECT_EQ(0, ::android::aidl::compile_aidl(options, io_delegate_));
  string actual_dep_file_contents;
  EXPECT_TRUE(io_delegate_.GetWrittenContents(options.DependencyFile(), &actual_dep_file_contents));
  EXPECT_EQ(actual_dep_file_contents, kExpectedDepFileContents);
}

TEST_F(AidlTest, WritesCorrectDependencyFileNinja) {
  // While the in tree build system always gives us an output file name,
  // other android tools take advantage of our ability to infer the intended
  // file name.  This test makes sure we handle this correctly.
  vector<string> args = {
    "aidl",
    "-d dep/file/path",
    "--ninja",
    "-o place/for/output",
    "p/IFoo.aidl"};
  Options options = Options::From(args);
  io_delegate_.SetFileContents(options.InputFiles().front(), "package p; interface IFoo {}");
  EXPECT_EQ(0, ::android::aidl::compile_aidl(options, io_delegate_));
  string actual_dep_file_contents;
  EXPECT_TRUE(io_delegate_.GetWrittenContents(options.DependencyFile(), &actual_dep_file_contents));
  EXPECT_EQ(actual_dep_file_contents, kExpectedNinjaDepFileContents);
}

TEST_F(AidlTest, WritesTrivialDependencyFileForParcelableDeclaration) {
  // The SDK uses aidl to decide whether a .aidl file is a parcelable.  It does
  // this by calling aidl with every .aidl file it finds, then parsing the
  // generated dependency files.  Those that reference .java output files are
  // for interfaces and those that do not are parcelables.  However, for both
  // parcelables and interfaces, we *must* generate a non-empty dependency file.
  vector<string> args = {
    "aidl",
    "-o place/for/output",
    "-d dep/file/path",
    "p/Foo.aidl"};
  Options options = Options::From(args);
  io_delegate_.SetFileContents(options.InputFiles().front(), "package p; parcelable Foo;");
  EXPECT_EQ(0, ::android::aidl::compile_aidl(options, io_delegate_));
  string actual_dep_file_contents;
  EXPECT_TRUE(io_delegate_.GetWrittenContents(options.DependencyFile(), &actual_dep_file_contents));
  EXPECT_EQ(actual_dep_file_contents, kExpectedParcelableDeclarationDepFileContents);
}

TEST_F(AidlTest, WritesDependencyFileForStructuredParcelable) {
  vector<string> args = {
    "aidl",
    "--structured",
    "-o place/for/output",
    "-d dep/file/path",
    "p/Foo.aidl"};
  Options options = Options::From(args);
  io_delegate_.SetFileContents(options.InputFiles().front(), "package p; parcelable Foo {int a;}");
  EXPECT_EQ(0, ::android::aidl::compile_aidl(options, io_delegate_));
  string actual_dep_file_contents;
  EXPECT_TRUE(io_delegate_.GetWrittenContents(options.DependencyFile(), &actual_dep_file_contents));
  EXPECT_EQ(actual_dep_file_contents, kExpectedStructuredParcelableDepFileContents);
}

TEST_F(AidlTest, NoJavaOutputForParcelableDeclaration) {
 vector<string> args = {
    "aidl",
    "--lang=java",
    "-o place/for/output",
    "p/Foo.aidl"};
  Options options = Options::From(args);
  io_delegate_.SetFileContents(options.InputFiles().front(), "package p; parcelable Foo;");
  EXPECT_EQ(0, ::android::aidl::compile_aidl(options, io_delegate_));
  string output_file_contents;
  EXPECT_FALSE(io_delegate_.GetWrittenContents(options.OutputFile(), &output_file_contents));
}

TEST_P(AidlTest, RejectsListArray) {
  const string expected_stderr = "ERROR: a/Foo.aidl:2.1-7: List[] is not supported.\n";
  const string list_array_parcelable =
      "package a; parcelable Foo {\n"
      "  List[] lists; }";
  CaptureStderr();
  EXPECT_EQ(nullptr, Parse("a/Foo.aidl", list_array_parcelable, typenames_, GetLanguage()));
  EXPECT_EQ(expected_stderr, GetCapturedStderr());
}

TEST_P(AidlTest, RejectsPrimitiveListInStableAidl) {
  AidlError error;
  string expected_stderr =
      "ERROR: a/IFoo.aidl:2.7-11: "
      "Encountered an untyped List or Map. The use of untyped List/Map is "
      "prohibited because it is not guaranteed that the objects in the list are recognizable in "
      "the receiving side. Consider switching to an array or a generic List/Map.\n";
  if (GetLanguage() != Options::Language::JAVA) {
    expected_stderr =
        "ERROR: a/IFoo.aidl:2.1-7: "
        "Currently, only the Java backend supports non-generic List.\n";
  }

  const string primitive_interface =
      "package a; interface IFoo {\n"
      "  List foo(); }";
  CaptureStderr();
  AidlTypenames tn1;
  EXPECT_EQ(nullptr, Parse("a/IFoo.aidl", primitive_interface, tn1, GetLanguage(), &error,
                           {"--structured"}));
  EXPECT_EQ(expected_stderr, GetCapturedStderr());

  string primitive_parcelable =
      "package a; parcelable IFoo {\n"
      "  List foo;}";
  CaptureStderr();
  AidlTypenames tn2;
  EXPECT_EQ(nullptr, Parse("a/IFoo.aidl", primitive_parcelable, tn2, GetLanguage(), &error,
                           {"--structured"}));
  EXPECT_EQ(expected_stderr, GetCapturedStderr());
}

TEST_P(AidlTest, ExtensionTest) {
  CaptureStderr();
  string extendable_parcelable =
      "package a; parcelable Data {\n"
      "  ParcelableHolder extension;\n"
      "  ParcelableHolder extension2;\n"
      "}";
  if (GetLanguage() == Options::Language::RUST) {
    EXPECT_EQ(nullptr, Parse("a/Data.aidl", extendable_parcelable, typenames_, GetLanguage()));
    EXPECT_EQ(
        "ERROR: a/Data.aidl:2.1-19: The Rust backend does not support ParcelableHolder "
        "yet.\n",
        GetCapturedStderr());
  } else {
    EXPECT_NE(nullptr, Parse("a/Data.aidl", extendable_parcelable, typenames_, GetLanguage()));
    EXPECT_EQ("", GetCapturedStderr());
  }
}
TEST_P(AidlTest, ParcelableHolderAsReturnType) {
  CaptureStderr();
  string parcelableholder_return_interface =
      "package a; interface IFoo {\n"
      "  ParcelableHolder foo();\n"
      "}";
  EXPECT_EQ(nullptr,
            Parse("a/IFoo.aidl", parcelableholder_return_interface, typenames_, GetLanguage()));

  if (GetLanguage() == Options::Language::RUST) {
    EXPECT_EQ(
        "ERROR: a/IFoo.aidl:2.19-23: ParcelableHolder cannot be a return type\n"
        "ERROR: a/IFoo.aidl:2.1-19: The Rust backend does not support ParcelableHolder "
        "yet.\n",
        GetCapturedStderr());
    return;
  }
  EXPECT_EQ("ERROR: a/IFoo.aidl:2.19-23: ParcelableHolder cannot be a return type\n",
            GetCapturedStderr());
}

TEST_P(AidlTest, ParcelableHolderAsArgumentType) {
  CaptureStderr();
  string extendable_parcelable_arg_interface =
      "package a; interface IFoo {\n"
      "  void foo(in ParcelableHolder ph);\n"
      "}";
  EXPECT_EQ(nullptr,
            Parse("a/IFoo.aidl", extendable_parcelable_arg_interface, typenames_, GetLanguage()));

  if (GetLanguage() == Options::Language::RUST) {
    EXPECT_EQ(
        "ERROR: a/IFoo.aidl:2.31-34: ParcelableHolder cannot be an argument type\n"
        "ERROR: a/IFoo.aidl:2.14-31: The Rust backend does not support ParcelableHolder "
        "yet.\n",
        GetCapturedStderr());
    return;
  }
  EXPECT_EQ("ERROR: a/IFoo.aidl:2.31-34: ParcelableHolder cannot be an argument type\n",
            GetCapturedStderr());
}

TEST_P(AidlTest, RejectNullableParcelableHolderField) {
  io_delegate_.SetFileContents("Foo.aidl", "parcelable Foo { @nullable ParcelableHolder ext; }");
  Options options = Options::From("aidl Foo.aidl --lang=" + to_string(GetLanguage()));
  const string expected_stderr = "ERROR: Foo.aidl:1.27-44: ParcelableHolder cannot be nullable.\n";
  CaptureStderr();
  EXPECT_NE(0, ::android::aidl::compile_aidl(options, io_delegate_));
  if (GetLanguage() == Options::Language::RUST) {
    EXPECT_EQ(
        "ERROR: Foo.aidl:1.27-44: ParcelableHolder cannot be nullable.\n"
        "ERROR: Foo.aidl:1.27-44: The Rust backend does not support ParcelableHolder "
        "yet.\n",
        GetCapturedStderr());
    return;
  }
  EXPECT_EQ(expected_stderr, GetCapturedStderr());
}

TEST_P(AidlTest, ParcelablesWithConstants) {
  io_delegate_.SetFileContents("Foo.aidl", "parcelable Foo { const int BIT = 0x1 << 3; }");
  Options options = Options::From("aidl Foo.aidl --lang=" + to_string(GetLanguage()));
  CaptureStderr();
  EXPECT_EQ(0, ::android::aidl::compile_aidl(options, io_delegate_));
  EXPECT_EQ("", GetCapturedStderr());
}

TEST_P(AidlTest, UnionWithConstants) {
  io_delegate_.SetFileContents("Foo.aidl", "union Foo { const int BIT = 0x1 << 3; int n; }");
  Options options = Options::From("aidl Foo.aidl --lang=" + to_string(GetLanguage()));
  CaptureStderr();
  EXPECT_EQ(0, ::android::aidl::compile_aidl(options, io_delegate_));
  EXPECT_EQ("", GetCapturedStderr());
}

TEST_F(AidlTest, ConstantsWithAnnotations) {
  io_delegate_.SetFileContents("IFoo.aidl",
                               "interface IFoo {\n"
                               " @JavaPassthrough(annotation=\"@Foo\")\n"
                               " const @JavaPassthrough(annotation=\"@Bar\") int FOO = 0;\n"
                               "}");
  Options options = Options::From("aidl IFoo.aidl --lang=java -o out");
  CaptureStderr();
  EXPECT_EQ(0, ::android::aidl::compile_aidl(options, io_delegate_));
  EXPECT_EQ("", GetCapturedStderr());
  string code;
  EXPECT_TRUE(io_delegate_.GetWrittenContents("out/IFoo.java", &code));
  EXPECT_THAT(code, HasSubstr("@Foo\n"));
  EXPECT_THAT(code, HasSubstr("@Bar\n"));
}

TEST_F(AidlTest, ApiDump) {
  io_delegate_.SetFileContents(
      "foo/bar/IFoo.aidl",
      "package foo.bar;\n"
      "import foo.bar.Data;\n"
      "// commented /* @hide */\n"
      "interface IFoo {\n"
      "    /* @hide applied \n"
      "       @deprecated use foo2 */\n"
      "    int foo(out int[] a, String b, boolean c, inout List<String> d);\n"
      "    int foo2(@utf8InCpp String x, inout List<String> y);\n"
      "    IFoo foo3(IFoo foo);\n"
      "    Data getData();\n"
      "    // @hide not applied\n"
      "    /** blahblah\n"
      "        @deprecated\n"
      "          reason why... */\n"
      "    const int A = 1;\n"
      "    // @deprecated tags in line comments are ignored\n"
      "    const String STR = \"Hello\";\n"
      "}\n");
  io_delegate_.SetFileContents("foo/bar/Data.aidl",
                               "package foo.bar;\n"
                               "import foo.bar.IFoo;\n"
                               "/* @hide*/\n"
                               "parcelable Data {\n"
                               "   // @hide\n"
                               "   int x = 10;\n"
                               "   // @hide\n"
                               "   int y;\n"
                               "   /*@hide2*/\n"
                               "   IFoo foo;\n"
                               "   // Ignore @hide property in line comment\n"
                               "   @nullable String[] c;\n"
                               "}\n");
  io_delegate_.SetFileContents("api.aidl", "");
  vector<string> args = {"aidl", "--dumpapi", "--out=dump", "--include=.",
                         "foo/bar/IFoo.aidl", "foo/bar/Data.aidl"};
  Options options = Options::From(args);
  bool result = dump_api(options, io_delegate_);
  ASSERT_TRUE(result);
  string actual;
  EXPECT_TRUE(io_delegate_.GetWrittenContents("dump/foo/bar/IFoo.aidl", &actual));
  EXPECT_EQ(string(kPreamble).append(R"(package foo.bar;
interface IFoo {
  /**
   * @hide
   * @deprecated use foo2
   */
  int foo(out int[] a, String b, boolean c, inout List<String> d);
  int foo2(@utf8InCpp String x, inout List<String> y);
  foo.bar.IFoo foo3(foo.bar.IFoo foo);
  foo.bar.Data getData();
  /**
   * @deprecated reason why...
   */
  const int A = 1;
  const String STR = "Hello";
}
)"),
            actual);

  EXPECT_TRUE(io_delegate_.GetWrittenContents("dump/foo/bar/Data.aidl", &actual));
  EXPECT_EQ(string(kPreamble).append(R"(package foo.bar;
/* @hide */
parcelable Data {
  int x = 10;
  int y;
  foo.bar.IFoo foo;
  @nullable String[] c;
}
)"),
            actual);
}

TEST_F(AidlTest, ApiDumpWithManualIds) {
  io_delegate_.SetFileContents(
      "foo/bar/IFoo.aidl",
      "package foo.bar;\n"
      "interface IFoo {\n"
      "    int foo() = 1;\n"
      "    int bar() = 2;\n"
      "    int baz() = 10;\n"
      "}\n");

  vector<string> args = {"aidl", "--dumpapi", "-o dump", "foo/bar/IFoo.aidl"};
  Options options = Options::From(args);
  bool result = dump_api(options, io_delegate_);
  ASSERT_TRUE(result);
  string actual;
  EXPECT_TRUE(io_delegate_.GetWrittenContents("dump/foo/bar/IFoo.aidl", &actual));
  EXPECT_EQ(actual, string(kPreamble).append(R"(package foo.bar;
interface IFoo {
  int foo() = 1;
  int bar() = 2;
  int baz() = 10;
}
)"));
}

TEST_F(AidlTest, ApiDumpWithManualIdsOnlyOnSomeMethods) {
  const string expected_stderr =
      "ERROR: foo/bar/IFoo.aidl:4.8-12: You must either assign id's to all methods or to none of "
      "them.\n";
  io_delegate_.SetFileContents(
      "foo/bar/IFoo.aidl",
      "package foo.bar;\n"
      "interface IFoo {\n"
      "    int foo() = 1;\n"
      "    int bar();\n"
      "    int baz() = 10;\n"
      "}\n");

  vector<string> args = {"aidl", "--dumpapi", "-o dump", "foo/bar/IFoo.aidl"};
  Options options = Options::From(args);
  CaptureStderr();
  EXPECT_FALSE(dump_api(options, io_delegate_));
  EXPECT_EQ(expected_stderr, GetCapturedStderr());
}

TEST_F(AidlTest, ApiDumpConstWithAnnotation) {
  io_delegate_.SetFileContents("foo/bar/IFoo.aidl",
                               "package foo.bar;\n"
                               "interface IFoo {\n"
                               "    @utf8InCpp String foo();\n"
                               "    const @utf8InCpp String bar = \"bar\";\n"
                               "}\n");

  vector<string> args = {"aidl", "--dumpapi", "-o dump", "foo/bar/IFoo.aidl"};
  Options options = Options::From(args);
  CaptureStderr();
  EXPECT_TRUE(dump_api(options, io_delegate_));
  EXPECT_EQ("", GetCapturedStderr());
  string actual;
  EXPECT_TRUE(io_delegate_.GetWrittenContents("dump/foo/bar/IFoo.aidl", &actual));
  EXPECT_EQ(string(kPreamble).append(R"(package foo.bar;
interface IFoo {
  @utf8InCpp String foo();
  const @utf8InCpp String bar = "bar";
}
)"),
            actual);
}

TEST_F(AidlTest, ApiDumpWithEnums) {
  io_delegate_.SetFileContents("foo/bar/Enum.aidl",
                               "package foo.bar;\n"
                               "enum Enum {\n"
                               "    FOO,\n"
                               "    BAR = FOO + 1,\n"
                               "}\n");

  vector<string> args = {"aidl", "--dumpapi", "-I . ", "-o dump", "foo/bar/Enum.aidl"};
  Options options = Options::From(args);
  CaptureStderr();
  EXPECT_TRUE(dump_api(options, io_delegate_));
  EXPECT_EQ("", GetCapturedStderr());
  string actual;
  EXPECT_TRUE(io_delegate_.GetWrittenContents("dump/foo/bar/Enum.aidl", &actual));
  EXPECT_EQ(string(kPreamble).append("package foo.bar;\n"
                                     "enum Enum {\n"
                                     "  FOO = 0,\n"
                                     "  BAR = 1,\n"
                                     "}\n"),
            actual);
}

TEST_F(AidlTest, ApiDumpWithEnumDefaultValues) {
  io_delegate_.SetFileContents("foo/bar/Enum.aidl",
                               "package foo.bar;\n"
                               "enum Enum {\n"
                               "    FOO,\n"
                               "}\n");
  io_delegate_.SetFileContents("foo/bar/Foo.aidl",
                               "package foo.bar;\n"
                               "import foo.bar.Enum;\n"
                               "parcelable Foo {\n"
                               "    Enum e = Enum.FOO;\n"
                               "}\n");

  vector<string> args = {"aidl", "--dumpapi", "-I . ", "-o dump", "foo/bar/Foo.aidl"};
  Options options = Options::From(args);
  CaptureStderr();
  EXPECT_TRUE(dump_api(options, io_delegate_));
  EXPECT_EQ("", GetCapturedStderr());
  string actual;
  EXPECT_TRUE(io_delegate_.GetWrittenContents("dump/foo/bar/Foo.aidl", &actual));
  EXPECT_EQ(string(kPreamble).append("package foo.bar;\n"
                                     "parcelable Foo {\n"
                                     "  foo.bar.Enum e = foo.bar.Enum.FOO;\n"
                                     "}\n"),
            actual);
}

TEST_F(AidlTest, ApiDumpWithGenerics) {
  io_delegate_.SetFileContents("foo/bar/Foo.aidl",
                               "package foo.bar;\n"
                               "parcelable Foo<T, U> {\n"
                               "}\n");

  vector<string> args = {"aidl", "--dumpapi", "-I . ", "-o dump", "foo/bar/Foo.aidl"};
  Options options = Options::From(args);
  CaptureStderr();
  EXPECT_TRUE(dump_api(options, io_delegate_));
  EXPECT_EQ("", GetCapturedStderr());
  string actual;
  EXPECT_TRUE(io_delegate_.GetWrittenContents("dump/foo/bar/Foo.aidl", &actual));
  EXPECT_EQ(string(kPreamble).append("package foo.bar;\n"
                                     "parcelable Foo<T, U> {\n"
                                     "}\n"),
            actual);
}

TEST_F(AidlTest, CheckNumGenericTypeSecifier) {
  const string expected_list_stderr =
      "ERROR: p/IFoo.aidl:1.37-41: List can only have one type parameter, but got: "
      "'List<String,String>'\n";
  const string expected_map_stderr =
      "ERROR: p/IFoo.aidl:1.37-40: Map must have 0 or 2 type parameters, but got 'Map<String>'\n";
  Options options = Options::From("aidl p/IFoo.aidl IFoo.java");
  io_delegate_.SetFileContents(options.InputFiles().front(),
                               "package p; interface IFoo {"
                               "void foo(List<String, String> a);}");
  CaptureStderr();
  EXPECT_NE(0, ::android::aidl::compile_aidl(options, io_delegate_));
  EXPECT_EQ(expected_list_stderr, GetCapturedStderr());

  io_delegate_.SetFileContents(options.InputFiles().front(),
                               "package p; interface IFoo {"
                               "void foo(Map<String> a);}");
  CaptureStderr();
  EXPECT_NE(0, ::android::aidl::compile_aidl(options, io_delegate_));
  EXPECT_EQ(expected_map_stderr, GetCapturedStderr());
}

TEST_F(AidlTest, CheckTypeParameterInMapType) {
  const string expected_stderr =
      "ERROR: p/IFoo.aidl:1.28-31: The type of key in map must be String, but it is 'p.Bar'\n";
  Options options = Options::From("aidl -I p p/IFoo.aidl");
  io_delegate_.SetFileContents("p/Bar.aidl", "package p; parcelable Bar { String s; }");

  io_delegate_.SetFileContents("p/IFoo.aidl",
                               "package p; interface IFoo {"
                               "Map<String, Bar> foo();}");
  EXPECT_EQ(0, ::android::aidl::compile_aidl(options, io_delegate_));

  io_delegate_.SetFileContents("p/IFoo.aidl",
                               "package p; interface IFoo {"
                               "Map<Bar, Bar> foo();}");
  CaptureStderr();
  EXPECT_NE(0, ::android::aidl::compile_aidl(options, io_delegate_));
  EXPECT_EQ(expected_stderr, GetCapturedStderr());

  io_delegate_.SetFileContents("p/IFoo.aidl",
                               "package p; interface IFoo {"
                               "Map<String, String> foo();}");
  EXPECT_EQ(0, ::android::aidl::compile_aidl(options, io_delegate_));

  io_delegate_.SetFileContents("p/IFoo.aidl",
                               "package p; interface IFoo {"
                               "Map<String, ParcelFileDescriptor> foo();}");
  EXPECT_EQ(0, ::android::aidl::compile_aidl(options, io_delegate_));
}

TEST_F(AidlTest, WrongGenericType) {
  const string expected_stderr = "ERROR: p/IFoo.aidl:1.28-34: String is not a generic type.\n";
  Options options = Options::From("aidl p/IFoo.aidl IFoo.java");
  io_delegate_.SetFileContents(options.InputFiles().front(),
                               "package p; interface IFoo {"
                               "String<String> foo(); }");
  CaptureStderr();
  EXPECT_NE(0, ::android::aidl::compile_aidl(options, io_delegate_));
  EXPECT_EQ(expected_stderr, GetCapturedStderr());
}

TEST_F(AidlTest, UserDefinedUnstructuredGenericParcelableType) {
  Options optionsForParcelable = Options::From("aidl -I p p/Bar.aidl");
  io_delegate_.SetFileContents("p/Bar.aidl", "package p; parcelable Bar<T, T>;");
  CaptureStderr();
  EXPECT_NE(0, ::android::aidl::compile_aidl(optionsForParcelable, io_delegate_));
  EXPECT_EQ("ERROR: p/Bar.aidl:1.22-26: Every type parameter should be unique.\n",
            GetCapturedStderr());

  Options options = Options::From("aidl -I p p/IFoo.aidl");
  io_delegate_.SetFileContents("p/Bar.aidl", "package p; parcelable Bar;");
  io_delegate_.SetFileContents("p/IFoo.aidl",
                               "package p; interface IFoo {"
                               "Bar<String, String> foo();}");
  CaptureStderr();
  EXPECT_NE(0, ::android::aidl::compile_aidl(options, io_delegate_));
  EXPECT_EQ("ERROR: p/IFoo.aidl:1.28-31: p.Bar is not a generic type.\n", GetCapturedStderr());
  io_delegate_.SetFileContents("p/Bar.aidl", "package p; parcelable Bar<T>;");
  CaptureStderr();
  EXPECT_NE(0, ::android::aidl::compile_aidl(options, io_delegate_));
  EXPECT_EQ("ERROR: p/IFoo.aidl:1.28-31: p.Bar must have 1 type parameters, but got 2\n",
            GetCapturedStderr());
  io_delegate_.SetFileContents("p/Bar.aidl", "package p; parcelable Bar<T, V>;");
  EXPECT_EQ(0, ::android::aidl::compile_aidl(options, io_delegate_));
  io_delegate_.SetFileContents("p/IFoo.aidl",
                               "package p; interface IFoo {"
                               "Bar<String, ParcelFileDescriptor> foo();}");
  EXPECT_EQ(0, ::android::aidl::compile_aidl(options, io_delegate_));

  io_delegate_.SetFileContents("p/IFoo.aidl",
                               "package p; interface IFoo {"
                               "Bar<int, long> foo();}");

  io_delegate_.SetFileContents("p/IFoo.aidl",
                               "package p; interface IFoo {"
                               "Bar<int[], long[]> foo();}");

  EXPECT_EQ(0, ::android::aidl::compile_aidl(options, io_delegate_));
}

TEST_F(AidlTest, FailOnMultipleTypesInSingleFile) {
  std::vector<std::string> rawOptions{"aidl --lang=java -o out foo/bar/Foo.aidl",
                                      "aidl --lang=cpp -o out -h out/include foo/bar/Foo.aidl",
                                      "aidl --lang=rust -o out foo/bar/Foo.aidl"};
  for (const auto& rawOption : rawOptions) {
    string expected_stderr =
        "ERROR: foo/bar/Foo.aidl:3.1-10: You must declare only one type per file.\n";
    Options options = Options::From(rawOption);
    io_delegate_.SetFileContents(options.InputFiles().front(),
                                 "package foo.bar;\n"
                                 "interface IFoo1 { int foo(); }\n"
                                 "interface IFoo2 { int foo(); }\n"
                                 "parcelable Data1 { int a; int b;}\n"
                                 "parcelable Data2 { int a; int b;}\n");
    CaptureStderr();
    EXPECT_NE(0, ::android::aidl::compile_aidl(options, io_delegate_));
    EXPECT_EQ(expected_stderr, GetCapturedStderr());

    io_delegate_.SetFileContents(options.InputFiles().front(),
                                 "package foo.bar;\n"
                                 "interface IFoo1 { int foo(); }\n"
                                 "interface IFoo2 { int foo(); }\n");
    CaptureStderr();
    EXPECT_NE(0, ::android::aidl::compile_aidl(options, io_delegate_));
    EXPECT_EQ(expected_stderr, GetCapturedStderr());

    expected_stderr = "ERROR: foo/bar/Foo.aidl:3.11-17: You must declare only one type per file.\n";
    io_delegate_.SetFileContents(options.InputFiles().front(),
                                 "package foo.bar;\n"
                                 "parcelable Data1 { int a; int b;}\n"
                                 "parcelable Data2 { int a; int b;}\n");
    CaptureStderr();
    EXPECT_NE(0, ::android::aidl::compile_aidl(options, io_delegate_));
    EXPECT_EQ(expected_stderr, GetCapturedStderr());
  }
}

TEST_P(AidlTest, FailParseOnEmptyFile) {
  const string contents = "";
  const string expected_stderr = "ERROR: a/IFoo.aidl:1.1-1: syntax error, unexpected $end\n";
  CaptureStderr();
  EXPECT_EQ(nullptr, Parse("a/IFoo.aidl", contents, typenames_, GetLanguage()));
  EXPECT_EQ(expected_stderr, GetCapturedStderr());
}

TEST_F(AidlTest, MultipleInputFiles) {
  Options options = Options::From(
      "aidl --lang=java -o out -I . foo/bar/IFoo.aidl foo/bar/Data.aidl");

  io_delegate_.SetFileContents(options.InputFiles().at(0),
      "package foo.bar;\n"
      "import foo.bar.Data;\n"
      "interface IFoo { Data getData(); }\n");

  io_delegate_.SetFileContents(options.InputFiles().at(1),
        "package foo.bar;\n"
        "import foo.bar.IFoo;\n"
        "parcelable Data { IFoo foo; }\n");

  EXPECT_EQ(0, ::android::aidl::compile_aidl(options, io_delegate_));

  string content;
  for (const auto file : {
    "out/foo/bar/IFoo.java", "out/foo/bar/Data.java"}) {
    content.clear();
    EXPECT_TRUE(io_delegate_.GetWrittenContents(file, &content));
    EXPECT_FALSE(content.empty());
  }
}

TEST_F(AidlTest, MultipleInputFilesCpp) {
  Options options = Options::From("aidl --lang=cpp -o out -h out/include "
      "-I . foo/bar/IFoo.aidl foo/bar/Data.aidl");

  io_delegate_.SetFileContents(options.InputFiles().at(0),
      "package foo.bar;\n"
      "import foo.bar.Data;\n"
      "interface IFoo { Data getData(); }\n");

  io_delegate_.SetFileContents(options.InputFiles().at(1),
        "package foo.bar;\n"
        "import foo.bar.IFoo;\n"
        "parcelable Data { IFoo foo; }\n");

  EXPECT_EQ(0, ::android::aidl::compile_aidl(options, io_delegate_));

  string content;
  for (const auto file : {
    "out/foo/bar/IFoo.cpp", "out/foo/bar/Data.cpp",
    "out/include/foo/bar/IFoo.h", "out/include/foo/bar/Data.h",
    "out/include/foo/bar/BpFoo.h", "out/include/foo/bar/BpData.h",
    "out/include/foo/bar/BnFoo.h", "out/include/foo/bar/BnData.h"}) {
    content.clear();
    EXPECT_TRUE(io_delegate_.GetWrittenContents(file, &content));
    EXPECT_FALSE(content.empty());
  }
}

TEST_F(AidlTest, MultipleInputFilesRust) {
  Options options =
      Options::From("aidl --lang=rust -o out -I . foo/bar/IFoo.aidl foo/bar/Data.aidl");

  io_delegate_.SetFileContents(options.InputFiles().at(0),
                               "package foo.bar;\n"
                               "import foo.bar.Data;\n"
                               "interface IFoo { Data getData(); }\n");

  io_delegate_.SetFileContents(options.InputFiles().at(1),
                               "package foo.bar;\n"
                               "import foo.bar.IFoo;\n"
                               "parcelable Data { IFoo foo; }\n");

  EXPECT_EQ(0, ::android::aidl::compile_aidl(options, io_delegate_));

  string content;
  for (const auto file : {"out/foo/bar/IFoo.rs", "out/foo/bar/Data.rs"}) {
    content.clear();
    EXPECT_TRUE(io_delegate_.GetWrittenContents(file, &content));
    EXPECT_FALSE(content.empty());
  }
}

TEST_F(AidlTest, ConflictWithMetaTransactionGetVersion) {
  const string expected_stderr =
      "ERROR: p/IFoo.aidl:1.31-51:  method getInterfaceVersion() is reserved for internal use.\n";
  Options options = Options::From("aidl --lang=java -o place/for/output p/IFoo.aidl");
  // int getInterfaceVersion() is one of the meta transactions
  io_delegate_.SetFileContents(options.InputFiles().front(),
                               "package p; interface IFoo {"
                               "int getInterfaceVersion(); }");
  CaptureStderr();
  EXPECT_NE(0, ::android::aidl::compile_aidl(options, io_delegate_));
  EXPECT_EQ(expected_stderr, GetCapturedStderr());
}

TEST_F(AidlTest, ConflictWithSimilarMetaTransaction) {
  // boolean getInterfaceVersion() is not a meta transaction, but should be
  // prevented because return type is not part of a method signature
  const string expected_stderr =
      "ERROR: p/IFoo.aidl:1.35-55:  method getInterfaceVersion() is reserved for internal use.\n";
  Options options = Options::From("aidl --lang=java -o place/for/output p/IFoo.aidl");
  io_delegate_.SetFileContents(options.InputFiles().front(),
                               "package p; interface IFoo {"
                               "boolean getInterfaceVersion(); }");
  CaptureStderr();
  EXPECT_NE(0, ::android::aidl::compile_aidl(options, io_delegate_));
  EXPECT_EQ(expected_stderr, GetCapturedStderr());
}

TEST_F(AidlTest, ConflictWithMetaTransactionGetName) {
  // this is another reserved name
  const string expected_stderr =
      "ERROR: p/IFoo.aidl:1.34-53:  method getTransactionName(int) is reserved for internal use.\n";
  Options options = Options::From("aidl --lang=java -o place/for/output p/IFoo.aidl");
  io_delegate_.SetFileContents(options.InputFiles().front(),
                               "package p; interface IFoo {"
                               "String getTransactionName(int code); }");
  CaptureStderr();
  EXPECT_NE(0, ::android::aidl::compile_aidl(options, io_delegate_));
  EXPECT_EQ(expected_stderr, GetCapturedStderr());

  // this is not a meta interface method as it differs type arguments
  io_delegate_.SetFileContents(options.InputFiles().front(),
                               "package p; interface IFoo {"
                               "String getTransactionName(); }");
  EXPECT_EQ(0, ::android::aidl::compile_aidl(options, io_delegate_));
}

TEST_F(AidlTest, CheckApiForEquality) {
  CaptureStderr();
  Options options = Options::From("aidl --checkapi=equal old new");

  io_delegate_.SetFileContents("old/p/IFoo.aidl",
                               "package p; interface IFoo{ @utf8InCpp @nullable String foo();}");
  io_delegate_.SetFileContents("new/p/IFoo.aidl",
                               "package p; interface IFoo{ @utf8InCpp String foo();}");

  EXPECT_FALSE(::android::aidl::check_api(options, io_delegate_));
  EXPECT_THAT(GetCapturedStderr(), HasSubstr("+  @utf8InCpp String foo();"));
}

TEST_F(AidlTest, DifferentOrderAnnotationsInCheckAPI) {
  Options options = Options::From("aidl --checkapi old new");
  io_delegate_.SetFileContents("old/p/IFoo.aidl",
                               "package p; interface IFoo{ @utf8InCpp @nullable String foo();}");
  io_delegate_.SetFileContents("new/p/IFoo.aidl",
                               "package p; interface IFoo{ @nullable @utf8InCpp String foo();}");

  EXPECT_TRUE(::android::aidl::check_api(options, io_delegate_));
}

TEST_F(AidlTest, SuccessOnIdenticalApiDumps) {
  Options options = Options::From("aidl --checkapi old new");
  io_delegate_.SetFileContents("old/p/IFoo.aidl", "package p; interface IFoo{ void foo();}");
  io_delegate_.SetFileContents("new/p/IFoo.aidl", "package p; interface IFoo{ void foo();}");

  EXPECT_TRUE(::android::aidl::check_api(options, io_delegate_));
}

TEST_F(AidlTest, CheckApi_EnumFieldsWithDefaultValues) {
  Options options = Options::From("aidl --checkapi old new");
  const string foo_definition = "package p; parcelable Foo{ p.Enum e = p.Enum.FOO; }";
  const string enum_definition = "package p; enum Enum { FOO }";
  io_delegate_.SetFileContents("old/p/Foo.aidl", foo_definition);
  io_delegate_.SetFileContents("old/p/Enum.aidl", enum_definition);
  io_delegate_.SetFileContents("new/p/Foo.aidl", foo_definition);
  io_delegate_.SetFileContents("new/p/Enum.aidl", enum_definition);

  EXPECT_TRUE(::android::aidl::check_api(options, io_delegate_));
}

TEST_F(AidlTest, CheckApiEqual_EnumFieldsWithDefaultValues) {
  Options options = Options::From("aidl --checkapi=equal old new");
  const string foo_definition = "package p; parcelable Foo{ p.Enum e = p.Enum.FOO; }";
  const string enum_definition = "package p; enum Enum { FOO }";
  io_delegate_.SetFileContents("old/p/Foo.aidl", foo_definition);
  io_delegate_.SetFileContents("old/p/Enum.aidl", enum_definition);
  io_delegate_.SetFileContents("new/p/Foo.aidl", foo_definition);
  io_delegate_.SetFileContents("new/p/Enum.aidl", enum_definition);
  CaptureStderr();
  EXPECT_TRUE(::android::aidl::check_api(options, io_delegate_));
  EXPECT_EQ("", GetCapturedStderr());
}

class AidlTestCompatibleChanges : public AidlTest {
 protected:
  Options options_ = Options::From("aidl --checkapi old new");
};

TEST_F(AidlTestCompatibleChanges, NewType) {
  io_delegate_.SetFileContents("old/p/IFoo.aidl",
                               "package p;"
                               "interface IFoo {"
                               "  void foo(int a);"
                               "}");
  io_delegate_.SetFileContents("new/p/IFoo.aidl",
                               "package p;"
                               "interface IFoo {"
                               "  void foo(int a);"
                               "}");
  io_delegate_.SetFileContents("new/p/IBar.aidl",
                               "package p;"
                               "interface IBar {"
                               "  void bar();"
                               "}");
  EXPECT_TRUE(::android::aidl::check_api(options_, io_delegate_));
}

TEST_F(AidlTestCompatibleChanges, NewMethod) {
  io_delegate_.SetFileContents("old/p/IFoo.aidl",
                               "package p;"
                               "interface IFoo {"
                               "  void foo(int a);"
                               "}");
  io_delegate_.SetFileContents("new/p/IFoo.aidl",
                               "package p;"
                               "interface IFoo {"
                               "  void foo(int a);"
                               "  void bar();"
                               "  void baz(in List<IFoo> arg);"
                               "}");
  EXPECT_TRUE(::android::aidl::check_api(options_, io_delegate_));
}

TEST_F(AidlTestCompatibleChanges, NewField) {
  io_delegate_.SetFileContents("old/p/Data.aidl",
                               "package p;"
                               "parcelable Data {"
                               "  int foo;"
                               "}");
  io_delegate_.SetFileContents("new/p/Data.aidl",
                               "package p;"
                               "parcelable Data {"
                               "  int foo;"
                               "  int bar = 0;"
                               "  @nullable List<Data> list;"
                               "}");
  EXPECT_TRUE(::android::aidl::check_api(options_, io_delegate_));
}

TEST_F(AidlTestCompatibleChanges, NewField2) {
  io_delegate_.SetFileContents("old/p/Data.aidl",
                               "package p;"
                               "parcelable Data {"
                               "}");
  io_delegate_.SetFileContents("new/p/Data.aidl",
                               "package p;"
                               "parcelable Data {"
                               "  int foo = 0;"
                               "}");
  EXPECT_TRUE(::android::aidl::check_api(options_, io_delegate_));
}

TEST_F(AidlTestCompatibleChanges, NewEnumerator) {
  io_delegate_.SetFileContents("old/p/Enum.aidl",
                               "package p;"
                               "enum Enum {"
                               "  FOO = 1,"
                               "}");
  io_delegate_.SetFileContents("new/p/Enum.aidl",
                               "package p;"
                               "enum Enum {"
                               "  FOO = 1,"
                               "  BAR = 2,"
                               "}");
  EXPECT_TRUE(::android::aidl::check_api(options_, io_delegate_));
}

TEST_F(AidlTestCompatibleChanges, ReorderedEnumerator) {
  io_delegate_.SetFileContents("old/p/Enum.aidl",
                               "package p;"
                               "enum Enum {"
                               "  FOO = 1,"
                               "  BAR = 2,"
                               "}");
  io_delegate_.SetFileContents("new/p/Enum.aidl",
                               "package p;"
                               "enum Enum {"
                               "  BAR = 2,"
                               "  FOO = 1,"
                               "}");
  EXPECT_TRUE(::android::aidl::check_api(options_, io_delegate_));
}

TEST_F(AidlTestCompatibleChanges, NewUnionField) {
  io_delegate_.SetFileContents("old/p/Union.aidl",
                               "package p;"
                               "union Union {"
                               "  String foo;"
                               "}");
  io_delegate_.SetFileContents("new/p/Union.aidl",
                               "package p;"
                               "union Union {"
                               "  String foo;"
                               "  int num;"
                               "}");
  EXPECT_TRUE(::android::aidl::check_api(options_, io_delegate_));
}

TEST_F(AidlTestCompatibleChanges, NewPackage) {
  io_delegate_.SetFileContents("old/p/IFoo.aidl",
                               "package p;"
                               "interface IFoo {"
                               "  void foo(int a);"
                               "}");
  io_delegate_.SetFileContents("old/p/Data.aidl",
                               "package p;"
                               "parcelable Data {"
                               "  int foo;"
                               "}");
  io_delegate_.SetFileContents("new/p/IFoo.aidl",
                               "package p;"
                               "interface IFoo {"
                               "  void foo(int a);"
                               "}");
  io_delegate_.SetFileContents("new/p/Data.aidl",
                               "package p;"
                               "parcelable Data {"
                               "  int foo;"
                               "}");
  io_delegate_.SetFileContents("new/q/IFoo.aidl",
                               "package q;"
                               "interface IFoo {"
                               "  void foo(int a);"
                               "}");
  io_delegate_.SetFileContents("new/q/Data.aidl",
                               "package q;"
                               "parcelable Data {"
                               "  int foo;"
                               "}");
  EXPECT_TRUE(::android::aidl::check_api(options_, io_delegate_));
}

TEST_F(AidlTestCompatibleChanges, ArgNameChange) {
  io_delegate_.SetFileContents("old/p/IFoo.aidl",
                               "package p;"
                               "interface IFoo {"
                               "  void foo(int a);"
                               "}");
  io_delegate_.SetFileContents("new/p/IFoo.aidl",
                               "package p;"
                               "interface IFoo {"
                               "  void foo(int b);"
                               "}");
  EXPECT_TRUE(::android::aidl::check_api(options_, io_delegate_));
}

TEST_F(AidlTestCompatibleChanges, AddedConstValue) {
  io_delegate_.SetFileContents("old/p/I.aidl",
                               "package p; interface I {"
                               "const int A = 1; }");
  io_delegate_.SetFileContents("new/p/I.aidl",
                               "package p ; interface I {"
                               "const int A = 1; const int B = 2;}");
  EXPECT_TRUE(::android::aidl::check_api(options_, io_delegate_));
}

TEST_F(AidlTestCompatibleChanges, ChangedConstValueOrder) {
  io_delegate_.SetFileContents("old/p/I.aidl",
                               "package p; interface I {"
                               "const int A = 1; const int B = 2;}");
  io_delegate_.SetFileContents("new/p/I.aidl",
                               "package p ; interface I {"
                               "const int B = 2; const int A = 1;}");
  EXPECT_TRUE(::android::aidl::check_api(options_, io_delegate_));
}

TEST_F(AidlTestCompatibleChanges, ReorderedAnnatations) {
  io_delegate_.SetFileContents("old/p/Foo.aidl",
                               "package p;"
                               "@JavaPassthrough(annotation=\"Alice\")"
                               "@JavaPassthrough(annotation=\"Bob\")"
                               "parcelable Foo {}");
  io_delegate_.SetFileContents("new/p/Foo.aidl",
                               "package p;"
                               "@JavaPassthrough(annotation=\"Bob\")"
                               "@JavaPassthrough(annotation=\"Alice\")"
                               "parcelable Foo {}");
  EXPECT_TRUE(::android::aidl::check_api(options_, io_delegate_));
}

TEST_F(AidlTestCompatibleChanges, OkayToDeprecate) {
  io_delegate_.SetFileContents("old/p/Foo.aidl",
                               "package p;"
                               "parcelable Foo {}");
  io_delegate_.SetFileContents("new/p/Foo.aidl",
                               "package p;"
                               "@JavaPassthrough(annotation=\"@Deprecated\")"
                               "parcelable Foo {}");
  EXPECT_TRUE(::android::aidl::check_api(options_, io_delegate_));
}

TEST_F(AidlTestCompatibleChanges, NewFieldOfNewType) {
  io_delegate_.SetFileContents("old/p/Data.aidl",
                               "package p;"
                               "parcelable Data {"
                               "  int num;"
                               "}");
  io_delegate_.SetFileContents(
      "new/p/Data.aidl",
      "package p;"
      "parcelable Data {"
      "  int num;"
      "  p.Enum e;"  // this is considered as valid since 0(enum default) is valid for "Enum" type
      "}");
  io_delegate_.SetFileContents("new/p/Enum.aidl",
                               "package p;"
                               "enum Enum {"
                               "  FOO = 0,"
                               "  BAR = 1,"
                               "}");
  EXPECT_TRUE(::android::aidl::check_api(options_, io_delegate_));
}

TEST_F(AidlTestCompatibleChanges, CompatibleExplicitDefaults) {
  io_delegate_.SetFileContents("old/p/Data.aidl",
                               "package p;\n"
                               "parcelable Data {\n"
                               "  p.Enum e;\n"
                               "}");
  io_delegate_.SetFileContents("old/p/Enum.aidl",
                               "package p;\n"
                               "enum Enum {\n"
                               "  FOO = 0,\n"
                               "  BAR = 1,\n"
                               "}");
  io_delegate_.SetFileContents("new/p/Data.aidl",
                               "package p;\n"
                               "parcelable Data {\n"
                               "  p.Enum e = p.Enum.FOO;\n"
                               "}");
  io_delegate_.SetFileContents("new/p/Enum.aidl",
                               "package p;\n"
                               "enum Enum {\n"
                               "  FOO = 0,\n"
                               "  BAR = 1,\n"
                               "}");
  EXPECT_TRUE(::android::aidl::check_api(options_, io_delegate_));
}

class AidlTestIncompatibleChanges : public AidlTest {
 protected:
  Options options_ = Options::From("aidl --checkapi old new");
};

TEST_F(AidlTestIncompatibleChanges, RemovedType) {
  const string expected_stderr = "ERROR: old/p/IFoo.aidl:1.11-20: Removed type: p.IFoo\n";
  io_delegate_.SetFileContents("old/p/IFoo.aidl",
                               "package p;"
                               "interface IFoo {"
                               "  void foo(in String[] str);"
                               "  void bar(@utf8InCpp String str);"
                               "}");
  CaptureStderr();
  EXPECT_FALSE(::android::aidl::check_api(options_, io_delegate_));
  EXPECT_EQ(expected_stderr, GetCapturedStderr());
}

TEST_F(AidlTestIncompatibleChanges, RemovedMethod) {
  const string expected_stderr =
      "ERROR: old/p/IFoo.aidl:1.61-65: Removed or changed method: p.IFoo.bar(String)\n";
  io_delegate_.SetFileContents("old/p/IFoo.aidl",
                               "package p;"
                               "interface IFoo {"
                               "  void foo(in String[] str);"
                               "  void bar(@utf8InCpp String str);"
                               "}");
  io_delegate_.SetFileContents("new/p/IFoo.aidl",
                               "package p;"
                               "interface IFoo {"
                               "  void foo(in String[] str);"
                               "}");
  CaptureStderr();
  EXPECT_FALSE(::android::aidl::check_api(options_, io_delegate_));
  EXPECT_EQ(expected_stderr, GetCapturedStderr());
}

TEST_F(AidlTestIncompatibleChanges, UntypedListInInterface) {
  const string expected_stderr =
      "ERROR: new/p/IFoo.aidl:1.61-65: "
      "Encountered an untyped List or Map. The use of untyped List/Map is "
      "prohibited because it is not guaranteed that the objects in the list are recognizable in "
      "the receiving side. Consider switching to an array or a generic List/Map.\n"
      "ERROR: new/p/IFoo.aidl: Failed to read.\n";
  io_delegate_.SetFileContents("old/p/IFoo.aidl",
                               "package p;"
                               "interface IFoo {"
                               "  void foo(in String[] str);"
                               "}");
  io_delegate_.SetFileContents("new/p/IFoo.aidl",
                               "package p;"
                               "interface IFoo {"
                               "  void foo(in String[] str);"
                               "  void bar(in List arg);"
                               "}");
  CaptureStderr();
  EXPECT_FALSE(::android::aidl::check_api(options_, io_delegate_));
  EXPECT_EQ(expected_stderr, GetCapturedStderr());
}

TEST_F(AidlTestCompatibleChanges, UntypedListInParcelable) {
  const string expected_stderr =
      "ERROR: new/p/Data.aidl:1.54-59: "
      "Encountered an untyped List or Map. The use of untyped List/Map is "
      "prohibited because it is not guaranteed that the objects in the list are recognizable in "
      "the receiving side. Consider switching to an array or a generic List/Map.\n"
      "ERROR: new/p/Data.aidl: Failed to read.\n";
  io_delegate_.SetFileContents("old/p/Data.aidl",
                               "package p;"
                               "parcelable Data {"
                               "  int foo;"
                               "}");
  io_delegate_.SetFileContents("new/p/Data.aidl",
                               "package p;"
                               "parcelable Data {"
                               "  int foo;"
                               "  @nullable List list;"
                               "}");
  CaptureStderr();
  EXPECT_FALSE(::android::aidl::check_api(options_, io_delegate_));
  EXPECT_EQ(expected_stderr, GetCapturedStderr());
}

TEST_F(AidlTestIncompatibleChanges, RemovedField) {
  const string expected_stderr =
      "ERROR: new/p/Data.aidl:1.21-26: Number of fields in p.Data is reduced from 2 to 1.\n";
  io_delegate_.SetFileContents("old/p/Data.aidl",
                               "package p;"
                               "parcelable Data {"
                               "  int foo;"
                               "  int bar;"
                               "}");
  io_delegate_.SetFileContents("new/p/Data.aidl",
                               "package p;"
                               "parcelable Data {"
                               "  int foo;"
                               "}");
  CaptureStderr();
  EXPECT_FALSE(::android::aidl::check_api(options_, io_delegate_));
  EXPECT_EQ(expected_stderr, GetCapturedStderr());
}

TEST_F(AidlTestIncompatibleChanges, NewFieldWithNoDefault) {
  const string expected_stderr =
      "ERROR: new/p/Data.aidl:1.46-50: Field 'str' does not have a useful default in some "
      "backends. Please either provide a default value for this field or mark the field as "
      "@nullable. This value or a null value will be used automatically when an old version of "
      "this parcelable is sent to a process which understands a new version of this parcelable. In "
      "order to make sure your code continues to be backwards compatible, make sure the default or "
      "null value does not cause a semantic change to this parcelable.\n";
  io_delegate_.SetFileContents("old/p/Data.aidl",
                               "package p;"
                               "parcelable Data {"
                               "  int num;"
                               "}");
  io_delegate_.SetFileContents("new/p/Data.aidl",
                               "package p;"
                               "parcelable Data {"
                               "  int num;"
                               "  String str;"
                               "}");
  CaptureStderr();
  EXPECT_FALSE(::android::aidl::check_api(options_, io_delegate_));
  EXPECT_EQ(expected_stderr, GetCapturedStderr());
}

TEST_F(AidlTestIncompatibleChanges, NewFieldWithNonZeroEnum) {
  const string expected_stderr =
      "ERROR: new/p/Data.aidl:1.46-48: Field 'e' of enum 'Enum' can't be initialized as '0'. "
      "Please make sure 'Enum' has '0' as a valid value.\n";
  io_delegate_.SetFileContents("old/p/Data.aidl",
                               "package p;"
                               "parcelable Data {"
                               "  int num;"
                               "}");
  io_delegate_.SetFileContents("new/p/Data.aidl",
                               "package p;"
                               "parcelable Data {"
                               "  int num;"
                               "  p.Enum e;"
                               "}");
  io_delegate_.SetFileContents("new/p/Enum.aidl",
                               "package p;"
                               "enum Enum {"
                               "  FOO = 1,"
                               "  BAR = 2,"
                               "}");
  CaptureStderr();
  EXPECT_FALSE(::android::aidl::check_api(options_, io_delegate_));
  EXPECT_EQ(expected_stderr, GetCapturedStderr());
}

TEST_F(AidlTestIncompatibleChanges, RemovedEnumerator) {
  const string expected_stderr =
      "ERROR: new/p/Enum.aidl:1.15-20: Removed enumerator from p.Enum: FOO\n";
  io_delegate_.SetFileContents("old/p/Enum.aidl",
                               "package p;"
                               "enum Enum {"
                               "  FOO = 1,"
                               "  BAR = 2,"
                               "}");
  io_delegate_.SetFileContents("new/p/Enum.aidl",
                               "package p;"
                               "enum Enum {"
                               "  BAR = 2,"
                               "}");
  CaptureStderr();
  EXPECT_FALSE(::android::aidl::check_api(options_, io_delegate_));
  EXPECT_EQ(expected_stderr, GetCapturedStderr());
}

TEST_F(AidlTestIncompatibleChanges, RemovedUnionField) {
  const string expected_stderr =
      "ERROR: new/p/Union.aidl:1.16-22: Number of fields in p.Union is reduced from 2 to 1.\n";
  io_delegate_.SetFileContents("old/p/Union.aidl",
                               "package p;"
                               "union Union {"
                               "  String str;"
                               "  int num;"
                               "}");
  io_delegate_.SetFileContents("new/p/Union.aidl",
                               "package p;"
                               "union Union {"
                               "  String str;"
                               "}");
  CaptureStderr();
  EXPECT_FALSE(::android::aidl::check_api(options_, io_delegate_));
  EXPECT_EQ(expected_stderr, GetCapturedStderr());
}

TEST_F(AidlTestIncompatibleChanges, RenamedMethod) {
  const string expected_stderr =
      "ERROR: old/p/IFoo.aidl:1.61-65: Removed or changed method: p.IFoo.bar(String)\n";
  io_delegate_.SetFileContents("old/p/IFoo.aidl",
                               "package p;"
                               "interface IFoo {"
                               "  void foo(in String[] str);"
                               "  void bar(@utf8InCpp String str);"
                               "}");
  io_delegate_.SetFileContents("new/p/IFoo.aidl",
                               "package p;"
                               "interface IFoo {"
                               "  void foo(in String[] str);"
                               "  void bar2(@utf8InCpp String str);"
                               "}");
  CaptureStderr();
  EXPECT_FALSE(::android::aidl::check_api(options_, io_delegate_));
  EXPECT_EQ(expected_stderr, GetCapturedStderr());
}

TEST_F(AidlTestIncompatibleChanges, RenamedType) {
  const string expected_stderr = "ERROR: old/p/IFoo.aidl:1.11-20: Removed type: p.IFoo\n";
  io_delegate_.SetFileContents("old/p/IFoo.aidl",
                               "package p;"
                               "interface IFoo {"
                               "  void foo(in String[] str);"
                               "  void bar(@utf8InCpp String str);"
                               "}");
  io_delegate_.SetFileContents("new/p/IFoo2.aidl",
                               "package p;"
                               "interface IFoo2 {"
                               "  void foo(in String[] str);"
                               "  void bar(@utf8InCpp String str);"
                               "}");
  CaptureStderr();
  EXPECT_FALSE(::android::aidl::check_api(options_, io_delegate_));
  EXPECT_EQ(expected_stderr, GetCapturedStderr());
}

TEST_F(AidlTestIncompatibleChanges, ChangedEnumerator) {
  const string expected_stderr =
      "ERROR: new/p/Enum.aidl:1.15-20: Changed enumerator value: p.Enum::FOO from 1 to 3.\n";
  io_delegate_.SetFileContents("old/p/Enum.aidl",
                               "package p;"
                               "enum Enum {"
                               "  FOO = 1,"
                               "  BAR = 2,"
                               "}");
  io_delegate_.SetFileContents("new/p/Enum.aidl",
                               "package p;"
                               "enum Enum {"
                               "  FOO = 3,"
                               "  BAR = 2,"
                               "}");
  CaptureStderr();
  EXPECT_FALSE(::android::aidl::check_api(options_, io_delegate_));
  EXPECT_EQ(expected_stderr, GetCapturedStderr());
}

TEST_F(AidlTestIncompatibleChanges, ReorderedMethod) {
  const string expected_stderr =
      "ERROR: new/p/IFoo.aidl:1.67-71: Transaction ID changed: p.IFoo.foo(String[]) is changed "
      "from 0 to 1.\n"
      "ERROR: new/p/IFoo.aidl:1.33-37: Transaction ID changed: p.IFoo.bar(String) is changed from "
      "1 to 0.\n";
  io_delegate_.SetFileContents("old/p/IFoo.aidl",
                               "package p;"
                               "interface IFoo {"
                               "  void foo(in String[] str);"
                               "  void bar(@utf8InCpp String str);"
                               "}");
  io_delegate_.SetFileContents("new/p/IFoo.aidl",
                               "package p;"
                               "interface IFoo {"
                               "  void bar(@utf8InCpp String str);"
                               "  void foo(in String[] str);"
                               "}");
  CaptureStderr();
  EXPECT_FALSE(::android::aidl::check_api(options_, io_delegate_));
  EXPECT_EQ(expected_stderr, GetCapturedStderr());
}

TEST_F(AidlTestIncompatibleChanges, ReorderedField) {
  const string expected_stderr =
      "ERROR: new/p/Data.aidl:1.33-37: Reordered bar from 1 to 0.\n"
      "ERROR: new/p/Data.aidl:1.43-47: Reordered foo from 0 to 1.\n";
  io_delegate_.SetFileContents("old/p/Data.aidl",
                               "package p;"
                               "parcelable Data {"
                               "  int foo;"
                               "  int bar;"
                               "}");
  io_delegate_.SetFileContents("new/p/Data.aidl",
                               "package p;"
                               "parcelable Data {"
                               "  int bar;"
                               "  int foo;"
                               "}");
  CaptureStderr();
  EXPECT_FALSE(::android::aidl::check_api(options_, io_delegate_));
  EXPECT_EQ(expected_stderr, GetCapturedStderr());
}

TEST_F(AidlTestIncompatibleChanges, ChangedDirectionSpecifier) {
  const string expected_stderr = "ERROR: new/p/IFoo.aidl:1.33-37: Direction changed: in to out.\n";
  io_delegate_.SetFileContents("old/p/IFoo.aidl",
                               "package p;"
                               "interface IFoo {"
                               "  void foo(in String[] str);"
                               "  void bar(@utf8InCpp String str);"
                               "}");
  io_delegate_.SetFileContents("new/p/IFoo.aidl",
                               "package p;"
                               "interface IFoo {"
                               "  void foo(out String[] str);"
                               "  void bar(@utf8InCpp String str);"
                               "}");
  CaptureStderr();
  EXPECT_FALSE(::android::aidl::check_api(options_, io_delegate_));
  EXPECT_EQ(expected_stderr, GetCapturedStderr());
}

TEST_F(AidlTestIncompatibleChanges, AddedAnnotation) {
  const string expected_stderr =
      "ERROR: new/p/IFoo.aidl:1.51-58: Changed annotations: (empty) to @utf8InCpp\n";
  io_delegate_.SetFileContents("old/p/IFoo.aidl",
                               "package p;"
                               "interface IFoo {"
                               "  void foo(in String[] str);"
                               "  void bar(@utf8InCpp String str);"
                               "}");
  io_delegate_.SetFileContents("new/p/IFoo.aidl",
                               "package p;"
                               "interface IFoo {"
                               "  void foo(in @utf8InCpp String[] str);"
                               "  void bar(@utf8InCpp String str);"
                               "}");
  CaptureStderr();
  EXPECT_FALSE(::android::aidl::check_api(options_, io_delegate_));
  EXPECT_EQ(expected_stderr, GetCapturedStderr());
}

TEST_F(AidlTestIncompatibleChanges, RemovedAnnotation) {
  const string expected_stderr =
      "ERROR: new/p/IFoo.aidl:1.66-72: Changed annotations: @utf8InCpp to (empty)\n";
  io_delegate_.SetFileContents("old/p/IFoo.aidl",
                               "package p;"
                               "interface IFoo {"
                               "  void foo(in String[] str);"
                               "  void bar(@utf8InCpp String str);"
                               "}");
  io_delegate_.SetFileContents("new/p/IFoo.aidl",
                               "package p;"
                               "interface IFoo {"
                               "  void foo(in String[] str);"
                               "  void bar(String str);"
                               "}");
  CaptureStderr();
  EXPECT_FALSE(::android::aidl::check_api(options_, io_delegate_));
  EXPECT_EQ(expected_stderr, GetCapturedStderr());
}

TEST_F(AidlTestIncompatibleChanges, ChangedBackingTypeOfEnum) {
  const string expected_stderr =
      "ERROR: new/p/Foo.aidl:1.11-32: Type changed: byte to long.\n"
      "ERROR: new/p/Foo.aidl:1.36-40: Changed backing types.\n";
  io_delegate_.SetFileContents("old/p/Foo.aidl",
                               "package p;"
                               "@Backing(type=\"byte\")"
                               "enum Foo {"
                               " FOO, BAR,"
                               "}");
  io_delegate_.SetFileContents("new/p/Foo.aidl",
                               "package p;"
                               "@Backing(type=\"long\")"
                               "enum Foo {"
                               " FOO, BAR,"
                               "}");
  CaptureStderr();
  EXPECT_FALSE(::android::aidl::check_api(options_, io_delegate_));
  EXPECT_EQ(expected_stderr, GetCapturedStderr());
}

TEST_F(AidlTestIncompatibleChanges, ChangedAnnatationParams) {
  const string expected_stderr =
      "ERROR: new/p/Foo.aidl:1.55-59: Changed annotations: @JavaPassthrough(annotation=\"Alice\") "
      "to @JavaPassthrough(annotation=\"Bob\")\n";
  io_delegate_.SetFileContents("old/p/Foo.aidl",
                               "package p;"
                               "@JavaPassthrough(annotation=\"Alice\")"
                               "parcelable Foo {}");
  io_delegate_.SetFileContents("new/p/Foo.aidl",
                               "package p;"
                               "@JavaPassthrough(annotation=\"Bob\")"
                               "parcelable Foo {}");

  CaptureStderr();
  EXPECT_FALSE(::android::aidl::check_api(options_, io_delegate_));
  EXPECT_EQ(expected_stderr, GetCapturedStderr());
}

TEST_F(AidlTestIncompatibleChanges, AddedParcelableAnnotation) {
  const string expected_stderr =
      "ERROR: new/p/Foo.aidl:1.32-36: Changed annotations: (empty) to @FixedSize\n";
  io_delegate_.SetFileContents("old/p/Foo.aidl",
                               "package p;"
                               "parcelable Foo {"
                               "  int A;"
                               "}");
  io_delegate_.SetFileContents("new/p/Foo.aidl",
                               "package p;"
                               "@FixedSize parcelable Foo {"
                               "  int A;"
                               "}");
  CaptureStderr();
  EXPECT_FALSE(::android::aidl::check_api(options_, io_delegate_));
  EXPECT_EQ(expected_stderr, GetCapturedStderr());
}

TEST_F(AidlTestIncompatibleChanges, RemovedParcelableAnnotation) {
  const string expected_stderr =
      "ERROR: new/p/Foo.aidl:1.21-25: Changed annotations: @FixedSize to (empty)\n";
  io_delegate_.SetFileContents("old/p/Foo.aidl",
                               "package p;"
                               "@FixedSize parcelable Foo {"
                               "  int A;"
                               "}");
  io_delegate_.SetFileContents("new/p/Foo.aidl",
                               "package p;"
                               "parcelable Foo {"
                               "  int A;"
                               "}");
  CaptureStderr();
  EXPECT_FALSE(::android::aidl::check_api(options_, io_delegate_));
  EXPECT_EQ(expected_stderr, GetCapturedStderr());
}

TEST_F(AidlTestIncompatibleChanges, RemovedPackage) {
  const string expected_stderr = "ERROR: old/q/IFoo.aidl:1.11-21: Removed type: q.IFoo\n";
  io_delegate_.SetFileContents("old/p/IFoo.aidl", "package p; interface IFoo{}");
  io_delegate_.SetFileContents("old/q/IFoo.aidl", "package q; interface IFoo{}");
  io_delegate_.SetFileContents("new/p/IFoo.aidl", "package p; interface IFoo{}");
  CaptureStderr();
  EXPECT_FALSE(::android::aidl::check_api(options_, io_delegate_));
  EXPECT_EQ(expected_stderr, GetCapturedStderr());
}

TEST_F(AidlTestIncompatibleChanges, ChangedDefaultValue) {
  const string expected_stderr = "ERROR: new/p/D.aidl:1.30-32: Changed default value: 1 to 2.\n";
  io_delegate_.SetFileContents("old/p/D.aidl", "package p; parcelable D { int a = 1; }");
  io_delegate_.SetFileContents("new/p/D.aidl", "package p; parcelable D { int a = 2; }");
  CaptureStderr();
  EXPECT_FALSE(::android::aidl::check_api(options_, io_delegate_));
  EXPECT_EQ(expected_stderr, GetCapturedStderr());
}

TEST_F(AidlTestIncompatibleChanges, RemovedConstValue) {
  const string expected_stderr =
      "ERROR: old/p/I.aidl:1.51-53: Removed constant declaration: p.I.B\n";
  io_delegate_.SetFileContents("old/p/I.aidl",
                               "package p; interface I {"
                               "const int A = 1; const int B = 2;}");
  io_delegate_.SetFileContents("new/p/I.aidl", "package p; interface I { const int A = 1; }");
  CaptureStderr();
  EXPECT_FALSE(::android::aidl::check_api(options_, io_delegate_));
  EXPECT_EQ(expected_stderr, GetCapturedStderr());
}

TEST_F(AidlTestIncompatibleChanges, ChangedConstValue) {
  const string expected_stderr =
      "ERROR: new/p/I.aidl:1.11-21: Changed constant value: p.I.A from 1 to 2.\n";
  io_delegate_.SetFileContents("old/p/I.aidl", "package p; interface I { const int A = 1; }");
  io_delegate_.SetFileContents("new/p/I.aidl", "package p; interface I { const int A = 2; }");
  CaptureStderr();
  EXPECT_FALSE(::android::aidl::check_api(options_, io_delegate_));
  EXPECT_EQ(expected_stderr, GetCapturedStderr());
}

TEST_F(AidlTestIncompatibleChanges, FixedSizeAddedField) {
  const string expected_stderr =
      "ERROR: new/p/Foo.aidl:1.33-37: Number of fields in p.Foo is changed from 1 to 2. "
      "This is an incompatible change for FixedSize types.\n";
  io_delegate_.SetFileContents("old/p/Foo.aidl",
                               "package p; @FixedSize parcelable Foo { int A = 1; }");
  io_delegate_.SetFileContents("new/p/Foo.aidl",
                               "package p; @FixedSize parcelable Foo { int A = 1; int B = 2; }");
  CaptureStderr();
  EXPECT_FALSE(::android::aidl::check_api(options_, io_delegate_));
  EXPECT_EQ(expected_stderr, GetCapturedStderr());
}

TEST_F(AidlTestIncompatibleChanges, UidRangeParcelAddedField) {
  const string expected_stderr =
      "ERROR: new/android/net/UidRangeParcel.aidl:1.32-47: Number of fields in "
      "android.net.UidRangeParcel is changed from 1 to 2. "
      "But it is forbidden because of legacy support.\n";
  io_delegate_.SetFileContents("old/android/net/UidRangeParcel.aidl",
                               "package android.net; parcelable UidRangeParcel { int A = 1; }");
  io_delegate_.SetFileContents(
      "new/android/net/UidRangeParcel.aidl",
      "package android.net; parcelable UidRangeParcel { int A = 1; int B = 2; }");
  CaptureStderr();
  EXPECT_FALSE(::android::aidl::check_api(options_, io_delegate_));
  EXPECT_EQ(expected_stderr, GetCapturedStderr());
}

TEST_F(AidlTestIncompatibleChanges, FixedSizeRemovedField) {
  const string expected_stderr =
      "ERROR: new/p/Foo.aidl:1.33-37: Number of fields in p.Foo is reduced from 2 to 1.\n";
  io_delegate_.SetFileContents("old/p/Foo.aidl",
                               "package p; @FixedSize parcelable Foo { int A = 1; int B = 1; }");
  io_delegate_.SetFileContents("new/p/Foo.aidl",
                               "package p; @FixedSize parcelable Foo { int A = 1; }");
  CaptureStderr();
  EXPECT_FALSE(::android::aidl::check_api(options_, io_delegate_));
  EXPECT_EQ(expected_stderr, GetCapturedStderr());
}

TEST_P(AidlTest, RejectNonFixedSizeFromFixedSize) {
  const string expected_stderr =
      "ERROR: Foo.aidl:1.36-38: The @FixedSize parcelable 'Foo' has a non-fixed size field named "
      "a.\n"
      "ERROR: Foo.aidl:1.44-46: The @FixedSize parcelable 'Foo' has a non-fixed size field named "
      "b.\n"
      "ERROR: Foo.aidl:1.55-57: The @FixedSize parcelable 'Foo' has a non-fixed size field named "
      "c.\n"
      "ERROR: Foo.aidl:1.80-82: The @FixedSize parcelable 'Foo' has a non-fixed size field named "
      "d.\n"
      "ERROR: Foo.aidl:1.92-94: The @FixedSize parcelable 'Foo' has a non-fixed size field named "
      "e.\n"
      "ERROR: Foo.aidl:1.109-111: The @FixedSize parcelable 'Foo' has a non-fixed size field named "
      "f.\n";

  io_delegate_.SetFileContents("Foo.aidl",
                               "@FixedSize parcelable Foo { "
                               "  int[] a;"
                               "  Bar b;"
                               "  String c;"
                               "  ParcelFileDescriptor d;"
                               "  IBinder e;"
                               "  List<String> f;"
                               "  int isFixedSize;"
                               "}");
  io_delegate_.SetFileContents("Bar.aidl", "parcelable Bar { int a; }");
  Options options = Options::From("aidl Foo.aidl -I . --lang=" + to_string(GetLanguage()));

  CaptureStderr();
  EXPECT_NE(0, ::android::aidl::compile_aidl(options, io_delegate_));
  EXPECT_EQ(expected_stderr, GetCapturedStderr());
}

TEST_P(AidlTest, AcceptFixedSizeFromFixedSize) {
  const string expected_stderr = "";

  io_delegate_.SetFileContents("Foo.aidl", "@FixedSize parcelable Foo { int a; Bar b; }");
  io_delegate_.SetFileContents("Bar.aidl", "@FixedSize parcelable Bar { Val c; }");
  io_delegate_.SetFileContents("Val.aidl", "enum Val { A, B, }");
  Options options = Options::From("aidl Foo.aidl -I . --lang=" + to_string(GetLanguage()));

  CaptureStderr();
  EXPECT_EQ(0, ::android::aidl::compile_aidl(options, io_delegate_));
  EXPECT_EQ(expected_stderr, GetCapturedStderr());
}

TEST_F(AidlTest, RejectAmbiguousImports) {
  const string expected_stderr =
      "ERROR: p/IFoo.aidl: Duplicate files found for q.IBar from:\n"
      "dir1/q/IBar.aidl\n"
      "dir2/q/IBar.aidl\n"
      "ERROR: p/IFoo.aidl: Couldn't find import for class q.IBar\n";
  Options options = Options::From("aidl --lang=java -o out -I dir1 -I dir2 p/IFoo.aidl");
  io_delegate_.SetFileContents("p/IFoo.aidl", "package p; import q.IBar; interface IFoo{}");
  io_delegate_.SetFileContents("dir1/q/IBar.aidl", "package q; interface IBar{}");
  io_delegate_.SetFileContents("dir2/q/IBar.aidl", "package q; interface IBar{}");

  CaptureStderr();
  EXPECT_NE(0, ::android::aidl::compile_aidl(options, io_delegate_));
  EXPECT_EQ(expected_stderr, GetCapturedStderr());
}

TEST_F(AidlTest, HandleManualIdAssignments) {
  const string expected_stderr =
      "ERROR: new/p/IFoo.aidl:1.32-36: Transaction ID changed: p.IFoo.foo() is changed from 10 to "
      "11.\n";
  Options options = Options::From("aidl --checkapi old new");
  io_delegate_.SetFileContents("old/p/IFoo.aidl", "package p; interface IFoo{ void foo() = 10;}");
  io_delegate_.SetFileContents("new/p/IFoo.aidl", "package p; interface IFoo{ void foo() = 10;}");

  EXPECT_TRUE(::android::aidl::check_api(options, io_delegate_));

  io_delegate_.SetFileContents("new/p/IFoo.aidl", "package p; interface IFoo{ void foo() = 11;}");
  CaptureStderr();
  EXPECT_FALSE(::android::aidl::check_api(options, io_delegate_));
  EXPECT_EQ(expected_stderr, GetCapturedStderr());
}

TEST_P(AidlTest, ParcelFileDescriptorIsBuiltinType) {
  Options options =
      Options::From("aidl --lang=" + to_string(GetLanguage()) + " -h out -o out p/IFoo.aidl");

  // use without import
  io_delegate_.SetFileContents("p/IFoo.aidl",
                               "package p; interface IFoo{ void foo(in ParcelFileDescriptor fd);}");
  EXPECT_EQ(0, ::android::aidl::compile_aidl(options, io_delegate_));

  // capture output files
  map<string, string> outputs = io_delegate_.OutputFiles();

  // use without import but with full name
  io_delegate_.SetFileContents(
      "p/IFoo.aidl",
      "package p; interface IFoo{ void foo(in android.os.ParcelFileDescriptor fd);}");
  EXPECT_EQ(0, ::android::aidl::compile_aidl(options, io_delegate_));
  // output files should be the same
  EXPECT_EQ(outputs, io_delegate_.OutputFiles());

  // use with import (as before)
  io_delegate_.SetFileContents("p/IFoo.aidl",
                               "package p;"
                               "import android.os.ParcelFileDescriptor;"
                               "interface IFoo{"
                               "  void foo(in ParcelFileDescriptor fd);"
                               "}");
  EXPECT_EQ(0, ::android::aidl::compile_aidl(options, io_delegate_));
  // output files should be the same
  EXPECT_EQ(outputs, io_delegate_.OutputFiles());
}

TEST_P(AidlTest, RejectsOutputParcelFileDescriptor) {
  Options options = Options::From("aidl p/IFoo.aidl -I . --lang=" + to_string(GetLanguage()));
  CaptureStderr();
  io_delegate_.SetFileContents("p/IFoo.aidl",
                               "package p;"
                               "interface IFoo{"
                               "  void foo(out ParcelFileDescriptor fd);"
                               "}");
  EXPECT_EQ(1, ::android::aidl::compile_aidl(options, io_delegate_));
  EXPECT_THAT(GetCapturedStderr(), HasSubstr("can't be an out parameter"));
}

TEST_P(AidlTest, RejectsArgumentDirectionNotSpecified) {
  Options options = Options::From("aidl p/IFoo.aidl -I . --lang=" + to_string(GetLanguage()));
  CaptureStderr();
  io_delegate_.SetFileContents("p/IFoo.aidl",
                               "package p;"
                               "interface IFoo{"
                               "  void foo(ParcelFileDescriptor fd);"
                               "}");
  EXPECT_EQ(1, ::android::aidl::compile_aidl(options, io_delegate_));
  EXPECT_THAT(GetCapturedStderr(),
              HasSubstr("ParcelFileDescriptor can be an in or inout parameter."));
}

TEST_F(AidlTest, ManualIds) {
  Options options = Options::From("aidl --lang=java -o out IFoo.aidl");
  io_delegate_.SetFileContents("IFoo.aidl",
                               "interface IFoo {\n"
                               "  void foo() = 0;\n"
                               "  void bar() = 1;\n"
                               "}");
  EXPECT_EQ(0, ::android::aidl::compile_aidl(options, io_delegate_));
}

TEST_F(AidlTest, ManualIdsWithMetaTransactions) {
  Options options = Options::From("aidl --lang=java --version 10 -o out IFoo.aidl");
  io_delegate_.SetFileContents("IFoo.aidl",
                               "interface IFoo {\n"
                               "  void foo() = 0;\n"
                               "  void bar() = 1;\n"
                               "}");
  EXPECT_EQ(0, ::android::aidl::compile_aidl(options, io_delegate_));
}

TEST_F(AidlTest, FailOnDuplicatedIds) {
  const string expected_stderr =
      "ERROR: IFoo.aidl:3.7-11: Found duplicate method id (3) for method bar\n";
  Options options = Options::From("aidl --lang=java --version 10 -o out IFoo.aidl");
  io_delegate_.SetFileContents("IFoo.aidl",
                               "interface IFoo {\n"
                               "  void foo() = 3;\n"
                               "  void bar() = 3;\n"
                               "}");
  CaptureStderr();
  EXPECT_NE(0, ::android::aidl::compile_aidl(options, io_delegate_));
  EXPECT_EQ(expected_stderr, GetCapturedStderr());
}

TEST_F(AidlTest, FailOnOutOfRangeIds) {
  // 16777115 is kLastMetaMethodId + 1
  const string expected_stderr =
      "ERROR: IFoo.aidl:3.7-11: Found out of bounds id (16777115) for method bar. "
      "Value for id must be between 0 and 16777114 inclusive.\n";
  Options options = Options::From("aidl --lang=java --version 10 -o out IFoo.aidl");
  io_delegate_.SetFileContents("IFoo.aidl",
                               "interface IFoo {\n"
                               "  void foo() = 3;\n"
                               "  void bar() = 16777115;\n"
                               "}");
  CaptureStderr();
  EXPECT_NE(0, ::android::aidl::compile_aidl(options, io_delegate_));
  EXPECT_EQ(expected_stderr, GetCapturedStderr());
}

TEST_F(AidlTest, FailOnPartiallyAssignedIds) {
  const string expected_stderr =
      "ERROR: IFoo.aidl:3.7-11: You must either assign id's to all methods or to none of them.\n";
  Options options = Options::From("aidl --lang=java --version 10 -o out IFoo.aidl");
  io_delegate_.SetFileContents("IFoo.aidl",
                               "interface IFoo {\n"
                               "  void foo() = 3;\n"
                               "  void bar();\n"
                               "}");
  CaptureStderr();
  EXPECT_NE(0, ::android::aidl::compile_aidl(options, io_delegate_));
  EXPECT_EQ(expected_stderr, GetCapturedStderr());
}

TEST_F(AidlTest, AllowDuplicatedImportPaths) {
  Options options = Options::From("aidl --lang=java -I dir -I dir IFoo.aidl");
  io_delegate_.SetFileContents("dir/IBar.aidl", "interface IBar{}");
  io_delegate_.SetFileContents("IFoo.aidl", "import IBar; interface IFoo{}");
  EXPECT_EQ(0, ::android::aidl::compile_aidl(options, io_delegate_));
}

TEST_F(AidlTest, FailOnAmbiguousImports) {
  const string expected_stderr =
      "ERROR: IFoo.aidl: Duplicate files found for IBar from:\n"
      "dir/IBar.aidl\n"
      "dir2/IBar.aidl\n"
      "ERROR: IFoo.aidl: Couldn't find import for class IBar\n";

  Options options = Options::From("aidl --lang=java -I dir -I dir2 IFoo.aidl");
  io_delegate_.SetFileContents("dir/IBar.aidl", "interface IBar{}");
  io_delegate_.SetFileContents("dir2/IBar.aidl", "interface IBar{}");
  io_delegate_.SetFileContents("IFoo.aidl", "import IBar; interface IFoo{}");
  CaptureStderr();
  EXPECT_NE(0, ::android::aidl::compile_aidl(options, io_delegate_));
  EXPECT_EQ(expected_stderr, GetCapturedStderr());
}

TEST_F(AidlTest, UnusedImportDoesNotContributeInclude) {
  io_delegate_.SetFileContents("a/b/IFoo.aidl",
                               "package a.b;\n"
                               "import a.b.IBar;\n"
                               "import a.b.IQux;\n"
                               "interface IFoo { IQux foo(); }\n");
  io_delegate_.SetFileContents("a/b/IBar.aidl", "package a.b; interface IBar { void foo(); }");
  io_delegate_.SetFileContents("a/b/IQux.aidl", "package a.b; interface IQux { void foo(); }");

  Options options = Options::From("aidl --lang=ndk a/b/IFoo.aidl -I . -o out -h out/include");
  EXPECT_EQ(0, ::android::aidl::compile_aidl(options, io_delegate_));

  string output;
  EXPECT_TRUE(io_delegate_.GetWrittenContents("out/include/aidl/a/b/IFoo.h", &output));
  // IBar was imported but wasn't used. include is not expected.
  EXPECT_THAT(output, Not(testing::HasSubstr("#include <aidl/a/b/IBar.h>")));
  // IBar was imported and used. include is expected.
  EXPECT_THAT(output, (testing::HasSubstr("#include <aidl/a/b/IQux.h>")));
}

TEST_F(AidlTest, ParseJavaPassthroughAnnotation) {
  io_delegate_.SetFileContents("a/IFoo.aidl", R"--(package a;
    import a.MyEnum;
    @JavaPassthrough(annotation="@com.android.Alice(arg=com.android.Alice.Value.A)")
    @JavaPassthrough(annotation="@com.android.AliceTwo")
    interface IFoo {
        @JavaPassthrough(annotation="@com.android.Bob")
        void foo(@JavaPassthrough(annotation="@com.android.Cat") int x, MyEnum y);
        const @JavaPassthrough(annotation="@com.android.David") int A = 3;
    })--");
  // JavaPassthrough should work with other types as well (e.g. enum)
  io_delegate_.SetFileContents("a/MyEnum.aidl", R"--(package a;
    @JavaPassthrough(annotation="@com.android.Alice(arg=com.android.Alice.Value.A)")
    @JavaPassthrough(annotation="@com.android.AliceTwo")
    @Backing(type="byte")
    enum MyEnum {
      a, b, c
    })--");

  Options java_options = Options::From("aidl -I . --lang=java -o out a/IFoo.aidl a/MyEnum.aidl");
  EXPECT_EQ(0, ::android::aidl::compile_aidl(java_options, io_delegate_));

  string java_out;
  EXPECT_TRUE(io_delegate_.GetWrittenContents("out/a/IFoo.java", &java_out));
  // type-decl-level annotations with newline at the end
  EXPECT_THAT(java_out, testing::HasSubstr("@com.android.Alice(arg=com.android.Alice.Value.A)\n"));
  EXPECT_THAT(java_out, testing::HasSubstr("@com.android.AliceTwo\n"));
  // member-decl-level annotations with newline at the end
  EXPECT_THAT(java_out, testing::HasSubstr("@com.android.Bob\n"));
  EXPECT_THAT(java_out, testing::HasSubstr("@com.android.David\n"));
  // inline annotations with space at the end
  EXPECT_THAT(java_out, testing::HasSubstr("@com.android.Cat "));

  EXPECT_TRUE(io_delegate_.GetWrittenContents("out/a/MyEnum.java", &java_out));
  // type-decl-level annotations with newline at the end
  EXPECT_THAT(java_out, testing::HasSubstr("@com.android.Alice(arg=com.android.Alice.Value.A)\n"));
  EXPECT_THAT(java_out, testing::HasSubstr("@com.android.AliceTwo\n"));

  // Other backends shouldn't be bothered
  Options cpp_options =
      Options::From("aidl -I . --lang=cpp -o out -h out a/IFoo.aidl a/MyEnum.aidl");
  EXPECT_EQ(0, ::android::aidl::compile_aidl(cpp_options, io_delegate_));

  Options ndk_options =
      Options::From("aidl -I . --lang=ndk -o out -h out a/IFoo.aidl a/MyEnum.aidl");
  EXPECT_EQ(0, ::android::aidl::compile_aidl(ndk_options, io_delegate_));

  Options rust_options = Options::From("aidl -I . --lang=rust -o out a/IFoo.aidl a/MyEnum.aidl");
  EXPECT_EQ(0, ::android::aidl::compile_aidl(rust_options, io_delegate_));
}

TEST_F(AidlTest, ParseRustDerive) {
  io_delegate_.SetFileContents("a/Foo.aidl", R"(package a;
    @RustDerive(Clone=true, Copy=false)
    parcelable Foo {
        int a;
    })");

  Options rust_options = Options::From("aidl --lang=rust -o out a/Foo.aidl");
  EXPECT_EQ(0, ::android::aidl::compile_aidl(rust_options, io_delegate_));

  string rust_out;
  EXPECT_TRUE(io_delegate_.GetWrittenContents("out/a/Foo.rs", &rust_out));
  EXPECT_THAT(rust_out, testing::HasSubstr("#[derive(Debug, Clone)]"));

  // Other backends shouldn't be bothered
  Options cpp_options = Options::From("aidl --lang=cpp -o out -h out a/Foo.aidl");
  EXPECT_EQ(0, ::android::aidl::compile_aidl(cpp_options, io_delegate_));

  Options ndk_options = Options::From("aidl --lang=ndk -o out -h out a/Foo.aidl");
  EXPECT_EQ(0, ::android::aidl::compile_aidl(ndk_options, io_delegate_));

  Options java_options = Options::From("aidl --lang=java -o out a/Foo.aidl");
  EXPECT_EQ(0, ::android::aidl::compile_aidl(java_options, io_delegate_));
}

class AidlOutputPathTest : public AidlTest {
 protected:
  void SetUp() override {
    AidlTest::SetUp();
    io_delegate_.SetFileContents("sub/dir/foo/bar/IFoo.aidl", "package foo.bar; interface IFoo {}");
  }

  void Test(const Options& options, const std::string expected_output_path) {
    EXPECT_EQ(0, ::android::aidl::compile_aidl(options, io_delegate_));
    // check the existence
    EXPECT_TRUE(io_delegate_.GetWrittenContents(expected_output_path, nullptr));
  }
};

TEST_F(AidlOutputPathTest, OutDirWithNoOutputFile) {
  // <out_dir> / <package_name> / <type_name>.java
  Test(Options::From("aidl -o out sub/dir/foo/bar/IFoo.aidl"), "out/foo/bar/IFoo.java");
}

TEST_F(AidlOutputPathTest, OutDirWithOutputFile) {
  // when output file is explicitly set, it is always respected. -o option is
  // ignored.
  Test(Options::From("aidl -o out sub/dir/foo/bar/IFoo.aidl output/IFoo.java"), "output/IFoo.java");
}

TEST_F(AidlOutputPathTest, NoOutDirWithOutputFile) {
  Test(Options::From("aidl -o out sub/dir/foo/bar/IFoo.aidl output/IFoo.java"), "output/IFoo.java");
}

TEST_F(AidlOutputPathTest, NoOutDirWithNoOutputFile) {
  // output is the same as the input file except for the suffix
  Test(Options::From("aidl sub/dir/foo/bar/IFoo.aidl"), "sub/dir/foo/bar/IFoo.java");
}

TEST_P(AidlTest, FailOnOutOfBoundsInt32MaxConstInt) {
  AidlError error;
  const string expected_stderr =
      "ERROR: p/IFoo.aidl:3.58-69: Invalid type specifier for an int64 literal: int\n";
  CaptureStderr();
  EXPECT_EQ(nullptr, Parse("p/IFoo.aidl",
                           R"(package p;
                              interface IFoo {
                                const int int32_max_oob = 2147483650;
                              }
                             )",
                           typenames_, GetLanguage(), &error));
  EXPECT_EQ(expected_stderr, GetCapturedStderr());
  EXPECT_EQ(AidlError::BAD_TYPE, error);
}

TEST_P(AidlTest, FailOnOutOfBoundsInt32MinConstInt) {
  AidlError error;
  const string expected_stderr =
      "ERROR: p/IFoo.aidl:3.58-60: Invalid type specifier for an int64 literal: int\n";
  CaptureStderr();
  EXPECT_EQ(nullptr, Parse("p/IFoo.aidl",
                           R"(package p;
                              interface IFoo {
                                const int int32_min_oob = -2147483650;
                              }
                             )",
                           typenames_, GetLanguage(), &error));
  EXPECT_EQ(expected_stderr, GetCapturedStderr());
  EXPECT_EQ(AidlError::BAD_TYPE, error);
}

TEST_P(AidlTest, FailOnOutOfBoundsInt64MaxConstInt) {
  AidlError error;
  const string expected_stderr =
      "ERROR: p/IFoo.aidl:3.59-86: Could not parse integer: 21474836509999999999999999\n";
  CaptureStderr();
  EXPECT_EQ(nullptr, Parse("p/IFoo.aidl",
                           R"(package p;
                              interface IFoo {
                                const long int64_max_oob = 21474836509999999999999999;
                              }
                             )",
                           typenames_, GetLanguage(), &error));
  EXPECT_EQ(expected_stderr, GetCapturedStderr());
  EXPECT_EQ(AidlError::PARSE_ERROR, error);
}

TEST_P(AidlTest, FailOnOutOfBoundsInt64MinConstInt) {
  AidlError error;
  const string expected_stderr =
      "ERROR: p/IFoo.aidl:3.61-87: Could not parse integer: 21474836509999999999999999\n";
  CaptureStderr();
  EXPECT_EQ(nullptr, Parse("p/IFoo.aidl",
                           R"(package p;
                              interface IFoo {
                                const long int64_min_oob = -21474836509999999999999999;
                              }
                             )",
                           typenames_, GetLanguage(), &error));
  EXPECT_EQ(expected_stderr, GetCapturedStderr());
  EXPECT_EQ(AidlError::PARSE_ERROR, error);
}

TEST_P(AidlTest, FailOnOutOfBoundsAutofilledEnum) {
  AidlError error;
  const string expected_stderr =
      "ERROR: p/TestEnum.aidl:5.1-36: Invalid type specifier for an int32 literal: byte\n"
      "ERROR: p/TestEnum.aidl:5.1-36: Enumerator type differs from enum backing type.\n";
  CaptureStderr();
  EXPECT_EQ(nullptr, Parse("p/TestEnum.aidl",
                           R"(package p;
                              @Backing(type="byte")
                              enum TestEnum {
                                FOO = 127,
                                BAR,
                              }
                             )",
                           typenames_, GetLanguage(), &error));
  EXPECT_EQ(expected_stderr, GetCapturedStderr());
  EXPECT_EQ(AidlError::BAD_TYPE, error);
}

TEST_P(AidlTest, UnsupportedBackingAnnotationParam) {
  AidlError error;
  const string expected_stderr =
      "ERROR: p/TestEnum.aidl:2.1-51: Parameter foo not supported for annotation Backing. It must "
      "be one of: type\n";
  CaptureStderr();
  EXPECT_EQ(nullptr, Parse("p/TestEnum.aidl",
                           R"(package p;
                              @Backing(foo="byte")
                              enum TestEnum {
                                FOO = 1,
                                BAR,
                              }
                             )",
                           typenames_, GetLanguage(), &error));
  EXPECT_EQ(expected_stderr, GetCapturedStderr());
  EXPECT_EQ(AidlError::BAD_TYPE, error);
}

TEST_P(AidlTest, BackingAnnotationRequireTypeParameter) {
  const string expected_stderr = "ERROR: Enum.aidl:1.1-9: Missing 'type' on @Backing.\n";
  CaptureStderr();
  EXPECT_EQ(nullptr, Parse("Enum.aidl", "@Backing enum Enum { FOO }", typenames_, GetLanguage()));
  EXPECT_EQ(expected_stderr, GetCapturedStderr());
}

TEST_F(AidlTest, SupportJavaOnlyImmutableAnnotation) {
  io_delegate_.SetFileContents("Foo.aidl",
                               "@JavaOnlyImmutable parcelable Foo { int a; Bar b; List<Bar> c; "
                               "Map<String, Baz> d; Bar[] e; }");
  io_delegate_.SetFileContents("Bar.aidl", "@JavaOnlyImmutable parcelable Bar { String a; }");
  io_delegate_.SetFileContents("Baz.aidl",
                               "@JavaOnlyImmutable @JavaOnlyStableParcelable parcelable Baz;");
  Options options = Options::From("aidl --lang=java -I . Foo.aidl");
  EXPECT_EQ(0, ::android::aidl::compile_aidl(options, io_delegate_));
}

TEST_F(AidlTest, RejectMutableParcelableFromJavaOnlyImmutableParcelable) {
  io_delegate_.SetFileContents("Foo.aidl", "@JavaOnlyImmutable parcelable Foo { Bar bar; }");
  io_delegate_.SetFileContents("Bar.aidl", "parcelable Bar { String a; }");
  string expected_error =
      "ERROR: Foo.aidl:1.40-44: The @JavaOnlyImmutable 'Foo' has a non-immutable field "
      "named 'bar'.\n";
  CaptureStderr();
  Options options = Options::From("aidl --lang=java Foo.aidl -I .");
  EXPECT_NE(0, ::android::aidl::compile_aidl(options, io_delegate_));
  EXPECT_EQ(expected_error, GetCapturedStderr());
}

TEST_F(AidlTest, JavaOnlyImmutableParcelableWithEnumFields) {
  io_delegate_.SetFileContents("Foo.aidl", "@JavaOnlyImmutable parcelable Foo { Bar bar; }");
  io_delegate_.SetFileContents("Bar.aidl", "enum Bar { FOO }");
  CaptureStderr();
  Options options = Options::From("aidl --lang=java Foo.aidl -I .");
  EXPECT_EQ(0, ::android::aidl::compile_aidl(options, io_delegate_));
  EXPECT_EQ("", GetCapturedStderr());
}

TEST_F(AidlTest, RejectMutableParcelableFromJavaOnlyImmutableUnion) {
  io_delegate_.SetFileContents("Foo.aidl", "@JavaOnlyImmutable union Foo { Bar bar; }");
  io_delegate_.SetFileContents("Bar.aidl", "parcelable Bar { String a; }");
  string expected_error =
      "ERROR: Foo.aidl:1.35-39: The @JavaOnlyImmutable 'Foo' has a non-immutable field "
      "named 'bar'.\n";
  CaptureStderr();
  Options options = Options::From("aidl --lang=java Foo.aidl -I .");
  EXPECT_NE(0, ::android::aidl::compile_aidl(options, io_delegate_));
  EXPECT_EQ(expected_error, GetCapturedStderr());
}

TEST_F(AidlTest, ImmutableParcelableCannotBeInOut) {
  io_delegate_.SetFileContents("Foo.aidl", "@JavaOnlyImmutable parcelable Foo { int a; }");
  io_delegate_.SetFileContents("IBar.aidl", "interface IBar { void my(inout Foo foo); }");
  string expected_error =
      "ERROR: IBar.aidl:1.35-39: 'foo' can't be an inout parameter because @JavaOnlyImmutable can "
      "only be an in parameter.\n";
  CaptureStderr();
  Options options = Options::From("aidl --lang=java IBar.aidl -I .");
  EXPECT_NE(0, ::android::aidl::compile_aidl(options, io_delegate_));
  EXPECT_EQ(expected_error, GetCapturedStderr());
}

TEST_F(AidlTest, ImmutableParcelableCannotBeOut) {
  io_delegate_.SetFileContents("Foo.aidl", "@JavaOnlyImmutable parcelable Foo { int a; }");
  io_delegate_.SetFileContents("IBar.aidl", "interface IBar { void my(out Foo foo); }");
  string expected_error =
      "ERROR: IBar.aidl:1.33-37: 'foo' can't be an out parameter because @JavaOnlyImmutable can "
      "only be an in parameter.\n";
  CaptureStderr();
  Options options = Options::From("aidl --lang=java IBar.aidl -I .");
  EXPECT_NE(0, ::android::aidl::compile_aidl(options, io_delegate_));
  EXPECT_EQ(expected_error, GetCapturedStderr());
}

TEST_F(AidlTest, ImmutableParcelableFieldNameRestriction) {
  io_delegate_.SetFileContents("Foo.aidl", "@JavaOnlyImmutable parcelable Foo { int a; int A; }");
  Options options = Options::From("aidl --lang=java Foo.aidl");
  const string expected_stderr =
      "ERROR: Foo.aidl:1.47-49: 'Foo' has duplicate field name 'A' after capitalizing the first "
      "letter\n";
  CaptureStderr();
  EXPECT_NE(0, ::android::aidl::compile_aidl(options, io_delegate_));
  EXPECT_EQ(expected_stderr, GetCapturedStderr());
}

TEST_P(AidlTest, UnionInUnion) {
  import_paths_.insert(".");
  io_delegate_.SetFileContents("Bar.aidl", "union Bar { int n = 42; long l; }");
  CaptureStderr();
  EXPECT_NE(nullptr, Parse("Foo.aidl", "union Foo { Bar b; int n; }", typenames_, GetLanguage()));
  EXPECT_THAT("", GetCapturedStderr());
}

TEST_P(AidlTest, UnionRejectsEmptyDecl) {
  const string method = "package a; union Foo {}";
  const string expected_stderr = "ERROR: a/Foo.aidl:1.17-21: The union 'Foo' has no fields.\n";
  CaptureStderr();
  EXPECT_EQ(nullptr, Parse("a/Foo.aidl", method, typenames_, GetLanguage()));
  EXPECT_THAT(GetCapturedStderr(), testing::HasSubstr(expected_stderr));
}

TEST_P(AidlTest, UnionRejectsParcelableHolder) {
  const string method = "package a; union Foo { ParcelableHolder x; }";
  const string expected_stderr =
      "ERROR: a/Foo.aidl:1.40-42: A union can't have a member of ParcelableHolder 'x'\n";
  CaptureStderr();
  EXPECT_EQ(nullptr, Parse("a/Foo.aidl", method, typenames_, GetLanguage()));
  EXPECT_THAT(GetCapturedStderr(), testing::HasSubstr(expected_stderr));
}

TEST_P(AidlTest, UnionRejectsFirstEnumWithNoDefaults) {
  import_paths_.insert(".");
  io_delegate_.SetFileContents("a/Enum.aidl", "package a; enum Enum { FOO, BAR }");
  const string expected_err = "The union's first member should have a useful default value.";
  CaptureStderr();
  EXPECT_EQ(nullptr,
            Parse("a/Foo.aidl", "package a; union Foo { a.Enum e; }", typenames_, GetLanguage()));
  EXPECT_THAT(GetCapturedStderr(), testing::HasSubstr(expected_err));
}

TEST_P(AidlTest, GenericStructuredParcelable) {
  io_delegate_.SetFileContents("Foo.aidl", "parcelable Foo<T, U> { int a; int A; }");
  Options options = Options::From("aidl Foo.aidl --lang=" + to_string(GetLanguage()));
  const string expected_stderr = "";
  CaptureStderr();
  EXPECT_EQ(0, ::android::aidl::compile_aidl(options, io_delegate_));
  EXPECT_EQ(expected_stderr, GetCapturedStderr());
}

TEST_F(AidlTest, GenericStructuredParcelableWithStringConstants_Cpp) {
  io_delegate_.SetFileContents("Foo.aidl",
                               "parcelable Foo<T, U> { int a; const String s = \"\"; }");
  Options options =
      Options::From("aidl Foo.aidl --lang=" + to_string(Options::Language::CPP) + " -o out -h out");
  const string expected_stderr = "";
  CaptureStderr();
  EXPECT_EQ(0, ::android::aidl::compile_aidl(options, io_delegate_));
  EXPECT_EQ(expected_stderr, GetCapturedStderr());

  string code;
  EXPECT_TRUE(io_delegate_.GetWrittenContents("out/Foo.h", &code));
  EXPECT_THAT(code, testing::HasSubstr(R"--(template <typename T, typename U>
const ::android::String16& Foo<T,U>::s() {
  static const ::android::String16 value(::android::String16(""));
  return value;
})--"));
}

TEST_F(AidlTest, GenericStructuredParcelableWithStringConstants_Ndk) {
  io_delegate_.SetFileContents("Foo.aidl",
                               "parcelable Foo<T, U> { int a; const String s = \"\"; }");
  Options options =
      Options::From("aidl Foo.aidl --lang=" + to_string(Options::Language::NDK) + " -o out -h out");
  const string expected_stderr = "";
  CaptureStderr();
  EXPECT_EQ(0, ::android::aidl::compile_aidl(options, io_delegate_));
  EXPECT_EQ(expected_stderr, GetCapturedStderr());

  string code;
  EXPECT_TRUE(io_delegate_.GetWrittenContents("out/aidl/Foo.h", &code));
  EXPECT_THAT(code, testing::HasSubstr(R"--(template <typename T, typename U>
const char* Foo<T, U>::s = "";
)--"));
}

TEST_F(AidlTest, NestedTypeArgs) {
  io_delegate_.SetFileContents("a/Bar.aidl", "package a; parcelable Bar<A> { }");
  io_delegate_.SetFileContents("a/Baz.aidl", "package a; parcelable Baz<A, B> { }");

  io_delegate_.SetFileContents("a/Foo.aidl",
                               "package a; import a.Bar; import a.Baz; parcelable Foo { "
                               "Baz<Bar<Bar<String[]>>[], Bar<String>> barss; }");
  Options options = Options::From("aidl a/Foo.aidl -I . -o out --lang=java");
  const string expected_stderr = "";
  CaptureStderr();
  EXPECT_EQ(0, ::android::aidl::compile_aidl(options, io_delegate_));
  EXPECT_EQ(expected_stderr, GetCapturedStderr());

  string code;
  EXPECT_TRUE(io_delegate_.GetWrittenContents("out/a/Foo.java", &code));
  EXPECT_THAT(code,
              testing::HasSubstr(
                  "a.Baz<a.Bar<a.Bar<java.lang.String[]>>[],a.Bar<java.lang.String>> barss;"));
}

TEST_F(AidlTest, DoubleArrayError) {
  io_delegate_.SetFileContents("a/Bar.aidl", "package a; parcelable Bar { String[][] a; }");

  Options options = Options::From("aidl a/Bar.aidl -I . -o out --lang=java");
  const string expected_stderr =
      "ERROR: a/Bar.aidl:1.28-37: Can only have one dimensional arrays.\n";
  CaptureStderr();
  EXPECT_NE(0, ::android::aidl::compile_aidl(options, io_delegate_));
  EXPECT_EQ(expected_stderr, GetCapturedStderr());
}

TEST_F(AidlTest, DoubleGenericError) {
  io_delegate_.SetFileContents("a/Bar.aidl",
                               "package a; parcelable Bar { List<String><String> a; }");

  Options options = Options::From("aidl a/Bar.aidl -I . -o out --lang=java");
  const string expected_stderr =
      "ERROR: a/Bar.aidl:1.28-33: Can only specify one set of type parameters.\n";
  CaptureStderr();
  EXPECT_NE(0, ::android::aidl::compile_aidl(options, io_delegate_));
  EXPECT_EQ(expected_stderr, GetCapturedStderr());
}

TEST_F(AidlTest, ArrayBeforeGenericError) {
  io_delegate_.SetFileContents("a/Bar.aidl", "package a; parcelable Bar { List[]<String> a; }");

  Options options = Options::From("aidl a/Bar.aidl -I . -o out --lang=java");
  CaptureStderr();
  EXPECT_NE(0, ::android::aidl::compile_aidl(options, io_delegate_));
  EXPECT_THAT(GetCapturedStderr(), testing::HasSubstr("syntax error, unexpected '<'"));
}

TEST_F(AidlTest, NullableArraysAreNotSupported) {
  io_delegate_.SetFileContents("a/Bar.aidl",
                               "package a; parcelable Bar { String @nullable [] a; }");

  Options options = Options::From("aidl a/Bar.aidl -I . -o out --lang=java");
  CaptureStderr();
  EXPECT_EQ(1, ::android::aidl::compile_aidl(options, io_delegate_));
  EXPECT_THAT(GetCapturedStderr(), testing::HasSubstr("Annotations for arrays are not supported."));
}

TEST_F(AidlTest, ListOfNullablesAreNotSupported) {
  io_delegate_.SetFileContents("a/Bar.aidl",
                               "package a; parcelable Bar { List<@nullable String> a; }");

  Options options = Options::From("aidl a/Bar.aidl -I . -o out --lang=java");
  CaptureStderr();
  EXPECT_EQ(1, ::android::aidl::compile_aidl(options, io_delegate_));
  EXPECT_THAT(GetCapturedStderr(),
              testing::HasSubstr("Annotations for type arguments are not supported."));
}

struct GenericAidlTest : ::testing::Test {
  FakeIoDelegate io_delegate_;
  void Compile(string cmd) {
    io_delegate_.SetFileContents("Foo.aidl", "parcelable Foo { Bar<Baz<Qux>> x; }");
    io_delegate_.SetFileContents("Bar.aidl", "parcelable Bar<T> {  }");
    io_delegate_.SetFileContents("Baz.aidl", "parcelable Baz<T> {  }");
    io_delegate_.SetFileContents("Qux.aidl", "parcelable Qux {  }");

    Options options = Options::From(cmd);
    CaptureStderr();
    EXPECT_EQ(0, ::android::aidl::compile_aidl(options, io_delegate_));
    EXPECT_EQ("", GetCapturedStderr());
  }
};

TEST_F(GenericAidlTest, ImportGenericParameterTypesCPP) {
  Compile("aidl Foo.aidl --lang=cpp -I . -o out -h out");
  string code;
  EXPECT_TRUE(io_delegate_.GetWrittenContents("out/Foo.h", &code));
  EXPECT_THAT(code, testing::HasSubstr("#include <Bar.h>"));
  EXPECT_THAT(code, testing::HasSubstr("#include <Baz.h>"));
  EXPECT_THAT(code, testing::HasSubstr("#include <Qux.h>"));
}

TEST_F(GenericAidlTest, ImportGenericParameterTypesNDK) {
  Compile("aidl Foo.aidl --lang=ndk -I . -o out -h out");
  string code;
  EXPECT_TRUE(io_delegate_.GetWrittenContents("out/aidl/Foo.h", &code));
  EXPECT_THAT(code, testing::HasSubstr("#include <aidl/Bar.h>"));
  EXPECT_THAT(code, testing::HasSubstr("#include <aidl/Baz.h>"));
  EXPECT_THAT(code, testing::HasSubstr("#include <aidl/Qux.h>"));
}

TEST_P(AidlTest, RejectGenericStructuredParcelabelRepeatedParam) {
  io_delegate_.SetFileContents("Foo.aidl", "parcelable Foo<T,T> { int a; int A; }");
  Options options = Options::From("aidl Foo.aidl --lang=" + to_string(GetLanguage()));
  const string expected_stderr =
      "ERROR: Foo.aidl:1.11-15: Every type parameter should be unique.\n";
  CaptureStderr();
  EXPECT_NE(0, ::android::aidl::compile_aidl(options, io_delegate_));
  EXPECT_EQ(expected_stderr, GetCapturedStderr());
}

TEST_P(AidlTest, RejectGenericStructuredParcelableField) {
  io_delegate_.SetFileContents("Foo.aidl", "parcelable Foo<T,T> { T a; int A; }");
  Options options = Options::From("aidl Foo.aidl --lang=" + to_string(GetLanguage()));
  const string expected_stderr = "ERROR: Foo.aidl:1.22-24: Failed to resolve 'T'\n";
  CaptureStderr();
  EXPECT_NE(0, ::android::aidl::compile_aidl(options, io_delegate_));
  EXPECT_EQ(expected_stderr, GetCapturedStderr());
}

TEST_P(AidlTest, LongCommentWithinConstExpression) {
  io_delegate_.SetFileContents("Foo.aidl", "enum Foo { FOO = (1 << 1) /* comment */ | 0x0 }");
  Options options = Options::From("aidl Foo.aidl --lang=" + to_string(GetLanguage()));
  CaptureStderr();
  EXPECT_EQ(0, ::android::aidl::compile_aidl(options, io_delegate_));
  EXPECT_EQ("", GetCapturedStderr());
}

TEST_F(AidlTest, RejectUntypdeListAndMapInUnion) {
  io_delegate_.SetFileContents("a/Foo.aidl", "package a; union Foo { List l; Map m; }");
  Options options = Options::From("aidl a/Foo.aidl --lang=java -o out");
  std::string expectedErr =
      "ERROR: a/Foo.aidl:1.28-30: "
      "Encountered an untyped List or Map. The use of untyped List/Map is "
      "prohibited because it is not guaranteed that the objects in the list are recognizable in "
      "the receiving side. Consider switching to an array or a generic List/Map.\n"
      "ERROR: a/Foo.aidl:1.35-37: "
      "Encountered an untyped List or Map. The use of untyped List/Map is "
      "prohibited because it is not guaranteed that the objects in the list are recognizable in "
      "the receiving side. Consider switching to an array or a generic List/Map.\n";
  CaptureStderr();
  EXPECT_NE(0, ::android::aidl::compile_aidl(options, io_delegate_));
  EXPECT_EQ(expectedErr, GetCapturedStderr());
}

TEST_F(AidlTest, RejectUntypdeListAndMapInUnstructuredParcelable) {
  io_delegate_.SetFileContents("a/Foo.aidl", "package a; parcelable Foo { List l; Map m; }");
  Options options = Options::From("aidl a/Foo.aidl --lang=java -o out");
  std::string expectedErr =
      "ERROR: a/Foo.aidl:1.33-35: "
      "Encountered an untyped List or Map. The use of untyped List/Map is "
      "prohibited because it is not guaranteed that the objects in the list are recognizable in "
      "the receiving side. Consider switching to an array or a generic List/Map.\n"
      "ERROR: a/Foo.aidl:1.40-42: "
      "Encountered an untyped List or Map. The use of untyped List/Map is "
      "prohibited because it is not guaranteed that the objects in the list are recognizable in "
      "the receiving side. Consider switching to an array or a generic List/Map.\n";
  CaptureStderr();
  EXPECT_NE(0, ::android::aidl::compile_aidl(options, io_delegate_));
  EXPECT_EQ(expectedErr, GetCapturedStderr());
}

TEST_F(AidlTest, RejectNestedUntypedListAndMap) {
  io_delegate_.SetFileContents("a/Bar.aidl", "package a; parcelable Bar<T>;");
  io_delegate_.SetFileContents(
      "a/Foo.aidl", "package a; import a.Bar; parcelable Foo { Bar<List> a; Bar<Map> b; }");
  Options options = Options::From("aidl a/Foo.aidl -I . --lang=java -o out");
  std::string expectedErr =
      "ERROR: a/Foo.aidl:1.52-54: "
      "Encountered an untyped List or Map. The use of untyped List/Map is "
      "prohibited because it is not guaranteed that the objects in the list are recognizable in "
      "the receiving side. Consider switching to an array or a generic List/Map.\n"
      "ERROR: a/Foo.aidl:1.64-66: "
      "Encountered an untyped List or Map. The use of untyped List/Map is "
      "prohibited because it is not guaranteed that the objects in the list are recognizable in "
      "the receiving side. Consider switching to an array or a generic List/Map.\n";
  CaptureStderr();
  EXPECT_NE(0, ::android::aidl::compile_aidl(options, io_delegate_));
  EXPECT_EQ(expectedErr, GetCapturedStderr());
}

TEST_F(AidlTest, EnumWithDefaults_Java) {
  io_delegate_.SetFileContents("a/p/Enum.aidl", "package p; enum Enum { FOO, BAR }");
  io_delegate_.SetFileContents("a/p/Foo.aidl", R"(
package p;
import p.Enum;
parcelable Foo {
  Enum e = Enum.BAR;
})");
  CaptureStderr();
  auto options = Options::From("aidl -I a --lang java -o out a/p/Foo.aidl");
  EXPECT_EQ(0, aidl::compile_aidl(options, io_delegate_));
  auto err = GetCapturedStderr();
  EXPECT_EQ("", err);

  string code;
  EXPECT_TRUE(io_delegate_.GetWrittenContents("out/p/Foo.java", &code));
  EXPECT_THAT(code, testing::HasSubstr("byte e = p.Enum.BAR"));
}

TEST_F(AidlTest, EnumWithDefaults_Cpp) {
  io_delegate_.SetFileContents("a/p/Enum.aidl", "package p; enum Enum { FOO, BAR }");
  io_delegate_.SetFileContents("a/p/Foo.aidl", R"(
package p;
import p.Enum;
parcelable Foo {
  Enum e = Enum.BAR;
})");
  CaptureStderr();
  auto options = Options::From("aidl -I a --lang cpp -o out -h out a/p/Foo.aidl");
  EXPECT_EQ(0, aidl::compile_aidl(options, io_delegate_));
  auto err = GetCapturedStderr();
  EXPECT_EQ("", err);

  string code;
  EXPECT_TRUE(io_delegate_.GetWrittenContents("out/p/Foo.h", &code));
  EXPECT_THAT(code, testing::HasSubstr("::p::Enum e = ::p::Enum(::p::Enum::BAR);"));
}

TEST_F(AidlTest, EnumWithDefaults_Ndk) {
  io_delegate_.SetFileContents("a/p/Enum.aidl", "package p; enum Enum { FOO, BAR }");
  io_delegate_.SetFileContents("a/p/Foo.aidl", R"(
package p;
import p.Enum;
parcelable Foo {
  Enum e = Enum.BAR;
})");
  CaptureStderr();
  auto options = Options::From("aidl -I a --lang ndk -o out -h out a/p/Foo.aidl");
  EXPECT_EQ(0, aidl::compile_aidl(options, io_delegate_));
  auto err = GetCapturedStderr();
  EXPECT_EQ("", err);

  string code;
  EXPECT_TRUE(io_delegate_.GetWrittenContents("out/aidl/p/Foo.h", &code));
  EXPECT_THAT(code, testing::HasSubstr("::aidl::p::Enum e = ::aidl::p::Enum::BAR;"));
}

TEST_F(AidlTest, EnumWithDefaults_Rust) {
  io_delegate_.SetFileContents("a/p/Enum.aidl", "package p; enum Enum { FOO, BAR }");
  io_delegate_.SetFileContents("a/p/Foo.aidl", R"(
package p;
import p.Enum;
parcelable Foo {
  int  n = 42;
  Enum e = Enum.BAR;
})");
  CaptureStderr();
  auto options = Options::From("aidl -I a --lang rust -o out -h out a/p/Foo.aidl");
  EXPECT_EQ(0, aidl::compile_aidl(options, io_delegate_));
  auto err = GetCapturedStderr();
  EXPECT_EQ("", err);

  string code;
  EXPECT_TRUE(io_delegate_.GetWrittenContents("out/p/Foo.rs", &code));
  EXPECT_THAT(code, testing::HasSubstr(R"(
  fn default() -> Self {
    Self {
      n: 42,
      e: crate::mangled::_1_p_4_Enum::BAR,
    }
  })"));
}

TEST_P(AidlTest, EnumeratorIsConstantValue_DefaultValue) {
  import_paths_.insert("a");
  io_delegate_.SetFileContents("a/p/Enum.aidl", "package p; enum Enum { FOO = 1, BAR = 2}");
  CaptureStderr();
  const AidlDefinedType* type = Parse("a/p/Foo.aidl", R"(
package p;
import p.Enum;
parcelable Foo {
  int e = Enum.FOO | Enum.BAR;
})",
                                      typenames_, GetLanguage());
  auto err = GetCapturedStderr();
  EXPECT_EQ("", err);
  EXPECT_TRUE(type);
  const auto& fields = type->AsStructuredParcelable()->GetFields();
  EXPECT_EQ("int e = 3", fields[0]->ToString());
}

TEST_P(AidlTest, EnumeratorIsConstantValue_CanDefineOtherEnumerator) {
  CaptureStderr();
  const AidlDefinedType* type = Parse("a/p/Foo.aidl", R"(
@Backing(type="int")
enum Foo {
      STANDARD_SHIFT = 16,
      STANDARD_BT709 = 1 << STANDARD_SHIFT,
      STANDARD_BT601_625 = 2 << STANDARD_SHIFT,
}
)",
                                      typenames_, GetLanguage());
  auto err = GetCapturedStderr();
  EXPECT_EQ("", err);
  EXPECT_TRUE(type);
  const auto& enum_type = type->AsEnumDeclaration();
  string code;
  auto writer = CodeWriter::ForString(&code);
  DumpVisitor visitor(*writer);
  visitor.Visit(*enum_type);
  writer->Close();
  EXPECT_EQ(R"--(@Backing(type="int")
enum Foo {
  STANDARD_SHIFT = 16,
  STANDARD_BT709 = 65536,
  STANDARD_BT601_625 = 131072,
}
)--",
            code);
}

TEST_F(AidlTest, EnumDefaultShouldBeEnumerators) {
  io_delegate_.SetFileContents("a/p/Enum.aidl", "package p; enum Enum { FOO = 1, BAR = 2}");
  io_delegate_.SetFileContents("a/p/Foo.aidl", R"(
package p;
import p.Enum;
parcelable Foo {
  Enum e = Enum.FOO | Enum.BAR;
})");
  CaptureStderr();
  auto options = Options::From("aidl -I a --lang java -o out -h out a/p/Foo.aidl");
  EXPECT_EQ(1, aidl::compile_aidl(options, io_delegate_));
  auto err = GetCapturedStderr();
  EXPECT_EQ("ERROR: a/p/Foo.aidl:5.11-20: Invalid value (Enum.FOO|Enum.BAR) for enum p.Enum\n",
            err);
}

TEST_P(AidlTest, DefaultWithEmptyArray) {
  io_delegate_.SetFileContents("a/p/Foo.aidl", "package p; parcelable Foo { p.Bar[] bars = {}; }");
  io_delegate_.SetFileContents("a/p/Bar.aidl", "package p; parcelable Bar { }");
  CaptureStderr();
  auto options =
      Options::From("aidl -I a --lang " + to_string(GetLanguage()) + " -o out -h out a/p/Foo.aidl");
  EXPECT_EQ(0, aidl::compile_aidl(options, io_delegate_));
  auto err = GetCapturedStderr();
  EXPECT_EQ("", err);
}

TEST_P(AidlTest, RejectRefsInAnnotation) {
  io_delegate_.SetFileContents("a/p/IFoo.aidl",
                               "package p; interface IFoo {\n"
                               "  const String ANNOTATION = \"@Annotation\";\n"
                               "  @JavaPassthrough(annotation=ANNOTATION) void foo();\n"
                               "}");
  CaptureStderr();
  auto options =
      Options::From("aidl --lang " + to_string(GetLanguage()) + " -o out -h out a/p/IFoo.aidl");
  EXPECT_EQ(1, aidl::compile_aidl(options, io_delegate_));
  auto err = GetCapturedStderr();
  EXPECT_EQ(
      "ERROR: a/p/IFoo.aidl:3.31-41: Value must be a constant expression but contains reference to "
      "ANNOTATION.\n",
      err);
}

TEST_F(AidlTest, DefaultWithEnumValues) {
  io_delegate_.SetFileContents(
      "a/p/Foo.aidl",
      "package p; import p.Bar; parcelable Foo { Bar[] bars = { Bar.FOO, Bar.FOO }; }");
  io_delegate_.SetFileContents("a/p/Bar.aidl", "package p; enum Bar { FOO, BAR }");
  CaptureStderr();
  auto options = Options::From("aidl -I a --lang ndk -o out -h out a/p/Foo.aidl");
  EXPECT_EQ(0, aidl::compile_aidl(options, io_delegate_));
  auto err = GetCapturedStderr();
  EXPECT_EQ("", err);
  string code;
  EXPECT_TRUE(io_delegate_.GetWrittenContents("out/aidl/p/Foo.h", &code));
  EXPECT_THAT(
      code, testing::HasSubstr(
                "std::vector<::aidl::p::Bar> bars = {::aidl::p::Bar::FOO, ::aidl::p::Bar::FOO};"));
}

TEST_F(AidlTest, RejectsCircularReferencingEnumerators) {
  io_delegate_.SetFileContents("a/p/Foo.aidl", "package p; enum Foo { A = B, B }");
  CaptureStderr();
  auto options = Options::From("aidl -I a --lang ndk -o out -h out a/p/Foo.aidl");
  EXPECT_EQ(1, aidl::compile_aidl(options, io_delegate_));
  auto err = GetCapturedStderr();
  EXPECT_EQ(
      "ERROR: a/p/Foo.aidl:1.26-28: Found a circular reference: B -> A -> B\n"
      "ERROR: a/p/Foo.aidl:1.29-31: Found a circular reference: A -> B -> A\n",
      err);
}

TEST_F(AidlTest, RejectsCircularReferencingConsts) {
  io_delegate_.SetFileContents("a/p/Foo.aidl",
                               "package p; parcelable Foo { const int A = A + 1; }");
  CaptureStderr();
  auto options = Options::From("aidl -I a --lang ndk -o out -h out a/p/Foo.aidl");
  EXPECT_EQ(1, aidl::compile_aidl(options, io_delegate_));
  auto err = GetCapturedStderr();
  EXPECT_EQ("ERROR: a/p/Foo.aidl:1.42-44: Found a circular reference: A -> A\n", err);
}

TEST_F(AidlTest, RecursiveReferences) {
  io_delegate_.SetFileContents("a/p/Foo.aidl",
                               "package p; parcelable Foo { const int A = p.Bar.A + 1; }");
  io_delegate_.SetFileContents("a/p/Bar.aidl",
                               "package p; parcelable Bar { const int A = p.Baz.A + 1; }");
  io_delegate_.SetFileContents("a/p/Baz.aidl", "package p; parcelable Baz { const int A = 1; }");
  CaptureStderr();
  auto options = Options::From("aidl -I a --lang ndk -o out -h out a/p/Foo.aidl");
  EXPECT_EQ(0, aidl::compile_aidl(options, io_delegate_));
  EXPECT_EQ("", GetCapturedStderr());
}

TEST_P(AidlTest, UnknownConstReference) {
  io_delegate_.SetFileContents("Foo.aidl", " parcelable Foo { UnknownType field = UNKNOWN_REF; }");
  auto options =
      Options::From("aidl --lang " + to_string(GetLanguage()) + " -o out -h out Foo.aidl");
  const string err =
      "ERROR: Foo.aidl:1.18-30: Failed to resolve 'UnknownType'\n"
      "ERROR: Foo.aidl:1.38-50: Can't find UNKNOWN_REF in Foo\n"
      "ERROR: Foo.aidl:1.38-50: Unknown reference 'UNKNOWN_REF'\n";
  CaptureStderr();
  EXPECT_EQ(1, aidl::compile_aidl(options, io_delegate_));
  EXPECT_EQ(err, GetCapturedStderr());
}

TEST_P(AidlTest, JavaCompatibleBuiltinTypes) {
  string contents = R"(
import android.os.IBinder;
import android.os.IInterface;
interface IFoo {}
  )";
  EXPECT_NE(nullptr, Parse("IFoo.aidl", contents, typenames_, GetLanguage()));
}

TEST_P(AidlTest, WarningInterfaceName) {
  io_delegate_.SetFileContents("p/Foo.aidl", "interface Foo {}");
  auto options = Options::From("aidl --lang " + to_string(GetLanguage()) +
                               " -Weverything -o out -h out p/Foo.aidl");
  CaptureStderr();
  EXPECT_EQ(0, aidl::compile_aidl(options, io_delegate_));
  EXPECT_EQ("WARNING: p/Foo.aidl:1.1-10: Interface names should start with I. [-Winterface-name]\n",
            GetCapturedStderr());
}

TEST_P(AidlTest, ErrorInterfaceName) {
  io_delegate_.SetFileContents("p/Foo.aidl", "interface Foo {}");
  auto options = Options::From("aidl --lang " + to_string(GetLanguage()) +
                               " -Weverything -Werror -o out -h out p/Foo.aidl");
  CaptureStderr();
  EXPECT_EQ(1, aidl::compile_aidl(options, io_delegate_));
  EXPECT_EQ("ERROR: p/Foo.aidl:1.1-10: Interface names should start with I. [-Winterface-name]\n",
            GetCapturedStderr());
}

TEST_F(AidlTest, RejectsIncorrectOutputFilePathOnLegacyCppInput) {
  const std::string input_file = "base/p/q/IFoo.aidl";
  const std::string header_dir = "out/";
  const std::string output_file = "out/base/p/q/IFoo.cpp";
  const std::string package = "p.q";  // not base.p.q
  io_delegate_.SetFileContents(input_file, "package " + package + "; interface IFoo {}");

  auto options = Options::From({"aidl-cpp", input_file, header_dir, output_file});
  CaptureStderr();
  EXPECT_EQ(1, aidl::compile_aidl(options, io_delegate_));
  EXPECT_THAT(
      GetCapturedStderr(),
      testing::StartsWith(
          "ERROR: base/p/q/IFoo.aidl:1.13-23: Output file is expected to be at out/p/q/IFoo.cpp, "
          "but is out/base/p/q/IFoo.cpp."));
}

TEST_F(AidlTest, FormatCommentsForJava) {
  using android::aidl::FormatCommentsForJava;

  struct TestCase {
    vector<Comment> comments;
    string formatted;
  };
  vector<TestCase> testcases = {
      {{}, ""},
      {{{"// line comments\n"}}, "// line comments\n"},
      {{{"// @hide \n"}}, "// @hide \n"},
      // Transform the last block comment as Javadoc.
      {{{"/*\n"
         " * Hello, world!\n"
         " */"}},
       "/**\n"
       " * Hello, world!\n"
       " */"},
      {{{"/* @hide */"}}, "/** @hide */"},
      {{{"/**\n"
         "   @param foo ...\n"
         "*/"}},
       "/**\n"
       "   @param foo ...\n"
       "*/"},
      {{{"/* @hide */"}, {"/* @hide */"}}, "/* @hide *//** @hide */"},
      {{{"/* @deprecated first */"}, {"/* @deprecated second */"}},
       "/* @deprecated first *//** @deprecated second */"},
      {{{"/* @deprecated */"}, {"/** @param foo */"}}, "/* @deprecated *//** @param foo */"},
      // Line comments are printed as they are
      {{{"/* @deprecated */"}, {"// line comments\n"}}, "/* @deprecated */// line comments\n"},
  };
  for (const auto& [input, formatted] : testcases) {
    EXPECT_EQ(formatted, FormatCommentsForJava(input));
  }
}

TEST_F(AidlTest, HideIsNotForArgs) {
  io_delegate_.SetFileContents("IFoo.aidl",
                               "interface IFoo {\n"
                               "  void foo(in @Hide int x);\n"
                               "}");
  auto options = Options::From("aidl --lang=java IFoo.aidl");
  CaptureStderr();
  EXPECT_EQ(1, aidl::compile_aidl(options, io_delegate_));
  EXPECT_THAT(GetCapturedStderr(), HasSubstr("@Hide is not available"));
}

TEST_F(AidlTest, SuppressWarningsIsNotForArgs) {
  io_delegate_.SetFileContents(
      "IFoo.aidl",
      "interface IFoo {\n"
      "  void foo(in @SuppressWarnings(value=\"inout-parameter\") int x);\n"
      "}");
  auto options = Options::From("aidl --lang=java IFoo.aidl");
  CaptureStderr();
  EXPECT_EQ(1, aidl::compile_aidl(options, io_delegate_));
  EXPECT_THAT(GetCapturedStderr(), HasSubstr("@SuppressWarnings is not available"));
}

struct TypeParam {
  string kind;
  string literal;
};

const TypeParam kTypeParams[] = {
    {"primitive", "int"},   {"primitiveArray", "int[]"},
    {"String", "String"},   {"StringArray", "String[]"},
    {"IBinder", "IBinder"}, {"ParcelFileDescriptor", "ParcelFileDescriptor"},
    {"parcelable", "Foo"},  {"enum", "a.Enum"},
    {"union", "a.Union"},   {"interface", "a.IBar"},
};

const std::map<std::string, std::string> kListSupportExpectations = {
    {"cpp_primitive", "A generic type cannot have any primitive type parameters."},
    {"java_primitive", "A generic type cannot have any primitive type parameters."},
    {"ndk_primitive", "A generic type cannot have any primitive type parameters."},
    {"rust_primitive", "A generic type cannot have any primitive type parameters."},
    {"cpp_primitiveArray", "List of arrays is not supported."},
    {"java_primitiveArray", "List of arrays is not supported."},
    {"ndk_primitiveArray", "List of arrays is not supported."},
    {"rust_primitiveArray", "List of arrays is not supported."},
    {"cpp_String", ""},
    {"java_String", ""},
    {"ndk_String", ""},
    {"rust_String", ""},
    {"cpp_StringArray", "List of arrays is not supported."},
    {"java_StringArray", "List of arrays is not supported."},
    {"ndk_StringArray", "List of arrays is not supported."},
    {"rust_StringArray", "List of arrays is not supported."},
    {"cpp_IBinder", ""},
    {"java_IBinder", ""},
    {"ndk_IBinder", "List<IBinder> is not supported. List in NDK doesn't support IBinder."},
    {"rust_IBinder", ""},
    {"cpp_ParcelFileDescriptor", ""},
    {"java_ParcelFileDescriptor", ""},
    {"ndk_ParcelFileDescriptor", ""},
    {"rust_ParcelFileDescriptor", ""},
    {"cpp_interface", "List<a.IBar> is not supported."},
    {"java_interface", "List<a.IBar> is not supported."},
    {"ndk_interface", "List<a.IBar> is not supported."},
    {"rust_interface", "List<a.IBar> is not supported."},
    {"cpp_parcelable", ""},
    {"java_parcelable", ""},
    {"ndk_parcelable", ""},
    {"rust_parcelable", ""},
    {"cpp_enum", "A generic type cannot have any primitive type parameters."},
    {"java_enum", "A generic type cannot have any primitive type parameters."},
    {"ndk_enum", "A generic type cannot have any primitive type parameters."},
    {"rust_enum", "A generic type cannot have any primitive type parameters."},
    {"cpp_union", ""},
    {"java_union", ""},
    {"ndk_union", ""},
    {"rust_union", ""},
};

const std::map<std::string, std::string> kArraySupportExpectations = {
    {"cpp_primitive", ""},
    {"java_primitive", ""},
    {"ndk_primitive", ""},
    {"rust_primitive", ""},
    {"cpp_primitiveArray", "Can only have one dimensional arrays."},
    {"java_primitiveArray", "Can only have one dimensional arrays."},
    {"ndk_primitiveArray", "Can only have one dimensional arrays."},
    {"rust_primitiveArray", "Can only have one dimensional arrays."},
    {"cpp_String", ""},
    {"java_String", ""},
    {"ndk_String", ""},
    {"rust_String", ""},
    {"cpp_StringArray", "Can only have one dimensional arrays."},
    {"java_StringArray", "Can only have one dimensional arrays."},
    {"ndk_StringArray", "Can only have one dimensional arrays."},
    {"rust_StringArray", "Can only have one dimensional arrays."},
    {"cpp_IBinder", ""},
    {"java_IBinder", ""},
    {"ndk_IBinder", "The ndk backend does not support array of IBinder"},
    {"rust_IBinder", "The rust backend does not support array of IBinder"},
    {"cpp_ParcelFileDescriptor", ""},
    {"java_ParcelFileDescriptor", ""},
    {"ndk_ParcelFileDescriptor", ""},
    {"rust_ParcelFileDescriptor", ""},
    {"cpp_interface", "Binder type cannot be an array"},
    {"java_interface", "Binder type cannot be an array"},
    {"ndk_interface", "Binder type cannot be an array"},
    {"rust_interface", "Binder type cannot be an array"},
    {"cpp_parcelable", ""},
    {"java_parcelable", ""},
    {"ndk_parcelable", ""},
    {"rust_parcelable", ""},
    {"cpp_enum", ""},
    {"java_enum", ""},
    {"ndk_enum", ""},
    {"rust_enum", ""},
    {"cpp_union", ""},
    {"java_union", ""},
    {"ndk_union", ""},
    {"rust_union", ""},
};

class AidlTypeParamTest : public testing::TestWithParam<std::tuple<Options::Language, TypeParam>> {
 public:
  void Run(const std::string& generic_type_decl,
           const std::map<std::string, std::string>& expectations) {
    const auto& param = GetParam();
    const auto& lang = to_string(std::get<0>(param));
    const auto& kind = std::get<1>(param).kind;

    FakeIoDelegate io;
    io.SetFileContents("a/IBar.aidl", "package a; interface IBar { }");
    io.SetFileContents("a/Enum.aidl", "package a; enum Enum { A }");
    io.SetFileContents("a/Union.aidl", "package a; union Union { int a; }");
    std::string decl = fmt::format(generic_type_decl, std::get<1>(param).literal);
    io.SetFileContents("a/Foo.aidl", "package a; parcelable Foo { " + decl + " f; }");

    const auto options =
        Options::From(fmt::format("aidl -I . --lang={} a/Foo.aidl -o out -h out", lang));
    CaptureStderr();
    compile_aidl(options, io);
    auto it = expectations.find(lang + "_" + kind);
    EXPECT_TRUE(it != expectations.end());
    const string err = GetCapturedStderr();
    if (it->second.empty()) {
      EXPECT_EQ("", err);
    } else {
      EXPECT_THAT(err, testing::HasSubstr(it->second));
    }
  }
};

INSTANTIATE_TEST_SUITE_P(
    AidlTestSuite, AidlTypeParamTest,
    testing::Combine(testing::Values(Options::Language::CPP, Options::Language::JAVA,
                                     Options::Language::NDK, Options::Language::RUST),
                     testing::ValuesIn(kTypeParams)),
    [](const testing::TestParamInfo<std::tuple<Options::Language, TypeParam>>& info) {
      return to_string(std::get<0>(info.param)) + "_" + std::get<1>(info.param).kind;
    });

TEST_P(AidlTypeParamTest, ListSupportedTypes) {
  Run("List<{}>", kListSupportExpectations);
}

TEST_P(AidlTypeParamTest, ArraySupportedTypes) {
  Run("{}[]", kArraySupportExpectations);
}

}  // namespace aidl
}  // namespace android