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
|
//===----------------------------------------------------------------------===//
//
// Copyright (c) 2012, 2013, 2014, 2015, 2016 The University of Utah
// All rights reserved.
//
// This file is distributed under the University of Illinois Open Source
// License. See the file COPYING for details.
//
//===----------------------------------------------------------------------===//
#if HAVE_CONFIG_H
# include <config.h>
#endif
#include "RewriteUtils.h"
#include <cctype>
#include <sstream>
#include "clang/Basic/SourceManager.h"
#include "clang/Rewrite/Core/Rewriter.h"
#include "clang/AST/Decl.h"
#include "clang/AST/DeclCXX.h"
#include "clang/AST/DeclTemplate.h"
#include "clang/AST/Expr.h"
#include "clang/AST/TypeLoc.h"
#include "clang/AST/ExprCXX.h"
using namespace clang;
using namespace llvm;
static const char *DefaultIndentStr = " ";
RewriteUtils *RewriteUtils::Instance;
const char *RewriteUtils::TmpVarNamePrefix = "__trans_tmp_";
RewriteUtils *RewriteUtils::GetInstance(Rewriter *RW)
{
if (RewriteUtils::Instance) {
RewriteUtils::Instance->TheRewriter = RW;
RewriteUtils::Instance->SrcManager = &(RW->getSourceMgr());
return RewriteUtils::Instance;
}
RewriteUtils::Instance = new RewriteUtils();
assert(RewriteUtils::Instance);
RewriteUtils::Instance->TheRewriter = RW;
RewriteUtils::Instance->SrcManager = &(RW->getSourceMgr());
return RewriteUtils::Instance;
}
void RewriteUtils::Finalize(void)
{
if (RewriteUtils::Instance) {
delete RewriteUtils::Instance;
RewriteUtils::Instance = NULL;
}
}
// copied from Rewriter.cpp
unsigned RewriteUtils::getLocationOffsetAndFileID(SourceLocation Loc,
FileID &FID,
SourceManager *SrcManager)
{
assert(Loc.isValid() && "Invalid location");
std::pair<FileID,unsigned> V = SrcManager->getDecomposedLoc(Loc);
FID = V.first;
return V.second;
}
unsigned RewriteUtils::getOffsetBetweenLocations(SourceLocation StartLoc,
SourceLocation EndLoc,
SourceManager *SrcManager)
{
FileID FID;
unsigned StartOffset =
getLocationOffsetAndFileID(StartLoc, FID, SrcManager);
unsigned EndOffset =
getLocationOffsetAndFileID(EndLoc, FID, SrcManager);
TransAssert((EndOffset >= StartOffset) && "Bad locations!");
return (EndOffset - StartOffset);
}
SourceLocation RewriteUtils::getEndLocationFromBegin(SourceRange Range)
{
SourceLocation StartLoc = Range.getBegin();
SourceLocation EndLoc = Range.getEnd();
if (StartLoc.isInvalid())
return StartLoc;
if (EndLoc.isInvalid())
return EndLoc;
if (StartLoc.isMacroID())
StartLoc = SrcManager->getFileLoc(StartLoc);
if (EndLoc.isMacroID())
EndLoc = SrcManager->getFileLoc(EndLoc);
SourceRange NewRange(StartLoc, EndLoc);
int LocRangeSize = TheRewriter->getRangeSize(NewRange);
if (LocRangeSize == -1)
return NewRange.getEnd();
return StartLoc.getLocWithOffset(LocRangeSize);
}
int RewriteUtils::getOffsetUntil(const char *Buf, char Symbol)
{
int Offset = 0;
while (*Buf != Symbol) {
Buf++;
if (*Buf == '\0')
break;
Offset++;
}
return Offset;
}
int RewriteUtils::getSkippingOffset(const char *Buf, char Symbol)
{
int Offset = 0;
while (*Buf == Symbol) {
Buf++;
if (*Buf == '\0')
break;
Offset++;
}
return Offset;
}
SourceLocation RewriteUtils::getEndLocationUntil(SourceRange Range,
char Symbol)
{
SourceLocation EndLoc = getEndLocationFromBegin(Range);
if (EndLoc.isInvalid())
return EndLoc;
const char *EndBuf = SrcManager->getCharacterData(EndLoc);
int Offset = getOffsetUntil(EndBuf, Symbol);
return EndLoc.getLocWithOffset(Offset);
}
SourceLocation RewriteUtils::getLocationUntil(SourceLocation Loc,
char Symbol)
{
const char *Buf = SrcManager->getCharacterData(Loc);
int Offset = getOffsetUntil(Buf, Symbol);
return Loc.getLocWithOffset(Offset);
}
SourceLocation RewriteUtils::getEndLocationAfter(SourceRange Range,
char Symbol)
{
SourceLocation EndLoc = getEndLocationFromBegin(Range);
if (EndLoc.isInvalid())
return EndLoc;
const char *EndBuf = SrcManager->getCharacterData(EndLoc);
int Offset = getOffsetUntil(EndBuf, Symbol);
Offset++;
return EndLoc.getLocWithOffset(Offset);
}
SourceLocation RewriteUtils::getLocationAfter(SourceLocation Loc,
char Symbol)
{
const char *Buf = SrcManager->getCharacterData(Loc);
int Offset = getOffsetUntil(Buf, Symbol);
Offset++;
return Loc.getLocWithOffset(Offset);
}
SourceLocation RewriteUtils::getLocationAfterSkiping(SourceLocation StartLoc,
char Symbol)
{
const char *StartBuf = SrcManager->getCharacterData(StartLoc);
int Offset = getSkippingOffset(StartBuf, Symbol);
return StartLoc.getLocWithOffset(Offset);
}
SourceLocation RewriteUtils::getParamSubstringLocation(SourceLocation StartLoc,
size_t Size,
const std::string &Substr)
{
const char *StartBuf = SrcManager->getCharacterData(StartLoc);
std::string TmpStr(StartBuf, Size);
size_t Pos = TmpStr.find(Substr);
TransAssert((Pos != std::string::npos) && "Bad Name Position!");
if (Pos == 0)
return StartLoc;
else
return StartLoc.getLocWithOffset(Pos);
}
bool RewriteUtils::removeParamFromFuncDecl(const ParmVarDecl *PV,
unsigned int NumParams,
int ParamPos)
{
SourceRange ParamLocRange = PV->getSourceRange();
int RangeSize;
SourceLocation StartLoc = ParamLocRange.getBegin();
SourceLocation EndLoc = ParamLocRange.getEnd();
if (StartLoc.isInvalid() && EndLoc.isInvalid()) {
return false;
}
else if (StartLoc.isInvalid()) {
StartLoc = EndLoc;
RangeSize = PV->getNameAsString().size();
}
else if (EndLoc.isInvalid()) {
const char *Buf = SrcManager->getCharacterData(StartLoc);
if ((ParamPos == 0) && (NumParams == 1)) {
RangeSize = getOffsetUntil(Buf, ')');
}
else {
RangeSize = getOffsetUntil(Buf, ',');
}
}
else {
RangeSize = TheRewriter->getRangeSize(ParamLocRange);
if (RangeSize == -1)
return false;
}
// The param is the only parameter of the function declaration.
// Replace it with void
if ((ParamPos == 0) && (NumParams == 1)) {
return !(TheRewriter->ReplaceText(StartLoc,
RangeSize, "void"));
}
// The param is the last parameter
if (ParamPos == static_cast<int>(NumParams - 1)) {
int Offset = 0;
const char *StartBuf =
SrcManager->getCharacterData(StartLoc);
TransAssert(StartBuf && "Invalid start buffer!");
while (*StartBuf != ',') {
StartBuf--;
Offset--;
}
SourceLocation NewStartLoc = StartLoc.getLocWithOffset(Offset);
return !(TheRewriter->RemoveText(NewStartLoc, RangeSize - Offset));
}
// We cannot use the code below:
// SourceLocation EndLoc = ParamLocRange.getEnd();
// const char *EndBuf =
// ConsumerInstance->SrcManager->getCharacterData(EndLoc);
// Because getEnd() returns the start of the last token if this
// is a token range. For example, in the above example,
// getEnd() points to the start of "x"
// See the comments on getRangeSize in clang/lib/Rewriter/Rewriter.cpp
int NewRangeSize = 0;
const char *StartBuf = SrcManager->getCharacterData(StartLoc);
while (NewRangeSize < RangeSize) {
StartBuf++;
NewRangeSize++;
}
TransAssert(StartBuf && "Invalid start buffer!");
while (*StartBuf != ',') {
StartBuf++;
NewRangeSize++;
}
return !(TheRewriter->RemoveText(StartLoc, NewRangeSize + 1));
}
// Handle CXXConstructExpr and CallExpr.
// These two do not inherit each other, and we need a couple of
// `common` member functions from them.
// Is this too ugly? Any better way to do this?
const Expr *RewriteUtils::getArgWrapper(const Expr *E,
int ParamPos)
{
const CXXConstructExpr *CtorE = dyn_cast<CXXConstructExpr>(E);
if (CtorE)
return CtorE->getArg(ParamPos);
const CallExpr *CE = dyn_cast<CallExpr>(E);
if (CE)
return CE->getArg(ParamPos);
TransAssert(0 && "Invalid Expr!");
return NULL;
}
unsigned RewriteUtils::getNumArgsWrapper(const Expr *E)
{
const CXXConstructExpr *CtorE = dyn_cast<CXXConstructExpr>(E);
if (CtorE)
return CtorE->getNumArgs();
const CallExpr *CE = dyn_cast<CallExpr>(E);
if (CE)
return CE->getNumArgs();
TransAssert(0 && "Invalid Expr!");
return 0;
}
bool RewriteUtils::removeArgFromExpr(const Expr *E,
int ParamPos)
{
if (ParamPos >= static_cast<int>(getNumArgsWrapper(E)))
return true;
const Expr *Arg = getArgWrapper(E, ParamPos);
TransAssert(Arg && "Null arg!");
if (dyn_cast<CXXDefaultArgExpr>(Arg->IgnoreParenCasts()))
return true;
SourceRange ArgRange = Arg->getSourceRange();
int RangeSize = TheRewriter->getRangeSize(ArgRange);
if (RangeSize == -1)
return false;
SourceLocation StartLoc = ArgRange.getBegin();
unsigned int NumArgs = getNumArgsWrapper(E);
if ((ParamPos == 0) && ((NumArgs == 1) ||
((NumArgs > 1) &&
dyn_cast<CXXDefaultArgExpr>(
getArgWrapper(E, 1)->IgnoreParenCasts())))) {
// Note that ')' is included in ParamLocRange
return !(TheRewriter->RemoveText(ArgRange));
}
int LastArgPos = static_cast<int>(NumArgs - 1);
// The param is the last non-default parameter
if ((ParamPos == LastArgPos) ||
((ParamPos < LastArgPos) &&
dyn_cast<CXXDefaultArgExpr>(
getArgWrapper(E, ParamPos+1)->IgnoreParenCasts()))) {
int Offset = 0;
const char *StartBuf = SrcManager->getCharacterData(StartLoc);
TransAssert(StartBuf && "Invalid start buffer!");
while (*StartBuf != ',') {
StartBuf--;
Offset--;
}
SourceLocation NewStartLoc = StartLoc.getLocWithOffset(Offset);
return !(TheRewriter->RemoveText(NewStartLoc,
RangeSize - Offset));
}
// We cannot use SrcManager->getCharacterData(StartLoc) to get the buffer,
// because it returns the unmodified string. I've tried to use
// getEndlocationUntil(ArgRange, ",", ...) call, but still failed.
// Seems in some cases, it returns bad results for a complex case like:
// foo(...foo(...), ...)
// So I ended up with this ugly way - get the end loc from the next arg.
const Expr *NextArg = getArgWrapper(E, ParamPos+1);
SourceRange NextArgRange = NextArg->getSourceRange();
SourceLocation NextStartLoc = NextArgRange.getBegin();
const char *NextStartBuf = SrcManager->getCharacterData(NextStartLoc);
int Offset = 0;
while (*NextStartBuf != ',') {
NextStartBuf--;
Offset--;
}
SourceLocation NewEndLoc = NextStartLoc.getLocWithOffset(Offset);
return !TheRewriter->RemoveText(SourceRange(StartLoc, NewEndLoc));
}
bool RewriteUtils::removeArgFromCXXConstructExpr(const CXXConstructExpr *CE,
int ParamPos)
{
return removeArgFromExpr(CE, ParamPos);
}
bool RewriteUtils::removeArgFromCallExpr(const CallExpr *CallE,
int ParamPos)
{
return removeArgFromExpr(CallE, ParamPos);
}
void RewriteUtils::skipRangeByType(const std::string &BufStr,
const Type *Ty,
int &Offset)
{
Offset = 0;
int BufSz = static_cast<int>(BufStr.size());
size_t Pos;
while (Offset < BufSz) {
if (isspace(BufStr[Offset])) {
Offset++;
continue;
}
Pos = BufStr.find("char", Offset);
if (Pos != std::string::npos) {
Offset += 4;
continue;
}
Pos = BufStr.find("int", Offset);
if (Pos != std::string::npos) {
Offset += 3;
continue;
}
Pos = BufStr.find("short", Offset);
if (Pos != std::string::npos) {
Offset += 5;
continue;
}
Pos = BufStr.find("long", Offset);
if (Pos != std::string::npos) {
Offset += 4;
continue;
}
return;
}
}
SourceLocation RewriteUtils::skipPossibleTypeRange(const Type *Ty,
SourceLocation OrigEndLoc,
SourceLocation VarStartLoc)
{
if (!Ty->isIntegerType())
return OrigEndLoc;
int Offset;
std::string BufStr;
getStringBetweenLocs(BufStr, OrigEndLoc, VarStartLoc);
skipRangeByType(BufStr, Ty, Offset);
return OrigEndLoc.getLocWithOffset(Offset);
}
SourceLocation RewriteUtils::getVarDeclTypeLocBegin(const VarDecl *VD)
{
TypeLoc VarTypeLoc = VD->getTypeSourceInfo()->getTypeLoc();
TypeLoc NextTL = VarTypeLoc.getNextTypeLoc();
while (!NextTL.isNull()) {
VarTypeLoc = NextTL;
NextTL = NextTL.getNextTypeLoc();
}
return VarTypeLoc.getLocStart();
}
SourceLocation RewriteUtils::getVarDeclTypeLocEnd(const VarDecl *VD)
{
TypeLoc VarTypeLoc = VD->getTypeSourceInfo()->getTypeLoc();
const IdentifierInfo *Id = VD->getType().getBaseTypeIdentifier();
// handle a special case shown as below:
// x;
// *y[];
// (*z)[];
// void foo(void) {...}
// where x implicitly has type of int, whereas y has type of int *
if (!Id) {
SourceLocation EndLoc = VD->getLocation();
const char *Buf = SrcManager->getCharacterData(EndLoc);
int Offset = -1;
SourceLocation NewEndLoc = EndLoc.getLocWithOffset(Offset);
if (!NewEndLoc.isValid())
return EndLoc;
Buf--;
while (isspace(*Buf) || (*Buf == '*') || (*Buf == '(')) {
Offset--;
NewEndLoc = EndLoc.getLocWithOffset(Offset);
if (!NewEndLoc.isValid())
return EndLoc.getLocWithOffset(Offset+1);
Buf--;
}
return EndLoc.getLocWithOffset(Offset+1);
}
TypeLoc NextTL = VarTypeLoc.getNextTypeLoc();
while (!NextTL.isNull()) {
VarTypeLoc = NextTL;
NextTL = NextTL.getNextTypeLoc();
}
SourceRange TypeLocRange = VarTypeLoc.getSourceRange();
SourceLocation EndLoc = getEndLocationFromBegin(TypeLocRange);
TransAssert(EndLoc.isValid() && "Invalid EndLoc!");
const Type *Ty = VarTypeLoc.getTypePtr();
// I am not sure why, but for a declaration like below:
// unsigned int a; (or long long a;)
// TypeLoc.getBeginLoc() returns the position of 'u'
// TypeLoc.getEndLoc() also returns the position of 'u'
// The size of TypeLoc.getSourceRange() is 8, which is the
// length of "unsigned"
// Then we are getting trouble, because now EndLoc is right
// after 'd', but we need it points to the location after "int".
// skipPossibleTypeRange corrects the above deviation
// Or am I doing something horrible here?
EndLoc = skipPossibleTypeRange(Ty, EndLoc, VD->getLocation());
return EndLoc;
}
bool RewriteUtils::removeVarFromDeclStmt(DeclStmt *DS,
const VarDecl *VD,
Decl *PrevDecl,
bool IsFirstDecl)
{
SourceRange StmtRange = DS->getSourceRange();
// VD is the the only declaration, so it is safe to remove the entire stmt
if (DS->isSingleDecl()) {
return !(TheRewriter->RemoveText(StmtRange));
}
// handle the case where we could have implicit declaration of RecordDecl
// e.g.,
// foo (void) {
// struct S0 *s;
// ...;
// }
// in this case, struct S0 is implicitly declared
if (PrevDecl) {
if ( RecordDecl *RD = dyn_cast<RecordDecl>(PrevDecl) ) {
DeclGroup DGroup = DS->getDeclGroup().getDeclGroup();
IsFirstDecl = true;
if (!RD->getDefinition() && DGroup.size() == 2)
return !(TheRewriter->RemoveText(StmtRange));
}
}
SourceRange VarRange = VD->getSourceRange();
// VD is the first declaration in a declaration group.
// We keep the leading type string
if (IsFirstDecl) {
// We need to get the outermost TypeLocEnd instead of the StartLoc of
// a var name, because we need to handle the case below:
// int *x, *y;
// If we rely on the StartLoc of a var name, then we will make bad
// transformation like:
// int * *y;
SourceLocation NewStartLoc = getVarDeclTypeLocEnd(VD);
if (NewStartLoc.isMacroID()) {
NewStartLoc = SrcManager->getSpellingLoc(NewStartLoc);
const char *StartBuf = SrcManager->getCharacterData(NewStartLoc);
// Make sure we have at least one space before the name.
if (*StartBuf == ' ')
NewStartLoc = NewStartLoc.getLocWithOffset(1);
}
SourceLocation NewEndLoc = getEndLocationUntil(VarRange, ',');
if (NewEndLoc.isMacroID())
NewEndLoc = SrcManager->getSpellingLoc(NewEndLoc);
return
!(TheRewriter->RemoveText(SourceRange(NewStartLoc, NewEndLoc)));
}
TransAssert(PrevDecl && "PrevDecl cannot be NULL!");
SourceLocation VarEndLoc = VarRange.getEnd();
SourceRange PrevDeclRange = PrevDecl->getSourceRange();
SourceLocation PrevDeclEndLoc = getEndLocationUntil(PrevDeclRange, ',');
if (VarEndLoc.isMacroID())
VarEndLoc = SrcManager->getSpellingLoc(VarEndLoc);
if (PrevDeclEndLoc.isMacroID())
PrevDeclEndLoc = SrcManager->getSpellingLoc(PrevDeclEndLoc);
return !(TheRewriter->RemoveText(SourceRange(PrevDeclEndLoc, VarEndLoc)));
}
bool RewriteUtils::getExprString(const Expr *E,
std::string &ES)
{
SourceRange ExprRange = E->getSourceRange();
SourceLocation StartLoc = ExprRange.getBegin();
int RangeSize = TheRewriter->getRangeSize(ExprRange);
if (RangeSize == -1) {
if (StartLoc.isMacroID()) {
StartLoc = SrcManager->getFileLoc(StartLoc);
SourceLocation EndLoc = SrcManager->getFileLoc(ExprRange.getEnd());
RangeSize = TheRewriter->getRangeSize(SourceRange(StartLoc, EndLoc));
}
else {
return false;
}
}
const char *StartBuf = SrcManager->getCharacterData(StartLoc);
ES.assign(StartBuf, RangeSize);
const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(E);
// Keep the semantics of Comma operator
if (BinOp && (BinOp->getOpcode() == BO_Comma))
ES = "(" + ES + ")";
return true;
}
bool RewriteUtils::getStmtString(const Stmt *S,
std::string &Str)
{
SourceRange StmtRange = S->getSourceRange();
int RangeSize = TheRewriter->getRangeSize(StmtRange);
if (RangeSize == -1)
return false;
SourceLocation StartLoc = StmtRange.getBegin();
const char *StartBuf = SrcManager->getCharacterData(StartLoc);
Str.assign(StartBuf, RangeSize);
return true;
}
SourceLocation RewriteUtils::getExpansionEndLoc(SourceLocation EndLoc)
{
FileID FID = SrcManager->getFileID(EndLoc);
const SrcMgr::SLocEntry *Entry = &SrcManager->getSLocEntry(FID);
while (Entry->getExpansion().getExpansionLocStart().isMacroID()) {
EndLoc = Entry->getExpansion().getExpansionLocStart();
FID = SrcManager->getFileID(EndLoc);
Entry = &SrcManager->getSLocEntry(FID);
}
return Entry->getExpansion().getExpansionLocEnd();
}
bool RewriteUtils::replaceExpr(const Expr *E,
const std::string &ES)
{
SourceRange ExprRange = E->getSourceRange();
int RangeSize = TheRewriter->getRangeSize(ExprRange);
if (RangeSize == -1) {
SourceLocation StartLoc = ExprRange.getBegin();
if (!SrcManager->isMacroBodyExpansion(StartLoc))
return false;
StartLoc = SrcManager->getFileLoc(StartLoc);
SourceLocation EndLoc = ExprRange.getEnd();
if (SrcManager->isMacroBodyExpansion(EndLoc)) {
// FIXME: handle cases below:
// #define macro bar(1,2);
// int bar(int p1, int p2) { return p1 + p2; }
// void foo(void) { int x = macro }
EndLoc = getExpansionEndLoc(EndLoc);
}
return !(TheRewriter->ReplaceText(SourceRange(StartLoc, EndLoc), ES));
}
return !(TheRewriter->ReplaceText(ExprRange, ES));
}
bool RewriteUtils::replaceExprNotInclude(const Expr *E,
const std::string &ES)
{
SourceRange ExprRange = E->getSourceRange();
SourceLocation StartLoc = ExprRange.getBegin();
if (StartLoc.isMacroID()) {
StartLoc = SrcManager->getFileLoc(StartLoc);
SourceLocation EndLoc = ExprRange.getEnd();
TransAssert(EndLoc.isMacroID() && "EndLoc is not from a macro!");
ExprRange = SourceRange(StartLoc, SrcManager->getFileLoc(EndLoc));
}
TransAssert((TheRewriter->getRangeSize(ExprRange) != -1) &&
"Bad expr range!");
Rewriter::RewriteOptions Opts;
// We don't want to include the previously inserted string
Opts.IncludeInsertsAtBeginOfRange = false;
TheRewriter->RemoveText(ExprRange, Opts);
return !(TheRewriter->InsertText(StartLoc, ES));
}
std::string RewriteUtils::getStmtIndentString(Stmt *S,
SourceManager *SrcManager)
{
SourceLocation StmtStartLoc = S->getLocStart();
if (StmtStartLoc.isMacroID()) {
StmtStartLoc = SrcManager->getFileLoc(StmtStartLoc);
}
FileID FID;
unsigned StartOffset =
getLocationOffsetAndFileID(StmtStartLoc, FID, SrcManager);
StringRef MB = SrcManager->getBufferData(FID);
unsigned lineNo = SrcManager->getLineNumber(FID, StartOffset) - 1;
const SrcMgr::ContentCache *
Content = SrcManager->getSLocEntry(FID).getFile().getContentCache();
unsigned lineOffs = Content->SourceLineCache[lineNo];
// Find the whitespace at the start of the line.
StringRef indentSpace;
unsigned I = lineOffs;
while (isspace(MB[I]))
++I;
indentSpace = MB.substr(lineOffs, I-lineOffs);
return indentSpace;
}
bool RewriteUtils::addLocalVarToFunc(const std::string &VarStr,
FunctionDecl *FD)
{
Stmt *Body = FD->getBody();
TransAssert(Body && "NULL body for a function definition!");
std::string IndentStr;
StmtIterator I = Body->child_begin();
if (I == Body->child_end())
IndentStr = DefaultIndentStr;
else
IndentStr = getStmtIndentString((*I), SrcManager);
std::string NewVarStr = "\n" + IndentStr + VarStr;
SourceLocation StartLoc = Body->getLocStart();
return !(TheRewriter->InsertTextAfterToken(StartLoc, NewVarStr));
}
const char *RewriteUtils::getTmpVarNamePrefix(void)
{
return TmpVarNamePrefix;
}
bool RewriteUtils::addNewAssignStmtBefore(Stmt *BeforeStmt,
const std::string &VarName,
Expr *RHS,
bool NeedParen)
{
std::string IndentStr =
RewriteUtils::getStmtIndentString(BeforeStmt, SrcManager);
if (NeedParen) {
SourceRange StmtRange = BeforeStmt->getSourceRange();
SourceLocation LocEnd =
RewriteUtils::getEndLocationFromBegin(StmtRange);
TransAssert(LocEnd.isValid() && "Invalid LocEnd!");
std::string PostStr = "\n" + IndentStr + "}";
if (TheRewriter->InsertTextAfterToken(LocEnd, PostStr))
return false;
}
SourceLocation StmtLocStart = BeforeStmt->getLocStart();
if (StmtLocStart.isMacroID()) {
StmtLocStart = SrcManager->getFileLoc(StmtLocStart);
}
std::string ExprStr;
RewriteUtils::getExprString(RHS, ExprStr);
std::string AssignStmtStr;
if (NeedParen) {
AssignStmtStr = "{\n";
AssignStmtStr += IndentStr + " " + VarName + " = ";
AssignStmtStr += ExprStr;
AssignStmtStr += ";\n" + IndentStr + " ";
}
else {
AssignStmtStr = VarName + " = ";
AssignStmtStr += ExprStr;
AssignStmtStr += ";\n" + IndentStr;
}
return !(TheRewriter->InsertText(StmtLocStart,
AssignStmtStr, /*InsertAfter=*/false));
}
void RewriteUtils::indentAfterNewLine(StringRef Str,
std::string &NewStr,
const std::string &IndentStr)
{
SmallVector<StringRef, 20> StrVec;
Str.split(StrVec, "\n");
NewStr = "";
for(SmallVector<StringRef, 20>::iterator I = StrVec.begin(),
E = StrVec.end(); I != E; ++I) {
NewStr += ((*I).str() + "\n" + IndentStr);
}
}
void RewriteUtils::addOpenParenBeforeStmt(Stmt *S, const std::string &IndentStr)
{
SourceRange StmtRange = S->getSourceRange();
SourceLocation LocEnd =
RewriteUtils::getEndLocationFromBegin(StmtRange);
TransAssert(LocEnd.isValid() && "Invalid LocEnd!");
std::string PostStr = "\n" + IndentStr + "}";
TheRewriter->InsertTextAfterToken(LocEnd, PostStr);
}
bool RewriteUtils::addStringBeforeStmtInternal(Stmt *S,
const std::string &Str,
const std::string &IndentStr,
bool NeedParen)
{
std::string NewStr;
if (NeedParen) {
NewStr = "{\n";
}
NewStr += Str;
NewStr += "\n";
std::string IndentedStr;
indentAfterNewLine(NewStr, IndentedStr, IndentStr);
return !(TheRewriter->InsertText(S->getLocStart(),
IndentedStr, /*InsertAfter=*/false));
}
bool RewriteUtils::addStringBeforeStmt(Stmt *BeforeStmt,
const std::string &Str,
bool NeedParen)
{
std::string IndentStr =
RewriteUtils::getStmtIndentString(BeforeStmt, SrcManager);
if (NeedParen) {
addOpenParenBeforeStmt(BeforeStmt, IndentStr);
}
return addStringBeforeStmtInternal(BeforeStmt, Str,
IndentStr, NeedParen);
}
// Note that we can't use addStringBeforeStmt because
// we need to modify an expression in BeforeStmt. We have
// to do rewrite from end to begin to avoid crash.
bool RewriteUtils::addStringBeforeStmtAndReplaceExpr(Stmt *BeforeStmt,
const std::string &StmtStr,
const Expr *E, const std::string &ExprStr,
bool NeedParen)
{
std::string IndentStr =
RewriteUtils::getStmtIndentString(BeforeStmt, SrcManager);
if (NeedParen) {
addOpenParenBeforeStmt(BeforeStmt, IndentStr);
}
replaceExpr(E, ExprStr);
return addStringBeforeStmtInternal(BeforeStmt, StmtStr,
IndentStr, NeedParen);
}
bool RewriteUtils::addStringAfterStmt(Stmt *AfterStmt,
const std::string &Str)
{
std::string IndentStr =
RewriteUtils::getStmtIndentString(AfterStmt, SrcManager);
std::string NewStr = "\n" + IndentStr + Str;
SourceRange StmtRange = AfterStmt->getSourceRange();
SourceLocation LocEnd =
RewriteUtils::getEndLocationFromBegin(StmtRange);
TransAssert(LocEnd.isValid() && "Invalid LocEnd!");
return !(TheRewriter->InsertText(LocEnd, NewStr));
}
bool RewriteUtils::addStringAfterVarDecl(const VarDecl *VD,
const std::string &Str)
{
SourceRange VarRange = VD->getSourceRange();
SourceLocation LocEnd = getEndLocationAfter(VarRange, ';');
return !(TheRewriter->InsertText(LocEnd, "\n" + Str));
}
bool RewriteUtils::addStringAfterFuncDecl(const FunctionDecl *FD,
const std::string &Str)
{
SourceRange FDRange = FD->getSourceRange();
SourceLocation LocEnd = getEndLocationAfter(FDRange, ';');
return !(TheRewriter->InsertText(LocEnd, "\n" + Str));
}
// This function is an experimental one. It doesn't work
// if ND is a class of FunctionDecl, but I am not sure
// how it works for other types of NamedDecls
bool RewriteUtils::replaceNamedDeclName(const NamedDecl *ND,
const std::string &NameStr)
{
TransAssert(!isa<FunctionDecl>(ND) &&
"Please use replaceFunctionDeclName for renaming a FunctionDecl!");
TransAssert(!isa<UsingDirectiveDecl>(ND) &&
"Cannot use this function for renaming UsingDirectiveDecl");
SourceLocation NameLocStart = ND->getLocation();
return !(TheRewriter->ReplaceText(NameLocStart,
ND->getNameAsString().size(), NameStr));
}
bool RewriteUtils::replaceValueDecl(const ValueDecl *VD, const std::string &Str)
{
SourceRange Range = VD->getSourceRange();
unsigned RangeSize = TheRewriter->getRangeSize(Range);
return !(TheRewriter->ReplaceText(Range.getBegin(), RangeSize, Str));
}
bool RewriteUtils::replaceVarDeclName(VarDecl *VD,
const std::string &NameStr)
{
SourceLocation NameLocStart = VD->getLocation();
return !(TheRewriter->ReplaceText(NameLocStart,
VD->getNameAsString().size(), NameStr));
}
bool RewriteUtils::replaceFunctionDeclName(const FunctionDecl *FD,
const std::string &NameStr)
{
// We cannot naively use FD->getNameAsString() here.
// For example, for a template class
// template<typename T>
// class SomeClass {
// public:
// SomeClass() {}
// };
// applying getNameAsString() on SomeClass() gives us SomeClass<T>.
DeclarationNameInfo NameInfo = FD->getNameInfo();
DeclarationName DeclName = NameInfo.getName();
DeclarationName::NameKind K = DeclName.getNameKind();
TransAssert((K != DeclarationName::CXXDestructorName) &&
"Cannot rename CXXDestructorName here!");
std::string FDName = FD->getNameAsString();
size_t FDNameLen = FD->getNameAsString().length();
if (K == DeclarationName::CXXConstructorName) {
const Type *Ty = DeclName.getCXXNameType().getTypePtr();
if (Ty->getTypeClass() == Type::InjectedClassName) {
const CXXRecordDecl *CXXRD = Ty->getAsCXXRecordDecl();
std::string RDName = CXXRD->getNameAsString();
FDNameLen = FDName.find(RDName);
TransAssert((FDNameLen != std::string::npos) &&
"Cannot find RecordDecl Name!");
FDNameLen += RDName.length();
}
}
return !TheRewriter->ReplaceText(NameInfo.getLoc(),
FDNameLen,
NameStr);
}
bool RewriteUtils::replaceCXXDestructorDeclName(
const CXXDestructorDecl *DtorDecl,
const std::string &Name)
{
SourceLocation StartLoc = DtorDecl->getLocation();
const char *StartBuf = SrcManager->getCharacterData(StartLoc);
TransAssert((*StartBuf == '~') && "Invalid Destructor Location");
// FIXME: it's quite ugly, better to use clang's Lexer
unsigned Off = 0;
StartBuf++;
while (isspace(*StartBuf)) {
StartBuf++;
Off++;
}
std::string DName = DtorDecl->getNameAsString();
DeclarationNameInfo NameInfo = DtorDecl->getNameInfo();
DeclarationName DeclName = NameInfo.getName();
const Type *Ty = DeclName.getCXXNameType().getTypePtr();
size_t NameLen;
if (Ty->getTypeClass() == Type::InjectedClassName) {
const CXXRecordDecl *CXXRD = Ty->getAsCXXRecordDecl();
std::string RDName = CXXRD->getNameAsString();
NameLen = DName.find(RDName);
TransAssert((NameLen != std::string::npos) &&
"Cannot find RecordDecl Name!");
NameLen += RDName.length();
}
else {
NameLen = DName.length();
}
NameLen += Off;
return !TheRewriter->ReplaceText(StartLoc,
NameLen,
"~" + Name);
}
bool RewriteUtils::replaceRecordDeclName(const RecordDecl *RD,
const std::string &NameStr)
{
SourceLocation LocStart = RD->getLocation();
return !TheRewriter->ReplaceText(LocStart,
RD->getNameAsString().length(),
NameStr);
}
bool RewriteUtils::replaceVarTypeName(const VarDecl *VD,
const std::string &NameStr)
{
const IdentifierInfo *TypeId = VD->getType().getBaseTypeIdentifier();
SourceLocation LocStart = getVarDeclTypeLocBegin(VD);
return !TheRewriter->ReplaceText(LocStart,
TypeId->getLength(),
NameStr);
}
void RewriteUtils::getStringBetweenLocs(std::string &Str,
SourceLocation LocStart,
SourceLocation LocEnd)
{
const char *StartBuf = SrcManager->getCharacterData(LocStart);
const char *EndBuf = SrcManager->getCharacterData(LocEnd);
TransAssert(StartBuf < EndBuf);
size_t Off = EndBuf - StartBuf;
Str.assign(StartBuf, Off);
}
void RewriteUtils::getStringBetweenLocsAfterStart(std::string &Str,
SourceLocation LocStart,
SourceLocation LocEnd)
{
const char *StartBuf = SrcManager->getCharacterData(LocStart);
const char *EndBuf = SrcManager->getCharacterData(LocEnd);
StartBuf++;
TransAssert(StartBuf <= EndBuf);
size_t Off = EndBuf - StartBuf;
Str.assign(StartBuf, Off);
}
bool RewriteUtils::getEntireDeclGroupStrAndRemove(DeclGroupRef DGR,
std::string &Str)
{
Decl *FirstD, *LastD;
if (DGR.isSingleDecl()) {
FirstD = DGR.getSingleDecl();
LastD = FirstD;
}
else {
DeclGroupRef::iterator I = DGR.begin();
FirstD = (*I);
DeclGroupRef::iterator E = DGR.end();
--E;
LastD = (*E);
}
SourceRange FirstRange = FirstD->getSourceRange();
SourceLocation StartLoc = FirstRange.getBegin();
SourceRange LastRange = LastD->getSourceRange();
SourceLocation EndLoc = getEndLocationUntil(LastRange, ';');
// This isn't really good, but if EndLoc is invalid, what can we do?
if (EndLoc.isInvalid()) {
unsigned Off = 0;
const char *StartBuf = SrcManager->getCharacterData(StartLoc);
while ((*StartBuf != '\n') && (*StartBuf != ';') && (*StartBuf != '\0')) {
Off++;
StartBuf++;
}
assert(Off && "Zero offset!");
EndLoc = StartLoc.getLocWithOffset(Off);
}
getStringBetweenLocs(Str, StartLoc, EndLoc);
return !TheRewriter->RemoveText(SourceRange(StartLoc, EndLoc));
}
// This function skips type specifiers
bool RewriteUtils::getDeclGroupStrAndRemove(DeclGroupRef DGR,
std::string &Str)
{
if (DGR.isSingleDecl()) {
Decl *D = DGR.getSingleDecl();
VarDecl *VD = dyn_cast<VarDecl>(D);
TransAssert(VD && "Bad VarDecl!");
// We need to get the outermost TypeLocEnd instead of the StartLoc of
// a var name, because we need to handle the case below:
// int *x;
// int *y;
// If we rely on the StartLoc of a var name, then we will make bad
// transformation like:
// int *x, y;
SourceLocation TypeLocEnd = getVarDeclTypeLocEnd(VD);
if (TypeLocEnd.isMacroID())
TypeLocEnd = SrcManager->getFileLoc(TypeLocEnd);
SourceRange VarRange = VD->getSourceRange();
SourceLocation LocEnd = getEndLocationUntil(VarRange, ';');
getStringBetweenLocs(Str, TypeLocEnd, LocEnd);
SourceLocation StartLoc = VarRange.getBegin();
if (StartLoc.isMacroID())
StartLoc = SrcManager->getFileLoc(StartLoc);
SourceLocation NewEndLoc = getLocationAfterSkiping(LocEnd, ';');
return !(TheRewriter->RemoveText(SourceRange(StartLoc, NewEndLoc)));
}
TransAssert(DGR.getDeclGroup().size() > 1);
DeclGroupRef::iterator I = DGR.begin();
DeclGroupRef::iterator E = DGR.end();
--E;
Decl *FirstD = (*I);
VarDecl *FirstVD = dyn_cast<VarDecl>(FirstD);
Decl *LastD = (*E);
VarDecl *LastVD = dyn_cast<VarDecl>(LastD);
TransAssert(FirstVD && "Bad First VarDecl!");
TransAssert(LastVD && "Bad First VarDecl!");
SourceLocation TypeLocEnd = getVarDeclTypeLocEnd(FirstVD);
SourceRange LastVarRange = LastVD->getSourceRange();
SourceLocation LastEndLoc = getEndLocationUntil(LastVarRange, ';');
getStringBetweenLocs(Str, TypeLocEnd, LastEndLoc);
SourceLocation StartLoc = FirstVD->getLocStart();
SourceLocation NewLastEndLoc = getLocationAfterSkiping(LastEndLoc, ';');
return !(TheRewriter->RemoveText(SourceRange(StartLoc, NewLastEndLoc)));
}
SourceLocation RewriteUtils::getDeclGroupRefEndLoc(DeclGroupRef DGR)
{
Decl *LastD;
if (DGR.isSingleDecl()) {
LastD = DGR.getSingleDecl();
}
else {
DeclGroupRef::iterator E = DGR.end();
--E;
LastD = (*E);
}
#if 0
VarDecl *VD = dyn_cast<VarDecl>(LastD);
TransAssert(VD && "Bad VD!");
SourceRange VarRange = VD->getSourceRange();
return getEndLocationFromBegin(VarRange);
#endif
// The LastD could be a RecordDecl
SourceRange Range = LastD->getSourceRange();
SourceLocation EndLoc = getEndLocationFromBegin(Range);
TransAssert(EndLoc.isValid() && "Invalid EndLoc!");
return EndLoc;
}
SourceLocation RewriteUtils::getDeclStmtEndLoc(DeclStmt *DS)
{
DeclGroupRef DGR = DS->getDeclGroup();
return getDeclGroupRefEndLoc(DGR);
}
bool RewriteUtils::getDeclStmtStrAndRemove(DeclStmt *DS,
std::string &Str)
{
DeclGroupRef DGR = DS->getDeclGroup();
return getDeclGroupStrAndRemove(DGR, Str);
}
bool RewriteUtils::removeAStarBefore(const Decl *D)
{
SourceLocation LocStart = D->getLocation();
const char *StartBuf = SrcManager->getCharacterData(LocStart);
int Offset = 0;
while (*StartBuf != '*') {
StartBuf--;
Offset--;
}
SourceLocation StarLoc = LocStart.getLocWithOffset(Offset);
return !TheRewriter->RemoveText(StarLoc, 1);
}
bool RewriteUtils::removeASymbolAfter(const Expr *E,
char Symbol)
{
SourceRange ExprRange = E->getSourceRange();
SourceLocation LocStart = ExprRange.getBegin();
const char *StartBuf = SrcManager->getCharacterData(LocStart);
int Offset = 0;
while (*StartBuf != Symbol) {
StartBuf++;
Offset++;
}
SourceLocation StarLoc = LocStart.getLocWithOffset(Offset);
return !TheRewriter->RemoveText(StarLoc, 1);
}
bool RewriteUtils::removeAStarAfter(const Expr *E)
{
return removeASymbolAfter(E, '*');
}
bool RewriteUtils::removeAnAddrOfAfter(const Expr *E)
{
return removeASymbolAfter(E, '&');
}
bool RewriteUtils::insertAnAddrOfBefore(const Expr *E)
{
SourceRange ExprRange = E->getSourceRange();
SourceLocation LocStart = ExprRange.getBegin();
return !TheRewriter->InsertTextBefore(LocStart, "&");
}
bool RewriteUtils::insertAStarBefore(const Expr *E)
{
SourceRange ExprRange = E->getSourceRange();
SourceLocation LocStart = ExprRange.getBegin();
return !TheRewriter->InsertTextBefore(LocStart, "*");
}
bool RewriteUtils::removeVarInitExpr(const VarDecl *VD)
{
TransAssert(VD->hasInit() && "VarDecl doesn't have an Init Expr!");
SourceLocation NameStartLoc = VD->getLocation();
SourceLocation InitStartLoc = getLocationUntil(NameStartLoc, '=');
const Expr *Init = VD->getInit();
SourceRange ExprRange = Init->getSourceRange();
SourceLocation InitEndLoc = ExprRange.getEnd();
// handle macro, e.g.:
// #define NULL 0
// void foo(void)
// {
// int *p = NULL;
// }
if (SrcManager->isMacroBodyExpansion(InitEndLoc)) {
InitEndLoc = SrcManager->getFileLoc(InitEndLoc);
}
return !TheRewriter->RemoveText(SourceRange(InitStartLoc, InitEndLoc));
}
SourceLocation RewriteUtils::getMacroExpansionLoc(SourceLocation Loc) {
if (SrcManager->isMacroBodyExpansion(Loc))
return SrcManager->getFileLoc(Loc);
return Loc;
}
bool RewriteUtils::removeVarDecl(const VarDecl *VD,
DeclGroupRef DGR)
{
SourceRange VarRange = VD->getSourceRange();
if (DGR.isSingleDecl()) {
SourceLocation StartLoc = getMacroExpansionLoc(VarRange.getBegin());
SourceLocation EndLoc = getEndLocationUntil(VarRange, ';');
// in case the previous EndLoc is invalid, for example,
// VarRange could have bad EndLoc value
if (EndLoc.isInvalid())
EndLoc = getLocationUntil(StartLoc, ';');
return !(TheRewriter->RemoveText(SourceRange(StartLoc, EndLoc)));
}
DeclGroupRef::const_iterator I = DGR.begin();
const VarDecl *FirstVD = dyn_cast<VarDecl>(*I);
// dyn_cast (*I) to VarDecl could fail, because it could be a struct decl,
// e.g., struct S1 { int f1; } s2 = {1}, where FirstDecl is
// struct S1 {int f1;}. We need to skip it
if (!FirstVD) {
// handle the case where we could have implicit declaration of RecordDecl
// e.g.,
// struct S0 *s;
// ...;
// in this case, struct S0 is implicitly declared
if ( RecordDecl *RD = dyn_cast<RecordDecl>(*I) ) {
if (!RD->getDefinition() && DGR.getDeclGroup().size() == 2) {
SourceLocation StartLoc = VarRange.getBegin();
SourceLocation EndLoc = getEndLocationUntil(VarRange, ';');
return !(TheRewriter->RemoveText(SourceRange(StartLoc, EndLoc)));
}
}
++I;
TransAssert((I != DGR.end()) && "Bad Decl!");
FirstVD = dyn_cast<VarDecl>(*I);
TransAssert(FirstVD && "Invalid Var Decl!");
if (VD == FirstVD) {
SourceLocation StartLoc = VD->getLocation();
SourceLocation EndLoc =
getEndLocationUntil(VarRange, ',');
return !(TheRewriter->RemoveText(SourceRange(StartLoc, EndLoc)));
}
}
else if (VD == FirstVD) {
SourceLocation StartLoc = getVarDeclTypeLocEnd(VD);
SourceLocation EndLoc =
getEndLocationUntil(VarRange, ',');
return !(TheRewriter->RemoveText(SourceRange(StartLoc, EndLoc)));
}
const VarDecl *PrevVD = FirstVD;
const VarDecl *CurrVD = NULL;
++I;
DeclGroupRef::const_iterator E = DGR.end();
for (; I != E; ++I) {
CurrVD = dyn_cast<VarDecl>(*I);
TransAssert(CurrVD && "Not a valid VarDecl!");
if (VD == CurrVD)
break;
PrevVD = CurrVD;
}
TransAssert((VD == CurrVD) && "Cannot find VD!");
SourceLocation VarEndLoc = VarRange.getEnd();
SourceRange PrevDeclRange = PrevVD->getSourceRange();
SourceLocation PrevDeclEndLoc =
getEndLocationUntil(PrevDeclRange, ',');
return !(TheRewriter->RemoveText(SourceRange(PrevDeclEndLoc, VarEndLoc)));
}
void RewriteUtils::getTmpTransName(unsigned Postfix, std::string &Name)
{
std::stringstream SS;
SS << getTmpVarNamePrefix() << Postfix;
Name = SS.str();
}
bool RewriteUtils::insertStringBeforeFunc(const FunctionDecl *FD,
const std::string &Str)
{
SourceRange FuncRange;
if (FunctionTemplateDecl *TmplD = FD->getDescribedFunctionTemplate()) {
FuncRange = TmplD->getSourceRange();
}
else {
FuncRange = FD->getSourceRange();
}
SourceLocation StartLoc = FuncRange.getBegin();
return !TheRewriter->InsertTextBefore(StartLoc, Str);
}
bool RewriteUtils::insertStringBeforeTemplateDecl(const TemplateDecl *D,
const std::string &Str)
{
SourceRange Range = D->getSourceRange();
SourceLocation StartLoc = Range.getBegin();
TransAssert(StartLoc.isValid() && "Invalid template decl StartLoc!");
return !TheRewriter->InsertTextBefore(StartLoc, Str);
}
bool RewriteUtils::replaceUnionWithStruct(const NamedDecl *ND)
{
SourceRange NDRange = ND->getSourceRange();
int RangeSize = TheRewriter->getRangeSize(NDRange);
TransAssert((RangeSize != -1) && "Bad Range!");
SourceLocation StartLoc = NDRange.getBegin();
const char *StartBuf = SrcManager->getCharacterData(StartLoc);
std::string TmpStr(StartBuf, RangeSize);
std::string UStr = "union";
size_t Pos = TmpStr.find(UStr);
if (Pos == std::string::npos)
return true;
if (Pos != 0)
StartLoc = StartLoc.getLocWithOffset(Pos);
return !TheRewriter->ReplaceText(StartLoc, UStr.size(), "struct");
}
bool RewriteUtils::removeIfAndCond(const IfStmt *IS)
{
SourceLocation IfLoc = IS->getIfLoc();
const Stmt *ThenStmt = IS->getThen();
TransAssert(ThenStmt && "NULL ThenStmt!");
SourceLocation ThenLoc = ThenStmt->getLocStart();
SourceLocation EndLoc = ThenLoc.getLocWithOffset(-1);
Rewriter::RewriteOptions Opts;
// We don't want to include the previously inserted string
Opts.IncludeInsertsAtBeginOfRange = false;
return !TheRewriter->RemoveText(SourceRange(IfLoc, EndLoc), Opts);
}
bool RewriteUtils::removeArraySubscriptExpr(const Expr *E)
{
SourceRange ERange = E->getSourceRange();
SourceLocation StartLoc = ERange.getBegin();
const char *StartBuf = SrcManager->getCharacterData(StartLoc);
int Offset = 0;
while (*StartBuf != '[') {
StartBuf--;
Offset--;
}
StartLoc = StartLoc.getLocWithOffset(Offset);
SourceLocation EndLoc = ERange.getEnd();
EndLoc = EndLoc.getLocWithOffset(1);
if (EndLoc.isInvalid())
return !TheRewriter->RemoveText(SourceRange(StartLoc, ERange.getEnd()));
SourceLocation RBLoc = getLocationUntil(EndLoc, ']');
if (RBLoc.isInvalid())
return !TheRewriter->RemoveText(SourceRange(StartLoc, EndLoc));
return !TheRewriter->RemoveText(SourceRange(StartLoc, RBLoc));
}
bool RewriteUtils::getFunctionDefStrAndRemove(const FunctionDecl *FD,
std::string &Str)
{
SourceRange FDRange = FD->getSourceRange();
int RangeSize = TheRewriter->getRangeSize(FDRange);
if (RangeSize == -1)
return false;
SourceLocation StartLoc = FDRange.getBegin();
const char *StartBuf = SrcManager->getCharacterData(StartLoc);
Str.assign(StartBuf, RangeSize);
TheRewriter->RemoveText(FDRange);
return true;
}
bool RewriteUtils::getFunctionDeclStrAndRemove(const FunctionDecl *FD,
std::string &Str)
{
TransAssert(!FD->isThisDeclarationADefinition() &&
"FD cannot be a definition!");
SourceRange FDRange = FD->getSourceRange();
SourceLocation StartLoc = FDRange.getBegin();
SourceLocation EndLoc = getEndLocationUntil(FDRange, ';');
getStringBetweenLocs(Str, StartLoc, EndLoc);
return !TheRewriter->RemoveText(SourceRange(StartLoc, EndLoc));
}
bool RewriteUtils::replaceFunctionDefWithStr(const FunctionDecl *FD,
const std::string &Str)
{
const Stmt *Body = FD->getBody();
TransAssert(Body && "FunctionDecl is not a definition!");
return !TheRewriter->ReplaceText(Body->getSourceRange(), Str);
}
// FIXME: probably we don't need this function, because we could use
// removeDecl insteadly
bool RewriteUtils::removeFieldDecl(const FieldDecl *FD)
{
SourceRange Range = FD->getSourceRange();
SourceLocation StartLoc = Range.getBegin();
SourceLocation EndLoc = getEndLocationUntil(Range, ';');
SourceLocation CurlyEndLoc = getEndLocationUntil(Range, '}');
// handle cases like:
// struct {
// int f <- no semicolon here
// };
const char *SemiPos = SrcManager->getCharacterData(EndLoc);
const char *CurlyPos = SrcManager->getCharacterData(CurlyEndLoc);
if (SemiPos > CurlyPos) {
EndLoc = CurlyEndLoc.getLocWithOffset(-1);
}
// If EndLoc is invalid, just remove one char to avoid crash
if (EndLoc.isInvalid()) {
EndLoc = StartLoc;
}
return !(TheRewriter->RemoveText(SourceRange(StartLoc, EndLoc)));
}
bool RewriteUtils::removeDecl(const Decl *D)
{
SourceRange Range = D->getSourceRange();
TransAssert((TheRewriter->getRangeSize(Range) != -1) &&
"Bad UsingDecl SourceRange!");
SourceLocation StartLoc = Range.getBegin();
SourceLocation EndLoc = getEndLocationUntil(Range, ';');
return !(TheRewriter->RemoveText(SourceRange(StartLoc, EndLoc)));
}
bool RewriteUtils::replaceCXXDtorCallExpr(const CXXMemberCallExpr *CE,
std::string &Name)
{
const CXXMethodDecl *MD = CE->getMethodDecl();
const CXXDestructorDecl *DtorDecl = dyn_cast<CXXDestructorDecl>(MD);
if (!DtorDecl)
return true;
Name = "~" + Name;
std::string ExprStr;
getExprString(CE, ExprStr);
std::string OldDtorName = DtorDecl->getNameAsString();
size_t Pos = ExprStr.find(OldDtorName);
TransAssert((Pos != std::string::npos) && "Bad Name Position!");
if (Pos == 0)
return true;
SourceLocation StartLoc = CE->getLocStart();
StartLoc = StartLoc.getLocWithOffset(Pos);
return !(TheRewriter->ReplaceText(StartLoc, OldDtorName.size(), Name));
}
bool RewriteUtils::removeSpecifier(NestedNameSpecifierLoc Loc)
{
SourceRange LocRange = Loc.getLocalSourceRange();
TransAssert((TheRewriter->getRangeSize(LocRange) != -1) &&
"Bad NestedNameSpecifierLoc Range!");
return !(TheRewriter->RemoveText(LocRange));
}
bool RewriteUtils::replaceSpecifier(NestedNameSpecifierLoc Loc,
const std::string &Name)
{
SourceRange LocRange = Loc.getLocalSourceRange();
TransAssert((TheRewriter->getRangeSize(LocRange) != -1) &&
"Bad NestedNameSpecifierLoc Range!");
return !(TheRewriter->ReplaceText(LocRange, Name + "::"));
}
void RewriteUtils::getQualifierAsString(NestedNameSpecifierLoc Loc,
std::string &Str)
{
SourceLocation StartLoc = Loc.getBeginLoc();
TransAssert(StartLoc.isValid() && "Bad StartLoc for NestedNameSpecifier!");
SourceRange Range = Loc.getSourceRange();
int Len = TheRewriter->getRangeSize(Range);
const char *StartBuf = SrcManager->getCharacterData(StartLoc);
Str.assign(StartBuf, Len);
}
void RewriteUtils::getSpecifierAsString(NestedNameSpecifierLoc Loc,
std::string &Str)
{
SourceLocation StartLoc = Loc.getBeginLoc();
TransAssert(StartLoc.isValid() && "Bad StartLoc for NestedNameSpecifier!");
const char *StartBuf = SrcManager->getCharacterData(StartLoc);
const char *OrigBuf = StartBuf;
unsigned int Len = 0;
while (!isspace(*StartBuf) && (*StartBuf != ':')) {
StartBuf++;
Len++;
}
Str.assign(OrigBuf, Len);
}
bool RewriteUtils::replaceRecordType(RecordTypeLoc &RTLoc,
const std::string &Name)
{
const IdentifierInfo *TypeId = RTLoc.getType().getBaseTypeIdentifier();
SourceLocation LocStart = RTLoc.getLocStart();
// Loc could be invalid, for example:
// class AAA { };
// class BBB:AAA {
// public:
// BBB () { }
// };
// In Clang's internal representation, BBB's Ctor is BBB() : AAA() {}
// The implicit AAA() will be visited here
// This is the only case where RTLoc is invalid, so the question is -
// Is the guard below too strong? It is possible it could mask other
// potential bugs?
if (LocStart.isInvalid())
return true;
return !(TheRewriter->ReplaceText(LocStart, TypeId->getLength(), Name));
}
bool RewriteUtils::isTheFirstDecl(const VarDecl *VD)
{
SourceRange Range = VD->getSourceRange();
SourceLocation StartLoc = Range.getBegin();
SourceLocation NameStartLoc = VD->getLocation();
const char *StartBuf = SrcManager->getCharacterData(StartLoc);
const char *NameStartBuf = SrcManager->getCharacterData(NameStartLoc);
while (StartBuf != NameStartBuf) {
if (*StartBuf == ',')
return false;
StartBuf++;
}
return true;
}
bool RewriteUtils::isSingleDecl(const VarDecl *VD)
{
if (!isTheFirstDecl(VD))
return false;
SourceRange Range = VD->getSourceRange();
SourceLocation StartLoc = Range.getBegin();
int RangeSize = TheRewriter->getRangeSize(Range);
SourceLocation EndLoc = StartLoc.getLocWithOffset(RangeSize);
const char *EndBuf = SrcManager->getCharacterData(EndLoc);
while (isspace(*EndBuf))
EndBuf++;
return (*EndBuf == ';');
}
// In case we don't know if VD is in a single decl group,
// also we don't know if VD is the first decl or not.
// once this version is well-tested, probably we should remove
// bool RewriteUtils::removeVarDecl(const VarDecl *VD,
// DeclGroupRef DGR)
bool RewriteUtils::removeVarDecl(const VarDecl *VD)
{
if (isSingleDecl(VD)) {
return removeDecl(VD);
}
SourceRange VarRange = VD->getSourceRange();
// VD is the first declaration in a declaration group.
// We keep the leading type string
if (isTheFirstDecl(VD)) {
// We need to get the outermost TypeLocEnd instead of the StartLoc of
// a var name, because we need to handle the case below:
// int *x, *y;
// If we rely on the StartLoc of a var name, then we will make bad
// transformation like:
// int * *y;
SourceLocation NewStartLoc = getVarDeclTypeLocEnd(VD);
SourceLocation NewEndLoc = getEndLocationUntil(VarRange, ',');
return
!(TheRewriter->RemoveText(SourceRange(NewStartLoc, NewEndLoc)));
}
SourceLocation NameLoc = VD->getLocation();
SourceLocation VarStartLoc = VarRange.getBegin();
const char *NameStartBuf = SrcManager->getCharacterData(NameLoc);
const char *VarStartBuf = SrcManager->getCharacterData(VarStartLoc);
int Offset = 0;
TransAssert((VarStartBuf < NameStartBuf) && "Bad Name Location!");
while (NameStartBuf != VarStartBuf) {
if (*NameStartBuf == ',')
break;
Offset--;
NameStartBuf--;
}
TransAssert((VarStartBuf < NameStartBuf) && "Cannot find comma!");
SourceLocation PrevDeclEndLoc = NameLoc.getLocWithOffset(Offset);
SourceLocation VarEndLoc = VarRange.getEnd();
return !(TheRewriter->RemoveText(SourceRange(PrevDeclEndLoc, VarEndLoc)));
}
bool RewriteUtils::removeTextFromLeftAt(SourceRange Range, char C,
SourceLocation EndLoc)
{
SourceLocation StartLoc = Range.getBegin();
const char *StartBuf = SrcManager->getCharacterData(StartLoc);
int Offset = 0;
while (*StartBuf != C) {
StartBuf--;
Offset--;
}
StartLoc = StartLoc.getLocWithOffset(Offset);
return !TheRewriter->RemoveText(SourceRange(StartLoc, EndLoc));
}
SourceLocation RewriteUtils::getLocationFromLeftUntil(SourceLocation StartLoc,
char C)
{
const char *StartBuf = SrcManager->getCharacterData(StartLoc);
int Offset = 0;
while (*StartBuf != C) {
StartBuf--;
Offset--;
}
return StartLoc.getLocWithOffset(Offset);
}
bool RewriteUtils::removeTextUntil(SourceRange Range, char C)
{
SourceLocation StartLoc = Range.getBegin();
// I don't know the reason, but seems Clang treats the following two
// cases differently:
// (1) template<bool, typename>
// in this case, the RangeSize is 5, which includes the ','
// (2) template<typename, typename>
// in this case, the RangeSize is 8, which excludes the comma
SourceLocation EndLoc = Range.getEnd();
const char *EndBuf = SrcManager->getCharacterData(EndLoc);
if (*EndBuf != C)
EndLoc = getEndLocationUntil(Range, C);
return !TheRewriter->RemoveText(SourceRange(StartLoc, EndLoc));
}
bool RewriteUtils::removeCXXCtorInitializer(const CXXCtorInitializer *Init,
unsigned Index, unsigned NumInits)
{
SourceRange Range = Init->getSourceRange();
SourceLocation EndLoc = Init->getRParenLoc();
if (Index == 0) {
if (NumInits == 1)
return removeTextFromLeftAt(Range, ':', EndLoc);
else
return removeTextUntil(Range, ',');
}
else {
return removeTextFromLeftAt(Range, ',', EndLoc);
}
}
bool RewriteUtils::removeClassDecls(const CXXRecordDecl *CXXRD)
{
for (CXXRecordDecl::redecl_iterator I = CXXRD->redecls_begin(),
E = CXXRD->redecls_end(); I != E; ++I) {
SourceRange Range = (*I)->getSourceRange();
SourceLocation LocEnd;
if ((*I)->isThisDeclarationADefinition()) {
LocEnd = (*I)->getBraceRange().getEnd();
if (LocEnd.isValid())
LocEnd = getLocationUntil(LocEnd, ';');
else
LocEnd = getEndLocationUntil(Range, ';');
}
else {
LocEnd = getEndLocationUntil(Range, ';');
}
TheRewriter->RemoveText(SourceRange(Range.getBegin(), LocEnd));
}
return true;
}
bool RewriteUtils::removeClassTemplateDecls(const ClassTemplateDecl *TmplD)
{
for (ClassTemplateDecl::redecl_iterator I = TmplD->redecls_begin(),
E = TmplD->redecls_end(); I != E; ++I) {
const CXXRecordDecl *CXXRD =
dyn_cast<CXXRecordDecl>((*I)->getTemplatedDecl());
TransAssert(CXXRD && "Invalid class template!");
SourceRange Range = (*I)->getSourceRange();
SourceLocation LocEnd;
if (CXXRD->isThisDeclarationADefinition()) {
LocEnd = CXXRD->getBraceRange().getEnd();
LocEnd = getLocationUntil(LocEnd, ';');
}
else {
LocEnd = getEndLocationUntil(Range, ';');
}
TheRewriter->RemoveText(SourceRange(Range.getBegin(), LocEnd));
}
return true;
}
bool RewriteUtils::replaceCXXMethodNameAfterQualifier(
const NestedNameSpecifierLoc *QualLoc,
const CXXMethodDecl *MD,
const std::string &NewName)
{
SourceLocation EndLoc = QualLoc->getEndLoc();
const char *EndBuf = SrcManager->getCharacterData(EndLoc);
unsigned int Offset = 0;
while (isspace(*EndBuf) || (*EndBuf == ':')) {
EndBuf++;
Offset++;
}
EndLoc = EndLoc.getLocWithOffset(Offset);
TheRewriter->ReplaceText(EndLoc, MD->getNameAsString().size(), NewName);
return true;
}
|