cppfunctiondecldeflink.cpp 40.3 KB
Newer Older
1
2
3
4
5
6
/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
**
7
** Contact: Nokia Corporation (qt-info@nokia.com)
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
**
**
** GNU Lesser General Public License Usage
**
** 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.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** 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.
**
** If you have questions regarding the use of this file, please contact
29
** Nokia at qt-info@nokia.com.
30
31
32
33
34
35
**
**************************************************************************/

#include "cppfunctiondecldeflink.h"

#include "cppeditor.h"
36
#include "cppquickfixassistant.h"
37
#include "cpplocalsymbols.h"
38
39
40
41
42
43
44
45
46

#include <cplusplus/CppRewriter.h>
#include <cplusplus/ASTPath.h>
#include <cplusplus/AST.h>
#include <cplusplus/Symbols.h>
#include <cplusplus/TypeOfExpression.h>
#include <cplusplus/TranslationUnit.h>
#include <cplusplus/LookupContext.h>
#include <cplusplus/Overview.h>
47
#include <cpptools/cpprefactoringchanges.h>
48
49
50
51
#include <texteditor/refactoroverlay.h>
#include <texteditor/tooltip/tooltip.h>
#include <texteditor/tooltip/tipcontents.h>
#include <utils/qtcassert.h>
52
53
54
55
#include <utils/proxyaction.h>
#include <coreplugin/actionmanager/actionmanager.h>
#include <coreplugin/icore.h>
#include <texteditor/texteditorconstants.h>
56
57

#include <QtCore/QtConcurrentRun>
58
#include <QtCore/QVarLengthArray>
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73

using namespace CPlusPlus;
using namespace CppEditor;
using namespace CppEditor::Internal;

FunctionDeclDefLinkFinder::FunctionDeclDefLinkFinder(QObject *parent)
    : QObject(parent)
{
    connect(&m_watcher, SIGNAL(finished()),
            this, SLOT(onFutureDone()));
}

void FunctionDeclDefLinkFinder::onFutureDone()
{
    QSharedPointer<FunctionDeclDefLink> link = m_watcher.result();
74
    if (link) {
75
        link->linkSelection = m_scannedSelection;
76
77
78
79
        link->nameSelection = m_nameSelection;
        if (m_nameSelection.selectedText() != link->nameInitial)
            link.clear();
    }
80
    m_scannedSelection = QTextCursor();
81
    m_nameSelection = QTextCursor();
82
83
84
85
86
87
88
89
90
91
    if (link)
        emit foundLink(link);
}

QTextCursor FunctionDeclDefLinkFinder::scannedSelection() const
{
    return m_scannedSelection;
}

// parent is either a FunctionDefinitionAST or a SimpleDeclarationAST
92
93
// line and column are 1-based
static bool findDeclOrDef(const Document::Ptr &doc, int line, int column,
94
95
                          DeclarationAST **parent, DeclaratorAST **decl,
                          FunctionDeclaratorAST **funcDecl)
96
{
97
    QList<AST *> path = ASTPath(doc)(line, column);
98
99
100
101
102
103
104

    // for function definitions, simply scan for FunctionDefinitionAST not preceded
    //    by CompoundStatement/CtorInitializer
    // for function declarations, look for SimpleDeclarations with a single Declarator
    //    with a FunctionDeclarator postfix
    FunctionDefinitionAST *funcDef = 0;
    SimpleDeclarationAST *simpleDecl = 0;
105
    *decl = 0;
106
107
108
109
110
111
    for (int i = path.size() - 1; i > 0; --i) {
        AST *ast = path.at(i);
        if (ast->asCompoundStatement() || ast->asCtorInitializer())
            break;
        if ((funcDef = ast->asFunctionDefinition()) != 0) {
            *parent = funcDef;
112
            *decl = funcDef->declarator;
113
114
115
116
117
118
            break;
        }
        if ((simpleDecl = ast->asSimpleDeclaration()) != 0) {
            *parent = simpleDecl;
            if (!simpleDecl->declarator_list || !simpleDecl->declarator_list->value)
                break;
119
            *decl = simpleDecl->declarator_list->value;
120
121
122
            break;
        }
    }
123
    if (!*parent || !*decl)
124
        return false;
125
    if (!(*decl)->postfix_declarator_list || !(*decl)->postfix_declarator_list->value)
126
        return false;
127
    *funcDecl = (*decl)->postfix_declarator_list->value->asFunctionDeclarator();
128
129
130
    return *funcDecl;
}

131
static void declDefLinkStartEnd(const CppTools::CppRefactoringFileConstPtr &file,
132
133
134
                                DeclarationAST *parent, FunctionDeclaratorAST *funcDecl,
                                int *start, int *end)
{
135
    *start = file->startOf(parent);
136
    if (funcDecl->trailing_return_type)
137
        *end = file->endOf(funcDecl->trailing_return_type);
138
    else if (funcDecl->exception_specification)
139
        *end = file->endOf(funcDecl->exception_specification);
140
    else if (funcDecl->cv_qualifier_list)
141
        *end = file->endOf(funcDecl->cv_qualifier_list->lastValue());
142
    else
143
        *end = file->endOf(funcDecl->rparen_token);
144
145
}

