indexer.cpp 37.5 KB
Newer Older
1 2
/****************************************************************************
**
3
** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
4 5 6 7 8 9 10 11 12
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** 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
** a written agreement between you and Digia.  For licensing terms and
Eike Ziller's avatar
Eike Ziller committed
13 14
** conditions see http://www.qt.io/licensing.  For further information
** use the contact form at http://www.qt.io/contact-us.
15 16 17
**
** GNU Lesser General Public License Usage
** 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.
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
**
** In addition, as a special exception, Digia gives you certain additional
** rights.  These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/

#include "clangutils.h"
#include "indexer.h"
#include "index.h"
#include "cxraii.h"
#include "sourcelocation.h"
#include "utils_p.h"
#include "pchmanager.h"
#include "raii/scopedclangoptions.h"

#include <clang-c/Index.h>

#include <coreplugin/editormanager/editormanager.h>
#include <coreplugin/icore.h>
#include <coreplugin/progressmanager/progressmanager.h>
#include <utils/fileutils.h>
#include <utils/QtConcurrentTools>

#include <QDebug>
#include <QVector>
#include <QHash>
#include <QSet>
#include <QFile>
#include <QFileInfo>
#include <QFutureWatcher>
#include <QDir>
#include <QFuture>
#include <QTime>
#include <QRunnable>
#include <QThreadPool>
#include <QDateTime>
#include <QStringBuilder>

using namespace Utils;
using namespace ClangCodeModel;
using namespace Internal;

namespace ClangCodeModel {

// The indexing result, containing the symbols found, reported by the indexer processor.
struct IndexingResult
{
    typedef CppTools::ProjectPart ProjectPart;

    IndexingResult()
75
        : m_unit(Unit::create())
76 77 78 79
    {}

    IndexingResult(const QVector<Symbol> &symbol,
                   const QSet<QString> &processedFiles,
80
                   const Unit::Ptr &unit,
81 82 83 84 85 86 87 88 89
                   const ProjectPart::Ptr &projectPart)
        : m_symbolsInfo(symbol)
        , m_processedFiles(processedFiles)
        , m_unit(unit)
        , m_projectPart(projectPart)
    {}

    QVector<Symbol> m_symbolsInfo;
    QSet<QString> m_processedFiles;
90
    Unit::Ptr m_unit;
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
    ProjectPart::Ptr m_projectPart;
};

class LibClangIndexer;

class IndexerPrivate : public QObject
{
    Q_OBJECT

public:
    typedef CppTools::ProjectPart ProjectPart;

public:
    IndexerPrivate(Indexer *indexer);
    ~IndexerPrivate()
    { cancel(true); }

    // This enumeration is used to index a vector. So be careful when changing.
    enum FileType {
        ImplementationFile = 0,
        HeaderFile,
        TotalFileTypes
    };

    struct FileData
    {
        FileData() : m_upToDate(false) {}
        FileData(const QString &fileName,
                 const ProjectPart::Ptr &projectPart,
                 bool upToDate = false)
            : m_fileName(fileName)
            , m_projectPart(projectPart)
            , m_upToDate(upToDate)
            , m_managementOptions(CXTranslationUnit_DetailedPreprocessingRecord
                                  | CXTranslationUnit_Incomplete)
        {}

        QString m_fileName;
        ProjectPart::Ptr m_projectPart;
        bool m_upToDate;
        unsigned m_managementOptions;
    };

    void synchronize(const QVector<IndexingResult> &results);
    void finished(LibClangIndexer *indexer);
    bool noIndexersRunning() const;

private:
    mutable QMutex m_mutex;

    void indexingFinished();
    void cancelIndexing();
    int runningIndexerCount() const;

public slots:
    void dependencyGraphComputed();
    void restoredSymbolsAnalysed();

public:
    enum IndexingMode {
        RelaxedIndexing,        // Index symbols from any file.
        ConstrainedIndexing     // Index symbols only from the requested files.
    };

    void startLoading();
    void concludeLoading();

    void computeDependencyGraph();
    void analyzeRestoredSymbols();

161
    void runQuickIndexing(const Unit::Ptr &unit, const ProjectPart::Ptr &part);
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
    void run();
    void run(const QStringList &fileNames);
    void runCore(const QHash<QString, FileData> &headers,
                          const QHash<QString, FileData> &impls,
                          IndexingMode mode);
    void watchIndexingThreads(QFutureInterface<void> &future);
    bool isBusy() const;
    void cancel(bool wait);
    void reset();

    bool addFile(const QString &fileName,
                 ProjectPart::Ptr projectPart);
    void addOrUpdateFileData(const QString &fileName,
                             ProjectPart::Ptr projectPart,
                             bool upToDate);
    QStringList allFiles() const;
    bool isTrackingFile(const QString &fileName, FileType type) const;
    static FileType identifyFileType(const QString &fileName);
    static void populateFileNames(QStringList *all, const QList<FileData> &data);
    QStringList compilationOptions(const QString &fileName) const;

    bool deserealizeSymbols();
    void serializeSymbols() const;

    QList<Symbol> symbols(Symbol::Kind kind) const;
    QList<Symbol> symbols(const QString &fileName, const Symbol::Kind kind) const;
    void match(ClangSymbolSearcher *searcher) const;

    Indexer *m_q;
    QVector<QHash<QString, FileData> > m_files;
    Index m_index;
    bool m_hasQueuedFullRun;
    QSet<QString> m_queuedFilesRun;
    QString m_storagePath;
    bool m_isLoaded;
//    DependencyGraph m_dependencyGraph;
    QScopedPointer<QFutureWatcher<void> >m_loadingWatcher;
    QScopedPointer<QFutureWatcher<void> >m_indexingWatcher;
    QThreadPool m_indexingPool;
    QSet<LibClangIndexer *> m_runningIndexers;
};

} // ClangCodeModel

Q_DECLARE_METATYPE(IndexingResult)

namespace {

struct ScopepTimer
{
    ScopepTimer(int id = 0) : m_id(id) { m_t.start(); }
    ~ScopepTimer() { qDebug() << "\t#Timer" << m_id << ":" << m_t.elapsed() << "ms"; }
    int m_id;
    QTime m_t;
};

} // Anonymous

namespace ClangCodeModel {

class LibClangIndexer: public QRunnable
{
protected:
    typedef CppTools::ProjectPart ProjectPart;

public:
    LibClangIndexer(IndexerPrivate *indexer)
        : m_indexer(indexer)
        , m_isCanceled(false)
    {}

    virtual ~LibClangIndexer()
    {}

    void cancel()
    { m_isCanceled = true; }

protected:
    void propagateResults(const ProjectPart::Ptr &projectPart)
    {
        if (!isCanceled()) {
            QVector<IndexingResult> indexingResults;
            indexingResults.reserve(m_allFiles.size());

            foreach (const QString &fn, m_allFiles.keys()) {
247
                QVector<Symbol> symbols; unfoldSymbols(symbols, fn);
248
                QSet<QString> processedFiles = QSet<QString>::fromList(m_allFiles.keys());
249
                Unit::Ptr unit = Unit::create(fn);
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
                IndexingResult indexingResult(symbols, processedFiles, unit, projectPart);
                indexingResults.append(indexingResult);

                // TODO: includes need to be propagated to the dependency table.
            }
            m_indexer->synchronize(indexingResults);
        }

        qDeleteAll(m_allFiles.values());
        m_allFiles.clear();
        qDeleteAll(m_allSymbols);
        m_allSymbols.clear();
    }

protected:
    static inline LibClangIndexer *indexer(CXClientData d)
    { return static_cast<LibClangIndexer *>(d); }

    static int abortQuery(CXClientData client_data, void *reserved) {
        Q_UNUSED(reserved);

        return indexer(client_data)->isCanceled();
    }

    static void diagnostic(CXClientData client_data, CXDiagnosticSet diagSet, void *reserved) {
        Q_UNUSED(client_data);
        Q_UNUSED(diagSet);
        Q_UNUSED(reserved);
    }

    static CXIdxClientFile enteredMainFile(CXClientData client_data, CXFile file, void *reserved) {
        Q_UNUSED(client_data);
        Q_UNUSED(reserved);

        const QString fileName = getQString(clang_getFileName(file));
//        qDebug() << "enteredMainFile:" << fileName;
        LibClangIndexer *lci = indexer(client_data);
        File *f = lci->file(fileName);
        f->setMainFile();

        return f;
    }

    static CXIdxClientFile includedFile(CXClientData client_data, const CXIdxIncludedFileInfo *info) {
        Q_UNUSED(client_data);

        File *includingFile = 0;
        clang_indexLoc_getFileLocation(info->hashLoc, reinterpret_cast<CXIdxClientFile*>(&includingFile), 0, 0, 0, 0);

        const QString fileName = getQString(clang_getFileName(info->file));
        File *f = indexer(client_data)->file(fileName);

        if (includingFile)
            includingFile->addInclude(f);

        return f;
    }

    static CXIdxClientFile importedASTFile(CXClientData client_data, const CXIdxImportedASTFileInfo *info) {
        const QString fileName = getQString(clang_getFileName(info->file));

//        qDebug() << "importedASTFile:" << fileName;

        indexer(client_data)->m_importedASTs.insert(fileName, false);

        return info->file;
    }

    static CXIdxClientContainer startedTranslationUnit(CXClientData client_data, void *reserved) {
        Q_UNUSED(client_data);
        Q_UNUSED(reserved);

//        qDebug() << "startedTranslationUnit";
        return 0;
    }

    static void indexDeclaration(CXClientData client_data, const CXIdxDeclInfo *info) {
        LibClangIndexer *lci = indexer(client_data);

        File *includingFile = 0;
        unsigned line = 0, column = 0, offset = 0;
        clang_indexLoc_getFileLocation(info->loc, reinterpret_cast<CXIdxClientFile*>(&includingFile), 0, &line, &column, &offset);

        QString kind = getQString(clang_getCursorKindSpelling(info->cursor.kind));
        QString displayName = getQString(clang_getCursorDisplayName(info->cursor));
        QString spellingName = getQString(clang_getCursorSpelling(info->cursor));
//        qDebug() << (includingFile ? includingFile->name() : QLatin1String("<UNKNOWN FILE>")) << ":"<<line<<":"<<column<<": display name ="<<displayName<<"spelling name ="<<spellingName<<"of kind"<<kind;

        Symbol *sym = lci->newSymbol(info->cursor.kind, displayName, spellingName, includingFile, line, column, offset);

        // TODO: add to decl container...
        if (includingFile) // TODO: check why includingFile can be null...
            includingFile->addSymbol(sym);

        if (const CXIdxContainerInfo *semanticContainer = info->semanticContainer) {
            if (Symbol *container = static_cast<Symbol *>(clang_index_getClientContainer(semanticContainer))) {
                sym->semanticContainer = container;
                container->addSymbol(sym);
            }
        }

        // TODO: ObjC containers
        // TODO: index forward decls too?

        if (info->declAsContainer)
            clang_index_setClientContainer(info->declAsContainer, sym);
    }

    static void indexEntityReference(CXClientData client_data, const CXIdxEntityRefInfo *info) {
        Q_UNUSED(client_data);
        Q_UNUSED(info);

        // TODO: well, we do get the info, so why not (optionally?) remember all references?
    }

protected:
    struct File;
    struct Symbol;

    typedef QHash<QString, File *> FilesByName;
    struct File
    {
        File(const QString &fileName)
            : m_fileName(fileName)
        {}

        void addInclude(File *f)
        {
378
//            assert(f);
379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395
            m_includes.insert(f->name(), f);
        }

        QList<File *> includes() const
        { return m_includes.values(); }

        QString name() const
        { return m_fileName; }

        void setMainFile(bool isMainFile = true)
        { m_isMainFile = isMainFile; }

        bool isMainFile() const
        { return m_isMainFile; }

        void addSymbol(Symbol *symbol)
        {
396
//            assert(symbol);
397 398 399 400 401 402 403 404 405 406 407 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 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 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489
            m_symbols.append(symbol);
        }

        QVector<Symbol *> symbols() const
        { return m_symbols; }

    private:
        QString m_fileName;
        FilesByName m_includes;
        bool m_isMainFile;
        QVector<Symbol *> m_symbols;
    };

    struct Symbol
    {
        Symbol(enum CXCursorKind kind, const QString &displayName, const QString &spellingName, File *file, unsigned line, unsigned column, unsigned offset)
            : kind(kind)
            , displayName(displayName)
            , spellingName(spellingName)
            , file(file)
            , line(line)
            , column(column)
            , offset(offset)
            , semanticContainer(0)
        {}

        QString spellKind() const
        { return getQString(clang_getCursorKindSpelling(kind)); }

        void addSymbol(Symbol *symbol)
        { symbols.append(symbol); }

        enum CXCursorKind kind;
        QString displayName, spellingName;
        File *file;
        unsigned line, column, offset;
        Symbol *semanticContainer;
        QVector<Symbol *> symbols;
    };

protected:
    bool isCanceled() const
    { return m_isCanceled; }

    void finish()
    { m_indexer->finished(this); }

    File *file(const QString &fileName)
    {
        File *f = m_allFiles[fileName];
        if (!f) {
            f = new File(fileName);
            m_allFiles.insert(fileName, f);
        }
        return f;
    }

    Symbol *newSymbol(enum CXCursorKind kind, const QString &displayName, const QString &spellingName, File *file, unsigned line, unsigned column, unsigned offset)
    {
        Symbol *s = new Symbol(kind, displayName, spellingName, file, line, column, offset);
        m_allSymbols.append(s);
        return s;
    }

    void dumpInfo()
    {
        qDebug() << "=== indexing info dump ===";
        qDebug() << "indexed" << m_allFiles.size() << "files. Main files:";
        foreach (const File *f, m_allFiles) {
            if (!f->isMainFile())
                continue;
            qDebug() << f->name() << ":";
            foreach (const File *inc, f->includes())
                qDebug() << "  includes" << inc->name();
            dumpSymbols(f->symbols(), QByteArray("  "));
        }

        qDebug() << "=== end of dump ===";
    }

    void dumpSymbols(const QVector<Symbol *> &symbols, const QByteArray &indent)
    {
        if (symbols.isEmpty())
            return;

        qDebug("%scontained symbols:", indent.constData());
        QByteArray newIndent = indent + "  ";
        foreach (const Symbol *s, symbols) {
            qDebug("%s%s (%s)", newIndent.constData(), s->spellingName.toUtf8().constData(), s->spellKind().toUtf8().constData());
            dumpSymbols(s->symbols, newIndent);
        }
    }

490
    void unfoldSymbols(QVector<Symbol> &result, const QString &fileName) {
491 492 493 494 495 496
        const QVector<Symbol *> symbolsForFile = file(fileName)->symbols();
        foreach (const Symbol *s, symbolsForFile) {
            unfoldSymbols(s, result);
        }
    }

497
    void unfoldSymbols(const Symbol *s, QVector<Symbol> &result) {
498 499 500
        if (!s->file)
            return;

501
        Symbol sym;
502 503 504 505 506 507 508 509 510 511
        sym.m_name = s->spellingName;
        sym.m_qualification = s->spellingName;

        static QLatin1String sep("::");
        for (Symbol *parent = s->semanticContainer; parent; parent = parent->semanticContainer)
            sym.m_qualification = parent->spellingName + sep + sym.m_qualification;

        sym.m_location = SourceLocation(s->file->name(), s->line, s->column, s->offset);

        switch (s->kind) {
512
        case CXCursor_EnumDecl: sym.m_kind = Symbol::Enum; break;
513
        case CXCursor_StructDecl:
514 515
        case CXCursor_ClassDecl: sym.m_kind = Symbol::Class; break;
        case CXCursor_CXXMethod: sym.m_kind = Symbol::Method; break;
516
        case CXCursor_FunctionTemplate:
517 518 519 520 521
        case CXCursor_FunctionDecl: sym.m_kind = Symbol::Function; break;
        case CXCursor_DeclStmt: sym.m_kind = Symbol::Declaration; break;
        case CXCursor_Constructor: sym.m_kind = Symbol::Constructor; break;
        case CXCursor_Destructor: sym.m_kind = Symbol::Destructor; break;
        default: sym.m_kind = Symbol::Unknown; break;
522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576
        }

        result.append(sym);
    }

protected:
    static IndexerCallbacks IndexCB;

protected:
    IndexerPrivate *m_indexer;
    bool m_isCanceled;
    QHash<QString, bool> m_importedASTs;
    FilesByName  m_allFiles;
    QVector<Symbol *> m_allSymbols;
};

IndexerCallbacks LibClangIndexer::IndexCB = {
    abortQuery,
    diagnostic,
    enteredMainFile,
    includedFile,
    importedASTFile,
    startedTranslationUnit,
    indexDeclaration,
    indexEntityReference
};

class ProjectPartIndexer: public LibClangIndexer
{
public:
    ProjectPartIndexer(IndexerPrivate *indexer, const QList<IndexerPrivate::FileData> &todo)
        : LibClangIndexer(indexer)
        , m_todo(todo)
    {}

    void run()
    {
        if (isCanceled() || m_todo.isEmpty()) {
            finish();
            return;
        }

        const ProjectPart::Ptr &pPart = m_todo[0].m_projectPart;

restart:
        CXIndex idx;
        if (!(idx = clang_createIndex(/* excludeDeclsFromPCH */ 1,
                                      /* displayDiagnosics=*/1))) {
          qDebug() << "Could not create Index";
          return;
        }

        CXIndexAction idxAction = clang_IndexAction_create(idx);
        const unsigned index_opts = CXIndexOpt_SuppressWarnings;

