File: CompletionLookup.cpp

package info (click to toggle)
swiftlang 6.1.3-4
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 2,791,644 kB
  • sloc: cpp: 9,901,738; ansic: 2,201,433; asm: 1,091,827; python: 308,252; objc: 82,166; f90: 80,126; lisp: 38,358; pascal: 25,559; sh: 20,429; ml: 5,058; perl: 4,745; makefile: 4,484; awk: 3,535; javascript: 3,018; xml: 918; fortran: 664; cs: 573; ruby: 396
file content (3510 lines) | stat: -rw-r--r-- 128,317 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
//===--- CompletionLookup.cpp ---------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2022 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//

#include "swift/IDE/CompletionLookup.h"
#include "CodeCompletionResultBuilder.h"
#include "ExprContextAnalysis.h"
#include "swift/AST/ConformanceLookup.h"
#include "swift/AST/GenericEnvironment.h"
#include "swift/AST/GenericSignature.h"
#include "swift/AST/ParameterList.h"
#include "swift/AST/SourceFile.h"
#include "swift/Basic/Assertions.h"

using namespace swift;
using namespace swift::ide;

namespace {

static bool SwiftKeyPathFilter(ValueDecl *decl, DeclVisibilityKind) {
  switch (decl->getKind()) {
  case DeclKind::Var:
  case DeclKind::Subscript:
    return true;
  default:
    return false;
  }
}

static bool isTopLevelSubcontext(const DeclContext *DC) {
  for (; DC && DC->isLocalContext(); DC = DC->getParent()) {
    switch (DC->getContextKind()) {
    case DeclContextKind::TopLevelCodeDecl:
      return true;
    case DeclContextKind::AbstractFunctionDecl:
    case DeclContextKind::SubscriptDecl:
    case DeclContextKind::EnumElementDecl:
      return false;
    default:
      continue;
    }
  }
  return false;
}

static KnownProtocolKind
protocolForLiteralKind(CodeCompletionLiteralKind kind) {
  switch (kind) {
  case CodeCompletionLiteralKind::ArrayLiteral:
    return KnownProtocolKind::ExpressibleByArrayLiteral;
  case CodeCompletionLiteralKind::BooleanLiteral:
    return KnownProtocolKind::ExpressibleByBooleanLiteral;
  case CodeCompletionLiteralKind::ColorLiteral:
    return KnownProtocolKind::ExpressibleByColorLiteral;
  case CodeCompletionLiteralKind::ImageLiteral:
    return KnownProtocolKind::ExpressibleByImageLiteral;
  case CodeCompletionLiteralKind::DictionaryLiteral:
    return KnownProtocolKind::ExpressibleByDictionaryLiteral;
  case CodeCompletionLiteralKind::IntegerLiteral:
    return KnownProtocolKind::ExpressibleByIntegerLiteral;
  case CodeCompletionLiteralKind::NilLiteral:
    return KnownProtocolKind::ExpressibleByNilLiteral;
  case CodeCompletionLiteralKind::StringLiteral:
    return KnownProtocolKind::ExpressibleByUnicodeScalarLiteral;
  case CodeCompletionLiteralKind::Tuple:
    llvm_unreachable("no such protocol kind");
  }

  llvm_unreachable("Unhandled CodeCompletionLiteralKind in switch.");
}

static Type defaultTypeLiteralKind(CodeCompletionLiteralKind kind,
                                   ASTContext &Ctx) {
  switch (kind) {
  case CodeCompletionLiteralKind::BooleanLiteral:
    return Ctx.getBoolType();
  case CodeCompletionLiteralKind::IntegerLiteral:
    return Ctx.getIntType();
  case CodeCompletionLiteralKind::StringLiteral:
    return Ctx.getStringType();
  case CodeCompletionLiteralKind::ArrayLiteral:
    if (!Ctx.getArrayDecl())
      return Type();
    return Ctx.getArrayDecl()->getDeclaredType();
  case CodeCompletionLiteralKind::DictionaryLiteral:
    if (!Ctx.getDictionaryDecl())
      return Type();
    return Ctx.getDictionaryDecl()->getDeclaredType();
  case CodeCompletionLiteralKind::NilLiteral:
  case CodeCompletionLiteralKind::ColorLiteral:
  case CodeCompletionLiteralKind::ImageLiteral:
  case CodeCompletionLiteralKind::Tuple:
    return Type();
  }

  llvm_unreachable("Unhandled CodeCompletionLiteralKind in switch.");
}

/// Whether funcType has a single argument (not including defaulted arguments)
/// that is of type () -> ().
static bool hasTrivialTrailingClosure(const FuncDecl *FD,
                                      AnyFunctionType *funcType) {
  ParameterListInfo paramInfo(funcType->getParams(), FD,
                              /*skipCurriedSelf*/ FD->hasCurriedSelf());

  if (paramInfo.size() - paramInfo.numNonDefaultedParameters() == 1) {
    auto param = funcType->getParams().back();
    if (!param.isAutoClosure()) {
      if (auto Fn = param.getOldType()->getAs<AnyFunctionType>()) {
        return Fn->getParams().empty() && Fn->getResult()->isVoid();
      }
    }
  }

  return false;
}
} // end anonymous namespace

bool swift::ide::DefaultFilter(ValueDecl *VD, DeclVisibilityKind Kind,
                               DynamicLookupInfo dynamicLookupInfo) {
  return true;
}

bool swift::ide::KeyPathFilter(ValueDecl *decl, DeclVisibilityKind,
                               DynamicLookupInfo dynamicLookupInfo) {
  return isa<TypeDecl>(decl) ||
         (isa<VarDecl>(decl) && decl->getDeclContext()->isTypeContext());
}

bool swift::ide::MacroFilter(ValueDecl *decl, DeclVisibilityKind,
                             DynamicLookupInfo dynamicLookupInfo) {
  return isa<MacroDecl>(decl);
}

bool swift::ide::isCodeCompletionAtTopLevel(const DeclContext *DC) {
  if (DC->isModuleScopeContext())
    return true;

  // CC token at top-level is parsed as an expression. If the only element
  // body of the TopLevelCodeDecl is a CodeCompletionExpr without a base
  // expression, the user might be writing a top-level declaration.
  if (const TopLevelCodeDecl *TLCD = dyn_cast<const TopLevelCodeDecl>(DC)) {
    auto body = TLCD->getBody();
    if (!body || body->empty())
      return true;
    if (body->getElements().size() > 1)
      return false;
    auto expr = body->getFirstElement().dyn_cast<Expr *>();
    if (!expr)
      return false;
    if (CodeCompletionExpr *CCExpr = dyn_cast<CodeCompletionExpr>(expr)) {
      if (CCExpr->getBase() == nullptr)
        return true;
    }
  }

  return false;
}

bool swift::ide::isCompletionDeclContextLocalContext(DeclContext *DC) {
  if (!DC->isLocalContext())
    return false;
  if (isCodeCompletionAtTopLevel(DC))
    return false;
  return true;
}

/// Returns \c true if \p DC can handles async call.
bool swift::ide::canDeclContextHandleAsync(const DeclContext *DC) {
  if (auto *func = dyn_cast<AbstractFunctionDecl>(DC))
    return func->isAsyncContext();

  if (auto *closure = dyn_cast<ClosureExpr>(DC)) {
    // See if the closure has 'async' function type.
    if (auto closureType = closure->getType())
      if (auto fnType = closureType->getAs<AnyFunctionType>())
        if (fnType->isAsync())
          return true;

    // If the closure doesn't contain any async call in the body, closure itself
    // doesn't have 'async' type even if 'async' closure is expected.
    //   func foo(fn: () async -> Void)
    //   foo { <HERE> }
    // In this case, the closure is wrapped with a 'FunctionConversionExpr'
    // which has 'async' function type.
    struct AsyncClosureChecker : public ASTWalker {
      const ClosureExpr *Target;
      bool Result = false;

      /// Walk everything in a macro.
      MacroWalking getMacroWalkingBehavior() const override {
        return MacroWalking::ArgumentsAndExpansion;
      }

      AsyncClosureChecker(const ClosureExpr *Target) : Target(Target) {}

      PreWalkResult<Expr *> walkToExprPre(Expr *E) override {
        if (E == Target)
          return Action::SkipNode(E);

        if (auto conversionExpr = dyn_cast<FunctionConversionExpr>(E)) {
          if (conversionExpr->getSubExpr() == Target) {
            if (conversionExpr->getType()->is<AnyFunctionType>() &&
                conversionExpr->getType()->castTo<AnyFunctionType>()->isAsync())
              Result = true;
            return Action::SkipNode(E);
          }
        }
        return Action::Continue(E);
      }
    } checker(closure);
    closure->getParent()->walkContext(checker);
    return checker.Result;
  }

  return false;
}

/// Return \c true if the completion happens at top-level of a library file.
bool swift::ide::isCodeCompletionAtTopLevelOfLibraryFile(
    const DeclContext *DC) {
  if (DC->getParentSourceFile()->isScriptMode())
    return false;
  return isCodeCompletionAtTopLevel(DC);
}

// MARK: - CompletionLookup

void CompletionLookup::foundFunction(const AbstractFunctionDecl *AFD) {
  FoundFunctionCalls = true;
  const DeclName Name = AFD->getName();
  auto ArgNames = Name.getArgumentNames();
  if (ArgNames.empty())
    return;
  if (ArgNames[0].empty())
    FoundFunctionsWithoutFirstKeyword = true;
}

void CompletionLookup::foundFunction(const AnyFunctionType *AFT) {
  FoundFunctionCalls = true;
  auto Params = AFT->getParams();
  if (Params.empty())
    return;
  if (Params.size() == 1 && !Params[0].hasLabel()) {
    FoundFunctionsWithoutFirstKeyword = true;
    return;
  }
  if (!Params[0].hasLabel())
    FoundFunctionsWithoutFirstKeyword = true;
}

bool CompletionLookup::canBeUsedAsRequirementFirstType(Type selfTy,
                                                       TypeAliasDecl *TAD) {
  if (TAD->isGeneric())
    return false;

  auto T = TAD->getDeclaredInterfaceType();
  auto subMap = selfTy->getContextSubstitutionMap(TAD->getDeclContext());

  return T.subst(subMap)->is<ArchetypeType>();
}

CompletionLookup::CompletionLookup(CodeCompletionResultSink &Sink,
                                   ASTContext &Ctx,
                                   const DeclContext *CurrDeclContext,
                                   CodeCompletionContext *CompletionContext)
    : Sink(Sink), Ctx(Ctx), CurrDeclContext(CurrDeclContext),
      CurrModule(CurrDeclContext ? CurrDeclContext->getParentModule()
                                 : nullptr),
      Importer(static_cast<ClangImporter *>(
          CurrDeclContext->getASTContext().getClangModuleLoader())),
      CompletionContext(CompletionContext) {
  // Determine if we are doing code completion inside a static method.
  if (CurrDeclContext) {
    CurrentMethod = CurrDeclContext->getInnermostMethodContext();
    if (auto *FD = dyn_cast_or_null<FuncDecl>(CurrentMethod))
      InsideStaticMethod = FD->isStatic();
    CanCurrDeclContextHandleAsync = canDeclContextHandleAsync(CurrDeclContext);
  }
}

void CompletionLookup::addSubModuleNames(
    std::vector<std::pair<std::string, bool>> &SubModuleNameVisibilityPairs) {
  for (auto &Pair : SubModuleNameVisibilityPairs) {
    CodeCompletionResultBuilder Builder = makeResultBuilder(
        CodeCompletionResultKind::Declaration, SemanticContextKind::None);
    auto MD = ModuleDecl::create(Ctx.getIdentifier(Pair.first), Ctx);
    MD->setFailedToLoad();
    Builder.setAssociatedDecl(MD);
    Builder.addBaseName(MD->getNameStr());
    Builder.addTypeAnnotation("Module");
    if (Pair.second)
      Builder.setContextualNotRecommended(
          ContextualNotRecommendedReason::RedundantImport);
  }
}

void CompletionLookup::collectImportedModules(
    llvm::StringSet<> &directImportedModules,
    llvm::StringSet<> &allImportedModules) {
  SmallVector<ImportedModule, 16> Imported;
  SmallVector<ImportedModule, 16> FurtherImported;
  CurrDeclContext->getParentSourceFile()->getImportedModules(
      Imported, ModuleDecl::getImportFilterLocal());

  for (ImportedModule &imp : Imported)
    directImportedModules.insert(imp.importedModule->getNameStr());

  while (!Imported.empty()) {
    ModuleDecl *MD = Imported.back().importedModule;
    Imported.pop_back();
    if (!allImportedModules.insert(MD->getNameStr()).second)
      continue;
    FurtherImported.clear();
    MD->getImportedModules(FurtherImported,
                           ModuleDecl::ImportFilterKind::Exported);
    Imported.append(FurtherImported.begin(), FurtherImported.end());
  }
}

void CompletionLookup::addModuleName(
    ModuleDecl *MD, std::optional<ContextualNotRecommendedReason> R) {

  // Don't add underscored cross-import overlay modules.
  if (MD->getDeclaringModuleIfCrossImportOverlay())
    return;

  CodeCompletionResultBuilder Builder = makeResultBuilder(
      CodeCompletionResultKind::Declaration, SemanticContextKind::None);
  Builder.setAssociatedDecl(MD);
  auto moduleName = MD->getName();

  // This checks if module aliasing was used. For example, when editing
  // `import ...`, and `-module-alias Foo=Bar` was passed, we want to show
  // Foo as an option to import, instead of Bar (name of the binary), as
  // Foo is the name that should appear in source files.
  auto aliasedName = Ctx.getRealModuleName(
      moduleName, ASTContext::ModuleAliasLookupOption::aliasFromRealName);
  if (aliasedName != moduleName && // check if module aliasing was applied
      !aliasedName.empty()) { // check an alias mapped to the binary name exists
    moduleName = aliasedName; // if so, use the aliased name
  }
  Builder.addBaseName(moduleName.str());
  Builder.addTypeAnnotation("Module");
  if (R)
    Builder.setContextualNotRecommended(*R);
}

void CompletionLookup::addImportModuleNames() {
  SmallVector<Identifier, 0> ModuleNames;
  Ctx.getVisibleTopLevelModuleNames(ModuleNames);

  llvm::StringSet<> directImportedModules;
  llvm::StringSet<> allImportedModules;
  collectImportedModules(directImportedModules, allImportedModules);

  auto mainModuleName = CurrModule->getName();
  for (auto ModuleName : ModuleNames) {
    if (ModuleName == mainModuleName || isHiddenModuleName(ModuleName))
      continue;

    auto MD = ModuleDecl::create(ModuleName, Ctx);
    MD->setFailedToLoad();

    std::optional<ContextualNotRecommendedReason> Reason = std::nullopt;

    // Imported modules are not recommended.
    if (directImportedModules.contains(MD->getNameStr())) {
      Reason = ContextualNotRecommendedReason::RedundantImport;
    } else if (allImportedModules.contains(MD->getNameStr())) {
      Reason = ContextualNotRecommendedReason::RedundantImportIndirect;
    }

    addModuleName(MD, Reason);
  }
}

SemanticContextKind
CompletionLookup::getSemanticContext(const Decl *D, DeclVisibilityKind Reason,
                                     DynamicLookupInfo dynamicLookupInfo) {
  if (ForcedSemanticContext)
    return *ForcedSemanticContext;

  switch (Reason) {
  case DeclVisibilityKind::LocalDecl:
  case DeclVisibilityKind::FunctionParameter:
  case DeclVisibilityKind::GenericParameter:
    return SemanticContextKind::Local;

  case DeclVisibilityKind::MemberOfCurrentNominal:
    return SemanticContextKind::CurrentNominal;

  case DeclVisibilityKind::MemberOfProtocolConformedToByCurrentNominal:
  case DeclVisibilityKind::MemberOfSuper:
    return SemanticContextKind::Super;

  case DeclVisibilityKind::MemberOfOutsideNominal:
    return SemanticContextKind::OutsideNominal;

  case DeclVisibilityKind::VisibleAtTopLevel:
    if (CurrDeclContext && D->getModuleContext() == CurrModule) {
      // Treat global variables from the same source file as local when
      // completing at top-level.
      if (isa<VarDecl>(D) && isTopLevelSubcontext(CurrDeclContext) &&
          D->getDeclContext()->getParentSourceFile() ==
              CurrDeclContext->getParentSourceFile()) {
        return SemanticContextKind::Local;
      } else {
        return SemanticContextKind::CurrentModule;
      }
    } else {
      return SemanticContextKind::OtherModule;
    }

  case DeclVisibilityKind::DynamicLookup:
    switch (dynamicLookupInfo.getKind()) {
    case DynamicLookupInfo::None:
      llvm_unreachable("invalid DynamicLookupInfo::Kind for dynamic lookup");

    case DynamicLookupInfo::AnyObject:
      // AnyObject results can come from different modules, including the
      // current module, but we always assign them the OtherModule semantic
      // context.  These declarations are uniqued by signature, so it is
      // totally random (determined by the hash function) which of the
      // equivalent declarations (across multiple modules) we will get.
      return SemanticContextKind::OtherModule;

    case DynamicLookupInfo::KeyPathDynamicMember:
      // Use the visibility of the underlying declaration.
      // FIXME: KeyPath<AnyObject, U> !?!?
      assert(dynamicLookupInfo.getKeyPathDynamicMember().originalVisibility !=
             DeclVisibilityKind::DynamicLookup);
      return getSemanticContext(
          D, dynamicLookupInfo.getKeyPathDynamicMember().originalVisibility,
          {});
    }

  case DeclVisibilityKind::MemberOfProtocolDerivedByCurrentNominal:
    llvm_unreachable("should not see this kind");
  }
  llvm_unreachable("unhandled kind");
}

