File: basicrefactoring.cpp

package info (click to toggle)
kdevelop 4%3A5.6.2-4
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 57,892 kB
  • sloc: cpp: 278,773; javascript: 3,558; python: 3,385; sh: 1,317; ansic: 689; xml: 273; php: 95; makefile: 40; lisp: 13; sed: 12
file content (381 lines) | stat: -rw-r--r-- 14,812 bytes parent folder | download
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
/* This file is part of KDevelop
 *
 * Copyright 2014 Miquel Sabaté <mikisabate@gmail.com>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Library General Public License as
 * published by the Free Software Foundation; either version 2 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public
 * License along with this program; if not, write to the
 * Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 */

// Qt
#include <QAction>
// KF
#include <KParts/MainWindow>
#include <KTextEditor/Document>
#include <KTextEditor/View>
// KDevelop
#include <interfaces/icore.h>
#include <interfaces/idocument.h>
#include <interfaces/iuicontroller.h>
#include <interfaces/idocumentcontroller.h>
#include <interfaces/contextmenuextension.h>
#include <language/duchain/duchain.h>
#include <language/duchain/duchainlock.h>
#include <language/duchain/duchainutils.h>
#include <language/duchain/navigation/abstractnavigationwidget.h>
#include <language/codegen/basicrefactoring.h>
#include <language/interfaces/codecontext.h>
#include <duchain/classdeclaration.h>
#include <duchain/classfunctiondeclaration.h>
#include <duchain/use.h>
#include <sublime/message.h>

#include "progressdialogs/refactoringdialog.h"
#include <debug.h>

#include "ui_basicrefactoring.h"

namespace {
QPair<QString, QString> splitFileAtExtension(const QString& fileName)
{
    int idx = fileName.indexOf(QLatin1Char('.'));
    if (idx == -1) {
        return qMakePair(fileName, QString());
    }
    return qMakePair(fileName.left(idx), fileName.mid(idx));
}
}

using namespace KDevelop;

//BEGIN: BasicRefactoringCollector

BasicRefactoringCollector::BasicRefactoringCollector(const IndexedDeclaration& decl)
    : UsesWidgetCollector(decl)
{
    setCollectConstructors(true);
    setCollectDefinitions(true);
    setCollectOverloads(true);
}

QVector<IndexedTopDUContext> BasicRefactoringCollector::allUsingContexts() const
{
    return m_allUsingContexts;
}

void BasicRefactoringCollector::processUses(KDevelop::ReferencedTopDUContext topContext)
{
    m_allUsingContexts << IndexedTopDUContext(topContext.data());
    UsesWidgetCollector::processUses(topContext);
}

//END: BasicRefactoringCollector

//BEGIN: BasicRefactoring

BasicRefactoring::BasicRefactoring(QObject* parent)
    : QObject(parent)
{
    /* There's nothing to do here. */
}

void BasicRefactoring::fillContextMenu(ContextMenuExtension& extension, Context* context, QWidget* parent)
{
    auto* declContext = dynamic_cast<DeclarationContext*>(context);
    if (!declContext)
        return;

    DUChainReadLocker lock;
    Declaration* declaration = declContext->declaration().data();
    if (declaration && acceptForContextMenu(declaration)) {
        QFileInfo finfo(declaration->topContext()->url().str());
        if (finfo.isWritable()) {
            auto* action = new QAction(i18nc("@action", "Rename \"%1\"...",
                                            declaration->qualifiedIdentifier().toString()), parent);
            action->setData(QVariant::fromValue(IndexedDeclaration(declaration)));
            action->setIcon(QIcon::fromTheme(QStringLiteral("edit-rename")));
            connect(action, &QAction::triggered, this, &BasicRefactoring::executeRenameAction);
            extension.addAction(ContextMenuExtension::RefactorGroup, action);
        }
    }
}

bool BasicRefactoring::shouldRenameUses(KDevelop::Declaration* declaration) const
{
    // Now we know we're editing a declaration, but some declarations we don't offer a rename for
    // basically that's any declaration that wouldn't be fully renamed just by renaming its uses().
    if (declaration->internalContext() || declaration->isForwardDeclaration()) {
        //make an exception for non-class functions
        if (!declaration->isFunctionDeclaration() || dynamic_cast<ClassFunctionDeclaration*>(declaration))
            return false;
    }
    return true;
}

QString BasicRefactoring::newFileName(const QUrl& current, const QString& newName)
{
    QPair<QString, QString> nameExtensionPair = splitFileAtExtension(current.fileName());
    // if current file is lowercased, keep that
    if (nameExtensionPair.first == nameExtensionPair.first.toLower()) {
        return newName.toLower() + nameExtensionPair.second;
    } else {
        return newName + nameExtensionPair.second;
    }
}

DocumentChangeSet::ChangeResult BasicRefactoring::addRenameFileChanges(const QUrl& current,
                                                                       const QString& newName,
                                                                       DocumentChangeSet* changes)
{
    return changes->addDocumentRenameChange(
        IndexedString(current), IndexedString(newFileName(current, newName)));
}

bool BasicRefactoring::shouldRenameFile(Declaration* declaration)
{
    // only try to rename files when we renamed a class/struct
    if (!dynamic_cast<ClassDeclaration*>(declaration)) {
        return false;
    }
    const QUrl currUrl = declaration->topContext()->url().toUrl();
    const QString fileName = currUrl.fileName();
    const QPair<QString, QString> nameExtensionPair = splitFileAtExtension(fileName);
    // check whether we renamed something that is called like the document it lives in
    return nameExtensionPair.first.compare(declaration->identifier().toString(), Qt::CaseInsensitive) == 0;
}

DocumentChangeSet::ChangeResult BasicRefactoring::applyChanges(const QString& oldName, const QString& newName,
                                                               DocumentChangeSet& changes, DUContext* context,
                                                               int usedDeclarationIndex)
{
    if (usedDeclarationIndex == std::numeric_limits<int>::max())
        return DocumentChangeSet::ChangeResult::successfulResult();

    for (int a = 0; a < context->usesCount(); ++a) {
        const Use& use(context->uses()[a]);
        if (use.m_declarationIndex != usedDeclarationIndex)
            continue;
        if (use.m_range.isEmpty()) {
            qCDebug(LANGUAGE) << "found empty use";
            continue;
        }
        DocumentChangeSet::ChangeResult result =
            changes.addChange(DocumentChange(context->url(), context->transformFromLocalRevision(use.m_range), oldName,
                                             newName));
        if (!result)
            return result;
    }

    const auto childContexts = context->childContexts();
    for (DUContext* child : childContexts) {
        DocumentChangeSet::ChangeResult result = applyChanges(oldName, newName, changes, child, usedDeclarationIndex);
        if (!result)
            return result;
    }

    return DocumentChangeSet::ChangeResult::successfulResult();
}

DocumentChangeSet::ChangeResult BasicRefactoring::applyChangesToDeclarations(const QString& oldName,
                                                                             const QString& newName,
                                                                             DocumentChangeSet& changes,
                                                                             const QList<IndexedDeclaration>& declarations)
{
    for (auto& decl : declarations) {
        Declaration* declaration = decl.data();
        if (!declaration)
            continue;
        if (declaration->range().isEmpty())
            qCDebug(LANGUAGE) << "found empty declaration";

        TopDUContext* top = declaration->topContext();
        DocumentChangeSet::ChangeResult result =
            changes.addChange(DocumentChange(top->url(), declaration->rangeInCurrentRevision(), oldName, newName));
        if (!result)
            return result;
    }

    return DocumentChangeSet::ChangeResult::successfulResult();
}

KDevelop::IndexedDeclaration BasicRefactoring::declarationUnderCursor(bool allowUse)
{
    KTextEditor::View* view = ICore::self()->documentController()->activeTextDocumentView();
    if (!view)
        return KDevelop::IndexedDeclaration();
    KTextEditor::Document* doc = view->document();

    DUChainReadLocker lock;
    if (allowUse)
        return DUChainUtils::itemUnderCursor(doc->url(), KTextEditor::Cursor(view->cursorPosition())).declaration;
    else
        return DUChainUtils::declarationInLine(KTextEditor::Cursor(
                                                   view->cursorPosition()),
                                               DUChainUtils::standardContextForUrl(doc->url()));
}

void BasicRefactoring::startInteractiveRename(const KDevelop::IndexedDeclaration& decl)
{
    DUChainReadLocker lock(DUChain::lock());

    Declaration* declaration = decl.data();
    if (!declaration) {
        auto* message = new Sublime::Message(i18n("No declaration under cursor"), Sublime::Message::Error);
        ICore::self()->uiController()->postMessage(message);
        return;
    }
    QFileInfo info(declaration->topContext()->url().str());
    if (!info.isWritable()) {
        const QString messageText = i18n("Declaration is located in non-writable file %1.",
                                declaration->topContext()->url().str());
        auto* message = new Sublime::Message(messageText, Sublime::Message::Error);
        ICore::self()->uiController()->postMessage(message);
        return;
    }

    QString originalName = declaration->identifier().identifier().str();
    lock.unlock();

    NameAndCollector nc = newNameForDeclaration(DeclarationPointer(declaration));

    if (nc.newName == originalName || nc.newName.isEmpty())
        return;

    renameCollectedDeclarations(nc.collector.data(), nc.newName, originalName);
}