hjk's avatar
hjk committed
577
        PchManager *pchManager = PchManager::instance();
578 579 580 581 582 583 584 585 586 587 588 589 590
        PchInfo::Ptr pchInfo = pchManager->pchInfo(pPart);

        for (int i = 0, ei = m_todo.size(); i < ei; ++i) {
            const IndexerPrivate::FileData &fd = m_todo.at(i);
            if (fd.m_upToDate)
                continue;

            if (pchManager->pchInfo(pPart) != pchInfo) {
                clang_IndexAction_dispose(idxAction);
                clang_disposeIndex(idx);
                goto restart;
            }

591
            QStringList opts = Utils::createClangOptions(pPart, fd.m_fileName);
592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644
            if (!pchInfo.isNull())
                opts.append(Utils::createPCHInclusionOptions(pchInfo->fileName()));

            ScopedClangOptions scopedOpts(opts);
            QByteArray fileName = fd.m_fileName.toUtf8();

//            qDebug() << "Indexing file" << fd.m_fileName << "with options" << opts;
            unsigned parsingOptions = fd.m_managementOptions;
            parsingOptions |= CXTranslationUnit_SkipFunctionBodies;

            /*int result =*/ clang_indexSourceFile(idxAction, this,
                                                   &IndexCB, sizeof(IndexCB),
                                                   index_opts, fileName.constData(),
                                                   scopedOpts.data(), scopedOpts.size(), 0, 0, 0,
                                                   parsingOptions);

            // index imported ASTs:
            foreach (const QString &astFile, m_importedASTs.keys()) {
                if (m_importedASTs.value(astFile))
                    continue;

                if (CXTranslationUnit TU = clang_createTranslationUnit(
                            idx, astFile.toUtf8().constData())) {
                    /*result =*/ clang_indexTranslationUnit(idxAction, this,
                                                            &IndexCB,
                                                            sizeof(IndexCB),
                                                            index_opts, TU);
                    clang_disposeTranslationUnit(TU);
                }

                m_importedASTs[astFile] = true;
            }

            propagateResults(fd.m_projectPart);
            if (isCanceled())
                break;
        }

