aboutsummaryrefslogtreecommitdiffstats
path: root/src/tools/clangbackend/ipcsource/highlightingmark.cpp
blob: 58a8a298ce12a88bc54b1b4a0c043f19d076082a (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
/****************************************************************************
**
** Copyright (C) 2016 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 <highlightingmarkcontainer.h>

#include "clangstring.h"
#include "cursor.h"
#include "highlightingmark.h"
#include "sourcelocation.h"
#include "sourcerange.h"
#include "sourcerangecontainer.h"

#include <cstring>
#include <ostream>

#include <QDebug>

namespace ClangBackEnd {

HighlightingMark::HighlightingMark(const CXCursor &cxCursor,
                                   CXToken *cxToken,
                                   CXTranslationUnit cxTranslationUnit,
                                   std::vector<CXSourceRange> &currentOutputArgumentRanges)
    : currentOutputArgumentRanges(&currentOutputArgumentRanges),
      originalCursor(cxCursor)
{
    const SourceRange sourceRange = clang_getTokenExtent(cxTranslationUnit, *cxToken);
    const auto start = sourceRange.start();
    const auto end = sourceRange.end();

    line = start.line();
    column = start.column();
    offset = start.offset();
    length = end.offset() - start.offset();
    collectKinds(cxTranslationUnit, cxToken, originalCursor);
}

HighlightingMark::HighlightingMark(uint line, uint column, uint length, HighlightingTypes types)
    : line(line),
      column(column),
      length(length),
      types(types)
{
}

HighlightingMark::HighlightingMark(uint line, uint column, uint length, HighlightingType type)
    : line(line),
      column(column),
      length(length),
      types(HighlightingTypes())
{
    types.mainHighlightingType = type;
}

bool HighlightingMark::hasInvalidMainType() const
{
    return types.mainHighlightingType == HighlightingType::Invalid;
}

bool HighlightingMark::hasMainType(HighlightingType type) const
{
    return types.mainHighlightingType == type;
}

bool HighlightingMark::hasMixinType(HighlightingType type) const
{
    auto found = std::find(types.mixinHighlightingTypes.begin(),
                           types.mixinHighlightingTypes.end(),
                           type);

    return found != types.mixinHighlightingTypes.end();
}

bool HighlightingMark::hasOnlyType(HighlightingType type) const
{
    return types.mixinHighlightingTypes.size() == 0 && hasMainType(type);
}

bool HighlightingMark::hasFunctionArguments() const
{
    return originalCursor.argumentCount() > 0;
}

HighlightingMark::operator HighlightingMarkContainer() const
{
    return HighlightingMarkContainer(line, column, length, types);
}

namespace {

bool isFinalFunction(const Cursor &cursor)
{
    auto referencedCursor = cursor.referenced();
    if (referencedCursor.hasFinalFunctionAttribute())
        return true;
    else
        return false;
}

bool isFunctionInFinalClass(const Cursor &cursor)
{
    auto functionBase = cursor.functionBaseDeclaration();
    if (functionBase.isValid() && functionBase.hasFinalClassAttribute())
        return true;

    return false;
}
}

void HighlightingMark::memberReferenceKind(const Cursor &cursor)
{
    if (cursor.isDynamicCall()) {
        if (isFinalFunction(cursor) || isFunctionInFinalClass(cursor))
            types.mainHighlightingType = HighlightingType::Function;
        else
            types.mainHighlightingType = HighlightingType::VirtualFunction;
    } else {
        identifierKind(cursor.referenced(), Recursion::RecursivePass);
    }
}

void HighlightingMark::referencedTypeKind(const Cursor &cursor)
{
    const Cursor referencedCursor = cursor.referenced();

    switch (referencedCursor.kind()) {
        case CXCursor_ClassDecl:
        case CXCursor_StructDecl:
        case CXCursor_UnionDecl:
        case CXCursor_TypedefDecl:
        case CXCursor_TemplateTypeParameter:
        case CXCursor_TypeAliasDecl:
        case CXCursor_EnumDecl:              types.mainHighlightingType = HighlightingType::Type; break;
        default:                             types.mainHighlightingType = HighlightingType::Invalid; break;
    }
}

void HighlightingMark::overloadedDeclRefKind(const Cursor &cursor)
{
    types.mainHighlightingType = HighlightingType::Function;

    // CLANG-UPGRADE-CHECK: Workaround still needed?
    // Workaround https://bugs.llvm.org//show_bug.cgi?id=33256 - SomeType in
    // "using N::SomeType" is mistakenly considered as a CXCursor_OverloadedDeclRef.
    if (cursor.overloadedDeclarationsCount() >= 1
            && cursor.overloadedDeclaration(0).kind() != CXCursor_FunctionDecl) {
        types.mainHighlightingType = HighlightingType::Type;
    }
}

void HighlightingMark::variableKind(const Cursor &cursor)
{
    if (cursor.isLocalVariable())
        types.mainHighlightingType = HighlightingType::LocalVariable;
    else
        types.mainHighlightingType = HighlightingType::GlobalVariable;

    if (isOutputArgument())
        types.mixinHighlightingTypes.push_back(HighlightingType::OutputArgument);
}

void HighlightingMark::fieldKind(const Cursor &)
{
    types.mainHighlightingType = HighlightingType::Field;

    if (isOutputArgument())
        types.mixinHighlightingTypes.push_back(HighlightingType::OutputArgument);
}

bool HighlightingMark::isVirtualMethodDeclarationOrDefinition(const Cursor &cursor) const
{
    return cursor.isVirtualMethod()
        && (originalCursor.isDeclaration() || originalCursor.isDefinition());
}
namespace {
bool isNotFinalFunction(const Cursor &cursor)
{
    return !cursor.hasFinalFunctionAttribute();
}

}
bool HighlightingMark::isRealDynamicCall(const Cursor &cursor) const
{
    return originalCursor.isDynamicCall() && isNotFinalFunction(cursor);
}

void HighlightingMark::addExtraTypeIfFirstPass(HighlightingType type,
                                               Recursion recursion)
{
    if (recursion == Recursion::FirstPass)
        types.mixinHighlightingTypes.push_back(type);
}

bool HighlightingMark::isArgumentInCurrentOutputArgumentLocations() const
{
    auto originalSourceLocation = originalCursor.cxSourceLocation();

    const auto isNotSameOutputArgument = [&] (const CXSourceRange &currentSourceRange) {
        return originalSourceLocation.int_data >= currentSourceRange.begin_int_data
            && originalSourceLocation.int_data <= currentSourceRange.end_int_data;
    };

    auto found = std::find_if(currentOutputArgumentRanges->begin(),
                                       currentOutputArgumentRanges->end(),
                                       isNotSameOutputArgument);

    bool isOutputArgument = found != currentOutputArgumentRanges->end();

    return isOutputArgument;
}

bool HighlightingMark::isOutputArgument() const
{
    if (currentOutputArgumentRanges->empty())
        return false;

    return isArgumentInCurrentOutputArgumentLocations();
}

void HighlightingMark::collectOutputArguments(const Cursor &cursor)
{
    cursor.collectOutputArgumentRangesTo(*currentOutputArgumentRanges);
    filterOutPreviousOutputArguments();
}

namespace {

uint getStart(CXSourceRange cxSourceRange)
{
    CXSourceLocation startSourceLocation = clang_getRangeStart(cxSourceRange);

    uint startOffset;

    clang_getFileLocation(startSourceLocation, nullptr, nullptr, nullptr, &startOffset);

    return startOffset;
}
}

void HighlightingMark::filterOutPreviousOutputArguments()
{
    auto isAfterLocation = [this] (CXSourceRange outputRange) {
        return getStart(outputRange) > offset;
    };

    auto precedingBegin = std::partition(currentOutputArgumentRanges->begin(),
                                         currentOutputArgumentRanges->end(),
                                         isAfterLocation);

    currentOutputArgumentRanges->erase(precedingBegin, currentOutputArgumentRanges->end());
}

void HighlightingMark::functionKind(const Cursor &cursor, Recursion recursion)
{
    if (isRealDynamicCall(cursor) || isVirtualMethodDeclarationOrDefinition(cursor))
        types.mainHighlightingType = HighlightingType::VirtualFunction;
    else
        types.mainHighlightingType = HighlightingType::Function;

    addExtraTypeIfFirstPass(HighlightingType::Declaration, recursion);
}

void HighlightingMark::identifierKind(const Cursor &cursor, Recursion recursion)
{
    switch (cursor.kind()) {
        case CXCursor_Destructor:
        case CXCursor_Constructor:
        case CXCursor_FunctionDecl:
        case CXCursor_CallExpr:
        case CXCursor_CXXMethod:                 functionKind(cursor, recursion); break;
        case CXCursor_NonTypeTemplateParameter:
        case CXCursor_CompoundStmt:              types.mainHighlightingType = HighlightingType::LocalVariable; break;
        case CXCursor_ParmDecl:
        case CXCursor_VarDecl:                   variableKind(cursor); break;
        case CXCursor_DeclRefExpr:               identifierKind(cursor.referenced(), Recursion::RecursivePass); break;
        case CXCursor_MemberRefExpr:             memberReferenceKind(cursor); break;
        case CXCursor_FieldDecl:
        case CXCursor_MemberRef:                 fieldKind(cursor); break;
        case CXCursor_ObjCIvarDecl:
        case CXCursor_ObjCPropertyDecl:
        case CXCursor_ObjCClassMethodDecl:
        case CXCursor_ObjCInstanceMethodDecl:
        case CXCursor_ObjCSynthesizeDecl:
        case CXCursor_ObjCDynamicDecl:           types.mainHighlightingType = HighlightingType::Field; break;
        case CXCursor_TypeRef:                   referencedTypeKind(cursor); break;
        case CXCursor_ClassDecl:
        case CXCursor_ClassTemplatePartialSpecialization:
        case CXCursor_TemplateTypeParameter:
        case CXCursor_TemplateTemplateParameter:
        case CXCursor_UnionDecl:
        case CXCursor_StructDecl:
        case CXCursor_TemplateRef:
        case CXCursor_Namespace:
        case CXCursor_NamespaceRef:
        case CXCursor_NamespaceAlias:
        case CXCursor_TypeAliasDecl:
        case CXCursor_TypedefDecl:
        case CXCursor_ClassTemplate:
        case CXCursor_EnumDecl:
        case CXCursor_CXXStaticCastExpr:
        case CXCursor_CXXReinterpretCastExpr:
        case CXCursor_ObjCCategoryDecl:
        case CXCursor_ObjCCategoryImplDecl:
        case CXCursor_ObjCImplementationDecl:
        case CXCursor_ObjCInterfaceDecl:
        case CXCursor_ObjCProtocolDecl:
        case CXCursor_ObjCProtocolRef:
        case CXCursor_ObjCClassRef:
        case CXCursor_ObjCSuperClassRef:         types.mainHighlightingType = HighlightingType::Type; break;
        case CXCursor_OverloadedDeclRef:         overloadedDeclRefKind(cursor); break;
        case CXCursor_FunctionTemplate:          types.mainHighlightingType = HighlightingType::Function; break;
        case CXCursor_EnumConstantDecl:          types.mainHighlightingType = HighlightingType::Enumeration; break;
        case CXCursor_PreprocessingDirective:    types.mainHighlightingType = HighlightingType::Preprocessor; break;
        case CXCursor_MacroExpansion:            types.mainHighlightingType = HighlightingType::PreprocessorExpansion; break;
        case CXCursor_MacroDefinition:           types.mainHighlightingType = HighlightingType::PreprocessorDefinition; break;
        case CXCursor_InclusionDirective:        types.mainHighlightingType = HighlightingType::StringLiteral; break;
        case CXCursor_LabelRef:
        case CXCursor_LabelStmt:                 types.mainHighlightingType = HighlightingType::Label; break;
        default:                                 break;
    }
}

namespace {
HighlightingType literalKind(const Cursor &cursor)
{
    switch (cursor.kind()) {
        case CXCursor_CharacterLiteral:
        case CXCursor_StringLiteral:
        case CXCursor_ObjCStringLiteral: return HighlightingType::StringLiteral;
        case CXCursor_IntegerLiteral:
        case CXCursor_ImaginaryLiteral:
        case CXCursor_FloatingLiteral:   return HighlightingType::NumberLiteral;
        default:                         return HighlightingType::Invalid;
    }

    Q_UNREACHABLE();
}

bool hasOperatorName(const char *operatorString)
{
    return std::strncmp(operatorString, "operator", 8) == 0;
}

HighlightingType operatorKind(const Cursor &cursor)
{
    if (hasOperatorName(cursor.spelling().cString()))
        return HighlightingType::Operator;
    else
        return HighlightingType::Invalid;
}

}

HighlightingType HighlightingMark::punctuationKind(const Cursor &cursor)
{
    HighlightingType highlightingType = HighlightingType::Invalid;

    switch (cursor.kind()) {
        case CXCursor_DeclRefExpr: highlightingType = operatorKind(cursor); break;
        case CXCursor_Constructor:
        case CXCursor_CallExpr:    collectOutputArguments(cursor); break;
        default:                   break;
    }

    return highlightingType;
}

static HighlightingType highlightingTypeForKeyword(CXTranslationUnit cxTranslationUnit,
                                                   CXToken *cxToken,
                                                   const Cursor &cursor)
{
    switch (cursor.kind()) {
        case CXCursor_PreprocessingDirective: return HighlightingType::Preprocessor;
        case CXCursor_InclusionDirective: return HighlightingType::StringLiteral;
        default: break;
    }

    const ClangString spelling = clang_getTokenSpelling(cxTranslationUnit, *cxToken);
    if (spelling == "bool"
            || spelling == "char"
            || spelling == "char16_t"
            || spelling == "char32_t"
            || spelling == "double"
            || spelling == "float"
            || spelling == "int"
            || spelling == "long"
            || spelling == "short"
            || spelling == "signed"
            || spelling == "unsigned"
            || spelling == "void"
            || spelling == "wchar_t") {
        return HighlightingType::PrimitiveType;
    }

    return HighlightingType::Keyword;
}

void HighlightingMark::collectKinds(CXTranslationUnit cxTranslationUnit,
                                    CXToken *cxToken, const Cursor &cursor)
{
    auto cxTokenKind = clang_getTokenKind(*cxToken);

    types = HighlightingTypes();

    switch (cxTokenKind) {
        case CXToken_Keyword:     types.mainHighlightingType = highlightingTypeForKeyword(cxTranslationUnit, cxToken, originalCursor); break;
        case CXToken_Punctuation: types.mainHighlightingType = punctuationKind(cursor); break;
        case CXToken_Identifier:  identifierKind(cursor, Recursion::FirstPass); break;
        case CXToken_Comment:     types.mainHighlightingType = HighlightingType::Comment; break;
        case CXToken_Literal:     types.mainHighlightingType = literalKind(cursor); break;
    }
}

std::ostream &operator<<(std::ostream &os, const HighlightingMark& highlightingMark)
{
    os << "(type: " << highlightingMark.types << ", "
       << " line: " << highlightingMark.line << ", "
       << " column: " << highlightingMark.column << ", "
       << " length: " << highlightingMark.length
       << ")";

    return  os;
}

} // namespace ClangBackEnd