aboutsummaryrefslogtreecommitdiff
path: root/clang-tools-extra/clangd/unittests/FindTargetTests.cpp
blob: 0af6036734ba53b49cb8772f508f9415a8aed04f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
//===-- FindTargetTests.cpp --------------------------*- C++ -*------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "FindTarget.h"

#include "Selection.h"
#include "TestTU.h"
#include "clang/AST/Decl.h"
#include "clang/AST/DeclTemplate.h"
#include "clang/Basic/SourceLocation.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Testing/Annotations/Annotations.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include <initializer_list>

namespace clang {
namespace clangd {
namespace {

// A referenced Decl together with its DeclRelationSet, for assertions.
//
// There's no great way to assert on the "content" of a Decl in the general case
// that's both expressive and unambiguous (e.g. clearly distinguishes between
// templated decls and their specializations).
//
// We use the result of pretty-printing the decl, with the {body} truncated.
struct PrintedDecl {
  PrintedDecl(const char *Name, DeclRelationSet Relations = {})
      : Name(Name), Relations(Relations) {}
  PrintedDecl(const NamedDecl *D, DeclRelationSet Relations = {})
      : Relations(Relations) {
    std::string S;
    llvm::raw_string_ostream OS(S);
    D->print(OS);
    llvm::StringRef FirstLine =
        llvm::StringRef(OS.str()).take_until([](char C) { return C == '\n'; });
    FirstLine = FirstLine.rtrim(" {");
    Name = std::string(FirstLine.rtrim(" {"));
  }

  std::string Name;
  DeclRelationSet Relations;
};
bool operator==(const PrintedDecl &L, const PrintedDecl &R) {
  return std::tie(L.Name, L.Relations) == std::tie(R.Name, R.Relations);
}
llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, const PrintedDecl &D) {
  return OS << D.Name << " Rel=" << D.Relations;
}

// The test cases in for targetDecl() take the form
//  - a piece of code (Code = "...")
//  - Code should have a single AST node marked as a [[range]]
//  - an EXPECT_DECLS() assertion that verify the type of node selected, and
//    all the decls that targetDecl() considers it to reference
// Despite the name, these cases actually test allTargetDecls() for brevity.
class TargetDeclTest : public ::testing::Test {
protected:
  using Rel = DeclRelation;
  std::string Code;
  std::vector<std::string> Flags;

  // Asserts that `Code` has a marked selection of a node `NodeType`,
  // and returns allTargetDecls() as PrintedDecl structs.
  // Use via EXPECT_DECLS().
  std::vector<PrintedDecl> assertNodeAndPrintDecls(const char *NodeType) {
    llvm::Annotations A(Code);
    auto TU = TestTU::withCode(A.code());
    TU.ExtraArgs = Flags;
    auto AST = TU.build();
    llvm::Annotations::Range R = A.range();
    auto Selection = SelectionTree::createRight(
        AST.getASTContext(), AST.getTokens(), R.Begin, R.End);
    const SelectionTree::Node *N = Selection.commonAncestor();
    if (!N) {
      ADD_FAILURE() << "No node selected!\n" << Code;
      return {};
    }
    EXPECT_EQ(N->kind(), NodeType) << Selection;

    std::vector<PrintedDecl> ActualDecls;
    for (const auto &Entry :
         allTargetDecls(N->ASTNode, AST.getHeuristicResolver()))
      ActualDecls.emplace_back(Entry.first, Entry.second);
    return ActualDecls;
  }
};

// This is a macro to preserve line numbers in assertion failures.
// It takes the expected decls as varargs to work around comma-in-macro issues.
#define EXPECT_DECLS(NodeType, ...)                                            \
  EXPECT_THAT(assertNodeAndPrintDecls(NodeType),                               \
              ::testing::UnorderedElementsAreArray(                            \
                  std::vector<PrintedDecl>({__VA_ARGS__})))                    \
      << Code
using ExpectedDecls = std::vector<PrintedDecl>;

TEST_F(TargetDeclTest, Exprs) {
  Code = R"cpp(
    int f();
    int x = [[f]]();
  )cpp";
  EXPECT_DECLS("DeclRefExpr", "int f()");

  Code = R"cpp(
    struct S { S operator+(S) const; };
    auto X = S() [[+]] S();
  )cpp";
  EXPECT_DECLS("DeclRefExpr", "S operator+(S) const");

  Code = R"cpp(
    int foo();
    int s = foo[[()]];
  )cpp";
  EXPECT_DECLS("CallExpr", "int foo()");

  Code = R"cpp(
    struct X {
    void operator()(int n);
    };
    void test() {
      X x;
      x[[(123)]];
    }
  )cpp";
  EXPECT_DECLS("CXXOperatorCallExpr", "void operator()(int n)");

  Code = R"cpp(
    void test() {
      goto [[label]];
    label:
      return;
    }
  )cpp";
  EXPECT_DECLS("GotoStmt", "label:");
  Code = R"cpp(
    void test() {
    [[label]]:
      return;
    }
  )cpp";
  EXPECT_DECLS("LabelStmt", "label:");
}

TEST_F(TargetDeclTest, RecoveryForC) {
  Flags = {"-xc", "-Xclang", "-frecovery-ast"};
  Code = R"cpp(
    // error-ok: testing behavior on broken code
    // int f();
    int f(int);
    int x = [[f]]();
  )cpp";
  EXPECT_DECLS("DeclRefExpr", "int f(int)");
}

TEST_F(TargetDeclTest, Recovery) {
  Code = R"cpp(
    // error-ok: testing behavior on broken code
    int f();
    int f(int, int);
    int x = [[f]](42);
  )cpp";
  EXPECT_DECLS("UnresolvedLookupExpr", "int f()", "int f(int, int)");
}

TEST_F(TargetDeclTest, RecoveryType) {
  Code = R"cpp(
    // error-ok: testing behavior on broken code
    struct S { int member; };
    S overloaded(int);
    void foo() {
      // No overload matches, but we have recovery-expr with the correct type.
      overloaded().[[member]];
    }
  )cpp";
  EXPECT_DECLS("MemberExpr", "int member");
}

TEST_F(TargetDeclTest, UsingDecl) {
  Code = R"cpp(
    namespace foo {
      int f(int);
      int f(char);
    }
    using foo::f;
    int x = [[f]](42);
  )cpp";
  // f(char) is not referenced!
  EXPECT_DECLS("DeclRefExpr", {"using foo::f", Rel::Alias}, {"int f(int)"});

  Code = R"cpp(
    namespace foo {
      int f(int);
      int f(char);
    }
    [[using foo::f]];
  )cpp";
  // All overloads are referenced.
  EXPECT_DECLS("UsingDecl", {"using foo::f", Rel::Alias}, {"int f(int)"},
               {"int f(char)"});

  Code = R"cpp(
    struct X {
      int foo();
    };
    struct Y : X {
      using X::foo;
    };
    int x = Y().[[foo]]();
  )cpp";
  EXPECT_DECLS("MemberExpr", {"using X::foo", Rel::Alias}, {"int foo()"});

  Code = R"cpp(
      template <typename T>
      struct Base {
        void waldo() {}
      };
      template <typename T>
      struct Derived : Base<T> {
        using Base<T>::[[waldo]];
      };
    )cpp";
  EXPECT_DECLS("UnresolvedUsingValueDecl", {"using Base<T>::waldo", Rel::Alias},
               {"void waldo()"});

  Code = R"cpp(
    namespace ns {
    template<typename T> class S {};
    }

    using ns::S;

    template<typename T>
    using A = [[S]]<T>;
  )cpp";
  EXPECT_DECLS("TemplateSpecializationTypeLoc", {"using ns::S", Rel::Alias},
               {"template <typename T> class S"},
               {"class S", Rel::TemplatePattern});

  Code = R"cpp(
    namespace ns {
    template<typename T> class S {};
    }

    using ns::S;
    template <template <typename> class T> class X {};
    using B = X<[[S]]>;
  )cpp";
  EXPECT_DECLS("TemplateArgumentLoc", {"using ns::S", Rel::Alias},
               {"template <typename T> class S"});

  Code = R"cpp(
    namespace ns {
    template<typename T> class S { public: S(T); };
    }

    using ns::S;
    [[S]] s(123);
  )cpp";
  Flags.push_back("-std=c++17"); // For CTAD feature.
  EXPECT_DECLS("DeducedTemplateSpecializationTypeLoc",
               {"using ns::S", Rel::Alias}, {"template <typename T> class S"},
               {"class S", Rel::TemplatePattern});

  Code = R"cpp(
    template<typename T>
    class Foo { public: class foo {}; };
    template <class T> class A : public Foo<T> {
      using typename Foo<T>::foo;
      [[foo]] abc;
    };
  )cpp";
  EXPECT_DECLS("UnresolvedUsingTypeLoc",
               {"using typename Foo<T>::foo", Rel::Alias});

  // Using enum.
  Flags.push_back("-std=c++20");
  Code = R"cpp(
    namespace ns { enum class A { X }; }
    [[using enum ns::A]];
  )cpp";
  EXPECT_DECLS("UsingEnumDecl", "enum class A : int");

  Code = R"cpp(
    namespace ns { enum class A { X }; }
    using enum ns::A;
    auto m = [[X]];
  )cpp";
  EXPECT_DECLS("DeclRefExpr", "X");
}

