Debian Codegraph @

clang_delta/RewriteUtils.cpp

raw symbols SCIP
1 //===----------------------------------------------------------------------===//
2 //
3 // Copyright (c) 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020 The University of Utah
4 // All rights reserved.
5 //
6 // This file is distributed under the University of Illinois Open Source
7 // License. See the file COPYING for details.
8 //
9 //===----------------------------------------------------------------------===//
10
11 #if HAVE_CONFIG_H
12 # include <config.h>
13 #endif
14
15 #include "RewriteUtils.h"
16
17 #include <cctype>
18 #include <sstream>
19 #include "clang/Basic/SourceManager.h"
20 #include "clang/Rewrite/Core/Rewriter.h"
21 #include "clang/AST/Decl.h"
22 #include "clang/AST/DeclCXX.h"
23 #include "clang/AST/DeclTemplate.h"
24 #include "clang/AST/Expr.h"
25 #include "clang/AST/TypeLoc.h"
26 #include "clang/AST/ExprCXX.h"
27
28 using namespace clang;
29
30 static const char *DefaultIndentStr = " ";
31
32 RewriteUtils *RewriteUtils::Instance;
33
34 const char *RewriteUtils::TmpVarNamePrefix = "__trans_tmp_";
35
36 RewriteUtils *RewriteUtils::GetInstance(Rewriter *RW)
37 {
38 if (RewriteUtils::Instance) {
39 RewriteUtils::Instance->TheRewriter = RW;
40 RewriteUtils::Instance->SrcManager = &(RW->getSourceMgr());
41 return RewriteUtils::Instance;
42 }
43
44 RewriteUtils::Instance = new RewriteUtils();
45 assert(RewriteUtils::Instance);
46
47 RewriteUtils::Instance->TheRewriter = RW;
48 RewriteUtils::Instance->SrcManager = &(RW->getSourceMgr());
49 return RewriteUtils::Instance;
50 }
51
52 void RewriteUtils::Finalize(void)
53 {
54 if (RewriteUtils::Instance) {
55 delete RewriteUtils::Instance;
56 RewriteUtils::Instance = NULL;
57 }
58 }
59
60 SourceLocation RewriteUtils::getRealLocation(SourceLocation Loc) {
61 if (Loc.isMacroID()) {
62 return SrcManager->getExpansionLoc(Loc);
63 }
64 return Loc;
65 }
66
67 SourceRange RewriteUtils::getRealSourceRange(SourceRange Range) {
68 SourceLocation StartLoc = Range.getBegin();
69 SourceLocation EndLoc = Range.getEnd();
70 return SourceRange(getRealLocation(StartLoc), getRealLocation(EndLoc));
71 }
72
73 // copied from Rewriter.cpp
74 unsigned RewriteUtils::getLocationOffsetAndFileID(SourceLocation Loc,
75 FileID &FID,
76 SourceManager *SrcManager)
77 {
78 assert(Loc.isValid() && "Invalid location");
79 std::pair<FileID,unsigned> V = SrcManager->getDecomposedLoc(Loc);
80 FID = V.first;
81 return V.second;
82 }
83
84 unsigned RewriteUtils::getOffsetBetweenLocations(SourceLocation StartLoc,
85 SourceLocation EndLoc,
86 SourceManager *SrcManager)
87 {
88 FileID FID;
89 unsigned StartOffset =
90 getLocationOffsetAndFileID(StartLoc, FID, SrcManager);
91 unsigned EndOffset =
92 getLocationOffsetAndFileID(EndLoc, FID, SrcManager);
93 TransAssert((EndOffset >= StartOffset) && "Bad locations!");
94 return (EndOffset - StartOffset);
95 }
96
97 SourceLocation RewriteUtils::getEndLocationFromBegin(SourceRange Range)
98 {
99 SourceLocation StartLoc = Range.getBegin();
100 SourceLocation EndLoc = Range.getEnd();
101 if (StartLoc.isInvalid())
102 return StartLoc;
103 if (EndLoc.isInvalid())
104 return EndLoc;
105
106 if (StartLoc.isMacroID())
107 StartLoc = SrcManager->getFileLoc(StartLoc);
108 if (EndLoc.isMacroID())
109 EndLoc = SrcManager->getFileLoc(EndLoc);
110
111 SourceRange NewRange(StartLoc, EndLoc);
112 int LocRangeSize = TheRewriter->getRangeSize(NewRange);
113 if (LocRangeSize == -1)
114 return NewRange.getEnd();
115
116 return StartLoc.getLocWithOffset(LocRangeSize);
117 }
118
119 int RewriteUtils::getOffsetUntil(const char *Buf, char Symbol)
120 {
121 int Offset = 0;
122 while (*Buf != Symbol) {
123 Buf++;
124 if (*Buf == '\0')
125 break;
126 Offset++;
127 }
128 return Offset;
129 }
130
131 int RewriteUtils::getSkippingOffset(const char *Buf, char Symbol)
132 {
133 int Offset = 0;
134 while (*Buf == Symbol) {
135 Buf++;
136 if (*Buf == '\0')
137 break;
138 Offset++;
139 }
140 return Offset;
141 }
142
143 SourceLocation RewriteUtils::getEndLocationUntil(SourceRange Range,
144 char Symbol)
145 {
146 SourceLocation EndLoc = getEndLocationFromBegin(Range);
147 if (EndLoc.isInvalid())
148 return EndLoc;
149
150 const char *EndBuf = SrcManager->getCharacterData(EndLoc);
151 int Offset = getOffsetUntil(EndBuf, Symbol);
152 return EndLoc.getLocWithOffset(Offset);
153 }
154
155 SourceLocation RewriteUtils::getLocationUntil(SourceLocation Loc,
156 char Symbol)
157 {
158 const char *Buf = SrcManager->getCharacterData(Loc);
159 int Offset = getOffsetUntil(Buf, Symbol);
160 return Loc.getLocWithOffset(Offset);
161 }
162
163 SourceLocation RewriteUtils::getEndLocationAfter(SourceRange Range,
164 char Symbol)
165 {
166 SourceLocation EndLoc = getEndLocationFromBegin(Range);
167 if (EndLoc.isInvalid())
168 return EndLoc;
169
170 const char *EndBuf = SrcManager->getCharacterData(EndLoc);
171 int Offset = getOffsetUntil(EndBuf, Symbol);
172 Offset++;
173 return EndLoc.getLocWithOffset(Offset);
174 }
175
176 SourceLocation RewriteUtils::getLocationAfter(SourceLocation Loc,
177 char Symbol)
178 {
179 const char *Buf = SrcManager->getCharacterData(Loc);
180 int Offset = getOffsetUntil(Buf, Symbol);
181 Offset++;
182 return Loc.getLocWithOffset(Offset);
183 }
184
185 SourceLocation RewriteUtils::getLocationAfterSkiping(SourceLocation StartLoc,
186 char Symbol)
187 {
188 const char *StartBuf = SrcManager->getCharacterData(StartLoc);
189 int Offset = getSkippingOffset(StartBuf, Symbol);
190 return StartLoc.getLocWithOffset(Offset);
191 }
192
193 SourceLocation RewriteUtils::getParamSubstringLocation(SourceLocation StartLoc,
194 size_t Size,
195 const std::string &Substr)
196 {
197 const char *StartBuf = SrcManager->getCharacterData(StartLoc);
198 std::string TmpStr(StartBuf, Size);
199
200 size_t Pos = TmpStr.find(Substr);
201 TransAssert((Pos != std::string::npos) && "Bad Name Position!");
202
203 if (Pos == 0)
204 return StartLoc;
205 else
206 return StartLoc.getLocWithOffset(Pos);
207 }
208
209 bool RewriteUtils::removeParamFromFuncDecl(const ParmVarDecl *PV,
210 unsigned int NumParams,
211 int ParamPos)
212 {
213 SourceRange ParamLocRange = PV->getSourceRange();
214 int RangeSize;
215
216 SourceLocation StartLoc = ParamLocRange.getBegin();
217 if (StartLoc.isMacroID())
218 StartLoc = SrcManager->getExpansionLoc(StartLoc);
219 SourceLocation EndLoc = ParamLocRange.getEnd();
220 if (EndLoc.isMacroID())
221 EndLoc = SrcManager->getExpansionLoc(EndLoc);
222 if (StartLoc.isInvalid() && EndLoc.isInvalid()) {
223 return false;
224 }
225 else if (StartLoc.isInvalid()) {
226 StartLoc = EndLoc;
227 RangeSize = PV->getNameAsString().size();
228 }
229 else if (EndLoc.isInvalid()) {
230 const char *Buf = SrcManager->getCharacterData(StartLoc);
231 if ((ParamPos == 0) && (NumParams == 1)) {
232 RangeSize = getOffsetUntil(Buf, ')');
233 }
234 else {
235 RangeSize = getOffsetUntil(Buf, ',');
236 }
237 }
238 else {
239 RangeSize = TheRewriter->getRangeSize(SourceRange(StartLoc, EndLoc));
240 if (RangeSize == -1)
241 return false;
242 }
243
244 // The param is the only parameter of the function declaration.
245 // Replace it with void
246 if ((ParamPos == 0) && (NumParams == 1)) {
247 return !(TheRewriter->ReplaceText(StartLoc,
248 RangeSize, "void"));
249 }
250
251 // The param is the last parameter
252 if (ParamPos == static_cast<int>(NumParams - 1)) {
253 int Offset = 0;
254 const char *StartBuf =
255 SrcManager->getCharacterData(StartLoc);
256
257 TransAssert(StartBuf && "Invalid start buffer!");
258 while (*StartBuf != ',') {
259 StartBuf--;
260 Offset--;
261 }
262
263 SourceLocation NewStartLoc = StartLoc.getLocWithOffset(Offset);
264
265 return !(TheRewriter->RemoveText(NewStartLoc, RangeSize - Offset));
266 }
267
268 // We cannot use the code below:
269 // SourceLocation EndLoc = ParamLocRange.getEnd();
270 // const char *EndBuf =
271 // ConsumerInstance->SrcManager->getCharacterData(EndLoc);
272 // Because getEnd() returns the start of the last token if this
273 // is a token range. For example, in the above example,
274 // getEnd() points to the start of "x"
275 // See the comments on getRangeSize in clang/lib/Rewriter/Rewriter.cpp
276 int NewRangeSize = 0;
277 const char *StartBuf = SrcManager->getCharacterData(StartLoc);
278
279 while (NewRangeSize < RangeSize) {
280 StartBuf++;
281 NewRangeSize++;
282 }
283
284 TransAssert(StartBuf && "Invalid start buffer!");
285 // FIXME: This isn't really correct for processing old-style function
286 // declarations, but just let's live with it for now.
287 while (*StartBuf != ',' && *StartBuf != ';') {
288 StartBuf++;
289 NewRangeSize++;
290 }
291
292 return !(TheRewriter->RemoveText(StartLoc, NewRangeSize + 1));
293 }
294
295 // Handle CXXConstructExpr and CallExpr.
296 // These two do not inherit each other, and we need a couple of
297 // `common` member functions from them.
298 // Is this too ugly? Any better way to do this?
299 const Expr *RewriteUtils::getArgWrapper(const Expr *E,
300 int ParamPos)
301 {
302 const CXXConstructExpr *CtorE = dyn_cast<CXXConstructExpr>(E);
303 if (CtorE)
304 return CtorE->getArg(ParamPos);
305
306 const CallExpr *CE = dyn_cast<CallExpr>(E);
307 if (CE)
308 return CE->getArg(ParamPos);
309
310 TransAssert(0 && "Invalid Expr!");
311 return NULL;
312 }
313
314 unsigned RewriteUtils::getNumArgsWrapper(const Expr *E)
315 {
316 const CXXConstructExpr *CtorE = dyn_cast<CXXConstructExpr>(E);
317 if (CtorE)
318 return CtorE->getNumArgs();
319
320 const CallExpr *CE = dyn_cast<CallExpr>(E);
321 if (CE)
322 return CE->getNumArgs();
323
324 TransAssert(0 && "Invalid Expr!");
325 return 0;
326 }
327
328 bool RewriteUtils::removeArgFromExpr(const Expr *E,
329 int ParamPos)
330 {
331
332 if (ParamPos >= static_cast<int>(getNumArgsWrapper(E)))
333 return true;
334
335 const Expr *Arg = getArgWrapper(E, ParamPos);
336 TransAssert(Arg && "Null arg!");
337 if (dyn_cast<CXXDefaultArgExpr>(Arg->IgnoreParenCasts()))
338 return true;
339
340 SourceRange ArgRange = Arg->getSourceRange();
341 int RangeSize = TheRewriter->getRangeSize(ArgRange);
342
343 if (RangeSize == -1)
344 return false;
345
346 SourceLocation StartLoc = ArgRange.getBegin();
347 unsigned int NumArgs = getNumArgsWrapper(E);
348
349 if ((ParamPos == 0) && ((NumArgs == 1) ||
350 ((NumArgs > 1) &&
351 dyn_cast<CXXDefaultArgExpr>(
352 getArgWrapper(E, 1)->IgnoreParenCasts())))) {
353 // Note that ')' is included in ParamLocRange
354 return !(TheRewriter->RemoveText(ArgRange));
355 }
356
357 int LastArgPos = static_cast<int>(NumArgs - 1);
358 // The param is the last non-default parameter
359 if ((ParamPos == LastArgPos) ||
360 ((ParamPos < LastArgPos) &&
361 dyn_cast<CXXDefaultArgExpr>(
362 getArgWrapper(E, ParamPos+1)->IgnoreParenCasts()))) {
363 int Offset = 0;
364 const char *StartBuf = SrcManager->getCharacterData(StartLoc);
365
366 TransAssert(StartBuf && "Invalid start buffer!");
367 while (*StartBuf != ',') {
368 StartBuf--;
369 Offset--;
370 }
371
372 SourceLocation NewStartLoc = StartLoc.getLocWithOffset(Offset);
373 return !(TheRewriter->RemoveText(NewStartLoc,
374 RangeSize - Offset));
375 }
376
377 // We cannot use SrcManager->getCharacterData(StartLoc) to get the buffer,
378 // because it returns the unmodified string. I've tried to use
379 // getEndlocationUntil(ArgRange, ",", ...) call, but still failed.
380 // Seems in some cases, it returns bad results for a complex case like:
381 // foo(...foo(...), ...)
382 // So I ended up with this ugly way - get the end loc from the next arg.
383 const Expr *NextArg = getArgWrapper(E, ParamPos+1);
384 SourceRange NextArgRange = NextArg->getSourceRange();
385 SourceLocation NextStartLoc = NextArgRange.getBegin();
386 const char *NextStartBuf = SrcManager->getCharacterData(NextStartLoc);
387 int Offset = 0;
388 while (*NextStartBuf != ',') {
389 NextStartBuf--;
390 Offset--;
391 }
392
393 SourceLocation NewEndLoc = NextStartLoc.getLocWithOffset(Offset);
394 return !TheRewriter->RemoveText(SourceRange(StartLoc, NewEndLoc));
395 }
396
397 bool RewriteUtils::removeArgFromCXXConstructExpr(const CXXConstructExpr *CE,
398 int ParamPos)
399 {
400 return removeArgFromExpr(CE, ParamPos);
401 }
402
403 bool RewriteUtils::removeArgFromCallExpr(const CallExpr *CallE,
404 int ParamPos)
405 {
406 return removeArgFromExpr(CallE, ParamPos);
407 }
408
409 void RewriteUtils::skipRangeByType(const std::string &BufStr,
410 const Type *Ty,
411 int &Offset)
412 {
413 Offset = 0;
414 int BufSz = static_cast<int>(BufStr.size());
415 size_t Pos;
416 while (Offset < BufSz) {
417 if (isspace(BufStr[Offset])) {
418 Offset++;
419 continue;
420 }
421
422 Pos = BufStr.find("char", Offset);
423 if (Pos != std::string::npos) {
424 Offset += 4;
425 continue;
426 }
427
428 Pos = BufStr.find("int", Offset);
429 if (Pos != std::string::npos) {
430 Offset += 3;
431 continue;
432 }
433
434 Pos = BufStr.find("short", Offset);
435 if (Pos != std::string::npos) {
436 Offset += 5;
437 continue;
438 }
439
440 Pos = BufStr.find("long", Offset);
441 if (Pos != std::string::npos) {
442 Offset += 4;
443 continue;
444 }
445
446 return;
447 }
448 }
449
450 SourceLocation RewriteUtils::skipPossibleTypeRange(const Type *Ty,
451 SourceLocation OrigEndLoc,
452 SourceLocation VarStartLoc)
453 {
454 if (!Ty->isIntegerType())
455 return OrigEndLoc;
456
457 int Offset;
458 std::string BufStr;
459 getStringBetweenLocs(BufStr, OrigEndLoc, VarStartLoc);
460 skipRangeByType(BufStr, Ty, Offset);
461
462 return OrigEndLoc.getLocWithOffset(Offset);
463 }
464
465 SourceLocation RewriteUtils::getVarDeclTypeLocBegin(const VarDecl *VD)
466 {
467 TypeLoc VarTypeLoc = VD->getTypeSourceInfo()->getTypeLoc();
468
469 TypeLoc NextTL = VarTypeLoc.getNextTypeLoc();
470 while (!NextTL.isNull()) {
471 VarTypeLoc = NextTL;
472 NextTL = NextTL.getNextTypeLoc();
473 }
474
475 return VarTypeLoc.getBeginLoc();
476 }
477
478 SourceLocation RewriteUtils::getVarDeclTypeLocEnd(const VarDecl *VD)
479 {
480 TypeLoc VarTypeLoc = VD->getTypeSourceInfo()->getTypeLoc();
481 const IdentifierInfo *Id = VD->getType().getBaseTypeIdentifier();
482
483 // handle a special case shown as below:
484 // x;
485 // *y[];
486 // (*z)[];
487 // void foo(void) {...}
488 // where x implicitly has type of int, whereas y has type of int *
489 if (!Id) {
490 SourceLocation EndLoc = VD->getLocation();
491 const char *Buf = SrcManager->getCharacterData(EndLoc);
492 int Offset = -1;
493 SourceLocation NewEndLoc = EndLoc.getLocWithOffset(Offset);
494 if (!NewEndLoc.isValid())
495 return EndLoc;
496
497 Buf--;
498 while (isspace(*Buf) || (*Buf == '*') || (*Buf == '(')) {
499 Offset--;
500 NewEndLoc = EndLoc.getLocWithOffset(Offset);
501 if (!NewEndLoc.isValid())
502 return EndLoc.getLocWithOffset(Offset+1);
503
504 Buf--;
505 }
506 return EndLoc.getLocWithOffset(Offset+1);
507 }
508
509 TypeLoc NextTL = VarTypeLoc.getNextTypeLoc();
510 while (!NextTL.isNull()) {
511 VarTypeLoc = NextTL;
512 NextTL = NextTL.getNextTypeLoc();
513 }
514
515 SourceRange TypeLocRange = VarTypeLoc.getSourceRange();
516 SourceLocation EndLoc = getEndLocationFromBegin(TypeLocRange);
517 TransAssert(EndLoc.isValid() && "Invalid EndLoc!");
518
519 const Type *Ty = VarTypeLoc.getTypePtr();
520
521 // I am not sure why, but for a declaration like below:
522 // unsigned int a; (or long long a;)
523 // TypeLoc.getBeginLoc() returns the position of 'u'
524 // TypeLoc.getEndLoc() also returns the position of 'u'
525 // The size of TypeLoc.getSourceRange() is 8, which is the
526 // length of "unsigned"
527 // Then we are getting trouble, because now EndLoc is right
528 // after 'd', but we need it points to the location after "int".
529 // skipPossibleTypeRange corrects the above deviation
530 // Or am I doing something horrible here?
531 EndLoc = skipPossibleTypeRange(Ty, EndLoc, VD->getLocation());
532 return EndLoc;
533 }
534
535 bool RewriteUtils::removeVarFromDeclStmt(DeclStmt *DS,
536 const VarDecl *VD,
537 Decl *PrevDecl,
538 bool IsFirstDecl,
539 bool *StmtRemoved)
540 {
541 SourceRange StmtRange = DS->getSourceRange();
542
543 // VD is the the only declaration, so it is safe to remove the entire stmt
544 if (DS->isSingleDecl()) {
545 return !(TheRewriter->RemoveText(getRealSourceRange(StmtRange)));
546 }
547
548 // handle the case where we could have implicit declaration of RecordDecl
549 // e.g.,
550 // foo (void) {
551 // struct S0 *s;
552 // ...;
553 // }
554 // in this case, struct S0 is implicitly declared
555 if (PrevDecl) {
556 if ( RecordDecl *RD = dyn_cast<RecordDecl>(PrevDecl) ) {
557 const DeclGroup &DGroup = DS->getDeclGroup().getDeclGroup();
558 IsFirstDecl = true;
559 if ((!RD->getDefinition() || RD->getNameAsString() == "") &&
560 DGroup.size() == 2) {
561 *StmtRemoved = true;
562 return !(TheRewriter->RemoveText(StmtRange));
563 }
564 }
565 }
566
567 SourceRange VarRange = VD->getSourceRange();
568
569 // VD is the first declaration in a declaration group.
570 // We keep the leading type string
571 if (IsFirstDecl) {
572 // We need to get the outermost TypeLocEnd instead of the StartLoc of
573 // a var name, because we need to handle the case below:
574 // int *x, *y;
575 // If we rely on the StartLoc of a var name, then we will make bad
576 // transformation like:
577 // int * *y;
578 SourceLocation NewStartLoc = getVarDeclTypeLocEnd(VD);
579 if (NewStartLoc.isMacroID()) {
580 NewStartLoc = SrcManager->getSpellingLoc(NewStartLoc);
581 const char *StartBuf = SrcManager->getCharacterData(NewStartLoc);
582 // Make sure we have at least one space before the name.
583 if (*StartBuf == ' ')
584 NewStartLoc = NewStartLoc.getLocWithOffset(1);
585 }
586
587 SourceLocation NewEndLoc = getEndLocationUntil(VarRange, ',');
588 if (NewEndLoc.isMacroID())
589 NewEndLoc = SrcManager->getSpellingLoc(NewEndLoc);
590
591 return
592 !(TheRewriter->RemoveText(SourceRange(NewStartLoc, NewEndLoc)));
593 }
594
595 TransAssert(PrevDecl && "PrevDecl cannot be NULL!");
596 SourceLocation VarEndLoc = VarRange.getEnd();
597 SourceRange PrevDeclRange = PrevDecl->getSourceRange();
598
599 SourceLocation PrevDeclEndLoc = getEndLocationUntil(PrevDeclRange, ',');
600
601 if (VarEndLoc.isMacroID())
602 VarEndLoc = SrcManager->getSpellingLoc(VarEndLoc);
603 if (PrevDeclEndLoc.isMacroID())
604 PrevDeclEndLoc = SrcManager->getSpellingLoc(PrevDeclEndLoc);
605 return !(TheRewriter->RemoveText(SourceRange(PrevDeclEndLoc, VarEndLoc)));
606 }
607
608 bool RewriteUtils::getExprString(const Expr *E,
609 std::string &ES)
610 {
611 SourceRange ExprRange = E->getSourceRange();
612 SourceLocation StartLoc = ExprRange.getBegin();
613 if (StartLoc.isInvalid() && !StartLoc.isMacroID()) {
614 ES = "<invalid-expr>";
615 return false;
616 }
617
618 int RangeSize = TheRewriter->getRangeSize(ExprRange);
619 if (RangeSize == -1) {
620 if (StartLoc.isMacroID()) {
621 StartLoc = SrcManager->getFileLoc(StartLoc);
622 SourceLocation EndLoc = SrcManager->getFileLoc(ExprRange.getEnd());
623 RangeSize = TheRewriter->getRangeSize(SourceRange(StartLoc, EndLoc));
624 }
625 else {
626 ES = "<invalid-expr>";
627 return false;
628 }
629 }
630
631 const char *StartBuf = SrcManager->getCharacterData(StartLoc);
632
633 ES.assign(StartBuf, RangeSize);
634
635 const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(E);
636
637 // Keep the semantics of Comma operator
638 if (BinOp && (BinOp->getOpcode() == BO_Comma))
639 ES = "(" + ES + ")";
640
641 return true;
642 }
643
644 bool RewriteUtils::getStmtString(const Stmt *S,
645 std::string &Str)
646 {
647 SourceRange StmtRange = S->getSourceRange();
648
649 int RangeSize = TheRewriter->getRangeSize(StmtRange);
650 if (RangeSize == -1)
651 return false;
652
653 SourceLocation StartLoc = StmtRange.getBegin();
654 const char *StartBuf = SrcManager->getCharacterData(StartLoc);
655
656 Str.assign(StartBuf, RangeSize);
657
658 return true;
659 }
660
661 SourceLocation RewriteUtils::getExpansionEndLoc(SourceLocation EndLoc)
662 {
663 FileID FID = SrcManager->getFileID(EndLoc);
664 const SrcMgr::SLocEntry *Entry = &SrcManager->getSLocEntry(FID);
665
666 while (Entry->getExpansion().getExpansionLocStart().isMacroID()) {
667 EndLoc = Entry->getExpansion().getExpansionLocStart();
668 FID = SrcManager->getFileID(EndLoc);
669 Entry = &SrcManager->getSLocEntry(FID);
670 }
671
672 return Entry->getExpansion().getExpansionLocEnd();
673 }
674
675 bool RewriteUtils::replaceExpr(const Expr *E,
676 const std::string &ES)
677 {
678 SourceRange ExprRange = E->getSourceRange();
679
680 int RangeSize = TheRewriter->getRangeSize(ExprRange);
681 if (RangeSize == -1) {
682 SourceLocation StartLoc = ExprRange.getBegin();
683 if (StartLoc.isMacroID()) {
684 StartLoc = SrcManager->getExpansionLoc(StartLoc);
685 }
686 SourceLocation EndLoc = ExprRange.getEnd();
687 if (SrcManager->isMacroBodyExpansion(EndLoc) ||
688 SrcManager->isMacroArgExpansion(EndLoc)) {
689 // FIXME: handle cases below:
690 // #define macro bar(1,2);
691 // int bar(int p1, int p2) { return p1 + p2; }
692 // void foo(void) { int x = macro }
693 EndLoc = getExpansionEndLoc(EndLoc);
694 }
695 return !(TheRewriter->ReplaceText(SourceRange(StartLoc, EndLoc), ES));
696 }
697
698 return !(TheRewriter->ReplaceText(ExprRange, ES));
699 }
700
701 bool RewriteUtils::replaceExprNotInclude(const Expr *E,
702 const std::string &ES)
703 {
704 SourceRange ExprRange = E->getSourceRange();
705 SourceLocation StartLoc = ExprRange.getBegin();
706 if (StartLoc.isMacroID()) {
707 StartLoc = SrcManager->getFileLoc(StartLoc);
708 SourceLocation EndLoc = ExprRange.getEnd();
709 TransAssert(EndLoc.isMacroID() && "EndLoc is not from a macro!");
710 ExprRange = SourceRange(StartLoc, SrcManager->getFileLoc(EndLoc));
711 }
712 TransAssert((TheRewriter->getRangeSize(ExprRange) != -1) &&
713 "Bad expr range!");
714
715 Rewriter::RewriteOptions Opts;
716 // We don't want to include the previously inserted string
717 Opts.IncludeInsertsAtBeginOfRange = false;
718
719 TheRewriter->RemoveText(ExprRange, Opts);
720 return !(TheRewriter->InsertText(StartLoc, ES));
721 }
722
723 std::string RewriteUtils::getStmtIndentString(Stmt *S,
724 SourceManager *SrcManager)
725 {
726 SourceLocation StmtStartLoc = S->getBeginLoc();
727
728 if (StmtStartLoc.isMacroID()) {
729 StmtStartLoc = SrcManager->getFileLoc(StmtStartLoc);
730 }
731
732 FileID FID;
733 unsigned StartOffset =
734 getLocationOffsetAndFileID(StmtStartLoc, FID, SrcManager);
735
736 StringRef MB = SrcManager->getBufferData(FID);
737
738 unsigned lineNo = SrcManager->getLineNumber(FID, StartOffset) - 1;
739 const SrcMgr::ContentCache *Content =
740 &SrcManager->getSLocEntry(FID).getFile().getContentCache();
741 unsigned lineOffs = Content->SourceLineCache[lineNo];
742
743 // Find the whitespace at the start of the line.
744 StringRef indentSpace;
745
746 unsigned I = lineOffs;
747 while (isspace(MB[I]))
748 ++I;
749 indentSpace = MB.substr(lineOffs, I-lineOffs);
750
751 return indentSpace.str();
752 }
753
754 bool RewriteUtils::addLocalVarToFunc(const std::string &VarStr,
755 FunctionDecl *FD)
756 {
757 Stmt *Body = FD->getBody();
758 TransAssert(Body && "NULL body for a function definition!");
759
760 std::string IndentStr;
761 StmtIterator I = Body->child_begin();
762
763 if (I == Body->child_end())
764 IndentStr = DefaultIndentStr;
765 else
766 IndentStr = getStmtIndentString((*I), SrcManager);
767
768 std::string NewVarStr = "\n" + IndentStr + VarStr;
769 SourceLocation StartLoc = Body->getBeginLoc();
770 return !(TheRewriter->InsertTextAfterToken(StartLoc, NewVarStr));
771 }
772
773 const char *RewriteUtils::getTmpVarNamePrefix(void)
774 {
775 return TmpVarNamePrefix;
776 }
777
778 bool RewriteUtils::addNewAssignStmtBefore(Stmt *BeforeStmt,
779 const std::string &VarName,
780 Expr *RHS,
781 bool NeedParen)
782 {
783 std::string IndentStr =
784 RewriteUtils::getStmtIndentString(BeforeStmt, SrcManager);
785
786 if (NeedParen) {
787 SourceRange StmtRange = BeforeStmt->getSourceRange();
788 SourceLocation LocEnd =
789 RewriteUtils::getEndLocationFromBegin(StmtRange);
790 TransAssert(LocEnd.isValid() && "Invalid LocEnd!");
791
792 std::string PostStr = "\n" + IndentStr + "}";
793 if (TheRewriter->InsertTextAfterToken(LocEnd, PostStr))
794 return false;
795 }
796
797 SourceLocation StmtLocStart = BeforeStmt->getBeginLoc();
798 if (StmtLocStart.isMacroID()) {
799 StmtLocStart = SrcManager->getFileLoc(StmtLocStart);
800 }
801
802 std::string ExprStr;
803 RewriteUtils::getExprString(RHS, ExprStr);
804
805 std::string AssignStmtStr;
806
807 if (NeedParen) {
808 AssignStmtStr = "{\n";
809 AssignStmtStr += IndentStr + " " + VarName + " = ";
810 AssignStmtStr += ExprStr;
811 AssignStmtStr += ";\n" + IndentStr + " ";
812 }
813 else {
814 AssignStmtStr = VarName + " = ";
815 AssignStmtStr += ExprStr;
816 AssignStmtStr += ";\n" + IndentStr;
817 }
818
819 return !(TheRewriter->InsertText(StmtLocStart,
820 AssignStmtStr, /*InsertAfter=*/false));
821 }
822
823 void RewriteUtils::indentAfterNewLine(StringRef Str,
824 std::string &NewStr,
825 const std::string &IndentStr)
826 {
827 SmallVector<StringRef, 20> StrVec;
828 Str.split(StrVec, "\n");
829 NewStr = "";
830 for(SmallVector<StringRef, 20>::iterator I = StrVec.begin(),
831 E = StrVec.end(); I != E; ++I) {
832 NewStr += ((*I).str() + "\n" + IndentStr);
833 }
834 }
835
836 void RewriteUtils::addOpenParenBeforeStmt(Stmt *S, const std::string &IndentStr)
837 {
838 SourceRange StmtRange = S->getSourceRange();
839 SourceLocation LocEnd =
840 RewriteUtils::getEndLocationFromBegin(StmtRange);
841 TransAssert(LocEnd.isValid() && "Invalid LocEnd!");
842
843 std::string PostStr = "\n" + IndentStr + "}";
844 TheRewriter->InsertTextAfterToken(LocEnd, PostStr);
845 }
846
847 bool RewriteUtils::addStringBeforeStmtInternal(Stmt *S,
848 const std::string &Str,
849 const std::string &IndentStr,
850 bool NeedParen)
851 {
852 std::string NewStr;
853
854 if (NeedParen) {
855 NewStr = "{\n";
856 }
857 NewStr += Str;
858 NewStr += "\n";
859
860 std::string IndentedStr;
861 indentAfterNewLine(NewStr, IndentedStr, IndentStr);
862
863 return !(TheRewriter->InsertText(S->getBeginLoc(),
864 IndentedStr, /*InsertAfter=*/false));
865 }
866
867 bool RewriteUtils::addStringBeforeStmt(Stmt *BeforeStmt,
868 const std::string &Str,
869 bool NeedParen)
870 {
871 std::string IndentStr =
872 RewriteUtils::getStmtIndentString(BeforeStmt, SrcManager);
873
874 if (NeedParen) {
875 addOpenParenBeforeStmt(BeforeStmt, IndentStr);
876 }
877 return addStringBeforeStmtInternal(BeforeStmt, Str,
878 IndentStr, NeedParen);
879 }
880
881 // Note that we can't use addStringBeforeStmt because
882 // we need to modify an expression in BeforeStmt. We have
883 // to do rewrite from end to begin to avoid crash.
884 bool RewriteUtils::addStringBeforeStmtAndReplaceExpr(Stmt *BeforeStmt,
885 const std::string &StmtStr,
886 const Expr *E, const std::string &ExprStr,
887 bool NeedParen)
888 {
889 std::string IndentStr =
890 RewriteUtils::getStmtIndentString(BeforeStmt, SrcManager);
891
892 if (NeedParen) {
893 addOpenParenBeforeStmt(BeforeStmt, IndentStr);
894 }
895 replaceExpr(E, ExprStr);
896 return addStringBeforeStmtInternal(BeforeStmt, StmtStr,
897 IndentStr, NeedParen);
898 }
899
900 bool RewriteUtils::addStringAfterStmt(Stmt *AfterStmt,
901 const std::string &Str)
902 {
903 std::string IndentStr =
904 RewriteUtils::getStmtIndentString(AfterStmt, SrcManager);
905
906 std::string NewStr = "\n" + IndentStr + Str;
907 SourceRange StmtRange = AfterStmt->getSourceRange();
908 SourceLocation LocEnd =
909 RewriteUtils::getEndLocationFromBegin(StmtRange);
910 TransAssert(LocEnd.isValid() && "Invalid LocEnd!");
911
912 return !(TheRewriter->InsertText(LocEnd, NewStr));
913 }
914
915 bool RewriteUtils::addStringAfterVarDecl(const VarDecl *VD,
916 const std::string &Str)
917 {
918 SourceRange VarRange = VD->getSourceRange();
919 SourceLocation LocEnd = getEndLocationAfter(VarRange, ';');
920
921 return !(TheRewriter->InsertText(LocEnd, "\n" + Str));
922 }
923
924 bool RewriteUtils::addStringAfterFuncDecl(const FunctionDecl *FD,
925 const std::string &Str)
926 {
927 SourceRange FDRange = FD->getSourceRange();
928 SourceLocation LocEnd = getEndLocationAfter(FDRange, ';');
929
930 return !(TheRewriter->InsertText(LocEnd, "\n" + Str));
931 }
932
933 // This function is an experimental one. It doesn't work
934 // if ND is a class of FunctionDecl, but I am not sure
935 // how it works for other types of NamedDecls
936 bool RewriteUtils::replaceNamedDeclName(const NamedDecl *ND,
937 const std::string &NameStr)
938 {
939 TransAssert(!isa<FunctionDecl>(ND) &&
940 "Please use replaceFunctionDeclName for renaming a FunctionDecl!");
941 TransAssert(!isa<UsingDirectiveDecl>(ND) &&
942 "Cannot use this function for renaming UsingDirectiveDecl");
943 SourceLocation NameLocStart = ND->getLocation();
944 return !(TheRewriter->ReplaceText(NameLocStart,
945 ND->getNameAsString().size(), NameStr));
946 }
947
948 bool RewriteUtils::replaceValueDecl(const ValueDecl *VD, const std::string &Str)
949 {
950 SourceRange Range = VD->getSourceRange();
951 unsigned RangeSize = TheRewriter->getRangeSize(Range);
952 return !(TheRewriter->ReplaceText(Range.getBegin(), RangeSize, Str));
953 }
954
955 bool RewriteUtils::replaceVarDeclName(VarDecl *VD,
956 const std::string &NameStr)
957 {
958 SourceLocation NameLocStart = VD->getLocation();
959 return !(TheRewriter->ReplaceText(NameLocStart,
960 VD->getNameAsString().size(), NameStr));
961 }
962
963 bool RewriteUtils::replaceFunctionDeclName(const FunctionDecl *FD,
964 const std::string &NameStr)
965 {
966 // We cannot naively use FD->getNameAsString() here.
967 // For example, for a template class
968 // template<typename T>
969 // class SomeClass {
970 // public:
971 // SomeClass() {}
972 // };
973 // applying getNameAsString() on SomeClass() gives us SomeClass<T>.
974
975 DeclarationNameInfo NameInfo = FD->getNameInfo();
976 if (const IdentifierInfo *IdInfo = FD->getLiteralIdentifier()) {
977 SourceLocation OpLoc = NameInfo.getBeginLoc();
978 const char *OpStartBuf = SrcManager->getCharacterData(OpLoc);
979
980 // skip string operator
981 std::string TmpStr(OpStartBuf,
982 TheRewriter->getRangeSize(NameInfo.getSourceRange()));
983 std::string OperatorStr = "operator";
984 size_t Pos = TmpStr.find(OperatorStr);
985 TransAssert(Pos != std::string::npos && "cannot find operator!");
986
987 size_t OldNamePos =
988 TmpStr.find(IdInfo->getNameStart(), Pos, IdInfo->getLength());
989 TransAssert(OldNamePos != std::string::npos && "cannot find old name!");
990
991 SourceLocation NewStartLoc = OpLoc.getLocWithOffset(OldNamePos);
992 return !TheRewriter->ReplaceText(NewStartLoc, IdInfo->getLength(), NameStr);
993 }
994
995 DeclarationName DeclName = NameInfo.getName();
996 DeclarationName::NameKind K = DeclName.getNameKind();
997 TransAssert((K != DeclarationName::CXXDestructorName) &&
998 "Cannot rename CXXDestructorName here!");
999
1000 std::string FDName = FD->getNameAsString();
1001 size_t FDNameLen = FD->getNameAsString().length();
1002 if (K == DeclarationName::CXXConstructorName) {
1003 const Type *Ty = DeclName.getCXXNameType().getTypePtr();
1004 if (Ty->getTypeClass() == Type::InjectedClassName) {
1005 const CXXRecordDecl *CXXRD = Ty->getAsCXXRecordDecl();
1006 std::string RDName = CXXRD->getNameAsString();
1007 FDNameLen = FDName.find(RDName);
1008 TransAssert((FDNameLen != std::string::npos) &&
1009 "Cannot find RecordDecl Name!");
1010 FDNameLen += RDName.length();
1011 }
1012 }
1013
1014 return !TheRewriter->ReplaceText(NameInfo.getLoc(),
1015 FDNameLen,
1016 NameStr);
1017 }
1018
1019 bool RewriteUtils::replaceCXXDestructorDeclName(
1020 const CXXDestructorDecl *DtorDecl,
1021 const std::string &Name)
1022 {
1023 SourceLocation StartLoc = DtorDecl->getLocation();
1024 const char *StartBuf = SrcManager->getCharacterData(StartLoc);
1025 TransAssert((*StartBuf == '~') && "Invalid Destructor Location");
1026 // FIXME: it's quite ugly, better to use clang's Lexer
1027 unsigned Off = 0;
1028 StartBuf++;
1029 while (isspace(*StartBuf)) {
1030 StartBuf++;
1031 Off++;
1032 }
1033
1034 std::string DName = DtorDecl->getNameAsString();
1035 DeclarationNameInfo NameInfo = DtorDecl->getNameInfo();
1036 DeclarationName DeclName = NameInfo.getName();
1037 const Type *Ty = DeclName.getCXXNameType().getTypePtr();
1038 size_t NameLen;
1039 if (Ty->getTypeClass() == Type::InjectedClassName) {
1040 const CXXRecordDecl *CXXRD = Ty->getAsCXXRecordDecl();
1041 std::string RDName = CXXRD->getNameAsString();
1042 NameLen = DName.find(RDName);
1043 TransAssert((NameLen != std::string::npos) &&
1044 "Cannot find RecordDecl Name!");
1045 NameLen += RDName.length();
1046 }
1047 else {
1048 NameLen = DName.length();
1049 }
1050 NameLen += Off;
1051
1052 return !TheRewriter->ReplaceText(StartLoc,
1053 NameLen,
1054 "~" + Name);
1055 }
1056
1057 bool RewriteUtils::replaceRecordDeclName(const RecordDecl *RD,
1058 const std::string &NameStr)
1059 {
1060 SourceLocation LocStart = RD->getLocation();
1061 return !TheRewriter->ReplaceText(LocStart,
1062 RD->getNameAsString().length(),
1063 NameStr);
1064 }
1065
1066 bool RewriteUtils::replaceRecordDeclDef(const RecordDecl *RD,
1067 const std::string &NameStr)
1068 {
1069 if (RD->isThisDeclarationADefinition()) {
1070 SourceLocation RBLoc = RD->getBraceRange().getEnd();
1071 if (RBLoc.isInvalid()) {
1072 return !TheRewriter->ReplaceText(RD->getSourceRange(), NameStr);
1073 }
1074 else {
1075 SourceLocation StartLoc = RD->getSourceRange().getBegin();
1076 return !TheRewriter->ReplaceText(SourceRange(StartLoc, RBLoc), NameStr);
1077 }
1078 }
1079 return true;
1080 }
1081
1082 bool RewriteUtils::replaceVarTypeName(const VarDecl *VD,
1083 const std::string &NameStr)
1084 {
1085 const IdentifierInfo *TypeId = VD->getType().getBaseTypeIdentifier();
1086
1087 SourceLocation LocStart = getVarDeclTypeLocBegin(VD);
1088 return !TheRewriter->ReplaceText(LocStart,
1089 TypeId->getLength(),
1090 NameStr);
1091 }
1092
1093 void RewriteUtils::getStringBetweenLocs(std::string &Str,
1094 SourceLocation LocStart,
1095 SourceLocation LocEnd)
1096 {
1097 const char *StartBuf = SrcManager->getCharacterData(LocStart);
1098 const char *EndBuf = SrcManager->getCharacterData(LocEnd);
1099 TransAssert(StartBuf < EndBuf);
1100 size_t Off = EndBuf - StartBuf;
1101 Str.assign(StartBuf, Off);
1102 }
1103
1104 void RewriteUtils::getStringBetweenLocsAfterStart(std::string &Str,
1105 SourceLocation LocStart,
1106 SourceLocation LocEnd)
1107 {
1108 const char *StartBuf = SrcManager->getCharacterData(LocStart);
1109 const char *EndBuf = SrcManager->getCharacterData(LocEnd);
1110 StartBuf++;
1111 TransAssert(StartBuf <= EndBuf);
1112 size_t Off = EndBuf - StartBuf;
1113 Str.assign(StartBuf, Off);
1114 }
1115
1116 bool RewriteUtils::getEntireDeclGroupStrAndRemove(DeclGroupRef DGR,
1117 std::string &Str)
1118 {
1119 Decl *FirstD, *LastD;
1120 if (DGR.isSingleDecl()) {
1121 FirstD = DGR.getSingleDecl();
1122 LastD = FirstD;
1123 }
1124 else {
1125 DeclGroupRef::iterator I = DGR.begin();
1126 FirstD = (*I);
1127
1128 DeclGroupRef::iterator E = DGR.end();
1129 --E;
1130 LastD = (*E);
1131 }
1132
1133 SourceRange FirstRange = FirstD->getSourceRange();
1134 SourceLocation StartLoc = FirstRange.getBegin();
1135 SourceRange LastRange = LastD->getSourceRange();
1136 SourceLocation EndLoc = getEndLocationUntil(LastRange, ';');
1137
1138 // This isn't really good, but if EndLoc is invalid, what can we do?
1139 if (EndLoc.isInvalid()) {
1140 unsigned Off = 0;
1141 const char *StartBuf = SrcManager->getCharacterData(StartLoc);
1142 while ((*StartBuf != '\n') && (*StartBuf != ';') && (*StartBuf != '\0')) {
1143 Off++;
1144 StartBuf++;
1145 }
1146 assert(Off && "Zero offset!");
1147 EndLoc = StartLoc.getLocWithOffset(Off);
1148 }
1149 getStringBetweenLocs(Str, StartLoc, EndLoc);
1150 return !TheRewriter->RemoveText(SourceRange(StartLoc, EndLoc));
1151 }
1152
1153 // This function skips type specifiers
1154 bool RewriteUtils::getDeclGroupStrAndRemove(DeclGroupRef DGR,
1155 std::string &Str)
1156 {
1157 if (DGR.isSingleDecl()) {
1158 Decl *D = DGR.getSingleDecl();
1159 VarDecl *VD = dyn_cast<VarDecl>(D);
1160 TransAssert(VD && "Bad VarDecl!");
1161
1162 // We need to get the outermost TypeLocEnd instead of the StartLoc of
1163 // a var name, because we need to handle the case below:
1164 // int *x;
1165 // int *y;
1166 // If we rely on the StartLoc of a var name, then we will make bad
1167 // transformation like:
1168 // int *x, y;
1169 SourceLocation TypeLocEnd = getVarDeclTypeLocEnd(VD);
1170 if (TypeLocEnd.isMacroID())
1171 TypeLocEnd = SrcManager->getFileLoc(TypeLocEnd);
1172 SourceRange VarRange = VD->getSourceRange();
1173
1174 SourceLocation LocEnd = getEndLocationUntil(VarRange, ';');
1175
1176 getStringBetweenLocs(Str, TypeLocEnd, LocEnd);
1177
1178 SourceLocation StartLoc = VarRange.getBegin();
1179 if (StartLoc.isMacroID())
1180 StartLoc = SrcManager->getFileLoc(StartLoc);
1181 SourceLocation NewEndLoc = getLocationAfterSkiping(LocEnd, ';');
1182 return !(TheRewriter->RemoveText(SourceRange(StartLoc, NewEndLoc)));
1183 }
1184
1185 TransAssert(DGR.getDeclGroup().size() > 1);
1186
1187 DeclGroupRef::iterator I = DGR.begin();
1188 DeclGroupRef::iterator E = DGR.end();
1189 --E;
1190
1191 Decl *FirstD = (*I);
1192 VarDecl *FirstVD = dyn_cast<VarDecl>(FirstD);
1193 Decl *LastD = (*E);
1194 VarDecl *LastVD = dyn_cast<VarDecl>(LastD);
1195
1196 TransAssert(FirstVD && "Bad First VarDecl!");
1197 TransAssert(LastVD && "Bad First VarDecl!");
1198
1199 SourceLocation TypeLocEnd = getVarDeclTypeLocEnd(FirstVD);
1200 SourceRange LastVarRange = LastVD->getSourceRange();
1201 SourceLocation LastEndLoc = getEndLocationUntil(LastVarRange, ';');
1202 getStringBetweenLocs(Str, TypeLocEnd, LastEndLoc);
1203
1204 SourceLocation StartLoc = FirstVD->getBeginLoc();
1205 SourceLocation NewLastEndLoc = getLocationAfterSkiping(LastEndLoc, ';');
1206 return !(TheRewriter->RemoveText(SourceRange(StartLoc, NewLastEndLoc)));
1207 }
1208
1209 SourceLocation RewriteUtils::getDeclGroupRefEndLoc(DeclGroupRef DGR)
1210 {
1211 Decl *LastD;
1212
1213 if (DGR.isSingleDecl()) {
1214 LastD = DGR.getSingleDecl();
1215 }
1216 else {
1217 DeclGroupRef::iterator E = DGR.end();
1218 --E;
1219 LastD = (*E);
1220 }
1221
1222 #if 0
1223 VarDecl *VD = dyn_cast<VarDecl>(LastD);
1224 TransAssert(VD && "Bad VD!");
1225 SourceRange VarRange = VD->getSourceRange();
1226 return getEndLocationFromBegin(VarRange);
1227 #endif
1228
1229 // The LastD could be a RecordDecl
1230 SourceRange Range = LastD->getSourceRange();
1231 SourceLocation EndLoc = getEndLocationFromBegin(Range);
1232 TransAssert(EndLoc.isValid() && "Invalid EndLoc!");
1233 return EndLoc;
1234 }
1235
1236 SourceLocation RewriteUtils::getDeclStmtEndLoc(DeclStmt *DS)
1237 {
1238 DeclGroupRef DGR = DS->getDeclGroup();
1239 return getDeclGroupRefEndLoc(DGR);
1240 }
1241
1242 bool RewriteUtils::getDeclStmtStrAndRemove(DeclStmt *DS,
1243 std::string &Str)
1244 {
1245 DeclGroupRef DGR = DS->getDeclGroup();
1246 return getDeclGroupStrAndRemove(DGR, Str);
1247 }
1248
1249 bool RewriteUtils::removeAStarBefore(const Decl *D)
1250 {
1251 SourceLocation LocStart = D->getLocation();
1252 const char *StartBuf = SrcManager->getCharacterData(LocStart);
1253 int Offset = 0;
1254 while (*StartBuf != '*') {
1255 StartBuf--;
1256 Offset--;
1257 }
1258 SourceLocation StarLoc = LocStart.getLocWithOffset(Offset);
1259 return !TheRewriter->RemoveText(StarLoc, 1);
1260 }
1261
1262 bool RewriteUtils::removeASymbolAfter(const Expr *E,
1263 char Symbol)
1264 {
1265 SourceRange ExprRange = E->getSourceRange();
1266 SourceLocation LocStart = ExprRange.getBegin();
1267 const char *StartBuf = SrcManager->getCharacterData(LocStart);
1268 int Offset = 0;
1269 while (*StartBuf != Symbol) {
1270 StartBuf++;
1271 Offset++;
1272 }
1273 SourceLocation StarLoc = LocStart.getLocWithOffset(Offset);
1274 return !TheRewriter->RemoveText(StarLoc, 1);
1275 }
1276
1277 bool RewriteUtils::removeAStarAfter(const Expr *E)
1278 {
1279 return removeASymbolAfter(E, '*');
1280 }
1281
1282 bool RewriteUtils::removeAnAddrOfAfter(const Expr *E)
1283 {
1284 return removeASymbolAfter(E, '&');
1285 }
1286
1287 bool RewriteUtils::insertAnAddrOfBefore(const Expr *E)
1288 {
1289 SourceRange ExprRange = E->getSourceRange();
1290 SourceLocation LocStart = ExprRange.getBegin();
1291 return !TheRewriter->InsertTextBefore(LocStart, "&");
1292 }
1293
1294 bool RewriteUtils::insertAStarBefore(const Expr *E)
1295 {
1296 SourceRange ExprRange = E->getSourceRange();
1297 SourceLocation LocStart = ExprRange.getBegin();
1298 return !TheRewriter->InsertTextBefore(LocStart, "*");
1299 }
1300
1301 bool RewriteUtils::removeVarInitExpr(const VarDecl *VD)
1302 {
1303 TransAssert(VD->hasInit() && "VarDecl doesn't have an Init Expr!");
1304 SourceLocation NameStartLoc = VD->getLocation();
1305
1306 SourceLocation InitStartLoc = getLocationUntil(NameStartLoc, '=');
1307
1308 const Expr *Init = VD->getInit();
1309 SourceRange ExprRange = Init->getSourceRange();
1310 SourceLocation InitEndLoc = ExprRange.getEnd();
1311 // handle macro, e.g.:
1312 // #define NULL 0
1313 // void foo(void)
1314 // {
1315 // int *p = NULL;
1316 // }
1317 if (SrcManager->isMacroBodyExpansion(InitEndLoc)) {
1318 InitEndLoc = SrcManager->getFileLoc(InitEndLoc);
1319 }
1320 return !TheRewriter->RemoveText(SourceRange(InitStartLoc, InitEndLoc));
1321 }
1322
1323 SourceLocation RewriteUtils::getMacroExpansionLoc(SourceLocation Loc) {
1324 if (SrcManager->isMacroBodyExpansion(Loc))
1325 return SrcManager->getFileLoc(Loc);
1326 return Loc;
1327 }
1328
1329 bool RewriteUtils::removeVarDecl(const VarDecl *VD,
1330 DeclGroupRef DGR)
1331 {
1332 SourceRange VarRange = VD->getSourceRange();
1333
1334 if (DGR.isSingleDecl()) {
1335 SourceLocation StartLoc = getMacroExpansionLoc(VarRange.getBegin());
1336 SourceLocation EndLoc = getEndLocationUntil(VarRange, ';');
1337 // in case the previous EndLoc is invalid, for example,
1338 // VarRange could have bad EndLoc value
1339 if (EndLoc.isInvalid())
1340 EndLoc = getLocationUntil(StartLoc, ';');
1341 return !(TheRewriter->RemoveText(SourceRange(StartLoc, EndLoc)));
1342 }
1343
1344 DeclGroupRef::const_iterator I = DGR.begin();
1345 const VarDecl *FirstVD = dyn_cast<VarDecl>(*I);
1346 // dyn_cast (*I) to VarDecl could fail, because it could be a struct decl,
1347 // e.g., struct S1 { int f1; } s2 = {1}, where FirstDecl is
1348 // struct S1 {int f1;}. We need to skip it
1349 if (!FirstVD) {
1350 // handle the case where we could have implicit declaration of RecordDecl
1351 // e.g.,
1352 // struct S0 *s;
1353 // ...;
1354 // in this case, struct S0 is implicitly declared
1355 if ( RecordDecl *RD = dyn_cast<RecordDecl>(*I) ) {
1356 if (!RD->getDefinition() && DGR.getDeclGroup().size() == 2) {
1357 SourceLocation StartLoc = VarRange.getBegin();
1358 SourceLocation EndLoc = getEndLocationUntil(VarRange, ';');
1359 return !(TheRewriter->RemoveText(SourceRange(StartLoc, EndLoc)));
1360 }
1361 }
1362
1363 ++I;
1364 TransAssert((I != DGR.end()) && "Bad Decl!");
1365 FirstVD = dyn_cast<VarDecl>(*I);
1366 TransAssert(FirstVD && "Invalid Var Decl!");
1367 if (VD == FirstVD) {
1368 SourceLocation StartLoc = VD->getLocation();
1369 SourceLocation EndLoc;
1370 if (I + 1 == DGR.end()) {
1371 EndLoc = StartLoc;
1372 }
1373 else {
1374 EndLoc = getEndLocationUntil(VarRange, ',');
1375 }
1376
1377 return !(TheRewriter->RemoveText(SourceRange(StartLoc, EndLoc)));
1378 }
1379 }
1380 else if (VD == FirstVD) {
1381 SourceLocation StartLoc = getVarDeclTypeLocEnd(VD);
1382
1383 SourceLocation EndLoc =
1384 getEndLocationUntil(VarRange, ',');
1385
1386 return !(TheRewriter->RemoveText(SourceRange(StartLoc, EndLoc)));
1387 }
1388
1389 const Decl *PrevDecl = FirstVD;
1390 const VarDecl *CurrVD = NULL;
1391 ++I;
1392 DeclGroupRef::const_iterator E = DGR.end();
1393 for (; I != E; ++I) {
1394 CurrVD = dyn_cast<VarDecl>(*I);
1395 if (CurrVD && VD == CurrVD)
1396 break;
1397 PrevDecl = *I;
1398 }
1399
1400 TransAssert((VD == CurrVD) && "Cannot find VD!");
1401
1402 SourceLocation VarEndLoc = VarRange.getEnd();
1403 SourceRange PrevDeclRange = PrevDecl->getSourceRange();
1404
1405 SourceLocation PrevDeclEndLoc =
1406 getEndLocationUntil(PrevDeclRange, ',');
1407
1408 return !(TheRewriter->RemoveText(SourceRange(PrevDeclEndLoc, VarEndLoc)));
1409 }
1410
1411 void RewriteUtils::getTmpTransName(unsigned Postfix, std::string &Name)
1412 {
1413 std::stringstream SS;
1414 SS << getTmpVarNamePrefix() << Postfix;
1415 Name = SS.str();
1416 }
1417
1418 bool RewriteUtils::insertStringBeforeFunc(const FunctionDecl *FD,
1419 const std::string &Str)
1420 {
1421 SourceRange FuncRange;
1422 if (FunctionTemplateDecl *TmplD = FD->getDescribedFunctionTemplate()) {
1423 FuncRange = TmplD->getSourceRange();
1424 }
1425 else {
1426 FuncRange = FD->getSourceRange();
1427 }
1428 SourceLocation StartLoc = FuncRange.getBegin();
1429 return !TheRewriter->InsertTextBefore(StartLoc, Str);
1430 }
1431
1432 bool RewriteUtils::insertStringBeforeTemplateDecl(const TemplateDecl *D,
1433 const std::string &Str)
1434 {
1435 SourceRange Range = D->getSourceRange();
1436 SourceLocation StartLoc = Range.getBegin();
1437 TransAssert(StartLoc.isValid() && "Invalid template decl StartLoc!");
1438 return !TheRewriter->InsertTextBefore(StartLoc, Str);
1439 }
1440
1441 bool RewriteUtils::replaceUnionWithStruct(const NamedDecl *ND)
1442 {
1443 SourceRange NDRange = ND->getSourceRange();
1444 int RangeSize = TheRewriter->getRangeSize(NDRange);
1445 TransAssert((RangeSize != -1) && "Bad Range!");
1446
1447 SourceLocation StartLoc = NDRange.getBegin();
1448 const char *StartBuf = SrcManager->getCharacterData(StartLoc);
1449 std::string TmpStr(StartBuf, RangeSize);
1450 std::string UStr = "union";
1451 size_t Pos = TmpStr.find(UStr);
1452 if (Pos == std::string::npos)
1453 return true;
1454
1455 if (Pos != 0)
1456 StartLoc = StartLoc.getLocWithOffset(Pos);
1457 return !TheRewriter->ReplaceText(StartLoc, UStr.size(), "struct");
1458 }
1459
1460 bool RewriteUtils::removeIfAndCond(const IfStmt *IS)
1461 {
1462 SourceLocation IfLoc = IS->getIfLoc();
1463 const Stmt *ThenStmt = IS->getThen();
1464 TransAssert(ThenStmt && "NULL ThenStmt!");
1465
1466 SourceLocation ThenLoc = getRealLocation(ThenStmt->getBeginLoc());
1467 SourceLocation EndLoc = ThenLoc.getLocWithOffset(-1);
1468
1469 Rewriter::RewriteOptions Opts;
1470 // We don't want to include the previously inserted string
1471 Opts.IncludeInsertsAtBeginOfRange = false;
1472 return !TheRewriter->RemoveText(SourceRange(getRealLocation(IfLoc), EndLoc), Opts);
1473 }
1474
1475 bool RewriteUtils::removeArraySubscriptExpr(const Expr *E)
1476 {
1477 SourceRange ERange = E->getSourceRange();
1478 SourceLocation StartLoc = ERange.getBegin();
1479 const char *StartBuf = SrcManager->getCharacterData(StartLoc);
1480 int Offset = 0;
1481 while (*StartBuf != '[') {
1482 StartBuf--;
1483 Offset--;
1484 }
1485 StartLoc = StartLoc.getLocWithOffset(Offset);
1486
1487 SourceLocation EndLoc = ERange.getEnd();
1488 EndLoc = EndLoc.getLocWithOffset(1);
1489 if (EndLoc.isInvalid())
1490 return !TheRewriter->RemoveText(SourceRange(StartLoc, ERange.getEnd()));
1491
1492 SourceLocation RBLoc = getLocationUntil(EndLoc, ']');
1493 if (RBLoc.isInvalid())
1494 return !TheRewriter->RemoveText(SourceRange(StartLoc, EndLoc));
1495 return !TheRewriter->RemoveText(SourceRange(StartLoc, RBLoc));
1496 }
1497
1498 bool RewriteUtils::getFunctionDefStrAndRemove(const FunctionDecl *FD,
1499 std::string &Str)
1500 {
1501 SourceRange FDRange = FD->getSourceRange();
1502
1503 int RangeSize = TheRewriter->getRangeSize(FDRange);
1504 if (RangeSize == -1)
1505 return false;
1506
1507 SourceLocation StartLoc = FDRange.getBegin();
1508 const char *StartBuf = SrcManager->getCharacterData(StartLoc);
1509
1510 Str.assign(StartBuf, RangeSize);
1511 TheRewriter->RemoveText(FDRange);
1512 return true;
1513 }
1514
1515 bool RewriteUtils::getFunctionDeclStrAndRemove(const FunctionDecl *FD,
1516 std::string &Str)
1517 {
1518 TransAssert(!FD->isThisDeclarationADefinition() &&
1519 "FD cannot be a definition!");
1520
1521 SourceRange FDRange = FD->getSourceRange();
1522 SourceLocation StartLoc = FDRange.getBegin();
1523 SourceLocation EndLoc = getEndLocationUntil(FDRange, ';');
1524
1525 getStringBetweenLocs(Str, StartLoc, EndLoc);
1526 return !TheRewriter->RemoveText(SourceRange(StartLoc, EndLoc));
1527 }
1528
1529 bool RewriteUtils::replaceFunctionDefWithStr(const FunctionDecl *FD,
1530 const std::string &Str)
1531 {
1532 const Stmt *Body = FD->getBody();
1533 TransAssert(Body && "FunctionDecl is not a definition!");
1534 SourceRange Range = Body->getSourceRange();
1535 SourceLocation StartLoc = Range.getBegin();
1536 if (StartLoc.isMacroID())
1537 StartLoc = SrcManager->getExpansionLoc(StartLoc);
1538 SourceLocation EndLoc = Range.getEnd();
1539 if (EndLoc.isMacroID())
1540 EndLoc = SrcManager->getExpansionLoc(EndLoc);
1541 return !TheRewriter->ReplaceText(SourceRange(StartLoc, EndLoc), Str);
1542 }
1543
1544 // FIXME: probably we don't need this function, because we could use
1545 // removeDecl insteadly
1546 bool RewriteUtils::removeFieldDecl(const FieldDecl *FD)
1547 {
1548 SourceRange Range = FD->getSourceRange();
1549 SourceLocation StartLoc = Range.getBegin();
1550 SourceLocation EndLoc = getEndLocationUntil(Range, ';');
1551 SourceLocation CurlyEndLoc = getEndLocationUntil(Range, '}');
1552
1553 // handle cases like:
1554 // struct {
1555 // int f <- no semicolon here
1556 // };
1557 const char *SemiPos = SrcManager->getCharacterData(EndLoc);
1558 const char *CurlyPos = SrcManager->getCharacterData(CurlyEndLoc);
1559 if (SemiPos > CurlyPos) {
1560 EndLoc = CurlyEndLoc.getLocWithOffset(-1);
1561 }
1562
1563 // If EndLoc is invalid, just remove one char to avoid crash
1564 if (EndLoc.isInvalid()) {
1565 EndLoc = StartLoc;
1566 }
1567 return !(TheRewriter->RemoveText(SourceRange(StartLoc, EndLoc)));
1568 }
1569
1570 bool RewriteUtils::removeDecl(const Decl *D)
1571 {
1572 SourceRange Range = D->getSourceRange();
1573 TransAssert((TheRewriter->getRangeSize(Range) != -1) &&
1574 "Bad UsingDecl SourceRange!");
1575 SourceLocation StartLoc = Range.getBegin();
1576 SourceLocation EndLoc = getEndLocationUntil(Range, ';');
1577 return !(TheRewriter->RemoveText(SourceRange(StartLoc, EndLoc)));
1578 }
1579
1580 bool RewriteUtils::replaceCXXDtorCallExpr(const CXXMemberCallExpr *CE,
1581 std::string &Name)
1582 {
1583 const CXXMethodDecl *MD = CE->getMethodDecl();
1584 const CXXDestructorDecl *DtorDecl = dyn_cast<CXXDestructorDecl>(MD);
1585 if (!DtorDecl)
1586 return true;
1587
1588 Name = "~" + Name;
1589
1590 std::string ExprStr;
1591 getExprString(CE, ExprStr);
1592 std::string OldDtorName = DtorDecl->getNameAsString();
1593 size_t Pos = ExprStr.find(OldDtorName);
1594 TransAssert((Pos != std::string::npos) && "Bad Name Position!");
1595 if (Pos == 0)
1596 return true;
1597
1598 SourceLocation StartLoc = CE->getBeginLoc();
1599 StartLoc = StartLoc.getLocWithOffset(Pos);
1600
1601 return !(TheRewriter->ReplaceText(StartLoc, OldDtorName.size(), Name));
1602 }
1603
1604 SourceRange RewriteUtils::getFileLocSourceRange(SourceRange LocRange)
1605 {
1606 SourceLocation StartLoc = LocRange.getBegin();
1607 if (StartLoc.isMacroID()) {
1608 StartLoc = SrcManager->getFileLoc(StartLoc);
1609 }
1610 SourceLocation EndLoc = LocRange.getEnd();
1611 if (EndLoc.isMacroID()) {
1612 EndLoc = SrcManager->getFileLoc(EndLoc);
1613 }
1614 LocRange = SourceRange(StartLoc, EndLoc);
1615 return LocRange;
1616 }
1617
1618 bool RewriteUtils::removeSpecifier(NestedNameSpecifierLoc Loc)
1619 {
1620 SourceRange LocRange = getFileLocSourceRange(Loc.getLocalSourceRange());
1621 TransAssert((TheRewriter->getRangeSize(LocRange) != -1) &&
1622 "Bad NestedNameSpecifierLoc Range!");
1623 return !(TheRewriter->RemoveText(LocRange));
1624 }
1625
1626 bool RewriteUtils::replaceSpecifier(NestedNameSpecifierLoc Loc,
1627 const std::string &Name)
1628 {
1629 SourceRange LocRange = getFileLocSourceRange(Loc.getLocalSourceRange());
1630 TransAssert((TheRewriter->getRangeSize(LocRange) != -1) &&
1631 "Bad NestedNameSpecifierLoc Range!");
1632 return !(TheRewriter->ReplaceText(LocRange, Name + "::"));
1633 }
1634
1635 void RewriteUtils::getQualifierAsString(NestedNameSpecifierLoc Loc,
1636 std::string &Str)
1637 {
1638 SourceLocation StartLoc = Loc.getBeginLoc();
1639 TransAssert(StartLoc.isValid() && "Bad StartLoc for NestedNameSpecifier!");
1640 SourceRange Range = Loc.getSourceRange();
1641 int Len = TheRewriter->getRangeSize(Range);
1642 const char *StartBuf = SrcManager->getCharacterData(StartLoc);
1643 Str.assign(StartBuf, Len);
1644 }
1645
1646 void RewriteUtils::getSpecifierAsString(NestedNameSpecifierLoc Loc,
1647 std::string &Str)
1648 {
1649 SourceLocation StartLoc = Loc.getBeginLoc();
1650 TransAssert(StartLoc.isValid() && "Bad StartLoc for NestedNameSpecifier!");
1651 const char *StartBuf = SrcManager->getCharacterData(StartLoc);
1652 const char *OrigBuf = StartBuf;
1653 unsigned int Len = 0;
1654 while (!isspace(*StartBuf) && (*StartBuf != ':')) {
1655 StartBuf++;
1656 Len++;
1657 }
1658
1659 Str.assign(OrigBuf, Len);
1660 }
1661
1662 bool RewriteUtils::replaceRecordType(RecordTypeLoc &RTLoc,
1663 const std::string &Name)
1664 {
1665 const IdentifierInfo *TypeId = RTLoc.getType().getBaseTypeIdentifier();
1666 if (!TypeId)
1667 return true;
1668
1669 SourceLocation LocStart = RTLoc.getBeginLoc();
1670
1671 // Loc could be invalid, for example:
1672 // class AAA { };
1673 // class BBB:AAA {
1674 // public:
1675 // BBB () { }
1676 // };
1677 // In Clang's internal representation, BBB's Ctor is BBB() : AAA() {}
1678 // The implicit AAA() will be visited here
1679 // This is the only case where RTLoc is invalid, so the question is -
1680 // Is the guard below too strong? It is possible it could mask other
1681 // potential bugs?
1682 if (LocStart.isInvalid())
1683 return true;
1684
1685 return !(TheRewriter->ReplaceText(LocStart, TypeId->getLength(), Name));
1686 }
1687
1688 bool RewriteUtils::isTheFirstDecl(const VarDecl *VD)
1689 {
1690 SourceRange Range = VD->getSourceRange();
1691 SourceLocation StartLoc = Range.getBegin();
1692 SourceLocation NameStartLoc = VD->getLocation();
1693
1694 const char *StartBuf = SrcManager->getCharacterData(StartLoc);
1695 const char *NameStartBuf = SrcManager->getCharacterData(NameStartLoc);
1696
1697 while (StartBuf != NameStartBuf) {
1698 if (*StartBuf == ',')
1699 return false;
1700 StartBuf++;
1701 }
1702 return true;
1703 }
1704
1705 bool RewriteUtils::isSingleDecl(const VarDecl *VD)
1706 {
1707 if (!isTheFirstDecl(VD))
1708 return false;
1709
1710 SourceRange Range = VD->getSourceRange();
1711 SourceLocation StartLoc = Range.getBegin();
1712 int RangeSize = TheRewriter->getRangeSize(Range);
1713 SourceLocation EndLoc = StartLoc.getLocWithOffset(RangeSize);
1714 const char *EndBuf = SrcManager->getCharacterData(EndLoc);
1715 while (isspace(*EndBuf))
1716 EndBuf++;
1717
1718 return (*EndBuf == ';');
1719 }
1720
1721 // In case we don't know if VD is in a single decl group,
1722 // also we don't know if VD is the first decl or not.
1723 // once this version is well-tested, probably we should remove
1724 // bool RewriteUtils::removeVarDecl(const VarDecl *VD,
1725 // DeclGroupRef DGR)
1726 bool RewriteUtils::removeVarDecl(const VarDecl *VD)
1727 {
1728 if (isSingleDecl(VD)) {
1729 return removeDecl(VD);
1730 }
1731
1732 SourceRange VarRange = VD->getSourceRange();
1733
1734 // VD is the first declaration in a declaration group.
1735 // We keep the leading type string
1736 if (isTheFirstDecl(VD)) {
1737 // We need to get the outermost TypeLocEnd instead of the StartLoc of
1738 // a var name, because we need to handle the case below:
1739 // int *x, *y;
1740 // If we rely on the StartLoc of a var name, then we will make bad
1741 // transformation like:
1742 // int * *y;
1743 SourceLocation NewStartLoc = getVarDeclTypeLocEnd(VD);
1744
1745 SourceLocation NewEndLoc = getEndLocationUntil(VarRange, ',');
1746
1747 return
1748 !(TheRewriter->RemoveText(SourceRange(NewStartLoc, NewEndLoc)));
1749 }
1750
1751 SourceLocation NameLoc = VD->getLocation();
1752 SourceLocation VarStartLoc = VarRange.getBegin();
1753 const char *NameStartBuf = SrcManager->getCharacterData(NameLoc);
1754 const char *VarStartBuf = SrcManager->getCharacterData(VarStartLoc);
1755 int Offset = 0;
1756 TransAssert((VarStartBuf < NameStartBuf) && "Bad Name Location!");
1757 while (NameStartBuf != VarStartBuf) {
1758 if (*NameStartBuf == ',')
1759 break;
1760 Offset--;
1761 NameStartBuf--;
1762 }
1763 TransAssert((VarStartBuf < NameStartBuf) && "Cannot find comma!");
1764 SourceLocation PrevDeclEndLoc = NameLoc.getLocWithOffset(Offset);
1765 SourceLocation VarEndLoc = VarRange.getEnd();
1766
1767 return !(TheRewriter->RemoveText(SourceRange(PrevDeclEndLoc, VarEndLoc)));
1768 }
1769
1770 bool RewriteUtils::removeTextFromLeftAt(SourceRange Range, char C,
1771 SourceLocation EndLoc)
1772 {
1773 SourceLocation StartLoc = Range.getBegin();
1774 const char *StartBuf = SrcManager->getCharacterData(StartLoc);
1775 int Offset = 0;
1776 while (*StartBuf != C) {
1777 StartBuf--;
1778 Offset--;
1779 }
1780 StartLoc = StartLoc.getLocWithOffset(Offset);
1781 return !TheRewriter->RemoveText(SourceRange(StartLoc, EndLoc));
1782 }
1783
1784 SourceLocation RewriteUtils::getLocationFromLeftUntil(SourceLocation StartLoc,
1785 char C)
1786 {
1787 const char *StartBuf = SrcManager->getCharacterData(StartLoc);
1788 int Offset = 0;
1789 while (*StartBuf != C) {
1790 StartBuf--;
1791 Offset--;
1792 }
1793 return StartLoc.getLocWithOffset(Offset);
1794 }
1795
1796 bool RewriteUtils::removeTextUntil(SourceRange Range, char C)
1797 {
1798 SourceLocation StartLoc = Range.getBegin();
1799
1800 // I don't know the reason, but seems Clang treats the following two
1801 // cases differently:
1802 // (1) template<bool, typename>
1803 // in this case, the RangeSize is 5, which includes the ','
1804 // (2) template<typename, typename>
1805 // in this case, the RangeSize is 8, which excludes the comma
1806 SourceLocation EndLoc = Range.getEnd();
1807 const char *EndBuf = SrcManager->getCharacterData(EndLoc);
1808 if (*EndBuf != C)
1809 EndLoc = getEndLocationUntil(Range, C);
1810 return !TheRewriter->RemoveText(SourceRange(StartLoc, EndLoc));
1811 }
1812
1813 bool RewriteUtils::removeCXXCtorInitializer(const CXXCtorInitializer *Init,
1814 unsigned Index, unsigned NumInits)
1815 {
1816 SourceRange Range = Init->getSourceRange();
1817 SourceLocation EndLoc = Init->getRParenLoc();
1818 if (Index == 0) {
1819 if (NumInits == 1)
1820 return removeTextFromLeftAt(Range, ':', EndLoc);
1821 else
1822 return removeTextUntil(Range, ',');
1823 }
1824 else {
1825 return removeTextFromLeftAt(Range, ',', EndLoc);
1826 }
1827 }
1828
1829 bool RewriteUtils::removeClassDecls(const CXXRecordDecl *CXXRD)
1830 {
1831 for (CXXRecordDecl::redecl_iterator I = CXXRD->redecls_begin(),
1832 E = CXXRD->redecls_end(); I != E; ++I) {
1833 SourceRange Range = (*I)->getSourceRange();
1834 SourceLocation LocEnd;
1835 if ((*I)->isThisDeclarationADefinition()) {
1836 LocEnd = (*I)->getBraceRange().getEnd();
1837 if (LocEnd.isValid())
1838 LocEnd = getLocationUntil(LocEnd, ';');
1839 else
1840 LocEnd = getEndLocationUntil(Range, ';');
1841 }
1842 else {
1843 LocEnd = getEndLocationUntil(Range, ';');
1844 }
1845 TheRewriter->RemoveText(SourceRange(Range.getBegin(), LocEnd));
1846 }
1847 return true;
1848 }
1849
1850 bool RewriteUtils::removeClassTemplateDecls(const ClassTemplateDecl *TmplD)
1851 {
1852 for (ClassTemplateDecl::redecl_iterator I = TmplD->redecls_begin(),
1853 E = TmplD->redecls_end(); I != E; ++I) {
1854 const CXXRecordDecl *CXXRD =
1855 dyn_cast<CXXRecordDecl>((*I)->getTemplatedDecl());
1856 TransAssert(CXXRD && "Invalid class template!");
1857
1858 SourceRange Range = (*I)->getSourceRange();
1859 SourceLocation LocEnd;
1860 if (CXXRD->isThisDeclarationADefinition()) {
1861 LocEnd = CXXRD->getBraceRange().getEnd();
1862 LocEnd = getLocationUntil(LocEnd, ';');
1863 }
1864 else {
1865 LocEnd = getEndLocationUntil(Range, ';');
1866 }
1867 TheRewriter->RemoveText(SourceRange(Range.getBegin(), LocEnd));
1868 }
1869 return true;
1870 }
1871
1872 bool RewriteUtils::replaceCXXMethodNameAfterQualifier(
1873 const NestedNameSpecifierLoc *QualLoc,
1874 const CXXMethodDecl *MD,
1875 const std::string &NewName)
1876 {
1877 SourceLocation EndLoc = QualLoc->getEndLoc();
1878 const char *EndBuf = SrcManager->getCharacterData(EndLoc);
1879 unsigned int Offset = 0;
1880 while (isspace(*EndBuf) || (*EndBuf == ':')) {
1881 EndBuf++;
1882 Offset++;
1883 }
1884 EndLoc = EndLoc.getLocWithOffset(Offset);
1885 TheRewriter->ReplaceText(EndLoc, MD->getNameAsString().size(), NewName);
1886 return true;
1887 }
1888