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
use super::{
    EvaluationResult, Obligation, ObligationCause, ObligationCauseCode, PredicateObligation,
    SelectionContext,
};

use crate::autoderef::Autoderef;
use crate::infer::InferCtxt;
use crate::traits::normalize_projection_type;

use rustc_data_structures::fx::FxHashSet;
use rustc_data_structures::stack::ensure_sufficient_stack;
use rustc_data_structures::sync::Lrc;
use rustc_errors::{
    error_code, pluralize, struct_span_err, Applicability, DiagnosticBuilder, Style,
};
use rustc_hir as hir;
use rustc_hir::def::DefKind;
use rustc_hir::def_id::DefId;
use rustc_hir::intravisit::Visitor;
use rustc_hir::lang_items::LangItem;
use rustc_hir::{AsyncGeneratorKind, GeneratorKind, Node};
use rustc_middle::ty::{
    self, suggest_arbitrary_trait_bound, suggest_constraining_type_param, AdtKind, DefIdTree,
    Infer, InferTy, ToPredicate, Ty, TyCtxt, TypeFoldable, WithConstness,
};
use rustc_middle::ty::{TypeAndMut, TypeckResults};
use rustc_session::Limit;
use rustc_span::def_id::LOCAL_CRATE;
use rustc_span::symbol::{kw, sym, Ident, Symbol};
use rustc_span::{BytePos, DesugaringKind, ExpnKind, ForLoopLoc, MultiSpan, Span, DUMMY_SP};
use rustc_target::spec::abi;
use std::fmt;

use super::InferCtxtPrivExt;
use crate::infer::InferCtxtExt as _;
use crate::traits::query::evaluate_obligation::InferCtxtExt as _;
use rustc_middle::ty::print::with_no_trimmed_paths;

#[derive(Debug)]
pub enum GeneratorInteriorOrUpvar {
    // span of interior type
    Interior(Span),
    // span of upvar
    Upvar(Span),
}

