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
|
/*
* Copyright 2014 David Stevens <dgedstevens@gmail.com>
* Copyright 2014 Kevin Funk <kfunk@kde.org>
* Copyright 2015 Milian Wolff <mail@milianw.de>
* Copyright 2015 Sergey Kalinichev <kalinichev.so.0@gmail.com>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of
* the License or (at your option) version 3 or any later version
* accepted by the membership of KDE e.V. (or its successor approved
* by the membership of KDE e.V.), which shall act as a proxy
* defined in Section 14 of version 3 of the license.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "test_codecompletion.h"
#include <language/backgroundparser/backgroundparser.h>
#include <tests/testcore.h>
#include <tests/autotestshell.h>
#include <tests/testfile.h>
#include <tests/testproject.h>
#include "duchain/parsesession.h"
#include "duchain/clanghelpers.h"
#include "util/clangtypes.h"
#include <interfaces/idocumentcontroller.h>
#include <interfaces/ilanguagecontroller.h>
#include <language/codecompletion/codecompletiontesthelper.h>
#include <language/duchain/types/functiontype.h>
#include "codecompletion/completionhelper.h"
#include "codecompletion/context.h"
#include "codecompletion/includepathcompletioncontext.h"
#include "../clangsettings/clangsettingsmanager.h"
#include <KTextEditor/Editor>
#include <KTextEditor/Document>
#include <KTextEditor/View>
#include <KConfigGroup>
#include <QVersionNumber>
QTEST_MAIN(TestCodeCompletion)
static const auto NoMacroOrBuiltin = ClangCodeCompletionContext::ContextFilters(
ClangCodeCompletionContext::NoBuiltins | ClangCodeCompletionContext::NoMacros);
using namespace KDevelop;
using ClangCodeCompletionItemTester = CodeCompletionItemTester<ClangCodeCompletionContext>;
struct CompletionItems {
CompletionItems(){}
CompletionItems(const KTextEditor::Cursor& position, const QStringList& completions, const QStringList& declarationItems = {})
: position(position)
, completions(completions)
, declarationItems(declarationItems)
{};
KTextEditor::Cursor position;
QStringList completions;
QStringList declarationItems; ///< completion items that have associated declarations. Declarations with higher match quality at the top. @sa KTextEditor::CodeCompletionModel::MatchQuality
};
Q_DECLARE_TYPEINFO(CompletionItems, Q_MOVABLE_TYPE);
Q_DECLARE_METATYPE(CompletionItems)
struct CompletionPriorityItem
{
CompletionPriorityItem(const QString& name, int matchQuality = 0, int inheritanceDepth = 0, const QString& failMessage = {})
: name(name)
, failMessage(failMessage)
, matchQuality(matchQuality)
, inheritanceDepth(inheritanceDepth)
{}
QString name;
QString failMessage;
int matchQuality;
int inheritanceDepth;
};
struct CompletionPriorityItems : public CompletionItems
{
CompletionPriorityItems(){}
CompletionPriorityItems(const KTextEditor::Cursor& position, const QList<CompletionPriorityItem>& completions)
: CompletionItems(position, {})
, completions(completions)
{};
QList<CompletionPriorityItem> completions;
};
Q_DECLARE_TYPEINFO(CompletionPriorityItems, Q_MOVABLE_TYPE);
Q_DECLARE_METATYPE(CompletionPriorityItems)
namespace {
struct NoopTestFunction
{
void operator()(const ClangCodeCompletionItemTester& /*tester*/) const
{
}
};
QString textForDocument(const QUrl& url, const KTextEditor::Cursor& position)
{
bool close = false;
auto* doc = ICore::self()->documentController()->documentForUrl(url);
if (!doc) {
doc = ICore::self()->documentController()->openDocument(url);
close = true;
}
auto text = doc->textDocument()->text({{0, 0}, position});
if (close) {
doc->close(IDocument::Discard);
}
return text;
}
QExplicitlySharedDataPointer<ClangCodeCompletionContext> createContext(const ReferencedTopDUContext& top,
const ParseSessionData::Ptr& sessionData,
const KTextEditor::Cursor position,
const QString& code = {})
{
const auto url = top->url().toUrl();
const auto text = code.isEmpty() ? textForDocument(url, position) : code;
return QExplicitlySharedDataPointer<ClangCodeCompletionContext>{
new ClangCodeCompletionContext(DUContextPointer(top), sessionData, url, position, text)};
}
template<typename CustomTestFunction = NoopTestFunction>
void executeCompletionTest(const ReferencedTopDUContext& top, const CompletionItems& expectedCompletionItems,
const ClangCodeCompletionContext::ContextFilters& filters = NoMacroOrBuiltin,
CustomTestFunction customTestFunction = {})
{
DUChainReadLocker lock;
const ParseSessionData::Ptr sessionData(dynamic_cast<ParseSessionData*>(top->ast().data()));
QVERIFY(sessionData);
lock.unlock();
// TODO: We should not need to pass 'session' to the context, should just use the base class ctor
auto context = createContext(top, sessionData, expectedCompletionItems.position);
context->setFilters(filters);
lock.lock();
auto tester = ClangCodeCompletionItemTester(context);
int previousMatchQuality = 10;
for(const auto& declarationName : expectedCompletionItems.declarationItems){
const auto declarationItem = tester.findItem(declarationName);
QVERIFY(declarationItem);
QVERIFY(declarationItem->declaration());
auto matchQuality = tester.itemData(declarationItem, KTextEditor::CodeCompletionModel::Name, KTextEditor::CodeCompletionModel::MatchQuality).toInt();
QVERIFY(matchQuality <= previousMatchQuality);
previousMatchQuality = matchQuality;
}
tester.names.sort();
QEXPECT_FAIL("look-ahead function primary type argument", "No API in LibClang to determine expected code completion type", Continue);
QEXPECT_FAIL("look-ahead template parameter substitution", "No parameters substitution so far", Continue);
#if CINDEX_VERSION_MINOR < 30
QEXPECT_FAIL("look-ahead auto item", "Auto type, like many other types, is not exposed through LibClang. We assign DelayedType to it instead of IdentifiedType", Continue);
#endif
if (QTest::currentTestFunction() == QByteArrayLiteral("testImplementAfterEdit") && expectedCompletionItems.position.line() == 3) {
QEXPECT_FAIL("", "TU is not properly updated after edit", Continue);
}
if (QTest::currentTestFunction() == QByteArrayLiteral("testClangCodeCompletion")) {
QEXPECT_FAIL("look-ahead pointer", "self-assignment isn't done anymore, so we don't find any suitable type anymore", Continue);
if (QVersionNumber::fromString(ClangHelpers::clangVersion()) >= QVersionNumber(9, 0, 0)) {
QEXPECT_FAIL("enum-case", "quite a lot of unrelated cruft is suggested, needs to be fixed upstream", Continue);
}
}
if (tester.names.size() != expectedCompletionItems.completions.size()) {
qDebug() << "different results:\nactual:" << tester.names << "\nexpected:" << expectedCompletionItems.completions;
}
QCOMPARE(tester.names, expectedCompletionItems.completions);
lock.unlock(); // customTestFunction should lock appropriately
customTestFunction(tester);
}
template<typename CustomTestFunction = NoopTestFunction>
void executeCompletionTest(const QString& code, const CompletionItems& expectedCompletionItems,
const ClangCodeCompletionContext::ContextFilters& filters = NoMacroOrBuiltin,
CustomTestFunction customTestFunction = {},
// Using QStringLiteral fails here with Ubuntu Bionic's GNU 7.4.0 C++ compiler,
// Assembler messages: Error: symbol `_ZZNK12_GLOBAL__N_1UlvE_clEvE15qstring_literal' is already defined
// Seems the symbol is not including the template arguments, but might be created
// per instantiation of the template
// Seems fixed in newer versions of GCC
const QString& fileExtension = QString::fromLatin1("cpp"))
{
TestFile file(code, fileExtension);
QVERIFY(file.parseAndWait(TopDUContext::AllDeclarationsContextsUsesAndAST));
executeCompletionTest(file.topContext(), expectedCompletionItems, filters, customTestFunction);
}
void executeCompletionPriorityTest(const QString& code, const CompletionPriorityItems& expectedCompletionItems,
const ClangCodeCompletionContext::ContextFilters& filters = NoMacroOrBuiltin)
{
TestFile file(code, QStringLiteral("cpp"));
QVERIFY(file.parseAndWait(TopDUContext::AllDeclarationsContextsUsesAndAST));
DUChainReadLocker lock;
auto top = file.topContext();
QVERIFY(top);
const ParseSessionData::Ptr sessionData(dynamic_cast<ParseSessionData*>(top->ast().data()));
QVERIFY(sessionData);
// don't hold DUChain lock when constructing ClangCodeCompletionContext
lock.unlock();
auto context = createContext(top, sessionData, expectedCompletionItems.position);
context->setFilters(filters);
lock.lock();
auto tester = ClangCodeCompletionItemTester(context);
for(const auto& declaration : expectedCompletionItems.completions){
const auto declarationItem = tester.findItem(declaration.name);
QVERIFY(declarationItem);
QVERIFY(declarationItem->declaration());
auto matchQuality = tester.itemData(declarationItem, KTextEditor::CodeCompletionModel::Name, KTextEditor::CodeCompletionModel::MatchQuality).toInt();
auto inheritanceDepth = declarationItem->inheritanceDepth();
if(!declaration.failMessage.isEmpty()){
QEXPECT_FAIL("", declaration.failMessage.toUtf8().constData(), Continue);
}
QVERIFY(matchQuality == declaration.matchQuality && inheritanceDepth == declaration.inheritanceDepth);
}
}
void executeMemberAccessReplacerTest(const QString& code, const CompletionItems& expectedCompletionItems,
const ClangCodeCompletionContext::ContextFilters& filters = NoMacroOrBuiltin)
{
TestFile file(code, QStringLiteral("cpp"));
auto document = ICore::self()->documentController()->openDocument(file.url().toUrl());
QVERIFY(document);
ICore::self()->documentController()->activateDocument(document);
auto view = ICore::self()->documentController()->activeTextDocumentView();
Q_ASSERT(view);
view->setCursorPosition(expectedCompletionItems.position);
QVERIFY(file.parseAndWait(TopDUContext::AllDeclarationsContextsUsesAndAST));
DUChainReadLocker lock;
auto top = file.topContext();
QVERIFY(top);
const ParseSessionData::Ptr sessionData(dynamic_cast<ParseSessionData*>(top->ast().data()));
QVERIFY(sessionData);
lock.unlock();
auto context = createContext(top, sessionData, expectedCompletionItems.position, code);
QApplication::processEvents();
document->close(KDevelop::IDocument::Silent);
// The previous ClangCodeCompletionContext call should replace member access.
// That triggers an update request in the duchain which we are not interested in,
// so let's stop that request.
ICore::self()->languageController()->backgroundParser()->removeDocument(file.url());
context = createContext(top, sessionData, expectedCompletionItems.position);
context->setFilters(filters);
lock.lock();
auto tester = ClangCodeCompletionItemTester(context);
tester.names.sort();
QCOMPARE(tester.names, expectedCompletionItems.completions);
}
using IncludeTester = CodeCompletionItemTester<IncludePathCompletionContext>;
QExplicitlySharedDataPointer<IncludePathCompletionContext> executeIncludePathCompletion(TestFile* file, const KTextEditor::Cursor& position)
{
if (!file->parseAndWait(TopDUContext::AllDeclarationsContextsUsesAndAST)) {
QTest::qFail("Failed to parse source file.", __FILE__, __LINE__);
return {};
}
DUChainReadLocker lock;
auto top = file->topContext();
if (!top) {
QTest::qFail("Failed to parse source file.", __FILE__, __LINE__);
return {};
}
const ParseSessionData::Ptr sessionData(dynamic_cast<ParseSessionData*>(top->ast().data()));
if (!sessionData) {
QTest::qFail("Failed to acquire parse session data.", __FILE__, __LINE__);
return {};
}
DUContextPointer topPtr(top);
lock.unlock();
auto text = file->fileContents();
int textLength = -1;
if (position.isValid()) {
textLength = 0;
for (int i = 0; i < position.line(); ++i) {
textLength = text.indexOf('\n', textLength) + 1;
}
textLength += position.column();
}
auto context = new IncludePathCompletionContext(topPtr, sessionData, file->url().toUrl(), position, text.mid(0, textLength));
return QExplicitlySharedDataPointer<IncludePathCompletionContext>{context};
}
}
void TestCodeCompletion::testClangCodeCompletion()
{
QFETCH(QString, code);
QFETCH(CompletionItems, expectedItems);
executeCompletionTest(code, expectedItems);
}
void TestCodeCompletion::testClangCodeCompletion_data()
{
QTest::addColumn<QString>("code");
QTest::addColumn<CompletionItems>("expectedItems");
QTest::newRow("assignment")
<< "int foo = 5; \nint bar = "
<< CompletionItems{{1,9}, {
"foo",
}, {"foo"}};
QTest::newRow("dotmemberaccess")
<< "class Foo { public: void foo() {} bool operator=(Foo &&) }; int main() { Foo f; \nf. "
<< CompletionItems{{1, 2}, {
"foo",
"operator="
}, {"foo", "operator="}};
QTest::newRow("arrowmemberaccess")
<< "class Foo { public: void foo() {} }; int main() { Foo* f = new Foo; \nf-> }"
<< CompletionItems{{1, 3}, {
"foo"
}, {"foo"}};
QTest::newRow("enum-case")
<< "enum Foo { foo, bar }; int main() { Foo f; switch (f) {\ncase "
<< CompletionItems{{1,4}, {
"bar",
"foo",
}, {"foo", "bar"}};
QTest::newRow("only-private")
<< "class SomeStruct { private: void priv() {} };\n"
"int main() { SomeStruct s;\ns. "
<< CompletionItems{{2, 2}, {
}};
QTest::newRow("private-friend")
<< "class SomeStruct { private: void priv() {} friend int main(); };\n"
"int main() { SomeStruct s;\ns. "
<< CompletionItems{{2, 2}, {
"priv",
}, {"priv"}};
QTest::newRow("private-public")
<< "class SomeStruct { public: void pub() {} private: void priv() {} };\n"
"int main() { SomeStruct s;\ns. "
<< CompletionItems{{2, 2}, {
"pub",
}, {"pub"}};
QTest::newRow("protected-public")
<< "class SomeStruct { public: void pub() {} protected: void prot() {} };\n"
"int main() { SomeStruct s;\ns. "
<< CompletionItems{{2, 2}, {
"pub",
}, {"pub"}};
QTest::newRow("localVariable")
<< "int main() { int localVariable;\nloc "
<< CompletionItems{{1, 3},
{"localVariable","main"},
{"localVariable", "main"}
};
QTest::newRow("globalVariable")
<< "int globalVariable;\nint main() { \ngl "
<< CompletionItems{{2, 2},
{"globalVariable","main"},
{"globalVariable", "main"}
};
QTest::newRow("namespaceVariable")
<< "namespace NameSpace{int variable};\nint main() { \nNameSpace:: "
<< CompletionItems{{2, 11},
{"variable"},
{"variable"}
};
QTest::newRow("parentVariable")
<< "class A{public: int m_variable;};class B : public A{};\nint main() { B b;\nb. "
<< CompletionItems{{2, 2},
{"m_variable"},
{"m_variable"}
};
QTest::newRow("itemsPriority")
<< "class A; class B; void f(A); int main(){ A c; B b;f(\n} "
<< CompletionItems{{1, 0},
{"A", "B", "b", "c", "f",
#if CINDEX_VERSION_MINOR >= 30
"f",
#endif
"main"},
{"c", "A", "b", "B"}
};
QTest::newRow("function-arguments")
<< "class Abc; int f(Abc){\n "
<< CompletionItems{{1, 0}, {
"Abc",
"f",
}};
QTest::newRow("look-ahead int")
<< "struct LookAhead { int intItem;}; int main() {LookAhead* pInstance; LookAhead instance; int i =\n }"
<< CompletionItems{{1, 0}, {
"LookAhead", "instance",
"instance.intItem", "main",
"pInstance", "pInstance->intItem",
}};
QTest::newRow("look-ahead class")
<< "class Class{}; struct LookAhead {Class classItem;}; int main() {LookAhead* pInstance; LookAhead instance; Class cl =\n }"
<< CompletionItems{{1, 0}, {
"Class", "LookAhead",
"instance", "instance.classItem",
"main", "pInstance", "pInstance->classItem",
}};
QTest::newRow("look-ahead function argument")
<< "class Class{}; struct LookAhead {Class classItem;}; void function(Class cl);"
"int main() {LookAhead* pInstance; LookAhead instance; function(\n }"
<< CompletionItems{{1, 0}, {
"Class", "LookAhead", "function",
#if CINDEX_VERSION_MINOR >= 30
"function",
#endif
"instance", "instance.classItem",
"main", "pInstance", "pInstance->classItem",
}};
QTest::newRow("look-ahead function primary type argument")
<< "struct LookAhead {double doubleItem;}; void function(double double);"
"int main() {LookAhead* pInstance; LookAhead instance; function(\n }"
<< CompletionItems{{1, 0}, {
"LookAhead", "function", "instance",
"instance.doubleItem", "main",
"pInstance", "pInstance->doubleItem",
}};
QTest::newRow("look-ahead typedef")
<< "typedef double DOUBLE; struct LookAhead {DOUBLE doubleItem;};"
"int main() {LookAhead* pInstance; LookAhead instance; double i =\n "
<< CompletionItems{{1, 0}, {
"DOUBLE", "LookAhead",
"instance", "instance.doubleItem",
"main", "pInstance", "pInstance->doubleItem",
}};
QTest::newRow("look-ahead pointer")
<< "struct LookAhead {int* pInt;};"
"int main() {LookAhead* pInstance; LookAhead instance; int* i =\n "
<< CompletionItems{{1, 0}, {
"LookAhead", "instance",
"instance.pInt", "main",
"pInstance", "pInstance->pInt",
}};
QTest::newRow("look-ahead template")
<< "template <typename T> struct LookAhead {int intItem;};"
"int main() {LookAhead<int>* pInstance; LookAhead<int> instance; int i =\n "
<< CompletionItems{{1, 0}, {
"LookAhead", "instance",
"instance.intItem", "main",
"pInstance", "pInstance->intItem",
}};
QTest::newRow("look-ahead template parameter substitution")
<< "template <typename T> struct LookAhead {T itemT;};"
"int main() {LookAhead<int>* pInstance; LookAhead<int> instance; int i =\n "
<< CompletionItems{{1, 0}, {
"LookAhead", "instance",
"instance.itemT", "main",
"pInstance", "pInstance->itemT",
}};
QTest::newRow("look-ahead item access")
<< "class Class { public: int publicInt; protected: int protectedInt; private: int privateInt;};"
"int main() {Class cl; int i =\n "
<< CompletionItems{{1, 0}, {
"Class", "cl",
"cl.publicInt",
"main",
}};
QTest::newRow("look-ahead auto item")
<< "struct LookAhead { int intItem; };"
"int main() {auto instance = LookAhead(); int i = \n "
<< CompletionItems{{1, 0}, {
"LookAhead",
"instance",
"instance.intItem",
"main"
}};
QTest::newRow("variadic template recursive class")
<< R"(
template <typename Head, typename ...Tail>
struct my_class : Head, my_class<Tail...>
{
using base = Head;
};)"
<< CompletionItems{{3, 17}, { "Head", "Tail", "my_class" }};
}
void TestCodeCompletion::testClangCodeCompletionType()
{
QFETCH(QString, fileExtension);
QFETCH(QString, code);
QFETCH(CompletionItems, expectedItems);
QFETCH(QString, expedtedItem);
QFETCH(QString, expectedType);
auto executeItem = [=] (const ClangCodeCompletionItemTester& tester) {
auto item = tester.findItem(expedtedItem);
QVERIFY(item);
auto declaration = item->declaration();
QVERIFY(declaration);
QCOMPARE(declaration->abstractType()->toString(), expectedType);
};
executeCompletionTest(code, expectedItems, NoMacroOrBuiltin, executeItem, fileExtension);
}
void TestCodeCompletion::testClangCodeCompletionType_data()
{
QTest::addColumn<QString>("fileExtension");
QTest::addColumn<QString>("code");
QTest::addColumn<CompletionItems>("expectedItems");
QTest::addColumn<QString>("expedtedItem");
QTest::addColumn<QString>("expectedType");
QTest::newRow("bug409041")
<< "c"
<< "typedef struct { int bitmask[1]; } bitmask_a;\n"
"typedef struct { int bitmask[6]; } bitmask_c;\n"
"typedef union { bitmask_c bitmask; } bitmask_union;\n"
"int main() { bitmask_union u;\n"
"u. \n "
<< CompletionItems{{4, 2}, { "bitmask" }}
<< "bitmask"
<< "bitmask_c";
}
void TestCodeCompletion::testReplaceMemberAccess()
{
QFETCH(QString, code);
QFETCH(CompletionItems, expectedItems);
executeMemberAccessReplacerTest(code, expectedItems);
}
void TestCodeCompletion::testReplaceMemberAccess_data()
{
QTest::addColumn<QString>("code");
QTest::addColumn<CompletionItems>("expectedItems");
QTest::newRow("replace arrow to dot")
<< "struct Struct { void function(); };"
"int main() { Struct s; \ns-> "
<< CompletionItems{{1, 3}, {
"function"
}};
QTest::newRow("replace dot to arrow")
<< "struct Struct { void function(); };"
"int main() { Struct* s; \ns. "
<< CompletionItems{{1, 3}, {
"function"
}};
QTest::newRow("no replacement needed")
<< "int main() { double a = \n0. "
<< CompletionItems{{1, 2}, {
}};
}
void TestCodeCompletion::testVirtualOverride()
{
QFETCH(QString, code);
QFETCH(CompletionItems, expectedItems);
executeCompletionTest(code, expectedItems, ClangCodeCompletionContext::NoClangCompletion);
}
void TestCodeCompletion::testVirtualOverride_data()
{
QTest::addColumn<QString>("code");
QTest::addColumn<CompletionItems>("expectedItems");
QTest::newRow("basic")
<< "class Foo { virtual void foo(); virtual void foo(char c); virtual char foo(char c, int i, double d); };\n"
"class Bar : Foo \n{void foo(char c) override;\n}"
<< CompletionItems{{3, 1}, {"foo()", "foo(char c, int i, double d)"}};
QTest::newRow("template")
<< "template<class T1, class T2> class Foo { virtual T2 foo(T1 a, T2 b, int i); virtual T2 overridden(T1 a); } ;\n"
"class Bar : Foo<char, double> \n{double overridden(char a) override;\n}"
<< CompletionItems{{3, 1}, {"foo(char a, double b, int i)"}};
QTest::newRow("nested-template")
<< "template<class T1, class T2> class Foo { virtual T2 foo(T1 a, T2 b, int i); virtual T2 overridden(T1 a, T2 b, int i); } ;\n"
"template<class T1, class T2> class Baz { };\n"
"class Bar : Foo<char, Baz<char, double>> \n{Baz<char, double> overridden(char a, Baz<char, double> b, int i) override;\n}"
<< CompletionItems{{4, 1}, {"foo(char a, Baz<char, double> b, int i)"}};
QTest::newRow("multi")
<< "class Foo { virtual int foo(int i); virtual int overridden(int i); };\n"
"class Baz { virtual char baz(char c); };\n"
"class Bar : Foo, Baz \n{int overridden(int i) override;\n}"
<< CompletionItems{{4, 1}, {"baz(char c)", "foo(int i)"}};
QTest::newRow("deep")
<< "class Foo { virtual int foo(int i); virtual int overridden(int i); };\n"
"class Baz : Foo { };\n"
"class Bar : Baz \n{int overridden(int i) override;\n}"
<< CompletionItems{{4, 1}, {"foo(int i)"}};
QTest::newRow("repeated")
<< "class Foo { virtual int foo(int i); virtual int overridden(int i); };\n"
"class Baz : Foo { int foo(int i) override; };\n"
"class Bar : Baz \n{int overridden(int i) override;\n}"
<< CompletionItems{{4, 1}, {"foo(int i)"}};
QTest::newRow("pure")
<< "class Foo { virtual void foo() = 0; virtual void overridden() = 0;};\n"
"class Bar : Foo \n{void overridden() override;\n};"
<< CompletionItems{{3, 0}, {"foo() = 0"}};
QTest::newRow("repeated-pure")
<< "class Foo { virtual void foo() = 0; virtual void overridden() = 0; };\n"
"class Baz : Foo { void foo() override; };\n"
"class Bar : Baz \n{void overridden() override;\n}"
<< CompletionItems{{4, 1}, {"foo()"}};
QTest::newRow("const")
<< "class Foo { virtual void foo(const int b) const; virtual void overridden(const int b) const; }\n;"
"class Bar : Foo \n{void overridden(const int b) const override;\n}"
<< CompletionItems{{3, 1}, {"foo(const int b) const"}};
QTest::newRow("dont-override")
<< R"(class A {
virtual void something() = 0;
};
class B : public A
{
public:
void foo();
};
void B::foo() {}
)" << CompletionItems{{8, 14}, {}};
}
void TestCodeCompletion::testOverrideExecute()
{
QFETCH(QString, code);
QFETCH(CompletionItems, expectedItems);
QFETCH(QString, itemToExecute);
QFETCH(QString, cppStandard);
QFETCH(QString, expectedCode);
QTemporaryDir directory;
TestProject testProject {Path{directory.path()}};
auto t = testProject.path().toLocalFile();
auto configGroup = testProject.projectConfiguration()->group("CustomDefinesAndIncludes").group("ProjectPath0");
configGroup.writeEntry("Path", ".");
configGroup.writeEntry("parserArguments", cppStandard);
configGroup.sync();
m_projectController->addProject(&testProject);
TestFile file(code, QStringLiteral("cpp"), &testProject, directory.path());
QVERIFY(file.parseAndWait(TopDUContext::AllDeclarationsContextsUsesAndAST));
auto executeItem = [=] (const ClangCodeCompletionItemTester& tester) {
auto item = tester.findItem(itemToExecute);
QVERIFY(item);
auto view = createView(tester.completionContext->duContext()->url().toUrl());
DUChainReadLocker lock;
item->execute(view.get(), view->document()->wordRangeAt(expectedItems.position));
QCOMPARE(view->document()->text(), expectedCode);
};
executeCompletionTest(file.topContext(), expectedItems, NoMacroOrBuiltin, executeItem);
m_projectController->closeProject(&testProject);
}
void TestCodeCompletion::testOverrideExecute_data()
{
QTest::addColumn<QString>("code");
QTest::addColumn<CompletionItems>("expectedItems");
QTest::addColumn<QString>("itemToExecute");
QTest::addColumn<QString>("cppStandard");
QTest::addColumn<QString>("expectedCode");
QTest::newRow("override-modern")
<< "class Foo { virtual int bar(char c); };\nclass Baz : Foo\n{\n};"
<< CompletionItems{{3, 0}, {"Baz", "Foo", "bar(char c)"}}
<< "bar(char c)"
<< "-std=c++11"
<< "class Foo { virtual int bar(char c); };\n"
"class Baz : Foo\n{\nint bar(char c) override;};";
QTest::newRow("override-non-modern")
<< "class Foo { virtual int bar(char c); };\nclass Baz : Foo\n{\n};"
<< CompletionItems{{3, 0}, {"Baz", "Foo", "bar(char c)"}}
<< "bar(char c)"
<< "-std=c++98"
<< "class Foo { virtual int bar(char c); };\n"
"class Baz : Foo\n{\nint bar(char c);};";
QTest::newRow("override-unknown")
<< "class Foo { virtual int bar(char c); };\nclass Baz : Foo\n{\n};"
<< CompletionItems{{3, 0}, {"Baz", "Foo", "bar(char c)"}}
<< "bar(char c)"
<< "-std=c++17"
<< "class Foo { virtual int bar(char c); };\n"
"class Baz : Foo\n{\nint bar(char c) override;};";
}
void TestCodeCompletion::testImplement()
{
QFETCH(QString, code);
QFETCH(CompletionItems, expectedItems);
executeCompletionTest(code, expectedItems, ClangCodeCompletionContext::NoClangCompletion);
}
void TestCodeCompletion::testImplement_data()
{
QTest::addColumn<QString>("code");
QTest::addColumn<CompletionItems>("expectedItems");
QTest::newRow("basic")
<< "int foo(char c, int i); \n"
<< CompletionItems{{1, 0}, {"foo(char c, int i)"}};
QTest::newRow("class")
<< "class Foo { \n"
"int bar(char c, int i); \n\n"
"}; \n"
<< CompletionItems{{2, 0}, {}};
QTest::newRow("class2")
<< "class Foo { \n"
"int bar(char c, int i); \n\n"
"}; \n"
<< CompletionItems{{4, 0}, {"Foo::bar(char c, int i)"}};
QTest::newRow("namespace")
<< "namespace Foo { \n"
"int bar(char c, int i); \n\n"
"}; \n"
<< CompletionItems{{2, 0}, {"bar(char c, int i)"}};
QTest::newRow("anonymous-namespace")
<< R"(
namespace {
int bar(char c, int i);
};
)"
<< CompletionItems{{3, 0}, {"bar(char c, int i)"}};
QTest::newRow("anonymous-namespace2")
<< R"(
namespace {
int bar(char c, int i);
};
)"
<< CompletionItems{{4, 0}, {}};
QTest::newRow("namespace2")
<< "namespace Foo { \n"
"int bar(char c, int i); \n\n"
"}; \n"
<< CompletionItems{{4, 0}, {"Foo::bar(char c, int i)"}};
QTest::newRow("two-namespace")
<< "namespace Foo { int bar(char c, int i); };\n"
"namespace Foo {\n"
"};\n"
<< CompletionItems{{2, 0}, {"bar(char c, int i)"}};
QTest::newRow("destructor")
<< "class Foo { ~Foo(); }\n"
<< CompletionItems{{1, 0}, {"Foo::~Foo()"}};
QTest::newRow("constructor")
<< "class Foo { \n"
"Foo(int i); \n"
"}; \n"
<< CompletionItems{{3, 1}, {"Foo::Foo(int i)"}};
QTest::newRow("template")
<< "template<typename T> class Foo { T bar(T t); };\n"
<< CompletionItems{{1, 1}, {"Foo<T>::bar(T t)"}};
QTest::newRow("specialized-template")
<< "template<typename T> class Foo { \n"
"T bar(T t); \n"
"}; \n"
"template<typename T> T Foo<T>::bar(T t){} \n"
"template<> class Foo<int> { \n"
"int bar(int t); \n"
"}\n"
<< CompletionItems{{6, 1}, {"Foo<int>::bar(int t)"}};
QTest::newRow("nested-class")
<< "class Foo { \n"
"class Bar { \n"
"int baz(char c, int i); \n\n"
"}; \n\n"
"}; \n\n"
<< CompletionItems {{3, 1}, {}};
QTest::newRow("nested-class2")
<< "class Foo { \n"
"class Bar { \n"
"int baz(char c, int i); \n\n"
"}; \n\n"
"}; \n\n"
<< CompletionItems {{5, 1}, {}};
QTest::newRow("nested-class3")
<< "class Foo { \n"
"class Bar { \n"
"int baz(char c, int i); \n\n"
"}; \n\n"
"}; \n\n"
<< CompletionItems {{7, 1}, {"Foo::Bar::baz(char c, int i)"}};
QTest::newRow("nested-namespace")
<< "namespace Foo { \n"
"namespace Bar { \n"
"int baz(char c, int i); \n\n"
"}; \n\n"
"}; \n\n"
<< CompletionItems {{3, 1}, {"baz(char c, int i)"}};
QTest::newRow("nested-namespace2")
<< "namespace Foo { \n"
"namespace Bar { \n"
"int baz(char c, int i); \n\n"
"}; \n\n"
"}; \n\n"
<< CompletionItems {{5, 1}, {"Bar::baz(char c, int i)"}};
QTest::newRow("nested-namespace3")
<< "namespace Foo { \n"
"namespace Bar { \n"
"int baz(char c, int i); \n\n"
"}; \n\n"
"}; \n\n"
<< CompletionItems {{7, 1}, {"Foo::Bar::baz(char c, int i)"}};
QTest::newRow("partial-template")
<< "template<typename T> class Foo { \n"
"template<typename U> class Bar;\n"
"template<typename U> class Bar<U*> { void baz(T t, U u); }\n"
"}\n"
<< CompletionItems{{5,1}, {"Foo<T>::Bar<U *>::baz(T t, U u)"}};
QTest::newRow("variadic")
<< "int foo(...); int bar(int i, ...); \n"
<< CompletionItems{{1, 1}, {"bar(int i, ...)", "foo(...)"}};
QTest::newRow("const")
<< "class Foo { int bar() const; };"
<< CompletionItems{{3, 1}, {"Foo::bar() const"}};
QTest::newRow("multiple-methods")
<< "class Foo { int bar(); void foo(); char asdf() const; };"
<< CompletionItems{{1, 1}, {"Foo::asdf() const", "Foo::bar()", "Foo::foo()"}};
// explicitly deleted/defaulted functions should not appear in the implements completion
QTest::newRow("deleted-copy-ctor")
<< "struct S { S(); S(const S&) = /*some comment*/ delete; };"
<< CompletionItems{{1,1}, {"S::S()"}};
QTest::newRow("deleted-overload-member")
<< "struct Foo {\n"
" int x();\n"
" int x(int) =delete;\n"
"};\n"
<< CompletionItems{{5,1}, {"Foo::x()"}};
QTest::newRow("deleted-overload-global")
<< "int x();\n"
"int x(int)= delete;\n"
<< CompletionItems{{2,1}, {"x()"}};
QTest::newRow("defaulted-copy-ctor")
<< "struct S { S(); S(const S&) = default; };"
<< CompletionItems{{1,1}, {"S::S()"}};
QTest::newRow("defaulted-dtor")
<< "struct Foo {\n"
" Foo();\n"
" ~Foo() =default;\n"
"};\n"
<< CompletionItems{{5,1}, {"Foo::Foo()"}};
QTest::newRow("bug355163")
<< R"(
#include <type_traits>
namespace test {
template<typename T, typename U>
struct IsSafeConversion : public std::is_same<T, typename std::common_type<T, U>::type>
{
};
} // namespace test
)"
<< CompletionItems{{7,0}, {}};
QTest::newRow("bug355954")
<< R"(
struct Hello {
struct Private;
};
struct Hello::Private {
void test();
};
)"
<< CompletionItems{{8,0}, {"Hello::Private::test()"}};
QTest::newRow("lineOfNextFunction")
<< "void foo();\nvoid bar() {}"
<< CompletionItems{{1,0}, {"foo()"}};
QTest::newRow("pure")
<< R"(
struct Hello {
virtual void foo() = 0;
virtual void bar();
};
)"
<< CompletionItems{{5, 0}, {"Hello::bar()"}};
QTest::newRow("bug368544")
<< R"(
class Klass {
public:
template <typename T>
void func(int a, T x, int b) const;
};
)"
<< CompletionItems{{6, 0}, {"Klass::func(int a, T x, int b) const"}};
}
void TestCodeCompletion::testImplementOtherFile()
{
TestFile header1(QStringLiteral("void foo();"), QStringLiteral("h"));
QVERIFY(header1.parseAndWait());
TestFile header2(QStringLiteral("void bar();"), QStringLiteral("h"));
QVERIFY(header2.parseAndWait());
TestFile impl(QString("#include \"%1\"\n"
"#include \"%2\"\n"
"void asdf();\n\n")
.arg(header1.url().str(), header2.url().str()),
QStringLiteral("cpp"), &header1);
CompletionItems expectedItems{{3,1}, {"asdf()", "foo()"}};
QVERIFY(impl.parseAndWait(TopDUContext::AllDeclarationsContextsUsesAndAST));
executeCompletionTest(impl.topContext(), expectedItems);
}
void TestCodeCompletion::testImplementAfterEdit()
{
TestFile header1(QStringLiteral("void foo();"), QStringLiteral("h"));
QVERIFY(header1.parseAndWait());
TestFile impl(QString("#include \"%1\"\n"
"void asdf() {}\nvoid bar() {}")
.arg(header1.url().str()),
QStringLiteral("cpp"), &header1);
auto document = ICore::self()->documentController()->openDocument(impl.url().toUrl());
QVERIFY(impl.parseAndWait(TopDUContext::AllDeclarationsContextsUsesAndAST));
CompletionItems expectedItems{{2,0}, {"foo()"}};
executeCompletionTest(impl.topContext(), expectedItems);
document->textDocument()->insertText(expectedItems.position, QStringLiteral("\n"));
expectedItems.position.setLine(3);
executeCompletionTest(impl.topContext(), expectedItems);
document->close(IDocument::Discard);
}
void TestCodeCompletion::testInvalidCompletions()
{
QFETCH(QString, code);
QFETCH(CompletionItems, expectedItems);
executeCompletionTest(code, expectedItems);
}
void TestCodeCompletion::testInvalidCompletions_data()
{
QTest::addColumn<QString>("code");
QTest::addColumn<CompletionItems>("expectedItems");
QTest::newRow("invalid-context-incomment")
<< "class Foo { int bar() const; };\n/*\n*/"
<< CompletionItems{{2, 0}, {}};
}
void TestCodeCompletion::testIncludePathCompletion_data()
{
QTest::addColumn<QString>("code");
QTest::addColumn<KTextEditor::Cursor>("cursor");
QTest::addColumn<QString>("itemId");
QTest::addColumn<QString>("result");
QTest::newRow("global-1") << QStringLiteral("#include ") << KTextEditor::Cursor(0, 9)
<< QStringLiteral("iostream") << QStringLiteral("#include <iostream>");
QTest::newRow("global-2") << QStringLiteral("#include <") << KTextEditor::Cursor(0, 9)
<< QStringLiteral("iostream") << QStringLiteral("#include <iostream>");
QTest::newRow("global-3") << QStringLiteral("#include <") << KTextEditor::Cursor(0, 10)
<< QStringLiteral("iostream") << QStringLiteral("#include <iostream>");
QTest::newRow("global-4") << QStringLiteral("# include <") << KTextEditor::Cursor(0, 12)
<< QStringLiteral("iostream") << QStringLiteral("# include <iostream>");
QTest::newRow("global-5") << QStringLiteral("# include <") << KTextEditor::Cursor(0, 14)
<< QStringLiteral("iostream") << QStringLiteral("# include <iostream>");
QTest::newRow("global-6") << QStringLiteral("# include <> /* 1 */") << KTextEditor::Cursor(0, 14)
<< QStringLiteral("iostream") << QStringLiteral("# include <iostream> /* 1 */");
QTest::newRow("global-7") << QStringLiteral("# include /* 1 */ <> /* 1 */") << KTextEditor::Cursor(0, 21)
<< QStringLiteral("iostream") << QStringLiteral("# include /* 1 */ <iostream> /* 1 */");
QTest::newRow("global-8") << QStringLiteral("# /* 1 */ include /* 1 */ <> /* 1 */") << KTextEditor::Cursor(0, 28)
<< QStringLiteral("iostream") << QStringLiteral("# /* 1 */ include /* 1 */ <iostream> /* 1 */");
QTest::newRow("global-9") << QStringLiteral("#include <cstdint>") << KTextEditor::Cursor(0, 10)
<< QStringLiteral("iostream") << QStringLiteral("#include <iostream>");
QTest::newRow("global-10") << QStringLiteral("#include <cstdint>") << KTextEditor::Cursor(0, 14)
<< QStringLiteral("cstdint") << QStringLiteral("#include <cstdint>");
QTest::newRow("global-11") << QStringLiteral("#include <cstdint>") << KTextEditor::Cursor(0, 17)
<< QStringLiteral("cstdint") << QStringLiteral("#include <cstdint>");
QTest::newRow("local-0") << QStringLiteral("#include \"") << KTextEditor::Cursor(0, 10)
<< QStringLiteral("foo/") << QStringLiteral("#include \"foo/\"");
QTest::newRow("local-1") << QStringLiteral("#include \"foo/\"") << KTextEditor::Cursor(0, 14)
<< QStringLiteral("bar/") << QStringLiteral("#include \"foo/bar/\"");
QTest::newRow("local-2") << QStringLiteral("#include \"foo/") << KTextEditor::Cursor(0, 14)
<< QStringLiteral("bar/") << QStringLiteral("#include \"foo/bar/\"");
QTest::newRow("local-3") << QStringLiteral("# /* 1 */ include /* 1 */ \"\" /* 1 */") << KTextEditor::Cursor(0, 28)
<< QStringLiteral("foo/") << QStringLiteral("# /* 1 */ include /* 1 */ \"foo/\" /* 1 */");
QTest::newRow("local-4") << QStringLiteral("# /* 1 */ include /* 1 */ \"foo/\" /* 1 */") << KTextEditor::Cursor(0, 31)
<< QStringLiteral("bar/") << QStringLiteral("# /* 1 */ include /* 1 */ \"foo/bar/\" /* 1 */");
QTest::newRow("local-5") << QStringLiteral("#include \"foo/\"") << KTextEditor::Cursor(0, 10)
<< QStringLiteral("foo/") << QStringLiteral("#include \"foo/\"");
QTest::newRow("local-6") << QStringLiteral("#include \"foo/asdf\"") << KTextEditor::Cursor(0, 10)
<< QStringLiteral("foo/") << QStringLiteral("#include \"foo/\"");
QTest::newRow("local-7") << QStringLiteral("#include \"foo/asdf\"") << KTextEditor::Cursor(0, 14)
<< QStringLiteral("bar/") << QStringLiteral("#include \"foo/bar/\"");
QTest::newRow("dash-1") << QStringLiteral("#include \"") << KTextEditor::Cursor(0, 10)
<< QStringLiteral("dash-file.h") << QStringLiteral("#include \"dash-file.h\"");
QTest::newRow("dash-2") << QStringLiteral("#include \"dash-") << KTextEditor::Cursor(0, 15)
<< QStringLiteral("dash-file.h") << QStringLiteral("#include \"dash-file.h\"");
QTest::newRow("dash-4") << QStringLiteral("#include \"dash-file.h\"") << KTextEditor::Cursor(0, 13)
<< QStringLiteral("dash-file.h") << QStringLiteral("#include \"dash-file.h\"");
QTest::newRow("dash-5") << QStringLiteral("#include \"dash-file.h\"") << KTextEditor::Cursor(0, 14)
<< QStringLiteral("dash-file.h") << QStringLiteral("#include \"dash-file.h\"");
QTest::newRow("dash-6") << QStringLiteral("#include \"dash-file.h\"") << KTextEditor::Cursor(0, 15)
<< QStringLiteral("dash-file.h") << QStringLiteral("#include \"dash-file.h\"");
}
void TestCodeCompletion::testIncludePathCompletion()
{
QFETCH(QString, code);
QFETCH(KTextEditor::Cursor, cursor);
QFETCH(QString, itemId);
QFETCH(QString, result);
QTemporaryDir tempDir;
QDir dir(tempDir.path());
QVERIFY(dir.mkpath("foo/bar/asdf"));
TestFile file(code, QStringLiteral("cpp"), nullptr, tempDir.path());
{
QFile otherFile(tempDir.path() + "/dash-file.h");
QVERIFY(otherFile.open(QIODevice::WriteOnly));
}
IncludeTester tester(executeIncludePathCompletion(&file, cursor));
QVERIFY(tester.completionContext);
QVERIFY(tester.completionContext->isValid());
auto item = tester.findItem(itemId);
QVERIFY(item);
auto view = createView(file.url().toUrl());
QVERIFY(view.get());
auto doc = view->document();
item->execute(view.get(), KTextEditor::Range(cursor, cursor));
QCOMPARE(doc->text(), result);
const auto newCursor = view->cursorPosition();
QCOMPARE(newCursor.line(), cursor.line());
if (!itemId.endsWith('/')) {
// file inserted, cursor should be at end of line
QCOMPARE(newCursor.column(), doc->lineLength(cursor.line()));
} else {
// directory inserted, cursor should be before the " or >
const auto cursorChar = doc->characterAt(newCursor);
QVERIFY(cursorChar == '"' || cursorChar == '>');
}
}
void TestCodeCompletion::testIncludePathCompletionLocal()
{
TestFile header(QStringLiteral("int foo() { return 42; }\n"), QStringLiteral("h"));
TestFile impl(QStringLiteral("#include \""), QStringLiteral("cpp"), &header);
IncludeTester tester(executeIncludePathCompletion(&impl, {0, 10}));
QVERIFY(tester.names.contains(header.url().toUrl().fileName()));
QVERIFY(tester.names.contains("iostream"));
}
void TestCodeCompletion::testOverloadedFunctions()
{
TestFile file(QStringLiteral("void f(); int f(int); void f(int, double){\n "), QStringLiteral("cpp"));
QVERIFY(file.parseAndWait(TopDUContext::AllDeclarationsContextsUsesAndAST));
DUChainReadLocker lock;
auto top = file.topContext();
QVERIFY(top);
const ParseSessionData::Ptr sessionData(dynamic_cast<ParseSessionData*>(top->ast().data()));
QVERIFY(sessionData);
lock.unlock();
const auto context = createContext(top, sessionData, {1, 0});
context->setFilters(NoMacroOrBuiltin);
lock.lock();
const auto tester = ClangCodeCompletionItemTester(context);
QCOMPARE(tester.items.size(), 3);
for (const auto& item : tester.items) {
auto function = item->declaration()->type<FunctionType>();
const QString display = item->declaration()->identifier().toString() + function->partToString(FunctionType::SignatureArguments);
const QString itemDisplay = tester.itemData(item).toString() + tester.itemData(item, KTextEditor:: CodeCompletionModel::Arguments).toString();
QCOMPARE(display, itemDisplay);
}
QVERIFY(tester.items[0]->declaration().data() != tester.items[1]->declaration().data());
QVERIFY(tester.items[0]->declaration().data() != tester.items[2]->declaration().data());
QVERIFY(tester.items[1]->declaration().data() != tester.items[2]->declaration().data());
}
void TestCodeCompletion::testCompletionPriority()
{
QFETCH(QString, code);
QFETCH(CompletionPriorityItems, expectedItems);
executeCompletionPriorityTest(code, expectedItems);
}
void TestCodeCompletion::testCompletionPriority_data()
{
QTest::addColumn<QString>("code");
QTest::addColumn<CompletionPriorityItems>("expectedItems");
QTest::newRow("pointer")
<< "class A{}; class B{}; class C : public B{}; int main(){A* a; B* b; C* c; b =\n "
<< CompletionPriorityItems{{1,0}, {{"a", 0, 21}, {"b", 9, 0},
{"c", 8, 0, QStringLiteral("Pointer to derived class is not added to the Best Matches group")}}};
QTest::newRow("class")
<< "class A{}; class B{}; class C : public B{}; int main(){A a; B b; C c; b =\n "
<< CompletionPriorityItems{{1,0}, {{"a", 0, 21}, {"b", 9, 0},
{"c", 8, 0, QStringLiteral("Derived class is not added to the Best Matches group")}}};
QTest::newRow("primary-types")
<< "class A{}; int main(){A a; int b; bool c = \n "
<< CompletionPriorityItems{{1,0}, {{"a", 0, 34}, {"b", 8, 0}}};
QTest::newRow("reference")
<< "class A{}; class B{}; class C : public B{};"
"int main(){A tmp; A& a = tmp; C tmp2; C& c = tmp2; B& b =\n ;}"
<< CompletionPriorityItems{{1,0}, {{"a", 0, 21},
{"c", 8, 0, QStringLiteral("Reference to derived class is not added to the Best Matches group")}}};
QTest::newRow("typedef")
<< "struct A{}; struct B{}; typedef A AA; typedef B BB; void f(A p);"
"int main(){ BB b; AA a; f(\n }"
<< CompletionPriorityItems{{1,0}, {{"a", 9, 0}, {"b", 0, 21}}};
QTest::newRow("returnType")
<< "struct A{}; struct B{}; struct Test{A f();B g(); Test() { A a =\n }};"
<< CompletionPriorityItems{{1,0}, {{"f", 9, 0}, {"g", 0, 21}}};
QTest::newRow("template")
<< "template <typename T> class Class{}; template <typename T> class Class2{};"
"int main(){ Class<int> a; Class2<int> b =\n }"
<< CompletionPriorityItems{{1,0}, {{"a", 0, 21}}};
QTest::newRow("protected-access")
<< "class Base { protected: int m_protected; };"
"class Derived: public Base {public: void g(){\n }};"
<< CompletionPriorityItems{{1,0}, {{"m_protected", 0, 37}}};
QTest::newRow("protected-access2")
<< "class Base { protected: int m_protected; };"
"class Derived: public Base {public: void f();};"
"void Derived::f(){\n }"
<< CompletionPriorityItems{{1,0}, {{"m_protected", 0, 37}}};
}
void TestCodeCompletion::testVariableScope()
{
TestFile file(QStringLiteral("int var; \nvoid test(int var) {int tmp =\n }"), QStringLiteral("cpp"));
QVERIFY(file.parseAndWait(TopDUContext::AllDeclarationsContextsUsesAndAST));
DUChainReadLocker lock;
auto top = file.topContext();
QVERIFY(top);
const ParseSessionData::Ptr sessionData(dynamic_cast<ParseSessionData*>(top->ast().data()));
QVERIFY(sessionData);
lock.unlock();
const auto context = createContext(top, sessionData, {2, 0});
context->setFilters(NoMacroOrBuiltin);
lock.lock();
const auto tester = ClangCodeCompletionItemTester(context);
QCOMPARE(tester.items.size(), 3);
auto item = tester.findItem(QStringLiteral("var"));
VERIFY(item);
QCOMPARE(item->declaration()->range().start, CursorInRevision(1, 14));
}
struct HintItem
{
QString hint;
bool hasDeclaration;
bool operator==(const HintItem& rhs) const
{
return std::tie(hint, hasDeclaration) == std::tie(rhs.hint, rhs.hasDeclaration);
}
bool operator<(const HintItem& rhs) const
{
return std::tie(hint, hasDeclaration) < std::tie(rhs.hint, rhs.hasDeclaration);
}
QByteArray toString() const
{
return "HintItem(" + hint.toUtf8() + ", " + (hasDeclaration ? "true" : "false") + ')';
}
};
Q_DECLARE_METATYPE(HintItem)
using HintItemList = QVector<HintItem>;
namespace QTest {
template<>
char *toString(const HintItem& hint)
{
return qstrdup(hint.toString());
}
template<>
char *toString(const HintItemList& hints)
{
QByteArray ba = "HintItemList(";
for (int i = 0, c = hints.size(); i < c; ++i) {
ba += hints[i].toString();
if (i == c - 1) {
ba += ')';
} else {
ba += ", ";
}
}
return qstrdup(ba.constData());
}
}
void TestCodeCompletion::testArgumentHintCompletion()
{
QFETCH(QString, code);
QFETCH(CompletionItems, expectedItems);
QFETCH(HintItemList, hints);
executeCompletionTest(code, expectedItems, NoMacroOrBuiltin, [&](const ClangCodeCompletionItemTester& tester) {
DUChainReadLocker lock;
HintItemList actualHints;
for (const auto& item : tester.items) {
if (item->argumentHintDepth() == 1) {
actualHints << HintItem{
tester.itemData(item).toString() + tester.itemData(item, KTextEditor:: CodeCompletionModel::Arguments).toString(),
item->declaration()
};
}
}
std::sort(hints.begin(), hints.end());
std::sort(actualHints.begin(), actualHints.end());
QEXPECT_FAIL("member function", "clang_getCompletionParent returns nothing, thus decl lookup fails", Continue);
QEXPECT_FAIL("namespaced function", "clang_getCompletionParent returns nothing, thus decl lookup fails", Continue);
QEXPECT_FAIL("namespaced constructor", "clang_getCompletionParent returns nothing, thus decl lookup fails", Continue);
QCOMPARE(actualHints, hints);
});
}
void TestCodeCompletion::testArgumentHintCompletion_data()
{
#if CINDEX_VERSION_MINOR < 30
QSKIP("You need at least LibClang 3.7");
#endif
qRegisterMetaType<HintItemList>("HintItemList");
QTest::addColumn<QString>("code");
QTest::addColumn<CompletionItems>("expectedItems");
QTest::addColumn<HintItemList>("hints");
QTest::newRow("global function")
<< "void foo(int);\n"
"int main() { \nfoo( "
<< CompletionItems{{2,4}, {
"foo", "foo",
"main"
}}
<< HintItemList{{"foo(int)", true}};
QTest::newRow("namespaced function")
<< "namespace ns { void foo(int); }\n"
"int main() { \nns::foo( "
<< CompletionItems{{2,4}, {
"foo"
}}
<< HintItemList{{"foo(int)", true}};
QTest::newRow("member function")
<< "struct Struct{ void foo(int);}\n"
"int main() {Struct s; \ns.foo( "
<< CompletionItems{{2,6}, {
"Struct", "foo",
"main", "s"
}}
<< HintItemList{{"foo(int)", true}};
QTest::newRow("template function")
<< "template <typename T> void foo(T);\n"
"int main() { \nfoo( "
<< CompletionItems{{2,6}, {
"foo", "foo",
"main"
}}
<< HintItemList{{"foo(T)", true}};
QTest::newRow("overloaded functions")
<< "void foo(int); void foo(int, double)\n"
"int main() { \nfoo( "
<< CompletionItems{{2,6}, {
"foo", "foo", "foo", "foo",
"main"
}}
<< HintItemList{
{"foo(int)", true},
{"foo(int, double)", true}
};
QTest::newRow("overloaded functions2")
<< "void foo(int); void foo(int, double)\n"
"int main() { foo(1,\n "
<< CompletionItems{{2,1}, {
"foo", "foo", "foo",
"main"
}}
<< HintItemList{{"foo(int, double)", true}};
QTest::newRow("constructor")
<< "struct foo { foo(int); foo(int, double); }\n"
"int main() { foo f(\n "
<< CompletionItems{{2,1}, {
"f", "foo", "foo", "foo", "foo", "foo",
"main"
}}
<< HintItemList{
{"foo(int)", true},
{"foo(int, double)", true},
{"foo(foo &&)", false},
{"foo(const foo &)", false}
};
QTest::newRow("constructor2")
<< "struct foo { foo(int); foo(int, double); }\n"
"int main() { foo f(1,\n "
<< CompletionItems{{2,1}, {
"f", "foo", "foo",
"main"
}}
<< HintItemList{
{"foo(int, double)", true}
};
QTest::newRow("namespaced constructor")
<< "namespace ns { struct foo { foo(int); foo(int, double); } }\n"
"int main() { ns::foo f(\n "
<< CompletionItems{{2,1}, {
"f", "foo", "foo", "foo", "foo",
"main", "ns"
}}
<< HintItemList{
{"foo(int)", true},
{"foo(int, double)", true},
{"foo(ns::foo &&)", false},
{"foo(const ns::foo &)", false}
};
}
void TestCodeCompletion::testArgumentHintCompletionDefaultParameters()
{
#if CINDEX_VERSION_MINOR < 30
QSKIP("You need at least LibClang 3.7");
#endif
TestFile file(QStringLiteral("void f(int i, int j = 0, double k =1){\nf( "), QStringLiteral("cpp"));
QVERIFY(file.parseAndWait(TopDUContext::AllDeclarationsContextsUsesAndAST));
DUChainReadLocker lock;
auto top = file.topContext();
QVERIFY(top);
const ParseSessionData::Ptr sessionData(dynamic_cast<ParseSessionData*>(top->ast().data()));
QVERIFY(sessionData);
lock.unlock();
const auto context = createContext(top, sessionData, {1, 2});
context->setFilters(NoMacroOrBuiltin);
lock.lock();
const auto tester = ClangCodeCompletionItemTester(context);
QExplicitlySharedDataPointer<KDevelop::CompletionTreeItem> f;
for (const auto& item : tester.items) {
if (item->argumentHintDepth() == 1) {
f = item;
break;
}
}
QVERIFY(f.data());
const QString itemDisplay = tester.itemData(f).toString() + tester.itemData(f, KTextEditor:: CodeCompletionModel::Arguments).toString();
QCOMPARE(itemDisplay, QStringLiteral("f(int i, int j = 0, double k = 1)"));
}
void TestCodeCompletion::testCompleteFunction()
{
QFETCH(QString, code);
QFETCH(CompletionItems, expectedItems);
QFETCH(QString, itemToExecute);
QFETCH(QString, expectedCode);
auto executeItem = [=] (const ClangCodeCompletionItemTester& tester) {
auto item = tester.findItem(itemToExecute);
QVERIFY(item);
auto view = createView(tester.completionContext->duContext()->url().toUrl());
DUChainReadLocker lock;
item->execute(view.get(), view->document()->wordRangeAt(expectedItems.position));
QCOMPARE(view->document()->text(), expectedCode);
};
executeCompletionTest(code, expectedItems, NoMacroOrBuiltin, executeItem);
}
void TestCodeCompletion::testCompleteFunction_data()
{
QTest::addColumn<QString>("code");
QTest::addColumn<CompletionItems>("expectedItems");
QTest::addColumn<QString>("itemToExecute");
QTest::addColumn<QString>("expectedCode");
QTest::newRow("add-parens")
<< "int foo();\nint main() {\n\n}"
<< CompletionItems({2, 0}, {"foo", "main"})
<< "foo"
<< "int foo();\nint main() {\nfoo()\n}";
QTest::newRow("keep-parens")
<< "int foo();\nint main() {\nfoo();\n}"
<< CompletionItems({2, 0}, {"foo", "main"})
<< "main"
<< "int foo();\nint main() {\nmain();\n}";
QTest::newRow("bug375635")
<< "enum class Color {\nBlue, Green, Red, Yellow\n};\nvoid foo() {\nColor x;\nswitch (x) {\ncase : break;}\n}"
<< CompletionItems({6, 5}, {"Blue", "Green", "Red", "Yellow"})
<< "Yellow"
<< "enum class Color {\nBlue, Green, Red, Yellow\n};\nvoid foo() {\nColor x;\nswitch (x) {\ncase Color::Yellow: break;}\n}";
QTest::newRow("bug368544")
<< "class Klass {\npublic:\ntemplate <typename T>\nvoid func(int a, T x, int b) const;\n};\n"
<< CompletionItems({5, 0}, {"Klass", "Klass::func(int a, T x, int b) const"})
<< "Klass::func(int a, T x, int b) const"
<< "class Klass {\npublic:\ntemplate <typename T>\nvoid func(int a, T x, int b) const;\n};\ntemplate<typename T> void Klass::func(int a, T x, int b) const\n{\n}\n";
QTest::newRow("bug377397")
<< "template<typename T> class Foo {\nvoid bar();\n};\n"
<< CompletionItems({3, 0}, {"Foo", "Foo<T>::bar()"})
<< "Foo<T>::bar()"
<< "template<typename T> class Foo {\nvoid bar();\n};\ntemplate<typename T> void Foo<T>::bar()\n{\n}\n";
QTest::newRow("template-template-parameter")
<< "template <template<class, int> class X, typename B>\nclass Test {\npublic:\nvoid bar(B a);\n};\n"
<< CompletionItems({5, 0}, {"Test", "Test<X, B>::bar(B a)"})
<< "Test<X, B>::bar(B a)"
<< "template <template<class, int> class X, typename B>\nclass Test {\npublic:\nvoid bar(B a);\n};\ntemplate<template<typename, int> class X, typename B> void Test<X, B>::bar(B a)\n{\n}\n";
QTest::newRow("replace-leading-return-type")
<< "void foo(int x);\nvoid "
<< CompletionItems({1, 5}, {"foo(int x)"})
<< "foo(int x)"
<< "void foo(int x);\nvoid foo(int x)\n{\n}\n";
QTest::newRow("replace-leading-function-name")
<< "void foo(int x);\nfoo"
<< CompletionItems({1, 3}, {"foo(int x)"})
<< "foo(int x)"
<< "void foo(int x);\nvoid foo(int x)\n{\n}\n";
QTest::newRow("replace-leading-with-class-method")
<< "class Foo { int bar(int x); };\nint "
<< CompletionItems({1, 4}, {"Foo", "Foo::bar(int x)"})
<< "Foo::bar(int x)"
<< "class Foo { int bar(int x); };\nint Foo::bar(int x)\n{\n}\n";
QTest::newRow("replace-leading-whitespace-mismatch")
<< "class Foo { int** bar(int x); };\nint * *"
<< CompletionItems({1, 7}, {"** Foo::bar(int x)"})
<< "** Foo::bar(int x)"
<< "class Foo { int** bar(int x); };\nint ** Foo::bar(int x)\n{\n}\n";
}
void TestCodeCompletion::testIgnoreGccBuiltins()
{
// TODO: make it easier to change the compiler provider for testing purposes
QTemporaryDir dir;
auto project = new TestProject(Path(dir.path()), this);
auto definesAndIncludesConfig = project->projectConfiguration()->group("CustomDefinesAndIncludes");
auto pathConfig = definesAndIncludesConfig.group("ProjectPath0");
pathConfig.writeEntry("Path", ".");
pathConfig.group("Compiler").writeEntry("Name", "GCC");
m_projectController->addProject(project);
{
TestFile file(QString(), QStringLiteral("cpp"), project, dir.path());
QVERIFY(file.parseAndWait(TopDUContext::AllDeclarationsContextsUsesAndAST));
executeCompletionTest(file.topContext(), {});
}
}
|