146
147
148
149
150
151
152
153
154
155
156
157
158
static DeclaratorIdAST *getDeclaratorId(DeclaratorAST *declarator)
{
    if (!declarator || !declarator->core_declarator)
        return 0;
    if (DeclaratorIdAST *id = declarator->core_declarator->asDeclaratorId()) {
        return id;
    }
    if (NestedDeclaratorAST *nested = declarator->core_declarator->asNestedDeclarator()) {
        return getDeclaratorId(nested->declarator);
    }
    return 0;
}

159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
static QSharedPointer<FunctionDeclDefLink> findLinkHelper(QSharedPointer<FunctionDeclDefLink> link, CppTools::CppRefactoringChanges changes)
{
    QSharedPointer<FunctionDeclDefLink> noResult;
    const Snapshot &snapshot = changes.snapshot();

    // find the matching decl/def symbol
    Symbol *target = 0;
    if (FunctionDefinitionAST *funcDef = link->sourceDeclaration->asFunctionDefinition()) {
        QList<Declaration *> nameMatch, argumentCountMatch, typeMatch;
        findMatchingDeclaration(LookupContext(link->sourceDocument, snapshot),
                                funcDef->symbol,
                                &typeMatch, &argumentCountMatch, &nameMatch);
        if (!typeMatch.isEmpty())
            target = typeMatch.first();
    } else if (link->sourceDeclaration->asSimpleDeclaration()) {
        target = snapshot.findMatchingDefinition(link->sourceFunctionDeclarator->symbol, true);
    }
    if (!target) {
        return noResult;
    }

    // parse the target file to get the linked decl/def
    const QString targetFileName = QString::fromUtf8(
                target->fileName(), target->fileNameLength());
183
184
    CppTools::CppRefactoringFileConstPtr targetFile = changes.fileNoEditor(targetFileName);
    if (!targetFile->isValid())
185
186
187
188
        return noResult;

    DeclarationAST *targetParent = 0;
    FunctionDeclaratorAST *targetFuncDecl = 0;
189
    DeclaratorAST *targetDeclarator = 0;
190
    if (!findDeclOrDef(targetFile->cppDocument(), target->line(), target->column(),
191
                       &targetParent, &targetDeclarator, &targetFuncDecl))
192
193
194
195
196
        return noResult;

    // the parens are necessary for finding good places for changes
    if (!targetFuncDecl->lparen_token || !targetFuncDecl->rparen_token)
        return noResult;
197
198
    // if the source and target argument counts differ, something is wrong
    QTC_ASSERT(targetFuncDecl->symbol->argumentCount() == link->sourceFunction->argumentCount(), return noResult);
199
200
201

    int targetStart, targetEnd;
    declDefLinkStartEnd(targetFile, targetParent, targetFuncDecl, &targetStart, &targetEnd);
202
203
    QString targetInitial = targetFile->textOf(
                targetFile->startOf(targetParent),
204
205
                targetEnd);

206
    targetFile->lineAndColumn(targetStart, &link->targetLine, &link->targetColumn);
207
208
    link->targetInitial = targetInitial;

209
    link->targetFile = targetFile;
210
211
212
213
214
215
216
217
218
219
220
221
222
    link->targetFunction = targetFuncDecl->symbol;
    link->targetFunctionDeclarator = targetFuncDecl;
    link->targetDeclaration = targetParent;

    return link;
}

void FunctionDeclDefLinkFinder::startFindLinkAt(
        QTextCursor cursor, const Document::Ptr &doc, const Snapshot &snapshot)
{
    // check if cursor is on function decl/def
    DeclarationAST *parent = 0;
    FunctionDeclaratorAST *funcDecl = 0;
223
224
225
    DeclaratorAST *declarator = 0;
    if (!findDeclOrDef(doc, cursor.blockNumber() + 1, cursor.columnNumber() + 1,
                       &parent, &declarator, &funcDecl))
226
227
228
229
        return;

    // find the start/end offsets
    CppTools::CppRefactoringChanges refactoringChanges(snapshot);
230
231
    CppTools::CppRefactoringFilePtr sourceFile = refactoringChanges.file(doc->fileName());
    sourceFile->setCppDocument(doc);
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
    int start, end;
    declDefLinkStartEnd(sourceFile, parent, funcDecl, &start, &end);

    // if already scanning, don't scan again
    if (!m_scannedSelection.isNull()
            && m_scannedSelection.selectionStart() == start
            && m_scannedSelection.selectionEnd() == end) {
        return;
    }

    // build the selection for the currently scanned area
    m_scannedSelection = cursor;
    m_scannedSelection.setPosition(end);
    m_scannedSelection.setPosition(start, QTextCursor::KeepAnchor);
    m_scannedSelection.setKeepPositionOnInsert(true);

248
249
250
251
252
253
254
    // build selection for the name
    DeclaratorIdAST *declId = getDeclaratorId(declarator);
    m_nameSelection = cursor;
    m_nameSelection.setPosition(sourceFile->endOf(declId));
    m_nameSelection.setPosition(sourceFile->startOf(declId), QTextCursor::KeepAnchor);
    m_nameSelection.setKeepPositionOnInsert(true);

255
256
    // set up a base result
    QSharedPointer<FunctionDeclDefLink> result(new FunctionDeclDefLink);
257
    result->nameInitial = m_nameSelection.selectedText();
258
259
260
261
262
263
264
265
266
267
268
269
    result->sourceDocument = doc;
    result->sourceFunction = funcDecl->symbol;
    result->sourceDeclaration = parent;
    result->sourceFunctionDeclarator = funcDecl;

    // handle the rest in a thread
    m_watcher.setFuture(QtConcurrent::run(&findLinkHelper, result, refactoringChanges));
}

FunctionDeclDefLink::FunctionDeclDefLink()
{
    hasMarker = false;
270
271
    targetLine = 0;
    targetColumn = 0;
272
273
274
275
276
277
278
279
280
281
282
283
    sourceFunction = 0;
    targetFunction = 0;
    targetDeclaration = 0;
    targetFunctionDeclarator = 0;
}

FunctionDeclDefLink::~FunctionDeclDefLink()
{
}

bool FunctionDeclDefLink::isValid() const
{
284
    return !linkSelection.isNull();
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
}

bool FunctionDeclDefLink::isMarkerVisible() const
{
    return hasMarker;
}

static bool namesEqual(const Name *n1, const Name *n2)
{
    return n1 == n2 || (n1 && n2 && n1->isEqualTo(n2));
}

void FunctionDeclDefLink::apply(CPPEditorWidget *editor, bool jumpToMatch)
{
    Snapshot snapshot = editor->semanticInfo().snapshot;

    // first verify the interesting region of the target file is unchanged
    CppTools::CppRefactoringChanges refactoringChanges(snapshot);
303
304
    CppTools::CppRefactoringFilePtr newTargetFile = refactoringChanges.file(targetFile->fileName());
    if (!newTargetFile->isValid())
305
        return;
306
307
308
309
    const int targetStart = newTargetFile->position(targetLine, targetColumn);
    const int targetEnd = targetStart + targetInitial.size();
    if (targetInitial == newTargetFile->textOf(targetStart, targetEnd)) {
        const Utils::ChangeSet changeset = changes(snapshot, targetStart);
310
        newTargetFile->setChangeSet(changeset);
311
312
313
314
        if (jumpToMatch) {
            const int jumpTarget = newTargetFile->position(targetFunction->line(), targetFunction->column());
            newTargetFile->setOpenEditor(true, jumpTarget);
        }
315
        newTargetFile->apply();
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
    } else {
        TextEditor::ToolTip::instance()->show(
                    editor->toolTipPosition(linkSelection),
                    TextEditor::TextContent(
                        tr("Target file was changed, could not apply changes")));
    }
}

template <class T>
static QList<TextEditor::RefactorMarker> removeMarkersOfType(const QList<TextEditor::RefactorMarker> &markers)
{
    QList<TextEditor::RefactorMarker> result;
    foreach (const TextEditor::RefactorMarker &marker, markers) {
        if (!marker.data.canConvert<T>())
            result += marker;
    }
    return result;
}

void FunctionDeclDefLink::hideMarker(CPPEditorWidget *editor)
{
    if (!hasMarker)
        return;
    editor->setRefactorMarkers(
                removeMarkersOfType<Marker>(editor->refactorMarkers()));
    hasMarker = false;
}

void FunctionDeclDefLink::showMarker(CPPEditorWidget *editor)
{
    if (hasMarker)
        return;

    QList<TextEditor::RefactorMarker> markers = removeMarkersOfType<Marker>(editor->refactorMarkers());
    TextEditor::RefactorMarker marker;

    // show the marker at the end of the linked area, with a special case
    // to avoid it overlapping with a trailing semicolon
    marker.cursor = editor->textCursor();
    marker.cursor.setPosition(linkSelection.selectionEnd());
    const int endBlockNr = marker.cursor.blockNumber();
    marker.cursor.setPosition(linkSelection.selectionEnd() + 1, QTextCursor::KeepAnchor);
    if (marker.cursor.blockNumber() != endBlockNr
            || marker.cursor.selectedText() != QLatin1String(";")) {
        marker.cursor.setPosition(linkSelection.selectionEnd());
    }

    QString message;
    if (targetDeclaration->asFunctionDefinition())
        message = tr("Apply changes to definition");
    else
        message = tr("Apply changes to declaration");
368
369
370
371
372
373

    Core::ActionManager *actionManager = Core::ICore::instance()->actionManager();
    Core::Command *quickfixCommand = actionManager->command(TextEditor::Constants::QUICKFIX_THIS);
    if (quickfixCommand)
        message = Utils::ProxyAction::stringWithAppendedShortcut(message, quickfixCommand->keySequence());

374
375
376
377
378
379
380
381
    marker.tooltip = message;
    marker.data = QVariant::fromValue(Marker());
    markers += marker;
    editor->setRefactorMarkers(markers);

    hasMarker = true;
}

382
// does consider foo(void) to have one argument
383
static int declaredParameterCount(Function *function)
384
{
385
386
387
    int c = function->argumentCount();
    if (c == 0 && function->memberCount() > 0 && function->memberAt(0)->type().type()->isVoidType())
        return 1;
388
389
390
    return c;
}

391
392
393
394
395
396
397
398
399
400
401
402
403
404
Q_GLOBAL_STATIC(QRegExp, commentArgNameRegexp)