bool CompletionLookup::isUnresolvedMemberIdealType(Type Ty) {
  assert(Ty);
  if (!IsUnresolvedMember)
    return false;
  Type idealTy = expectedTypeContext.getIdealType();
  if (!idealTy)
    return false;
  /// Consider optional object type is the ideal.
  /// For example:
  ///   enum MyEnum { case foo, bar }
  ///   func foo(_: MyEnum?)
  ///   fooo(.<HERE>)
  /// Prefer '.foo' and '.bar' over '.some' and '.none'.
  idealTy = idealTy->lookThroughAllOptionalTypes();
  return idealTy->isEqual(Ty);
}

CodeCompletionResultBuilder
CompletionLookup::makeResultBuilder(CodeCompletionResultKind kind,
                                    SemanticContextKind semanticContext) const {
  CodeCompletionResultBuilder builder(Sink, kind, semanticContext);
  builder.setTypeContext(expectedTypeContext, CurrDeclContext);
  return builder;
}

void CompletionLookup::addValueBaseName(CodeCompletionResultBuilder &Builder,
                                        DeclBaseName Name) {
  auto NameStr = Name.userFacingName();
  bool shouldEscapeKeywords;
  if (Name.isSpecial()) {
    // Special names (i.e. 'init') are always displayed as its user facing
    // name.
    shouldEscapeKeywords = false;
  } else if (ExprType) {
    // After dot. User can write any keyword after '.' except for `init` and
    // `self`. E.g. 'func `init`()' must be called by 'expr.`init`()'.
    shouldEscapeKeywords = NameStr == "self" || NameStr == "init";
  } else {
    // As primary expresson. We have to escape almost every keywords except
    // for 'self' and 'Self'.
    shouldEscapeKeywords = NameStr != "self" && NameStr != "Self";
  }

  if (!shouldEscapeKeywords) {
    Builder.addBaseName(NameStr);
  } else {
    SmallString<16> buffer;
    Builder.addBaseName(Builder.escapeKeyword(NameStr, true, buffer));
  }
}

void CompletionLookup::addLeadingDot(CodeCompletionResultBuilder &Builder) {
  if (NeedOptionalUnwrap) {
    Builder.setNumBytesToErase(NumBytesToEraseForOptionalUnwrap);
    Builder.addQuestionMark();
    Builder.addLeadingDot();
    return;
  }
  if (needDot())
    Builder.addLeadingDot();
}

void CompletionLookup::addTypeAnnotation(CodeCompletionResultBuilder &Builder,
                                         Type T, GenericSignature genericSig) {
  PrintOptions PO;
  PO.OpaqueReturnTypePrinting =
      PrintOptions::OpaqueReturnTypePrintingMode::WithoutOpaqueKeyword;
  if (auto typeContext = CurrDeclContext->getInnermostTypeContext())
    PO.setBaseType(typeContext->getDeclaredTypeInContext());
  Builder.addTypeAnnotation(eraseArchetypes(T, genericSig), PO);
  Builder.setResultTypes(T);
}

void CompletionLookup::addTypeAnnotationForImplicitlyUnwrappedOptional(
    CodeCompletionResultBuilder &Builder, Type T, GenericSignature genericSig,
    bool dynamicOrOptional) {

  std::string suffix;
  // FIXME: This retains previous behavior, but in reality the type of dynamic
  // lookups is IUO, not Optional as it is for the @optional attribute.
  if (dynamicOrOptional) {
    T = T->getOptionalObjectType();
    suffix = "?";
  }

  PrintOptions PO;
  PO.PrintOptionalAsImplicitlyUnwrapped = true;
  PO.OpaqueReturnTypePrinting =
      PrintOptions::OpaqueReturnTypePrintingMode::WithoutOpaqueKeyword;
  if (auto typeContext = CurrDeclContext->getInnermostTypeContext())
    PO.setBaseType(typeContext->getDeclaredTypeInContext());
  Builder.addTypeAnnotation(eraseArchetypes(T, genericSig), PO, suffix);
  Builder.setResultTypes(T);
  Builder.setTypeContext(expectedTypeContext, CurrDeclContext);
}

/// For printing in code completion results, replace archetypes with
/// protocol compositions.
///
/// FIXME: Perhaps this should be an option in PrintOptions instead.
Type CompletionLookup::eraseArchetypes(Type type, GenericSignature genericSig) {
  if (!genericSig)
    return type;

  if (auto *genericFuncType = type->getAs<GenericFunctionType>()) {
    assert(genericFuncType->getGenericSignature()->isEqual(genericSig) &&
           "if not, just use the GFT's signature instead below");

    SmallVector<AnyFunctionType::Param, 8> erasedParams;
    for (const auto &param : genericFuncType->getParams()) {
      auto erasedTy = eraseArchetypes(param.getPlainType(), genericSig);
      erasedParams.emplace_back(param.withType(erasedTy));
    }
    return GenericFunctionType::get(
        genericSig, erasedParams,
        eraseArchetypes(genericFuncType->getResult(), genericSig),
        genericFuncType->getExtInfo());
  }

  return type.transformRec([&](Type t) -> std::optional<Type> {
    // FIXME: Code completion should only deal with one or the other,
    // and not both.
    if (auto *archetypeType = t->getAs<ArchetypeType>()) {
      // Don't erase opaque archetype.
      if (isa<OpaqueTypeArchetypeType>(archetypeType) &&
          archetypeType->isRoot())
        return std::nullopt;

      auto genericSig = archetypeType->getGenericEnvironment()->getGenericSignature();
      auto upperBound = genericSig->getUpperBound(
          archetypeType->getInterfaceType(),
          /*forExistentialSelf=*/false,
          /*withParameterizedProtocols=*/false);

      if (!upperBound->isAny())
        return upperBound;
    }

    if (t->isTypeParameter()) {
      auto upperBound = genericSig->getUpperBound(
          t,
          /*forExistentialSelf=*/false,
          /*withParameterizedProtocols=*/false);

      if (!upperBound->isAny())
        return upperBound;
    }

    return std::nullopt;
  });
}

Type CompletionLookup::getTypeOfMember(const ValueDecl *VD,
                                       DynamicLookupInfo dynamicLookupInfo) {
  switch (dynamicLookupInfo.getKind()) {
  case DynamicLookupInfo::None:
    return getTypeOfMember(VD, this->ExprType);
  case DynamicLookupInfo::AnyObject:
    return getTypeOfMember(VD, Type());
  case DynamicLookupInfo::KeyPathDynamicMember: {
    auto &keyPathInfo = dynamicLookupInfo.getKeyPathDynamicMember();

    // Map the result of VD to keypath member lookup results.
    // Given:
    //   struct Wrapper<T> {
    //     subscript<U>(dynamicMember: KeyPath<T, U>) -> Wrapped<U> { get }
    //   }
    //   struct Circle {
    //     var center: Point { get }
    //     var radius: Length { get }
    //   }
    //
    // Consider 'Wrapper<Circle>.center'.
    //   'VD' is 'Circle.center' decl.
    //   'keyPathInfo.subscript' is 'Wrapper<T>.subscript' decl.
    //   'keyPathInfo.baseType' is 'Wrapper<Circle>' type.

    // FIXME: Handle nested keypath member lookup.
    // i.e. cases where 'ExprType' != 'keyPathInfo.baseType'.

    auto *SD = keyPathInfo.subscript;
    const auto elementTy = SD->getElementInterfaceType();
    if (!elementTy->hasTypeParameter())
      return elementTy;

    // Map is:
    //   { τ_0_0(T) => Circle
    //     τ_1_0(U) => U }
    auto subs = keyPathInfo.baseType->getMemberSubstitutions(SD);

    // FIXME: The below should use substitution map substitution.

    // If the keyPath result type has type parameters, that might affect the
    // subscript result type.
    auto keyPathResultTy = getResultTypeOfKeypathDynamicMember(SD);
    if (keyPathResultTy->hasTypeParameter()) {
      auto keyPathRootTy = getRootTypeOfKeypathDynamicMember(SD).subst(
          QueryTypeSubstitutionMap{subs},
          LookUpConformanceInModule());

      // The result type of the VD.
      // i.e. 'Circle.center' => 'Point'.
      auto innerResultTy = getTypeOfMember(VD, keyPathRootTy);

      if (auto paramTy = keyPathResultTy->getAs<GenericTypeParamType>()) {
        // Replace keyPath result type in the map with the inner result type.
        // i.e. Make the map as:
        //   { τ_0_0(T) => Circle
        //     τ_1_0(U) => Point }
        auto key = paramTy->getCanonicalType()->castTo<GenericTypeParamType>();
        subs[key] = innerResultTy;
      } else {
        // FIXME: Handle the case where the KeyPath result is generic.
        // e.g. 'subscript<U>(dynamicMember: KeyPath<T, Box<U>>) -> Bag<U>'
        // For now, just return the inner type.
        return innerResultTy;
      }
    }

    // Substitute the element type of the subscript using modified map.
    // i.e. 'Wrapped<U>' => 'Wrapped<Point>'.
    return elementTy.subst(QueryTypeSubstitutionMap{subs},
                           LookUpConformanceInModule());
  }
  }
  llvm_unreachable("Unhandled DynamicLookupInfo Kind in switch");
}

Type CompletionLookup::getTypeOfMember(const ValueDecl *VD, Type ExprType) {
  Type T = VD->getInterfaceType();
  assert(!T.isNull());

  if (ExprType) {
    Type ContextTy = VD->getDeclContext()->getDeclaredInterfaceType();
    if (ContextTy) {
      // Look through lvalue types and metatypes
      Type MaybeNominalType = ExprType->getRValueType();

      if (auto Metatype = MaybeNominalType->getAs<MetatypeType>())
        MaybeNominalType = Metatype->getInstanceType();

      if (auto SelfType = MaybeNominalType->getAs<DynamicSelfType>())
        MaybeNominalType = SelfType->getSelfType();

      // For optional protocol requirements and dynamic dispatch,
      // strip off optionality from the base type, but only if
      // we're not actually completing a member of Optional.
      if (!ContextTy->getOptionalObjectType() &&
          MaybeNominalType->getOptionalObjectType())
        MaybeNominalType = MaybeNominalType->getOptionalObjectType();

      // For dynamic lookup don't substitute in the base type.
      if (MaybeNominalType->isAnyObject())
        return T;

      // FIXME: Sometimes ExprType is the type of the member here,
      // and not the type of the base. That is inconsistent and
      // should be cleaned up.
      if (!MaybeNominalType->mayHaveMembers())
        return T;

      // We can't do anything if the base type has unbound generic parameters.
      if (MaybeNominalType->hasUnboundGenericType())
        return T;

      // If we are doing implicit member lookup on a protocol and we have found
      // a declaration in a constrained extension, use the extension's `Self`
      // type for the generic substitution.
      // Eg in the following, the `Self` type returned by `qux` is
      // `MyGeneric<Int>`, not `MyProto` because of the `Self` type restriction.
      // ```
      // protocol MyProto {}
      // struct MyGeneric<T>: MyProto {}
      // extension MyProto where Self == MyGeneric<Int> {
      //   static func qux() -> Self { .init() }
      // }
      // func takeMyProto(_: any MyProto)  {}
      // func test() {
      //   takeMyProto(.#^COMPLETE^#)
      // }
      // ```
      if (MaybeNominalType->isExistentialType()) {
        Type SelfType;
        if (auto *ED = dyn_cast<ExtensionDecl>(VD->getDeclContext())) {
          if (ED->getSelfProtocolDecl() && ED->isConstrainedExtension()) {
            auto Sig = ED->getGenericSignature();
            SelfType = Sig->getConcreteType(ED->getSelfInterfaceType());
          }
        }
        if (SelfType) {
          MaybeNominalType = SelfType;
        } else {
          return T;
        }
      }

      // For everything else, substitute in the base type.
      auto Subs = MaybeNominalType->getMemberSubstitutionMap(VD);

      // For a GenericFunctionType, we only want to substitute the
      // param/result types, as otherwise we might end up with a bad generic
      // signature if there are UnresolvedTypes present in the base type. Note
      // we pass in DesugarMemberTypes so that we see the actual concrete type
      // witnesses instead of type alias types.
      if (auto *GFT = T->getAs<GenericFunctionType>()) {
        T = GFT->substGenericArgs(Subs, SubstFlags::DesugarMemberTypes);
      } else {
        T = T.subst(Subs, SubstFlags::DesugarMemberTypes);
      }
    }
  }

  return T;
}

Type CompletionLookup::getAssociatedTypeType(const AssociatedTypeDecl *ATD) {
  Type BaseTy = BaseType;
  if (!BaseTy)
    BaseTy = ExprType;
  if (!BaseTy && CurrDeclContext)
    BaseTy =
        CurrDeclContext->getInnermostTypeContext()->getDeclaredTypeInContext();
  if (BaseTy) {
    BaseTy = BaseTy->getInOutObjectType()->getMetatypeInstanceType();
    if (auto NTD = BaseTy->getAnyNominal()) {
      auto Conformance = lookupConformance(BaseTy, ATD->getProtocol());
      if (Conformance.isConcrete()) {
        return Conformance.getConcrete()->getTypeWitness(
            const_cast<AssociatedTypeDecl *>(ATD));
      }
    }
  }
  return Type();
}

void CompletionLookup::analyzeActorIsolation(
    const ValueDecl *VD, Type T, bool &implicitlyAsync,
    std::optional<ContextualNotRecommendedReason> &NotRecommended) {
  auto isolation = getActorIsolation(const_cast<ValueDecl *>(VD));

  switch (isolation.getKind()) {
  case ActorIsolation::ActorInstance: {
    // TODO: implicitlyThrowing here for distributed
    if (IsCrossActorReference) {
      implicitlyAsync = true;
      // TODO: 'NotRecommended' if this is a r-value reference.
    }
    break;
  }
  case ActorIsolation::GlobalActor: {
    // For "preconcurrency" global actor isolation, automatic 'async' only happens
    // if the context has adopted concurrency.
    if (isolation.preconcurrency() &&
        !CanCurrDeclContextHandleAsync &&
        !completionContextUsesConcurrencyFeatures(CurrDeclContext)) {
      return;
    }

    auto getClosureActorIsolation = [this](AbstractClosureExpr *CE) {
      // Prefer solution-specific actor-isolations and fall back to the one
      // recorded in the AST.
      auto isolation = ClosureActorIsolations.find(CE);
      if (isolation != ClosureActorIsolations.end()) {
        return isolation->second;
      } else {
        return CE->getActorIsolation();
      }
    };
    auto contextIsolation = getActorIsolationOfContext(
        const_cast<DeclContext *>(CurrDeclContext), getClosureActorIsolation);
    if (contextIsolation != isolation) {
      implicitlyAsync = true;
    }
    break;
  }
  case ActorIsolation::Erased:
    implicitlyAsync = true;
    break;
  case ActorIsolation::Unspecified:
  case ActorIsolation::Nonisolated:
  case ActorIsolation::NonisolatedUnsafe:
    return;
  }
}

void CompletionLookup::addVarDeclRef(const VarDecl *VD,
                                     DeclVisibilityKind Reason,
                                     DynamicLookupInfo dynamicLookupInfo) {
  if (!VD->hasName())
    return;

  const Identifier Name = VD->getName();
  assert(!Name.empty() && "name should not be empty");

  Type VarType;
  auto SolutionSpecificType = SolutionSpecificVarTypes.find(VD);
  if (SolutionSpecificType != SolutionSpecificVarTypes.end()) {
    assert(!VarType && "Type recorded in the AST and is also solution-specific?");
    VarType = SolutionSpecificType->second;
  } else if (VD->hasInterfaceType()) {
    VarType = getTypeOfMember(VD, dynamicLookupInfo);
  }

  std::optional<ContextualNotRecommendedReason> NotRecommended;
  // "not recommended" in its own getter.
  if (Kind == LookupKind::ValueInDeclContext) {
    if (auto accessor = dyn_cast<AccessorDecl>(CurrDeclContext)) {
      if (accessor->getStorage() == VD && accessor->isGetter())
        NotRecommended =
            ContextualNotRecommendedReason::VariableUsedInOwnDefinition;
    }
  }
  bool implicitlyAsync = false;
  analyzeActorIsolation(VD, VarType, implicitlyAsync, NotRecommended);
  CodeCompletionResultBuilder Builder =
      makeResultBuilder(CodeCompletionResultKind::Declaration,
                        getSemanticContext(VD, Reason, dynamicLookupInfo));
  Builder.setCanCurrDeclContextHandleAsync(CanCurrDeclContextHandleAsync);
  Builder.setAssociatedDecl(VD);
  addLeadingDot(Builder);
  addValueBaseName(Builder, Name);

  if (NotRecommended)
    Builder.setContextualNotRecommended(*NotRecommended);

  if (!VarType)
    return;

  if (auto *PD = dyn_cast<ParamDecl>(VD)) {
    if (Name != Ctx.Id_self && PD->isInOut()) {
      // It is useful to show inout for function parameters.
      // But for 'self' it is just noise.
      VarType = InOutType::get(VarType);
    }
  }
  auto DynamicOrOptional =
      IsDynamicLookup || VD->getAttrs().hasAttribute<OptionalAttr>();
  if (DynamicOrOptional) {
    // Values of properties that were found on a AnyObject have
    // Optional<T> type.  Same applies to optional members.
    VarType = OptionalType::get(VarType);
  }

  auto genericSig =
      VD->getInnermostDeclContext()->getGenericSignatureOfContext();
  if (VD->isImplicitlyUnwrappedOptional())
    addTypeAnnotationForImplicitlyUnwrappedOptional(
        Builder, VarType, genericSig, DynamicOrOptional);
  else
    addTypeAnnotation(Builder, VarType, genericSig);

  if (implicitlyAsync)
    Builder.addAnnotatedAsync();

  if (isUnresolvedMemberIdealType(VarType))
    Builder.addFlair(CodeCompletionFlairBit::ExpressionSpecific);

  if (auto Accessor = VD->getEffectfulGetAccessor()) {
    if (auto AFT = getTypeOfMember(Accessor, dynamicLookupInfo)->getAs<AnyFunctionType>()) {
      if (Accessor->hasImplicitSelfDecl()) {
        AFT = AFT->getResult()->getAs<AnyFunctionType>();
        assert(AFT);
      }
      addEffectsSpecifiers(Builder, AFT, Accessor);
    }
  }
}

