XRefsTests.cpp
52 KB
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
//===-- XRefsTests.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 "Annotations.h"
#include "Compiler.h"
#include "Matchers.h"
#include "ParsedAST.h"
#include "Protocol.h"
#include "SourceCode.h"
#include "SyncAPI.h"
#include "TestFS.h"
#include "TestIndex.h"
#include "TestTU.h"
#include "XRefs.h"
#include "index/FileIndex.h"
#include "index/MemIndex.h"
#include "index/SymbolCollector.h"
#include "clang/AST/Decl.h"
#include "clang/Basic/SourceLocation.h"
#include "clang/Index/IndexingAction.h"
#include "llvm/ADT/None.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/Error.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/ScopedPrinter.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include <string>
#include <vector>
namespace clang {
namespace clangd {
namespace {
using ::testing::ElementsAre;
using ::testing::Eq;
using ::testing::IsEmpty;
using ::testing::Matcher;
using ::testing::UnorderedElementsAre;
using ::testing::UnorderedElementsAreArray;
MATCHER_P2(FileRange, File, Range, "") {
return Location{URIForFile::canonicalize(File, testRoot()), Range} == arg;
}
MATCHER(DeclRange, "") {
const LocatedSymbol &Sym = ::testing::get<0>(arg);
const Range &Range = ::testing::get<1>(arg);
return Sym.PreferredDeclaration.range == Range;
}
// Extracts ranges from an annotated example, and constructs a matcher for a
// highlight set. Ranges should be named $read/$write as appropriate.
Matcher<const std::vector<DocumentHighlight> &>
HighlightsFrom(const Annotations &Test) {
std::vector<DocumentHighlight> Expected;
auto Add = [&](const Range &R, DocumentHighlightKind K) {
Expected.emplace_back();
Expected.back().range = R;
Expected.back().kind = K;
};
for (const auto &Range : Test.ranges())
Add(Range, DocumentHighlightKind::Text);
for (const auto &Range : Test.ranges("read"))
Add(Range, DocumentHighlightKind::Read);
for (const auto &Range : Test.ranges("write"))
Add(Range, DocumentHighlightKind::Write);
return UnorderedElementsAreArray(Expected);
}
TEST(HighlightsTest, All) {
const char *Tests[] = {
R"cpp(// Local variable
int main() {
int [[bonjour]];
$write[[^bonjour]] = 2;
int test1 = $read[[bonjour]];
}
)cpp",
R"cpp(// Struct
namespace ns1 {
struct [[MyClass]] {
static void foo([[MyClass]]*) {}
};
} // namespace ns1
int main() {
ns1::[[My^Class]]* Params;
}
)cpp",
R"cpp(// Function
int [[^foo]](int) {}
int main() {
[[foo]]([[foo]](42));
auto *X = &[[foo]];
}
)cpp",
R"cpp(// Function parameter in decl
void foo(int [[^bar]]);
)cpp",
R"cpp(// Not touching any identifiers.
struct Foo {
[[~]]Foo() {};
};
void foo() {
Foo f;
f.[[^~]]Foo();
}
)cpp",
};
for (const char *Test : Tests) {
Annotations T(Test);
auto AST = TestTU::withCode(T.code()).build();
EXPECT_THAT(findDocumentHighlights(AST, T.point()), HighlightsFrom(T))
<< Test;
}
}
TEST(HighlightsTest, ControlFlow) {
const char *Tests[] = {
R"cpp(
// Highlight same-function returns.
int fib(unsigned n) {
if (n <= 1) [[ret^urn]] 1;
[[return]] fib(n - 1) + fib(n - 2);
// Returns from other functions not highlighted.
auto Lambda = [] { return; };
class LocalClass { void x() { return; } };
}
)cpp",
R"cpp(
#define FAIL() return false
#define DO(x) { x; }
bool foo(int n) {
if (n < 0) [[FAIL]]();
DO([[re^turn]] true)
}
)cpp",
R"cpp(
// Highlight loop control flow
int magic() {
int counter = 0;
[[^for]] (char c : "fruit loops!") {
if (c == ' ') [[continue]];
counter += c;
if (c == '!') [[break]];
if (c == '?') [[return]] -1;
}
return counter;
}
)cpp",
R"cpp(
// Highlight loop and same-loop control flow
void nonsense() {
[[while]] (true) {
if (false) [[bre^ak]];
switch (1) break;
[[continue]];
}
}
)cpp",
R"cpp(
// Highlight switch for break (but not other breaks).
void describe(unsigned n) {
[[switch]](n) {
case 0:
break;
[[default]]:
[[^break]];
}
}
)cpp",
R"cpp(
// Highlight case and exits for switch-break (but not other cases).
void describe(unsigned n) {
[[switch]](n) {
case 0:
break;
[[case]] 1:
[[default]]:
[[return]];
[[^break]];
}
}
)cpp",
R"cpp(
// Highlight exits and switch for case
void describe(unsigned n) {
[[switch]](n) {
case 0:
break;
[[case]] 1:
[[d^efault]]:
[[return]];
[[break]];
}
}
)cpp",
R"cpp(
// Highlight nothing for switch.
void describe(unsigned n) {
s^witch(n) {
case 0:
break;
case 1:
default:
return;
break;
}
}
)cpp",
R"cpp(
// FIXME: match exception type against catch blocks
int catchy() {
try { // wrong: highlight try with matching catch
try { // correct: has no matching catch
[[thr^ow]] "oh no!";
} catch (int) { } // correct: catch doesn't match type
[[return]] -1; // correct: exits the matching catch
} catch (const char*) { } // wrong: highlight matching catch
[[return]] 42; // wrong: throw doesn't exit function
}
)cpp",
R"cpp(
// Loop highlights goto exiting the loop, but not jumping within it.
void jumpy() {
[[wh^ile]](1) {
up:
if (0) [[goto]] out;
goto up;
}
out: return;
}
)cpp",
};
for (const char *Test : Tests) {
Annotations T(Test);
auto TU = TestTU::withCode(T.code());
TU.ExtraArgs.push_back("-fexceptions"); // FIXME: stop testing on PS4.
auto AST = TU.build();
EXPECT_THAT(findDocumentHighlights(AST, T.point()), HighlightsFrom(T))
<< Test;
}
}
MATCHER_P3(Sym, Name, Decl, DefOrNone, "") {
llvm::Optional<Range> Def = DefOrNone;
if (Name != arg.Name) {
*result_listener << "Name is " << arg.Name;
return false;
}
if (Decl != arg.PreferredDeclaration.range) {
*result_listener << "Declaration is "
<< llvm::to_string(arg.PreferredDeclaration);
return false;
}
if (!Def && !arg.Definition)
return true;
if (Def && !arg.Definition) {
*result_listener << "Has no definition";
return false;
}
if (!Def && arg.Definition) {
*result_listener << "Definition is " << llvm::to_string(arg.Definition);
return false;
}
if (arg.Definition->range != *Def) {
*result_listener << "Definition is " << llvm::to_string(arg.Definition);
return false;
}
return true;
}
MATCHER_P(Sym, Name, "") { return arg.Name == Name; }
MATCHER_P(RangeIs, R, "") { return arg.range == R; }
TEST(LocateSymbol, WithIndex) {
Annotations SymbolHeader(R"cpp(
class $forward[[Forward]];
class $foo[[Foo]] {};
void $f1[[f1]]();
inline void $f2[[f2]]() {}
)cpp");
Annotations SymbolCpp(R"cpp(
class $forward[[forward]] {};
void $f1[[f1]]() {}
)cpp");
TestTU TU;
TU.Code = std::string(SymbolCpp.code());
TU.HeaderCode = std::string(SymbolHeader.code());
auto Index = TU.index();
auto LocateWithIndex = [&Index](const Annotations &Main) {
auto AST = TestTU::withCode(Main.code()).build();
return clangd::locateSymbolAt(AST, Main.point(), Index.get());
};
Annotations Test(R"cpp(// only declaration in AST.
void [[f1]]();
int main() {
^f1();
}
)cpp");
EXPECT_THAT(LocateWithIndex(Test),
ElementsAre(Sym("f1", Test.range(), SymbolCpp.range("f1"))));
Test = Annotations(R"cpp(// definition in AST.
void [[f1]]() {}
int main() {
^f1();
}
)cpp");
EXPECT_THAT(LocateWithIndex(Test),
ElementsAre(Sym("f1", SymbolHeader.range("f1"), Test.range())));
Test = Annotations(R"cpp(// forward declaration in AST.
class [[Foo]];
F^oo* create();
)cpp");
EXPECT_THAT(LocateWithIndex(Test),
ElementsAre(Sym("Foo", Test.range(), SymbolHeader.range("foo"))));
Test = Annotations(R"cpp(// definition in AST.
class [[Forward]] {};
F^orward create();
)cpp");
EXPECT_THAT(
LocateWithIndex(Test),
ElementsAre(Sym("Forward", SymbolHeader.range("forward"), Test.range())));
}
TEST(LocateSymbol, WithIndexPreferredLocation) {
Annotations SymbolHeader(R"cpp(
class $p[[Proto]] {};
void $f[[func]]() {};
)cpp");
TestTU TU;
TU.HeaderCode = std::string(SymbolHeader.code());
TU.HeaderFilename = "x.proto"; // Prefer locations in codegen files.
auto Index = TU.index();
Annotations Test(R"cpp(// only declaration in AST.
// Shift to make range different.
class Proto;
void func() {}
P$p^roto* create() {
fu$f^nc();
return nullptr;
}
)cpp");
auto AST = TestTU::withCode(Test.code()).build();
{
auto Locs = clangd::locateSymbolAt(AST, Test.point("p"), Index.get());
auto CodeGenLoc = SymbolHeader.range("p");
EXPECT_THAT(Locs, ElementsAre(Sym("Proto", CodeGenLoc, CodeGenLoc)));
}
{
auto Locs = clangd::locateSymbolAt(AST, Test.point("f"), Index.get());
auto CodeGenLoc = SymbolHeader.range("f");
EXPECT_THAT(Locs, ElementsAre(Sym("func", CodeGenLoc, CodeGenLoc)));
}
}
TEST(LocateSymbol, All) {
// Ranges in tests:
// $decl is the declaration location (if absent, no symbol is located)
// $def is the definition location (if absent, symbol has no definition)
// unnamed range becomes both $decl and $def.
const char *Tests[] = {
R"cpp(// Local variable
int main() {
int [[bonjour]];
^bonjour = 2;
int test1 = bonjour;
}
)cpp",
R"cpp(// Struct
namespace ns1 {
struct [[MyClass]] {};
} // namespace ns1
int main() {
ns1::My^Class* Params;
}
)cpp",
R"cpp(// Function definition via pointer
void [[foo]](int) {}
int main() {
auto *X = &^foo;
}
)cpp",
R"cpp(// Function declaration via call
int $decl[[foo]](int);
int main() {
return ^foo(42);
}
)cpp",
R"cpp(// Field
struct Foo { int [[x]]; };
int main() {
Foo bar;
(void)bar.^x;
}
)cpp",
R"cpp(// Field, member initializer
struct Foo {
int [[x]];
Foo() : ^x(0) {}
};
)cpp",
R"cpp(// Field, field designator
struct Foo { int [[x]]; };
int main() {
Foo bar = { .^x = 2 };
}
)cpp",
R"cpp(// Method call
struct Foo { int $decl[[x]](); };
int main() {
Foo bar;
bar.^x();
}
)cpp",
R"cpp(// Typedef
typedef int $decl[[Foo]];
int main() {
^Foo bar;
}
)cpp",
R"cpp(// Template type parameter
template <typename [[T]]>
void foo() { ^T t; }
)cpp",
R"cpp(// Template template type parameter
template <template<typename> class [[T]]>
void foo() { ^T<int> t; }
)cpp",
R"cpp(// Namespace
namespace $decl[[ns]] {
struct Foo { static void bar(); };
} // namespace ns
int main() { ^ns::Foo::bar(); }
)cpp",
R"cpp(// Macro
class TTT { public: int a; };
#define [[FF]](S) if (int b = S.a) {}
void f() {
TTT t;
F^F(t);
}
)cpp",
R"cpp(// Macro argument
int [[i]];
#define ADDRESSOF(X) &X;
int *j = ADDRESSOF(^i);
)cpp",
R"cpp(// Macro argument appearing multiple times in expansion
#define VALIDATE_TYPE(x) (void)x;
#define ASSERT(expr) \
do { \
VALIDATE_TYPE(expr); \
if (!expr); \
} while (false)
bool [[waldo]]() { return true; }
void foo() {
ASSERT(wa^ldo());
}
)cpp",
R"cpp(// Symbol concatenated inside macro (not supported)
int *pi;
#define POINTER(X) p ## X;
int x = *POINTER(^i);
)cpp",
R"cpp(// Forward class declaration
class $decl[[Foo]];
class $def[[Foo]] {};
F^oo* foo();
)cpp",
R"cpp(// Function declaration
void $decl[[foo]]();
void g() { f^oo(); }
void $def[[foo]]() {}
)cpp",
R"cpp(
#define FF(name) class name##_Test {};
[[FF]](my);
void f() { my^_Test a; }
)cpp",
R"cpp(
#define FF() class [[Test]] {};
FF();
void f() { T^est a; }
)cpp",
R"cpp(// explicit template specialization
template <typename T>
struct Foo { void bar() {} };
template <>
struct [[Foo]]<int> { void bar() {} };
void foo() {
Foo<char> abc;
Fo^o<int> b;
}
)cpp",
R"cpp(// implicit template specialization
template <typename T>
struct [[Foo]] { void bar() {} };
template <>
struct Foo<int> { void bar() {} };
void foo() {
Fo^o<char> abc;
Foo<int> b;
}
)cpp",
R"cpp(// partial template specialization
template <typename T>
struct Foo { void bar() {} };
template <typename T>
struct [[Foo]]<T*> { void bar() {} };
^Foo<int*> x;
)cpp",
R"cpp(// function template specializations
template <class T>
void foo(T) {}
template <>
void [[foo]](int) {}
void bar() {
fo^o(10);
}
)cpp",
R"cpp(// variable template decls
template <class T>
T var = T();
template <>
double [[var]]<int> = 10;
double y = va^r<int>;
)cpp",
R"cpp(// No implicit constructors
struct X {
X(X&& x) = default;
};
X $decl[[makeX]]();
void foo() {
auto x = m^akeX();
}
)cpp",
R"cpp(
struct X {
X& $decl[[operator]]++();
};
void foo(X& x) {
+^+x;
}
)cpp",
R"cpp(
struct S1 { void f(); };
struct S2 { S1 * $decl[[operator]]->(); };
void test(S2 s2) {
s2-^>f();
}
)cpp",
R"cpp(// Declaration of explicit template specialization
template <typename T>
struct $decl[[Foo]] {};
template <>
struct Fo^o<int> {};
)cpp",
R"cpp(// Declaration of partial template specialization
template <typename T>
struct $decl[[Foo]] {};
template <typename T>
struct Fo^o<T*> {};
)cpp",
R"cpp(// Override specifier jumps to overridden method
class Y { virtual void $decl[[a]]() = 0; };
class X : Y { void a() ^override {} };
)cpp",
R"cpp(// Final specifier jumps to overridden method
class Y { virtual void $decl[[a]]() = 0; };
class X : Y { void a() ^final {} };
)cpp",
R"cpp(// Heuristic resolution of dependent method
template <typename T>
struct S {
void [[bar]]() {}
};
template <typename T>
void foo(S<T> arg) {
arg.ba^r();
}
)cpp",
R"cpp(// Heuristic resolution of dependent method via this->
template <typename T>
struct S {
void [[foo]]() {
this->fo^o();
}
};
)cpp",
R"cpp(// Heuristic resolution of dependent static method
template <typename T>
struct S {
static void [[bar]]() {}
};
template <typename T>
void foo() {
S<T>::ba^r();
}
)cpp",
R"cpp(// Heuristic resolution of dependent method
// invoked via smart pointer
template <typename> struct S { void [[foo]]() {} };
template <typename T> struct unique_ptr {
T* operator->();
};
template <typename T>
void test(unique_ptr<S<T>>& V) {
V->fo^o();
}
)cpp",
R"cpp(// Heuristic resolution of dependent enumerator
template <typename T>
struct Foo {
enum class E { [[A]], B };
E e = E::A^;
};
)cpp",
R"objc(
@protocol Dog;
@protocol $decl[[Dog]]
- (void)bark;
@end
id<Do^g> getDoggo() {
return 0;
}
)objc",
R"objc(
@interface Cat
@end
@implementation Cat
@end
@interface $decl[[Cat]] (Exte^nsion)
- (void)meow;
@end
@implementation $def[[Cat]] (Extension)
- (void)meow {}
@end
)objc",
R"objc(
@class $decl[[Foo]];
Fo^o * getFoo() {
return 0;
}
)objc",
R"objc(// Prefer interface definition over forward declaration
@class Foo;
@interface $decl[[Foo]]
@end
Fo^o * getFoo() {
return 0;
}
)objc",
R"objc(
@class Foo;
@interface $decl[[Foo]]
@end
@implementation $def[[Foo]]
@end
Fo^o * getFoo() {
return 0;
}
)objc"};
for (const char *Test : Tests) {
Annotations T(Test);
llvm::Optional<Range> WantDecl;
llvm::Optional<Range> WantDef;
if (!T.ranges().empty())
WantDecl = WantDef = T.range();
if (!T.ranges("decl").empty())
WantDecl = T.range("decl");
if (!T.ranges("def").empty())
WantDef = T.range("def");
TestTU TU;
TU.Code = std::string(T.code());
// FIXME: Auto-completion in a template requires disabling delayed template
// parsing.
TU.ExtraArgs.push_back("-fno-delayed-template-parsing");
TU.ExtraArgs.push_back("-xobjective-c++");
auto AST = TU.build();
auto Results = locateSymbolAt(AST, T.point());
if (!WantDecl) {
EXPECT_THAT(Results, IsEmpty()) << Test;
} else {
ASSERT_THAT(Results, ::testing::SizeIs(1)) << Test;
EXPECT_EQ(Results[0].PreferredDeclaration.range, *WantDecl) << Test;
llvm::Optional<Range> GotDef;
if (Results[0].Definition)
GotDef = Results[0].Definition->range;
EXPECT_EQ(WantDef, GotDef) << Test;
}
}
}
TEST(LocateSymbol, AllMulti) {
// Ranges in tests:
// $declN is the declaration location
// $defN is the definition location (if absent, symbol has no definition)
//
// NOTE:
// N starts at 0.
struct ExpectedRanges {
Range WantDecl;
llvm::Optional<Range> WantDef;
};
const char *Tests[] = {
R"objc(
@interface $decl0[[Cat]]
@end
@implementation $def0[[Cat]]
@end
@interface $decl1[[Ca^t]] (Extension)
- (void)meow;
@end
@implementation $def1[[Cat]] (Extension)
- (void)meow {}
@end
)objc",
R"objc(
@interface $decl0[[Cat]]
@end
@implementation $def0[[Cat]]
@end
@interface $decl1[[Cat]] (Extension)
- (void)meow;
@end
@implementation $def1[[Ca^t]] (Extension)
- (void)meow {}
@end
)objc",
R"objc(
@interface $decl0[[Cat]]
@end
@interface $decl1[[Ca^t]] ()
- (void)meow;
@end
@implementation $def0[[$def1[[Cat]]]]
- (void)meow {}
@end
)objc",
};
for (const char *Test : Tests) {
Annotations T(Test);
std::vector<ExpectedRanges> Ranges;
for (int Idx = 0; true; Idx++) {
bool HasDecl = !T.ranges("decl" + std::to_string(Idx)).empty();
bool HasDef = !T.ranges("def" + std::to_string(Idx)).empty();
if (!HasDecl && !HasDef)
break;
ExpectedRanges Range;
if (HasDecl)
Range.WantDecl = T.range("decl" + std::to_string(Idx));
if (HasDef)
Range.WantDef = T.range("def" + std::to_string(Idx));
Ranges.push_back(Range);
}
TestTU TU;
TU.Code = std::string(T.code());
TU.ExtraArgs.push_back("-xobjective-c++");
auto AST = TU.build();
auto Results = locateSymbolAt(AST, T.point());
ASSERT_THAT(Results, ::testing::SizeIs(Ranges.size())) << Test;
for (size_t Idx = 0; Idx < Ranges.size(); Idx++) {
EXPECT_EQ(Results[Idx].PreferredDeclaration.range, Ranges[Idx].WantDecl)
<< "($decl" << Idx << ")" << Test;
llvm::Optional<Range> GotDef;
if (Results[Idx].Definition)
GotDef = Results[Idx].Definition->range;
EXPECT_EQ(GotDef, Ranges[Idx].WantDef) << "($def" << Idx << ")" << Test;
}
}
}
// LocateSymbol test cases that produce warnings.
// These are separated out from All so that in All we can assert
// that there are no diagnostics.
TEST(LocateSymbol, Warnings) {
const char *Tests[] = {
R"cpp(// Field, GNU old-style field designator
struct Foo { int [[x]]; };
int main() {
Foo bar = { ^x : 1 };
}
)cpp",
R"cpp(// Macro
#define MACRO 0
#define [[MACRO]] 1
int main() { return ^MACRO; }
#define MACRO 2
#undef macro
)cpp",
};
for (const char *Test : Tests) {
Annotations T(Test);
llvm::Optional<Range> WantDecl;
llvm::Optional<Range> WantDef;
if (!T.ranges().empty())
WantDecl = WantDef = T.range();
if (!T.ranges("decl").empty())
WantDecl = T.range("decl");
if (!T.ranges("def").empty())
WantDef = T.range("def");
TestTU TU;
TU.Code = std::string(T.code());
auto AST = TU.build();
auto Results = locateSymbolAt(AST, T.point());
if (!WantDecl) {
EXPECT_THAT(Results, IsEmpty()) << Test;
} else {
ASSERT_THAT(Results, ::testing::SizeIs(1)) << Test;
EXPECT_EQ(Results[0].PreferredDeclaration.range, *WantDecl) << Test;
llvm::Optional<Range> GotDef;
if (Results[0].Definition)
GotDef = Results[0].Definition->range;
EXPECT_EQ(WantDef, GotDef) << Test;
}
}
}
TEST(LocateSymbol, TextualSmoke) {
auto T = Annotations(
R"cpp(
struct [[MyClass]] {};
// Comment mentioning M^yClass
)cpp");
auto TU = TestTU::withCode(T.code());
auto AST = TU.build();
auto Index = TU.index();
EXPECT_THAT(locateSymbolAt(AST, T.point(), Index.get()),
ElementsAre(Sym("MyClass", T.range(), T.range())));
}
TEST(LocateSymbol, Textual) {
const char *Tests[] = {
R"cpp(// Comment
struct [[MyClass]] {};
// Comment mentioning M^yClass
)cpp",
R"cpp(// String
struct MyClass {};
// Not triggered for string literal tokens.
const char* s = "String literal mentioning M^yClass";
)cpp",
R"cpp(// Ifdef'ed out code
struct [[MyClass]] {};
#ifdef WALDO
M^yClass var;
#endif
)cpp",
R"cpp(// Macro definition
struct [[MyClass]] {};
#define DECLARE_MYCLASS_OBJ(name) M^yClass name;
)cpp",
R"cpp(// Invalid code
/*error-ok*/
int myFunction(int);
// Not triggered for token which survived preprocessing.
int var = m^yFunction();
)cpp"};
for (const char *Test : Tests) {
Annotations T(Test);
llvm::Optional<Range> WantDecl;
if (!T.ranges().empty())
WantDecl = T.range();
auto TU = TestTU::withCode(T.code());
auto AST = TU.build();
auto Index = TU.index();
auto Word = SpelledWord::touching(
cantFail(sourceLocationInMainFile(AST.getSourceManager(), T.point())),
AST.getTokens(), AST.getLangOpts());
if (!Word) {
ADD_FAILURE() << "No word touching point!" << Test;
continue;
}
auto Results = locateSymbolTextually(*Word, AST, Index.get(),
testPath(TU.Filename), ASTNodeKind());
if (!WantDecl) {
EXPECT_THAT(Results, IsEmpty()) << Test;
} else {
ASSERT_THAT(Results, ::testing::SizeIs(1)) << Test;
EXPECT_EQ(Results[0].PreferredDeclaration.range, *WantDecl) << Test;
}
}
} // namespace
TEST(LocateSymbol, Ambiguous) {
auto T = Annotations(R"cpp(
struct Foo {
Foo();
Foo(Foo&&);
$ConstructorLoc[[Foo]](const char*);
};
Foo f();
void g(Foo foo);
void call() {
const char* str = "123";
Foo a = $1^str;
Foo b = Foo($2^str);
Foo c = $3^f();
$4^g($5^f());
g($6^str);
Foo ab$7^c;
Foo ab$8^cd("asdf");
Foo foox = Fo$9^o("asdf");
Foo abcde$10^("asdf");
Foo foox2 = Foo$11^("asdf");
}
template <typename T>
struct S {
void $NonstaticOverload1[[bar]](int);
void $NonstaticOverload2[[bar]](float);
static void $StaticOverload1[[baz]](int);
static void $StaticOverload2[[baz]](float);
};
template <typename T, typename U>
void dependent_call(S<T> s, U u) {
s.ba$12^r(u);
S<T>::ba$13^z(u);
}
)cpp");
auto TU = TestTU::withCode(T.code());
// FIXME: Go-to-definition in a template requires disabling delayed template
// parsing.
TU.ExtraArgs.push_back("-fno-delayed-template-parsing");
auto AST = TU.build();
// Ordered assertions are deliberate: we expect a predictable order.
EXPECT_THAT(locateSymbolAt(AST, T.point("1")), ElementsAre(Sym("str")));
EXPECT_THAT(locateSymbolAt(AST, T.point("2")), ElementsAre(Sym("str")));
EXPECT_THAT(locateSymbolAt(AST, T.point("3")), ElementsAre(Sym("f")));
EXPECT_THAT(locateSymbolAt(AST, T.point("4")), ElementsAre(Sym("g")));
EXPECT_THAT(locateSymbolAt(AST, T.point("5")), ElementsAre(Sym("f")));
EXPECT_THAT(locateSymbolAt(AST, T.point("6")), ElementsAre(Sym("str")));
// FIXME: Target the constructor as well.
EXPECT_THAT(locateSymbolAt(AST, T.point("7")), ElementsAre(Sym("abc")));
// FIXME: Target the constructor as well.
EXPECT_THAT(locateSymbolAt(AST, T.point("8")), ElementsAre(Sym("abcd")));
// FIXME: Target the constructor as well.
EXPECT_THAT(locateSymbolAt(AST, T.point("9")), ElementsAre(Sym("Foo")));
EXPECT_THAT(locateSymbolAt(AST, T.point("10")),
ElementsAre(Sym("Foo", T.range("ConstructorLoc"), llvm::None)));
EXPECT_THAT(locateSymbolAt(AST, T.point("11")),
ElementsAre(Sym("Foo", T.range("ConstructorLoc"), llvm::None)));
// These assertions are unordered because the order comes from
// CXXRecordDecl::lookupDependentName() which doesn't appear to provide
// an order guarantee.
EXPECT_THAT(locateSymbolAt(AST, T.point("12")),
UnorderedElementsAre(
Sym("bar", T.range("NonstaticOverload1"), llvm::None),
Sym("bar", T.range("NonstaticOverload2"), llvm::None)));
EXPECT_THAT(
locateSymbolAt(AST, T.point("13")),
UnorderedElementsAre(Sym("baz", T.range("StaticOverload1"), llvm::None),
Sym("baz", T.range("StaticOverload2"), llvm::None)));
}
TEST(LocateSymbol, TextualDependent) {
// Put the declarations in the header to make sure we are
// finding them via the index heuristic and not the
// nearby-ident heuristic.
Annotations Header(R"cpp(
struct Foo {
void $FooLoc[[uniqueMethodName]]();
};
struct Bar {
void $BarLoc[[uniqueMethodName]]();
};
)cpp");
Annotations Source(R"cpp(
template <typename T>
void f(T t) {
t.u^niqueMethodName();
}
)cpp");
TestTU TU;
TU.Code = std::string(Source.code());
TU.HeaderCode = std::string(Header.code());
auto AST = TU.build();
auto Index = TU.index();
// Need to use locateSymbolAt() since we are testing an
// interaction between locateASTReferent() and
// locateSymbolNamedTextuallyAt().
auto Results = locateSymbolAt(AST, Source.point(), Index.get());
EXPECT_THAT(Results,
UnorderedElementsAre(
Sym("uniqueMethodName", Header.range("FooLoc"), llvm::None),
Sym("uniqueMethodName", Header.range("BarLoc"), llvm::None)));
}
TEST(LocateSymbol, Alias) {
const char *Tests[] = {
R"cpp(
template <class T> struct function {};
template <class T> using [[callback]] = function<T()>;
c^allback<int> foo;
)cpp",
// triggered on non-definition of a renaming alias: should not give any
// underlying decls.
R"cpp(
class Foo {};
typedef Foo [[Bar]];
B^ar b;
)cpp",
R"cpp(
class Foo {};
using [[Bar]] = Foo; // definition
Ba^r b;
)cpp",
// triggered on the underlying decl of a renaming alias.
R"cpp(
class [[Foo]];
using Bar = Fo^o;
)cpp",
// triggered on definition of a non-renaming alias: should give underlying
// decls.
R"cpp(
namespace ns { class [[Foo]] {}; }
using ns::F^oo;
)cpp",
R"cpp(
namespace ns { int [[x]](char); int [[x]](double); }
using ns::^x;
)cpp",
R"cpp(
namespace ns { int [[x]](char); int x(double); }
using ns::x;
int y = ^x('a');
)cpp",
R"cpp(
namespace ns { class [[Foo]] {}; }
using ns::Foo;
F^oo f;
)cpp",
// other cases that don't matter much.
R"cpp(
class Foo {};
typedef Foo [[Ba^r]];
)cpp",
R"cpp(
class Foo {};
using [[B^ar]] = Foo;
)cpp",
// Member of dependent base
R"cpp(
template <typename T>
struct Base {
void [[waldo]]() {}
};
template <typename T>
struct Derived : Base<T> {
using Base<T>::w^aldo;
};
)cpp",
};
for (const auto* Case : Tests) {
SCOPED_TRACE(Case);
auto T = Annotations(Case);
auto AST = TestTU::withCode(T.code()).build();
EXPECT_THAT(locateSymbolAt(AST, T.point()),
::testing::UnorderedPointwise(DeclRange(), T.ranges()));
}
}
TEST(LocateSymbol, RelPathsInCompileCommand) {
// The source is in "/clangd-test/src".
// We build in "/clangd-test/build".
Annotations SourceAnnotations(R"cpp(
#include "header_in_preamble.h"
int [[foo]];
#include "header_not_in_preamble.h"
int baz = f$p1^oo + bar_pre$p2^amble + bar_not_pre$p3^amble;
)cpp");
Annotations HeaderInPreambleAnnotations(R"cpp(
int [[bar_preamble]];
)cpp");
Annotations HeaderNotInPreambleAnnotations(R"cpp(
int [[bar_not_preamble]];
)cpp");
// Make the compilation paths appear as ../src/foo.cpp in the compile
// commands.
SmallString<32> RelPathPrefix("..");
llvm::sys::path::append(RelPathPrefix, "src");
std::string BuildDir = testPath("build");
MockCompilationDatabase CDB(BuildDir, RelPathPrefix);
MockFS FS;
ClangdServer Server(CDB, FS, ClangdServer::optsForTest());
// Fill the filesystem.
auto FooCpp = testPath("src/foo.cpp");
FS.Files[FooCpp] = "";
auto HeaderInPreambleH = testPath("src/header_in_preamble.h");
FS.Files[HeaderInPreambleH] = std::string(HeaderInPreambleAnnotations.code());
auto HeaderNotInPreambleH = testPath("src/header_not_in_preamble.h");
FS.Files[HeaderNotInPreambleH] =
std::string(HeaderNotInPreambleAnnotations.code());
runAddDocument(Server, FooCpp, SourceAnnotations.code());
// Go to a definition in main source file.
auto Locations =
runLocateSymbolAt(Server, FooCpp, SourceAnnotations.point("p1"));
EXPECT_TRUE(bool(Locations)) << "findDefinitions returned an error";
EXPECT_THAT(*Locations, ElementsAre(Sym("foo", SourceAnnotations.range(),
SourceAnnotations.range())));
// Go to a definition in header_in_preamble.h.
Locations = runLocateSymbolAt(Server, FooCpp, SourceAnnotations.point("p2"));
EXPECT_TRUE(bool(Locations)) << "findDefinitions returned an error";
EXPECT_THAT(
*Locations,
ElementsAre(Sym("bar_preamble", HeaderInPreambleAnnotations.range(),
HeaderInPreambleAnnotations.range())));
// Go to a definition in header_not_in_preamble.h.
Locations = runLocateSymbolAt(Server, FooCpp, SourceAnnotations.point("p3"));
EXPECT_TRUE(bool(Locations)) << "findDefinitions returned an error";
EXPECT_THAT(*Locations,
ElementsAre(Sym("bar_not_preamble",
HeaderNotInPreambleAnnotations.range(),
HeaderNotInPreambleAnnotations.range())));
}
TEST(GoToInclude, All) {
MockFS FS;
MockCompilationDatabase CDB;
ClangdServer Server(CDB, FS, ClangdServer::optsForTest());
auto FooCpp = testPath("foo.cpp");
const char *SourceContents = R"cpp(
#include ^"$2^foo.h$3^"
#include "$4^invalid.h"
int b = a;
// test
int foo;
#in$5^clude "$6^foo.h"$7^
)cpp";
Annotations SourceAnnotations(SourceContents);
FS.Files[FooCpp] = std::string(SourceAnnotations.code());
auto FooH = testPath("foo.h");
const char *HeaderContents = R"cpp([[]]#pragma once
int a;
)cpp";
Annotations HeaderAnnotations(HeaderContents);
FS.Files[FooH] = std::string(HeaderAnnotations.code());
Server.addDocument(FooH, HeaderAnnotations.code());
Server.addDocument(FooCpp, SourceAnnotations.code());
// Test include in preamble.
auto Locations = runLocateSymbolAt(Server, FooCpp, SourceAnnotations.point());
ASSERT_TRUE(bool(Locations)) << "locateSymbolAt returned an error";
EXPECT_THAT(*Locations, ElementsAre(Sym("foo.h", HeaderAnnotations.range(),
HeaderAnnotations.range())));
// Test include in preamble, last char.
Locations = runLocateSymbolAt(Server, FooCpp, SourceAnnotations.point("2"));
ASSERT_TRUE(bool(Locations)) << "locateSymbolAt returned an error";
EXPECT_THAT(*Locations, ElementsAre(Sym("foo.h", HeaderAnnotations.range(),
HeaderAnnotations.range())));
Locations = runLocateSymbolAt(Server, FooCpp, SourceAnnotations.point("3"));
ASSERT_TRUE(bool(Locations)) << "locateSymbolAt returned an error";
EXPECT_THAT(*Locations, ElementsAre(Sym("foo.h", HeaderAnnotations.range(),
HeaderAnnotations.range())));
// Test include outside of preamble.
Locations = runLocateSymbolAt(Server, FooCpp, SourceAnnotations.point("6"));
ASSERT_TRUE(bool(Locations)) << "locateSymbolAt returned an error";
EXPECT_THAT(*Locations, ElementsAre(Sym("foo.h", HeaderAnnotations.range(),
HeaderAnnotations.range())));
// Test a few positions that do not result in Locations.
Locations = runLocateSymbolAt(Server, FooCpp, SourceAnnotations.point("4"));
ASSERT_TRUE(bool(Locations)) << "locateSymbolAt returned an error";
EXPECT_THAT(*Locations, IsEmpty());
Locations = runLocateSymbolAt(Server, FooCpp, SourceAnnotations.point("5"));
ASSERT_TRUE(bool(Locations)) << "locateSymbolAt returned an error";
EXPECT_THAT(*Locations, ElementsAre(Sym("foo.h", HeaderAnnotations.range(),
HeaderAnnotations.range())));
Locations = runLocateSymbolAt(Server, FooCpp, SourceAnnotations.point("7"));
ASSERT_TRUE(bool(Locations)) << "locateSymbolAt returned an error";
EXPECT_THAT(*Locations, ElementsAre(Sym("foo.h", HeaderAnnotations.range(),
HeaderAnnotations.range())));
// Objective C #import directive.
Annotations ObjC(R"objc(
#import "^foo.h"
)objc");
auto FooM = testPath("foo.m");
FS.Files[FooM] = std::string(ObjC.code());
Server.addDocument(FooM, ObjC.code());
Locations = runLocateSymbolAt(Server, FooM, ObjC.point());
ASSERT_TRUE(bool(Locations)) << "locateSymbolAt returned an error";
EXPECT_THAT(*Locations, ElementsAre(Sym("foo.h", HeaderAnnotations.range(),
HeaderAnnotations.range())));
}
TEST(LocateSymbol, WithPreamble) {
// Test stragety: AST should always use the latest preamble instead of last
// good preamble.
MockFS FS;
MockCompilationDatabase CDB;
ClangdServer Server(CDB, FS, ClangdServer::optsForTest());
auto FooCpp = testPath("foo.cpp");
// The trigger locations must be the same.
Annotations FooWithHeader(R"cpp(#include "fo^o.h")cpp");
Annotations FooWithoutHeader(R"cpp(double [[fo^o]]();)cpp");
FS.Files[FooCpp] = std::string(FooWithHeader.code());
auto FooH = testPath("foo.h");
Annotations FooHeader(R"cpp([[]])cpp");
FS.Files[FooH] = std::string(FooHeader.code());
runAddDocument(Server, FooCpp, FooWithHeader.code());
// LocateSymbol goes to a #include file: the result comes from the preamble.
EXPECT_THAT(
cantFail(runLocateSymbolAt(Server, FooCpp, FooWithHeader.point())),
ElementsAre(Sym("foo.h", FooHeader.range(), FooHeader.range())));
// Only preamble is built, and no AST is built in this request.
Server.addDocument(FooCpp, FooWithoutHeader.code(), "null",
WantDiagnostics::No);
// We build AST here, and it should use the latest preamble rather than the
// stale one.
EXPECT_THAT(
cantFail(runLocateSymbolAt(Server, FooCpp, FooWithoutHeader.point())),
ElementsAre(Sym("foo", FooWithoutHeader.range(), llvm::None)));
// Reset test environment.
runAddDocument(Server, FooCpp, FooWithHeader.code());
// Both preamble and AST are built in this request.
Server.addDocument(FooCpp, FooWithoutHeader.code(), "null",
WantDiagnostics::Yes);
// Use the AST being built in above request.
EXPECT_THAT(
cantFail(runLocateSymbolAt(Server, FooCpp, FooWithoutHeader.point())),
ElementsAre(Sym("foo", FooWithoutHeader.range(), llvm::None)));
}
TEST(LocateSymbol, NearbyTokenSmoke) {
auto T = Annotations(R"cpp(
// prints e^rr and crashes
void die(const char* [[err]]);
)cpp");
auto AST = TestTU::withCode(T.code()).build();
// We don't pass an index, so can't hit index-based fallback.
EXPECT_THAT(locateSymbolAt(AST, T.point()),
ElementsAre(Sym("err", T.range(), T.range())));
}
TEST(LocateSymbol, NearbyIdentifier) {
const char *Tests[] = {
R"cpp(
// regular identifiers (won't trigger)
int hello;
int y = he^llo;
)cpp",
R"cpp(
// disabled preprocessor sections
int [[hello]];
#if 0
int y = ^hello;
#endif
)cpp",
R"cpp(
// comments
// he^llo, world
int [[hello]];
)cpp",
R"cpp(
// not triggered by string literals
int hello;
const char* greeting = "h^ello, world";
)cpp",
R"cpp(
// can refer to macro invocations
#define INT int
[[INT]] x;
// I^NT
)cpp",
R"cpp(
// can refer to macro invocations (even if they expand to nothing)
#define EMPTY
[[EMPTY]] int x;
// E^MPTY
)cpp",
R"cpp(
// prefer nearest occurrence, backwards is worse than forwards
int hello;
int x = hello;
// h^ello
int y = [[hello]];
int z = hello;
)cpp",
R"cpp(
// short identifiers find near results
int [[hi]];
// h^i
)cpp",
R"cpp(
// short identifiers don't find far results
int hi;
// h^i
int x = hi;
)cpp",
R"cpp(
// prefer nearest occurrence even if several matched tokens
// have the same value of `floor(log2(<token line> - <word line>))`.
int hello;
int x = hello, y = hello;
int z = [[hello]];
// h^ello
)cpp"};
for (const char *Test : Tests) {
Annotations T(Test);
auto AST = TestTU::withCode(T.code()).build();
const auto &SM = AST.getSourceManager();
llvm::Optional<Range> Nearby;
auto Word =
SpelledWord::touching(cantFail(sourceLocationInMainFile(SM, T.point())),
AST.getTokens(), AST.getLangOpts());
if (!Word) {
ADD_FAILURE() << "No word at point! " << Test;
continue;
}
if (const auto *Tok = findNearbyIdentifier(*Word, AST.getTokens()))
Nearby = halfOpenToRange(SM, CharSourceRange::getCharRange(
Tok->location(), Tok->endLocation()));
if (T.ranges().empty())
EXPECT_THAT(Nearby, Eq(llvm::None)) << Test;
else
EXPECT_EQ(Nearby, T.range()) << Test;
}
}
TEST(FindReferences, WithinAST) {
const char *Tests[] = {
R"cpp(// Local variable
int main() {
int [[foo]];
[[^foo]] = 2;
int test1 = [[foo]];
}
)cpp",
R"cpp(// Struct
namespace ns1 {
struct [[Foo]] {};
} // namespace ns1
int main() {
ns1::[[Fo^o]]* Params;
}
)cpp",
R"cpp(// Forward declaration
class [[Foo]];
class [[Foo]] {};
int main() {
[[Fo^o]] foo;
}
)cpp",
R"cpp(// Function
int [[foo]](int) {}
int main() {
auto *X = &[[^foo]];
[[foo]](42);
}
)cpp",
R"cpp(// Field
struct Foo {
int [[foo]];
Foo() : [[foo]](0) {}
};
int main() {
Foo f;
f.[[f^oo]] = 1;
}
)cpp",
R"cpp(// Method call
struct Foo { int [[foo]](); };
int Foo::[[foo]]() {}
int main() {
Foo f;
f.[[^foo]]();
}
)cpp",
R"cpp(// Constructor
struct Foo {
[[F^oo]](int);
};
void foo() {
Foo f = [[Foo]](42);
}
)cpp",
R"cpp(// Typedef
typedef int [[Foo]];
int main() {
[[^Foo]] bar;
}
)cpp",
R"cpp(// Namespace
namespace [[ns]] {
struct Foo {};
} // namespace ns
int main() { [[^ns]]::Foo foo; }
)cpp",
R"cpp(// Macros
#define TYPE(X) X
#define FOO Foo
#define CAT(X, Y) X##Y
class [[Fo^o]] {};
void test() {
TYPE([[Foo]]) foo;
[[FOO]] foo2;
TYPE(TYPE([[Foo]])) foo3;
[[CAT]](Fo, o) foo4;
}
)cpp",
R"cpp(// Macros
#define [[MA^CRO]](X) (X+1)
void test() {
int x = [[MACRO]]([[MACRO]](1));
}
)cpp",
R"cpp(
int [[v^ar]] = 0;
void foo(int s = [[var]]);
)cpp",
R"cpp(
template <typename T>
class [[Fo^o]] {};
void func([[Foo]]<int>);
)cpp",
R"cpp(
template <typename T>
class [[Foo]] {};
void func([[Fo^o]]<int>);
)cpp",
R"cpp(// Not touching any identifiers.
struct Foo {
[[~]]Foo() {};
};
void foo() {
Foo f;
f.[[^~]]Foo();
}
)cpp",
R"cpp(// Lambda capture initializer
void foo() {
int [[w^aldo]] = 42;
auto lambda = [x = [[waldo]]](){};
}
)cpp",
R"cpp(// Renaming alias
template <typename> class Vector {};
using [[^X]] = Vector<int>;
[[X]] x1;
Vector<int> x2;
Vector<double> y;
)cpp",
};
for (const char *Test : Tests) {
Annotations T(Test);
auto AST = TestTU::withCode(T.code()).build();
std::vector<Matcher<Location>> ExpectedLocations;
for (const auto &R : T.ranges())
ExpectedLocations.push_back(RangeIs(R));
EXPECT_THAT(findReferences(AST, T.point(), 0).References,
ElementsAreArray(ExpectedLocations))
<< Test;
}
}
TEST(FindReferences, MainFileReferencesOnly) {
llvm::StringRef Test =
R"cpp(
void test() {
int [[fo^o]] = 1;
// refs not from main file should not be included.
#include "foo.inc"
})cpp";
Annotations Code(Test);
auto TU = TestTU::withCode(Code.code());
TU.AdditionalFiles["foo.inc"] = R"cpp(
foo = 3;
)cpp";
auto AST = TU.build();
std::vector<Matcher<Location>> ExpectedLocations;
for (const auto &R : Code.ranges())
ExpectedLocations.push_back(RangeIs(R));
EXPECT_THAT(findReferences(AST, Code.point(), 0).References,
ElementsAreArray(ExpectedLocations))
<< Test;
}
TEST(FindReferences, ExplicitSymbols) {
const char *Tests[] = {
R"cpp(
struct Foo { Foo* [[self]]() const; };
void f() {
Foo foo;
if (Foo* T = foo.[[^self]]()) {} // Foo member call expr.
}
)cpp",
R"cpp(
struct Foo { Foo(int); };
Foo f() {
int [[b]];
return [[^b]]; // Foo constructor expr.
}
)cpp",
R"cpp(
struct Foo {};
void g(Foo);
Foo [[f]]();
void call() {
g([[^f]]()); // Foo constructor expr.
}
)cpp",
R"cpp(
void [[foo]](int);
void [[foo]](double);
namespace ns {
using ::[[fo^o]];
}
)cpp",
R"cpp(
struct X {
operator bool();
};
int test() {
X [[a]];
[[a]].operator bool();
if ([[a^]]) {} // ignore implicit conversion-operator AST node
}
)cpp",
};
for (const char *Test : Tests) {
Annotations T(Test);
auto AST = TestTU::withCode(T.code()).build();
std::vector<Matcher<Location>> ExpectedLocations;
for (const auto &R : T.ranges())
ExpectedLocations.push_back(RangeIs(R));
ASSERT_THAT(ExpectedLocations, Not(IsEmpty()));
EXPECT_THAT(findReferences(AST, T.point(), 0).References,
ElementsAreArray(ExpectedLocations))
<< Test;
}
}
TEST(FindReferences, NeedsIndexForSymbols) {
const char *Header = "int foo();";
Annotations Main("int main() { [[f^oo]](); }");
TestTU TU;
TU.Code = std::string(Main.code());
TU.HeaderCode = Header;
auto AST = TU.build();
// References in main file are returned without index.
EXPECT_THAT(
findReferences(AST, Main.point(), 0, /*Index=*/nullptr).References,
ElementsAre(RangeIs(Main.range())));
Annotations IndexedMain(R"cpp(
int main() { [[f^oo]](); }
)cpp");
// References from indexed files are included.
TestTU IndexedTU;
IndexedTU.Code = std::string(IndexedMain.code());
IndexedTU.Filename = "Indexed.cpp";
IndexedTU.HeaderCode = Header;
EXPECT_THAT(
findReferences(AST, Main.point(), 0, IndexedTU.index().get()).References,
ElementsAre(RangeIs(Main.range()), RangeIs(IndexedMain.range())));
auto LimitRefs =
findReferences(AST, Main.point(), /*Limit*/ 1, IndexedTU.index().get());
EXPECT_EQ(1u, LimitRefs.References.size());
EXPECT_TRUE(LimitRefs.HasMore);
// Avoid indexed results for the main file. Use AST for the mainfile.
TU.Code = ("\n\n" + Main.code()).str();
EXPECT_THAT(findReferences(AST, Main.point(), 0, TU.index().get()).References,
ElementsAre(RangeIs(Main.range())));
}
TEST(FindReferences, NeedsIndexForMacro) {
const char *Header = "#define MACRO(X) (X+1)";
Annotations Main(R"cpp(
int main() {
int a = [[MA^CRO]](1);
}
)cpp");
TestTU TU;
TU.Code = std::string(Main.code());
TU.HeaderCode = Header;
auto AST = TU.build();
// References in main file are returned without index.
EXPECT_THAT(
findReferences(AST, Main.point(), 0, /*Index=*/nullptr).References,
ElementsAre(RangeIs(Main.range())));
Annotations IndexedMain(R"cpp(
int indexed_main() {
int a = [[MACRO]](1);
}
)cpp");
// References from indexed files are included.
TestTU IndexedTU;
IndexedTU.Code = std::string(IndexedMain.code());
IndexedTU.Filename = "Indexed.cpp";
IndexedTU.HeaderCode = Header;
EXPECT_THAT(
findReferences(AST, Main.point(), 0, IndexedTU.index().get()).References,
ElementsAre(RangeIs(Main.range()), RangeIs(IndexedMain.range())));
auto LimitRefs =
findReferences(AST, Main.point(), /*Limit*/ 1, IndexedTU.index().get());
EXPECT_EQ(1u, LimitRefs.References.size());
EXPECT_TRUE(LimitRefs.HasMore);
}
TEST(FindReferences, NoQueryForLocalSymbols) {
struct RecordingIndex : public MemIndex {
mutable Optional<llvm::DenseSet<SymbolID>> RefIDs;
bool refs(const RefsRequest &Req,
llvm::function_ref<void(const Ref &)>) const override {
RefIDs = Req.IDs;
return false;
}
};
struct Test {
StringRef AnnotatedCode;
bool WantQuery;
} Tests[] = {
{"int ^x;", true},
// For now we don't assume header structure which would allow skipping.
{"namespace { int ^x; }", true},
{"static int ^x;", true},
// Anything in a function certainly can't be referenced though.
{"void foo() { int ^x; }", false},
{"void foo() { struct ^x{}; }", false},
{"auto lambda = []{ int ^x; };", false},
};
for (Test T : Tests) {
Annotations File(T.AnnotatedCode);
RecordingIndex Rec;
auto AST = TestTU::withCode(File.code()).build();
findReferences(AST, File.point(), 0, &Rec);
if (T.WantQuery)
EXPECT_NE(Rec.RefIDs, None) << T.AnnotatedCode;
else
EXPECT_EQ(Rec.RefIDs, None) << T.AnnotatedCode;
}
}
TEST(GetNonLocalDeclRefs, All) {
struct Case {
llvm::StringRef AnnotatedCode;
std::vector<std::string> ExpectedDecls;
} Cases[] = {
{
// VarDecl and ParamVarDecl
R"cpp(
void bar();
void ^foo(int baz) {
int x = 10;
bar();
})cpp",
{"bar"},
},
{
// Method from class
R"cpp(
class Foo { public: void foo(); };
class Bar {
void foo();
void bar();
};
void Bar::^foo() {
Foo f;
bar();
f.foo();
})cpp",
{"Bar", "Bar::bar", "Foo", "Foo::foo"},
},
{
// Local types
R"cpp(
void ^foo() {
class Foo { public: void foo() {} };
class Bar { public: void bar() {} };
Foo f;
Bar b;
b.bar();
f.foo();
})cpp",
{},
},
{
// Template params
R"cpp(
template <typename T, template<typename> class Q>
void ^foo() {
T x;
Q<T> y;
})cpp",
{},
},
};
for (const Case &C : Cases) {
Annotations File(C.AnnotatedCode);
auto AST = TestTU::withCode(File.code()).build();
SourceLocation SL = llvm::cantFail(
sourceLocationInMainFile(AST.getSourceManager(), File.point()));
const FunctionDecl *FD =
llvm::dyn_cast<FunctionDecl>(&findDecl(AST, [SL](const NamedDecl &ND) {
return ND.getLocation() == SL && llvm::isa<FunctionDecl>(ND);
}));
ASSERT_NE(FD, nullptr);
auto NonLocalDeclRefs = getNonLocalDeclRefs(AST, FD);
std::vector<std::string> Names;
for (const Decl *D : NonLocalDeclRefs) {
if (const auto *ND = llvm::dyn_cast<NamedDecl>(D))
Names.push_back(ND->getQualifiedNameAsString());
}
EXPECT_THAT(Names, UnorderedElementsAreArray(C.ExpectedDecls))
<< File.code();
}
}
TEST(DocumentLinks, All) {
Annotations MainCpp(R"cpp(
#/*comments*/include /*comments*/ $foo[["foo.h"]] //more comments
int end_of_preamble = 0;
#include $bar[[<bar.h>]]
)cpp");
TestTU TU;
TU.Code = std::string(MainCpp.code());
TU.AdditionalFiles = {{"foo.h", ""}, {"bar.h", ""}};
TU.ExtraArgs = {"-isystem."};
auto AST = TU.build();
EXPECT_THAT(
clangd::getDocumentLinks(AST),
ElementsAre(
DocumentLink({MainCpp.range("foo"),
URIForFile::canonicalize(testPath("foo.h"), "")}),
DocumentLink({MainCpp.range("bar"),
URIForFile::canonicalize(testPath("bar.h"), "")})));
}
} // namespace
} // namespace clangd
} // namespace clang