TEST_F(TargetDeclTest, BaseSpecifier) {
  Code = R"cpp(
    struct X {};
    struct Y : [[private]] X {};
  )cpp";
  EXPECT_DECLS("CXXBaseSpecifier", "struct X");
  Code = R"cpp(
    struct X {};
    struct Y : [[private X]] {};
  )cpp";
  EXPECT_DECLS("CXXBaseSpecifier", "struct X");
  Code = R"cpp(
    struct X {};
    struct Y : private [[X]] {};
  )cpp";
  EXPECT_DECLS("RecordTypeLoc", "struct X");
}

TEST_F(TargetDeclTest, ConstructorInitList) {
  Code = R"cpp(
    struct X {
      int a;
      X() : [[a]](42) {}
    };
  )cpp";
  EXPECT_DECLS("CXXCtorInitializer", "int a");

  Code = R"cpp(
    struct X {
      X() : [[X]](1) {}
      X(int);
    };
  )cpp";
  EXPECT_DECLS("RecordTypeLoc", "struct X");
}

TEST_F(TargetDeclTest, DesignatedInit) {
  Flags = {"-xc"}; // array designators are a C99 extension.
  Code = R"c(
    struct X { int a; };
    struct Y { int b; struct X c[2]; };
    struct Y y = { .c[0].[[a]] = 1 };
  )c";
  EXPECT_DECLS("DesignatedInitExpr", "int a");
}

TEST_F(TargetDeclTest, NestedNameSpecifier) {
  Code = R"cpp(
    namespace a { namespace b { int c; } }
    int x = a::[[b::]]c;
  )cpp";
  EXPECT_DECLS("NestedNameSpecifierLoc", "namespace b");

  Code = R"cpp(
    namespace a { struct X { enum { y }; }; }
    int x = a::[[X::]]y;
  )cpp";
  EXPECT_DECLS("NestedNameSpecifierLoc", "struct X");

  Code = R"cpp(
    template <typename T>
    int x = [[T::]]y;
  )cpp";
  EXPECT_DECLS("NestedNameSpecifierLoc", "typename T");

  Code = R"cpp(
    namespace a { int x; }
    namespace b = a;
    int y = [[b]]::x;
  )cpp";
  EXPECT_DECLS("NestedNameSpecifierLoc", {"namespace b = a", Rel::Alias},
               {"namespace a", Rel::Underlying});
}

TEST_F(TargetDeclTest, Types) {
  Code = R"cpp(
    struct X{};
    [[X]] x;
  )cpp";
  EXPECT_DECLS("RecordTypeLoc", "struct X");

  Code = R"cpp(
    struct S{};
    typedef S X;
    [[X]] x;
  )cpp";
  EXPECT_DECLS("TypedefTypeLoc", {"typedef S X", Rel::Alias},
               {"struct S", Rel::Underlying});
  Code = R"cpp(
    namespace ns { struct S{}; }
    typedef ns::S X;
    [[X]] x;
  )cpp";
  EXPECT_DECLS("TypedefTypeLoc", {"typedef ns::S X", Rel::Alias},
               {"struct S", Rel::Underlying});

  Code = R"cpp(
    template<class T>
    void foo() { [[T]] x; }
  )cpp";
  EXPECT_DECLS("TemplateTypeParmTypeLoc", "class T");
  Flags.clear();

  Code = R"cpp(
    template<template<typename> class T>
    void foo() { [[T<int>]] x; }
  )cpp";
  EXPECT_DECLS("TemplateSpecializationTypeLoc", "template <typename> class T");
  Flags.clear();

  Code = R"cpp(
  template<template<typename> class ...T>
  class C {
    C<[[T...]]> foo;
    };
  )cpp";
  EXPECT_DECLS("TemplateArgumentLoc", {"template <typename> class ...T"});
  Flags.clear();

  Code = R"cpp(
    struct S{};
    S X;
    [[decltype]](X) Y;
  )cpp";
  EXPECT_DECLS("DecltypeTypeLoc", {"struct S", Rel::Underlying});

  Code = R"cpp(
    struct S{};
    [[auto]] X = S{};
  )cpp";
  // FIXME: deduced type missing in AST. https://llvm.org/PR42914
  EXPECT_DECLS("AutoTypeLoc");

  Code = R"cpp(
    template <typename... E>
    struct S {
      static const int size = sizeof...([[E]]);
    };
  )cpp";
  EXPECT_DECLS("SizeOfPackExpr", "typename ...E");

  Code = R"cpp(
    template <typename T>
    class Foo {
      void f([[Foo]] x);
    };
  )cpp";
  EXPECT_DECLS("InjectedClassNameTypeLoc", "class Foo");
}

TEST_F(TargetDeclTest, ClassTemplate) {
  Code = R"cpp(
    // Implicit specialization.
    template<int x> class Foo{};
    [[Foo<42>]] B;
  )cpp";
  EXPECT_DECLS("TemplateSpecializationTypeLoc",
               {"template<> class Foo<42>", Rel::TemplateInstantiation},
               {"class Foo", Rel::TemplatePattern});

  Code = R"cpp(
    template<typename T> class Foo {};
    // The "Foo<int>" SpecializationDecl is incomplete, there is no
    // instantiation happening.
    void func([[Foo<int>]] *);
  )cpp";
  EXPECT_DECLS("TemplateSpecializationTypeLoc",
               {"class Foo", Rel::TemplatePattern},
               {"template<> class Foo<int>", Rel::TemplateInstantiation});

  Code = R"cpp(
    // Explicit specialization.
    template<int x> class Foo{};
    template<> class Foo<42>{};
    [[Foo<42>]] B;
  )cpp";
  EXPECT_DECLS("TemplateSpecializationTypeLoc", "template<> class Foo<42>");

  Code = R"cpp(
    // Partial specialization.
    template<typename T> class Foo{};
    template<typename T> class Foo<T*>{};
    [[Foo<int*>]] B;
  )cpp";
  EXPECT_DECLS("TemplateSpecializationTypeLoc",
               {"template<> class Foo<int *>", Rel::TemplateInstantiation},
               {"template <typename T> class Foo<T *>", Rel::TemplatePattern});

  Code = R"cpp(
    // Template template argument.
    template<typename T> struct Vector {};
    template <template <typename> class Container>
    struct A {};
    A<[[Vector]]> a;
  )cpp";
  EXPECT_DECLS("TemplateArgumentLoc", {"template <typename T> struct Vector"});

  Flags.push_back("-std=c++17"); // for CTAD tests

  Code = R"cpp(
    // Class template argument deduction
    template <typename T>
    struct Test {
      Test(T);
    };
    void foo() {
      [[Test]] a(5);
    }
  )cpp";
  EXPECT_DECLS("DeducedTemplateSpecializationTypeLoc",
               {"struct Test", Rel::TemplatePattern});

  Code = R"cpp(
    // Deduction guide
    template <typename T>
    struct Test {
      template <typename I>
      Test(I, I);
    };
    template <typename I>
    [[Test]](I, I) -> Test<typename I::type>;
  )cpp";
  EXPECT_DECLS("CXXDeductionGuideDecl", {"template <typename T> struct Test"});
}