//        dumpInfo();

        clang_IndexAction_dispose(idxAction);
        clang_disposeIndex(idx);

        finish();
    }

private:
    QList<IndexerPrivate::FileData> m_todo;
};

class QuickIndexer: public LibClangIndexer
{
public:
645
    QuickIndexer(IndexerPrivate *indexer, const Unit::Ptr &unit, const ProjectPart::Ptr&projectPart)
646 647 648 649 650 651 652
        : LibClangIndexer(indexer)
        , m_unit(unit)
        , m_projectPart(projectPart)
    {}

    void run()
    {
653
        if (isCanceled() || !m_unit->isLoaded()) {
654 655 656 657
            finish();
            return;
        }

658
        CXIndexAction idxAction = clang_IndexAction_create(m_unit->clangIndex());
659 660 661 662 663 664
        const unsigned index_opts = CXIndexOpt_SuppressWarnings;

//        qDebug() << "Indexing TU" << m_unit.fileName() << "...";
        /*int result =*/ clang_indexTranslationUnit(idxAction, this,
                                                    &IndexCB, sizeof(IndexCB),
                                                    index_opts,
665
                                                    m_unit->clangTranslationUnit());
666 667 668 669 670 671 672 673

        propagateResults(m_projectPart);

        clang_IndexAction_dispose(idxAction);
        finish();
    }

private:
674
    Unit::Ptr m_unit;
675 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 702 703
    ProjectPart::Ptr m_projectPart;
};

} // ClangCodeModel