/// Return whether \p param has a non-desirable default value for code
/// completion.
///
/// 'ClangImporter::Implementation::inferDefaultArgument()' automatically adds
/// default values for some parameters;
///   * NS_OPTIONS enum type with the name '...Options'.
///   * NSDictionary and labeled 'options', 'attributes', or 'userInfo'.
///
/// But sometimes, this behavior isn't really desirable. This function add a
/// heuristic where if a parameter matches all the following condition, we
/// consider the imported default value is _not_ desirable:
///   * it is the first parameter,
///   * it doesn't have an argument label, and
///   * the imported function base name ends with those words
/// For example, ClangImporter imports:
///
///   -(void)addAttributes:(NSDictionary *)attrs, options:(NSDictionary *)opts;
///
/// as:
///
///   func addAttributes(_ attrs: [AnyHashable:Any] = [:],
///                      options opts: [AnyHashable:Any] = [:])
///
/// In this case, we don't want 'attrs' defaulted because the function name have
/// 'Attribute' in its name so calling 'value.addAttribute()' doesn't make
/// sense, but we _do_ want to keep 'opts' defaulted.
///
/// Note that:
///
///   -(void)performWithOptions:(NSDictionary *) opts;
///
/// This doesn't match the condition because the base name of the function in
/// Swift is 'peform':
///
///   func perform(options opts: [AnyHashable:Any] = [:])
///
bool isNonDesirableImportedDefaultArg(const ParamDecl *param) {
  auto kind = param->getDefaultArgumentKind();
  if (kind != DefaultArgumentKind::EmptyArray &&
      kind != DefaultArgumentKind::EmptyDictionary)
    return false;

  if (!param->getArgumentName().empty())
    return false;

  auto *func = dyn_cast<FuncDecl>(param->getDeclContext());
  if (!func->hasClangNode())
    return false;
  if (func->getParameters()->front() != param)
    return false;
  if (func->getBaseName().isSpecial())
    return false;

  auto baseName = func->getBaseName().getIdentifier().str();
  switch (kind) {
  case DefaultArgumentKind::EmptyArray:
    return (baseName.ends_with("Options"));
  case DefaultArgumentKind::EmptyDictionary:
    return (baseName.ends_with("Options") || baseName.ends_with("Attributes") ||
            baseName.ends_with("UserInfo"));
  default:
    llvm_unreachable("unhandled DefaultArgumentKind");
  }
}

bool CompletionLookup::hasInterestingDefaultValue(const ParamDecl *param) {
  if (!param)
    return false;

  switch (param->getDefaultArgumentKind()) {
  case DefaultArgumentKind::Normal:
  case DefaultArgumentKind::NilLiteral:
  case DefaultArgumentKind::StoredProperty:
  case DefaultArgumentKind::Inherited:
    return true;

  case DefaultArgumentKind::EmptyArray:
  case DefaultArgumentKind::EmptyDictionary:
    if (isNonDesirableImportedDefaultArg(param))
      return false;
    return true;

  case DefaultArgumentKind::None:
#define MAGIC_IDENTIFIER(NAME, STRING, SYNTAX_KIND)                            \
  case DefaultArgumentKind::NAME:
#include "swift/AST/MagicIdentifierKinds.def"
  case DefaultArgumentKind::ExpressionMacro:
    return false;
  }
}

bool CompletionLookup::shouldAddItemWithoutDefaultArgs(
    const AbstractFunctionDecl *func) {
  if (!func || !Sink.addCallWithNoDefaultArgs)
    return false;
  for (auto param : *func->getParameters()) {
    if (hasInterestingDefaultValue(param))
      return true;
  }
  return false;
}

bool CompletionLookup::addCallArgumentPatterns(
    CodeCompletionResultBuilder &Builder,
    ArrayRef<AnyFunctionType::Param> typeParams,
    ArrayRef<const ParamDecl *> declParams, GenericSignature genericSig,
    bool includeDefaultArgs) {
  assert(declParams.empty() || typeParams.size() == declParams.size());

  bool modifiedBuilder = false;
  bool needComma = false;
  // Iterate over each parameter.
  for (unsigned i = 0; i != typeParams.size(); ++i) {
    auto &typeParam = typeParams[i];

    Identifier argName = typeParam.getLabel();
    Identifier bodyName;
    bool isIUO = false;
    bool hasDefault = false;
    if (!declParams.empty()) {
      const ParamDecl *PD = declParams[i];
      hasDefault =
          PD->isDefaultArgument() && !isNonDesirableImportedDefaultArg(PD);
      // Skip default arguments if we're either not including them or they
      // aren't interesting
      if (hasDefault &&
          (!includeDefaultArgs || !hasInterestingDefaultValue(PD)))
        continue;

      argName = PD->getArgumentName();
      bodyName = PD->getParameterName();
      isIUO = PD->isImplicitlyUnwrappedOptional();
    }

    bool isVariadic = typeParam.isVariadic();
    bool isInOut = typeParam.isInOut();
    bool isAutoclosure = typeParam.isAutoClosure();
    Type paramTy = typeParam.getPlainType();
    if (isVariadic)
      paramTy = ParamDecl::getVarargBaseTy(paramTy);

    Type contextTy;
    if (auto typeContext = CurrDeclContext->getInnermostTypeContext())
      contextTy = typeContext->getDeclaredTypeInContext();

    if (needComma)
      Builder.addComma();
    Builder.addCallArgument(argName, bodyName,
                            eraseArchetypes(paramTy, genericSig), contextTy,
                            isVariadic, isInOut, isIUO, isAutoclosure,
                            /*IsLabeledTrailingClosure=*/false,
                            /*IsForOperator=*/false, hasDefault);

    modifiedBuilder = true;
    needComma = true;
  }

  return modifiedBuilder;
}

bool CompletionLookup::addCallArgumentPatterns(
    CodeCompletionResultBuilder &Builder, const AnyFunctionType *AFT,
    const ParameterList *Params, GenericSignature genericSig,
    bool includeDefaultArgs) {
  ArrayRef<const ParamDecl *> declParams;
  if (Params)
    declParams = Params->getArray();
  return addCallArgumentPatterns(Builder, AFT->getParams(), declParams,
                                 genericSig, includeDefaultArgs);
}

void CompletionLookup::addEffectsSpecifiers(
    CodeCompletionResultBuilder &Builder, const AnyFunctionType *AFT,
    const AbstractFunctionDecl *AFD, bool forceAsync) {
  assert(AFT != nullptr);

  // 'async'.
  if (forceAsync || (AFD && AFD->hasAsync()) ||
      (AFT->hasExtInfo() && AFT->isAsync()))
    Builder.addAnnotatedAsync();

  // 'throws' or 'rethrows'.
  if (AFD && AFD->getAttrs().hasAttribute<RethrowsAttr>())
    Builder.addAnnotatedRethrows();
  else if (AFT->hasExtInfo() && AFT->isThrowing())
    Builder.addAnnotatedThrows();
}

void CompletionLookup::addPoundAvailable(std::optional<StmtKind> ParentKind) {
  if (ParentKind != StmtKind::If && ParentKind != StmtKind::Guard)
    return;
  CodeCompletionResultBuilder Builder = makeResultBuilder(
      CodeCompletionResultKind::Keyword,
      // FIXME: SemanticContextKind::Local is not correct.
      // Use 'None' (and fix prioritization) or introduce a new context.
      SemanticContextKind::Local);
  Builder.addFlair(CodeCompletionFlairBit::ExpressionSpecific);
  Builder.addBaseName("available");
  Builder.addLeftParen();
  Builder.addSimpleTypedParameter("Platform", /*IsVarArg=*/true);
  Builder.addComma();
  Builder.addTextChunk("*");
  Builder.addRightParen();
}

void CompletionLookup::addPoundSelector(bool needPound) {
  // #selector is only available when the Objective-C runtime is.
  if (!Ctx.LangOpts.EnableObjCInterop)
    return;

  CodeCompletionResultBuilder Builder = makeResultBuilder(
      CodeCompletionResultKind::Keyword, SemanticContextKind::None);
  if (needPound)
    Builder.addTextChunk("#selector");
  else
    Builder.addTextChunk("selector");
  Builder.addLeftParen();
  Builder.addSimpleTypedParameter("@objc method", /*IsVarArg=*/false);
  Builder.addRightParen();
  Builder.addTypeAnnotation("Selector");
  // This function is called only if the context type is 'Selector'.
  Builder.setResultTypes(Ctx.getSelectorType());
  Builder.setTypeContext(expectedTypeContext, CurrDeclContext);
}

void CompletionLookup::addPoundKeyPath(bool needPound) {
  // #keyPath is only available when the Objective-C runtime is.
  if (!Ctx.LangOpts.EnableObjCInterop)
    return;

  CodeCompletionResultBuilder Builder = makeResultBuilder(
      CodeCompletionResultKind::Keyword, SemanticContextKind::None);
  if (needPound)
    Builder.addTextChunk("#keyPath");
  else
    Builder.addTextChunk("keyPath");
  Builder.addLeftParen();
  Builder.addSimpleTypedParameter("@objc property sequence",
                                  /*IsVarArg=*/false);
  Builder.addRightParen();
  Builder.addTypeAnnotation("String");
  Builder.setResultTypes(Ctx.getStringType());
  Builder.setTypeContext(expectedTypeContext, CurrDeclContext);
}

SemanticContextKind
CompletionLookup::getSemanticContextKind(const ValueDecl *VD) {
  // FIXME: to get the corect semantic context we need to know how lookup
  // would have found the VD. For now, just infer a reasonable semantics.

  if (!VD)
    return SemanticContextKind::CurrentModule;

  DeclContext *calleeDC = VD->getDeclContext();

  if (calleeDC->isTypeContext())
    // FIXME: We should distinguish CurrentNominal and Super. We need to
    // propagate the base type to do that.
    return SemanticContextKind::CurrentNominal;

  if (calleeDC->isLocalContext())
    return SemanticContextKind::Local;
  if (calleeDC->getParentModule() == CurrModule)
    return SemanticContextKind::CurrentModule;

  return SemanticContextKind::OtherModule;
}

void CompletionLookup::addSubscriptCallPattern(
    const AnyFunctionType *AFT, const SubscriptDecl *SD,
    const std::optional<SemanticContextKind> SemanticContext) {
  foundFunction(AFT);
  GenericSignature genericSig;
  if (SD)
    genericSig = SD->getGenericSignatureOfContext();

  CodeCompletionResultBuilder Builder = makeResultBuilder(
      SD ? CodeCompletionResultKind::Declaration
         : CodeCompletionResultKind::Pattern,
      SemanticContext ? *SemanticContext : getSemanticContextKind(SD));
  if (SD)
    Builder.setAssociatedDecl(SD);
  if (!HaveLParen) {
    Builder.addLeftBracket();
  } else {
    // Add 'ArgumentLabels' only if it has '['. Without existing '[',
    // consider it suggesting 'subscript' itself, not call arguments for it.
    Builder.addFlair(CodeCompletionFlairBit::ArgumentLabels);
    Builder.addAnnotatedLeftBracket();
  }
  ArrayRef<const ParamDecl *> declParams;
  if (SD)
    declParams = SD->getIndices()->getArray();
  addCallArgumentPatterns(Builder, AFT->getParams(), declParams, genericSig);
  if (!HaveLParen)
    Builder.addRightBracket();
  else
    Builder.addAnnotatedRightBracket();
  if (SD && SD->isImplicitlyUnwrappedOptional())
    addTypeAnnotationForImplicitlyUnwrappedOptional(Builder, AFT->getResult(),
                                                    genericSig);
  else
    addTypeAnnotation(Builder, AFT->getResult(), genericSig);
}

void CompletionLookup::addFunctionCallPattern(
    const AnyFunctionType *AFT, const AbstractFunctionDecl *AFD,
    const std::optional<SemanticContextKind> SemanticContext) {
  GenericSignature genericSig;
  if (AFD)
    genericSig = AFD->getGenericSignatureOfContext();

  // Add the pattern, possibly including any default arguments.
  auto addPattern = [&](ArrayRef<const ParamDecl *> declParams = {},
                        bool includeDefaultArgs = true) {
    CodeCompletionResultBuilder Builder = makeResultBuilder(
        AFD ? CodeCompletionResultKind::Declaration
            : CodeCompletionResultKind::Pattern,
        SemanticContext ? *SemanticContext : getSemanticContextKind(AFD));
    Builder.addFlair(CodeCompletionFlairBit::ArgumentLabels);
    if (DotLoc) {
      Builder.setNumBytesToErase(Ctx.SourceMgr.getByteDistance(
          DotLoc, Ctx.SourceMgr.getIDEInspectionTargetLoc()));
    }
    if (AFD)
      Builder.setAssociatedDecl(AFD);

    if (!HaveLParen)
      Builder.addLeftParen();
    else
      Builder.addAnnotatedLeftParen();

    addCallArgumentPatterns(Builder, AFT->getParams(), declParams, genericSig,
                            includeDefaultArgs);

    // The rparen matches the lparen here so that we insert both or neither.
    if (!HaveLParen)
      Builder.addRightParen();
    else
      Builder.addAnnotatedRightParen();

    addEffectsSpecifiers(Builder, AFT, AFD);

    if (AFD && AFD->isImplicitlyUnwrappedOptional())
      addTypeAnnotationForImplicitlyUnwrappedOptional(Builder, AFT->getResult(),
                                                      genericSig);
    else
      addTypeAnnotation(Builder, AFT->getResult(), genericSig);

    Builder.setCanCurrDeclContextHandleAsync(CanCurrDeclContextHandleAsync);
  };

  if (!AFD || !AFD->getInterfaceType()->is<AnyFunctionType>()) {
    // Probably, calling closure type expression.
    foundFunction(AFT);
    addPattern();
    return;
  } else {
    // Calling function or method.
    foundFunction(AFD);

    // FIXME: Hack because we don't know we are calling instance
    // method or not. There's invariant that funcTy is derived from AFD.
    // Only if we are calling instance method on meta type, AFT is still
    // curried. So we should be able to detect that by comparing curried level
    // of AFT and the interface type of AFD.
    auto getCurriedLevel = [](const AnyFunctionType *funcTy) -> unsigned {
      unsigned level = 0;
      while ((funcTy = funcTy->getResult()->getAs<AnyFunctionType>()))
        ++level;
      return level;
    };
    bool isImplicitlyCurriedInstanceMethod =
        (AFD->hasImplicitSelfDecl() &&
         getCurriedLevel(AFT) ==
             getCurriedLevel(
                 AFD->getInterfaceType()->castTo<AnyFunctionType>()) &&
         // NOTE: shouldn't be necessary, but just in case curried level check
         // is insufficient.
         AFT->getParams().size() == 1 &&
         AFT->getParams()[0].getLabel().empty());

    if (isImplicitlyCurriedInstanceMethod) {
      addPattern({AFD->getImplicitSelfDecl()}, /*includeDefaultArgs=*/true);
    } else {
      if (shouldAddItemWithoutDefaultArgs(AFD))
        addPattern(AFD->getParameters()->getArray(),
                   /*includeDefaultArgs=*/false);
      addPattern(AFD->getParameters()->getArray(),
                 /*includeDefaultArgs=*/true);
    }
  }
}

bool CompletionLookup::isImplicitlyCurriedInstanceMethod(
    const AbstractFunctionDecl *FD) {
  if (FD->isStatic())
    return false;

  switch (Kind) {
  case LookupKind::ValueExpr:
  case LookupKind::StoredProperty:
    return ExprType->is<AnyMetatypeType>();
  case LookupKind::ValueInDeclContext:
    if (InsideStaticMethod)
      return FD->getDeclContext() == CurrentMethod->getDeclContext();
    if (auto Init = dyn_cast<Initializer>(CurrDeclContext)) {
      if (auto PatInit = dyn_cast<PatternBindingInitializer>(Init)) {
        if (PatInit->getInitializedLazyVar())
          return false;
      }
      return FD->getDeclContext() == Init->getInnermostTypeContext();
    }
    return false;
  case LookupKind::EnumElement:
  case LookupKind::Type:
  case LookupKind::TypeInDeclContext:
  case LookupKind::GenericRequirement:
    llvm_unreachable("cannot have a method call while doing a "
                     "type completion");
  case LookupKind::ImportFromModule:
    return false;
  }

  llvm_unreachable("Unhandled LookupKind in switch.");
}