TEST_F(TargetDeclTest, Concept) {
  Flags.push_back("-std=c++20");

  // FIXME: Should we truncate the pretty-printed form of a concept decl
  // somewhere?

  Code = R"cpp(
    template <typename T>
    concept Fooable = requires (T t) { t.foo(); };

    template <typename T> requires [[Fooable]]<T>
    void bar(T t) {
      t.foo();
    }
  )cpp";
  EXPECT_DECLS(
      "ConceptReference",
      {"template <typename T> concept Fooable = requires (T t) { t.foo(); }"});

  // trailing requires clause
  Code = R"cpp(
      template <typename T>
      concept Fooable = true;

      template <typename T>
      void foo() requires [[Fooable]]<T>;
  )cpp";
  EXPECT_DECLS("ConceptReference",
               {"template <typename T> concept Fooable = true"});

  // constrained-parameter
  Code = R"cpp(
    template <typename T>
    concept Fooable = true;

    template <[[Fooable]] T>
    void bar(T t);
  )cpp";
  EXPECT_DECLS("ConceptReference",
               {"template <typename T> concept Fooable = true"});

  // partial-concept-id
  Code = R"cpp(
    template <typename T, typename U>
    concept Fooable = true;

    template <[[Fooable]]<int> T>
    void bar(T t);
  )cpp";
  EXPECT_DECLS("ConceptReference",
               {"template <typename T, typename U> concept Fooable = true"});
}

TEST_F(TargetDeclTest, Coroutine) {
  Flags.push_back("-std=c++20");

  Code = R"cpp(
    namespace std {
    template <typename, typename...> struct coroutine_traits;
    template <typename> struct coroutine_handle {
      template <typename U>
      coroutine_handle(coroutine_handle<U>&&) noexcept;
      static coroutine_handle from_address(void* __addr) noexcept;
    };
    } // namespace std

    struct executor {};
    struct awaitable {};
    struct awaitable_frame {
      awaitable get_return_object();
      void return_void();
      void unhandled_exception();
      struct result_t {
        ~result_t();
        bool await_ready() const noexcept;
        void await_suspend(std::coroutine_handle<void>) noexcept;
        void await_resume() const noexcept;
      };
      result_t initial_suspend() noexcept;
      result_t final_suspend() noexcept;
      result_t await_transform(executor) noexcept;
    };

    namespace std {
    template <>
    struct coroutine_traits<awaitable> {
      typedef awaitable_frame promise_type;
    };
    } // namespace std

    awaitable foo() {
      co_await [[executor]]();
    }
  )cpp";
  EXPECT_DECLS("RecordTypeLoc", "struct executor");
}

TEST_F(TargetDeclTest, RewrittenBinaryOperator) {
  Flags.push_back("-std=c++20");

  Code = R"cpp(
  namespace std {
    struct strong_ordering {
      int n;
      constexpr operator int() const { return n; }
      static const strong_ordering equal, greater, less;
    };
    constexpr strong_ordering strong_ordering::equal = {0};
    constexpr strong_ordering strong_ordering::greater = {1};
    constexpr strong_ordering strong_ordering::less = {-1};
    }

    struct Foo
    {
      int x;
      auto operator<=>(const Foo&) const = default;
    };

    bool x = (Foo(1) [[!=]] Foo(2));
  )cpp";
  EXPECT_DECLS("CXXRewrittenBinaryOperator",
               {"std::strong_ordering operator<=>(const Foo &) const = default",
                Rel::TemplatePattern},
               {"bool operator==(const Foo &) const noexcept = default",
                Rel::TemplateInstantiation});
}

TEST_F(TargetDeclTest, FunctionTemplate) {
  Code = R"cpp(
    // Implicit specialization.
    template<typename T> bool foo(T) { return false; };
    bool x = [[foo]](42);
  )cpp";
  EXPECT_DECLS("DeclRefExpr",
               {"template<> bool foo<int>(int)", Rel::TemplateInstantiation},
               {"bool foo(T)", Rel::TemplatePattern});

  Code = R"cpp(
    // Explicit specialization.
    template<typename T> bool foo(T) { return false; };
    template<> bool foo<int>(int) { return false; };
    bool x = [[foo]](42);
  )cpp";
  EXPECT_DECLS("DeclRefExpr", "template<> bool foo<int>(int)");
}

TEST_F(TargetDeclTest, VariableTemplate) {
  // Pretty-printer doesn't do a very good job of variable templates :-(
  Code = R"cpp(
    // Implicit specialization.
    template<typename T> int foo;
    int x = [[foo]]<char>;
  )cpp";
  EXPECT_DECLS("DeclRefExpr", {"int foo", Rel::TemplateInstantiation},
               {"int foo", Rel::TemplatePattern});

  Code = R"cpp(
    // Explicit specialization.
    template<typename T> int foo;
    template <> bool foo<char>;
    int x = [[foo]]<char>;
  )cpp";
  EXPECT_DECLS("DeclRefExpr", "bool foo");

  Code = R"cpp(
    // Partial specialization.
    template<typename T> int foo;
    template<typename T> bool foo<T*>;
    bool x = [[foo]]<char*>;
  )cpp";
  EXPECT_DECLS("DeclRefExpr", {"bool foo", Rel::TemplateInstantiation},
               {"bool foo", Rel::TemplatePattern});
}

TEST_F(TargetDeclTest, TypeAliasTemplate) {
  Code = R"cpp(
    template<typename T, int X> class SmallVector {};
    template<typename U> using TinyVector = SmallVector<U, 1>;
    [[TinyVector<int>]] X;
  )cpp";
  EXPECT_DECLS("TemplateSpecializationTypeLoc",
               {"template<> class SmallVector<int, 1>",
                Rel::TemplateInstantiation | Rel::Underlying},
               {"class SmallVector", Rel::TemplatePattern | Rel::Underlying},
               {"using TinyVector = SmallVector<U, 1>",
                Rel::Alias | Rel::TemplatePattern});
}

TEST_F(TargetDeclTest, BuiltinTemplates) {
  Code = R"cpp(
    template <class T, T... Index> struct integer_sequence {};
    [[__make_integer_seq]]<integer_sequence, int, 3> X;
  )cpp";
  EXPECT_DECLS(
      "TemplateSpecializationTypeLoc",
      {"struct integer_sequence", Rel::TemplatePattern | Rel::Underlying},
      {"template<> struct integer_sequence<int, <0, 1, 2>>",
       Rel::TemplateInstantiation | Rel::Underlying});

  // Dependent context.
  Code = R"cpp(
    template <class T, T... Index> struct integer_sequence;

    template <class T, int N>
    using make_integer_sequence = [[__make_integer_seq]]<integer_sequence, T, N>;
  )cpp";
  EXPECT_DECLS("TemplateSpecializationTypeLoc");

  Code = R"cpp(
    template <int N, class... Pack>
    using type_pack_element = [[__type_pack_element]]<N, Pack...>;
  )cpp";
  EXPECT_DECLS("TemplateSpecializationTypeLoc");
}

TEST_F(TargetDeclTest, MemberOfTemplate) {
  Code = R"cpp(
    template <typename T> struct Foo {
      int x(T);
    };
    int y = Foo<int>().[[x]](42);
  )cpp";
  EXPECT_DECLS("MemberExpr", {"int x(int)", Rel::TemplateInstantiation},
               {"int x(T)", Rel::TemplatePattern});

  Code = R"cpp(
    template <typename T> struct Foo {
      template <typename U>
      int x(T, U);
    };
    int y = Foo<char>().[[x]]('c', 42);
  )cpp";
  EXPECT_DECLS("MemberExpr",
               {"template<> int x<int>(char, int)", Rel::TemplateInstantiation},
               {"int x(T, U)", Rel::TemplatePattern});
}

TEST_F(TargetDeclTest, Lambda) {
  Code = R"cpp(
    void foo(int x = 42) {
      auto l = [ [[x]] ]{ return x + 1; };
    };
  )cpp";
  EXPECT_DECLS("DeclRefExpr", "int x = 42");

  // It seems like this should refer to another var, with the outer param being
  // an underlying decl. But it doesn't seem to exist.
  Code = R"cpp(
    void foo(int x = 42) {
      auto l = [x]{ return [[x]] + 1; };
    };
  )cpp";
  EXPECT_DECLS("DeclRefExpr", "int x = 42");

  Code = R"cpp(
    void foo() {
      auto l = [x = 1]{ return [[x]] + 1; };
    };
  )cpp";
  // FIXME: why both auto and int?
  EXPECT_DECLS("DeclRefExpr", "auto int x = 1");
}

