summaryrefslogtreecommitdiff
path: root/clang/rename.cxx
blob: 4b87cb1ad8b11efbe7ac2f194a3d5dec2d531c4c (plain)
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
#include <fstream>
#include <iostream>
#include <set>
#include <sstream>

#include <clang/AST/ASTConsumer.h>
#include <clang/AST/ASTContext.h>
#include <clang/AST/RecursiveASTVisitor.h>
#include <clang/Rewrite/Core/Rewriter.h>
#include <clang/Tooling/CommonOptionsParser.h>
#include <clang/Tooling/Tooling.h>
#include <clang/Lex/Lexer.h>

namespace
{
/// From clang-tools-extra.git's clang-move/ClangMove.cpp.
clang::SourceLocation getLocForEndOfDecl(const clang::Decl *D, const clang::LangOptions &LangOpts = clang::LangOptions()) {
    const auto &SM = D->getASTContext().getSourceManager();
    auto EndExpansionLoc = SM.getExpansionLoc(D->getLocEnd());
    std::pair<clang::FileID, unsigned> LocInfo = SM.getDecomposedLoc(EndExpansionLoc);
    // Try to load the file buffer.
    bool InvalidTemp = false;
    llvm::StringRef File = SM.getBufferData(LocInfo.first, &InvalidTemp);
    if (InvalidTemp)
        return clang::SourceLocation();

    const char *TokBegin = File.data() + LocInfo.second;
    // Lex from the start of the given location.
    clang::Lexer Lex(SM.getLocForStartOfFile(LocInfo.first), LangOpts, File.begin(),TokBegin, File.end());

    llvm::SmallVector<char, 16> Line;
    // FIXME: this is a bit hacky to get ReadToEndOfLine work.
    Lex.setParsingPreprocessorDirective(true);
    Lex.ReadToEndOfLine(&Line);
    clang::SourceLocation EndLoc = EndExpansionLoc.getLocWithOffset(Line.size());
    // If we already reach EOF, just return the EOF SourceLocation;
    // otherwise, move 1 offset ahead to include the trailing newline character
    // '\n'.
    return SM.getLocForEndOfFile(LocInfo.first) == EndLoc ? EndLoc : EndLoc.getLocWithOffset(1);
}
}

class RenameRewriter : public clang::Rewriter
{
    /// Old names -> new names map.
    std::map<std::string, std::string> maNameMap;
    bool mbDump;

public:
    RenameRewriter(const std::map<std::string, std::string>& rNameMap, bool bDump)
        : maNameMap(rNameMap),
          mbDump(bDump)
    {
    }

    const std::map<std::string, std::string>& getNameMap()
    {
        return maNameMap;
    }

    bool getDump()
    {
        return mbDump;
    }
};

class RenameVisitor : public clang::RecursiveASTVisitor<RenameVisitor>
{
    RenameRewriter& mrRewriter;
    // A set of handled locations, so in case a location would be handled
    // multiple times due to macro usage, we only do the rewrite once.
    // Otherwise an A -> BA replacement would be done twice.
    std::set<clang::SourceLocation> maHandledLocations;

    void RewriteText(clang::SourceLocation aStart, unsigned nLength, const std::string& rOldName, const std::string& rPrefix = std::string())
    {
        std::string aOldName = rOldName;
        if (!rPrefix.empty())
            // E.g. rOldName is '~C' and rPrefix is '~', then check if 'C' is to be renamed.
            aOldName = aOldName.substr(rPrefix.size());
        const std::map<std::string, std::string>::const_iterator it = mrRewriter.getNameMap().find(aOldName);
        if (it != mrRewriter.getNameMap().end())
        {
            if (aStart.isMacroID())
                /*
                 * int foo(int x);
                 * #define FOO(a) foo(a)
                 * FOO(aC.nX); <- Handles this.
                 */
                aStart = mrRewriter.getSourceMgr().getSpellingLoc(aStart);
            if (maHandledLocations.find(aStart) == maHandledLocations.end())
            {
                std::string aNewName = it->second;
                if (!rPrefix.empty())
                    // E.g. aNewName is 'D' and rPrefix is '~', then rename to '~D'.
                    aNewName = rPrefix + aNewName;
                mrRewriter.ReplaceText(aStart, nLength, aNewName);
                maHandledLocations.insert(aStart);
            }
        }
    }