IndexerPrivate::IndexerPrivate(Indexer *indexer)
    : m_mutex(QMutex::Recursive)
    , m_q(indexer)
    , m_files(TotalFileTypes)
    , m_hasQueuedFullRun(false)
    , m_isLoaded(false)
    , m_loadingWatcher(new QFutureWatcher<void>)
    , m_indexingWatcher(new QFutureWatcher<void>)
{
//    const int magicThreadCount = QThread::idealThreadCount() * 4 / 3;
    const int magicThreadCount = QThread::idealThreadCount() - 1;
    m_indexingPool.setMaxThreadCount(std::max(magicThreadCount, 1));
    m_indexingPool.setExpiryTimeout(1000);
}

void IndexerPrivate::runCore(const QHash<QString, FileData> & /*headers*/,
                             const QHash<QString, FileData> &impls,
                             IndexingMode /*mode*/)
{
    QMutexLocker locker(&m_mutex);

    typedef QHash<QString, FileData>::const_iterator FileContIt;
    QHash<ProjectPart::Ptr, QList<IndexerPrivate::FileData> > parts;
    typedef QHash<ProjectPart::Ptr, QList<IndexerPrivate::FileData> >::Iterator PartIter;
704

hjk's avatar
hjk committed
705
    QList<Core::IDocument *> docs = Core::DocumentModel::openedDocuments();
706 707
    QSet<QString> openDocs;
    foreach (Core::IDocument *doc, docs)
708
        openDocs.insert(doc->filePath().toString());
709 710

    for (FileContIt tit = impls.begin(), eit = impls.end(); tit != eit; ++tit) {
711
        if (!tit->m_upToDate && openDocs.contains(tit.key())) {
712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 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 816 817 818 819 820 821 822 823 824 825 826 827
            const IndexerPrivate::FileData &fd = tit.value();
            parts[fd.m_projectPart].append(fd);
        }
    }

    if (parts.isEmpty())
        return;

    for (PartIter i = parts.begin(), ei = parts.end(); i != ei; ++i) {
        ProjectPartIndexer *ppi = new ProjectPartIndexer(this, i.value());
        m_runningIndexers.insert(ppi);
        m_indexingPool.start(ppi);
    }

    QFuture<void> task = QtConcurrent::run(&IndexerPrivate::watchIndexingThreads, this);
    m_indexingWatcher->setFuture(task);
    emit m_q->indexingStarted(task);
}

