clangeditordocumentprocessor.cpp 12.4 KB
Newer Older
1 2
/****************************************************************************
**
Eike Ziller's avatar
Eike Ziller committed
3 4
** Copyright (C) 2015 The Qt Company Ltd.
** Contact: http://www.qt.io/licensing
5 6 7 8 9 10 11
**
** 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
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
Tobias Hunger's avatar
Tobias Hunger committed
14
** 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
Tobias Hunger's avatar
Tobias Hunger 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
**
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
27 28 29 30 31 32
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/

#include "clangeditordocumentprocessor.h"

33
#include "clangbackendipcintegration.h"
34 35
#include "clangfixitoperation.h"
#include "clangfixitoperationsextractor.h"
36
#include "clanghighlightingmarksreporter.h"
37
#include "clangutils.h"
38

Marco Bubke's avatar
Marco Bubke committed
39 40 41
#include <diagnosticcontainer.h>
#include <sourcelocationcontainer.h>

42
#include <cpptools/cppcodemodelsettings.h>
43
#include <cpptools/cppmodelmanager.h>
44
#include <cpptools/cppprojects.h>
Marco Bubke's avatar
Marco Bubke committed
45
#include <cpptools/cpptoolsbridge.h>
46
#include <cpptools/cpptoolsreuse.h>
47 48
#include <cpptools/cppworkingcopy.h>

49
#include <texteditor/convenience.h>
50
#include <texteditor/fontsettings.h>
Marco Bubke's avatar
Marco Bubke committed
51
#include <texteditor/texteditor.h>
52 53
#include <texteditor/texteditorconstants.h>
#include <texteditor/texteditorsettings.h>
Marco Bubke's avatar
Marco Bubke committed
54

55 56 57 58 59
#include <cplusplus/CppDocument.h>

#include <utils/qtcassert.h>
#include <utils/QtConcurrentTools>

Marco Bubke's avatar
Marco Bubke committed
60 61
#include <QTextBlock>

62
namespace ClangCodeModel {
63
namespace Internal {
64

65
ClangEditorDocumentProcessor::ClangEditorDocumentProcessor(
66
        IpcCommunicator &ipcCommunicator,
67
        TextEditor::TextDocument *document)
68
    : BaseEditorDocumentProcessor(document->document(), document->filePath().toString())
69
    , m_diagnosticManager(document)
70
    , m_ipcCommunicator(ipcCommunicator)
71
    , m_parser(new ClangEditorDocumentParser(document->filePath().toString()))
72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87
    , m_parserRevision(0)
    , m_semanticHighlighter(document)
    , m_builtinProcessor(document, /*enableSemanticHighlighter=*/ false)
{
    // Forwarding the semantic info from the builtin processor enables us to provide all
    // editor (widget) related features that are not yet implemented by the clang plugin.
    connect(&m_builtinProcessor, &CppTools::BuiltinEditorDocumentProcessor::cppDocumentUpdated,
            this, &ClangEditorDocumentProcessor::cppDocumentUpdated);
    connect(&m_builtinProcessor, &CppTools::BuiltinEditorDocumentProcessor::semanticInfoUpdated,
            this, &ClangEditorDocumentProcessor::semanticInfoUpdated);
}

ClangEditorDocumentProcessor::~ClangEditorDocumentProcessor()
{
    m_parserWatcher.cancel();
    m_parserWatcher.waitForFinished();
88

89
    if (m_projectPart) {
90
        m_ipcCommunicator.unregisterTranslationUnitsForEditor(
91 92
            {ClangBackEnd::FileContainer(filePath(), m_projectPart->id())});
    }
93 94 95 96
}

void ClangEditorDocumentProcessor::run()
{
97
    updateTranslationUnitIfProjectPartExists();
Marco Bubke's avatar
Marco Bubke committed
98

99 100 101 102 103 104 105 106 107
    // Run clang parser
    disconnect(&m_parserWatcher, &QFutureWatcher<void>::finished,
               this, &ClangEditorDocumentProcessor::onParserFinished);
    m_parserWatcher.cancel();
    m_parserWatcher.setFuture(QFuture<void>());

    m_parserRevision = revision();
    connect(&m_parserWatcher, &QFutureWatcher<void>::finished,
            this, &ClangEditorDocumentProcessor::onParserFinished);
108 109
    const CppTools::WorkingCopy workingCopy = CppTools::CppModelManager::instance()->workingCopy();
    const QFuture<void> future = QtConcurrent::run(&runParser, parser(), workingCopy);
110 111 112 113 114 115
    m_parserWatcher.setFuture(future);

    // Run builtin processor
    m_builtinProcessor.run();
}

116
void ClangEditorDocumentProcessor::recalculateSemanticInfoDetached(bool force)
117
{
118
    m_builtinProcessor.recalculateSemanticInfoDetached(force);
119 120
}

121 122 123
void ClangEditorDocumentProcessor::semanticRehighlight()
{
    m_semanticHighlighter.updateFormatMapFromFontSettings();
124 125 126

    if (m_projectPart)
        requestDocumentAnnotations(m_projectPart->id());
127 128
}

