clangeditordocumentprocessor.cpp 17.7 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 34
#include "clangmodelmanagersupport.h"
#include "clangutils.h"
35 36 37 38
#include "cppcreatemarkers.h"
#include "diagnostic.h"
#include "pchinfo.h"

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

42 43 44
#include <cpptools/cpptoolsplugin.h>
#include <cpptools/cppworkingcopy.h>

45
#include <texteditor/fontsettings.h>
Marco Bubke's avatar
Marco Bubke committed
46
#include <texteditor/texteditor.h>
47 48
#include <texteditor/texteditorconstants.h>
#include <texteditor/texteditorsettings.h>
Marco Bubke's avatar
Marco Bubke committed
49

50 51 52 53 54
#include <cplusplus/CppDocument.h>

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

Marco Bubke's avatar
Marco Bubke committed
55 56
#include <QTextBlock>

57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
namespace {

typedef CPlusPlus::Document::DiagnosticMessage CppToolsDiagnostic;

QList<TextEditor::BlockRange> toTextEditorBlocks(
        const QList<ClangCodeModel::SemanticMarker::Range> &ranges)
{
    QList<TextEditor::BlockRange> result;
    result.reserve(ranges.size());
    foreach (const ClangCodeModel::SemanticMarker::Range &range, ranges)
        result.append(TextEditor::BlockRange(range.first, range.last));
    return result;
}

} // anonymous namespace

namespace ClangCodeModel {
74
namespace Internal {
75

76 77 78
ClangEditorDocumentProcessor::ClangEditorDocumentProcessor(
        ModelManagerSupportClang *modelManagerSupport,
        TextEditor::TextDocument *document)
79
    : BaseEditorDocumentProcessor(document)
80
    , m_modelManagerSupport(modelManagerSupport)
81
    , m_parser(new ClangEditorDocumentParser(document->filePath().toString()))
82 83 84 85 86 87 88 89 90 91 92
    , 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);

93 94 95
    connect(CppTools::CppModelManager::instance(), &CppTools::CppModelManager::projectPartsRemoved,
            this, &ClangEditorDocumentProcessor::onProjectPartsRemoved);

96 97 98 99 100
    m_semanticHighlighter.setHighlightingRunner(
        [this]() -> QFuture<TextEditor::HighlightingResult> {
            const int firstLine = 1;
            const int lastLine = baseTextDocument()->document()->blockCount();

101
            CreateMarkers *createMarkers = CreateMarkers::create(m_parser->semanticMarker(),
102
                                                                 baseTextDocument()->filePath().toString(),
103 104 105 106 107 108 109 110 111
                                                                 firstLine, lastLine);
            return createMarkers->start();
        });
}

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

113 114
    if (m_projectPart) {
        QTC_ASSERT(m_modelManagerSupport, return);
115
        m_modelManagerSupport->ipcCommunicator().unregisterTranslationUnitsForEditor(
116 117
            {ClangBackEnd::FileContainer(filePath(), m_projectPart->id())});
    }
118 119 120 121
}

