aboutsummaryrefslogtreecommitdiffstats
path: root/sources/shiboken6/ApiExtractor/clangparser/clangparser.cpp
blob: da6930476cd2bd19d97ccc991b917c73406415b7 (plain)
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
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
// Copyright (C) 2017 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0

#include "clangparser.h"
#include "clangutils.h"
#include "clangdebugutils.h"
#include "compilersupport.h"

#include <QtCore/QByteArrayList>
#include <QtCore/QDebug>
#include <QtCore/QDir>
#include <QtCore/QFile>
#include <QtCore/QScopedArrayPointer>
#include <QtCore/QString>

using namespace Qt::StringLiterals;

namespace clang {

QString SourceFileCache::getFileName(CXFile file)
{
    auto it = m_fileNameCache.find(file);
    if (it == m_fileNameCache.end())
        it = m_fileNameCache.insert(file, clang::getFileName(file));
    return it.value();
}

std::string_view SourceFileCache::getCodeSnippet(const CXCursor &cursor,
                                                 QString *errorMessage)
{
    static const char empty[] = "";

    if (errorMessage)
        errorMessage->clear();

    const SourceRange range = getCursorRange(cursor);
    // Quick check for equal locations: Frequently happens if the code is
    // the result of a macro expansion
    if (range.first == range.second)
         return std::string_view(empty, 0);

    if (range.first.file != range.second.file) {
        if (errorMessage)
            *errorMessage = "Range spans several files"_L1;
        return std::string_view(empty, 0);
    }

    auto it = m_fileBufferCache.find(range.first.file);
    if (it == m_fileBufferCache.end()) {
        const QString fileName = getFileName(range.first.file);
        if (fileName.isEmpty()) {
            if (errorMessage)
                 *errorMessage = "Range has no file"_L1;
            return std::string_view(empty, 0);
        }
        QFile file(fileName);
        if (!file.open(QIODevice::ReadOnly)) {
            if (errorMessage) {
                QTextStream str(errorMessage);
                str << "Cannot open \"" << QDir::toNativeSeparators(fileName)
                    << "\": " << file.errorString();
            }
            return std::string_view(empty, 0);
        }
        it = m_fileBufferCache.insert(range.first.file, file.readAll());
    }

    const unsigned pos = range.first.offset;
    const unsigned end = range.second.offset;
    Q_ASSERT(end > pos);
    const QByteArray &contents = it.value();
    if (end >= unsigned(contents.size())) {
        if (errorMessage) {
            QTextStream str(errorMessage);
            str << "Range end " << end << " is above size of \""
                << QDir::toNativeSeparators(getFileName(range.first.file))
                << "\" (" << contents.size() << ')';
        }
        return std::string_view(empty, 0);
    }

    return std::string_view(contents.constData() + pos, end - pos);
}

BaseVisitor::BaseVisitor() = default;
BaseVisitor::~BaseVisitor() = default;

bool BaseVisitor::visitLocation(const QString &, LocationType locationType) const
{
    return locationType != LocationType::System;
}

BaseVisitor::StartTokenResult BaseVisitor::cbHandleStartToken(const CXCursor &cursor)
{
    switch (cursor.kind) {
    default:
        break;
    }

    return startToken(cursor);
}

bool BaseVisitor::cbHandleEndToken(const CXCursor &cursor, StartTokenResult startResult)
{
    const bool result = startResult != Recurse || endToken(cursor);
    switch (cursor.kind) {
    default:
        break;
    }

    return result;
}

std::string_view BaseVisitor::getCodeSnippet(const CXCursor &cursor)
{
    QString errorMessage;
    const std::string_view result = m_fileCache.getCodeSnippet(cursor, &errorMessage);
    if (result.empty() && !errorMessage.isEmpty()) {
        QString message;
        QTextStream str(&message);
        str << "Unable to retrieve code snippet \"" << getCursorSpelling(cursor)
            << "\": " << errorMessage;
        appendDiagnostic(Diagnostic(message, cursor, CXDiagnostic_Error));
    }
    return result;
}

bool BaseVisitor::_handleVisitLocation(const CXSourceLocation &location)
{
    CXFile cxFile; // void *
    unsigned line;
    unsigned column;
    unsigned offset;
    clang_getExpansionLocation(location, &cxFile, &line, &column, &offset);

    if (cxFile == m_currentCxFile) // Same file?
        return m_visitCurrent;

    const QString fileName = getFileName(cxFile);

    LocationType locationType = LocationType::Unknown;
    if (!fileName.isEmpty()) {
        if (clang_Location_isFromMainFile(location) != 0)
            locationType = LocationType::Main;
        else if (clang_Location_isInSystemHeader(location) != 0)
            locationType = LocationType::System;
        else
            locationType = LocationType::Other;
    }

    m_currentCxFile = cxFile;
    m_visitCurrent = visitLocation(fileName, locationType);
    return m_visitCurrent;
}

QString BaseVisitor::getCodeSnippetString(const CXCursor &cursor)
{
    const std::string_view result = getCodeSnippet(cursor);
    return result.empty()
        ? QString()
        : QString::fromUtf8(result.data(), qsizetype(result.size()));
}

static CXChildVisitResult
    visitorCallback(CXCursor cursor, CXCursor /* parent */, CXClientData clientData)
{
    auto *bv = reinterpret_cast<BaseVisitor *>(clientData);

    const CXSourceLocation location = clang_getCursorLocation(cursor);
    if (!bv->_handleVisitLocation(location))
        return CXChildVisit_Continue;

    const BaseVisitor::StartTokenResult startResult = bv->cbHandleStartToken(cursor);
    switch (startResult) {
    case clang::BaseVisitor::Error:
        return CXChildVisit_Break;
    case clang::BaseVisitor::Skip:
        break;
    case clang::BaseVisitor::Recurse:
        clang_visitChildren(cursor, visitorCallback, clientData);
        break;
    }

    if (!bv->cbHandleEndToken(cursor, startResult))
        return CXChildVisit_Break;

    return CXChildVisit_Continue;
}

BaseVisitor::Diagnostics BaseVisitor::diagnostics() const
{
    return m_diagnostics;
}

void BaseVisitor::setDiagnostics(const Diagnostics &d)
{
    m_diagnostics = d;
}

void BaseVisitor::appendDiagnostic(const Diagnostic &d)
{
    m_diagnostics.append(d);
}

static inline const char **byteArrayListToFlatArgV(const QByteArrayList &bl)
{
    const char **result = new const char *[bl.size() + 1];
    result[bl.size()] = nullptr;
    std::transform(bl.cbegin(), bl.cend(), result,
                   [] (const QByteArray &a) { return a.constData(); });
    return result;
}

static QByteArray msgCreateTranslationUnit(const QByteArrayList &clangArgs, unsigned flags)
{
    QByteArray result = "clang_parseTranslationUnit2(0x";
    result += QByteArray::number(flags, 16);
    const auto count = clangArgs.size();
    result += ", cmd[" + QByteArray::number(count) + "]=";
    for (qsizetype i = 0; i < count; ++i) {
        const QByteArray &arg = clangArgs.at(i);
        if (i)
            result += ' ';
        const bool quote = arg.contains(' ') || arg.contains('(');
        if (quote)
            result += '"';
        result += arg;
        if (quote)
            result += '"';
    }
    result += ')';
    return result;
}

static CXTranslationUnit createTranslationUnit(CXIndex index,
                                               const QByteArrayList &args,
                                               bool addCompilerSupportArguments,
                                               unsigned flags = 0)
{
    // courtesy qdoc
    const unsigned defaultFlags = CXTranslationUnit_Incomplete;

    static const QByteArrayList defaultArgs = {
#ifndef Q_OS_WIN
        "-fPIC",
#endif
#ifdef Q_OS_MACOS
        "-Wno-expansion-to-defined", // Workaround for warnings in Darwin stdlib, see
                                     // https://github.com/darlinghq/darling/issues/204
#endif
        "-Wno-constant-logical-operand",
        "-x",
        "c++" // Treat .h as C++, not C
    };

    QByteArrayList clangArgs;
    if (addCompilerSupportArguments) {
        clangArgs += emulatedCompilerOptions();
        clangArgs += defaultArgs;
    }
    clangArgs += detectVulkan();
    clangArgs += args;
    QScopedArrayPointer<const char *> argv(byteArrayListToFlatArgV(clangArgs));
    qDebug().noquote().nospace() << msgCreateTranslationUnit(clangArgs, flags);

    CXTranslationUnit tu;
    CXErrorCode err = clang_parseTranslationUnit2(index, nullptr, argv.data(),
                                                  clangArgs.size(), nullptr, 0,
                                                  defaultFlags | flags, &tu);
    if (err || !tu) {
        qWarning().noquote().nospace() << "Could not parse "
            << clangArgs.constLast().constData() << ", error code: " << err;
        return nullptr;
    }
    return tu;
}

/* clangFlags are flags to clang_parseTranslationUnit2() such as
 * CXTranslationUnit_KeepGoing (from CINDEX_VERSION_MAJOR/CINDEX_VERSION_MINOR 0.35)
 */

bool parse(const QByteArrayList  &clangArgs, bool addCompilerSupportArguments,
           unsigned clangFlags, BaseVisitor &bv)
{
    CXIndex index = clang_createIndex(0 /* excludeDeclarationsFromPCH */,
                                      1 /* displayDiagnostics */);
    if (!index) {
        qWarning() << "clang_createIndex() failed!";
        return false;
    }

    CXTranslationUnit translationUnit =
        createTranslationUnit(index, clangArgs, addCompilerSupportArguments,
                              clangFlags);
    if (!translationUnit)
        return false;

    CXCursor rootCursor = clang_getTranslationUnitCursor(translationUnit);

    clang_visitChildren(rootCursor, visitorCallback, reinterpret_cast<CXClientData>(&bv));

    QList<Diagnostic> diagnostics = getDiagnostics(translationUnit);
    diagnostics.append(bv.diagnostics());
    bv.setDiagnostics(diagnostics);

    const bool ok = maxSeverity(diagnostics) < CXDiagnostic_Error;
    if (!ok) {
        QDebug debug = qWarning();
        debug.noquote();
        debug.nospace();
        debug << "Errors in "
            << QDir::toNativeSeparators(QFile::decodeName(clangArgs.constLast())) << ":\n";
        for (const Diagnostic &diagnostic : std::as_const(diagnostics))
            debug << diagnostic << '\n';
    }

    clang_disposeTranslationUnit(translationUnit);
    clang_disposeIndex(index);
    return ok;
}

} // namespace clang