129 130 131 132 133
CppTools::SemanticInfo ClangEditorDocumentProcessor::recalculateSemanticInfo()
{
    return m_builtinProcessor.recalculateSemanticInfo();
}

134
CppTools::BaseEditorDocumentParser::Ptr ClangEditorDocumentProcessor::parser()
135
{
136
    return m_parser;
137 138
}

139 140 141 142 143
CPlusPlus::Snapshot ClangEditorDocumentProcessor::snapshot()
{
   return m_builtinProcessor.snapshot();
}

144 145 146 147 148
bool ClangEditorDocumentProcessor::isParserRunning() const
{
    return m_parserWatcher.isRunning();
}

149 150 151 152 153
bool ClangEditorDocumentProcessor::hasProjectPart() const
{
    return m_projectPart;
}

154 155 156 157 158
CppTools::ProjectPart::Ptr ClangEditorDocumentProcessor::projectPart() const
{
    return m_projectPart;
}

159 160 161 162 163
void ClangEditorDocumentProcessor::clearProjectPart()
{
    m_projectPart.clear();
}

Marco Bubke's avatar
Marco Bubke committed
164 165 166 167
void ClangEditorDocumentProcessor::updateCodeWarnings(const QVector<ClangBackEnd::DiagnosticContainer> &diagnostics,
                                                      uint documentRevision)
{
    if (documentRevision == revision()) {
168 169
        m_diagnosticManager.processNewDiagnostics(diagnostics);
        const auto codeWarnings = m_diagnosticManager.takeExtraSelections();
Marco Bubke's avatar
Marco Bubke committed
170 171 172
        emit codeWarningsUpdated(revision(), codeWarnings);
    }
}
173
namespace {
Marco Bubke's avatar
Marco Bubke committed
174

175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193
int positionInText(QTextDocument *textDocument,
                   const ClangBackEnd::SourceLocationContainer &sourceLocationContainer)
{
    auto textBlock = textDocument->findBlockByNumber(int(sourceLocationContainer.line()) - 1);

    return textBlock.position() + int(sourceLocationContainer.column()) - 1;
}

TextEditor::BlockRange
toTextEditorBlock(QTextDocument *textDocument,
                  const ClangBackEnd::SourceRangeContainer &sourceRangeContainer)
{
    return TextEditor::BlockRange(positionInText(textDocument, sourceRangeContainer.start()),
                                  positionInText(textDocument, sourceRangeContainer.end()));
}

QList<TextEditor::BlockRange>
toTextEditorBlocks(QTextDocument *textDocument,
                   const QVector<ClangBackEnd::SourceRangeContainer> &ifdefedOutRanges)
194 195 196 197 198
{
    QList<TextEditor::BlockRange> blockRanges;
    blockRanges.reserve(ifdefedOutRanges.size());

    for (const auto &range : ifdefedOutRanges)
199
        blockRanges.append(toTextEditorBlock(textDocument, range));
200 201 202

    return blockRanges;
}
203
}
204 205 206 207 208 209 210

void ClangEditorDocumentProcessor::updateHighlighting(
        const QVector<ClangBackEnd::HighlightingMarkContainer> &highlightingMarks,
        const QVector<ClangBackEnd::SourceRangeContainer> &skippedPreprocessorRanges,
        uint documentRevision)
{
    if (documentRevision == revision()) {
211
        const auto skippedPreprocessorBlocks = toTextEditorBlocks(textDocument(), skippedPreprocessorRanges);
212 213 214 215 216 217 218 219 220 221 222
        emit ifdefedOutBlocksUpdated(documentRevision, skippedPreprocessorBlocks);

        m_semanticHighlighter.setHighlightingRunner(
            [highlightingMarks]() {
                auto *reporter = new HighlightingMarksReporter(highlightingMarks);
                return reporter->start();
            });
        m_semanticHighlighter.run();
    }
}

223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240
static int currentLine(const TextEditor::AssistInterface &assistInterface)
{
    int line, column;
    TextEditor::Convenience::convertPosition(assistInterface.textDocument(),
                                             assistInterface.position(),
                                             &line,
                                             &column);
    return line;
}

TextEditor::QuickFixOperations ClangEditorDocumentProcessor::extraRefactoringOperations(
        const TextEditor::AssistInterface &assistInterface)
{
    ClangFixItOperationsExtractor extractor(m_diagnosticManager.diagnosticsWithFixIts());

    return extractor.extract(assistInterface.fileName(), currentLine(assistInterface));
}

241
ClangBackEnd::FileContainer ClangEditorDocumentProcessor::fileContainerWithArguments() const
Marco Bubke's avatar
Marco Bubke committed
242
{
243
    return fileContainerWithArguments(m_projectPart.data());
Marco Bubke's avatar
Marco Bubke committed
244 245
}

246 247 248 249 250
void ClangEditorDocumentProcessor::clearDiagnosticsWithFixIts()
{
    m_diagnosticManager.clearDiagnosticsWithFixIts();
}