    /// Get the namespace part of a new name.
    std::string GetNamespace(const std::string& rOldName)
    {
        auto it = mrRewriter.getNameMap().find(rOldName);
        if (it == mrRewriter.getNameMap().end())
            return std::string();

        std::string aNewName = it->second;
        std::string::size_type nPos = aNewName.find("::");
        if (nPos == std::string::npos)
            return std::string();

        return aNewName.substr(0, nPos);
    }

    /// Get the local name part of a new name.
    std::string GetLocalName(const std::string& rOldName)
    {
        auto it = mrRewriter.getNameMap().find(rOldName);
        if (it == mrRewriter.getNameMap().end())
            return std::string();

        std::string aNewName = it->second;
        std::string::size_type nPos = aNewName.find("::");
        if (nPos == std::string::npos)
            return aNewName;

        return aNewName.substr(nPos + strlen("::"));
    }

    /// If a new name has a namespace part.
    bool HasNamespace(const std::string& rOldName)
    {
        return !GetNamespace(rOldName).empty();
    }

public:
    explicit RenameVisitor(RenameRewriter& rRewriter)
        : mrRewriter(rRewriter)
    {
    }

    // Data member names.

    /*
     * class C
     * {
     * public:
     *     int nX; <- Handles this declaration.
     * };
     */
    bool VisitFieldDecl(clang::FieldDecl* pDecl)
    {
        // Qualified name includes "C::" as a prefix, normal name does not.
        std::string aName = pDecl->getQualifiedNameAsString();
        RewriteText(pDecl->getLocation(), pDecl->getNameAsString().length(), aName);
        return true;
    }

    /*
     * class C
     * {
     * public:
     *     static const int aS[]; <- Handles e.g. this declaration;
     * };
     */
    bool VisitVarDecl(clang::VarDecl* pDecl)
    {
        std::string aName = pDecl->getQualifiedNameAsString();
        RewriteText(pDecl->getLocation(), pDecl->getNameAsString().length(), aName);

        /*
         * C* pC = 0;
         * ^ Handles this.
         */
        clang::QualType pType = pDecl->getType();
        const clang::RecordDecl* pRecordDecl = pType->getPointeeCXXRecordDecl();
        if (pRecordDecl)
        {
            aName = pRecordDecl->getNameAsString();
            RewriteText(pDecl->getTypeSpecStartLoc(), pRecordDecl->getNameAsString().length(), aName);
        }
        else if (clang::CXXRecordDecl* pCXXRecordDecl = pType->getAsCXXRecordDecl())
        {
            /*
             * C c;
             * ^ Handles this.
             */
            aName = pCXXRecordDecl->getNameAsString();
            RewriteText(pDecl->getTypeSpecStartLoc(), pCXXRecordDecl->getNameAsString().length(), aName);
        }
        return true;
    }

    /*
     * C::C()
     *     : nX(0) <- Handles this initializer.
     * {
     * }
     */
    bool VisitCXXConstructorDecl(clang::CXXConstructorDecl* pDecl)
    {
        for (clang::CXXConstructorDecl::init_const_iterator itInit = pDecl->init_begin(); itInit != pDecl->init_end(); ++itInit)
        {
            const clang::CXXCtorInitializer* pInitializer = *itInit;

            // Ignore implicit initializers.
            if (pInitializer->getSourceOrder() == -1)
                continue;

            if (const clang::FieldDecl* pFieldDecl = pInitializer->getAnyMember())
            {
                std::string aName = pFieldDecl->getQualifiedNameAsString();
                RewriteText(pInitializer->getSourceLocation(), pFieldDecl->getNameAsString().length(), aName);
            }
        }

        std::string aName = pDecl->getNameAsString();
        /*
         * Foo::Foo(...) {}
         * ^~~ Handles this.
         */
        if (!HasNamespace(aName) || pDecl->isThisDeclarationADefinition())
            RewriteText(pDecl->getLocStart(), aName.length(), aName);

        /*
         * Foo::Foo(...) {}
         *      ^~~ Handles this.
         */
        if (!HasNamespace(aName))
            RewriteText(pDecl->getLocation(), aName.length(), aName);

        return true;
    }