TEST_F(TargetDeclTest, OverloadExpr) {
  Flags.push_back("--target=x86_64-pc-linux-gnu");

  Code = R"cpp(
    void func(int*);
    void func(char*);

    template <class T>
    void foo(T t) {
      [[func]](t);
    };
  )cpp";
  EXPECT_DECLS("UnresolvedLookupExpr", "void func(int *)", "void func(char *)");

  Code = R"cpp(
    struct X {
      void func(int*);
      void func(char*);
    };

    template <class T>
    void foo(X x, T t) {
      x.[[func]](t);
    };
  )cpp";
  EXPECT_DECLS("UnresolvedMemberExpr", "void func(int *)", "void func(char *)");

  Code = R"cpp(
    struct X {
      static void *operator new(unsigned long);
    };
    auto* k = [[new]] X();
  )cpp";
  EXPECT_DECLS("CXXNewExpr", "static void *operator new(unsigned long)");
  Code = R"cpp(
    void *operator new(unsigned long);
    auto* k = [[new]] int();
  )cpp";
  EXPECT_DECLS("CXXNewExpr", "void *operator new(unsigned long)");

  Code = R"cpp(
    struct X {
      static void operator delete(void *) noexcept;
    };
    void k(X* x) {
      [[delete]] x;
    }
  )cpp";
  EXPECT_DECLS("CXXDeleteExpr", "static void operator delete(void *) noexcept");
  Code = R"cpp(
    void operator delete(void *) noexcept;
    void k(int* x) {
      [[delete]] x;
    }
  )cpp";
  EXPECT_DECLS("CXXDeleteExpr", "void operator delete(void *) noexcept");
}

TEST_F(TargetDeclTest, DependentExprs) {
  // Heuristic resolution of method of dependent field
  Code = R"cpp(
        struct A { void foo() {} };
        template <typename T>
        struct B {
          A a;
          void bar() {
            this->a.[[foo]]();
          }
        };
      )cpp";
  EXPECT_DECLS("CXXDependentScopeMemberExpr", "void foo()");

  // Similar to above but base expression involves a function call.
  Code = R"cpp(
        struct A {
          void foo() {}
        };
        struct B {
          A getA();
        };
        template <typename T>
        struct C {
          B c;
          void bar() {
            this->c.getA().[[foo]]();
          }
        };
      )cpp";
  EXPECT_DECLS("CXXDependentScopeMemberExpr", "void foo()");

  // Similar to above but uses a function pointer.
  Code = R"cpp(
        struct A {
          void foo() {}
        };
        struct B {
          using FPtr = A(*)();
          FPtr fptr;
        };
        template <typename T>
        struct C {
          B c;
          void bar() {
            this->c.fptr().[[foo]]();
          }
        };
      )cpp";
  EXPECT_DECLS("CXXDependentScopeMemberExpr", "void foo()");

  // Base expression involves a member access into this.
  Code = R"cpp(
        struct Bar {
          int aaaa;
        };
        template <typename T> struct Foo {
          Bar func(int);
          void test() {
            func(1).[[aaaa]];
          }
        };
      )cpp";
  EXPECT_DECLS("CXXDependentScopeMemberExpr", "int aaaa");

  Code = R"cpp(
        class Foo {
        public:
          static Foo k(int);
          template <typename T> T convert() const;
        };
        template <typename T>
        void test() {
          Foo::k(T()).template [[convert]]<T>();
        }
      )cpp";
  EXPECT_DECLS("CXXDependentScopeMemberExpr",
               "template <typename T> T convert() const");

  Code = R"cpp(
        template <typename T>
        struct Waldo {
          void find();
        };
        template <typename T>
        using Wally = Waldo<T>;
        template <typename T>
        void foo(Wally<T> w) {
          w.[[find]]();
        }
  )cpp";
  EXPECT_DECLS("CXXDependentScopeMemberExpr", "void find()");

  Code = R"cpp(
        template <typename T>
        struct Waldo {
          void find();
        };
        template <typename T>
        struct MetaWaldo {
          using Type = Waldo<T>;
        };
        template <typename T>
        void foo(typename MetaWaldo<T>::Type w) {
          w.[[find]]();
        }
  )cpp";
  EXPECT_DECLS("CXXDependentScopeMemberExpr", "void find()");

  Code = R"cpp(
        struct Waldo {
          void find();
        };
        template <typename T>
        using Wally = Waldo;
        template <typename>
        struct S : Wally<int> {
          void Foo() { this->[[find]](); }
        };
  )cpp";
  EXPECT_DECLS("CXXDependentScopeMemberExpr", "void find()");
}

TEST_F(TargetDeclTest, DependentTypes) {
  // Heuristic resolution of dependent type name
  Code = R"cpp(
        template <typename>
        struct A { struct B {}; };

        template <typename T>
        void foo(typename A<T>::[[B]]);
      )cpp";
  EXPECT_DECLS("DependentNameTypeLoc", "struct B");

  // Heuristic resolution of dependent type name which doesn't get a TypeLoc
  Code = R"cpp(
        template <typename>
        struct A { struct B { struct C {}; }; };

        template <typename T>
        void foo(typename A<T>::[[B]]::C);
      )cpp";
  EXPECT_DECLS("NestedNameSpecifierLoc", "struct B");

  // Heuristic resolution of dependent type name whose qualifier is also
  // dependent
  Code = R"cpp(
        template <typename>
        struct A { struct B { struct C {}; }; };

        template <typename T>
        void foo(typename A<T>::B::[[C]]);
      )cpp";
  EXPECT_DECLS("DependentNameTypeLoc", "struct C");

  // Heuristic resolution of dependent template name
  Code = R"cpp(
        template <typename>
        struct A {
          template <typename> struct B {};
        };

        template <typename T>
        void foo(typename A<T>::template [[B]]<int>);
      )cpp";
  EXPECT_DECLS("DependentTemplateSpecializationTypeLoc",
               "template <typename> struct B");

  // Dependent name with recursive definition. We don't expect a
  // result, but we shouldn't get into a stack overflow either.
  Code = R"cpp(
        template <int N>
        struct waldo {
          typedef typename waldo<N - 1>::type::[[next]] type;
        };
  )cpp";
  EXPECT_DECLS("DependentNameTypeLoc");

  // Similar to above but using mutually recursive templates.
  Code = R"cpp(
        template <int N>
        struct odd;

        template <int N>
        struct even {
          using type = typename odd<N - 1>::type::next;
        };

        template <int N>
        struct odd {
          using type = typename even<N - 1>::type::[[next]];
        };
  )cpp";
  EXPECT_DECLS("DependentNameTypeLoc");
}

TEST_F(TargetDeclTest, TypedefCascade) {
  Code = R"cpp(
        struct C {
          using type = int;
        };
        struct B {
          using type = C::type;
        };
        struct A {
          using type = B::type;
        };
        A::[[type]] waldo;
  )cpp";
  EXPECT_DECLS("TypedefTypeLoc",
               {"using type = int", Rel::Alias | Rel::Underlying},
               {"using type = C::type", Rel::Alias | Rel::Underlying},
               {"using type = B::type", Rel::Alias});
}

TEST_F(TargetDeclTest, RecursiveTemplate) {
  Flags.push_back("-std=c++20"); // the test case uses concepts

  Code = R"cpp(
        template <typename T>
        concept Leaf = false;

        template <typename Tree>
        struct descend_left {
          using type = typename descend_left<typename Tree::left>::[[type]];
        };

        template <Leaf Tree>
        struct descend_left<Tree> {
          using type = typename Tree::value;
        };
  )cpp";
  EXPECT_DECLS("DependentNameTypeLoc",
               {"using type = typename descend_left<typename Tree::left>::type",
                Rel::Alias | Rel::Underlying});
}

