File: EcjParser.java

package info (click to toggle)
android-platform-tools-base 2.2.2-1
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 123,960 kB
  • ctags: 236,781
  • sloc: java: 826,450; xml: 45,920; cpp: 2,526; ansic: 1,432; sh: 537; lisp: 110; makefile: 21
file content (2893 lines) | stat: -rw-r--r-- 114,615 bytes parent folder | download | duplicates (2)
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
/*
 * Copyright (C) 2013 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.
 */

package com.android.tools.lint;

import static com.android.SdkConstants.INT_DEF_ANNOTATION;
import static com.android.SdkConstants.STRING_DEF_ANNOTATION;
import static com.android.SdkConstants.UTF_8;

import com.android.SdkConstants;
import com.android.annotations.NonNull;
import com.android.annotations.Nullable;
import com.android.annotations.VisibleForTesting;
import com.android.sdklib.IAndroidTarget;
import com.android.tools.lint.client.api.JavaParser;
import com.android.tools.lint.client.api.LintClient;
import com.android.tools.lint.detector.api.ClassContext;
import com.android.tools.lint.detector.api.DefaultPosition;
import com.android.tools.lint.detector.api.JavaContext;
import com.android.tools.lint.detector.api.Location;
import com.android.tools.lint.detector.api.Project;
import com.android.tools.lint.detector.api.Scope;
import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import com.google.common.collect.Lists;
import com.google.common.collect.MapMaker;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.intellij.psi.PsiJavaFile;

import org.eclipse.jdt.core.compiler.CategorizedProblem;
import org.eclipse.jdt.core.compiler.IProblem;
import org.eclipse.jdt.internal.compiler.CompilationResult;
import org.eclipse.jdt.internal.compiler.Compiler;
import org.eclipse.jdt.internal.compiler.DefaultErrorHandlingPolicies;
import org.eclipse.jdt.internal.compiler.ICompilerRequestor;
import org.eclipse.jdt.internal.compiler.IErrorHandlingPolicy;
import org.eclipse.jdt.internal.compiler.IProblemFactory;
import org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration;
import org.eclipse.jdt.internal.compiler.ast.AbstractVariableDeclaration;
import org.eclipse.jdt.internal.compiler.ast.AllocationExpression;
import org.eclipse.jdt.internal.compiler.ast.Annotation;
import org.eclipse.jdt.internal.compiler.ast.Argument;
import org.eclipse.jdt.internal.compiler.ast.ArrayInitializer;
import org.eclipse.jdt.internal.compiler.ast.Block;
import org.eclipse.jdt.internal.compiler.ast.CharLiteral;
import org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration;
import org.eclipse.jdt.internal.compiler.ast.DoubleLiteral;
import org.eclipse.jdt.internal.compiler.ast.ExplicitConstructorCall;
import org.eclipse.jdt.internal.compiler.ast.Expression;
import org.eclipse.jdt.internal.compiler.ast.FalseLiteral;
import org.eclipse.jdt.internal.compiler.ast.FieldDeclaration;
import org.eclipse.jdt.internal.compiler.ast.FloatLiteral;
import org.eclipse.jdt.internal.compiler.ast.IntLiteral;
import org.eclipse.jdt.internal.compiler.ast.Literal;
import org.eclipse.jdt.internal.compiler.ast.LocalDeclaration;
import org.eclipse.jdt.internal.compiler.ast.LongLiteral;
import org.eclipse.jdt.internal.compiler.ast.MagicLiteral;
import org.eclipse.jdt.internal.compiler.ast.MemberValuePair;
import org.eclipse.jdt.internal.compiler.ast.MessageSend;
import org.eclipse.jdt.internal.compiler.ast.NameReference;
import org.eclipse.jdt.internal.compiler.ast.NullLiteral;
import org.eclipse.jdt.internal.compiler.ast.NumberLiteral;
import org.eclipse.jdt.internal.compiler.ast.Statement;
import org.eclipse.jdt.internal.compiler.ast.StringLiteral;
import org.eclipse.jdt.internal.compiler.ast.TrueLiteral;
import org.eclipse.jdt.internal.compiler.ast.TryStatement;
import org.eclipse.jdt.internal.compiler.ast.TypeDeclaration;
import org.eclipse.jdt.internal.compiler.ast.TypeReference;
import org.eclipse.jdt.internal.compiler.ast.UnionTypeReference;
import org.eclipse.jdt.internal.compiler.batch.FileSystem;
import org.eclipse.jdt.internal.compiler.classfmt.ClassFileConstants;
import org.eclipse.jdt.internal.compiler.env.ICompilationUnit;
import org.eclipse.jdt.internal.compiler.env.INameEnvironment;
import org.eclipse.jdt.internal.compiler.impl.BooleanConstant;
import org.eclipse.jdt.internal.compiler.impl.ByteConstant;
import org.eclipse.jdt.internal.compiler.impl.CharConstant;
import org.eclipse.jdt.internal.compiler.impl.CompilerOptions;
import org.eclipse.jdt.internal.compiler.impl.Constant;
import org.eclipse.jdt.internal.compiler.impl.DoubleConstant;
import org.eclipse.jdt.internal.compiler.impl.FloatConstant;
import org.eclipse.jdt.internal.compiler.impl.IntConstant;
import org.eclipse.jdt.internal.compiler.impl.LongConstant;
import org.eclipse.jdt.internal.compiler.impl.ShortConstant;
import org.eclipse.jdt.internal.compiler.impl.StringConstant;
import org.eclipse.jdt.internal.compiler.lookup.AnnotationBinding;
import org.eclipse.jdt.internal.compiler.lookup.Binding;
import org.eclipse.jdt.internal.compiler.lookup.ElementValuePair;
import org.eclipse.jdt.internal.compiler.lookup.FieldBinding;
import org.eclipse.jdt.internal.compiler.lookup.LocalVariableBinding;
import org.eclipse.jdt.internal.compiler.lookup.LookupEnvironment;
import org.eclipse.jdt.internal.compiler.lookup.MethodBinding;
import org.eclipse.jdt.internal.compiler.lookup.NestedTypeBinding;
import org.eclipse.jdt.internal.compiler.lookup.PackageBinding;
import org.eclipse.jdt.internal.compiler.lookup.ProblemBinding;
import org.eclipse.jdt.internal.compiler.lookup.ProblemFieldBinding;
import org.eclipse.jdt.internal.compiler.lookup.ProblemMethodBinding;
import org.eclipse.jdt.internal.compiler.lookup.ProblemPackageBinding;
import org.eclipse.jdt.internal.compiler.lookup.ProblemReferenceBinding;
import org.eclipse.jdt.internal.compiler.lookup.ReferenceBinding;
import org.eclipse.jdt.internal.compiler.lookup.TypeBinding;
import org.eclipse.jdt.internal.compiler.lookup.TypeConstants;
import org.eclipse.jdt.internal.compiler.lookup.VariableBinding;
import org.eclipse.jdt.internal.compiler.parser.Parser;
import org.eclipse.jdt.internal.compiler.problem.AbortCompilation;
import org.eclipse.jdt.internal.compiler.problem.DefaultProblemFactory;
import org.eclipse.jdt.internal.compiler.problem.ProblemReporter;

import java.io.File;
import java.lang.reflect.Modifier;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.EnumSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;

import lombok.ast.Catch;
import lombok.ast.Identifier;
import lombok.ast.MethodDeclaration;
import lombok.ast.Node;
import lombok.ast.Position;
import lombok.ast.StrictListAccessor;
import lombok.ast.Try;
import lombok.ast.VariableDeclaration;
import lombok.ast.VariableDefinition;
import lombok.ast.VariableDefinitionEntry;
import lombok.ast.ecj.EcjTreeConverter;

/**
 * Java parser which uses ECJ for parsing and type attribution
 */
// Currently ships with deprecated API support
@SuppressWarnings({"deprecation", "UnusedParameters"})
public class EcjParser extends JavaParser {
    private static final boolean DEBUG_DUMP_PARSE_ERRORS = false;

    /**
     * Whether we're going to keep the ECJ compiler mLookupEnvironment around between
     * the parse phase and disposal. The lookup environment is important for type attribution.
     * We should be able to inline this field to true, but making it optional now to allow
     * people to revert this behavior in the field immediately if there's an unexpected
     * problem.
     */
    private static final boolean KEEP_LOOKUP_ENVIRONMENT = !Boolean.getBoolean("lint.reset.ecj");

    private final LintClient mClient;
    private final Project mProject;
    private Map<File, EcjSourceFile> mSourceUnits;
    @Deprecated private Map<String, TypeDeclaration> mTypeUnits;
    private Parser mParser;
    protected EcjResult mEcjResult;
    private Object mResolver;

    public EcjParser(@NonNull LintCliClient client, @Nullable Project project) {
        mClient = client;
        mProject = project;
        mParser = getParser();
    }

    @NonNull
    @Override
    public com.android.tools.lint.client.api.JavaEvaluator getEvaluator() {
        throw new RuntimeException("ECJ module temporarily disabled!");
    }

    /**
     * Create the default compiler options
     */
    public static CompilerOptions createCompilerOptions() {
        CompilerOptions options = new CompilerOptions();

        // Always using JDK 7 rather than basing it on project metadata since we
        // don't do compilation error validation in lint (we leave that to the IDE's
        // error parser or the command line build's compilation step); we want an
        // AST that is as tolerant as possible.
        long languageLevel = ClassFileConstants.JDK1_8;
        options.complianceLevel = languageLevel;
        options.sourceLevel = languageLevel;
        options.targetJDK = languageLevel;
        options.originalComplianceLevel = languageLevel;
        options.originalSourceLevel = languageLevel;
        options.inlineJsrBytecode = true; // >1.5

        options.parseLiteralExpressionsAsConstants = true;
        options.analyseResourceLeaks = false;
        options.docCommentSupport = false;
        options.defaultEncoding = UTF_8;
        options.suppressOptionalErrors = true;
        options.generateClassFiles = false;
        options.isAnnotationBasedNullAnalysisEnabled = false;
        options.reportUnusedDeclaredThrownExceptionExemptExceptionAndThrowable = false;
        options.reportUnusedDeclaredThrownExceptionIncludeDocCommentReference = false;
        options.reportUnusedDeclaredThrownExceptionWhenOverriding = false;
        options.reportUnusedParameterIncludeDocCommentReference = false;
        options.reportUnusedParameterWhenImplementingAbstract = false;
        options.reportUnusedParameterWhenOverridingConcrete = false;
        options.suppressWarnings = true;
        options.processAnnotations = true;
        options.storeAnnotations = true;
        options.verbose = false;
        return options;
    }

    public static long getLanguageLevel(int major, int minor) {
        assert major == 1;
        switch (minor) {
            case 5: return ClassFileConstants.JDK1_5;
            case 6: return ClassFileConstants.JDK1_6;
            case 8: return ClassFileConstants.JDK1_8;
            case 7:
            default:
                return ClassFileConstants.JDK1_8;
        }
    }

    private Parser getParser() {
        if (mParser == null) {
            CompilerOptions options = createCompilerOptions();
            ProblemReporter problemReporter = new ProblemReporter(
                    DefaultErrorHandlingPolicies.exitOnFirstError(),
                    options,
                    new DefaultProblemFactory());
            mParser = new Parser(problemReporter,
                    options.parseLiteralExpressionsAsConstants);
            mParser.javadocParser.checkDocComment = false;
        }
        return mParser;
    }