    bool VisitCXXDestructorDecl(clang::CXXDestructorDecl* pDecl)
    {
        std::string aName = pDecl->getNameAsString();
        std::string aPrefix("~");
        if (pDecl->getLocStart() != pDecl->getLocation())
        {
            /*
             * Foo::~Foo(...) {}
             * ^~~ Handles this.
             */
            if (!HasNamespace(aName.substr(aPrefix.size())) || pDecl->isThisDeclarationADefinition())
                RewriteText(pDecl->getLocStart(), pDecl->getNameAsString().length() - aPrefix.size(), aName.substr(aPrefix.size()));
        }

        /*
         * Foo::~Foo(...) {}
         *      ^~~ Handles this.
         */
        if (!HasNamespace(aName.substr(aPrefix.size())))
            RewriteText(pDecl->getLocation(), pDecl->getNameAsString().length(), aName, aPrefix);

        return true;
    }

    /*
     * C aC;
     * aC.nX = 1; <- Handles e.g. this...
     * int y = aC.nX; <- ...and this.
     */
    bool VisitMemberExpr(clang::MemberExpr* pExpr)
    {
        if (clang::ValueDecl* pDecl = pExpr->getMemberDecl())
        {
            std::string aName = pDecl->getQualifiedNameAsString();
            RewriteText(pExpr->getMemberLoc(), pDecl->getNameAsString().length(), aName);
        }
        return true;
    }

    /*
     * class C
     * {
     * public:
     *     static const int aS[];
     *     static const int* getS() { return aS; } <- Handles this.
     * };
     */
    bool VisitDeclRefExpr(clang::DeclRefExpr* pExpr)
    {
        if (clang::ValueDecl* pDecl = pExpr->getDecl())
        {
            std::string aName = pDecl->getQualifiedNameAsString();
            RewriteText(pExpr->getLocation(), pDecl->getNameAsString().length(), aName);
        }
        return true;
    }

    // Member function names.

    /*
     * class C
     * {
     * public:
     *     foo(); <- Handles this.
     * };
     *
     * C::foo() <- And this.
     * {
     * }
     *
     * ...
     *
     * aC.foo(); <- And this.
     */
    bool VisitCXXMethodDecl(const clang::CXXMethodDecl* pDecl)
    {
        std::string aName = pDecl->getQualifiedNameAsString();
        RewriteText(pDecl->getLocation(), pDecl->getNameAsString().length(), aName);

        /*
         * void C::foo() {}
         *      ^ Handles this.
         */
        std::string aClassName = pDecl->getParent()->getNameAsString();
        if (HasNamespace(aClassName) && pDecl->isThisDeclarationADefinition())
            RewriteText(pDecl->getQualifierLoc().getBeginLoc(), aClassName.length(), aClassName);

        /*
         * inline C C::bar() { return C(); }
         *        ^ Handle this.
         */
        if (HasNamespace(aClassName))
        {
            clang::QualType pType = pDecl->getReturnType();
            const clang::RecordDecl* pRecordDecl = pType->getAsCXXRecordDecl();

            /*
             * inline C& C::bar() { return *this; }
             *        ^ Handle this.
             */
            if (!pRecordDecl)
            {
                if (const clang::ReferenceType* pReferenceType = pType->getAs<clang::ReferenceType>())
                    pRecordDecl = pReferenceType->getPointeeType()->getAsCXXRecordDecl();
            }

            if (pRecordDecl)
                RewriteText(pDecl->getReturnTypeSourceRange().getBegin(), pRecordDecl->getNameAsString().length(), pRecordDecl->getNameAsString());
        }
        return true;
    }

    // Class names.

