insertionpointlocator.cpp 17.8 KB
Newer Older
1
2
3
4
/**************************************************************************
**
** This file is part of Qt Creator
**
con's avatar
con committed
5
** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
6
**
hjk's avatar
hjk committed
7
** Contact: Nokia Corporation (info@qt.nokia.com)
8
9
10
11
**
**
** GNU Lesser General Public License Usage
**
hjk's avatar
hjk committed
12
13
14
15
16
17
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this file.
** Please review the following information to ensure the GNU Lesser General
** Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
18
**
con's avatar
con committed
19
** In addition, as a special exception, Nokia gives you certain additional
hjk's avatar
hjk committed
20
** rights. These rights are described in the Nokia Qt LGPL Exception
con's avatar
con committed
21
22
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
hjk's avatar
hjk committed
23
24
25
26
27
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
con's avatar
con committed
28
** If you have questions regarding the use of this file, please contact
Tobias Hunger's avatar
Tobias Hunger committed
29
** Nokia at info@qt.nokia.com.
30
31
32
**
**************************************************************************/

33
#include "cpptoolsplugin.h"
34
#include "cpprefactoringchanges.h"
35
#include "insertionpointlocator.h"
36
37
38
39

#include <AST.h>
#include <ASTVisitor.h>
#include <TranslationUnit.h>
40
#include <Literals.h>
41
#include <Symbols.h>
42

43
44
45
#include <coreplugin/icore.h>
#include <coreplugin/mimedatabase.h>

46
using namespace CPlusPlus;
47
using namespace CppTools;
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70

namespace {

static QString generate(InsertionPointLocator::AccessSpec xsSpec)
{
    switch (xsSpec) {
    default:
    case InsertionPointLocator::Public:
        return QLatin1String("public:\n");

    case InsertionPointLocator::Protected:
        return QLatin1String("protected:\n");

    case InsertionPointLocator::Private:
        return QLatin1String("private:\n");

    case InsertionPointLocator::PublicSlot:
        return QLatin1String("public slots:\n");

    case InsertionPointLocator::ProtectedSlot:
        return QLatin1String("protected slots:\n");

    case InsertionPointLocator::PrivateSlot:
71
        return QLatin1String("private slots:\n");
72
73
74
75
76
77

    case InsertionPointLocator::Signals:
        return QLatin1String("signals:\n");
    }
}

78
static int ordering(InsertionPointLocator::AccessSpec xsSpec)
79
{
80
    static QList<InsertionPointLocator::AccessSpec> order = QList<InsertionPointLocator::AccessSpec>()
81
82
83
84
85
86
87
88
89
            << InsertionPointLocator::Public
            << InsertionPointLocator::PublicSlot
            << InsertionPointLocator::Signals
            << InsertionPointLocator::Protected
            << InsertionPointLocator::ProtectedSlot
            << InsertionPointLocator::PrivateSlot
            << InsertionPointLocator::Private
            ;

90
    return order.indexOf(xsSpec);
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
}

struct AccessRange
{
    unsigned start;
    unsigned end;
    InsertionPointLocator::AccessSpec xsSpec;

    AccessRange()
        : start(0)
        , end(0)
        , xsSpec(InsertionPointLocator::Invalid)
    {}

    AccessRange(unsigned start, unsigned end, InsertionPointLocator::AccessSpec xsSpec)
        : start(start)
        , end(end)
        , xsSpec(xsSpec)
    {}
};

class FindInClass: public ASTVisitor
{
public:
    FindInClass(const Document::Ptr &doc, const Class *clazz, InsertionPointLocator::AccessSpec xsSpec)
        : ASTVisitor(doc->translationUnit())
        , _doc(doc)
        , _clazz(clazz)
        , _xsSpec(xsSpec)
    {}

    InsertionLocation operator()()
    {
        _result = InsertionLocation();

        AST *ast = translationUnit()->ast();
        accept(ast);

        return _result;
    }

protected:
    using ASTVisitor::visit;