    @Override
    public void prepareJavaParse(@NonNull final List<JavaContext> contexts) {
        if (mProject == null || contexts.isEmpty()) {
            return;
        }

        List<EcjSourceFile> sources = Lists.newArrayListWithExpectedSize(contexts.size());
        mSourceUnits = Maps.newHashMapWithExpectedSize(sources.size());
        for (JavaContext context : contexts) {
            String contents = context.getContents();
            if (contents == null) {
                continue;
            }
            File file = context.file;
            EcjSourceFile unit = new EcjSourceFile(contents, file);
            sources.add(unit);
            mSourceUnits.put(file, unit);
        }
        List<String> classPath = computeClassPath(contexts);
        try {
            mEcjResult = parse(createCompilerOptions(), sources, classPath, mClient);
            mResolver = null;

            if (DEBUG_DUMP_PARSE_ERRORS) {
                for (CompilationUnitDeclaration unit : mEcjResult.getCompilationUnits()) {
                    // so maybe I don't need my map!!
                    CategorizedProblem[] problems = unit.compilationResult()
                            .getAllProblems();
                    if (problems != null) {
                        for (IProblem problem : problems) {
                            if (problem == null || !problem.isError()) {
                                continue;
                            }
                            System.out.println(
                                    new String(problem.getOriginatingFileName()) + ":"
                                    + (problem.isError() ? "Error" : "Warning") + ": "
                                    + problem.getSourceLineNumber() + ": " + problem.getMessage());
                        }
                    }
                }
            }
            throw new RuntimeException("ECJ module temporarily disabled!");
        } catch (Throwable t) {
            mClient.log(t, "ECJ compiler crashed");
        }
    }

    /**
     * A result from an ECJ compilation. In addition to the {@link #mSourceToUnit} it also
     * returns the {@link #mNameEnvironment} and {@link #mLookupEnvironment} which are sometimes
     * needed after parsing to perform for example type attribution. <b>NOTE</b>: Clients are
     * expected to dispose of the {@link #mNameEnvironment} when done with the compilation units!
     */
    public static class EcjResult {
        @Nullable private final INameEnvironment mNameEnvironment;
        @Nullable private final LookupEnvironment mLookupEnvironment;
        @NonNull  private final Map<EcjSourceFile, CompilationUnitDeclaration> mSourceToUnit;
        @Nullable private Map<ICompilationUnit, PsiJavaFile> mPsiMap;
        @Nullable private Map<CompilationUnitDeclaration, EcjSourceFile> mUnitToSource;
        @Nullable Map<Binding, CompilationUnitDeclaration> mBindingToUnit;
        private Object mPsiManager;

        public EcjResult(@Nullable INameEnvironment nameEnvironment,
                @Nullable LookupEnvironment lookupEnvironment,
                @NonNull Map<EcjSourceFile, CompilationUnitDeclaration> compilationUnits) {
            mNameEnvironment = nameEnvironment;
            mLookupEnvironment = lookupEnvironment;
            mSourceToUnit = compilationUnits;
        }

        @Nullable
        public LookupEnvironment getLookupEnvironment() {
            return mLookupEnvironment;
        }

        public void setPsiManager(@NonNull Object psiManager) {
            mPsiManager = psiManager;
        }

        @Nullable
        public PsiJavaFile findFile(
                @NonNull EcjSourceFile sourceUnit,
                @Nullable String source) {
            if (mPsiMap != null) {
                PsiJavaFile file = mPsiMap.get(sourceUnit);
                if (file != null) {
                    return file;
                }
            } else {
                // Using weak values to allow map to occasionally refresh
                mPsiMap = new MapMaker()
                        .initialCapacity(mSourceToUnit.size())
                        .weakValues()
                        .concurrencyLevel(1)
                        .makeMap();

            }

            CompilationUnitDeclaration unit = getCompilationUnit(sourceUnit);
            if (unit != null) {
                PsiJavaFile file = null;
                assert mPsiMap != null;
                mPsiMap.put(sourceUnit, file);
                throw new RuntimeException("ECJ module temporarily disabled!");
            }

            return null;
        }

        @Nullable
        public PsiJavaFile findFileContaining(@Nullable ReferenceBinding declaringClass) {
            if (mUnitToSource == null) {
                int size = mSourceToUnit.size();
                mUnitToSource = Maps.newHashMapWithExpectedSize(size);
                mBindingToUnit = Maps.newHashMapWithExpectedSize(size);
                for (Map.Entry<EcjSourceFile, CompilationUnitDeclaration> entry
                        : mSourceToUnit.entrySet()) {
                    CompilationUnitDeclaration unit = entry.getValue();
                    EcjSourceFile sourceUnit = entry.getKey();
                    //noinspection ConstantConditions
                    mUnitToSource.put(unit, sourceUnit);

                    if (unit.types == null) {
                        // Usually not the case, but for really misconfigured projects with broken
                        // classpath setup etc this is possible
                        continue;
                    }

                    for (TypeDeclaration declaration : unit.types) {
                        //noinspection ConstantConditions
                        recordTypeAssociation(mBindingToUnit, declaration, unit);
                    }
                }
            }

            assert mBindingToUnit != null;
            while (declaringClass != null) {
                CompilationUnitDeclaration unit = mBindingToUnit.get(declaringClass);
                if (unit != null) {
                    EcjSourceFile sourceUnit = mUnitToSource.get(unit);
                    if (sourceUnit != null) {
                        return findFile(sourceUnit, null);
                    }
                }
                declaringClass = declaringClass.enclosingType();
            }

            return null;
        }

        private static void recordTypeAssociation(
                @NonNull Map<Binding, CompilationUnitDeclaration> bindingMap,
                @NonNull TypeDeclaration declaration,
                @NonNull CompilationUnitDeclaration unit) {
            bindingMap.put(declaration.binding, unit);
            if (declaration.memberTypes != null) {
                for (TypeDeclaration d : declaration.memberTypes) {
                    recordTypeAssociation(bindingMap, d, unit);
                }
            }
        }

        /**
         * Returns the collection of compilation units found by the parse task
         *
         * @return a read-only collection of compilation units
         */
        @NonNull
        public Collection<CompilationUnitDeclaration> getCompilationUnits() {
            return mSourceToUnit.values();
        }

        /**
         * Returns the compilation unit parsed from the given source unit, if any
         *
         * @param sourceUnit the original source passed to ECJ
         * @return the corresponding compilation unit, if created
         */
        @Nullable
        public CompilationUnitDeclaration getCompilationUnit(
                @NonNull EcjSourceFile sourceUnit) {
            return mSourceToUnit.get(sourceUnit);
        }

        /**
         * Removes the compilation unit for the given source unit, if any. Used when individual
         * source units are disposed to allow memory to be freed up.
         *
         * @param sourceUnit the source unit
         */
        void removeCompilationUnit(@NonNull EcjSourceFile sourceUnit) {
            mSourceToUnit.remove(sourceUnit);
        }

        /**
         * Disposes this parser result, allowing various ECJ data structures to be freed up even if
         * the parser instance hangs around.
         */
        public void dispose() {
            if (mNameEnvironment != null) {
                mNameEnvironment.cleanup();
            }

            if (mLookupEnvironment != null) {
                mLookupEnvironment.reset();
            }

            mSourceToUnit.clear();
        }
    }

    /** Parse the given source units and class path and store it into the given output map */
    @NonNull
    public static EcjResult parse(
            CompilerOptions options,
            @NonNull List<EcjSourceFile> sourceUnits,
            @NonNull List<String> classPath,
            @Nullable LintClient client) {
        Map<EcjSourceFile, CompilationUnitDeclaration> outputMap =
                Maps.newHashMapWithExpectedSize(sourceUnits.size());

        INameEnvironment environment = new FileSystem(
                classPath.toArray(new String[classPath.size()]), new String[0],
                options.defaultEncoding);
        IErrorHandlingPolicy policy = DefaultErrorHandlingPolicies.proceedWithAllProblems();
        IProblemFactory problemFactory = new DefaultProblemFactory(Locale.getDefault());
        ICompilerRequestor requestor = new ICompilerRequestor() {
            @Override
            public void acceptResult(CompilationResult result) {
                // Not used; we need the corresponding CompilationUnitDeclaration for the source
                // units (the AST parsed from source) which we don't get access to here, so we
                // instead subclass AST to get our hands on them.
            }
        };

        NonGeneratingCompiler compiler = new NonGeneratingCompiler(environment, policy, options,
                requestor, problemFactory, outputMap);
        try {
            compiler.compile(sourceUnits.toArray(new ICompilationUnit[sourceUnits.size()]));
        } catch (OutOfMemoryError e) {
            environment.cleanup();

            // Since we're running out of memory, if it's all still held we could potentially
            // fail attempting to log the failure. Actively get rid of the large ECJ data
            // structure references first so minimize the chance of that
            //noinspection UnusedAssignment
            compiler = null;
            //noinspection UnusedAssignment
            environment = null;
            //noinspection UnusedAssignment
            requestor = null;
            //noinspection UnusedAssignment
            problemFactory = null;
            //noinspection UnusedAssignment
            policy = null;

            String msg = "Ran out of memory analyzing .java sources with ECJ: Some lint checks "
                    + "may not be accurate (missing type information from the compiler)";
            if (client != null) {
                // Don't log exception too; this isn't a compiler error per se where we
                // need to pin point the exact unlucky code that asked for memory when it
                // had already run out
                client.log(null, msg);
            } else {
                System.out.println(msg);
            }
        } catch (Throwable t) {
            if (client != null) {
                CompilationUnitDeclaration currentUnit = compiler.getCurrentUnit();
                if (currentUnit == null || currentUnit.getFileName() == null) {
                    client.log(t, "ECJ compiler crashed");
                } else {
                    client.log(t, "ECJ compiler crashed processing %1$s",
                            new String(currentUnit.getFileName()));
                }
            } else {
                t.printStackTrace();
            }

            environment.cleanup();
            environment = null;
        }

        LookupEnvironment lookupEnvironment = compiler != null ? compiler.lookupEnvironment : null;
        EcjResult ecjResult = new EcjResult(environment, lookupEnvironment, outputMap);
        Object psiManager = null;
        ecjResult.setPsiManager(psiManager);
        throw new RuntimeException("ECJ module temporarily disabled!");
    }

    @NonNull
    private List<String> computeClassPath(@NonNull List<JavaContext> contexts) {
        assert mProject != null;
        List<String> classPath = Lists.newArrayList();

        IAndroidTarget compileTarget = mProject.getBuildTarget();
        if (compileTarget != null) {
            String androidJar = compileTarget.getPath(IAndroidTarget.ANDROID_JAR);
            if (androidJar != null && new File(androidJar).exists()) {
                classPath.add(androidJar);
            }
        } else if (!mProject.isAndroidProject()) {
            // Gradle Java library? We don't have the correct classpath here.
            String bootClassPath = System.getProperty("sun.boot.class.path");
            if (bootClassPath != null) {
                for (String path : Splitter.on(File.pathSeparatorChar).split(bootClassPath)) {
                    // Sadly sometimes the path doesn't exist (e.g. the boot classpath property
                    // includes jar files that don't exist, or directories) so we need to validate
                    // these
                    if (new File(path).isFile()) {
                        classPath.add(path);
                    }
                }
            }
        }

        Set<File> libraries = Sets.newHashSet();
        Set<String> names = Sets.newHashSet();
        for (File library : mProject.getJavaLibraries(true)) {
            libraries.add(library);
            names.add(getLibraryName(library));
        }
        for (Project project : mProject.getAllLibraries()) {
            for (File library : project.getJavaLibraries(true)) {
                String name = getLibraryName(library);
                // Avoid pulling in android-support-v4.jar from libraries etc
                // since we're pointing to the local copies rather than the real
                // maven/gradle source copies
                if (!names.contains(name)) {
                    libraries.add(library);
                    names.add(name);
                }
            }
        }

        for (File file : libraries) {
            if (file.exists()) {
                classPath.add(file.getPath());
            }
        }

        // In incremental mode we may need to point to other sources in the project
        // for type resolution
        EnumSet<Scope> scope = contexts.get(0).getScope();
        if (!scope.contains(Scope.ALL_JAVA_FILES)) {
            // May need other compiled classes too
            for (File dir : mProject.getJavaClassFolders()) {
                if (dir.exists()) {
                    classPath.add(dir.getPath());
                }
            }
        }

        return classPath;
    }