// This trait is public to expose the diagnostics methods to clippy.
pub trait InferCtxtExt<'tcx> {
    fn suggest_restricting_param_bound(
        &self,
        err: &mut DiagnosticBuilder<'_>,
        trait_ref: ty::PolyTraitRef<'tcx>,
        body_id: hir::HirId,
    );

    fn suggest_dereferences(
        &self,
        obligation: &PredicateObligation<'tcx>,
        err: &mut DiagnosticBuilder<'tcx>,
        trait_ref: ty::PolyTraitRef<'tcx>,
    );

    fn get_closure_name(
        &self,
        def_id: DefId,
        err: &mut DiagnosticBuilder<'_>,
        msg: &str,
    ) -> Option<String>;

    fn suggest_fn_call(
        &self,
        obligation: &PredicateObligation<'tcx>,
        err: &mut DiagnosticBuilder<'_>,
        trait_ref: ty::Binder<'tcx, ty::TraitRef<'tcx>>,
    );

    fn suggest_add_reference_to_arg(
        &self,
        obligation: &PredicateObligation<'tcx>,
        err: &mut DiagnosticBuilder<'_>,
        trait_ref: &ty::Binder<'tcx, ty::TraitRef<'tcx>>,
        has_custom_message: bool,
    ) -> bool;

    fn suggest_remove_reference(
        &self,
        obligation: &PredicateObligation<'tcx>,
        err: &mut DiagnosticBuilder<'_>,
        trait_ref: ty::Binder<'tcx, ty::TraitRef<'tcx>>,
    );

    fn suggest_change_mut(
        &self,
        obligation: &PredicateObligation<'tcx>,
        err: &mut DiagnosticBuilder<'_>,
        trait_ref: ty::Binder<'tcx, ty::TraitRef<'tcx>>,
    );

    fn suggest_semicolon_removal(
        &self,
        obligation: &PredicateObligation<'tcx>,
        err: &mut DiagnosticBuilder<'_>,
        span: Span,
        trait_ref: ty::Binder<'tcx, ty::TraitRef<'tcx>>,
    );

    fn return_type_span(&self, obligation: &PredicateObligation<'tcx>) -> Option<Span>;

    fn suggest_impl_trait(
        &self,
        err: &mut DiagnosticBuilder<'_>,
        span: Span,
        obligation: &PredicateObligation<'tcx>,
        trait_ref: ty::Binder<'tcx, ty::TraitRef<'tcx>>,
    ) -> bool;

    fn point_at_returns_when_relevant(
        &self,
        err: &mut DiagnosticBuilder<'_>,
        obligation: &PredicateObligation<'tcx>,
    );

    fn report_closure_arg_mismatch(
        &self,
        span: Span,
        found_span: Option<Span>,
        expected_ref: ty::PolyTraitRef<'tcx>,
        found: ty::PolyTraitRef<'tcx>,
    ) -> DiagnosticBuilder<'tcx>;

    fn suggest_fully_qualified_path(
        &self,
        err: &mut DiagnosticBuilder<'_>,
        def_id: DefId,
        span: Span,
        trait_ref: DefId,
    );

    fn maybe_note_obligation_cause_for_async_await(
        &self,
        err: &mut DiagnosticBuilder<'_>,
        obligation: &PredicateObligation<'tcx>,
    ) -> bool;

    fn note_obligation_cause_for_async_await(
        &self,
        err: &mut DiagnosticBuilder<'_>,
        interior_or_upvar_span: GeneratorInteriorOrUpvar,
        interior_extra_info: Option<(Option<Span>, Span, Option<hir::HirId>, Option<Span>)>,
        inner_generator_body: Option<&hir::Body<'tcx>>,
        outer_generator: Option<DefId>,
        trait_ref: ty::TraitRef<'tcx>,
        target_ty: Ty<'tcx>,
        typeck_results: &ty::TypeckResults<'tcx>,
        obligation: &PredicateObligation<'tcx>,
        next_code: Option<&ObligationCauseCode<'tcx>>,
    );

    fn note_obligation_cause_code<T>(
        &self,
        err: &mut DiagnosticBuilder<'_>,
        predicate: &T,
        cause_code: &ObligationCauseCode<'tcx>,
        obligated_types: &mut Vec<&ty::TyS<'tcx>>,
        seen_requirements: &mut FxHashSet<DefId>,
    ) where
        T: fmt::Display;

    fn suggest_new_overflow_limit(&self, err: &mut DiagnosticBuilder<'_>);

    /// Suggest to await before try: future? => future.await?
    fn suggest_await_before_try(
        &self,
        err: &mut DiagnosticBuilder<'_>,
        obligation: &PredicateObligation<'tcx>,
        trait_ref: ty::Binder<'tcx, ty::TraitRef<'tcx>>,
        span: Span,
    );
}

fn predicate_constraint(generics: &hir::Generics<'_>, pred: String) -> (Span, String) {
    (
        generics.where_clause.tail_span_for_suggestion(),
        format!(
            "{} {}",
            if !generics.where_clause.predicates.is_empty() { "," } else { " where" },
            pred,
        ),
    )
}

/// Type parameter needs more bounds. The trivial case is `T` `where T: Bound`, but
/// it can also be an `impl Trait` param that needs to be decomposed to a type
/// param for cleaner code.
fn suggest_restriction(
    tcx: TyCtxt<'tcx>,
    generics: &hir::Generics<'tcx>,
    msg: &str,
    err: &mut DiagnosticBuilder<'_>,
    fn_sig: Option<&hir::FnSig<'_>>,
    projection: Option<&ty::ProjectionTy<'_>>,
    trait_ref: ty::PolyTraitRef<'tcx>,
    super_traits: Option<(&Ident, &hir::GenericBounds<'_>)>,
) {
    // When we are dealing with a trait, `super_traits` will be `Some`:
    // Given `trait T: A + B + C {}`
    //              -  ^^^^^^^^^ GenericBounds
    //              |
    //              &Ident
    let span = generics.where_clause.span_for_predicates_or_empty_place();
    if span.from_expansion() || span.desugaring_kind().is_some() {
        return;
    }
    // Given `fn foo(t: impl Trait)` where `Trait` requires assoc type `A`...
    if let Some((bound_str, fn_sig)) =
        fn_sig.zip(projection).and_then(|(sig, p)| match p.self_ty().kind() {
            // Shenanigans to get the `Trait` from the `impl Trait`.
            ty::Param(param) => {
                // `fn foo(t: impl Trait)`
                //                 ^^^^^ get this string
                param.name.as_str().strip_prefix("impl").map(|s| (s.trim_start().to_string(), sig))
            }
            _ => None,
        })
    {
        // We know we have an `impl Trait` that doesn't satisfy a required projection.

        // Find all of the ocurrences of `impl Trait` for `Trait` in the function arguments'
        // types. There should be at least one, but there might be *more* than one. In that
        // case we could just ignore it and try to identify which one needs the restriction,
        // but instead we choose to suggest replacing all instances of `impl Trait` with `T`
        // where `T: Trait`.
        let mut ty_spans = vec![];
        let impl_trait_str = format!("impl {}", bound_str);
        for input in fn_sig.decl.inputs {
            if let hir::TyKind::Path(hir::QPath::Resolved(
                None,
                hir::Path { segments: [segment], .. },
            )) = input.kind
            {
                if segment.ident.as_str() == impl_trait_str.as_str() {
                    // `fn foo(t: impl Trait)`
                    //            ^^^^^^^^^^ get this to suggest `T` instead

                    // There might be more than one `impl Trait`.
                    ty_spans.push(input.span);
                }
            }
        }

        let type_param_name = generics.params.next_type_param_name(Some(&bound_str));
        // The type param `T: Trait` we will suggest to introduce.
        let type_param = format!("{}: {}", type_param_name, bound_str);

        // FIXME: modify the `trait_ref` instead of string shenanigans.
        // Turn `<impl Trait as Foo>::Bar: Qux` into `<T as Foo>::Bar: Qux`.
        let pred = trait_ref.without_const().to_predicate(tcx).to_string();
        let pred = pred.replace(&impl_trait_str, &type_param_name);
        let mut sugg = vec![
            // Find the last of the generic parameters contained within the span of
            // the generics
            match generics
                .params
                .iter()
                .map(|p| p.bounds_span().unwrap_or(p.span))
                .filter(|&span| generics.span.contains(span) && span.desugaring_kind().is_none())
                .max_by_key(|span| span.hi())
            {
                // `fn foo(t: impl Trait)`
                //        ^ suggest `<T: Trait>` here
                None => (generics.span, format!("<{}>", type_param)),
                // `fn foo<A>(t: impl Trait)`
                //        ^^^ suggest `<A, T: Trait>` here
                Some(span) => (span.shrink_to_hi(), format!(", {}", type_param)),
            },
            // `fn foo(t: impl Trait)`
            //                       ^ suggest `where <T as Trait>::A: Bound`
            predicate_constraint(generics, pred),
        ];
        sugg.extend(ty_spans.into_iter().map(|s| (s, type_param_name.to_string())));

        // Suggest `fn foo<T: Trait>(t: T) where <T as Trait>::A: Bound`.
        // FIXME: once `#![feature(associated_type_bounds)]` is stabilized, we should suggest
        // `fn foo(t: impl Trait<A: Bound>)` instead.
        err.multipart_suggestion(
            "introduce a type parameter with a trait bound instead of using `impl Trait`",
            sugg,
            Applicability::MaybeIncorrect,
        );
    } else {
        // Trivial case: `T` needs an extra bound: `T: Bound`.
        let (sp, suggestion) = match (
            generics.params.iter().find(|p| {
                !matches!(p.kind, hir::GenericParamKind::Type { synthetic: Some(_), .. })
            }),
            super_traits,
        ) {
            (_, None) => predicate_constraint(
                generics,
                trait_ref.without_const().to_predicate(tcx).to_string(),
            ),
            (None, Some((ident, []))) => (
                ident.span.shrink_to_hi(),
                format!(": {}", trait_ref.print_only_trait_path().to_string()),
            ),
            (_, Some((_, [.., bounds]))) => (
                bounds.span().shrink_to_hi(),
                format!(" + {}", trait_ref.print_only_trait_path().to_string()),
            ),
            (Some(_), Some((_, []))) => (
                generics.span.shrink_to_hi(),
                format!(": {}", trait_ref.print_only_trait_path().to_string()),
            ),
        };

        err.span_suggestion_verbose(
            sp,
            &format!("consider further restricting {}", msg),
            suggestion,
            Applicability::MachineApplicable,
        );
    }
}

impl<'a, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'a, 'tcx> {
    fn suggest_restricting_param_bound(
        &self,
        mut err: &mut DiagnosticBuilder<'_>,
        trait_ref: ty::PolyTraitRef<'tcx>,
        body_id: hir::HirId,
    ) {
        let self_ty = trait_ref.skip_binder().self_ty();
        let (param_ty, projection) = match self_ty.kind() {
            ty::Param(_) => (true, None),
            ty::Projection(projection) => (false, Some(projection)),
            _ => (false, None),
        };

        // FIXME: Add check for trait bound that is already present, particularly `?Sized` so we
        //        don't suggest `T: Sized + ?Sized`.
        let mut hir_id = body_id;
        while let Some(node) = self.tcx.hir().find(hir_id) {
            match node {
                hir::Node::Item(hir::Item {
                    ident,
                    kind: hir::ItemKind::Trait(_, _, generics, bounds, _),
                    ..
                }) if self_ty == self.tcx.types.self_param => {
                    assert!(param_ty);
                    // Restricting `Self` for a single method.
                    suggest_restriction(
                        self.tcx,
                        &generics,
                        "`Self`",
                        err,
                        None,
                        projection,
                        trait_ref,
                        Some((ident, bounds)),
                    );
                    return;
                }

                hir::Node::TraitItem(hir::TraitItem {
                    generics,
                    kind: hir::TraitItemKind::Fn(..),
                    ..
                }) if self_ty == self.tcx.types.self_param => {
                    assert!(param_ty);
                    // Restricting `Self` for a single method.
                    suggest_restriction(
                        self.tcx, &generics, "`Self`", err, None, projection, trait_ref, None,
                    );
                    return;
                }

                hir::Node::TraitItem(hir::TraitItem {
                    generics,
                    kind: hir::TraitItemKind::Fn(fn_sig, ..),
                    ..
                })
                | hir::Node::ImplItem(hir::ImplItem {
                    generics,
                    kind: hir::ImplItemKind::Fn(fn_sig, ..),
                    ..
                })
                | hir::Node::Item(hir::Item {
                    kind: hir::ItemKind::Fn(fn_sig, generics, _), ..
                }) if projection.is_some() => {
                    // Missing restriction on associated type of type parameter (unmet projection).
                    suggest_restriction(
                        self.tcx,
                        &generics,
                        "the associated type",
                        err,
                        Some(fn_sig),
                        projection,
                        trait_ref,
                        None,
                    );
                    return;
                }
                hir::Node::Item(hir::Item {
                    kind:
                        hir::ItemKind::Trait(_, _, generics, _, _)
                        | hir::ItemKind::Impl(hir::Impl { generics, .. }),
                    ..
                }) if projection.is_some() => {
                    // Missing restriction on associated type of type parameter (unmet projection).
                    suggest_restriction(
                        self.tcx,
                        &generics,
                        "the associated type",
                        err,
                        None,
                        projection,
                        trait_ref,
                        None,
                    );
                    return;
                }

                hir::Node::Item(hir::Item {
                    kind:
                        hir::ItemKind::Struct(_, generics)
                        | hir::ItemKind::Enum(_, generics)
                        | hir::ItemKind::Union(_, generics)
                        | hir::ItemKind::Trait(_, _, generics, ..)
                        | hir::ItemKind::Impl(hir::Impl { generics, .. })
                        | hir::ItemKind::Fn(_, generics, _)
                        | hir::ItemKind::TyAlias(_, generics)
                        | hir::ItemKind::TraitAlias(generics, _)
                        | hir::ItemKind::OpaqueTy(hir::OpaqueTy { generics, .. }),
                    ..
                })
                | hir::Node::TraitItem(hir::TraitItem { generics, .. })
                | hir::Node::ImplItem(hir::ImplItem { generics, .. })
                    if param_ty =>
                {
                    // Missing generic type parameter bound.
                    let param_name = self_ty.to_string();
                    let constraint =
                        with_no_trimmed_paths(|| trait_ref.print_only_trait_path().to_string());
                    if suggest_constraining_type_param(
                        self.tcx,
                        generics,
                        &mut err,
                        &param_name,
                        &constraint,
                        Some(trait_ref.def_id()),
                    ) {
                        return;
                    }
                }

                hir::Node::Item(hir::Item {
                    kind:
                        hir::ItemKind::Struct(_, generics)
                        | hir::ItemKind::Enum(_, generics)
                        | hir::ItemKind::Union(_, generics)
                        | hir::ItemKind::Trait(_, _, generics, ..)
                        | hir::ItemKind::Impl(hir::Impl { generics, .. })
                        | hir::ItemKind::Fn(_, generics, _)
                        | hir::ItemKind::TyAlias(_, generics)
                        | hir::ItemKind::TraitAlias(generics, _)
                        | hir::ItemKind::OpaqueTy(hir::OpaqueTy { generics, .. }),
                    ..
                }) if !param_ty => {
                    // Missing generic type parameter bound.
                    let param_name = self_ty.to_string();
                    let constraint = trait_ref.print_only_trait_path().to_string();
                    if suggest_arbitrary_trait_bound(generics, &mut err, &param_name, &constraint) {
                        return;
                    }
                }
                hir::Node::Crate(..) => return,

                _ => {}
            }

            hir_id = self.tcx.hir().get_parent_item(hir_id);
        }
    }

    /// When after several dereferencing, the reference satisfies the trait
    /// binding. This function provides dereference suggestion for this
    /// specific situation.
    fn suggest_dereferences(
        &self,
        obligation: &PredicateObligation<'tcx>,
        err: &mut DiagnosticBuilder<'tcx>,
        trait_ref: ty::PolyTraitRef<'tcx>,
    ) {
        // It only make sense when suggesting dereferences for arguments
        let code = if let ObligationCauseCode::FunctionArgumentObligation { parent_code, .. } =
            &obligation.cause.code
        {
            parent_code.clone()
        } else {
            return;
        };
        let param_env = obligation.param_env;
        let body_id = obligation.cause.body_id;
        let span = obligation.cause.span;
        let real_trait_ref = match &*code {
            ObligationCauseCode::ImplDerivedObligation(cause)
            | ObligationCauseCode::DerivedObligation(cause)
            | ObligationCauseCode::BuiltinDerivedObligation(cause) => cause.parent_trait_ref,
            _ => trait_ref,
        };
        let real_ty = match real_trait_ref.self_ty().no_bound_vars() {
            Some(ty) => ty,
            None => return,
        };

        if let ty::Ref(region, base_ty, mutbl) = *real_ty.kind() {
            let mut autoderef = Autoderef::new(self, param_env, body_id, span, base_ty, span);
            if let Some(steps) = autoderef.find_map(|(ty, steps)| {
                // Re-add the `&`
                let ty = self.tcx.mk_ref(region, TypeAndMut { ty, mutbl });
                let obligation =
                    self.mk_trait_obligation_with_new_self_ty(param_env, real_trait_ref, ty);
                Some(steps).filter(|_| self.predicate_may_hold(&obligation))
            }) {
                if steps > 0 {
                    if let Ok(src) = self.tcx.sess.source_map().span_to_snippet(span) {
                        // Don't care about `&mut` because `DerefMut` is used less
                        // often and user will not expect autoderef happens.
                        if src.starts_with('&') && !src.starts_with("&mut ") {
                            let derefs = "*".repeat(steps);
                            err.span_suggestion(
                                span,
                                "consider adding dereference here",
                                format!("&{}{}", derefs, &src[1..]),
                                Applicability::MachineApplicable,
                            );
                        }
                    }
                }
            }
        }
    }

    /// Given a closure's `DefId`, return the given name of the closure.
    ///
    /// This doesn't account for reassignments, but it's only used for suggestions.
    fn get_closure_name(
        &self,
        def_id: DefId,
        err: &mut DiagnosticBuilder<'_>,
        msg: &str,
    ) -> Option<String> {
        let get_name =
            |err: &mut DiagnosticBuilder<'_>, kind: &hir::PatKind<'_>| -> Option<String> {
                // Get the local name of this closure. This can be inaccurate because
                // of the possibility of reassignment, but this should be good enough.
                match &kind {
                    hir::PatKind::Binding(hir::BindingAnnotation::Unannotated, _, name, None) => {
                        Some(format!("{}", name))
                    }
                    _ => {
                        err.note(&msg);
                        None
                    }
                }
            };

        let hir = self.tcx.hir();
        let hir_id = hir.local_def_id_to_hir_id(def_id.as_local()?);
        let parent_node = hir.get_parent_node(hir_id);
        match hir.find(parent_node) {
            Some(hir::Node::Stmt(hir::Stmt { kind: hir::StmtKind::Local(local), .. })) => {
                get_name(err, &local.pat.kind)
            }
            // Different to previous arm because one is `&hir::Local` and the other
            // is `P<hir::Local>`.
            Some(hir::Node::Local(local)) => get_name(err, &local.pat.kind),
            _ => None,
        }
    }

    /// We tried to apply the bound to an `fn` or closure. Check whether calling it would
    /// evaluate to a type that *would* satisfy the trait binding. If it would, suggest calling
    /// it: `bar(foo)` → `bar(foo())`. This case is *very* likely to be hit if `foo` is `async`.
    fn suggest_fn_call(
        &self,
        obligation: &PredicateObligation<'tcx>,
        err: &mut DiagnosticBuilder<'_>,
        trait_ref: ty::Binder<'tcx, ty::TraitRef<'tcx>>,
    ) {
        let self_ty = match trait_ref.self_ty().no_bound_vars() {
            None => return,
            Some(ty) => ty,
        };

        let (def_id, output_ty, callable) = match *self_ty.kind() {
            ty::Closure(def_id, substs) => (def_id, substs.as_closure().sig().output(), "closure"),
            ty::FnDef(def_id, _) => (def_id, self_ty.fn_sig(self.tcx).output(), "function"),
            _ => return,
        };
        let msg = format!("use parentheses to call the {}", callable);

        // `mk_trait_obligation_with_new_self_ty` only works for types with no escaping bound
        // variables, so bail out if we have any.
        let output_ty = match output_ty.no_bound_vars() {
            Some(ty) => ty,
            None => return,
        };

        let new_obligation =
            self.mk_trait_obligation_with_new_self_ty(obligation.param_env, trait_ref, output_ty);

        match self.evaluate_obligation(&new_obligation) {
            Ok(
                EvaluationResult::EvaluatedToOk
                | EvaluationResult::EvaluatedToOkModuloRegions
                | EvaluationResult::EvaluatedToAmbig,
            ) => {}
            _ => return,
        }
        let hir = self.tcx.hir();
        // Get the name of the callable and the arguments to be used in the suggestion.
        let (snippet, sugg) = match hir.get_if_local(def_id) {
            Some(hir::Node::Expr(hir::Expr {
                kind: hir::ExprKind::Closure(_, decl, _, span, ..),
                ..
            })) => {
                err.span_label(*span, "consider calling this closure");
                let name = match self.get_closure_name(def_id, err, &msg) {
                    Some(name) => name,
                    None => return,
                };
                let args = decl.inputs.iter().map(|_| "_").collect::<Vec<_>>().join(", ");
                let sugg = format!("({})", args);
                (format!("{}{}", name, sugg), sugg)
            }
            Some(hir::Node::Item(hir::Item {
                ident,
                kind: hir::ItemKind::Fn(.., body_id),
                ..
            })) => {
                err.span_label(ident.span, "consider calling this function");
                let body = hir.body(*body_id);
                let args = body
                    .params
                    .iter()
                    .map(|arg| match &arg.pat.kind {
                        hir::PatKind::Binding(_, _, ident, None)
                        // FIXME: provide a better suggestion when encountering `SelfLower`, it
                        // should suggest a method call.
                        if ident.name != kw::SelfLower => ident.to_string(),
                        _ => "_".to_string(),
                    })
                    .collect::<Vec<_>>()
                    .join(", ");
                let sugg = format!("({})", args);
                (format!("{}{}", ident, sugg), sugg)
            }
            _ => return,
        };
        if matches!(obligation.cause.code, ObligationCauseCode::FunctionArgumentObligation { .. }) {
            // When the obligation error has been ensured to have been caused by
            // an argument, the `obligation.cause.span` points at the expression
            // of the argument, so we can provide a suggestion. Otherwise, we give
            // a more general note.
            err.span_suggestion_verbose(
                obligation.cause.span.shrink_to_hi(),
                &msg,
                sugg,
                Applicability::HasPlaceholders,
            );
        } else {
            err.help(&format!("{}: `{}`", msg, snippet));
        }
    }

    fn suggest_add_reference_to_arg(
        &self,
        obligation: &PredicateObligation<'tcx>,
        err: &mut DiagnosticBuilder<'_>,
        poly_trait_ref: &ty::Binder<'tcx, ty::TraitRef<'tcx>>,
        has_custom_message: bool,
    ) -> bool {
        let span = obligation.cause.span;

        let code = if let ObligationCauseCode::FunctionArgumentObligation { parent_code, .. } =
            &obligation.cause.code
        {
            parent_code.clone()
        } else if let ExpnKind::Desugaring(DesugaringKind::ForLoop(ForLoopLoc::IntoIter)) =
            span.ctxt().outer_expn_data().kind
        {
            Lrc::new(obligation.cause.code.clone())
        } else {
            return false;
        };

        // List of traits for which it would be nonsensical to suggest borrowing.
        // For instance, immutable references are always Copy, so suggesting to
        // borrow would always succeed, but it's probably not what the user wanted.
        let mut never_suggest_borrow: Vec<_> =
            [LangItem::Copy, LangItem::Clone, LangItem::Unpin, LangItem::Sized]
                .iter()
                .filter_map(|lang_item| self.tcx.lang_items().require(*lang_item).ok())
                .collect();

        if let Some(def_id) = self.tcx.get_diagnostic_item(sym::Send) {
            never_suggest_borrow.push(def_id);
        }

        let param_env = obligation.param_env;
        let trait_ref = poly_trait_ref.skip_binder();

        let found_ty = trait_ref.self_ty();
        let found_ty_str = found_ty.to_string();
        let imm_borrowed_found_ty = self.tcx.mk_imm_ref(self.tcx.lifetimes.re_static, found_ty);
        let imm_substs = self.tcx.mk_substs_trait(imm_borrowed_found_ty, &[]);
        let mut_borrowed_found_ty = self.tcx.mk_mut_ref(self.tcx.lifetimes.re_static, found_ty);
        let mut_substs = self.tcx.mk_substs_trait(mut_borrowed_found_ty, &[]);

        // Try to apply the original trait binding obligation by borrowing.
        let mut try_borrowing = |new_imm_trait_ref: ty::Binder<'tcx, ty::TraitRef<'tcx>>,
                                 new_mut_trait_ref: ty::Binder<'tcx, ty::TraitRef<'tcx>>,
                                 expected_trait_ref: ty::Binder<'tcx, ty::TraitRef<'tcx>>,
                                 blacklist: &[DefId]|
         -> bool {
            if blacklist.contains(&expected_trait_ref.def_id()) {
                return false;
            }

            let imm_result = self.predicate_must_hold_modulo_regions(&Obligation::new(
                ObligationCause::dummy(),
                param_env,
                new_imm_trait_ref.without_const().to_predicate(self.tcx),
            ));

            let mut_result = self.predicate_must_hold_modulo_regions(&Obligation::new(
                ObligationCause::dummy(),
                param_env,
                new_mut_trait_ref.without_const().to_predicate(self.tcx),
            ));

            if imm_result || mut_result {
                if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
                    // We have a very specific type of error, where just borrowing this argument
                    // might solve the problem. In cases like this, the important part is the
                    // original type obligation, not the last one that failed, which is arbitrary.
                    // Because of this, we modify the error to refer to the original obligation and
                    // return early in the caller.

                    let msg = format!(
                        "the trait bound `{}: {}` is not satisfied",
                        found_ty_str,
                        expected_trait_ref.print_only_trait_path(),
                    );
                    if has_custom_message {
                        err.note(&msg);
                    } else {
                        err.message = vec![(msg, Style::NoStyle)];
                    }
                    if snippet.starts_with('&') {
                        // This is already a literal borrow and the obligation is failing
                        // somewhere else in the obligation chain. Do not suggest non-sense.
                        return false;
                    }
                    err.span_label(
                        span,
                        &format!(
                            "expected an implementor of trait `{}`",
                            expected_trait_ref.print_only_trait_path(),
                        ),
                    );

                    // This if is to prevent a special edge-case
                    if matches!(
                        span.ctxt().outer_expn_data().kind,
                        ExpnKind::Root
                            | ExpnKind::Desugaring(DesugaringKind::ForLoop(ForLoopLoc::IntoIter))
                    ) {
                        // We don't want a borrowing suggestion on the fields in structs,
                        // ```
                        // struct Foo {
                        //  the_foos: Vec<Foo>
                        // }
                        // ```

                        if imm_result && mut_result {
                            err.span_suggestions(
                                span.shrink_to_lo(),
                                "consider borrowing here",
                                ["&".to_string(), "&mut ".to_string()].into_iter(),
                                Applicability::MaybeIncorrect,
                            );
                        } else {
                            err.span_suggestion_verbose(
                                span.shrink_to_lo(),
                                &format!(
                                    "consider{} borrowing here",
                                    if mut_result { " mutably" } else { "" }
                                ),
                                format!("&{}", if mut_result { "mut " } else { "" }),
                                Applicability::MaybeIncorrect,
                            );
                        }
                    }
                    return true;
                }
            }
            return false;
        };

        if let ObligationCauseCode::ImplDerivedObligation(obligation) = &*code {
            let expected_trait_ref = obligation.parent_trait_ref;
            let new_imm_trait_ref = poly_trait_ref
                .rebind(ty::TraitRef::new(obligation.parent_trait_ref.def_id(), imm_substs));
            let new_mut_trait_ref = poly_trait_ref
                .rebind(ty::TraitRef::new(obligation.parent_trait_ref.def_id(), mut_substs));
            return try_borrowing(new_imm_trait_ref, new_mut_trait_ref, expected_trait_ref, &[]);
        } else if let ObligationCauseCode::BindingObligation(_, _)
        | ObligationCauseCode::ItemObligation(_) = &*code
        {
            return try_borrowing(
                poly_trait_ref.rebind(ty::TraitRef::new(trait_ref.def_id, imm_substs)),
                poly_trait_ref.rebind(ty::TraitRef::new(trait_ref.def_id, mut_substs)),
                *poly_trait_ref,
                &never_suggest_borrow[..],
            );
        } else {
            false
        }
    }

    /// Whenever references are used by mistake, like `for (i, e) in &vec.iter().enumerate()`,
    /// suggest removing these references until we reach a type that implements the trait.
    fn suggest_remove_reference(
        &self,
        obligation: &PredicateObligation<'tcx>,
        err: &mut DiagnosticBuilder<'_>,
        trait_ref: ty::Binder<'tcx, ty::TraitRef<'tcx>>,
    ) {
        let span = obligation.cause.span;

        if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
            let refs_number =
                snippet.chars().filter(|c| !c.is_whitespace()).take_while(|c| *c == '&').count();
            if let Some('\'') = snippet.chars().filter(|c| !c.is_whitespace()).nth(refs_number) {
                // Do not suggest removal of borrow from type arguments.
                return;
            }

            let mut suggested_ty = match trait_ref.self_ty().no_bound_vars() {
                Some(ty) => ty,
                None => return,
            };

            for refs_remaining in 0..refs_number {
                if let ty::Ref(_, inner_ty, _) = suggested_ty.kind() {
                    suggested_ty = inner_ty;

                    let new_obligation = self.mk_trait_obligation_with_new_self_ty(
                        obligation.param_env,
                        trait_ref,
                        suggested_ty,
                    );

                    if self.predicate_may_hold(&new_obligation) {
                        let sp = self
                            .tcx
                            .sess
                            .source_map()
                            .span_take_while(span, |c| c.is_whitespace() || *c == '&');

                        let remove_refs = refs_remaining + 1;

                        let msg = if remove_refs == 1 {
                            "consider removing the leading `&`-reference".to_string()
                        } else {
                            format!("consider removing {} leading `&`-references", remove_refs)
                        };

                        err.span_suggestion_short(
                            sp,
                            &msg,
                            String::new(),
                            Applicability::MachineApplicable,
                        );
                        break;
                    }
                } else {
                    break;
                }
            }
        }
    }

    /// Check if the trait bound is implemented for a different mutability and note it in the
    /// final error.
    fn suggest_change_mut(
        &self,
        obligation: &PredicateObligation<'tcx>,
        err: &mut DiagnosticBuilder<'_>,
        trait_ref: ty::Binder<'tcx, ty::TraitRef<'tcx>>,
    ) {
        let points_at_arg = matches!(
            obligation.cause.code,
            ObligationCauseCode::FunctionArgumentObligation { .. },
        );

        let span = obligation.cause.span;
        if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
            let refs_number =
                snippet.chars().filter(|c| !c.is_whitespace()).take_while(|c| *c == '&').count();
            if let Some('\'') = snippet.chars().filter(|c| !c.is_whitespace()).nth(refs_number) {
                // Do not suggest removal of borrow from type arguments.
                return;
            }
            let trait_ref = self.resolve_vars_if_possible(trait_ref);
            if trait_ref.has_infer_types_or_consts() {
                // Do not ICE while trying to find if a reborrow would succeed on a trait with
                // unresolved bindings.
                return;
            }

            if let ty::Ref(region, t_type, mutability) = *trait_ref.skip_binder().self_ty().kind() {
                if region.is_late_bound() || t_type.has_escaping_bound_vars() {
                    // Avoid debug assertion in `mk_obligation_for_def_id`.
                    //
                    // If the self type has escaping bound vars then it's not
                    // going to be the type of an expression, so the suggestion
                    // probably won't apply anyway.
                    return;
                }

                let suggested_ty = match mutability {
                    hir::Mutability::Mut => self.tcx.mk_imm_ref(region, t_type),
                    hir::Mutability::Not => self.tcx.mk_mut_ref(region, t_type),
                };

                let new_obligation = self.mk_trait_obligation_with_new_self_ty(
                    obligation.param_env,
                    trait_ref,
                    suggested_ty,
                );
                let suggested_ty_would_satisfy_obligation = self
                    .evaluate_obligation_no_overflow(&new_obligation)
                    .must_apply_modulo_regions();
                if suggested_ty_would_satisfy_obligation {
                    let sp = self
                        .tcx
                        .sess
                        .source_map()
                        .span_take_while(span, |c| c.is_whitespace() || *c == '&');
                    if points_at_arg && mutability == hir::Mutability::Not && refs_number > 0 {
                        err.span_suggestion_verbose(
                            sp,
                            "consider changing this borrow's mutability",
                            "&mut ".to_string(),
                            Applicability::MachineApplicable,
                        );
                    } else {
                        err.note(&format!(
                            "`{}` is implemented for `{:?}`, but not for `{:?}`",
                            trait_ref.print_only_trait_path(),
                            suggested_ty,
                            trait_ref.skip_binder().self_ty(),
                        ));
                    }
                }
            }
        }
    }

    fn suggest_semicolon_removal(
        &self,
        obligation: &PredicateObligation<'tcx>,
        err: &mut DiagnosticBuilder<'_>,
        span: Span,
        trait_ref: ty::Binder<'tcx, ty::TraitRef<'tcx>>,
    ) {
        let is_empty_tuple =
            |ty: ty::Binder<'tcx, Ty<'_>>| *ty.skip_binder().kind() == ty::Tuple(ty::List::empty());

        let hir = self.tcx.hir();
        let parent_node = hir.get_parent_node(obligation.cause.body_id);
        let node = hir.find(parent_node);
        if let Some(hir::Node::Item(hir::Item {
            kind: hir::ItemKind::Fn(sig, _, body_id), ..
        })) = node
        {
            let body = hir.body(*body_id);
            if let hir::ExprKind::Block(blk, _) = &body.value.kind {
                if sig.decl.output.span().overlaps(span)
                    && blk.expr.is_none()
                    && is_empty_tuple(trait_ref.self_ty())
                {
                    // FIXME(estebank): When encountering a method with a trait
                    // bound not satisfied in the return type with a body that has
                    // no return, suggest removal of semicolon on last statement.
                    // Once that is added, close #54771.
                    if let Some(ref stmt) = blk.stmts.last() {
                        if let hir::StmtKind::Semi(_) = stmt.kind {
                            let sp = self.tcx.sess.source_map().end_point(stmt.span);
                            err.span_label(sp, "consider removing this semicolon");
                        }
                    }
                }
            }
        }
    }

    fn return_type_span(&self, obligation: &PredicateObligation<'tcx>) -> Option<Span> {
        let hir = self.tcx.hir();
        let parent_node = hir.get_parent_node(obligation.cause.body_id);
        let sig = match hir.find(parent_node) {
            Some(hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn(sig, ..), .. })) => sig,
            _ => return None,
        };

        if let hir::FnRetTy::Return(ret_ty) = sig.decl.output { Some(ret_ty.span) } else { None }
    }

    /// If all conditions are met to identify a returned `dyn Trait`, suggest using `impl Trait` if
    /// applicable and signal that the error has been expanded appropriately and needs to be
    /// emitted.
    fn suggest_impl_trait(
        &self,
        err: &mut DiagnosticBuilder<'_>,
        span: Span,
        obligation: &PredicateObligation<'tcx>,
        trait_ref: ty::Binder<'tcx, ty::TraitRef<'tcx>>,
    ) -> bool {
        match obligation.cause.code.peel_derives() {
            // Only suggest `impl Trait` if the return type is unsized because it is `dyn Trait`.
            ObligationCauseCode::SizedReturnType => {}
            _ => return false,
        }

        let hir = self.tcx.hir();
        let parent_node = hir.get_parent_node(obligation.cause.body_id);
        let node = hir.find(parent_node);
        let Some(hir::Node::Item(hir::Item {
            kind: hir::ItemKind::Fn(sig, _, body_id),
            ..
        })) = node
        else {
            return false;
        };
        let body = hir.body(*body_id);
        let trait_ref = self.resolve_vars_if_possible(trait_ref);
        let ty = trait_ref.skip_binder().self_ty();
        let is_object_safe = match ty.kind() {
            ty::Dynamic(predicates, _) => {
                // If the `dyn Trait` is not object safe, do not suggest `Box<dyn Trait>`.
                predicates
                    .principal_def_id()
                    .map_or(true, |def_id| self.tcx.object_safety_violations(def_id).is_empty())
            }
            // We only want to suggest `impl Trait` to `dyn Trait`s.
            // For example, `fn foo() -> str` needs to be filtered out.
            _ => return false,
        };

        let ret_ty = if let hir::FnRetTy::Return(ret_ty) = sig.decl.output {
            ret_ty
        } else {
            return false;
        };

        // Use `TypeVisitor` instead of the output type directly to find the span of `ty` for
        // cases like `fn foo() -> (dyn Trait, i32) {}`.
        // Recursively look for `TraitObject` types and if there's only one, use that span to
        // suggest `impl Trait`.

        // Visit to make sure there's a single `return` type to suggest `impl Trait`,
        // otherwise suggest using `Box<dyn Trait>` or an enum.
        let mut visitor = ReturnsVisitor::default();
        visitor.visit_body(&body);

        let typeck_results = self.in_progress_typeck_results.map(|t| t.borrow()).unwrap();

        let mut ret_types = visitor
            .returns
            .iter()
            .filter_map(|expr| typeck_results.node_type_opt(expr.hir_id))
            .map(|ty| self.resolve_vars_if_possible(ty));
        let (last_ty, all_returns_have_same_type, only_never_return) = ret_types.clone().fold(
            (None, true, true),
            |(last_ty, mut same, only_never_return): (std::option::Option<Ty<'_>>, bool, bool),
             ty| {
                let ty = self.resolve_vars_if_possible(ty);
                same &=
                    !matches!(ty.kind(), ty::Error(_))
                        && last_ty.map_or(true, |last_ty| {
                            // FIXME: ideally we would use `can_coerce` here instead, but `typeck` comes
                            // *after* in the dependency graph.
                            match (ty.kind(), last_ty.kind()) {
                                (Infer(InferTy::IntVar(_)), Infer(InferTy::IntVar(_)))
                                | (Infer(InferTy::FloatVar(_)), Infer(InferTy::FloatVar(_)))
                                | (Infer(InferTy::FreshIntTy(_)), Infer(InferTy::FreshIntTy(_)))
                                | (
                                    Infer(InferTy::FreshFloatTy(_)),
                                    Infer(InferTy::FreshFloatTy(_)),
                                ) => true,
                                _ => ty == last_ty,
                            }
                        });
                (Some(ty), same, only_never_return && matches!(ty.kind(), ty::Never))
            },
        );
        let all_returns_conform_to_trait =
            if let Some(ty_ret_ty) = typeck_results.node_type_opt(ret_ty.hir_id) {
                match ty_ret_ty.kind() {
                    ty::Dynamic(predicates, _) => {
                        let cause = ObligationCause::misc(ret_ty.span, ret_ty.hir_id);
                        let param_env = ty::ParamEnv::empty();
                        only_never_return
                            || ret_types.all(|returned_ty| {
                                predicates.iter().all(|predicate| {
                                    let pred = predicate.with_self_ty(self.tcx, returned_ty);
                                    let obl = Obligation::new(cause.clone(), param_env, pred);
                                    self.predicate_may_hold(&obl)
                                })
                            })
                    }
                    _ => false,
                }
            } else {
                true
            };

        let sm = self.tcx.sess.source_map();
        let snippet = if let (true, hir::TyKind::TraitObject(..), Ok(snippet), true) = (
            // Verify that we're dealing with a return `dyn Trait`
            ret_ty.span.overlaps(span),
            &ret_ty.kind,
            sm.span_to_snippet(ret_ty.span),
            // If any of the return types does not conform to the trait, then we can't
            // suggest `impl Trait` nor trait objects: it is a type mismatch error.
            all_returns_conform_to_trait,
        ) {
            snippet
        } else {
            return false;
        };
        err.code(error_code!(E0746));
        err.set_primary_message("return type cannot have an unboxed trait object");
        err.children.clear();
        let impl_trait_msg = "for information on `impl Trait`, see \
            <https://doc.rust-lang.org/book/ch10-02-traits.html\
            #returning-types-that-implement-traits>";
        let trait_obj_msg = "for information on trait objects, see \
            <https://doc.rust-lang.org/book/ch17-02-trait-objects.html\
            #using-trait-objects-that-allow-for-values-of-different-types>";
        let has_dyn = snippet.split_whitespace().next().map_or(false, |s| s == "dyn");
        let trait_obj = if has_dyn { &snippet[4..] } else { &snippet[..] };
        if only_never_return {
            // No return paths, probably using `panic!()` or similar.
            // Suggest `-> T`, `-> impl Trait`, and if `Trait` is object safe, `-> Box<dyn Trait>`.
            suggest_trait_object_return_type_alternatives(
                err,
                ret_ty.span,
                trait_obj,
                is_object_safe,
            );
        } else if let (Some(last_ty), true) = (last_ty, all_returns_have_same_type) {
            // Suggest `-> impl Trait`.
            err.span_suggestion(
                ret_ty.span,
                &format!(
                    "use `impl {1}` as the return type, as all return paths are of type `{}`, \
                     which implements `{1}`",
                    last_ty, trait_obj,
                ),
                format!("impl {}", trait_obj),
                Applicability::MachineApplicable,
            );
            err.note(impl_trait_msg);
        } else {
            if is_object_safe {
                // Suggest `-> Box<dyn Trait>` and `Box::new(returned_value)`.
                // Get all the return values and collect their span and suggestion.
                let mut suggestions: Vec<_> = visitor
                    .returns
                    .iter()
                    .flat_map(|expr| {
                        vec![
                            (expr.span.shrink_to_lo(), "Box::new(".to_string()),
                            (expr.span.shrink_to_hi(), ")".to_string()),
                        ]
                        .into_iter()
                    })
                    .collect();
                if !suggestions.is_empty() {
                    // Add the suggestion for the return type.
                    suggestions.push((ret_ty.span, format!("Box<dyn {}>", trait_obj)));
                    err.multipart_suggestion(
                        "return a boxed trait object instead",
                        suggestions,
                        Applicability::MaybeIncorrect,
                    );
                }
            } else {
                // This is currently not possible to trigger because E0038 takes precedence, but
                // leave it in for completeness in case anything changes in an earlier stage.
                err.note(&format!(
                    "if trait `{}` were object-safe, you could return a trait object",
                    trait_obj,
                ));
            }
            err.note(trait_obj_msg);
            err.note(&format!(
                "if all the returned values were of the same type you could use `impl {}` as the \
                 return type",
                trait_obj,
            ));
            err.note(impl_trait_msg);
            err.note("you can create a new `enum` with a variant for each returned type");
        }
        true
    }

    fn point_at_returns_when_relevant(
        &self,
        err: &mut DiagnosticBuilder<'_>,
        obligation: &PredicateObligation<'tcx>,
    ) {
        match obligation.cause.code.peel_derives() {
            ObligationCauseCode::SizedReturnType => {}
            _ => return,
        }

        let hir = self.tcx.hir();
        let parent_node = hir.get_parent_node(obligation.cause.body_id);
        let node = hir.find(parent_node);
        if let Some(hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn(_, _, body_id), .. })) =
            node
        {
            let body = hir.body(*body_id);
            // Point at all the `return`s in the function as they have failed trait bounds.
            let mut visitor = ReturnsVisitor::default();
            visitor.visit_body(&body);
            let typeck_results = self.in_progress_typeck_results.map(|t| t.borrow()).unwrap();
            for expr in &visitor.returns {
                if let Some(returned_ty) = typeck_results.node_type_opt(expr.hir_id) {
                    let ty = self.resolve_vars_if_possible(returned_ty);
                    err.span_label(expr.span, &format!("this returned value is of type `{}`", ty));
                }
            }
        }
    }

    fn report_closure_arg_mismatch(
        &self,
        span: Span,
        found_span: Option<Span>,
        expected_ref: ty::PolyTraitRef<'tcx>,
        found: ty::PolyTraitRef<'tcx>,
    ) -> DiagnosticBuilder<'tcx> {
        crate fn build_fn_sig_string<'tcx>(
            tcx: TyCtxt<'tcx>,
            trait_ref: ty::PolyTraitRef<'tcx>,
        ) -> String {
            let inputs = trait_ref.skip_binder().substs.type_at(1);
            let sig = match inputs.kind() {
                ty::Tuple(inputs)
                    if tcx.fn_trait_kind_from_lang_item(trait_ref.def_id()).is_some() =>
                {
                    tcx.mk_fn_sig(
                        inputs.iter().map(|k| k.expect_ty()),
                        tcx.mk_ty_infer(ty::TyVar(ty::TyVid::from_u32(0))),
                        false,
                        hir::Unsafety::Normal,
                        abi::Abi::Rust,
                    )
                }
                _ => tcx.mk_fn_sig(
                    std::iter::once(inputs),
                    tcx.mk_ty_infer(ty::TyVar(ty::TyVid::from_u32(0))),
                    false,
                    hir::Unsafety::Normal,
                    abi::Abi::Rust,
                ),
            };
            trait_ref.rebind(sig).to_string()
        }

        let argument_kind = match expected_ref.skip_binder().substs.type_at(0) {
            t if t.is_closure() => "closure",
            t if t.is_generator() => "generator",
            _ => "function",
        };
        let mut err = struct_span_err!(
            self.tcx.sess,
            span,
            E0631,
            "type mismatch in {} arguments",
            argument_kind
        );

        let found_str = format!("expected signature of `{}`", build_fn_sig_string(self.tcx, found));
        err.span_label(span, found_str);

        let found_span = found_span.unwrap_or(span);
        let expected_str =
            format!("found signature of `{}`", build_fn_sig_string(self.tcx, expected_ref));
        err.span_label(found_span, expected_str);

        err
    }

    fn suggest_fully_qualified_path(
        &self,
        err: &mut DiagnosticBuilder<'_>,
        def_id: DefId,
        span: Span,
        trait_ref: DefId,
    ) {
        if let Some(assoc_item) = self.tcx.opt_associated_item(def_id) {
            if let ty::AssocKind::Const | ty::AssocKind::Type = assoc_item.kind {
                err.note(&format!(
                    "{}s cannot be accessed directly on a `trait`, they can only be \
                        accessed through a specific `impl`",
                    assoc_item.kind.as_def_kind().descr(def_id)
                ));
                err.span_suggestion(
                    span,
                    "use the fully qualified path to an implementation",
                    format!("<Type as {}>::{}", self.tcx.def_path_str(trait_ref), assoc_item.ident),
                    Applicability::HasPlaceholders,
                );
            }
        }
    }

    /// Adds an async-await specific note to the diagnostic when the future does not implement
    /// an auto trait because of a captured type.
    ///
    /// ```text
    /// note: future does not implement `Qux` as this value is used across an await
    ///   --> $DIR/issue-64130-3-other.rs:17:5
    ///    |
    /// LL |     let x = Foo;
    ///    |         - has type `Foo`
    /// LL |     baz().await;
    ///    |     ^^^^^^^^^^^ await occurs here, with `x` maybe used later
    /// LL | }
    ///    | - `x` is later dropped here
    /// ```
    ///
    /// When the diagnostic does not implement `Send` or `Sync` specifically, then the diagnostic
    /// is "replaced" with a different message and a more specific error.
    ///
    /// ```text
    /// error: future cannot be sent between threads safely
    ///   --> $DIR/issue-64130-2-send.rs:21:5
    ///    |
    /// LL | fn is_send<T: Send>(t: T) { }
    ///    |               ---- required by this bound in `is_send`
    /// ...
    /// LL |     is_send(bar());
    ///    |     ^^^^^^^ future returned by `bar` is not send
    ///    |
    ///    = help: within `impl std::future::Future`, the trait `std::marker::Send` is not
    ///            implemented for `Foo`
    /// note: future is not send as this value is used across an await
    ///   --> $DIR/issue-64130-2-send.rs:15:5
    ///    |
    /// LL |     let x = Foo;
    ///    |         - has type `Foo`
    /// LL |     baz().await;
    ///    |     ^^^^^^^^^^^ await occurs here, with `x` maybe used later
    /// LL | }
    ///    | - `x` is later dropped here
    /// ```
    ///
    /// Returns `true` if an async-await specific note was added to the diagnostic.
    fn maybe_note_obligation_cause_for_async_await(
        &self,
        err: &mut DiagnosticBuilder<'_>,
        obligation: &PredicateObligation<'tcx>,
    ) -> bool {
        debug!(
            "maybe_note_obligation_cause_for_async_await: obligation.predicate={:?} \
                obligation.cause.span={:?}",
            obligation.predicate, obligation.cause.span
        );
        let hir = self.tcx.hir();

        // Attempt to detect an async-await error by looking at the obligation causes, looking
        // for a generator to be present.
        //
        // When a future does not implement a trait because of a captured type in one of the
        // generators somewhere in the call stack, then the result is a chain of obligations.
        //
        // Given an `async fn` A that calls an `async fn` B which captures a non-send type and that
        // future is passed as an argument to a function C which requires a `Send` type, then the
        // chain looks something like this:
        //
        // - `BuiltinDerivedObligation` with a generator witness (B)
        // - `BuiltinDerivedObligation` with a generator (B)
        // - `BuiltinDerivedObligation` with `std::future::GenFuture` (B)
        // - `BuiltinDerivedObligation` with `impl std::future::Future` (B)
        // - `BuiltinDerivedObligation` with `impl std::future::Future` (B)
        // - `BuiltinDerivedObligation` with a generator witness (A)
        // - `BuiltinDerivedObligation` with a generator (A)
        // - `BuiltinDerivedObligation` with `std::future::GenFuture` (A)
        // - `BuiltinDerivedObligation` with `impl std::future::Future` (A)
        // - `BuiltinDerivedObligation` with `impl std::future::Future` (A)
        // - `BindingObligation` with `impl_send (Send requirement)
        //
        // The first obligation in the chain is the most useful and has the generator that captured
        // the type. The last generator (`outer_generator` below) has information about where the
        // bound was introduced. At least one generator should be present for this diagnostic to be
        // modified.
        let (mut trait_ref, mut target_ty) = match obligation.predicate.kind().skip_binder() {
            ty::PredicateKind::Trait(p) => (Some(p.trait_ref), Some(p.self_ty())),
            _ => (None, None),
        };
        let mut generator = None;
        let mut outer_generator = None;
        let mut next_code = Some(&obligation.cause.code);

        let mut seen_upvar_tys_infer_tuple = false;

        while let Some(code) = next_code {
            debug!("maybe_note_obligation_cause_for_async_await: code={:?}", code);
            match code {
                ObligationCauseCode::DerivedObligation(derived_obligation)
                | ObligationCauseCode::BuiltinDerivedObligation(derived_obligation)
                | ObligationCauseCode::ImplDerivedObligation(derived_obligation) => {
                    let ty = derived_obligation.parent_trait_ref.skip_binder().self_ty();
                    debug!(
                        "maybe_note_obligation_cause_for_async_await: \
                            parent_trait_ref={:?} self_ty.kind={:?}",
                        derived_obligation.parent_trait_ref,
                        ty.kind()
                    );

                    match *ty.kind() {
                        ty::Generator(did, ..) => {
                            generator = generator.or(Some(did));
                            outer_generator = Some(did);
                        }
                        ty::GeneratorWitness(..) => {}
                        ty::Tuple(_) if !seen_upvar_tys_infer_tuple => {
                            // By introducing a tuple of upvar types into the chain of obligations
                            // of a generator, the first non-generator item is now the tuple itself,
                            // we shall ignore this.

                            seen_upvar_tys_infer_tuple = true;
                        }
                        _ if generator.is_none() => {
                            trait_ref = Some(derived_obligation.parent_trait_ref.skip_binder());
                            target_ty = Some(ty);
                        }
                        _ => {}
                    }

                    next_code = Some(derived_obligation.parent_code.as_ref());
                }
                _ => break,
            }
        }

        // Only continue if a generator was found.
        debug!(
            "maybe_note_obligation_cause_for_async_await: generator={:?} trait_ref={:?} \
                target_ty={:?}",
            generator, trait_ref, target_ty
        );
        let (generator_did, trait_ref, target_ty) = match (generator, trait_ref, target_ty) {
            (Some(generator_did), Some(trait_ref), Some(target_ty)) => {
                (generator_did, trait_ref, target_ty)
            }
            _ => return false,
        };

        let span = self.tcx.def_span(generator_did);

        // Do not ICE on closure typeck (#66868).
        if !generator_did.is_local() {
            return false;
        }

        // Get the typeck results from the infcx if the generator is the function we are
        // currently type-checking; otherwise, get them by performing a query.
        // This is needed to avoid cycles.
        let in_progress_typeck_results = self.in_progress_typeck_results.map(|t| t.borrow());
        let generator_did_root = self.tcx.closure_base_def_id(generator_did);
        debug!(
            "maybe_note_obligation_cause_for_async_await: generator_did={:?} \
             generator_did_root={:?} in_progress_typeck_results.hir_owner={:?} span={:?}",
            generator_did,
            generator_did_root,
            in_progress_typeck_results.as_ref().map(|t| t.hir_owner),
            span
        );
        let query_typeck_results;
        let typeck_results: &TypeckResults<'tcx> = match &in_progress_typeck_results {
            Some(t) if t.hir_owner.to_def_id() == generator_did_root => t,
            _ => {
                query_typeck_results = self.tcx.typeck(generator_did.expect_local());
                &query_typeck_results
            }
        };

        let generator_body = generator_did
            .as_local()
            .map(|def_id| hir.local_def_id_to_hir_id(def_id))
            .and_then(|hir_id| hir.maybe_body_owned_by(hir_id))
            .map(|body_id| hir.body(body_id));
        let mut visitor = AwaitsVisitor::default();
        if let Some(body) = generator_body {
            visitor.visit_body(body);
        }
        debug!("maybe_note_obligation_cause_for_async_await: awaits = {:?}", visitor.awaits);

        // Look for a type inside the generator interior that matches the target type to get
        // a span.
        let target_ty_erased = self.tcx.erase_regions(target_ty);
        let ty_matches = |ty| -> bool {
            // Careful: the regions for types that appear in the
            // generator interior are not generally known, so we
            // want to erase them when comparing (and anyway,
            // `Send` and other bounds are generally unaffected by
            // the choice of region).  When erasing regions, we
            // also have to erase late-bound regions. This is
            // because the types that appear in the generator
            // interior generally contain "bound regions" to
            // represent regions that are part of the suspended
            // generator frame. Bound regions are preserved by
            // `erase_regions` and so we must also call
            // `erase_late_bound_regions`.
            let ty_erased = self.tcx.erase_late_bound_regions(ty);
            let ty_erased = self.tcx.erase_regions(ty_erased);
            let eq = ty::TyS::same_type(ty_erased, target_ty_erased);
            debug!(
                "maybe_note_obligation_cause_for_async_await: ty_erased={:?} \
                    target_ty_erased={:?} eq={:?}",
                ty_erased, target_ty_erased, eq
            );
            eq
        };

        let mut interior_or_upvar_span = None;
        let mut interior_extra_info = None;

        if let Some(upvars) = self.tcx.upvars_mentioned(generator_did) {
            interior_or_upvar_span = upvars.iter().find_map(|(upvar_id, upvar)| {
                let upvar_ty = typeck_results.node_type(*upvar_id);
                let upvar_ty = self.resolve_vars_if_possible(upvar_ty);
                if ty_matches(ty::Binder::dummy(upvar_ty)) {
                    Some(GeneratorInteriorOrUpvar::Upvar(upvar.span))
                } else {
                    None
                }
            });
        };

        // The generator interior types share the same binders
        if let Some(cause) =
            typeck_results.generator_interior_types.as_ref().skip_binder().iter().find(
                |ty::GeneratorInteriorTypeCause { ty, .. }| {
                    ty_matches(typeck_results.generator_interior_types.rebind(ty))
                },
            )
        {
            // Check to see if any awaited expressions have the target type.
            let from_awaited_ty = visitor
                .awaits
                .into_iter()
                .map(|id| hir.expect_expr(id))
                .find(|await_expr| {
                    let ty = typeck_results.expr_ty_adjusted(&await_expr);
                    debug!(
                        "maybe_note_obligation_cause_for_async_await: await_expr={:?}",
                        await_expr
                    );
                    ty_matches(ty::Binder::dummy(ty))
                })
                .map(|expr| expr.span);
            let ty::GeneratorInteriorTypeCause { span, scope_span, yield_span, expr, .. } = cause;

            interior_or_upvar_span = Some(GeneratorInteriorOrUpvar::Interior(*span));
            interior_extra_info = Some((*scope_span, *yield_span, *expr, from_awaited_ty));
        };

        debug!(
            "maybe_note_obligation_cause_for_async_await: interior_or_upvar={:?} \
                generator_interior_types={:?}",
            interior_or_upvar_span, typeck_results.generator_interior_types
        );
        if let Some(interior_or_upvar_span) = interior_or_upvar_span {
            self.note_obligation_cause_for_async_await(
                err,
                interior_or_upvar_span,
                interior_extra_info,
                generator_body,
                outer_generator,
                trait_ref,
                target_ty,
                typeck_results,
                obligation,
                next_code,
            );
            true
        } else {
            false
        }
    }

    /// Unconditionally adds the diagnostic note described in
    /// `maybe_note_obligation_cause_for_async_await`'s documentation comment.
    fn note_obligation_cause_for_async_await(
        &self,
        err: &mut DiagnosticBuilder<'_>,
        interior_or_upvar_span: GeneratorInteriorOrUpvar,
        interior_extra_info: Option<(Option<Span>, Span, Option<hir::HirId>, Option<Span>)>,
        inner_generator_body: Option<&hir::Body<'tcx>>,
        outer_generator: Option<DefId>,
        trait_ref: ty::TraitRef<'tcx>,
        target_ty: Ty<'tcx>,
        typeck_results: &ty::TypeckResults<'tcx>,
        obligation: &PredicateObligation<'tcx>,
        next_code: Option<&ObligationCauseCode<'tcx>>,
    ) {
        let source_map = self.tcx.sess.source_map();

        let is_async = inner_generator_body
            .and_then(|body| body.generator_kind())
            .map(|generator_kind| matches!(generator_kind, hir::GeneratorKind::Async(..)))
            .unwrap_or(false);
        let (await_or_yield, an_await_or_yield) =
            if is_async { ("await", "an await") } else { ("yield", "a yield") };
        let future_or_generator = if is_async { "future" } else { "generator" };

        // Special case the primary error message when send or sync is the trait that was
        // not implemented.
        let hir = self.tcx.hir();
        let trait_explanation = if let Some(name @ (sym::Send | sym::Sync)) =
            self.tcx.get_diagnostic_name(trait_ref.def_id)
        {
            let (trait_name, trait_verb) =
                if name == sym::Send { ("`Send`", "sent") } else { ("`Sync`", "shared") };

            err.clear_code();
            err.set_primary_message(format!(
                "{} cannot be {} between threads safely",
                future_or_generator, trait_verb
            ));

            let original_span = err.span.primary_span().unwrap();
            let mut span = MultiSpan::from_span(original_span);

            let message = outer_generator
                .and_then(|generator_did| {
                    Some(match self.tcx.generator_kind(generator_did).unwrap() {
                        GeneratorKind::Gen => format!("generator is not {}", trait_name),
                        GeneratorKind::Async(AsyncGeneratorKind::Fn) => self
                            .tcx
                            .parent(generator_did)
                            .and_then(|parent_did| parent_did.as_local())
                            .map(|parent_did| hir.local_def_id_to_hir_id(parent_did))
                            .and_then(|parent_hir_id| hir.opt_name(parent_hir_id))
                            .map(|name| {
                                format!("future returned by `{}` is not {}", name, trait_name)
                            })?,
                        GeneratorKind::Async(AsyncGeneratorKind::Block) => {
                            format!("future created by async block is not {}", trait_name)
                        }
                        GeneratorKind::Async(AsyncGeneratorKind::Closure) => {
                            format!("future created by async closure is not {}", trait_name)
                        }
                    })
                })
                .unwrap_or_else(|| format!("{} is not {}", future_or_generator, trait_name));

            span.push_span_label(original_span, message);
            err.set_span(span);

            format!("is not {}", trait_name)
        } else {
            format!("does not implement `{}`", trait_ref.print_only_trait_path())
        };

        let mut explain_yield =
            |interior_span: Span, yield_span: Span, scope_span: Option<Span>| {
                let mut span = MultiSpan::from_span(yield_span);
                if let Ok(snippet) = source_map.span_to_snippet(interior_span) {
                    // #70935: If snippet contains newlines, display "the value" instead
                    // so that we do not emit complex diagnostics.
                    let snippet = &format!("`{}`", snippet);
                    let snippet = if snippet.contains('\n') { "the value" } else { snippet };
                    // The multispan can be complex here, like:
                    // note: future is not `Send` as this value is used across an await
                    //   --> $DIR/issue-70935-complex-spans.rs:13:9
                    //    |
                    // LL |            baz(|| async{
                    //    |  __________^___-
                    //    | | _________|
                    //    | ||
                    // LL | ||             foo(tx.clone());
                    // LL | ||         }).await;
                    //    | ||         -      ^- value is later dropped here
                    //    | ||_________|______|
                    //    | |__________|      await occurs here, with value maybe used later
                    //    |            has type `closure` which is not `Send`
                    //
                    // So, detect it and separate into some notes, like:
                    //
                    // note: future is not `Send` as this value is used across an await
                    //   --> $DIR/issue-70935-complex-spans.rs:13:9
                    //    |
                    // LL | /         baz(|| async{
                    // LL | |             foo(tx.clone());
                    // LL | |         }).await;
                    //    | |________________^ first, await occurs here, with the value maybe used later...
                    // note: the value is later dropped here
                    //   --> $DIR/issue-70935-complex-spans.rs:15:17
                    //    |
                    // LL |         }).await;
                    //    |                 ^
                    //
                    // If available, use the scope span to annotate the drop location.
                    if let Some(scope_span) = scope_span {
                        let scope_span = source_map.end_point(scope_span);
                        let is_overlapped =
                            yield_span.overlaps(scope_span) || yield_span.overlaps(interior_span);
                        if is_overlapped {
                            span.push_span_label(
                                yield_span,
                                format!(
                                    "first, {} occurs here, with {} maybe used later...",
                                    await_or_yield, snippet
                                ),
                            );
                            err.span_note(
                                span,
                                &format!(
                                    "{} {} as this value is used across {}",
                                    future_or_generator, trait_explanation, an_await_or_yield
                                ),
                            );
                            if source_map.is_multiline(interior_span) {
                                err.span_note(
                                    scope_span,
                                    &format!("{} is later dropped here", snippet),
                                );
                                err.span_note(
                                    interior_span,
                                    &format!(
                                        "this has type `{}` which {}",
                                        target_ty, trait_explanation
                                    ),
                                );
                            } else {
                                let mut span = MultiSpan::from_span(scope_span);
                                span.push_span_label(
                                    interior_span,
                                    format!("has type `{}` which {}", target_ty, trait_explanation),
                                );
                                err.span_note(span, &format!("{} is later dropped here", snippet));
                            }
                        } else {
                            span.push_span_label(
                                yield_span,
                                format!(
                                    "{} occurs here, with {} maybe used later",
                                    await_or_yield, snippet
                                ),
                            );
                            span.push_span_label(
                                scope_span,
                                format!("{} is later dropped here", snippet),
                            );
                            span.push_span_label(
                                interior_span,
                                format!("has type `{}` which {}", target_ty, trait_explanation),
                            );
                            err.span_note(
                                span,
                                &format!(
                                    "{} {} as this value is used across {}",
                                    future_or_generator, trait_explanation, an_await_or_yield
                                ),
                            );
                        }
                    } else {
                        span.push_span_label(
                            yield_span,
                            format!(
                                "{} occurs here, with {} maybe used later",
                                await_or_yield, snippet
                            ),
                        );
                        span.push_span_label(
                            interior_span,
                            format!("has type `{}` which {}", target_ty, trait_explanation),
                        );
                        err.span_note(
                            span,
                            &format!(
                                "{} {} as this value is used across {}",
                                future_or_generator, trait_explanation, an_await_or_yield
                            ),
                        );
                    }
                }
            };
        match interior_or_upvar_span {
            GeneratorInteriorOrUpvar::Interior(interior_span) => {
                if let Some((scope_span, yield_span, expr, from_awaited_ty)) = interior_extra_info {
                    if let Some(await_span) = from_awaited_ty {
                        // The type causing this obligation is one being awaited at await_span.
                        let mut span = MultiSpan::from_span(await_span);
                        span.push_span_label(
                            await_span,
                            format!(
                                "await occurs here on type `{}`, which {}",
                                target_ty, trait_explanation
                            ),
                        );
                        err.span_note(
                            span,
                            &format!(
                                "future {not_trait} as it awaits another future which {not_trait}",
                                not_trait = trait_explanation
                            ),
                        );
                    } else {
                        // Look at the last interior type to get a span for the `.await`.
                        debug!(
                            "note_obligation_cause_for_async_await generator_interior_types: {:#?}",
                            typeck_results.generator_interior_types
                        );
                        explain_yield(interior_span, yield_span, scope_span);
                    }

                    if let Some(expr_id) = expr {
                        let expr = hir.expect_expr(expr_id);
                        debug!("target_ty evaluated from {:?}", expr);

                        let parent = hir.get_parent_node(expr_id);
                        if let Some(hir::Node::Expr(e)) = hir.find(parent) {
                            let parent_span = hir.span(parent);
                            let parent_did = parent.owner.to_def_id();
                            // ```rust
                            // impl T {
                            //     fn foo(&self) -> i32 {}
                            // }
                            // T.foo();
                            // ^^^^^^^ a temporary `&T` created inside this method call due to `&self`
                            // ```
                            //
                            let is_region_borrow = typeck_results
                                .expr_adjustments(expr)
                                .iter()
                                .any(|adj| adj.is_region_borrow());

                            // ```rust
                            // struct Foo(*const u8);
                            // bar(Foo(std::ptr::null())).await;
                            //     ^^^^^^^^^^^^^^^^^^^^^ raw-ptr `*T` created inside this struct ctor.
                            // ```
                            debug!("parent_def_kind: {:?}", self.tcx.def_kind(parent_did));
                            let is_raw_borrow_inside_fn_like_call =
                                match self.tcx.def_kind(parent_did) {
                                    DefKind::Fn | DefKind::Ctor(..) => target_ty.is_unsafe_ptr(),
                                    _ => false,
                                };

                            if (typeck_results.is_method_call(e) && is_region_borrow)
                                || is_raw_borrow_inside_fn_like_call
                            {
                                err.span_help(
                                    parent_span,
                                    "consider moving this into a `let` \
                        binding to create a shorter lived borrow",
                                );
                            }
                        }
                    }
                }
            }
            GeneratorInteriorOrUpvar::Upvar(upvar_span) => {
                // `Some(ref_ty)` if `target_ty` is `&T` and `T` fails to impl `Sync`
                let refers_to_non_sync = match target_ty.kind() {
                    ty::Ref(_, ref_ty, _) => match self.evaluate_obligation(&obligation) {
                        Ok(eval) if !eval.may_apply() => Some(ref_ty),
                        _ => None,
                    },
                    _ => None,
                };

                let (span_label, span_note) = match refers_to_non_sync {
                    // if `target_ty` is `&T` and `T` fails to impl `Sync`,
                    // include suggestions to make `T: Sync` so that `&T: Send`
                    Some(ref_ty) => (
                        format!(
                            "has type `{}` which {}, because `{}` is not `Sync`",
                            target_ty, trait_explanation, ref_ty
                        ),
                        format!(
                            "captured value {} because `&` references cannot be sent unless their referent is `Sync`",
                            trait_explanation
                        ),
                    ),
                    None => (
                        format!("has type `{}` which {}", target_ty, trait_explanation),
                        format!("captured value {}", trait_explanation),
                    ),
                };

                let mut span = MultiSpan::from_span(upvar_span);
                span.push_span_label(upvar_span, span_label);
                err.span_note(span, &span_note);
            }
        }

        // Add a note for the item obligation that remains - normally a note pointing to the
        // bound that introduced the obligation (e.g. `T: Send`).
        debug!("note_obligation_cause_for_async_await: next_code={:?}", next_code);
        self.note_obligation_cause_code(
            err,
            &obligation.predicate,
            next_code.unwrap(),
            &mut Vec::new(),
            &mut Default::default(),
        );
    }

    fn note_obligation_cause_code<T>(
        &self,
        err: &mut DiagnosticBuilder<'_>,
        predicate: &T,
        cause_code: &ObligationCauseCode<'tcx>,
        obligated_types: &mut Vec<&ty::TyS<'tcx>>,
        seen_requirements: &mut FxHashSet<DefId>,
    ) where
        T: fmt::Display,
    {
        let tcx = self.tcx;
        match *cause_code {
            ObligationCauseCode::ExprAssignable
            | ObligationCauseCode::MatchExpressionArm { .. }
            | ObligationCauseCode::Pattern { .. }
            | ObligationCauseCode::IfExpression { .. }
            | ObligationCauseCode::IfExpressionWithNoElse
            | ObligationCauseCode::MainFunctionType
            | ObligationCauseCode::StartFunctionType
            | ObligationCauseCode::IntrinsicType
            | ObligationCauseCode::MethodReceiver
            | ObligationCauseCode::ReturnNoExpression
            | ObligationCauseCode::UnifyReceiver(..)
            | ObligationCauseCode::OpaqueType
            | ObligationCauseCode::MiscObligation
            | ObligationCauseCode::WellFormed(..)
            | ObligationCauseCode::MatchImpl(..)
            | ObligationCauseCode::ReturnType
            | ObligationCauseCode::ReturnValue(_)
            | ObligationCauseCode::BlockTailExpression(_)
            | ObligationCauseCode::LetElse => {}
            ObligationCauseCode::SliceOrArrayElem => {
                err.note("slice and array elements must have `Sized` type");
            }
            ObligationCauseCode::TupleElem => {
                err.note("only the last element of a tuple may have a dynamically sized type");
            }
            ObligationCauseCode::ProjectionWf(data) => {
                err.note(&format!("required so that the projection `{}` is well-formed", data,));
            }
            ObligationCauseCode::ReferenceOutlivesReferent(ref_ty) => {
                err.note(&format!(
                    "required so that reference `{}` does not outlive its referent",
                    ref_ty,
                ));
            }
            ObligationCauseCode::ObjectTypeBound(object_ty, region) => {
                err.note(&format!(
                    "required so that the lifetime bound of `{}` for `{}` is satisfied",
                    region, object_ty,
                ));
            }
            ObligationCauseCode::ItemObligation(item_def_id) => {
                let item_name = tcx.def_path_str(item_def_id);
                let msg = format!("required by `{}`", item_name);
                let sp = tcx
                    .hir()
                    .span_if_local(item_def_id)
                    .unwrap_or_else(|| tcx.def_span(item_def_id));
                let sp = tcx.sess.source_map().guess_head_span(sp);
                err.span_note(sp, &msg);
            }
            ObligationCauseCode::BindingObligation(item_def_id, span) => {
                let item_name = tcx.def_path_str(item_def_id);
                let mut multispan = MultiSpan::from(span);
                if let Some(ident) = tcx.opt_item_name(item_def_id) {
                    let sm = tcx.sess.source_map();
                    let same_line =
                        match (sm.lookup_line(ident.span.hi()), sm.lookup_line(span.lo())) {
                            (Ok(l), Ok(r)) => l.line == r.line,
                            _ => true,
                        };
                    if !ident.span.overlaps(span) && !same_line {
                        multispan
                            .push_span_label(ident.span, "required by a bound in this".to_string());
                    }
                }
                let descr = format!("required by a bound in `{}`", item_name);
                if span != DUMMY_SP {
                    let msg = format!("required by this bound in `{}`", item_name);
                    multispan.push_span_label(span, msg);
                    err.span_note(multispan, &descr);
                } else {
                    err.span_note(tcx.def_span(item_def_id), &descr);
                }
            }
            ObligationCauseCode::ObjectCastObligation(object_ty) => {
                err.note(&format!(
                    "required for the cast to the object type `{}`",
                    self.ty_to_string(object_ty)
                ));
            }
            ObligationCauseCode::Coercion { source: _, target } => {
                err.note(&format!("required by cast to type `{}`", self.ty_to_string(target)));
            }
            ObligationCauseCode::RepeatVec(is_const_fn) => {
                err.note(
                    "the `Copy` trait is required because the repeated element will be copied",
                );

                if is_const_fn {
                    err.help(
                        "consider creating a new `const` item and initializing it with the result \
                        of the function call to be used in the repeat position, like \
                        `const VAL: Type = const_fn();` and `let x = [VAL; 42];`",
                    );
                }

                if self.tcx.sess.is_nightly_build() && is_const_fn {
                    err.help(
                        "create an inline `const` block, see RFC #2920 \
                         <https://github.com/rust-lang/rfcs/pull/2920> for more information",
                    );
                }
            }
            ObligationCauseCode::VariableType(hir_id) => {
                let parent_node = self.tcx.hir().get_parent_node(hir_id);
                match self.tcx.hir().find(parent_node) {
                    Some(Node::Local(hir::Local {
                        init: Some(hir::Expr { kind: hir::ExprKind::Index(_, _), span, .. }),
                        ..
                    })) => {
                        // When encountering an assignment of an unsized trait, like
                        // `let x = ""[..];`, provide a suggestion to borrow the initializer in
                        // order to use have a slice instead.
                        err.span_suggestion_verbose(
                            span.shrink_to_lo(),
                            "consider borrowing here",
                            "&".to_owned(),
                            Applicability::MachineApplicable,
                        );
                        err.note("all local variables must have a statically known size");
                    }
                    Some(Node::Param(param)) => {
                        err.span_suggestion_verbose(
                            param.ty_span.shrink_to_lo(),
                            "function arguments must have a statically known size, borrowed types \
                            always have a known size",
                            "&".to_owned(),
                            Applicability::MachineApplicable,
                        );
                    }
                    _ => {
                        err.note("all local variables must have a statically known size");
                    }
                }
                if !self.tcx.features().unsized_locals {
                    err.help("unsized locals are gated as an unstable feature");
                }
            }
            ObligationCauseCode::SizedArgumentType(sp) => {
                if let Some(span) = sp {
                    err.span_suggestion_verbose(
                        span.shrink_to_lo(),
                        "function arguments must have a statically known size, borrowed types \
                         always have a known size",
                        "&".to_string(),
                        Applicability::MachineApplicable,
                    );
                } else {
                    err.note("all function arguments must have a statically known size");
                }
                if tcx.sess.opts.unstable_features.is_nightly_build()
                    && !self.tcx.features().unsized_fn_params
                {
                    err.help("unsized fn params are gated as an unstable feature");
                }
            }
            ObligationCauseCode::SizedReturnType => {
                err.note("the return type of a function must have a statically known size");
            }
            ObligationCauseCode::SizedYieldType => {
                err.note("the yield type of a generator must have a statically known size");
            }
            ObligationCauseCode::SizedBoxType => {
                err.note("the type of a box expression must have a statically known size");
            }
            ObligationCauseCode::AssignmentLhsSized => {
                err.note("the left-hand-side of an assignment must have a statically known size");
            }
            ObligationCauseCode::TupleInitializerSized => {
                err.note("tuples must have a statically known size to be initialized");
            }
            ObligationCauseCode::StructInitializerSized => {
                err.note("structs must have a statically known size to be initialized");
            }
            ObligationCauseCode::FieldSized { adt_kind: ref item, last, span } => {
                match *item {
                    AdtKind::Struct => {
                        if last {
                            err.note(
                                "the last field of a packed struct may only have a \
                                dynamically sized type if it does not need drop to be run",
                            );
                        } else {
                            err.note(
                                "only the last field of a struct may have a dynamically sized type",
                            );
                        }
                    }
                    AdtKind::Union => {
                        err.note("no field of a union may have a dynamically sized type");
                    }
                    AdtKind::Enum => {
                        err.note("no field of an enum variant may have a dynamically sized type");
                    }
                }
                err.help("change the field's type to have a statically known size");
                err.span_suggestion(
                    span.shrink_to_lo(),
                    "borrowed types always have a statically known size",
                    "&".to_string(),
                    Applicability::MachineApplicable,
                );
                err.multipart_suggestion(
                    "the `Box` type always has a statically known size and allocates its contents \
                     in the heap",
                    vec![
                        (span.shrink_to_lo(), "Box<".to_string()),
                        (span.shrink_to_hi(), ">".to_string()),
                    ],
                    Applicability::MachineApplicable,
                );
            }
            ObligationCauseCode::ConstSized => {
                err.note("constant expressions must have a statically known size");
            }
            ObligationCauseCode::InlineAsmSized => {
                err.note("all inline asm arguments must have a statically known size");
            }
            ObligationCauseCode::ConstPatternStructural => {
                err.note("constants used for pattern-matching must derive `PartialEq` and `Eq`");
            }
            ObligationCauseCode::SharedStatic => {
                err.note("shared static variables must have a type that implements `Sync`");
            }
            ObligationCauseCode::BuiltinDerivedObligation(ref data) => {
                let parent_trait_ref = self.resolve_vars_if_possible(data.parent_trait_ref);
                let ty = parent_trait_ref.skip_binder().self_ty();
                if parent_trait_ref.references_error() {
                    err.cancel();
                    return;
                }

                // If the obligation for a tuple is set directly by a Generator or Closure,
                // then the tuple must be the one containing capture types.
                let is_upvar_tys_infer_tuple = if !matches!(ty.kind(), ty::Tuple(..)) {
                    false
                } else {
                    if let ObligationCauseCode::BuiltinDerivedObligation(ref data) =
                        *data.parent_code
                    {
                        let parent_trait_ref = self.resolve_vars_if_possible(data.parent_trait_ref);
                        let ty = parent_trait_ref.skip_binder().self_ty();
                        matches!(ty.kind(), ty::Generator(..))
                            || matches!(ty.kind(), ty::Closure(..))
                    } else {
                        false
                    }
                };

                // Don't print the tuple of capture types
                if !is_upvar_tys_infer_tuple {
                    let msg = format!("required because it appears within the type `{}`", ty);
                    match ty.kind() {
                        ty::Adt(def, _) => match self.tcx.opt_item_name(def.did) {
                            Some(ident) => err.span_note(ident.span, &msg),
                            None => err.note(&msg),
                        },
                        _ => err.note(&msg),
                    };
                }

                obligated_types.push(ty);

                let parent_predicate = parent_trait_ref.without_const().to_predicate(tcx);
                if !self.is_recursive_obligation(obligated_types, &data.parent_code) {
                    // #74711: avoid a stack overflow
                    ensure_sufficient_stack(|| {
                        self.note_obligation_cause_code(
                            err,
                            &parent_predicate,
                            &data.parent_code,
                            obligated_types,
                            seen_requirements,
                        )
                    });
                }
            }
            ObligationCauseCode::ImplDerivedObligation(ref data) => {
                let mut parent_trait_ref = self.resolve_vars_if_possible(data.parent_trait_ref);
                let parent_def_id = parent_trait_ref.def_id();
                let msg = format!(
                    "required because of the requirements on the impl of `{}` for `{}`",
                    parent_trait_ref.print_only_trait_path(),
                    parent_trait_ref.skip_binder().self_ty()
                );
                let mut candidates = vec![];
                self.tcx.for_each_relevant_impl(
                    parent_def_id,
                    parent_trait_ref.self_ty().skip_binder(),
                    |impl_def_id| match self.tcx.hir().get_if_local(impl_def_id) {
                        Some(Node::Item(hir::Item {
                            kind: hir::ItemKind::Impl(hir::Impl { .. }),
                            ..
                        })) => {
                            candidates.push(impl_def_id);
                        }
                        _ => {}
                    },
                );
                match &candidates[..] {
                    [def_id] => match self.tcx.hir().get_if_local(*def_id) {
                        Some(Node::Item(hir::Item {
                            kind: hir::ItemKind::Impl(hir::Impl { of_trait, self_ty, .. }),
                            ..
                        })) => {
                            let mut spans = Vec::with_capacity(2);
                            if let Some(trait_ref) = of_trait {
                                spans.push(trait_ref.path.span);
                            }
                            spans.push(self_ty.span);
                            err.span_note(spans, &msg)
                        }
                        _ => err.note(&msg),
                    },
                    _ => err.note(&msg),
                };

                let mut parent_predicate = parent_trait_ref.without_const().to_predicate(tcx);
                let mut data = data;
                let mut count = 0;
                seen_requirements.insert(parent_def_id);
                while let ObligationCauseCode::ImplDerivedObligation(child) = &*data.parent_code {
                    // Skip redundant recursive obligation notes. See `ui/issue-20413.rs`.
                    let child_trait_ref = self.resolve_vars_if_possible(child.parent_trait_ref);
                    let child_def_id = child_trait_ref.def_id();
                    if seen_requirements.insert(child_def_id) {
                        break;
                    }
                    count += 1;
                    data = child;
                    parent_predicate = child_trait_ref.without_const().to_predicate(tcx);
                    parent_trait_ref = child_trait_ref;
                }
                if count > 0 {
                    err.note(&format!(
                        "{} redundant requirement{} hidden",
                        count,
                        pluralize!(count)
                    ));
                    err.note(&format!(
                        "required because of the requirements on the impl of `{}` for `{}`",
                        parent_trait_ref.print_only_trait_path(),
                        parent_trait_ref.skip_binder().self_ty()
                    ));
                }
                // #74711: avoid a stack overflow
                ensure_sufficient_stack(|| {
                    self.note_obligation_cause_code(
                        err,
                        &parent_predicate,
                        &data.parent_code,
                        obligated_types,
                        seen_requirements,
                    )
                });
            }
            ObligationCauseCode::DerivedObligation(ref data) => {
                let parent_trait_ref = self.resolve_vars_if_possible(data.parent_trait_ref);
                let parent_predicate = parent_trait_ref.without_const().to_predicate(tcx);
                // #74711: avoid a stack overflow
                ensure_sufficient_stack(|| {
                    self.note_obligation_cause_code(
                        err,
                        &parent_predicate,
                        &data.parent_code,
                        obligated_types,
                        seen_requirements,
                    )
                });
            }
            ObligationCauseCode::FunctionArgumentObligation {
                arg_hir_id,
                call_hir_id,
                ref parent_code,
            } => {
                let hir = self.tcx.hir();
                if let Some(Node::Expr(expr @ hir::Expr { kind: hir::ExprKind::Block(..), .. })) =
                    hir.find(arg_hir_id)
                {
                    let in_progress_typeck_results =
                        self.in_progress_typeck_results.map(|t| t.borrow());
                    let parent_id = hir.local_def_id(hir.get_parent_item(arg_hir_id));
                    let typeck_results: &TypeckResults<'tcx> = match &in_progress_typeck_results {
                        Some(t) if t.hir_owner == parent_id => t,
                        _ => self.tcx.typeck(parent_id),
                    };
                    let ty = typeck_results.expr_ty_adjusted(expr);
                    let span = expr.peel_blocks().span;
                    if Some(span) != err.span.primary_span() {
                        err.span_label(
                            span,
                            &if ty.references_error() {
                                String::new()
                            } else {
                                format!("this tail expression is of type `{:?}`", ty)
                            },
                        );
                    }
                }
                if let Some(Node::Expr(hir::Expr {
                    kind:
                        hir::ExprKind::Call(hir::Expr { span, .. }, _)
                        | hir::ExprKind::MethodCall(_, span, ..),
                    ..
                })) = hir.find(call_hir_id)
                {
                    if Some(*span) != err.span.primary_span() {
                        err.span_label(*span, "required by a bound introduced by this call");
                    }
                }
                ensure_sufficient_stack(|| {
                    self.note_obligation_cause_code(
                        err,
                        predicate,
                        &parent_code,
                        obligated_types,
                        seen_requirements,
                    )
                });
            }
            ObligationCauseCode::CompareImplMethodObligation {
                item_name,
                trait_item_def_id,
                ..
            } => {
                let msg = format!(
                    "the requirement `{}` appears on the impl method `{}` but not on the \
                     corresponding trait method",
                    predicate, item_name,
                );
                let sp = self
                    .tcx
                    .opt_item_name(trait_item_def_id)
                    .map(|i| i.span)
                    .unwrap_or_else(|| self.tcx.def_span(trait_item_def_id));
                let mut assoc_span: MultiSpan = sp.into();
                assoc_span.push_span_label(
                    sp,
                    format!("this trait method doesn't have the requirement `{}`", predicate),
                );
                if let Some(ident) = self
                    .tcx
                    .opt_associated_item(trait_item_def_id)
                    .and_then(|i| self.tcx.opt_item_name(i.container.id()))
                {
                    assoc_span.push_span_label(ident.span, "in this trait".into());
                }
                err.span_note(assoc_span, &msg);
            }
            ObligationCauseCode::CompareImplTypeObligation {
                item_name, trait_item_def_id, ..
            } => {
                let msg = format!(
                    "the requirement `{}` appears on the associated impl type `{}` but not on the \
                     corresponding associated trait type",
                    predicate, item_name,
                );
                let sp = self.tcx.def_span(trait_item_def_id);
                let mut assoc_span: MultiSpan = sp.into();
                assoc_span.push_span_label(
                    sp,
                    format!(
                        "this trait associated type doesn't have the requirement `{}`",
                        predicate,
                    ),
                );
                if let Some(ident) = self
                    .tcx
                    .opt_associated_item(trait_item_def_id)
                    .and_then(|i| self.tcx.opt_item_name(i.container.id()))
                {
                    assoc_span.push_span_label(ident.span, "in this trait".into());
                }
                err.span_note(assoc_span, &msg);
            }
            ObligationCauseCode::CompareImplConstObligation => {
                err.note(&format!(
                    "the requirement `{}` appears on the associated impl constant \
                     but not on the corresponding associated trait constant",
                    predicate
                ));
            }
            ObligationCauseCode::TrivialBound => {
                err.help("see issue #48214");
                if tcx.sess.opts.unstable_features.is_nightly_build() {
                    err.help("add `#![feature(trivial_bounds)]` to the crate attributes to enable");
                }
            }
        }
    }

    fn suggest_new_overflow_limit(&self, err: &mut DiagnosticBuilder<'_>) {
        let suggested_limit = match self.tcx.recursion_limit() {
            Limit(0) => Limit(2),
            limit => limit * 2,
        };
        err.help(&format!(
            "consider increasing the recursion limit by adding a \
             `#![recursion_limit = \"{}\"]` attribute to your crate (`{}`)",
            suggested_limit,
            self.tcx.crate_name(LOCAL_CRATE),
        ));
    }

    fn suggest_await_before_try(
        &self,
        err: &mut DiagnosticBuilder<'_>,
        obligation: &PredicateObligation<'tcx>,
        trait_ref: ty::Binder<'tcx, ty::TraitRef<'tcx>>,
        span: Span,
    ) {
        debug!(
            "suggest_await_before_try: obligation={:?}, span={:?}, trait_ref={:?}, trait_ref_self_ty={:?}",
            obligation,
            span,
            trait_ref,
            trait_ref.self_ty()
        );
        let body_hir_id = obligation.cause.body_id;
        let item_id = self.tcx.hir().get_parent_node(body_hir_id);

        if let Some(body_id) = self.tcx.hir().maybe_body_owned_by(item_id) {
            let body = self.tcx.hir().body(body_id);
            if let Some(hir::GeneratorKind::Async(_)) = body.generator_kind {
                let future_trait = self.tcx.require_lang_item(LangItem::Future, None);

                let self_ty = self.resolve_vars_if_possible(trait_ref.self_ty());

                // Do not check on infer_types to avoid panic in evaluate_obligation.
                if self_ty.has_infer_types() {
                    return;
                }
                let self_ty = self.tcx.erase_regions(self_ty);

                let impls_future = self.type_implements_trait(
                    future_trait,
                    self_ty.skip_binder(),
                    ty::List::empty(),
                    obligation.param_env,
                );

                let item_def_id = self
                    .tcx
                    .associated_items(future_trait)
                    .in_definition_order()
                    .next()
                    .unwrap()
                    .def_id;
                // `<T as Future>::Output`
                let projection_ty = ty::ProjectionTy {
                    // `T`
                    substs: self.tcx.mk_substs_trait(
                        trait_ref.self_ty().skip_binder(),
                        self.fresh_substs_for_item(span, item_def_id),
                    ),
                    // `Future::Output`
                    item_def_id,
                };

                let mut selcx = SelectionContext::new(self);

                let mut obligations = vec![];
                let normalized_ty = normalize_projection_type(
                    &mut selcx,
                    obligation.param_env,
                    projection_ty,
                    obligation.cause.clone(),
                    0,
                    &mut obligations,
                );

                debug!(
                    "suggest_await_before_try: normalized_projection_type {:?}",
                    self.resolve_vars_if_possible(normalized_ty)
                );
                let try_obligation = self.mk_trait_obligation_with_new_self_ty(
                    obligation.param_env,
                    trait_ref,
                    normalized_ty,
                );
                debug!("suggest_await_before_try: try_trait_obligation {:?}", try_obligation);
                if self.predicate_may_hold(&try_obligation)
                    && impls_future.must_apply_modulo_regions()
                {
                    if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
                        if snippet.ends_with('?') {
                            err.span_suggestion_verbose(
                                span.with_hi(span.hi() - BytePos(1)).shrink_to_hi(),
                                "consider `await`ing on the `Future`",
                                ".await".to_string(),
                                Applicability::MaybeIncorrect,
                            );
                        }
                    }
                }
            }
        }
    }
}