    bool visit(ClassSpecifierAST *ast)
    {
        if (!ast->lbrace_token || !ast->rbrace_token)
            return true;
        if (!ast->symbol || !ast->symbol->isEqualTo(_clazz))
            return true;

        QList<AccessRange> ranges = collectAccessRanges(
                    ast->member_specifier_list,
                    tokenKind(ast->classkey_token) == T_CLASS ? InsertionPointLocator::Private : InsertionPointLocator::Public,
                    ast->lbrace_token,
                    ast->rbrace_token);

148
149
150
151
        unsigned beforeToken = 0;
        bool needsPrefix = false;
        bool needsSuffix = false;
        findMatch(ranges, _xsSpec, beforeToken, needsPrefix, needsSuffix);
152
153

        unsigned line = 0, column = 0;
154
        getTokenStartPosition(beforeToken, &line, &column);
155
156

        QString prefix;
157
        if (needsPrefix)
158
159
            prefix = generate(_xsSpec);

160
161
162
163
        QString suffix;
        if (needsSuffix)
            suffix = QLatin1Char('\n');

164
165
        _result = InsertionLocation(_doc->fileName(), prefix, suffix,
                                    line, column);
166
167
168
        return false;
    }

169
170
171
172
173
    static void findMatch(const QList<AccessRange> &ranges,
                          InsertionPointLocator::AccessSpec xsSpec,
                          unsigned &beforeToken,
                          bool &needsPrefix,
                          bool &needsSuffix)
174
    {
175
176
177
        Q_ASSERT(!ranges.isEmpty());
        const int lastIndex = ranges.size() - 1;

178
        // try an exact match, and ignore the first (default) access spec:
179
        for (int i = lastIndex; i > 0; --i) {
180
            const AccessRange &range = ranges.at(i);
181
182
183
184
185
186
            if (range.xsSpec == xsSpec) {
                beforeToken = range.end;
                needsPrefix = false;
                needsSuffix = (i != lastIndex);
                return;
            }
187
188
        }

189
190
191
192
193
194
195
196
197
198
        // try to find a fitting access spec to insert XXX:
        for (int i = lastIndex; i > 0; --i) {
            const AccessRange &current = ranges.at(i);

            if (ordering(xsSpec) > ordering(current.xsSpec)) {
                beforeToken = current.end;
                needsPrefix = true;
                needsSuffix = (i != lastIndex);
                return;
            }
199
200
201
        }

        // otherwise:
202
203
204
        beforeToken = ranges.first().end;
        needsPrefix = true;
        needsSuffix = (ranges.size() != 1);
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
    }

    QList<AccessRange> collectAccessRanges(DeclarationListAST *decls,
                                           InsertionPointLocator::AccessSpec initialXs,
                                           int firstRangeStart,
                                           int lastRangeEnd) const
    {
        QList<AccessRange> ranges;
        ranges.append(AccessRange(firstRangeStart, lastRangeEnd, initialXs));

        for (DeclarationListAST *iter = decls; iter; iter = iter->next) {
            DeclarationAST *decl = iter->value;

            if (AccessDeclarationAST *xsDecl = decl->asAccessDeclaration()) {
                const unsigned token = xsDecl->access_specifier_token;
                int newXsSpec = initialXs;
221
222
                bool isSlot = xsDecl->slots_token
                        && tokenKind(xsDecl->slots_token) == T_Q_SLOTS;
223
224
225

                switch (tokenKind(token)) {
                case T_PUBLIC:
226
227
                    newXsSpec = isSlot ? InsertionPointLocator::PublicSlot
                                       : InsertionPointLocator::Public;
228
229
230
                    break;

                case T_PROTECTED:
231
232
                    newXsSpec = isSlot ? InsertionPointLocator::ProtectedSlot
                                       : InsertionPointLocator::Protected;
233
234
235
                    break;

                case T_PRIVATE:
236
237
                    newXsSpec = isSlot ? InsertionPointLocator::PrivateSlot
                                       : InsertionPointLocator::Private;
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
                    break;

                case T_Q_SIGNALS:
                    newXsSpec = InsertionPointLocator::Signals;
                    break;

                case T_Q_SLOTS: {
                    newXsSpec = ranges.last().xsSpec | InsertionPointLocator::SlotBit;
                    break;
                }

                default:
                    break;
                }

                if (newXsSpec != ranges.last().xsSpec) {
                    ranges.last().end = token;
                    ranges.append(AccessRange(token, lastRangeEnd, (InsertionPointLocator::AccessSpec) newXsSpec));
                }
            }
        }

        ranges.last().end = lastRangeEnd;
        return ranges;
    }

private:
    Document::Ptr _doc;
    const Class *_clazz;
    InsertionPointLocator::AccessSpec _xsSpec;

    InsertionLocation _result;
};

} // end of anonymous namespace

InsertionLocation::InsertionLocation()
    : m_line(0)
    , m_column(0)
{}

279
280
281
InsertionLocation::InsertionLocation(const QString &fileName,
                                     const QString &prefix,
                                     const QString &suffix,
282
                                     unsigned line, unsigned column)
283
284
    : m_fileName(fileName)
    , m_prefix(prefix)
285
    , m_suffix(suffix)
286
287
288
289
    , m_line(line)
    , m_column(column)
{}

290
InsertionPointLocator::InsertionPointLocator(const CppRefactoringChanges &refactoringChanges)
291
    : m_refactoringChanges(refactoringChanges)