    @NonNull
    private static String getLibraryName(@NonNull File library) {
        String name = library.getName();
        if (name.equals(SdkConstants.FN_CLASSES_JAR)) {
            // For AAR artifacts they'll all clash with "classes.jar"; include more unique
            // context
            String path = library.getPath();
            int index = path.indexOf("exploded-aar");
            if (index != -1) {
                return path.substring(index);
            } else {
                index = path.indexOf("exploded-bundles");
                if (index != -1) {
                    return path.substring(index);
                }
            }
            File parent = library.getParentFile();
            if (parent != null) {
                return parent.getName() + File.separatorChar + name;
            }
        }
        return name;
    }

    @Override
    public PsiJavaFile parseJavaToPsi(@NonNull JavaContext context) {
        if (mSourceUnits != null && mEcjResult != null) {
            EcjSourceFile sourceUnit = mSourceUnits.get(context.file);
            if (sourceUnit != null) {
                try {
                    return mEcjResult.findFile(sourceUnit, context.getContents());
                } catch (Throwable t) {
                    mClient.log(t, "Failed converting ECJ parse tree to PSI for file %1$s",
                            context.file.getPath());
                    return null;
                }
            }
        }

        return null;
    }

    @Override
    public Node parseJava(@NonNull JavaContext context) {
        String code = context.getContents();
        if (code == null) {
            return null;
        }

        CompilationUnitDeclaration unit = getParsedUnit(context, code);
        try {
            EcjTreeConverter converter = new EcjTreeConverter();
            converter.visit(code, unit);
            List<? extends Node> nodes = converter.getAll();

            if (nodes != null) {
                // There could be more than one node when there are errors; pick out the
                // compilation unit node
                for (Node node : nodes) {
                    if (node instanceof lombok.ast.CompilationUnit) {
                        return node;
                    }
                }
            }

            return null;
        } catch (Throwable t) {
            mClient.log(t, "Failed converting ECJ parse tree to Lombok for file %1$s",
                    context.file.getPath());
            return null;
        }
    }

    @Nullable
    private CompilationUnitDeclaration getParsedUnit(
            @NonNull JavaContext context,
            @NonNull String code) {
        EcjSourceFile sourceUnit = null;
        if (mSourceUnits != null && mEcjResult != null) {
            sourceUnit = mSourceUnits.get(context.file);
            if (sourceUnit != null) {
                CompilationUnitDeclaration unit = mEcjResult.getCompilationUnit(sourceUnit);
                if (unit != null) {
                    return unit;
                }
            }
        }

        if (sourceUnit == null) {
            sourceUnit = new EcjSourceFile(code, context.file);
        }
        try {
            CompilationResult compilationResult = new CompilationResult(sourceUnit, 0, 0, 0);
            return getParser().parse(sourceUnit, compilationResult);
        } catch (AbortCompilation e) {
            // No need to report Java parsing errors while running in Eclipse.
            // Eclipse itself will already provide problem markers for these files,
            // so all this achieves is creating "multiple annotations on this line"
            // tooltips instead.
            return null;
        }
    }

    @NonNull
    @Override
    public Location getLocation(@NonNull JavaContext context, @NonNull Node node) {
        lombok.ast.Position position = node.getPosition();

        // Not all ECJ nodes have offsets; in particular, VariableDefinitionEntries
        while (position == Position.UNPLACED) {
            node = node.getParent();
            //noinspection ConstantConditions
            if (node == null) {
                break;
            }
            position = node.getPosition();
        }
        return Location.create(context.file, context.getContents(),
                position.getStart(), position.getEnd());
    }

    @NonNull
    @Override
    public Location getRangeLocation(
            @NonNull JavaContext context,
            @NonNull Node from,
            int fromDelta,
            @NonNull Node to,
            int toDelta) {
        String contents = context.getContents();
        int start = Math.max(0, from.getPosition().getStart() + fromDelta);
        int end = Math.min(contents == null ? Integer.MAX_VALUE : contents.length(),
                to.getPosition().getEnd() + toDelta);
        return Location.create(context.file, contents, start, end);
    }

    @Override
    @NonNull
    public Location getNameLocation(@NonNull JavaContext context, @NonNull Node node) {
        // The range on method name identifiers is wrong in the ECJ nodes; just take start of
        // name + length of name
        if (node instanceof MethodDeclaration) {
            MethodDeclaration declaration = (MethodDeclaration) node;
            Identifier identifier = declaration.astMethodName();
            Location location = getLocation(context, identifier);
            com.android.tools.lint.detector.api.Position start = location.getStart();
            com.android.tools.lint.detector.api.Position end = location.getEnd();
            int methodNameLength = identifier.astValue().length();
            if (start != null && end != null &&
                    end.getOffset() - start.getOffset() > methodNameLength) {
                end = new DefaultPosition(start.getLine(), start.getColumn() + methodNameLength,
                        start.getOffset() + methodNameLength);
                return Location.create(location.getFile(), start, end);
            }
            return location;
        }
        return super.getNameLocation(context, node);
    }

    @NonNull
    @Override
    public
    Location.Handle createLocationHandle(@NonNull JavaContext context, @NonNull Node node) {
        return new LocationHandle(context.file, node);
    }

    @Override
    public void dispose(@NonNull JavaContext context, @NonNull PsiJavaFile compilationUnit) {
        if (mSourceUnits != null) {
            mSourceUnits.remove(context.file);
        }

        // We can't delete the AST since it's needed for type resolution etc
    }

    @Override
    public void dispose(@NonNull JavaContext context, @NonNull Node compilationUnit) {
        if (mSourceUnits != null) {
            EcjSourceFile sourceUnit = mSourceUnits.get(context.file);
            if (sourceUnit != null) {
                mSourceUnits.remove(context.file);
                if (mEcjResult != null) {
                    CompilationUnitDeclaration unit = mEcjResult.getCompilationUnit(sourceUnit);
                    if (unit != null) {
                        // See if this compilation unit defines any enum types; if so,
                        // keep those around for the type map (see #findAnnotationDeclaration())
                        if (unit.types != null) {
                            for (TypeDeclaration type : unit.types) {
                                if (isAnnotationType(type)) {
                                    return;
                                }
                                if (type.memberTypes != null) {
                                    for (TypeDeclaration member : type.memberTypes) {
                                        if (isAnnotationType(member)) {
                                            return;
                                        }
                                    }
                                }
                            }
                        }
                        // Compilation unit is not defining an annotation type at the top two
                        // levels: we can remove it now; findAnnotationDeclaration will not need
                        // to go looking for it
                        mEcjResult.removeCompilationUnit(sourceUnit);
                    }
                }
            }
        }
    }

    private static boolean isAnnotationType(@NonNull TypeDeclaration type) {
        return TypeDeclaration.kind(type.modifiers) == TypeDeclaration.ANNOTATION_TYPE_DECL;
    }

    @Override
    public void dispose() {
        if (mEcjResult != null) {
            mEcjResult.dispose();
            mEcjResult = null;
        }

        mSourceUnits = null;
        mTypeUnits = null;
    }

    @Nullable
    private static Object getNativeNode(@NonNull Node node) {
        Object nativeNode = node.getNativeNode();
        if (nativeNode != null) {
            return nativeNode;
        }

        // Special case the handling for variables: these are missing
        // native nodes in Lombok, but we can generally reconstruct them
        // by looking at the context and fishing into the ECJ hierarchy.
        // For example, for a method parameter, we can look at the surrounding
        // method declaration, which we do have an ECJ node for, and then
        // iterate through its Argument nodes and match those up with the
        // variable name.
        if (node instanceof VariableDeclaration) {
            node = ((VariableDeclaration)node).astDefinition();
        }
        if (node instanceof VariableDefinition) {
            StrictListAccessor<VariableDefinitionEntry, VariableDefinition>
                    variables = ((VariableDefinition)node).astVariables();
            if (variables.size() == 1) {
                node = variables.first();
            }
        }
        if (node instanceof VariableDefinitionEntry) {
            VariableDefinitionEntry entry = (VariableDefinitionEntry) node;
            String name = entry.astName().astValue();

            // Find the nearest surrounding native node
            Node parent = node.getParent();
            while (parent != null) {
                Object parentNativeNode = parent.getNativeNode();
                if (parentNativeNode != null) {
                    if (parentNativeNode instanceof AbstractMethodDeclaration) {
                        // Parameter in a method declaration?
                        AbstractMethodDeclaration method =
                                (AbstractMethodDeclaration) parentNativeNode;
                        for (Argument argument : method.arguments) {
                            if (sameChars(name, argument.name)) {
                                return argument;
                            }
                        }
                        for (Statement statement : method.statements) {
                            if (statement instanceof LocalDeclaration) {
                                LocalDeclaration declaration = (LocalDeclaration)statement;
                                if (sameChars(name, declaration.name)) {
                                    return declaration;
                                }
                            }
                        }
                    } else if (parentNativeNode instanceof TypeDeclaration) {
                        TypeDeclaration typeDeclaration = (TypeDeclaration) parentNativeNode;
                        for (FieldDeclaration fieldDeclaration : typeDeclaration.fields) {
                            if (sameChars(name, fieldDeclaration.name)) {
                                return fieldDeclaration;
                            }
                        }
                    } else if (parentNativeNode instanceof Block) {
                        Block block = (Block)parentNativeNode;
                        for (Statement statement : block.statements) {
                            if (statement instanceof LocalDeclaration) {
                                LocalDeclaration declaration = (LocalDeclaration)statement;
                                if (sameChars(name, declaration.name)) {
                                    return declaration;
                                }
                            }
                        }
                    }
                    break;
                }
                parent = parent.getParent();
            }
        }

        Node parent = node.getParent();
        // The ECJ native nodes are sometimes spotty; for example, for a
        // MethodInvocation node we can have a null native node, but its
        // parent expression statement will point to the real MessageSend node
        if (parent != null) {
            nativeNode = parent.getNativeNode();
            if (nativeNode != null) {
                return nativeNode;
            }
        }

        return null;
    }