void CompletionLookup::addMethodCall(const FuncDecl *FD,
                                     DeclVisibilityKind Reason,
                                     DynamicLookupInfo dynamicLookupInfo) {
  if (FD->getBaseIdentifier().empty())
    return;
  foundFunction(FD);

  const Identifier Name = FD->getBaseIdentifier();
  assert(!Name.empty() && "name should not be empty");

  Type FunctionType = getTypeOfMember(FD, dynamicLookupInfo);
  assert(FunctionType);

  auto AFT = FunctionType->getAs<AnyFunctionType>();

  bool IsImplicitlyCurriedInstanceMethod = false;
  if (FD->hasImplicitSelfDecl()) {
    IsImplicitlyCurriedInstanceMethod = isImplicitlyCurriedInstanceMethod(FD);

    // Strip off '(_ self: Self)' if needed.
    if (AFT && !IsImplicitlyCurriedInstanceMethod) {
      AFT = AFT->getResult()->getAs<AnyFunctionType>();

      // Check for duplicates with the adjusted type too.
      if (isDuplicate(FD, AFT))
        return;
    }
  }

  bool trivialTrailingClosure = false;
  if (AFT && !IsImplicitlyCurriedInstanceMethod)
    trivialTrailingClosure = hasTrivialTrailingClosure(FD, AFT);

  std::optional<ContextualNotRecommendedReason> NotRecommended;
  bool implictlyAsync = false;
  analyzeActorIsolation(FD, AFT, implictlyAsync, NotRecommended);

  // Add the method, possibly including any default arguments.
  auto addMethodImpl = [&](bool includeDefaultArgs = true,
                           bool trivialTrailingClosure = false) {
    CodeCompletionResultBuilder Builder =
        makeResultBuilder(CodeCompletionResultKind::Declaration,
                          getSemanticContext(FD, Reason, dynamicLookupInfo));
    Builder.setHasAsyncAlternative(
        FD->getAsyncAlternative() &&
        !FD->getAsyncAlternative()->shouldHideFromEditor());
    Builder.setCanCurrDeclContextHandleAsync(CanCurrDeclContextHandleAsync);
    Builder.setAssociatedDecl(FD);

    if (IsSuperRefExpr && CurrentMethod &&
        CurrentMethod->getOverriddenDecl() == FD)
      Builder.addFlair(CodeCompletionFlairBit::SuperChain);

    if (NotRecommended)
      Builder.setContextualNotRecommended(*NotRecommended);

    addLeadingDot(Builder);
    addValueBaseName(Builder, Name);
    if (IsDynamicLookup)
      Builder.addDynamicLookupMethodCallTail();
    else if (FD->getAttrs().hasAttribute<OptionalAttr>())
      Builder.addOptionalMethodCallTail();

    if (!AFT) {
      addTypeAnnotation(Builder, FunctionType,
                        FD->getGenericSignatureOfContext());
      return;
    }
    if (IsImplicitlyCurriedInstanceMethod) {
      Builder.addLeftParen();
      addCallArgumentPatterns(
          Builder, AFT->getParams(), {FD->getImplicitSelfDecl()},
          FD->getGenericSignatureOfContext(), includeDefaultArgs);
      Builder.addRightParen();
    } else if (trivialTrailingClosure) {
      Builder.addBraceStmtWithCursor(" { code }");
      addEffectsSpecifiers(Builder, AFT, FD, implictlyAsync);
    } else {
      Builder.addLeftParen();
      addCallArgumentPatterns(Builder, AFT, FD->getParameters(),
                              FD->getGenericSignatureOfContext(),
                              includeDefaultArgs);
      Builder.addRightParen();
      addEffectsSpecifiers(Builder, AFT, FD, implictlyAsync);
    }

    // Build type annotation.
    Type ResultType = AFT->getResult();
    // As we did with parameters in addParamPatternFromFunction,
    // for regular methods we'll print '!' after implicitly
    // unwrapped optional results.
    bool IsIUO = !IsImplicitlyCurriedInstanceMethod &&
                 FD->isImplicitlyUnwrappedOptional();

    PrintOptions PO;
    PO.OpaqueReturnTypePrinting =
        PrintOptions::OpaqueReturnTypePrintingMode::WithoutOpaqueKeyword;
    PO.PrintOptionalAsImplicitlyUnwrapped = IsIUO;
    if (auto typeContext = CurrDeclContext->getInnermostTypeContext())
      PO.setBaseType(typeContext->getDeclaredTypeInContext());
    Type AnnotationTy =
        eraseArchetypes(ResultType, FD->getGenericSignatureOfContext());
    if (Builder.shouldAnnotateResults()) {
      Builder.withNestedGroup(
          CodeCompletionString::Chunk::ChunkKind::TypeAnnotationBegin, [&] {
            CodeCompletionStringPrinter printer(Builder);
            auto TL = TypeLoc::withoutLoc(AnnotationTy);
            printer.printTypePre(TL);
            if (IsImplicitlyCurriedInstanceMethod) {
              auto *FnType = AnnotationTy->castTo<AnyFunctionType>();
              AnyFunctionType::printParams(FnType->getParams(), printer,
                                           PrintOptions());
              AnnotationTy = FnType->getResult();
              printer.printText(" -> ");
            }

            // What's left is the result type.
            if (AnnotationTy->isVoid())
              AnnotationTy = Ctx.getVoidDecl()->getDeclaredInterfaceType();
            AnnotationTy.print(printer, PO);
            printer.printTypePost(TL);
          });
    } else {
      llvm::SmallString<32> TypeStr;
      llvm::raw_svector_ostream OS(TypeStr);
      if (IsImplicitlyCurriedInstanceMethod) {
        auto *FnType = AnnotationTy->castTo<AnyFunctionType>();
        AnyFunctionType::printParams(FnType->getParams(), OS);
        AnnotationTy = FnType->getResult();
        OS << " -> ";
      }

      // What's left is the result type.
      if (AnnotationTy->isVoid())
        AnnotationTy = Ctx.getVoidDecl()->getDeclaredInterfaceType();
      AnnotationTy.print(OS, PO);
      Builder.addTypeAnnotation(TypeStr);
    }

    Builder.setResultTypes(ResultType);
    Builder.setTypeContext(expectedTypeContext, CurrDeclContext);

    if (isUnresolvedMemberIdealType(ResultType))
      Builder.addFlair(CodeCompletionFlairBit::ExpressionSpecific);
  };

  // Do not add imported C++ methods that are treated as unsafe in Swift.
  if (Importer->isUnsafeCXXMethod(FD))
    return;

  if (!AFT || IsImplicitlyCurriedInstanceMethod) {
    addMethodImpl();
  } else {
    if (trivialTrailingClosure)
      addMethodImpl(/*includeDefaultArgs=*/false,
                    /*trivialTrailingClosure=*/true);
    if (shouldAddItemWithoutDefaultArgs(FD))
      addMethodImpl(/*includeDefaultArgs=*/false);
    addMethodImpl(/*includeDefaultArgs=*/true);
  }
}

void CompletionLookup::addConstructorCall(const ConstructorDecl *CD,
                                          DeclVisibilityKind Reason,
                                          DynamicLookupInfo dynamicLookupInfo,
                                          std::optional<Type> BaseType,
                                          std::optional<Type> Result,
                                          bool IsOnType, Identifier addName) {
  foundFunction(CD);
  Type MemberType = getTypeOfMember(CD, BaseType.value_or(ExprType));
  AnyFunctionType *ConstructorType = nullptr;
  if (auto MemberFuncType = MemberType->getAs<AnyFunctionType>())
    ConstructorType = MemberFuncType->getResult()->castTo<AnyFunctionType>();

  bool needInit = false;
  if (!IsOnType) {
    assert(addName.empty());
    needInit = true;
  } else if (addName.empty() && HaveDot) {
    needInit = true;
  }

  // If we won't be able to provide a result, bail out.
  if (!ConstructorType && addName.empty() && !needInit)
    return;

  // Add the constructor, possibly including any default arguments.
  auto addConstructorImpl = [&](bool includeDefaultArgs = true) {
    CodeCompletionResultBuilder Builder =
        makeResultBuilder(CodeCompletionResultKind::Declaration,
                          getSemanticContext(CD, Reason, dynamicLookupInfo));
    Builder.setAssociatedDecl(CD);

    if (IsSuperRefExpr && CurrentMethod &&
        CurrentMethod->getOverriddenDecl() == CD)
      Builder.addFlair(CodeCompletionFlairBit::SuperChain);

    if (needInit) {
      assert(addName.empty());
      addLeadingDot(Builder);
      Builder.addBaseName("init");
    } else if (!addName.empty()) {
      Builder.addBaseName(addName.str());
    } else {
      Builder.addFlair(CodeCompletionFlairBit::ArgumentLabels);
    }

    if (!ConstructorType) {
      addTypeAnnotation(Builder, MemberType,
                        CD->getGenericSignatureOfContext());
      return;
    }

    if (!HaveLParen)
      Builder.addLeftParen();
    else
      Builder.addAnnotatedLeftParen();

    addCallArgumentPatterns(Builder, ConstructorType, CD->getParameters(),
                            CD->getGenericSignatureOfContext(),
                            includeDefaultArgs);

    // The rparen matches the lparen here so that we insert both or neither.
    if (!HaveLParen)
      Builder.addRightParen();
    else
      Builder.addAnnotatedRightParen();

    addEffectsSpecifiers(Builder, ConstructorType, CD);

    if (!Result.has_value())
      Result = ConstructorType->getResult();
    if (CD->isImplicitlyUnwrappedOptional()) {
      addTypeAnnotationForImplicitlyUnwrappedOptional(
          Builder, *Result, CD->getGenericSignatureOfContext());
    } else {
      addTypeAnnotation(Builder, *Result, CD->getGenericSignatureOfContext());
    }

    Builder.setCanCurrDeclContextHandleAsync(CanCurrDeclContextHandleAsync);
  };

  if (ConstructorType && shouldAddItemWithoutDefaultArgs(CD))
    addConstructorImpl(/*includeDefaultArgs=*/false);
  addConstructorImpl();
}

void CompletionLookup::addConstructorCallsForType(
    Type type, Identifier name, DeclVisibilityKind Reason,
    DynamicLookupInfo dynamicLookupInfo) {
  if (!Sink.addInitsToTopLevel)
    return;

  // Existential types cannot be instantiated. e.g. 'MyProtocol()'.
  if (type->isExistentialType())
    return;

  // 'AnyObject' is not initializable.
  // FIXME: Should we do this in 'AnyObjectLookupRequest'?
  if (type->isAnyObject())
    return;

  assert(CurrDeclContext);

  auto results =
      swift::lookupSemanticMember(const_cast<DeclContext *>(CurrDeclContext),
                                  type, DeclBaseName::createConstructor());
  for (const auto &entry : results.allResults()) {
    auto *init = cast<ConstructorDecl>(entry.getValueDecl());
    if (init->shouldHideFromEditor())
      continue;
    addConstructorCall(cast<ConstructorDecl>(init), Reason, dynamicLookupInfo,
                       type, std::nullopt,
                       /*IsOnType=*/true, name);
  }
}

void CompletionLookup::addSubscriptCall(const SubscriptDecl *SD,
                                        DeclVisibilityKind Reason,
                                        DynamicLookupInfo dynamicLookupInfo) {
  // Don't add subscript call to unqualified completion.
  if (!ExprType)
    return;

  // Subscript after '.' is valid only after type part of Swift keypath
  // expression. (e.g. '\TyName.SubTy.[0])
  if (HaveDot && !IsAfterSwiftKeyPathRoot)
    return;

  auto subscriptType =
      getTypeOfMember(SD, dynamicLookupInfo)->getAs<AnyFunctionType>();
  if (!subscriptType)
    return;

  std::optional<ContextualNotRecommendedReason> NotRecommended;
  bool implictlyAsync = false;
  analyzeActorIsolation(SD, subscriptType, implictlyAsync, NotRecommended);

  CodeCompletionResultBuilder Builder =
      makeResultBuilder(CodeCompletionResultKind::Declaration,
                        getSemanticContext(SD, Reason, dynamicLookupInfo));
  Builder.setCanCurrDeclContextHandleAsync(CanCurrDeclContextHandleAsync);
  Builder.setAssociatedDecl(SD);

  if (NotRecommended)
    Builder.setContextualNotRecommended(*NotRecommended);

  // '\TyName#^TOKEN^#' requires leading dot.
  if (!HaveDot && IsAfterSwiftKeyPathRoot)
    Builder.addLeadingDot();

  if (NeedOptionalUnwrap) {
    Builder.setNumBytesToErase(NumBytesToEraseForOptionalUnwrap);
    Builder.addQuestionMark();
  }

  Builder.addLeftBracket();
  addCallArgumentPatterns(Builder, subscriptType, SD->getIndices(),
                          SD->getGenericSignatureOfContext(), true);
  Builder.addRightBracket();

  // Add a type annotation.
  Type resultTy = subscriptType->getResult();
  if (IsDynamicLookup) {
    // Values of properties that were found on a AnyObject have
    // std::optional<T> type.
    resultTy = OptionalType::get(resultTy);
  }

  if (implictlyAsync)
    Builder.addAnnotatedAsync();

  addTypeAnnotation(Builder, resultTy, SD->getGenericSignatureOfContext());
}

static StringRef getTypeAnnotationString(const NominalTypeDecl *NTD,
                                         SmallVectorImpl<char> &stash) {
  SmallVector<StringRef, 1> attrRoleStrs;
  if (NTD->getAttrs().hasAttribute<PropertyWrapperAttr>())
    attrRoleStrs.push_back("Property Wrapper");
  if (NTD->getAttrs().hasAttribute<ResultBuilderAttr>())
    attrRoleStrs.push_back("Result Builder");
  if (NTD->isGlobalActor())
    attrRoleStrs.push_back("Global Actor");

  if (attrRoleStrs.empty())
    return StringRef();
  if (attrRoleStrs.size() == 1)
    return attrRoleStrs[0];

  assert(stash.empty());
  llvm::raw_svector_ostream OS(stash);
  llvm::interleave(attrRoleStrs, OS, ", ");
  return {stash.data(), stash.size()};
}

void CompletionLookup::addNominalTypeRef(const NominalTypeDecl *NTD,
                                         DeclVisibilityKind Reason,
                                         DynamicLookupInfo dynamicLookupInfo) {
  CodeCompletionResultBuilder Builder =
      makeResultBuilder(CodeCompletionResultKind::Declaration,
                        getSemanticContext(NTD, Reason, dynamicLookupInfo));
  Builder.setAssociatedDecl(NTD);
  addLeadingDot(Builder);
  Builder.addBaseName(NTD->getName().str());

  // "Fake" annotation for custom attribute types.
  SmallVector<char, 0> stash;
  StringRef customAttributeAnnotation = getTypeAnnotationString(NTD, stash);
  if (!customAttributeAnnotation.empty()) {
    Builder.addTypeAnnotation(customAttributeAnnotation);
  } else {
    addTypeAnnotation(Builder, NTD->getDeclaredType());
  }

  // Override the type relation for NominalTypes. Use the better relation
  // for the metatypes and the instance type. For example,
  //
  //   func receiveInstance(_: Int) {}
  //   func receiveMetatype(_: Int.Type) {}
  //
  // We want to suggest 'Int' as 'Identical' for both arguments.
  Builder.setResultTypes(
      {NTD->getInterfaceType(), NTD->getDeclaredInterfaceType()});
  Builder.setTypeContext(expectedTypeContext, CurrDeclContext);
}

void CompletionLookup::addTypeAliasRef(const TypeAliasDecl *TAD,
                                       DeclVisibilityKind Reason,
                                       DynamicLookupInfo dynamicLookupInfo) {
  CodeCompletionResultBuilder Builder =
      makeResultBuilder(CodeCompletionResultKind::Declaration,
                        getSemanticContext(TAD, Reason, dynamicLookupInfo));
  Builder.setAssociatedDecl(TAD);
  addLeadingDot(Builder);
  Builder.addBaseName(TAD->getName().str());
  if (auto underlyingType = TAD->getUnderlyingType()) {
    if (underlyingType->hasError()) {
      addTypeAnnotation(Builder,
                        TAD->isGeneric()
                        ? TAD->getUnboundGenericType()
                        : TAD->getDeclaredInterfaceType());

    } else {
      addTypeAnnotation(Builder, underlyingType);
    }
  }
}

void CompletionLookup::addGenericTypeParamRef(
    const GenericTypeParamDecl *GP, DeclVisibilityKind Reason,
    DynamicLookupInfo dynamicLookupInfo) {
  assert(!GP->getName().empty());
  CodeCompletionResultBuilder Builder =
      makeResultBuilder(CodeCompletionResultKind::Declaration,
                        getSemanticContext(GP, Reason, dynamicLookupInfo));
  Builder.setAssociatedDecl(GP);
  addLeadingDot(Builder);
  Builder.addBaseName(GP->getName().str());
  addTypeAnnotation(Builder, GP->getDeclaredInterfaceType());
}