292
293
294
{
}

295
296
297
298
InsertionLocation InsertionPointLocator::methodDeclarationInClass(
    const QString &fileName,
    const Class *clazz,
    AccessSpec xsSpec) const
299
{
300
    const Document::Ptr doc = m_refactoringChanges.file(fileName)->cppDocument();
301
302
303
304
305
306
307
308
    if (doc) {
        FindInClass find(doc, clazz, xsSpec);
        return find();
    } else {
        return InsertionLocation();
    }
}

309
310
311
312
313
314
315
316
317
318
319
320
321
static bool isSourceFile(const QString &fileName)
{
    const Core::MimeDatabase *mimeDb = Core::ICore::instance()->mimeDatabase();
    Core::MimeType cSourceTy = mimeDb->findByType(QLatin1String("text/x-csrc"));
    Core::MimeType cppSourceTy = mimeDb->findByType(QLatin1String("text/x-c++src"));
    Core::MimeType mSourceTy = mimeDb->findByType(QLatin1String("text/x-objcsrc"));
    QStringList suffixes = cSourceTy.suffixes();
    suffixes += cppSourceTy.suffixes();
    suffixes += mSourceTy.suffixes();
    QFileInfo fileInfo(fileName);
    return suffixes.contains(fileInfo.suffix());
}

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
namespace {
template <class Key, class Value>
class HighestValue
{
    Key _key;
    Value _value;
    bool _set;
public:
    HighestValue()
        : _set(false)
    {}

    HighestValue(const Key &initialKey, const Value &initialValue)
        : _key(initialKey)
        , _value(initialValue)
        , _set(true)
    {}

    void maybeSet(const Key &key, const Value &value)
    {
        if (!_set || key > _key) {
            _value = value;
            _key = key;
            _set = true;
        }
    }

    const Value &get() const
    {
        Q_ASSERT(_set);
        return _value;
    }
};

class FindMethodDefinitionInsertPoint : protected ASTVisitor
{
    QList<const Identifier *> _namespaceNames;
    int _currentDepth;
    HighestValue<int, int> _bestToken;

public:
    FindMethodDefinitionInsertPoint(TranslationUnit *translationUnit)
        : ASTVisitor(translationUnit)
    {}

    void operator()(Declaration *decl, unsigned *line, unsigned *column)
    {
        *line = *column = 0;
        if (translationUnit()->ast()->lastToken() < 2)
            return;

        QList<const Name *> names = LookupContext::fullyQualifiedName(decl);
        foreach (const Name *name, names) {
            const Identifier *id = name->asNameId();
            if (!id)
                break;
            _namespaceNames += id;
        }
        _currentDepth = 0;

        // default to end of file
        _bestToken.maybeSet(-1, translationUnit()->ast()->lastToken() - 1);
        accept(translationUnit()->ast());
        translationUnit()->getTokenEndPosition(_bestToken.get(), line, column);
    }

protected:
    bool preVisit(AST *ast)
    {
        return ast->asNamespace() || ast->asTranslationUnit() || ast->asLinkageBody();
    }

    bool visit(NamespaceAST *ast)
    {
        if (_currentDepth >= _namespaceNames.size())
            return false;

        // ignore anonymous namespaces
        if (!ast->identifier_token)
            return false;

        const Identifier *name = translationUnit()->identifier(ast->identifier_token);
        if (!name->equalTo(_namespaceNames.at(_currentDepth)))
            return false;

        // found a good namespace
        _bestToken.maybeSet(_currentDepth, ast->lastToken() - 2);

        ++_currentDepth;
        accept(ast->linkage_body);
        --_currentDepth;

        return false;
    }
};
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

class FindFunctionDefinition : protected ASTVisitor
{
    FunctionDefinitionAST *_result;
    unsigned _line, _column;
public:
    FindFunctionDefinition(TranslationUnit *translationUnit)
        : ASTVisitor(translationUnit)
    {
    }

    FunctionDefinitionAST *operator()(unsigned line, unsigned column)
    {
        _result = 0;
        _line = line;
        _column = column;
        accept(translationUnit()->ast());
        return _result;
    }

protected:
    bool preVisit(AST *ast)
    {
        if (_result)
            return false;
        unsigned line, column;
        translationUnit()->getTokenStartPosition(ast->firstToken(), &line, &column);
        if (line > _line || (line == _line && column > _column))
            return false;
        translationUnit()->getTokenEndPosition(ast->lastToken() - 1, &line, &column);
        if (line < _line || (line == _line && column < _column))
            return false;
        return true;
    }