/// Collect all the returned expressions within the input expression.
/// Used to point at the return spans when we want to suggest some change to them.
#[derive(Default)]
pub struct ReturnsVisitor<'v> {
    pub returns: Vec<&'v hir::Expr<'v>>,
    in_block_tail: bool,
}

impl<'v> Visitor<'v> for ReturnsVisitor<'v> {
    type Map = hir::intravisit::ErasedMap<'v>;

    fn nested_visit_map(&mut self) -> hir::intravisit::NestedVisitorMap<Self::Map> {
        hir::intravisit::NestedVisitorMap::None
    }

    fn visit_expr(&mut self, ex: &'v hir::Expr<'v>) {
        // Visit every expression to detect `return` paths, either through the function's tail
        // expression or `return` statements. We walk all nodes to find `return` statements, but
        // we only care about tail expressions when `in_block_tail` is `true`, which means that
        // they're in the return path of the function body.
        match ex.kind {
            hir::ExprKind::Ret(Some(ex)) => {
                self.returns.push(ex);
            }
            hir::ExprKind::Block(block, _) if self.in_block_tail => {
                self.in_block_tail = false;
                for stmt in block.stmts {
                    hir::intravisit::walk_stmt(self, stmt);
                }
                self.in_block_tail = true;
                if let Some(expr) = block.expr {
                    self.visit_expr(expr);
                }
            }
            hir::ExprKind::If(_, then, else_opt) if self.in_block_tail => {
                self.visit_expr(then);
                if let Some(el) = else_opt {
                    self.visit_expr(el);
                }
            }
            hir::ExprKind::Match(_, arms, _) if self.in_block_tail => {
                for arm in arms {
                    self.visit_expr(arm.body);
                }
            }
            // We need to walk to find `return`s in the entire body.
            _ if !self.in_block_tail => hir::intravisit::walk_expr(self, ex),
            _ => self.returns.push(ex),
        }
    }

    fn visit_body(&mut self, body: &'v hir::Body<'v>) {
        assert!(!self.in_block_tail);
        if body.generator_kind().is_none() {
            if let hir::ExprKind::Block(block, None) = body.value.kind {
                if block.expr.is_some() {
                    self.in_block_tail = true;
                }
            }
        }
        hir::intravisit::walk_body(self, body);
    }
}