    /*
     * class C <- Handles this.
     * {
     * };
     */
    bool VisitCXXRecordDecl(const clang::CXXRecordDecl* pDecl)
    {
        std::string aName = pDecl->getQualifiedNameAsString();
        if (HasNamespace(aName))
        {
            std::string aInsert = "namespace ";
            aInsert += GetNamespace(aName);
            aInsert += "\n{\n";
            mrRewriter.ReplaceText(pDecl->getLocStart(), 0, aInsert);
            mrRewriter.ReplaceText(getLocForEndOfDecl(pDecl), 0, "}\n");
        }
        else
            RewriteText(pDecl->getLocation(), pDecl->getNameAsString().length(), aName);
        return true;
    }

    /*
     * ... new C(...); <- Handles this.
     */
    bool VisitCXXNewExpr(const clang::CXXNewExpr* pExpr)
    {
        if (const clang::CXXConstructExpr* pConstructExpr = pExpr->getConstructExpr())
        {
            if (const clang::CXXConstructorDecl* pDecl = pConstructExpr->getConstructor())
            {
                std::string aName = pDecl->getNameAsString();
                RewriteText(pConstructExpr->getLocation(), pDecl->getNameAsString().length(), aName);
            }
        }

        return true;
    }

    /*
     * ... static_cast<const C*>(...) ...;
     *                       ^ Handles this...
     *
     * ... static_cast<const C&>(...) ...;
     *                       ^ ... and this.
     *
     * ... and the same for dynamic_cast<>().
     */
    bool handleCXXNamedCastExpr(clang::CXXNamedCastExpr* pExpr)
    {
        clang::QualType pType = pExpr->getType();
        const clang::RecordDecl* pDecl = pType->getPointeeCXXRecordDecl();
        if (!pDecl)
            pDecl = pType->getAsCXXRecordDecl();
        if (pDecl)
        {
            std::string aName = pDecl->getNameAsString();
            clang::SourceLocation aLocation = pExpr->getTypeInfoAsWritten()->getTypeLoc().getBeginLoc();
            RewriteText(aLocation, pDecl->getNameAsString().length(), aName);
        }
        return true;
    }

    bool VisitCXXStaticCastExpr(clang::CXXStaticCastExpr* pExpr)
    {
        return handleCXXNamedCastExpr(pExpr);
    }

    bool VisitCXXDynamicCastExpr(clang::CXXDynamicCastExpr* pExpr)
    {
        return handleCXXNamedCastExpr(pExpr);
    }

    bool VisitCXXReinterpretCastExpr(clang::CXXReinterpretCastExpr* pExpr)
    {
        return handleCXXNamedCastExpr(pExpr);
    }

    bool VisitCXXConstCastExpr(clang::CXXConstCastExpr* pExpr)
    {
        return handleCXXNamedCastExpr(pExpr);
    }
};

class RenameASTConsumer : public clang::ASTConsumer
{
    RenameRewriter& mrRewriter;

    std::string getNewName(const clang::FileEntry& rEntry)
    {
        std::stringstream ss;
        ss << rEntry.getName();
        ss << ".new-rename";
        return ss.str();
    }

public:
    RenameASTConsumer(RenameRewriter& rRewriter)
        : mrRewriter(rRewriter)
    {
    }

    virtual void HandleTranslationUnit(clang::ASTContext& rContext)
    {
        if (rContext.getDiagnostics().hasErrorOccurred())
            return;

        RenameVisitor aVisitor(mrRewriter);
        mrRewriter.setSourceMgr(rContext.getSourceManager(), rContext.getLangOpts());
        aVisitor.TraverseDecl(rContext.getTranslationUnitDecl());

        for (clang::Rewriter::buffer_iterator it = mrRewriter.buffer_begin(); it != mrRewriter.buffer_end(); ++it)
        {
            if (mrRewriter.getDump())
                it->second.write(llvm::errs());
            else
            {
                const clang::FileEntry* pEntry = rContext.getSourceManager().getFileEntryForID(it->first);
                if (!pEntry)
                    continue;
                std::string aNewName = getNewName(*pEntry);
#if (__clang_major__ == 3 && __clang_minor__ >= 6) || __clang_major__ > 3
                std::error_code aError;
                std::unique_ptr<llvm::raw_fd_ostream> pStream(new llvm::raw_fd_ostream(aNewName, aError, llvm::sys::fs::F_None));
                if (!aError)
#else
                std::string aError;
                std::unique_ptr<llvm::raw_fd_ostream> pStream(new llvm::raw_fd_ostream(aNewName.c_str(), aError, llvm::sys::fs::F_None));
                if (aError.empty())
#endif
                    it->second.write(*pStream);
            }
        }
    }
};