TEST_F(TargetDeclTest, ObjC) {
  Flags = {"-xobjective-c"};
  Code = R"cpp(
    @interface Foo {}
    -(void)bar;
    @end
    void test(Foo *f) {
      [f [[bar]] ];
    }
  )cpp";
  EXPECT_DECLS("ObjCMessageExpr", "- (void)bar");

  Code = R"cpp(
    @interface Foo { @public int bar; }
    @end
    int test(Foo *f) {
      return [[f->bar]];
    }
  )cpp";
  EXPECT_DECLS("ObjCIvarRefExpr", "int bar");

  Code = R"cpp(
    @interface Foo {}
    -(int) x;
    -(void) setX:(int)x;
    @end
    void test(Foo *f) {
      [[f.x]] = 42;
    }
  )cpp";
  EXPECT_DECLS("ObjCPropertyRefExpr", "- (void)setX:(int)x");

  Code = R"cpp(
    @interface I {}
    @property(retain) I* x;
    @property(retain) I* y;
    @end
    void test(I *f) {
      [[f.x]].y = 0;
    }
  )cpp";
  EXPECT_DECLS("ObjCPropertyRefExpr",
               "@property(atomic, retain, readwrite) I *x");

  Code = R"cpp(
    @interface MYObject
    @end
    @interface Interface
    @property(retain) [[MYObject]] *x;
    @end
  )cpp";
  EXPECT_DECLS("ObjCInterfaceTypeLoc", "@interface MYObject");

  Code = R"cpp(
    @interface MYObject2
    @end
    @interface Interface
    @property(retain, nonnull) [[MYObject2]] *x;
    @end
  )cpp";
  EXPECT_DECLS("ObjCInterfaceTypeLoc", "@interface MYObject2");

  Code = R"cpp(
    @protocol Foo
    @end
    id test() {
      return [[@protocol(Foo)]];
    }
  )cpp";
  EXPECT_DECLS("ObjCProtocolExpr", "@protocol Foo");

  Code = R"cpp(
    @interface Foo
    @end
    void test([[Foo]] *p);
  )cpp";
  EXPECT_DECLS("ObjCInterfaceTypeLoc", "@interface Foo");

  Code = R"cpp(// Don't consider implicit interface as the target.
    @implementation [[Implicit]]
    @end
  )cpp";
  EXPECT_DECLS("ObjCImplementationDecl", "@implementation Implicit");

  Code = R"cpp(
    @interface Foo
    @end
    @implementation [[Foo]]
    @end
  )cpp";
  EXPECT_DECLS("ObjCImplementationDecl", "@interface Foo");

  Code = R"cpp(
    @interface Foo
    @end
    @interface Foo (Ext)
    @end
    @implementation [[Foo]] (Ext)
    @end
  )cpp";
  EXPECT_DECLS("ObjCCategoryImplDecl", "@interface Foo(Ext)");

  Code = R"cpp(
    @interface Foo
    @end
    @interface Foo (Ext)
    @end
    @implementation Foo ([[Ext]])
    @end
  )cpp";
  EXPECT_DECLS("ObjCCategoryImplDecl", "@interface Foo(Ext)");

  Code = R"cpp(
    void test(id</*error-ok*/[[InvalidProtocol]]> p);
  )cpp";
  EXPECT_DECLS("ParmVarDecl", "id p");

  Code = R"cpp(
    @class C;
    @protocol Foo
    @end
    void test([[C]]<Foo> *p);
  )cpp";
  EXPECT_DECLS("ObjCInterfaceTypeLoc", "@class C;");

  Code = R"cpp(
    @class C;
    @protocol Foo
    @end
    void test(C<[[Foo]]> *p);
  )cpp";
  EXPECT_DECLS("ObjCProtocolLoc", "@protocol Foo");

  Code = R"cpp(
    @class C;
    @protocol Foo
    @end
    @protocol Bar
    @end
    void test(C<[[Foo]], Bar> *p);
  )cpp";
  EXPECT_DECLS("ObjCProtocolLoc", "@protocol Foo");

  Code = R"cpp(
    @class C;
    @protocol Foo
    @end
    @protocol Bar
    @end
    void test(C<Foo, [[Bar]]> *p);
  )cpp";
  EXPECT_DECLS("ObjCProtocolLoc", "@protocol Bar");

  Code = R"cpp(
    @interface Foo
    + (id)sharedInstance;
    @end
    @implementation Foo
    + (id)sharedInstance { return 0; }
    @end
    void test() {
      id value = [[Foo]].sharedInstance;
    }
  )cpp";
  EXPECT_DECLS("ObjCInterfaceTypeLoc", "@interface Foo");

  Code = R"cpp(
    @interface Foo
    + (id)sharedInstance;
    @end
    @implementation Foo
    + (id)sharedInstance { return 0; }
    @end
    void test() {
      id value = Foo.[[sharedInstance]];
    }
  )cpp";
  EXPECT_DECLS("ObjCPropertyRefExpr", "+ (id)sharedInstance");

  Code = R"cpp(
    @interface Foo
    + ([[id]])sharedInstance;
    @end
  )cpp";
  EXPECT_DECLS("TypedefTypeLoc");

  Code = R"cpp(
    @interface Foo
    + ([[instancetype]])sharedInstance;
    @end
  )cpp";
  EXPECT_DECLS("TypedefTypeLoc");
}

class FindExplicitReferencesTest : public ::testing::Test {
protected:
  struct AllRefs {
    std::string AnnotatedCode;
    std::string DumpedReferences;
  };

  TestTU newTU(llvm::StringRef Code) {
    TestTU TU;
    TU.Code = std::string(Code);

    // FIXME: Auto-completion in a template requires disabling delayed template
    // parsing.
    TU.ExtraArgs.push_back("-std=c++20");
    TU.ExtraArgs.push_back("-xobjective-c++");

    return TU;
  }

  AllRefs annotatedReferences(llvm::StringRef Code, ParsedAST &AST,
                              std::vector<ReferenceLoc> Refs) {
    auto &SM = AST.getSourceManager();
    llvm::stable_sort(Refs, [&](const ReferenceLoc &L, const ReferenceLoc &R) {
      return SM.isBeforeInTranslationUnit(L.NameLoc, R.NameLoc);
    });

    std::string AnnotatedCode;
    unsigned NextCodeChar = 0;
    for (unsigned I = 0; I < Refs.size(); ++I) {
      auto &R = Refs[I];

      SourceLocation Pos = R.NameLoc;
      assert(Pos.isValid());
      if (Pos.isMacroID()) // FIXME: figure out how to show macro locations.
        Pos = SM.getExpansionLoc(Pos);
      assert(Pos.isFileID());

      FileID File;
      unsigned Offset;
      std::tie(File, Offset) = SM.getDecomposedLoc(Pos);
      if (File == SM.getMainFileID()) {
        // Print the reference in a source code.
        assert(NextCodeChar <= Offset);
        AnnotatedCode += Code.substr(NextCodeChar, Offset - NextCodeChar);
        AnnotatedCode += "$" + std::to_string(I) + "^";

        NextCodeChar = Offset;
      }
    }
    AnnotatedCode += Code.substr(NextCodeChar);

    std::string DumpedReferences;
    for (unsigned I = 0; I < Refs.size(); ++I)
      DumpedReferences += std::string(llvm::formatv("{0}: {1}\n", I, Refs[I]));

    return AllRefs{std::move(AnnotatedCode), std::move(DumpedReferences)};
  }

  /// Parses \p Code, and annotates its body with results of
  /// findExplicitReferences on all top level decls.
  /// See actual tests for examples of annotation format.
  AllRefs annotateAllReferences(llvm::StringRef Code) {
    TestTU TU = newTU(Code);
    auto AST = TU.build();

    std::vector<ReferenceLoc> Refs;
    for (auto *TopLevel : AST.getLocalTopLevelDecls())
      findExplicitReferences(
          TopLevel, [&Refs](ReferenceLoc R) { Refs.push_back(std::move(R)); },
          AST.getHeuristicResolver());
    return annotatedReferences(Code, AST, std::move(Refs));
  }