void ClangEditorDocumentProcessor::run()
{
Marco Bubke's avatar
Marco Bubke committed
122 123
    requestDiagnostics();

124 125 126 127 128 129 130 131 132
    // 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);
133 134 135
    const QFuture<void> future = QtConcurrent::run(&runParser,
                                                   parser(),
                                                   ClangEditorDocumentParser::InMemoryInfo(true));
136 137 138 139 140 141
    m_parserWatcher.setFuture(future);

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

142
void ClangEditorDocumentProcessor::recalculateSemanticInfoDetached(bool force)
143
{
144
    m_builtinProcessor.recalculateSemanticInfoDetached(force);
145 146
}

147 148 149 150 151 152
void ClangEditorDocumentProcessor::semanticRehighlight()
{
    m_semanticHighlighter.updateFormatMapFromFontSettings();
    m_semanticHighlighter.run();
}

153 154 155 156 157
CppTools::SemanticInfo ClangEditorDocumentProcessor::recalculateSemanticInfo()
{
    return m_builtinProcessor.recalculateSemanticInfo();
}

158
CppTools::BaseEditorDocumentParser::Ptr ClangEditorDocumentProcessor::parser()
159
{
160
    return m_parser;
161 162
}

163 164 165 166 167
CPlusPlus::Snapshot ClangEditorDocumentProcessor::snapshot()
{
   return m_builtinProcessor.snapshot();
}

168 169 170 171 172
bool ClangEditorDocumentProcessor::isParserRunning() const
{
    return m_parserWatcher.isRunning();
}

173 174 175 176 177
CppTools::ProjectPart::Ptr ClangEditorDocumentProcessor::projectPart() const
{
    return m_projectPart;
}

Marco Bubke's avatar
Marco Bubke committed
178 179 180 181 182 183 184 185 186
void ClangEditorDocumentProcessor::updateCodeWarnings(const QVector<ClangBackEnd::DiagnosticContainer> &diagnostics,
                                                      uint documentRevision)
{
    if (documentRevision == revision()) {
        const auto codeWarnings = generateDiagnosticHints(diagnostics);
        emit codeWarningsUpdated(revision(), codeWarnings);
    }
}

187 188 189 190 191
ClangEditorDocumentProcessor *ClangEditorDocumentProcessor::get(const QString &filePath)
{
    return qobject_cast<ClangEditorDocumentProcessor *>(BaseEditorDocumentProcessor::get(filePath));
}

192
void ClangEditorDocumentProcessor::updateProjectPartAndTranslationUnitForEditor()
193
{
194
    const CppTools::ProjectPart::Ptr projectPart = m_parser->projectPart();
195 196
    QTC_ASSERT(projectPart, return);

197
    updateTranslationUnitForEditor(*projectPart.data());
Marco Bubke's avatar
Marco Bubke committed
198 199
    requestDiagnostics(*projectPart.data());

200 201 202
    m_projectPart = projectPart;
}

203 204 205 206 207 208
void ClangEditorDocumentProcessor::onParserFinished()
{
    if (revision() != m_parserRevision)
        return;

    // Emit ifdefed out blocks
209
    const auto ifdefoutBlocks = toTextEditorBlocks(m_parser->ifdefedOutBlocks());
210 211 212 213
    emit ifdefedOutBlocksUpdated(revision(), ifdefoutBlocks);

    // Run semantic highlighter
    m_semanticHighlighter.run();
214

215
    updateProjectPartAndTranslationUnitForEditor();
216 217 218 219 220 221 222 223
}

void ClangEditorDocumentProcessor::onProjectPartsRemoved(const QStringList &projectPartIds)
{
    if (m_projectPart && projectPartIds.contains(m_projectPart->id()))
        m_projectPart.clear();
}

224
void ClangEditorDocumentProcessor::updateTranslationUnitForEditor(CppTools::ProjectPart &projectPart)
225 226 227 228 229 230
{
    QTC_ASSERT(m_modelManagerSupport, return);
    IpcCommunicator &ipcCommunicator = m_modelManagerSupport->ipcCommunicator();

    if (m_projectPart) {
        if (projectPart.id() != m_projectPart->id()) {
231 232 233
            auto container1 = ClangBackEnd::FileContainer(filePath(),
                                                          m_projectPart->id(),
                                                          revision());
234
            ipcCommunicator.unregisterTranslationUnitsForEditor({container1});
235

236 237 238
            auto container2 = ClangBackEnd::FileContainer(filePath(),
                                                          projectPart.id(),
                                                          revision());
239
            ipcCommunicator.registerTranslationUnitsForEditor({container2});
240 241
        }
    } else {
242 243 244
        auto container = ClangBackEnd::FileContainer(filePath(),
                                                     projectPart.id(),
                                                     revision());
245
        ipcCommunicator.registerTranslationUnitsForEditor({container});
Marco Bubke's avatar
Marco Bubke committed
246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394
    }
}

namespace {
bool isWarningOrNote(ClangBackEnd::DiagnosticSeverity severity)
{
    using ClangBackEnd::DiagnosticSeverity;
    switch (severity) {
        case DiagnosticSeverity::Ignored:
        case DiagnosticSeverity::Note:
        case DiagnosticSeverity::Warning: return true;
        case DiagnosticSeverity::Error:
        case DiagnosticSeverity::Fatal: return false;
    }

    Q_UNREACHABLE();
}

bool isHelpfulChildDiagnostic(const ClangBackEnd::DiagnosticContainer &parentDiagnostic,
                              const ClangBackEnd::DiagnosticContainer &childDiagnostic)
{
    auto parentLocation = parentDiagnostic.location();
    auto childLocation = childDiagnostic.location();

    return parentLocation == childLocation;
}

QString diagnosticText(const ClangBackEnd::DiagnosticContainer &diagnostic)
{
    QString text = diagnostic.category().toString()
            + QStringLiteral(" ")
            + diagnostic.text().toString();
    if (!diagnostic.enableOption().isEmpty()) {
        text += QStringLiteral(" (clang option: ")
                + diagnostic.enableOption().toString()
                + QStringLiteral(" disable with: ")
                + diagnostic.disableOption().toString()
                + QStringLiteral(")");
    }

    for (auto &&childDiagnostic : diagnostic.children()) {
        if (isHelpfulChildDiagnostic(diagnostic, childDiagnostic))
            text += QStringLiteral("\n  ") + childDiagnostic.text().toString();
    }

    return text;
}

template <class Condition>
std::vector<ClangBackEnd::DiagnosticContainer>
filterDiagnostics(const QVector<ClangBackEnd::DiagnosticContainer> &diagnostics,
                  const Condition &condition)
{
    std::vector<ClangBackEnd::DiagnosticContainer> filteredDiagnostics;

    std::copy_if(diagnostics.cbegin(),
                 diagnostics.cend(),
                 std::back_inserter(filteredDiagnostics),
                 condition);

    return filteredDiagnostics;
}

std::vector<ClangBackEnd::DiagnosticContainer>
filterInterestingWarningDiagnostics(const QVector<ClangBackEnd::DiagnosticContainer> &diagnostics,
                                    QString &&documentFilePath)
{
    auto isLocalWarning = [documentFilePath] (const ClangBackEnd::DiagnosticContainer &diagnostic) {
        return isWarningOrNote(diagnostic.severity())
            && diagnostic.location().filePath() == documentFilePath;
    };

    return filterDiagnostics(diagnostics, isLocalWarning);
}

std::vector<ClangBackEnd::DiagnosticContainer>
filterInterestingErrorsDiagnostics(const QVector<ClangBackEnd::DiagnosticContainer> &diagnostics,
                                   QString &&documentFilePath)
{
    auto isLocalWarning = [documentFilePath] (const ClangBackEnd::DiagnosticContainer &diagnostic) {
        return !isWarningOrNote(diagnostic.severity())
            && diagnostic.location().filePath() == documentFilePath;
    };

    return filterDiagnostics(diagnostics, isLocalWarning);
}

QTextEdit::ExtraSelection createExtraSelections(const QTextCharFormat &mainformat,
                                               const QTextCursor &cursor,
                                               const QString &diagnosticText)
{
    QTextEdit::ExtraSelection extraSelection;

    extraSelection.format = mainformat;
    extraSelection.cursor = cursor;
    extraSelection.format.setToolTip(diagnosticText);

    return extraSelection;
}

void addRangeSelections(const ClangBackEnd::DiagnosticContainer &diagnostic,
                        QTextDocument *textDocument,
                        const QTextCharFormat &rangeFormat,
                        const QString &diagnosticText,
                        QList<QTextEdit::ExtraSelection> &extraSelections)
{
    for (auto &&range : diagnostic.ranges()) {
        QTextCursor cursor(textDocument);
        cursor.setPosition(int(range.start().offset()));
        cursor.setPosition(int(range.end().offset()), QTextCursor::KeepAnchor);

        auto extraSelection = createExtraSelections(rangeFormat, cursor, diagnosticText);

        extraSelections.push_back(std::move(extraSelection));
    }
}

QTextCursor createSelectionCursor(QTextDocument *textDocument, uint position)
{
    QTextCursor cursor(textDocument);
    cursor.setPosition(int(position));
    cursor.movePosition(QTextCursor::EndOfWord, QTextCursor::KeepAnchor);

    if (!cursor.hasSelection()) {
        cursor.setPosition(int(position) - 1);
        cursor.movePosition(QTextCursor::Right, QTextCursor::KeepAnchor, 2);
    }

    return cursor;
}

void addSelections(const std::vector<ClangBackEnd::DiagnosticContainer> &diagnostics,
                   QTextDocument *textDocument,
                   const QTextCharFormat &mainFormat,
                   const QTextCharFormat &rangeFormat,
                   QList<QTextEdit::ExtraSelection> &extraSelections)
{
    for (auto &&diagnostic : diagnostics) {
        auto cursor = createSelectionCursor(textDocument, diagnostic.location().offset());

        auto text = diagnosticText(diagnostic);
        auto extraSelection = createExtraSelections(mainFormat, cursor, text);

        addRangeSelections(diagnostic, textDocument, rangeFormat, text, extraSelections);

        extraSelections.push_back(std::move(extraSelection));
    }
}

395 396 397 398 399
QTextCharFormat fontsettingsTextFormat(TextEditor::TextStyle textStyle)
{
    return TextEditor::TextEditorSettings::fontSettings().toTextCharFormat(textStyle);
}

Marco Bubke's avatar
Marco Bubke committed
400 401 402 403
void addWarningSelections(const std::vector<ClangBackEnd::DiagnosticContainer> &diagnostics,
                          QTextDocument *textDocument,
                          QList<QTextEdit::ExtraSelection> &extraSelections)
{
404 405 406 407 408
    addSelections(diagnostics,
                  textDocument,
                  fontsettingsTextFormat(TextEditor::C_WARNING),
                  fontsettingsTextFormat(TextEditor::C_WARNING_CONTEXT),
                  extraSelections);
Marco Bubke's avatar
Marco Bubke committed
409 410 411 412 413 414
}

void addErrorSelections(const std::vector<ClangBackEnd::DiagnosticContainer> &diagnostics,
                         QTextDocument *textDocument,
                         QList<QTextEdit::ExtraSelection> &extraSelections)
{
415 416 417 418 419
    addSelections(diagnostics,
                  textDocument,
                  fontsettingsTextFormat(TextEditor::C_ERROR),
                  fontsettingsTextFormat(TextEditor::C_ERROR_CONTEXT),
                  extraSelections);
Marco Bubke's avatar
Marco Bubke committed
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
}

}  // anonymous namespace

QList<QTextEdit::ExtraSelection>
ClangEditorDocumentProcessor::generateDiagnosticHints(const QVector<ClangBackEnd::DiagnosticContainer> &allDiagnostics)
{
    const auto warningDiagnostic = filterInterestingWarningDiagnostics(allDiagnostics, filePath());
    const auto errorDiagnostic = filterInterestingErrorsDiagnostics(allDiagnostics, filePath());

    m_clangTextMarks.clear();
    m_clangTextMarks.reserve(warningDiagnostic.size() + errorDiagnostic.size());

    addClangTextMarks(warningDiagnostic);
    addClangTextMarks(errorDiagnostic);

    QList<QTextEdit::ExtraSelection> extraSelections;
    extraSelections.reserve(int(warningDiagnostic.size() + errorDiagnostic.size()));

    addWarningSelections(warningDiagnostic, textDocument(), extraSelections);
    addErrorSelections(errorDiagnostic, textDocument(), extraSelections);

    return extraSelections;
}

void ClangEditorDocumentProcessor::addClangTextMarks(const std::vector<ClangBackEnd::DiagnosticContainer> &diagnostics)
{
    QTC_ASSERT(m_clangTextMarks.size() + diagnostics.size() <= m_clangTextMarks.capacity(), return);

    for (auto &&diagnostic : diagnostics) {
        m_clangTextMarks.emplace_back(filePath(),
                                      diagnostic.location().line(),
                                      diagnostic.severity());

        ClangTextMark &textMark = m_clangTextMarks.back();

        textMark.setBaseTextDocument(baseTextDocument());

        baseTextDocument()->addMark(&textMark);
    }
}

void ClangEditorDocumentProcessor::requestDiagnostics(CppTools::ProjectPart &projectPart)
{
    if (!m_projectPart || projectPart.id() != m_projectPart->id()) {
        IpcCommunicator &ipcCommunicator = m_modelManagerSupport->ipcCommunicator();

467 468 469 470 471
        ipcCommunicator.requestDiagnostics({filePath(),
                                            projectPart.id(),
                                            Utf8String(),
                                            false,
                                            revision()});
Marco Bubke's avatar
Marco Bubke committed
472 473 474 475 476 477 478 479 480
    }
}

void ClangEditorDocumentProcessor::requestDiagnostics()
{
    // Get diagnostics
    if (m_projectPart) {
        auto  &ipcCommunicator = m_modelManagerSupport->ipcCommunicator();
        ipcCommunicator.requestDiagnostics({filePath(),
481 482 483 484
                                            m_projectPart->id(),
                                            baseTextDocument()->plainText(),
                                            true,
                                            revision()});
485
    }
486 487
}

488
} // namespace Internal
489
} // namespace ClangCodeModel