class RenameFrontendAction
{
    RenameRewriter& mrRewriter;

public:
    RenameFrontendAction(RenameRewriter& rRewriter)
        : mrRewriter(rRewriter)
    {
    }

#if (__clang_major__ == 3 && __clang_minor__ >= 6) || __clang_major__ > 3
    std::unique_ptr<clang::ASTConsumer> newASTConsumer()
    {
        return llvm::make_unique<RenameASTConsumer>(mrRewriter);
    }
#else
    clang::ASTConsumer* newASTConsumer()
    {
        return new RenameASTConsumer(mrRewriter);
    }
#endif
};

/// Parses rCsv and puts the first two column of it into rNameMap.
static bool parseCsv(const std::string& rCsv, std::map<std::string, std::string>& rNameMap)
{
    std::ifstream aStream(rCsv);
    if (!aStream.is_open())
    {
        std::cerr << "parseCsv: failed to open " << rCsv << std::endl;
        return false;
    }

    std::string aLine;
    while (std::getline(aStream, aLine))
    {
        std::stringstream ss(aLine);
        std::string aOldName;
        std::getline(ss, aOldName, ',');
        if (aOldName.empty())
        {
            std::cerr << "parseCsv: first column is empty for line '" << aLine << "'" << std::endl;
            return false;
        }
        std::string aNewName;
        std::getline(ss, aNewName, ',');
        if (aNewName.empty())
        {
            std::cerr << "parseCsv: second column is empty for line '" << aLine << "'" << std::endl;
            return false;
        }
        rNameMap[aOldName] = aNewName;
    }

    aStream.close();
    return true;
}

int main(int argc, const char** argv)
{
    llvm::cl::OptionCategory aCategory("rename options");
    llvm::cl::OptionCategory aCategory2("rename options");
    llvm::cl::opt<std::string> aOldName("old-name",
                                        llvm::cl::desc("Old, qualified name (Class::member)."),
                                        llvm::cl::cat(aCategory), llvm::cl::cat(aCategory2));
    llvm::cl::opt<std::string> aNewName("new-name",
                                        llvm::cl::desc("New, non-qualified name (without Class::)."),
                                        llvm::cl::cat(aCategory));
    llvm::cl::opt<std::string> aCsv("csv",
                                    llvm::cl::desc("Path to a CSV file, containing multiple renames -- seprator must be a comma (,)."),
                                    llvm::cl::cat(aCategory));
    llvm::cl::opt<bool> bDump("dump",
                              llvm::cl::desc("Dump output on the console instead of writing to .new files."),
                              llvm::cl::cat(aCategory));
    clang::tooling::CommonOptionsParser aParser(argc, argv, aCategory);

    std::map<std::string, std::string> aNameMap;
    if (!aOldName.empty() && !aNewName.empty())
        aNameMap[aOldName] = aNewName;
    else if (!aCsv.empty())
    {
        if (!parseCsv(aCsv, aNameMap))
            return 1;
    }
    else
    {
        std::cerr << "either -old-name + -new-name or -csv is required." << std::endl;
        return 1;
    }

    clang::tooling::ClangTool aTool(aParser.getCompilations(), aParser.getSourcePathList());

    RenameRewriter aRewriter(aNameMap, bDump);
    RenameFrontendAction aAction(aRewriter);
    std::unique_ptr<clang::tooling::FrontendActionFactory> pFactory = clang::tooling::newFrontendActionFactory(&aAction);
    return aTool.run(pFactory.get());
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */