cppmodelmanager.cpp 35.5 KB
Newer Older
hjk's avatar
hjk committed
1
/****************************************************************************
con's avatar
con committed
2
**
Eike Ziller's avatar
Eike Ziller committed
3 4
** Copyright (C) 2015 The Qt Company Ltd.
** Contact: http://www.qt.io/licensing
con's avatar
con committed
5
**
hjk's avatar
hjk committed
6
** This file is part of Qt Creator.
con's avatar
con committed
7
**
hjk's avatar
hjk committed
8 9 10 11
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
Eike Ziller's avatar
Eike Ziller committed
12 13
** a written agreement between you and The Qt Company.  For licensing terms and
** conditions see http://www.qt.io/terms-conditions.  For further information
Eike Ziller's avatar
Eike Ziller committed
14
** use the contact form at http://www.qt.io/contact-us.
15
**
16
** GNU Lesser General Public License Usage
hjk's avatar
hjk committed
17
** Alternatively, this file may be used under the terms of the GNU Lesser
Eike Ziller's avatar
Eike Ziller committed
18 19 20 21 22 23
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file.  Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
hjk's avatar
hjk committed
24
**
Eike Ziller's avatar
Eike Ziller committed
25 26
** In addition, as a special exception, The Qt Company gives you certain additional
** rights.  These rights are described in The Qt Company LGPL Exception
con's avatar
con committed
27 28
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
hjk's avatar
hjk committed
29
****************************************************************************/
hjk's avatar
hjk committed
30

con's avatar
con committed
31
#include "cppmodelmanager.h"
32

33
#include "abstracteditorsupport.h"
34
#include "builtinindexingsupport.h"
35
#include "cppcodemodelinspectordumper.h"
36
#include "cppcodemodelsettings.h"
37
#include "cppfindreferences.h"
38
#include "cppindexingsupport.h"
39
#include "cppmodelmanagersupportinternal.h"
40
#include "cpprefactoringchanges.h"
41
#include "cppsourceprocessor.h"
42
#include "cpptoolsconstants.h"
43
#include "cpptoolsplugin.h"
44
#include "editordocumenthandle.h"
con's avatar
con committed
45

46
#include <coreplugin/documentmanager.h>
47 48
#include <coreplugin/icore.h>
#include <coreplugin/progressmanager/progressmanager.h>
49 50
#include <coreplugin/editormanager/editormanager.h>
#include <texteditor/textdocument.h>
51 52
#include <projectexplorer/projectexplorer.h>
#include <projectexplorer/session.h>
53
#include <extensionsystem/pluginmanager.h>
54
#include <utils/fileutils.h>
hjk's avatar
hjk committed
55
#include <utils/qtcassert.h>
con's avatar
con committed
56

57 58 59 60
#include <QCoreApplication>
#include <QDebug>
#include <QMutexLocker>
#include <QTextBlock>
61
#include <QTimer>
62

63 64
#if defined(QTCREATOR_WITH_DUMP_AST) && defined(Q_CC_GNU)
#define WITH_AST_DUMP
65 66
#include <iostream>
#include <sstream>
67
#endif
hjk's avatar
hjk committed
68

69 70
Q_DECLARE_METATYPE(QSet<QString>)

71 72
static const bool DumpProjectInfo = qgetenv("QTC_DUMP_PROJECT_INFO") == "1";

73 74
using namespace CppTools;
using namespace CppTools::Internal;
con's avatar
con committed
75 76
using namespace CPlusPlus;

77
#ifdef QTCREATOR_WITH_DUMP_AST
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

#include <cxxabi.h>

class DumpAST: protected ASTVisitor
{
public:
    int depth;

    DumpAST(Control *control)
        : ASTVisitor(control), depth(0)
    { }

    void operator()(AST *ast)
    { accept(ast); }

protected:
    virtual bool preVisit(AST *ast)
    {
        std::ostringstream s;
        PrettyPrinter pp(control(), s);
        pp(ast);
        QString code = QString::fromStdString(s.str());
        code.replace('\n', ' ');
        code.replace(QRegExp("\\s+"), " ");

        const char *name = abi::__cxa_demangle(typeid(*ast).name(), 0, 0, 0) + 11;

        QByteArray ind(depth, ' ');
        ind += name;

        printf("%-40s %s\n", ind.constData(), qPrintable(code));
        ++depth;
        return true;
    }