void IndexerPrivate::watchIndexingThreads(QFutureInterface<void> &future)
{
    int maxTodo = runningIndexerCount();
    future.setProgressRange(0, maxTodo);

    int todo = -1;
    while (todo) {
        int newTodo = runningIndexerCount();
        if (todo != newTodo)
            future.setProgressValue(maxTodo - newTodo);
        todo = newTodo;
        if (future.isCanceled()) {
            cancelIndexing();
            return;
        }
        m_indexingPool.waitForDone(500);
    }
}

void IndexerPrivate::run()
{
    Q_ASSERT(m_isLoaded);

    QMutexLocker locker(&m_mutex);

    if (m_runningIndexers.isEmpty()) {
        runCore(m_files.value(HeaderFile),
                m_files.value(ImplementationFile),
                RelaxedIndexing);
    } else {
        m_hasQueuedFullRun = true;
        cancelIndexing();
    }
}

void IndexerPrivate::run(const QStringList &fileNames)
{
    Q_ASSERT(m_isLoaded);
    QMutexLocker locker(&m_mutex);

    if (noIndexersRunning()) {
        QVector<QHash<QString, FileData> > files(TotalFileTypes);
        foreach (const QString &fileName, fileNames) {
            FileType type = identifyFileType(fileName);
            if (!isTrackingFile(fileName, type)) {
                // @TODO
                continue;
            }

            FileData *data = &m_files[type][fileName];
            data->m_upToDate = false;
            files[type].insert(fileName, *data);
            m_index.removeFile(fileName);
        }
        runCore(files.value(HeaderFile),
                files.value(ImplementationFile),
                ConstrainedIndexing);
    } else {
        m_queuedFilesRun.unite(fileNames.toSet());
    }
}