  /// Parses \p Code, finds function or namespace '::foo' and annotates its body
  /// with results of findExplicitReferences.
  /// See actual tests for examples of annotation format.
  AllRefs annotateReferencesInFoo(llvm::StringRef Code) {
    TestTU TU = newTU(Code);
    auto AST = TU.build();
    auto *TestDecl = &findDecl(AST, "foo");
    if (auto *T = llvm::dyn_cast<FunctionTemplateDecl>(TestDecl))
      TestDecl = T->getTemplatedDecl();

    std::vector<ReferenceLoc> Refs;
    if (const auto *Func = llvm::dyn_cast<FunctionDecl>(TestDecl))
      findExplicitReferences(
          Func->getBody(),
          [&Refs](ReferenceLoc R) { Refs.push_back(std::move(R)); },
          AST.getHeuristicResolver());
    else if (const auto *NS = llvm::dyn_cast<NamespaceDecl>(TestDecl))
      findExplicitReferences(
          NS,
          [&Refs, &NS](ReferenceLoc R) {
            // Avoid adding the namespace foo decl to the results.
            if (R.Targets.size() == 1 && R.Targets.front() == NS)
              return;
            Refs.push_back(std::move(R));
          },
          AST.getHeuristicResolver());
    else if (const auto *OC = llvm::dyn_cast<ObjCContainerDecl>(TestDecl))
      findExplicitReferences(
          OC, [&Refs](ReferenceLoc R) { Refs.push_back(std::move(R)); },
          AST.getHeuristicResolver());
    else
      ADD_FAILURE() << "Failed to find ::foo decl for test";

    return annotatedReferences(Code, AST, std::move(Refs));
  }
};