    virtual void postVisit(AST *)
    { --depth; }
};

Roberto Raggi's avatar
Roberto Raggi committed
117
#endif // QTCREATOR_WITH_DUMP_AST
118

119 120 121 122 123 124 125 126 127 128 129
namespace CppTools {
namespace Internal {

static QMutex m_instanceMutex;
static CppModelManager *m_instance;

class CppModelManagerPrivate
{
public:
    // Snapshot
    mutable QMutex m_snapshotMutex;
130
    Snapshot m_snapshot;
131 132 133 134

    // Project integration
    mutable QMutex m_projectMutex;
    QMap<ProjectExplorer::Project *, ProjectInfo> m_projectToProjectsInfo;
135 136
    QMap<Utils::FileName, QList<ProjectPart::Ptr> > m_fileToProjectParts;
    QMap<QString, ProjectPart::Ptr> m_projectFileToProjectPart;
137 138 139 140 141 142 143
    // The members below are cached/(re)calculated from the projects and/or their project parts
    bool m_dirty;
    QStringList m_projectFiles;
    ProjectPart::HeaderPaths m_headerPaths;
    QByteArray m_definedMacros;

    // Editor integration
144 145
    mutable QMutex m_cppEditorDocumentsMutex;
    QMap<QString, CppEditorDocumentHandle *> m_cppEditorDocuments;
146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165
    QSet<AbstractEditorSupport *> m_extraEditorSupports;

    // Completion & highlighting
    QHash<QString, ModelManagerSupport *> m_idTocodeModelSupporter;
    QScopedPointer<ModelManagerSupport> m_modelManagerSupportFallback;

    // Indexing
    CppIndexingSupport *m_indexingSupporter;
    CppIndexingSupport *m_internalIndexingSupport;
    bool m_indexerEnabled;

    CppFindReferences *m_findReferences;