void CompletionLookup::addAssociatedTypeRef(
    const AssociatedTypeDecl *AT, DeclVisibilityKind Reason,
    DynamicLookupInfo dynamicLookupInfo) {
  CodeCompletionResultBuilder Builder =
      makeResultBuilder(CodeCompletionResultKind::Declaration,
                        getSemanticContext(AT, Reason, dynamicLookupInfo));
  Builder.setAssociatedDecl(AT);
  addLeadingDot(Builder);
  Builder.addBaseName(AT->getName().str());
  if (Type T = getAssociatedTypeType(AT))
    addTypeAnnotation(Builder, T);
}

void CompletionLookup::addPrecedenceGroupRef(PrecedenceGroupDecl *PGD) {
  auto semanticContext =
      getSemanticContext(PGD, DeclVisibilityKind::VisibleAtTopLevel, {});
  CodeCompletionResultBuilder builder =
      makeResultBuilder(CodeCompletionResultKind::Declaration, semanticContext);

  builder.addBaseName(PGD->getName().str());
  builder.setAssociatedDecl(PGD);
}

void CompletionLookup::addBuiltinMemberRef(StringRef Name,
                                           Type TypeAnnotation) {
  CodeCompletionResultBuilder Builder = makeResultBuilder(
      CodeCompletionResultKind::Pattern, SemanticContextKind::CurrentNominal);
  addLeadingDot(Builder);
  Builder.addBaseName(Name);
  addTypeAnnotation(Builder, TypeAnnotation);
}

void CompletionLookup::addEnumElementRef(const EnumElementDecl *EED,
                                         DeclVisibilityKind Reason,
                                         DynamicLookupInfo dynamicLookupInfo,
                                         bool HasTypeContext) {
  if (!EED->hasName() || !EED->isAccessibleFrom(CurrDeclContext) ||
      EED->shouldHideFromEditor())
    return;

  CodeCompletionResultBuilder Builder =
      makeResultBuilder(CodeCompletionResultKind::Declaration,
                        getSemanticContext(EED, Reason, dynamicLookupInfo));
  Builder.setAssociatedDecl(EED);

  addLeadingDot(Builder);
  addValueBaseName(Builder, EED->getBaseIdentifier());

  // Enum element is of function type; (Self.type) -> Self or
  // (Self.Type) -> (Args...) -> Self.
  Type EnumType = getTypeOfMember(EED, dynamicLookupInfo);
  if (EnumType->is<AnyFunctionType>())
    EnumType = EnumType->castTo<AnyFunctionType>()->getResult();

  if (EnumType->is<FunctionType>()) {
    Builder.addLeftParen();
    addCallArgumentPatterns(Builder, EnumType->castTo<FunctionType>(),
                            EED->getParameterList(),
                            EED->getGenericSignatureOfContext());
    Builder.addRightParen();

    // Extract result as the enum type.
    EnumType = EnumType->castTo<FunctionType>()->getResult();
  }

  addTypeAnnotation(Builder, EnumType, EED->getGenericSignatureOfContext());

  if (isUnresolvedMemberIdealType(EnumType))
    Builder.addFlair(CodeCompletionFlairBit::ExpressionSpecific);
}

static StringRef getTypeAnnotationString(const MacroDecl *MD,
                                         SmallVectorImpl<char> &stash) {
  auto roles = MD->getMacroRoles();
  SmallVector<StringRef, 1> roleStrs;
  for (auto role : getAllMacroRoles()) {
    if (!roles.contains(role))
      continue;

    switch (role) {
    case MacroRole::Accessor:
      roleStrs.push_back("Accessor Macro");
      break;
    case MacroRole::CodeItem:
      roleStrs.push_back("Code Item Macro");
      break;
    case MacroRole::Conformance:
      roleStrs.push_back("Conformance Macro");
      break;
    case MacroRole::Declaration:
      roleStrs.push_back("Declaration Macro");
      break;
    case MacroRole::Expression:
      roleStrs.push_back("Expression Macro");
      break;
    case MacroRole::Extension:
      roleStrs.push_back("Extension Macro");
      break;
    case MacroRole::Member:
      roleStrs.push_back("Member Macro");
      break;
    case MacroRole::MemberAttribute:
      roleStrs.push_back("Member Attribute Macro");
      break;
    case MacroRole::Peer:
      roleStrs.push_back("Peer Macro");
      break;
    case MacroRole::Preamble:
      roleStrs.push_back("Preamble Macro");
      break;
    case MacroRole::Body:
      roleStrs.push_back("Body Macro");
      break;
    }
  }

  if (roleStrs.empty())
    return "Macro";
  if (roleStrs.size() == 1)
    return roleStrs[0];

  assert(stash.empty());
  llvm::raw_svector_ostream OS(stash);
  llvm::interleave(roleStrs, OS, ", ");
  return {stash.data(), stash.size()};
}

void CompletionLookup::addMacroExpansion(const MacroDecl *MD,
                                         DeclVisibilityKind Reason) {
  if (!MD->hasName() || !MD->isAccessibleFrom(CurrDeclContext) ||
      MD->shouldHideFromEditor())
    return;

  OptionSet<CustomAttributeKind> expectedKinds =
      expectedTypeContext.getExpectedCustomAttributeKinds();
  if (expectedKinds) {
    CodeCompletionMacroRoles expectedRoles =
        getCompletionMacroRoles(expectedKinds);
    CodeCompletionMacroRoles roles = getCompletionMacroRoles(MD);
    if (!(roles & expectedRoles))
      return;
  }

  CodeCompletionResultBuilder Builder =
      makeResultBuilder(CodeCompletionResultKind::Declaration,
                        getSemanticContext(MD, Reason, DynamicLookupInfo()));
  Builder.setAssociatedDecl(MD);

  addValueBaseName(Builder, MD->getBaseIdentifier());

  Type macroType = MD->getInterfaceType();
  if (MD->parameterList && MD->parameterList->size() > 0) {
    Builder.addLeftParen();
    addCallArgumentPatterns(Builder, macroType->castTo<AnyFunctionType>(),
                            MD->parameterList,
                            MD->getGenericSignature());
    Builder.addRightParen();
  }

  auto roles = MD->getMacroRoles();
  if (roles.containsOnly(MacroRole::Expression)) {
    addTypeAnnotation(Builder, MD->getResultInterfaceType(),
                      MD->getGenericSignature());
  } else {
    llvm::SmallVector<char, 0> stash;
    Builder.addTypeAnnotation(getTypeAnnotationString(MD, stash));
  }
}

void CompletionLookup::addKeyword(StringRef Name, Type TypeAnnotation,
                                  SemanticContextKind SK,
                                  CodeCompletionKeywordKind KeyKind,
                                  unsigned NumBytesToErase) {
  CodeCompletionResultBuilder Builder =
      makeResultBuilder(CodeCompletionResultKind::Keyword, SK);
  addLeadingDot(Builder);
  Builder.addKeyword(Name);
  Builder.setKeywordKind(KeyKind);
  if (TypeAnnotation)
    addTypeAnnotation(Builder, TypeAnnotation);
  if (NumBytesToErase > 0)
    Builder.setNumBytesToErase(NumBytesToErase);
}

void CompletionLookup::addKeyword(StringRef Name, StringRef TypeAnnotation,
                                  CodeCompletionKeywordKind KeyKind,
                                  CodeCompletionFlair flair) {
  CodeCompletionResultBuilder Builder = makeResultBuilder(
      CodeCompletionResultKind::Keyword, SemanticContextKind::None);
  Builder.addFlair(flair);
  addLeadingDot(Builder);
  Builder.addKeyword(Name);
  Builder.setKeywordKind(KeyKind);
  if (!TypeAnnotation.empty())
    Builder.addTypeAnnotation(TypeAnnotation);
}

void CompletionLookup::addDeclAttrParamKeyword(StringRef Name,
                                               ArrayRef<StringRef> Parameters,
                                               StringRef Annotation,
                                               bool NeedSpecify) {
  CodeCompletionResultBuilder Builder = makeResultBuilder(
      CodeCompletionResultKind::Keyword, SemanticContextKind::None);
  Builder.addDeclAttrParamKeyword(Name, Parameters, Annotation, NeedSpecify);
}

void CompletionLookup::addDeclAttrKeyword(StringRef Name,
                                          StringRef Annotation) {
  CodeCompletionResultBuilder Builder = makeResultBuilder(
      CodeCompletionResultKind::Keyword, SemanticContextKind::None);
  Builder.addDeclAttrKeyword(Name, Annotation);
}

/// Add the compound function name for the given function.
/// Returns \c true if the compound function name is actually used.
bool CompletionLookup::addCompoundFunctionNameIfDesiable(
    AbstractFunctionDecl *AFD, DeclVisibilityKind Reason,
    DynamicLookupInfo dynamicLookupInfo) {
  auto funcTy =
      getTypeOfMember(AFD, dynamicLookupInfo)->getAs<AnyFunctionType>();
  bool dropCurryLevel = funcTy && AFD->getDeclContext()->isTypeContext() &&
                        !isImplicitlyCurriedInstanceMethod(AFD);
  if (dropCurryLevel)
    funcTy = funcTy->getResult()->getAs<AnyFunctionType>();

  bool useFunctionReference = PreferFunctionReferencesToCalls;
  if (!useFunctionReference && funcTy) {
    // We know that the CodeCompletionResultType is AST-based so we can pass
    // nullptr for USRTypeContext.
    auto maxFuncTyRel = CodeCompletionResultType(funcTy).calculateTypeRelation(
        &expectedTypeContext, CurrDeclContext, /*USRTypeContext=*/nullptr);
    auto maxResultTyRel = CodeCompletionResultType(funcTy->getResult()).calculateTypeRelation(
        &expectedTypeContext, CurrDeclContext, /*USRTypeContext=*/nullptr);
    useFunctionReference = maxFuncTyRel > maxResultTyRel;
  }
  if (!useFunctionReference)
    return false;

  // Check for duplicates with the adjusted type too.
  if (dropCurryLevel && isDuplicate(AFD, funcTy))
    return true;

  CodeCompletionResultBuilder Builder =
      makeResultBuilder(CodeCompletionResultKind::Declaration,
                        getSemanticContext(AFD, Reason, dynamicLookupInfo));
  Builder.setAssociatedDecl(AFD);

  // Base name
  addLeadingDot(Builder);
  addValueBaseName(Builder, AFD->getBaseName());

  // Add the argument labels.
  const auto ArgLabels = AFD->getName().getArgumentNames();
  if (!ArgLabels.empty()) {
    if (!HaveLParen)
      Builder.addLeftParen();
    else
      Builder.addAnnotatedLeftParen();

    for (auto ArgLabel : ArgLabels) {
      if (ArgLabel.empty())
        Builder.addTextChunk("_");
      else
        Builder.addTextChunk(ArgLabel.str());
      Builder.addTextChunk(":");
    }

    Builder.addRightParen();
  }

  if (funcTy)
    addTypeAnnotation(Builder, funcTy, AFD->getGenericSignatureOfContext());

  return true;
}

void CompletionLookup::onLookupNominalTypeMembers(NominalTypeDecl *NTD,
                                                  DeclVisibilityKind Reason) {

  // Remember the decl name to
  SmallString<32> buffer;
  llvm::raw_svector_ostream OS(buffer);
  PrintOptions PS = PrintOptions::printDocInterface();
  PS.FullyQualifiedTypes = true;
  NTD->getDeclaredType()->print(OS, PS);
  NullTerminatedStringRef qualifiedName(
      buffer, *CompletionContext->getResultSink().Allocator);
  CompletionContext->LookedupNominalTypeNames.push_back(qualifiedName);
}

Type CompletionLookup::normalizeTypeForDuplicationCheck(Type Ty) {
  return Ty.transformRec([](Type T) -> std::optional<Type> {
    if (auto opaque = T->getAs<OpaqueTypeArchetypeType>()) {
      /// Opaque type has a _invisible_ substitution map. Since IDE can't
      /// differentiate them, replace it with empty substitution map.
      return Type(OpaqueTypeArchetypeType::get(opaque->getDecl(),
                                               opaque->getInterfaceType(),
                                               /*Substitutions=*/{}));
    }
    return std::nullopt;
  });
}

void CompletionLookup::foundDecl(ValueDecl *D, DeclVisibilityKind Reason,
                                 DynamicLookupInfo dynamicLookupInfo) {
  assert(Reason !=
             DeclVisibilityKind::MemberOfProtocolDerivedByCurrentNominal &&
         "Including derived requirement in non-override lookup");

  if (D->shouldHideFromEditor())
    return;

  if (IsKeyPathExpr && !KeyPathFilter(D, Reason, dynamicLookupInfo))
    return;

  if (IsSwiftKeyPathExpr && !SwiftKeyPathFilter(D, Reason))
    return;

  // If we've seen this decl+type before (possible when multiple lookups are
  // performed e.g. because of ambiguous base types), bail.
  if (isDuplicate(D, dynamicLookupInfo))
    return;

  // FIXME(InterfaceTypeRequest): Remove this.
  (void)D->getInterfaceType();
  switch (Kind) {
  case LookupKind::ValueExpr:
    if (auto *CD = dyn_cast<ConstructorDecl>(D)) {
      // Do we want compound function names here?
      if (addCompoundFunctionNameIfDesiable(CD, Reason, dynamicLookupInfo))
        return;

      if (auto MT = ExprType->getAs<AnyMetatypeType>()) {
        Type Ty = MT->getInstanceType();
        assert(Ty && "Cannot find instance type.");

        // If instance type is type alias, show users that the constructed
        // type is the typealias instead of the underlying type of the alias.
        std::optional<Type> Result = std::nullopt;
        if (!CD->getInterfaceType()->is<ErrorType>() &&
            isa<TypeAliasType>(Ty.getPointer()) &&
            Ty->getDesugaredType() ==
                CD->getResultInterfaceType().getPointer()) {
          Result = Ty;
        }
        // If the expression type is not a static metatype or an archetype, the
        // base is not a type. Direct call syntax is illegal on values, so we
        // only add initializer completions if we do not have a left parenthesis
        // and either the initializer is required, the base type's instance type
        // is not a class, or this is a 'self' or 'super' reference.
        if (IsStaticMetatype || IsUnresolvedMember || Ty->is<ArchetypeType>())
          addConstructorCall(CD, Reason, dynamicLookupInfo, std::nullopt,
                             Result,
                             /*isOnType*/ true);
        else if ((IsSelfRefExpr || IsSuperRefExpr || !Ty->is<ClassType>() ||
                  CD->isRequired()) &&
                 !HaveLParen)
          addConstructorCall(CD, Reason, dynamicLookupInfo, std::nullopt,
                             Result,
                             /*isOnType*/ false);
        return;
      }
      if (!HaveLParen) {
        auto CDC = dyn_cast<ConstructorDecl>(CurrDeclContext);
        if (!CDC)
          return;

        // For classes, we do not want 'init' completions for 'self' in
        // non-convenience initializers and for 'super' in convenience
        // initializers.
        if (ExprType->is<ClassType>()) {
          if ((IsSelfRefExpr && !CDC->isConvenienceInit()) ||
              (IsSuperRefExpr && CDC->isConvenienceInit()))
            return;
        }
        if (IsSelfRefExpr || IsSuperRefExpr)
          addConstructorCall(CD, Reason, dynamicLookupInfo, std::nullopt,
                             std::nullopt,
                             /*IsOnType=*/false);
      }
      return;
    }

    if (HaveLParen)
      return;

    LLVM_FALLTHROUGH;

  case LookupKind::ValueInDeclContext:
  case LookupKind::ImportFromModule:
    if (auto *VD = dyn_cast<VarDecl>(D)) {
      addVarDeclRef(VD, Reason, dynamicLookupInfo);
      return;
    }

    if (auto *FD = dyn_cast<FuncDecl>(D)) {
      // We cannot call operators with a postfix parenthesis syntax.
      if (FD->isBinaryOperator() || FD->isUnaryOperator())
        return;

      // We cannot call accessors.  We use VarDecls and SubscriptDecls to
      // produce completions that refer to getters and setters.
      if (isa<AccessorDecl>(FD))
        return;

      // Do we want compound function names here?
      if (addCompoundFunctionNameIfDesiable(FD, Reason, dynamicLookupInfo))
        return;

      addMethodCall(FD, Reason, dynamicLookupInfo);

      // SE-0253: Callable values of user-defined nominal types.
      if (FD->isCallAsFunctionMethod() && !HaveDot &&
          (!ExprType || !ExprType->is<AnyMetatypeType>())) {
        Type funcType = getTypeOfMember(FD, dynamicLookupInfo)
                            ->castTo<AnyFunctionType>()
                            ->getResult();

        // Check for duplicates with the adjusted type too.
        if (isDuplicate(FD, funcType))
          return;

        addFunctionCallPattern(
            funcType->castTo<AnyFunctionType>(), FD,
            getSemanticContext(FD, Reason, dynamicLookupInfo));
      }
      return;
    }

    if (auto *NTD = dyn_cast<NominalTypeDecl>(D)) {
      addNominalTypeRef(NTD, Reason, dynamicLookupInfo);
      addConstructorCallsForType(NTD->getDeclaredInterfaceType(),
                                 NTD->getName(), Reason, dynamicLookupInfo);
      return;
    }

    if (auto *TAD = dyn_cast<TypeAliasDecl>(D)) {
      addTypeAliasRef(TAD, Reason, dynamicLookupInfo);
      auto type = TAD->mapTypeIntoContext(TAD->getDeclaredInterfaceType());
      if (type->mayHaveMembers())
        addConstructorCallsForType(type, TAD->getName(), Reason,
                                   dynamicLookupInfo);
      return;
    }

    if (auto *GP = dyn_cast<GenericTypeParamDecl>(D)) {
      addGenericTypeParamRef(GP, Reason, dynamicLookupInfo);
      auto type =
          CurrDeclContext->mapTypeIntoContext(GP->getDeclaredInterfaceType());
      addConstructorCallsForType(type, GP->getName(), Reason,
                                 dynamicLookupInfo);
      return;
    }

    if (auto *AT = dyn_cast<AssociatedTypeDecl>(D)) {
      addAssociatedTypeRef(AT, Reason, dynamicLookupInfo);
      return;
    }

    if (auto *EED = dyn_cast<EnumElementDecl>(D)) {
      addEnumElementRef(EED, Reason, dynamicLookupInfo,
                        /*HasTypeContext=*/false);
      return;
    }

    // Swift key path allows .[0]
    if (auto *SD = dyn_cast<SubscriptDecl>(D)) {
      addSubscriptCall(SD, Reason, dynamicLookupInfo);
      return;
    }

    if (auto *MD = dyn_cast<MacroDecl>(D)) {
      addMacroExpansion(MD, Reason);
      return;
    }
    return;

  case LookupKind::EnumElement:
    handleEnumElement(D, Reason, dynamicLookupInfo);
    return;

  case LookupKind::Type:
  case LookupKind::TypeInDeclContext:
    if (auto *NTD = dyn_cast<NominalTypeDecl>(D)) {
      addNominalTypeRef(NTD, Reason, dynamicLookupInfo);
      return;
    }

    if (auto *GP = dyn_cast<GenericTypeParamDecl>(D)) {
      addGenericTypeParamRef(GP, Reason, dynamicLookupInfo);
      return;
    }

    LLVM_FALLTHROUGH;
  case LookupKind::GenericRequirement:

    if (TypeAliasDecl *TAD = dyn_cast<TypeAliasDecl>(D)) {
      if (Kind == LookupKind::GenericRequirement &&
          !canBeUsedAsRequirementFirstType(BaseType, TAD))
        return;
      addTypeAliasRef(TAD, Reason, dynamicLookupInfo);
      return;
    }

    if (auto *AT = dyn_cast<AssociatedTypeDecl>(D)) {
      addAssociatedTypeRef(AT, Reason, dynamicLookupInfo);
      return;
    }

    return;
  case LookupKind::StoredProperty:
    if (auto *VD = dyn_cast<VarDecl>(D)) {
      if (VD->hasStorage()) {
        addVarDeclRef(VD, Reason, dynamicLookupInfo);
      }
      return;
    }
  }
}

