clangeditordocumentprocessor.cpp 18 KB
Newer Older
1 2
/****************************************************************************
**
3 4
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://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
12 13 14
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
15
**
16 17 18 19 20 21 22
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3 as published by the Free Software
** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-3.0.html.
23 24 25 26 27
**
****************************************************************************/

#include "clangeditordocumentprocessor.h"

28
#include "clangbackendipcintegration.h"
29
#include "clangdiagnostictooltipwidget.h"
30 31
#include "clangfixitoperation.h"
#include "clangfixitoperationsextractor.h"
32
#include "clanghighlightingmarksreporter.h"
33
#include "clangprojectsettings.h"
34
#include "clangutils.h"
35

Marco Bubke's avatar
Marco Bubke committed
36 37 38
#include <diagnosticcontainer.h>
#include <sourcelocationcontainer.h>

39 40
#include <cpptools/clangdiagnosticconfigsmodel.h>
#include <cpptools/clangdiagnosticconfigsmodel.h>
41
#include <cpptools/compileroptionsbuilder.h>
42
#include <cpptools/cppcodemodelsettings.h>
43
#include <cpptools/cppmodelmanager.h>
Marco Bubke's avatar
Marco Bubke committed
44
#include <cpptools/cpptoolsbridge.h>
45
#include <cpptools/cpptoolsreuse.h>
46
#include <cpptools/cppworkingcopy.h>
47
#include <cpptools/editordocumenthandle.h>
48

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
#include <cplusplus/CppDocument.h>

#include <utils/qtcassert.h>
58
#include <utils/runextensions.h>
59

Marco Bubke's avatar
Marco Bubke committed
60
#include <QTextBlock>
61 62
#include <QVBoxLayout>
#include <QWidget>
Marco Bubke's avatar
Marco Bubke committed
63