static bool hasCommentedName(
        TranslationUnit *unit,
        const QString &source,
        FunctionDeclaratorAST *declarator,
        int i)
{
    if (!declarator
            || !declarator->parameter_declaration_clause
            || !declarator->parameter_declaration_clause->parameter_declaration_list)
        return false;

    if (Function *f = declarator->symbol) {
405
        QTC_ASSERT(f, return false);
406
        if (Symbol *a = f->argumentAt(i)) {
407
            QTC_ASSERT(a, return false);
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
            if (a->name())
                return false;
        }
    }

    ParameterDeclarationListAST *list = declarator->parameter_declaration_clause->parameter_declaration_list;
    while (list && i) {
        list = list->next;
        --i;
    }
    if (!list || !list->value || i)
        return false;

    ParameterDeclarationAST *param = list->value;
    if (param->symbol && param->symbol->name()) {
        return false;
    }

    // maybe in a comment but in the right spot?
    int nameStart = 0;
    if (param->declarator)
        nameStart = unit->tokenAt(param->declarator->lastToken() - 1).end();
    else if (param->type_specifier_list)
        nameStart = unit->tokenAt(param->type_specifier_list->lastToken() - 1).end();
    else
        nameStart = unit->tokenAt(param->firstToken()).begin();

    int nameEnd = 0;
    if (param->equal_token)
        nameEnd = unit->tokenAt(param->equal_token).begin();
    else
        nameEnd = unit->tokenAt(param->lastToken()).begin(); // one token after

    QString text = source.mid(nameStart, nameEnd - nameStart);

    if (commentArgNameRegexp()->isEmpty()) {
        *commentArgNameRegexp() = QRegExp(QLatin1String("/\\*\\s*(\\w*)\\s*\\*/"));
    }
    return commentArgNameRegexp()->indexIn(text) != -1;
}

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
static bool canReplaceSpecifier(TranslationUnit *translationUnit, SpecifierAST *specifier)
{
    if (SimpleSpecifierAST *simple = specifier->asSimpleSpecifier()) {
        switch (translationUnit->tokenAt(simple->specifier_token).kind()) {
        case T_CONST:
        case T_VOLATILE:
        case T_CHAR:
        case T_WCHAR_T:
        case T_BOOL:
        case T_SHORT:
        case T_INT:
        case T_LONG:
        case T_SIGNED:
        case T_UNSIGNED:
        case T_FLOAT:
        case T_DOUBLE:
        case T_VOID:
        case T_AUTO:
        case T___TYPEOF__:
        case T___ATTRIBUTE__:
            return true;
        default:
            return false;
        }
    }
474
475
476
    if (specifier->asAttributeSpecifier())
        return false;
    return true;
477
478
479
480
481
482
483
484
485
486
487
}

static SpecifierAST *findFirstReplaceableSpecifier(TranslationUnit *translationUnit, SpecifierListAST *list)
{
    for (SpecifierListAST *it = list; it; it = it->next) {
        if (canReplaceSpecifier(translationUnit, it->value))
            return it->value;
    }
    return 0;
}

488
489
490
491
492
493
494
495
496
typedef QVarLengthArray<int, 10> IndicesList;

template <class IndicesListType>
static int findUniqueTypeMatch(int sourceParamIndex, Function *sourceFunction, Function *newFunction,
                               const IndicesListType &sourceParams, const IndicesListType &newParams)
{
    Symbol *sourceParam = sourceFunction->argumentAt(sourceParamIndex);

    // if other sourceParams have the same type, we can't do anything
497
498
    for (int i = 0; i < sourceParams.size(); ++i) {
        int otherSourceParamIndex = sourceParams.at(i);
499
500
501
502
503
504
505
506
507
        if (sourceParamIndex == otherSourceParamIndex)
            continue;
        if (sourceParam->type().isEqualTo(sourceFunction->argumentAt(otherSourceParamIndex)->type()))
            return -1;
    }

    // if there's exactly one newParam with the same type, bind to that
    // this is primarily done to catch moves of unnamed parameters
    int newParamWithSameTypeIndex = -1;
508
509
    for (int i = 0; i < newParams.size(); ++i) {
        int newParamIndex = newParams.at(i);
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
        if (sourceParam->type().isEqualTo(newFunction->argumentAt(newParamIndex)->type())) {
            if (newParamWithSameTypeIndex != -1)
                return -1;
            newParamWithSameTypeIndex = newParamIndex;
        }
    }
    return newParamWithSameTypeIndex;
}

static IndicesList unmatchedIndices(const IndicesList &indices)
{
    IndicesList ret;
    ret.reserve(indices.size());
    for (int i = 0; i < indices.size(); ++i) {
        if (indices[i] == -1)
525
            ret.append(i);
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
    }
    return ret;
}

static QString ensureCorrectParameterSpacing(const QString &text, bool isFirstParam)
{
    if (isFirstParam) { // drop leading spaces
        int firstNonSpace = 0;
        while (firstNonSpace + 1 < text.size() && text.at(firstNonSpace).isSpace())
            ++firstNonSpace;
        return text.mid(firstNonSpace);
    } else { // ensure one leading space
        if (text.isEmpty() || !text.at(0).isSpace()) {
            return QLatin1Char(' ') + text;
        }
    }
    return text;
}

