File: clangproblem.cpp

package info (click to toggle)
kdevelop 4%3A5.3.1-3
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 52,544 kB
  • sloc: cpp: 254,897; python: 3,380; sh: 1,271; ansic: 657; xml: 221; php: 95; makefile: 36; lisp: 13; sed: 12
file content (271 lines) | stat: -rw-r--r-- 8,856 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
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
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
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
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
/*
 * Copyright 2014 Kevin Funk <kfunk@kde.org>
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 2 of
 * the License or (at your option) version 3 or any later version
 * accepted by the membership of KDE e.V. (or its successor approved
 * by the membership of KDE e.V.), which shall act as a proxy
 * defined in Section 14 of version 3 of the license.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

#include "clangproblem.h"
#include <interfaces/idocumentcontroller.h>
#include <interfaces/icore.h>

#include "util/clangtypes.h"
#include "util/clangdebug.h"

#include <language/duchain/duchainlock.h>
#include <language/codegen/documentchangeset.h>
#include <qtcompat_p.h>

#include <KLocalizedString>

using namespace KDevelop;

namespace {

IProblem::Severity diagnosticSeverityToSeverity(CXDiagnosticSeverity severity, const QString& optionName)
{
    switch (severity) {
    case CXDiagnostic_Fatal:
    case CXDiagnostic_Error:
        return IProblem::Error;
    case CXDiagnostic_Warning:
        if (optionName.startsWith(QLatin1String("-Wunused-"))) {
            return IProblem::Hint;
        }
        return IProblem::Warning;
        break;
    default:
        return IProblem::Hint;
    }
}

/**
 * Clang diagnostic messages always start with a lowercase character
 *
 * @return Prettified version, starting with uppercase character
 */
inline QString prettyDiagnosticSpelling(const QString& str)
{
    QString ret = str;
    if (ret.isEmpty()) {
      return {};
    }
    ret[0] = ret[0].toUpper();
    return ret;
}

ClangFixits fixitsForDiagnostic(CXDiagnostic diagnostic)
{
    ClangFixits fixits;
    auto numFixits = clang_getDiagnosticNumFixIts(diagnostic);
    fixits.reserve(numFixits);
    for (uint i = 0; i < numFixits; ++i) {
        CXSourceRange range;
        const QString replacementText = ClangString(clang_getDiagnosticFixIt(diagnostic, i, &range)).toString();

        const auto docRange = ClangRange(range).toDocumentRange();
        auto doc = KDevelop::ICore::self()->documentController()->documentForUrl(docRange.document.toUrl());
        const QString original = doc ? doc->text(docRange) : QString{};

        fixits << ClangFixit{replacementText, docRange, QString(), original};
    }
    return fixits;
}

}

QDebug operator<<(QDebug debug, const ClangFixit& fixit)
{
    debug.nospace() << "ClangFixit["
        << "replacementText=" << fixit.replacementText
        << ", range=" << fixit.range
        << ", description=" << fixit.description
        << "]";
    return debug;
}

ClangProblem::ClangProblem(CXDiagnostic diagnostic, CXTranslationUnit unit)
{
    const QString diagnosticOption = ClangString(clang_getDiagnosticOption(diagnostic, nullptr)).toString();

    auto severity = diagnosticSeverityToSeverity(clang_getDiagnosticSeverity(diagnostic), diagnosticOption);
    setSeverity(severity);

    QString description = ClangString(clang_getDiagnosticSpelling(diagnostic)).toString();
    if (!diagnosticOption.isEmpty()) {
        description.append(QLatin1String(" [") + diagnosticOption + QLatin1Char(']'));
    }
    setDescription(prettyDiagnosticSpelling(description));

    ClangLocation location(clang_getDiagnosticLocation(diagnostic));
    CXFile diagnosticFile;
    clang_getFileLocation(location, &diagnosticFile, nullptr, nullptr, nullptr);
    const ClangString fileName(clang_getFileName(diagnosticFile));
    DocumentRange docRange(IndexedString(QUrl::fromLocalFile(fileName.toString()).adjusted(QUrl::NormalizePathSegments)), KTextEditor::Range(location, location));
    const uint numRanges = clang_getDiagnosticNumRanges(diagnostic);
    for (uint i = 0; i < numRanges; ++i) {
        auto range = ClangRange(clang_getDiagnosticRange(diagnostic, i)).toRange();
        if(!range.isValid()){
            continue;
        }

        if (range.start() < docRange.start()) {
            docRange.setStart(range.start());
        }
        if (range.end() > docRange.end()) {
            docRange.setEnd(range.end());
        }
    }
    if (docRange.isEmpty()) {
        // try to find a bigger range for the given location by using the token at the given location
        CXFile file = nullptr;
        unsigned line = 0;
        unsigned column = 0;
        clang_getExpansionLocation(location, &file, &line, &column, nullptr);
        // just skip ahead some characters, hoping that it's sufficient to encompass
        // a token we can use for building the range
        auto nextLocation = clang_getLocation(unit, file, line, column + 100);
        auto rangeToTokenize = clang_getRange(location, nextLocation);
        const ClangTokens tokens(unit, rangeToTokenize);
        if (tokens.size()) {
            docRange.setRange(ClangRange(clang_getTokenExtent(unit, tokens.at(0))).toRange());
        }
    }

    setFixits(fixitsForDiagnostic(diagnostic));
    setFinalLocation(docRange);
    setSource(IProblem::SemanticAnalysis);

    QVector<IProblem::Ptr> diagnostics;
    auto childDiagnostics = clang_getChildDiagnostics(diagnostic);
    auto numChildDiagnostics = clang_getNumDiagnosticsInSet(childDiagnostics);
    diagnostics.reserve(numChildDiagnostics);
    for (uint j = 0; j < numChildDiagnostics; ++j) {
        auto childDiagnostic = clang_getDiagnosticInSet(childDiagnostics, j);
        ClangProblem::Ptr problem(new ClangProblem(childDiagnostic, unit));
        diagnostics << ProblemPointer(problem.data());
    }
    setDiagnostics(diagnostics);
}

