summaryrefslogtreecommitdiff
path: root/compilerplugins/clang/plugin.cxx
blob: 143897b499d5349c427cfcaf0b993bd56fd49f2b (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
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * Based on LLVM/Clang.
 *
 * This file is distributed under the University of Illinois Open Source
 * License. See LICENSE.TXT for details.
 *
 */

#include "plugin.hxx"

#include <cassert>
#include <string>

#include <clang/Basic/FileManager.h>
#include <clang/Lex/Lexer.h>

#include "pluginhandler.hxx"

/*
Base classes for plugin actions.
*/
namespace loplugin
{

Plugin::Plugin( const InstantiationData& data )
    : compiler( data.compiler ), handler( data.handler ), name( data.name )
    {
    }

DiagnosticBuilder Plugin::report( DiagnosticsEngine::Level level, StringRef message, SourceLocation loc ) const
    {
    return handler.report( level, name, message, compiler, loc );
    }

bool Plugin::ignoreLocation( SourceLocation loc )
    {
    SourceLocation expansionLoc = compiler.getSourceManager().getExpansionLoc( loc );
    if( compiler.getSourceManager().isInSystemHeader( expansionLoc ))
        return true;
    const char* bufferName = compiler.getSourceManager().getPresumedLoc( expansionLoc ).getFilename();
    if( bufferName == NULL
        || strncmp( bufferName, SRCDIR "/external/", strlen( SRCDIR "/external/" )) == 0 )
        return true;
    if( strncmp( bufferName, WORKDIR, strlen( WORKDIR )) == 0 )
    {
        // workdir/CustomTarget/vcl/unx/kde4/tst_exclude_socket_notifiers.moc
        // includes
        // "../../../../../vcl/unx/kde4/tst_exclude_socket_notifiers.hxx",
        // making the latter file erroneously match here; so strip any ".."
        // segments:
        if (strstr(bufferName, "/..") == nullptr) {
            return true;
        }
        std::string s(bufferName);
        normalizeDotDotInFilePath(s);
        if (strncmp(s.c_str(), WORKDIR, strlen(WORKDIR)) == 0) {
            return true;
        }
    }
    if( strncmp( bufferName, BUILDDIR, strlen( BUILDDIR )) == 0
        || strncmp( bufferName, SRCDIR, strlen( SRCDIR )) == 0 )
        return false; // ok
    return true;
    }

void Plugin::normalizeDotDotInFilePath( std::string & s )
    {
    for (std::string::size_type i = 0;;) {
        i = s.find("/.", i);
        if (i == std::string::npos) {
            break;
        }
        if (i + 2 == s.length() || s[i + 2] == '/') {
            s.erase(i, 2); // [AAA]/.[/CCC] -> [AAA][/CCC]
        } else if (s[i + 2] == '.'
                   && (i + 3 == s.length() || s[i + 3] == '/'))
        {
            if (i == 0) { // /..[/CCC] -> /..[/CCC]
                break;
            }
            auto j = s.rfind('/', i - 1);
            if (j == std::string::npos) {
                // BBB/..[/CCC] -> BBB/..[/CCC] (instead of BBB/../CCC ->
                // CCC, to avoid wrong ../../CCC -> CCC; relative paths
                // shouldn't happen anyway, and even if they did, wouldn't
                // match against WORKDIR anyway, as WORKDIR should be
                // absolute):
                break;
            }
            s.erase(j, i + 3 - j); // AAA/BBB/..[/CCC] -> AAA[/CCC]
            i = j;
        } else {
            i += 2;
        }
    }
    }

void Plugin::registerPlugin( Plugin* (*create)( const InstantiationData& ), const char* optionName, bool isPPCallback, bool byDefault )
    {
    PluginHandler::registerPlugin( create, optionName, isPPCallback, byDefault );
    }

unordered_map< const Stmt*, const Stmt* > Plugin::parents;

const Stmt* Plugin::parentStmt( const Stmt* stmt )
    {
    if( parents.empty())
        buildParents( compiler );
    //if(parents.count(stmt)!=1)stmt->dump();
    //assert( parents.count( stmt ) == 1 );
    return parents[ stmt ];
    }

Stmt* Plugin::parentStmt( Stmt* stmt )
    {
    if( parents.empty())
        buildParents( compiler );
    //assert( parents.count( stmt ) == 1 );
    return const_cast< Stmt* >( parents[ stmt ] );
    }

static const Decl* getDeclContext(ASTContext& context, const Stmt* stmt)
    {
    auto it = context.getParents(*stmt).begin();

    if (it == context.getParents(*stmt).end())
          return nullptr;

    const Decl *aDecl = it->get<Decl>();
    if (aDecl)
          return aDecl;

    const Stmt *aStmt = it->get<Stmt>();
    if (aStmt)
        return getDeclContext(context, aStmt);

    return nullptr;
    }

const FunctionDecl* Plugin::parentFunctionDecl( const Stmt* stmt )
    {
    const Decl *decl = getDeclContext(compiler.getASTContext(), stmt);
    if (decl)
        return static_cast<const FunctionDecl*>(decl->getNonClosureContext());

    return nullptr;
    }


bool Plugin::isInUnoIncludeFile(SourceLocation spellingLocation) const {
    StringRef name {
        compiler.getSourceManager().getFilename(spellingLocation) };
    return compiler.getSourceManager().isInMainFile(spellingLocation)
        ? (name == SRCDIR "/cppu/source/cppu/compat.cxx"
           || name == SRCDIR "/cppuhelper/source/compat.cxx"
           || name == SRCDIR "/sal/osl/all/compat.cxx")
        : (name.startswith(SRCDIR "/include/com/")
           || name.startswith(SRCDIR "/include/cppu/")
           || name.startswith(SRCDIR "/include/cppuhelper/")
           || name.startswith(SRCDIR "/include/osl/")
           || name.startswith(SRCDIR "/include/rtl/")
           || name.startswith(SRCDIR "/include/sal/")
           || name.startswith(SRCDIR "/include/salhelper/")
           || name.startswith(SRCDIR "/include/systools/")
           || name.startswith(SRCDIR "/include/typelib/")
           || name.startswith(SRCDIR "/include/uno/"));
}

bool Plugin::isInUnoIncludeFile(const FunctionDecl* functionDecl) const {
    return isInUnoIncludeFile(compiler.getSourceManager().getSpellingLoc(
             functionDecl->getCanonicalDecl()->getNameInfo().getLoc()));
}

namespace
{
class ParentBuilder
    : public RecursiveASTVisitor< ParentBuilder >
    {
    public:
        bool VisitFunctionDecl( const FunctionDecl* function );
        bool VisitObjCMethodDecl( const ObjCMethodDecl* method );
        void walk( const Stmt* stmt );
        bool shouldVisitTemplateInstantiations () const { return true; }
        unordered_map< const Stmt*, const Stmt* >* parents;
    };

bool ParentBuilder::VisitFunctionDecl( const FunctionDecl* function )
    {
//    if( ignoreLocation( declaration ))
//        return true; ???
    if( function->doesThisDeclarationHaveABody())
        {
        const Stmt* body = function->getBody();
        (*parents)[ body ] = NULL; // no parent
        walk( body );
        }
    if( const CXXConstructorDecl* ctor = dyn_cast< CXXConstructorDecl >( function ))
        {
        for( CXXConstructorDecl::init_const_iterator it = ctor->init_begin();
             it != ctor->init_end();
             ++it )
            {
            const Expr* init_expression = (*it)->getInit();
            (*parents)[ init_expression ] = NULL;
            walk( init_expression );
            }
        }
    return true;
    }

bool ParentBuilder::VisitObjCMethodDecl( const ObjCMethodDecl* method )
    {
//    if( ignoreLocation( declaration ))
//        return true; ???
    if( method->hasBody())
        {
        const Stmt* body = method->getBody();
        (*parents)[ body ] = NULL; // no parent
        walk( body );
        }
    return true;
    }

void ParentBuilder::walk( const Stmt* stmt )
    {
    for( ConstStmtIterator it = stmt->child_begin();
         it != stmt->child_end();
         ++it )
        {
        if( *it != NULL )
            {
            (*parents)[ *it ] = stmt;
            walk( *it );
            }
        }
    }

} // namespace

void Plugin::buildParents( CompilerInstance& compiler )
    {
    assert( parents.empty());
    ParentBuilder builder;
    builder.parents = &parents;
    builder.TraverseDecl( compiler.getASTContext().getTranslationUnitDecl());
    }

SourceLocation Plugin::locationAfterToken( SourceLocation location )
    {
    return Lexer::getLocForEndOfToken( location, 0, compiler.getSourceManager(), compiler.getLangOpts());
    }

RewritePlugin::RewritePlugin( const InstantiationData& data )
    : Plugin( data )
    , rewriter( data.rewriter )
    {
    }

bool RewritePlugin::insertText( SourceLocation Loc, StringRef Str, bool InsertAfter, bool indentNewLines )
    {
    assert( rewriter );
    if( rewriter->InsertText( Loc, Str, InsertAfter, indentNewLines ))
        return reportEditFailure( Loc );
    return true;
    }

bool RewritePlugin::insertTextAfter( SourceLocation Loc, StringRef Str )
    {
    assert( rewriter );
    if( rewriter->InsertTextAfter( Loc, Str ))
        return reportEditFailure( Loc );
    return true;
    }

bool RewritePlugin::insertTextAfterToken( SourceLocation Loc, StringRef Str )
    {
    assert( rewriter );
    if( rewriter->InsertTextAfterToken( Loc, Str ))
        return reportEditFailure( Loc );
    return true;
    }

bool RewritePlugin::insertTextBefore( SourceLocation Loc, StringRef Str )
    {
    assert( rewriter );
    if( rewriter->InsertTextBefore( Loc, Str ))
        return reportEditFailure( Loc );
    return true;
    }

bool RewritePlugin::removeText( SourceLocation Start, unsigned Length, RewriteOptions opts )
    {
    CharSourceRange range( SourceRange( Start, Start.getLocWithOffset( Length )), false );
    return removeText( range, opts );
    }

bool RewritePlugin::removeText( SourceRange range, RewriteOptions opts )
    {
    return removeText( CharSourceRange( range, true ), opts );
    }

bool RewritePlugin::removeText( CharSourceRange range, RewriteOptions opts )
    {
    assert( rewriter );
    if( rewriter->getRangeSize( range, opts ) == -1 )
        return reportEditFailure( range.getBegin());
    if( !handler.addRemoval( range.getBegin() ) )
        {
        report( DiagnosticsEngine::Warning, "double code removal, possible plugin error", range.getBegin());
        return true;
        }
    if( opts.flags & RemoveWholeStatement || opts.flags & RemoveAllWhitespace )
        {
        if( !adjustRangeForOptions( &range, opts ))
            return reportEditFailure( range.getBegin());
        }
    if( rewriter->RemoveText( range, opts ))
        return reportEditFailure( range.getBegin());
    return true;
    }

bool RewritePlugin::adjustRangeForOptions( CharSourceRange* range, RewriteOptions opts )
    {
    assert( rewriter );
    SourceManager& SM = rewriter->getSourceMgr();
    SourceLocation fileStartLoc = SM.getLocForStartOfFile( SM.getFileID( range->getBegin()));
    if( fileStartLoc.isInvalid())
        return false;
    bool isInvalid = false;
    const char* fileBuf = SM.getCharacterData( fileStartLoc, &isInvalid );
    if( isInvalid )
        return false;
    const char* startBuf = SM.getCharacterData( range->getBegin(), &isInvalid );
    if( isInvalid )
        return false;
    SourceLocation locationEnd = range->getEnd();
    if( range->isTokenRange())
        locationEnd = locationAfterToken( locationEnd );
    const char* endBuf = SM.getCharacterData( locationEnd, &isInvalid );
    if( isInvalid )
        return false;
    const char* startPos = startBuf;
    --startPos;
    while( startPos >= fileBuf && ( *startPos == ' ' || *startPos == '\t' ))
        --startPos;
    if( startPos >= fileBuf && *startPos == '\n' )
        startPos = startBuf - 1; // do not remove indentation whitespace (RemoveLineIfEmpty can do that)
    const char* endPos = endBuf;
    while( *endPos == ' ' || *endPos == '\t' )
        ++endPos;
    if( opts.flags & RemoveWholeStatement )
        {
        if( *endPos == ';' )
            ++endPos;
        else
            return false;
        }
    *range = CharSourceRange( SourceRange( range->getBegin().getLocWithOffset( startPos - startBuf + 1 ),
        locationEnd.getLocWithOffset( endPos - endBuf )), false );
    return true;
    }

bool RewritePlugin::replaceText( SourceLocation Start, unsigned OrigLength, StringRef NewStr )
    {
    assert( rewriter );
    if( OrigLength != 0 && !handler.addRemoval( Start ) )
        {
        report( DiagnosticsEngine::Warning, "double code replacement, possible plugin error", Start );
        return true;
        }
    if( rewriter->ReplaceText( Start, OrigLength, NewStr ))
        return reportEditFailure( Start );
    return true;
    }

bool RewritePlugin::replaceText( SourceRange range, StringRef NewStr )
    {
    assert( rewriter );
    if( rewriter->getRangeSize( range ) == -1 )
        return reportEditFailure( range.getBegin());
    if( !handler.addRemoval( range.getBegin() ) )
        {
        report( DiagnosticsEngine::Warning, "double code replacement, possible plugin error", range.getBegin());
        return true;
        }
    if( rewriter->ReplaceText( range, NewStr ))
        return reportEditFailure( range.getBegin());
    return true;
    }

bool RewritePlugin::replaceText( SourceRange range, SourceRange replacementRange )
    {
    assert( rewriter );
    if( rewriter->getRangeSize( range ) == -1 )
        return reportEditFailure( range.getBegin());
    if( !handler.addRemoval( range.getBegin() ) )
        {
        report( DiagnosticsEngine::Warning, "double code replacement, possible plugin error", range.getBegin());
        return true;
        }
    if( rewriter->ReplaceText( range, replacementRange ))
        return reportEditFailure( range.getBegin());
    return true;
    }

bool RewritePlugin::reportEditFailure( SourceLocation loc )
    {
    report( DiagnosticsEngine::Warning, "cannot perform source modification (macro expansion involved?)", loc );
    return false;
    }

} // namespace

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