bool CompletionLookup::handleEnumElement(ValueDecl *D,
                                         DeclVisibilityKind Reason,
                                         DynamicLookupInfo dynamicLookupInfo) {
  if (auto *EED = dyn_cast<EnumElementDecl>(D)) {
    addEnumElementRef(EED, Reason, dynamicLookupInfo,
                      /*HasTypeContext=*/true);
    return true;
  } else if (auto *ED = dyn_cast<EnumDecl>(D)) {
    for (auto *Ele : ED->getAllElements()) {
      addEnumElementRef(Ele, Reason, dynamicLookupInfo,
                        /*HasTypeContext=*/true);
    }
    return true;
  }
  return false;
}

bool CompletionLookup::tryTupleExprCompletions(Type ExprType) {
  auto *TT = ExprType->getAs<TupleType>();
  if (!TT)
    return false;

  unsigned Index = 0;
  for (auto TupleElt : TT->getElements()) {
    auto Ty = TupleElt.getType();
    if (TupleElt.hasName()) {
      addBuiltinMemberRef(TupleElt.getName().str(), Ty);
    } else {
      llvm::SmallString<4> IndexStr;
      {
        llvm::raw_svector_ostream OS(IndexStr);
        OS << Index;
      }
      addBuiltinMemberRef(IndexStr, Ty);
    }
    ++Index;
  }
  return true;
}

void CompletionLookup::tryFunctionIsolationCompletion(Type ExprType) {
  auto *FT = ExprType->getAs<FunctionType>();
  if (!FT || !FT->getIsolation().isErased())
    return;

  // The type of `.isolation` is `(any Actor)?`
  auto *actorProto = Ctx.getProtocol(KnownProtocolKind::Actor);
  auto memberTy = OptionalType::get(actorProto->getDeclaredExistentialType());

  addBuiltinMemberRef(Ctx.Id_isolation.str(), memberTy);
}

bool CompletionLookup::tryFunctionCallCompletions(
    Type ExprType, const ValueDecl *VD,
    std::optional<SemanticContextKind> SemanticContext) {
  ExprType = ExprType->getRValueType();
  if (auto AFT = ExprType->getAs<AnyFunctionType>()) {
    if (auto *AFD = dyn_cast_or_null<AbstractFunctionDecl>(VD)) {
      addFunctionCallPattern(AFT, AFD, SemanticContext);
    } else {
      addFunctionCallPattern(AFT);
    }
    return true;
  }
  return false;
}

bool CompletionLookup::tryModuleCompletions(Type ExprType,
                                            CodeCompletionFilter Filter) {
  if (auto MT = ExprType->getAs<ModuleType>()) {
    ModuleDecl *M = MT->getModule();

    // Only lookup this module's symbols from the cache if it is not the
    // current module.
    if (M == CurrModule)
      return false;

    // If the module is shadowed by a separately imported overlay(s), look up
    // the symbols from the overlay(s) instead.
    SmallVector<ModuleDecl *, 1> ShadowingOrOriginal;
    if (auto *SF = CurrDeclContext->getParentSourceFile()) {
      SF->getSeparatelyImportedOverlays(M, ShadowingOrOriginal);
      if (ShadowingOrOriginal.empty())
        ShadowingOrOriginal.push_back(M);
    }
    for (ModuleDecl *M : ShadowingOrOriginal) {
      RequestedResultsTy Request =
          RequestedResultsTy::fromModule(M, Filter).needLeadingDot(needDot());
      RequestedCachedResults.insert(Request);
    }
    return true;
  }
  return false;
}

bool CompletionLookup::tryUnwrappedCompletions(Type ExprType, bool isIUO) {
  // FIXME: consider types convertible to T?.

  ExprType = ExprType->getRValueType();
  // FIXME: We don't always pass down whether a type is from an
  // unforced IUO.
  if (isIUO) {
    if (Type Unwrapped = ExprType->getOptionalObjectType()) {
      lookupVisibleMemberDecls(*this, Unwrapped, DotLoc, CurrDeclContext,
                               IncludeInstanceMembers,
                               /*includeDerivedRequirements*/ false,
                               /*includeProtocolExtensionMembers*/ true);
      return true;
    }
    assert(IsUnwrappedOptional &&
           "IUOs should be optional if not bound/forced");
    return false;
  }

  if (Type Unwrapped = ExprType->getOptionalObjectType()) {
    llvm::SaveAndRestore<bool> ChangeNeedOptionalUnwrap(NeedOptionalUnwrap,
                                                        true);
    if (DotLoc.isValid()) {
      // Let's not erase the dot if the completion is after a swift key path
      // root because \A?.?.member is the correct way to access wrapped type
      // member from an optional key path root.
      auto loc = IsAfterSwiftKeyPathRoot ? DotLoc.getAdvancedLoc(1) : DotLoc;
      NumBytesToEraseForOptionalUnwrap = Ctx.SourceMgr.getByteDistance(
          loc, Ctx.SourceMgr.getIDEInspectionTargetLoc());
    } else {
      NumBytesToEraseForOptionalUnwrap = 0;
    }
    if (NumBytesToEraseForOptionalUnwrap <=
        CodeCompletionResult::MaxNumBytesToErase) {
      // Add '.isolation' to @isolated(any) functions.
      tryFunctionIsolationCompletion(Unwrapped);

      if (!tryTupleExprCompletions(Unwrapped)) {
        lookupVisibleMemberDecls(*this, Unwrapped, DotLoc,
                                 CurrDeclContext,
                                 IncludeInstanceMembers,
                                 /*includeDerivedRequirements*/ false,
                                 /*includeProtocolExtensionMembers*/ true);
      }
    }
    return true;
  }
  return false;
}

void CompletionLookup::getPostfixKeywordCompletions(Type ExprType,
                                                    Expr *ParsedExpr) {
  if (IsSuperRefExpr)
    return;

  NeedLeadingDot = !HaveDot;

  if (!ExprType->getAs<ModuleType>()) {
    addKeyword(getTokenText(tok::kw_self), ExprType->getRValueType(),
               SemanticContextKind::CurrentNominal,
               CodeCompletionKeywordKind::kw_self);
  }

  if (isa<TypeExpr>(ParsedExpr)) {
    if (auto *T = ExprType->getAs<AnyMetatypeType>()) {
      auto instanceTy = T->getInstanceType();
      if (instanceTy->isAnyExistentialType()) {
        addKeyword("Protocol", MetatypeType::get(instanceTy),
                   SemanticContextKind::CurrentNominal);
        addKeyword("Type", ExistentialMetatypeType::get(instanceTy),
                   SemanticContextKind::CurrentNominal);
      } else {
        addKeyword("Type", MetatypeType::get(instanceTy),
                   SemanticContextKind::CurrentNominal);
      }
    }
  }
}

void CompletionLookup::getValueExprCompletions(Type ExprType, ValueDecl *VD,
                                               bool IsDeclUnapplied) {
  Kind = LookupKind::ValueExpr;
  NeedLeadingDot = !HaveDot;

  ExprType = ExprType->getRValueType();
  assert(!ExprType->hasTypeParameter());

  this->ExprType = ExprType;

  // Open existential types, so that lookupVisibleMemberDecls() can properly
  // substitute them.
  bool WasOptional = false;
  if (auto OptionalType = ExprType->getOptionalObjectType()) {
    ExprType = OptionalType;
    WasOptional = true;
  }

  if (!ExprType->getMetatypeInstanceType()->isAnyObject()) {
    if (ExprType->isAnyExistentialType()) {
      ExprType = OpenedArchetypeType::getAny(ExprType->getCanonicalType());
    }
  }
  if (!IsSelfRefExpr && !IsSuperRefExpr && ExprType->getAnyNominal() &&
      ExprType->getAnyNominal()->isActor()) {
    IsCrossActorReference = true;
  }

  if (WasOptional)
    ExprType = OptionalType::get(ExprType);

  // Handle special cases

  // Add '.isolation' to @isolated(any) functions.
  tryFunctionIsolationCompletion(ExprType);

  bool isIUO = VD && VD->isImplicitlyUnwrappedOptional();
  if (tryFunctionCallCompletions(ExprType, IsDeclUnapplied ? VD : nullptr))
    return;
  if (tryModuleCompletions(ExprType, {CodeCompletionFilterFlag::Expr,
                                      CodeCompletionFilterFlag::Type}))
    return;
  if (tryTupleExprCompletions(ExprType))
    return;
  // Don't check/return so we still add the members of Optional itself below
  tryUnwrappedCompletions(ExprType, isIUO);

  lookupVisibleMemberDecls(*this, ExprType, DotLoc, CurrDeclContext,
                           IncludeInstanceMembers,
                           /*includeDerivedRequirements*/ false,
                           /*includeProtocolExtensionMembers*/ true);
}

void CompletionLookup::getStoredPropertyCompletions(const NominalTypeDecl *D) {
  Kind = LookupKind::StoredProperty;
  NeedLeadingDot = false;

  lookupVisibleMemberDecls(*this, D->getDeclaredInterfaceType(),
                           /*DotLoc=*/SourceLoc(), CurrDeclContext,
                           /*IncludeInstanceMembers*/ true,
                           /*includeDerivedRequirements*/ false,
                           /*includeProtocolExtensionMembers*/ false);
}

void CompletionLookup::collectOperators(
    SmallVectorImpl<OperatorDecl *> &results) {
  assert(CurrDeclContext);
  for (auto import : namelookup::getAllImports(CurrDeclContext))
    import.importedModule->getOperatorDecls(results);
}

void CompletionLookup::addPostfixBang(Type resultType) {
  CodeCompletionResultBuilder builder = makeResultBuilder(
      CodeCompletionResultKind::BuiltinOperator, SemanticContextKind::None);
  // FIXME: we can't use the exclamation mark chunk kind, or it isn't
  // included in the completion name.
  builder.addTextChunk("!");
  assert(resultType);
  addTypeAnnotation(builder, resultType);
}

void CompletionLookup::addPostfixOperatorCompletion(OperatorDecl *op,
                                                    Type resultType) {
  // FIXME: we should get the semantic context of the function, not the
  // operator decl.
  auto semanticContext =
      getSemanticContext(op, DeclVisibilityKind::VisibleAtTopLevel, {});
  CodeCompletionResultBuilder builder =
      makeResultBuilder(CodeCompletionResultKind::Declaration, semanticContext);

  // FIXME: handle variable amounts of space.
  if (HaveLeadingSpace)
    builder.setNumBytesToErase(1);
  builder.setAssociatedDecl(op);
  builder.addBaseName(op->getName().str());
  assert(resultType);
  addTypeAnnotation(builder, resultType);
}

void CompletionLookup::addAssignmentOperator(Type RHSType) {
  CodeCompletionResultBuilder builder = makeResultBuilder(
      CodeCompletionResultKind::BuiltinOperator, SemanticContextKind::None);

  if (HaveLeadingSpace)
    builder.addAnnotatedWhitespace(" ");
  else
    builder.addWhitespace(" ");
  builder.addEqual();
  builder.addWhitespace(" ");
  assert(RHSType);
  Type contextTy;
  if (auto typeContext = CurrDeclContext->getInnermostTypeContext())
    contextTy = typeContext->getDeclaredTypeInContext();
  builder.addCallArgument(Identifier(), RHSType, contextTy,
                          /*IsForOperator=*/true);
}

void CompletionLookup::addInfixOperatorCompletion(OperatorDecl *op,
                                                  Type resultType,
                                                  Type RHSType) {
  // FIXME: we should get the semantic context of the function, not the
  // operator decl.
  auto semanticContext =
      getSemanticContext(op, DeclVisibilityKind::VisibleAtTopLevel, {});
  CodeCompletionResultBuilder builder =
      makeResultBuilder(CodeCompletionResultKind::Declaration, semanticContext);
  builder.setAssociatedDecl(op);

  if (HaveLeadingSpace)
    builder.addAnnotatedWhitespace(" ");
  else
    builder.addWhitespace(" ");
  builder.addBaseName(op->getName().str());
  builder.addWhitespace(" ");
  if (RHSType) {
    Type contextTy;
    if (auto typeContext = CurrDeclContext->getInnermostTypeContext())
      contextTy = typeContext->getDeclaredTypeInContext();
    builder.addCallArgument(Identifier(), RHSType, contextTy,
                            /*IsForOperator=*/true);
  }
  if (resultType)
    addTypeAnnotation(builder, resultType);
}

void CompletionLookup::addTypeRelationFromProtocol(
    CodeCompletionResultBuilder &builder, CodeCompletionLiteralKind kind) {
  Type literalType;

  // The literal can produce any type that conforms to its ExpressibleBy
  // protocol. Figure out as which type we want to show it in code completion.
  auto *PD = Ctx.getProtocol(protocolForLiteralKind(kind));
  for (auto T : expectedTypeContext.getPossibleTypes()) {
    if (!T)
      continue;

    // Convert through optional types unless we're looking for a protocol
    // that Optional itself conforms to.
    if (kind != CodeCompletionLiteralKind::NilLiteral) {
      if (auto optionalObjT = T->getOptionalObjectType()) {
        T = optionalObjT;
      }
    }

    // Check for conformance to the literal protocol.
    if (T->getAnyNominal()) {
      if (lookupConformance(T, PD)) {
        literalType = T;
        break;
      }
    }
  }

  // Fallback to showing the default type.
  if (!literalType) {
    literalType = defaultTypeLiteralKind(kind, Ctx);
  }
  if (literalType) {
    addTypeAnnotation(builder, literalType);
    builder.setResultTypes(literalType);
    builder.setTypeContext(expectedTypeContext, CurrDeclContext);
  }
}

void CompletionLookup::addValueLiteralCompletions() {
  auto &context = CurrDeclContext->getASTContext();

  CodeCompletionFlair flair;
  if (isCodeCompletionAtTopLevelOfLibraryFile(CurrDeclContext))
    flair |= CodeCompletionFlairBit::ExpressionAtNonScriptOrMainFileScope;

  auto addFromProto =
      [&](CodeCompletionLiteralKind kind,
          llvm::function_ref<void(CodeCompletionResultBuilder &)> consumer,
          bool isKeyword = false) {
        CodeCompletionResultBuilder builder = makeResultBuilder(
            CodeCompletionResultKind::Literal, SemanticContextKind::None);
        builder.setLiteralKind(kind);
        builder.addFlair(flair);

        consumer(builder);
        addTypeRelationFromProtocol(builder, kind);
      };

  // FIXME: the pedantically correct way is to resolve Swift.*LiteralType.

  using LK = CodeCompletionLiteralKind;
  using Builder = CodeCompletionResultBuilder;

  // Add literal completions that conform to specific protocols.
  addFromProto(LK::IntegerLiteral,
               [](Builder &builder) { builder.addTextChunk("0"); });
  addFromProto(
      LK::BooleanLiteral, [](Builder &builder) { builder.addBaseName("true"); },
      /*isKeyword=*/true);
  addFromProto(
      LK::BooleanLiteral,
      [](Builder &builder) { builder.addBaseName("false"); },
      /*isKeyword=*/true);
  addFromProto(
      LK::NilLiteral, [](Builder &builder) { builder.addBaseName("nil"); },
      /*isKeyword=*/true);
  addFromProto(LK::StringLiteral, [&](Builder &builder) {
    builder.addTextChunk("\"");
    builder.addSimpleNamedParameter("abc");
    builder.addTextChunk("\"");
  });
  addFromProto(LK::ArrayLiteral, [&](Builder &builder) {
    builder.addLeftBracket();
    builder.addSimpleNamedParameter("values");
    builder.addRightBracket();
  });
  addFromProto(LK::DictionaryLiteral, [&](Builder &builder) {
    builder.addLeftBracket();
    builder.addSimpleNamedParameter("key");
    builder.addTextChunk(": ");
    builder.addSimpleNamedParameter("value");
    builder.addRightBracket();
  });

  // Optionally add object literals.
  if (Sink.includeObjectLiterals) {
    auto floatType = context.getFloatType();
    addFromProto(LK::ColorLiteral, [&](Builder &builder) {
      builder.addBaseName("#colorLiteral");
      builder.addLeftParen();
      builder.addCallArgument(context.getIdentifier("red"), floatType);
      builder.addComma();
      builder.addCallArgument(context.getIdentifier("green"), floatType);
      builder.addComma();
      builder.addCallArgument(context.getIdentifier("blue"), floatType);
      builder.addComma();
      builder.addCallArgument(context.getIdentifier("alpha"), floatType);
      builder.addRightParen();
    });

    auto stringType = context.getStringType();
    addFromProto(LK::ImageLiteral, [&](Builder &builder) {
      builder.addBaseName("#imageLiteral");
      builder.addLeftParen();
      builder.addCallArgument(context.getIdentifier("resourceName"),
                              stringType);
      builder.addRightParen();
    });
  }

  // Add tuple completion (item, item).
  {
    CodeCompletionResultBuilder builder = makeResultBuilder(
        CodeCompletionResultKind::Literal, SemanticContextKind::None);
    builder.setLiteralKind(LK::Tuple);
    builder.addFlair(flair);

    builder.addLeftParen();
    builder.addSimpleNamedParameter("values");
    builder.addRightParen();
    for (auto T : expectedTypeContext.getPossibleTypes()) {
      if (T && T->is<TupleType>() && !T->isVoid()) {
        addTypeAnnotation(builder, T);
        builder.setResultTypes(T);
        builder.setTypeContext(expectedTypeContext, CurrDeclContext);
        break;
      }
    }
  }
}

void CompletionLookup::addObjCPoundKeywordCompletions(bool needPound) {
  if (!Ctx.LangOpts.EnableObjCInterop)
    return;

  // If the expected type is ObjectiveC.Selector, add #selector. If
  // it's String, add #keyPath.
  bool addedSelector = false;
  bool addedKeyPath = false;

  for (auto T : expectedTypeContext.getPossibleTypes()) {
    T = T->lookThroughAllOptionalTypes();
    if (auto structDecl = T->getStructOrBoundGenericStruct()) {
      if (!addedSelector && structDecl->getName() == Ctx.Id_Selector &&
          structDecl->getParentModule()->getName() == Ctx.Id_ObjectiveC) {
        addPoundSelector(needPound);
        if (addedKeyPath)
          break;
        addedSelector = true;
        continue;
      }
    }

    if (!addedKeyPath && T->isString()) {
      addPoundKeyPath(needPound);
      if (addedSelector)
        break;
      addedKeyPath = true;
      continue;
    }
  }
}

void CompletionLookup::getMacroCompletions(CodeCompletionMacroRoles roles) {
  RequestedCachedResults.insert(
      RequestedResultsTy::topLevelResults(getCompletionFilter(roles)));
}

void CompletionLookup::getValueCompletionsInDeclContext(SourceLoc Loc,
                                                        DeclFilter Filter,
                                                        bool LiteralCompletions,
                                                        bool ModuleQualifier) {
  ExprType = Type();
  Kind = LookupKind::ValueInDeclContext;
  NeedLeadingDot = false;

  AccessFilteringDeclConsumer AccessFilteringConsumer(CurrDeclContext, *this);
  FilteredDeclConsumer FilteringConsumer(AccessFilteringConsumer, Filter);

  lookupVisibleDecls(FilteringConsumer, Loc, CurrDeclContext,
                     /*IncludeTopLevel=*/false);

  CodeCompletionFilter filter{CodeCompletionFilterFlag::Expr,
                              CodeCompletionFilterFlag::Type};
  if (ModuleQualifier) {
    filter |= CodeCompletionFilterFlag::Module;
  }
  RequestedCachedResults.insert(RequestedResultsTy::topLevelResults(filter));

  if (CompletionContext) {
    // FIXME: this is an awful simplification that says all and only enums can
    // use implicit member syntax (leading dot). Computing the accurate answer
    // using lookup (e.g. getUnresolvedMemberCompletions) is too expensive,
    // and for some clients this approximation is good enough.
    CompletionContext->MayUseImplicitMemberExpr =
        llvm::any_of(expectedTypeContext.getPossibleTypes(), [](Type T) {
          if (auto *NTD = T->getAnyNominal())
            return isa<EnumDecl>(NTD);
          return false;
        });
  }

  if (LiteralCompletions) {
    addValueLiteralCompletions();
  }

  addObjCPoundKeywordCompletions(/*needPound=*/true);
}

bool CompletionLookup::isInitializerOnOptional(Type T, ValueDecl *VD) {
  bool IsOptionalType = false;
  IsOptionalType |= static_cast<bool>(T->getOptionalObjectType());
  if (auto *NTD = T->getAnyNominal()) {
    IsOptionalType |= NTD->getBaseIdentifier() ==
                      VD->getASTContext().Id_OptionalNilComparisonType;
  }
  if (IsOptionalType && VD->getModuleContext()->isStdlibModule() &&
      isa<ConstructorDecl>(VD)) {
    return true;
  } else {
    return false;
  }
}

void CompletionLookup::getUnresolvedMemberCompletions(Type T) {
  if (!T->mayHaveMembers())
    return;

  NeedLeadingDot = !HaveDot;

  if (auto objT = T->getOptionalObjectType()) {
    // Add 'nil' keyword with erasing '.' instruction.
    unsigned bytesToErase = 0;
    auto &SM = CurrDeclContext->getASTContext().SourceMgr;
    if (DotLoc.isValid())
      bytesToErase = SM.getByteDistance(DotLoc, SM.getIDEInspectionTargetLoc());
    addKeyword("nil", T, SemanticContextKind::None,
               CodeCompletionKeywordKind::kw_nil, bytesToErase);
  }

  // We can only say .foo where foo is a static member of the contextual
  // type and has the same type (or if the member is a function, then the
  // same result type) as the contextual type.
  FilteredDeclConsumer consumer(*this,
                                [=](ValueDecl *VD, DeclVisibilityKind Reason,
                                    DynamicLookupInfo dynamicLookupInfo) {
                                  // In optional context, ignore
                                  // '.init(<some>)', 'init(nilLiteral:)',
                                  return !isInitializerOnOptional(T, VD);
                                });

  auto baseType = MetatypeType::get(T);
  llvm::SaveAndRestore<LookupKind> SaveLook(Kind, LookupKind::ValueExpr);
  llvm::SaveAndRestore<Type> SaveType(ExprType, baseType);
  llvm::SaveAndRestore<bool> SaveUnresolved(IsUnresolvedMember, true);
  lookupVisibleMemberDecls(consumer, baseType, DotLoc, CurrDeclContext,
                           /*includeInstanceMembers=*/false,
                           /*includeDerivedRequirements*/ false,
                           /*includeProtocolExtensionMembers*/ true);
}

void CompletionLookup::getEnumElementPatternCompletions(Type T) {
  if (!isa_and_nonnull<EnumDecl>(T->getAnyNominal()))
    return;

  auto baseType = MetatypeType::get(T);
  llvm::SaveAndRestore<LookupKind> SaveLook(Kind, LookupKind::EnumElement);
  llvm::SaveAndRestore<Type> SaveType(ExprType, baseType);
  llvm::SaveAndRestore<bool> SaveUnresolved(IsUnresolvedMember, true);
  lookupVisibleMemberDecls(*this, baseType, DotLoc, CurrDeclContext,
                           /*includeInstanceMembers=*/false,
                           /*includeDerivedRequirements=*/false,
                           /*includeProtocolExtensionMembers=*/true);
}

void CompletionLookup::getUnresolvedMemberCompletions(ArrayRef<Type> Types) {
  NeedLeadingDot = !HaveDot;

  SmallPtrSet<CanType, 4> seenTypes;
  for (auto T : Types) {
    if (!T || !seenTypes.insert(T->getCanonicalType()).second)
      continue;

    if (auto objT = T->getOptionalObjectType()) {
      // If this is optional type, perform completion for the object type.
      // i.e. 'let _: Enum??? = .enumMember' is legal.
      objT = objT->lookThroughAllOptionalTypes();
      if (seenTypes.insert(objT->getCanonicalType()).second)
        getUnresolvedMemberCompletions(objT);
    }
    getUnresolvedMemberCompletions(T);
  }
}

void CompletionLookup::addCallArgumentCompletionResults(
    ArrayRef<PossibleParamInfo> ParamInfos, bool isLabeledTrailingClosure) {
  Type ContextType;
  if (auto typeContext = CurrDeclContext->getInnermostTypeContext())
    ContextType = typeContext->getDeclaredTypeInContext();

  for (auto Info : ParamInfos) {
    const auto *Arg = Info.Param;
    if (!Arg)
      continue;
    CodeCompletionResultBuilder Builder = makeResultBuilder(
        CodeCompletionResultKind::Pattern,
        // FIXME: SemanticContextKind::Local is not correct.
        // Use 'None' (and fix prioritization) or introduce a new context.
        SemanticContextKind::Local);
    Builder.addCallArgument(Arg->getLabel(), Identifier(), Arg->getPlainType(),
                            ContextType, Arg->isVariadic(), Arg->isInOut(),
                            /*IsIUO=*/false, Arg->isAutoClosure(),
                            isLabeledTrailingClosure,
                            /*IsForOperator=*/false,
                            /*HasDefault=*/false);
    Builder.addFlair(CodeCompletionFlairBit::ArgumentLabels);
    auto Ty = Arg->getPlainType();
    if (Arg->isInOut()) {
      Ty = InOutType::get(Ty);
    } else if (Arg->isAutoClosure()) {
      // 'Ty' may be ErrorType.
      if (auto funcTy = Ty->getAs<FunctionType>())
        Ty = funcTy->getResult();
    }
    // The type annotation is the argument type. But the argument label itself
    // does not produce an expression with a result type so we set the result
    // type as being not applicable.
    addTypeAnnotation(Builder, Ty);
    Builder.setResultTypeNotApplicable();
  }
}

void CompletionLookup::getTypeCompletions(Type BaseType) {
  if (tryModuleCompletions(BaseType, CodeCompletionFilterFlag::Type))
    return;
  Kind = LookupKind::Type;
  this->BaseType = BaseType;
  NeedLeadingDot = !HaveDot;
  lookupVisibleMemberDecls(*this, MetatypeType::get(BaseType), DotLoc,
                           CurrDeclContext, IncludeInstanceMembers,
                           /*includeDerivedRequirements*/ false,
                           /*includeProtocolExtensionMembers*/ false);
  if (BaseType->isAnyExistentialType()) {
    addKeyword("Protocol", MetatypeType::get(BaseType));
    addKeyword("Type", ExistentialMetatypeType::get(BaseType));
  } else if (!BaseType->is<ModuleType>()) {
    addKeyword("Type", MetatypeType::get(BaseType));
  }
}

void CompletionLookup::getInvertedTypeCompletions() {
  Kind = LookupKind::Type;

  auto addCompletion = [&](InvertibleProtocolKind invertableKind) {
    auto *P = Ctx.getProtocol(getKnownProtocolKind(invertableKind));
    if (!P)
      return;

    addNominalTypeRef(P, DeclVisibilityKind::VisibleAtTopLevel,
                      DynamicLookupInfo());
  };
#define INVERTIBLE_PROTOCOL(Name, Bit)         \
  addCompletion(InvertibleProtocolKind::Name);
#include "swift/ABI/InvertibleProtocols.def"
}

void CompletionLookup::getGenericRequirementCompletions(
    DeclContext *DC, SourceLoc CodeCompletionLoc) {
  auto genericSig = DC->getGenericSignatureOfContext();
  if (!genericSig)
    return;

  for (auto GPT : genericSig.getGenericParams()) {
    addGenericTypeParamRef(GPT->getDecl(), DeclVisibilityKind::GenericParameter,
                           {});
  }

  // For non-protocol nominal type decls, only suggest generic parameters.
  if (auto D = DC->getAsDecl())
    if (isa<NominalTypeDecl>(D) && !isa<ProtocolDecl>(D))
      return;

  auto typeContext = DC->getInnermostTypeContext();
  if (!typeContext)
    return;

  auto selfTy = typeContext->getSelfTypeInContext();
  Kind = LookupKind::GenericRequirement;
  this->BaseType = selfTy;
  NeedLeadingDot = false;
  lookupVisibleMemberDecls(*this, MetatypeType::get(selfTy), DotLoc,
                           CurrDeclContext, IncludeInstanceMembers,
                           /*includeDerivedRequirements*/ false,
                           /*includeProtocolExtensionMembers*/ true);
  // We not only allow referencing nested types/typealiases directly, but also
  // qualified by the current type. Thus also suggest current self type so the
  // user can do a memberwise lookup on it.
  if (auto SelfType = typeContext->getSelfNominalTypeDecl()) {
    addNominalTypeRef(SelfType, DeclVisibilityKind::LocalDecl,
                      DynamicLookupInfo());
  }

  // Self is also valid in all cases in which it can be used in function
  // bodies. Suggest it if applicable.
  getSelfTypeCompletionInDeclContext(CodeCompletionLoc,
                                     /*isForResultType=*/false);
}

bool CompletionLookup::canUseAttributeOnDecl(DeclAttrKind DAK, bool IsInSil,
                                             bool IsConcurrencyEnabled,
                                             std::optional<DeclKind> DK,
                                             StringRef Name) {
  if (DeclAttribute::isUserInaccessible(DAK))
    return false;
  if (DeclAttribute::isDeclModifier(DAK))
    return false;
  if (DeclAttribute::shouldBeRejectedByParser(DAK))
    return false;
  if (!IsInSil && DeclAttribute::isSilOnly(DAK))
    return false;
  if (!IsConcurrencyEnabled && DeclAttribute::isConcurrencyOnly(DAK))
    return false;
  if (!DK.has_value())
    return true;
  // Hide underscored attributes even if they are not marked as user
  // inaccessible. This can happen for attributes that are an underscored
  // variant of a user-accessible attribute (like @_backDeployed)
  if (Name.empty() || Name[0] == '_')
    return false;
  return DeclAttribute::canAttributeAppearOnDeclKind(DAK, DK.value());
}

void CompletionLookup::getAttributeDeclCompletions(bool IsInSil,
                                                   std::optional<DeclKind> DK) {
  // FIXME: also include user-defined attribute keywords
  StringRef TargetName = "Declaration";
  if (DK.has_value()) {
    switch (DK.value()) {
#define DECL(Id, ...)                                                          \
  case DeclKind::Id:                                                           \
    TargetName = #Id;                                                          \
    break;
#include "swift/AST/DeclNodes.def"
    }
  }
  bool IsConcurrencyEnabled = Ctx.LangOpts.EnableExperimentalConcurrency;
  std::string Description = TargetName.str() + " Attribute";
#define DECL_ATTR_ALIAS(KEYWORD, NAME) DECL_ATTR(KEYWORD, NAME, 0, 0)
#define DECL_ATTR(KEYWORD, NAME, ...)                                          \
  if (canUseAttributeOnDecl(DeclAttrKind::NAME, IsInSil, IsConcurrencyEnabled, \
                            DK, #KEYWORD))                                     \
    addDeclAttrKeyword(#KEYWORD, Description);
#include "swift/AST/DeclAttr.def"
}

void CompletionLookup::getAttributeDeclParamCompletions(
    CustomSyntaxAttributeKind AttrKind, int ParamIndex, bool HasLabel) {
  switch (AttrKind) {
  case CustomSyntaxAttributeKind::Available:
    if (ParamIndex == 0) {
      addDeclAttrParamKeyword("*", /*Parameters=*/{}, "Platform", false);

#define AVAILABILITY_PLATFORM(X, PrettyName)                                   \
  addDeclAttrParamKeyword(swift::platformString(PlatformKind::X),              \
                          /*Parameters=*/{}, "Platform", false);
#include "swift/AST/PlatformKinds.def"

    } else {
      addDeclAttrParamKeyword("unavailable", /*Parameters=*/{}, "", false);
      addDeclAttrParamKeyword("message", /*Parameters=*/{}, "Specify message",
                              true);
      addDeclAttrParamKeyword("renamed", /*Parameters=*/{},
                              "Specify replacing name", true);
      addDeclAttrParamKeyword("introduced", /*Parameters=*/{},
                              "Specify version number", true);
      addDeclAttrParamKeyword("deprecated", /*Parameters=*/{},
                              "Specify version number", true);
    }
    break;
  case CustomSyntaxAttributeKind::FreestandingMacro:
  case CustomSyntaxAttributeKind::AttachedMacro:
    switch (ParamIndex) {
    case 0:
      for (auto role : getAllMacroRoles()) {
        bool isRoleSupported = isMacroSupported(role, Ctx);
        if (AttrKind == CustomSyntaxAttributeKind::FreestandingMacro) {
          isRoleSupported &= isFreestandingMacro(role);
        } else if (AttrKind == CustomSyntaxAttributeKind::AttachedMacro) {
          isRoleSupported &= isAttachedMacro(role);
        }
        if (isRoleSupported) {
          addDeclAttrParamKeyword(getMacroRoleString(role), /*Parameters=*/{},
                                  /*Annotation=*/"", /*NeedsSpecify=*/false);
        }
      }
      break;
    case 1:
      if (HasLabel) {
        for (auto kind : getAllMacroIntroducedDeclNameKinds()) {
          auto name = getMacroIntroducedDeclNameString(kind);
          SmallVector<StringRef, 1> Parameters;
          if (macroIntroducedNameRequiresArgument(kind)) {
            Parameters = {"name"};
          }
          addDeclAttrParamKeyword(name, Parameters, /*Annotation=*/"",
                                  /*NeedsSpecify=*/false);
        }
      } else {
        addDeclAttrParamKeyword("names", /*Parameters=*/{},
                                "Specify declared names",
                                /*NeedsSpecify=*/true);
      }
      break;
    }
    break;
  case CustomSyntaxAttributeKind::StorageRestrictions: {
    bool suggestInitializesLabel = false;
    bool suggestAccessesLabel = false;
    bool suggestArgument = false;
    switch (static_cast<StorageRestrictionsCompletionKind>(ParamIndex)) {
    case StorageRestrictionsCompletionKind::Label:
      suggestAccessesLabel = true;
      suggestInitializesLabel = true;
      break;
    case StorageRestrictionsCompletionKind::Argument:
      suggestArgument = true;
      break;
    case StorageRestrictionsCompletionKind::ArgumentOrInitializesLabel:
      suggestArgument = true;
      suggestInitializesLabel = true;
      break;
    case StorageRestrictionsCompletionKind::ArgumentOrAccessesLabel:
      suggestArgument = true;
      suggestAccessesLabel = true;
      break;
    }
    if (suggestInitializesLabel) {
      addDeclAttrParamKeyword(
          "initializes", /*Parameters=*/{},
          "Specify stored properties initialized by the accessor", true);
    }
    if (suggestAccessesLabel) {
      addDeclAttrParamKeyword(
          "accesses", /*Parameters=*/{},
          "Specify stored properties accessed by the accessor", true);
    }
    if (suggestArgument) {
      if (auto NT = dyn_cast<NominalTypeDecl>(CurrDeclContext)) {
        getStoredPropertyCompletions(NT);
      }
    }
  }
  }
}

void CompletionLookup::getTypeAttributeKeywordCompletions(
    CompletionKind completionKind) {
  auto addTypeAttr = [&](TypeAttrKind Kind, StringRef Name) {
    if (completionKind != CompletionKind::TypeAttrInheritanceBeginning) {
      switch (Kind) {
      case TypeAttrKind::Retroactive:
      case TypeAttrKind::Preconcurrency:
      case TypeAttrKind::Unchecked:
        // These attributes are only available in inheritance clasuses.
        return;
      default:
        break;
      }
    }
    CodeCompletionResultBuilder Builder = makeResultBuilder(
        CodeCompletionResultKind::Keyword, SemanticContextKind::None);
    Builder.addAttributeKeyword(Name, "Type Attribute");
  };

  // Add simple user-accessible attributes.
#define SIL_TYPE_ATTR(SPELLING, C)
#define SIMPLE_SIL_TYPE_ATTR(SPELLING, C)
#define SIMPLE_TYPE_ATTR(SPELLING, C)                                          \
  if (!TypeAttribute::isUserInaccessible(TypeAttrKind::C))                     \
    addTypeAttr(TypeAttrKind::C, #SPELLING);
#include "swift/AST/TypeAttr.def"

  // Add non-simple cases.
  addTypeAttr(TypeAttrKind::Convention, "convention(swift)");
  addTypeAttr(TypeAttrKind::Convention, "convention(block)");
  addTypeAttr(TypeAttrKind::Convention, "convention(c)");
  addTypeAttr(TypeAttrKind::Convention, "convention(thin)");
  addTypeAttr(TypeAttrKind::Isolated, "isolated(any)");
}

void CompletionLookup::collectPrecedenceGroups() {
  assert(CurrDeclContext);

  if (CurrModule) {
    for (auto FU : CurrModule->getFiles()) {
      // We are looking through the current module,
      // inspect only source files.
      if (FU->getKind() != FileUnitKind::Source)
        continue;

      llvm::SmallVector<PrecedenceGroupDecl *, 4> results;
      cast<SourceFile>(FU)->getPrecedenceGroups(results);

      for (auto PG : results)
        addPrecedenceGroupRef(PG);
    }
  }
  for (auto Import : namelookup::getAllImports(CurrDeclContext)) {
    auto Module = Import.importedModule;
    if (Module == CurrModule)
      continue;

    RequestedCachedResults.insert(RequestedResultsTy::fromModule(
        Module, CodeCompletionFilterFlag::PrecedenceGroup));
  }
}

void CompletionLookup::getPrecedenceGroupCompletions(
    CodeCompletionCallbacks::PrecedenceGroupCompletionKind SK) {
  switch (SK) {
  case CodeCompletionCallbacks::PrecedenceGroupCompletionKind::Associativity:
    addKeyword(getAssociativitySpelling(Associativity::None));
    addKeyword(getAssociativitySpelling(Associativity::Left));
    addKeyword(getAssociativitySpelling(Associativity::Right));
    return;
  case CodeCompletionCallbacks::PrecedenceGroupCompletionKind::Assignment:
    addKeyword(getTokenText(tok::kw_false), Type(), SemanticContextKind::None,
               CodeCompletionKeywordKind::kw_false);
    addKeyword(getTokenText(tok::kw_true), Type(), SemanticContextKind::None,
               CodeCompletionKeywordKind::kw_true);
    return;
  case CodeCompletionCallbacks::PrecedenceGroupCompletionKind::AttributeList:
    addKeyword("associativity");
    addKeyword("higherThan");
    addKeyword("lowerThan");
    addKeyword("assignment");
    return;
  case CodeCompletionCallbacks::PrecedenceGroupCompletionKind::Relation:
    collectPrecedenceGroups();
    return;
  }
  llvm_unreachable("not a precedencegroup SyntaxKind");
}

void CompletionLookup::getPoundAvailablePlatformCompletions() {

  // The platform names should be identical to those in @available.
  getAttributeDeclParamCompletions(CustomSyntaxAttributeKind::Available, 0,
                                   /*HasLabel=*/false);
}

void CompletionLookup::getSelfTypeCompletionInDeclContext(
    SourceLoc Loc, bool isForDeclResult) {
  const DeclContext *typeDC = CurrDeclContext->getInnermostTypeContext();
  if (!typeDC)
    return;

  // For protocols, there's a 'Self' generic parameter.
  if (typeDC->getSelfProtocolDecl())
    return;

  Type selfType =
      CurrDeclContext->mapTypeIntoContext(typeDC->getSelfInterfaceType());

  if (typeDC->getSelfClassDecl()) {
    // In classes, 'Self' can be used in result type of func, subscript and
    // computed property, or inside function bodies.
    bool canUseDynamicSelf = false;
    if (isForDeclResult) {
      canUseDynamicSelf = true;
    } else {
      const auto *checkDC = CurrDeclContext;
      if (isa<TypeAliasDecl>(checkDC))
        checkDC = checkDC->getParent();

      if (const auto *AFD = checkDC->getInnermostMethodContext()) {
        canUseDynamicSelf =
            Ctx.SourceMgr.rangeContainsTokenLoc(AFD->getBodySourceRange(), Loc);
      }
    }
    if (!canUseDynamicSelf)
      return;
    // 'Self' in class is a dynamic type.
    selfType = DynamicSelfType::get(selfType, Ctx);
  } else {
    // In enums and structs, 'Self' is just an alias for the nominal type,
    // and can be used anywhere.
  }

  CodeCompletionResultBuilder Builder = makeResultBuilder(
      CodeCompletionResultKind::Keyword, SemanticContextKind::CurrentNominal);
  Builder.addKeyword("Self");
  Builder.setKeywordKind(CodeCompletionKeywordKind::kw_Self);
  addTypeAnnotation(Builder, selfType);
}

void CompletionLookup::getTypeCompletionsInDeclContext(SourceLoc Loc,
                                                       bool ModuleQualifier) {
  Kind = LookupKind::TypeInDeclContext;

  AccessFilteringDeclConsumer AccessFilteringConsumer(CurrDeclContext, *this);
  lookupVisibleDecls(AccessFilteringConsumer, Loc, CurrDeclContext,
                     /*IncludeTopLevel=*/false);

  CodeCompletionFilter filter{CodeCompletionFilterFlag::Type};
  if (ModuleQualifier) {
    filter |= CodeCompletionFilterFlag::Module;
  }
  RequestedCachedResults.insert(RequestedResultsTy::topLevelResults(filter));
}

namespace {

/// A \c VisibleDeclConsumer that stores all decls that are found and is able
/// to forward the to another \c VisibleDeclConsumer later.
class StoringDeclConsumer : public VisibleDeclConsumer {
  struct FoundDecl {
    ValueDecl *VD;
    DeclVisibilityKind Reason;
    DynamicLookupInfo DynamicLookupInfo;
  };

  std::vector<FoundDecl> FoundDecls;

  void foundDecl(ValueDecl *VD, DeclVisibilityKind Reason,
                 DynamicLookupInfo DynamicLookupInfo = {}) override {
    FoundDecls.push_back({VD, Reason, DynamicLookupInfo});
  }

public:
  /// Call \c foundDecl for every declaration that this consumer has found.
  void forward(VisibleDeclConsumer &Consumer) {
    for (auto &FoundDecl : FoundDecls) {
      Consumer.foundDecl(FoundDecl.VD, FoundDecl.Reason,
                         FoundDecl.DynamicLookupInfo);
    }
  }
};

} // namespace

void CompletionLookup::getToplevelCompletions(CodeCompletionFilter Filter) {
  Kind = (Filter - CodeCompletionFilterFlag::Module)
                 .containsOnly(CodeCompletionFilterFlag::Type)
             ? LookupKind::TypeInDeclContext
             : LookupKind::ValueInDeclContext;
  NeedLeadingDot = false;

  // If we have 'addinitstotoplevel' enabled, calling `foundDecl` on `this`
  // can cause macros to get expanded, which can then cause new members ot get
  // added to 'TopLevelValues', invalidating iterator over `TopLevelDecls` in
  // `SourceLookupCache::lookupVisibleDecls`.
  //
  // Technically `foundDecl` should not expand macros or discover new top level
  // members in any way because those newly discovered decls will not be added
  // to the code completion results. However, it's preferrable to miss results
  // than to silently invalidate a collection, resulting in hard-to-diagnose
  // crashes.
  // Thus, store all the decls found by `CurrModule->lookupVisibleDecls` in a
  // vector first and only call `this->foundDecl` once we have left the
  // iteration loop over `TopLevelDecls`.
  StoringDeclConsumer StoringConsumer;

  UsableFilteringDeclConsumer UsableFilteringConsumer(
      Ctx.SourceMgr, CurrDeclContext, Ctx.SourceMgr.getIDEInspectionTargetLoc(),
      StoringConsumer);
  AccessFilteringDeclConsumer AccessFilteringConsumer(CurrDeclContext,
                                                      UsableFilteringConsumer);

  CodeCompletionMacroRoles ExpectedRoles = getCompletionMacroRoles(Filter);
  DeclFilter VisibleFilter =
      [ExpectedRoles](ValueDecl *VD, DeclVisibilityKind Kind,
                      DynamicLookupInfo DynamicLookupInfo) {
        CodeCompletionMacroRoles Roles = getCompletionMacroRoles(VD);
        if (!ExpectedRoles)
          return !Roles;
        return (bool)(Roles & ExpectedRoles);
      };

  FilteredDeclConsumer FilteringConsumer(AccessFilteringConsumer,
                                         VisibleFilter);

  CurrModule->lookupVisibleDecls({}, FilteringConsumer,
                                 NLKind::UnqualifiedLookup);

  StoringConsumer.forward(*this);
}

void CompletionLookup::lookupExternalModuleDecls(
    const ModuleDecl *TheModule, ArrayRef<std::string> AccessPath,
    bool ResultsHaveLeadingDot) {
  assert(CurrModule != TheModule && "requested module should be external");

  Kind = LookupKind::ImportFromModule;
  NeedLeadingDot = ResultsHaveLeadingDot;

  ImportPath::Access::Builder builder;
  for (auto Piece : AccessPath) {
    builder.push_back(Ctx.getIdentifier(Piece));
  }

  AccessFilteringDeclConsumer FilteringConsumer(CurrDeclContext, *this);
  TheModule->lookupVisibleDecls(builder.get(), FilteringConsumer,
                                NLKind::UnqualifiedLookup);

  llvm::SmallVector<PrecedenceGroupDecl *, 16> precedenceGroups;
  TheModule->getPrecedenceGroups(precedenceGroups);

  for (auto PGD : precedenceGroups)
    addPrecedenceGroupRef(PGD);
}

void CompletionLookup::getStmtLabelCompletions(SourceLoc Loc, bool isContinue) {
  class LabelFinder : public ASTWalker {
    SourceManager &SM;
    SourceLoc TargetLoc;
    bool IsContinue;

  public:
    SmallVector<Identifier, 2> Result;

    /// Walk only the arguments of a macro.
    MacroWalking getMacroWalkingBehavior() const override {
      return MacroWalking::Arguments;
    }

    LabelFinder(SourceManager &SM, SourceLoc TargetLoc, bool IsContinue)
        : SM(SM), TargetLoc(TargetLoc), IsContinue(IsContinue) {}

    PreWalkResult<Stmt *> walkToStmtPre(Stmt *S) override {
      if (SM.isBeforeInBuffer(S->getEndLoc(), TargetLoc))
        return Action::SkipNode(S);

      if (LabeledStmt *LS = dyn_cast<LabeledStmt>(S)) {
        if (LS->getLabelInfo()) {
          if (!IsContinue || LS->isPossibleContinueTarget()) {
            auto label = LS->getLabelInfo().Name;
            if (!llvm::is_contained(Result, label))
              Result.push_back(label);
          }
        }
      }

      return Action::Continue(S);
    }

    PostWalkResult<Stmt *> walkToStmtPost(Stmt *S) override {
      return Action::Stop();
    }

    PreWalkResult<Expr *> walkToExprPre(Expr *E) override {
      if (SM.isBeforeInBuffer(E->getEndLoc(), TargetLoc))
        return Action::SkipNode(E);
      return Action::Continue(E);
    }
  } Finder(CurrDeclContext->getASTContext().SourceMgr, Loc, isContinue);
  const_cast<DeclContext *>(CurrDeclContext)->walkContext(Finder);
  for (auto name : Finder.Result) {
    CodeCompletionResultBuilder Builder = makeResultBuilder(
        CodeCompletionResultKind::Pattern, SemanticContextKind::Local);
    Builder.addTextChunk(name.str());
  }
}

void CompletionLookup::getOptionalBindingCompletions(SourceLoc Loc) {
  ExprType = Type();
  Kind = LookupKind::ValueInDeclContext;
  NeedLeadingDot = false;

  AccessFilteringDeclConsumer AccessFilteringConsumer(CurrDeclContext, *this);

  // Suggest only 'Optional' type var decls (incl. parameters)
  FilteredDeclConsumer FilteringConsumer(
      AccessFilteringConsumer,
      [&](ValueDecl *VD, DeclVisibilityKind Reason,
          DynamicLookupInfo dynamicLookupInfo) -> bool {
        auto *VarD = dyn_cast<VarDecl>(VD);
        if (!VarD)
          return false;

        auto Ty = getTypeOfMember(VD, dynamicLookupInfo);
        return Ty->isOptional();
      });

  // FIXME: Currently, it doesn't include top level decls for performance
  // reason. Enabling 'IncludeTopLevel' pulls everything including imported
  // modules. For suggesting top level results, we need a way to filter cached
  // results.

  lookupVisibleDecls(FilteringConsumer, Loc, CurrDeclContext,
                     /*IncludeTopLevel=*/false);
}