bool IndexerPrivate::isBusy() const
{
    return !noIndexersRunning() || m_loadingWatcher->isRunning();
}

void IndexerPrivate::cancel(bool wait)
{
//    m_dependencyGraph.discard();

    m_loadingWatcher->cancel();
    cancelIndexing();
    if (wait) {
        m_loadingWatcher->waitForFinished();
        m_indexingWatcher->waitForFinished();
        while (!noIndexersRunning())
            m_indexingPool.waitForDone(100);
    }
}

void IndexerPrivate::reset()
{
    cancel(true);
    serializeSymbols();

    for (int i = 0; i < TotalFileTypes; ++i)
        m_files[i].clear();
    m_hasQueuedFullRun = false;
    m_queuedFilesRun.clear();
    m_storagePath.clear();
    m_index.clear();
    m_isLoaded = false;
}

void IndexerPrivate::synchronize(const QVector<IndexingResult> &results)
{
828 829 830
    Q_UNUSED(results);
#if 0
    foreach (const IndexingResult &result, results) {
831 832 833 834 835 836 837 838
        QMutexLocker locker(&m_mutex);

        foreach (const Symbol &symbol, result.m_symbolsInfo) {
            addOrUpdateFileData(symbol.m_location.fileName(),
                                result.m_projectPart,
                                true);

            // Make the symbol available in the database.
839
            m_index.insertSymbol(symbol, result.m_unit->timeStamp());
840 841 842 843
        }

        // There might be files which were processed but did not "generate" any indexable symbol,
        // but we still need to make the index aware of them.
844
        result.m_processedFiles.insert(result.m_unit->fileName());
845 846 847 848 849 850 851 852 853
        foreach (const QString &fileName, result.m_processedFiles) {
            if (!m_index.containsFile(fileName))
                m_index.insertFile(fileName, result.m_unit.timeStamp());
        }

        // If this unit is being kept alive, update in the manager.
        if (LiveUnitsManager::instance()->isTracking(result.m_unit.fileName()))
            LiveUnitsManager::instance()->updateUnit(result.m_unit.fileName(), result.m_unit);
    }
854
#endif
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 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078
}

void IndexerPrivate::finished(LibClangIndexer *indexer)
{
    QMutexLocker locker(&m_mutex);

    m_runningIndexers.remove(indexer);
    if (noIndexersRunning())
        indexingFinished();
}

bool IndexerPrivate::noIndexersRunning() const
{
    QMutexLocker locker(&m_mutex);

    return m_runningIndexers.isEmpty();
}

void IndexerPrivate::indexingFinished()
{
    if (m_hasQueuedFullRun) {
        m_hasQueuedFullRun = false;
        run();
    } else if (!m_queuedFilesRun.isEmpty()) {
        const QStringList &files = m_queuedFilesRun.toList();
        m_queuedFilesRun.clear();
        run(files);
    }

    emit m_q->indexingFinished();
}

void IndexerPrivate::cancelIndexing()
{
    QMutexLocker locker(&m_mutex);

    foreach (LibClangIndexer* partIndexer, m_runningIndexers) {
        partIndexer->cancel();
    }
}

int IndexerPrivate::runningIndexerCount() const
{
    QMutexLocker locker(&m_mutex);
    return m_runningIndexers.size();
}

void IndexerPrivate::addOrUpdateFileData(const QString &fileName,
                                         ProjectPart::Ptr projectPart,
                                         bool upToDate)
{
    Q_ASSERT(QDir::isAbsolutePath(fileName));

    QString cleanFileName(normalizeFileName(fileName));

    FileType fileType = identifyFileType(cleanFileName);
    if (isTrackingFile(cleanFileName, fileType)) {
        m_files[fileType][cleanFileName].m_projectPart = projectPart;
        m_files[fileType][cleanFileName].m_upToDate = upToDate;
    } else {
        m_files[fileType].insert(cleanFileName,
                                 FileData(cleanFileName, projectPart, upToDate));
    }

    if (!upToDate)
        m_index.removeFile(cleanFileName);
}

bool IndexerPrivate::addFile(const QString &fileName,
                             ProjectPart::Ptr projectPart)
{
    if (isBusy()
            || fileName.trimmed().isEmpty()
            || !QFileInfo(fileName).isFile())
        return false;

    addOrUpdateFileData(fileName, projectPart, false);

    return true;
}

