clangdiagnosticmanager.cpp 13.3 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 "clangdiagnosticfilter.h"
#include "clangdiagnosticmanager.h"
28
#include "clangisdiagnosticrelatedtolocation.h"
29

30 31 32 33 34
#include <coreplugin/actionmanager/actionmanager.h>
#include <coreplugin/actionmanager/command.h>

#include <cpptools/cpptoolsconstants.h>

35
#include <texteditor/convenience.h>
36
#include <texteditor/fontsettings.h>
37
#include <texteditor/textdocument.h>
38
#include <texteditor/texteditorsettings.h>
39 40

#include <utils/fileutils.h>
41
#include <utils/proxyaction.h>
42 43
#include <utils/qtcassert.h>

44 45
#include <QTextBlock>

46 47 48
namespace  {

QTextEdit::ExtraSelection createExtraSelections(const QTextCharFormat &mainformat,
49
                                                const QTextCursor &cursor)
50 51 52 53 54 55 56 57 58
{
    QTextEdit::ExtraSelection extraSelection;

    extraSelection.format = mainformat;
    extraSelection.cursor = cursor;

    return extraSelection;
}

59 60 61 62 63 64 65 66
int positionInText(QTextDocument *textDocument,
                   const ClangBackEnd::SourceLocationContainer &sourceLocationContainer)
{
    auto textBlock = textDocument->findBlockByNumber(int(sourceLocationContainer.line()) - 1);

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

67 68
void addRangeSelections(const ClangBackEnd::DiagnosticContainer &diagnostic,
                        QTextDocument *textDocument,
69
                        const QTextCharFormat &contextFormat,
70 71 72 73
                        QList<QTextEdit::ExtraSelection> &extraSelections)
{
    for (auto &&range : diagnostic.ranges()) {
        QTextCursor cursor(textDocument);
74 75
        cursor.setPosition(positionInText(textDocument, range.start()));
        cursor.setPosition(positionInText(textDocument, range.end()), QTextCursor::KeepAnchor);
76

77
        auto extraSelection = createExtraSelections(contextFormat, cursor);
78 79 80 81 82

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

83 84
QTextCursor createSelectionCursor(QTextDocument *textDocument,
                                  const ClangBackEnd::SourceLocationContainer &sourceLocationContainer)
85 86
{
    QTextCursor cursor(textDocument);
87
    cursor.setPosition(positionInText(textDocument, sourceLocationContainer));
88 89 90
    cursor.movePosition(QTextCursor::EndOfWord, QTextCursor::KeepAnchor);

    if (!cursor.hasSelection()) {
91
        cursor.setPosition(positionInText(textDocument, sourceLocationContainer) - 1);
92 93 94 95 96 97 98 99 100
        cursor.movePosition(QTextCursor::Right, QTextCursor::KeepAnchor, 2);
    }

    return cursor;
}

void addSelections(const QVector<ClangBackEnd::DiagnosticContainer> &diagnostics,
                   QTextDocument *textDocument,
                   const QTextCharFormat &mainFormat,
101
                   const QTextCharFormat &contextFormat,
102 103 104
                   QList<QTextEdit::ExtraSelection> &extraSelections)
{
    for (auto &&diagnostic : diagnostics) {
105
        auto cursor = createSelectionCursor(textDocument, diagnostic.location());
106
        auto extraSelection = createExtraSelections(mainFormat, cursor);
107

108
        addRangeSelections(diagnostic, textDocument, contextFormat, extraSelections);
109 110 111 112 113 114 115 116 117

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

void addWarningSelections(const QVector<ClangBackEnd::DiagnosticContainer> &diagnostics,
                          QTextDocument *textDocument,
                          QList<QTextEdit::ExtraSelection> &extraSelections)
{
118
    const auto fontSettings = TextEditor::TextEditorSettings::instance()->fontSettings();
119

120
    QTextCharFormat warningFormat = fontSettings.toTextCharFormat(TextEditor::C_WARNING);
121

122 123 124
    QTextCharFormat warningContextFormat = fontSettings.toTextCharFormat(TextEditor::C_WARNING_CONTEXT);

    addSelections(diagnostics, textDocument, warningFormat, warningContextFormat, extraSelections);
125 126 127 128 129 130
}

void addErrorSelections(const QVector<ClangBackEnd::DiagnosticContainer> &diagnostics,
                        QTextDocument *textDocument,
                        QList<QTextEdit::ExtraSelection> &extraSelections)
{
131
    const auto fontSettings = TextEditor::TextEditorSettings::instance()->fontSettings();
132

133 134
    QTextCharFormat errorFormat = fontSettings.toTextCharFormat(TextEditor::C_ERROR);
    QTextCharFormat errorContextFormat = fontSettings.toTextCharFormat(TextEditor::C_ERROR_CONTEXT);
135

136
    addSelections(diagnostics, textDocument, errorFormat, errorContextFormat, extraSelections);
137 138
}

139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 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
ClangBackEnd::SourceLocationContainer toSourceLocation(QTextDocument *textDocument, int position)
{
    int line, column;
    if (TextEditor::Convenience::convertPosition(textDocument, position, &line, &column))
        return ClangBackEnd::SourceLocationContainer(Utf8String(), line, column);

    return ClangBackEnd::SourceLocationContainer();
}

ClangBackEnd::SourceRangeContainer toSourceRange(const QTextCursor &cursor)
{
    using namespace ClangBackEnd;

    QTextDocument *textDocument = cursor.document();

    return SourceRangeContainer(toSourceLocation(textDocument, cursor.anchor()),
                                toSourceLocation(textDocument, cursor.position()));
}

bool isDiagnosticAtLocation(const ClangBackEnd::DiagnosticContainer &diagnostic,
                            uint line,
                            uint column,
                            QTextDocument *textDocument)
{
    using namespace ClangCodeModel::Internal;

    const ClangBackEnd::SourceLocationContainer &location = diagnostic.location();
    const QTextCursor cursor = createSelectionCursor(textDocument, location);
    const ClangBackEnd::SourceRangeContainer cursorRange = toSourceRange(cursor);

    return isDiagnosticRelatedToLocation(diagnostic, {cursorRange}, line, column);
}

QVector<ClangBackEnd::DiagnosticContainer>
filteredDiagnosticsAtLocation(const QVector<ClangBackEnd::DiagnosticContainer> &diagnostics,
                              uint line,
                              uint column,
                              QTextDocument *textDocument)
{
    QVector<ClangBackEnd::DiagnosticContainer> filteredDiagnostics;

    foreach (const auto &diagnostic, diagnostics) {
        if (isDiagnosticAtLocation(diagnostic, line, column, textDocument))
            filteredDiagnostics.append(diagnostic);
    }

    return filteredDiagnostics;
}

bool editorDocumentProcessorHasDiagnosticAt(
        const QVector<ClangBackEnd::DiagnosticContainer> &diagnostics,
        uint line,
        uint column,
        QTextDocument *textDocument)
{
    foreach (const auto &diagnostic, diagnostics) {
        if (isDiagnosticAtLocation(diagnostic, line, column, textDocument))
            return true;
    }

    return false;
}

202 203 204 205 206 207 208 209 210 211 212 213 214 215 216
QTextCursor cursorAtLastPositionOfLine(QTextDocument *textDocument, int lineNumber)
{
    const QTextBlock textBlock = textDocument->findBlockByNumber(lineNumber - 1);
    QTC_ASSERT(textBlock.isValid(), return QTextCursor());

    const int lastPositionOfLine = textBlock.position() + textBlock.length() - 1;

    QTextCursor textCursor(textDocument);
    textCursor.setPosition(lastPositionOfLine);

    return textCursor;
}

QString tooltipForFixItAvailableMarker()
{
Takumi ASAKI's avatar
Takumi ASAKI committed
217
    QString text = QCoreApplication::translate("ClangCodeModel::Internal::ClangDiagnosticManager", "Inspect available fixits");
218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235

    Core::Command *command = Core::ActionManager::command(TextEditor::Constants::QUICKFIX_THIS);
    if (command)
        text = Utils::ProxyAction::stringWithAppendedShortcut(text, command->keySequence());

    return text;
}

TextEditor::RefactorMarker createFixItAvailableMarker(QTextDocument *textDocument, int lineNumber)
{
    TextEditor::RefactorMarker marker;
    marker.tooltip = tooltipForFixItAvailableMarker();
    marker.cursor = cursorAtLastPositionOfLine(textDocument, lineNumber);
    marker.data = QLatin1String(CppTools::Constants::CPP_CLANG_FIXIT_AVAILABLE_MARKER_ID);

    return marker;
}

236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254
} // anonymous

namespace ClangCodeModel {
namespace Internal {

ClangDiagnosticManager::ClangDiagnosticManager(TextEditor::TextDocument *textDocument)
    : m_textDocument(textDocument)
{
}

void ClangDiagnosticManager::generateTextMarks()
{
    m_clangTextMarks.clear();
    m_clangTextMarks.reserve(m_warningDiagnostics.size() + m_errorDiagnostics.size());

    addClangTextMarks(m_warningDiagnostics);
    addClangTextMarks(m_errorDiagnostics);
}

255 256 257 258 259 260 261 262 263
void ClangDiagnosticManager::generateFixItAvailableMarkers()
{
    m_fixItAvailableMarkers.clear();

    QSet<int> lineNumbersWithFixItMarker;
    addFixItAvailableMarker(m_warningDiagnostics, lineNumbersWithFixItMarker);
    addFixItAvailableMarker(m_errorDiagnostics, lineNumbersWithFixItMarker);
}

264 265 266 267 268 269 270 271 272
QList<QTextEdit::ExtraSelection> ClangDiagnosticManager::takeExtraSelections()
{
    auto extraSelections = m_extraSelections;

    m_extraSelections.clear();

    return extraSelections;
}

273 274 275 276 277 278 279 280 281
TextEditor::RefactorMarkers ClangDiagnosticManager::takeFixItAvailableMarkers()
{
    TextEditor::RefactorMarkers fixItAvailableMarkers = m_fixItAvailableMarkers;

    m_fixItAvailableMarkers.clear();

    return fixItAvailableMarkers;
}

282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301
bool ClangDiagnosticManager::hasDiagnosticsAt(uint line, uint column) const
{
    QTextDocument *textDocument = m_textDocument->document();

    return editorDocumentProcessorHasDiagnosticAt(m_errorDiagnostics, line, column, textDocument)
        || editorDocumentProcessorHasDiagnosticAt(m_warningDiagnostics, line, column, textDocument);
}

QVector<ClangBackEnd::DiagnosticContainer>
ClangDiagnosticManager::diagnosticsAt(uint line, uint column) const
{
    QTextDocument *textDocument = m_textDocument->document();

    QVector<ClangBackEnd::DiagnosticContainer> diagnostics;
    diagnostics += filteredDiagnosticsAtLocation(m_errorDiagnostics, line, column, textDocument);
    diagnostics += filteredDiagnosticsAtLocation(m_warningDiagnostics, line, column, textDocument);

    return diagnostics;
}

302 303 304 305 306
void ClangDiagnosticManager::clearDiagnosticsWithFixIts()
{
    m_fixItdiagnostics.clear();
}

307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322
void ClangDiagnosticManager::generateEditorSelections()
{
    m_extraSelections.clear();
    m_extraSelections.reserve(int(m_warningDiagnostics.size() + m_errorDiagnostics.size()));

    addWarningSelections(m_warningDiagnostics, m_textDocument->document(), m_extraSelections);
    addErrorSelections(m_errorDiagnostics, m_textDocument->document(), m_extraSelections);
}

void ClangDiagnosticManager::processNewDiagnostics(
        const QVector<ClangBackEnd::DiagnosticContainer> &allDiagnostics)
{
    filterDiagnostics(allDiagnostics);

    generateTextMarks();
    generateEditorSelections();
323
    generateFixItAvailableMarkers();
324 325
}

326 327 328 329 330 331
const QVector<ClangBackEnd::DiagnosticContainer> &
ClangDiagnosticManager::diagnosticsWithFixIts() const
{
    return m_fixItdiagnostics;
}

332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349
void ClangDiagnosticManager::addClangTextMarks(
        const QVector<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(m_textDocument);

        m_textDocument->addMark(&textMark);
    }
}

350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367
void ClangDiagnosticManager::addFixItAvailableMarker(
        const QVector<ClangBackEnd::DiagnosticContainer> &diagnostics,
        QSet<int> &lineNumbersWithFixItMarker)
{
    for (auto &&diagnostic : diagnostics) {
        const int line = int(diagnostic.location().line());
        if (!diagnostic.fixIts().isEmpty() && !lineNumbersWithFixItMarker.contains(line)) {
            const TextEditor::RefactorMarker marker
                    = createFixItAvailableMarker(m_textDocument->document(), line);

            lineNumbersWithFixItMarker.insert(line);
            m_fixItAvailableMarkers.append(marker);
        }

        addFixItAvailableMarker(diagnostic.children(), lineNumbersWithFixItMarker);
    }
}

368 369 370 371 372 373 374 375 376 377 378 379 380
QString ClangDiagnosticManager::filePath() const
{
    return m_textDocument->filePath().toString();
}

void ClangDiagnosticManager::filterDiagnostics(
        const QVector<ClangBackEnd::DiagnosticContainer> &diagnostics)
{
    ClangDiagnosticFilter filter(filePath());
    filter.filter(diagnostics);

    m_warningDiagnostics = filter.takeWarnings();
    m_errorDiagnostics = filter.takeErrors();
381
    m_fixItdiagnostics = filter.takeFixIts();
382 383 384 385
}

} // namespace Internal
} // namespace ClangCodeModel