bool BasicRefactoring::acceptForContextMenu(const Declaration* decl)
{
    // Default implementation. Some language plugins might override it to
    // handle some cases.
    Q_UNUSED(decl);
    return true;
}

void BasicRefactoring::executeRenameAction()
{
    auto* action = qobject_cast<QAction*>(sender());
    if (action) {
        IndexedDeclaration decl = action->data().value<IndexedDeclaration>();
        if (!decl.isValid())
            decl = declarationUnderCursor();

        if (!decl.isValid())
            return;

        startInteractiveRename(decl);
    }
}

BasicRefactoring::NameAndCollector BasicRefactoring::newNameForDeclaration(
    const KDevelop::DeclarationPointer& declaration)
{
    DUChainReadLocker lock;
    if (!declaration) {
        return {};
    }

    QSharedPointer<BasicRefactoringCollector> collector(new BasicRefactoringCollector(declaration.data()));

    Ui::RenameDialog renameDialog;
    QDialog dialog;
    renameDialog.setupUi(&dialog);

    UsesWidget uses(declaration.data(), collector);

    //So the context-links work
    auto* navigationWidget = declaration->context()->createNavigationWidget(declaration.data());
    if (navigationWidget)
        connect(&uses, &UsesWidget::navigateDeclaration, navigationWidget,
                &AbstractNavigationWidget::navigateDeclaration);

    QString declarationName = declaration->toString();
    dialog.setWindowTitle(i18nc("@title:window Renaming some declaration", "Rename \"%1\"", declarationName));
    renameDialog.edit->setText(declaration->identifier().identifier().str());
    renameDialog.edit->selectAll();

    renameDialog.tabWidget->addTab(&uses, i18nc("@title:tab", "Uses"));
    if (navigationWidget)
        renameDialog.tabWidget->addTab(navigationWidget, i18nc("@title:tab", "Declaration Info"));
    lock.unlock();

    if (dialog.exec() != QDialog::Accepted)
        return {};

    const auto text = renameDialog.edit->text().trimmed();
    RefactoringProgressDialog refactoringProgress(i18n("Renaming \"%1\" to \"%2\"", declarationName,
                                                       text), collector.data());
    if (!collector->isReady()) {
        if (refactoringProgress.exec() != QDialog::Accepted) { // krazy:exclude=crashy
            return {};
        }
    }

    //TODO: input validation
    return {
               text, collector
    };
}

DocumentChangeSet BasicRefactoring::renameCollectedDeclarations(KDevelop::BasicRefactoringCollector* collector,
                                                                const QString& replacementName,
                                                                const QString& originalName, bool apply)
{
    DocumentChangeSet changes;
    DUChainReadLocker lock;

    const auto allUsingContexts = collector->allUsingContexts();
    for (const KDevelop::IndexedTopDUContext collected : allUsingContexts) {
        QSet<int> hadIndices;
        const auto declarations = collector->declarations();
        for (const IndexedDeclaration decl : declarations) {
            uint usedDeclarationIndex = collected.data()->indexForUsedDeclaration(decl.data(), false);
            if (hadIndices.contains(usedDeclarationIndex))
                continue;
            hadIndices.insert(usedDeclarationIndex);
            DocumentChangeSet::ChangeResult result = applyChanges(originalName, replacementName, changes,
                                                                  collected.data(), usedDeclarationIndex);
            if (!result) {
                auto* message = new Sublime::Message(i18n("Failed to apply changes: %1", result.m_failureReason), Sublime::Message::Error);
                ICore::self()->uiController()->postMessage(message);
                return {};
            }
        }
    }

    DocumentChangeSet::ChangeResult result = applyChangesToDeclarations(originalName, replacementName, changes,
                                                                        collector->declarations());
    if (!result) {
        auto* message = new Sublime::Message(i18n("Failed to apply changes: %1", result.m_failureReason), Sublime::Message::Error);
        ICore::self()->uiController()->postMessage(message);
        return {};
    }

    ///We have to ignore failed changes for now, since uses of a constructor or of operator() may be created on "(" parens
    changes.setReplacementPolicy(DocumentChangeSet::IgnoreFailedChange);

    if (!apply) {
        return changes;
    }

    result = changes.applyAllChanges();
    if (!result) {
        auto* message = new Sublime::Message(i18n("Failed to apply changes: %1", result.m_failureReason), Sublime::Message::Error);
        ICore::self()->uiController()->postMessage(message);
    }

    return {};
}

//END: BasicRefactoring