251 252
ClangEditorDocumentProcessor *ClangEditorDocumentProcessor::get(const QString &filePath)
{
Marco Bubke's avatar
Marco Bubke committed
253 254 255
    auto *processor = CppTools::CppToolsBridge::baseEditorDocumentProcessor(filePath);

    return qobject_cast<ClangEditorDocumentProcessor*>(processor);
256 257
}

258 259 260
static bool isProjectPartLoadedOrIsFallback(CppTools::ProjectPart::Ptr projectPart)
{
    return projectPart
261
        && (projectPart->id().isEmpty() || ClangCodeModel::Utils::isProjectPartLoaded(projectPart));
262 263
}

264
void ClangEditorDocumentProcessor::updateProjectPartAndTranslationUnitForEditor()
265
{
266
    const CppTools::ProjectPart::Ptr projectPart = m_parser->projectPart();
267

268
    if (isProjectPartLoadedOrIsFallback(projectPart)) {
269
        registerTranslationUnitForEditor(projectPart.data());
Marco Bubke's avatar
Marco Bubke committed
270

271 272
        m_projectPart = projectPart;
    }
273 274
}

275 276 277 278 279
void ClangEditorDocumentProcessor::onParserFinished()
{
    if (revision() != m_parserRevision)
        return;

280
    updateProjectPartAndTranslationUnitForEditor();
281 282
}

283
void ClangEditorDocumentProcessor::registerTranslationUnitForEditor(CppTools::ProjectPart *projectPart)
284 285
{
    if (m_projectPart) {
Marco Bubke's avatar
Marco Bubke committed
286
        if (projectPart->id() != m_projectPart->id()) {
287 288
            m_ipcCommunicator.unregisterTranslationUnitsForEditor({fileContainerWithArguments()});
            m_ipcCommunicator.registerTranslationUnitsForEditor({fileContainerWithArguments(projectPart)});
289 290
        }
    } else {
291
        m_ipcCommunicator.registerTranslationUnitsForEditor({{fileContainerWithArguments(projectPart)}});
Marco Bubke's avatar
Marco Bubke committed
292 293 294
    }
}

295
void ClangEditorDocumentProcessor::updateTranslationUnitIfProjectPartExists()
Marco Bubke's avatar
Marco Bubke committed
296
{
297 298
    if (m_projectPart) {
        const ClangBackEnd::FileContainer fileContainer = fileContainerWithDocumentContent(m_projectPart->id());
Marco Bubke's avatar
Marco Bubke committed
299

300
        m_ipcCommunicator.updateTranslationUnitWithRevisionCheck(fileContainer);
Marco Bubke's avatar
Marco Bubke committed
301 302 303
    }
}

304
void ClangEditorDocumentProcessor::requestDocumentAnnotations(const QString &projectpartId)
305
{
306
    const auto fileContainer = fileContainerWithDocumentContent(projectpartId);
307

308 309
    m_ipcCommunicator.requestDiagnostics(fileContainer);
    m_ipcCommunicator.requestHighlighting(fileContainer);
310 311
}

312 313 314 315 316 317 318 319 320
static CppTools::ProjectPart projectPartForLanguageOption(CppTools::ProjectPart *projectPart)
{
    if (projectPart)
        return *projectPart;
    return *CppTools::CppModelManager::instance()->fallbackProjectPart().data();
}

static QStringList languageOptions(const QString &filePath, CppTools::ProjectPart *projectPart)
{
321
    const auto theProjectPart = projectPartForLanguageOption(projectPart);
322 323 324 325 326 327
    CppTools::CompilerOptionsBuilder builder(theProjectPart);
    builder.addLanguageOption(CppTools::ProjectFile::classify(filePath));

    return builder.options();
}

328 329 330 331 332 333
static QStringList fileArguments(const QString &filePath, CppTools::ProjectPart *projectPart)
{
    return QStringList(languageOptions(filePath, projectPart))
         + CppTools::codeModelSettings()->extraClangOptions();
}

Marco Bubke's avatar
Marco Bubke committed
334
ClangBackEnd::FileContainer
335
ClangEditorDocumentProcessor::fileContainerWithArguments(CppTools::ProjectPart *projectPart) const
Marco Bubke's avatar
Marco Bubke committed
336
{
337 338 339
    const auto projectPartId = projectPart
            ? Utf8String::fromString(projectPart->id())
            : Utf8String();
340
    const QStringList theFileArguments = fileArguments(filePath(), projectPart);
Marco Bubke's avatar
Marco Bubke committed
341

342
    return {filePath(), projectPartId, Utf8StringVector(theFileArguments), revision()};
Marco Bubke's avatar
Marco Bubke committed
343 344
}

345 346 347 348 349
ClangBackEnd::FileContainer
ClangEditorDocumentProcessor::fileContainerWithDocumentContent(const QString &projectpartId) const
{
    return ClangBackEnd::FileContainer(filePath(),
                                       projectpartId,
350
                                       textDocument()->toPlainText(),
351 352 353 354
                                       true,
                                       revision());
}

355
} // namespace Internal
356
} // namespace ClangCodeModel