QStringList IndexerPrivate::allFiles() const
{
    QStringList all;
    populateFileNames(&all, m_files.at(ImplementationFile).values());
    populateFileNames(&all, m_files.at(HeaderFile).values());
    return all;
}

bool IndexerPrivate::isTrackingFile(const QString &fileName, FileType type) const
{
    return m_files.value(type).contains(normalizeFileName(fileName));
}

QStringList IndexerPrivate::compilationOptions(const QString &fileName) const
{
    FileType type = identifyFileType(fileName);
    return Utils::createClangOptions(m_files.value(type).value(normalizeFileName(fileName)).m_projectPart);
}

IndexerPrivate::FileType IndexerPrivate::identifyFileType(const QString &fileName)
{
    const QString fn = fileName.toLower();
    if (fn.endsWith(QLatin1String(".cpp"))
            || fn.endsWith(QLatin1String(".cxx"))
            || fn.endsWith(QLatin1String(".cc"))
            || fn.endsWith(QLatin1String(".c"))
            || fn.endsWith(QLatin1String(".m"))
            || fn.endsWith(QLatin1String(".mm"))) {
        return ImplementationFile;
    }

    // Everything that is not an implementation file is treated as a header. This makes things
    // easier when handling standard library files and any other file that does not use
    // conventional suffixes.
    return HeaderFile;
}

void IndexerPrivate::populateFileNames(QStringList *all, const QList<FileData> &data)
{
    foreach (const FileData &fileData, data)
        all->append(fileData.m_fileName);
}


namespace {

struct DepedencyVisitor
{
    DepedencyVisitor(IndexerPrivate *indexer) : m_indexer(indexer) {}

    bool acceptFile(const QString &includer)
    {
        IndexerPrivate::FileType fileType = IndexerPrivate::identifyFileType(includer);
        if (m_indexer->isTrackingFile(includer, fileType)) {
            m_match = m_indexer->m_files.at(fileType).value(includer);
            return true;
        }
        return false;
    }

    IndexerPrivate *m_indexer;
    IndexerPrivate::FileData m_match;
};

} // Anonymous

void IndexerPrivate::startLoading()
{
    // In the case of existent persisted symbols, we restore them and make them visible
    // to the indexer. However, we need a dependency graph in order to identify the proper
    // options.

    if (deserealizeSymbols() && !m_index.isEmpty())
        computeDependencyGraph();
    else
        concludeLoading();
}

void IndexerPrivate::concludeLoading()
{
    m_isLoaded = true;
    run();
}

void IndexerPrivate::computeDependencyGraph()
{
    // FIXME
//    for (int fileType = ImplementationFile; fileType < TotalFileTypes; ++fileType) {
//        QHash<QString, FileData>::iterator it = m_files[fileType].begin();
//        for (; it != m_files[fileType].end(); ++it)
//            m_dependencyGraph.addFile(it.value().m_fileName, it.value().m_compilationOptions);
//    }

    m_loadingWatcher.reset(new QFutureWatcher<void>);
    connect(m_loadingWatcher.data(), SIGNAL(finished()), this, SLOT(dependencyGraphComputed()));
//    m_loadingWatcher->setFuture(m_dependencyGraph.compute());
}

void IndexerPrivate::dependencyGraphComputed()
{
    if (m_loadingWatcher->isCanceled())
        return;

    m_loadingWatcher.reset(new QFutureWatcher<void>);
    connect(m_loadingWatcher.data(), SIGNAL(finished()), this, SLOT(restoredSymbolsAnalysed()));
    m_loadingWatcher->setFuture(QtConcurrent::run(this, &IndexerPrivate::analyzeRestoredSymbols));
}

void IndexerPrivate::analyzeRestoredSymbols()
{
    // @TODO: We only check for time stamps, so we still need to handle somehow the case in
    // which the project options (for example a .pro file) changed while "outside" a Creator
    // session.

    foreach (const QString &fileName, m_index.files()) {
        bool upToDate = m_index.validate(fileName);

        FileType fileType = identifyFileType(fileName);
        if (isTrackingFile(fileName, fileType)) {
            // When the file is already being tracked we simply need to update its state.
            if (upToDate)
                m_files[fileType][fileName].m_upToDate = true;
        } else {
            // If it's not being tracked we need to find at least one tracked dependency
            // so we can use its options.
            DepedencyVisitor visitor(this);
//            m_dependencyGraph.collectDependencies(fileName,
//                                                  DependencyGraph::FilesWhichInclude,
//                                                  &visitor);
            if (!visitor.m_match.m_fileName.isEmpty()) {
                addOrUpdateFileData(fileName,
                                    visitor.m_match.m_projectPart,
                                    upToDate);
            } else {
                m_index.removeFile(fileName);
            }
        }

        if (!upToDate && m_index.containsFile(fileName))
            m_index.removeFile(fileName);
    }
}