64
namespace ClangCodeModel {
65
namespace Internal {
66

67
ClangEditorDocumentProcessor::ClangEditorDocumentProcessor(
68
        IpcCommunicator &ipcCommunicator,
69
        TextEditor::TextDocument *document)
70
    : BaseEditorDocumentProcessor(document->document(), document->filePath().toString())
71
    , m_diagnosticManager(document)
72
    , m_ipcCommunicator(ipcCommunicator)
73
    , m_parser(new ClangEditorDocumentParser(document->filePath().toString()))
74 75 76 77
    , m_parserRevision(0)
    , m_semanticHighlighter(document)
    , m_builtinProcessor(document, /*enableSemanticHighlighter=*/ false)
{
78 79 80 81 82
    m_updateTranslationUnitTimer.setSingleShot(true);
    m_updateTranslationUnitTimer.setInterval(350);
    connect(&m_updateTranslationUnitTimer, &QTimer::timeout,
            this, &ClangEditorDocumentProcessor::updateTranslationUnitIfProjectPartExists);

83 84 85
    connect(m_parser.data(), &ClangEditorDocumentParser::projectPartInfoUpdated,
            this, &BaseEditorDocumentProcessor::projectPartInfoUpdated);

86 87 88 89 90 91 92 93 94 95
    // 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()
{
96 97
    m_updateTranslationUnitTimer.stop();

98 99
    m_parserWatcher.cancel();
    m_parserWatcher.waitForFinished();
100

101
    if (m_projectPart) {
102
        m_ipcCommunicator.unregisterTranslationUnitsForEditor(
103 104
            {ClangBackEnd::FileContainer(filePath(), m_projectPart->id())});
    }
105 106
}

107 108
void ClangEditorDocumentProcessor::runImpl(
        const CppTools::BaseEditorDocumentParser::UpdateParams &updateParams)
109
{
110
    m_updateTranslationUnitTimer.start();
Marco Bubke's avatar
Marco Bubke committed
111

112 113 114 115 116 117 118 119 120
    // 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);
121
    const QFuture<void> future = ::Utils::runAsync(&runParser, parser(), updateParams);
122 123 124
    m_parserWatcher.setFuture(future);

    // Run builtin processor
125
    m_builtinProcessor.runImpl(updateParams);
126 127
}

128
void ClangEditorDocumentProcessor::recalculateSemanticInfoDetached(bool force)
129
{
130
    m_builtinProcessor.recalculateSemanticInfoDetached(force);
131 132
}

133 134 135
void ClangEditorDocumentProcessor::semanticRehighlight()
{
    m_semanticHighlighter.updateFormatMapFromFontSettings();
136 137 138

    if (m_projectPart)
        requestDocumentAnnotations(m_projectPart->id());
139 140
}

141 142 143 144 145
CppTools::SemanticInfo ClangEditorDocumentProcessor::recalculateSemanticInfo()
{
    return m_builtinProcessor.recalculateSemanticInfo();
}

146
CppTools::BaseEditorDocumentParser::Ptr ClangEditorDocumentProcessor::parser()
147
{
148
    return m_parser;
149 150
}

151 152 153 154 155
CPlusPlus::Snapshot ClangEditorDocumentProcessor::snapshot()
{
   return m_builtinProcessor.snapshot();
}

156 157 158 159 160
bool ClangEditorDocumentProcessor::isParserRunning() const
{
    return m_parserWatcher.isRunning();
}

161 162 163 164 165
bool ClangEditorDocumentProcessor::hasProjectPart() const
{
    return m_projectPart;
}

166 167 168 169 170
CppTools::ProjectPart::Ptr ClangEditorDocumentProcessor::projectPart() const
{
    return m_projectPart;
}

171 172 173 174 175
void ClangEditorDocumentProcessor::clearProjectPart()
{
    m_projectPart.clear();
}

176 177 178 179
void ClangEditorDocumentProcessor::updateCodeWarnings(
        const QVector<ClangBackEnd::DiagnosticContainer> &diagnostics,
        const ClangBackEnd::DiagnosticContainer &firstHeaderErrorDiagnostic,
        uint documentRevision)
Marco Bubke's avatar
Marco Bubke committed
180 181
{
    if (documentRevision == revision()) {
182 183
        m_diagnosticManager.processNewDiagnostics(diagnostics);
        const auto codeWarnings = m_diagnosticManager.takeExtraSelections();
184
        const auto fixitAvailableMarkers = m_diagnosticManager.takeFixItAvailableMarkers();
185 186 187 188 189 190
        const auto creator = creatorForHeaderErrorDiagnosticWidget(firstHeaderErrorDiagnostic);

        emit codeWarningsUpdated(revision(),
                                 codeWarnings,
                                 creator,
                                 fixitAvailableMarkers);
Marco Bubke's avatar
Marco Bubke committed
191 192
    }
}
193
namespace {
Marco Bubke's avatar
Marco Bubke committed
194

195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213
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)
214 215 216 217 218
{
    QList<TextEditor::BlockRange> blockRanges;
    blockRanges.reserve(ifdefedOutRanges.size());

    for (const auto &range : ifdefedOutRanges)
219
        blockRanges.append(toTextEditorBlock(textDocument, range));
220 221 222

    return blockRanges;
}
223
}
224 225 226 227 228 229 230

void ClangEditorDocumentProcessor::updateHighlighting(
        const QVector<ClangBackEnd::HighlightingMarkContainer> &highlightingMarks,
        const QVector<ClangBackEnd::SourceRangeContainer> &skippedPreprocessorRanges,
        uint documentRevision)
{
    if (documentRevision == revision()) {
231
        const auto skippedPreprocessorBlocks = toTextEditorBlocks(textDocument(), skippedPreprocessorRanges);
232 233 234 235 236 237 238 239 240 241 242
        emit ifdefedOutBlocksUpdated(documentRevision, skippedPreprocessorBlocks);

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

243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260
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));
}

261 262 263 264 265
bool ClangEditorDocumentProcessor::hasDiagnosticsAt(uint line, uint column) const
{
    return m_diagnosticManager.hasDiagnosticsAt(line, column);
}

266 267 268
void ClangEditorDocumentProcessor::addDiagnosticToolTipToLayout(uint line,
                                                                uint column,
                                                                QLayout *target) const
269
{
270 271 272 273 274 275
    using Internal::ClangDiagnosticWidget;

    const QVector<ClangBackEnd::DiagnosticContainer> diagnostics
        = m_diagnosticManager.diagnosticsAt(line, column);

    target->addWidget(ClangDiagnosticWidget::create(diagnostics, ClangDiagnosticWidget::ToolTip));
276 277
}

278 279 280 281 282
void ClangEditorDocumentProcessor::editorDocumentTimerRestarted()
{
    m_updateTranslationUnitTimer.stop(); // Wait for the next call to run().
}

283 284 285 286 287 288 289
void ClangEditorDocumentProcessor::setParserConfig(
        const CppTools::BaseEditorDocumentParser::Configuration config)
{
    m_parser->setConfiguration(config);
    m_builtinProcessor.parser()->setConfiguration(config);
}

290
ClangBackEnd::FileContainer ClangEditorDocumentProcessor::fileContainerWithArguments() const
Marco Bubke's avatar
Marco Bubke committed
291
{
292
    return fileContainerWithArguments(m_projectPart.data());
Marco Bubke's avatar
Marco Bubke committed
293 294
}

295 296 297 298 299
void ClangEditorDocumentProcessor::clearDiagnosticsWithFixIts()
{
    m_diagnosticManager.clearDiagnosticsWithFixIts();
}

300 301
ClangEditorDocumentProcessor *ClangEditorDocumentProcessor::get(const QString &filePath)
{
Marco Bubke's avatar
Marco Bubke committed
302 303 304
    auto *processor = CppTools::CppToolsBridge::baseEditorDocumentProcessor(filePath);

    return qobject_cast<ClangEditorDocumentProcessor*>(processor);
305 306
}

307 308 309
static bool isProjectPartLoadedOrIsFallback(CppTools::ProjectPart::Ptr projectPart)
{
    return projectPart
310
        && (projectPart->id().isEmpty() || ClangCodeModel::Utils::isProjectPartLoaded(projectPart));
311 312
}

313
void ClangEditorDocumentProcessor::updateProjectPartAndTranslationUnitForEditor()
314
{
315
    const CppTools::ProjectPart::Ptr projectPart = m_parser->projectPartInfo().projectPart;
316

317
    if (isProjectPartLoadedOrIsFallback(projectPart)) {
318
        registerTranslationUnitForEditor(projectPart.data());
Marco Bubke's avatar
Marco Bubke committed
319

320 321
        m_projectPart = projectPart;
    }
322 323
}

324 325 326 327 328
void ClangEditorDocumentProcessor::onParserFinished()
{
    if (revision() != m_parserRevision)
        return;

329
    updateProjectPartAndTranslationUnitForEditor();
330 331
}

332
void ClangEditorDocumentProcessor::registerTranslationUnitForEditor(CppTools::ProjectPart *projectPart)
333
{
334 335 336 337 338 339 340 341 342
    // On registration we send the document content immediately as an unsaved
    // file, because
    //   (1) a refactoring action might have opened and already modified
    //       this document.
    //   (2) it prevents an extra preamble generation on first user
    //       modification of the document in case the line endings on disk
    //       differ from the ones returned by textDocument()->toPlainText(),
    //       like on Windows.

343
    if (m_projectPart) {
344 345 346
        if (projectPart->id() == m_projectPart->id())
            return;
        m_ipcCommunicator.unregisterTranslationUnitsForEditor({fileContainerWithArguments()});
Marco Bubke's avatar
Marco Bubke committed
347
    }
348 349 350 351

    m_ipcCommunicator.registerTranslationUnitsForEditor(
        {fileContainerWithArgumentsAndDocumentContent(projectPart)});
    ClangCodeModel::Utils::setLastSentDocumentRevision(filePath(), revision());
Marco Bubke's avatar
Marco Bubke committed
352 353
}

354
void ClangEditorDocumentProcessor::updateTranslationUnitIfProjectPartExists()
Marco Bubke's avatar
Marco Bubke committed
355
{
356 357
    if (m_projectPart) {
        const ClangBackEnd::FileContainer fileContainer = fileContainerWithDocumentContent(m_projectPart->id());
Marco Bubke's avatar
Marco Bubke committed
358

359
        m_ipcCommunicator.updateTranslationUnitWithRevisionCheck(fileContainer);
Marco Bubke's avatar
Marco Bubke committed
360 361 362
    }
}

363
void ClangEditorDocumentProcessor::requestDocumentAnnotations(const QString &projectpartId)
364
{
365
    const auto fileContainer = fileContainerWithDocumentContent(projectpartId);
366

367
    m_ipcCommunicator.requestDocumentAnnotations(fileContainer);
368 369
}

370 371 372 373 374 375 376 377 378 379 380 381 382
CppTools::BaseEditorDocumentProcessor::HeaderErrorDiagnosticWidgetCreator
ClangEditorDocumentProcessor::creatorForHeaderErrorDiagnosticWidget(
        const ClangBackEnd::DiagnosticContainer &firstHeaderErrorDiagnostic)
{
    if (firstHeaderErrorDiagnostic.text().isEmpty())
        return CppTools::BaseEditorDocumentProcessor::HeaderErrorDiagnosticWidgetCreator();

    return [firstHeaderErrorDiagnostic]() {
        auto vbox = new QVBoxLayout;
        vbox->setMargin(0);
        vbox->setContentsMargins(10, 0, 0, 2);
        vbox->setSpacing(2);

383 384
        vbox->addWidget(ClangDiagnosticWidget::create({firstHeaderErrorDiagnostic},
                                                      ClangDiagnosticWidget::InfoBar));
385 386 387 388 389 390 391 392

        auto widget = new QWidget;
        widget->setLayout(vbox);

        return widget;
    };
}

393 394 395 396 397 398 399 400 401
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)
{
402
    const auto theProjectPart = projectPartForLanguageOption(projectPart);
403 404 405 406 407 408 409 410 411

    // Determine file kind with respect to ambiguous headers.
    CppTools::ProjectFile::Kind fileKind = CppTools::ProjectFile::classify(filePath);
    if (fileKind == CppTools::ProjectFile::AmbiguousHeader) {
        fileKind = theProjectPart.languageVersion <= CppTools::ProjectPart::LatestCVersion
             ? CppTools::ProjectFile::CHeader
             : CppTools::ProjectFile::CXXHeader;
    }

412
    CppTools::CompilerOptionsBuilder builder(theProjectPart);
413
    builder.addLanguageOption(fileKind);
414 415 416 417

    return builder.options();
}