/// Collect all the awaited expressions within the input expression.
#[derive(Default)]
struct AwaitsVisitor {
    awaits: Vec<hir::HirId>,
}

impl<'v> Visitor<'v> for AwaitsVisitor {
    type Map = hir::intravisit::ErasedMap<'v>;

    fn nested_visit_map(&mut self) -> hir::intravisit::NestedVisitorMap<Self::Map> {
        hir::intravisit::NestedVisitorMap::None
    }

    fn visit_expr(&mut self, ex: &'v hir::Expr<'v>) {
        if let hir::ExprKind::Yield(_, hir::YieldSource::Await { expr: Some(id) }) = ex.kind {
            self.awaits.push(id)
        }
        hir::intravisit::walk_expr(self, ex)
    }
}

pub trait NextTypeParamName {
    fn next_type_param_name(&self, name: Option<&str>) -> String;
}

impl NextTypeParamName for &[hir::GenericParam<'_>] {
    fn next_type_param_name(&self, name: Option<&str>) -> String {
        // This is the list of possible parameter names that we might suggest.
        let name = name.and_then(|n| n.chars().next()).map(|c| c.to_string().to_uppercase());
        let name = name.as_deref();
        let possible_names = [name.unwrap_or("T"), "T", "U", "V", "X", "Y", "Z", "A", "B", "C"];
        let used_names = self
            .iter()
            .filter_map(|p| match p.name {
                hir::ParamName::Plain(ident) => Some(ident.name),
                _ => None,
            })
            .collect::<Vec<_>>();

        possible_names
            .iter()
            .find(|n| !used_names.contains(&Symbol::intern(n)))
            .unwrap_or(&"ParamName")
            .to_string()
    }
}

fn suggest_trait_object_return_type_alternatives(
    err: &mut DiagnosticBuilder<'_>,
    ret_ty: Span,
    trait_obj: &str,
    is_object_safe: bool,
) {
    err.span_suggestion(
        ret_ty,
        "use some type `T` that is `T: Sized` as the return type if all return paths have the \
            same type",
        "T".to_string(),
        Applicability::MaybeIncorrect,
    );
    err.span_suggestion(
        ret_ty,
        &format!(
            "use `impl {}` as the return type if all return paths have the same type but you \
                want to expose only the trait in the signature",
            trait_obj,
        ),
        format!("impl {}", trait_obj),
        Applicability::MaybeIncorrect,
    );
    if is_object_safe {
        err.span_suggestion(
            ret_ty,
            &format!(
                "use a boxed trait object if all return paths implement trait `{}`",
                trait_obj,
            ),
            format!("Box<dyn {}>", trait_obj),
            Applicability::MaybeIncorrect,
        );
    }
}