1079
void IndexerPrivate::runQuickIndexing(const Unit::Ptr &unit, const CppTools::ProjectPart::Ptr &part)
1080 1081 1082
{
    QMutexLocker locker(&m_mutex);

1083
    addOrUpdateFileData(unit->fileName(), part, false);
1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272

    QuickIndexer indexer(this, unit, part);
    indexer.run();
}

void IndexerPrivate::restoredSymbolsAnalysed()
{
    if (m_loadingWatcher->isCanceled())
        return;

    concludeLoading();
}

bool IndexerPrivate::deserealizeSymbols()
{
    if (m_storagePath.isEmpty())
        return false;

    ::Utils::FileReader reader;
    if (reader.fetch(m_storagePath)) {
        m_index.deserialize(reader.data());
        return true;
    }

    return false;
}

void IndexerPrivate::serializeSymbols() const
{
    if (m_storagePath.isEmpty())
        return;

    ::Utils::FileSaver saver(m_storagePath);
    saver.write(m_index.serialize());
    if (!saver.finalize())
        qWarning("Failed to serialize index");
}

QList<Symbol> IndexerPrivate::symbols(Symbol::Kind kind) const
{
    if (m_loadingWatcher->isRunning())
        return QList<Symbol>();

    return m_index.symbols(kind);
}

QList<Symbol> IndexerPrivate::symbols(const QString &fileName, const Symbol::Kind kind) const
{
    if (m_loadingWatcher->isRunning())
        return QList<Symbol>();

    if (kind == Symbol::Unknown)
        return m_index.symbols(fileName);

    return m_index.symbols(fileName, kind);
}

void IndexerPrivate::match(ClangSymbolSearcher *searcher) const
{
    if (m_loadingWatcher->isRunning())
        return;

    m_index.match(searcher);
}

Indexer::Indexer(QObject *parent)
    : QObject(parent)
    , m_d(new IndexerPrivate(this))
{}

Indexer::~Indexer()
{}

void Indexer::regenerate()
{
    if (!m_d->m_isLoaded) {
        if (m_d->m_loadingWatcher->isRunning())
            return;
        m_d->startLoading();
    } else {
        m_d->run();
    }
}

void Indexer::initialize(const QString &storagePath)
{
    Q_ASSERT(!m_d->m_isLoaded);

    m_d->m_storagePath = storagePath;
}

void Indexer::evaluateFile(const QString &fileName)
{
    if (!m_d->m_isLoaded)
        return;

    m_d->run(QStringList(normalizeFileName(fileName)));
}

bool Indexer::isBusy() const
{
    return m_d->isBusy();
}

void Indexer::cancel(bool waitForFinished)
{
    return m_d->cancel(waitForFinished);
}

void Indexer::finalize()
{
    m_d->reset();
}

bool Indexer::addFile(const QString &fileName, ProjectPart::Ptr projectPart)
{
    return m_d->addFile(fileName, projectPart);
}

QStringList Indexer::allFiles() const
{
    return m_d->allFiles();
}

QStringList Indexer::compilationOptions(const QString &fileName) const
{
    return m_d->compilationOptions(fileName);
}

QList<Symbol> Indexer::allFunctions() const
{
    return m_d->symbols(Symbol::Function);
}

QList<Symbol> Indexer::allClasses() const
{
    return m_d->symbols(Symbol::Class);
}

QList<Symbol> Indexer::allMethods() const
{
    return m_d->symbols(Symbol::Method);
}

QList<Symbol> Indexer::allConstructors() const
{
    return m_d->symbols(Symbol::Constructor);
}

QList<Symbol> Indexer::allDestructors() const
{
    return m_d->symbols(Symbol::Destructor);
}

QList<Symbol> Indexer::functionsFromFile(const QString &fileName) const
{
    return m_d->symbols(fileName, Symbol::Function);
}

QList<Symbol> Indexer::classesFromFile(const QString &fileName) const
{
    return m_d->symbols(fileName, Symbol::Class);
}

QList<Symbol> Indexer::methodsFromFile(const QString &fileName) const
{
    return m_d->symbols(fileName, Symbol::Method);
}

QList<Symbol> Indexer::constructorsFromFile(const QString &fileName) const
{
    return m_d->symbols(fileName, Symbol::Constructor);
}

QList<Symbol> Indexer::destructorsFromFile(const QString &fileName) const
{
    return m_d->symbols(fileName, Symbol::Destructor);
}

QList<Symbol> Indexer::allFromFile(const QString &fileName) const
{
    return m_d->symbols(fileName, Symbol::Unknown);
}

void Indexer::match(ClangSymbolSearcher *searcher) const
{
    m_d->match(searcher);
}

1273
void Indexer::runQuickIndexing(Unit::Ptr unit, const CppTools::ProjectPart::Ptr &part)
1274 1275 1276 1277
{
    m_d->runQuickIndexing(unit, part);
}

1278 1279 1280 1281 1282 1283
bool Indexer::isTracking(const QString &fileName) const
{
    return m_d->isTrackingFile(fileName, IndexerPrivate::ImplementationFile)
            || m_d->isTrackingFile(fileName, IndexerPrivate::HeaderFile);
}

1284
#include "indexer.moc"