1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986
|
//===- CRefactor.cpp - Refactoring API hooks ------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
//
// This file implements the Clang-C refactoring library.
//
//===----------------------------------------------------------------------===//
#include "CIndexDiagnostic.h"
#include "CIndexer.h"
#include "CLog.h"
#include "CXCursor.h"
#include "CXSourceLocation.h"
#include "CXString.h"
#include "CXTranslationUnit.h"
#include "clang-c/Refactor.h"
#include "clang/AST/ASTConsumer.h"
#include "clang/Basic/DiagnosticCategories.h"
#include "clang/Frontend/ASTUnit.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Frontend/CompilerInvocation.h"
#include "clang/Frontend/Utils.h"
#include "clang/Index/USRGeneration.h"
#include "clang/Tooling/CompilationDatabase.h"
#include "clang/Tooling/Refactor/IndexerQuery.h"
#include "clang/Tooling/Refactor/RefactoringActionFinder.h"
#include "clang/Tooling/Refactor/RefactoringActions.h"
#include "clang/Tooling/Refactor/RefactoringOperation.h"
#include "clang/Tooling/Refactor/RefactoringOptions.h"
#include "clang/Tooling/Refactor/RenameIndexedFile.h"
#include "clang/Tooling/Refactor/RenamingOperation.h"
#include "clang/Tooling/Refactor/SymbolOccurrenceFinder.h"
#include "clang/Tooling/Refactor/USRFinder.h"
#include "clang/Tooling/Tooling.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/StringMap.h"
#include <set>
#include <vector>
using namespace clang;
using namespace clang::tooling;
static RefactoringActionType
translateRefactoringActionType(CXRefactoringActionType Action) {
switch (Action) {
#define REFACTORING_ACTION(Name, Spelling) \
case CXRefactor_##Name: \
return RefactoringActionType::Name;
#include "clang/Tooling/Refactor/RefactoringActions.def"
}
llvm_unreachable("unknown CXRefactoringActionType value");
}
static CXRefactoringActionType
translateRefactoringActionType(RefactoringActionType Action) {
switch (Action) {
#define REFACTORING_ACTION(Name, Spelling) \
case RefactoringActionType::Name: \
return CXRefactor_##Name;
#include "clang/Tooling/Refactor/RefactoringActions.def"
}
llvm_unreachable("unknown RefactoringActionType value");
}
static CXSymbolOccurrenceKind
translateOccurrenceKind(rename::OldSymbolOccurrence::OccurrenceKind Kind) {
switch (Kind) {
case rename::OldSymbolOccurrence::MatchingSymbol:
return CXSymbolOccurrence_MatchingSymbol;
case rename::OldSymbolOccurrence::MatchingSelector:
return CXSymbolOccurrence_MatchingSelector;
case rename::OldSymbolOccurrence::MatchingImplicitProperty:
return CXSymbolOccurrence_MatchingImplicitProperty;
case rename::OldSymbolOccurrence::MatchingComment:
return CXSymbolOccurrence_MatchingCommentString;
case rename::OldSymbolOccurrence::MatchingDocComment:
return CXSymbolOccurrence_MatchingDocCommentString;
case rename::OldSymbolOccurrence::MatchingFilename:
return CXSymbolOccurrence_MatchingFilename;
case rename::OldSymbolOccurrence::MatchingStringLiteral:
return CXSymbolOccurrence_MatchingStringLiteral;
}
llvm_unreachable("unknown OccurrenceKind value");
}
namespace {
// TODO: Remove
class RenamingResult {
struct RenamedNameString {
CXString NewString;
unsigned OldLength;
};
typedef SmallVector<RenamedNameString, 4> SymbolNameInfo;
std::vector<SymbolNameInfo> NameInfo;
/// The set of files that have to be modified.
llvm::SmallVector<CXString, 2> Filenames;
llvm::SpecificBumpPtrAllocator<CXRefactoringReplacement_Old> Replacements;
std::vector<std::vector<CXRenamedSymbolOccurrence>> Occurrences;
void addOccurrence(const rename::OldSymbolOccurrence &RenamedOccurrence,
const SourceManager &SM, const LangOptions &LangOpts) {
CXRefactoringReplacement_Old *OccurrenceReplacements =
Replacements.Allocate(RenamedOccurrence.locations().size());
unsigned I = 0;
const auto &SymbolNameInfo = NameInfo[RenamedOccurrence.SymbolIndex];
if (!RenamedOccurrence.IsMacroExpansion &&
RenamedOccurrence.Kind !=
rename::OldSymbolOccurrence::MatchingComment &&
RenamedOccurrence.Kind !=
rename::OldSymbolOccurrence::MatchingDocComment)
assert(RenamedOccurrence.locations().size() == SymbolNameInfo.size());
for (const auto &Location : RenamedOccurrence.locations()) {
CXSourceRange Range = cxloc::translateSourceRange(
SM, LangOpts,
CharSourceRange::getCharRange(RenamedOccurrence.getLocationRange(
Location, SymbolNameInfo[I].OldLength)));
CXFileLocation Begin, End;
clang_getFileLocation(clang_getRangeStart(Range), nullptr, &Begin.Line,
&Begin.Column, nullptr);
clang_getFileLocation(clang_getRangeEnd(Range), nullptr, &End.Line,
&End.Column, nullptr);
OccurrenceReplacements[I] = CXRefactoringReplacement_Old{
{Begin, End},
RenamedOccurrence.IsMacroExpansion ? cxstring::createNull()
: SymbolNameInfo[I].NewString};
++I;
}
Occurrences.back().push_back(CXRenamedSymbolOccurrence{
OccurrenceReplacements, I,
translateOccurrenceKind(RenamedOccurrence.Kind),
RenamedOccurrence.IsMacroExpansion});
}
public:
RenamingResult(ArrayRef<SymbolName> NewNames,
ArrayRef<rename::Symbol> Symbols) {
assert(NewNames.size() == Symbols.size());
for (size_t I = 0, E = NewNames.size(); I != E; ++I) {
const auto &NewName = NewNames[I];
const auto &OldName = Symbols[I].Name;
assert(NewName.getNamePieces().size() == OldName.getNamePieces().size());
SymbolNameInfo Info;
for (size_t I = 0, E = NewName.getNamePieces().size(); I != E; ++I)
Info.push_back(
RenamedNameString{cxstring::createDup(NewName.getNamePieces()[I]),
(unsigned)OldName.getNamePieces()[I].size()});
NameInfo.push_back(std::move(Info));
}
}
// FIXME: Don't duplicate code, Use just one constructor.
RenamingResult(ArrayRef<SymbolName> NewNames, ArrayRef<SymbolName> OldNames) {
assert(NewNames.size() == OldNames.size());
for (size_t I = 0, E = NewNames.size(); I != E; ++I) {
const auto &NewName = NewNames[I];
const auto &OldName = OldNames[I];
assert(NewName.getNamePieces().size() == OldName.getNamePieces().size());
SymbolNameInfo Info;
for (size_t I = 0, E = NewName.getNamePieces().size(); I != E; ++I)
Info.push_back(
RenamedNameString{cxstring::createDup(NewName.getNamePieces()[I]),
(unsigned)OldName.getNamePieces()[I].size()});
NameInfo.push_back(std::move(Info));
}
}
~RenamingResult() {
for (const auto &SymbolInfo : NameInfo)
for (const auto &NameString : SymbolInfo)
clang_disposeString(NameString.NewString);
for (const auto &Filename : Filenames)
clang_disposeString(Filename);
}
void
handleTUResults(CXTranslationUnit TU,
llvm::MutableArrayRef<rename::OldSymbolOccurrence> Results) {
ASTUnit *Unit = cxtu::getASTUnit(TU);
assert(Unit && "Invalid TU");
auto &Ctx = Unit->getASTContext();
// Find the set of files that have to be modified and gather the indices of
// the occurrences for each file.
const SourceManager &SM = Ctx.getSourceManager();
typedef std::set<rename::OldSymbolOccurrence> OccurrenceSet;
llvm::StringMap<OccurrenceSet> FilenamesToSymbolOccurrences;
for (auto &Occurrence : Results) {
const std::pair<FileID, unsigned> DecomposedLocation =
SM.getDecomposedLoc(Occurrence.locations()[0]);
const FileEntry *Entry = SM.getFileEntryForID(DecomposedLocation.first);
assert(Entry && "Invalid file entry");
auto &FileOccurrences =
FilenamesToSymbolOccurrences
.try_emplace(Entry->getName(), OccurrenceSet())
.first->getValue();
FileOccurrences.insert(std::move(Occurrence));
}
// Create the filenames
for (const auto &FilenameCount : FilenamesToSymbolOccurrences)
Filenames.push_back(cxstring::createDup(FilenameCount.getKey()));
unsigned FileIndex = 0;
(void)FileIndex;
for (const auto &RenamedOccurrences : FilenamesToSymbolOccurrences) {
assert(clang_getCString(Filenames[FileIndex]) ==
RenamedOccurrences.getKey() &&
"Unstable iteration order");
Occurrences.push_back(std::vector<CXRenamedSymbolOccurrence>());
for (const auto &Occurrence : RenamedOccurrences.getValue())
addOccurrence(Occurrence, SM, Ctx.getLangOpts());
++FileIndex;
}
}
void addMainFilename(const SourceManager &SM) {
assert(Filenames.empty() && "Main filename should be added only once");
Filenames.push_back(cxstring::createDup(
SM.getFileEntryForID(SM.getMainFileID())->getName()));
Occurrences.push_back(std::vector<CXRenamedSymbolOccurrence>());
}
void
handleSingleFileTUResults(const ASTContext &Ctx,
ArrayRef<rename::OldSymbolOccurrence> Occurrences) {
addMainFilename(Ctx.getSourceManager());
for (const auto &Occurrence : Occurrences)
addOccurrence(Occurrence, Ctx.getSourceManager(), Ctx.getLangOpts());
}
void
handleIndexedFileOccurrence(const rename::OldSymbolOccurrence &Occurrence,
const SourceManager &SM,
const LangOptions &LangOpts) {
if (Filenames.empty()) {
addMainFilename(SM);
}
addOccurrence(Occurrence, SM, LangOpts);
}
ArrayRef<CXRenamedSymbolOccurrence> getOccurrences(unsigned FileIndex) const {
return Occurrences[FileIndex];
}
ArrayRef<CXString> getFilenames() const { return Filenames; }
};
class SymbolOccurrencesResult {
struct SymbolNamePiece {
unsigned OldLength;
};
typedef SmallVector<SymbolNamePiece, 4> SymbolNameInfo;
std::vector<SymbolNameInfo> NameInfo;
/// The set of files that have to be modified.
llvm::SmallVector<CXString, 2> Filenames;
llvm::SpecificBumpPtrAllocator<CXFileRange> Ranges;
std::vector<std::vector<CXSymbolOccurrence>> SymbolOccurrences;
void addOccurrence(const rename::OldSymbolOccurrence &RenamedOccurrence,
const SourceManager &SM, const LangOptions &LangOpts) {
ArrayRef<SourceLocation> Locations = RenamedOccurrence.locations();
CXFileRange *OccurrenceRanges = Ranges.Allocate(Locations.size());
unsigned I = 0;
const auto &SymbolNameInfo = NameInfo[RenamedOccurrence.SymbolIndex];
if (!RenamedOccurrence.IsMacroExpansion &&
RenamedOccurrence.Kind !=
rename::OldSymbolOccurrence::MatchingComment &&
RenamedOccurrence.Kind !=
rename::OldSymbolOccurrence::MatchingDocComment)
assert(Locations.size() == SymbolNameInfo.size());
for (const auto &Location : Locations) {
CXSourceRange Range = cxloc::translateSourceRange(
SM, LangOpts,
CharSourceRange::getCharRange(RenamedOccurrence.getLocationRange(
Location, SymbolNameInfo[I].OldLength)));
CXFileLocation Begin, End;
clang_getFileLocation(clang_getRangeStart(Range), nullptr, &Begin.Line,
&Begin.Column, nullptr);
clang_getFileLocation(clang_getRangeEnd(Range), nullptr, &End.Line,
&End.Column, nullptr);
OccurrenceRanges[I] = CXFileRange{Begin, End};
++I;
}
SymbolOccurrences.back().push_back(CXSymbolOccurrence{
OccurrenceRanges, /*NumNamePieces=*/I,
translateOccurrenceKind(RenamedOccurrence.Kind),
RenamedOccurrence.IsMacroExpansion, RenamedOccurrence.SymbolIndex});
}
public:
SymbolOccurrencesResult(ArrayRef<rename::Symbol> Symbols) {
for (const auto &Symbol : Symbols) {
const SymbolName &Name = Symbol.Name;
SymbolNameInfo Info;
for (size_t I = 0, E = Name.getNamePieces().size(); I != E; ++I)
Info.push_back(
SymbolNamePiece{(unsigned)Name.getNamePieces()[I].size()});
NameInfo.push_back(std::move(Info));
}
}
SymbolOccurrencesResult(ArrayRef<SymbolName> Names) {
for (const SymbolName &Name : Names) {
SymbolNameInfo Info;
for (size_t I = 0, E = Name.getNamePieces().size(); I != E; ++I)
Info.push_back(
SymbolNamePiece{(unsigned)Name.getNamePieces()[I].size()});
NameInfo.push_back(std::move(Info));
}
}
~SymbolOccurrencesResult() {
for (const auto &Filename : Filenames)
clang_disposeString(Filename);
}
void
handleTUResults(CXTranslationUnit TU,
llvm::MutableArrayRef<rename::OldSymbolOccurrence> Results) {
ASTUnit *Unit = cxtu::getASTUnit(TU);
assert(Unit && "Invalid TU");
auto &Ctx = Unit->getASTContext();
// Find the set of files that have to be modified and gather the indices of
// the occurrences for each file.
const SourceManager &SM = Ctx.getSourceManager();
typedef std::set<rename::OldSymbolOccurrence> OccurrenceSet;
llvm::StringMap<OccurrenceSet> FilenamesToSymbolOccurrences;
for (auto &Occurrence : Results) {
const std::pair<FileID, unsigned> DecomposedLocation =
SM.getDecomposedLoc(Occurrence.locations()[0]);
const FileEntry *Entry = SM.getFileEntryForID(DecomposedLocation.first);
assert(Entry && "Invalid file entry");
auto &FileOccurrences =
FilenamesToSymbolOccurrences
.try_emplace(Entry->getName(), OccurrenceSet())
.first->getValue();
FileOccurrences.insert(std::move(Occurrence));
}
// Create the filenames
for (const auto &FilenameCount : FilenamesToSymbolOccurrences)
Filenames.push_back(cxstring::createDup(FilenameCount.getKey()));
unsigned FileIndex = 0;
(void)FileIndex;
for (const auto &RenamedOccurrences : FilenamesToSymbolOccurrences) {
assert(clang_getCString(Filenames[FileIndex]) ==
RenamedOccurrences.getKey() &&
"Unstable iteration order");
SymbolOccurrences.push_back(std::vector<CXSymbolOccurrence>());
for (const auto &Occurrence : RenamedOccurrences.getValue())
addOccurrence(Occurrence, SM, Ctx.getLangOpts());
++FileIndex;
}
}
void addMainFilename(const SourceManager &SM) {
assert(Filenames.empty() && "Main filename should be added only once");
Filenames.push_back(cxstring::createDup(
SM.getFileEntryForID(SM.getMainFileID())->getName()));
SymbolOccurrences.push_back(std::vector<CXSymbolOccurrence>());
}
void
handleIndexedFileOccurrence(const rename::OldSymbolOccurrence &Occurrence,
const SourceManager &SM,
const LangOptions &LangOpts) {
if (Filenames.empty()) {
addMainFilename(SM);
}
addOccurrence(Occurrence, SM, LangOpts);
}
ArrayRef<CXSymbolOccurrence> getOccurrences(unsigned FileIndex) const {
return SymbolOccurrences[FileIndex];
}
ArrayRef<CXString> getFilenames() const { return Filenames; }
};
class RenamingAction {
public:
LangOptions LangOpts;
IdentifierTable IDs;
// TODO: Remove
SmallVector<SymbolName, 4> NewNames;
SymbolOperation Operation;
RenamingAction(const LangOptions &LangOpts, SymbolOperation Operation)
: LangOpts(LangOpts), IDs(LangOpts), Operation(std::move(Operation)) {}
/// \brief Sets the new renaming name and returns CXError_Success on success.
// TODO: Remove
CXErrorCode setNewName(StringRef Name) {
SymbolName NewSymbolName(Name, LangOpts);
if (NewSymbolName.getNamePieces().size() !=
Operation.symbols()[0].Name.getNamePieces().size())
return CXError_RefactoringNameSizeMismatch;
if (!rename::isNewNameValid(NewSymbolName, Operation, IDs, LangOpts))
return CXError_RefactoringNameInvalid;
rename::determineNewNames(std::move(NewSymbolName), Operation, NewNames,
LangOpts);
return CXError_Success;
}
// TODO: Remove
CXString usrForSymbolAt(unsigned Index) {
llvm::SmallVector<char, 128> Buff;
if (index::generateUSRForDecl(Operation.symbols()[Index].FoundDecl, Buff))
return cxstring::createNull();
return cxstring::createDup(StringRef(Buff.begin(), Buff.size()));
}
// TODO: Remove
CXString getUSRThatRequiresImplementationTU() {
llvm::SmallVector<char, 128> Buff;
if (!Operation.requiresImplementationTU() ||
index::generateUSRForDecl(Operation.declThatRequiresImplementationTU(),
Buff))
return cxstring::createNull();
return cxstring::createDup(StringRef(Buff.begin(), Buff.size()));
}
// TODO: Remove
RenamingResult *handlePrimaryTU(CXTranslationUnit TU, ASTUnit &Unit) {
// Perform the renaming.
if (NewNames.empty())
return nullptr;
const ASTContext &Context = Unit.getASTContext();
auto Occurrences = rename::findSymbolOccurrences(
Operation, Context.getTranslationUnitDecl());
auto *Result = new RenamingResult(NewNames, Operation.symbols());
Result->handleTUResults(TU, Occurrences);
return Result;
}
SymbolOccurrencesResult *findSymbolsInInitiationTU(CXTranslationUnit TU,
ASTUnit &Unit) {
const ASTContext &Context = Unit.getASTContext();
auto Occurrences = rename::findSymbolOccurrences(
Operation, Context.getTranslationUnitDecl());
auto *Result = new SymbolOccurrencesResult(Operation.symbols());
Result->handleTUResults(TU, Occurrences);
return Result;
}
};
static bool isObjCSelectorKind(CXCursorKind Kind) {
return Kind == CXCursor_ObjCInstanceMethodDecl ||
Kind == CXCursor_ObjCClassMethodDecl ||
Kind == CXCursor_ObjCMessageExpr;
}
// TODO: Remove
static bool isObjCSelector(const CXRenamedIndexedSymbol &Symbol) {
if (isObjCSelectorKind(Symbol.CursorKind))
return true;
for (const auto &Occurrence : ArrayRef(
Symbol.IndexedLocations, Symbol.IndexedLocationCount)) {
if (isObjCSelectorKind(Occurrence.CursorKind))
return true;
}
return false;
}
static bool isObjCSelector(const CXIndexedSymbol &Symbol) {
if (isObjCSelectorKind(Symbol.CursorKind))
return true;
for (const auto &Occurrence : ArrayRef(
Symbol.IndexedLocations, Symbol.IndexedLocationCount)) {
if (isObjCSelectorKind(Occurrence.CursorKind))
return true;
}
return false;
}
// New names are initialized and verified after the LangOptions are created.
CXErrorCode computeNewNames(ArrayRef<CXRenamedIndexedSymbol> Symbols,
ArrayRef<SymbolName> SymbolNames,
const LangOptions &LangOpts,
SmallVectorImpl<SymbolName> &NewNames) {
IdentifierTable IDs(LangOpts);
for (const auto &Symbol : Symbols) {
SymbolName NewSymbolName(Symbol.NewName, LangOpts);
if (NewSymbolName.getNamePieces().size() !=
SymbolNames[0].getNamePieces().size())
return CXError_RefactoringNameSizeMismatch;
if (!rename::isNewNameValid(NewSymbolName, isObjCSelector(Symbol), IDs,
LangOpts))
return CXError_RefactoringNameInvalid;
NewNames.push_back(std::move(NewSymbolName));
}
return CXError_Success;
}
static rename::IndexedOccurrence::OccurrenceKind
translateIndexedOccurrenceKind(CXCursorKind Kind) {
switch (Kind) {
case CXCursor_ObjCMessageExpr:
return rename::IndexedOccurrence::IndexedObjCMessageSend;
case CXCursor_InclusionDirective:
return rename::IndexedOccurrence::InclusionDirective;
default:
return rename::IndexedOccurrence::IndexedSymbol;
}
}
/// ClangTool::run is not thread-safe, so we have to guard it.
static llvm::ManagedStatic<llvm::sys::Mutex> ClangToolConstructionMutex;
// TODO: Remove
CXErrorCode performIndexedFileRename(
ArrayRef<CXRenamedIndexedSymbol> Symbols, StringRef Filename,
ArrayRef<const char *> Arguments, CXIndex CIdx,
MutableArrayRef<CXUnsavedFile> UnsavedFiles,
const RefactoringOptionSet *Options, CXRenamingResult &Result) {
Result = nullptr;
// Adjust the given command line arguments to ensure that any positional
// arguments in them are stripped.
std::vector<const char *> ClangToolArguments;
ClangToolArguments.push_back("--");
for (const auto &Arg : Arguments) {
// Remove the '-gmodules' option, as the -fmodules-format=obj isn't
// supported without the linked object reader.
if (StringRef(Arg) == "-gmodules")
continue;
ClangToolArguments.push_back(Arg);
}
int Argc = ClangToolArguments.size();
std::string ErrorMessage;
std::unique_ptr<CompilationDatabase> Compilations =
FixedCompilationDatabase::loadFromCommandLine(
Argc, ClangToolArguments.data(), ErrorMessage);
if (!Compilations) {
llvm::errs() << "CRefactor: Failed to load command line: " << ErrorMessage
<< "\n";
return CXError_Failure;
}
// Translate the symbols.
llvm::SmallVector<rename::IndexedSymbol, 4> IndexedSymbols;
for (const auto &Symbol : Symbols) {
// Parse the symbol name.
bool IsObjCSelector = false;
// Selectors have to be parsed.
if (isObjCSelector(Symbol))
IsObjCSelector = true;
// Ensure that we don't get selectors with incorrect symbol kind.
else if (StringRef(Symbol.Name).contains(':'))
return CXError_InvalidArguments;
std::vector<rename::IndexedOccurrence> IndexedOccurrences;
for (const auto &Loc : ArrayRef(Symbol.IndexedLocations,
Symbol.IndexedLocationCount)) {
rename::IndexedOccurrence Result;
Result.Line = Loc.Location.Line;
Result.Column = Loc.Location.Column;
Result.Kind = translateIndexedOccurrenceKind(Loc.CursorKind);
IndexedOccurrences.push_back(Result);
}
IndexedSymbols.emplace_back(SymbolName(Symbol.Name, IsObjCSelector),
IndexedOccurrences,
/*IsObjCSelector=*/IsObjCSelector);
}
class ToolRunner final : public FrontendActionFactory,
public rename::IndexedFileOccurrenceConsumer {
ArrayRef<CXRenamedIndexedSymbol> Symbols;
ArrayRef<rename::IndexedSymbol> IndexedSymbols;
rename::IndexedFileRenamerLock &Lock;
const RefactoringOptionSet *Options;
public:
RenamingResult *Result;
CXErrorCode Err;
ToolRunner(ArrayRef<CXRenamedIndexedSymbol> Symbols,
ArrayRef<rename::IndexedSymbol> IndexedSymbols,
rename::IndexedFileRenamerLock &Lock,
const RefactoringOptionSet *Options)
: Symbols(Symbols), IndexedSymbols(IndexedSymbols), Lock(Lock),
Options(Options), Result(nullptr), Err(CXError_Success) {}
std::unique_ptr<FrontendAction> create() override {
return std::unique_ptr<FrontendAction>(
new rename::IndexedFileOccurrenceProducer(IndexedSymbols, *this, Lock,
Options));
}
void handleOccurrence(const rename::OldSymbolOccurrence &Occurrence,
SourceManager &SM,
const LangOptions &LangOpts) override {
if (Err != CXError_Success)
return;
if (!Result) {
SmallVector<SymbolName, 4> SymbolNames;
for (const auto &Symbol : IndexedSymbols)
SymbolNames.push_back(Symbol.Name);
SmallVector<SymbolName, 4> NewNames;
Err = computeNewNames(Symbols, SymbolNames, LangOpts, NewNames);
if (Err != CXError_Success)
return;
Result = new RenamingResult(NewNames, SymbolNames);
}
Result->handleIndexedFileOccurrence(Occurrence, SM, LangOpts);
}
};
rename::IndexedFileRenamerLock Lock(*ClangToolConstructionMutex);
auto Runner =
std::make_unique<ToolRunner>(Symbols, IndexedSymbols, Lock, Options);
// Run a clang tool on the input file.
std::string Name = Filename.str();
ClangTool Tool(*Compilations, Name);
Tool.run(Runner.get());
if (Runner->Err != CXError_Success)
return Runner->Err;
Result = Runner->Result;
return CXError_Success;
}
CXErrorCode performIndexedSymbolSearch(
ArrayRef<CXIndexedSymbol> Symbols, StringRef Filename,
ArrayRef<const char *> Arguments, CXIndex CIdx,
MutableArrayRef<CXUnsavedFile> UnsavedFiles,
const RefactoringOptionSet *Options, CXSymbolOccurrencesResult &Result) {
Result = nullptr;
// Adjust the given command line arguments to ensure that any positional
// arguments in them are stripped.
std::vector<const char *> ClangToolArguments;
ClangToolArguments.push_back("--");
for (const auto &Arg : Arguments) {
// Remove the '-gmodules' option, as the -fmodules-format=obj isn't
// supported without the linked object reader.
if (StringRef(Arg) == "-gmodules")
continue;
ClangToolArguments.push_back(Arg);
}
int Argc = ClangToolArguments.size();
std::string ErrorMessage;
std::unique_ptr<CompilationDatabase> Compilations =
FixedCompilationDatabase::loadFromCommandLine(
Argc, ClangToolArguments.data(), ErrorMessage);
if (!Compilations) {
llvm::errs() << "CRefactor: Failed to load command line: " << ErrorMessage
<< "\n";
return CXError_Failure;
}
// Translate the symbols.
llvm::SmallVector<rename::IndexedSymbol, 4> IndexedSymbols;
for (const auto &Symbol : Symbols) {
// Parse the symbol name.
bool IsObjCSelector = false;
// Selectors have to be parsed.
if (isObjCSelector(Symbol))
IsObjCSelector = true;
// Ensure that we don't get selectors with incorrect symbol kind.
else if (StringRef(Symbol.Name).contains(':'))
return CXError_InvalidArguments;
std::vector<rename::IndexedOccurrence> IndexedOccurrences;
for (const auto &Loc : ArrayRef(Symbol.IndexedLocations,
Symbol.IndexedLocationCount)) {
rename::IndexedOccurrence Result;
Result.Line = Loc.Location.Line;
Result.Column = Loc.Location.Column;
Result.Kind = translateIndexedOccurrenceKind(Loc.CursorKind);
IndexedOccurrences.push_back(Result);
}
IndexedSymbols.emplace_back(
SymbolName(Symbol.Name, IsObjCSelector), IndexedOccurrences,
/*IsObjCSelector=*/IsObjCSelector,
/*SearchForStringLiteralOccurrences=*/
Symbol.CursorKind == CXCursor_ObjCInterfaceDecl);
}
class ToolRunner final : public FrontendActionFactory,
public rename::IndexedFileOccurrenceConsumer {
ArrayRef<rename::IndexedSymbol> IndexedSymbols;
rename::IndexedFileRenamerLock &Lock;
const RefactoringOptionSet *Options;
public:
SymbolOccurrencesResult *Result;
ToolRunner(ArrayRef<rename::IndexedSymbol> IndexedSymbols,
rename::IndexedFileRenamerLock &Lock,
const RefactoringOptionSet *Options)
: IndexedSymbols(IndexedSymbols), Lock(Lock), Options(Options),
Result(nullptr) {}
std::unique_ptr<clang::FrontendAction> create() override {
return std::unique_ptr<clang::FrontendAction>(
new rename::IndexedFileOccurrenceProducer(IndexedSymbols, *this, Lock,
Options));
}
void handleOccurrence(const rename::OldSymbolOccurrence &Occurrence,
SourceManager &SM,
const LangOptions &LangOpts) override {
if (!Result) {
SmallVector<SymbolName, 4> SymbolNames;
for (const auto &Symbol : IndexedSymbols)
SymbolNames.push_back(Symbol.Name);
Result = new SymbolOccurrencesResult(SymbolNames);
}
Result->handleIndexedFileOccurrence(Occurrence, SM, LangOpts);
}
};
rename::IndexedFileRenamerLock Lock(*ClangToolConstructionMutex);
auto Runner = std::make_unique<ToolRunner>(IndexedSymbols, Lock, Options);
// Run a clang tool on the input file.
std::string Name = Filename.str();
ClangTool Tool(*Compilations, Name);
for (const CXUnsavedFile &File : UnsavedFiles)
Tool.mapVirtualFile(File.Filename, StringRef(File.Contents, File.Length));
if (Tool.run(Runner.get()))
return CXError_Failure;
Result = Runner->Result;
return CXError_Success;
}
class RefactoringAction {
std::unique_ptr<RefactoringOperation> Operation;
std::unique_ptr<RenamingAction> Rename;
SmallVector<CXRefactoringCandidate, 2> RefactoringCandidates;
CXRefactoringCandidateSet CandidateSet = {nullptr, 0};
bool HasCandidateSet = false;
public:
CXRefactoringActionType Type;
unsigned SelectedCandidate = 0;
CXTranslationUnit InitiationTU;
// TODO: Remove (no longer needed due to continuations).
CXTranslationUnit ImplementationTU;
RefactoringAction(std::unique_ptr<RefactoringOperation> Operation,
CXRefactoringActionType Type,
CXTranslationUnit InitiationTU)
: Operation(std::move(Operation)), Type(Type), InitiationTU(InitiationTU),
ImplementationTU(nullptr) {}
RefactoringAction(std::unique_ptr<RenamingAction> Rename,
CXTranslationUnit InitiationTU)
: Rename(std::move(Rename)),
Type(this->Rename->Operation.isLocal() ? CXRefactor_Rename_Local
: CXRefactor_Rename),
InitiationTU(InitiationTU), ImplementationTU(nullptr) {}
~RefactoringAction() {
for (const auto &Candidate : RefactoringCandidates)
clang_disposeString(Candidate.Description);
}
RefactoringOperation *getOperation() const { return Operation.get(); }
RenamingAction *getRenamingAction() const { return Rename.get(); }
CXRefactoringCandidateSet getRefactoringCandidates() {
if (HasCandidateSet)
return CandidateSet;
HasCandidateSet = true;
RefactoringOperation *Operation = getOperation();
if (!Operation)
return CandidateSet;
auto Candidates = Operation->getRefactoringCandidates();
if (Candidates.empty())
return CandidateSet;
for (const auto &Candidate : Candidates)
RefactoringCandidates.push_back({cxstring::createDup(Candidate)});
CandidateSet = {RefactoringCandidates.data(),
(unsigned)RefactoringCandidates.size()};
return CandidateSet;
}
CXErrorCode selectCandidate(unsigned Index) {
RefactoringOperation *Operation = getOperation();
if (!Operation)
return CXError_InvalidArguments;
if (Index != 0 && Index >= getRefactoringCandidates().NumCandidates)
return CXError_InvalidArguments;
SelectedCandidate = Index;
return CXError_Success;
}
};
static bool operator==(const CXFileLocation &LHS, const CXFileLocation &RHS) {
return LHS.Line == RHS.Line && LHS.Column == RHS.Column;
}
static CXFileRange translateOffsetToRelativeRange(unsigned Offset,
unsigned Size,
StringRef Source) {
assert(Source.drop_front(Offset).take_front(Size).count('\n') == 0 &&
"Newlines in translated range?");
StringRef Prefix = Source.take_front(Offset);
unsigned StartLines = Prefix.count('\n') + 1;
if (StartLines > 1)
Offset -= Prefix.rfind('\n') + 1;
return CXFileRange{{StartLines, Offset + 1}, {StartLines, Offset + 1 + Size}};
}
class RefactoringResultWrapper {
public:
CXRefactoringReplacements_Old Replacements; // TODO: Remove.
CXRefactoringReplacements SourceReplacements;
std::unique_ptr<RefactoringContinuation> Continuation;
llvm::BumpPtrAllocator Allocator;
CXTranslationUnit TU;
struct AssociatedReplacementInfo {
CXSymbolOccurrence *AssociatedSymbolOccurrences;
unsigned NumAssociatedSymbolOccurrences;
};
~RefactoringResultWrapper() {
// TODO: Remove.
for (unsigned I = 0; I < Replacements.NumFileReplacementSets; ++I) {
const CXRefactoringFileReplacementSet_Old &FileSet =
Replacements.FileReplacementSets[I];
clang_disposeString(FileSet.Filename);
for (unsigned J = 0; J < FileSet.NumReplacements; ++J)
clang_disposeString(FileSet.Replacements[J].ReplacementString);
delete[] FileSet.Replacements;
}
delete[] Replacements.FileReplacementSets;
for (unsigned I = 0; I < SourceReplacements.NumFileReplacementSets; ++I) {
const CXRefactoringFileReplacementSet &FileSet =
SourceReplacements.FileReplacementSets[I];
clang_disposeString(FileSet.Filename);
for (unsigned J = 0; J < FileSet.NumReplacements; ++J)
clang_disposeString(FileSet.Replacements[J].ReplacementString);
}
}
RefactoringResultWrapper(
ArrayRef<RefactoringReplacement> Replacements,
ArrayRef<std::unique_ptr<RefactoringResultAssociatedSymbol>>
AssociatedSymbols,
std::unique_ptr<RefactoringContinuation> Continuation,
ASTContext &Context, CXTranslationUnit TU)
: Continuation(std::move(Continuation)), TU(TU) {
SourceManager &SM = Context.getSourceManager();
if (Replacements.empty()) {
assert(AssociatedSymbols.empty() && "Symbols without replacements??");
// TODO: Remove begin
this->Replacements.NumFileReplacementSets = 0;
this->Replacements.FileReplacementSets = nullptr;
// Remove end
this->SourceReplacements.NumFileReplacementSets = 0;
this->SourceReplacements.FileReplacementSets = nullptr;
return;
}
llvm::SmallDenseMap<const RefactoringResultAssociatedSymbol *, unsigned>
AssociatedSymbolToIndex;
for (const auto &Symbol : llvm::enumerate(AssociatedSymbols))
AssociatedSymbolToIndex[Symbol.value().get()] = Symbol.index();
// Find the set of files that have to be modified and gather the indices of
// the occurrences for each file.
llvm::DenseMap<const FileEntry *, std::vector<unsigned>>
FilesToReplacements;
for (const auto &Replacement : llvm::enumerate(Replacements)) {
SourceLocation Loc = Replacement.value().Range.getBegin();
const std::pair<FileID, unsigned> DecomposedLocation =
SM.getDecomposedLoc(Loc);
assert(DecomposedLocation.first.isValid() && "Invalid file!");
const FileEntry *Entry = SM.getFileEntryForID(DecomposedLocation.first);
FilesToReplacements.try_emplace(Entry, std::vector<unsigned>())
.first->second.push_back(Replacement.index());
}
// TODO: Remove
unsigned NumFiles = FilesToReplacements.size();
auto *FileReplacementSets =
new CXRefactoringFileReplacementSet_Old[NumFiles];
unsigned FileIndex = 0;
for (const auto &Entry : FilesToReplacements) {
CXRefactoringFileReplacementSet_Old &FileSet =
FileReplacementSets[FileIndex];
++FileIndex;
ArrayRef<unsigned> ReplacementIndices = Entry.second;
FileSet.Filename = cxstring::createDup(Entry.first->getName());
FileSet.NumReplacements = ReplacementIndices.size();
auto *FileReplacements =
new CXRefactoringReplacement_Old[ReplacementIndices.size()];
FileSet.Replacements = FileReplacements;
unsigned NumRemoved = 0;
for (unsigned I = 0; I < FileSet.NumReplacements; ++I) {
const RefactoringReplacement &RefReplacement =
Replacements[ReplacementIndices[I]];
CXSourceRange Range = cxloc::translateSourceRange(
SM, Context.getLangOpts(),
CharSourceRange::getCharRange(RefReplacement.Range.getBegin(),
RefReplacement.Range.getEnd()));
CXFileLocation Begin, End;
clang_getFileLocation(clang_getRangeStart(Range), nullptr, &Begin.Line,
&Begin.Column, nullptr);
clang_getFileLocation(clang_getRangeEnd(Range), nullptr, &End.Line,
&End.Column, nullptr);
if (I && FileReplacements[I - NumRemoved - 1].Range.End == Begin) {
// Merge the previous and the current replacement.
FileReplacements[I - NumRemoved - 1].Range.End = End;
std::string Replacement =
std::string(clang_getCString(
FileReplacements[I - NumRemoved - 1].ReplacementString)) +
RefReplacement.ReplacementString;
clang_disposeString(
FileReplacements[I - NumRemoved - 1].ReplacementString);
FileReplacements[I - NumRemoved - 1].ReplacementString =
cxstring::createDup(Replacement);
NumRemoved++;
continue;
}
CXRefactoringReplacement_Old &Replacement =
FileReplacements[I - NumRemoved];
Replacement.ReplacementString =
cxstring::createDup(RefReplacement.ReplacementString);
Replacement.Range.Begin = Begin;
Replacement.Range.End = End;
}
FileSet.NumReplacements -= NumRemoved;
}
this->Replacements.FileReplacementSets = FileReplacementSets;
this->Replacements.NumFileReplacementSets = NumFiles;
// TODO: Outdent.
{
unsigned NumFiles = FilesToReplacements.size();
auto *FileReplacementSets =
Allocator.Allocate<CXRefactoringFileReplacementSet>(NumFiles);
SourceReplacements.FileReplacementSets = FileReplacementSets;
SourceReplacements.NumFileReplacementSets = NumFiles;
unsigned FileIndex = 0;
for (const auto &Entry : FilesToReplacements) {
CXRefactoringFileReplacementSet &FileSet =
FileReplacementSets[FileIndex];
++FileIndex;
ArrayRef<unsigned> ReplacementIndices = Entry.second;
FileSet.Filename = cxstring::createDup(Entry.first->getName());
FileSet.NumReplacements = ReplacementIndices.size();
auto *FileReplacements = Allocator.Allocate<CXRefactoringReplacement>(
ReplacementIndices.size());
FileSet.Replacements = FileReplacements;
unsigned NumRemoved = 0;
for (unsigned I = 0; I < FileSet.NumReplacements; ++I) {
const RefactoringReplacement &RefReplacement =
Replacements[ReplacementIndices[I]];
CXSourceRange Range = cxloc::translateSourceRange(
SM, Context.getLangOpts(),
CharSourceRange::getCharRange(RefReplacement.Range.getBegin(),
RefReplacement.Range.getEnd()));
CXFileLocation Begin, End;
clang_getFileLocation(clang_getRangeStart(Range), nullptr,
&Begin.Line, &Begin.Column, nullptr);
clang_getFileLocation(clang_getRangeEnd(Range), nullptr, &End.Line,
&End.Column, nullptr);
if (I && FileReplacements[I - NumRemoved - 1].Range.End == Begin) {
// Merge the previous and the current replacement.
FileReplacements[I - NumRemoved - 1].Range.End = End;
std::string Replacement =
std::string(clang_getCString(
FileReplacements[I - NumRemoved - 1].ReplacementString)) +
RefReplacement.ReplacementString;
clang_disposeString(
FileReplacements[I - NumRemoved - 1].ReplacementString);
FileReplacements[I - NumRemoved - 1].ReplacementString =
cxstring::createDup(Replacement);
NumRemoved++;
continue;
}
CXRefactoringReplacement &Replacement =
FileReplacements[I - NumRemoved];
Replacement.ReplacementString =
cxstring::createDup(RefReplacement.ReplacementString);
Replacement.Range.Begin = Begin;
Replacement.Range.End = End;
unsigned NumAssociatedSymbols = RefReplacement.SymbolLocations.size();
if (!NumAssociatedSymbols) {
Replacement.AssociatedData = nullptr;
continue;
}
AssociatedReplacementInfo *AssociatedData =
Allocator.Allocate<AssociatedReplacementInfo>();
Replacement.AssociatedData = AssociatedData;
AssociatedData->AssociatedSymbolOccurrences =
Allocator.Allocate<CXSymbolOccurrence>(NumAssociatedSymbols);
AssociatedData->NumAssociatedSymbolOccurrences = NumAssociatedSymbols;
unsigned SymbolIndex = 0;
for (const auto &AssociatedSymbol : RefReplacement.SymbolLocations) {
unsigned Index = AssociatedSymbolToIndex[AssociatedSymbol.first];
const RefactoringReplacement::AssociatedSymbolLocation &Loc =
AssociatedSymbol.second;
CXFileRange *NamePieces =
Allocator.Allocate<CXFileRange>(Loc.Offsets.size());
assert(AssociatedSymbol.first->getName().getNamePieces().size() ==
Loc.Offsets.size() &&
"mismatching symbol name and offsets");
for (const auto &Offset : llvm::enumerate(Loc.Offsets)) {
StringRef NamePiece = AssociatedSymbol.first->getName()
.getNamePieces()[Offset.index()];
NamePieces[Offset.index()] = translateOffsetToRelativeRange(
Offset.value(), NamePiece.size(),
RefReplacement.ReplacementString);
}
AssociatedData->AssociatedSymbolOccurrences[SymbolIndex] =
CXSymbolOccurrence{
NamePieces, (unsigned)Loc.Offsets.size(),
Loc.IsDeclaration
? CXSymbolOccurrence_ExtractedDeclaration
: CXSymbolOccurrence_ExtractedDeclaration_Reference,
/*IsMacroExpansion=*/0, Index};
++SymbolIndex;
}
}
FileSet.NumReplacements -= NumRemoved;
}
}
}
};
class RefactoringContinuationWrapper {
public:
std::unique_ptr<RefactoringContinuation> Continuation;
struct QueryWrapper {
indexer::IndexerQuery *Query;
CXTranslationUnit TU;
std::vector<indexer::Indexed<PersistentDeclRef<Decl>>> DeclResults;
unsigned ConsumedResults = 0;
QueryWrapper(indexer::IndexerQuery *Query, CXTranslationUnit TU)
: Query(Query), TU(TU) {}
};
SmallVector<QueryWrapper, 4> Queries;
bool IsInitiationTUAbandoned = false;
RefactoringContinuationWrapper(
std::unique_ptr<RefactoringContinuation> Continuation,
CXTranslationUnit TU)
: Continuation(std::move(Continuation)) {
Queries.emplace_back(this->Continuation->getASTUnitIndexerQuery(), TU);
assert(Queries.back().Query && "Invalid ast query");
std::vector<indexer::IndexerQuery *> AdditionalQueries =
this->Continuation->getAdditionalIndexerQueries();
for (indexer::IndexerQuery *IQ : AdditionalQueries)
Queries.emplace_back(IQ, TU);
}
};
class RefactoringDiagnosticConsumer : public DiagnosticConsumer {
const ASTContext &Context;
DiagnosticConsumer *PreviousClient;
std::unique_ptr<DiagnosticConsumer> PreviousClientPtr;
llvm::SmallVector<StoredDiagnostic, 2> RenameDiagnostics;
llvm::SmallVector<StoredDiagnostic, 1> ContinuationDiagnostics;
public:
RefactoringDiagnosticConsumer(ASTContext &Context) : Context(Context) {
PreviousClient = Context.getDiagnostics().getClient();
PreviousClientPtr = Context.getDiagnostics().takeClient();
Context.getDiagnostics().setClient(this, /*ShouldOwnClient=*/false);
}
~RefactoringDiagnosticConsumer() {
if (PreviousClientPtr)
Context.getDiagnostics().setClient(PreviousClientPtr.release());
else
Context.getDiagnostics().setClient(PreviousClient,
/*ShouldOwnClient=*/false);
}
void HandleDiagnostic(DiagnosticsEngine::Level Level,
const Diagnostic &Info) override {
unsigned Cat = DiagnosticIDs::getCategoryNumberForDiag(Info.getID());
if (Cat == diag::DiagCat_Rename_Issue)
RenameDiagnostics.push_back(StoredDiagnostic(Level, Info));
else if (Cat == diag::DiagCat_Refactoring_Continuation_Issue)
ContinuationDiagnostics.push_back(StoredDiagnostic(Level, Info));
else
assert(false && "Unhandled refactoring category");
}
CXDiagnosticSetImpl *createDiags() const {
if (RenameDiagnostics.empty() && ContinuationDiagnostics.empty())
return nullptr;
llvm::SmallVector<StoredDiagnostic, 2> AllDiagnostics;
for (const auto &D : RenameDiagnostics)
AllDiagnostics.push_back(D);
for (const auto &D : ContinuationDiagnostics)
AllDiagnostics.push_back(D);
return cxdiag::createStoredDiags(AllDiagnostics, Context.getLangOpts());
}
CXRefactoringActionSetWithDiagnostics createActionSet() const {
if (RenameDiagnostics.empty())
return {nullptr, 0};
CXRefactoringActionWithDiagnostics *Actions =
new CXRefactoringActionWithDiagnostics[1];
Actions[0].Action = CXRefactor_Rename;
Actions[0].Diagnostics =
cxdiag::createStoredDiags(RenameDiagnostics, Context.getLangOpts());
return {Actions, 1};
}
};
} // end anonymous namespace
template <typename T>
static T withRenamingAction(CXRefactoringAction Action, T DefaultValue,
llvm::function_ref<T(RenamingAction &)> Callback) {
if (!Action)
return DefaultValue;
RenamingAction *Rename =
static_cast<RefactoringAction *>(Action)->getRenamingAction();
if (!Rename)
return DefaultValue;
return Callback(*Rename);
}
static enum CXIndexerQueryKind
translateDeclPredicate(const indexer::DeclPredicate &Predicate) {
indexer::DeclEntity Entity;
if (Predicate == Entity.isDefined().Predicate)
return CXIndexerQuery_Decl_IsDefined;
return CXIndexerQuery_Unknown;
}
extern "C" {
CXString
clang_RefactoringActionType_getName(enum CXRefactoringActionType Action) {
return cxstring::createRef(
getRefactoringActionTypeName(translateRefactoringActionType(Action)));
}
void clang_RefactoringActionSet_dispose(CXRefactoringActionSet *Set) {
if (Set && Set->Actions)
delete[] Set->Actions;
}
void clang_RefactoringActionSetWithDiagnostics_dispose(
CXRefactoringActionSetWithDiagnostics *Set) {
if (Set && Set->Actions) {
for (auto &S : ArrayRef(Set->Actions, Set->NumActions))
clang_disposeDiagnosticSet(S.Diagnostics);
delete[] Set->Actions;
}
}
CXRefactoringOptionSet clang_RefactoringOptionSet_create() {
return new RefactoringOptionSet;
}
CXRefactoringOptionSet
clang_RefactoringOptionSet_createFromString(const char *String) {
RefactoringOptionSet *Result = new RefactoringOptionSet;
auto Options = RefactoringOptionSet::parse(String);
if (Options) {
*Result = std::move(*Options);
return Result;
}
llvm::handleAllErrors(Options.takeError(),
[](const llvm::StringError &Error) {});
return clang_RefactoringOptionSet_create();
}
void clang_RefactoringOptionSet_add(CXRefactoringOptionSet Set,
enum CXRefactoringOption Option) {
if (!Set)
return;
switch (Option) {
case CXRefactorOption_AvoidTextualMatches:
static_cast<RefactoringOptionSet *>(Set)->add(
option::AvoidTextualMatches::getTrue());
break;
}
}
CXString clang_RefactoringOptionSet_toString(CXRefactoringOptionSet Set) {
if (!Set)
return cxstring::createNull();
std::string Result;
llvm::raw_string_ostream OS(Result);
static_cast<RefactoringOptionSet *>(Set)->print(OS);
return cxstring::createDup(OS.str());
}
void clang_RefactoringOptionSet_dispose(CXRefactoringOptionSet Set) {
if (Set)
delete static_cast<RefactoringOptionSet *>(Set);
}
enum CXErrorCode
clang_Refactoring_findActionsAt(CXTranslationUnit TU, CXSourceLocation Location,
CXSourceRange SelectionRange,
CXRefactoringOptionSet Options,
CXRefactoringActionSet *OutSet) {
return clang_Refactoring_findActionsWithInitiationFailureDiagnosicsAt(
TU, Location, SelectionRange, Options, OutSet, /*OutFailureSet=*/nullptr);
}
enum CXErrorCode clang_Refactoring_findActionsWithInitiationFailureDiagnosicsAt(
CXTranslationUnit TU, CXSourceLocation Location,
CXSourceRange SelectionRange, CXRefactoringOptionSet Options,
CXRefactoringActionSet *OutSet,
CXRefactoringActionSetWithDiagnostics *OutFailureSet) {
LOG_FUNC_SECTION { *Log << TU << ' '; }
if (OutFailureSet) {
OutFailureSet->Actions = nullptr;
OutFailureSet->NumActions = 0;
}
if (!OutSet)
return CXError_InvalidArguments;
OutSet->Actions = nullptr;
OutSet->NumActions = 0;
if (cxtu::isNotUsableTU(TU)) {
LOG_BAD_TU(TU);
return CXError_InvalidArguments;
}
ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
if (!CXXUnit)
return CXError_InvalidArguments;
SourceLocation Loc = cxloc::translateSourceLocation(Location);
if (Loc.isInvalid())
return CXError_InvalidArguments;
ASTUnit::ConcurrencyCheck Check(*CXXUnit);
(void)Options; // FIXME: handle options
ASTContext &Context = CXXUnit->getASTContext();
RefactoringDiagnosticConsumer DiagConsumer(Context);
RefactoringActionSet ActionSet = findActionSetAt(
Loc, cxloc::translateCXSourceRange(SelectionRange), Context);
if (OutFailureSet)
*OutFailureSet = DiagConsumer.createActionSet();
if (ActionSet.Actions.empty())
return CXError_RefactoringActionUnavailable;
CXRefactoringActionType *Actions =
new CXRefactoringActionType[ActionSet.Actions.size()];
OutSet->Actions = Actions;
OutSet->NumActions = ActionSet.Actions.size();
for (const auto &Action : llvm::enumerate(ActionSet.Actions))
Actions[Action.index()] = translateRefactoringActionType(Action.value());
return CXError_Success;
}
void clang_RefactoringAction_dispose(CXRefactoringAction Action) {
if (Action)
delete static_cast<RefactoringAction *>(Action);
}
CXSourceRange
clang_RefactoringAction_getSourceRangeOfInterest(CXRefactoringAction Action) {
if (Action) {
RefactoringOperation *Operation =
static_cast<RefactoringAction *>(Action)->getOperation();
if (Operation) {
ASTUnit *CXXUnit = cxtu::getASTUnit(
static_cast<RefactoringAction *>(Action)->InitiationTU);
if (const Stmt *S = Operation->getTransformedStmt()) {
SourceRange Range = S->getSourceRange();
if (const Stmt *Last = Operation->getLastTransformedStmt())
Range.setEnd(Last->getEndLoc());
return cxloc::translateSourceRange(CXXUnit->getASTContext(), Range);
} else if (const Decl *D = Operation->getTransformedDecl()) {
SourceRange Range = D->getSourceRange();
if (const Decl *Last = Operation->getLastTransformedDecl())
Range.setEnd(Last->getEndLoc());
return cxloc::translateSourceRange(CXXUnit->getASTContext(), Range);
}
}
}
return clang_getNullRange();
}
int clang_RefactoringAction_requiresImplementationTU(
CXRefactoringAction Action) {
return withRenamingAction<int>(Action, 0, [](RenamingAction &Action) {
return Action.Operation.requiresImplementationTU();
});
}
CXString clang_RefactoringAction_getUSRThatRequiresImplementationTU(
CXRefactoringAction Action) {
return withRenamingAction<CXString>(
Action, cxstring::createNull(), [](RenamingAction &Action) {
return Action.getUSRThatRequiresImplementationTU();
});
}
enum CXErrorCode
clang_RefactoringAction_addImplementationTU(CXRefactoringAction Action,
CXTranslationUnit TU) {
if (!Action || !TU)
return CXError_InvalidArguments;
// Prohibit multiple additions of implementation TU.
if (static_cast<RefactoringAction *>(Action)->ImplementationTU)
return CXError_Failure;
static_cast<RefactoringAction *>(Action)->ImplementationTU = TU;
return CXError_Success;
}
enum CXErrorCode clang_RefactoringAction_getRefactoringCandidates(
CXRefactoringAction Action,
CXRefactoringCandidateSet *OutRefactoringCandidateSet) {
if (!Action || !OutRefactoringCandidateSet)
return CXError_InvalidArguments;
*OutRefactoringCandidateSet =
static_cast<RefactoringAction *>(Action)->getRefactoringCandidates();
return CXError_Success;
}
enum CXErrorCode
clang_RefactoringAction_selectRefactoringCandidate(CXRefactoringAction Action,
unsigned Index) {
if (!Action)
return CXError_InvalidArguments;
return static_cast<RefactoringAction *>(Action)->selectCandidate(Index);
}
// TODO: Remove.
enum CXErrorCode clang_Refactoring_initiateActionAt(
CXTranslationUnit TU, CXSourceLocation Location,
CXSourceRange SelectionRange, enum CXRefactoringActionType ActionType,
CXRefactoringOptionSet Options, CXRefactoringAction *OutAction,
CXString *OutFailureReason) {
CXDiagnosticSet Diags;
CXErrorCode Result = clang_Refactoring_initiateAction(
TU, Location, SelectionRange, ActionType, Options, OutAction, &Diags);
if (OutFailureReason && Diags && clang_getNumDiagnosticsInSet(Diags) == 1) {
CXString Spelling =
clang_getDiagnosticSpelling(clang_getDiagnosticInSet(Diags, 0));
*OutFailureReason = cxstring::createDup(clang_getCString(Spelling));
clang_disposeString(Spelling);
} else if (OutFailureReason)
*OutFailureReason = cxstring::createEmpty();
clang_disposeDiagnosticSet(Diags);
return Result;
}
enum CXErrorCode clang_Refactoring_initiateAction(
CXTranslationUnit TU, CXSourceLocation Location,
CXSourceRange SelectionRange, enum CXRefactoringActionType ActionType,
CXRefactoringOptionSet Options, CXRefactoringAction *OutAction,
CXDiagnosticSet *OutDiagnostics) {
if (!OutAction)
return CXError_InvalidArguments;
*OutAction = nullptr;
if (OutDiagnostics)
*OutDiagnostics = nullptr;
if (cxtu::isNotUsableTU(TU)) {
LOG_BAD_TU(TU);
return CXError_InvalidArguments;
}
ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
if (!CXXUnit)
return CXError_InvalidArguments;
SourceLocation Loc = cxloc::translateSourceLocation(Location);
if (Loc.isInvalid())
return CXError_InvalidArguments;
ASTUnit::ConcurrencyCheck Check(*CXXUnit);
(void)Options; // FIXME: handle options
ASTContext &Context = CXXUnit->getASTContext();
RefactoringDiagnosticConsumer DiagConsumer(Context);
auto Operation = initiateRefactoringOperationAt(
Loc, cxloc::translateCXSourceRange(SelectionRange), Context,
translateRefactoringActionType(ActionType));
if (!Operation.Initiated) {
if (OutDiagnostics) {
if (!Operation.FailureReason.empty()) {
// TODO: Remove when other actions migrate to diagnostics.
StoredDiagnostic Diag(DiagnosticsEngine::Error, /*ID=*/0,
Operation.FailureReason);
*OutDiagnostics =
cxdiag::createStoredDiags(Diag, Context.getLangOpts());
} else
*OutDiagnostics = DiagConsumer.createDiags();
}
return CXError_RefactoringActionUnavailable;
}
if (Operation.RefactoringOp)
*OutAction = new RefactoringAction(std::move(Operation.RefactoringOp),
ActionType, TU);
else
*OutAction = new RefactoringAction(
std::make_unique<RenamingAction>(CXXUnit->getLangOpts(),
std::move(*Operation.SymbolOp)),
TU);
return CXError_Success;
}
enum CXErrorCode clang_Refactoring_initiateActionOnDecl(
CXTranslationUnit TU, const char *DeclUSR,
enum CXRefactoringActionType ActionType, CXRefactoringOptionSet Options,
CXRefactoringAction *OutAction, CXString *OutFailureReason) {
if (!OutAction)
return CXError_InvalidArguments;
*OutAction = nullptr;
if (OutFailureReason)
*OutFailureReason = cxstring::createNull();
if (cxtu::isNotUsableTU(TU)) {
LOG_BAD_TU(TU);
return CXError_InvalidArguments;
}
ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
if (!CXXUnit)
return CXError_InvalidArguments;
ASTUnit::ConcurrencyCheck Check(*CXXUnit);
(void)Options; // FIXME: handle options
auto Operation = initiateRefactoringOperationOnDecl(
DeclUSR, CXXUnit->getASTContext(),
translateRefactoringActionType(ActionType));
if (!Operation.Initiated)
return CXError_RefactoringActionUnavailable;
// FIXME: Don't dupe with above
if (Operation.RefactoringOp)
*OutAction = new RefactoringAction(std::move(Operation.RefactoringOp),
ActionType, TU);
else
*OutAction = new RefactoringAction(
std::make_unique<RenamingAction>(CXXUnit->getLangOpts(),
std::move(*Operation.SymbolOp)),
TU);
return CXError_Success;
}
enum CXErrorCode
clang_Refactoring_initiateRenamingOperation(CXRefactoringAction Action) {
if (!Action)
return CXError_InvalidArguments;
RefactoringAction *RefAction = static_cast<RefactoringAction *>(Action);
RenamingAction *Rename = RefAction->getRenamingAction();
if (!Rename)
return CXError_InvalidArguments;
// TODO
return CXError_Success;
}
CINDEX_LINKAGE
enum CXErrorCode clang_Refactoring_findRenamedCursor(
CXTranslationUnit TU, CXSourceLocation Location,
CXSourceRange SelectionRange, CXCursor *OutCursor) {
if (!OutCursor)
return CXError_InvalidArguments;
if (cxtu::isNotUsableTU(TU)) {
LOG_BAD_TU(TU);
return CXError_InvalidArguments;
}
ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
if (!CXXUnit)
return CXError_InvalidArguments;
SourceLocation Loc = cxloc::translateSourceLocation(Location);
if (Loc.isInvalid())
return CXError_InvalidArguments;
const NamedDecl *ND = rename::getNamedDeclAt(CXXUnit->getASTContext(), Loc);
if (!ND) {
*OutCursor = cxcursor::MakeCXCursorInvalid(CXCursor_NoDeclFound, TU);
return CXError_RefactoringActionUnavailable;
}
*OutCursor = cxcursor::MakeCXCursor(ND, TU);
return CXError_Success;
}
enum CXErrorCode clang_RenamingOperation_setNewName(CXRefactoringAction Action,
const char *NewName) {
return withRenamingAction<CXErrorCode>(
Action, CXError_InvalidArguments,
[=](RenamingAction &Action) -> CXErrorCode {
if (!NewName)
return CXError_InvalidArguments;
StringRef Name = NewName;
if (Name.empty())
return CXError_InvalidArguments;
return Action.setNewName(Name);
});
}
enum CXRefactoringActionType
clang_RefactoringAction_getInitiatedActionType(CXRefactoringAction Action) {
return static_cast<RefactoringAction *>(Action)->Type;
}
unsigned clang_RenamingOperation_getNumSymbols(CXRefactoringAction Action) {
return withRenamingAction<unsigned>(Action, 0, [](RenamingAction &Action) {
return Action.Operation.symbols().size();
});
}
CXString clang_RenamingOperation_getUSRForSymbol(CXRefactoringAction Action,
unsigned Index) {
return withRenamingAction<CXString>(
Action, cxstring::createNull(),
[=](RenamingAction &Action) { return Action.usrForSymbolAt(Index); });
}
CXRenamingResult clang_Refactoring_findRenamedOccurrencesInPrimaryTUs(
CXRefactoringAction Action, const char *const *CommandLineArgs,
int NumCommandLineArgs, CXUnsavedFile *UnsavedFiles,
unsigned NumUnsavedFiles) {
if (!Action)
return nullptr;
RefactoringAction *RefAction = static_cast<RefactoringAction *>(Action);
RenamingAction *Rename = RefAction->getRenamingAction();
if (!Rename)
return nullptr;
// TODO: Handle implementation TU
if (cxtu::isNotUsableTU(RefAction->InitiationTU)) {
LOG_BAD_TU(RefAction->InitiationTU);
return nullptr;
}
ASTUnit *CXXUnit = cxtu::getASTUnit(RefAction->InitiationTU);
if (!CXXUnit)
return nullptr;
ASTUnit::ConcurrencyCheck Check(*CXXUnit);
return Rename->handlePrimaryTU(RefAction->InitiationTU, *CXXUnit);
}
CXSymbolOccurrencesResult clang_Refactoring_findSymbolOccurrencesInInitiationTU(
CXRefactoringAction Action, const char *const *CommandLineArgs,
int NumCommandLineArgs, struct CXUnsavedFile *UnsavedFiles,
unsigned NumUnsavedFiles) {
if (!Action)
return nullptr;
RefactoringAction *RefAction = static_cast<RefactoringAction *>(Action);
RenamingAction *Rename = RefAction->getRenamingAction();
if (!Rename)
return nullptr;
if (cxtu::isNotUsableTU(RefAction->InitiationTU)) {
LOG_BAD_TU(RefAction->InitiationTU);
return nullptr;
}
ASTUnit *CXXUnit = cxtu::getASTUnit(RefAction->InitiationTU);
if (!CXXUnit)
return nullptr;
ASTUnit::ConcurrencyCheck Check(*CXXUnit);
return Rename->findSymbolsInInitiationTU(RefAction->InitiationTU, *CXXUnit);
}
CXErrorCode clang_Refactoring_findRenamedOccurrencesInIndexedFile(
const CXRenamedIndexedSymbol *Symbols, unsigned NumSymbols, CXIndex CIdx,
const char *Filename, const char *const *CommandLineArgs,
int NumCommandLineArgs, struct CXUnsavedFile *UnsavedFiles,
unsigned NumUnsavedFiles, CXRefactoringOptionSet Options,
CXRenamingResult *OutResult) {
if (!OutResult)
return CXError_InvalidArguments;
if (!Symbols || !NumSymbols || !Filename)
return CXError_InvalidArguments;
return performIndexedFileRename(
ArrayRef(Symbols, NumSymbols), StringRef(Filename),
ArrayRef(CommandLineArgs, NumCommandLineArgs), CIdx,
MutableArrayRef<CXUnsavedFile>(UnsavedFiles, NumUnsavedFiles),
Options ? static_cast<RefactoringOptionSet *>(Options) : nullptr,
*OutResult);
}
CXErrorCode clang_Refactoring_findSymbolOccurrencesInIndexedFile(
const CXIndexedSymbol *Symbols, unsigned NumSymbols, CXIndex CIdx,
const char *Filename, const char *const *CommandLineArgs,
int NumCommandLineArgs, struct CXUnsavedFile *UnsavedFiles,
unsigned NumUnsavedFiles, CXRefactoringOptionSet Options,
CXSymbolOccurrencesResult *OutResult) {
if (!OutResult)
return CXError_InvalidArguments;
if (!Symbols || !NumSymbols || !Filename)
return CXError_InvalidArguments;
return performIndexedSymbolSearch(
ArrayRef(Symbols, NumSymbols), StringRef(Filename),
ArrayRef(CommandLineArgs, NumCommandLineArgs), CIdx,
MutableArrayRef<CXUnsavedFile>(UnsavedFiles, NumUnsavedFiles),
Options ? static_cast<RefactoringOptionSet *>(Options) : nullptr,
*OutResult);
}
unsigned clang_RenamingResult_getNumModifiedFiles(CXRenamingResult Result) {
if (Result)
return static_cast<RenamingResult *>(Result)->getFilenames().size();
return 0;
}
void clang_RenamingResult_getResultForFile(CXRenamingResult Result,
unsigned FileIndex,
CXFileRenamingResult *OutResult) {
if (!Result ||
FileIndex >=
static_cast<RenamingResult *>(Result)->getFilenames().size()) {
OutResult->Filename = cxstring::createNull();
OutResult->NumOccurrences = 0;
OutResult->Occurrences = nullptr;
return;
}
auto &RenameResult = *static_cast<RenamingResult *>(Result);
OutResult->Filename = RenameResult.getFilenames()[FileIndex];
OutResult->NumOccurrences = RenameResult.getOccurrences(FileIndex).size();
OutResult->Occurrences = RenameResult.getOccurrences(FileIndex).data();
}
void clang_RenamingResult_dispose(CXRenamingResult Result) {
if (Result)
delete static_cast<RenamingResult *>(Result);
}
unsigned clang_SymbolOccurrences_getNumFiles(CXSymbolOccurrencesResult Result) {
if (Result)
return static_cast<SymbolOccurrencesResult *>(Result)
->getFilenames()
.size();
return 0;
}
void clang_SymbolOccurrences_getOccurrencesForFile(
CXSymbolOccurrencesResult Result, unsigned FileIndex,
CXSymbolOccurrencesInFile *OutResult) {
if (!Result ||
FileIndex >= static_cast<SymbolOccurrencesResult *>(Result)
->getFilenames()
.size()) {
OutResult->Filename = cxstring::createNull();
OutResult->NumOccurrences = 0;
OutResult->Occurrences = nullptr;
return;
}
auto &RenameResult = *static_cast<SymbolOccurrencesResult *>(Result);
OutResult->Filename = RenameResult.getFilenames()[FileIndex];
OutResult->NumOccurrences = RenameResult.getOccurrences(FileIndex).size();
OutResult->Occurrences = RenameResult.getOccurrences(FileIndex).data();
}
void clang_SymbolOccurrences_dispose(CXSymbolOccurrencesResult Result) {
if (Result)
delete static_cast<SymbolOccurrencesResult *>(Result);
}
CXRefactoringResult clang_Refactoring_performOperation(
CXRefactoringAction Action, const char *const *CommandLineArgs,
int NumCommandLineArgs, struct CXUnsavedFile *UnsavedFiles,
unsigned NumUnsavedFiles, CXRefactoringOptionSet Options,
CXString *OutFailureReason) {
if (OutFailureReason)
*OutFailureReason = cxstring::createNull();
if (!Action)
return nullptr;
RefactoringAction *RefAction = static_cast<RefactoringAction *>(Action);
if (!RefAction->getOperation())
return nullptr;
ASTUnit *CXXUnit = cxtu::getASTUnit(RefAction->InitiationTU);
if (!CXXUnit)
return nullptr;
ASTUnit::ConcurrencyCheck Check(*CXXUnit);
RefactoringOptionSet EmptyOptionSet;
const RefactoringOptionSet &OptionSet =
Options ? *static_cast<RefactoringOptionSet *>(Options) : EmptyOptionSet;
llvm::Expected<RefactoringResult> Result = RefAction->getOperation()->perform(
CXXUnit->getASTContext(), CXXUnit->getPreprocessor(), OptionSet,
RefAction->SelectedCandidate);
if (!Result) {
if (OutFailureReason) {
(void)!llvm::handleErrors(
Result.takeError(), [&](const RefactoringOperationError &Error) {
*OutFailureReason = cxstring::createDup(Error.FailureReason);
});
}
return nullptr;
}
return new RefactoringResultWrapper(
Result.get().Replacements, Result.get().AssociatedSymbols,
std::move(Result.get().Continuation), CXXUnit->getASTContext(),
RefAction->InitiationTU);
}
void clang_RefactoringResult_getReplacements(
CXRefactoringResult Result,
CXRefactoringReplacements_Old *OutReplacements) {
if (!OutReplacements)
return;
if (!Result) {
OutReplacements->FileReplacementSets = nullptr;
OutReplacements->NumFileReplacementSets = 0;
return;
}
*OutReplacements = static_cast<RefactoringResultWrapper *>(Result)->Replacements;
}
CXRefactoringReplacements
clang_RefactoringResult_getSourceReplacements(CXRefactoringResult Result) {
if (!Result)
return CXRefactoringReplacements{nullptr, 0};
return static_cast<RefactoringResultWrapper *>(Result)->SourceReplacements;
}
CXRefactoringReplacementAssociatedSymbolOccurrences
clang_RefactoringReplacement_getAssociatedSymbolOccurrences(
CXRefactoringReplacement Replacement) {
if (!Replacement.AssociatedData)
return CXRefactoringReplacementAssociatedSymbolOccurrences{nullptr, 0};
auto *Data =
static_cast<RefactoringResultWrapper::AssociatedReplacementInfo *>(
Replacement.AssociatedData);
return CXRefactoringReplacementAssociatedSymbolOccurrences{
Data->AssociatedSymbolOccurrences, Data->NumAssociatedSymbolOccurrences};
}
void clang_RefactoringResult_dispose(CXRefactoringResult Result) {
if (Result)
delete static_cast<RefactoringResultWrapper *>(Result);
}
CXRefactoringContinuation
clang_RefactoringResult_getContinuation(CXRefactoringResult Result) {
if (!Result)
return nullptr;
auto *Wrapper = static_cast<RefactoringResultWrapper *>(Result);
if (!Wrapper->Continuation)
return nullptr;
return new RefactoringContinuationWrapper(std::move(Wrapper->Continuation),
Wrapper->TU);
}
enum CXErrorCode
clang_RefactoringContinuation_loadSerializedIndexerQueryResults(
CXRefactoringContinuation Continuation, const char *Source) {
if (!Continuation)
return CXError_InvalidArguments;
auto *Wrapper = static_cast<RefactoringContinuationWrapper *>(Continuation);
llvm::SmallVector<indexer::IndexerQuery *, 4> Queries;
for (const auto &Query : Wrapper->Queries)
Queries.push_back(Query.Query);
auto Err = indexer::IndexerQuery::loadResultsFromYAML(Source, Queries);
if (Err) {
consumeError(std::move(Err));
return CXError_Failure;
}
return CXError_Success;
}
unsigned clang_RefactoringContinuation_getNumIndexerQueries(
CXRefactoringContinuation Continuation) {
if (Continuation)
return static_cast<RefactoringContinuationWrapper *>(Continuation)
->Queries.size();
return 0;
}
CXIndexerQuery clang_RefactoringContinuation_getIndexerQuery(
CXRefactoringContinuation Continuation, unsigned Index) {
if (!Continuation)
return nullptr;
auto *Wrapper = static_cast<RefactoringContinuationWrapper *>(Continuation);
if (Index >= Wrapper->Queries.size())
return nullptr;
return &Wrapper->Queries[Index];
}
CXDiagnosticSet clang_RefactoringContinuation_verifyBeforeFinalizing(
CXRefactoringContinuation Continuation) {
if (!Continuation)
return nullptr;
auto *Wrapper = static_cast<RefactoringContinuationWrapper *>(Continuation);
CXTranslationUnit TU = Wrapper->Queries[0].TU;
ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
if (!CXXUnit)
return nullptr;
ASTContext &Context = CXXUnit->getASTContext();
RefactoringDiagnosticConsumer DiagConsumer(Context);
for (const auto &Query : Wrapper->Queries) {
if (Query.Query->verify(Context))
break;
}
return DiagConsumer.createDiags();
}
void clang_RefactoringContinuation_finalizeEvaluationInInitationTU(
CXRefactoringContinuation Continuation) {
if (!Continuation)
return;
auto *Wrapper = static_cast<RefactoringContinuationWrapper *>(Continuation);
Wrapper->Queries.clear();
Wrapper->Continuation->persistTUSpecificState();
Wrapper->IsInitiationTUAbandoned = true;
}
CXRefactoringResult clang_RefactoringContinuation_continueOperationInTU(
CXRefactoringContinuation Continuation, CXTranslationUnit TU,
CXString *OutFailureReason) {
if (!Continuation || !TU)
return nullptr;
ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
if (!CXXUnit)
return nullptr;
ASTUnit::ConcurrencyCheck Check(*CXXUnit);
const auto *Wrapper =
static_cast<RefactoringContinuationWrapper *>(Continuation);
if (!Wrapper->IsInitiationTUAbandoned) {
// FIXME: We can avoid conversions of TU-specific state if the given TU is
// the same as the initiation TU.
clang_RefactoringContinuation_finalizeEvaluationInInitationTU(Continuation);
}
auto Result =
Wrapper->Continuation->runInExternalASTUnit(CXXUnit->getASTContext());
if (!Result) {
if (OutFailureReason) {
(void)!llvm::handleErrors(
Result.takeError(), [&](const RefactoringOperationError &Error) {
*OutFailureReason = cxstring::createDup(Error.FailureReason);
});
}
return nullptr;
}
return new RefactoringResultWrapper(
Result.get().Replacements, Result.get().AssociatedSymbols,
std::move(Result.get().Continuation), CXXUnit->getASTContext(), TU);
}
void clang_RefactoringContinuation_dispose(
CXRefactoringContinuation Continuation) {
if (Continuation)
delete static_cast<RefactoringContinuationWrapper *>(Continuation);
}
enum CXIndexerQueryKind clang_IndexerQuery_getKind(CXIndexerQuery Query) {
if (!Query)
return CXIndexerQuery_Unknown;
const auto *IQ =
static_cast<RefactoringContinuationWrapper::QueryWrapper *>(Query)->Query;
if (const auto *DQ = dyn_cast<indexer::DeclarationsQuery>(IQ)) {
const indexer::detail::DeclPredicateNode &Node = DQ->getPredicateNode();
if (const auto *NP =
dyn_cast<indexer::detail::DeclPredicateNotPredicate>(&Node))
return translateDeclPredicate(
cast<indexer::detail::DeclPredicateNodePredicate>(NP->getChild())
.getPredicate());
return translateDeclPredicate(
cast<indexer::detail::DeclPredicateNodePredicate>(Node).getPredicate());
} else if (isa<indexer::ASTUnitForImplementationOfDeclarationQuery>(IQ))
return CXIndexerQuery_Decl_FileThatShouldImplement;
return CXIndexerQuery_Unknown;
}
unsigned clang_IndexerQuery_getNumCursors(CXIndexerQuery Query) {
if (!Query)
return 0;
const auto *IQ =
static_cast<RefactoringContinuationWrapper::QueryWrapper *>(Query)->Query;
if (const auto *DQ = dyn_cast<indexer::DeclarationsQuery>(IQ))
return DQ->getInputs().size();
else if (isa<indexer::ASTUnitForImplementationOfDeclarationQuery>(IQ))
return 1;
return 0;
}
CXCursor clang_IndexerQuery_getCursor(CXIndexerQuery Query,
unsigned CursorIndex) {
if (Query) {
const auto *Wrapper =
static_cast<RefactoringContinuationWrapper::QueryWrapper *>(Query);
const indexer::IndexerQuery *IQ = Wrapper->Query;
CXTranslationUnit TU = Wrapper->TU;
if (const auto *DQ = dyn_cast<indexer::DeclarationsQuery>(IQ)) {
if (CursorIndex < DQ->getInputs().size())
return cxcursor::MakeCXCursor(DQ->getInputs()[CursorIndex], TU);
} else if (const auto *ASTQuery = dyn_cast<
indexer::ASTUnitForImplementationOfDeclarationQuery>(IQ)) {
if (CursorIndex == 0)
return cxcursor::MakeCXCursor(ASTQuery->getDecl(), TU);
}
}
return cxcursor::MakeCXCursorInvalid(CXCursor_InvalidCode);
}
enum CXIndexerQueryAction
clang_IndexerQuery_consumeIntResult(CXIndexerQuery Query, unsigned CursorIndex,
int Value) {
if (!Query)
return CXIndexerQueryAction_None;
auto *Wrapper =
static_cast<RefactoringContinuationWrapper::QueryWrapper *>(Query);
auto *DQ = dyn_cast<indexer::DeclarationsQuery>(Wrapper->Query);
if (!DQ)
return CXIndexerQueryAction_None;
if (CursorIndex >= DQ->getInputs().size() ||
Wrapper->ConsumedResults == DQ->getInputs().size())
return CXIndexerQueryAction_None;
if (Wrapper->DeclResults.empty())
Wrapper->DeclResults.resize(DQ->getInputs().size(),
indexer::Indexed<PersistentDeclRef<Decl>>(
PersistentDeclRef<Decl>::create(nullptr)));
// Filter the declarations!
bool IsNot = false;
if (isa<indexer::detail::DeclPredicateNotPredicate>(DQ->getPredicateNode()))
IsNot = true;
bool Result = IsNot ? !Value : !!Value;
Wrapper->DeclResults[CursorIndex] = indexer::Indexed<PersistentDeclRef<Decl>>(
PersistentDeclRef<Decl>::create(Result ? DQ->getInputs()[CursorIndex]
: nullptr),
Result ? indexer::QueryBoolResult::Yes : indexer::QueryBoolResult::No);
Wrapper->ConsumedResults++;
if (Wrapper->ConsumedResults == Wrapper->DeclResults.size()) {
// We've received all the results, pass them back to the query.
DQ->setOutput(std::move(Wrapper->DeclResults));
}
return CXIndexerQueryAction_None;
}
enum CXIndexerQueryAction
clang_IndexerQuery_consumeFileResult(CXIndexerQuery Query, unsigned CursorIndex,
const char *Filename) {
if (!Query || !Filename)
return CXIndexerQueryAction_None;
auto *IQ =
static_cast<RefactoringContinuationWrapper::QueryWrapper *>(Query)->Query;
if (auto *ASTQuery =
dyn_cast<indexer::ASTUnitForImplementationOfDeclarationQuery>(IQ)) {
if (CursorIndex != 0)
return CXIndexerQueryAction_None;
ASTQuery->setResult(PersistentFileID(Filename));
return CXIndexerQueryAction_RunContinuationInTUThatHasThisFile;
}
return CXIndexerQueryAction_None;
}
}
|