IAssistant::Ptr ClangProblem::solutionAssistant() const
{
    if (allFixits().isEmpty()) {
        return {};
    }

    return IAssistant::Ptr(new ClangFixitAssistant(allFixits()));
}

ClangFixits ClangProblem::fixits() const
{
    return m_fixits;
}

void ClangProblem::setFixits(const ClangFixits& fixits)
{
    m_fixits = fixits;
}

ClangFixits ClangProblem::allFixits() const
{
    ClangFixits result;
    result << m_fixits;

    const auto& diagnostics = this->diagnostics();
    for (const IProblem::Ptr& diagnostic : diagnostics) {
        const Ptr problem(dynamic_cast<ClangProblem*>(diagnostic.data()));
        Q_ASSERT(problem);
        result << problem->allFixits();
    }
    return result;
}

ClangFixitAssistant::ClangFixitAssistant(const ClangFixits& fixits)
    : m_title(i18n("Fix-it Hints"))
    , m_fixits(fixits)
{
}

ClangFixitAssistant::ClangFixitAssistant(const QString& title, const ClangFixits& fixits)
    : m_title(title)
    , m_fixits(fixits)
{
}

QString ClangFixitAssistant::title() const
{
    return m_title;
}

void ClangFixitAssistant::createActions()
{
    KDevelop::IAssistant::createActions();

    for (const ClangFixit& fixit : qAsConst(m_fixits)) {
        addAction(IAssistantAction::Ptr(new ClangFixitAction(fixit)));
    }
}

ClangFixits ClangFixitAssistant::fixits() const
{
    return m_fixits;
}

ClangFixitAction::ClangFixitAction(const ClangFixit& fixit)
    : m_fixit(fixit)
{
}

QString ClangFixitAction::description() const
{
    if (!m_fixit.description.isEmpty())
        return m_fixit.description;

    const auto range = m_fixit.range;
    if (range.start() == range.end()) {
        return i18n("Insert \"%1\" at line: %2, column: %3",
                    m_fixit.replacementText, range.start().line()+1, range.start().column()+1);
    } else if (range.start().line() == range.end().line()) {
        if (m_fixit.currentText.isEmpty()) {
            return i18n("Replace text at line: %1, column: %2 with: \"%3\"",
                    range.start().line()+1, range.start().column()+1, m_fixit.replacementText);
        } else
            return i18n("Replace \"%1\" with: \"%2\"",
                    m_fixit.currentText, m_fixit.replacementText);
    } else {
        return i18n("Replace multiple lines starting at line: %1, column: %2 with: \"%3\"",
                    range.start().line()+1, range.start().column()+1, m_fixit.replacementText);
    }
}

void ClangFixitAction::execute()
{
    DocumentChangeSet changes;
    {
        DUChainReadLocker lock;

        DocumentChange change(m_fixit.range.document, m_fixit.range,
                    m_fixit.currentText, m_fixit.replacementText);
        change.m_ignoreOldText = !m_fixit.currentText.isEmpty();
        changes.addChange(change);
    }

    changes.setReplacementPolicy(DocumentChangeSet::WarnOnFailedChange);
    changes.applyAllChanges();
    emit executed(this);
}