TEST_F(FindExplicitReferencesTest, AllRefsInFoo) {
  std::pair</*Code*/ llvm::StringRef, /*References*/ llvm::StringRef> Cases[] =
      {// Simple expressions.
       {R"cpp(
        int global;
        int func();
        void foo(int param) {
          $0^global = $1^param + $2^func();
        }
        )cpp",
        "0: targets = {global}\n"
        "1: targets = {param}\n"
        "2: targets = {func}\n"},
       {R"cpp(
        struct X { int a; };
        void foo(X x) {
          $0^x.$1^a = 10;
        }
        )cpp",
        "0: targets = {x}\n"
        "1: targets = {X::a}\n"},
       {R"cpp(
        // error-ok: testing with broken code
        int bar();
        int foo() {
          return $0^bar() + $1^bar(42);
        }
        )cpp",
        "0: targets = {bar}\n"
        "1: targets = {bar}\n"},
       // Namespaces and aliases.
       {R"cpp(
          namespace ns {}
          namespace alias = ns;
          void foo() {
            using namespace $0^ns;
            using namespace $1^alias;
          }
        )cpp",
        "0: targets = {ns}\n"
        "1: targets = {alias}\n"},
       // Using declarations.
       {R"cpp(
          namespace ns { int global; }
          void foo() {
            using $0^ns::$1^global;
          }
        )cpp",
        "0: targets = {ns}\n"
        "1: targets = {ns::global}, qualifier = 'ns::'\n"},
       // Using enum declarations.
       {R"cpp(
          namespace ns { enum class A {}; }
          void foo() {
            using enum $0^ns::$1^A;
          }
        )cpp",
        "0: targets = {ns}\n"
        "1: targets = {ns::A}, qualifier = 'ns::'\n"},
       // Simple types.
       {R"cpp(
         struct Struct { int a; };
         using Typedef = int;
         void foo() {
           $0^Struct $1^x;
           $2^Typedef $3^y;
           static_cast<$4^Struct*>(0);
         }
       )cpp",
        "0: targets = {Struct}\n"
        "1: targets = {x}, decl\n"
        "2: targets = {Typedef}\n"
        "3: targets = {y}, decl\n"
        "4: targets = {Struct}\n"},
       // Name qualifiers.
       {R"cpp(
         namespace a { namespace b { struct S { typedef int type; }; } }
         void foo() {
           $0^a::$1^b::$2^S $3^x;
           using namespace $4^a::$5^b;
           $6^S::$7^type $8^y;
         }
        )cpp",
        "0: targets = {a}\n"
        "1: targets = {a::b}, qualifier = 'a::'\n"
        "2: targets = {a::b::S}, qualifier = 'a::b::'\n"
        "3: targets = {x}, decl\n"
        "4: targets = {a}\n"
        "5: targets = {a::b}, qualifier = 'a::'\n"
        "6: targets = {a::b::S}\n"
        "7: targets = {a::b::S::type}, qualifier = 'struct S::'\n"
        "8: targets = {y}, decl\n"},
       {R"cpp(
         void foo() {
           $0^ten: // PRINT "HELLO WORLD!"
           goto $1^ten;
         }
       )cpp",
        "0: targets = {ten}, decl\n"
        "1: targets = {ten}\n"},
       // Simple templates.
       {R"cpp(
          template <class T> struct vector { using value_type = T; };
          template <> struct vector<bool> { using value_type = bool; };
          void foo() {
            $0^vector<int> $1^vi;
            $2^vector<bool> $3^vb;
          }
        )cpp",
        "0: targets = {vector<int>}\n"
        "1: targets = {vi}, decl\n"
        "2: targets = {vector<bool>}\n"
        "3: targets = {vb}, decl\n"},
       // Template type aliases.
       {R"cpp(
            template <class T> struct vector { using value_type = T; };
            template <> struct vector<bool> { using value_type = bool; };
            template <class T> using valias = vector<T>;
            void foo() {
              $0^valias<int> $1^vi;
              $2^valias<bool> $3^vb;
            }
          )cpp",
        "0: targets = {valias}\n"
        "1: targets = {vi}, decl\n"
        "2: targets = {valias}\n"
        "3: targets = {vb}, decl\n"},
       // Injected class name.
       {R"cpp(
            namespace foo {
              template <typename $0^T>
              class $1^Bar {
                ~$2^Bar();
                void $3^f($4^Bar);
              };
            }
          )cpp",
        "0: targets = {foo::Bar::T}, decl\n"
        "1: targets = {foo::Bar}, decl\n"
        "2: targets = {foo::Bar}\n"
        "3: targets = {foo::Bar::f}, decl\n"
        "4: targets = {foo::Bar}\n"},
       // MemberExpr should know their using declaration.
       {R"cpp(
            struct X { void func(int); };
            struct Y : X {
              using X::func;
            };
            void foo(Y y) {
              $0^y.$1^func(1);
            }
        )cpp",
        "0: targets = {y}\n"
        "1: targets = {Y::func}\n"},
       // DeclRefExpr should know their using declaration.
       {R"cpp(
            namespace ns { void bar(int); }
            using ns::bar;

            void foo() {
              $0^bar(10);
            }
        )cpp",
        "0: targets = {bar}\n"},
       // References from a macro.
       {R"cpp(
            #define FOO a
            #define BAR b

            void foo(int a, int b) {
              $0^FOO+$1^BAR;
            }
        )cpp",
        "0: targets = {a}\n"
        "1: targets = {b}\n"},
       // No references from implicit nodes.
       {R"cpp(
            struct vector {
              int *begin();
              int *end();
            };

            void foo() {
              for (int $0^x : $1^vector()) {
                $2^x = 10;
              }
            }
        )cpp",
        "0: targets = {x}, decl\n"
        "1: targets = {vector}\n"
        "2: targets = {x}\n"},
       // Handle UnresolvedLookupExpr.
       {R"cpp(
            namespace ns1 { void func(char*); }
            namespace ns2 { void func(int*); }
            using namespace ns1;
            using namespace ns2;

            template <class T>
            void foo(T t) {
              $0^func($1^t);
            }
        )cpp",
        "0: targets = {ns1::func, ns2::func}\n"
        "1: targets = {t}\n"},
       // Handle UnresolvedMemberExpr.
       {R"cpp(
            struct X {
              void func(char*);
              void func(int*);
            };

            template <class T>
            void foo(X x, T t) {
              $0^x.$1^func($2^t);
            }
        )cpp",
        "0: targets = {x}\n"
        "1: targets = {X::func, X::func}\n"
        "2: targets = {t}\n"},
       // Handle DependentScopeDeclRefExpr.
       {R"cpp(
            template <class T>
            struct S {
              static int value;
            };

            template <class T>
            void foo() {
              $0^S<$1^T>::$2^value;
            }
       )cpp",
        "0: targets = {S}\n"
        "1: targets = {T}\n"
        "2: targets = {S::value}, qualifier = 'S<T>::'\n"},
       // Handle CXXDependentScopeMemberExpr.
       {R"cpp(
            template <class T>
            struct S {
              int value;
            };

            template <class T>
            void foo(S<T> t) {
              $0^t.$1^value;
            }
       )cpp",
        "0: targets = {t}\n"
        "1: targets = {S::value}\n"},
       // Type template parameters.
       {R"cpp(
            template <class T>
            void foo() {
              static_cast<$0^T>(0);
              $1^T();
              $2^T $3^t;
            }
        )cpp",
        "0: targets = {T}\n"
        "1: targets = {T}\n"
        "2: targets = {T}\n"
        "3: targets = {t}, decl\n"},
       // Non-type template parameters.
       {R"cpp(
            template <int I>
            void foo() {
              int $0^x = $1^I;
            }
        )cpp",
        "0: targets = {x}, decl\n"
        "1: targets = {I}\n"},
       // Template template parameters.
       {R"cpp(
            template <class T> struct vector {};

            template <template<class> class TT, template<class> class ...TP>
            void foo() {
              $0^TT<int> $1^x;
              $2^foo<$3^TT>();
              $4^foo<$5^vector>();
              $6^foo<$7^TP...>();
            }
        )cpp",
        "0: targets = {TT}\n"
        "1: targets = {x}, decl\n"
        "2: targets = {foo}\n"
        "3: targets = {TT}\n"
        "4: targets = {foo}\n"
        "5: targets = {vector}\n"
        "6: targets = {foo}\n"
        "7: targets = {TP}\n"},
       // Non-type template parameters with declarations.
       {R"cpp(
            int func();
            template <int(*)()> struct wrapper {};

            template <int(*FuncParam)()>
            void foo() {
              $0^wrapper<$1^func> $2^w;
              $3^FuncParam();
            }
        )cpp",
        "0: targets = {wrapper<&func>}\n"
        "1: targets = {func}\n"
        "2: targets = {w}, decl\n"
        "3: targets = {FuncParam}\n"},
       // declaration references.
       {R"cpp(
             namespace ns {}
             class S {};
             void foo() {
               class $0^Foo { $1^Foo(); ~$2^Foo(); int $3^field; };
               int $4^Var;
               enum $5^E { $6^ABC };
               typedef int $7^INT;
               using $8^INT2 = int;
               namespace $9^NS = $10^ns;
             }
           )cpp",
        "0: targets = {Foo}, decl\n"
        "1: targets = {foo()::Foo::Foo}, decl\n"
        "2: targets = {Foo}\n"
        "3: targets = {foo()::Foo::field}, decl\n"
        "4: targets = {Var}, decl\n"
        "5: targets = {E}, decl\n"
        "6: targets = {foo()::ABC}, decl\n"
        "7: targets = {INT}, decl\n"
        "8: targets = {INT2}, decl\n"
        "9: targets = {NS}, decl\n"
        "10: targets = {ns}\n"},
       // User-defined conversion operator.
       {R"cpp(
            void foo() {
               class $0^Bar {};
               class $1^Foo {
               public:
                 // FIXME: This should have only one reference to Bar.
                 $2^operator $3^$4^Bar();
               };

               $5^Foo $6^f;
               $7^f.$8^operator $9^Bar();
            }
        )cpp",
        "0: targets = {Bar}, decl\n"
        "1: targets = {Foo}, decl\n"
        "2: targets = {foo()::Foo::operator Bar}, decl\n"
        "3: targets = {Bar}\n"
        "4: targets = {Bar}\n"
        "5: targets = {Foo}\n"
        "6: targets = {f}, decl\n"
        "7: targets = {f}\n"
        "8: targets = {foo()::Foo::operator Bar}\n"
        "9: targets = {Bar}\n"},
       // Destructor.
       {R"cpp(
             void foo() {
               class $0^Foo {
               public:
                 ~$1^Foo() {}

                 void $2^destructMe() {
                   this->~$3^Foo();
                 }
               };

               $4^Foo $5^f;
               $6^f.~ /*...*/ $7^Foo();
             }
           )cpp",
        "0: targets = {Foo}, decl\n"
        // FIXME: It's better to target destructor's FunctionDecl instead of
        // the type itself (similar to constructor).
        "1: targets = {Foo}\n"
        "2: targets = {foo()::Foo::destructMe}, decl\n"
        "3: targets = {Foo}\n"
        "4: targets = {Foo}\n"
        "5: targets = {f}, decl\n"
        "6: targets = {f}\n"
        "7: targets = {Foo}\n"},
       // cxx constructor initializer.
       {R"cpp(
             class Base {};
             void foo() {
               // member initializer
               class $0^X {
                 int $1^abc;
                 $2^X(): $3^abc() {}
               };
               // base initializer
               class $4^Derived : public $5^Base {
                 $6^Base $7^B;
                 $8^Derived() : $9^Base() {}
               };
               // delegating initializer
               class $10^Foo {
                 $11^Foo(int);
                 $12^Foo(): $13^Foo(111) {}
               };
             }
           )cpp",
        "0: targets = {X}, decl\n"
        "1: targets = {foo()::X::abc}, decl\n"
        "2: targets = {foo()::X::X}, decl\n"
        "3: targets = {foo()::X::abc}\n"
        "4: targets = {Derived}, decl\n"
        "5: targets = {Base}\n"
        "6: targets = {Base}\n"
        "7: targets = {foo()::Derived::B}, decl\n"
        "8: targets = {foo()::Derived::Derived}, decl\n"
        "9: targets = {Base}\n"
        "10: targets = {Foo}, decl\n"
        "11: targets = {foo()::Foo::Foo}, decl\n"
        "12: targets = {foo()::Foo::Foo}, decl\n"
        "13: targets = {Foo}\n"},
       // Anonymous entities should not be reported.
       {
           R"cpp(
             void foo() {
              $0^class {} $1^x;
              int (*$2^fptr)(int $3^a, int) = nullptr;
             }
           )cpp",
           "0: targets = {(unnamed)}\n"
           "1: targets = {x}, decl\n"
           "2: targets = {fptr}, decl\n"
           "3: targets = {a}, decl\n"},
       // Namespace aliases should be handled properly.
       {
           R"cpp(
                namespace ns { struct Type {}; }
                namespace alias = ns;
                namespace rec_alias = alias;

                void foo() {
                  $0^ns::$1^Type $2^a;
                  $3^alias::$4^Type $5^b;
                  $6^rec_alias::$7^Type $8^c;
                }
           )cpp",
           "0: targets = {ns}\n"
           "1: targets = {ns::Type}, qualifier = 'ns::'\n"
           "2: targets = {a}, decl\n"
           "3: targets = {alias}\n"
           "4: targets = {ns::Type}, qualifier = 'alias::'\n"
           "5: targets = {b}, decl\n"
           "6: targets = {rec_alias}\n"
           "7: targets = {ns::Type}, qualifier = 'rec_alias::'\n"
           "8: targets = {c}, decl\n"},
       // Handle SizeOfPackExpr.
       {
           R"cpp(
                template <typename... E>
                void foo() {
                  constexpr int $0^size = sizeof...($1^E);
                };
            )cpp",
           "0: targets = {size}, decl\n"
           "1: targets = {E}\n"},
       // Class template argument deduction
       {
           R"cpp(
                template <typename T>
                struct Test {
                Test(T);
              };
              void foo() {
                $0^Test $1^a(5);
              }
            )cpp",
           "0: targets = {Test}\n"
           "1: targets = {a}, decl\n"},
       // Templates
       {R"cpp(
            namespace foo {
              template <typename $0^T>
              class $1^Bar {};
            }
          )cpp",
        "0: targets = {foo::Bar::T}, decl\n"
        "1: targets = {foo::Bar}, decl\n"},
       // Templates
       {R"cpp(
            namespace foo {
              template <typename $0^T>
              void $1^func();
            }
          )cpp",
        "0: targets = {T}, decl\n"
        "1: targets = {foo::func}, decl\n"},
       // Templates
       {R"cpp(
            namespace foo {
              template <typename $0^T>
              $1^T $2^x;
            }
          )cpp",
        "0: targets = {foo::T}, decl\n"
        "1: targets = {foo::T}\n"
        "2: targets = {foo::x}, decl\n"},
       // Templates
       {R"cpp(
            template<typename T> class vector {};
            namespace foo {
              template <typename $0^T>
              using $1^V = $2^vector<$3^T>;
            }
          )cpp",
        "0: targets = {foo::T}, decl\n"
        "1: targets = {foo::V}, decl\n"
        "2: targets = {vector}\n"
        "3: targets = {foo::T}\n"},
       // Concept
       {
           R"cpp(
              template <typename T>
              concept Drawable = requires (T t) { t.draw(); };

              namespace foo {
                template <typename $0^T> requires $1^Drawable<$2^T>
                void $3^bar($4^T $5^t) {
                  $6^t.$7^draw();
                }
              }
          )cpp",
           "0: targets = {T}, decl\n"
           "1: targets = {Drawable}\n"
           "2: targets = {T}\n"
           "3: targets = {foo::bar}, decl\n"
           "4: targets = {T}\n"
           "5: targets = {t}, decl\n"
           "6: targets = {t}\n"
           "7: targets = {}\n"},
       // Objective-C: instance variables
       {
           R"cpp(
            @interface I {
            @public
              I *_z;
            }
            @end
            I *f;
            void foo() {
              $0^f->$1^_z = 0;
            }
          )cpp",
           "0: targets = {f}\n"
           "1: targets = {I::_z}\n"},
       // Objective-C: properties
       {
           R"cpp(
            @interface I {}
            @property(retain) I* x;
            @property(retain) I* y;
            @end
            I *f;
            void foo() {
              $0^f.$1^x.$2^y = 0;
            }
          )cpp",
           "0: targets = {f}\n"
           "1: targets = {I::x}\n"
           "2: targets = {I::y}\n"},
       // Objective-C: implicit properties
       {
           R"cpp(
            @interface I {}
            -(I*)x;
            -(void)setY:(I*)y;
            @end
            I *f;
            void foo() {
              $0^f.$1^x.$2^y = 0;
            }
          )cpp",
           "0: targets = {f}\n"
           "1: targets = {I::x}\n"
           "2: targets = {I::setY:}\n"},
       // Objective-C: class properties
       {
           R"cpp(
            @interface I {}
            @property(class) I *x;
            @end
            id local;
            void foo() {
              $0^I.$1^x = 0;
              $2^local = $3^I.$4^x;
            }
          )cpp",
           "0: targets = {I}\n"
           "1: targets = {I::setX:}\n"
           "2: targets = {local}\n"
           "3: targets = {I}\n"
           "4: targets = {I::x}\n"},
       // Objective-C: implicit class properties
       {
           R"cpp(
            @interface I {}
            +(I*)x;
            +(void)setX:(I*)x;
            @end
            id local;
            void foo() {
              $0^I.$1^x = 0;
              $2^local = $3^I.$4^x;
            }
          )cpp",
           "0: targets = {I}\n"
           "1: targets = {I::setX:}\n"
           "2: targets = {local}\n"
           "3: targets = {I}\n"
           "4: targets = {I::x}\n"},
       {// Objective-C: methods
        R"cpp(
            @interface I
              -(void) a:(int)x b:(int)y;
            @end
            void foo(I *i) {
              [$0^i $1^a:1 b:2];
            }
          )cpp",
        "0: targets = {i}\n"
        "1: targets = {I::a:b:}\n"},
       {// Objective-C: protocols
        R"cpp(
            @interface I
            @end
            @protocol P
            @end
            void foo() {
              $0^I<$1^P> *$2^x;
            }
          )cpp",
        "0: targets = {I}\n"
        "1: targets = {P}\n"
        "2: targets = {x}, decl\n"},

       // Designated initializers.
       {R"cpp(
            void foo() {
              struct $0^Foo {
                int $1^Bar;
              };
              $2^Foo $3^f { .$4^Bar = 42 };
            }
        )cpp",
        "0: targets = {Foo}, decl\n"
        "1: targets = {foo()::Foo::Bar}, decl\n"
        "2: targets = {Foo}\n"
        "3: targets = {f}, decl\n"
        "4: targets = {foo()::Foo::Bar}\n"},
       {R"cpp(
            void foo() {
              struct $0^Baz {
                int $1^Field;
              };
              struct $2^Bar {
                $3^Baz $4^Foo;
              };
              $5^Bar $6^bar { .$7^Foo.$8^Field = 42 };
            }
        )cpp",
        "0: targets = {Baz}, decl\n"
        "1: targets = {foo()::Baz::Field}, decl\n"
        "2: targets = {Bar}, decl\n"
        "3: targets = {Baz}\n"
        "4: targets = {foo()::Bar::Foo}, decl\n"
        "5: targets = {Bar}\n"
        "6: targets = {bar}, decl\n"
        "7: targets = {foo()::Bar::Foo}\n"
        "8: targets = {foo()::Baz::Field}\n"},
       {R"cpp(
           template<typename T>
           void crash(T);
           template<typename T>
           void foo() {
             $0^crash({.$1^x = $2^T()});
           }
        )cpp",
        "0: targets = {crash}\n"
        "1: targets = {}\n"
        "2: targets = {T}\n"},
       // unknown template name should not crash.
       {R"cpp(
        template <template <typename> typename T>
        struct Base {};
        namespace foo {
        template <typename $0^T>
        struct $1^Derive : $2^Base<$3^T::template $4^Unknown> {};
        }
      )cpp",
        "0: targets = {foo::Derive::T}, decl\n"
        "1: targets = {foo::Derive}, decl\n"
        "2: targets = {Base}\n"
        "3: targets = {foo::Derive::T}\n"
        "4: targets = {}, qualifier = 'T::'\n"},
       // deduction guide
       {R"cpp(
          namespace foo {
            template <typename $0^T>
            struct $1^Test {
              template <typename $2^I>
              $3^Test($4^I);
            };
            template <typename $5^I>
            $6^Test($7^I) -> $8^Test<typename $9^I::$10^type>;
          }
        )cpp",
        "0: targets = {T}, decl\n"
        "1: targets = {foo::Test}, decl\n"
        "2: targets = {I}, decl\n"
        "3: targets = {foo::Test::Test<T>}, decl\n"
        "4: targets = {I}\n"
        "5: targets = {I}, decl\n"
        "6: targets = {foo::Test}\n"
        "7: targets = {I}\n"
        "8: targets = {foo::Test}\n"
        "9: targets = {I}\n"
        "10: targets = {}, qualifier = 'I::'\n"}};

  for (const auto &C : Cases) {
    llvm::StringRef ExpectedCode = C.first;
    llvm::StringRef ExpectedRefs = C.second;

    auto Actual =
        annotateReferencesInFoo(llvm::Annotations(ExpectedCode).code());
    EXPECT_EQ(ExpectedCode, Actual.AnnotatedCode);
    EXPECT_EQ(ExpectedRefs, Actual.DumpedReferences) << ExpectedCode;
  }
}

