forked from MaskRay/ccls
-
Notifications
You must be signed in to change notification settings - Fork 0
/
clang_indexer.cc
2419 lines (2157 loc) · 85.1 KB
/
clang_indexer.cc
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
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "indexer.h"
#include "clang_cursor.h"
#include "clang_utils.h"
#include "platform.h"
#include "serializer.h"
#include "timer.h"
#include "type_printer.h"
#include <loguru.hpp>
#include <algorithm>
#include <cassert>
#include <chrono>
#include <climits>
#include <iostream>
// TODO: See if we can use clang_indexLoc_getFileLocation to get a type ref on
// |Foobar| in DISALLOW_COPY(Foobar)
#if CINDEX_VERSION >= 47
#define CINDEX_HAVE_PRETTY 1
#endif
#if CINDEX_VERSION >= 48
#define CINDEX_HAVE_ROLE 1
#endif
namespace {
// For typedef/using spanning less than or equal to (this number) of lines,
// display their declarations on hover.
constexpr int kMaxLinesDisplayTypeAliasDeclarations = 3;
// TODO How to check if a reference to type is a declaration?
// This currently also includes constructors/destructors.
// It seems declarations in functions are not indexed.
bool IsDeclContext(CXIdxEntityKind kind) {
switch (kind) {
case CXIdxEntity_CXXClass:
case CXIdxEntity_CXXNamespace:
case CXIdxEntity_ObjCCategory:
case CXIdxEntity_ObjCClass:
case CXIdxEntity_ObjCProtocol:
case CXIdxEntity_Struct:
return true;
default:
return false;
}
}
Role GetRole(const CXIdxEntityRefInfo* ref_info, Role role) {
#if CINDEX_HAVE_ROLE
return static_cast<Role>(static_cast<int>(ref_info->role));
#else
return role;
#endif
}
SymbolKind GetSymbolKind(CXCursorKind kind) {
switch (kind) {
case CXCursor_TranslationUnit:
return SymbolKind::File;
case CXCursor_FunctionDecl:
case CXCursor_CXXMethod:
case CXCursor_Constructor:
case CXCursor_Destructor:
case CXCursor_ConversionFunction:
case CXCursor_FunctionTemplate:
case CXCursor_OverloadedDeclRef:
case CXCursor_LambdaExpr:
case CXCursor_ObjCInstanceMethodDecl:
case CXCursor_ObjCClassMethodDecl:
return SymbolKind::Func;
case CXCursor_StructDecl:
case CXCursor_UnionDecl:
case CXCursor_ClassDecl:
case CXCursor_EnumDecl:
case CXCursor_ObjCInterfaceDecl:
case CXCursor_ObjCCategoryDecl:
case CXCursor_ObjCImplementationDecl:
case CXCursor_Namespace:
return SymbolKind::Type;
default:
return SymbolKind::Invalid;
}
}
// Inverse of libclang/CXIndexDataConsumer.cpp getEntityKindFromSymbolKind
lsSymbolKind GetSymbolKind(CXIdxEntityKind kind) {
switch (kind) {
case CXIdxEntity_Unexposed:
return lsSymbolKind::Unknown;
case CXIdxEntity_Typedef:
return lsSymbolKind::TypeAlias;
case CXIdxEntity_Function:
return lsSymbolKind::Function;
case CXIdxEntity_Variable:
// Can also be Parameter
return lsSymbolKind::Variable;
case CXIdxEntity_Field:
return lsSymbolKind::Field;
case CXIdxEntity_EnumConstant:
return lsSymbolKind::EnumMember;
case CXIdxEntity_ObjCClass:
return lsSymbolKind::Class;
case CXIdxEntity_ObjCProtocol:
return lsSymbolKind::Interface;
case CXIdxEntity_ObjCCategory:
return lsSymbolKind::Interface;
case CXIdxEntity_ObjCInstanceMethod:
return lsSymbolKind::Method;
case CXIdxEntity_ObjCClassMethod:
return lsSymbolKind::StaticMethod;
case CXIdxEntity_ObjCProperty:
return lsSymbolKind::Property;
case CXIdxEntity_ObjCIvar:
return lsSymbolKind::Field;
case CXIdxEntity_Enum:
return lsSymbolKind::Enum;
case CXIdxEntity_Struct:
case CXIdxEntity_Union:
return lsSymbolKind::Struct;
case CXIdxEntity_CXXClass:
return lsSymbolKind::Class;
case CXIdxEntity_CXXNamespace:
return lsSymbolKind::Namespace;
case CXIdxEntity_CXXNamespaceAlias:
return lsSymbolKind::Namespace;
case CXIdxEntity_CXXStaticVariable:
return lsSymbolKind::Field;
case CXIdxEntity_CXXStaticMethod:
return lsSymbolKind::StaticMethod;
case CXIdxEntity_CXXInstanceMethod:
return lsSymbolKind::Method;
case CXIdxEntity_CXXConstructor:
return lsSymbolKind::Constructor;
case CXIdxEntity_CXXDestructor:
return lsSymbolKind::Method;
case CXIdxEntity_CXXConversionFunction:
return lsSymbolKind::Constructor;
case CXIdxEntity_CXXTypeAlias:
return lsSymbolKind::TypeAlias;
case CXIdxEntity_CXXInterface:
return lsSymbolKind::Struct;
}
return lsSymbolKind::Unknown;
}
StorageClass GetStorageClass(CX_StorageClass storage) {
switch (storage) {
case CX_SC_Invalid:
case CX_SC_OpenCLWorkGroupLocal:
return StorageClass::Invalid;
case CX_SC_None:
return StorageClass::None;
case CX_SC_Extern:
return StorageClass::Extern;
case CX_SC_Static:
return StorageClass::Static;
case CX_SC_PrivateExtern:
return StorageClass::PrivateExtern;
case CX_SC_Auto:
return StorageClass::Auto;
case CX_SC_Register:
return StorageClass::Register;
}
return StorageClass::None;
}
// Caches all instances of constructors, regardless if they are indexed or not.
// The constructor may have a make_unique call associated with it that we need
// to export. If we do not capture the parameter type description for the
// constructor we will not be able to attribute the constructor call correctly.
struct ConstructorCache {
struct Constructor {
Usr usr;
std::vector<std::string> param_type_desc;
};
std::unordered_map<Usr, std::vector<Constructor>> constructors_;
// This should be called whenever there is a constructor declaration.
void NotifyConstructor(ClangCursor ctor_cursor) {
auto build_type_desc = [](ClangCursor cursor) {
std::vector<std::string> type_desc;
for (ClangCursor arg : cursor.get_arguments()) {
if (arg.get_kind() == CXCursor_ParmDecl)
type_desc.push_back(arg.get_type_description());
}
return type_desc;
};
Constructor ctor{ctor_cursor.get_usr_hash(), build_type_desc(ctor_cursor)};
// Insert into |constructors_|.
auto type_usr_hash = ctor_cursor.get_semantic_parent().get_usr_hash();
auto existing_ctors = constructors_.find(type_usr_hash);
if (existing_ctors != constructors_.end()) {
existing_ctors->second.push_back(ctor);
} else {
constructors_[type_usr_hash] = {ctor};
}
}
// Tries to lookup a constructor in |type_usr| that takes arguments most
// closely aligned to |param_type_desc|.
optional<Usr> TryFindConstructorUsr(
Usr type_usr,
const std::vector<std::string>& param_type_desc) {
auto count_matching_prefix_length = [](const char* a, const char* b) {
int matched = 0;
while (*a && *b) {
if (*a != *b)
break;
++a;
++b;
++matched;
}
// Additional score if the strings were the same length, which makes
// "a"/"a" match higher than "a"/"a&"
if (*a == *b)
matched += 1;
return matched;
};
// Try to find constructors for the type. If there are no constructors
// available, return an empty result.
auto ctors_it = constructors_.find(type_usr);
if (ctors_it == constructors_.end())
return nullopt;
const std::vector<Constructor>& ctors = ctors_it->second;
if (ctors.empty())
return nullopt;
Usr best_usr = ctors[0].usr;
int best_score = INT_MIN;
// Scan constructors for the best possible match.
for (const Constructor& ctor : ctors) {
// If |param_type_desc| is empty and the constructor is as well, we don't
// need to bother searching, as this is the match.
if (param_type_desc.empty() && ctor.param_type_desc.empty()) {
best_usr = ctor.usr;
break;
}
// Weight matching parameter length heavily, as it is more accurate than
// the fuzzy type matching approach.
int score = 0;
if (param_type_desc.size() == ctor.param_type_desc.size())
score += param_type_desc.size() * 1000;
// Do prefix-based match on parameter type description. This works well in
// practice because clang appends qualifiers to the end of the type, ie,
// |foo *&&|
for (size_t i = 0;
i < std::min(param_type_desc.size(), ctor.param_type_desc.size());
++i) {
score += count_matching_prefix_length(param_type_desc[i].c_str(),
ctor.param_type_desc[i].c_str());
}
if (score > best_score) {
best_usr = ctor.usr;
best_score = score;
}
}
return best_usr;
}
};
struct IndexParam {
Config* config = nullptr;
std::unordered_set<CXFile> seen_cx_files;
std::vector<std::string> seen_files;
FileContentsMap file_contents;
std::unordered_map<std::string, int64_t> file_modification_times;
// Only use this when strictly needed (ie, primary translation unit is
// needed). Most logic should get the IndexFile instance via
// |file_consumer|.
//
// This can be null if we're not generating an index for the primary
// translation unit.
IndexFile* primary_file = nullptr;
ClangTranslationUnit* tu = nullptr;
FileConsumer* file_consumer = nullptr;
NamespaceHelper ns;
ConstructorCache ctors;
IndexParam(Config* config,
ClangTranslationUnit* tu,
FileConsumer* file_consumer)
: config(config), tu(tu), file_consumer(file_consumer) {}
#if CINDEX_HAVE_PRETTY
CXPrintingPolicy print_policy = nullptr;
CXPrintingPolicy print_policy_more = nullptr;
~IndexParam() {
clang_PrintingPolicy_dispose(print_policy);
clang_PrintingPolicy_dispose(print_policy_more);
}
std::string PrettyPrintCursor(CXCursor cursor, bool initializer = true) {
if (!print_policy) {
print_policy = clang_getCursorPrintingPolicy(cursor);
clang_PrintingPolicy_setProperty(print_policy,
CXPrintingPolicy_TerseOutput, 1);
clang_PrintingPolicy_setProperty(print_policy,
CXPrintingPolicy_FullyQualifiedName, 1);
clang_PrintingPolicy_setProperty(
print_policy, CXPrintingPolicy_SuppressInitializers, 1);
print_policy_more = clang_getCursorPrintingPolicy(cursor);
clang_PrintingPolicy_setProperty(print_policy_more,
CXPrintingPolicy_FullyQualifiedName, 1);
clang_PrintingPolicy_setProperty(print_policy_more,
CXPrintingPolicy_TerseOutput, 1);
}
return ToString(clang_getCursorPrettyPrinted(
cursor, initializer ? print_policy_more : print_policy));
}
#endif
};
IndexFile* ConsumeFile(IndexParam* param, CXFile file) {
bool is_first_ownership = false;
IndexFile* db = param->file_consumer->TryConsumeFile(
file, &is_first_ownership, ¶m->file_contents);
// If this is the first time we have seen the file (ignoring if we are
// generating an index for it):
if (param->seen_cx_files.insert(file).second) {
std::string file_name = FileName(file);
// file_name may be empty when it contains .. and is outside of WorkingDir.
// https://reviews.llvm.org/D42893
// https://github.com/cquery-project/cquery/issues/413
if (!file_name.empty()) {
// Add to all files we have seen so we can generate proper dependency
// graph.
param->seen_files.push_back(file_name);
// Set modification time.
optional<int64_t> modification_time = GetLastModificationTime(file_name);
LOG_IF_S(ERROR, !modification_time)
<< "Failed fetching modification time for " << file_name;
if (modification_time)
param->file_modification_times[file_name] = *modification_time;
}
}
if (is_first_ownership) {
// Report skipped source range list.
CXSourceRangeList* skipped = clang_getSkippedRanges(param->tu->cx_tu, file);
for (unsigned i = 0; i < skipped->count; ++i) {
Range range = ResolveCXSourceRange(skipped->ranges[i]);
#if CINDEX_VERSION < 45 // Before clang 6.0.0
// clang_getSkippedRanges reports start one token after the '#', move it
// back so it starts at the '#'
range.start.column -= 1;
#endif
db->skipped_by_preprocessor.push_back(range);
}
clang_disposeSourceRangeList(skipped);
}
return db;
}
// Returns true if the given entity kind can be called implicitly, ie, without
// actually being written in the source code.
bool CanBeCalledImplicitly(CXIdxEntityKind kind) {
switch (kind) {
case CXIdxEntity_CXXConstructor:
case CXIdxEntity_CXXConversionFunction:
case CXIdxEntity_CXXDestructor:
return true;
default:
return false;
}
}
// Returns true if the cursor spelling contains the given string. This is
// useful to check for implicit function calls.
bool CursorSpellingContainsString(CXCursor cursor,
CXTranslationUnit cx_tu,
std::string_view needle) {
CXSourceRange range = clang_Cursor_getSpellingNameRange(cursor, 0, 0);
CXToken* tokens;
unsigned num_tokens;
clang_tokenize(cx_tu, range, &tokens, &num_tokens);
bool result = false;
for (unsigned i = 0; i < num_tokens; ++i) {
CXString name = clang_getTokenSpelling(cx_tu, tokens[i]);
if (needle == clang_getCString(name)) {
result = true;
break;
}
clang_disposeString(name);
}
clang_disposeTokens(cx_tu, tokens, num_tokens);
return result;
}
// Returns the document content for the given range. May not work perfectly
// when there are tabs instead of spaces.
std::string GetDocumentContentInRange(CXTranslationUnit cx_tu,
CXSourceRange range) {
std::string result;
CXToken* tokens;
unsigned num_tokens;
clang_tokenize(cx_tu, range, &tokens, &num_tokens);
optional<Range> previous_token_range;
for (unsigned i = 0; i < num_tokens; ++i) {
// Add whitespace between the previous token and this one.
Range token_range =
ResolveCXSourceRange(clang_getTokenExtent(cx_tu, tokens[i]));
if (previous_token_range) {
// Insert newlines.
int16_t line_delta =
token_range.start.line - previous_token_range->end.line;
assert(line_delta >= 0);
if (line_delta > 0) {
result.append((size_t)line_delta, '\n');
// Reset column so we insert starting padding.
previous_token_range->end.column = 0;
}
// Insert spaces.
int16_t column_delta =
token_range.start.column - previous_token_range->end.column;
assert(column_delta >= 0);
result.append((size_t)column_delta, ' ');
}
previous_token_range = token_range;
// Add token content.
CXString spelling = clang_getTokenSpelling(cx_tu, tokens[i]);
result += clang_getCString(spelling);
clang_disposeString(spelling);
}
clang_disposeTokens(cx_tu, tokens, num_tokens);
return result;
}
void SetUsePreflight(IndexFile* db, ClangCursor parent) {
switch (GetSymbolKind(parent.get_kind())) {
case SymbolKind::Func:
(void)db->ToFuncId(parent.cx_cursor);
break;
case SymbolKind::Type:
(void)db->ToTypeId(parent.cx_cursor);
break;
case SymbolKind::Var:
(void)db->ToVarId(parent.cx_cursor);
break;
default:
break;
}
}
// |parent| should be resolved before using |SetUsePreflight| so that |def| will
// not be invalidated by |To{Func,Type,Var}Id|.
Use SetUse(IndexFile* db, Range range, ClangCursor parent, Role role) {
switch (GetSymbolKind(parent.get_kind())) {
case SymbolKind::Func:
return Use(range, db->ToFuncId(parent.cx_cursor), SymbolKind::Func, role,
{});
case SymbolKind::Type:
return Use(range, db->ToTypeId(parent.cx_cursor), SymbolKind::Type, role,
{});
case SymbolKind::Var:
return Use(range, db->ToVarId(parent.cx_cursor), SymbolKind::Var, role,
{});
default:
return Use(range, Id<void>(), SymbolKind::File, role, {});
}
}
const char* GetAnonName(CXCursorKind kind) {
switch (kind) {
case CXCursor_ClassDecl:
return "(anon class)";
case CXCursor_EnumDecl:
return "(anon enum)";
case CXCursor_StructDecl:
return "(anon struct)";
case CXCursor_UnionDecl:
return "(anon union)";
default:
return "(anon)";
}
}
void SetTypeName(IndexType* type,
const ClangCursor& cursor,
const CXIdxContainerInfo* container,
const char* name,
IndexParam* param) {
CXIdxContainerInfo parent;
// |name| can be null in an anonymous struct (see
// tests/types/anonymous_struct.cc).
if (!name)
name = GetAnonName(cursor.get_kind());
if (!container)
parent.cursor = cursor.get_semantic_parent().cx_cursor;
// Investigate why clang_getCursorPrettyPrinted gives `struct A {}` `namespace
// ns {}` which are not qualified.
// type->def.detailed_name = param->PrettyPrintCursor(cursor.cx_cursor);
type->def.detailed_name =
param->ns.QualifiedName(container ? container : &parent, name);
auto idx = type->def.detailed_name.rfind(name);
assert(idx != std::string::npos);
type->def.short_name_offset = idx;
type->def.short_name_size = strlen(name);
}
// Finds the cursor associated with the declaration type of |cursor|. This
// strips
// qualifies from |cursor| (ie, Foo* => Foo) and removes template arguments
// (ie, Foo<A,B> => Foo<*,*>).
optional<IndexTypeId> ResolveToDeclarationType(IndexFile* db,
ClangCursor cursor,
IndexParam* param) {
ClangType type = cursor.get_type();
// auto x = new Foo() will not be deduced to |Foo| if we do not use the
// canonical type. However, a canonical type will look past typedefs so we
// will not accurately report variables on typedefs if we always do this.
if (type.cx_type.kind == CXType_Auto)
type = type.get_canonical();
type = type.strip_qualifiers();
if (type.is_builtin()) {
// For builtin types, use type kinds as USR hash.
return db->ToTypeId(type.cx_type.kind);
}
ClangCursor declaration =
type.get_declaration().template_specialization_to_template_definition();
CXString cx_usr = clang_getCursorUSR(declaration.cx_cursor);
const char* str_usr = clang_getCString(cx_usr);
if (!str_usr || str_usr[0] == '\0') {
clang_disposeString(cx_usr);
return nullopt;
}
Usr usr = HashUsr(str_usr);
clang_disposeString(cx_usr);
IndexTypeId type_id = db->ToTypeId(usr);
IndexType* typ = db->Resolve(type_id);
if (typ->def.detailed_name.empty()) {
std::string name = declaration.get_spell_name();
SetTypeName(typ, declaration, nullptr, name.c_str(), param);
}
return type_id;
}
void SetVarDetail(IndexVar* var,
std::string_view short_name,
const ClangCursor& cursor,
const CXIdxContainerInfo* semanticContainer,
bool is_first_seen,
IndexFile* db,
IndexParam* param) {
IndexVar::Def& def = var->def;
const CXType cx_type = clang_getCursorType(cursor.cx_cursor);
std::string type_name = ToString(clang_getTypeSpelling(cx_type));
// clang may report "(lambda at foo.cc)" which end up being a very long
// string. Shorten it to just "lambda".
if (type_name.find("(lambda at") != std::string::npos)
type_name = "lambda";
if (param->config->index.comments)
def.comments = cursor.get_comments();
def.storage = GetStorageClass(clang_Cursor_getStorageClass(cursor.cx_cursor));
// TODO how to make PrettyPrint'ed variable name qualified?
std::string qualified_name =
#if 0 && CINDEX_HAVE_PRETTY
cursor.get_kind() != CXCursor_EnumConstantDecl
? param->PrettyPrintCursor(cursor.cx_cursor)
:
#endif
param->ns.QualifiedName(semanticContainer, short_name);
if (cursor.get_kind() == CXCursor_EnumConstantDecl && semanticContainer) {
CXType enum_type = clang_getCanonicalType(
clang_getEnumDeclIntegerType(semanticContainer->cursor));
std::string hover = qualified_name + " = ";
if (enum_type.kind == CXType_UInt || enum_type.kind == CXType_ULong ||
enum_type.kind == CXType_ULongLong)
hover += std::to_string(
clang_getEnumConstantDeclUnsignedValue(cursor.cx_cursor));
else
hover += std::to_string(clang_getEnumConstantDeclValue(cursor.cx_cursor));
def.detailed_name = std::move(qualified_name);
def.hover = hover;
} else {
#if 0 && CINDEX_HAVE_PRETTY
//def.detailed_name = param->PrettyPrintCursor(cursor.cx_cursor, false);
#else
ConcatTypeAndName(type_name, qualified_name);
def.detailed_name = type_name;
// Append the textual initializer, bit field, constructor to |hover|.
// Omit |hover| for these types:
// int (*a)(); int (&a)(); int (&&a)(); int a[1]; auto x = ...
// We can take these into consideration after we have better support for
// inside-out syntax.
CXType deref = cx_type;
while (deref.kind == CXType_Pointer || deref.kind == CXType_MemberPointer ||
deref.kind == CXType_LValueReference ||
deref.kind == CXType_RValueReference)
deref = clang_getPointeeType(deref);
if (deref.kind != CXType_Unexposed && deref.kind != CXType_Auto &&
clang_getResultType(deref).kind == CXType_Invalid &&
clang_getElementType(deref).kind == CXType_Invalid) {
const FileContents& fc = param->file_contents[db->path];
optional<int> spell_end = fc.ToOffset(cursor.get_spell().end);
optional<int> extent_end = fc.ToOffset(cursor.get_extent().end);
if (extent_end && *spell_end < *extent_end)
def.hover = std::string(def.detailed_name.c_str()) +
fc.content.substr(*spell_end, *extent_end - *spell_end);
}
#endif
}
// FIXME QualifiedName should return index
auto idx = def.detailed_name.rfind(short_name.begin(), std::string::npos,
short_name.size());
assert(idx != std::string::npos);
def.short_name_offset = idx;
def.short_name_size = short_name.size();
if (is_first_seen) {
optional<IndexTypeId> var_type =
ResolveToDeclarationType(db, cursor, param);
if (var_type) {
// Don't treat enum definition variables as instantiations.
bool is_enum_member = semanticContainer &&
semanticContainer->cursor.kind == CXCursor_EnumDecl;
if (!is_enum_member)
db->Resolve(var_type.value())->instances.push_back(var->id);
def.type = *var_type;
}
}
}
void OnIndexReference_Function(IndexFile* db,
Range loc,
ClangCursor parent_cursor,
IndexFuncId called_id,
Role role) {
switch (GetSymbolKind(parent_cursor.get_kind())) {
case SymbolKind::Func: {
IndexFunc* parent = db->Resolve(db->ToFuncId(parent_cursor.cx_cursor));
IndexFunc* called = db->Resolve(called_id);
parent->def.callees.push_back(
SymbolRef(loc, called->id, SymbolKind::Func, role));
called->uses.push_back(Use(loc, parent->id, SymbolKind::Func, role, {}));
break;
}
case SymbolKind::Type: {
IndexType* parent = db->Resolve(db->ToTypeId(parent_cursor.cx_cursor));
IndexFunc* called = db->Resolve(called_id);
called = db->Resolve(called_id);
called->uses.push_back(Use(loc, parent->id, SymbolKind::Type, role, {}));
break;
}
default: {
IndexFunc* called = db->Resolve(called_id);
called->uses.push_back(Use(loc, Id<void>(), SymbolKind::File, role, {}));
break;
}
}
}
} // namespace
// static
const int IndexFile::kMajorVersion = 15;
const int IndexFile::kMinorVersion = 0;
IndexFile::IndexFile(const std::string& path, const std::string& contents)
: id_cache(path), path(path), file_contents(contents) {}
IndexTypeId IndexFile::ToTypeId(Usr usr) {
auto it = id_cache.usr_to_type_id.find(usr);
if (it != id_cache.usr_to_type_id.end())
return it->second;
IndexTypeId id(types.size());
types.push_back(IndexType(id, usr));
id_cache.usr_to_type_id[usr] = id;
id_cache.type_id_to_usr[id] = usr;
return id;
}
IndexFuncId IndexFile::ToFuncId(Usr usr) {
auto it = id_cache.usr_to_func_id.find(usr);
if (it != id_cache.usr_to_func_id.end())
return it->second;
IndexFuncId id(funcs.size());
funcs.push_back(IndexFunc(id, usr));
id_cache.usr_to_func_id[usr] = id;
id_cache.func_id_to_usr[id] = usr;
return id;
}
IndexVarId IndexFile::ToVarId(Usr usr) {
auto it = id_cache.usr_to_var_id.find(usr);
if (it != id_cache.usr_to_var_id.end())
return it->second;
IndexVarId id(vars.size());
vars.push_back(IndexVar(id, usr));
id_cache.usr_to_var_id[usr] = id;
id_cache.var_id_to_usr[id] = usr;
return id;
}
IndexTypeId IndexFile::ToTypeId(const CXCursor& cursor) {
return ToTypeId(ClangCursor(cursor).get_usr_hash());
}
IndexFuncId IndexFile::ToFuncId(const CXCursor& cursor) {
return ToFuncId(ClangCursor(cursor).get_usr_hash());
}
IndexVarId IndexFile::ToVarId(const CXCursor& cursor) {
return ToVarId(ClangCursor(cursor).get_usr_hash());
}
IndexType* IndexFile::Resolve(IndexTypeId id) {
return &types[id.id];
}
IndexFunc* IndexFile::Resolve(IndexFuncId id) {
return &funcs[id.id];
}
IndexVar* IndexFile::Resolve(IndexVarId id) {
return &vars[id.id];
}
std::string IndexFile::ToString() {
return Serialize(SerializeFormat::Json, *this);
}
IndexType::IndexType(IndexTypeId id, Usr usr) : usr(usr), id(id) {}
template <typename T>
void Uniquify(std::vector<Id<T>>& ids) {
std::unordered_set<Id<T>> seen;
size_t n = 0;
for (size_t i = 0; i < ids.size(); i++)
if (seen.insert(ids[i]).second)
ids[n++] = ids[i];
ids.resize(n);
}
void Uniquify(std::vector<Use>& uses) {
std::unordered_set<Range> seen;
size_t n = 0;
for (size_t i = 0; i < uses.size(); i++)
if (seen.insert(uses[i].range).second)
uses[n++] = uses[i];
uses.resize(n);
}
// FIXME Reference: set id in call sites and remove this
// void AddUse(std::vector<Use>& values, Range value) {
// values.push_back(
// Use(value, Id<void>(), SymbolKind::File, Role::Reference, {}));
//}
void AddUse(IndexFile* db,
std::vector<Use>& uses,
Range range,
ClangCursor parent,
Role role = Role::Reference) {
switch (GetSymbolKind(parent.get_kind())) {
case SymbolKind::Func:
uses.push_back(Use(range, db->ToFuncId(parent.cx_cursor),
SymbolKind::Func, role, {}));
break;
case SymbolKind::Type:
uses.push_back(Use(range, db->ToTypeId(parent.cx_cursor),
SymbolKind::Type, role, {}));
break;
default:
uses.push_back(Use(range, Id<void>(), SymbolKind::File, role, {}));
break;
}
}
CXCursor fromContainer(const CXIdxContainerInfo* parent) {
return parent ? parent->cursor : clang_getNullCursor();
}
void AddUseSpell(IndexFile* db, std::vector<Use>& uses, ClangCursor cursor) {
AddUse(db, uses, cursor.get_spell(), cursor.get_lexical_parent().cx_cursor);
}
IdCache::IdCache(const std::string& primary_file)
: primary_file(primary_file) {}
void OnIndexDiagnostic(CXClientData client_data,
CXDiagnosticSet diagnostics,
void* reserved) {
IndexParam* param = static_cast<IndexParam*>(client_data);
for (unsigned i = 0; i < clang_getNumDiagnosticsInSet(diagnostics); ++i) {
CXDiagnostic diagnostic = clang_getDiagnosticInSet(diagnostics, i);
CXSourceLocation diag_loc = clang_getDiagnosticLocation(diagnostic);
// Skip diagnostics in system headers.
// if (clang_Location_isInSystemHeader(diag_loc))
// continue;
// Get db so we can attribute diagnostic to the right indexed file.
CXFile file;
unsigned int line, column;
clang_getSpellingLocation(diag_loc, &file, &line, &column, nullptr);
// Skip empty diagnostic.
if (!line && !column)
continue;
IndexFile* db = ConsumeFile(param, file);
if (!db)
continue;
// Build diagnostic.
optional<lsDiagnostic> ls_diagnostic =
BuildAndDisposeDiagnostic(diagnostic, db->path);
if (ls_diagnostic)
db->diagnostics_.push_back(*ls_diagnostic);
}
}
CXIdxClientFile OnIndexIncludedFile(CXClientData client_data,
const CXIdxIncludedFileInfo* file) {
IndexParam* param = static_cast<IndexParam*>(client_data);
// file->hashLoc only has the position of the hash. We don't have the full
// range for the include.
CXSourceLocation hash_loc = clang_indexLoc_getCXSourceLocation(file->hashLoc);
CXFile cx_file;
unsigned int line;
clang_getSpellingLocation(hash_loc, &cx_file, &line, nullptr, nullptr);
line--;
IndexFile* db = ConsumeFile(param, cx_file);
if (!db)
return nullptr;
IndexInclude include;
include.line = line;
include.resolved_path = FileName(file->file);
if (!include.resolved_path.empty())
db->includes.push_back(include);
return nullptr;
}
ClangCursor::VisitResult DumpVisitor(ClangCursor cursor,
ClangCursor parent,
int* level) {
for (int i = 0; i < *level; ++i)
std::cerr << " ";
std::cerr << ToString(cursor.get_kind()) << " " << cursor.get_spell_name()
<< std::endl;
*level += 1;
cursor.VisitChildren(&DumpVisitor, level);
*level -= 1;
return ClangCursor::VisitResult::Continue;
}
void Dump(ClangCursor cursor) {
int level = 0;
cursor.VisitChildren(&DumpVisitor, &level);
}
struct FindChildOfKindParam {
CXCursorKind target_kind;
optional<ClangCursor> result;
FindChildOfKindParam(CXCursorKind target_kind) : target_kind(target_kind) {}
};
ClangCursor::VisitResult FindTypeVisitor(ClangCursor cursor,
ClangCursor parent,
optional<ClangCursor>* result) {
switch (cursor.get_kind()) {
case CXCursor_TypeRef:
case CXCursor_TemplateRef:
*result = cursor;
return ClangCursor::VisitResult::Break;
default:
break;
}
return ClangCursor::VisitResult::Recurse;
}
optional<ClangCursor> FindType(ClangCursor cursor) {
optional<ClangCursor> result;
cursor.VisitChildren(&FindTypeVisitor, &result);
return result;
}
bool IsTypeDefinition(const CXIdxContainerInfo* container) {
if (!container)
return false;
return GetSymbolKind(container->cursor.kind) == SymbolKind::Type;
}
struct VisitDeclForTypeUsageParam {
IndexFile* db;
optional<IndexTypeId> toplevel_type;
int has_processed_any = false;
optional<ClangCursor> previous_cursor;
optional<IndexTypeId> initial_type;
VisitDeclForTypeUsageParam(IndexFile* db, optional<IndexTypeId> toplevel_type)
: db(db), toplevel_type(toplevel_type) {}
};
void VisitDeclForTypeUsageVisitorHandler(ClangCursor cursor,
VisitDeclForTypeUsageParam* param) {
param->has_processed_any = true;
IndexFile* db = param->db;
// For |A<int> a| where there is a specialization for |A<int>|,
// the |referenced_usr| below resolves to the primary template and
// attributes the use to the primary template instead of the specialization.
// |toplevel_type| is retrieved |clang_getCursorType| which can be a
// specialization. If its name is the same as the primary template's, we
// assume the use should be attributed to the specialization. This heuristic
// fails when a member class bears the same name with its container.
//
// template<class T>
// struct C { struct C {}; };
// C<int>::C a;
//
// We will attribute |::C| to the parent class.
if (param->toplevel_type) {
IndexType* ref_type = db->Resolve(*param->toplevel_type);
std::string name = cursor.get_referenced().get_spell_name();
if (name == ref_type->def.ShortName()) {
AddUseSpell(db, ref_type->uses, cursor);
param->toplevel_type = nullopt;
return;
}
}
std::string referenced_usr =
cursor.get_referenced()
.template_specialization_to_template_definition()
.get_usr();
// TODO: things in STL cause this to be empty. Figure out why and document it.
if (referenced_usr == "")
return;
IndexTypeId ref_type_id = db->ToTypeId(HashUsr(referenced_usr));
if (!param->initial_type)
param->initial_type = ref_type_id;
IndexType* ref_type_def = db->Resolve(ref_type_id);
// TODO: Should we even be visiting this if the file is not from the main
// def? Try adding assert on |loc| later.
AddUseSpell(db, ref_type_def->uses, cursor);
}
ClangCursor::VisitResult VisitDeclForTypeUsageVisitor(
ClangCursor cursor,
ClangCursor parent,
VisitDeclForTypeUsageParam* param) {
switch (cursor.get_kind()) {
case CXCursor_TemplateRef:
case CXCursor_TypeRef:
if (param->previous_cursor) {
VisitDeclForTypeUsageVisitorHandler(param->previous_cursor.value(),
param);