    @Override
    @Nullable
    public ResolvedNode resolve(@NonNull JavaContext context, @NonNull Node node) {
        Object nativeNode = getNativeNode(node);
        if (nativeNode == null) {
            return null;
        }

        if (nativeNode instanceof NameReference) {
            return resolve(((NameReference) nativeNode).binding);
        } else if (nativeNode instanceof TypeReference) {
            return resolve(((TypeReference) nativeNode).resolvedType);
        } else if (nativeNode instanceof MessageSend) {
            return resolve(((MessageSend) nativeNode).binding);
        } else if (nativeNode instanceof AllocationExpression) {
            return resolve(((AllocationExpression) nativeNode).binding);
        } else if (nativeNode instanceof TypeDeclaration) {
            return resolve(((TypeDeclaration) nativeNode).binding);
        } else if (nativeNode instanceof ExplicitConstructorCall) {
            return resolve(((ExplicitConstructorCall) nativeNode).binding);
        } else if (nativeNode instanceof Annotation) {
            AnnotationBinding compilerAnnotation =
                    ((Annotation) nativeNode).getCompilerAnnotation();
            if (compilerAnnotation != null) {
                return new EcjResolvedAnnotation(compilerAnnotation);
            }
            return resolve(((Annotation) nativeNode).resolvedType);
        } else if (nativeNode instanceof AbstractMethodDeclaration) {
            return resolve(((AbstractMethodDeclaration) nativeNode).binding);
        } else if (nativeNode instanceof AbstractVariableDeclaration) {
            if (nativeNode instanceof LocalDeclaration) {
                return resolve(((LocalDeclaration) nativeNode).binding);
            } else if (nativeNode instanceof FieldDeclaration) {
                FieldDeclaration fieldDeclaration = (FieldDeclaration) nativeNode;
                if (fieldDeclaration.initialization instanceof AllocationExpression) {
                    AllocationExpression allocation =
                            (AllocationExpression)fieldDeclaration.initialization;
                    if (allocation.binding != null) {
                        // Field constructor call: this is an enum constant.
                        return new EcjResolvedMethod(allocation.binding);
                    }
                }
                return resolve(fieldDeclaration.binding);
            }
        }

        // TODO: Handle org.eclipse.jdt.internal.compiler.ast.SuperReference. It
        // doesn't contain an actual method binding; the parent node call should contain
        // it, but is missing a native node reference; investigate the ECJ bridge's super
        // handling.

        return null;
    }

    private ResolvedNode resolve(@Nullable Binding binding) {
        if (binding == null || binding instanceof ProblemBinding) {
            return null;
        }

        if (binding instanceof TypeBinding) {
            TypeBinding tb = (TypeBinding) binding;
            return new EcjResolvedClass(tb);
        } else if (binding instanceof MethodBinding) {
            MethodBinding mb = (MethodBinding) binding;
            if (mb instanceof ProblemMethodBinding) {
                return null;
            }
            //noinspection VariableNotUsedInsideIf
            if (mb.declaringClass != null) {
                return new EcjResolvedMethod(mb);
            }
        } else if (binding instanceof LocalVariableBinding) {
            LocalVariableBinding lvb = (LocalVariableBinding) binding;
            //noinspection VariableNotUsedInsideIf
            if (lvb.type != null) {
                return new EcjResolvedVariable(lvb);
            }
        } else if (binding instanceof FieldBinding) {
            FieldBinding fb = (FieldBinding) binding;
            if (fb instanceof ProblemFieldBinding) {
                return null;
            }
            if (fb.type != null && fb.declaringClass != null) {
                return new EcjResolvedField(fb);
            }
        }

        return null;
    }

    @Deprecated // Use new binding map instead
    private TypeDeclaration findTypeDeclaration(@NonNull String signature) {
        // Type: use binding instead
        if (mTypeUnits == null) {
            Collection<CompilationUnitDeclaration> units = mEcjResult.getCompilationUnits();
            mTypeUnits = Maps.newHashMapWithExpectedSize(units.size());
            for (CompilationUnitDeclaration unit : units) {
                if (unit.types != null) {
                    for (TypeDeclaration typeDeclaration : unit.types) {
                        addTypeDeclaration(typeDeclaration);
                    }
                }
            }
        }

        return mTypeUnits.get(signature);
    }

    @Deprecated
    private void addTypeDeclaration(TypeDeclaration typeDeclaration) {
        String type = new String(typeDeclaration.binding.readableName());
        mTypeUnits.put(type, typeDeclaration);
        // Recurse on member types
        if (typeDeclaration.memberTypes != null) {
            for (TypeDeclaration member : typeDeclaration.memberTypes) {
                addTypeDeclaration(member);
            }
        }
    }

    @Override
    @Nullable
    public TypeDescriptor getType(@NonNull JavaContext context, @NonNull Node node) {
        Object nativeNode = getNativeNode(node);
        if (nativeNode == null) {
            return null;
        }

        if (nativeNode instanceof MessageSend) {
            nativeNode = ((MessageSend)nativeNode).binding;
        } else if (nativeNode instanceof AllocationExpression) {
            nativeNode = ((AllocationExpression)nativeNode).resolvedType;
        } else if (nativeNode instanceof NameReference) {
            nativeNode = ((NameReference)nativeNode).resolvedType;
        } else if (nativeNode instanceof Expression) {
            if (nativeNode instanceof Literal) {
                if (nativeNode instanceof StringLiteral) {
                    return getTypeDescriptor(TYPE_STRING);
                } else if (nativeNode instanceof NumberLiteral) {
                    if (nativeNode instanceof IntLiteral) {
                        return getTypeDescriptor(TYPE_INT);
                    } else if (nativeNode instanceof LongLiteral) {
                        return getTypeDescriptor(TYPE_LONG);
                    } else if (nativeNode instanceof CharLiteral) {
                        return getTypeDescriptor(TYPE_CHAR);
                    } else if (nativeNode instanceof FloatLiteral) {
                        return getTypeDescriptor(TYPE_FLOAT);
                    } else if (nativeNode instanceof DoubleLiteral) {
                        return getTypeDescriptor(TYPE_DOUBLE);
                    }
                } else if (nativeNode instanceof MagicLiteral) {
                    if (nativeNode instanceof TrueLiteral || nativeNode instanceof FalseLiteral) {
                        return getTypeDescriptor(TYPE_BOOLEAN);
                    } else if (nativeNode instanceof NullLiteral) {
                        return getTypeDescriptor(TYPE_NULL);
                    }
                }
            }
            nativeNode = ((Expression)nativeNode).resolvedType;
        } else if (nativeNode instanceof TypeDeclaration) {
            nativeNode = ((TypeDeclaration) nativeNode).binding;
        } else if (nativeNode instanceof AbstractMethodDeclaration) {
            nativeNode = ((AbstractMethodDeclaration) nativeNode).binding;
        } else if (nativeNode instanceof FieldDeclaration) {
            nativeNode = ((FieldDeclaration) nativeNode).binding;
        } else if (nativeNode instanceof LocalDeclaration) {
            nativeNode = ((LocalDeclaration) nativeNode).binding;
        }

        if (nativeNode instanceof Binding) {
            Binding binding = (Binding) nativeNode;
            if (binding instanceof TypeBinding) {
                TypeBinding tb = (TypeBinding) binding;
                return getTypeDescriptor(tb);
            } else if (binding instanceof LocalVariableBinding) {
                LocalVariableBinding lvb = (LocalVariableBinding) binding;
                if (lvb.type != null) {
                    return getTypeDescriptor(lvb.type);
                }
            } else if (binding instanceof FieldBinding) {
                FieldBinding fb = (FieldBinding) binding;
                if (fb.type != null) {
                    return getTypeDescriptor(fb.type);
                }
            } else if (binding instanceof MethodBinding) {
                return getTypeDescriptor(((MethodBinding) binding).returnType);
            } else if (binding instanceof ProblemBinding) {
                // Unresolved type. We just don't know.
                return null;
            }
        }
        return null;
    }

    @Override
    public void runReadAction(@NonNull Runnable runnable) {
        // No lock needed for read access under ECJ, but we should consider
        // having a debug mode where we enforce read access to help catch bugs
        runnable.run();
    }

    @Nullable
    @Override
    public ResolvedClass findClass(@NonNull JavaContext context,
            @NonNull String fullyQualifiedName) {
        // Inner classes must use $ as separators. Switch to internal name first
        // to make it more likely that we handle this correctly:
        String internal = ClassContext.getInternalName(fullyQualifiedName);

        // Convert "foo/bar/Baz" into char[][] 'foo','bar','Baz' as required for
        // ECJ name lookup
        List<char[]> arrays = Lists.newArrayList();
        for (String segment : Splitter.on('/').split(internal)) {
            arrays.add(segment.toCharArray());
        }
        char[][] compoundName = new char[arrays.size()][];
        for (int i = 0, n = arrays.size(); i < n; i++) {
            compoundName[i] = arrays.get(i);
        }

        LookupEnvironment lookup = mEcjResult.mLookupEnvironment;
        if (lookup != null) {
            ReferenceBinding type = lookup.getType(compoundName);
            if (type != null && !(type instanceof ProblemReferenceBinding)) {
                return new EcjResolvedClass(type);
            }
        }

        return null;
    }

    @Override
    public List<TypeDescriptor> getCatchTypes(@NonNull JavaContext context,
            @NonNull Catch catchBlock) {
        Try aTry = catchBlock.upToTry();
        if (aTry != null) {
            Object nativeNode = getNativeNode(aTry);
            if (nativeNode instanceof TryStatement) {
                TryStatement tryStatement = (TryStatement) nativeNode;
                Argument[] catchArguments = tryStatement.catchArguments;
                Argument argument = null;
                if (catchArguments.length > 1) {
                    int index = 0;
                    for (Catch aCatch : aTry.astCatches()) {
                        if (aCatch == catchBlock) {
                            if (index < catchArguments.length) {
                                argument = catchArguments[index];
                                break;
                            }
                        }
                        index++;
                    }
                } else {
                    argument = catchArguments[0];
                }
                if (argument != null) {
                    if (argument.type instanceof UnionTypeReference) {
                        UnionTypeReference typeRef = (UnionTypeReference) argument.type;
                        List<TypeDescriptor> types = Lists.newArrayListWithCapacity(typeRef.typeReferences.length);
                        for (TypeReference typeReference : typeRef.typeReferences) {
                            TypeBinding binding = typeReference.resolvedType;
                            if (binding != null) {
                                types.add(new EcjTypeDescriptor(binding));
                            }
                        }
                        return types;
                    } else if (argument.type.resolvedType != null) {
                        TypeDescriptor t = new EcjTypeDescriptor(argument.type.resolvedType);
                        return Collections.singletonList(t);
                    }
                }
            }
        }

        return super.getCatchTypes(context, catchBlock);
    }

    @Nullable
    private TypeDescriptor getTypeDescriptor(@Nullable TypeBinding resolvedType) {
        if (resolvedType == null) {
            return null;
        }
        return new EcjTypeDescriptor(resolvedType);
    }

    private static TypeDescriptor getTypeDescriptor(String fqn) {
        return new DefaultTypeDescriptor(fqn);
    }

    /** Computes the super method, if any, given a method binding */
    private static MethodBinding findSuperMethodBinding(@NonNull MethodBinding binding) {
        try {
            ReferenceBinding superclass = binding.declaringClass.superclass();
            while (superclass != null) {
                MethodBinding[] methods = superclass.getMethods(binding.selector,
                        binding.parameters.length);
                for (MethodBinding method : methods) {
                    if (method.areParameterErasuresEqual(binding)) {
                        if (method.isPrivate()) {
                            if (method.declaringClass.outermostEnclosingType()
                                    == binding.declaringClass.outermostEnclosingType()) {
                                return method;
                            } else {
                                return null;
                            }
                        } else {
                            return method;
                        }
                    }
                }

                superclass = superclass.superclass();
            }
        } catch (Exception ignore) {
            // Work around ECJ bugs; see https://code.google.com/p/android/issues/detail?id=172268
        }

        return null;
    }