static unsigned findCommaTokenBetween(const CppTools::CppRefactoringFileConstPtr &file,
                                      ParameterDeclarationAST *left, ParameterDeclarationAST *right)
{
    unsigned last = left->lastToken() - 1;
    for (unsigned tokenIndex = right->firstToken();
         tokenIndex > last;
         --tokenIndex) {
        if (file->tokenAt(tokenIndex).kind() == T_COMMA)
            return tokenIndex;
    }
    return 0;
}

558
Utils::ChangeSet FunctionDeclDefLink::changes(const Snapshot &snapshot, int targetOffset)
559
560
561
{
    Utils::ChangeSet changes;

562
563
564
565
566
567
    // Everything prefixed with 'new' in this function relates to the state of the 'source'
    // function *after* the user did his changes.

    // The 'newTarget' prefix indicates something relates to the changes we plan to do
    // to the 'target' function.

568
569
570
    // parse the current source declaration
    TypeOfExpression typeOfExpression; // ### just need to preprocess...
    typeOfExpression.init(sourceDocument, snapshot);
571
572
573
574
575
576
577
578
579

    QString newDeclText = linkSelection.selectedText();
    for (int i = 0; i < newDeclText.size(); ++i) {
        if (newDeclText.at(i).toAscii() == 0)
            newDeclText[i] = QLatin1Char('\n');
    }
    newDeclText.append(QLatin1String("{}"));
    const QString newDeclTextPreprocessed = typeOfExpression.preprocess(newDeclText);

580
    Document::Ptr newDeclDoc = Document::create(QLatin1String("<decl>"));
581
    newDeclDoc->setSource(newDeclTextPreprocessed.toUtf8());
582
583
584
585
    newDeclDoc->parse(Document::ParseDeclaration);
    newDeclDoc->check();

    // extract the function symbol
586
    if (!newDeclDoc->translationUnit()->ast())
587
588
        return changes;
    FunctionDefinitionAST *newDef = newDeclDoc->translationUnit()->ast()->asFunctionDefinition();
589
    if (!newDef)
590
591
        return changes;
    Function *newFunction = newDef->symbol;
592
593
    if (!newFunction)
        return changes;
594
595
596
597
598
599
600

    Overview overview;
    overview.setShowReturnTypes(true);
    overview.setShowTemplateParameters(true);
    overview.setShowArgumentNames(true);
    overview.setShowFunctionSignatures(true);

601
602
603
604
605
606
607
608
609
610
    // abort if the name of the newly parsed function is not the expected one
    DeclaratorIdAST *newDeclId = getDeclaratorId(newDef->declarator);
    if (!newDeclId || !newDeclId->name || !newDeclId->name->name
            || overview(newDeclId->name->name) != nameInitial) {
        return changes;
    }

    LookupContext sourceContext(sourceDocument, snapshot);
    LookupContext targetContext(targetFile->cppDocument(), snapshot);

611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
    // sync return type
    {
        // set up for rewriting return type
        SubstitutionEnvironment env;
        env.setContext(sourceContext);
        env.switchScope(sourceFunction->enclosingScope());
        ClassOrNamespace *targetCoN = targetContext.lookupType(targetFunction->enclosingScope());
        if (!targetCoN)
            targetCoN = targetContext.globalNamespace();
        UseMinimalNames q(targetCoN);
        env.enter(&q);
        Control *control = sourceContext.control().data();

        // get return type start position and declarator info from declaration
        DeclaratorAST *declarator = 0;
626
627
        SpecifierAST *firstReplaceableSpecifier = 0;
        TranslationUnit *targetTranslationUnit = targetFile->cppDocument()->translationUnit();
628
629
        if (SimpleDeclarationAST *simple = targetDeclaration->asSimpleDeclaration()) {
            declarator = simple->declarator_list->value;
630
631
            firstReplaceableSpecifier = findFirstReplaceableSpecifier(
                        targetTranslationUnit, simple->decl_specifier_list);
632
633
        } else if (FunctionDefinitionAST *def = targetDeclaration->asFunctionDefinition()) {
            declarator = def->declarator;
634
635
            firstReplaceableSpecifier = findFirstReplaceableSpecifier(
                        targetTranslationUnit, def->decl_specifier_list);
636
637
        }

638
639
640
641
642
643
        int returnTypeStart = 0;
        if (firstReplaceableSpecifier)
            returnTypeStart = targetFile->startOf(firstReplaceableSpecifier);
        else
            returnTypeStart = targetFile->startOf(declarator);

644
645
646
647
648
        if (!newFunction->returnType().isEqualTo(sourceFunction->returnType())
                && !newFunction->returnType().isEqualTo(targetFunction->returnType())) {
            FullySpecifiedType type = rewriteType(newFunction->returnType(), &env, control);
            const QString replacement = overview(type, targetFunction->name());
            changes.replace(returnTypeStart,
649
                            targetFile->startOf(targetFunctionDeclarator->lparen_token),
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
                            replacement);
        }
    }

    // sync parameters
    {
        // set up for rewriting parameter types
        SubstitutionEnvironment env;
        env.setContext(sourceContext);
        env.switchScope(sourceFunction);
        ClassOrNamespace *targetCoN = targetContext.lookupType(targetFunction);
        if (!targetCoN)
            targetCoN = targetContext.globalNamespace();
        UseMinimalNames q(targetCoN);
        env.enter(&q);
        Control *control = sourceContext.control().data();
        Overview overview;

668
669
        // make a easy to access list of the target parameter declarations
        QVarLengthArray<ParameterDeclarationAST *, 10> targetParameterDecls;
670
671
672
673
674
675
        // there is no parameter declaration clause if the function has no arguments
        if (targetFunctionDeclarator->parameter_declaration_clause) {
            for (ParameterDeclarationListAST *it = targetFunctionDeclarator->parameter_declaration_clause->parameter_declaration_list;
                 it; it = it->next) {
                targetParameterDecls.append(it->value);
            }
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
        }

        // the number of parameters in sourceFunction or targetFunction
        const int existingParamCount = declaredParameterCount(sourceFunction);
        QTC_ASSERT(existingParamCount == declaredParameterCount(targetFunction), return changes);
        QTC_ASSERT(existingParamCount == targetParameterDecls.size(), return changes);

        const int newParamCount = declaredParameterCount(newFunction);

        // When syncing parameters we need to take care that parameters inserted or
        // removed in the middle or parameters being reshuffled are treated correctly.
        // To do that, we construct a newParam -> sourceParam map, based on parameter
        // names and types.
        // Initially they start out with -1 to indicate a new parameter.
        IndicesList newParamToSourceParam(newParamCount);
        for (int i = 0; i < newParamCount; ++i)
            newParamToSourceParam[i] = -1;

        // fill newParamToSourceParam
        {
            IndicesList sourceParamToNewParam(existingParamCount);
            for (int i = 0; i < existingParamCount; ++i)
                sourceParamToNewParam[i] = -1;

            QMultiHash<QString, int> sourceParamNameToIndex;
            for (int i = 0; i < existingParamCount; ++i) {
702
                Symbol *sourceParam = sourceFunction->argumentAt(i);
703
                sourceParamNameToIndex.insert(overview(sourceParam->name()), i);
704
705
            }

706
707
708
709
            QMultiHash<QString, int> newParamNameToIndex;
            for (int i = 0; i < newParamCount; ++i) {
                Symbol *newParam = newFunction->argumentAt(i);
                newParamNameToIndex.insert(overview(newParam->name()), i);
710
            }
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726

            // name-based binds (possibly disambiguated by type)
            for (int sourceParamIndex = 0; sourceParamIndex < existingParamCount; ++sourceParamIndex) {
                Symbol *sourceParam = sourceFunction->argumentAt(sourceParamIndex);
                const QString &name = overview(sourceParam->name());
                QList<int> newParams = newParamNameToIndex.values(name);
                QList<int> sourceParams = sourceParamNameToIndex.values(name);

                if (newParams.isEmpty())
                    continue;

                // if the names match uniquely, bind them
                // this catches moves of named parameters
                if (newParams.size() == 1 && sourceParams.size() == 1) {
                    sourceParamToNewParam[sourceParamIndex] = newParams.first();
                    newParamToSourceParam[newParams.first()] = sourceParamIndex;
727
                } else {
728
729
730
731
732
733
734
735
                    // if the name match is not unique, try to find a unique
                    // type match among the same-name parameters
                    const int newParamWithSameTypeIndex = findUniqueTypeMatch(
                                sourceParamIndex, sourceFunction, newFunction,
                                sourceParams, newParams);
                    if (newParamWithSameTypeIndex != -1) {
                        sourceParamToNewParam[sourceParamIndex] = newParamWithSameTypeIndex;
                        newParamToSourceParam[newParamWithSameTypeIndex] = sourceParamIndex;
736
737
738
                    }
                }
            }
739
740
741
742

            // find unique type matches among the unbound parameters
            const IndicesList &freeSourceParams = unmatchedIndices(sourceParamToNewParam);
            const IndicesList &freeNewParams = unmatchedIndices(newParamToSourceParam);
743
744
            for (int i = 0; i < freeSourceParams.size(); ++i) {
                int sourceParamIndex = freeSourceParams.at(i);
745
746
747
748
749
750
751
752
753
754
755
756
757
758
                const int newParamWithSameTypeIndex = findUniqueTypeMatch(
                            sourceParamIndex, sourceFunction, newFunction,
                            freeSourceParams, freeNewParams);
                if (newParamWithSameTypeIndex != -1) {
                    sourceParamToNewParam[sourceParamIndex] = newParamWithSameTypeIndex;
                    newParamToSourceParam[newParamWithSameTypeIndex] = sourceParamIndex;
                }
            }

            // add position based binds if possible
            for (int i = 0; i < existingParamCount && i < newParamCount; ++i) {
                if (newParamToSourceParam[i] == -1 && sourceParamToNewParam[i] == -1) {
                    newParamToSourceParam[i] = i;
                    sourceParamToNewParam[i] = i;
759
760
                }
            }
761
        }
762
763
764
765

        // build the new parameter declarations
        QString newTargetParameters;
        bool hadChanges = newParamCount < existingParamCount; // below, additions and changes set this to true as well
766
        QHash<Symbol *, QString> renamedTargetParameters;
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
        for (int newParamIndex = 0; newParamIndex < newParamCount; ++newParamIndex) {
            const int existingParamIndex = newParamToSourceParam[newParamIndex];
            Symbol *newParam = newFunction->argumentAt(newParamIndex);
            const bool isFirstNewParam = newParamIndex == 0;

            if (!isFirstNewParam)
                newTargetParameters += QLatin1Char(',');

            QString newTargetParam;

            // if it's genuinely new, add it
            if (existingParamIndex == -1) {
                FullySpecifiedType type = rewriteType(newParam->type(), &env, control);
                newTargetParam = overview(type, newParam->name());
                hadChanges = true;
782
            }
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
            // otherwise preserve as much as possible from the existing parameter
            else {
                Symbol *targetParam = targetFunction->argumentAt(existingParamIndex);
                Symbol *sourceParam = sourceFunction->argumentAt(existingParamIndex);
                ParameterDeclarationAST *targetParamAst = targetParameterDecls.at(existingParamIndex);

                int parameterStart = targetFile->endOf(targetFunctionDeclarator->lparen_token);
                if (existingParamIndex > 0) {
                    ParameterDeclarationAST *prevTargetParamAst = targetParameterDecls.at(existingParamIndex - 1);
                    const unsigned commaToken = findCommaTokenBetween(targetFile, prevTargetParamAst, targetParamAst);
                    if (commaToken > 0)
                        parameterStart = targetFile->endOf(commaToken);
                }

                int parameterEnd = targetFile->startOf(targetFunctionDeclarator->rparen_token);
                if (existingParamIndex + 1 < existingParamCount) {
                    ParameterDeclarationAST *nextTargetParamAst = targetParameterDecls.at(existingParamIndex + 1);
                    const unsigned commaToken = findCommaTokenBetween(targetFile, targetParamAst, nextTargetParamAst);
                    if (commaToken > 0)
                        parameterEnd = targetFile->startOf(commaToken);
                }

                // if the name wasn't changed, don't change the target name even if it's different
                const Name *replacementName = newParam->name();
                if (namesEqual(replacementName, sourceParam->name()))
                    replacementName = targetParam->name();

                // don't change the name if it's in a comment
                if (hasCommentedName(targetFile->cppDocument()->translationUnit(),
                                     targetFile->cppDocument()->source(),
                                     targetFunctionDeclarator, existingParamIndex))
                    replacementName = 0;

816
817
818
819
                // track renames
                if (replacementName != targetParam->name() && replacementName)
                    renamedTargetParameters[targetParam] = overview(replacementName);

820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
                // need to change the type (and name)?
                if (!newParam->type().isEqualTo(sourceParam->type())
                        && !newParam->type().isEqualTo(targetParam->type())) {
                    const int parameterTypeStart = targetFile->startOf(targetParamAst);
                    int parameterTypeEnd = 0;
                    if (targetParamAst->declarator)
                        parameterTypeEnd = targetFile->endOf(targetParamAst->declarator);
                    else if (targetParamAst->type_specifier_list)
                        parameterTypeEnd = targetFile->endOf(targetParamAst->type_specifier_list->lastToken() - 1);
                    else
                        parameterTypeEnd = targetFile->startOf(targetParamAst);

                    FullySpecifiedType replacementType = rewriteType(newParam->type(), &env, control);
                    newTargetParam = targetFile->textOf(parameterStart, parameterTypeStart);
                    newTargetParam += overview(replacementType, replacementName);
                    newTargetParam += targetFile->textOf(parameterTypeEnd, parameterEnd);
                    hadChanges = true;
                }
                // change the name only?
                else if (!namesEqual(targetParam->name(), replacementName)) {
                    DeclaratorIdAST *id = getDeclaratorId(targetParamAst->declarator);
                    const QString &replacementNameStr = overview(replacementName);
                    if (id) {
                        newTargetParam += targetFile->textOf(parameterStart, targetFile->startOf(id));
                        QString rest = targetFile->textOf(targetFile->endOf(id), parameterEnd);
                        if (replacementNameStr.isEmpty()) {
                            unsigned nextToken = targetFile->tokenAt(id->lastToken()).kind(); // token after id
                            if (nextToken == T_COMMA
                                    || nextToken == T_EQUAL
                                    || nextToken == T_RPAREN) {
                                if (nextToken != T_EQUAL)
                                    newTargetParam = newTargetParam.trimmed();
                                newTargetParam += rest.trimmed();
                            }
                        } else {
                            newTargetParam += replacementNameStr;
                            newTargetParam += rest;
                        }
                    } else {
                        // add name to unnamed parameter
                        int insertPos = parameterEnd;
                        if (targetParamAst->equal_token)
                            insertPos = targetFile->startOf(targetParamAst->equal_token);
                        newTargetParam += targetFile->textOf(parameterStart, insertPos);

                        // prepend a space, unless ' ', '*', '&'
                        QChar lastChar;
                        if (!newTargetParam.isEmpty())
                            lastChar = newTargetParam.at(newTargetParam.size() - 1);
                        if (!lastChar.isSpace() && lastChar != QLatin1Char('*') && lastChar != QLatin1Char('&'))
                            newTargetParam += QLatin1Char(' ');

                        newTargetParam += replacementNameStr;

                        // append a space, unless unnecessary
                        const QString &rest = targetFile->textOf(insertPos, parameterEnd);
                        if (!rest.isEmpty() && !rest.at(0).isSpace())
                            newTargetParam += QLatin1Char(' ');

                        newTargetParam += rest;
                    }
                    hadChanges = true;
                }
                // change nothing - though the parameter might still have moved
                else {
                    if (existingParamIndex != newParamIndex)
                        hadChanges = true;
                    newTargetParam = targetFile->textOf(parameterStart, parameterEnd);
                }
889
            }
890
891
892
893
894
895
896
897

            // apply
            newTargetParameters += ensureCorrectParameterSpacing(newTargetParam, isFirstNewParam);
        }
        if (hadChanges) {
            changes.replace(targetFile->endOf(targetFunctionDeclarator->lparen_token),
                            targetFile->startOf(targetFunctionDeclarator->rparen_token),
                            newTargetParameters);
898
        }
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917

        // for function definitions, rename the local usages
        FunctionDefinitionAST *targetDefinition = targetDeclaration->asFunctionDefinition();
        if (targetDefinition && !renamedTargetParameters.isEmpty()) {
            const LocalSymbols localSymbols(targetFile->cppDocument(), targetDefinition);
            const int endOfArguments = targetFile->endOf(targetFunctionDeclarator->rparen_token);

            QHashIterator<Symbol *, QString> it(renamedTargetParameters);
            while (it.hasNext()) {
                it.next();
                const QList<SemanticInfo::Use> &uses = localSymbols.uses.value(it.key());
                foreach (const SemanticInfo::Use &use, uses) {
                    const int useStart = targetFile->position(use.line, use.column);
                    if (useStart <= endOfArguments)
                        continue;
                    changes.replace(useStart, useStart + use.length, it.value());
                }
            }
        }
918
919
920
921
922
923
924
925
926
927
928
929
930
    }

    // sync cv qualification
    if (targetFunction->isConst() != newFunction->isConst()
            || targetFunction->isVolatile() != newFunction->isVolatile()) {
        QString cvString;
        if (newFunction->isConst())
            cvString += QLatin1String("const");
        if (newFunction->isVolatile()) {
            if (!cvString.isEmpty())
                cvString += QLatin1Char(' ');
            cvString += QLatin1String("volatile");
        }
931
        const int rparenEnd = targetFile->endOf(targetFunctionDeclarator->rparen_token);
932
        if (targetFunctionDeclarator->cv_qualifier_list) {
933
            const int cvEnd = targetFile->endOf(targetFunctionDeclarator->cv_qualifier_list->lastToken() - 1);
934
935
            // if the qualifies changed, replace
            if (!cvString.isEmpty()) {
936
                changes.replace(targetFile->startOf(targetFunctionDeclarator->cv_qualifier_list->firstToken()),
937
938
939
940
941
942
943
944
945
946
947
948
                                cvEnd, cvString);
            } else {
                // remove
                changes.remove(rparenEnd, cvEnd);
            }
        } else {
            // otherwise add
            cvString.prepend(QLatin1Char(' '));
            changes.insert(rparenEnd, cvString);
        }
    }

949
950
951
952
953
954
955
956
957
958
959
    if (targetOffset != -1) {
        // move all change operations to have the right start offset
        const int moveAmount = targetOffset - targetFile->startOf(targetDeclaration);
        QList<Utils::ChangeSet::EditOp> ops = changes.operationList();
        for (int i = 0; i < ops.size(); ++i) {
            ops[i].pos1 += moveAmount;
            ops[i].pos2 += moveAmount;
        }
        changes = Utils::ChangeSet(ops);
    }

960
961
    return changes;
}
962
963
964
965
966
967

