aboutsummaryrefslogtreecommitdiffstats
path: root/src/tools/clangbackend/source/clangtooltipinfocollector.cpp
blob: 0d001ca3d4df042d66f9be02070998ab1849dd73 (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
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
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
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
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
/****************************************************************************
**
** Copyright (C) 2018 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** 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
** 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.
**
** 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.
**
****************************************************************************/

#include "clangtooltipinfocollector.h"

#include "clangbackend_global.h"
#include "clangstring.h"
#include "cursor.h"
#include "sourcerange.h"
#include "token.h"
#include "unsavedfiles.h"
#include "unsavedfile.h"

#include <clangsupport/sourcerangecontainer.h>
#include <utils/qtcassert.h>
#include <utils/textfileformat.h>
#include <utils/qtcassert.h>

#include <utf8string.h>

#include <QDebug>
#include <QDir>
#include <QTextCodec>

namespace ClangBackEnd {

Utf8String qualificationPrefix(const Cursor &cursor)
{
    // TODO: Implement with qualificationPrefixAsVector()
    Utf8String qualifiedName;

    for (Cursor parent = cursor.semanticParent();
         parent.isValid() && (parent.kind() == CXCursor_Namespace);
         parent = parent.semanticParent()) {
        qualifiedName = parent.spelling() + Utf8StringLiteral("::") + qualifiedName;
    }

    return qualifiedName;
}

namespace {

Utf8StringVector qualificationPrefixAsVector(const Cursor &cursor)
{
    Utf8StringVector result;

    for (Cursor parent = cursor.semanticParent();
         parent.isValid() && (parent.kind() == CXCursor_Namespace || parent.isCompoundType());
         parent = parent.semanticParent()) {
        result.prepend(parent.spelling());
    }

    return result;
}

Utf8String displayName(const Cursor &cursor)
{
    if (cursor.kind() == CXCursor_ClassTemplate) {
        // TODO: The qualification should be part of the display name. Fix this in libclang.
        return qualificationPrefix(cursor) + cursor.displayName();
    }

    return cursor.displayName();
}

Utf8String textForFunctionLike(const Cursor &cursor)
{
    CXPrintingPolicy policy = clang_getCursorPrintingPolicy(cursor.cx());
    clang_PrintingPolicy_setProperty(policy, CXPrintingPolicy_FullyQualifiedName, 1);
    clang_PrintingPolicy_setProperty(policy, CXPrintingPolicy_TerseOutput, 1);
    // Avoid printing attributes/pragmas
    clang_PrintingPolicy_setProperty(policy, CXPrintingPolicy_PolishForDeclaration, 1);
    clang_PrintingPolicy_setProperty(policy, CXPrintingPolicy_SuppressInitializers, 1);
    const Utf8String prettyPrinted = ClangString(
        clang_getCursorPrettyPrinted(cursor.cx(), policy));
    clang_PrintingPolicy_dispose(policy);
    return prettyPrinted;
}

Utf8String textForEnumConstantDecl(const Cursor &cursor)
{
    const Cursor semanticParent = cursor.semanticParent();
    QTC_ASSERT(semanticParent.kind() == CXCursor_EnumDecl, return Utf8String());

    const Type enumType = semanticParent.enumType();
    if (enumType.isUnsigned())
        return Utf8String::number(cursor.enumConstantUnsignedValue());
    return Utf8String::number(cursor.enumConstantValue());
}

Utf8String textForInclusionDirective(const Cursor &cursor)
{
    const CXFile includedFile = cursor.includedFile();
    const Utf8String fileName = ClangString(clang_getFileName(includedFile));

    return QDir::toNativeSeparators(fileName.toString());
}

Utf8String textForAnyTypeAlias(const Cursor &cursor)
{
    // For a CXCursor_TypeAliasTemplateDecl the type of cursor/referenced
    // is invalid, so we do not get the underlying type. This here solely
    // reports the unresolved name instead of the empty string.
    if (cursor.kind() == CXCursor_TypeAliasTemplateDecl)
        return cursor.displayName();

    return cursor.type().alias().utf8Spelling();
}

bool includeSizeForCursor(const Cursor &cursor)
{
    return cursor.isCompoundType()
        || cursor.kind() == CXCursor_EnumDecl
        || cursor.kind() == CXCursor_UnionDecl
        || cursor.kind() == CXCursor_FieldDecl;
}

Utf8String sizeInBytes(const Cursor &cursor)
{
    if (includeSizeForCursor(cursor)) {
        bool ok = false;
        const long long size = cursor.type().sizeOf(&ok);
        if (ok)
            return Utf8String::number(size);
    }

    return Utf8String();
}

Cursor referencedCursor(const Cursor &cursor)
{
    // Query the referenced cursor directly instead of first testing with cursor.isReference().
    // cursor.isReference() reports false for e.g. CXCursor_DeclRefExpr or CXCursor_CallExpr
    // although it returns a valid cursor.
    const Cursor referenced = cursor.referenced();
    if (referenced.isValid())
        return referenced;

    const Cursor definition = cursor.definition();
    if (definition.isValid())
        return definition;

    return cursor;
}

class ToolTipInfoCollector
{
public:
    ToolTipInfoCollector(UnsavedFiles &unsavedFiles,
                         const Utf8String &textCodecName,
                         const Utf8String &mainFilePath,
                         CXTranslationUnit cxTranslationUnit);

    ToolTipInfo collect(uint line, uint column) const;

private:
    Utf8String text(const Cursor &cursor, const Cursor &referenced) const;
    Utf8String textForMacroExpansion(const Cursor &cursor) const;
    Utf8String textForNamespaceAlias(const Cursor &cursor) const;

    ToolTipInfo qDocInfo(const Cursor &cursor) const;

    CXSourceLocation toCXSourceLocation(uint line, uint column) const;

    UnsavedFile unsavedFile(const Utf8String &filePath) const;
    Utf8String lineRange(const Utf8String &filePath, unsigned fromLine, unsigned toLine) const;

private:
    UnsavedFiles &m_unsavedFiles;
    const Utf8String m_textCodecName;

    const Utf8String m_mainFilePath;
    CXTranslationUnit m_cxTranslationUnit = nullptr;

};

ToolTipInfoCollector::ToolTipInfoCollector(UnsavedFiles &unsavedFiles,
                                           const Utf8String &textCodecName,
                                           const Utf8String &mainFilePath,
                                           CXTranslationUnit cxTranslationUnit)
    : m_unsavedFiles(unsavedFiles)
    , m_textCodecName(textCodecName)
    , m_mainFilePath(mainFilePath)
    , m_cxTranslationUnit(cxTranslationUnit)
{
}

Utf8String ToolTipInfoCollector::text(const Cursor &cursor, const Cursor &referenced) const
{
    if (cursor.kind() == CXCursor_MacroExpansion)
        return textForMacroExpansion(referenced);

    if (referenced.kind() == CXCursor_EnumConstantDecl)
        return textForEnumConstantDecl(referenced);

    if (referenced.kind() == CXCursor_InclusionDirective)
        return textForInclusionDirective(referenced);

    if (referenced.kind() == CXCursor_Namespace)
        return qualificationPrefix(referenced) + referenced.spelling();

    if (referenced.kind() == CXCursor_NamespaceAlias)
        return textForNamespaceAlias(referenced);

    if (referenced.isAnyTypeAlias())
        return textForAnyTypeAlias(referenced);

    if (referenced.isFunctionLike() || referenced.kind() == CXCursor_Constructor)
        return textForFunctionLike(referenced);

    if (referenced.type().canonical().isBuiltinType())
        return referenced.type().canonical().builtinTypeToString();

    if (referenced.kind() == CXCursor_VarDecl)
        return referenced.type().spelling(); // e.g. "Zii<int>"

    const Type referencedType = referenced.type();
    if (referencedType.isValid()) {
        // Generally, the type includes the qualification but has this limitations:
        //  * namespace aliases are not resolved
        //  * outer class of a inner template class is not included
        // The type includes the qualification, but not resolved namespace aliases.

        // For a CXType_Record, this also includes e.g. "const " as prefix.
        return referencedType.canonical().utf8Spelling();
    }

    return displayName(referenced);
}

Utf8String ToolTipInfoCollector::textForMacroExpansion(const Cursor &cursor) const
{
    QTC_ASSERT(cursor.kind() == CXCursor_MacroDefinition, return Utf8String());

    const SourceRange sourceRange = cursor.sourceRange();
    const SourceLocation start = sourceRange.start();
    const SourceLocation end = sourceRange.end();

    return lineRange(start.filePath(), start.line(), end.line());
}

Utf8String ToolTipInfoCollector::textForNamespaceAlias(const Cursor &cursor) const
{
    // TODO: Add some libclang API to get the aliased name straight away.

    const Tokens tokens(cursor.sourceRange());

    Utf8String aliasedName;
    // Start at 3 in order to skip these tokens: namespace X =
    for (uint i = 3; i < tokens.size(); ++i)
        aliasedName += tokens[i].spelling();

    return aliasedName;
}

static Utf8String typeName(const Type &type)
{
    return type.declaration().spelling();
}

static Utf8String qdocMark(const Cursor &cursor)
{
    if (cursor.kind() == CXCursor_ClassTemplate)
        return cursor.spelling();

    if (cursor.type().kind() == CXType_Enum
            || cursor.type().kind() == CXType_Typedef
            || cursor.type().kind() == CXType_Record)
        return typeName(cursor.type());

    Utf8String text = cursor.displayName();
    if (cursor.kind() == CXCursor_FunctionDecl) {
        // TODO: Remove this workaround by fixing this in
        // libclang with the help of CXPrintingPolicy.
        text.replace(Utf8StringLiteral("<>"), Utf8String());
    }

    return text;
}

static ToolTipInfo::QdocCategory qdocCategory(const Cursor &cursor)
{
    if (cursor.isFunctionLike())
        return ToolTipInfo::Function;

    if (cursor.kind() == CXCursor_MacroDefinition)
        return ToolTipInfo::Macro;

    if (cursor.kind() == CXCursor_EnumConstantDecl)
        return ToolTipInfo::Enum;

    if (cursor.type().kind() == CXType_Enum)
        return ToolTipInfo::Enum;

    if (cursor.kind() == CXCursor_InclusionDirective)
        return ToolTipInfo::Brief;

    // TODO: Handle CXCursor_NamespaceAlias, too?!
    if (cursor.kind() == CXCursor_Namespace)
        return ToolTipInfo::ClassOrNamespace;

    if (cursor.isCompoundType())
        return ToolTipInfo::ClassOrNamespace;

    if (cursor.kind() == CXCursor_NamespaceAlias)
        return ToolTipInfo::ClassOrNamespace;

    if (cursor.type().kind() == CXType_Typedef)
        return ToolTipInfo::Typedef;

    if (cursor.type().kind() == CXType_Record)
        return ToolTipInfo::ClassOrNamespace;

    if (cursor.kind() == CXCursor_TypeAliasTemplateDecl)
        return ToolTipInfo::Typedef;

    if (cursor.kind() == CXCursor_ClassTemplate)
        return ToolTipInfo::ClassOrNamespace;

    return ToolTipInfo::Unknown;
}

static Utf8String name(const Cursor &cursor)
{
    if (cursor.type().kind() == CXType_Record || cursor.kind() == CXCursor_EnumDecl)
        return typeName(cursor.type());

    return cursor.spelling();
}

static Utf8StringVector qDocIdCandidates(const Cursor &cursor)
{
    Utf8StringVector components = qualificationPrefixAsVector(cursor);
    if (components.isEmpty())
        return { name(cursor) };

    components << name(cursor);
    Utf8StringVector result;
    Utf8String name;
    for (auto it = components.rbegin(); it != components.rend(); ++it) {
        if (name.isEmpty())
            name = *it;
        else
            name = *it + (Utf8StringLiteral("::") + name);

        result.prepend(name);
    }

    return result;
}

// TODO: Add libclang API for this?!
static bool isBuiltinOrPointerToBuiltin(const Type &type)
{
    Type theType = type;

    if (theType.isBuiltinType())
        return true;

    // TODO: Simplify
    // TODO: Test with **
    while (theType.pointeeType().isValid() && theType != theType.pointeeType()) {
        theType = theType.pointeeType();
        if (theType.isBuiltinType())
            return true;
    }

    return false;
}

ToolTipInfo ToolTipInfoCollector::qDocInfo(const Cursor &cursor) const
{
    ToolTipInfo result;

    if (isBuiltinOrPointerToBuiltin(cursor.type()))
        return result;

    if (cursor.kind() == CXCursor_Constructor) {
        const ToolTipInfo parentInfo = qDocInfo(cursor.semanticParent());
        result.qdocIdCandidates = parentInfo.qdocIdCandidates;
        result.qdocMark = parentInfo.qdocMark;
        result.qdocCategory = ToolTipInfo::Unknown;
        return result;
    }

    result.qdocIdCandidates = qDocIdCandidates(cursor);
    result.qdocMark = qdocMark(cursor);
    result.qdocCategory = qdocCategory(cursor);

    if (cursor.type().kind() == CXType_Record) {
        result.qdocIdCandidates = qDocIdCandidates(cursor.type().declaration());
        return result;
    }

    if (cursor.kind() == CXCursor_VarDecl || cursor.kind() == CXCursor_ParmDecl
        || cursor.kind() == CXCursor_FieldDecl) {
        // maybe template instantiation
        if (cursor.type().kind() == CXType_Unexposed && cursor.type().canonical().kind() == CXType_Record) {
            result.qdocIdCandidates = qDocIdCandidates(cursor.type().canonical().declaration());
            result.qdocMark = typeName(cursor.type());
            result.qdocCategory = ToolTipInfo::ClassOrNamespace;
            return result;
        }

        Type type = cursor.type();
        while (type.pointeeType().isValid() && type != type.pointeeType())
            type = type.pointeeType();

        const Cursor typeCursor = type.declaration();
        result.qdocIdCandidates = qDocIdCandidates(typeCursor);
        result.qdocCategory = qdocCategory(typeCursor);
        result.qdocMark = typeName(type);
    }

    // TODO: Handle also RValueReference()
    if (cursor.type().isLValueReference()) {
        const Cursor pointeeTypeDeclaration = cursor.type().pointeeType().declaration();
        result.qdocIdCandidates = qDocIdCandidates(pointeeTypeDeclaration);
        result.qdocMark = pointeeTypeDeclaration.spelling();
        result.qdocCategory = qdocCategory(pointeeTypeDeclaration);
        return result;
    }

    return result;
}

CXSourceLocation ToolTipInfoCollector::toCXSourceLocation(uint line, uint column) const
{
    return clang_getLocation(m_cxTranslationUnit,
                             clang_getFile(m_cxTranslationUnit,
                                           m_mainFilePath.constData()),
                             line,
                             column);
}

UnsavedFile ToolTipInfoCollector::unsavedFile(const Utf8String &filePath) const
{
    const UnsavedFile &unsavedFile = m_unsavedFiles.unsavedFile(filePath);
    if (!unsavedFile.filePath().isEmpty())
        return unsavedFile;

    // Create an unsaved file with the file content from disk.
    // TODO: Make use of clang_getFileContents() instead of reading from disk.
    QTextCodec *codec = QTextCodec::codecForName(m_textCodecName);
    QByteArray fileContent;
    QString errorString;
    using namespace Utils;
    const TextFileFormat::ReadResult readResult
            = TextFileFormat::readFileUTF8(filePath.toString(), codec, &fileContent, &errorString);
    if (readResult != TextFileFormat::ReadSuccess) {
        qWarning() << "Failed to read file" << filePath << ":" << errorString;
        return UnsavedFile();
    }

    return UnsavedFile(filePath, Utf8String::fromByteArray(fileContent));
}

Utf8String ToolTipInfoCollector::lineRange(const Utf8String &filePath,
                                           unsigned fromLine,
                                           unsigned toLine) const
{
    if (toLine < fromLine)
        return Utf8String();

    const UnsavedFile file = unsavedFile(filePath);
    if (file.fileContent().isEmpty())
        return Utf8String();

    return file.lineRange(fromLine, toLine);
}

ToolTipInfo ToolTipInfoCollector::collect(uint line, uint column) const
{
    const Cursor cursor = clang_getCursor(m_cxTranslationUnit, toCXSourceLocation(line, column));
    if (!cursor.isValid())
        return ToolTipInfo(); // E.g. cursor on ifdeffed out range

    const Cursor referenced = referencedCursor(cursor);
    QTC_CHECK(referenced.isValid());

    ToolTipInfo info;
    info.text = text(cursor, referenced);
    info.briefComment = referenced.briefComment();

    {
        ToolTipInfo qDocToolTipInfo = qDocInfo(referenced);
        info.qdocIdCandidates = qDocToolTipInfo.qdocIdCandidates;
        info.qdocMark = qDocToolTipInfo.qdocMark;
        info.qdocCategory = qDocToolTipInfo.qdocCategory;
    }

    info.sizeInBytes = sizeInBytes(cursor);

    return info;
}

} // anonymous namespace

ToolTipInfo collectToolTipInfo(UnsavedFiles &unsavedFiles,
                               const Utf8String &textCodecName,
                               const Utf8String &mainFilePath,
                               CXTranslationUnit cxTranslationUnit,
                               uint line,
                               uint column)
{
    ToolTipInfoCollector collector(unsavedFiles, textCodecName, mainFilePath, cxTranslationUnit);
    const ToolTipInfo info = collector.collect(line, column);

    return info;
}

} // namespace ClangBackEnd