418 419 420 421
static QStringList warningOptions(CppTools::ProjectPart *projectPart)
{
    if (projectPart && projectPart->project) {
        ClangProjectSettings projectSettings(projectPart->project);
422
        if (!projectSettings.useGlobalConfig()) {
423 424 425 426
            const Core::Id warningConfigId = projectSettings.warningConfigId();
            const CppTools::ClangDiagnosticConfigsModel configsModel(
                        CppTools::codeModelSettings()->clangCustomDiagnosticConfigs());
            if (configsModel.hasConfigWithId(warningConfigId))
427
                return configsModel.configWithId(warningConfigId).commandLineWarnings();
428 429 430
        }
    }

431 432 433 434 435 436 437 438 439
    return CppTools::codeModelSettings()->clangDiagnosticConfig().commandLineWarnings();
}

static QStringList commandLineOptions(CppTools::ProjectPart *projectPart)
{
    if (!projectPart || !projectPart->project)
        return ClangProjectSettings::globalCommandLineOptions();

    return ClangProjectSettings{projectPart->project}.commandLineOptions();
440 441
}

442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460
static QStringList precompiledHeaderOptions(
        const QString& filePath,
        CppTools::ProjectPart *projectPart)
{
    using namespace CppTools;

    if (CppTools::getPchUsage() == CompilerOptionsBuilder::PchUsage::None)
        return QStringList();

    if (projectPart->precompiledHeaders.contains(filePath))
        return QStringList();

    const CppTools::ProjectPart theProjectPart = projectPartForLanguageOption(projectPart);
    CppTools::CompilerOptionsBuilder builder(theProjectPart);
    builder.addPrecompiledHeaderOptions(CompilerOptionsBuilder::PchUsage::Use);

    return builder.options();
}