class ApplyDeclDefLinkOperation : public CppQuickFixOperation
{
public:
    explicit ApplyDeclDefLinkOperation(
            const QSharedPointer<const Internal::CppQuickFixAssistInterface> &interface,
Christian Kamm's avatar
Christian Kamm committed
968
969
            const QSharedPointer<FunctionDeclDefLink> &link)
        : CppQuickFixOperation(interface, 10)
970
971
972
973
974
975
976
977
978
979
        , m_link(link)
    {}

    virtual void perform()
    {
        CPPEditorWidget *editor = assistInterface()->editor();
        QSharedPointer<FunctionDeclDefLink> link = editor->declDefLink();
        if (link != m_link)
            return;

980
        return editor->applyDeclDefLinkChanges(/*don't jump*/false);
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
    }

protected:
    virtual void performChanges(const CppTools::CppRefactoringFilePtr &, const CppTools::CppRefactoringChanges &)
    { /* never called since perform is overridden */ }

private:
    QSharedPointer<FunctionDeclDefLink> m_link;
};

QList<CppQuickFixOperation::Ptr> ApplyDeclDefLinkChanges::match(const QSharedPointer<const CppQuickFixAssistInterface> &interface)
{
    QList<CppQuickFixOperation::Ptr> results;

    QSharedPointer<FunctionDeclDefLink> link = interface->editor()->declDefLink();
    if (!link || !link->isMarkerVisible())
        return results;

    QSharedPointer<ApplyDeclDefLinkOperation> op(new ApplyDeclDefLinkOperation(interface, link));
    op->setDescription(FunctionDeclDefLink::tr("Apply function signature changes"));
    results += op;

    return results;
}