forked from Andersbakken/rtags
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ClangIndexer.cpp
2537 lines (2343 loc) · 94.5 KB
/
ClangIndexer.cpp
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
/* This file is part of RTags (http://rtags.net).
RTags 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 3 of the License, or
(at your option) any later version.
RTags 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 RTags. If not, see <http://www.gnu.org/licenses/>. */
#define RTAGS_SINGLE_THREAD
#include "ClangIndexer.h"
#include <unistd.h>
#if CINDEX_VERSION >= CINDEX_VERSION_ENCODE(0, 25)
#include <clang-c/Documentation.h>
#endif
#include "Diagnostic.h"
#include "FileMap.h"
#include "QueryMessage.h"
#include "RClient.h"
#include "rct/Connection.h"
#include "rct/EventLoop.h"
#include "rct/SHA256.h"
#include "RTags.h"
#include "RTagsVersion.h"
#include "VisitFileMessage.h"
#include "VisitFileResponseMessage.h"
#include "Location.h"
static inline String usr(const CXCursor &cursor)
{
return RTags::eatString(clang_getCursorUSR(clang_getCanonicalCursor(cursor)));
}
static inline void setType(Symbol &symbol, const CXType &type)
{
symbol.type = type.kind;
symbol.typeName = RTags::eatString(clang_getTypeSpelling(type));
const CXType canonical = clang_getCanonicalType(type);
if (!clang_equalTypes(type, canonical)
#if CINDEX_VERSION >= CINDEX_VERSION_ENCODE(0, 32)
&& (symbol.typeName == "auto" || type.kind != CXType_Auto)
#endif
) {
symbol.typeName += " => " + RTags::eatString(clang_getTypeSpelling(canonical));
}
}
static inline void setRange(Symbol &symbol, const CXSourceRange &range, uint16_t *length = 0)
{
CXSourceLocation rangeStart = clang_getRangeStart(range);
CXSourceLocation rangeEnd = clang_getRangeEnd(range);
unsigned int startLine, startColumn, endLine, endColumn, startOffset, endOffset;
clang_getSpellingLocation(rangeStart, 0, &startLine, &startColumn, &startOffset);
clang_getSpellingLocation(rangeEnd, 0, &endLine, &endColumn, &endOffset);
symbol.startLine = startLine;
symbol.endLine = endLine;
symbol.startColumn = startColumn;
symbol.endColumn = endColumn;
if (length)
*length = static_cast<uint16_t>(endOffset - startOffset);
}
struct VerboseVisitorUserData {
int indent;
String out;
ClangIndexer *indexer;
};
Flags<Server::Option> ClangIndexer::sServerOpts;
Path ClangIndexer::sServerSandboxRoot;
ClangIndexer::ClangIndexer()
: mCurrentTranslationUnit(String::npos), mLastCursor(clang_getNullCursor()),
mLastCallExprSymbol(0), mVisitFileResponseMessageFileId(0),
mVisitFileResponseMessageVisit(0), mParseDuration(0), mVisitDuration(0), mBlocked(0),
mAllowed(0), mIndexed(1), mVisitFileTimeout(0), mIndexDataMessageTimeout(0),
mFileIdsQueried(0), mFileIdsQueriedTime(0), mCursorsVisited(0), mLogFile(0),
mConnection(Connection::create(RClient::NumOptions)), mUnionRecursion(false),
mInTemplateFunction(0)
{
mConnection->newMessage().connect(std::bind(&ClangIndexer::onMessage, this,
std::placeholders::_1, std::placeholders::_2));
}
ClangIndexer::~ClangIndexer()
{
if (mLogFile)
fclose(mLogFile);
}
bool ClangIndexer::exec(const String &data)
{
Deserializer deserializer(data);
uint16_t protocolVersion;
deserializer >> protocolVersion;
if (protocolVersion != RTags::DatabaseVersion) {
error("Wrong protocol %d vs %d", protocolVersion, RTags::DatabaseVersion);
return false;
}
uint64_t id;
String socketFile;
Flags<IndexerJob::Flag> indexerJobFlags;
uint32_t connectTimeout, connectAttempts;
int32_t niceValue;
Hash<uint32_t, Path> blockedFiles;
deserializer >> sServerSandboxRoot;
deserializer >> id;
deserializer >> socketFile;
deserializer >> mProject;
uint32_t count;
deserializer >> count;
mSources.resize(count);
for (uint32_t i=0; i<count; ++i) {
mSources[i].decode(deserializer, Source::IgnoreSandbox);
}
deserializer >> mSourceFile;
deserializer >> indexerJobFlags;
deserializer >> mVisitFileTimeout;
deserializer >> mIndexDataMessageTimeout;
deserializer >> connectTimeout;
deserializer >> connectAttempts;
deserializer >> niceValue;
deserializer >> sServerOpts;
deserializer >> mUnsavedFiles;
deserializer >> mDataDir;
deserializer >> mDebugLocations;
deserializer >> blockedFiles;
if (sServerOpts & Server::NoRealPath) {
Path::setRealPathEnabled(false);
}
#if 0
while (true) {
FILE *f = fopen((String("/tmp/stop_") + mSourceFile.fileName()).constData(), "r+");
if (f) {
fseek(f, 0, SEEK_END);
fprintf(f, "Waiting ... %d\n", getpid());
fclose(f);
sleep(1);
} else {
break;
}
}
#endif
const uint64_t parseTime = Rct::currentTimeMs();
if (niceValue != INT_MIN) {
errno = 0;
if (nice(niceValue) == -1) {
error() << "Failed to nice rp" << Rct::strerror();
}
}
if (mSourceFile.isEmpty()) {
error("No sourcefile");
return false;
}
switch (mSources.size()) {
case 0:
error("No sourcefile");
return false;
case 1:
if (!mSources.front().fileId) {
error("Bad fileId");
return false;
}
default:
for (size_t i=1; i<mSources.size(); ++i) {
if (!mSources.at(i).fileId || mSources.at(i).fileId != mSources.front().fileId) {
error("Bad fileId");
return false;
}
}
}
if (mProject.isEmpty()) {
error("No project");
return false;
}
Location::init(blockedFiles);
Location::set(mSourceFile, mSources.front().fileId);
while (true) {
if (mConnection->connectUnix(socketFile, connectTimeout))
break;
if (!--connectAttempts) {
error("Failed to connect to rdm on %s (%dms timeout)", socketFile.constData(), connectTimeout);
return false;
}
usleep(500 * 1000);
}
// mLogFile = fopen(String::format("/tmp/%s", mSourceFile.fileName()).constData(), "w");
mIndexDataMessage.setProject(mProject);
mIndexDataMessage.setIndexerJobFlags(indexerJobFlags);
mIndexDataMessage.setParseTime(parseTime);
mIndexDataMessage.setFileId(mSources.front().fileId);
mIndexDataMessage.setId(id);
assert(mConnection->isConnected());
assert(mSources.front().fileId);
mIndexDataMessage.files()[mSources.front().fileId] |= IndexDataMessage::Visited;
parse() && visit() && diagnose();
String message = mSourceFile.toTilde();
String err;
StopWatch sw;
int writeDuration = -1;
bool hasUnit = false;
for (const auto &u : mTranslationUnits) {
if (u->unit) {
hasUnit = true;
break;
}
}
if (!hasUnit || !writeFiles(RTags::encodeSourceFilePath(mDataDir, mProject, 0), err)) {
message += " error";
if (!err.isEmpty())
message += (' ' + err);
} else {
writeDuration = sw.elapsed();
}
message += String::format<16>(" in %lldms. ", mTimer.elapsed());
if (mSources.size() > 1) {
message += String::format("(%zu builds) ", mSources.size());
}
int cursorCount = 0;
int symbolNameCount = 0;
for (const auto &unit : mUnits) {
cursorCount += unit.second->symbols.size();
symbolNameCount += unit.second->symbolNames.size();
}
if (hasUnit) {
String queryData;
if (mFileIdsQueried)
queryData = String::format(", %d queried %dms", mFileIdsQueried, mFileIdsQueriedTime);
const char *format = "(%d syms, %d symNames, %d includes, %d of %d files, symbols: %d of %d, %d cursors, %zu bytes written%s%s) (%d/%d/%dms)";
message += String::format<1024>(format, cursorCount, symbolNameCount,
mIndexDataMessage.includes().size(), mIndexed,
mIndexDataMessage.files().size(), mAllowed,
mAllowed + mBlocked, mCursorsVisited,
mIndexDataMessage.bytesWritten(),
queryData.constData(), mIndexDataMessage.flags() & IndexDataMessage::UsedPCH ? ", pch" : "",
mParseDuration, mVisitDuration, writeDuration);
}
if (mIndexDataMessage.indexerJobFlags() & IndexerJob::Dirty) {
message += " (dirty)";
} else if (mIndexDataMessage.indexerJobFlags() & IndexerJob::Reindex) {
message += " (reindex)";
}
mIndexDataMessage.setMessage(message);
sw.restart();
if (!mConnection->send(mIndexDataMessage)) {
error() << "Couldn't send IndexDataMessage" << mSourceFile;
return false;
}
mConnection->finished().connect(std::bind(&EventLoop::quit, EventLoop::eventLoop()));
if (EventLoop::eventLoop()->exec(mIndexDataMessageTimeout) == EventLoop::Timeout) {
error() << "Timed out sending IndexDataMessage" << mSourceFile;
return false;
}
if (getenv("RDM_DEBUG_INDEXERMESSAGE"))
error() << "Send took" << sw.elapsed() << "for" << mSourceFile;
return true;
}
void ClangIndexer::onMessage(const std::shared_ptr<Message> &msg, const std::shared_ptr<Connection> &/*conn*/)
{
assert(msg->messageId() == VisitFileResponseMessage::MessageId);
const std::shared_ptr<VisitFileResponseMessage> vm = std::static_pointer_cast<VisitFileResponseMessage>(msg);
mVisitFileResponseMessageVisit = vm->visit();
mVisitFileResponseMessageFileId = vm->fileId();
assert(EventLoop::eventLoop());
EventLoop::eventLoop()->quit();
}
Location ClangIndexer::createLocation(const Path &sourceFile, unsigned int line, unsigned int col, bool *blockedPtr)
{
uint32_t id = Location::fileId(sourceFile);
Path resolved;
if (!id) {
bool ok;
for (int i=0; i<4; ++i) {
resolved = sourceFile.resolved(Path::RealPath, Path(), &ok);
// if ok is false it means the file is gone, in case this happens
// during a git pull or something we'll give it a couple of chances.
if (ok)
break;
usleep(50000);
}
if (!ok)
return Location();
id = Location::fileId(resolved);
if (id)
Location::set(sourceFile, id);
}
assert(!resolved.contains("/../"));
if (id) {
if (blockedPtr) {
Hash<uint32_t, Flags<IndexDataMessage::FileFlag> >::iterator it = mIndexDataMessage.files().find(id);
if (it == mIndexDataMessage.files().end()) {
// the only reason we already have an id for a file that isn't
// in the mIndexDataMessage.mFiles is that it's blocked from the outset.
// The assumption is that we never will go and fetch a file id
// for a location without passing blockedPtr since any reference
// to a symbol in another file should have been preceded by that
// header in which case we would have to make a decision on
// whether or not to index it. This is a little hairy but we
// have to try to optimize this process.
#ifndef NDEBUG
if (resolved.isEmpty())
resolved = sourceFile.resolved();
#endif
assert(id);
mIndexDataMessage.files()[id] = IndexDataMessage::NoFileFlag;
*blockedPtr = true;
} else if (!it->second) {
*blockedPtr = true;
}
}
return Location(id, line, col);
}
++mFileIdsQueried;
VisitFileMessage msg(resolved, mProject, mIndexDataMessage.fileId());
mVisitFileResponseMessageFileId = UINT_MAX;
mVisitFileResponseMessageVisit = false;
mConnection->send(msg);
StopWatch sw;
EventLoop::eventLoop()->exec(mVisitFileTimeout);
const int elapsed = sw.elapsed();
mFileIdsQueriedTime += elapsed;
switch (mVisitFileResponseMessageFileId) {
case 0:
return Location();
case UINT_MAX:
// timed out.
if (mVisitFileResponseMessageFileId == UINT_MAX) {
error() << "Error getting fileId for" << resolved << mLastCursor
<< elapsed << mVisitFileTimeout;
}
exit(1);
default:
id = mVisitFileResponseMessageFileId;
break;
}
assert(id);
Flags<IndexDataMessage::FileFlag> &flags = mIndexDataMessage.files()[id];
if (mVisitFileResponseMessageVisit) {
flags |= IndexDataMessage::Visited;
++mIndexed;
}
// fprintf(mLogFile, "%s %s\n", file.second ? "WON" : "LOST", resolved.constData());
Location::set(resolved, id);
if (resolved != sourceFile)
Location::set(sourceFile, id);
if (blockedPtr && !mVisitFileResponseMessageVisit) {
*blockedPtr = true;
}
return Location(id, line, col);
}
static inline void tokenize(const char *buf, int start,
int *templateStart, int *templateEnd,
int *sectionCount, int sections[1024])
{
int templateCount = 0;
*templateStart = *templateEnd = -1;
*sectionCount = 1;
sections[0] = start;
int functionStart = -1;
int functionEnd = -1;
int idx = start;
while (true) {
switch (buf[++idx]) {
case '<':
if (buf[idx + 1] == '<') {
++idx;
} else if (functionStart == -1 && (idx - 8 < 0 || strncmp("operator", buf + idx - 8, 8) != 0)) {
if (!templateCount++)
*templateStart = idx;
}
break;
case '>':
if (buf[idx + 1] == '>') {
++idx;
} else if (functionStart == -1 && (idx - 8 < 0 || strncmp("operator", buf + idx - 8, 8) != 0)) {
if (!--templateCount)
*templateEnd = idx;
}
break;
case '(':
if (!templateCount)
functionStart = idx;
break;
case ')':
if (!templateCount)
functionEnd = idx;
break;
case ':':
if (!templateCount && (functionStart == -1 || functionEnd != -1) && buf[idx + 1] == ':' && (*sectionCount) < 1024) {
sections[(*sectionCount)++] = idx + 2;
++idx;
}
break;
case '\0':
if (templateCount) {
*templateStart = *templateEnd = -1;
}
return;
}
}
}
String ClangIndexer::addNamePermutations(const CXCursor &cursor, Location location, RTags::CursorType cursorType)
{
CXCursorKind kind = clang_getCursorKind(cursor);
const CXCursorKind originalKind = kind;
char buf[1024 * 512];
int pos = sizeof(buf) - 1;
buf[pos] = '\0';
int cutoff = -1;
CXCursor c = cursor;
do {
CXStringScope displayName(clang_getCursorDisplayName(c));
const char *name = displayName.data();
if (!name)
break;
const int len = strlen(name);
if (!len)
break;
if (pos != sizeof(buf) - 1) {
pos -= 2;
if (pos >= 0)
memset(buf + pos, ':', 2);
}
pos -= len;
if (pos < 0) {
error("SymbolName too long. Giving up");
return String();
}
memcpy(buf + pos, name, len);
c = clang_getCursorSemanticParent(c);
kind = clang_getCursorKind(c);
if (cutoff == -1) {
switch (kind) {
case CXCursor_ClassDecl:
case CXCursor_ClassTemplate:
case CXCursor_StructDecl:
break;
case CXCursor_Namespace:
// namespaces can include all namespaces in their symbolname
if (originalKind == CXCursor_Namespace)
break;
default:
cutoff = pos;
break;
}
}
} while (RTags::needsQualifiers(kind));
if (static_cast<size_t>(pos) == sizeof(buf) - 1) {
return String();
}
String type;
String trailer;
switch (originalKind) {
case CXCursor_StructDecl:
type = "struct ";
break;
case CXCursor_ClassDecl:
case CXCursor_ClassTemplate:
type = "class ";
break;
case CXCursor_Namespace:
type = "namespace ";
break;
case CXCursor_Destructor:
case CXCursor_Constructor:
break;
default: {
type = RTags::eatString(clang_getTypeSpelling(clang_getCanonicalType(clang_getCursorType(cursor))));
if (originalKind == CXCursor_FunctionDecl || originalKind == CXCursor_CXXMethod || originalKind == CXCursor_FunctionTemplate) {
const size_t idx = type.indexOf(" -> ");
if (idx != String::npos)
trailer = type.mid(idx);
}
const size_t paren = type.indexOf('(');
if (paren != String::npos) {
type.resize(paren);
} else if (!type.isEmpty() && !type.endsWith('*') && !type.endsWith('&')) {
type.append(' ');
}
break; }
}
if (cutoff == -1)
cutoff = pos;
String ret;
if (!type.isEmpty()) {
ret = type;
ret.append(buf + cutoff, std::max<int>(0, sizeof(buf) - cutoff - 1));
if (!trailer.isEmpty()) {
ret += trailer;
if (cursorType != RTags::Type_Reference)
unit(location.fileId())->symbolNames[ret].insert(location);
}
} else {
ret.assign(buf + cutoff, std::max<int>(0, sizeof(buf) - cutoff - 1));
}
if (cursorType == RTags::Type_Reference) {
return ret;
}
int templateStart, templateEnd, colonColonCount;
int colonColons[1024];
::tokenize(buf, pos,
&templateStart, &templateEnd,
&colonColonCount, colonColons);
assert((templateStart != -1) == (templateEnd != -1));
// i == 0 --> with templates,
// i == 1 without templates or without EnumConstantDecl part
for (int i=0; i<2; ++i) {
for (int j=0; j<colonColonCount; ++j) {
const char *ch = buf + colonColons[j];
const String name(ch, std::max<int>(0, sizeof(buf) - (ch - buf) - 1));
if (name.isEmpty())
continue;
unit(location.fileId())->symbolNames[name].insert(location);
if (!type.isEmpty() && (originalKind != CXCursor_ParmDecl || !strchr(ch, '('))) {
// We only want to add the type to the final declaration for ParmDecls
// e.g.
// void foo(int)::bar
// and
// int bar
//
// not
// int void foo(int)::bar
// or
// void foo(int)::int bar
unit(location.fileId())->symbolNames[type + name].insert(location);
}
}
if (i == 1 || (templateStart == -1 && originalKind != CXCursor_EnumConstantDecl)) {
// nothing more to do
break;
}
if (originalKind == CXCursor_EnumConstantDecl) { // remove CXCursor_EnumDecl
// struct A { enum B { C } };
// Will by default generate a A::B::C symbolname.
// This code removes the B:: part from it
if (colonColonCount > 2) {
const char *last = buf + colonColons[colonColonCount - 1];
const char *secondLast = buf + colonColons[colonColonCount - 2];
const int len = (last - secondLast);
memmove(buf + pos + len, buf + pos, secondLast - (buf + pos));
pos += len;
}
} else { // remove templates
assert(templateStart != -1);
assert(templateEnd != -1);
const int templateSize = (templateEnd - templateStart) + 1;
memmove(buf + pos + templateSize, buf + pos, (buf + templateStart) - (buf + pos));
pos += templateSize;
}
// ### We could/should just move the colon colon values but this
// should be pretty quick and I don't want to write the code to
// do it.
::tokenize(buf, pos,
&templateStart, &templateEnd,
&colonColonCount, colonColons);
}
return ret;
}
static inline CXCursor findDestructorForDelete(const CXCursor &deleteStatement)
{
const CXCursor child = RTags::findFirstChild(deleteStatement);
CXCursorKind kind = clang_getCursorKind(child);
switch (kind) {
case CXCursor_UnexposedExpr:
case CXCursor_CallExpr:
break;
default:
return clang_getNullCursor();
}
const CXCursor var = clang_getCursorReferenced(child);
kind = clang_getCursorKind(var);
switch (kind) {
case CXCursor_ObjCIvarDecl:
case CXCursor_VarDecl:
case CXCursor_FieldDecl:
case CXCursor_ParmDecl:
case CXCursor_CXXMethod:
case CXCursor_FunctionDecl:
case CXCursor_ConversionFunction:
break;
default:
if (!clang_isInvalid(kind)) {
error() << "Got unexpected cursor" << deleteStatement << var;
// assert(0);
}
return clang_getNullCursor();
}
CXCursor ref = RTags::findChild(var, CXCursor_TypeRef);
if (ref != CXCursor_TypeRef)
ref = RTags::findChild(var, CXCursor_TemplateRef);
kind = clang_getCursorKind(ref);
switch (kind) {
case CXCursor_TypeRef:
case CXCursor_TemplateRef:
break;
default:
return clang_getNullCursor();
}
const CXCursor referenced = clang_getCursorReferenced(ref);
kind = clang_getCursorKind(referenced);
switch (kind) {
case CXCursor_StructDecl:
case CXCursor_ClassDecl:
case CXCursor_ClassTemplate:
break;
default:
return clang_getNullCursor();
}
const CXCursor destructor = RTags::findChild(referenced, CXCursor_Destructor);
return destructor;
}
CXChildVisitResult ClangIndexer::visitorHelper(CXCursor cursor, CXCursor, CXClientData data)
{
ClangIndexer *indexer = static_cast<ClangIndexer*>(data);
const CXChildVisitResult res = indexer->indexVisitor(cursor);
if (res == CXChildVisit_Recurse)
indexer->visit(cursor);
return CXChildVisit_Continue;
}
CXChildVisitResult ClangIndexer::indexVisitor(CXCursor cursor)
{
++mCursorsVisited;
// error() << "indexVisitor" << cursor;
// FILE *f = fopen("/tmp/clangindex.log", "a");
// String str;
// Log(&str) << cursor;
// fwrite(str.constData(), 1, str.size(), f);
// fwrite("\n", 1, 1, f);
// fclose(f);
const CXCursorKind kind = clang_getCursorKind(cursor);
const RTags::CursorType type = RTags::cursorType(kind);
if (type == RTags::Type_Other) {
return CXChildVisit_Recurse;
}
struct UpdateLastCursor {
~UpdateLastCursor() { func(); }
std::function<void()> func;
} call = { [this, cursor]() { mLastCursor = cursor; } };
bool blocked = false;
Location loc = createLocation(cursor, &blocked);
if (blocked) {
++mBlocked;
return CXChildVisit_Continue;
} else if (loc.isNull()) {
// error() << "Got null" << cursor;
return CXChildVisit_Recurse;
}
for (const String &debug : mDebugLocations) {
if (debug == "all" || debug == loc) {
Log log(LogLevel::Error);
log << cursor;
CXCursor ref = clang_getCursorReferenced(cursor);
if (!clang_isInvalid(clang_getCursorKind(ref)) && ref != cursor) {
log << "refs" << ref;
}
break;
}
}
++mAllowed;
if (mLogFile) {
String out;
Log(&out) << cursor;
fwrite(out.constData(), 1, out.size(), mLogFile);
fwrite("\n", 1, 1, mLogFile);
}
if (testLog(LogLevel::VerboseDebug)) {
Log log(LogLevel::VerboseDebug);
log << cursor;
CXCursor ref = clang_getCursorReferenced(cursor);
if (!clang_isInvalid(clang_getCursorKind(ref)) && ref != cursor) {
log << "refs" << ref;
}
}
if (Symbol::isClass(kind)) {
mLastClass = loc;
} else {
if (kind == CXCursor_CXXBaseSpecifier) {
handleBaseClassSpecifier(cursor);
return CXChildVisit_Recurse;
}
}
CXChildVisitResult visitResult = CXChildVisit_Recurse;
switch (type) {
case RTags::Type_Cursor:
visitResult = handleCursor(cursor, kind, loc);
break;
case RTags::Type_Include:
handleInclude(cursor, kind, loc);
break;
case RTags::Type_Literal:
handleLiteral(cursor, kind, loc);
break;
case RTags::Type_Statement:
visitResult = handleStatement(cursor, kind, loc);
break;
case RTags::Type_Reference:
switch (kind) {
case CXCursor_OverloadedDeclRef: {
const int count = clang_getNumOverloadedDecls(cursor);
for (int i=0; i<count; ++i) {
const CXCursor ref = clang_getOverloadedDecl(cursor, i);
handleReference(cursor, kind, loc, ref);
}
break; }
case CXCursor_CXXDeleteExpr:
handleReference(cursor, kind, loc, findDestructorForDelete(cursor));
break;
case CXCursor_CallExpr: {
// uglehack, see rtags/tests/nestedClassConstructorCallUgleHack/
List<Symbol::Argument> arguments;
extractArguments(&arguments, cursor);
Symbol *old = 0;
Location oldLoc;
std::swap(mLastCallExprSymbol, old);
const CXCursor ref = clang_getCursorReferenced(cursor);
if (clang_getCursorKind(ref) == CXCursor_Constructor
&& (clang_getCursorKind(mLastCursor) == CXCursor_TypeRef || clang_getCursorKind(mLastCursor) == CXCursor_TemplateRef)
&& clang_getCursorKind(mParents.back()) != CXCursor_VarDecl) {
loc = createLocation(mLastCursor);
handleReference(mLastCursor, kind, loc, ref);
} else {
handleReference(cursor, kind, loc, ref);
}
List<Symbol::Argument> destArguments;
extractArguments(&destArguments, ref);
visit(cursor);
if (mLastCallExprSymbol && !arguments.isEmpty()) {
const Location invokedLocation = createLocation(ref);
auto u = unit(loc);
size_t idx = 0;
for (const auto &arg : arguments) {
const auto destArg = destArguments.value(idx);
if (destArg.location.isNull())
break;
const Location start = arg.location;
Location end;
if (idx + 1 == arguments.size()) {
end = Location(start.fileId(), start.line(), start.column() + arg.length); // this falls apart with multi-line args
} else {
end = arguments.value(idx + 1).location;
}
auto it = u->symbols.lower_bound(start);
while (it != u->symbols.end() && it->first < end) {
auto &sym = it->second;
sym.argumentUsage.index = idx;
sym.argumentUsage.invokedFunction = invokedLocation;
sym.argumentUsage.argument = destArg;
sym.argumentUsage.invocation = mLastCallExprSymbol->location;
++it;
}
++idx;
}
mLastCallExprSymbol->arguments = std::move(arguments);
}
std::swap(old, mLastCallExprSymbol);
visitResult = CXChildVisit_Continue;
break; }
default:
handleReference(cursor, kind, loc, clang_getCursorReferenced(cursor));
break;
}
break;
case RTags::Type_Other:
assert(0);
break;
}
return visitResult;
}
static inline bool isImplicit(const CXCursor &cursor)
{
return clang_equalLocations(clang_getCursorLocation(cursor),
clang_getCursorLocation(clang_getCursorSemanticParent(cursor)));
}
bool ClangIndexer::superclassTemplateMemberFunctionUgleHack(const CXCursor &cursor, CXCursorKind kind,
Location location, const CXCursor &/*ref*/,
Symbol **cursorPtr)
{
// This is for references to superclass template functions. Awful awful
// shit. See https://github.com/Andersbakken/rtags/issues/62 and commit
// for details. I really should report this as a bug.
if (cursorPtr)
*cursorPtr = 0;
if (kind != CXCursor_MemberRefExpr && clang_getCursorKind(mParents.last()) != CXCursor_CallExpr)
return false;
const CXCursor templateRef = RTags::findChild(cursor, CXCursor_TemplateRef);
if (templateRef != CXCursor_TemplateRef)
return false;
const CXCursor classTemplate = clang_getCursorReferenced(templateRef);
if (classTemplate != CXCursor_ClassTemplate)
return false;
FILE *f = fopen(location.path().constData(), "r");
if (!f)
return false;
const CXSourceRange range = clang_getCursorExtent(cursor);
const CXSourceLocation end = clang_getRangeEnd(range);
unsigned int offset;
clang_getSpellingLocation(end, 0, 0, 0, &offset);
String name;
while (offset > 0) {
fseek(f, --offset, SEEK_SET);
char ch = static_cast<char>(fgetc(f));
if (isalnum(ch) || ch == '_' || ch == '~') {
name.prepend(ch);
} else {
break;
}
}
fclose(f);
if (!name.isEmpty()) {
RTags::Filter out;
out.kinds.insert(CXCursor_MemberRefExpr);
const int argCount = RTags::children(mParents.last(), RTags::Filter(), out).size();
RTags::Filter in(RTags::Filter::And);
in.names.insert(name);
in.argumentCount = argCount;
const List<CXCursor> alternatives = RTags::children(classTemplate, in);
switch (alternatives.size()) {
case 1:
// ### not sure this is correct with line/col
return handleReference(cursor, kind,
Location(location.fileId(), location.line(), location.column() + 1),
alternatives.first(), cursorPtr);
break;
case 0:
break;
default:
warning() << "Can't decide which of these symbols are right for me"
<< cursor << alternatives
<< "Need to parse types";
break;
}
}
return false;
}
bool ClangIndexer::handleReference(const CXCursor &cursor, CXCursorKind kind, Location location, CXCursor ref, Symbol **cursorPtr)
{
if (cursorPtr)
*cursorPtr = 0;
// error() << "handleReference" << cursor << kind << location << ref;
const CXCursorKind refKind = clang_getCursorKind(ref);
if (clang_isInvalid(refKind)) {
return superclassTemplateMemberFunctionUgleHack(cursor, kind, location, ref, cursorPtr);
}
const CXCursor originalRef = ref;
bool isOperator = false;
if (kind == CXCursor_CallExpr && (refKind == CXCursor_CXXMethod
|| refKind == CXCursor_FunctionDecl
|| refKind == CXCursor_FunctionTemplate)) {
// These are bullshit. for this construct:
// foo.bar();
// the position of the cursor is at the foo, not the bar.
// They are not interesting for followLocation, renameSymbol or find
// references so we toss them.
// For functions it can be the position of the namespace.
// E.g. Foo::bar(); cursor is on Foo
// For constructors they happen to be the only thing we have that
// actually refs the constructor and not the class so we have to keep
// them for that.
return false;
}
Location refLoc = createLocation(ref);
if (!refLoc.isValid()) {
// ### THIS IS NOT SOLVED
// if (kind == CXCursor_ObjCMessageExpr) {
// mIndexDataMessage.mPendingReferenceMap[RTags::eatString(clang_getCursorUSR(clang_getCanonicalCursor(ref)))].insert(location);
// // insert it, we'll hook up the target and references later
// return handleCursor(cursor, kind, location, cursorPtr);
// }
return false;
}
switch (refKind) {
case CXCursor_Constructor:
case CXCursor_CXXMethod:
case CXCursor_FunctionDecl:
case CXCursor_Destructor:
case CXCursor_FunctionTemplate: {
bool visitReference = false;
ref = resolveTemplate(ref, refLoc, &visitReference);
if (visitReference && (kind == CXCursor_DeclRefExpr || kind == CXCursor_MemberRefExpr)) {
mTemplateSpecializations.insert(originalRef);
}
if (refKind == CXCursor_FunctionDecl)
break;
if (refKind == CXCursor_Constructor || refKind == CXCursor_Destructor) {
if (isImplicit(ref)) {
return false;
}
} else {
CXStringScope scope = clang_getCursorDisplayName(ref);
const char *data = scope.data();
if (data) {
const int len = strlen(data);
if (len > 8 && !strncmp(data, "operator", 8) && !isalnum(data[8]) && data[8] != '_') {
if (isImplicit(ref)) {
return false; // eat implicit operator calls
}
isOperator = true;
}
}
}
break; }
default:
break;
}
const String refUsr = usr(ref);
if (refUsr.isEmpty()) {
return false;
}
FindResult result;
auto reffedCursor = findSymbol(refLoc, &result);
Map<String, uint16_t> &targets = unit(location)->targets[location];
if (result == NotFound && !mUnionRecursion) {
CXCursor parent = clang_getCursorSemanticParent(ref);
CXCursor best = clang_getNullCursor();
while (true) {
if (clang_getCursorKind(parent) != CXCursor_UnionDecl)
break;
best = parent;
parent = clang_getCursorSemanticParent(parent);
}
if (best == CXCursor_UnionDecl) {
mUnionRecursion = true;
// for anonymous unions we don't get to their fields with normal
// recursing of the AST. In these cases we visit the union decl
visit(best);
mUnionRecursion = false;
reffedCursor = findSymbol(refLoc, &result);
}
}
int16_t refTargetValue;