    bool visit(FunctionDefinitionAST *ast)
    {
        _result = ast;
        return false;
    }
};

459
460
} // anonymous namespace

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
static Declaration *isNonVirtualFunctionDeclaration(Symbol *s)
{
    if (!s)
        return 0;
    Declaration *declaration = s->asDeclaration();
    if (!declaration)
        return 0;
    Function *type = s->type()->asFunctionType();
    if (!type || type->isPureVirtual())
        return 0;
    return declaration;
}

static InsertionLocation nextToSurroundingDefinitions(Declaration *declaration, const CppRefactoringChanges &changes)
{
    InsertionLocation noResult;
    Class *klass = declaration->enclosingClass();
    if (!klass)
        return noResult;

    // find the index of declaration
    int declIndex = -1;
    for (unsigned i = 0; i < klass->memberCount(); ++i) {
        Symbol *s = klass->memberAt(i);
        if (s == declaration) {
            declIndex = i;
            break;
        }
    }
    if (declIndex == -1)
        return noResult;

    // scan preceding declarations for a function declaration
    QString prefix, suffix;
    Declaration *surroundingFunctionDecl = 0;
    for (int i = declIndex - 1; i >= 0; --i) {
        Symbol *s = klass->memberAt(i);
        surroundingFunctionDecl = isNonVirtualFunctionDeclaration(s);
        if (surroundingFunctionDecl) {
            prefix = QLatin1String("\n\n");
            break;
        }
    }
    if (!surroundingFunctionDecl) {
        // try to find one below
        for (unsigned i = declIndex + 1; i < klass->memberCount(); ++i) {
            Symbol *s = klass->memberAt(i);
            surroundingFunctionDecl = isNonVirtualFunctionDeclaration(s);
            if (surroundingFunctionDecl) {
                suffix = QLatin1String("\n\n");
                break;
            }
        }
        if (!surroundingFunctionDecl)
            return noResult;
    }

    // find the declaration's definition
    Symbol *definition = changes.snapshot().findMatchingDefinition(surroundingFunctionDecl);
    if (!definition)
        return noResult;

    unsigned line, column;
    if (suffix.isEmpty()) {
        Function *definitionFunction = definition->asFunction();
        if (!definitionFunction)
            return noResult;

        Document::Ptr targetDoc = changes.snapshot().document(definition->fileName());
        if (!targetDoc)
            return noResult;

        targetDoc->translationUnit()->getPosition(definitionFunction->endOffset(), &line, &column);
    } else {
        // we don't have an offset to the start of the function definition, so we need to manually find it...
        CppRefactoringFilePtr targetFile = changes.file(definition->fileName());
        if (!targetFile->isValid())
            return noResult;

        FindFunctionDefinition finder(targetFile->cppDocument()->translationUnit());
        FunctionDefinitionAST *functionDefinition = finder(definition->line(), definition->column());
        if (!functionDefinition)
            return noResult;

        targetFile->cppDocument()->translationUnit()->getTokenStartPosition(functionDefinition->firstToken(), &line, &column);
    }

    return InsertionLocation(definition->fileName(), prefix, suffix, line, column);
}

551
QList<InsertionLocation> InsertionPointLocator::methodDefinition(
552
    Declaration *declaration) const
553
554
{
    QList<InsertionLocation> result;
555
556
    if (!declaration)
        return result;
557

558
559
560
561
562
563
564
565
566
567
568
569
570
571
    if (Symbol *s = m_refactoringChanges.snapshot().findMatchingDefinition(declaration, true)) {
        if (Function *f = s->asFunction()) {
            if (f->isConst() == declaration->type().isConst()
                    && f->isVolatile() == declaration->type().isVolatile())
                return result;
        }
    }

    const InsertionLocation location = nextToSurroundingDefinitions(declaration, m_refactoringChanges);
    if (location.isValid()) {
        result += location;
        return result;
    }

572
573
574
575
    const QString declFileName = QString::fromUtf8(declaration->fileName(),
                                                   declaration->fileNameLength());
    QString target = declFileName;
    if (!isSourceFile(declFileName)) {
576
        QString candidate = Internal::CppToolsPlugin::correspondingHeaderOrSource(declFileName);
577
578
        if (!candidate.isEmpty())
            target = candidate;
579
    }
580

581
    Document::Ptr doc = m_refactoringChanges.file(target)->cppDocument();
582
583
584
585
    if (doc.isNull())
        return result;

    unsigned line = 0, column = 0;
586
587
    FindMethodDefinitionInsertPoint finder(doc->translationUnit());
    finder(declaration, &line, &column);
588
589
590

    const QLatin1String prefix("\n\n");
    result.append(InsertionLocation(target, prefix, QString(), line, column));
591
592

    return result;
593
}