    @NonNull
    private static Collection<ResolvedAnnotation> merge(
            @Nullable Collection<ResolvedAnnotation> first,
            @Nullable Collection<ResolvedAnnotation> second) {
        if (first == null || first.isEmpty()) {
            if (second == null) {
                return Collections.emptyList();
            } else {
                return second;
            }
        } else if (second == null || second.isEmpty()) {
            return first;
        } else {
            int size = first.size() + second.size();
            List<ResolvedAnnotation> merged = Lists.newArrayListWithExpectedSize(size);
            merged.addAll(first);
            merged.addAll(second);
            return merged;
        }
    }

    /* Handle for creating positions cheaply and returning full fledged locations later */
    private static class LocationHandle implements Location.Handle {
        private File mFile;
        private Node mNode;
        private Object mClientData;

        public LocationHandle(File file, Node node) {
            mFile = file;
            mNode = node;
        }

        @NonNull
        @Override
        public Location resolve() {
            lombok.ast.Position pos = mNode.getPosition();
            return Location.create(mFile, null /*contents*/, pos.getStart(), pos.getEnd());
        }

        @Override
        public void setClientData(@Nullable Object clientData) {
            mClientData = clientData;
        }

        @Override
        @Nullable
        public Object getClientData() {
            return mClientData;
        }
    }

    // Custom version of the compiler which skips code generation and records source units
    private static class NonGeneratingCompiler extends Compiler {
        private Map<EcjSourceFile, CompilationUnitDeclaration> mUnits;
        private CompilationUnitDeclaration mCurrentUnit;

        public NonGeneratingCompiler(INameEnvironment environment, IErrorHandlingPolicy policy,
                CompilerOptions options, ICompilerRequestor requestor,
                IProblemFactory problemFactory,
                Map<EcjSourceFile, CompilationUnitDeclaration> units) {
            super(environment, policy, options, requestor, problemFactory, null, null);
            mUnits = units;
        }

        @Nullable
        CompilationUnitDeclaration getCurrentUnit() {
            // Can't use mLookupEnvironment.unitBeingCompleted directly; it gets nulled out
            // as part of the exception catch handling in the compiler before this method
            // is called from lint -- therefore we stash a copy in our own mCurrentUnit field
            return mCurrentUnit;
        }

        @Override
        protected synchronized void addCompilationUnit(ICompilationUnit sourceUnit,
                CompilationUnitDeclaration parsedUnit) {
            super.addCompilationUnit(sourceUnit, parsedUnit);
            mUnits.put((EcjSourceFile)sourceUnit, parsedUnit);
        }

        @Override
        public void process(CompilationUnitDeclaration unit, int unitNumber) {
            mCurrentUnit = lookupEnvironment.unitBeingCompleted = unit;

            parser.getMethodBodies(unit);
            if (unit.scope != null) {
                unit.scope.faultInTypes();
                unit.scope.verifyMethods(lookupEnvironment.methodVerifier());
            }
            unit.resolve();
            unit.analyseCode();

            // This is where we differ from super: DON'T call generateCode().
            // Sadly we can't just set ignoreMethodBodies=true to have the same effect,
            // since that would also skip the analyseCode call, which we DO, want:
            //     unit.generateCode();

            if (options.produceReferenceInfo && unit.scope != null) {
                unit.scope.storeDependencyInfo();
            }
            unit.finalizeProblems();
            unit.compilationResult.totalUnitsKnown = totalUnits;
            lookupEnvironment.unitBeingCompleted = null;
        }

        @Override
        public void reset() {
            if (KEEP_LOOKUP_ENVIRONMENT) {
                // Same as super.reset() in ECJ 4.4.2, but omits the following statement:
                //  this.mLookupEnvironment.reset();
                // because we need the lookup environment to stick around even after the
                // parse phase is done: at that point we're going to use the parse trees
                // from java detectors which may need to resolve types
                this.parser.scanner.source = null;
                this.unitsToProcess = null;
                if (DebugRequestor != null) DebugRequestor.reset();
                this.problemReporter.reset();

            } else {
                super.reset();
            }
        }
    }

    private class EcjTypeDescriptor extends TypeDescriptor {
        private final TypeBinding mBinding;

        private EcjTypeDescriptor(@NonNull TypeBinding binding) {
            mBinding = binding;
        }

        @NonNull
        @Override
        public String getName() {
            return new String(mBinding.readableName());
        }

        @Override
        public boolean matchesName(@NonNull String name) {
            return sameChars(name, mBinding.readableName());
        }

        @Override
        public boolean matchesSignature(@NonNull String signature) {
            return sameChars(signature, mBinding.readableName());
        }

        @Override
        public boolean isPrimitive() {
            return mBinding.isPrimitiveType();
        }

        @Override
        public boolean isArray() {
            return mBinding.isArrayType();
        }

        @NonNull
        @Override
        public String getSignature() {
            return getName();
        }

        @NonNull
        @Override
        public String getSimpleName() {
            if (mBinding instanceof ReferenceBinding) {
                ReferenceBinding ref = (ReferenceBinding) mBinding;
                char[][] name = ref.compoundName;
                char[] lastSegment = name[name.length - 1];
                StringBuilder sb = new StringBuilder(lastSegment.length);
                for (char c : lastSegment) {
                    if (c == '$') {
                        c = '.';
                    }
                    sb.append(c);
                }
                return sb.toString();
            }
            return super.getSimpleName();
        }

        @NonNull
        @Override
        public String getInternalName() {
            if (mBinding instanceof ReferenceBinding) {
                ReferenceBinding ref = (ReferenceBinding) mBinding;
                StringBuilder sb = new StringBuilder(100);
                char[][] name = ref.compoundName;
                if (name == null) {
                    return super.getInternalName();
                }
                for (char[] segment : name) {
                    if (sb.length() != 0) {
                        sb.append('/');
                    }
                    for (char c : segment) {
                        sb.append(c);
                    }
                }
                return sb.toString();
            }
            return super.getInternalName();
        }

        @Override
        @Nullable
        public ResolvedClass getTypeClass() {
            if (!mBinding.isPrimitiveType()) {
                return new EcjResolvedClass(mBinding);
            }
            return null;
        }

        @SuppressWarnings("RedundantIfStatement")
        @Override
        public boolean equals(Object o) {
            if (this == o) {
                return true;
            }
            if (o == null || getClass() != o.getClass()) {
                return false;
            }

            EcjTypeDescriptor that = (EcjTypeDescriptor) o;

            if (!mBinding.equals(that.mBinding)) {
                return false;
            }

            return true;
        }

        @Override
        public int hashCode() {
            return mBinding.hashCode();
        }
    }

    private class EcjResolvedMethod extends ResolvedMethod {
        private MethodBinding mBinding;

        private EcjResolvedMethod(MethodBinding binding) {
            mBinding = binding;
            assert mBinding.declaringClass != null;
        }

        @NonNull
        @Override
        public String getName() {
            char[] c = isConstructor() ? mBinding.declaringClass.readableName() : mBinding.selector;
            return new String(c);
        }

        @Override
        public boolean matches(@NonNull String name) {
            char[] c = isConstructor() ? mBinding.declaringClass.readableName() : mBinding.selector;
            return sameChars(name, c);
        }

        @NonNull
        @Override
        public ResolvedClass getContainingClass() {
            return new EcjResolvedClass(mBinding.declaringClass);
        }

        @Override
        public int getArgumentCount() {
            return mBinding.parameters != null ? mBinding.parameters.length : 0;
        }

        @NonNull
        @Override
        public TypeDescriptor getArgumentType(int index) {
            TypeBinding parameterType = mBinding.parameters[index];
            TypeDescriptor typeDescriptor = getTypeDescriptor(parameterType);
            assert typeDescriptor != null; // because parameter is not null
            return typeDescriptor;
        }

        @Override
        public boolean argumentMatchesType(int index, @NonNull String signature) {
            return sameChars(signature, mBinding.parameters[index].readableName());
        }

        @Nullable
        @Override
        public TypeDescriptor getReturnType() {
            return isConstructor() ? null : getTypeDescriptor(mBinding.returnType);
        }

        @Override
        public boolean isConstructor() {
            return mBinding.isConstructor();
        }

        @Override
        @Nullable
        public ResolvedMethod getSuperMethod() {
            MethodBinding superBinding = findSuperMethodBinding(mBinding);
            if (superBinding != null) {
                return new EcjResolvedMethod(superBinding);
            }

            return null;
        }

        @NonNull
        @Override
        public Iterable<ResolvedAnnotation> getAnnotations() {
            List<ResolvedAnnotation> all = Lists.newArrayListWithExpectedSize(4);
            ExternalAnnotationRepository manager = ExternalAnnotationRepository.get(mClient);

            MethodBinding binding = this.mBinding;
            while (binding != null) {
                AnnotationBinding[] annotations = binding.getAnnotations();
                int count = annotations.length;
                if (count > 0) {
                    for (AnnotationBinding annotation : annotations) {
                        if (annotation != null) {
                            all.add(new EcjResolvedAnnotation(annotation));
                        }
                    }
                }

                // Look for external annotations
                Collection<ResolvedAnnotation> external = manager.getAnnotations(
                        new EcjResolvedMethod(binding));
                if (external != null) {
                    all.addAll(external);
                }

                binding = findSuperMethodBinding(binding);
                if (binding != null && binding.isPrivate()) {
                    break;
                }
            }

            all = ensureUnique(all);
            return all;
        }

        @NonNull
        @Override
        public Iterable<ResolvedAnnotation> getParameterAnnotations(int index) {
            List<ResolvedAnnotation> all = Lists.newArrayListWithExpectedSize(4);
            ExternalAnnotationRepository manager = ExternalAnnotationRepository.get(mClient);

            MethodBinding binding = this.mBinding;
            while (binding != null) {
                AnnotationBinding[][] parameterAnnotations = binding.getParameterAnnotations();
                if (parameterAnnotations != null &&
                        index >= 0 && index < parameterAnnotations.length) {
                    AnnotationBinding[] annotations = parameterAnnotations[index];
                    int count = annotations.length;
                    if (count > 0) {
                        for (AnnotationBinding annotation : annotations) {
                            if (annotation != null) {
                                all.add(new EcjResolvedAnnotation(annotation));
                            }
                        }
                    }
                }

                // Look for external annotations
                Collection<ResolvedAnnotation> external = manager.getAnnotations(
                        new EcjResolvedMethod(binding), index);
                if (external != null) {
                    all.addAll(external);
                }

                binding = findSuperMethodBinding(binding);
            }

            all = ensureUnique(all);
            return all;
        }

        @Override
        public int getModifiers() {
            return mBinding.getAccessFlags();
        }

        @Override
        public String getSignature() {
            return mBinding.toString();
        }

        @Override
        public boolean isInPackage(@NonNull String pkgName, boolean includeSubPackages) {
            PackageBinding pkg = mBinding.declaringClass.getPackage();
            //noinspection SimplifiableIfStatement
            if (pkg != null) {
                return includeSubPackages ?
                        startsWithCompound(pkgName, pkg.compoundName) :
                        equalsCompound(pkgName, pkg.compoundName);
            }
            return false;
        }

        @SuppressWarnings("RedundantIfStatement")
        @Override
        public boolean equals(Object o) {
            if (this == o) {
                return true;
            }
            if (o == null || getClass() != o.getClass()) {
                return false;
            }

            EcjResolvedMethod that = (EcjResolvedMethod) o;

            if (mBinding != null ? !mBinding.equals(that.mBinding) : that.mBinding != null) {
                return false;
            }

            return true;
        }

        @Override
        public int hashCode() {
            return mBinding != null ? mBinding.hashCode() : 0;
        }
    }

    /**
     * It is valid (and in fact encouraged by IntelliJ's inspections) to specify the same
     * annotation on overriding methods and overriding parameters. However, we shouldn't
     * return all these "duplicates" when you ask for the annotation on a given element.
     * This method filters out duplicates.
     */
    @VisibleForTesting
    @NonNull
    static List<ResolvedAnnotation> ensureUnique(@NonNull List<ResolvedAnnotation> list) {
        if (list.size() < 2) {
            return list;
        }

        // The natural way to deduplicate would be to create a Set of seen names, iterate
        // through the list and look to see if the current annotation's name is already in the
        // set (if so, remove this annotation from the list, else add it to the set of seen names)
        // but this involves creating the set and all the Map entry objects; that's not
        // necessary here since these lists are always very short 2-5 elements.
        // Instead we'll just do an O(n^2) iteration comparing each subsequent element with each
        // previous element and removing if matches, which is fine for these tiny lists.
        int n = list.size();
        for (int i = 0; i < n - 1; i++) {
            ResolvedAnnotation current = list.get(i);
            String currentName = current.getName();
            // Deleting duplicates at end reduces number of elements that have to be shifted
            for (int j = n - 1; j > i; j--) {
                ResolvedAnnotation later = list.get(j);
                String laterName = later.getName();
                if (currentName.equals(laterName)) {
                    list.remove(j);
                    n--;
                }
            }
        }

        return list;
    }

    private class EcjResolvedClass extends ResolvedClass {
        protected final TypeBinding mBinding;

        private EcjResolvedClass(TypeBinding binding) {
            mBinding = binding;
        }

        @NonNull
        @Override
        public String getName() {
            String name = new String(mBinding.readableName());
            if (name.indexOf('.') == -1 && mBinding.enclosingType() != null) {
                name = new String(mBinding.enclosingType().readableName()) + '.' + name;
            }
            return stripTypeVariables(name);
        }

        @NonNull
        @Override
        public String getSimpleName() {
            return stripTypeVariables(new String(mBinding.sourceName()));
        }

        @Override
        public boolean matches(@NonNull String name) {
            return sameChars(name, mBinding.readableName());
        }

        @Nullable
        @Override
        public ResolvedClass getSuperClass() {
            ReferenceBinding superClass = mBinding.superclass();
            if (superClass != null) {
                return new EcjResolvedClass(superClass);
            }

            return null;
        }

        @Override
        @NonNull
        public Iterable<ResolvedClass> getInterfaces() {
            ReferenceBinding[] interfaces = mBinding.superInterfaces();
            if (interfaces.length == 0) {
                return Collections.emptyList();
            }
            List<ResolvedClass> classes = Lists.newArrayListWithExpectedSize(interfaces.length);
            for (ReferenceBinding binding : interfaces) {
                classes.add(new EcjResolvedClass(binding));
            }
            return classes;
        }

        @Override
        public boolean isInterface() {
            return mBinding.isInterface();
        }

        @Override
        public boolean isEnum() {
            return mBinding.isEnum();
        }

        @Nullable
        @Override
        public ResolvedClass getContainingClass() {
            if (mBinding instanceof NestedTypeBinding) {
                NestedTypeBinding ntb = (NestedTypeBinding) mBinding;
                if (ntb.enclosingType != null) {
                    return new EcjResolvedClass(ntb.enclosingType);
                }
            }

            return null;
        }

        @Override
        public boolean isSubclassOf(@NonNull String name, boolean strict) {
            ReferenceBinding cls = (ReferenceBinding) mBinding;
            if (strict) {
                cls = cls.superclass();
            }
            for (; cls != null; cls = cls.superclass()) {
                if (equalsCompound(name, cls.compoundName)) {
                    return true;
                }
            }

            return false;
        }

        @Override
        public boolean isImplementing(@NonNull String name, boolean strict) {
            if (mBinding instanceof ReferenceBinding) {
                ReferenceBinding cls = (ReferenceBinding) mBinding;
                if (strict) {
                    cls = cls.superclass();
                }
                return isInheritor(cls, name);
            }

            return false;
        }

        @Override
        public boolean isInheritingFrom(@NonNull String name, boolean strict) {
            if (mBinding instanceof ReferenceBinding) {
                ReferenceBinding cls = (ReferenceBinding) mBinding;
                if (strict) {
                    cls = cls.superclass();
                }
                return isInheritor(cls, name);
            }

            return false;
        }

        @Override
        @NonNull
        public Iterable<ResolvedMethod> getConstructors() {
            if (mBinding instanceof ReferenceBinding) {
                ReferenceBinding cls = (ReferenceBinding) mBinding;
                MethodBinding[] methods = cls.getMethods(TypeConstants.INIT);
                if (methods != null) {
                    int count = methods.length;
                    List<ResolvedMethod> result = Lists.newArrayListWithExpectedSize(count);
                    for (MethodBinding method : methods) {
                        if (method.isConstructor()) {
                            result.add(new EcjResolvedMethod(method));
                        }
                    }
                    return result;
                }
            }

            return Collections.emptyList();
        }

        @Override
        @NonNull
        public Iterable<ResolvedMethod> getMethods(@NonNull String name,
                boolean includeInherited) {
            return findMethods(name, includeInherited);
        }

        @Override
        @NonNull
        public Iterable<ResolvedMethod> getMethods(boolean includeInherited) {
            return findMethods(null, includeInherited);
        }

        @NonNull
        private Iterable<ResolvedMethod> findMethods(@Nullable String name,
                boolean includeInherited) {
            if (mBinding instanceof ReferenceBinding) {
                ReferenceBinding cls = (ReferenceBinding) mBinding;
                if (includeInherited) {
                    List<ResolvedMethod> result = null;
                    while (cls != null) {
                        MethodBinding[] methods =
                                name != null ? cls.getMethods(name.toCharArray()) : cls.methods();
                        if (methods != null) {
                            int count = methods.length;
                            if (count > 0) {
                                if (result == null) {
                                    result = Lists.newArrayListWithExpectedSize(count);
                                }
                                for (MethodBinding method : methods) {
                                    if ((method.modifiers & Modifier.PRIVATE) != 0 &&
                                            cls != mBinding) {
                                        // Ignore parent methods that are private
                                        continue;
                                    }

                                    if (!method.isConstructor()) {
                                        // See if this method looks like it's masked
                                        boolean masked = false;
                                        for (ResolvedMethod m : result) {
                                            MethodBinding mb = ((EcjResolvedMethod) m).mBinding;
                                            if (mb.areParameterErasuresEqual(method)) {
                                                masked = true;
                                                break;
                                            }
                                        }
                                        if (masked) {
                                            continue;
                                        }
                                        result.add(new EcjResolvedMethod(method));
                                    }
                                }
                            }
                        }
                        cls = cls.superclass();
                    }

                    return result != null ? result : Collections.<ResolvedMethod>emptyList();
                } else {
                    MethodBinding[] methods =
                            name != null ? cls.getMethods(name.toCharArray()) : cls.methods();
                    if (methods != null) {
                        int count = methods.length;
                        List<ResolvedMethod> result = Lists.newArrayListWithExpectedSize(count);
                        for (MethodBinding method : methods) {
                            if (!method.isConstructor()) {
                                result.add(new EcjResolvedMethod(method));
                            }
                        }
                        return result;
                    }
                }
            }

            return Collections.emptyList();
        }

        @NonNull
        @Override
        public Iterable<ResolvedAnnotation> getAnnotations() {
            List<ResolvedAnnotation> all = Lists.newArrayListWithExpectedSize(2);
            ExternalAnnotationRepository manager = ExternalAnnotationRepository.get(mClient);

            if (mBinding instanceof ReferenceBinding) {
                ReferenceBinding cls = (ReferenceBinding) mBinding;
                while (cls != null) {
                    AnnotationBinding[] annotations = cls.getAnnotations();
                    int count = annotations.length;
                    if (count > 0) {
                        all = Lists.newArrayListWithExpectedSize(count);
                        for (AnnotationBinding annotation : annotations) {
                            if (annotation != null) {
                                all.add(new EcjResolvedAnnotation(annotation));
                            }
                        }
                    }

                    // Look for external annotations
                    Collection<ResolvedAnnotation> external = manager.getAnnotations(
                            new EcjResolvedClass(cls));
                    if (external != null) {
                        all.addAll(external);
                    }

                    cls = cls.superclass();
                }
            } else {
                Collection<ResolvedAnnotation> external = manager.getAnnotations(this);
                if (external != null) {
                    all.addAll(external);
                }
            }

            all = ensureUnique(all);
            return all;
        }

        @NonNull
        @Override
        public Iterable<ResolvedField> getFields(boolean includeInherited) {
            if (mBinding instanceof ReferenceBinding) {
                ReferenceBinding cls = (ReferenceBinding) mBinding;
                if (includeInherited) {
                    List<ResolvedField> result = null;
                    while (cls != null) {
                        FieldBinding[] fields = cls.fields();
                        if (fields != null) {
                            int count = fields.length;
                            if (count > 0) {
                                if (result == null) {
                                    result = Lists.newArrayListWithExpectedSize(count);
                                }
                                for (FieldBinding field : fields) {
                                    if ((field.modifiers & Modifier.PRIVATE) != 0 &&
                                            cls != mBinding) {
                                        // Ignore parent fields that are private
                                        continue;
                                    }

                                    // See if this field looks like it's masked
                                    boolean masked = false;
                                    for (ResolvedField f : result) {
                                        FieldBinding mb = ((EcjResolvedField) f).mBinding;
                                        if (Arrays.equals(mb.readableName(),
                                                field.readableName())) {
                                            masked = true;
                                            break;
                                        }
                                    }
                                    if (masked) {
                                        continue;
                                    }

                                    result.add(new EcjResolvedField(field));
                                }
                            }
                        }
                        cls = cls.superclass();
                    }

                    return result != null ? result : Collections.<ResolvedField>emptyList();
                } else {
                    FieldBinding[] fields = cls.fields();
                    if (fields != null) {
                        int count = fields.length;
                        List<ResolvedField> result = Lists.newArrayListWithExpectedSize(count);
                        for (FieldBinding field : fields) {
                            result.add(new EcjResolvedField(field));
                        }
                        return result;
                    }
                }
            }

            return Collections.emptyList();
        }

        @Override
        @Nullable
        public ResolvedField getField(@NonNull String name, boolean includeInherited) {
            if (mBinding instanceof ReferenceBinding) {
                ReferenceBinding cls = (ReferenceBinding) mBinding;
                while (cls != null) {
                    FieldBinding[] fields = cls.fields();
                    if (fields != null) {
                        for (FieldBinding field : fields) {
                            if ((field.modifiers & Modifier.PRIVATE) != 0 &&
                                    cls != mBinding) {
                                // Ignore parent methods that are private
                                continue;
                            }

                            if (sameChars(name, field.name)) {
                                return new EcjResolvedField(field);
                            }
                        }
                    }
                    if (includeInherited) {
                        cls = cls.superclass();
                    } else {
                        break;
                    }
                }
            }

            return null;
        }

        @Nullable
        @Override
        public ResolvedPackage getPackage() {
            return new EcjResolvedPackage(mBinding.getPackage());
        }

        @Override
        public int getModifiers() {
            if (mBinding instanceof ReferenceBinding) {
                ReferenceBinding cls = (ReferenceBinding) mBinding;
                // These constants from ClassFileConstants luckily agree with the Modifier
                // constants in the low bits we care about (public, abstract, static, etc)
                return cls.getAccessFlags();
            }
            return 0;
        }

        @Override
        public TypeDescriptor getType() {
            return new EcjTypeDescriptor(mBinding);
        }

        @Override
        public String getSignature() {
            return getName();
        }

        @Override
        public boolean isInPackage(@NonNull String pkgName, boolean includeSubPackages) {
            PackageBinding pkg = mBinding.getPackage();
            //noinspection SimplifiableIfStatement
            if (pkg != null) {
                return includeSubPackages ?
                        startsWithCompound(pkgName, pkg.compoundName) :
                        equalsCompound(pkgName, pkg.compoundName);
            }
            return false;
        }

        @SuppressWarnings("RedundantIfStatement")
        @Override
        public boolean equals(Object o) {
            if (this == o) {
                return true;
            }
            if (o == null || getClass() != o.getClass()) {
                return false;
            }

            EcjResolvedClass that = (EcjResolvedClass) o;

            if (mBinding != null ? !mBinding.equals(that.mBinding) : that.mBinding != null) {
                return false;
            }

            return true;
        }

        @Override
        public int hashCode() {
            return mBinding != null ? mBinding.hashCode() : 0;
        }
    }

    @NonNull
    private static String stripTypeVariables(String name) {
        // Strip out type variables; there doesn't seem to be a way to
        // do it from the ECJ APIs; it unconditionally includes this.
        // (Converts for example
        //     android.support.v7.widget.RecyclerView.Adapter<VH>
        //  to
        //     android.support.v7.widget.RecyclerView.Adapter
        if (name.indexOf('<') != -1) {
            StringBuilder sb = new StringBuilder(name.length());
            int depth = 0;
            for (int i = 0, n = name.length(); i < n; i++) {
                char c = name.charAt(i);
                if (c == '<') {
                    depth++;
                } else if (c == '>') {
                    depth--;
                } else if (depth == 0) {
                    sb.append(c);
                }
            }
            name = sb.toString();
        }
        return name;
    }

    // "package-info" as a char
    private static final char[] PACKAGE_INFO_CHARS = new char[] {
            'p', 'a', 'c', 'k', 'a', 'g', 'e', '-', 'i', 'n', 'f', 'o'
    };

    private class EcjResolvedPackage extends ResolvedPackage {
        private final PackageBinding mBinding;

        public EcjResolvedPackage(PackageBinding binding) {
            mBinding = binding;
        }

        @NonNull
        @Override
        public String getName() {
            return new String(mBinding.readableName());
        }

        @Override
        public String getSignature() {
            return getName();
        }

        @NonNull
        @Override
        public Iterable<ResolvedAnnotation> getAnnotations() {
            List<ResolvedAnnotation> all = Lists.newArrayListWithExpectedSize(2);

            AnnotationBinding[] annotations = mBinding.getAnnotations();
            int count = annotations.length;
            if (count == 0) {
                Binding pkgInfo = mBinding.getTypeOrPackage(PACKAGE_INFO_CHARS);
                if (pkgInfo != null) {
                    annotations = pkgInfo.getAnnotations();
                }
                count = annotations.length;
            }
            if (count > 0) {
                for (AnnotationBinding annotation : annotations) {
                    if (annotation != null) {
                        all.add(new EcjResolvedAnnotation(annotation));
                    }
                }
            }

            // Merge external annotations
            ExternalAnnotationRepository manager = ExternalAnnotationRepository.get(mClient);
            Collection<ResolvedAnnotation> external = manager.getAnnotations(this);
            if (external != null) {
                all.addAll(external);
            }

            all = ensureUnique(all);
            return all;
        }

        @Override
        @Nullable
        public ResolvedPackage getParentPackage() {
            char[][] compoundName = mBinding.compoundName;
            if (compoundName.length == 1) {
                return null;
            } else {
                PackageBinding defaultPackage = mBinding.environment.defaultPackage;
                PackageBinding packageBinding =
                        (PackageBinding) defaultPackage.getTypeOrPackage(compoundName[0]);
                if (packageBinding == null || packageBinding instanceof ProblemPackageBinding) {
                    return null;
                }

                for (int i = 1, packageLength = compoundName.length - 1; i < packageLength; i++) {
                    Binding next = packageBinding.getTypeOrPackage(compoundName[i]);
                    if (next == null) {
                        return null;
                    }
                    if (next instanceof PackageBinding) {
                        if (next instanceof ProblemPackageBinding) {
                            return null;
                        }
                        packageBinding = (PackageBinding) next;
                    }
                }

                return new EcjResolvedPackage(packageBinding);
            }
        }

        @Override
        public int getModifiers() {
            return 0;
        }

        @SuppressWarnings("RedundantIfStatement")
        @Override
        public boolean equals(Object o) {
            if (this == o) {
                return true;
            }
            if (o == null || getClass() != o.getClass()) {
                return false;
            }

            EcjResolvedPackage that = (EcjResolvedPackage) o;

            if (mBinding != null ? !mBinding.equals(that.mBinding) : that.mBinding != null) {
                return false;
            }

            return true;
        }

        @Override
        public int hashCode() {
            return mBinding != null ? mBinding.hashCode() : 0;
        }
    }

    private class EcjResolvedField extends ResolvedField {
        private FieldBinding mBinding;

        private EcjResolvedField(FieldBinding binding) {
            mBinding = binding;
        }

        @NonNull
        @Override
        public String getName() {
            return new String(mBinding.readableName());
        }

        @Override
        public boolean matches(@NonNull String name) {
            return sameChars(name, mBinding.readableName());
        }

        @NonNull
        @Override
        public TypeDescriptor getType() {
            TypeDescriptor typeDescriptor = getTypeDescriptor(mBinding.type);
            assert typeDescriptor != null; // because mBinding.type is known not to be null
            return typeDescriptor;
        }

        @NonNull
        @Override
        public ResolvedClass getContainingClass() {
            return new EcjResolvedClass(mBinding.declaringClass);
        }

        @Nullable
        @Override
        public Object getValue() {
            return getConstantValue(mBinding.constant());
        }

        @NonNull
        @Override
        public Iterable<ResolvedAnnotation> getAnnotations() {
            List<ResolvedAnnotation> compiled = null;
            AnnotationBinding[] annotations = mBinding.getAnnotations();
            int count = annotations.length;
            if (count > 0) {
                compiled = Lists.newArrayListWithExpectedSize(count);
                for (AnnotationBinding annotation : annotations) {
                    if (annotation != null) {
                        compiled.add(new EcjResolvedAnnotation(annotation));
                    }
                }
            }

            // Look for external annotations
            ExternalAnnotationRepository manager = ExternalAnnotationRepository.get(mClient);
            Collection<ResolvedAnnotation> external = manager.getAnnotations(this);

            return merge(compiled, external);
        }

        @Override
        public int getModifiers() {
            return mBinding.getAccessFlags();
        }

        @Override
        public String getSignature() {
            return mBinding.toString();
        }

        @Override
        public boolean isInPackage(@NonNull String pkgName, boolean includeSubPackages) {
            PackageBinding pkg = mBinding.declaringClass.getPackage();
            //noinspection SimplifiableIfStatement
            if (pkg != null) {
                return includeSubPackages ?
                        startsWithCompound(pkgName, pkg.compoundName) :
                        equalsCompound(pkgName, pkg.compoundName);
            }
            return false;
        }

        @Nullable
        @Override
        public Node findAstNode() {
            // Map back from type binding to AST
            ResolvedClass containingClass = getContainingClass();
            TypeDeclaration typeDeclaration = findTypeDeclaration(containingClass.getName());
            if (typeDeclaration != null) {
                for (FieldDeclaration field : typeDeclaration.fields) {
                    if (field.binding == mBinding) {
                        EcjTreeConverter converter = new EcjTreeConverter();
                        converter.visit(null, field);
                        List<? extends Node> nodes = converter.getAll();
                        if (nodes.size() == 1) {
                            return nodes.get(0);
                        }
                        break;
                    }
                }
            }

            return super.findAstNode();
        }

        @SuppressWarnings("RedundantIfStatement")
        @Override
        public boolean equals(Object o) {
            if (this == o) {
                return true;
            }
            if (o == null || getClass() != o.getClass()) {
                return false;
            }

            EcjResolvedField that = (EcjResolvedField) o;

            if (mBinding != null ? !mBinding.equals(that.mBinding) : that.mBinding != null) {
                return false;
            }

            return true;
        }

        @Override
        public int hashCode() {
            return mBinding != null ? mBinding.hashCode() : 0;
        }
    }

    private class EcjResolvedVariable extends ResolvedVariable {
        private VariableBinding mBinding;

        private EcjResolvedVariable(VariableBinding binding) {
            mBinding = binding;
        }

        @NonNull
        @Override
        public String getName() {
            return new String(mBinding.readableName());
        }

        @Override
        public boolean matches(@NonNull String name) {
            return sameChars(name, mBinding.readableName());
        }

        @NonNull
        @Override
        public TypeDescriptor getType() {
            TypeDescriptor typeDescriptor = getTypeDescriptor(mBinding.type);
            assert typeDescriptor != null; // because mBinding.type is known not to be null
            return typeDescriptor;
        }

        @Override
        public int getModifiers() {
            return mBinding.modifiers;
        }

        @NonNull
        @Override
        public Iterable<ResolvedAnnotation> getAnnotations() {
            AnnotationBinding[] annotations = mBinding.getAnnotations();
            int count = annotations.length;
            if (count > 0) {
                List<ResolvedAnnotation> result = Lists.newArrayListWithExpectedSize(count);
                for (AnnotationBinding annotation : annotations) {
                    if (annotation != null) {
                        result.add(new EcjResolvedAnnotation(annotation));
                    }
                }
                return result;
            }

            // No external annotations for variables

            return Collections.emptyList();
        }

        @Override
        public String getSignature() {
            return mBinding.toString();
        }

        @SuppressWarnings("RedundantIfStatement")
        @Override
        public boolean equals(Object o) {
            if (this == o) {
                return true;
            }
            if (o == null || getClass() != o.getClass()) {
                return false;
            }

            EcjResolvedVariable that = (EcjResolvedVariable) o;

            if (mBinding != null ? !mBinding.equals(that.mBinding) : that.mBinding != null) {
                return false;
            }

            return true;
        }

        @Override
        public int hashCode() {
            return mBinding != null ? mBinding.hashCode() : 0;
        }
    }

    private class EcjResolvedAnnotation extends ResolvedAnnotation {
        private final AnnotationBinding mBinding;
        private final String mName;

        private EcjResolvedAnnotation(@NonNull final AnnotationBinding binding) {
            mBinding = binding;
            mName = new String(mBinding.getAnnotationType().readableName());
        }

        @NonNull
        @Override
        public String getName() {
            return mName;
        }

        @Override
        public boolean matches(@NonNull String name) {
            return name.equals(mName);
        }

        @NonNull
        @Override
        public TypeDescriptor getType() {
            TypeDescriptor typeDescriptor = getTypeDescriptor(mBinding.getAnnotationType());
            assert typeDescriptor != null; // because mBinding.type is known not to be null
            return typeDescriptor;
        }

        @Override
        public ResolvedClass getClassType() {
            ReferenceBinding annotationType = mBinding.getAnnotationType();
            return new EcjResolvedClass(annotationType) {
                @NonNull
                @Override
                public Iterable<ResolvedAnnotation> getAnnotations() {
                    AnnotationBinding[] annotations = mBinding.getAnnotations();
                    int count = annotations.length;
                    if (count > 0) {
                        List<ResolvedAnnotation> result = Lists.newArrayListWithExpectedSize(count);
                        for (AnnotationBinding annotation : annotations) {
                            if (annotation != null) {
                                // Special case: If you look up the annotations *on* annotations,
                                // you're probably working with the typedef annotations, @IntDef
                                // and @StringDef. For these, we can't use the normal annotation
                                // handling, because the compiler only keeps the values of the
                                // constants, not the references to the constants which is what we
                                // care about for those annotations. So in this case, construct
                                // a special subclass of ResolvedAnnotation: EcjAstAnnotation, where
                                // we keep the AST node for the annotation definition such that
                                // we can look up the constant references themselves when queries
                                // via the annotation's getValue() lookup methods.
                                char[] readableName = annotation.getAnnotationType().readableName();
                                if (sameChars(INT_DEF_ANNOTATION, readableName)
                                        || sameChars(STRING_DEF_ANNOTATION, readableName)) {
                                    TypeDeclaration typeDeclaration =
                                            findTypeDeclaration(getName());
                                    if (typeDeclaration != null && typeDeclaration.annotations != null) {
                                        Annotation astAnnotation = null;
                                        for (Annotation a : typeDeclaration.annotations) {
                                            if (a.resolvedType != null
                                                    && (sameChars(INT_DEF_ANNOTATION, a.resolvedType.readableName()) ||
                                                    sameChars(STRING_DEF_ANNOTATION, a.resolvedType.readableName()))) {
                                                astAnnotation = a;
                                                break;
                                            }
                                        }

                                        if (astAnnotation != null) {
                                            result.add(new EcjAstAnnotation(annotation, astAnnotation));
                                            continue;
                                        }
                                    } else {
                                        // Don't record these typedef annotations; without
                                        // finding the bindings, we'll get the literal values
                                        // from the ECJ annotation, and that will lead to incorrect
                                        // typedef warnings.
                                        continue;
                                    }
                                }

                                result.add(new EcjResolvedAnnotation(annotation));
                            }
                        }
                        return result;
                    }

                    return Collections.emptyList();
                }
            };
        }

        @NonNull
        @Override
        public List<Value> getValues() {
            ElementValuePair[] pairs = mBinding.getElementValuePairs();
            if (pairs != null && pairs.length > 0) {
                List<Value> values = Lists.newArrayListWithExpectedSize(pairs.length);
                for (ElementValuePair pair : pairs) {
                    values.add(new Value(new String(pair.getName()), getPairValue(pair)));
                }
            }

            return Collections.emptyList();
        }

        @Nullable
        @Override
        public Object getValue(@NonNull String name) {
            ElementValuePair[] pairs = mBinding.getElementValuePairs();
            if (pairs != null) {
                for (ElementValuePair pair : pairs) {
                    if (sameChars(name, pair.getName())) {
                        return getPairValue(pair);
                    }
                }
            }

            return null;
        }

        private Object getPairValue(ElementValuePair pair) {
            return getConstantValue(pair.getValue());
        }

        @Override
        public String getSignature() {
            return mName;
        }

        @Override
        public int getModifiers() {
            // Not applicable; move from ResolvedNode into ones that matter?
            return 0;
        }

        @NonNull
        @Override
        public Iterable<ResolvedAnnotation> getAnnotations() {
            List<ResolvedAnnotation> compiled = null;
            AnnotationBinding[] annotations = mBinding.getAnnotationType().getAnnotations();
            int count = annotations.length;
            if (count > 0) {
                compiled = Lists.newArrayListWithExpectedSize(count);
                for (AnnotationBinding annotation : annotations) {
                    if (annotation != null) {
                        compiled.add(new EcjResolvedAnnotation(annotation));
                    }
                }
            }

            // Look for external annotations
            ExternalAnnotationRepository manager = ExternalAnnotationRepository.get(mClient);
            Collection<ResolvedAnnotation> external = manager.getAnnotations(this);

            return merge(compiled, external);
        }

        private class EcjAstAnnotation extends EcjResolvedAnnotation {

            private final Annotation mAstAnnotation;
            private List<Value> mValues;

            public EcjAstAnnotation(
                    @NonNull AnnotationBinding binding, @NonNull Annotation astAnnotation) {
                super(binding);
                mAstAnnotation = astAnnotation;
            }

            @NonNull
            @Override
            public List<Value> getValues() {
                if (mValues == null) {
                    MemberValuePair[] memberValuePairs = mAstAnnotation.memberValuePairs();
                    List<Value> result = Lists
                            .newArrayListWithExpectedSize(memberValuePairs.length);

                    for (MemberValuePair pair : memberValuePairs) {
                        //  String n = new String(pair.name);
                        Expression expression = pair.value;
                        Object value = null;
                        if (expression instanceof ArrayInitializer) {
                            ArrayInitializer initializer = (ArrayInitializer) expression;
                            Expression[] expressions = initializer.expressions;
                            List<Object> values = Lists.newArrayList();
                            for (Expression e : expressions) {
                                if (e instanceof NameReference) {
                                    ResolvedNode resolved = resolve(((NameReference) e).binding);
                                    if (resolved != null) {
                                        values.add(resolved);
                                    }
                                } else if (e instanceof IntLiteral) {
                                    values.add(((IntLiteral) e).value);
                                } else if (e instanceof StringLiteral) {
                                    values.add(String.valueOf(((StringLiteral) e).source()));
                                } else {
                                    values.add(e.toString());
                                }
                            }
                            value = values.toArray();
                        } else if (expression instanceof IntLiteral) {
                            IntLiteral intLiteral = (IntLiteral) expression;
                            value = intLiteral.value;
                        } else if (expression instanceof TrueLiteral) {
                            value = true;
                        } else if (expression instanceof FalseLiteral) {
                            value = false;
                        } else if (expression instanceof StringLiteral) {
                            value = String.valueOf(((StringLiteral) expression).source());
                        }
                        // Unfortunately, FloatLiteral, LongLiteral etc do not
                        // expose the value field as public. Luckily, we don't need that
                        // for our current annotations.

                        result.add(new Value(new String(pair.name), value));
                    }
                    mValues = result;
                }

                return mValues;
            }

            @Nullable
            @Override
            public Object getValue(@NonNull String name) {
                for (Value value : getValues()) {
                    if (name.equals(value.name)) {
                        return value.value;
                    }
                }
                return null;
            }
        }

        @SuppressWarnings("RedundantIfStatement")
        @Override
        public boolean equals(Object o) {
            if (this == o) {
                return true;
            }
            if (o == null || getClass() != o.getClass()) {
                return false;
            }

            EcjResolvedAnnotation that = (EcjResolvedAnnotation) o;

            if (mBinding != null ? !mBinding.equals(that.mBinding) : that.mBinding != null) {
                return false;
            }

            return true;
        }

        @Override
        public int hashCode() {
            return mBinding != null ? mBinding.hashCode() : 0;
        }
    }

    @Nullable
    private Object getConstantValue(@Nullable Object value) {
        if (value instanceof Constant) {
            if (value == Constant.NotAConstant) {
                return null;
            }
            if (value instanceof StringConstant) {
                return ((StringConstant) value).stringValue();
            } else if (value instanceof IntConstant) {
                return ((IntConstant) value).intValue();
            } else if (value instanceof BooleanConstant) {
                return ((BooleanConstant) value).booleanValue();
            } else if (value instanceof FloatConstant) {
                return ((FloatConstant) value).floatValue();
            } else if (value instanceof LongConstant) {
                return ((LongConstant) value).longValue();
            } else if (value instanceof DoubleConstant) {
                return ((DoubleConstant) value).doubleValue();
            } else if (value instanceof ShortConstant) {
                return ((ShortConstant) value).shortValue();
            } else if (value instanceof CharConstant) {
                return ((CharConstant) value).charValue();
            } else if (value instanceof ByteConstant) {
                return ((ByteConstant) value).byteValue();
            }
        } else if (value instanceof Object[]) {
            Object[] array = (Object[]) value;
            if (array.length > 0) {
                List<Object> list = Lists.newArrayListWithExpectedSize(array.length);
                for (Object element : array) {
                    list.add(getConstantValue(element));
                }
                // Pick type of array. Annotations are limited to Strings, Classes
                // and Annotations
                if (!list.isEmpty()) {
                    Object first = list.get(0);
                    if (first instanceof String) {
                        //noinspection SuspiciousToArrayCall
                        return list.toArray(new String[list.size()]);
                    } else if (first instanceof java.lang.annotation.Annotation) {
                        //noinspection SuspiciousToArrayCall
                        return list.toArray(new Annotation[list.size()]);
                    } else if (first instanceof Class) {
                        //noinspection SuspiciousToArrayCall
                        return list.toArray(new Class[list.size()]);
                    }
                }

                return list.toArray();
            }
        } else if (value instanceof AnnotationBinding) {
            return new EcjResolvedAnnotation((AnnotationBinding) value);
        } else if (value instanceof FieldBinding) {
            return new EcjResolvedField((FieldBinding)value);
        }

        return value;
    }

    public static boolean sameChars(String str, char[] chars) {
        int length = str.length();
        if (chars.length != length) {
            return false;
        }

        for (int i = 0; i < length; i++) {
            if (chars[i] != str.charAt(i)) {
                return false;
            }
        }

        return true;
    }

    /**
     * Does the given compound name match the given string?
     * <p>
     * TODO: Check if ECJ already has this as a utility somewhere
     */
    @VisibleForTesting
    static boolean startsWithCompound(@NonNull String name, @NonNull char[][] compoundName) {
        int length = name.length();
        if (length == 0) {
            return false;
        }
        int index = 0;
        for (int i = 0, n = compoundName.length; i < n; i++) {
            char[] o = compoundName[i];
            //noinspection ForLoopReplaceableByForEach
            for (int j = 0, m = o.length; j < m; j++) {
                if (index == length) {
                    return false; // Don't allow prefix in a compound name
                }
                if (name.charAt(index) != o[j]
                        // Allow using . as an inner class separator whereas the
                        // symbol table will always use $
                        && !(o[j] == '$' && name.charAt(index) == '.')) {
                    return false;
                }
                index++;
            }
            if (i < n - 1) {
                if (index == length) {
                    return true;
                }
                if (name.charAt(index) != '.') {
                    return false;
                }
                index++;
                if (index == length) {
                    return true;
                }
            }
        }

        return index == length;
    }

    @VisibleForTesting
    static boolean equalsCompound(@NonNull String name, @NonNull char[][] compoundName) {
        int length = name.length();
        if (length == 0) {
            return false;
        }
        int index = 0;
        for (int i = 0, n = compoundName.length; i < n; i++) {
            char[] o = compoundName[i];
            //noinspection ForLoopReplaceableByForEach
            for (int j = 0, m = o.length; j < m; j++) {
                if (index == length) {
                    return false; // Don't allow prefix in a compound name
                }
                if (name.charAt(index) != o[j]
                        // Allow using . as an inner class separator whereas the
                        // symbol table will always use $
                        && !(o[j] == '$' && name.charAt(index) == '.')) {
                    return false;
                }
                index++;
            }
            if (i < n - 1) {
                if (index == length) {
                    return false;
                }
                if (name.charAt(index) != '.') {
                    return false;
                }
                index++;
                if (index == length) {
                    return false;
                }
            }
        }

        return index == length;
    }

    /** Checks whether the given class extends or implements a class with the given name */
    private static boolean isInheritor(@Nullable ReferenceBinding cls, @NonNull String name) {
        for (; cls != null; cls = cls.superclass()) {
            ReferenceBinding[] interfaces = cls.superInterfaces();
            for (ReferenceBinding binding : interfaces) {
                if (isInheritor(binding, name)) {
                    return true;
                }
            }

            if (equalsCompound(name, cls.compoundName)) {
                return true;
            }
        }

        return false;
    }
}