    bool m_enableGC;
    QTimer m_delayedGcTimer;
};

} // namespace Internal

const char pp_configuration[] =
con's avatar
con committed
166
    "# 1 \"<configuration>\"\n"
167
    "#define Q_CREATOR_RUN 1\n"
con's avatar
con committed
168 169 170 171 172 173
    "#define __cplusplus 1\n"
    "#define __extension__\n"
    "#define __context__\n"
    "#define __range__\n"
    "#define   restrict\n"
    "#define __restrict\n"
174
    "#define __restrict__\n"
con's avatar
con committed
175

176 177 178 179
    "#define __complex__\n"
    "#define __imag__\n"
    "#define __real__\n"

180 181
    "#define __builtin_va_arg(a,b) ((b)0)\n"

182 183
    "#define _Pragma(x)\n" // C99 _Pragma operator

con's avatar
con committed
184 185
    // ### add macros for win32
    "#define __cdecl\n"
186
    "#define __stdcall\n"
187
    "#define __thiscall\n"
con's avatar
con committed
188 189 190 191 192
    "#define QT_WA(x) x\n"
    "#define CALLBACK\n"
    "#define STDMETHODCALLTYPE\n"
    "#define __RPC_FAR\n"
    "#define __declspec(a)\n"
193 194 195
    "#define STDMETHOD(method) virtual HRESULT STDMETHODCALLTYPE method\n"
    "#define __try try\n"
    "#define __except catch\n"
196 197
    "#define __finally\n"
    "#define __inline inline\n"
198 199
    "#define __forceinline inline\n"
    "#define __pragma(x)\n";
con's avatar
con committed
200

201
QSet<QString> CppModelManager::timeStampModifiedFiles(const QList<Document::Ptr> &documentsToCheck)
202
{
203
    QSet<QString> sourceFiles;
204

205
    foreach (const Document::Ptr doc, documentsToCheck) {
206 207
        const QDateTime lastModified = doc->lastModified();

208
        if (!lastModified.isNull()) {
209 210 211
            QFileInfo fileInfo(doc->fileName());

            if (fileInfo.exists() && fileInfo.lastModified() != lastModified)
212
                sourceFiles.insert(doc->fileName());
213 214 215
        }
    }

216 217 218
    return sourceFiles;
}

219 220 221 222 223 224 225 226 227 228 229 230
/*!
 * \brief createSourceProcessor Create a new source processor, which will signal the
 * model manager when a document has been processed.
 *
 * Indexed file is truncated version of fully parsed document: copy of source
 * code and full AST will be dropped when indexing is done.
 *
 * \return a new source processor object, which the caller needs to delete when finished.
 */
CppSourceProcessor *CppModelManager::createSourceProcessor()
{
    CppModelManager *that = instance();
Orgad Shaneh's avatar
Orgad Shaneh committed
231
    return new CppSourceProcessor(that->snapshot(), [that](const Document::Ptr &doc) {
232 233 234 235 236
        that->emitDocumentUpdated(doc);
        doc->releaseSourceAndAST();
    });
}

237 238 239 240 241 242 243
QString CppModelManager::editorConfigurationFileName()
{
    return QLatin1String("<per-editor-defines>");
}

QString CppModelManager::configurationFileName()
{
244
    return Preprocessor::configurationFileName;
245 246
}

247 248 249 250 251 252 253
void CppModelManager::updateModifiedSourceFiles()
{
    const Snapshot snapshot = this->snapshot();
    QList<Document::Ptr> documentsToCheck;
    foreach (const Document::Ptr document, snapshot)
        documentsToCheck << document;

254
    updateSourceFiles(timeStampModifiedFiles(documentsToCheck));
255 256
}

con's avatar
con committed
257 258
/*!
    \class CppTools::CppModelManager
259 260 261
    \brief The CppModelManager keeps tracks of the source files the code model is aware of.

    The CppModelManager manages the source files in a Snapshot object.
con's avatar
con committed
262

263 264 265 266
    The snapshot is updated in case e.g.
        * New files are opened/edited (Editor integration)
        * A project manager pushes updated project information (Project integration)
        * Files are garbage collected
con's avatar
con committed
267 268
*/

269 270
CppModelManager *CppModelManager::instance()
{
271 272 273 274 275 276 277 278
    if (m_instance)
        return m_instance;

    QMutexLocker locker(&m_instanceMutex);
    if (!m_instance)
        m_instance = new CppModelManager;

    return m_instance;
279 280
}

281
CppModelManager::CppModelManager(QObject *parent)
282
    : CppModelManagerBase(parent), d(new CppModelManagerPrivate)
con's avatar
con committed
283
{
284 285 286
    d->m_indexingSupporter = 0;
    d->m_enableGC = true;

287
    qRegisterMetaType<QSet<QString> >();
288
    connect(this, SIGNAL(sourceFilesRefreshed(QSet<QString>)),
289
            this, SLOT(onSourceFilesRefreshed()));
Erik Verbruggen's avatar
Erik Verbruggen committed
290

291 292
    d->m_findReferences = new CppFindReferences(this);
    d->m_indexerEnabled = qgetenv("QTC_NO_CODE_INDEXER") != "1";
Roberto Raggi's avatar
Roberto Raggi committed
293

294
    d->m_dirty = true;
295

296 297 298
    d->m_delayedGcTimer.setObjectName(QLatin1String("CppModelManager::m_delayedGcTimer"));
    d->m_delayedGcTimer.setSingleShot(true);
    connect(&d->m_delayedGcTimer, SIGNAL(timeout()), this, SLOT(GC()));
299

hjk's avatar
hjk committed
300 301
    QObject *sessionManager = ProjectExplorer::SessionManager::instance();
    connect(sessionManager, SIGNAL(projectAdded(ProjectExplorer::Project*)),
302
            this, SLOT(onProjectAdded(ProjectExplorer::Project*)));
hjk's avatar
hjk committed
303
    connect(sessionManager, SIGNAL(aboutToRemoveProject(ProjectExplorer::Project*)),
Robert Loehning's avatar
Robert Loehning committed
304
            this, SLOT(onAboutToRemoveProject(ProjectExplorer::Project*)));
hjk's avatar
hjk committed
305
    connect(sessionManager, SIGNAL(aboutToLoadSession(QString)),
306
            this, SLOT(onAboutToLoadSession()));
hjk's avatar
hjk committed
307
    connect(sessionManager, SIGNAL(aboutToUnloadSession(QString)),
308
            this, SLOT(onAboutToUnloadSession()));
309 310 311 312

    connect(Core::EditorManager::instance(), &Core::EditorManager::currentEditorChanged,
            this, &CppModelManager::onCurrentEditorChanged);

313 314
    connect(Core::DocumentManager::instance(), &Core::DocumentManager::allDocumentsRenamed,
            this, &CppModelManager::renameIncludes);
con's avatar
con committed
315

316 317 318
    connect(Core::ICore::instance(), SIGNAL(coreAboutToClose()),
            this, SLOT(onCoreAboutToClose()));

con's avatar
con committed
319
    qRegisterMetaType<CPlusPlus::Document::Ptr>("CPlusPlus::Document::Ptr");
320
    qRegisterMetaType<QList<Document::DiagnosticMessage>>(
321
                "QList<CPlusPlus::Document::DiagnosticMessage>");
con's avatar
con committed
322

323
    d->m_modelManagerSupportFallback.reset(new ModelManagerSupportInternal);
324
    CppToolsPlugin::instance()->codeModelSettings()->setDefaultId(
325 326
                d->m_modelManagerSupportFallback->id());
    addModelManagerSupport(d->m_modelManagerSupportFallback.data());
327

328
    d->m_internalIndexingSupport = new BuiltinIndexingSupport;
con's avatar
con committed
329 330 331
}

CppModelManager::~CppModelManager()
332
{
333
    delete d->m_internalIndexingSupport;
334
    delete d;
335
}
con's avatar
con committed
336

337
Snapshot CppModelManager::snapshot() const
338
{
339 340
    QMutexLocker locker(&d->m_snapshotMutex);
    return d->m_snapshot;
341
}
con's avatar
con committed
342

343 344
Document::Ptr CppModelManager::document(const QString &fileName) const
{
345 346
    QMutexLocker locker(&d->m_snapshotMutex);
    return d->m_snapshot.document(fileName);
347 348 349 350 351 352 353
}

/// Replace the document in the snapshot.
///
/// \returns true if successful, false if the new document is out-dated.
bool CppModelManager::replaceDocument(Document::Ptr newDoc)
{
354
    QMutexLocker locker(&d->m_snapshotMutex);
355

356
    Document::Ptr previous = d->m_snapshot.document(newDoc->fileName());
357 358 359 360
    if (previous && (newDoc->revision() != 0 && newDoc->revision() < previous->revision()))
        // the new document is outdated
        return false;

361
    d->m_snapshot.insert(newDoc);
362 363 364
    return true;
}

365 366
void CppModelManager::ensureUpdated()
{
367 368
    QMutexLocker locker(&d->m_projectMutex);
    if (!d->m_dirty)
369 370
        return;

371 372 373 374
    d->m_projectFiles = internalProjectFiles();
    d->m_headerPaths = internalHeaderPaths();
    d->m_definedMacros = internalDefinedMacros();
    d->m_dirty = false;
375 376
}

377
QStringList CppModelManager::internalProjectFiles() const
con's avatar
con committed
378 379
{
    QStringList files;
380
    QMapIterator<ProjectExplorer::Project *, ProjectInfo> it(d->m_projectToProjectsInfo);
con's avatar
con committed
381 382
    while (it.hasNext()) {
        it.next();
383
        const ProjectInfo pinfo = it.value();
384
        foreach (const ProjectPart::Ptr &part, pinfo.projectParts()) {
385 386
            foreach (const ProjectFile &file, part->files)
                files += file.path;
387
        }
con's avatar
con committed
388
    }
389
    files.removeDuplicates();
con's avatar
con committed
390 391 392
    return files;
}

393
ProjectPart::HeaderPaths CppModelManager::internalHeaderPaths() const
con's avatar
con committed
394
{
395
    ProjectPart::HeaderPaths headerPaths;
396
    QMapIterator<ProjectExplorer::Project *, ProjectInfo> it(d->m_projectToProjectsInfo);
con's avatar
con committed
397 398
    while (it.hasNext()) {
        it.next();
399
        const ProjectInfo pinfo = it.value();
400 401
        foreach (const ProjectPart::Ptr &part, pinfo.projectParts()) {
            foreach (const ProjectPart::HeaderPath &path, part->headerPaths) {
402
                const ProjectPart::HeaderPath hp(QDir::cleanPath(path.path), path.type);
403 404 405 406
                if (!headerPaths.contains(hp))
                    headerPaths += hp;
            }
        }
con's avatar
con committed
407
    }
408
    return headerPaths;
con's avatar
con committed
409 410
}

411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426
static void addUnique(const QList<QByteArray> &defs, QByteArray *macros, QSet<QByteArray> *alreadyIn)
{
    Q_ASSERT(macros);
    Q_ASSERT(alreadyIn);

    foreach (const QByteArray &def, defs) {
        if (def.trimmed().isEmpty())
            continue;
        if (!alreadyIn->contains(def)) {
            macros->append(def);
            macros->append('\n');
            alreadyIn->insert(def);
        }
    }
}

427
QByteArray CppModelManager::internalDefinedMacros() const
con's avatar
con committed
428 429
{
    QByteArray macros;
430
    QSet<QByteArray> alreadyIn;
431
    QMapIterator<ProjectExplorer::Project *, ProjectInfo> it(d->m_projectToProjectsInfo);
con's avatar
con committed
432 433
    while (it.hasNext()) {
        it.next();
434
        const ProjectInfo pinfo = it.value();
435
        foreach (const ProjectPart::Ptr &part, pinfo.projectParts()) {
436 437
            addUnique(part->toolchainDefines.split('\n'), &macros, &alreadyIn);
            addUnique(part->projectDefines.split('\n'), &macros, &alreadyIn);
438
            if (!part->projectConfigFile.isEmpty())
439
                macros += ProjectPart::readProjectConfigFile(part);
440
        }
con's avatar
con committed
441 442 443 444
    }
    return macros;
}

445
/// This function will acquire mutexes!
446
void CppModelManager::dumpModelManagerConfiguration(const QString &logFileId)
447
{
448 449 450 451
    const Snapshot globalSnapshot = snapshot();
    const QString globalSnapshotTitle
        = QString::fromLatin1("Global/Indexing Snapshot (%1 Documents)").arg(globalSnapshot.size());

452
    CppCodeModelInspector::Dumper dumper(globalSnapshot, logFileId);
453 454 455
    dumper.dumpProjectInfos(projectInfos());
    dumper.dumpSnapshot(globalSnapshot, globalSnapshotTitle, /*isGlobalSnapshot=*/ true);
    dumper.dumpWorkingCopy(workingCopy());
456
    ensureUpdated();
457
    dumper.dumpMergedEntities(d->m_headerPaths, d->m_definedMacros);
458 459
}

460
void CppModelManager::addExtraEditorSupport(AbstractEditorSupport *editorSupport)
461
{
462
    d->m_extraEditorSupports.insert(editorSupport);
463 464
}

465
void CppModelManager::removeExtraEditorSupport(AbstractEditorSupport *editorSupport)
466
{
467
    d->m_extraEditorSupports.remove(editorSupport);
468 469
}

470
CppEditorDocumentHandle *CppModelManager::cppEditorDocument(const QString &filePath) const
471
{
472 473
    if (filePath.isEmpty())
        return 0;
474

475 476
    QMutexLocker locker(&d->m_cppEditorDocumentsMutex);
    return d->m_cppEditorDocuments.value(filePath, 0);
477 478
}

479
void CppModelManager::registerCppEditorDocument(CppEditorDocumentHandle *editorDocument)
480
{
481 482 483
    QTC_ASSERT(editorDocument, return);
    const QString filePath = editorDocument->filePath();
    QTC_ASSERT(!filePath.isEmpty(), return);
484

485 486 487
    QMutexLocker locker(&d->m_cppEditorDocumentsMutex);
    QTC_ASSERT(d->m_cppEditorDocuments.value(filePath, 0) == 0, return);
    d->m_cppEditorDocuments.insert(filePath, editorDocument);
488
}
489

490
void CppModelManager::unregisterCppEditorDocument(const QString &filePath)
491 492
{
    QTC_ASSERT(!filePath.isEmpty(), return);
493

494 495
    static short closedCppDocuments = 0;
    int openCppDocuments = 0;
496

497
    {
498 499 500 501
        QMutexLocker locker(&d->m_cppEditorDocumentsMutex);
        QTC_ASSERT(d->m_cppEditorDocuments.value(filePath, 0), return);
        QTC_CHECK(d->m_cppEditorDocuments.remove(filePath) == 1);
        openCppDocuments = d->m_cppEditorDocuments.size();
502 503
    }

504 505 506
    ++closedCppDocuments;
    if (openCppDocuments == 0 || closedCppDocuments == 5) {
        closedCppDocuments = 0;
507
        delayedGC();
508 509 510
    }
}

511
QList<int> CppModelManager::references(Symbol *symbol, const LookupContext &context)
512
{
513
    return d->m_findReferences->references(symbol, context);
514 515
}

516
void CppModelManager::findUsages(Symbol *symbol, const LookupContext &context)
Roberto Raggi's avatar
Roberto Raggi committed
517
{
518
    if (symbol->identifier())
519
        d->m_findReferences->findUsages(symbol, context);
520 521
}

522 523
void CppModelManager::renameUsages(Symbol *symbol,
                                   const LookupContext &context,
524
                                   const QString &replacement)
525 526
{
    if (symbol->identifier())
527
        d->m_findReferences->renameUsages(symbol, context, replacement);
Roberto Raggi's avatar
Roberto Raggi committed
528 529
}

530
void CppModelManager::findMacroUsages(const Macro &macro)
Christian Kamm's avatar
Christian Kamm committed
531
{
532
    d->m_findReferences->findMacroUses(macro);
Christian Kamm's avatar
Christian Kamm committed
533 534
}

535
void CppModelManager::renameMacroUsages(const Macro &macro, const QString &replacement)
536
{
537
    d->m_findReferences->renameMacroUses(macro, replacement);
538 539
}

540
void CppModelManager::replaceSnapshot(const Snapshot &newSnapshot)
541
{
542 543
    QMutexLocker snapshotLocker(&d->m_snapshotMutex);
    d->m_snapshot = newSnapshot;
544 545
}

546
WorkingCopy CppModelManager::buildWorkingCopyList()
con's avatar
con committed
547
{
548
    WorkingCopy workingCopy;
549

550 551 552 553 554
    foreach (const CppEditorDocumentHandle *cppEditorDocument, cppEditorDocuments()) {
        workingCopy.insert(cppEditorDocument->filePath(),
                           cppEditorDocument->contents(),
                           cppEditorDocument->revision());
    }
con's avatar
con committed
555

556
    QSetIterator<AbstractEditorSupport *> it(d->m_extraEditorSupports);
557 558
    while (it.hasNext()) {
        AbstractEditorSupport *es = it.next();
559
        workingCopy.insert(es->fileName(), es->contents(), es->revision());
560 561
    }

562
    // Add the project configuration file
563
    QByteArray conf = codeModelConfiguration();
con's avatar
con committed
564
    conf += definedMacros();
565
    workingCopy.insert(configurationFileName(), conf);
con's avatar
con committed
566 567 568 569

    return workingCopy;
}

570
WorkingCopy CppModelManager::workingCopy() const
571 572 573 574
{
    return const_cast<CppModelManager *>(this)->buildWorkingCopyList();
}

575 576 577 578 579
QByteArray CppModelManager::codeModelConfiguration() const
{
    return QByteArray::fromRawData(pp_configuration, qstrlen(pp_configuration));
}

580
QFuture<void> CppModelManager::updateSourceFiles(const QSet<QString> &sourceFiles,
581
                                                 ProgressNotificationMode mode)
582
{
583
    if (sourceFiles.isEmpty() || !d->m_indexerEnabled)
584 585
        return QFuture<void>();

586 587 588
    if (d->m_indexingSupporter)
        d->m_indexingSupporter->refreshSourceFiles(sourceFiles, mode);
    return d->m_internalIndexingSupport->refreshSourceFiles(sourceFiles, mode);
589
}
con's avatar
con committed
590

591
QList<ProjectInfo> CppModelManager::projectInfos() const
592
{
593 594
    QMutexLocker locker(&d->m_projectMutex);
    return d->m_projectToProjectsInfo.values();
595 596
}

597
ProjectInfo CppModelManager::projectInfo(ProjectExplorer::Project *project) const
598
{
599
    QMutexLocker locker(&d->m_projectMutex);
600
    return d->m_projectToProjectsInfo.value(project, ProjectInfo());
601 602
}

603 604 605 606 607 608
/// \brief Remove all files and their includes (recursively) of given ProjectInfo from the snapshot.
void CppModelManager::removeProjectInfoFilesAndIncludesFromSnapshot(const ProjectInfo &projectInfo)
{
    if (!projectInfo.isValid())
        return;

609
    QMutexLocker snapshotLocker(&d->m_snapshotMutex);
610 611
    foreach (const ProjectPart::Ptr &projectPart, projectInfo.projectParts()) {
        foreach (const ProjectFile &cxxFile, projectPart->files) {
612 613 614
            foreach (const QString &fileName, d->m_snapshot.allIncludesForDocument(cxxFile.path))
                d->m_snapshot.remove(fileName);
            d->m_snapshot.remove(cxxFile.path);
615 616 617 618
        }
    }
}

619
QList<CppEditorDocumentHandle *> CppModelManager::cppEditorDocuments() const
620
{
621 622
    QMutexLocker locker(&d->m_cppEditorDocumentsMutex);
    return d->m_cppEditorDocuments.values();
623 624
}

625 626 627
/// \brief Remove all given files from the snapshot.
void CppModelManager::removeFilesFromSnapshot(const QSet<QString> &filesToRemove)
{
628
    QMutexLocker snapshotLocker(&d->m_snapshotMutex);
629 630
    QSetIterator<QString> i(filesToRemove);
    while (i.hasNext())
631
        d->m_snapshot.remove(i.next());
632 633 634
}

class ProjectInfoComparer
635
{
636
public:
637 638
    ProjectInfoComparer(const ProjectInfo &oldProjectInfo,
                        const ProjectInfo &newProjectInfo)
639
        : m_old(oldProjectInfo)
640
        , m_oldSourceFiles(oldProjectInfo.sourceFiles())
641
        , m_new(newProjectInfo)
642
        , m_newSourceFiles(newProjectInfo.sourceFiles())
643 644
    {}

645 646 647
    bool definesChanged() const { return m_new.definesChanged(m_old); }
    bool configurationChanged() const { return m_new.configurationChanged(m_old); }
    bool configurationOrFilesChanged() const { return m_new.configurationOrFilesChanged(m_old); }
648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676

    QSet<QString> addedFiles() const
    {
        QSet<QString> addedFilesSet = m_newSourceFiles;
        addedFilesSet.subtract(m_oldSourceFiles);
        return addedFilesSet;
    }

    QSet<QString> removedFiles() const
    {
        QSet<QString> removedFilesSet = m_oldSourceFiles;
        removedFilesSet.subtract(m_newSourceFiles);
        return removedFilesSet;
    }

    /// Returns a list of common files that have a changed timestamp.
    QSet<QString> timeStampModifiedFiles(const Snapshot &snapshot) const
    {
        QSet<QString> commonSourceFiles = m_newSourceFiles;
        commonSourceFiles.intersect(m_oldSourceFiles);

        QList<Document::Ptr> documentsToCheck;
        QSetIterator<QString> i(commonSourceFiles);
        while (i.hasNext()) {
            const QString file = i.next();
            if (Document::Ptr document = snapshot.document(file))
                documentsToCheck << document;
        }

677
        return CppModelManager::timeStampModifiedFiles(documentsToCheck);
678 679 680
    }

private:
681
    const ProjectInfo &m_old;
682 683
    const QSet<QString> m_oldSourceFiles;

684
    const ProjectInfo &m_new;
685 686 687
    const QSet<QString> m_newSourceFiles;
};

688 689 690
/// Make sure that m_projectMutex is locked when calling this.
void CppModelManager::recalculateFileToProjectParts()
{
691 692 693
    d->m_projectFileToProjectPart.clear();
    d->m_fileToProjectParts.clear();
    foreach (const ProjectInfo &projectInfo, d->m_projectToProjectsInfo) {
694
        foreach (const ProjectPart::Ptr &projectPart, projectInfo.projectParts()) {
695
            d->m_projectFileToProjectPart[projectPart->projectFile] = projectPart;
696
            foreach (const ProjectFile &cxxFile, projectPart->files)
697 698
                d->m_fileToProjectParts[Utils::FileName::fromString(cxxFile.path)].append(
                            projectPart);
699

700 701 702 703
        }
    }
}

704
void CppModelManager::updateCppEditorDocuments() const
705
{
706 707
    // Refresh visible documents
    QSet<Core::IDocument *> visibleCppEditorDocuments;
708
    foreach (Core::IEditor *editor, Core::EditorManager::visibleEditors()) {
709
        if (Core::IDocument *document = editor->document()) {
710 711
            const QString filePath = document->filePath().toString();
            if (CppEditorDocumentHandle *theCppEditorDocument = cppEditorDocument(filePath)) {
712
                visibleCppEditorDocuments.insert(document);
713
                theCppEditorDocument->processor()->run();
714
            }
715 716 717
        }
    }

718 719 720 721 722
    // Mark invisible documents dirty
    QSet<Core::IDocument *> invisibleCppEditorDocuments
        = Core::DocumentModel::openedDocuments().toSet();
    invisibleCppEditorDocuments.subtract(visibleCppEditorDocuments);
    foreach (Core::IDocument *document, invisibleCppEditorDocuments) {
723 724 725
        const QString filePath = document->filePath().toString();
        if (CppEditorDocumentHandle *theCppEditorDocument = cppEditorDocument(filePath))
            theCppEditorDocument->setNeedsRefresh(true);
726 727 728
    }
}

729 730 731
QFuture<void> CppModelManager::updateProjectInfo(const ProjectInfo &newProjectInfo)
{
    if (!newProjectInfo.isValid())
732
        return QFuture<void>();
733

734
    QSet<QString> filesToReindex;
735 736
    bool filesRemoved = false;

737
    { // Only hold the mutex for a limited scope, so the dumping afterwards does not deadlock.
738
        QMutexLocker projectLocker(&d->m_projectMutex);
739 740

        ProjectExplorer::Project *project = newProjectInfo.project().data();
741
        const QSet<QString> newSourceFiles = newProjectInfo.sourceFiles();
742

743
        // Check if we can avoid a full reindexing
744
        ProjectInfo oldProjectInfo = d->m_projectToProjectsInfo.value(project);
745
        if (oldProjectInfo.isValid()) {
746
            ProjectInfoComparer comparer(oldProjectInfo, newProjectInfo);
747 748 749 750

            if (!comparer.configurationOrFilesChanged()) {
                // Some other attached data might have changed
                d->m_projectToProjectsInfo.insert(project, newProjectInfo);
751
                return QFuture<void>();
752
            }
753

754 755 756
            // If the project configuration changed, do a full reindexing
            if (comparer.configurationChanged()) {
                removeProjectInfoFilesAndIncludesFromSnapshot(oldProjectInfo);
757
                filesToReindex.unite(newSourceFiles);
758 759 760

                // The "configuration file" includes all defines and therefore should be updated
                if (comparer.definesChanged()) {
761 762
                    QMutexLocker snapshotLocker(&d->m_snapshotMutex);
                    d->m_snapshot.remove(configurationFileName());
763
                }
764 765 766 767

            // Otherwise check for added and modified files
            } else {
                const QSet<QString> addedFiles = comparer.addedFiles();
768
                filesToReindex.unite(addedFiles);
769 770

                const QSet<QString> modifiedFiles = comparer.timeStampModifiedFiles(snapshot());
771
                filesToReindex.unite(modifiedFiles);
772
            }
773 774 775 776 777 778 779 780 781 782 783

            // Announce and purge the removed files from the snapshot
            const QSet<QString> removedFiles = comparer.removedFiles();
            if (!removedFiles.isEmpty()) {
                filesRemoved = true;
                emit aboutToRemoveFiles(removedFiles.toList());
                removeFilesFromSnapshot(removedFiles);
            }

        // A new project was opened/created, do a full indexing
        } else {
784
            filesToReindex.unite(newSourceFiles);
785 786
        }

787
        // Update Project/ProjectInfo and File/ProjectPart table
788 789
        d->m_dirty = true;
        d->m_projectToProjectsInfo.insert(project, newProjectInfo);
790
        recalculateFileToProjectParts();
791

792 793 794
    } // Mutex scope

    // If requested, dump everything we got
795
    if (DumpProjectInfo)
796
        dumpModelManagerConfiguration(QLatin1String("updateProjectInfo"));
797

798 799 800 801 802
    // Remove files from snapshot that are not reachable any more
    if (filesRemoved)
        GC();

    emit projectPartsUpdated(newProjectInfo.project().data());
803

804 805 806 807
    // Ideally, we would update all the editor documents that depend on the 'filesToReindex'.
    // However, on e.g. a session restore first the editor documents are created and then the
    // project updates come in. That is, there are no reasonable dependency tables based on
    // resolved includes that we could rely on.
808
    updateCppEditorDocuments();
809

810 811
    // Trigger reindexing
    return updateSourceFiles(filesToReindex, ForcedProgressNotification);
812 813
}

814 815
ProjectPart::Ptr CppModelManager::projectPartForProjectFile(const QString &projectFile) const
{
816
    return d->m_projectFileToProjectPart.value(projectFile);