461 462
static QStringList fileArguments(const QString &filePath, CppTools::ProjectPart *projectPart)
{
463 464
    return languageOptions(filePath, projectPart)
            + warningOptions(projectPart)
465
            + commandLineOptions(projectPart)
466
            + precompiledHeaderOptions(filePath, projectPart);
467 468
}

Marco Bubke's avatar
Marco Bubke committed
469
ClangBackEnd::FileContainer
470
ClangEditorDocumentProcessor::fileContainerWithArguments(CppTools::ProjectPart *projectPart) const
Marco Bubke's avatar
Marco Bubke committed
471
{
472 473 474
    const auto projectPartId = projectPart
            ? Utf8String::fromString(projectPart->id())
            : Utf8String();
475
    const QStringList theFileArguments = fileArguments(filePath(), projectPart);
Marco Bubke's avatar
Marco Bubke committed
476

477
    return {filePath(), projectPartId, Utf8StringVector(theFileArguments), revision()};
Marco Bubke's avatar
Marco Bubke committed
478 479
}

480 481 482 483 484 485 486 487 488 489 490 491 492 493
ClangBackEnd::FileContainer
ClangEditorDocumentProcessor::fileContainerWithArgumentsAndDocumentContent(
        CppTools::ProjectPart *projectPart) const
{
    const QStringList theFileArguments = fileArguments(filePath(), projectPart);

    return ClangBackEnd::FileContainer(filePath(),
                                       projectPart->id(),
                                       Utf8StringVector(theFileArguments),
                                       textDocument()->toPlainText(),
                                       true,
                                       revision());
}

494 495 496 497 498
ClangBackEnd::FileContainer
ClangEditorDocumentProcessor::fileContainerWithDocumentContent(const QString &projectpartId) const
{
    return ClangBackEnd::FileContainer(filePath(),
                                       projectpartId,
499
                                       textDocument()->toPlainText(),
500 501 502 503
                                       true,
                                       revision());
}

504
} // namespace Internal
505
} // namespace ClangCodeModel