TEST_F(FindExplicitReferencesTest, AllRefs) {
  std::pair</*Code*/ llvm::StringRef, /*References*/ llvm::StringRef> Cases[] =
      {{R"cpp(
      @interface $0^MyClass
      @end
      @implementation $1^$2^MyClass
      @end
      )cpp",
        "0: targets = {MyClass}, decl\n"
        "1: targets = {MyClass}\n"
        "2: targets = {MyClass}, decl\n"},
       {R"cpp(
      @interface $0^MyClass
      @end
      @interface $1^MyClass ($2^Category)
      @end
      @implementation $3^MyClass ($4^$5^Category)
      @end
      )cpp",
        "0: targets = {MyClass}, decl\n"
        "1: targets = {MyClass}\n"
        "2: targets = {Category}, decl\n"
        "3: targets = {MyClass}\n"
        "4: targets = {Category}\n"
        "5: targets = {Category}, decl\n"}};

  for (const auto &C : Cases) {
    llvm::StringRef ExpectedCode = C.first;
    llvm::StringRef ExpectedRefs = C.second;

    auto Actual = annotateAllReferences(llvm::Annotations(ExpectedCode).code());
    EXPECT_EQ(ExpectedCode, Actual.AnnotatedCode);
    EXPECT_EQ(ExpectedRefs, Actual.DumpedReferences) << ExpectedCode;
  }
}

} // namespace
} // namespace clangd
} // namespace clang