blob: 210e74bf59cbdf20096f461b14bd404039465e11 [file] [log] [blame]
Guy Benyei11169dd2012-12-18 14:30:41 +00001//===- CIndex.cpp - Clang-C Source Indexing Library -----------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the main API hooks in the Clang-C Source Indexing
11// library.
12//
13//===----------------------------------------------------------------------===//
14
Guy Benyei11169dd2012-12-18 14:30:41 +000015#include "CIndexDiagnostic.h"
Mehdi Amini9670f842016-07-18 19:02:11 +000016#include "CIndexer.h"
Chandler Carruth4b417452013-01-19 08:09:44 +000017#include "CLog.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000018#include "CXCursor.h"
19#include "CXSourceLocation.h"
20#include "CXString.h"
21#include "CXTranslationUnit.h"
22#include "CXType.h"
23#include "CursorVisitor.h"
David Blaikie0a4e61f2013-09-13 18:32:52 +000024#include "clang/AST/Attr.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000025#include "clang/AST/StmtVisitor.h"
26#include "clang/Basic/Diagnostic.h"
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +000027#include "clang/Basic/DiagnosticCategories.h"
28#include "clang/Basic/DiagnosticIDs.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000029#include "clang/Basic/Version.h"
30#include "clang/Frontend/ASTUnit.h"
31#include "clang/Frontend/CompilerInstance.h"
32#include "clang/Frontend/FrontendDiagnostic.h"
Argyrios Kyrtzidisca741ce2016-02-14 22:30:14 +000033#include "clang/Index/CodegenNameGenerator.h"
Dmitri Gribenko9e605112013-11-13 22:16:51 +000034#include "clang/Index/CommentToXML.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000035#include "clang/Lex/HeaderSearch.h"
36#include "clang/Lex/Lexer.h"
37#include "clang/Lex/PreprocessingRecord.h"
38#include "clang/Lex/Preprocessor.h"
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +000039#include "clang/Serialization/SerializationDiagnostic.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000040#include "llvm/ADT/Optional.h"
41#include "llvm/ADT/STLExtras.h"
42#include "llvm/ADT/StringSwitch.h"
Alp Toker1d257e12014-06-04 03:28:55 +000043#include "llvm/Config/llvm-config.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000044#include "llvm/Support/Compiler.h"
45#include "llvm/Support/CrashRecoveryContext.h"
Chandler Carruth4b417452013-01-19 08:09:44 +000046#include "llvm/Support/Format.h"
Chandler Carruth37ad2582014-06-27 15:14:39 +000047#include "llvm/Support/ManagedStatic.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000048#include "llvm/Support/MemoryBuffer.h"
49#include "llvm/Support/Mutex.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000050#include "llvm/Support/Program.h"
51#include "llvm/Support/SaveAndRestore.h"
52#include "llvm/Support/Signals.h"
Adrian Prantlbc068582015-07-08 01:00:30 +000053#include "llvm/Support/TargetSelect.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000054#include "llvm/Support/Threading.h"
55#include "llvm/Support/Timer.h"
56#include "llvm/Support/raw_ostream.h"
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +000057
Alp Toker1a86ad22014-07-06 06:24:00 +000058#if LLVM_ENABLE_THREADS != 0 && defined(__APPLE__)
59#define USE_DARWIN_THREADS
60#endif
61
62#ifdef USE_DARWIN_THREADS
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +000063#include <pthread.h>
64#endif
Guy Benyei11169dd2012-12-18 14:30:41 +000065
66using namespace clang;
67using namespace clang::cxcursor;
Guy Benyei11169dd2012-12-18 14:30:41 +000068using namespace clang::cxtu;
69using namespace clang::cxindex;
70
Dmitri Gribenkod36209e2013-01-26 21:32:42 +000071CXTranslationUnit cxtu::MakeCXTranslationUnit(CIndexer *CIdx, ASTUnit *AU) {
72 if (!AU)
Craig Topper69186e72014-06-08 08:38:04 +000073 return nullptr;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +000074 assert(CIdx);
Guy Benyei11169dd2012-12-18 14:30:41 +000075 CXTranslationUnit D = new CXTranslationUnitImpl();
76 D->CIdx = CIdx;
Dmitri Gribenkod36209e2013-01-26 21:32:42 +000077 D->TheASTUnit = AU;
Dmitri Gribenko74895212013-02-03 13:52:47 +000078 D->StringPool = new cxstring::CXStringPool();
Craig Topper69186e72014-06-08 08:38:04 +000079 D->Diagnostics = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +000080 D->OverridenCursorsPool = createOverridenCXCursorsPool();
Craig Topper69186e72014-06-08 08:38:04 +000081 D->CommentToXML = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +000082 return D;
83}
84
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +000085bool cxtu::isASTReadError(ASTUnit *AU) {
86 for (ASTUnit::stored_diag_iterator D = AU->stored_diag_begin(),
87 DEnd = AU->stored_diag_end();
88 D != DEnd; ++D) {
89 if (D->getLevel() >= DiagnosticsEngine::Error &&
90 DiagnosticIDs::getCategoryNumberForDiag(D->getID()) ==
91 diag::DiagCat_AST_Deserialization_Issue)
92 return true;
93 }
94 return false;
95}
96
Guy Benyei11169dd2012-12-18 14:30:41 +000097cxtu::CXTUOwner::~CXTUOwner() {
98 if (TU)
99 clang_disposeTranslationUnit(TU);
100}
101
102/// \brief Compare two source ranges to determine their relative position in
103/// the translation unit.
104static RangeComparisonResult RangeCompare(SourceManager &SM,
105 SourceRange R1,
106 SourceRange R2) {
107 assert(R1.isValid() && "First range is invalid?");
108 assert(R2.isValid() && "Second range is invalid?");
109 if (R1.getEnd() != R2.getBegin() &&
110 SM.isBeforeInTranslationUnit(R1.getEnd(), R2.getBegin()))
111 return RangeBefore;
112 if (R2.getEnd() != R1.getBegin() &&
113 SM.isBeforeInTranslationUnit(R2.getEnd(), R1.getBegin()))
114 return RangeAfter;
115 return RangeOverlap;
116}
117
118/// \brief Determine if a source location falls within, before, or after a
119/// a given source range.
120static RangeComparisonResult LocationCompare(SourceManager &SM,
121 SourceLocation L, SourceRange R) {
122 assert(R.isValid() && "First range is invalid?");
123 assert(L.isValid() && "Second range is invalid?");
124 if (L == R.getBegin() || L == R.getEnd())
125 return RangeOverlap;
126 if (SM.isBeforeInTranslationUnit(L, R.getBegin()))
127 return RangeBefore;
128 if (SM.isBeforeInTranslationUnit(R.getEnd(), L))
129 return RangeAfter;
130 return RangeOverlap;
131}
132
133/// \brief Translate a Clang source range into a CIndex source range.
134///
135/// Clang internally represents ranges where the end location points to the
136/// start of the token at the end. However, for external clients it is more
137/// useful to have a CXSourceRange be a proper half-open interval. This routine
138/// does the appropriate translation.
139CXSourceRange cxloc::translateSourceRange(const SourceManager &SM,
140 const LangOptions &LangOpts,
141 const CharSourceRange &R) {
142 // We want the last character in this location, so we will adjust the
143 // location accordingly.
144 SourceLocation EndLoc = R.getEnd();
145 if (EndLoc.isValid() && EndLoc.isMacroID() && !SM.isMacroArgExpansion(EndLoc))
146 EndLoc = SM.getExpansionRange(EndLoc).second;
Yaron Keren8b563662015-10-03 10:46:20 +0000147 if (R.isTokenRange() && EndLoc.isValid()) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000148 unsigned Length = Lexer::MeasureTokenLength(SM.getSpellingLoc(EndLoc),
149 SM, LangOpts);
150 EndLoc = EndLoc.getLocWithOffset(Length);
151 }
152
Bill Wendlingeade3622013-01-23 08:25:41 +0000153 CXSourceRange Result = {
Dmitri Gribenkof9304482013-01-23 15:56:07 +0000154 { &SM, &LangOpts },
Bill Wendlingeade3622013-01-23 08:25:41 +0000155 R.getBegin().getRawEncoding(),
156 EndLoc.getRawEncoding()
157 };
Guy Benyei11169dd2012-12-18 14:30:41 +0000158 return Result;
159}
160
161//===----------------------------------------------------------------------===//
162// Cursor visitor.
163//===----------------------------------------------------------------------===//
164
165static SourceRange getRawCursorExtent(CXCursor C);
166static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr);
167
168
169RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
170 return RangeCompare(AU->getSourceManager(), R, RegionOfInterest);
171}
172
173/// \brief Visit the given cursor and, if requested by the visitor,
174/// its children.
175///
176/// \param Cursor the cursor to visit.
177///
178/// \param CheckedRegionOfInterest if true, then the caller already checked
179/// that this cursor is within the region of interest.
180///
181/// \returns true if the visitation should be aborted, false if it
182/// should continue.
183bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
184 if (clang_isInvalid(Cursor.kind))
185 return false;
186
187 if (clang_isDeclaration(Cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +0000188 const Decl *D = getCursorDecl(Cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +0000189 if (!D) {
190 assert(0 && "Invalid declaration cursor");
191 return true; // abort.
192 }
193
194 // Ignore implicit declarations, unless it's an objc method because
195 // currently we should report implicit methods for properties when indexing.
196 if (D->isImplicit() && !isa<ObjCMethodDecl>(D))
197 return false;
198 }
199
200 // If we have a range of interest, and this cursor doesn't intersect with it,
201 // we're done.
202 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
203 SourceRange Range = getRawCursorExtent(Cursor);
204 if (Range.isInvalid() || CompareRegionOfInterest(Range))
205 return false;
206 }
207
208 switch (Visitor(Cursor, Parent, ClientData)) {
209 case CXChildVisit_Break:
210 return true;
211
212 case CXChildVisit_Continue:
213 return false;
214
215 case CXChildVisit_Recurse: {
216 bool ret = VisitChildren(Cursor);
217 if (PostChildrenVisitor)
218 if (PostChildrenVisitor(Cursor, ClientData))
219 return true;
220 return ret;
221 }
222 }
223
224 llvm_unreachable("Invalid CXChildVisitResult!");
225}
226
227static bool visitPreprocessedEntitiesInRange(SourceRange R,
228 PreprocessingRecord &PPRec,
229 CursorVisitor &Visitor) {
230 SourceManager &SM = Visitor.getASTUnit()->getSourceManager();
231 FileID FID;
232
233 if (!Visitor.shouldVisitIncludedEntities()) {
234 // If the begin/end of the range lie in the same FileID, do the optimization
235 // where we skip preprocessed entities that do not come from the same FileID.
236 FID = SM.getFileID(SM.getFileLoc(R.getBegin()));
237 if (FID != SM.getFileID(SM.getFileLoc(R.getEnd())))
238 FID = FileID();
239 }
240
Benjamin Kramerb4ef6682015-02-06 17:25:10 +0000241 const auto &Entities = PPRec.getPreprocessedEntitiesInRange(R);
242 return Visitor.visitPreprocessedEntities(Entities.begin(), Entities.end(),
Guy Benyei11169dd2012-12-18 14:30:41 +0000243 PPRec, FID);
244}
245
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000246bool CursorVisitor::visitFileRegion() {
Guy Benyei11169dd2012-12-18 14:30:41 +0000247 if (RegionOfInterest.isInvalid())
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000248 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000249
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +0000250 ASTUnit *Unit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +0000251 SourceManager &SM = Unit->getSourceManager();
252
253 std::pair<FileID, unsigned>
254 Begin = SM.getDecomposedLoc(SM.getFileLoc(RegionOfInterest.getBegin())),
255 End = SM.getDecomposedLoc(SM.getFileLoc(RegionOfInterest.getEnd()));
256
257 if (End.first != Begin.first) {
258 // If the end does not reside in the same file, try to recover by
259 // picking the end of the file of begin location.
260 End.first = Begin.first;
261 End.second = SM.getFileIDSize(Begin.first);
262 }
263
264 assert(Begin.first == End.first);
265 if (Begin.second > End.second)
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000266 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000267
268 FileID File = Begin.first;
269 unsigned Offset = Begin.second;
270 unsigned Length = End.second - Begin.second;
271
272 if (!VisitDeclsOnly && !VisitPreprocessorLast)
273 if (visitPreprocessedEntitiesInRegion())
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000274 return true; // visitation break.
Guy Benyei11169dd2012-12-18 14:30:41 +0000275
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000276 if (visitDeclsFromFileRegion(File, Offset, Length))
277 return true; // visitation break.
Guy Benyei11169dd2012-12-18 14:30:41 +0000278
279 if (!VisitDeclsOnly && VisitPreprocessorLast)
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000280 return visitPreprocessedEntitiesInRegion();
281
282 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000283}
284
285static bool isInLexicalContext(Decl *D, DeclContext *DC) {
286 if (!DC)
287 return false;
288
289 for (DeclContext *DeclDC = D->getLexicalDeclContext();
290 DeclDC; DeclDC = DeclDC->getLexicalParent()) {
291 if (DeclDC == DC)
292 return true;
293 }
294 return false;
295}
296
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000297bool CursorVisitor::visitDeclsFromFileRegion(FileID File,
Guy Benyei11169dd2012-12-18 14:30:41 +0000298 unsigned Offset, unsigned Length) {
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +0000299 ASTUnit *Unit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +0000300 SourceManager &SM = Unit->getSourceManager();
301 SourceRange Range = RegionOfInterest;
302
303 SmallVector<Decl *, 16> Decls;
304 Unit->findFileRegionDecls(File, Offset, Length, Decls);
305
306 // If we didn't find any file level decls for the file, try looking at the
307 // file that it was included from.
308 while (Decls.empty() || Decls.front()->isTopLevelDeclInObjCContainer()) {
309 bool Invalid = false;
310 const SrcMgr::SLocEntry &SLEntry = SM.getSLocEntry(File, &Invalid);
311 if (Invalid)
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000312 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000313
314 SourceLocation Outer;
315 if (SLEntry.isFile())
316 Outer = SLEntry.getFile().getIncludeLoc();
317 else
318 Outer = SLEntry.getExpansion().getExpansionLocStart();
319 if (Outer.isInvalid())
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000320 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000321
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000322 std::tie(File, Offset) = SM.getDecomposedExpansionLoc(Outer);
Guy Benyei11169dd2012-12-18 14:30:41 +0000323 Length = 0;
324 Unit->findFileRegionDecls(File, Offset, Length, Decls);
325 }
326
327 assert(!Decls.empty());
328
329 bool VisitedAtLeastOnce = false;
Craig Topper69186e72014-06-08 08:38:04 +0000330 DeclContext *CurDC = nullptr;
Craig Topper2341c0d2013-07-04 03:08:24 +0000331 SmallVectorImpl<Decl *>::iterator DIt = Decls.begin();
332 for (SmallVectorImpl<Decl *>::iterator DE = Decls.end(); DIt != DE; ++DIt) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000333 Decl *D = *DIt;
334 if (D->getSourceRange().isInvalid())
335 continue;
336
337 if (isInLexicalContext(D, CurDC))
338 continue;
339
340 CurDC = dyn_cast<DeclContext>(D);
341
342 if (TagDecl *TD = dyn_cast<TagDecl>(D))
343 if (!TD->isFreeStanding())
344 continue;
345
346 RangeComparisonResult CompRes = RangeCompare(SM, D->getSourceRange(),Range);
347 if (CompRes == RangeBefore)
348 continue;
349 if (CompRes == RangeAfter)
350 break;
351
352 assert(CompRes == RangeOverlap);
353 VisitedAtLeastOnce = true;
354
355 if (isa<ObjCContainerDecl>(D)) {
356 FileDI_current = &DIt;
357 FileDE_current = DE;
358 } else {
Craig Topper69186e72014-06-08 08:38:04 +0000359 FileDI_current = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +0000360 }
361
362 if (Visit(MakeCXCursor(D, TU, Range), /*CheckedRegionOfInterest=*/true))
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000363 return true; // visitation break.
Guy Benyei11169dd2012-12-18 14:30:41 +0000364 }
365
366 if (VisitedAtLeastOnce)
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000367 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000368
369 // No Decls overlapped with the range. Move up the lexical context until there
370 // is a context that contains the range or we reach the translation unit
371 // level.
372 DeclContext *DC = DIt == Decls.begin() ? (*DIt)->getLexicalDeclContext()
373 : (*(DIt-1))->getLexicalDeclContext();
374
375 while (DC && !DC->isTranslationUnit()) {
376 Decl *D = cast<Decl>(DC);
377 SourceRange CurDeclRange = D->getSourceRange();
378 if (CurDeclRange.isInvalid())
379 break;
380
381 if (RangeCompare(SM, CurDeclRange, Range) == RangeOverlap) {
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000382 if (Visit(MakeCXCursor(D, TU, Range), /*CheckedRegionOfInterest=*/true))
383 return true; // visitation break.
Guy Benyei11169dd2012-12-18 14:30:41 +0000384 }
385
386 DC = D->getLexicalDeclContext();
387 }
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000388
389 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000390}
391
392bool CursorVisitor::visitPreprocessedEntitiesInRegion() {
393 if (!AU->getPreprocessor().getPreprocessingRecord())
394 return false;
395
396 PreprocessingRecord &PPRec
397 = *AU->getPreprocessor().getPreprocessingRecord();
398 SourceManager &SM = AU->getSourceManager();
399
400 if (RegionOfInterest.isValid()) {
401 SourceRange MappedRange = AU->mapRangeToPreamble(RegionOfInterest);
402 SourceLocation B = MappedRange.getBegin();
403 SourceLocation E = MappedRange.getEnd();
404
405 if (AU->isInPreambleFileID(B)) {
406 if (SM.isLoadedSourceLocation(E))
407 return visitPreprocessedEntitiesInRange(SourceRange(B, E),
408 PPRec, *this);
409
410 // Beginning of range lies in the preamble but it also extends beyond
411 // it into the main file. Split the range into 2 parts, one covering
412 // the preamble and another covering the main file. This allows subsequent
413 // calls to visitPreprocessedEntitiesInRange to accept a source range that
414 // lies in the same FileID, allowing it to skip preprocessed entities that
415 // do not come from the same FileID.
416 bool breaked =
417 visitPreprocessedEntitiesInRange(
418 SourceRange(B, AU->getEndOfPreambleFileID()),
419 PPRec, *this);
420 if (breaked) return true;
421 return visitPreprocessedEntitiesInRange(
422 SourceRange(AU->getStartOfMainFileID(), E),
423 PPRec, *this);
424 }
425
426 return visitPreprocessedEntitiesInRange(SourceRange(B, E), PPRec, *this);
427 }
428
429 bool OnlyLocalDecls
430 = !AU->isMainFileAST() && AU->getOnlyLocalDecls();
431
432 if (OnlyLocalDecls)
433 return visitPreprocessedEntities(PPRec.local_begin(), PPRec.local_end(),
434 PPRec);
435
436 return visitPreprocessedEntities(PPRec.begin(), PPRec.end(), PPRec);
437}
438
439template<typename InputIterator>
440bool CursorVisitor::visitPreprocessedEntities(InputIterator First,
441 InputIterator Last,
442 PreprocessingRecord &PPRec,
443 FileID FID) {
444 for (; First != Last; ++First) {
445 if (!FID.isInvalid() && !PPRec.isEntityInFileID(First, FID))
446 continue;
447
448 PreprocessedEntity *PPE = *First;
Argyrios Kyrtzidis1030f262013-05-07 20:37:17 +0000449 if (!PPE)
450 continue;
451
Guy Benyei11169dd2012-12-18 14:30:41 +0000452 if (MacroExpansion *ME = dyn_cast<MacroExpansion>(PPE)) {
453 if (Visit(MakeMacroExpansionCursor(ME, TU)))
454 return true;
Richard Smith66a81862015-05-04 02:25:31 +0000455
Guy Benyei11169dd2012-12-18 14:30:41 +0000456 continue;
457 }
Richard Smith66a81862015-05-04 02:25:31 +0000458
459 if (MacroDefinitionRecord *MD = dyn_cast<MacroDefinitionRecord>(PPE)) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000460 if (Visit(MakeMacroDefinitionCursor(MD, TU)))
461 return true;
Richard Smith66a81862015-05-04 02:25:31 +0000462
Guy Benyei11169dd2012-12-18 14:30:41 +0000463 continue;
464 }
465
466 if (InclusionDirective *ID = dyn_cast<InclusionDirective>(PPE)) {
467 if (Visit(MakeInclusionDirectiveCursor(ID, TU)))
468 return true;
469
470 continue;
471 }
472 }
473
474 return false;
475}
476
477/// \brief Visit the children of the given cursor.
478///
479/// \returns true if the visitation should be aborted, false if it
480/// should continue.
481bool CursorVisitor::VisitChildren(CXCursor Cursor) {
482 if (clang_isReference(Cursor.kind) &&
483 Cursor.kind != CXCursor_CXXBaseSpecifier) {
484 // By definition, references have no children.
485 return false;
486 }
487
488 // Set the Parent field to Cursor, then back to its old value once we're
489 // done.
490 SetParentRAII SetParent(Parent, StmtParent, Cursor);
491
492 if (clang_isDeclaration(Cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +0000493 Decl *D = const_cast<Decl *>(getCursorDecl(Cursor));
Guy Benyei11169dd2012-12-18 14:30:41 +0000494 if (!D)
495 return false;
496
497 return VisitAttributes(D) || Visit(D);
498 }
499
500 if (clang_isStatement(Cursor.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +0000501 if (const Stmt *S = getCursorStmt(Cursor))
Guy Benyei11169dd2012-12-18 14:30:41 +0000502 return Visit(S);
503
504 return false;
505 }
506
507 if (clang_isExpression(Cursor.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +0000508 if (const Expr *E = getCursorExpr(Cursor))
Guy Benyei11169dd2012-12-18 14:30:41 +0000509 return Visit(E);
510
511 return false;
512 }
513
514 if (clang_isTranslationUnit(Cursor.kind)) {
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +0000515 CXTranslationUnit TU = getCursorTU(Cursor);
516 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +0000517
518 int VisitOrder[2] = { VisitPreprocessorLast, !VisitPreprocessorLast };
519 for (unsigned I = 0; I != 2; ++I) {
520 if (VisitOrder[I]) {
521 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
522 RegionOfInterest.isInvalid()) {
523 for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
524 TLEnd = CXXUnit->top_level_end();
525 TL != TLEnd; ++TL) {
Argyrios Kyrtzidise7c91042016-07-01 19:10:54 +0000526 const Optional<bool> V = handleDeclForVisitation(*TL);
527 if (!V.hasValue())
528 continue;
529 return V.getValue();
Guy Benyei11169dd2012-12-18 14:30:41 +0000530 }
531 } else if (VisitDeclContext(
532 CXXUnit->getASTContext().getTranslationUnitDecl()))
533 return true;
534 continue;
535 }
536
537 // Walk the preprocessing record.
538 if (CXXUnit->getPreprocessor().getPreprocessingRecord())
539 visitPreprocessedEntitiesInRegion();
540 }
541
542 return false;
543 }
544
545 if (Cursor.kind == CXCursor_CXXBaseSpecifier) {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +0000546 if (const CXXBaseSpecifier *Base = getCursorCXXBaseSpecifier(Cursor)) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000547 if (TypeSourceInfo *BaseTSInfo = Base->getTypeSourceInfo()) {
548 return Visit(BaseTSInfo->getTypeLoc());
549 }
550 }
551 }
552
553 if (Cursor.kind == CXCursor_IBOutletCollectionAttr) {
Dmitri Gribenkoe4baea62013-01-26 18:08:08 +0000554 const IBOutletCollectionAttr *A =
Guy Benyei11169dd2012-12-18 14:30:41 +0000555 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(Cursor));
Richard Smithb1f9a282013-10-31 01:56:18 +0000556 if (const ObjCObjectType *ObjT = A->getInterface()->getAs<ObjCObjectType>())
Richard Smithb87c4652013-10-31 21:23:20 +0000557 return Visit(cxcursor::MakeCursorObjCClassRef(
558 ObjT->getInterface(),
559 A->getInterfaceLoc()->getTypeLoc().getLocStart(), TU));
Guy Benyei11169dd2012-12-18 14:30:41 +0000560 }
561
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +0000562 // If pointing inside a macro definition, check if the token is an identifier
563 // that was ever defined as a macro. In such a case, create a "pseudo" macro
564 // expansion cursor for that token.
565 SourceLocation BeginLoc = RegionOfInterest.getBegin();
566 if (Cursor.kind == CXCursor_MacroDefinition &&
567 BeginLoc == RegionOfInterest.getEnd()) {
568 SourceLocation Loc = AU->mapLocationToPreamble(BeginLoc);
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +0000569 const MacroInfo *MI =
570 getMacroInfo(cxcursor::getCursorMacroDefinition(Cursor), TU);
Richard Smith66a81862015-05-04 02:25:31 +0000571 if (MacroDefinitionRecord *MacroDef =
572 checkForMacroInMacroDefinition(MI, Loc, TU))
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +0000573 return Visit(cxcursor::MakeMacroExpansionCursor(MacroDef, BeginLoc, TU));
574 }
575
Guy Benyei11169dd2012-12-18 14:30:41 +0000576 // Nothing to visit at the moment.
577 return false;
578}
579
580bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
581 if (TypeSourceInfo *TSInfo = B->getSignatureAsWritten())
582 if (Visit(TSInfo->getTypeLoc()))
583 return true;
584
585 if (Stmt *Body = B->getBody())
586 return Visit(MakeCXCursor(Body, StmtParent, TU, RegionOfInterest));
587
588 return false;
589}
590
Ted Kremenek03325582013-02-21 01:29:01 +0000591Optional<bool> CursorVisitor::shouldVisitCursor(CXCursor Cursor) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000592 if (RegionOfInterest.isValid()) {
593 SourceRange Range = getFullCursorExtent(Cursor, AU->getSourceManager());
594 if (Range.isInvalid())
David Blaikie7a30dc52013-02-21 01:47:18 +0000595 return None;
Guy Benyei11169dd2012-12-18 14:30:41 +0000596
597 switch (CompareRegionOfInterest(Range)) {
598 case RangeBefore:
599 // This declaration comes before the region of interest; skip it.
David Blaikie7a30dc52013-02-21 01:47:18 +0000600 return None;
Guy Benyei11169dd2012-12-18 14:30:41 +0000601
602 case RangeAfter:
603 // This declaration comes after the region of interest; we're done.
604 return false;
605
606 case RangeOverlap:
607 // This declaration overlaps the region of interest; visit it.
608 break;
609 }
610 }
611 return true;
612}
613
614bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
615 DeclContext::decl_iterator I = DC->decls_begin(), E = DC->decls_end();
616
617 // FIXME: Eventually remove. This part of a hack to support proper
618 // iteration over all Decls contained lexically within an ObjC container.
619 SaveAndRestore<DeclContext::decl_iterator*> DI_saved(DI_current, &I);
620 SaveAndRestore<DeclContext::decl_iterator> DE_saved(DE_current, E);
621
622 for ( ; I != E; ++I) {
623 Decl *D = *I;
624 if (D->getLexicalDeclContext() != DC)
625 continue;
Argyrios Kyrtzidise7c91042016-07-01 19:10:54 +0000626 const Optional<bool> V = handleDeclForVisitation(D);
Guy Benyei11169dd2012-12-18 14:30:41 +0000627 if (!V.hasValue())
628 continue;
Argyrios Kyrtzidise7c91042016-07-01 19:10:54 +0000629 return V.getValue();
Guy Benyei11169dd2012-12-18 14:30:41 +0000630 }
631 return false;
632}
633
Argyrios Kyrtzidise7c91042016-07-01 19:10:54 +0000634Optional<bool> CursorVisitor::handleDeclForVisitation(const Decl *D) {
635 CXCursor Cursor = MakeCXCursor(D, TU, RegionOfInterest);
636
637 // Ignore synthesized ivars here, otherwise if we have something like:
638 // @synthesize prop = _prop;
639 // and '_prop' is not declared, we will encounter a '_prop' ivar before
640 // encountering the 'prop' synthesize declaration and we will think that
641 // we passed the region-of-interest.
642 if (auto *ivarD = dyn_cast<ObjCIvarDecl>(D)) {
643 if (ivarD->getSynthesize())
644 return None;
645 }
646
647 // FIXME: ObjCClassRef/ObjCProtocolRef for forward class/protocol
648 // declarations is a mismatch with the compiler semantics.
649 if (Cursor.kind == CXCursor_ObjCInterfaceDecl) {
650 auto *ID = cast<ObjCInterfaceDecl>(D);
651 if (!ID->isThisDeclarationADefinition())
652 Cursor = MakeCursorObjCClassRef(ID, ID->getLocation(), TU);
653
654 } else if (Cursor.kind == CXCursor_ObjCProtocolDecl) {
655 auto *PD = cast<ObjCProtocolDecl>(D);
656 if (!PD->isThisDeclarationADefinition())
657 Cursor = MakeCursorObjCProtocolRef(PD, PD->getLocation(), TU);
658 }
659
660 const Optional<bool> V = shouldVisitCursor(Cursor);
661 if (!V.hasValue())
662 return None;
663 if (!V.getValue())
664 return false;
665 if (Visit(Cursor, true))
666 return true;
667 return None;
668}
669
Guy Benyei11169dd2012-12-18 14:30:41 +0000670bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
671 llvm_unreachable("Translation units are visited directly by Visit()");
672}
673
Sergey Kalinichev8f3b1872015-11-15 13:48:32 +0000674bool CursorVisitor::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
675 if (VisitTemplateParameters(D->getTemplateParameters()))
676 return true;
677
678 return Visit(MakeCXCursor(D->getTemplatedDecl(), TU, RegionOfInterest));
679}
680
Guy Benyei11169dd2012-12-18 14:30:41 +0000681bool CursorVisitor::VisitTypeAliasDecl(TypeAliasDecl *D) {
682 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
683 return Visit(TSInfo->getTypeLoc());
684
685 return false;
686}
687
688bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
689 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
690 return Visit(TSInfo->getTypeLoc());
691
692 return false;
693}
694
695bool CursorVisitor::VisitTagDecl(TagDecl *D) {
696 return VisitDeclContext(D);
697}
698
699bool CursorVisitor::VisitClassTemplateSpecializationDecl(
700 ClassTemplateSpecializationDecl *D) {
701 bool ShouldVisitBody = false;
702 switch (D->getSpecializationKind()) {
703 case TSK_Undeclared:
704 case TSK_ImplicitInstantiation:
705 // Nothing to visit
706 return false;
707
708 case TSK_ExplicitInstantiationDeclaration:
709 case TSK_ExplicitInstantiationDefinition:
710 break;
711
712 case TSK_ExplicitSpecialization:
713 ShouldVisitBody = true;
714 break;
715 }
716
717 // Visit the template arguments used in the specialization.
718 if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) {
719 TypeLoc TL = SpecType->getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +0000720 if (TemplateSpecializationTypeLoc TSTLoc =
721 TL.getAs<TemplateSpecializationTypeLoc>()) {
722 for (unsigned I = 0, N = TSTLoc.getNumArgs(); I != N; ++I)
723 if (VisitTemplateArgumentLoc(TSTLoc.getArgLoc(I)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000724 return true;
725 }
726 }
Alexander Kornienko1a9f1842015-12-28 15:24:08 +0000727
728 return ShouldVisitBody && VisitCXXRecordDecl(D);
Guy Benyei11169dd2012-12-18 14:30:41 +0000729}
730
731bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl(
732 ClassTemplatePartialSpecializationDecl *D) {
733 // FIXME: Visit the "outer" template parameter lists on the TagDecl
734 // before visiting these template parameters.
735 if (VisitTemplateParameters(D->getTemplateParameters()))
736 return true;
737
738 // Visit the partial specialization arguments.
Enea Zaffanella6dbe1872013-08-10 07:24:53 +0000739 const ASTTemplateArgumentListInfo *Info = D->getTemplateArgsAsWritten();
740 const TemplateArgumentLoc *TemplateArgs = Info->getTemplateArgs();
741 for (unsigned I = 0, N = Info->NumTemplateArgs; I != N; ++I)
Guy Benyei11169dd2012-12-18 14:30:41 +0000742 if (VisitTemplateArgumentLoc(TemplateArgs[I]))
743 return true;
744
745 return VisitCXXRecordDecl(D);
746}
747
748bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
749 // Visit the default argument.
750 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
751 if (TypeSourceInfo *DefArg = D->getDefaultArgumentInfo())
752 if (Visit(DefArg->getTypeLoc()))
753 return true;
754
755 return false;
756}
757
758bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
759 if (Expr *Init = D->getInitExpr())
760 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
761 return false;
762}
763
764bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
Argyrios Kyrtzidis2ec76742013-04-05 21:04:10 +0000765 unsigned NumParamList = DD->getNumTemplateParameterLists();
766 for (unsigned i = 0; i < NumParamList; i++) {
767 TemplateParameterList* Params = DD->getTemplateParameterList(i);
768 if (VisitTemplateParameters(Params))
769 return true;
770 }
771
Guy Benyei11169dd2012-12-18 14:30:41 +0000772 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
773 if (Visit(TSInfo->getTypeLoc()))
774 return true;
775
776 // Visit the nested-name-specifier, if present.
777 if (NestedNameSpecifierLoc QualifierLoc = DD->getQualifierLoc())
778 if (VisitNestedNameSpecifierLoc(QualifierLoc))
779 return true;
780
781 return false;
782}
783
Benjamin Kramer4cadf292014-03-07 21:51:58 +0000784/// \brief Compare two base or member initializers based on their source order.
785static int CompareCXXCtorInitializers(CXXCtorInitializer *const *X,
786 CXXCtorInitializer *const *Y) {
787 return (*X)->getSourceOrder() - (*Y)->getSourceOrder();
788}
789
Guy Benyei11169dd2012-12-18 14:30:41 +0000790bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Argyrios Kyrtzidis2ec76742013-04-05 21:04:10 +0000791 unsigned NumParamList = ND->getNumTemplateParameterLists();
792 for (unsigned i = 0; i < NumParamList; i++) {
793 TemplateParameterList* Params = ND->getTemplateParameterList(i);
794 if (VisitTemplateParameters(Params))
795 return true;
796 }
797
Guy Benyei11169dd2012-12-18 14:30:41 +0000798 if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
799 // Visit the function declaration's syntactic components in the order
800 // written. This requires a bit of work.
801 TypeLoc TL = TSInfo->getTypeLoc().IgnoreParens();
David Blaikie6adc78e2013-02-18 22:06:02 +0000802 FunctionTypeLoc FTL = TL.getAs<FunctionTypeLoc>();
Guy Benyei11169dd2012-12-18 14:30:41 +0000803
804 // If we have a function declared directly (without the use of a typedef),
805 // visit just the return type. Otherwise, just visit the function's type
806 // now.
Alp Toker42a16a62014-01-25 23:51:36 +0000807 if ((FTL && !isa<CXXConversionDecl>(ND) && Visit(FTL.getReturnLoc())) ||
Guy Benyei11169dd2012-12-18 14:30:41 +0000808 (!FTL && Visit(TL)))
809 return true;
810
811 // Visit the nested-name-specifier, if present.
812 if (NestedNameSpecifierLoc QualifierLoc = ND->getQualifierLoc())
813 if (VisitNestedNameSpecifierLoc(QualifierLoc))
814 return true;
815
816 // Visit the declaration name.
Argyrios Kyrtzidis4a4d2b42014-02-09 08:13:47 +0000817 if (!isa<CXXDestructorDecl>(ND))
818 if (VisitDeclarationNameInfo(ND->getNameInfo()))
819 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +0000820
821 // FIXME: Visit explicitly-specified template arguments!
822
823 // Visit the function parameters, if we have a function type.
David Blaikie6adc78e2013-02-18 22:06:02 +0000824 if (FTL && VisitFunctionTypeLoc(FTL, true))
Guy Benyei11169dd2012-12-18 14:30:41 +0000825 return true;
826
Bill Wendling44426052012-12-20 19:22:21 +0000827 // FIXME: Attributes?
Guy Benyei11169dd2012-12-18 14:30:41 +0000828 }
829
830 if (ND->doesThisDeclarationHaveABody() && !ND->isLateTemplateParsed()) {
831 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ND)) {
832 // Find the initializers that were written in the source.
833 SmallVector<CXXCtorInitializer *, 4> WrittenInits;
Aaron Ballman0ad78302014-03-13 17:34:31 +0000834 for (auto *I : Constructor->inits()) {
835 if (!I->isWritten())
Guy Benyei11169dd2012-12-18 14:30:41 +0000836 continue;
837
Aaron Ballman0ad78302014-03-13 17:34:31 +0000838 WrittenInits.push_back(I);
Guy Benyei11169dd2012-12-18 14:30:41 +0000839 }
840
841 // Sort the initializers in source order
Benjamin Kramer4cadf292014-03-07 21:51:58 +0000842 llvm::array_pod_sort(WrittenInits.begin(), WrittenInits.end(),
843 &CompareCXXCtorInitializers);
844
Guy Benyei11169dd2012-12-18 14:30:41 +0000845 // Visit the initializers in source order
846 for (unsigned I = 0, N = WrittenInits.size(); I != N; ++I) {
847 CXXCtorInitializer *Init = WrittenInits[I];
848 if (Init->isAnyMemberInitializer()) {
849 if (Visit(MakeCursorMemberRef(Init->getAnyMember(),
850 Init->getMemberLocation(), TU)))
851 return true;
852 } else if (TypeSourceInfo *TInfo = Init->getTypeSourceInfo()) {
853 if (Visit(TInfo->getTypeLoc()))
854 return true;
855 }
856
857 // Visit the initializer value.
858 if (Expr *Initializer = Init->getInit())
859 if (Visit(MakeCXCursor(Initializer, ND, TU, RegionOfInterest)))
860 return true;
861 }
862 }
863
864 if (Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest)))
865 return true;
866 }
867
868 return false;
869}
870
871bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
872 if (VisitDeclaratorDecl(D))
873 return true;
874
875 if (Expr *BitWidth = D->getBitWidth())
876 return Visit(MakeCXCursor(BitWidth, StmtParent, TU, RegionOfInterest));
877
878 return false;
879}
880
881bool CursorVisitor::VisitVarDecl(VarDecl *D) {
882 if (VisitDeclaratorDecl(D))
883 return true;
884
885 if (Expr *Init = D->getInit())
886 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
887
888 return false;
889}
890
891bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
892 if (VisitDeclaratorDecl(D))
893 return true;
894
895 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
896 if (Expr *DefArg = D->getDefaultArgument())
897 return Visit(MakeCXCursor(DefArg, StmtParent, TU, RegionOfInterest));
898
899 return false;
900}
901
902bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
903 // FIXME: Visit the "outer" template parameter lists on the FunctionDecl
904 // before visiting these template parameters.
905 if (VisitTemplateParameters(D->getTemplateParameters()))
906 return true;
907
908 return VisitFunctionDecl(D->getTemplatedDecl());
909}
910
911bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) {
912 // FIXME: Visit the "outer" template parameter lists on the TagDecl
913 // before visiting these template parameters.
914 if (VisitTemplateParameters(D->getTemplateParameters()))
915 return true;
916
917 return VisitCXXRecordDecl(D->getTemplatedDecl());
918}
919
920bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
921 if (VisitTemplateParameters(D->getTemplateParameters()))
922 return true;
923
924 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() &&
925 VisitTemplateArgumentLoc(D->getDefaultArgument()))
926 return true;
927
928 return false;
929}
930
Douglas Gregor9bda6cf2015-07-07 03:58:14 +0000931bool CursorVisitor::VisitObjCTypeParamDecl(ObjCTypeParamDecl *D) {
932 // Visit the bound, if it's explicit.
933 if (D->hasExplicitBound()) {
934 if (auto TInfo = D->getTypeSourceInfo()) {
935 if (Visit(TInfo->getTypeLoc()))
936 return true;
937 }
938 }
939
940 return false;
941}
942
Guy Benyei11169dd2012-12-18 14:30:41 +0000943bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Alp Toker314cc812014-01-25 16:55:45 +0000944 if (TypeSourceInfo *TSInfo = ND->getReturnTypeSourceInfo())
Guy Benyei11169dd2012-12-18 14:30:41 +0000945 if (Visit(TSInfo->getTypeLoc()))
946 return true;
947
David Majnemer59f77922016-06-24 04:05:48 +0000948 for (const auto *P : ND->parameters()) {
Aaron Ballman43b68be2014-03-07 17:50:17 +0000949 if (Visit(MakeCXCursor(P, TU, RegionOfInterest)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000950 return true;
951 }
952
Alexander Kornienko1a9f1842015-12-28 15:24:08 +0000953 return ND->isThisDeclarationADefinition() &&
954 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest));
Guy Benyei11169dd2012-12-18 14:30:41 +0000955}
956
957template <typename DeclIt>
958static void addRangedDeclsInContainer(DeclIt *DI_current, DeclIt DE_current,
959 SourceManager &SM, SourceLocation EndLoc,
960 SmallVectorImpl<Decl *> &Decls) {
961 DeclIt next = *DI_current;
962 while (++next != DE_current) {
963 Decl *D_next = *next;
964 if (!D_next)
965 break;
966 SourceLocation L = D_next->getLocStart();
967 if (!L.isValid())
968 break;
969 if (SM.isBeforeInTranslationUnit(L, EndLoc)) {
970 *DI_current = next;
971 Decls.push_back(D_next);
972 continue;
973 }
974 break;
975 }
976}
977
Guy Benyei11169dd2012-12-18 14:30:41 +0000978bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
979 // FIXME: Eventually convert back to just 'VisitDeclContext()'. Essentially
980 // an @implementation can lexically contain Decls that are not properly
981 // nested in the AST. When we identify such cases, we need to retrofit
982 // this nesting here.
983 if (!DI_current && !FileDI_current)
984 return VisitDeclContext(D);
985
986 // Scan the Decls that immediately come after the container
987 // in the current DeclContext. If any fall within the
988 // container's lexical region, stash them into a vector
989 // for later processing.
990 SmallVector<Decl *, 24> DeclsInContainer;
991 SourceLocation EndLoc = D->getSourceRange().getEnd();
992 SourceManager &SM = AU->getSourceManager();
993 if (EndLoc.isValid()) {
994 if (DI_current) {
995 addRangedDeclsInContainer(DI_current, DE_current, SM, EndLoc,
996 DeclsInContainer);
997 } else {
998 addRangedDeclsInContainer(FileDI_current, FileDE_current, SM, EndLoc,
999 DeclsInContainer);
1000 }
1001 }
1002
1003 // The common case.
1004 if (DeclsInContainer.empty())
1005 return VisitDeclContext(D);
1006
1007 // Get all the Decls in the DeclContext, and sort them with the
1008 // additional ones we've collected. Then visit them.
Aaron Ballman629afae2014-03-07 19:56:05 +00001009 for (auto *SubDecl : D->decls()) {
1010 if (!SubDecl || SubDecl->getLexicalDeclContext() != D ||
1011 SubDecl->getLocStart().isInvalid())
Guy Benyei11169dd2012-12-18 14:30:41 +00001012 continue;
Aaron Ballman629afae2014-03-07 19:56:05 +00001013 DeclsInContainer.push_back(SubDecl);
Guy Benyei11169dd2012-12-18 14:30:41 +00001014 }
1015
1016 // Now sort the Decls so that they appear in lexical order.
1017 std::sort(DeclsInContainer.begin(), DeclsInContainer.end(),
Benjamin Kramerbbdd7642014-03-01 14:48:57 +00001018 [&SM](Decl *A, Decl *B) {
1019 SourceLocation L_A = A->getLocStart();
1020 SourceLocation L_B = B->getLocStart();
1021 assert(L_A.isValid() && L_B.isValid());
1022 return SM.isBeforeInTranslationUnit(L_A, L_B);
1023 });
Guy Benyei11169dd2012-12-18 14:30:41 +00001024
1025 // Now visit the decls.
1026 for (SmallVectorImpl<Decl*>::iterator I = DeclsInContainer.begin(),
1027 E = DeclsInContainer.end(); I != E; ++I) {
1028 CXCursor Cursor = MakeCXCursor(*I, TU, RegionOfInterest);
Ted Kremenek03325582013-02-21 01:29:01 +00001029 const Optional<bool> &V = shouldVisitCursor(Cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00001030 if (!V.hasValue())
1031 continue;
1032 if (!V.getValue())
1033 return false;
1034 if (Visit(Cursor, true))
1035 return true;
1036 }
1037 return false;
1038}
1039
1040bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
1041 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
1042 TU)))
1043 return true;
1044
Douglas Gregore9d95f12015-07-07 03:57:35 +00001045 if (VisitObjCTypeParamList(ND->getTypeParamList()))
1046 return true;
1047
Guy Benyei11169dd2012-12-18 14:30:41 +00001048 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
1049 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
1050 E = ND->protocol_end(); I != E; ++I, ++PL)
1051 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
1052 return true;
1053
1054 return VisitObjCContainerDecl(ND);
1055}
1056
1057bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
1058 if (!PID->isThisDeclarationADefinition())
1059 return Visit(MakeCursorObjCProtocolRef(PID, PID->getLocation(), TU));
1060
1061 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
1062 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
1063 E = PID->protocol_end(); I != E; ++I, ++PL)
1064 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
1065 return true;
1066
1067 return VisitObjCContainerDecl(PID);
1068}
1069
1070bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
1071 if (PD->getTypeSourceInfo() && Visit(PD->getTypeSourceInfo()->getTypeLoc()))
1072 return true;
1073
1074 // FIXME: This implements a workaround with @property declarations also being
1075 // installed in the DeclContext for the @interface. Eventually this code
1076 // should be removed.
1077 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
1078 if (!CDecl || !CDecl->IsClassExtension())
1079 return false;
1080
1081 ObjCInterfaceDecl *ID = CDecl->getClassInterface();
1082 if (!ID)
1083 return false;
1084
1085 IdentifierInfo *PropertyId = PD->getIdentifier();
1086 ObjCPropertyDecl *prevDecl =
Manman Ren5b786402016-01-28 18:49:28 +00001087 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId,
1088 PD->getQueryKind());
Guy Benyei11169dd2012-12-18 14:30:41 +00001089
1090 if (!prevDecl)
1091 return false;
1092
1093 // Visit synthesized methods since they will be skipped when visiting
1094 // the @interface.
1095 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
1096 if (MD->isPropertyAccessor() && MD->getLexicalDeclContext() == CDecl)
1097 if (Visit(MakeCXCursor(MD, TU, RegionOfInterest)))
1098 return true;
1099
1100 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
1101 if (MD->isPropertyAccessor() && MD->getLexicalDeclContext() == CDecl)
1102 if (Visit(MakeCXCursor(MD, TU, RegionOfInterest)))
1103 return true;
1104
1105 return false;
1106}
1107
Douglas Gregore9d95f12015-07-07 03:57:35 +00001108bool CursorVisitor::VisitObjCTypeParamList(ObjCTypeParamList *typeParamList) {
1109 if (!typeParamList)
1110 return false;
1111
1112 for (auto *typeParam : *typeParamList) {
1113 // Visit the type parameter.
1114 if (Visit(MakeCXCursor(typeParam, TU, RegionOfInterest)))
1115 return true;
Douglas Gregore9d95f12015-07-07 03:57:35 +00001116 }
1117
1118 return false;
1119}
1120
Guy Benyei11169dd2012-12-18 14:30:41 +00001121bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
1122 if (!D->isThisDeclarationADefinition()) {
1123 // Forward declaration is treated like a reference.
1124 return Visit(MakeCursorObjCClassRef(D, D->getLocation(), TU));
1125 }
1126
Douglas Gregore9d95f12015-07-07 03:57:35 +00001127 // Objective-C type parameters.
1128 if (VisitObjCTypeParamList(D->getTypeParamListAsWritten()))
1129 return true;
1130
Guy Benyei11169dd2012-12-18 14:30:41 +00001131 // Issue callbacks for super class.
1132 if (D->getSuperClass() &&
1133 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
1134 D->getSuperClassLoc(),
1135 TU)))
1136 return true;
1137
Douglas Gregore9d95f12015-07-07 03:57:35 +00001138 if (TypeSourceInfo *SuperClassTInfo = D->getSuperClassTInfo())
1139 if (Visit(SuperClassTInfo->getTypeLoc()))
1140 return true;
1141
Guy Benyei11169dd2012-12-18 14:30:41 +00001142 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1143 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
1144 E = D->protocol_end(); I != E; ++I, ++PL)
1145 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
1146 return true;
1147
1148 return VisitObjCContainerDecl(D);
1149}
1150
1151bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
1152 return VisitObjCContainerDecl(D);
1153}
1154
1155bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
1156 // 'ID' could be null when dealing with invalid code.
1157 if (ObjCInterfaceDecl *ID = D->getClassInterface())
1158 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
1159 return true;
1160
1161 return VisitObjCImplDecl(D);
1162}
1163
1164bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
1165#if 0
1166 // Issue callbacks for super class.
1167 // FIXME: No source location information!
1168 if (D->getSuperClass() &&
1169 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
1170 D->getSuperClassLoc(),
1171 TU)))
1172 return true;
1173#endif
1174
1175 return VisitObjCImplDecl(D);
1176}
1177
1178bool CursorVisitor::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *PD) {
1179 if (ObjCIvarDecl *Ivar = PD->getPropertyIvarDecl())
1180 if (PD->isIvarNameSpecified())
1181 return Visit(MakeCursorMemberRef(Ivar, PD->getPropertyIvarDeclLoc(), TU));
1182
1183 return false;
1184}
1185
1186bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
1187 return VisitDeclContext(D);
1188}
1189
1190bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
1191 // Visit nested-name-specifier.
1192 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1193 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1194 return true;
1195
1196 return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(),
1197 D->getTargetNameLoc(), TU));
1198}
1199
1200bool CursorVisitor::VisitUsingDecl(UsingDecl *D) {
1201 // Visit nested-name-specifier.
1202 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1203 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1204 return true;
1205 }
1206
1207 if (Visit(MakeCursorOverloadedDeclRef(D, D->getLocation(), TU)))
1208 return true;
1209
1210 return VisitDeclarationNameInfo(D->getNameInfo());
1211}
1212
1213bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
1214 // Visit nested-name-specifier.
1215 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1216 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1217 return true;
1218
1219 return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(),
1220 D->getIdentLocation(), TU));
1221}
1222
1223bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
1224 // Visit nested-name-specifier.
1225 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1226 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1227 return true;
1228 }
1229
1230 return VisitDeclarationNameInfo(D->getNameInfo());
1231}
1232
1233bool CursorVisitor::VisitUnresolvedUsingTypenameDecl(
1234 UnresolvedUsingTypenameDecl *D) {
1235 // Visit nested-name-specifier.
1236 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1237 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1238 return true;
1239
1240 return false;
1241}
1242
Olivier Goffart81978012016-06-09 16:15:55 +00001243bool CursorVisitor::VisitStaticAssertDecl(StaticAssertDecl *D) {
1244 if (Visit(MakeCXCursor(D->getAssertExpr(), StmtParent, TU, RegionOfInterest)))
1245 return true;
Richard Trieuf3b77662016-09-13 01:37:01 +00001246 if (StringLiteral *Message = D->getMessage())
1247 if (Visit(MakeCXCursor(Message, StmtParent, TU, RegionOfInterest)))
1248 return true;
Olivier Goffart81978012016-06-09 16:15:55 +00001249 return false;
1250}
1251
Olivier Goffartd211c642016-11-04 06:29:27 +00001252bool CursorVisitor::VisitFriendDecl(FriendDecl *D) {
1253 if (NamedDecl *FriendD = D->getFriendDecl()) {
1254 if (Visit(MakeCXCursor(FriendD, TU, RegionOfInterest)))
1255 return true;
1256 } else if (TypeSourceInfo *TI = D->getFriendType()) {
1257 if (Visit(TI->getTypeLoc()))
1258 return true;
1259 }
1260 return false;
1261}
1262
Guy Benyei11169dd2012-12-18 14:30:41 +00001263bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
1264 switch (Name.getName().getNameKind()) {
1265 case clang::DeclarationName::Identifier:
1266 case clang::DeclarationName::CXXLiteralOperatorName:
1267 case clang::DeclarationName::CXXOperatorName:
1268 case clang::DeclarationName::CXXUsingDirective:
1269 return false;
1270
1271 case clang::DeclarationName::CXXConstructorName:
1272 case clang::DeclarationName::CXXDestructorName:
1273 case clang::DeclarationName::CXXConversionFunctionName:
1274 if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
1275 return Visit(TSInfo->getTypeLoc());
1276 return false;
1277
1278 case clang::DeclarationName::ObjCZeroArgSelector:
1279 case clang::DeclarationName::ObjCOneArgSelector:
1280 case clang::DeclarationName::ObjCMultiArgSelector:
1281 // FIXME: Per-identifier location info?
1282 return false;
1283 }
1284
1285 llvm_unreachable("Invalid DeclarationName::Kind!");
1286}
1287
1288bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS,
1289 SourceRange Range) {
1290 // FIXME: This whole routine is a hack to work around the lack of proper
1291 // source information in nested-name-specifiers (PR5791). Since we do have
1292 // a beginning source location, we can visit the first component of the
1293 // nested-name-specifier, if it's a single-token component.
1294 if (!NNS)
1295 return false;
1296
1297 // Get the first component in the nested-name-specifier.
1298 while (NestedNameSpecifier *Prefix = NNS->getPrefix())
1299 NNS = Prefix;
1300
1301 switch (NNS->getKind()) {
1302 case NestedNameSpecifier::Namespace:
1303 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(),
1304 TU));
1305
1306 case NestedNameSpecifier::NamespaceAlias:
1307 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
1308 Range.getBegin(), TU));
1309
1310 case NestedNameSpecifier::TypeSpec: {
1311 // If the type has a form where we know that the beginning of the source
1312 // range matches up with a reference cursor. Visit the appropriate reference
1313 // cursor.
1314 const Type *T = NNS->getAsType();
1315 if (const TypedefType *Typedef = dyn_cast<TypedefType>(T))
1316 return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU));
1317 if (const TagType *Tag = dyn_cast<TagType>(T))
1318 return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU));
1319 if (const TemplateSpecializationType *TST
1320 = dyn_cast<TemplateSpecializationType>(T))
1321 return VisitTemplateName(TST->getTemplateName(), Range.getBegin());
1322 break;
1323 }
1324
1325 case NestedNameSpecifier::TypeSpecWithTemplate:
1326 case NestedNameSpecifier::Global:
1327 case NestedNameSpecifier::Identifier:
Nikola Smiljanic67860242014-09-26 00:28:20 +00001328 case NestedNameSpecifier::Super:
Guy Benyei11169dd2012-12-18 14:30:41 +00001329 break;
1330 }
1331
1332 return false;
1333}
1334
1335bool
1336CursorVisitor::VisitNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
1337 SmallVector<NestedNameSpecifierLoc, 4> Qualifiers;
1338 for (; Qualifier; Qualifier = Qualifier.getPrefix())
1339 Qualifiers.push_back(Qualifier);
1340
1341 while (!Qualifiers.empty()) {
1342 NestedNameSpecifierLoc Q = Qualifiers.pop_back_val();
1343 NestedNameSpecifier *NNS = Q.getNestedNameSpecifier();
1344 switch (NNS->getKind()) {
1345 case NestedNameSpecifier::Namespace:
1346 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(),
1347 Q.getLocalBeginLoc(),
1348 TU)))
1349 return true;
1350
1351 break;
1352
1353 case NestedNameSpecifier::NamespaceAlias:
1354 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
1355 Q.getLocalBeginLoc(),
1356 TU)))
1357 return true;
1358
1359 break;
1360
1361 case NestedNameSpecifier::TypeSpec:
1362 case NestedNameSpecifier::TypeSpecWithTemplate:
1363 if (Visit(Q.getTypeLoc()))
1364 return true;
1365
1366 break;
1367
1368 case NestedNameSpecifier::Global:
1369 case NestedNameSpecifier::Identifier:
Nikola Smiljanic67860242014-09-26 00:28:20 +00001370 case NestedNameSpecifier::Super:
Guy Benyei11169dd2012-12-18 14:30:41 +00001371 break;
1372 }
1373 }
1374
1375 return false;
1376}
1377
1378bool CursorVisitor::VisitTemplateParameters(
1379 const TemplateParameterList *Params) {
1380 if (!Params)
1381 return false;
1382
1383 for (TemplateParameterList::const_iterator P = Params->begin(),
1384 PEnd = Params->end();
1385 P != PEnd; ++P) {
1386 if (Visit(MakeCXCursor(*P, TU, RegionOfInterest)))
1387 return true;
1388 }
1389
1390 return false;
1391}
1392
1393bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) {
1394 switch (Name.getKind()) {
1395 case TemplateName::Template:
1396 return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
1397
1398 case TemplateName::OverloadedTemplate:
1399 // Visit the overloaded template set.
1400 if (Visit(MakeCursorOverloadedDeclRef(Name, Loc, TU)))
1401 return true;
1402
1403 return false;
1404
1405 case TemplateName::DependentTemplate:
1406 // FIXME: Visit nested-name-specifier.
1407 return false;
1408
1409 case TemplateName::QualifiedTemplate:
1410 // FIXME: Visit nested-name-specifier.
1411 return Visit(MakeCursorTemplateRef(
1412 Name.getAsQualifiedTemplateName()->getDecl(),
1413 Loc, TU));
1414
1415 case TemplateName::SubstTemplateTemplateParm:
1416 return Visit(MakeCursorTemplateRef(
1417 Name.getAsSubstTemplateTemplateParm()->getParameter(),
1418 Loc, TU));
1419
1420 case TemplateName::SubstTemplateTemplateParmPack:
1421 return Visit(MakeCursorTemplateRef(
1422 Name.getAsSubstTemplateTemplateParmPack()->getParameterPack(),
1423 Loc, TU));
1424 }
1425
1426 llvm_unreachable("Invalid TemplateName::Kind!");
1427}
1428
1429bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
1430 switch (TAL.getArgument().getKind()) {
1431 case TemplateArgument::Null:
1432 case TemplateArgument::Integral:
1433 case TemplateArgument::Pack:
1434 return false;
1435
1436 case TemplateArgument::Type:
1437 if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
1438 return Visit(TSInfo->getTypeLoc());
1439 return false;
1440
1441 case TemplateArgument::Declaration:
1442 if (Expr *E = TAL.getSourceDeclExpression())
1443 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
1444 return false;
1445
1446 case TemplateArgument::NullPtr:
1447 if (Expr *E = TAL.getSourceNullPtrExpression())
1448 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
1449 return false;
1450
1451 case TemplateArgument::Expression:
1452 if (Expr *E = TAL.getSourceExpression())
1453 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
1454 return false;
1455
1456 case TemplateArgument::Template:
1457 case TemplateArgument::TemplateExpansion:
1458 if (VisitNestedNameSpecifierLoc(TAL.getTemplateQualifierLoc()))
1459 return true;
1460
1461 return VisitTemplateName(TAL.getArgument().getAsTemplateOrTemplatePattern(),
1462 TAL.getTemplateNameLoc());
1463 }
1464
1465 llvm_unreachable("Invalid TemplateArgument::Kind!");
1466}
1467
1468bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1469 return VisitDeclContext(D);
1470}
1471
1472bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1473 return Visit(TL.getUnqualifiedLoc());
1474}
1475
1476bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
1477 ASTContext &Context = AU->getASTContext();
1478
1479 // Some builtin types (such as Objective-C's "id", "sel", and
1480 // "Class") have associated declarations. Create cursors for those.
1481 QualType VisitType;
1482 switch (TL.getTypePtr()->getKind()) {
1483
1484 case BuiltinType::Void:
1485 case BuiltinType::NullPtr:
1486 case BuiltinType::Dependent:
Alexey Bader954ba212016-04-08 13:40:33 +00001487#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1488 case BuiltinType::Id:
Alexey Baderb62f1442016-04-13 08:33:41 +00001489#include "clang/Basic/OpenCLImageTypes.def"
NAKAMURA Takumi288c42e2013-02-07 12:47:42 +00001490 case BuiltinType::OCLSampler:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001491 case BuiltinType::OCLEvent:
Alexey Bader9c8453f2015-09-15 11:18:52 +00001492 case BuiltinType::OCLClkEvent:
1493 case BuiltinType::OCLQueue:
1494 case BuiltinType::OCLNDRange:
1495 case BuiltinType::OCLReserveID:
Guy Benyei11169dd2012-12-18 14:30:41 +00001496#define BUILTIN_TYPE(Id, SingletonId)
1497#define SIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
1498#define UNSIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
1499#define FLOATING_TYPE(Id, SingletonId) case BuiltinType::Id:
1500#define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id:
1501#include "clang/AST/BuiltinTypes.def"
1502 break;
1503
1504 case BuiltinType::ObjCId:
1505 VisitType = Context.getObjCIdType();
1506 break;
1507
1508 case BuiltinType::ObjCClass:
1509 VisitType = Context.getObjCClassType();
1510 break;
1511
1512 case BuiltinType::ObjCSel:
1513 VisitType = Context.getObjCSelType();
1514 break;
1515 }
1516
1517 if (!VisitType.isNull()) {
1518 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
1519 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
1520 TU));
1521 }
1522
1523 return false;
1524}
1525
1526bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
1527 return Visit(MakeCursorTypeRef(TL.getTypedefNameDecl(), TL.getNameLoc(), TU));
1528}
1529
1530bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
1531 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1532}
1533
1534bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
1535 if (TL.isDefinition())
1536 return Visit(MakeCXCursor(TL.getDecl(), TU, RegionOfInterest));
1537
1538 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1539}
1540
1541bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
1542 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1543}
1544
1545bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
Hans Wennborg59dbe862015-09-29 20:56:43 +00001546 return Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU));
Guy Benyei11169dd2012-12-18 14:30:41 +00001547}
1548
Manman Rene6be26c2016-09-13 17:25:08 +00001549bool CursorVisitor::VisitObjCTypeParamTypeLoc(ObjCTypeParamTypeLoc TL) {
1550 if (Visit(MakeCursorTypeRef(TL.getDecl(), TL.getLocStart(), TU)))
1551 return true;
1552 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1553 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1554 TU)))
1555 return true;
1556 }
1557
1558 return false;
1559}
1560
Guy Benyei11169dd2012-12-18 14:30:41 +00001561bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1562 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
1563 return true;
1564
Douglas Gregore9d95f12015-07-07 03:57:35 +00001565 for (unsigned I = 0, N = TL.getNumTypeArgs(); I != N; ++I) {
1566 if (Visit(TL.getTypeArgTInfo(I)->getTypeLoc()))
1567 return true;
1568 }
1569
Guy Benyei11169dd2012-12-18 14:30:41 +00001570 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1571 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1572 TU)))
1573 return true;
1574 }
1575
1576 return false;
1577}
1578
1579bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
1580 return Visit(TL.getPointeeLoc());
1581}
1582
1583bool CursorVisitor::VisitParenTypeLoc(ParenTypeLoc TL) {
1584 return Visit(TL.getInnerLoc());
1585}
1586
1587bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
1588 return Visit(TL.getPointeeLoc());
1589}
1590
1591bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1592 return Visit(TL.getPointeeLoc());
1593}
1594
1595bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1596 return Visit(TL.getPointeeLoc());
1597}
1598
1599bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
1600 return Visit(TL.getPointeeLoc());
1601}
1602
1603bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
1604 return Visit(TL.getPointeeLoc());
1605}
1606
1607bool CursorVisitor::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
1608 return Visit(TL.getModifiedLoc());
1609}
1610
1611bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
1612 bool SkipResultType) {
Alp Toker42a16a62014-01-25 23:51:36 +00001613 if (!SkipResultType && Visit(TL.getReturnLoc()))
Guy Benyei11169dd2012-12-18 14:30:41 +00001614 return true;
1615
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00001616 for (unsigned I = 0, N = TL.getNumParams(); I != N; ++I)
1617 if (Decl *D = TL.getParam(I))
Guy Benyei11169dd2012-12-18 14:30:41 +00001618 if (Visit(MakeCXCursor(D, TU, RegionOfInterest)))
1619 return true;
1620
1621 return false;
1622}
1623
1624bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
1625 if (Visit(TL.getElementLoc()))
1626 return true;
1627
1628 if (Expr *Size = TL.getSizeExpr())
1629 return Visit(MakeCXCursor(Size, StmtParent, TU, RegionOfInterest));
1630
1631 return false;
1632}
1633
Reid Kleckner8a365022013-06-24 17:51:48 +00001634bool CursorVisitor::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
1635 return Visit(TL.getOriginalLoc());
1636}
1637
Reid Kleckner0503a872013-12-05 01:23:43 +00001638bool CursorVisitor::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
1639 return Visit(TL.getOriginalLoc());
1640}
1641
Guy Benyei11169dd2012-12-18 14:30:41 +00001642bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
1643 TemplateSpecializationTypeLoc TL) {
1644 // Visit the template name.
1645 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1646 TL.getTemplateNameLoc()))
1647 return true;
1648
1649 // Visit the template arguments.
1650 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1651 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1652 return true;
1653
1654 return false;
1655}
1656
1657bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1658 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
1659}
1660
1661bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1662 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1663 return Visit(TSInfo->getTypeLoc());
1664
1665 return false;
1666}
1667
1668bool CursorVisitor::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
1669 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1670 return Visit(TSInfo->getTypeLoc());
1671
1672 return false;
1673}
1674
1675bool CursorVisitor::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
Hans Wennborg59dbe862015-09-29 20:56:43 +00001676 return VisitNestedNameSpecifierLoc(TL.getQualifierLoc());
Guy Benyei11169dd2012-12-18 14:30:41 +00001677}
1678
1679bool CursorVisitor::VisitDependentTemplateSpecializationTypeLoc(
1680 DependentTemplateSpecializationTypeLoc TL) {
1681 // Visit the nested-name-specifier, if there is one.
1682 if (TL.getQualifierLoc() &&
1683 VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1684 return true;
1685
1686 // Visit the template arguments.
1687 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1688 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1689 return true;
1690
1691 return false;
1692}
1693
1694bool CursorVisitor::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
1695 if (VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1696 return true;
1697
1698 return Visit(TL.getNamedTypeLoc());
1699}
1700
1701bool CursorVisitor::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
1702 return Visit(TL.getPatternLoc());
1703}
1704
1705bool CursorVisitor::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
1706 if (Expr *E = TL.getUnderlyingExpr())
1707 return Visit(MakeCXCursor(E, StmtParent, TU));
1708
1709 return false;
1710}
1711
1712bool CursorVisitor::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
1713 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1714}
1715
1716bool CursorVisitor::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
1717 return Visit(TL.getValueLoc());
1718}
1719
Xiuli Pan9c14e282016-01-09 12:53:17 +00001720bool CursorVisitor::VisitPipeTypeLoc(PipeTypeLoc TL) {
1721 return Visit(TL.getValueLoc());
1722}
1723
Guy Benyei11169dd2012-12-18 14:30:41 +00001724#define DEFAULT_TYPELOC_IMPL(CLASS, PARENT) \
1725bool CursorVisitor::Visit##CLASS##TypeLoc(CLASS##TypeLoc TL) { \
1726 return Visit##PARENT##Loc(TL); \
1727}
1728
1729DEFAULT_TYPELOC_IMPL(Complex, Type)
1730DEFAULT_TYPELOC_IMPL(ConstantArray, ArrayType)
1731DEFAULT_TYPELOC_IMPL(IncompleteArray, ArrayType)
1732DEFAULT_TYPELOC_IMPL(VariableArray, ArrayType)
1733DEFAULT_TYPELOC_IMPL(DependentSizedArray, ArrayType)
1734DEFAULT_TYPELOC_IMPL(DependentSizedExtVector, Type)
1735DEFAULT_TYPELOC_IMPL(Vector, Type)
1736DEFAULT_TYPELOC_IMPL(ExtVector, VectorType)
1737DEFAULT_TYPELOC_IMPL(FunctionProto, FunctionType)
1738DEFAULT_TYPELOC_IMPL(FunctionNoProto, FunctionType)
1739DEFAULT_TYPELOC_IMPL(Record, TagType)
1740DEFAULT_TYPELOC_IMPL(Enum, TagType)
1741DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParm, Type)
1742DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParmPack, Type)
1743DEFAULT_TYPELOC_IMPL(Auto, Type)
1744
1745bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
1746 // Visit the nested-name-specifier, if present.
1747 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1748 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1749 return true;
1750
1751 if (D->isCompleteDefinition()) {
Aaron Ballman574705e2014-03-13 15:41:46 +00001752 for (const auto &I : D->bases()) {
1753 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(&I, TU)))
Guy Benyei11169dd2012-12-18 14:30:41 +00001754 return true;
1755 }
1756 }
1757
1758 return VisitTagDecl(D);
1759}
1760
1761bool CursorVisitor::VisitAttributes(Decl *D) {
Aaron Ballmanb97112e2014-03-08 22:19:01 +00001762 for (const auto *I : D->attrs())
1763 if (Visit(MakeCXCursor(I, D, TU)))
Guy Benyei11169dd2012-12-18 14:30:41 +00001764 return true;
1765
1766 return false;
1767}
1768
1769//===----------------------------------------------------------------------===//
1770// Data-recursive visitor methods.
1771//===----------------------------------------------------------------------===//
1772
1773namespace {
1774#define DEF_JOB(NAME, DATA, KIND)\
1775class NAME : public VisitorJob {\
1776public:\
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001777 NAME(const DATA *d, CXCursor parent) : \
1778 VisitorJob(parent, VisitorJob::KIND, d) {} \
Guy Benyei11169dd2012-12-18 14:30:41 +00001779 static bool classof(const VisitorJob *VJ) { return VJ->getKind() == KIND; }\
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001780 const DATA *get() const { return static_cast<const DATA*>(data[0]); }\
Guy Benyei11169dd2012-12-18 14:30:41 +00001781};
1782
1783DEF_JOB(StmtVisit, Stmt, StmtVisitKind)
1784DEF_JOB(MemberExprParts, MemberExpr, MemberExprPartsKind)
1785DEF_JOB(DeclRefExprParts, DeclRefExpr, DeclRefExprPartsKind)
1786DEF_JOB(OverloadExprParts, OverloadExpr, OverloadExprPartsKind)
Guy Benyei11169dd2012-12-18 14:30:41 +00001787DEF_JOB(SizeOfPackExprParts, SizeOfPackExpr, SizeOfPackExprPartsKind)
1788DEF_JOB(LambdaExprParts, LambdaExpr, LambdaExprPartsKind)
1789DEF_JOB(PostChildrenVisit, void, PostChildrenVisitKind)
1790#undef DEF_JOB
1791
James Y Knight04ec5bf2015-12-24 02:59:37 +00001792class ExplicitTemplateArgsVisit : public VisitorJob {
1793public:
1794 ExplicitTemplateArgsVisit(const TemplateArgumentLoc *Begin,
1795 const TemplateArgumentLoc *End, CXCursor parent)
1796 : VisitorJob(parent, VisitorJob::ExplicitTemplateArgsVisitKind, Begin,
1797 End) {}
1798 static bool classof(const VisitorJob *VJ) {
1799 return VJ->getKind() == ExplicitTemplateArgsVisitKind;
1800 }
1801 const TemplateArgumentLoc *begin() const {
1802 return static_cast<const TemplateArgumentLoc *>(data[0]);
1803 }
1804 const TemplateArgumentLoc *end() {
1805 return static_cast<const TemplateArgumentLoc *>(data[1]);
1806 }
1807};
Guy Benyei11169dd2012-12-18 14:30:41 +00001808class DeclVisit : public VisitorJob {
1809public:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001810 DeclVisit(const Decl *D, CXCursor parent, bool isFirst) :
Guy Benyei11169dd2012-12-18 14:30:41 +00001811 VisitorJob(parent, VisitorJob::DeclVisitKind,
Craig Topper69186e72014-06-08 08:38:04 +00001812 D, isFirst ? (void*) 1 : (void*) nullptr) {}
Guy Benyei11169dd2012-12-18 14:30:41 +00001813 static bool classof(const VisitorJob *VJ) {
1814 return VJ->getKind() == DeclVisitKind;
1815 }
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001816 const Decl *get() const { return static_cast<const Decl *>(data[0]); }
Dmitri Gribenkoe5423a72015-03-23 19:23:50 +00001817 bool isFirst() const { return data[1] != nullptr; }
Guy Benyei11169dd2012-12-18 14:30:41 +00001818};
1819class TypeLocVisit : public VisitorJob {
1820public:
1821 TypeLocVisit(TypeLoc tl, CXCursor parent) :
1822 VisitorJob(parent, VisitorJob::TypeLocVisitKind,
1823 tl.getType().getAsOpaquePtr(), tl.getOpaqueData()) {}
1824
1825 static bool classof(const VisitorJob *VJ) {
1826 return VJ->getKind() == TypeLocVisitKind;
1827 }
1828
1829 TypeLoc get() const {
1830 QualType T = QualType::getFromOpaquePtr(data[0]);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001831 return TypeLoc(T, const_cast<void *>(data[1]));
Guy Benyei11169dd2012-12-18 14:30:41 +00001832 }
1833};
1834
1835class LabelRefVisit : public VisitorJob {
1836public:
1837 LabelRefVisit(LabelDecl *LD, SourceLocation labelLoc, CXCursor parent)
1838 : VisitorJob(parent, VisitorJob::LabelRefVisitKind, LD,
1839 labelLoc.getPtrEncoding()) {}
1840
1841 static bool classof(const VisitorJob *VJ) {
1842 return VJ->getKind() == VisitorJob::LabelRefVisitKind;
1843 }
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001844 const LabelDecl *get() const {
1845 return static_cast<const LabelDecl *>(data[0]);
1846 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001847 SourceLocation getLoc() const {
1848 return SourceLocation::getFromPtrEncoding(data[1]); }
1849};
1850
1851class NestedNameSpecifierLocVisit : public VisitorJob {
1852public:
1853 NestedNameSpecifierLocVisit(NestedNameSpecifierLoc Qualifier, CXCursor parent)
1854 : VisitorJob(parent, VisitorJob::NestedNameSpecifierLocVisitKind,
1855 Qualifier.getNestedNameSpecifier(),
1856 Qualifier.getOpaqueData()) { }
1857
1858 static bool classof(const VisitorJob *VJ) {
1859 return VJ->getKind() == VisitorJob::NestedNameSpecifierLocVisitKind;
1860 }
1861
1862 NestedNameSpecifierLoc get() const {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001863 return NestedNameSpecifierLoc(
1864 const_cast<NestedNameSpecifier *>(
1865 static_cast<const NestedNameSpecifier *>(data[0])),
1866 const_cast<void *>(data[1]));
Guy Benyei11169dd2012-12-18 14:30:41 +00001867 }
1868};
1869
1870class DeclarationNameInfoVisit : public VisitorJob {
1871public:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001872 DeclarationNameInfoVisit(const Stmt *S, CXCursor parent)
Dmitri Gribenkodd7dacf2013-02-03 13:19:54 +00001873 : VisitorJob(parent, VisitorJob::DeclarationNameInfoVisitKind, S) {}
Guy Benyei11169dd2012-12-18 14:30:41 +00001874 static bool classof(const VisitorJob *VJ) {
1875 return VJ->getKind() == VisitorJob::DeclarationNameInfoVisitKind;
1876 }
1877 DeclarationNameInfo get() const {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001878 const Stmt *S = static_cast<const Stmt *>(data[0]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001879 switch (S->getStmtClass()) {
1880 default:
1881 llvm_unreachable("Unhandled Stmt");
1882 case clang::Stmt::MSDependentExistsStmtClass:
1883 return cast<MSDependentExistsStmt>(S)->getNameInfo();
1884 case Stmt::CXXDependentScopeMemberExprClass:
1885 return cast<CXXDependentScopeMemberExpr>(S)->getMemberNameInfo();
1886 case Stmt::DependentScopeDeclRefExprClass:
1887 return cast<DependentScopeDeclRefExpr>(S)->getNameInfo();
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001888 case Stmt::OMPCriticalDirectiveClass:
1889 return cast<OMPCriticalDirective>(S)->getDirectiveName();
Guy Benyei11169dd2012-12-18 14:30:41 +00001890 }
1891 }
1892};
1893class MemberRefVisit : public VisitorJob {
1894public:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001895 MemberRefVisit(const FieldDecl *D, SourceLocation L, CXCursor parent)
Guy Benyei11169dd2012-12-18 14:30:41 +00001896 : VisitorJob(parent, VisitorJob::MemberRefVisitKind, D,
1897 L.getPtrEncoding()) {}
1898 static bool classof(const VisitorJob *VJ) {
1899 return VJ->getKind() == VisitorJob::MemberRefVisitKind;
1900 }
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001901 const FieldDecl *get() const {
1902 return static_cast<const FieldDecl *>(data[0]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001903 }
1904 SourceLocation getLoc() const {
1905 return SourceLocation::getFromRawEncoding((unsigned)(uintptr_t) data[1]);
1906 }
1907};
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001908class EnqueueVisitor : public ConstStmtVisitor<EnqueueVisitor, void> {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001909 friend class OMPClauseEnqueue;
Guy Benyei11169dd2012-12-18 14:30:41 +00001910 VisitorWorkList &WL;
1911 CXCursor Parent;
1912public:
1913 EnqueueVisitor(VisitorWorkList &wl, CXCursor parent)
1914 : WL(wl), Parent(parent) {}
1915
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001916 void VisitAddrLabelExpr(const AddrLabelExpr *E);
1917 void VisitBlockExpr(const BlockExpr *B);
1918 void VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
1919 void VisitCompoundStmt(const CompoundStmt *S);
1920 void VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) { /* Do nothing. */ }
1921 void VisitMSDependentExistsStmt(const MSDependentExistsStmt *S);
1922 void VisitCXXDependentScopeMemberExpr(const CXXDependentScopeMemberExpr *E);
1923 void VisitCXXNewExpr(const CXXNewExpr *E);
1924 void VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E);
1925 void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *E);
1926 void VisitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *E);
1927 void VisitCXXTemporaryObjectExpr(const CXXTemporaryObjectExpr *E);
1928 void VisitCXXTypeidExpr(const CXXTypeidExpr *E);
1929 void VisitCXXUnresolvedConstructExpr(const CXXUnresolvedConstructExpr *E);
1930 void VisitCXXUuidofExpr(const CXXUuidofExpr *E);
1931 void VisitCXXCatchStmt(const CXXCatchStmt *S);
Argyrios Kyrtzidis99891242014-11-13 09:03:21 +00001932 void VisitCXXForRangeStmt(const CXXForRangeStmt *S);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001933 void VisitDeclRefExpr(const DeclRefExpr *D);
1934 void VisitDeclStmt(const DeclStmt *S);
1935 void VisitDependentScopeDeclRefExpr(const DependentScopeDeclRefExpr *E);
1936 void VisitDesignatedInitExpr(const DesignatedInitExpr *E);
1937 void VisitExplicitCastExpr(const ExplicitCastExpr *E);
1938 void VisitForStmt(const ForStmt *FS);
1939 void VisitGotoStmt(const GotoStmt *GS);
1940 void VisitIfStmt(const IfStmt *If);
1941 void VisitInitListExpr(const InitListExpr *IE);
1942 void VisitMemberExpr(const MemberExpr *M);
1943 void VisitOffsetOfExpr(const OffsetOfExpr *E);
1944 void VisitObjCEncodeExpr(const ObjCEncodeExpr *E);
1945 void VisitObjCMessageExpr(const ObjCMessageExpr *M);
1946 void VisitOverloadExpr(const OverloadExpr *E);
1947 void VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
1948 void VisitStmt(const Stmt *S);
1949 void VisitSwitchStmt(const SwitchStmt *S);
1950 void VisitWhileStmt(const WhileStmt *W);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001951 void VisitTypeTraitExpr(const TypeTraitExpr *E);
1952 void VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E);
1953 void VisitExpressionTraitExpr(const ExpressionTraitExpr *E);
1954 void VisitUnresolvedMemberExpr(const UnresolvedMemberExpr *U);
1955 void VisitVAArgExpr(const VAArgExpr *E);
1956 void VisitSizeOfPackExpr(const SizeOfPackExpr *E);
1957 void VisitPseudoObjectExpr(const PseudoObjectExpr *E);
1958 void VisitOpaqueValueExpr(const OpaqueValueExpr *E);
1959 void VisitLambdaExpr(const LambdaExpr *E);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001960 void VisitOMPExecutableDirective(const OMPExecutableDirective *D);
Alexander Musman3aaab662014-08-19 11:27:13 +00001961 void VisitOMPLoopDirective(const OMPLoopDirective *D);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001962 void VisitOMPParallelDirective(const OMPParallelDirective *D);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00001963 void VisitOMPSimdDirective(const OMPSimdDirective *D);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001964 void VisitOMPForDirective(const OMPForDirective *D);
Alexander Musmanf82886e2014-09-18 05:12:34 +00001965 void VisitOMPForSimdDirective(const OMPForSimdDirective *D);
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00001966 void VisitOMPSectionsDirective(const OMPSectionsDirective *D);
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001967 void VisitOMPSectionDirective(const OMPSectionDirective *D);
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00001968 void VisitOMPSingleDirective(const OMPSingleDirective *D);
Alexander Musman80c22892014-07-17 08:54:58 +00001969 void VisitOMPMasterDirective(const OMPMasterDirective *D);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001970 void VisitOMPCriticalDirective(const OMPCriticalDirective *D);
Alexey Bataev4acb8592014-07-07 13:01:15 +00001971 void VisitOMPParallelForDirective(const OMPParallelForDirective *D);
Alexander Musmane4e893b2014-09-23 09:33:00 +00001972 void VisitOMPParallelForSimdDirective(const OMPParallelForSimdDirective *D);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001973 void VisitOMPParallelSectionsDirective(const OMPParallelSectionsDirective *D);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001974 void VisitOMPTaskDirective(const OMPTaskDirective *D);
Alexey Bataev68446b72014-07-18 07:47:19 +00001975 void VisitOMPTaskyieldDirective(const OMPTaskyieldDirective *D);
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001976 void VisitOMPBarrierDirective(const OMPBarrierDirective *D);
Alexey Bataev2df347a2014-07-18 10:17:07 +00001977 void VisitOMPTaskwaitDirective(const OMPTaskwaitDirective *D);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001978 void VisitOMPTaskgroupDirective(const OMPTaskgroupDirective *D);
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001979 void
1980 VisitOMPCancellationPointDirective(const OMPCancellationPointDirective *D);
Alexey Bataev80909872015-07-02 11:25:17 +00001981 void VisitOMPCancelDirective(const OMPCancelDirective *D);
Alexey Bataev6125da92014-07-21 11:26:11 +00001982 void VisitOMPFlushDirective(const OMPFlushDirective *D);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001983 void VisitOMPOrderedDirective(const OMPOrderedDirective *D);
Alexey Bataev0162e452014-07-22 10:10:35 +00001984 void VisitOMPAtomicDirective(const OMPAtomicDirective *D);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001985 void VisitOMPTargetDirective(const OMPTargetDirective *D);
Michael Wong65f367f2015-07-21 13:44:28 +00001986 void VisitOMPTargetDataDirective(const OMPTargetDataDirective *D);
Samuel Antaodf67fc42016-01-19 19:15:56 +00001987 void VisitOMPTargetEnterDataDirective(const OMPTargetEnterDataDirective *D);
Samuel Antao72590762016-01-19 20:04:50 +00001988 void VisitOMPTargetExitDataDirective(const OMPTargetExitDataDirective *D);
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00001989 void VisitOMPTargetParallelDirective(const OMPTargetParallelDirective *D);
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00001990 void
1991 VisitOMPTargetParallelForDirective(const OMPTargetParallelForDirective *D);
Alexey Bataev13314bf2014-10-09 04:18:56 +00001992 void VisitOMPTeamsDirective(const OMPTeamsDirective *D);
Alexey Bataev49f6e782015-12-01 04:18:41 +00001993 void VisitOMPTaskLoopDirective(const OMPTaskLoopDirective *D);
Alexey Bataev0a6ed842015-12-03 09:40:15 +00001994 void VisitOMPTaskLoopSimdDirective(const OMPTaskLoopSimdDirective *D);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00001995 void VisitOMPDistributeDirective(const OMPDistributeDirective *D);
Carlo Bertolli9925f152016-06-27 14:55:37 +00001996 void VisitOMPDistributeParallelForDirective(
1997 const OMPDistributeParallelForDirective *D);
Kelvin Li4a39add2016-07-05 05:00:15 +00001998 void VisitOMPDistributeParallelForSimdDirective(
1999 const OMPDistributeParallelForSimdDirective *D);
Kelvin Li787f3fc2016-07-06 04:45:38 +00002000 void VisitOMPDistributeSimdDirective(const OMPDistributeSimdDirective *D);
Kelvin Lia579b912016-07-14 02:54:56 +00002001 void VisitOMPTargetParallelForSimdDirective(
2002 const OMPTargetParallelForSimdDirective *D);
Kelvin Li986330c2016-07-20 22:57:10 +00002003 void VisitOMPTargetSimdDirective(const OMPTargetSimdDirective *D);
Kelvin Li02532872016-08-05 14:37:37 +00002004 void VisitOMPTeamsDistributeDirective(const OMPTeamsDistributeDirective *D);
Kelvin Li4e325f72016-10-25 12:50:55 +00002005 void VisitOMPTeamsDistributeSimdDirective(
2006 const OMPTeamsDistributeSimdDirective *D);
Kelvin Li579e41c2016-11-30 23:51:03 +00002007 void VisitOMPTeamsDistributeParallelForSimdDirective(
2008 const OMPTeamsDistributeParallelForSimdDirective *D);
Kelvin Li7ade93f2016-12-09 03:24:30 +00002009 void VisitOMPTeamsDistributeParallelForDirective(
2010 const OMPTeamsDistributeParallelForDirective *D);
Kelvin Libf594a52016-12-17 05:48:59 +00002011 void VisitOMPTargetTeamsDirective(const OMPTargetTeamsDirective *D);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002012
Guy Benyei11169dd2012-12-18 14:30:41 +00002013private:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002014 void AddDeclarationNameInfo(const Stmt *S);
Guy Benyei11169dd2012-12-18 14:30:41 +00002015 void AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier);
James Y Knight04ec5bf2015-12-24 02:59:37 +00002016 void AddExplicitTemplateArgs(const TemplateArgumentLoc *A,
2017 unsigned NumTemplateArgs);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002018 void AddMemberRef(const FieldDecl *D, SourceLocation L);
2019 void AddStmt(const Stmt *S);
2020 void AddDecl(const Decl *D, bool isFirst = true);
Guy Benyei11169dd2012-12-18 14:30:41 +00002021 void AddTypeLoc(TypeSourceInfo *TI);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002022 void EnqueueChildren(const Stmt *S);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002023 void EnqueueChildren(const OMPClause *S);
Guy Benyei11169dd2012-12-18 14:30:41 +00002024};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002025} // end anonyous namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00002026
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002027void EnqueueVisitor::AddDeclarationNameInfo(const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002028 // 'S' should always be non-null, since it comes from the
2029 // statement we are visiting.
2030 WL.push_back(DeclarationNameInfoVisit(S, Parent));
2031}
2032
2033void
2034EnqueueVisitor::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
2035 if (Qualifier)
2036 WL.push_back(NestedNameSpecifierLocVisit(Qualifier, Parent));
2037}
2038
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002039void EnqueueVisitor::AddStmt(const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002040 if (S)
2041 WL.push_back(StmtVisit(S, Parent));
2042}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002043void EnqueueVisitor::AddDecl(const Decl *D, bool isFirst) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002044 if (D)
2045 WL.push_back(DeclVisit(D, Parent, isFirst));
2046}
James Y Knight04ec5bf2015-12-24 02:59:37 +00002047void EnqueueVisitor::AddExplicitTemplateArgs(const TemplateArgumentLoc *A,
2048 unsigned NumTemplateArgs) {
2049 WL.push_back(ExplicitTemplateArgsVisit(A, A + NumTemplateArgs, Parent));
Guy Benyei11169dd2012-12-18 14:30:41 +00002050}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002051void EnqueueVisitor::AddMemberRef(const FieldDecl *D, SourceLocation L) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002052 if (D)
2053 WL.push_back(MemberRefVisit(D, L, Parent));
2054}
2055void EnqueueVisitor::AddTypeLoc(TypeSourceInfo *TI) {
2056 if (TI)
2057 WL.push_back(TypeLocVisit(TI->getTypeLoc(), Parent));
2058 }
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002059void EnqueueVisitor::EnqueueChildren(const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002060 unsigned size = WL.size();
Benjamin Kramer642f1732015-07-02 21:03:14 +00002061 for (const Stmt *SubStmt : S->children()) {
2062 AddStmt(SubStmt);
Guy Benyei11169dd2012-12-18 14:30:41 +00002063 }
2064 if (size == WL.size())
2065 return;
2066 // Now reverse the entries we just added. This will match the DFS
2067 // ordering performed by the worklist.
2068 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2069 std::reverse(I, E);
2070}
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002071namespace {
2072class OMPClauseEnqueue : public ConstOMPClauseVisitor<OMPClauseEnqueue> {
2073 EnqueueVisitor *Visitor;
Alexey Bataev756c1962013-09-24 03:17:45 +00002074 /// \brief Process clauses with list of variables.
2075 template <typename T>
2076 void VisitOMPClauseList(T *Node);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002077public:
2078 OMPClauseEnqueue(EnqueueVisitor *Visitor) : Visitor(Visitor) { }
2079#define OPENMP_CLAUSE(Name, Class) \
2080 void Visit##Class(const Class *C);
2081#include "clang/Basic/OpenMPKinds.def"
Alexey Bataev3392d762016-02-16 11:18:12 +00002082 void VisitOMPClauseWithPreInit(const OMPClauseWithPreInit *C);
Alexey Bataev005248a2016-02-25 05:25:57 +00002083 void VisitOMPClauseWithPostUpdate(const OMPClauseWithPostUpdate *C);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002084};
2085
Alexey Bataev3392d762016-02-16 11:18:12 +00002086void OMPClauseEnqueue::VisitOMPClauseWithPreInit(
2087 const OMPClauseWithPreInit *C) {
2088 Visitor->AddStmt(C->getPreInitStmt());
2089}
2090
Alexey Bataev005248a2016-02-25 05:25:57 +00002091void OMPClauseEnqueue::VisitOMPClauseWithPostUpdate(
2092 const OMPClauseWithPostUpdate *C) {
Alexey Bataev37e594c2016-03-04 07:21:16 +00002093 VisitOMPClauseWithPreInit(C);
Alexey Bataev005248a2016-02-25 05:25:57 +00002094 Visitor->AddStmt(C->getPostUpdateExpr());
2095}
2096
Alexey Bataevaadd52e2014-02-13 05:29:23 +00002097void OMPClauseEnqueue::VisitOMPIfClause(const OMPIfClause *C) {
2098 Visitor->AddStmt(C->getCondition());
2099}
2100
Alexey Bataev3778b602014-07-17 07:32:53 +00002101void OMPClauseEnqueue::VisitOMPFinalClause(const OMPFinalClause *C) {
2102 Visitor->AddStmt(C->getCondition());
2103}
2104
Alexey Bataev568a8332014-03-06 06:15:19 +00002105void OMPClauseEnqueue::VisitOMPNumThreadsClause(const OMPNumThreadsClause *C) {
2106 Visitor->AddStmt(C->getNumThreads());
2107}
2108
Alexey Bataev62c87d22014-03-21 04:51:18 +00002109void OMPClauseEnqueue::VisitOMPSafelenClause(const OMPSafelenClause *C) {
2110 Visitor->AddStmt(C->getSafelen());
2111}
2112
Alexey Bataev66b15b52015-08-21 11:14:16 +00002113void OMPClauseEnqueue::VisitOMPSimdlenClause(const OMPSimdlenClause *C) {
2114 Visitor->AddStmt(C->getSimdlen());
2115}
2116
Alexander Musman8bd31e62014-05-27 15:12:19 +00002117void OMPClauseEnqueue::VisitOMPCollapseClause(const OMPCollapseClause *C) {
2118 Visitor->AddStmt(C->getNumForLoops());
2119}
2120
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002121void OMPClauseEnqueue::VisitOMPDefaultClause(const OMPDefaultClause *C) { }
Alexey Bataev756c1962013-09-24 03:17:45 +00002122
Alexey Bataevbcbadb62014-05-06 06:04:14 +00002123void OMPClauseEnqueue::VisitOMPProcBindClause(const OMPProcBindClause *C) { }
2124
Alexey Bataev56dafe82014-06-20 07:16:17 +00002125void OMPClauseEnqueue::VisitOMPScheduleClause(const OMPScheduleClause *C) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002126 VisitOMPClauseWithPreInit(C);
Alexey Bataev56dafe82014-06-20 07:16:17 +00002127 Visitor->AddStmt(C->getChunkSize());
2128}
2129
Alexey Bataev10e775f2015-07-30 11:36:16 +00002130void OMPClauseEnqueue::VisitOMPOrderedClause(const OMPOrderedClause *C) {
2131 Visitor->AddStmt(C->getNumForLoops());
2132}
Alexey Bataev142e1fc2014-06-20 09:44:06 +00002133
Alexey Bataev236070f2014-06-20 11:19:47 +00002134void OMPClauseEnqueue::VisitOMPNowaitClause(const OMPNowaitClause *) {}
2135
Alexey Bataev7aea99a2014-07-17 12:19:31 +00002136void OMPClauseEnqueue::VisitOMPUntiedClause(const OMPUntiedClause *) {}
2137
Alexey Bataev74ba3a52014-07-17 12:47:03 +00002138void OMPClauseEnqueue::VisitOMPMergeableClause(const OMPMergeableClause *) {}
2139
Alexey Bataevf98b00c2014-07-23 02:27:21 +00002140void OMPClauseEnqueue::VisitOMPReadClause(const OMPReadClause *) {}
2141
Alexey Bataevdea47612014-07-23 07:46:59 +00002142void OMPClauseEnqueue::VisitOMPWriteClause(const OMPWriteClause *) {}
2143
Alexey Bataev67a4f222014-07-23 10:25:33 +00002144void OMPClauseEnqueue::VisitOMPUpdateClause(const OMPUpdateClause *) {}
2145
Alexey Bataev459dec02014-07-24 06:46:57 +00002146void OMPClauseEnqueue::VisitOMPCaptureClause(const OMPCaptureClause *) {}
2147
Alexey Bataev82bad8b2014-07-24 08:55:34 +00002148void OMPClauseEnqueue::VisitOMPSeqCstClause(const OMPSeqCstClause *) {}
2149
Alexey Bataev346265e2015-09-25 10:37:12 +00002150void OMPClauseEnqueue::VisitOMPThreadsClause(const OMPThreadsClause *) {}
2151
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002152void OMPClauseEnqueue::VisitOMPSIMDClause(const OMPSIMDClause *) {}
2153
Alexey Bataevb825de12015-12-07 10:51:44 +00002154void OMPClauseEnqueue::VisitOMPNogroupClause(const OMPNogroupClause *) {}
2155
Michael Wonge710d542015-08-07 16:16:36 +00002156void OMPClauseEnqueue::VisitOMPDeviceClause(const OMPDeviceClause *C) {
2157 Visitor->AddStmt(C->getDevice());
2158}
2159
Kelvin Li099bb8c2015-11-24 20:50:12 +00002160void OMPClauseEnqueue::VisitOMPNumTeamsClause(const OMPNumTeamsClause *C) {
2161 Visitor->AddStmt(C->getNumTeams());
2162}
2163
Kelvin Lia15fb1a2015-11-27 18:47:36 +00002164void OMPClauseEnqueue::VisitOMPThreadLimitClause(const OMPThreadLimitClause *C) {
2165 Visitor->AddStmt(C->getThreadLimit());
2166}
2167
Alexey Bataeva0569352015-12-01 10:17:31 +00002168void OMPClauseEnqueue::VisitOMPPriorityClause(const OMPPriorityClause *C) {
2169 Visitor->AddStmt(C->getPriority());
2170}
2171
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00002172void OMPClauseEnqueue::VisitOMPGrainsizeClause(const OMPGrainsizeClause *C) {
2173 Visitor->AddStmt(C->getGrainsize());
2174}
2175
Alexey Bataev382967a2015-12-08 12:06:20 +00002176void OMPClauseEnqueue::VisitOMPNumTasksClause(const OMPNumTasksClause *C) {
2177 Visitor->AddStmt(C->getNumTasks());
2178}
2179
Alexey Bataev28c75412015-12-15 08:19:24 +00002180void OMPClauseEnqueue::VisitOMPHintClause(const OMPHintClause *C) {
2181 Visitor->AddStmt(C->getHint());
2182}
2183
Alexey Bataev756c1962013-09-24 03:17:45 +00002184template<typename T>
2185void OMPClauseEnqueue::VisitOMPClauseList(T *Node) {
Alexey Bataev03b340a2014-10-21 03:16:40 +00002186 for (const auto *I : Node->varlists()) {
Aaron Ballman2205d2a2014-03-14 15:55:35 +00002187 Visitor->AddStmt(I);
Alexey Bataev03b340a2014-10-21 03:16:40 +00002188 }
Alexey Bataev756c1962013-09-24 03:17:45 +00002189}
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002190
2191void OMPClauseEnqueue::VisitOMPPrivateClause(const OMPPrivateClause *C) {
Alexey Bataev756c1962013-09-24 03:17:45 +00002192 VisitOMPClauseList(C);
Alexey Bataev03b340a2014-10-21 03:16:40 +00002193 for (const auto *E : C->private_copies()) {
2194 Visitor->AddStmt(E);
2195 }
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002196}
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002197void OMPClauseEnqueue::VisitOMPFirstprivateClause(
2198 const OMPFirstprivateClause *C) {
2199 VisitOMPClauseList(C);
Alexey Bataev417089f2016-02-17 13:19:37 +00002200 VisitOMPClauseWithPreInit(C);
2201 for (const auto *E : C->private_copies()) {
2202 Visitor->AddStmt(E);
2203 }
2204 for (const auto *E : C->inits()) {
2205 Visitor->AddStmt(E);
2206 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002207}
Alexander Musman1bb328c2014-06-04 13:06:39 +00002208void OMPClauseEnqueue::VisitOMPLastprivateClause(
2209 const OMPLastprivateClause *C) {
2210 VisitOMPClauseList(C);
Alexey Bataev005248a2016-02-25 05:25:57 +00002211 VisitOMPClauseWithPostUpdate(C);
Alexey Bataev38e89532015-04-16 04:54:05 +00002212 for (auto *E : C->private_copies()) {
2213 Visitor->AddStmt(E);
2214 }
2215 for (auto *E : C->source_exprs()) {
2216 Visitor->AddStmt(E);
2217 }
2218 for (auto *E : C->destination_exprs()) {
2219 Visitor->AddStmt(E);
2220 }
2221 for (auto *E : C->assignment_ops()) {
2222 Visitor->AddStmt(E);
2223 }
Alexander Musman1bb328c2014-06-04 13:06:39 +00002224}
Alexey Bataev758e55e2013-09-06 18:03:48 +00002225void OMPClauseEnqueue::VisitOMPSharedClause(const OMPSharedClause *C) {
Alexey Bataev756c1962013-09-24 03:17:45 +00002226 VisitOMPClauseList(C);
Alexey Bataev758e55e2013-09-06 18:03:48 +00002227}
Alexey Bataevc5e02582014-06-16 07:08:35 +00002228void OMPClauseEnqueue::VisitOMPReductionClause(const OMPReductionClause *C) {
2229 VisitOMPClauseList(C);
Alexey Bataev61205072016-03-02 04:57:40 +00002230 VisitOMPClauseWithPostUpdate(C);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00002231 for (auto *E : C->privates()) {
2232 Visitor->AddStmt(E);
2233 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002234 for (auto *E : C->lhs_exprs()) {
2235 Visitor->AddStmt(E);
2236 }
2237 for (auto *E : C->rhs_exprs()) {
2238 Visitor->AddStmt(E);
2239 }
2240 for (auto *E : C->reduction_ops()) {
2241 Visitor->AddStmt(E);
2242 }
Alexey Bataevc5e02582014-06-16 07:08:35 +00002243}
Alexander Musman8dba6642014-04-22 13:09:42 +00002244void OMPClauseEnqueue::VisitOMPLinearClause(const OMPLinearClause *C) {
2245 VisitOMPClauseList(C);
Alexey Bataev78849fb2016-03-09 09:49:00 +00002246 VisitOMPClauseWithPostUpdate(C);
Alexey Bataevbd9fec12015-08-18 06:47:21 +00002247 for (const auto *E : C->privates()) {
2248 Visitor->AddStmt(E);
2249 }
Alexander Musman3276a272015-03-21 10:12:56 +00002250 for (const auto *E : C->inits()) {
2251 Visitor->AddStmt(E);
2252 }
2253 for (const auto *E : C->updates()) {
2254 Visitor->AddStmt(E);
2255 }
2256 for (const auto *E : C->finals()) {
2257 Visitor->AddStmt(E);
2258 }
Alexander Musman8dba6642014-04-22 13:09:42 +00002259 Visitor->AddStmt(C->getStep());
Alexander Musman3276a272015-03-21 10:12:56 +00002260 Visitor->AddStmt(C->getCalcStep());
Alexander Musman8dba6642014-04-22 13:09:42 +00002261}
Alexander Musmanf0d76e72014-05-29 14:36:25 +00002262void OMPClauseEnqueue::VisitOMPAlignedClause(const OMPAlignedClause *C) {
2263 VisitOMPClauseList(C);
2264 Visitor->AddStmt(C->getAlignment());
2265}
Alexey Bataevd48bcd82014-03-31 03:36:38 +00002266void OMPClauseEnqueue::VisitOMPCopyinClause(const OMPCopyinClause *C) {
2267 VisitOMPClauseList(C);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00002268 for (auto *E : C->source_exprs()) {
2269 Visitor->AddStmt(E);
2270 }
2271 for (auto *E : C->destination_exprs()) {
2272 Visitor->AddStmt(E);
2273 }
2274 for (auto *E : C->assignment_ops()) {
2275 Visitor->AddStmt(E);
2276 }
Alexey Bataevd48bcd82014-03-31 03:36:38 +00002277}
Alexey Bataevbae9a792014-06-27 10:37:06 +00002278void
2279OMPClauseEnqueue::VisitOMPCopyprivateClause(const OMPCopyprivateClause *C) {
2280 VisitOMPClauseList(C);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002281 for (auto *E : C->source_exprs()) {
2282 Visitor->AddStmt(E);
2283 }
2284 for (auto *E : C->destination_exprs()) {
2285 Visitor->AddStmt(E);
2286 }
2287 for (auto *E : C->assignment_ops()) {
2288 Visitor->AddStmt(E);
2289 }
Alexey Bataevbae9a792014-06-27 10:37:06 +00002290}
Alexey Bataev6125da92014-07-21 11:26:11 +00002291void OMPClauseEnqueue::VisitOMPFlushClause(const OMPFlushClause *C) {
2292 VisitOMPClauseList(C);
2293}
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00002294void OMPClauseEnqueue::VisitOMPDependClause(const OMPDependClause *C) {
2295 VisitOMPClauseList(C);
2296}
Kelvin Li0bff7af2015-11-23 05:32:03 +00002297void OMPClauseEnqueue::VisitOMPMapClause(const OMPMapClause *C) {
2298 VisitOMPClauseList(C);
2299}
Carlo Bertollib4adf552016-01-15 18:50:31 +00002300void OMPClauseEnqueue::VisitOMPDistScheduleClause(
2301 const OMPDistScheduleClause *C) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002302 VisitOMPClauseWithPreInit(C);
Carlo Bertollib4adf552016-01-15 18:50:31 +00002303 Visitor->AddStmt(C->getChunkSize());
Carlo Bertollib4adf552016-01-15 18:50:31 +00002304}
Alexey Bataev3392d762016-02-16 11:18:12 +00002305void OMPClauseEnqueue::VisitOMPDefaultmapClause(
2306 const OMPDefaultmapClause * /*C*/) {}
Samuel Antao661c0902016-05-26 17:39:58 +00002307void OMPClauseEnqueue::VisitOMPToClause(const OMPToClause *C) {
2308 VisitOMPClauseList(C);
2309}
Samuel Antaoec172c62016-05-26 17:49:04 +00002310void OMPClauseEnqueue::VisitOMPFromClause(const OMPFromClause *C) {
2311 VisitOMPClauseList(C);
2312}
Carlo Bertolli2404b172016-07-13 15:37:16 +00002313void OMPClauseEnqueue::VisitOMPUseDevicePtrClause(const OMPUseDevicePtrClause *C) {
2314 VisitOMPClauseList(C);
2315}
Carlo Bertolli70594e92016-07-13 17:16:49 +00002316void OMPClauseEnqueue::VisitOMPIsDevicePtrClause(const OMPIsDevicePtrClause *C) {
2317 VisitOMPClauseList(C);
2318}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002319}
Alexey Bataev756c1962013-09-24 03:17:45 +00002320
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002321void EnqueueVisitor::EnqueueChildren(const OMPClause *S) {
2322 unsigned size = WL.size();
2323 OMPClauseEnqueue Visitor(this);
2324 Visitor.Visit(S);
2325 if (size == WL.size())
2326 return;
2327 // Now reverse the entries we just added. This will match the DFS
2328 // ordering performed by the worklist.
2329 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2330 std::reverse(I, E);
2331}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002332void EnqueueVisitor::VisitAddrLabelExpr(const AddrLabelExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002333 WL.push_back(LabelRefVisit(E->getLabel(), E->getLabelLoc(), Parent));
2334}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002335void EnqueueVisitor::VisitBlockExpr(const BlockExpr *B) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002336 AddDecl(B->getBlockDecl());
2337}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002338void EnqueueVisitor::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002339 EnqueueChildren(E);
2340 AddTypeLoc(E->getTypeSourceInfo());
2341}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002342void EnqueueVisitor::VisitCompoundStmt(const CompoundStmt *S) {
Pete Cooper57d3f142015-07-30 17:22:52 +00002343 for (auto &I : llvm::reverse(S->body()))
2344 AddStmt(I);
Guy Benyei11169dd2012-12-18 14:30:41 +00002345}
2346void EnqueueVisitor::
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002347VisitMSDependentExistsStmt(const MSDependentExistsStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002348 AddStmt(S->getSubStmt());
2349 AddDeclarationNameInfo(S);
2350 if (NestedNameSpecifierLoc QualifierLoc = S->getQualifierLoc())
2351 AddNestedNameSpecifierLoc(QualifierLoc);
2352}
2353
2354void EnqueueVisitor::
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002355VisitCXXDependentScopeMemberExpr(const CXXDependentScopeMemberExpr *E) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002356 if (E->hasExplicitTemplateArgs())
2357 AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002358 AddDeclarationNameInfo(E);
2359 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
2360 AddNestedNameSpecifierLoc(QualifierLoc);
2361 if (!E->isImplicitAccess())
2362 AddStmt(E->getBase());
2363}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002364void EnqueueVisitor::VisitCXXNewExpr(const CXXNewExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002365 // Enqueue the initializer , if any.
2366 AddStmt(E->getInitializer());
2367 // Enqueue the array size, if any.
2368 AddStmt(E->getArraySize());
2369 // Enqueue the allocated type.
2370 AddTypeLoc(E->getAllocatedTypeSourceInfo());
2371 // Enqueue the placement arguments.
2372 for (unsigned I = E->getNumPlacementArgs(); I > 0; --I)
2373 AddStmt(E->getPlacementArg(I-1));
2374}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002375void EnqueueVisitor::VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CE) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002376 for (unsigned I = CE->getNumArgs(); I > 1 /* Yes, this is 1 */; --I)
2377 AddStmt(CE->getArg(I-1));
2378 AddStmt(CE->getCallee());
2379 AddStmt(CE->getArg(0));
2380}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002381void EnqueueVisitor::VisitCXXPseudoDestructorExpr(
2382 const CXXPseudoDestructorExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002383 // Visit the name of the type being destroyed.
2384 AddTypeLoc(E->getDestroyedTypeInfo());
2385 // Visit the scope type that looks disturbingly like the nested-name-specifier
2386 // but isn't.
2387 AddTypeLoc(E->getScopeTypeInfo());
2388 // Visit the nested-name-specifier.
2389 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
2390 AddNestedNameSpecifierLoc(QualifierLoc);
2391 // Visit base expression.
2392 AddStmt(E->getBase());
2393}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002394void EnqueueVisitor::VisitCXXScalarValueInitExpr(
2395 const CXXScalarValueInitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002396 AddTypeLoc(E->getTypeSourceInfo());
2397}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002398void EnqueueVisitor::VisitCXXTemporaryObjectExpr(
2399 const CXXTemporaryObjectExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002400 EnqueueChildren(E);
2401 AddTypeLoc(E->getTypeSourceInfo());
2402}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002403void EnqueueVisitor::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002404 EnqueueChildren(E);
2405 if (E->isTypeOperand())
2406 AddTypeLoc(E->getTypeOperandSourceInfo());
2407}
2408
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002409void EnqueueVisitor::VisitCXXUnresolvedConstructExpr(
2410 const CXXUnresolvedConstructExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002411 EnqueueChildren(E);
2412 AddTypeLoc(E->getTypeSourceInfo());
2413}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002414void EnqueueVisitor::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002415 EnqueueChildren(E);
2416 if (E->isTypeOperand())
2417 AddTypeLoc(E->getTypeOperandSourceInfo());
2418}
2419
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002420void EnqueueVisitor::VisitCXXCatchStmt(const CXXCatchStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002421 EnqueueChildren(S);
2422 AddDecl(S->getExceptionDecl());
2423}
2424
Argyrios Kyrtzidis99891242014-11-13 09:03:21 +00002425void EnqueueVisitor::VisitCXXForRangeStmt(const CXXForRangeStmt *S) {
Argyrios Kyrtzidiscde70692014-11-13 09:50:19 +00002426 AddStmt(S->getBody());
Argyrios Kyrtzidis99891242014-11-13 09:03:21 +00002427 AddStmt(S->getRangeInit());
Argyrios Kyrtzidiscde70692014-11-13 09:50:19 +00002428 AddDecl(S->getLoopVariable());
Argyrios Kyrtzidis99891242014-11-13 09:03:21 +00002429}
2430
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002431void EnqueueVisitor::VisitDeclRefExpr(const DeclRefExpr *DR) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002432 if (DR->hasExplicitTemplateArgs())
2433 AddExplicitTemplateArgs(DR->getTemplateArgs(), DR->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002434 WL.push_back(DeclRefExprParts(DR, Parent));
2435}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002436void EnqueueVisitor::VisitDependentScopeDeclRefExpr(
2437 const DependentScopeDeclRefExpr *E) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002438 if (E->hasExplicitTemplateArgs())
2439 AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002440 AddDeclarationNameInfo(E);
2441 AddNestedNameSpecifierLoc(E->getQualifierLoc());
2442}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002443void EnqueueVisitor::VisitDeclStmt(const DeclStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002444 unsigned size = WL.size();
2445 bool isFirst = true;
Aaron Ballman535bbcc2014-03-14 17:01:24 +00002446 for (const auto *D : S->decls()) {
2447 AddDecl(D, isFirst);
Guy Benyei11169dd2012-12-18 14:30:41 +00002448 isFirst = false;
2449 }
2450 if (size == WL.size())
2451 return;
2452 // Now reverse the entries we just added. This will match the DFS
2453 // ordering performed by the worklist.
2454 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2455 std::reverse(I, E);
2456}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002457void EnqueueVisitor::VisitDesignatedInitExpr(const DesignatedInitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002458 AddStmt(E->getInit());
David Majnemerf7e36092016-06-23 00:15:04 +00002459 for (const DesignatedInitExpr::Designator &D :
2460 llvm::reverse(E->designators())) {
2461 if (D.isFieldDesignator()) {
2462 if (FieldDecl *Field = D.getField())
2463 AddMemberRef(Field, D.getFieldLoc());
Guy Benyei11169dd2012-12-18 14:30:41 +00002464 continue;
2465 }
David Majnemerf7e36092016-06-23 00:15:04 +00002466 if (D.isArrayDesignator()) {
2467 AddStmt(E->getArrayIndex(D));
Guy Benyei11169dd2012-12-18 14:30:41 +00002468 continue;
2469 }
David Majnemerf7e36092016-06-23 00:15:04 +00002470 assert(D.isArrayRangeDesignator() && "Unknown designator kind");
2471 AddStmt(E->getArrayRangeEnd(D));
2472 AddStmt(E->getArrayRangeStart(D));
Guy Benyei11169dd2012-12-18 14:30:41 +00002473 }
2474}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002475void EnqueueVisitor::VisitExplicitCastExpr(const ExplicitCastExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002476 EnqueueChildren(E);
2477 AddTypeLoc(E->getTypeInfoAsWritten());
2478}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002479void EnqueueVisitor::VisitForStmt(const ForStmt *FS) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002480 AddStmt(FS->getBody());
2481 AddStmt(FS->getInc());
2482 AddStmt(FS->getCond());
2483 AddDecl(FS->getConditionVariable());
2484 AddStmt(FS->getInit());
2485}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002486void EnqueueVisitor::VisitGotoStmt(const GotoStmt *GS) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002487 WL.push_back(LabelRefVisit(GS->getLabel(), GS->getLabelLoc(), Parent));
2488}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002489void EnqueueVisitor::VisitIfStmt(const IfStmt *If) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002490 AddStmt(If->getElse());
2491 AddStmt(If->getThen());
2492 AddStmt(If->getCond());
2493 AddDecl(If->getConditionVariable());
2494}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002495void EnqueueVisitor::VisitInitListExpr(const InitListExpr *IE) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002496 // We care about the syntactic form of the initializer list, only.
2497 if (InitListExpr *Syntactic = IE->getSyntacticForm())
2498 IE = Syntactic;
2499 EnqueueChildren(IE);
2500}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002501void EnqueueVisitor::VisitMemberExpr(const MemberExpr *M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002502 WL.push_back(MemberExprParts(M, Parent));
2503
2504 // If the base of the member access expression is an implicit 'this', don't
2505 // visit it.
2506 // FIXME: If we ever want to show these implicit accesses, this will be
2507 // unfortunate. However, clang_getCursor() relies on this behavior.
Argyrios Kyrtzidis58d0e7a2015-03-13 04:40:07 +00002508 if (M->isImplicitAccess())
2509 return;
2510
2511 // Ignore base anonymous struct/union fields, otherwise they will shadow the
2512 // real field that that we are interested in.
2513 if (auto *SubME = dyn_cast<MemberExpr>(M->getBase())) {
2514 if (auto *FD = dyn_cast_or_null<FieldDecl>(SubME->getMemberDecl())) {
2515 if (FD->isAnonymousStructOrUnion()) {
2516 AddStmt(SubME->getBase());
2517 return;
2518 }
2519 }
2520 }
2521
2522 AddStmt(M->getBase());
Guy Benyei11169dd2012-12-18 14:30:41 +00002523}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002524void EnqueueVisitor::VisitObjCEncodeExpr(const ObjCEncodeExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002525 AddTypeLoc(E->getEncodedTypeSourceInfo());
2526}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002527void EnqueueVisitor::VisitObjCMessageExpr(const ObjCMessageExpr *M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002528 EnqueueChildren(M);
2529 AddTypeLoc(M->getClassReceiverTypeInfo());
2530}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002531void EnqueueVisitor::VisitOffsetOfExpr(const OffsetOfExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002532 // Visit the components of the offsetof expression.
2533 for (unsigned N = E->getNumComponents(), I = N; I > 0; --I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002534 const OffsetOfNode &Node = E->getComponent(I-1);
2535 switch (Node.getKind()) {
2536 case OffsetOfNode::Array:
2537 AddStmt(E->getIndexExpr(Node.getArrayExprIndex()));
2538 break;
2539 case OffsetOfNode::Field:
2540 AddMemberRef(Node.getField(), Node.getSourceRange().getEnd());
2541 break;
2542 case OffsetOfNode::Identifier:
2543 case OffsetOfNode::Base:
2544 continue;
2545 }
2546 }
2547 // Visit the type into which we're computing the offset.
2548 AddTypeLoc(E->getTypeSourceInfo());
2549}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002550void EnqueueVisitor::VisitOverloadExpr(const OverloadExpr *E) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002551 if (E->hasExplicitTemplateArgs())
2552 AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002553 WL.push_back(OverloadExprParts(E, Parent));
2554}
2555void EnqueueVisitor::VisitUnaryExprOrTypeTraitExpr(
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002556 const UnaryExprOrTypeTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002557 EnqueueChildren(E);
2558 if (E->isArgumentType())
2559 AddTypeLoc(E->getArgumentTypeInfo());
2560}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002561void EnqueueVisitor::VisitStmt(const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002562 EnqueueChildren(S);
2563}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002564void EnqueueVisitor::VisitSwitchStmt(const SwitchStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002565 AddStmt(S->getBody());
2566 AddStmt(S->getCond());
2567 AddDecl(S->getConditionVariable());
2568}
2569
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002570void EnqueueVisitor::VisitWhileStmt(const WhileStmt *W) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002571 AddStmt(W->getBody());
2572 AddStmt(W->getCond());
2573 AddDecl(W->getConditionVariable());
2574}
2575
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002576void EnqueueVisitor::VisitTypeTraitExpr(const TypeTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002577 for (unsigned I = E->getNumArgs(); I > 0; --I)
2578 AddTypeLoc(E->getArg(I-1));
2579}
2580
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002581void EnqueueVisitor::VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002582 AddTypeLoc(E->getQueriedTypeSourceInfo());
2583}
2584
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002585void EnqueueVisitor::VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002586 EnqueueChildren(E);
2587}
2588
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002589void EnqueueVisitor::VisitUnresolvedMemberExpr(const UnresolvedMemberExpr *U) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002590 VisitOverloadExpr(U);
2591 if (!U->isImplicitAccess())
2592 AddStmt(U->getBase());
2593}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002594void EnqueueVisitor::VisitVAArgExpr(const VAArgExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002595 AddStmt(E->getSubExpr());
2596 AddTypeLoc(E->getWrittenTypeInfo());
2597}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002598void EnqueueVisitor::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002599 WL.push_back(SizeOfPackExprParts(E, Parent));
2600}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002601void EnqueueVisitor::VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002602 // If the opaque value has a source expression, just transparently
2603 // visit that. This is useful for (e.g.) pseudo-object expressions.
2604 if (Expr *SourceExpr = E->getSourceExpr())
2605 return Visit(SourceExpr);
2606}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002607void EnqueueVisitor::VisitLambdaExpr(const LambdaExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002608 AddStmt(E->getBody());
2609 WL.push_back(LambdaExprParts(E, Parent));
2610}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002611void EnqueueVisitor::VisitPseudoObjectExpr(const PseudoObjectExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002612 // Treat the expression like its syntactic form.
2613 Visit(E->getSyntacticForm());
2614}
2615
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002616void EnqueueVisitor::VisitOMPExecutableDirective(
2617 const OMPExecutableDirective *D) {
2618 EnqueueChildren(D);
2619 for (ArrayRef<OMPClause *>::iterator I = D->clauses().begin(),
2620 E = D->clauses().end();
2621 I != E; ++I)
2622 EnqueueChildren(*I);
2623}
2624
Alexander Musman3aaab662014-08-19 11:27:13 +00002625void EnqueueVisitor::VisitOMPLoopDirective(const OMPLoopDirective *D) {
2626 VisitOMPExecutableDirective(D);
2627}
2628
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002629void EnqueueVisitor::VisitOMPParallelDirective(const OMPParallelDirective *D) {
2630 VisitOMPExecutableDirective(D);
2631}
2632
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002633void EnqueueVisitor::VisitOMPSimdDirective(const OMPSimdDirective *D) {
Alexander Musman3aaab662014-08-19 11:27:13 +00002634 VisitOMPLoopDirective(D);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002635}
2636
Alexey Bataevf29276e2014-06-18 04:14:57 +00002637void EnqueueVisitor::VisitOMPForDirective(const OMPForDirective *D) {
Alexander Musman3aaab662014-08-19 11:27:13 +00002638 VisitOMPLoopDirective(D);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002639}
2640
Alexander Musmanf82886e2014-09-18 05:12:34 +00002641void EnqueueVisitor::VisitOMPForSimdDirective(const OMPForSimdDirective *D) {
2642 VisitOMPLoopDirective(D);
2643}
2644
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002645void EnqueueVisitor::VisitOMPSectionsDirective(const OMPSectionsDirective *D) {
2646 VisitOMPExecutableDirective(D);
2647}
2648
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002649void EnqueueVisitor::VisitOMPSectionDirective(const OMPSectionDirective *D) {
2650 VisitOMPExecutableDirective(D);
2651}
2652
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00002653void EnqueueVisitor::VisitOMPSingleDirective(const OMPSingleDirective *D) {
2654 VisitOMPExecutableDirective(D);
2655}
2656
Alexander Musman80c22892014-07-17 08:54:58 +00002657void EnqueueVisitor::VisitOMPMasterDirective(const OMPMasterDirective *D) {
2658 VisitOMPExecutableDirective(D);
2659}
2660
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002661void EnqueueVisitor::VisitOMPCriticalDirective(const OMPCriticalDirective *D) {
2662 VisitOMPExecutableDirective(D);
2663 AddDeclarationNameInfo(D);
2664}
2665
Alexey Bataev4acb8592014-07-07 13:01:15 +00002666void
2667EnqueueVisitor::VisitOMPParallelForDirective(const OMPParallelForDirective *D) {
Alexander Musman3aaab662014-08-19 11:27:13 +00002668 VisitOMPLoopDirective(D);
Alexey Bataev4acb8592014-07-07 13:01:15 +00002669}
2670
Alexander Musmane4e893b2014-09-23 09:33:00 +00002671void EnqueueVisitor::VisitOMPParallelForSimdDirective(
2672 const OMPParallelForSimdDirective *D) {
2673 VisitOMPLoopDirective(D);
2674}
2675
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002676void EnqueueVisitor::VisitOMPParallelSectionsDirective(
2677 const OMPParallelSectionsDirective *D) {
2678 VisitOMPExecutableDirective(D);
2679}
2680
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002681void EnqueueVisitor::VisitOMPTaskDirective(const OMPTaskDirective *D) {
2682 VisitOMPExecutableDirective(D);
2683}
2684
Alexey Bataev68446b72014-07-18 07:47:19 +00002685void
2686EnqueueVisitor::VisitOMPTaskyieldDirective(const OMPTaskyieldDirective *D) {
2687 VisitOMPExecutableDirective(D);
2688}
2689
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002690void EnqueueVisitor::VisitOMPBarrierDirective(const OMPBarrierDirective *D) {
2691 VisitOMPExecutableDirective(D);
2692}
2693
Alexey Bataev2df347a2014-07-18 10:17:07 +00002694void EnqueueVisitor::VisitOMPTaskwaitDirective(const OMPTaskwaitDirective *D) {
2695 VisitOMPExecutableDirective(D);
2696}
2697
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002698void EnqueueVisitor::VisitOMPTaskgroupDirective(
2699 const OMPTaskgroupDirective *D) {
2700 VisitOMPExecutableDirective(D);
2701}
2702
Alexey Bataev6125da92014-07-21 11:26:11 +00002703void EnqueueVisitor::VisitOMPFlushDirective(const OMPFlushDirective *D) {
2704 VisitOMPExecutableDirective(D);
2705}
2706
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002707void EnqueueVisitor::VisitOMPOrderedDirective(const OMPOrderedDirective *D) {
2708 VisitOMPExecutableDirective(D);
2709}
2710
Alexey Bataev0162e452014-07-22 10:10:35 +00002711void EnqueueVisitor::VisitOMPAtomicDirective(const OMPAtomicDirective *D) {
2712 VisitOMPExecutableDirective(D);
2713}
2714
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002715void EnqueueVisitor::VisitOMPTargetDirective(const OMPTargetDirective *D) {
2716 VisitOMPExecutableDirective(D);
2717}
2718
Michael Wong65f367f2015-07-21 13:44:28 +00002719void EnqueueVisitor::VisitOMPTargetDataDirective(const
2720 OMPTargetDataDirective *D) {
2721 VisitOMPExecutableDirective(D);
2722}
2723
Samuel Antaodf67fc42016-01-19 19:15:56 +00002724void EnqueueVisitor::VisitOMPTargetEnterDataDirective(
2725 const OMPTargetEnterDataDirective *D) {
2726 VisitOMPExecutableDirective(D);
2727}
2728
Samuel Antao72590762016-01-19 20:04:50 +00002729void EnqueueVisitor::VisitOMPTargetExitDataDirective(
2730 const OMPTargetExitDataDirective *D) {
2731 VisitOMPExecutableDirective(D);
2732}
2733
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00002734void EnqueueVisitor::VisitOMPTargetParallelDirective(
2735 const OMPTargetParallelDirective *D) {
2736 VisitOMPExecutableDirective(D);
2737}
2738
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00002739void EnqueueVisitor::VisitOMPTargetParallelForDirective(
2740 const OMPTargetParallelForDirective *D) {
2741 VisitOMPLoopDirective(D);
2742}
2743
Alexey Bataev13314bf2014-10-09 04:18:56 +00002744void EnqueueVisitor::VisitOMPTeamsDirective(const OMPTeamsDirective *D) {
2745 VisitOMPExecutableDirective(D);
2746}
2747
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002748void EnqueueVisitor::VisitOMPCancellationPointDirective(
2749 const OMPCancellationPointDirective *D) {
2750 VisitOMPExecutableDirective(D);
2751}
2752
Alexey Bataev80909872015-07-02 11:25:17 +00002753void EnqueueVisitor::VisitOMPCancelDirective(const OMPCancelDirective *D) {
2754 VisitOMPExecutableDirective(D);
2755}
2756
Alexey Bataev49f6e782015-12-01 04:18:41 +00002757void EnqueueVisitor::VisitOMPTaskLoopDirective(const OMPTaskLoopDirective *D) {
2758 VisitOMPLoopDirective(D);
2759}
2760
Alexey Bataev0a6ed842015-12-03 09:40:15 +00002761void EnqueueVisitor::VisitOMPTaskLoopSimdDirective(
2762 const OMPTaskLoopSimdDirective *D) {
2763 VisitOMPLoopDirective(D);
2764}
2765
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002766void EnqueueVisitor::VisitOMPDistributeDirective(
2767 const OMPDistributeDirective *D) {
2768 VisitOMPLoopDirective(D);
2769}
2770
Carlo Bertolli9925f152016-06-27 14:55:37 +00002771void EnqueueVisitor::VisitOMPDistributeParallelForDirective(
2772 const OMPDistributeParallelForDirective *D) {
2773 VisitOMPLoopDirective(D);
2774}
2775
Kelvin Li4a39add2016-07-05 05:00:15 +00002776void EnqueueVisitor::VisitOMPDistributeParallelForSimdDirective(
2777 const OMPDistributeParallelForSimdDirective *D) {
2778 VisitOMPLoopDirective(D);
2779}
2780
Kelvin Li787f3fc2016-07-06 04:45:38 +00002781void EnqueueVisitor::VisitOMPDistributeSimdDirective(
2782 const OMPDistributeSimdDirective *D) {
2783 VisitOMPLoopDirective(D);
2784}
2785
Kelvin Lia579b912016-07-14 02:54:56 +00002786void EnqueueVisitor::VisitOMPTargetParallelForSimdDirective(
2787 const OMPTargetParallelForSimdDirective *D) {
2788 VisitOMPLoopDirective(D);
2789}
2790
Kelvin Li986330c2016-07-20 22:57:10 +00002791void EnqueueVisitor::VisitOMPTargetSimdDirective(
2792 const OMPTargetSimdDirective *D) {
2793 VisitOMPLoopDirective(D);
2794}
2795
Kelvin Li02532872016-08-05 14:37:37 +00002796void EnqueueVisitor::VisitOMPTeamsDistributeDirective(
2797 const OMPTeamsDistributeDirective *D) {
2798 VisitOMPLoopDirective(D);
2799}
2800
Kelvin Li4e325f72016-10-25 12:50:55 +00002801void EnqueueVisitor::VisitOMPTeamsDistributeSimdDirective(
2802 const OMPTeamsDistributeSimdDirective *D) {
2803 VisitOMPLoopDirective(D);
2804}
2805
Kelvin Li579e41c2016-11-30 23:51:03 +00002806void EnqueueVisitor::VisitOMPTeamsDistributeParallelForSimdDirective(
2807 const OMPTeamsDistributeParallelForSimdDirective *D) {
2808 VisitOMPLoopDirective(D);
2809}
2810
Kelvin Li7ade93f2016-12-09 03:24:30 +00002811void EnqueueVisitor::VisitOMPTeamsDistributeParallelForDirective(
2812 const OMPTeamsDistributeParallelForDirective *D) {
2813 VisitOMPLoopDirective(D);
2814}
2815
Kelvin Libf594a52016-12-17 05:48:59 +00002816void EnqueueVisitor::VisitOMPTargetTeamsDirective(
2817 const OMPTargetTeamsDirective *D) {
2818 VisitOMPExecutableDirective(D);
2819}
2820
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002821void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002822 EnqueueVisitor(WL, MakeCXCursor(S, StmtParent, TU,RegionOfInterest)).Visit(S);
2823}
2824
2825bool CursorVisitor::IsInRegionOfInterest(CXCursor C) {
2826 if (RegionOfInterest.isValid()) {
2827 SourceRange Range = getRawCursorExtent(C);
2828 if (Range.isInvalid() || CompareRegionOfInterest(Range))
2829 return false;
2830 }
2831 return true;
2832}
2833
2834bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) {
2835 while (!WL.empty()) {
2836 // Dequeue the worklist item.
Robert Wilhelm25284cc2013-08-23 16:11:15 +00002837 VisitorJob LI = WL.pop_back_val();
Guy Benyei11169dd2012-12-18 14:30:41 +00002838
2839 // Set the Parent field, then back to its old value once we're done.
2840 SetParentRAII SetParent(Parent, StmtParent, LI.getParent());
2841
2842 switch (LI.getKind()) {
2843 case VisitorJob::DeclVisitKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002844 const Decl *D = cast<DeclVisit>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00002845 if (!D)
2846 continue;
2847
2848 // For now, perform default visitation for Decls.
2849 if (Visit(MakeCXCursor(D, TU, RegionOfInterest,
2850 cast<DeclVisit>(&LI)->isFirst())))
2851 return true;
2852
2853 continue;
2854 }
2855 case VisitorJob::ExplicitTemplateArgsVisitKind: {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002856 for (const TemplateArgumentLoc &Arg :
2857 *cast<ExplicitTemplateArgsVisit>(&LI)) {
2858 if (VisitTemplateArgumentLoc(Arg))
Guy Benyei11169dd2012-12-18 14:30:41 +00002859 return true;
2860 }
2861 continue;
2862 }
2863 case VisitorJob::TypeLocVisitKind: {
2864 // Perform default visitation for TypeLocs.
2865 if (Visit(cast<TypeLocVisit>(&LI)->get()))
2866 return true;
2867 continue;
2868 }
2869 case VisitorJob::LabelRefVisitKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002870 const LabelDecl *LS = cast<LabelRefVisit>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00002871 if (LabelStmt *stmt = LS->getStmt()) {
2872 if (Visit(MakeCursorLabelRef(stmt, cast<LabelRefVisit>(&LI)->getLoc(),
2873 TU))) {
2874 return true;
2875 }
2876 }
2877 continue;
2878 }
2879
2880 case VisitorJob::NestedNameSpecifierLocVisitKind: {
2881 NestedNameSpecifierLocVisit *V = cast<NestedNameSpecifierLocVisit>(&LI);
2882 if (VisitNestedNameSpecifierLoc(V->get()))
2883 return true;
2884 continue;
2885 }
2886
2887 case VisitorJob::DeclarationNameInfoVisitKind: {
2888 if (VisitDeclarationNameInfo(cast<DeclarationNameInfoVisit>(&LI)
2889 ->get()))
2890 return true;
2891 continue;
2892 }
2893 case VisitorJob::MemberRefVisitKind: {
2894 MemberRefVisit *V = cast<MemberRefVisit>(&LI);
2895 if (Visit(MakeCursorMemberRef(V->get(), V->getLoc(), TU)))
2896 return true;
2897 continue;
2898 }
2899 case VisitorJob::StmtVisitKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002900 const Stmt *S = cast<StmtVisit>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00002901 if (!S)
2902 continue;
2903
2904 // Update the current cursor.
2905 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU, RegionOfInterest);
2906 if (!IsInRegionOfInterest(Cursor))
2907 continue;
2908 switch (Visitor(Cursor, Parent, ClientData)) {
2909 case CXChildVisit_Break: return true;
2910 case CXChildVisit_Continue: break;
2911 case CXChildVisit_Recurse:
2912 if (PostChildrenVisitor)
Craig Topper69186e72014-06-08 08:38:04 +00002913 WL.push_back(PostChildrenVisit(nullptr, Cursor));
Guy Benyei11169dd2012-12-18 14:30:41 +00002914 EnqueueWorkList(WL, S);
2915 break;
2916 }
2917 continue;
2918 }
2919 case VisitorJob::MemberExprPartsKind: {
2920 // Handle the other pieces in the MemberExpr besides the base.
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002921 const MemberExpr *M = cast<MemberExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00002922
2923 // Visit the nested-name-specifier
2924 if (NestedNameSpecifierLoc QualifierLoc = M->getQualifierLoc())
2925 if (VisitNestedNameSpecifierLoc(QualifierLoc))
2926 return true;
2927
2928 // Visit the declaration name.
2929 if (VisitDeclarationNameInfo(M->getMemberNameInfo()))
2930 return true;
2931
2932 // Visit the explicitly-specified template arguments, if any.
2933 if (M->hasExplicitTemplateArgs()) {
2934 for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(),
2935 *ArgEnd = Arg + M->getNumTemplateArgs();
2936 Arg != ArgEnd; ++Arg) {
2937 if (VisitTemplateArgumentLoc(*Arg))
2938 return true;
2939 }
2940 }
2941 continue;
2942 }
2943 case VisitorJob::DeclRefExprPartsKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002944 const DeclRefExpr *DR = cast<DeclRefExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00002945 // Visit nested-name-specifier, if present.
2946 if (NestedNameSpecifierLoc QualifierLoc = DR->getQualifierLoc())
2947 if (VisitNestedNameSpecifierLoc(QualifierLoc))
2948 return true;
2949 // Visit declaration name.
2950 if (VisitDeclarationNameInfo(DR->getNameInfo()))
2951 return true;
2952 continue;
2953 }
2954 case VisitorJob::OverloadExprPartsKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002955 const OverloadExpr *O = cast<OverloadExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00002956 // Visit the nested-name-specifier.
2957 if (NestedNameSpecifierLoc QualifierLoc = O->getQualifierLoc())
2958 if (VisitNestedNameSpecifierLoc(QualifierLoc))
2959 return true;
2960 // Visit the declaration name.
2961 if (VisitDeclarationNameInfo(O->getNameInfo()))
2962 return true;
2963 // Visit the overloaded declaration reference.
2964 if (Visit(MakeCursorOverloadedDeclRef(O, TU)))
2965 return true;
2966 continue;
2967 }
2968 case VisitorJob::SizeOfPackExprPartsKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002969 const SizeOfPackExpr *E = cast<SizeOfPackExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00002970 NamedDecl *Pack = E->getPack();
2971 if (isa<TemplateTypeParmDecl>(Pack)) {
2972 if (Visit(MakeCursorTypeRef(cast<TemplateTypeParmDecl>(Pack),
2973 E->getPackLoc(), TU)))
2974 return true;
2975
2976 continue;
2977 }
2978
2979 if (isa<TemplateTemplateParmDecl>(Pack)) {
2980 if (Visit(MakeCursorTemplateRef(cast<TemplateTemplateParmDecl>(Pack),
2981 E->getPackLoc(), TU)))
2982 return true;
2983
2984 continue;
2985 }
2986
2987 // Non-type template parameter packs and function parameter packs are
2988 // treated like DeclRefExpr cursors.
2989 continue;
2990 }
2991
2992 case VisitorJob::LambdaExprPartsKind: {
2993 // Visit captures.
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002994 const LambdaExpr *E = cast<LambdaExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00002995 for (LambdaExpr::capture_iterator C = E->explicit_capture_begin(),
2996 CEnd = E->explicit_capture_end();
2997 C != CEnd; ++C) {
Richard Smithba71c082013-05-16 06:20:58 +00002998 // FIXME: Lambda init-captures.
2999 if (!C->capturesVariable())
Guy Benyei11169dd2012-12-18 14:30:41 +00003000 continue;
Richard Smithba71c082013-05-16 06:20:58 +00003001
Guy Benyei11169dd2012-12-18 14:30:41 +00003002 if (Visit(MakeCursorVariableRef(C->getCapturedVar(),
3003 C->getLocation(),
3004 TU)))
3005 return true;
3006 }
3007
3008 // Visit parameters and return type, if present.
3009 if (E->hasExplicitParameters() || E->hasExplicitResultType()) {
3010 TypeLoc TL = E->getCallOperator()->getTypeSourceInfo()->getTypeLoc();
3011 if (E->hasExplicitParameters() && E->hasExplicitResultType()) {
3012 // Visit the whole type.
3013 if (Visit(TL))
3014 return true;
David Blaikie6adc78e2013-02-18 22:06:02 +00003015 } else if (FunctionProtoTypeLoc Proto =
3016 TL.getAs<FunctionProtoTypeLoc>()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003017 if (E->hasExplicitParameters()) {
3018 // Visit parameters.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00003019 for (unsigned I = 0, N = Proto.getNumParams(); I != N; ++I)
3020 if (Visit(MakeCXCursor(Proto.getParam(I), TU)))
Guy Benyei11169dd2012-12-18 14:30:41 +00003021 return true;
3022 } else {
3023 // Visit result type.
Alp Toker42a16a62014-01-25 23:51:36 +00003024 if (Visit(Proto.getReturnLoc()))
Guy Benyei11169dd2012-12-18 14:30:41 +00003025 return true;
3026 }
3027 }
3028 }
3029 break;
3030 }
3031
3032 case VisitorJob::PostChildrenVisitKind:
3033 if (PostChildrenVisitor(Parent, ClientData))
3034 return true;
3035 break;
3036 }
3037 }
3038 return false;
3039}
3040
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003041bool CursorVisitor::Visit(const Stmt *S) {
Craig Topper69186e72014-06-08 08:38:04 +00003042 VisitorWorkList *WL = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00003043 if (!WorkListFreeList.empty()) {
3044 WL = WorkListFreeList.back();
3045 WL->clear();
3046 WorkListFreeList.pop_back();
3047 }
3048 else {
3049 WL = new VisitorWorkList();
3050 WorkListCache.push_back(WL);
3051 }
3052 EnqueueWorkList(*WL, S);
3053 bool result = RunVisitorWorkList(*WL);
3054 WorkListFreeList.push_back(WL);
3055 return result;
3056}
3057
3058namespace {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003059typedef SmallVector<SourceRange, 4> RefNamePieces;
James Y Knight04ec5bf2015-12-24 02:59:37 +00003060RefNamePieces buildPieces(unsigned NameFlags, bool IsMemberRefExpr,
3061 const DeclarationNameInfo &NI, SourceRange QLoc,
3062 const SourceRange *TemplateArgsLoc = nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003063 const bool WantQualifier = NameFlags & CXNameRange_WantQualifier;
3064 const bool WantTemplateArgs = NameFlags & CXNameRange_WantTemplateArgs;
3065 const bool WantSinglePiece = NameFlags & CXNameRange_WantSinglePiece;
3066
3067 const DeclarationName::NameKind Kind = NI.getName().getNameKind();
3068
3069 RefNamePieces Pieces;
3070
3071 if (WantQualifier && QLoc.isValid())
3072 Pieces.push_back(QLoc);
3073
3074 if (Kind != DeclarationName::CXXOperatorName || IsMemberRefExpr)
3075 Pieces.push_back(NI.getLoc());
James Y Knight04ec5bf2015-12-24 02:59:37 +00003076
3077 if (WantTemplateArgs && TemplateArgsLoc && TemplateArgsLoc->isValid())
3078 Pieces.push_back(*TemplateArgsLoc);
3079
Guy Benyei11169dd2012-12-18 14:30:41 +00003080 if (Kind == DeclarationName::CXXOperatorName) {
3081 Pieces.push_back(SourceLocation::getFromRawEncoding(
3082 NI.getInfo().CXXOperatorName.BeginOpNameLoc));
3083 Pieces.push_back(SourceLocation::getFromRawEncoding(
3084 NI.getInfo().CXXOperatorName.EndOpNameLoc));
3085 }
3086
3087 if (WantSinglePiece) {
3088 SourceRange R(Pieces.front().getBegin(), Pieces.back().getEnd());
3089 Pieces.clear();
3090 Pieces.push_back(R);
3091 }
3092
3093 return Pieces;
3094}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003095}
Guy Benyei11169dd2012-12-18 14:30:41 +00003096
3097//===----------------------------------------------------------------------===//
3098// Misc. API hooks.
3099//===----------------------------------------------------------------------===//
3100
Chad Rosier05c71aa2013-03-27 18:28:23 +00003101static void fatal_error_handler(void *user_data, const std::string& reason,
3102 bool gen_crash_diag) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003103 // Write the result out to stderr avoiding errs() because raw_ostreams can
3104 // call report_fatal_error.
3105 fprintf(stderr, "LIBCLANG FATAL ERROR: %s\n", reason.c_str());
3106 ::abort();
3107}
3108
Chandler Carruth66660742014-06-27 16:37:27 +00003109namespace {
3110struct RegisterFatalErrorHandler {
3111 RegisterFatalErrorHandler() {
3112 llvm::install_fatal_error_handler(fatal_error_handler, nullptr);
3113 }
3114};
3115}
3116
3117static llvm::ManagedStatic<RegisterFatalErrorHandler> RegisterFatalErrorHandlerOnce;
3118
Guy Benyei11169dd2012-12-18 14:30:41 +00003119CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
3120 int displayDiagnostics) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003121 // We use crash recovery to make some of our APIs more reliable, implicitly
3122 // enable it.
Argyrios Kyrtzidis3701f542013-11-27 08:58:09 +00003123 if (!getenv("LIBCLANG_DISABLE_CRASH_RECOVERY"))
3124 llvm::CrashRecoveryContext::Enable();
Guy Benyei11169dd2012-12-18 14:30:41 +00003125
Chandler Carruth66660742014-06-27 16:37:27 +00003126 // Look through the managed static to trigger construction of the managed
3127 // static which registers our fatal error handler. This ensures it is only
3128 // registered once.
3129 (void)*RegisterFatalErrorHandlerOnce;
Guy Benyei11169dd2012-12-18 14:30:41 +00003130
Adrian Prantlbc068582015-07-08 01:00:30 +00003131 // Initialize targets for clang module support.
3132 llvm::InitializeAllTargets();
3133 llvm::InitializeAllTargetMCs();
3134 llvm::InitializeAllAsmPrinters();
3135 llvm::InitializeAllAsmParsers();
3136
Adrian Prantlfb2398d2015-07-17 01:19:54 +00003137 CIndexer *CIdxr = new CIndexer();
3138
Guy Benyei11169dd2012-12-18 14:30:41 +00003139 if (excludeDeclarationsFromPCH)
3140 CIdxr->setOnlyLocalDecls();
3141 if (displayDiagnostics)
3142 CIdxr->setDisplayDiagnostics();
3143
3144 if (getenv("LIBCLANG_BGPRIO_INDEX"))
3145 CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() |
3146 CXGlobalOpt_ThreadBackgroundPriorityForIndexing);
3147 if (getenv("LIBCLANG_BGPRIO_EDIT"))
3148 CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() |
3149 CXGlobalOpt_ThreadBackgroundPriorityForEditing);
3150
3151 return CIdxr;
3152}
3153
3154void clang_disposeIndex(CXIndex CIdx) {
3155 if (CIdx)
3156 delete static_cast<CIndexer *>(CIdx);
3157}
3158
3159void clang_CXIndex_setGlobalOptions(CXIndex CIdx, unsigned options) {
3160 if (CIdx)
3161 static_cast<CIndexer *>(CIdx)->setCXGlobalOptFlags(options);
3162}
3163
3164unsigned clang_CXIndex_getGlobalOptions(CXIndex CIdx) {
3165 if (CIdx)
3166 return static_cast<CIndexer *>(CIdx)->getCXGlobalOptFlags();
3167 return 0;
3168}
3169
3170void clang_toggleCrashRecovery(unsigned isEnabled) {
3171 if (isEnabled)
3172 llvm::CrashRecoveryContext::Enable();
3173 else
3174 llvm::CrashRecoveryContext::Disable();
3175}
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003176
Guy Benyei11169dd2012-12-18 14:30:41 +00003177CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
3178 const char *ast_filename) {
Dmitri Gribenko8850cda2014-02-19 10:24:00 +00003179 CXTranslationUnit TU;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003180 enum CXErrorCode Result =
3181 clang_createTranslationUnit2(CIdx, ast_filename, &TU);
Reid Klecknerfd48fc62014-02-12 23:56:20 +00003182 (void)Result;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003183 assert((TU && Result == CXError_Success) ||
3184 (!TU && Result != CXError_Success));
3185 return TU;
3186}
3187
3188enum CXErrorCode clang_createTranslationUnit2(CXIndex CIdx,
3189 const char *ast_filename,
3190 CXTranslationUnit *out_TU) {
Dmitri Gribenko8850cda2014-02-19 10:24:00 +00003191 if (out_TU)
Craig Topper69186e72014-06-08 08:38:04 +00003192 *out_TU = nullptr;
Dmitri Gribenko8850cda2014-02-19 10:24:00 +00003193
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003194 if (!CIdx || !ast_filename || !out_TU)
3195 return CXError_InvalidArguments;
Guy Benyei11169dd2012-12-18 14:30:41 +00003196
Argyrios Kyrtzidis27021012013-05-24 22:24:07 +00003197 LOG_FUNC_SECTION {
3198 *Log << ast_filename;
3199 }
3200
Guy Benyei11169dd2012-12-18 14:30:41 +00003201 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
3202 FileSystemOptions FileSystemOpts;
3203
Justin Bognerd512c1e2014-10-15 00:33:06 +00003204 IntrusiveRefCntPtr<DiagnosticsEngine> Diags =
3205 CompilerInstance::createDiagnostics(new DiagnosticOptions());
David Blaikie6f7382d2014-08-10 19:08:04 +00003206 std::unique_ptr<ASTUnit> AU = ASTUnit::LoadFromASTFile(
Adrian Prantlfb2398d2015-07-17 01:19:54 +00003207 ast_filename, CXXIdx->getPCHContainerOperations()->getRawReader(), Diags,
Adrian Prantl6b21ab22015-08-27 19:46:20 +00003208 FileSystemOpts, /*UseDebugInfo=*/false,
3209 CXXIdx->getOnlyLocalDecls(), None,
David Blaikie6f7382d2014-08-10 19:08:04 +00003210 /*CaptureDiagnostics=*/true,
3211 /*AllowPCHWithCompilerErrors=*/true,
3212 /*UserFilesAreVolatile=*/true);
3213 *out_TU = MakeCXTranslationUnit(CXXIdx, AU.release());
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003214 return *out_TU ? CXError_Success : CXError_Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003215}
3216
3217unsigned clang_defaultEditingTranslationUnitOptions() {
3218 return CXTranslationUnit_PrecompiledPreamble |
3219 CXTranslationUnit_CacheCompletionResults;
3220}
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003221
Guy Benyei11169dd2012-12-18 14:30:41 +00003222CXTranslationUnit
3223clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
3224 const char *source_filename,
3225 int num_command_line_args,
3226 const char * const *command_line_args,
3227 unsigned num_unsaved_files,
3228 struct CXUnsavedFile *unsaved_files) {
3229 unsigned Options = CXTranslationUnit_DetailedPreprocessingRecord;
3230 return clang_parseTranslationUnit(CIdx, source_filename,
3231 command_line_args, num_command_line_args,
3232 unsaved_files, num_unsaved_files,
3233 Options);
3234}
3235
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003236static CXErrorCode
3237clang_parseTranslationUnit_Impl(CXIndex CIdx, const char *source_filename,
3238 const char *const *command_line_args,
3239 int num_command_line_args,
3240 ArrayRef<CXUnsavedFile> unsaved_files,
3241 unsigned options, CXTranslationUnit *out_TU) {
Dmitri Gribenko1bf8d912014-02-18 15:20:02 +00003242 // Set up the initial return values.
3243 if (out_TU)
Craig Topper69186e72014-06-08 08:38:04 +00003244 *out_TU = nullptr;
Dmitri Gribenko1bf8d912014-02-18 15:20:02 +00003245
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003246 // Check arguments.
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003247 if (!CIdx || !out_TU)
3248 return CXError_InvalidArguments;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003249
Guy Benyei11169dd2012-12-18 14:30:41 +00003250 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
3251
3252 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
3253 setThreadBackgroundPriority();
3254
3255 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Benjamin Kramer5c248d82015-12-15 09:30:31 +00003256 bool CreatePreambleOnFirstParse =
3257 options & CXTranslationUnit_CreatePreambleOnFirstParse;
Guy Benyei11169dd2012-12-18 14:30:41 +00003258 // FIXME: Add a flag for modules.
3259 TranslationUnitKind TUKind
3260 = (options & CXTranslationUnit_Incomplete)? TU_Prefix : TU_Complete;
Alp Toker8c8a8752013-12-03 06:53:35 +00003261 bool CacheCodeCompletionResults
Guy Benyei11169dd2012-12-18 14:30:41 +00003262 = options & CXTranslationUnit_CacheCompletionResults;
3263 bool IncludeBriefCommentsInCodeCompletion
3264 = options & CXTranslationUnit_IncludeBriefCommentsInCodeCompletion;
3265 bool SkipFunctionBodies = options & CXTranslationUnit_SkipFunctionBodies;
3266 bool ForSerialization = options & CXTranslationUnit_ForSerialization;
3267
3268 // Configure the diagnostics.
3269 IntrusiveRefCntPtr<DiagnosticsEngine>
Sean Silvaf1b49e22013-01-20 01:58:28 +00003270 Diags(CompilerInstance::createDiagnostics(new DiagnosticOptions));
Guy Benyei11169dd2012-12-18 14:30:41 +00003271
Manuel Klimek016c0242016-03-01 10:56:19 +00003272 if (options & CXTranslationUnit_KeepGoing)
3273 Diags->setFatalsAsError(true);
3274
Guy Benyei11169dd2012-12-18 14:30:41 +00003275 // Recover resources if we crash before exiting this function.
3276 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
3277 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Alp Tokerf994cef2014-07-05 03:08:06 +00003278 DiagCleanup(Diags.get());
Guy Benyei11169dd2012-12-18 14:30:41 +00003279
Ahmed Charlesb8984322014-03-07 20:03:18 +00003280 std::unique_ptr<std::vector<ASTUnit::RemappedFile>> RemappedFiles(
3281 new std::vector<ASTUnit::RemappedFile>());
Guy Benyei11169dd2012-12-18 14:30:41 +00003282
3283 // Recover resources if we crash before exiting this function.
3284 llvm::CrashRecoveryContextCleanupRegistrar<
3285 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
3286
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003287 for (auto &UF : unsaved_files) {
Rafael Espindolad87f8d72014-08-27 20:03:29 +00003288 std::unique_ptr<llvm::MemoryBuffer> MB =
Alp Toker9d85b182014-07-07 01:23:14 +00003289 llvm::MemoryBuffer::getMemBufferCopy(getContents(UF), UF.Filename);
Rafael Espindolad87f8d72014-08-27 20:03:29 +00003290 RemappedFiles->push_back(std::make_pair(UF.Filename, MB.release()));
Guy Benyei11169dd2012-12-18 14:30:41 +00003291 }
3292
Ahmed Charlesb8984322014-03-07 20:03:18 +00003293 std::unique_ptr<std::vector<const char *>> Args(
3294 new std::vector<const char *>());
Guy Benyei11169dd2012-12-18 14:30:41 +00003295
3296 // Recover resources if we crash before exiting this method.
3297 llvm::CrashRecoveryContextCleanupRegistrar<std::vector<const char*> >
3298 ArgsCleanup(Args.get());
3299
3300 // Since the Clang C library is primarily used by batch tools dealing with
3301 // (often very broken) source code, where spell-checking can have a
3302 // significant negative impact on performance (particularly when
3303 // precompiled headers are involved), we disable it by default.
3304 // Only do this if we haven't found a spell-checking-related argument.
3305 bool FoundSpellCheckingArgument = false;
3306 for (int I = 0; I != num_command_line_args; ++I) {
3307 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
3308 strcmp(command_line_args[I], "-fspell-checking") == 0) {
3309 FoundSpellCheckingArgument = true;
3310 break;
3311 }
3312 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003313 Args->insert(Args->end(), command_line_args,
3314 command_line_args + num_command_line_args);
3315
Benjamin Kramerc02670e2015-11-18 16:14:27 +00003316 if (!FoundSpellCheckingArgument)
3317 Args->insert(Args->begin() + 1, "-fno-spell-checking");
3318
Guy Benyei11169dd2012-12-18 14:30:41 +00003319 // The 'source_filename' argument is optional. If the caller does not
3320 // specify it then it is assumed that the source file is specified
3321 // in the actual argument list.
3322 // Put the source file after command_line_args otherwise if '-x' flag is
3323 // present it will be unused.
3324 if (source_filename)
3325 Args->push_back(source_filename);
3326
3327 // Do we need the detailed preprocessing record?
3328 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
3329 Args->push_back("-Xclang");
3330 Args->push_back("-detailed-preprocessing-record");
3331 }
3332
3333 unsigned NumErrors = Diags->getClient()->getNumErrors();
Ahmed Charlesb8984322014-03-07 20:03:18 +00003334 std::unique_ptr<ASTUnit> ErrUnit;
Benjamin Kramer5c248d82015-12-15 09:30:31 +00003335 // Unless the user specified that they want the preamble on the first parse
3336 // set it up to be created on the first reparse. This makes the first parse
3337 // faster, trading for a slower (first) reparse.
3338 unsigned PrecompilePreambleAfterNParses =
3339 !PrecompilePreamble ? 0 : 2 - CreatePreambleOnFirstParse;
Ahmed Charlesb8984322014-03-07 20:03:18 +00003340 std::unique_ptr<ASTUnit> Unit(ASTUnit::LoadFromCommandLine(
Adrian Prantlbb165fb2015-06-20 18:53:08 +00003341 Args->data(), Args->data() + Args->size(),
3342 CXXIdx->getPCHContainerOperations(), Diags,
Ahmed Charlesb8984322014-03-07 20:03:18 +00003343 CXXIdx->getClangResourcesPath(), CXXIdx->getOnlyLocalDecls(),
3344 /*CaptureDiagnostics=*/true, *RemappedFiles.get(),
Benjamin Kramer5c248d82015-12-15 09:30:31 +00003345 /*RemappedFilesKeepOriginalName=*/true, PrecompilePreambleAfterNParses,
3346 TUKind, CacheCodeCompletionResults, IncludeBriefCommentsInCodeCompletion,
Ahmed Charlesb8984322014-03-07 20:03:18 +00003347 /*AllowPCHWithCompilerErrors=*/true, SkipFunctionBodies,
Argyrios Kyrtzidisa3e2ff12015-11-20 03:36:21 +00003348 /*UserFilesAreVolatile=*/true, ForSerialization,
3349 CXXIdx->getPCHContainerOperations()->getRawReader().getFormat(),
3350 &ErrUnit));
Guy Benyei11169dd2012-12-18 14:30:41 +00003351
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003352 // Early failures in LoadFromCommandLine may return with ErrUnit unset.
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003353 if (!Unit && !ErrUnit)
3354 return CXError_ASTReadError;
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003355
Guy Benyei11169dd2012-12-18 14:30:41 +00003356 if (NumErrors != Diags->getClient()->getNumErrors()) {
3357 // Make sure to check that 'Unit' is non-NULL.
3358 if (CXXIdx->getDisplayDiagnostics())
3359 printDiagsToStderr(Unit ? Unit.get() : ErrUnit.get());
3360 }
3361
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003362 if (isASTReadError(Unit ? Unit.get() : ErrUnit.get()))
3363 return CXError_ASTReadError;
3364
3365 *out_TU = MakeCXTranslationUnit(CXXIdx, Unit.release());
3366 return *out_TU ? CXError_Success : CXError_Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003367}
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003368
3369CXTranslationUnit
3370clang_parseTranslationUnit(CXIndex CIdx,
3371 const char *source_filename,
3372 const char *const *command_line_args,
3373 int num_command_line_args,
3374 struct CXUnsavedFile *unsaved_files,
3375 unsigned num_unsaved_files,
3376 unsigned options) {
3377 CXTranslationUnit TU;
3378 enum CXErrorCode Result = clang_parseTranslationUnit2(
3379 CIdx, source_filename, command_line_args, num_command_line_args,
3380 unsaved_files, num_unsaved_files, options, &TU);
Reid Kleckner6eaf05a2014-02-13 01:19:59 +00003381 (void)Result;
Dmitri Gribenko1bf8d912014-02-18 15:20:02 +00003382 assert((TU && Result == CXError_Success) ||
3383 (!TU && Result != CXError_Success));
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003384 return TU;
3385}
3386
3387enum CXErrorCode clang_parseTranslationUnit2(
Benjamin Kramerc02670e2015-11-18 16:14:27 +00003388 CXIndex CIdx, const char *source_filename,
3389 const char *const *command_line_args, int num_command_line_args,
3390 struct CXUnsavedFile *unsaved_files, unsigned num_unsaved_files,
3391 unsigned options, CXTranslationUnit *out_TU) {
3392 SmallVector<const char *, 4> Args;
3393 Args.push_back("clang");
3394 Args.append(command_line_args, command_line_args + num_command_line_args);
3395 return clang_parseTranslationUnit2FullArgv(
3396 CIdx, source_filename, Args.data(), Args.size(), unsaved_files,
3397 num_unsaved_files, options, out_TU);
3398}
3399
3400enum CXErrorCode clang_parseTranslationUnit2FullArgv(
3401 CXIndex CIdx, const char *source_filename,
3402 const char *const *command_line_args, int num_command_line_args,
3403 struct CXUnsavedFile *unsaved_files, unsigned num_unsaved_files,
3404 unsigned options, CXTranslationUnit *out_TU) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00003405 LOG_FUNC_SECTION {
3406 *Log << source_filename << ": ";
3407 for (int i = 0; i != num_command_line_args; ++i)
3408 *Log << command_line_args[i] << " ";
3409 }
3410
Alp Toker9d85b182014-07-07 01:23:14 +00003411 if (num_unsaved_files && !unsaved_files)
3412 return CXError_InvalidArguments;
3413
Alp Toker5c532982014-07-07 22:42:03 +00003414 CXErrorCode result = CXError_Failure;
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003415 auto ParseTranslationUnitImpl = [=, &result] {
3416 result = clang_parseTranslationUnit_Impl(
3417 CIdx, source_filename, command_line_args, num_command_line_args,
3418 llvm::makeArrayRef(unsaved_files, num_unsaved_files), options, out_TU);
3419 };
Guy Benyei11169dd2012-12-18 14:30:41 +00003420 llvm::CrashRecoveryContext CRC;
3421
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003422 if (!RunSafely(CRC, ParseTranslationUnitImpl)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003423 fprintf(stderr, "libclang: crash detected during parsing: {\n");
3424 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
3425 fprintf(stderr, " 'command_line_args' : [");
3426 for (int i = 0; i != num_command_line_args; ++i) {
3427 if (i)
3428 fprintf(stderr, ", ");
3429 fprintf(stderr, "'%s'", command_line_args[i]);
3430 }
3431 fprintf(stderr, "],\n");
3432 fprintf(stderr, " 'unsaved_files' : [");
3433 for (unsigned i = 0; i != num_unsaved_files; ++i) {
3434 if (i)
3435 fprintf(stderr, ", ");
3436 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
3437 unsaved_files[i].Length);
3438 }
3439 fprintf(stderr, "],\n");
3440 fprintf(stderr, " 'options' : %d,\n", options);
3441 fprintf(stderr, "}\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003442
3443 return CXError_Crashed;
Guy Benyei11169dd2012-12-18 14:30:41 +00003444 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003445 if (CXTranslationUnit *TU = out_TU)
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003446 PrintLibclangResourceUsage(*TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00003447 }
Alp Toker5c532982014-07-07 22:42:03 +00003448
3449 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003450}
3451
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003452CXString clang_Type_getObjCEncoding(CXType CT) {
3453 CXTranslationUnit tu = static_cast<CXTranslationUnit>(CT.data[1]);
3454 ASTContext &Ctx = getASTUnit(tu)->getASTContext();
3455 std::string encoding;
3456 Ctx.getObjCEncodingForType(QualType::getFromOpaquePtr(CT.data[0]),
3457 encoding);
3458
3459 return cxstring::createDup(encoding);
3460}
3461
3462static const IdentifierInfo *getMacroIdentifier(CXCursor C) {
3463 if (C.kind == CXCursor_MacroDefinition) {
3464 if (const MacroDefinitionRecord *MDR = getCursorMacroDefinition(C))
3465 return MDR->getName();
3466 } else if (C.kind == CXCursor_MacroExpansion) {
3467 MacroExpansionCursor ME = getCursorMacroExpansion(C);
3468 return ME.getName();
3469 }
3470 return nullptr;
3471}
3472
3473unsigned clang_Cursor_isMacroFunctionLike(CXCursor C) {
3474 const IdentifierInfo *II = getMacroIdentifier(C);
3475 if (!II) {
3476 return false;
3477 }
3478 ASTUnit *ASTU = getCursorASTUnit(C);
3479 Preprocessor &PP = ASTU->getPreprocessor();
3480 if (const MacroInfo *MI = PP.getMacroInfo(II))
3481 return MI->isFunctionLike();
3482 return false;
3483}
3484
3485unsigned clang_Cursor_isMacroBuiltin(CXCursor C) {
3486 const IdentifierInfo *II = getMacroIdentifier(C);
3487 if (!II) {
3488 return false;
3489 }
3490 ASTUnit *ASTU = getCursorASTUnit(C);
3491 Preprocessor &PP = ASTU->getPreprocessor();
3492 if (const MacroInfo *MI = PP.getMacroInfo(II))
3493 return MI->isBuiltinMacro();
3494 return false;
3495}
3496
3497unsigned clang_Cursor_isFunctionInlined(CXCursor C) {
3498 const Decl *D = getCursorDecl(C);
3499 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
3500 if (!FD) {
3501 return false;
3502 }
3503 return FD->isInlined();
3504}
3505
3506static StringLiteral* getCFSTR_value(CallExpr *callExpr) {
3507 if (callExpr->getNumArgs() != 1) {
3508 return nullptr;
3509 }
3510
3511 StringLiteral *S = nullptr;
3512 auto *arg = callExpr->getArg(0);
3513 if (arg->getStmtClass() == Stmt::ImplicitCastExprClass) {
3514 ImplicitCastExpr *I = static_cast<ImplicitCastExpr *>(arg);
3515 auto *subExpr = I->getSubExprAsWritten();
3516
3517 if(subExpr->getStmtClass() != Stmt::StringLiteralClass){
3518 return nullptr;
3519 }
3520
3521 S = static_cast<StringLiteral *>(I->getSubExprAsWritten());
3522 } else if (arg->getStmtClass() == Stmt::StringLiteralClass) {
3523 S = static_cast<StringLiteral *>(callExpr->getArg(0));
3524 } else {
3525 return nullptr;
3526 }
3527 return S;
3528}
3529
David Blaikie59272572016-04-13 18:23:33 +00003530struct ExprEvalResult {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003531 CXEvalResultKind EvalType;
3532 union {
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003533 unsigned long long unsignedVal;
3534 long long intVal;
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003535 double floatVal;
3536 char *stringVal;
3537 } EvalData;
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003538 bool IsUnsignedInt;
David Blaikie59272572016-04-13 18:23:33 +00003539 ~ExprEvalResult() {
3540 if (EvalType != CXEval_UnExposed && EvalType != CXEval_Float &&
3541 EvalType != CXEval_Int) {
3542 delete EvalData.stringVal;
3543 }
3544 }
3545};
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003546
3547void clang_EvalResult_dispose(CXEvalResult E) {
David Blaikie59272572016-04-13 18:23:33 +00003548 delete static_cast<ExprEvalResult *>(E);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003549}
3550
3551CXEvalResultKind clang_EvalResult_getKind(CXEvalResult E) {
3552 if (!E) {
3553 return CXEval_UnExposed;
3554 }
3555 return ((ExprEvalResult *)E)->EvalType;
3556}
3557
3558int clang_EvalResult_getAsInt(CXEvalResult E) {
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003559 return clang_EvalResult_getAsLongLong(E);
3560}
3561
3562long long clang_EvalResult_getAsLongLong(CXEvalResult E) {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003563 if (!E) {
3564 return 0;
3565 }
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003566 ExprEvalResult *Result = (ExprEvalResult*)E;
3567 if (Result->IsUnsignedInt)
3568 return Result->EvalData.unsignedVal;
3569 return Result->EvalData.intVal;
3570}
3571
3572unsigned clang_EvalResult_isUnsignedInt(CXEvalResult E) {
3573 return ((ExprEvalResult *)E)->IsUnsignedInt;
3574}
3575
3576unsigned long long clang_EvalResult_getAsUnsigned(CXEvalResult E) {
3577 if (!E) {
3578 return 0;
3579 }
3580
3581 ExprEvalResult *Result = (ExprEvalResult*)E;
3582 if (Result->IsUnsignedInt)
3583 return Result->EvalData.unsignedVal;
3584 return Result->EvalData.intVal;
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003585}
3586
3587double clang_EvalResult_getAsDouble(CXEvalResult E) {
3588 if (!E) {
3589 return 0;
3590 }
3591 return ((ExprEvalResult *)E)->EvalData.floatVal;
3592}
3593
3594const char* clang_EvalResult_getAsStr(CXEvalResult E) {
3595 if (!E) {
3596 return nullptr;
3597 }
3598 return ((ExprEvalResult *)E)->EvalData.stringVal;
3599}
3600
3601static const ExprEvalResult* evaluateExpr(Expr *expr, CXCursor C) {
3602 Expr::EvalResult ER;
3603 ASTContext &ctx = getCursorContext(C);
David Blaikiebbc00882016-04-13 18:36:19 +00003604 if (!expr)
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003605 return nullptr;
David Blaikiebbc00882016-04-13 18:36:19 +00003606
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003607 expr = expr->IgnoreParens();
David Blaikiebbc00882016-04-13 18:36:19 +00003608 if (!expr->EvaluateAsRValue(ER, ctx))
3609 return nullptr;
3610
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003611 QualType rettype;
3612 CallExpr *callExpr;
David Blaikie59272572016-04-13 18:23:33 +00003613 auto result = llvm::make_unique<ExprEvalResult>();
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003614 result->EvalType = CXEval_UnExposed;
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003615 result->IsUnsignedInt = false;
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003616
David Blaikiebbc00882016-04-13 18:36:19 +00003617 if (ER.Val.isInt()) {
3618 result->EvalType = CXEval_Int;
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003619
3620 auto& val = ER.Val.getInt();
3621 if (val.isUnsigned()) {
3622 result->IsUnsignedInt = true;
3623 result->EvalData.unsignedVal = val.getZExtValue();
3624 } else {
3625 result->EvalData.intVal = val.getExtValue();
3626 }
3627
David Blaikiebbc00882016-04-13 18:36:19 +00003628 return result.release();
3629 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003630
David Blaikiebbc00882016-04-13 18:36:19 +00003631 if (ER.Val.isFloat()) {
3632 llvm::SmallVector<char, 100> Buffer;
3633 ER.Val.getFloat().toString(Buffer);
3634 std::string floatStr(Buffer.data(), Buffer.size());
3635 result->EvalType = CXEval_Float;
3636 bool ignored;
3637 llvm::APFloat apFloat = ER.Val.getFloat();
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003638 apFloat.convert(llvm::APFloat::IEEEdouble(),
David Blaikiebbc00882016-04-13 18:36:19 +00003639 llvm::APFloat::rmNearestTiesToEven, &ignored);
3640 result->EvalData.floatVal = apFloat.convertToDouble();
3641 return result.release();
3642 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003643
David Blaikiebbc00882016-04-13 18:36:19 +00003644 if (expr->getStmtClass() == Stmt::ImplicitCastExprClass) {
3645 const ImplicitCastExpr *I = dyn_cast<ImplicitCastExpr>(expr);
3646 auto *subExpr = I->getSubExprAsWritten();
3647 if (subExpr->getStmtClass() == Stmt::StringLiteralClass ||
3648 subExpr->getStmtClass() == Stmt::ObjCStringLiteralClass) {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003649 const StringLiteral *StrE = nullptr;
3650 const ObjCStringLiteral *ObjCExpr;
David Blaikiebbc00882016-04-13 18:36:19 +00003651 ObjCExpr = dyn_cast<ObjCStringLiteral>(subExpr);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003652
3653 if (ObjCExpr) {
3654 StrE = ObjCExpr->getString();
3655 result->EvalType = CXEval_ObjCStrLiteral;
3656 } else {
David Blaikiebbc00882016-04-13 18:36:19 +00003657 StrE = cast<StringLiteral>(I->getSubExprAsWritten());
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003658 result->EvalType = CXEval_StrLiteral;
3659 }
3660
3661 std::string strRef(StrE->getString().str());
David Blaikie59272572016-04-13 18:23:33 +00003662 result->EvalData.stringVal = new char[strRef.size() + 1];
David Blaikiebbc00882016-04-13 18:36:19 +00003663 strncpy((char *)result->EvalData.stringVal, strRef.c_str(),
3664 strRef.size());
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003665 result->EvalData.stringVal[strRef.size()] = '\0';
David Blaikie59272572016-04-13 18:23:33 +00003666 return result.release();
David Blaikiebbc00882016-04-13 18:36:19 +00003667 }
3668 } else if (expr->getStmtClass() == Stmt::ObjCStringLiteralClass ||
3669 expr->getStmtClass() == Stmt::StringLiteralClass) {
3670 const StringLiteral *StrE = nullptr;
3671 const ObjCStringLiteral *ObjCExpr;
3672 ObjCExpr = dyn_cast<ObjCStringLiteral>(expr);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003673
David Blaikiebbc00882016-04-13 18:36:19 +00003674 if (ObjCExpr) {
3675 StrE = ObjCExpr->getString();
3676 result->EvalType = CXEval_ObjCStrLiteral;
3677 } else {
3678 StrE = cast<StringLiteral>(expr);
3679 result->EvalType = CXEval_StrLiteral;
3680 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003681
David Blaikiebbc00882016-04-13 18:36:19 +00003682 std::string strRef(StrE->getString().str());
3683 result->EvalData.stringVal = new char[strRef.size() + 1];
3684 strncpy((char *)result->EvalData.stringVal, strRef.c_str(), strRef.size());
3685 result->EvalData.stringVal[strRef.size()] = '\0';
3686 return result.release();
3687 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003688
David Blaikiebbc00882016-04-13 18:36:19 +00003689 if (expr->getStmtClass() == Stmt::CStyleCastExprClass) {
3690 CStyleCastExpr *CC = static_cast<CStyleCastExpr *>(expr);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003691
David Blaikiebbc00882016-04-13 18:36:19 +00003692 rettype = CC->getType();
3693 if (rettype.getAsString() == "CFStringRef" &&
3694 CC->getSubExpr()->getStmtClass() == Stmt::CallExprClass) {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003695
David Blaikiebbc00882016-04-13 18:36:19 +00003696 callExpr = static_cast<CallExpr *>(CC->getSubExpr());
3697 StringLiteral *S = getCFSTR_value(callExpr);
3698 if (S) {
3699 std::string strLiteral(S->getString().str());
3700 result->EvalType = CXEval_CFStr;
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003701
David Blaikiebbc00882016-04-13 18:36:19 +00003702 result->EvalData.stringVal = new char[strLiteral.size() + 1];
3703 strncpy((char *)result->EvalData.stringVal, strLiteral.c_str(),
3704 strLiteral.size());
3705 result->EvalData.stringVal[strLiteral.size()] = '\0';
David Blaikie59272572016-04-13 18:23:33 +00003706 return result.release();
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003707 }
3708 }
3709
David Blaikiebbc00882016-04-13 18:36:19 +00003710 } else if (expr->getStmtClass() == Stmt::CallExprClass) {
3711 callExpr = static_cast<CallExpr *>(expr);
3712 rettype = callExpr->getCallReturnType(ctx);
3713
3714 if (rettype->isVectorType() || callExpr->getNumArgs() > 1)
3715 return nullptr;
3716
3717 if (rettype->isIntegralType(ctx) || rettype->isRealFloatingType()) {
3718 if (callExpr->getNumArgs() == 1 &&
3719 !callExpr->getArg(0)->getType()->isIntegralType(ctx))
3720 return nullptr;
3721 } else if (rettype.getAsString() == "CFStringRef") {
3722
3723 StringLiteral *S = getCFSTR_value(callExpr);
3724 if (S) {
3725 std::string strLiteral(S->getString().str());
3726 result->EvalType = CXEval_CFStr;
3727 result->EvalData.stringVal = new char[strLiteral.size() + 1];
3728 strncpy((char *)result->EvalData.stringVal, strLiteral.c_str(),
3729 strLiteral.size());
3730 result->EvalData.stringVal[strLiteral.size()] = '\0';
3731 return result.release();
3732 }
3733 }
3734 } else if (expr->getStmtClass() == Stmt::DeclRefExprClass) {
3735 DeclRefExpr *D = static_cast<DeclRefExpr *>(expr);
3736 ValueDecl *V = D->getDecl();
3737 if (V->getKind() == Decl::Function) {
3738 std::string strName = V->getNameAsString();
3739 result->EvalType = CXEval_Other;
3740 result->EvalData.stringVal = new char[strName.size() + 1];
3741 strncpy(result->EvalData.stringVal, strName.c_str(), strName.size());
3742 result->EvalData.stringVal[strName.size()] = '\0';
3743 return result.release();
3744 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003745 }
3746
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003747 return nullptr;
3748}
3749
3750CXEvalResult clang_Cursor_Evaluate(CXCursor C) {
3751 const Decl *D = getCursorDecl(C);
3752 if (D) {
3753 const Expr *expr = nullptr;
3754 if (auto *Var = dyn_cast<VarDecl>(D)) {
3755 expr = Var->getInit();
3756 } else if (auto *Field = dyn_cast<FieldDecl>(D)) {
3757 expr = Field->getInClassInitializer();
3758 }
3759 if (expr)
Aaron Ballman01dc1572016-01-20 15:25:30 +00003760 return const_cast<CXEvalResult>(reinterpret_cast<const void *>(
3761 evaluateExpr(const_cast<Expr *>(expr), C)));
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003762 return nullptr;
3763 }
3764
3765 const CompoundStmt *compoundStmt = dyn_cast_or_null<CompoundStmt>(getCursorStmt(C));
3766 if (compoundStmt) {
3767 Expr *expr = nullptr;
3768 for (auto *bodyIterator : compoundStmt->body()) {
3769 if ((expr = dyn_cast<Expr>(bodyIterator))) {
3770 break;
3771 }
3772 }
3773 if (expr)
Aaron Ballman01dc1572016-01-20 15:25:30 +00003774 return const_cast<CXEvalResult>(
3775 reinterpret_cast<const void *>(evaluateExpr(expr, C)));
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003776 }
3777 return nullptr;
3778}
3779
3780unsigned clang_Cursor_hasAttrs(CXCursor C) {
3781 const Decl *D = getCursorDecl(C);
3782 if (!D) {
3783 return 0;
3784 }
3785
3786 if (D->hasAttrs()) {
3787 return 1;
3788 }
3789
3790 return 0;
3791}
Guy Benyei11169dd2012-12-18 14:30:41 +00003792unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
3793 return CXSaveTranslationUnit_None;
3794}
3795
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003796static CXSaveError clang_saveTranslationUnit_Impl(CXTranslationUnit TU,
3797 const char *FileName,
3798 unsigned options) {
3799 CIndexer *CXXIdx = TU->CIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00003800 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
3801 setThreadBackgroundPriority();
3802
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003803 bool hadError = cxtu::getASTUnit(TU)->Save(FileName);
3804 return hadError ? CXSaveError_Unknown : CXSaveError_None;
Guy Benyei11169dd2012-12-18 14:30:41 +00003805}
3806
3807int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
3808 unsigned options) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00003809 LOG_FUNC_SECTION {
3810 *Log << TU << ' ' << FileName;
3811 }
3812
Dmitri Gribenko852d6222014-02-11 15:02:48 +00003813 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00003814 LOG_BAD_TU(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00003815 return CXSaveError_InvalidTU;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00003816 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003817
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00003818 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00003819 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3820 if (!CXXUnit->hasSema())
3821 return CXSaveError_InvalidTU;
3822
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003823 CXSaveError result;
3824 auto SaveTranslationUnitImpl = [=, &result]() {
3825 result = clang_saveTranslationUnit_Impl(TU, FileName, options);
3826 };
Guy Benyei11169dd2012-12-18 14:30:41 +00003827
3828 if (!CXXUnit->getDiagnostics().hasUnrecoverableErrorOccurred() ||
3829 getenv("LIBCLANG_NOTHREADS")) {
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003830 SaveTranslationUnitImpl();
Guy Benyei11169dd2012-12-18 14:30:41 +00003831
3832 if (getenv("LIBCLANG_RESOURCE_USAGE"))
3833 PrintLibclangResourceUsage(TU);
3834
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003835 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003836 }
3837
3838 // We have an AST that has invalid nodes due to compiler errors.
3839 // Use a crash recovery thread for protection.
3840
3841 llvm::CrashRecoveryContext CRC;
3842
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003843 if (!RunSafely(CRC, SaveTranslationUnitImpl)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003844 fprintf(stderr, "libclang: crash detected during AST saving: {\n");
3845 fprintf(stderr, " 'filename' : '%s'\n", FileName);
3846 fprintf(stderr, " 'options' : %d,\n", options);
3847 fprintf(stderr, "}\n");
3848
3849 return CXSaveError_Unknown;
3850
3851 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
3852 PrintLibclangResourceUsage(TU);
3853 }
3854
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003855 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003856}
3857
3858void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
3859 if (CTUnit) {
3860 // If the translation unit has been marked as unsafe to free, just discard
3861 // it.
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003862 ASTUnit *Unit = cxtu::getASTUnit(CTUnit);
3863 if (Unit && Unit->isUnsafeToFree())
Guy Benyei11169dd2012-12-18 14:30:41 +00003864 return;
3865
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00003866 delete cxtu::getASTUnit(CTUnit);
Dmitri Gribenkob95b3f12013-01-26 22:44:19 +00003867 delete CTUnit->StringPool;
Guy Benyei11169dd2012-12-18 14:30:41 +00003868 delete static_cast<CXDiagnosticSetImpl *>(CTUnit->Diagnostics);
3869 disposeOverridenCXCursorsPool(CTUnit->OverridenCursorsPool);
Dmitri Gribenko9e605112013-11-13 22:16:51 +00003870 delete CTUnit->CommentToXML;
Guy Benyei11169dd2012-12-18 14:30:41 +00003871 delete CTUnit;
3872 }
3873}
3874
3875unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
3876 return CXReparse_None;
3877}
3878
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003879static CXErrorCode
3880clang_reparseTranslationUnit_Impl(CXTranslationUnit TU,
3881 ArrayRef<CXUnsavedFile> unsaved_files,
3882 unsigned options) {
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003883 // Check arguments.
Dmitri Gribenko852d6222014-02-11 15:02:48 +00003884 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00003885 LOG_BAD_TU(TU);
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003886 return CXError_InvalidArguments;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003887 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003888
3889 // Reset the associated diagnostics.
3890 delete static_cast<CXDiagnosticSetImpl*>(TU->Diagnostics);
Craig Topper69186e72014-06-08 08:38:04 +00003891 TU->Diagnostics = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00003892
Dmitri Gribenko183436e2013-01-26 21:49:50 +00003893 CIndexer *CXXIdx = TU->CIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00003894 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing))
3895 setThreadBackgroundPriority();
3896
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00003897 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00003898 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ahmed Charlesb8984322014-03-07 20:03:18 +00003899
3900 std::unique_ptr<std::vector<ASTUnit::RemappedFile>> RemappedFiles(
3901 new std::vector<ASTUnit::RemappedFile>());
3902
Guy Benyei11169dd2012-12-18 14:30:41 +00003903 // Recover resources if we crash before exiting this function.
3904 llvm::CrashRecoveryContextCleanupRegistrar<
3905 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
Alp Toker9d85b182014-07-07 01:23:14 +00003906
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003907 for (auto &UF : unsaved_files) {
Rafael Espindolad87f8d72014-08-27 20:03:29 +00003908 std::unique_ptr<llvm::MemoryBuffer> MB =
Alp Toker9d85b182014-07-07 01:23:14 +00003909 llvm::MemoryBuffer::getMemBufferCopy(getContents(UF), UF.Filename);
Rafael Espindolad87f8d72014-08-27 20:03:29 +00003910 RemappedFiles->push_back(std::make_pair(UF.Filename, MB.release()));
Guy Benyei11169dd2012-12-18 14:30:41 +00003911 }
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003912
Adrian Prantlbb165fb2015-06-20 18:53:08 +00003913 if (!CXXUnit->Reparse(CXXIdx->getPCHContainerOperations(),
3914 *RemappedFiles.get()))
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003915 return CXError_Success;
3916 if (isASTReadError(CXXUnit))
3917 return CXError_ASTReadError;
3918 return CXError_Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003919}
3920
3921int clang_reparseTranslationUnit(CXTranslationUnit TU,
3922 unsigned num_unsaved_files,
3923 struct CXUnsavedFile *unsaved_files,
3924 unsigned options) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00003925 LOG_FUNC_SECTION {
3926 *Log << TU;
3927 }
3928
Alp Toker9d85b182014-07-07 01:23:14 +00003929 if (num_unsaved_files && !unsaved_files)
3930 return CXError_InvalidArguments;
3931
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003932 CXErrorCode result;
3933 auto ReparseTranslationUnitImpl = [=, &result]() {
3934 result = clang_reparseTranslationUnit_Impl(
3935 TU, llvm::makeArrayRef(unsaved_files, num_unsaved_files), options);
3936 };
Guy Benyei11169dd2012-12-18 14:30:41 +00003937
3938 if (getenv("LIBCLANG_NOTHREADS")) {
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003939 ReparseTranslationUnitImpl();
Alp Toker5c532982014-07-07 22:42:03 +00003940 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003941 }
3942
3943 llvm::CrashRecoveryContext CRC;
3944
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003945 if (!RunSafely(CRC, ReparseTranslationUnitImpl)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003946 fprintf(stderr, "libclang: crash detected during reparsing\n");
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00003947 cxtu::getASTUnit(TU)->setUnsafeToFree(true);
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003948 return CXError_Crashed;
Guy Benyei11169dd2012-12-18 14:30:41 +00003949 } else if (getenv("LIBCLANG_RESOURCE_USAGE"))
3950 PrintLibclangResourceUsage(TU);
3951
Alp Toker5c532982014-07-07 22:42:03 +00003952 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003953}
3954
3955
3956CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00003957 if (isNotUsableTU(CTUnit)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00003958 LOG_BAD_TU(CTUnit);
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00003959 return cxstring::createEmpty();
Dmitri Gribenko256454f2014-02-11 14:34:14 +00003960 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003961
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00003962 ASTUnit *CXXUnit = cxtu::getASTUnit(CTUnit);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00003963 return cxstring::createDup(CXXUnit->getOriginalSourceFileName());
Guy Benyei11169dd2012-12-18 14:30:41 +00003964}
3965
3966CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00003967 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00003968 LOG_BAD_TU(TU);
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00003969 return clang_getNullCursor();
Dmitri Gribenko256454f2014-02-11 14:34:14 +00003970 }
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00003971
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00003972 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00003973 return MakeCXCursor(CXXUnit->getASTContext().getTranslationUnitDecl(), TU);
3974}
3975
Guy Benyei11169dd2012-12-18 14:30:41 +00003976//===----------------------------------------------------------------------===//
3977// CXFile Operations.
3978//===----------------------------------------------------------------------===//
3979
Guy Benyei11169dd2012-12-18 14:30:41 +00003980CXString clang_getFileName(CXFile SFile) {
3981 if (!SFile)
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00003982 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00003983
3984 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00003985 return cxstring::createRef(FEnt->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00003986}
3987
3988time_t clang_getFileTime(CXFile SFile) {
3989 if (!SFile)
3990 return 0;
3991
3992 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
3993 return FEnt->getModificationTime();
3994}
3995
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00003996CXFile clang_getFile(CXTranslationUnit TU, const char *file_name) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00003997 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00003998 LOG_BAD_TU(TU);
Craig Topper69186e72014-06-08 08:38:04 +00003999 return nullptr;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004000 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004001
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004002 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004003
4004 FileManager &FMgr = CXXUnit->getFileManager();
4005 return const_cast<FileEntry *>(FMgr.getFile(file_name));
4006}
4007
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004008unsigned clang_isFileMultipleIncludeGuarded(CXTranslationUnit TU,
4009 CXFile file) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004010 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004011 LOG_BAD_TU(TU);
4012 return 0;
4013 }
4014
4015 if (!file)
Guy Benyei11169dd2012-12-18 14:30:41 +00004016 return 0;
4017
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004018 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004019 FileEntry *FEnt = static_cast<FileEntry *>(file);
4020 return CXXUnit->getPreprocessor().getHeaderSearchInfo()
4021 .isFileMultipleIncludeGuarded(FEnt);
4022}
4023
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00004024int clang_getFileUniqueID(CXFile file, CXFileUniqueID *outID) {
4025 if (!file || !outID)
4026 return 1;
4027
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00004028 FileEntry *FEnt = static_cast<FileEntry *>(file);
Rafael Espindolaf8f91b82013-08-01 21:42:11 +00004029 const llvm::sys::fs::UniqueID &ID = FEnt->getUniqueID();
4030 outID->data[0] = ID.getDevice();
4031 outID->data[1] = ID.getFile();
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00004032 outID->data[2] = FEnt->getModificationTime();
4033 return 0;
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00004034}
4035
Argyrios Kyrtzidisac3997e2014-08-16 00:26:19 +00004036int clang_File_isEqual(CXFile file1, CXFile file2) {
4037 if (file1 == file2)
4038 return true;
4039
4040 if (!file1 || !file2)
4041 return false;
4042
4043 FileEntry *FEnt1 = static_cast<FileEntry *>(file1);
4044 FileEntry *FEnt2 = static_cast<FileEntry *>(file2);
4045 return FEnt1->getUniqueID() == FEnt2->getUniqueID();
4046}
4047
Guy Benyei11169dd2012-12-18 14:30:41 +00004048//===----------------------------------------------------------------------===//
4049// CXCursor Operations.
4050//===----------------------------------------------------------------------===//
4051
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004052static const Decl *getDeclFromExpr(const Stmt *E) {
4053 if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004054 return getDeclFromExpr(CE->getSubExpr());
4055
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004056 if (const DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004057 return RefExpr->getDecl();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004058 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004059 return ME->getMemberDecl();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004060 if (const ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004061 return RE->getDecl();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004062 if (const ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004063 if (PRE->isExplicitProperty())
4064 return PRE->getExplicitProperty();
4065 // It could be messaging both getter and setter as in:
4066 // ++myobj.myprop;
4067 // in which case prefer to associate the setter since it is less obvious
4068 // from inspecting the source that the setter is going to get called.
4069 if (PRE->isMessagingSetter())
4070 return PRE->getImplicitPropertySetter();
4071 return PRE->getImplicitPropertyGetter();
4072 }
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004073 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004074 return getDeclFromExpr(POE->getSyntacticForm());
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004075 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004076 if (Expr *Src = OVE->getSourceExpr())
4077 return getDeclFromExpr(Src);
4078
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004079 if (const CallExpr *CE = dyn_cast<CallExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004080 return getDeclFromExpr(CE->getCallee());
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004081 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004082 if (!CE->isElidable())
4083 return CE->getConstructor();
Richard Smith5179eb72016-06-28 19:03:57 +00004084 if (const CXXInheritedCtorInitExpr *CE =
4085 dyn_cast<CXXInheritedCtorInitExpr>(E))
4086 return CE->getConstructor();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004087 if (const ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004088 return OME->getMethodDecl();
4089
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004090 if (const ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004091 return PE->getProtocol();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004092 if (const SubstNonTypeTemplateParmPackExpr *NTTP
Guy Benyei11169dd2012-12-18 14:30:41 +00004093 = dyn_cast<SubstNonTypeTemplateParmPackExpr>(E))
4094 return NTTP->getParameterPack();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004095 if (const SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004096 if (isa<NonTypeTemplateParmDecl>(SizeOfPack->getPack()) ||
4097 isa<ParmVarDecl>(SizeOfPack->getPack()))
4098 return SizeOfPack->getPack();
Craig Topper69186e72014-06-08 08:38:04 +00004099
4100 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004101}
4102
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004103static SourceLocation getLocationFromExpr(const Expr *E) {
4104 if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004105 return getLocationFromExpr(CE->getSubExpr());
4106
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004107 if (const ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004108 return /*FIXME:*/Msg->getLeftLoc();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004109 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004110 return DRE->getLocation();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004111 if (const MemberExpr *Member = dyn_cast<MemberExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004112 return Member->getMemberLoc();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004113 if (const ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004114 return Ivar->getLocation();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004115 if (const SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004116 return SizeOfPack->getPackLoc();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004117 if (const ObjCPropertyRefExpr *PropRef = dyn_cast<ObjCPropertyRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004118 return PropRef->getLocation();
4119
4120 return E->getLocStart();
4121}
4122
NAKAMURA Takumia01f4c32016-12-19 16:50:43 +00004123extern "C" {
4124
Guy Benyei11169dd2012-12-18 14:30:41 +00004125unsigned clang_visitChildren(CXCursor parent,
4126 CXCursorVisitor visitor,
4127 CXClientData client_data) {
4128 CursorVisitor CursorVis(getCursorTU(parent), visitor, client_data,
4129 /*VisitPreprocessorLast=*/false);
4130 return CursorVis.VisitChildren(parent);
4131}
4132
4133#ifndef __has_feature
4134#define __has_feature(x) 0
4135#endif
4136#if __has_feature(blocks)
4137typedef enum CXChildVisitResult
4138 (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
4139
4140static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
4141 CXClientData client_data) {
4142 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
4143 return block(cursor, parent);
4144}
4145#else
4146// If we are compiled with a compiler that doesn't have native blocks support,
4147// define and call the block manually, so the
4148typedef struct _CXChildVisitResult
4149{
4150 void *isa;
4151 int flags;
4152 int reserved;
4153 enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor,
4154 CXCursor);
4155} *CXCursorVisitorBlock;
4156
4157static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
4158 CXClientData client_data) {
4159 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
4160 return block->invoke(block, cursor, parent);
4161}
4162#endif
4163
4164
4165unsigned clang_visitChildrenWithBlock(CXCursor parent,
4166 CXCursorVisitorBlock block) {
4167 return clang_visitChildren(parent, visitWithBlock, block);
4168}
4169
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004170static CXString getDeclSpelling(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004171 if (!D)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004172 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004173
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004174 const NamedDecl *ND = dyn_cast<NamedDecl>(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00004175 if (!ND) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004176 if (const ObjCPropertyImplDecl *PropImpl =
4177 dyn_cast<ObjCPropertyImplDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00004178 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004179 return cxstring::createDup(Property->getIdentifier()->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004180
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004181 if (const ImportDecl *ImportD = dyn_cast<ImportDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00004182 if (Module *Mod = ImportD->getImportedModule())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004183 return cxstring::createDup(Mod->getFullModuleName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004184
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004185 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004186 }
4187
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004188 if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004189 return cxstring::createDup(OMD->getSelector().getAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004190
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004191 if (const ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
Guy Benyei11169dd2012-12-18 14:30:41 +00004192 // No, this isn't the same as the code below. getIdentifier() is non-virtual
4193 // and returns different names. NamedDecl returns the class name and
4194 // ObjCCategoryImplDecl returns the category name.
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004195 return cxstring::createRef(CIMP->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004196
4197 if (isa<UsingDirectiveDecl>(D))
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004198 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004199
4200 SmallString<1024> S;
4201 llvm::raw_svector_ostream os(S);
4202 ND->printName(os);
4203
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004204 return cxstring::createDup(os.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00004205}
4206
4207CXString clang_getCursorSpelling(CXCursor C) {
4208 if (clang_isTranslationUnit(C.kind))
Dmitri Gribenko2c173b42013-01-11 19:28:44 +00004209 return clang_getTranslationUnitSpelling(getCursorTU(C));
Guy Benyei11169dd2012-12-18 14:30:41 +00004210
4211 if (clang_isReference(C.kind)) {
4212 switch (C.kind) {
4213 case CXCursor_ObjCSuperClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004214 const ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004215 return cxstring::createRef(Super->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004216 }
4217 case CXCursor_ObjCClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004218 const ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004219 return cxstring::createRef(Class->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004220 }
4221 case CXCursor_ObjCProtocolRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004222 const ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004223 assert(OID && "getCursorSpelling(): Missing protocol decl");
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004224 return cxstring::createRef(OID->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004225 }
4226 case CXCursor_CXXBaseSpecifier: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004227 const CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004228 return cxstring::createDup(B->getType().getAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004229 }
4230 case CXCursor_TypeRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004231 const TypeDecl *Type = getCursorTypeRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004232 assert(Type && "Missing type decl");
4233
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004234 return cxstring::createDup(getCursorContext(C).getTypeDeclType(Type).
Guy Benyei11169dd2012-12-18 14:30:41 +00004235 getAsString());
4236 }
4237 case CXCursor_TemplateRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004238 const TemplateDecl *Template = getCursorTemplateRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004239 assert(Template && "Missing template decl");
4240
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004241 return cxstring::createDup(Template->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004242 }
4243
4244 case CXCursor_NamespaceRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004245 const NamedDecl *NS = getCursorNamespaceRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004246 assert(NS && "Missing namespace decl");
4247
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004248 return cxstring::createDup(NS->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004249 }
4250
4251 case CXCursor_MemberRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004252 const FieldDecl *Field = getCursorMemberRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004253 assert(Field && "Missing member decl");
4254
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004255 return cxstring::createDup(Field->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004256 }
4257
4258 case CXCursor_LabelRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004259 const LabelStmt *Label = getCursorLabelRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004260 assert(Label && "Missing label");
4261
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004262 return cxstring::createRef(Label->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004263 }
4264
4265 case CXCursor_OverloadedDeclRef: {
4266 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004267 if (const Decl *D = Storage.dyn_cast<const Decl *>()) {
4268 if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004269 return cxstring::createDup(ND->getNameAsString());
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004270 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004271 }
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004272 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004273 return cxstring::createDup(E->getName().getAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004274 OverloadedTemplateStorage *Ovl
4275 = Storage.get<OverloadedTemplateStorage*>();
4276 if (Ovl->size() == 0)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004277 return cxstring::createEmpty();
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004278 return cxstring::createDup((*Ovl->begin())->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004279 }
4280
4281 case CXCursor_VariableRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004282 const VarDecl *Var = getCursorVariableRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004283 assert(Var && "Missing variable decl");
4284
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004285 return cxstring::createDup(Var->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004286 }
4287
4288 default:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004289 return cxstring::createRef("<not implemented>");
Guy Benyei11169dd2012-12-18 14:30:41 +00004290 }
4291 }
4292
4293 if (clang_isExpression(C.kind)) {
Argyrios Kyrtzidis3227d862014-03-03 19:40:52 +00004294 const Expr *E = getCursorExpr(C);
4295
4296 if (C.kind == CXCursor_ObjCStringLiteral ||
4297 C.kind == CXCursor_StringLiteral) {
4298 const StringLiteral *SLit;
4299 if (const ObjCStringLiteral *OSL = dyn_cast<ObjCStringLiteral>(E)) {
4300 SLit = OSL->getString();
4301 } else {
4302 SLit = cast<StringLiteral>(E);
4303 }
4304 SmallString<256> Buf;
4305 llvm::raw_svector_ostream OS(Buf);
4306 SLit->outputString(OS);
4307 return cxstring::createDup(OS.str());
4308 }
4309
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004310 const Decl *D = getDeclFromExpr(getCursorExpr(C));
Guy Benyei11169dd2012-12-18 14:30:41 +00004311 if (D)
4312 return getDeclSpelling(D);
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004313 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004314 }
4315
4316 if (clang_isStatement(C.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004317 const Stmt *S = getCursorStmt(C);
4318 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004319 return cxstring::createRef(Label->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004320
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004321 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004322 }
4323
4324 if (C.kind == CXCursor_MacroExpansion)
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004325 return cxstring::createRef(getCursorMacroExpansion(C).getName()
Guy Benyei11169dd2012-12-18 14:30:41 +00004326 ->getNameStart());
4327
4328 if (C.kind == CXCursor_MacroDefinition)
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004329 return cxstring::createRef(getCursorMacroDefinition(C)->getName()
Guy Benyei11169dd2012-12-18 14:30:41 +00004330 ->getNameStart());
4331
4332 if (C.kind == CXCursor_InclusionDirective)
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004333 return cxstring::createDup(getCursorInclusionDirective(C)->getFileName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004334
4335 if (clang_isDeclaration(C.kind))
4336 return getDeclSpelling(getCursorDecl(C));
4337
4338 if (C.kind == CXCursor_AnnotateAttr) {
Dmitri Gribenkoe4baea62013-01-26 18:08:08 +00004339 const AnnotateAttr *AA = cast<AnnotateAttr>(cxcursor::getCursorAttr(C));
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004340 return cxstring::createDup(AA->getAnnotation());
Guy Benyei11169dd2012-12-18 14:30:41 +00004341 }
4342
4343 if (C.kind == CXCursor_AsmLabelAttr) {
Dmitri Gribenkoe4baea62013-01-26 18:08:08 +00004344 const AsmLabelAttr *AA = cast<AsmLabelAttr>(cxcursor::getCursorAttr(C));
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004345 return cxstring::createDup(AA->getLabel());
Guy Benyei11169dd2012-12-18 14:30:41 +00004346 }
4347
Argyrios Kyrtzidis16834f12013-09-25 00:14:38 +00004348 if (C.kind == CXCursor_PackedAttr) {
4349 return cxstring::createRef("packed");
4350 }
4351
Saleem Abdulrasool79c69712015-09-05 18:53:43 +00004352 if (C.kind == CXCursor_VisibilityAttr) {
4353 const VisibilityAttr *AA = cast<VisibilityAttr>(cxcursor::getCursorAttr(C));
4354 switch (AA->getVisibility()) {
4355 case VisibilityAttr::VisibilityType::Default:
4356 return cxstring::createRef("default");
4357 case VisibilityAttr::VisibilityType::Hidden:
4358 return cxstring::createRef("hidden");
4359 case VisibilityAttr::VisibilityType::Protected:
4360 return cxstring::createRef("protected");
4361 }
4362 llvm_unreachable("unknown visibility type");
4363 }
4364
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004365 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004366}
4367
4368CXSourceRange clang_Cursor_getSpellingNameRange(CXCursor C,
4369 unsigned pieceIndex,
4370 unsigned options) {
4371 if (clang_Cursor_isNull(C))
4372 return clang_getNullRange();
4373
4374 ASTContext &Ctx = getCursorContext(C);
4375
4376 if (clang_isStatement(C.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004377 const Stmt *S = getCursorStmt(C);
4378 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004379 if (pieceIndex > 0)
4380 return clang_getNullRange();
4381 return cxloc::translateSourceRange(Ctx, Label->getIdentLoc());
4382 }
4383
4384 return clang_getNullRange();
4385 }
4386
4387 if (C.kind == CXCursor_ObjCMessageExpr) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004388 if (const ObjCMessageExpr *
Guy Benyei11169dd2012-12-18 14:30:41 +00004389 ME = dyn_cast_or_null<ObjCMessageExpr>(getCursorExpr(C))) {
4390 if (pieceIndex >= ME->getNumSelectorLocs())
4391 return clang_getNullRange();
4392 return cxloc::translateSourceRange(Ctx, ME->getSelectorLoc(pieceIndex));
4393 }
4394 }
4395
4396 if (C.kind == CXCursor_ObjCInstanceMethodDecl ||
4397 C.kind == CXCursor_ObjCClassMethodDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004398 if (const ObjCMethodDecl *
Guy Benyei11169dd2012-12-18 14:30:41 +00004399 MD = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(C))) {
4400 if (pieceIndex >= MD->getNumSelectorLocs())
4401 return clang_getNullRange();
4402 return cxloc::translateSourceRange(Ctx, MD->getSelectorLoc(pieceIndex));
4403 }
4404 }
4405
4406 if (C.kind == CXCursor_ObjCCategoryDecl ||
4407 C.kind == CXCursor_ObjCCategoryImplDecl) {
4408 if (pieceIndex > 0)
4409 return clang_getNullRange();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004410 if (const ObjCCategoryDecl *
Guy Benyei11169dd2012-12-18 14:30:41 +00004411 CD = dyn_cast_or_null<ObjCCategoryDecl>(getCursorDecl(C)))
4412 return cxloc::translateSourceRange(Ctx, CD->getCategoryNameLoc());
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004413 if (const ObjCCategoryImplDecl *
Guy Benyei11169dd2012-12-18 14:30:41 +00004414 CID = dyn_cast_or_null<ObjCCategoryImplDecl>(getCursorDecl(C)))
4415 return cxloc::translateSourceRange(Ctx, CID->getCategoryNameLoc());
4416 }
4417
4418 if (C.kind == CXCursor_ModuleImportDecl) {
4419 if (pieceIndex > 0)
4420 return clang_getNullRange();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004421 if (const ImportDecl *ImportD =
4422 dyn_cast_or_null<ImportDecl>(getCursorDecl(C))) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004423 ArrayRef<SourceLocation> Locs = ImportD->getIdentifierLocs();
4424 if (!Locs.empty())
4425 return cxloc::translateSourceRange(Ctx,
4426 SourceRange(Locs.front(), Locs.back()));
4427 }
4428 return clang_getNullRange();
4429 }
4430
Argyrios Kyrtzidisa2a1e532014-08-26 20:23:26 +00004431 if (C.kind == CXCursor_CXXMethod || C.kind == CXCursor_Destructor ||
Kevin Funk4be5d672016-12-20 09:56:56 +00004432 C.kind == CXCursor_ConversionFunction ||
4433 C.kind == CXCursor_FunctionDecl) {
Argyrios Kyrtzidisa2a1e532014-08-26 20:23:26 +00004434 if (pieceIndex > 0)
4435 return clang_getNullRange();
4436 if (const FunctionDecl *FD =
4437 dyn_cast_or_null<FunctionDecl>(getCursorDecl(C))) {
4438 DeclarationNameInfo FunctionName = FD->getNameInfo();
4439 return cxloc::translateSourceRange(Ctx, FunctionName.getSourceRange());
4440 }
4441 return clang_getNullRange();
4442 }
4443
Guy Benyei11169dd2012-12-18 14:30:41 +00004444 // FIXME: A CXCursor_InclusionDirective should give the location of the
4445 // filename, but we don't keep track of this.
4446
4447 // FIXME: A CXCursor_AnnotateAttr should give the location of the annotation
4448 // but we don't keep track of this.
4449
4450 // FIXME: A CXCursor_AsmLabelAttr should give the location of the label
4451 // but we don't keep track of this.
4452
4453 // Default handling, give the location of the cursor.
4454
4455 if (pieceIndex > 0)
4456 return clang_getNullRange();
4457
4458 CXSourceLocation CXLoc = clang_getCursorLocation(C);
4459 SourceLocation Loc = cxloc::translateSourceLocation(CXLoc);
4460 return cxloc::translateSourceRange(Ctx, Loc);
4461}
4462
Eli Bendersky44a206f2014-07-31 18:04:56 +00004463CXString clang_Cursor_getMangling(CXCursor C) {
4464 if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
4465 return cxstring::createEmpty();
4466
Eli Bendersky44a206f2014-07-31 18:04:56 +00004467 // Mangling only works for functions and variables.
Eli Bendersky79759592014-08-01 15:01:10 +00004468 const Decl *D = getCursorDecl(C);
Eli Bendersky44a206f2014-07-31 18:04:56 +00004469 if (!D || !(isa<FunctionDecl>(D) || isa<VarDecl>(D)))
4470 return cxstring::createEmpty();
4471
Argyrios Kyrtzidisca741ce2016-02-14 22:30:14 +00004472 ASTContext &Ctx = D->getASTContext();
4473 index::CodegenNameGenerator CGNameGen(Ctx);
4474 return cxstring::createDup(CGNameGen.getName(D));
Eli Bendersky44a206f2014-07-31 18:04:56 +00004475}
4476
Saleem Abdulrasool60034432015-11-12 03:57:22 +00004477CXStringSet *clang_Cursor_getCXXManglings(CXCursor C) {
4478 if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
4479 return nullptr;
4480
4481 const Decl *D = getCursorDecl(C);
4482 if (!(isa<CXXRecordDecl>(D) || isa<CXXMethodDecl>(D)))
4483 return nullptr;
4484
Argyrios Kyrtzidisca741ce2016-02-14 22:30:14 +00004485 ASTContext &Ctx = D->getASTContext();
4486 index::CodegenNameGenerator CGNameGen(Ctx);
4487 std::vector<std::string> Manglings = CGNameGen.getAllManglings(D);
Saleem Abdulrasool60034432015-11-12 03:57:22 +00004488 return cxstring::createSet(Manglings);
4489}
4490
Guy Benyei11169dd2012-12-18 14:30:41 +00004491CXString clang_getCursorDisplayName(CXCursor C) {
4492 if (!clang_isDeclaration(C.kind))
4493 return clang_getCursorSpelling(C);
4494
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004495 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00004496 if (!D)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004497 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004498
4499 PrintingPolicy Policy = getCursorContext(C).getPrintingPolicy();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004500 if (const FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00004501 D = FunTmpl->getTemplatedDecl();
4502
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004503 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004504 SmallString<64> Str;
4505 llvm::raw_svector_ostream OS(Str);
4506 OS << *Function;
4507 if (Function->getPrimaryTemplate())
4508 OS << "<>";
4509 OS << "(";
4510 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
4511 if (I)
4512 OS << ", ";
4513 OS << Function->getParamDecl(I)->getType().getAsString(Policy);
4514 }
4515
4516 if (Function->isVariadic()) {
4517 if (Function->getNumParams())
4518 OS << ", ";
4519 OS << "...";
4520 }
4521 OS << ")";
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004522 return cxstring::createDup(OS.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00004523 }
4524
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004525 if (const ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004526 SmallString<64> Str;
4527 llvm::raw_svector_ostream OS(Str);
4528 OS << *ClassTemplate;
4529 OS << "<";
4530 TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
4531 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
4532 if (I)
4533 OS << ", ";
4534
4535 NamedDecl *Param = Params->getParam(I);
4536 if (Param->getIdentifier()) {
4537 OS << Param->getIdentifier()->getName();
4538 continue;
4539 }
4540
4541 // There is no parameter name, which makes this tricky. Try to come up
4542 // with something useful that isn't too long.
4543 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
4544 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
4545 else if (NonTypeTemplateParmDecl *NTTP
4546 = dyn_cast<NonTypeTemplateParmDecl>(Param))
4547 OS << NTTP->getType().getAsString(Policy);
4548 else
4549 OS << "template<...> class";
4550 }
4551
4552 OS << ">";
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004553 return cxstring::createDup(OS.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00004554 }
4555
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004556 if (const ClassTemplateSpecializationDecl *ClassSpec
Guy Benyei11169dd2012-12-18 14:30:41 +00004557 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
4558 // If the type was explicitly written, use that.
4559 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004560 return cxstring::createDup(TSInfo->getType().getAsString(Policy));
Guy Benyei11169dd2012-12-18 14:30:41 +00004561
Benjamin Kramer9170e912013-02-22 15:46:01 +00004562 SmallString<128> Str;
Guy Benyei11169dd2012-12-18 14:30:41 +00004563 llvm::raw_svector_ostream OS(Str);
4564 OS << *ClassSpec;
David Majnemer6fbeee32016-07-07 04:43:07 +00004565 TemplateSpecializationType::PrintTemplateArgumentList(
4566 OS, ClassSpec->getTemplateArgs().asArray(), Policy);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004567 return cxstring::createDup(OS.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00004568 }
4569
4570 return clang_getCursorSpelling(C);
4571}
4572
4573CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
4574 switch (Kind) {
4575 case CXCursor_FunctionDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004576 return cxstring::createRef("FunctionDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004577 case CXCursor_TypedefDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004578 return cxstring::createRef("TypedefDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004579 case CXCursor_EnumDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004580 return cxstring::createRef("EnumDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004581 case CXCursor_EnumConstantDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004582 return cxstring::createRef("EnumConstantDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004583 case CXCursor_StructDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004584 return cxstring::createRef("StructDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004585 case CXCursor_UnionDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004586 return cxstring::createRef("UnionDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004587 case CXCursor_ClassDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004588 return cxstring::createRef("ClassDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004589 case CXCursor_FieldDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004590 return cxstring::createRef("FieldDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004591 case CXCursor_VarDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004592 return cxstring::createRef("VarDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004593 case CXCursor_ParmDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004594 return cxstring::createRef("ParmDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004595 case CXCursor_ObjCInterfaceDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004596 return cxstring::createRef("ObjCInterfaceDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004597 case CXCursor_ObjCCategoryDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004598 return cxstring::createRef("ObjCCategoryDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004599 case CXCursor_ObjCProtocolDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004600 return cxstring::createRef("ObjCProtocolDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004601 case CXCursor_ObjCPropertyDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004602 return cxstring::createRef("ObjCPropertyDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004603 case CXCursor_ObjCIvarDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004604 return cxstring::createRef("ObjCIvarDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004605 case CXCursor_ObjCInstanceMethodDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004606 return cxstring::createRef("ObjCInstanceMethodDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004607 case CXCursor_ObjCClassMethodDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004608 return cxstring::createRef("ObjCClassMethodDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004609 case CXCursor_ObjCImplementationDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004610 return cxstring::createRef("ObjCImplementationDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004611 case CXCursor_ObjCCategoryImplDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004612 return cxstring::createRef("ObjCCategoryImplDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004613 case CXCursor_CXXMethod:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004614 return cxstring::createRef("CXXMethod");
Guy Benyei11169dd2012-12-18 14:30:41 +00004615 case CXCursor_UnexposedDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004616 return cxstring::createRef("UnexposedDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004617 case CXCursor_ObjCSuperClassRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004618 return cxstring::createRef("ObjCSuperClassRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00004619 case CXCursor_ObjCProtocolRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004620 return cxstring::createRef("ObjCProtocolRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00004621 case CXCursor_ObjCClassRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004622 return cxstring::createRef("ObjCClassRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00004623 case CXCursor_TypeRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004624 return cxstring::createRef("TypeRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00004625 case CXCursor_TemplateRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004626 return cxstring::createRef("TemplateRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00004627 case CXCursor_NamespaceRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004628 return cxstring::createRef("NamespaceRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00004629 case CXCursor_MemberRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004630 return cxstring::createRef("MemberRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00004631 case CXCursor_LabelRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004632 return cxstring::createRef("LabelRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00004633 case CXCursor_OverloadedDeclRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004634 return cxstring::createRef("OverloadedDeclRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00004635 case CXCursor_VariableRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004636 return cxstring::createRef("VariableRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00004637 case CXCursor_IntegerLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004638 return cxstring::createRef("IntegerLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00004639 case CXCursor_FloatingLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004640 return cxstring::createRef("FloatingLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00004641 case CXCursor_ImaginaryLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004642 return cxstring::createRef("ImaginaryLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00004643 case CXCursor_StringLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004644 return cxstring::createRef("StringLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00004645 case CXCursor_CharacterLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004646 return cxstring::createRef("CharacterLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00004647 case CXCursor_ParenExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004648 return cxstring::createRef("ParenExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004649 case CXCursor_UnaryOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004650 return cxstring::createRef("UnaryOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00004651 case CXCursor_ArraySubscriptExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004652 return cxstring::createRef("ArraySubscriptExpr");
Alexey Bataev1a3320e2015-08-25 14:24:04 +00004653 case CXCursor_OMPArraySectionExpr:
4654 return cxstring::createRef("OMPArraySectionExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004655 case CXCursor_BinaryOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004656 return cxstring::createRef("BinaryOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00004657 case CXCursor_CompoundAssignOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004658 return cxstring::createRef("CompoundAssignOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00004659 case CXCursor_ConditionalOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004660 return cxstring::createRef("ConditionalOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00004661 case CXCursor_CStyleCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004662 return cxstring::createRef("CStyleCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004663 case CXCursor_CompoundLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004664 return cxstring::createRef("CompoundLiteralExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004665 case CXCursor_InitListExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004666 return cxstring::createRef("InitListExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004667 case CXCursor_AddrLabelExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004668 return cxstring::createRef("AddrLabelExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004669 case CXCursor_StmtExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004670 return cxstring::createRef("StmtExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004671 case CXCursor_GenericSelectionExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004672 return cxstring::createRef("GenericSelectionExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004673 case CXCursor_GNUNullExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004674 return cxstring::createRef("GNUNullExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004675 case CXCursor_CXXStaticCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004676 return cxstring::createRef("CXXStaticCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004677 case CXCursor_CXXDynamicCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004678 return cxstring::createRef("CXXDynamicCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004679 case CXCursor_CXXReinterpretCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004680 return cxstring::createRef("CXXReinterpretCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004681 case CXCursor_CXXConstCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004682 return cxstring::createRef("CXXConstCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004683 case CXCursor_CXXFunctionalCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004684 return cxstring::createRef("CXXFunctionalCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004685 case CXCursor_CXXTypeidExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004686 return cxstring::createRef("CXXTypeidExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004687 case CXCursor_CXXBoolLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004688 return cxstring::createRef("CXXBoolLiteralExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004689 case CXCursor_CXXNullPtrLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004690 return cxstring::createRef("CXXNullPtrLiteralExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004691 case CXCursor_CXXThisExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004692 return cxstring::createRef("CXXThisExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004693 case CXCursor_CXXThrowExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004694 return cxstring::createRef("CXXThrowExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004695 case CXCursor_CXXNewExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004696 return cxstring::createRef("CXXNewExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004697 case CXCursor_CXXDeleteExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004698 return cxstring::createRef("CXXDeleteExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004699 case CXCursor_UnaryExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004700 return cxstring::createRef("UnaryExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004701 case CXCursor_ObjCStringLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004702 return cxstring::createRef("ObjCStringLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00004703 case CXCursor_ObjCBoolLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004704 return cxstring::createRef("ObjCBoolLiteralExpr");
Erik Pilkington29099de2016-07-16 00:35:23 +00004705 case CXCursor_ObjCAvailabilityCheckExpr:
4706 return cxstring::createRef("ObjCAvailabilityCheckExpr");
Argyrios Kyrtzidisc2233be2013-04-23 17:57:17 +00004707 case CXCursor_ObjCSelfExpr:
4708 return cxstring::createRef("ObjCSelfExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004709 case CXCursor_ObjCEncodeExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004710 return cxstring::createRef("ObjCEncodeExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004711 case CXCursor_ObjCSelectorExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004712 return cxstring::createRef("ObjCSelectorExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004713 case CXCursor_ObjCProtocolExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004714 return cxstring::createRef("ObjCProtocolExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004715 case CXCursor_ObjCBridgedCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004716 return cxstring::createRef("ObjCBridgedCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004717 case CXCursor_BlockExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004718 return cxstring::createRef("BlockExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004719 case CXCursor_PackExpansionExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004720 return cxstring::createRef("PackExpansionExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004721 case CXCursor_SizeOfPackExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004722 return cxstring::createRef("SizeOfPackExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004723 case CXCursor_LambdaExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004724 return cxstring::createRef("LambdaExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004725 case CXCursor_UnexposedExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004726 return cxstring::createRef("UnexposedExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004727 case CXCursor_DeclRefExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004728 return cxstring::createRef("DeclRefExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004729 case CXCursor_MemberRefExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004730 return cxstring::createRef("MemberRefExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004731 case CXCursor_CallExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004732 return cxstring::createRef("CallExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004733 case CXCursor_ObjCMessageExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004734 return cxstring::createRef("ObjCMessageExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004735 case CXCursor_UnexposedStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004736 return cxstring::createRef("UnexposedStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004737 case CXCursor_DeclStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004738 return cxstring::createRef("DeclStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004739 case CXCursor_LabelStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004740 return cxstring::createRef("LabelStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004741 case CXCursor_CompoundStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004742 return cxstring::createRef("CompoundStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004743 case CXCursor_CaseStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004744 return cxstring::createRef("CaseStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004745 case CXCursor_DefaultStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004746 return cxstring::createRef("DefaultStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004747 case CXCursor_IfStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004748 return cxstring::createRef("IfStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004749 case CXCursor_SwitchStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004750 return cxstring::createRef("SwitchStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004751 case CXCursor_WhileStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004752 return cxstring::createRef("WhileStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004753 case CXCursor_DoStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004754 return cxstring::createRef("DoStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004755 case CXCursor_ForStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004756 return cxstring::createRef("ForStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004757 case CXCursor_GotoStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004758 return cxstring::createRef("GotoStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004759 case CXCursor_IndirectGotoStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004760 return cxstring::createRef("IndirectGotoStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004761 case CXCursor_ContinueStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004762 return cxstring::createRef("ContinueStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004763 case CXCursor_BreakStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004764 return cxstring::createRef("BreakStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004765 case CXCursor_ReturnStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004766 return cxstring::createRef("ReturnStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004767 case CXCursor_GCCAsmStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004768 return cxstring::createRef("GCCAsmStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004769 case CXCursor_MSAsmStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004770 return cxstring::createRef("MSAsmStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004771 case CXCursor_ObjCAtTryStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004772 return cxstring::createRef("ObjCAtTryStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004773 case CXCursor_ObjCAtCatchStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004774 return cxstring::createRef("ObjCAtCatchStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004775 case CXCursor_ObjCAtFinallyStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004776 return cxstring::createRef("ObjCAtFinallyStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004777 case CXCursor_ObjCAtThrowStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004778 return cxstring::createRef("ObjCAtThrowStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004779 case CXCursor_ObjCAtSynchronizedStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004780 return cxstring::createRef("ObjCAtSynchronizedStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004781 case CXCursor_ObjCAutoreleasePoolStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004782 return cxstring::createRef("ObjCAutoreleasePoolStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004783 case CXCursor_ObjCForCollectionStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004784 return cxstring::createRef("ObjCForCollectionStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004785 case CXCursor_CXXCatchStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004786 return cxstring::createRef("CXXCatchStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004787 case CXCursor_CXXTryStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004788 return cxstring::createRef("CXXTryStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004789 case CXCursor_CXXForRangeStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004790 return cxstring::createRef("CXXForRangeStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004791 case CXCursor_SEHTryStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004792 return cxstring::createRef("SEHTryStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004793 case CXCursor_SEHExceptStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004794 return cxstring::createRef("SEHExceptStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004795 case CXCursor_SEHFinallyStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004796 return cxstring::createRef("SEHFinallyStmt");
Nico Weber9b982072014-07-07 00:12:30 +00004797 case CXCursor_SEHLeaveStmt:
4798 return cxstring::createRef("SEHLeaveStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004799 case CXCursor_NullStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004800 return cxstring::createRef("NullStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004801 case CXCursor_InvalidFile:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004802 return cxstring::createRef("InvalidFile");
Guy Benyei11169dd2012-12-18 14:30:41 +00004803 case CXCursor_InvalidCode:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004804 return cxstring::createRef("InvalidCode");
Guy Benyei11169dd2012-12-18 14:30:41 +00004805 case CXCursor_NoDeclFound:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004806 return cxstring::createRef("NoDeclFound");
Guy Benyei11169dd2012-12-18 14:30:41 +00004807 case CXCursor_NotImplemented:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004808 return cxstring::createRef("NotImplemented");
Guy Benyei11169dd2012-12-18 14:30:41 +00004809 case CXCursor_TranslationUnit:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004810 return cxstring::createRef("TranslationUnit");
Guy Benyei11169dd2012-12-18 14:30:41 +00004811 case CXCursor_UnexposedAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004812 return cxstring::createRef("UnexposedAttr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004813 case CXCursor_IBActionAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004814 return cxstring::createRef("attribute(ibaction)");
Guy Benyei11169dd2012-12-18 14:30:41 +00004815 case CXCursor_IBOutletAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004816 return cxstring::createRef("attribute(iboutlet)");
Guy Benyei11169dd2012-12-18 14:30:41 +00004817 case CXCursor_IBOutletCollectionAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004818 return cxstring::createRef("attribute(iboutletcollection)");
Guy Benyei11169dd2012-12-18 14:30:41 +00004819 case CXCursor_CXXFinalAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004820 return cxstring::createRef("attribute(final)");
Guy Benyei11169dd2012-12-18 14:30:41 +00004821 case CXCursor_CXXOverrideAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004822 return cxstring::createRef("attribute(override)");
Guy Benyei11169dd2012-12-18 14:30:41 +00004823 case CXCursor_AnnotateAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004824 return cxstring::createRef("attribute(annotate)");
Guy Benyei11169dd2012-12-18 14:30:41 +00004825 case CXCursor_AsmLabelAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004826 return cxstring::createRef("asm label");
Argyrios Kyrtzidis16834f12013-09-25 00:14:38 +00004827 case CXCursor_PackedAttr:
4828 return cxstring::createRef("attribute(packed)");
Joey Gouly81228382014-05-01 15:41:58 +00004829 case CXCursor_PureAttr:
4830 return cxstring::createRef("attribute(pure)");
4831 case CXCursor_ConstAttr:
4832 return cxstring::createRef("attribute(const)");
4833 case CXCursor_NoDuplicateAttr:
4834 return cxstring::createRef("attribute(noduplicate)");
Eli Bendersky2581e662014-05-28 19:29:58 +00004835 case CXCursor_CUDAConstantAttr:
4836 return cxstring::createRef("attribute(constant)");
4837 case CXCursor_CUDADeviceAttr:
4838 return cxstring::createRef("attribute(device)");
4839 case CXCursor_CUDAGlobalAttr:
4840 return cxstring::createRef("attribute(global)");
4841 case CXCursor_CUDAHostAttr:
4842 return cxstring::createRef("attribute(host)");
Eli Bendersky9b071472014-08-08 14:59:00 +00004843 case CXCursor_CUDASharedAttr:
4844 return cxstring::createRef("attribute(shared)");
Saleem Abdulrasool79c69712015-09-05 18:53:43 +00004845 case CXCursor_VisibilityAttr:
4846 return cxstring::createRef("attribute(visibility)");
Saleem Abdulrasool8aa0b802015-12-10 18:45:18 +00004847 case CXCursor_DLLExport:
4848 return cxstring::createRef("attribute(dllexport)");
4849 case CXCursor_DLLImport:
4850 return cxstring::createRef("attribute(dllimport)");
Guy Benyei11169dd2012-12-18 14:30:41 +00004851 case CXCursor_PreprocessingDirective:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004852 return cxstring::createRef("preprocessing directive");
Guy Benyei11169dd2012-12-18 14:30:41 +00004853 case CXCursor_MacroDefinition:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004854 return cxstring::createRef("macro definition");
Guy Benyei11169dd2012-12-18 14:30:41 +00004855 case CXCursor_MacroExpansion:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004856 return cxstring::createRef("macro expansion");
Guy Benyei11169dd2012-12-18 14:30:41 +00004857 case CXCursor_InclusionDirective:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004858 return cxstring::createRef("inclusion directive");
Guy Benyei11169dd2012-12-18 14:30:41 +00004859 case CXCursor_Namespace:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004860 return cxstring::createRef("Namespace");
Guy Benyei11169dd2012-12-18 14:30:41 +00004861 case CXCursor_LinkageSpec:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004862 return cxstring::createRef("LinkageSpec");
Guy Benyei11169dd2012-12-18 14:30:41 +00004863 case CXCursor_CXXBaseSpecifier:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004864 return cxstring::createRef("C++ base class specifier");
Guy Benyei11169dd2012-12-18 14:30:41 +00004865 case CXCursor_Constructor:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004866 return cxstring::createRef("CXXConstructor");
Guy Benyei11169dd2012-12-18 14:30:41 +00004867 case CXCursor_Destructor:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004868 return cxstring::createRef("CXXDestructor");
Guy Benyei11169dd2012-12-18 14:30:41 +00004869 case CXCursor_ConversionFunction:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004870 return cxstring::createRef("CXXConversion");
Guy Benyei11169dd2012-12-18 14:30:41 +00004871 case CXCursor_TemplateTypeParameter:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004872 return cxstring::createRef("TemplateTypeParameter");
Guy Benyei11169dd2012-12-18 14:30:41 +00004873 case CXCursor_NonTypeTemplateParameter:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004874 return cxstring::createRef("NonTypeTemplateParameter");
Guy Benyei11169dd2012-12-18 14:30:41 +00004875 case CXCursor_TemplateTemplateParameter:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004876 return cxstring::createRef("TemplateTemplateParameter");
Guy Benyei11169dd2012-12-18 14:30:41 +00004877 case CXCursor_FunctionTemplate:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004878 return cxstring::createRef("FunctionTemplate");
Guy Benyei11169dd2012-12-18 14:30:41 +00004879 case CXCursor_ClassTemplate:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004880 return cxstring::createRef("ClassTemplate");
Guy Benyei11169dd2012-12-18 14:30:41 +00004881 case CXCursor_ClassTemplatePartialSpecialization:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004882 return cxstring::createRef("ClassTemplatePartialSpecialization");
Guy Benyei11169dd2012-12-18 14:30:41 +00004883 case CXCursor_NamespaceAlias:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004884 return cxstring::createRef("NamespaceAlias");
Guy Benyei11169dd2012-12-18 14:30:41 +00004885 case CXCursor_UsingDirective:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004886 return cxstring::createRef("UsingDirective");
Guy Benyei11169dd2012-12-18 14:30:41 +00004887 case CXCursor_UsingDeclaration:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004888 return cxstring::createRef("UsingDeclaration");
Guy Benyei11169dd2012-12-18 14:30:41 +00004889 case CXCursor_TypeAliasDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004890 return cxstring::createRef("TypeAliasDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004891 case CXCursor_ObjCSynthesizeDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004892 return cxstring::createRef("ObjCSynthesizeDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004893 case CXCursor_ObjCDynamicDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004894 return cxstring::createRef("ObjCDynamicDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004895 case CXCursor_CXXAccessSpecifier:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004896 return cxstring::createRef("CXXAccessSpecifier");
Guy Benyei11169dd2012-12-18 14:30:41 +00004897 case CXCursor_ModuleImportDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004898 return cxstring::createRef("ModuleImport");
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004899 case CXCursor_OMPParallelDirective:
Alexey Bataev1b59ab52014-02-27 08:29:12 +00004900 return cxstring::createRef("OMPParallelDirective");
4901 case CXCursor_OMPSimdDirective:
4902 return cxstring::createRef("OMPSimdDirective");
Alexey Bataevf29276e2014-06-18 04:14:57 +00004903 case CXCursor_OMPForDirective:
4904 return cxstring::createRef("OMPForDirective");
Alexander Musmanf82886e2014-09-18 05:12:34 +00004905 case CXCursor_OMPForSimdDirective:
4906 return cxstring::createRef("OMPForSimdDirective");
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004907 case CXCursor_OMPSectionsDirective:
4908 return cxstring::createRef("OMPSectionsDirective");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004909 case CXCursor_OMPSectionDirective:
4910 return cxstring::createRef("OMPSectionDirective");
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00004911 case CXCursor_OMPSingleDirective:
4912 return cxstring::createRef("OMPSingleDirective");
Alexander Musman80c22892014-07-17 08:54:58 +00004913 case CXCursor_OMPMasterDirective:
4914 return cxstring::createRef("OMPMasterDirective");
Alexander Musmand9ed09f2014-07-21 09:42:05 +00004915 case CXCursor_OMPCriticalDirective:
4916 return cxstring::createRef("OMPCriticalDirective");
Alexey Bataev4acb8592014-07-07 13:01:15 +00004917 case CXCursor_OMPParallelForDirective:
4918 return cxstring::createRef("OMPParallelForDirective");
Alexander Musmane4e893b2014-09-23 09:33:00 +00004919 case CXCursor_OMPParallelForSimdDirective:
4920 return cxstring::createRef("OMPParallelForSimdDirective");
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004921 case CXCursor_OMPParallelSectionsDirective:
4922 return cxstring::createRef("OMPParallelSectionsDirective");
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004923 case CXCursor_OMPTaskDirective:
4924 return cxstring::createRef("OMPTaskDirective");
Alexey Bataev68446b72014-07-18 07:47:19 +00004925 case CXCursor_OMPTaskyieldDirective:
4926 return cxstring::createRef("OMPTaskyieldDirective");
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00004927 case CXCursor_OMPBarrierDirective:
4928 return cxstring::createRef("OMPBarrierDirective");
Alexey Bataev2df347a2014-07-18 10:17:07 +00004929 case CXCursor_OMPTaskwaitDirective:
4930 return cxstring::createRef("OMPTaskwaitDirective");
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00004931 case CXCursor_OMPTaskgroupDirective:
4932 return cxstring::createRef("OMPTaskgroupDirective");
Alexey Bataev6125da92014-07-21 11:26:11 +00004933 case CXCursor_OMPFlushDirective:
4934 return cxstring::createRef("OMPFlushDirective");
Alexey Bataev9fb6e642014-07-22 06:45:04 +00004935 case CXCursor_OMPOrderedDirective:
4936 return cxstring::createRef("OMPOrderedDirective");
Alexey Bataev0162e452014-07-22 10:10:35 +00004937 case CXCursor_OMPAtomicDirective:
4938 return cxstring::createRef("OMPAtomicDirective");
Alexey Bataev0bd520b2014-09-19 08:19:49 +00004939 case CXCursor_OMPTargetDirective:
4940 return cxstring::createRef("OMPTargetDirective");
Michael Wong65f367f2015-07-21 13:44:28 +00004941 case CXCursor_OMPTargetDataDirective:
4942 return cxstring::createRef("OMPTargetDataDirective");
Samuel Antaodf67fc42016-01-19 19:15:56 +00004943 case CXCursor_OMPTargetEnterDataDirective:
4944 return cxstring::createRef("OMPTargetEnterDataDirective");
Samuel Antao72590762016-01-19 20:04:50 +00004945 case CXCursor_OMPTargetExitDataDirective:
4946 return cxstring::createRef("OMPTargetExitDataDirective");
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00004947 case CXCursor_OMPTargetParallelDirective:
4948 return cxstring::createRef("OMPTargetParallelDirective");
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00004949 case CXCursor_OMPTargetParallelForDirective:
4950 return cxstring::createRef("OMPTargetParallelForDirective");
Samuel Antao686c70c2016-05-26 17:30:50 +00004951 case CXCursor_OMPTargetUpdateDirective:
4952 return cxstring::createRef("OMPTargetUpdateDirective");
Alexey Bataev13314bf2014-10-09 04:18:56 +00004953 case CXCursor_OMPTeamsDirective:
4954 return cxstring::createRef("OMPTeamsDirective");
Alexey Bataev6d4ed052015-07-01 06:57:41 +00004955 case CXCursor_OMPCancellationPointDirective:
4956 return cxstring::createRef("OMPCancellationPointDirective");
Alexey Bataev80909872015-07-02 11:25:17 +00004957 case CXCursor_OMPCancelDirective:
4958 return cxstring::createRef("OMPCancelDirective");
Alexey Bataev49f6e782015-12-01 04:18:41 +00004959 case CXCursor_OMPTaskLoopDirective:
4960 return cxstring::createRef("OMPTaskLoopDirective");
Alexey Bataev0a6ed842015-12-03 09:40:15 +00004961 case CXCursor_OMPTaskLoopSimdDirective:
4962 return cxstring::createRef("OMPTaskLoopSimdDirective");
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004963 case CXCursor_OMPDistributeDirective:
4964 return cxstring::createRef("OMPDistributeDirective");
Carlo Bertolli9925f152016-06-27 14:55:37 +00004965 case CXCursor_OMPDistributeParallelForDirective:
4966 return cxstring::createRef("OMPDistributeParallelForDirective");
Kelvin Li4a39add2016-07-05 05:00:15 +00004967 case CXCursor_OMPDistributeParallelForSimdDirective:
4968 return cxstring::createRef("OMPDistributeParallelForSimdDirective");
Kelvin Li787f3fc2016-07-06 04:45:38 +00004969 case CXCursor_OMPDistributeSimdDirective:
4970 return cxstring::createRef("OMPDistributeSimdDirective");
Kelvin Lia579b912016-07-14 02:54:56 +00004971 case CXCursor_OMPTargetParallelForSimdDirective:
4972 return cxstring::createRef("OMPTargetParallelForSimdDirective");
Kelvin Li986330c2016-07-20 22:57:10 +00004973 case CXCursor_OMPTargetSimdDirective:
4974 return cxstring::createRef("OMPTargetSimdDirective");
Kelvin Li02532872016-08-05 14:37:37 +00004975 case CXCursor_OMPTeamsDistributeDirective:
4976 return cxstring::createRef("OMPTeamsDistributeDirective");
Kelvin Li4e325f72016-10-25 12:50:55 +00004977 case CXCursor_OMPTeamsDistributeSimdDirective:
4978 return cxstring::createRef("OMPTeamsDistributeSimdDirective");
Kelvin Li579e41c2016-11-30 23:51:03 +00004979 case CXCursor_OMPTeamsDistributeParallelForSimdDirective:
4980 return cxstring::createRef("OMPTeamsDistributeParallelForSimdDirective");
Kelvin Li7ade93f2016-12-09 03:24:30 +00004981 case CXCursor_OMPTeamsDistributeParallelForDirective:
4982 return cxstring::createRef("OMPTeamsDistributeParallelForDirective");
Kelvin Libf594a52016-12-17 05:48:59 +00004983 case CXCursor_OMPTargetTeamsDirective:
4984 return cxstring::createRef("OMPTargetTeamsDirective");
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00004985 case CXCursor_OverloadCandidate:
4986 return cxstring::createRef("OverloadCandidate");
Sergey Kalinichev8f3b1872015-11-15 13:48:32 +00004987 case CXCursor_TypeAliasTemplateDecl:
4988 return cxstring::createRef("TypeAliasTemplateDecl");
Olivier Goffart81978012016-06-09 16:15:55 +00004989 case CXCursor_StaticAssert:
4990 return cxstring::createRef("StaticAssert");
Olivier Goffartd211c642016-11-04 06:29:27 +00004991 case CXCursor_FriendDecl:
4992 return cxstring::createRef("FriendDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004993 }
4994
4995 llvm_unreachable("Unhandled CXCursorKind");
4996}
4997
4998struct GetCursorData {
4999 SourceLocation TokenBeginLoc;
5000 bool PointsAtMacroArgExpansion;
5001 bool VisitedObjCPropertyImplDecl;
5002 SourceLocation VisitedDeclaratorDeclStartLoc;
5003 CXCursor &BestCursor;
5004
5005 GetCursorData(SourceManager &SM,
5006 SourceLocation tokenBegin, CXCursor &outputCursor)
5007 : TokenBeginLoc(tokenBegin), BestCursor(outputCursor) {
5008 PointsAtMacroArgExpansion = SM.isMacroArgExpansion(tokenBegin);
5009 VisitedObjCPropertyImplDecl = false;
5010 }
5011};
5012
5013static enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
5014 CXCursor parent,
5015 CXClientData client_data) {
5016 GetCursorData *Data = static_cast<GetCursorData *>(client_data);
5017 CXCursor *BestCursor = &Data->BestCursor;
5018
5019 // If we point inside a macro argument we should provide info of what the
5020 // token is so use the actual cursor, don't replace it with a macro expansion
5021 // cursor.
5022 if (cursor.kind == CXCursor_MacroExpansion && Data->PointsAtMacroArgExpansion)
5023 return CXChildVisit_Recurse;
5024
5025 if (clang_isDeclaration(cursor.kind)) {
5026 // Avoid having the implicit methods override the property decls.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005027 if (const ObjCMethodDecl *MD
Guy Benyei11169dd2012-12-18 14:30:41 +00005028 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
5029 if (MD->isImplicit())
5030 return CXChildVisit_Break;
5031
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005032 } else if (const ObjCInterfaceDecl *ID
Guy Benyei11169dd2012-12-18 14:30:41 +00005033 = dyn_cast_or_null<ObjCInterfaceDecl>(getCursorDecl(cursor))) {
5034 // Check that when we have multiple @class references in the same line,
5035 // that later ones do not override the previous ones.
5036 // If we have:
5037 // @class Foo, Bar;
5038 // source ranges for both start at '@', so 'Bar' will end up overriding
5039 // 'Foo' even though the cursor location was at 'Foo'.
5040 if (BestCursor->kind == CXCursor_ObjCInterfaceDecl ||
5041 BestCursor->kind == CXCursor_ObjCClassRef)
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005042 if (const ObjCInterfaceDecl *PrevID
Guy Benyei11169dd2012-12-18 14:30:41 +00005043 = dyn_cast_or_null<ObjCInterfaceDecl>(getCursorDecl(*BestCursor))){
5044 if (PrevID != ID &&
5045 !PrevID->isThisDeclarationADefinition() &&
5046 !ID->isThisDeclarationADefinition())
5047 return CXChildVisit_Break;
5048 }
5049
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005050 } else if (const DeclaratorDecl *DD
Guy Benyei11169dd2012-12-18 14:30:41 +00005051 = dyn_cast_or_null<DeclaratorDecl>(getCursorDecl(cursor))) {
5052 SourceLocation StartLoc = DD->getSourceRange().getBegin();
5053 // Check that when we have multiple declarators in the same line,
5054 // that later ones do not override the previous ones.
5055 // If we have:
5056 // int Foo, Bar;
5057 // source ranges for both start at 'int', so 'Bar' will end up overriding
5058 // 'Foo' even though the cursor location was at 'Foo'.
5059 if (Data->VisitedDeclaratorDeclStartLoc == StartLoc)
5060 return CXChildVisit_Break;
5061 Data->VisitedDeclaratorDeclStartLoc = StartLoc;
5062
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005063 } else if (const ObjCPropertyImplDecl *PropImp
Guy Benyei11169dd2012-12-18 14:30:41 +00005064 = dyn_cast_or_null<ObjCPropertyImplDecl>(getCursorDecl(cursor))) {
5065 (void)PropImp;
5066 // Check that when we have multiple @synthesize in the same line,
5067 // that later ones do not override the previous ones.
5068 // If we have:
5069 // @synthesize Foo, Bar;
5070 // source ranges for both start at '@', so 'Bar' will end up overriding
5071 // 'Foo' even though the cursor location was at 'Foo'.
5072 if (Data->VisitedObjCPropertyImplDecl)
5073 return CXChildVisit_Break;
5074 Data->VisitedObjCPropertyImplDecl = true;
5075 }
5076 }
5077
5078 if (clang_isExpression(cursor.kind) &&
5079 clang_isDeclaration(BestCursor->kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005080 if (const Decl *D = getCursorDecl(*BestCursor)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005081 // Avoid having the cursor of an expression replace the declaration cursor
5082 // when the expression source range overlaps the declaration range.
5083 // This can happen for C++ constructor expressions whose range generally
5084 // include the variable declaration, e.g.:
5085 // MyCXXClass foo; // Make sure pointing at 'foo' returns a VarDecl cursor.
5086 if (D->getLocation().isValid() && Data->TokenBeginLoc.isValid() &&
5087 D->getLocation() == Data->TokenBeginLoc)
5088 return CXChildVisit_Break;
5089 }
5090 }
5091
5092 // If our current best cursor is the construction of a temporary object,
5093 // don't replace that cursor with a type reference, because we want
5094 // clang_getCursor() to point at the constructor.
5095 if (clang_isExpression(BestCursor->kind) &&
5096 isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
5097 cursor.kind == CXCursor_TypeRef) {
5098 // Keep the cursor pointing at CXXTemporaryObjectExpr but also mark it
5099 // as having the actual point on the type reference.
5100 *BestCursor = getTypeRefedCallExprCursor(*BestCursor);
5101 return CXChildVisit_Recurse;
5102 }
Douglas Gregore9d95f12015-07-07 03:57:35 +00005103
5104 // If we already have an Objective-C superclass reference, don't
5105 // update it further.
5106 if (BestCursor->kind == CXCursor_ObjCSuperClassRef)
5107 return CXChildVisit_Break;
5108
Guy Benyei11169dd2012-12-18 14:30:41 +00005109 *BestCursor = cursor;
5110 return CXChildVisit_Recurse;
5111}
5112
5113CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00005114 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00005115 LOG_BAD_TU(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00005116 return clang_getNullCursor();
Dmitri Gribenko256454f2014-02-11 14:34:14 +00005117 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005118
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00005119 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00005120 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
5121
5122 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
5123 CXCursor Result = cxcursor::getCursor(TU, SLoc);
5124
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005125 LOG_FUNC_SECTION {
Guy Benyei11169dd2012-12-18 14:30:41 +00005126 CXFile SearchFile;
5127 unsigned SearchLine, SearchColumn;
5128 CXFile ResultFile;
5129 unsigned ResultLine, ResultColumn;
5130 CXString SearchFileName, ResultFileName, KindSpelling, USR;
5131 const char *IsDef = clang_isCursorDefinition(Result)? " (Definition)" : "";
5132 CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
Craig Topper69186e72014-06-08 08:38:04 +00005133
5134 clang_getFileLocation(Loc, &SearchFile, &SearchLine, &SearchColumn,
5135 nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005136 clang_getFileLocation(ResultLoc, &ResultFile, &ResultLine,
Craig Topper69186e72014-06-08 08:38:04 +00005137 &ResultColumn, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005138 SearchFileName = clang_getFileName(SearchFile);
5139 ResultFileName = clang_getFileName(ResultFile);
5140 KindSpelling = clang_getCursorKindSpelling(Result.kind);
5141 USR = clang_getCursorUSR(Result);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005142 *Log << llvm::format("(%s:%d:%d) = %s",
5143 clang_getCString(SearchFileName), SearchLine, SearchColumn,
5144 clang_getCString(KindSpelling))
5145 << llvm::format("(%s:%d:%d):%s%s",
5146 clang_getCString(ResultFileName), ResultLine, ResultColumn,
5147 clang_getCString(USR), IsDef);
Guy Benyei11169dd2012-12-18 14:30:41 +00005148 clang_disposeString(SearchFileName);
5149 clang_disposeString(ResultFileName);
5150 clang_disposeString(KindSpelling);
5151 clang_disposeString(USR);
5152
5153 CXCursor Definition = clang_getCursorDefinition(Result);
5154 if (!clang_equalCursors(Definition, clang_getNullCursor())) {
5155 CXSourceLocation DefinitionLoc = clang_getCursorLocation(Definition);
5156 CXString DefinitionKindSpelling
5157 = clang_getCursorKindSpelling(Definition.kind);
5158 CXFile DefinitionFile;
5159 unsigned DefinitionLine, DefinitionColumn;
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005160 clang_getFileLocation(DefinitionLoc, &DefinitionFile,
Craig Topper69186e72014-06-08 08:38:04 +00005161 &DefinitionLine, &DefinitionColumn, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005162 CXString DefinitionFileName = clang_getFileName(DefinitionFile);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005163 *Log << llvm::format(" -> %s(%s:%d:%d)",
5164 clang_getCString(DefinitionKindSpelling),
5165 clang_getCString(DefinitionFileName),
5166 DefinitionLine, DefinitionColumn);
Guy Benyei11169dd2012-12-18 14:30:41 +00005167 clang_disposeString(DefinitionFileName);
5168 clang_disposeString(DefinitionKindSpelling);
5169 }
5170 }
5171
5172 return Result;
5173}
5174
5175CXCursor clang_getNullCursor(void) {
5176 return MakeCXCursorInvalid(CXCursor_InvalidFile);
5177}
5178
5179unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Argyrios Kyrtzidisbf1be592013-01-08 18:23:28 +00005180 // Clear out the "FirstInDeclGroup" part in a declaration cursor, since we
5181 // can't set consistently. For example, when visiting a DeclStmt we will set
5182 // it but we don't set it on the result of clang_getCursorDefinition for
5183 // a reference of the same declaration.
5184 // FIXME: Setting "FirstInDeclGroup" in CXCursors is a hack that only works
5185 // when visiting a DeclStmt currently, the AST should be enhanced to be able
5186 // to provide that kind of info.
5187 if (clang_isDeclaration(X.kind))
Craig Topper69186e72014-06-08 08:38:04 +00005188 X.data[1] = nullptr;
Argyrios Kyrtzidisbf1be592013-01-08 18:23:28 +00005189 if (clang_isDeclaration(Y.kind))
Craig Topper69186e72014-06-08 08:38:04 +00005190 Y.data[1] = nullptr;
Argyrios Kyrtzidisbf1be592013-01-08 18:23:28 +00005191
Guy Benyei11169dd2012-12-18 14:30:41 +00005192 return X == Y;
5193}
5194
5195unsigned clang_hashCursor(CXCursor C) {
5196 unsigned Index = 0;
5197 if (clang_isExpression(C.kind) || clang_isStatement(C.kind))
5198 Index = 1;
5199
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005200 return llvm::DenseMapInfo<std::pair<unsigned, const void*> >::getHashValue(
Guy Benyei11169dd2012-12-18 14:30:41 +00005201 std::make_pair(C.kind, C.data[Index]));
5202}
5203
5204unsigned clang_isInvalid(enum CXCursorKind K) {
5205 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
5206}
5207
5208unsigned clang_isDeclaration(enum CXCursorKind K) {
5209 return (K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl) ||
5210 (K >= CXCursor_FirstExtraDecl && K <= CXCursor_LastExtraDecl);
5211}
5212
5213unsigned clang_isReference(enum CXCursorKind K) {
5214 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
5215}
5216
5217unsigned clang_isExpression(enum CXCursorKind K) {
5218 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
5219}
5220
5221unsigned clang_isStatement(enum CXCursorKind K) {
5222 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
5223}
5224
5225unsigned clang_isAttribute(enum CXCursorKind K) {
5226 return K >= CXCursor_FirstAttr && K <= CXCursor_LastAttr;
5227}
5228
5229unsigned clang_isTranslationUnit(enum CXCursorKind K) {
5230 return K == CXCursor_TranslationUnit;
5231}
5232
5233unsigned clang_isPreprocessing(enum CXCursorKind K) {
5234 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
5235}
5236
5237unsigned clang_isUnexposed(enum CXCursorKind K) {
5238 switch (K) {
5239 case CXCursor_UnexposedDecl:
5240 case CXCursor_UnexposedExpr:
5241 case CXCursor_UnexposedStmt:
5242 case CXCursor_UnexposedAttr:
5243 return true;
5244 default:
5245 return false;
5246 }
5247}
5248
5249CXCursorKind clang_getCursorKind(CXCursor C) {
5250 return C.kind;
5251}
5252
5253CXSourceLocation clang_getCursorLocation(CXCursor C) {
5254 if (clang_isReference(C.kind)) {
5255 switch (C.kind) {
5256 case CXCursor_ObjCSuperClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005257 std::pair<const ObjCInterfaceDecl *, SourceLocation> P
Guy Benyei11169dd2012-12-18 14:30:41 +00005258 = getCursorObjCSuperClassRef(C);
5259 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5260 }
5261
5262 case CXCursor_ObjCProtocolRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005263 std::pair<const ObjCProtocolDecl *, SourceLocation> P
Guy Benyei11169dd2012-12-18 14:30:41 +00005264 = getCursorObjCProtocolRef(C);
5265 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5266 }
5267
5268 case CXCursor_ObjCClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005269 std::pair<const ObjCInterfaceDecl *, SourceLocation> P
Guy Benyei11169dd2012-12-18 14:30:41 +00005270 = getCursorObjCClassRef(C);
5271 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5272 }
5273
5274 case CXCursor_TypeRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005275 std::pair<const TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005276 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5277 }
5278
5279 case CXCursor_TemplateRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005280 std::pair<const TemplateDecl *, SourceLocation> P =
5281 getCursorTemplateRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005282 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5283 }
5284
5285 case CXCursor_NamespaceRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005286 std::pair<const NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005287 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5288 }
5289
5290 case CXCursor_MemberRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005291 std::pair<const FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005292 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5293 }
5294
5295 case CXCursor_VariableRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005296 std::pair<const VarDecl *, SourceLocation> P = getCursorVariableRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005297 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5298 }
5299
5300 case CXCursor_CXXBaseSpecifier: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005301 const CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005302 if (!BaseSpec)
5303 return clang_getNullLocation();
5304
5305 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
5306 return cxloc::translateSourceLocation(getCursorContext(C),
5307 TSInfo->getTypeLoc().getBeginLoc());
5308
5309 return cxloc::translateSourceLocation(getCursorContext(C),
5310 BaseSpec->getLocStart());
5311 }
5312
5313 case CXCursor_LabelRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005314 std::pair<const LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005315 return cxloc::translateSourceLocation(getCursorContext(C), P.second);
5316 }
5317
5318 case CXCursor_OverloadedDeclRef:
5319 return cxloc::translateSourceLocation(getCursorContext(C),
5320 getCursorOverloadedDeclRef(C).second);
5321
5322 default:
5323 // FIXME: Need a way to enumerate all non-reference cases.
5324 llvm_unreachable("Missed a reference kind");
5325 }
5326 }
5327
5328 if (clang_isExpression(C.kind))
5329 return cxloc::translateSourceLocation(getCursorContext(C),
5330 getLocationFromExpr(getCursorExpr(C)));
5331
5332 if (clang_isStatement(C.kind))
5333 return cxloc::translateSourceLocation(getCursorContext(C),
5334 getCursorStmt(C)->getLocStart());
5335
5336 if (C.kind == CXCursor_PreprocessingDirective) {
5337 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
5338 return cxloc::translateSourceLocation(getCursorContext(C), L);
5339 }
5340
5341 if (C.kind == CXCursor_MacroExpansion) {
5342 SourceLocation L
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00005343 = cxcursor::getCursorMacroExpansion(C).getSourceRange().getBegin();
Guy Benyei11169dd2012-12-18 14:30:41 +00005344 return cxloc::translateSourceLocation(getCursorContext(C), L);
5345 }
5346
5347 if (C.kind == CXCursor_MacroDefinition) {
5348 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
5349 return cxloc::translateSourceLocation(getCursorContext(C), L);
5350 }
5351
5352 if (C.kind == CXCursor_InclusionDirective) {
5353 SourceLocation L
5354 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
5355 return cxloc::translateSourceLocation(getCursorContext(C), L);
5356 }
5357
Argyrios Kyrtzidis16834f12013-09-25 00:14:38 +00005358 if (clang_isAttribute(C.kind)) {
5359 SourceLocation L
5360 = cxcursor::getCursorAttr(C)->getLocation();
5361 return cxloc::translateSourceLocation(getCursorContext(C), L);
5362 }
5363
Guy Benyei11169dd2012-12-18 14:30:41 +00005364 if (!clang_isDeclaration(C.kind))
5365 return clang_getNullLocation();
5366
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005367 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005368 if (!D)
5369 return clang_getNullLocation();
5370
5371 SourceLocation Loc = D->getLocation();
5372 // FIXME: Multiple variables declared in a single declaration
5373 // currently lack the information needed to correctly determine their
5374 // ranges when accounting for the type-specifier. We use context
5375 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
5376 // and if so, whether it is the first decl.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005377 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005378 if (!cxcursor::isFirstInDeclGroup(C))
5379 Loc = VD->getLocation();
5380 }
5381
5382 // For ObjC methods, give the start location of the method name.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005383 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00005384 Loc = MD->getSelectorStartLoc();
5385
5386 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
5387}
5388
NAKAMURA Takumia01f4c32016-12-19 16:50:43 +00005389} // end extern "C"
5390
Guy Benyei11169dd2012-12-18 14:30:41 +00005391CXCursor cxcursor::getCursor(CXTranslationUnit TU, SourceLocation SLoc) {
5392 assert(TU);
5393
5394 // Guard against an invalid SourceLocation, or we may assert in one
5395 // of the following calls.
5396 if (SLoc.isInvalid())
5397 return clang_getNullCursor();
5398
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00005399 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00005400
5401 // Translate the given source location to make it point at the beginning of
5402 // the token under the cursor.
5403 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
5404 CXXUnit->getASTContext().getLangOpts());
5405
5406 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
5407 if (SLoc.isValid()) {
5408 GetCursorData ResultData(CXXUnit->getSourceManager(), SLoc, Result);
5409 CursorVisitor CursorVis(TU, GetCursorVisitor, &ResultData,
5410 /*VisitPreprocessorLast=*/true,
5411 /*VisitIncludedEntities=*/false,
5412 SourceLocation(SLoc));
5413 CursorVis.visitFileRegion();
5414 }
5415
5416 return Result;
5417}
5418
5419static SourceRange getRawCursorExtent(CXCursor C) {
5420 if (clang_isReference(C.kind)) {
5421 switch (C.kind) {
5422 case CXCursor_ObjCSuperClassRef:
5423 return getCursorObjCSuperClassRef(C).second;
5424
5425 case CXCursor_ObjCProtocolRef:
5426 return getCursorObjCProtocolRef(C).second;
5427
5428 case CXCursor_ObjCClassRef:
5429 return getCursorObjCClassRef(C).second;
5430
5431 case CXCursor_TypeRef:
5432 return getCursorTypeRef(C).second;
5433
5434 case CXCursor_TemplateRef:
5435 return getCursorTemplateRef(C).second;
5436
5437 case CXCursor_NamespaceRef:
5438 return getCursorNamespaceRef(C).second;
5439
5440 case CXCursor_MemberRef:
5441 return getCursorMemberRef(C).second;
5442
5443 case CXCursor_CXXBaseSpecifier:
5444 return getCursorCXXBaseSpecifier(C)->getSourceRange();
5445
5446 case CXCursor_LabelRef:
5447 return getCursorLabelRef(C).second;
5448
5449 case CXCursor_OverloadedDeclRef:
5450 return getCursorOverloadedDeclRef(C).second;
5451
5452 case CXCursor_VariableRef:
5453 return getCursorVariableRef(C).second;
5454
5455 default:
5456 // FIXME: Need a way to enumerate all non-reference cases.
5457 llvm_unreachable("Missed a reference kind");
5458 }
5459 }
5460
5461 if (clang_isExpression(C.kind))
5462 return getCursorExpr(C)->getSourceRange();
5463
5464 if (clang_isStatement(C.kind))
5465 return getCursorStmt(C)->getSourceRange();
5466
5467 if (clang_isAttribute(C.kind))
5468 return getCursorAttr(C)->getRange();
5469
5470 if (C.kind == CXCursor_PreprocessingDirective)
5471 return cxcursor::getCursorPreprocessingDirective(C);
5472
5473 if (C.kind == CXCursor_MacroExpansion) {
5474 ASTUnit *TU = getCursorASTUnit(C);
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00005475 SourceRange Range = cxcursor::getCursorMacroExpansion(C).getSourceRange();
Guy Benyei11169dd2012-12-18 14:30:41 +00005476 return TU->mapRangeFromPreamble(Range);
5477 }
5478
5479 if (C.kind == CXCursor_MacroDefinition) {
5480 ASTUnit *TU = getCursorASTUnit(C);
5481 SourceRange Range = cxcursor::getCursorMacroDefinition(C)->getSourceRange();
5482 return TU->mapRangeFromPreamble(Range);
5483 }
5484
5485 if (C.kind == CXCursor_InclusionDirective) {
5486 ASTUnit *TU = getCursorASTUnit(C);
5487 SourceRange Range = cxcursor::getCursorInclusionDirective(C)->getSourceRange();
5488 return TU->mapRangeFromPreamble(Range);
5489 }
5490
5491 if (C.kind == CXCursor_TranslationUnit) {
5492 ASTUnit *TU = getCursorASTUnit(C);
5493 FileID MainID = TU->getSourceManager().getMainFileID();
5494 SourceLocation Start = TU->getSourceManager().getLocForStartOfFile(MainID);
5495 SourceLocation End = TU->getSourceManager().getLocForEndOfFile(MainID);
5496 return SourceRange(Start, End);
5497 }
5498
5499 if (clang_isDeclaration(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005500 const Decl *D = cxcursor::getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005501 if (!D)
5502 return SourceRange();
5503
5504 SourceRange R = D->getSourceRange();
5505 // FIXME: Multiple variables declared in a single declaration
5506 // currently lack the information needed to correctly determine their
5507 // ranges when accounting for the type-specifier. We use context
5508 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
5509 // and if so, whether it is the first decl.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005510 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005511 if (!cxcursor::isFirstInDeclGroup(C))
5512 R.setBegin(VD->getLocation());
5513 }
5514 return R;
5515 }
5516 return SourceRange();
5517}
5518
5519/// \brief Retrieves the "raw" cursor extent, which is then extended to include
5520/// the decl-specifier-seq for declarations.
5521static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr) {
5522 if (clang_isDeclaration(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005523 const Decl *D = cxcursor::getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005524 if (!D)
5525 return SourceRange();
5526
5527 SourceRange R = D->getSourceRange();
5528
5529 // Adjust the start of the location for declarations preceded by
5530 // declaration specifiers.
5531 SourceLocation StartLoc;
5532 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
5533 if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
5534 StartLoc = TI->getTypeLoc().getLocStart();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005535 } else if (const TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005536 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
5537 StartLoc = TI->getTypeLoc().getLocStart();
5538 }
5539
5540 if (StartLoc.isValid() && R.getBegin().isValid() &&
5541 SrcMgr.isBeforeInTranslationUnit(StartLoc, R.getBegin()))
5542 R.setBegin(StartLoc);
5543
5544 // FIXME: Multiple variables declared in a single declaration
5545 // currently lack the information needed to correctly determine their
5546 // ranges when accounting for the type-specifier. We use context
5547 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
5548 // and if so, whether it is the first decl.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005549 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005550 if (!cxcursor::isFirstInDeclGroup(C))
5551 R.setBegin(VD->getLocation());
5552 }
5553
5554 return R;
5555 }
5556
5557 return getRawCursorExtent(C);
5558}
5559
Guy Benyei11169dd2012-12-18 14:30:41 +00005560CXSourceRange clang_getCursorExtent(CXCursor C) {
5561 SourceRange R = getRawCursorExtent(C);
5562 if (R.isInvalid())
5563 return clang_getNullRange();
5564
5565 return cxloc::translateSourceRange(getCursorContext(C), R);
5566}
5567
5568CXCursor clang_getCursorReferenced(CXCursor C) {
5569 if (clang_isInvalid(C.kind))
5570 return clang_getNullCursor();
5571
5572 CXTranslationUnit tu = getCursorTU(C);
5573 if (clang_isDeclaration(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005574 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005575 if (!D)
5576 return clang_getNullCursor();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005577 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00005578 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), tu);
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005579 if (const ObjCPropertyImplDecl *PropImpl =
5580 dyn_cast<ObjCPropertyImplDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00005581 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
5582 return MakeCXCursor(Property, tu);
5583
5584 return C;
5585 }
5586
5587 if (clang_isExpression(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005588 const Expr *E = getCursorExpr(C);
5589 const Decl *D = getDeclFromExpr(E);
Guy Benyei11169dd2012-12-18 14:30:41 +00005590 if (D) {
5591 CXCursor declCursor = MakeCXCursor(D, tu);
5592 declCursor = getSelectorIdentifierCursor(getSelectorIdentifierIndex(C),
5593 declCursor);
5594 return declCursor;
5595 }
5596
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005597 if (const OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00005598 return MakeCursorOverloadedDeclRef(Ovl, tu);
5599
5600 return clang_getNullCursor();
5601 }
5602
5603 if (clang_isStatement(C.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00005604 const Stmt *S = getCursorStmt(C);
5605 if (const GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
Guy Benyei11169dd2012-12-18 14:30:41 +00005606 if (LabelDecl *label = Goto->getLabel())
5607 if (LabelStmt *labelS = label->getStmt())
5608 return MakeCXCursor(labelS, getCursorDecl(C), tu);
5609
5610 return clang_getNullCursor();
5611 }
Richard Smith66a81862015-05-04 02:25:31 +00005612
Guy Benyei11169dd2012-12-18 14:30:41 +00005613 if (C.kind == CXCursor_MacroExpansion) {
Richard Smith66a81862015-05-04 02:25:31 +00005614 if (const MacroDefinitionRecord *Def =
5615 getCursorMacroExpansion(C).getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00005616 return MakeMacroDefinitionCursor(Def, tu);
5617 }
5618
5619 if (!clang_isReference(C.kind))
5620 return clang_getNullCursor();
5621
5622 switch (C.kind) {
5623 case CXCursor_ObjCSuperClassRef:
5624 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, tu);
5625
5626 case CXCursor_ObjCProtocolRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005627 const ObjCProtocolDecl *Prot = getCursorObjCProtocolRef(C).first;
5628 if (const ObjCProtocolDecl *Def = Prot->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00005629 return MakeCXCursor(Def, tu);
5630
5631 return MakeCXCursor(Prot, tu);
5632 }
5633
5634 case CXCursor_ObjCClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005635 const ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
5636 if (const ObjCInterfaceDecl *Def = Class->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00005637 return MakeCXCursor(Def, tu);
5638
5639 return MakeCXCursor(Class, tu);
5640 }
5641
5642 case CXCursor_TypeRef:
5643 return MakeCXCursor(getCursorTypeRef(C).first, tu );
5644
5645 case CXCursor_TemplateRef:
5646 return MakeCXCursor(getCursorTemplateRef(C).first, tu );
5647
5648 case CXCursor_NamespaceRef:
5649 return MakeCXCursor(getCursorNamespaceRef(C).first, tu );
5650
5651 case CXCursor_MemberRef:
5652 return MakeCXCursor(getCursorMemberRef(C).first, tu );
5653
5654 case CXCursor_CXXBaseSpecifier: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005655 const CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005656 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
5657 tu ));
5658 }
5659
5660 case CXCursor_LabelRef:
5661 // FIXME: We end up faking the "parent" declaration here because we
5662 // don't want to make CXCursor larger.
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00005663 return MakeCXCursor(getCursorLabelRef(C).first,
5664 cxtu::getASTUnit(tu)->getASTContext()
5665 .getTranslationUnitDecl(),
Guy Benyei11169dd2012-12-18 14:30:41 +00005666 tu);
5667
5668 case CXCursor_OverloadedDeclRef:
5669 return C;
5670
5671 case CXCursor_VariableRef:
5672 return MakeCXCursor(getCursorVariableRef(C).first, tu);
5673
5674 default:
5675 // We would prefer to enumerate all non-reference cursor kinds here.
5676 llvm_unreachable("Unhandled reference cursor kind");
5677 }
5678}
5679
5680CXCursor clang_getCursorDefinition(CXCursor C) {
5681 if (clang_isInvalid(C.kind))
5682 return clang_getNullCursor();
5683
5684 CXTranslationUnit TU = getCursorTU(C);
5685
5686 bool WasReference = false;
5687 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
5688 C = clang_getCursorReferenced(C);
5689 WasReference = true;
5690 }
5691
5692 if (C.kind == CXCursor_MacroExpansion)
5693 return clang_getCursorReferenced(C);
5694
5695 if (!clang_isDeclaration(C.kind))
5696 return clang_getNullCursor();
5697
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005698 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005699 if (!D)
5700 return clang_getNullCursor();
5701
5702 switch (D->getKind()) {
5703 // Declaration kinds that don't really separate the notions of
5704 // declaration and definition.
5705 case Decl::Namespace:
5706 case Decl::Typedef:
5707 case Decl::TypeAlias:
5708 case Decl::TypeAliasTemplate:
5709 case Decl::TemplateTypeParm:
5710 case Decl::EnumConstant:
5711 case Decl::Field:
Richard Smithbdb84f32016-07-22 23:36:59 +00005712 case Decl::Binding:
John McCall5e77d762013-04-16 07:28:30 +00005713 case Decl::MSProperty:
Guy Benyei11169dd2012-12-18 14:30:41 +00005714 case Decl::IndirectField:
5715 case Decl::ObjCIvar:
5716 case Decl::ObjCAtDefsField:
5717 case Decl::ImplicitParam:
5718 case Decl::ParmVar:
5719 case Decl::NonTypeTemplateParm:
5720 case Decl::TemplateTemplateParm:
5721 case Decl::ObjCCategoryImpl:
5722 case Decl::ObjCImplementation:
5723 case Decl::AccessSpec:
5724 case Decl::LinkageSpec:
Richard Smith8df390f2016-09-08 23:14:54 +00005725 case Decl::Export:
Guy Benyei11169dd2012-12-18 14:30:41 +00005726 case Decl::ObjCPropertyImpl:
5727 case Decl::FileScopeAsm:
5728 case Decl::StaticAssert:
5729 case Decl::Block:
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00005730 case Decl::Captured:
Alexey Bataev4244be22016-02-11 05:35:55 +00005731 case Decl::OMPCapturedExpr:
Guy Benyei11169dd2012-12-18 14:30:41 +00005732 case Decl::Label: // FIXME: Is this right??
5733 case Decl::ClassScopeFunctionSpecialization:
5734 case Decl::Import:
Alexey Bataeva769e072013-03-22 06:34:35 +00005735 case Decl::OMPThreadPrivate:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00005736 case Decl::OMPDeclareReduction:
Douglas Gregor85f3f952015-07-07 03:57:15 +00005737 case Decl::ObjCTypeParam:
David Majnemerd9b1a4f2015-11-04 03:40:30 +00005738 case Decl::BuiltinTemplate:
Nico Weber66220292016-03-02 17:28:48 +00005739 case Decl::PragmaComment:
Nico Webercbbaeb12016-03-02 19:28:54 +00005740 case Decl::PragmaDetectMismatch:
Richard Smith151c4562016-12-20 21:35:28 +00005741 case Decl::UsingPack:
Guy Benyei11169dd2012-12-18 14:30:41 +00005742 return C;
5743
5744 // Declaration kinds that don't make any sense here, but are
5745 // nonetheless harmless.
David Blaikief005d3c2013-02-22 17:44:58 +00005746 case Decl::Empty:
Guy Benyei11169dd2012-12-18 14:30:41 +00005747 case Decl::TranslationUnit:
Richard Smithf19e1272015-03-07 00:04:49 +00005748 case Decl::ExternCContext:
Guy Benyei11169dd2012-12-18 14:30:41 +00005749 break;
5750
5751 // Declaration kinds for which the definition is not resolvable.
5752 case Decl::UnresolvedUsingTypename:
5753 case Decl::UnresolvedUsingValue:
5754 break;
5755
5756 case Decl::UsingDirective:
5757 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
5758 TU);
5759
5760 case Decl::NamespaceAlias:
5761 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), TU);
5762
5763 case Decl::Enum:
5764 case Decl::Record:
5765 case Decl::CXXRecord:
5766 case Decl::ClassTemplateSpecialization:
5767 case Decl::ClassTemplatePartialSpecialization:
5768 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
5769 return MakeCXCursor(Def, TU);
5770 return clang_getNullCursor();
5771
5772 case Decl::Function:
5773 case Decl::CXXMethod:
5774 case Decl::CXXConstructor:
5775 case Decl::CXXDestructor:
5776 case Decl::CXXConversion: {
Craig Topper69186e72014-06-08 08:38:04 +00005777 const FunctionDecl *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005778 if (cast<FunctionDecl>(D)->getBody(Def))
Dmitri Gribenko9c256e32013-01-14 00:46:27 +00005779 return MakeCXCursor(Def, TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00005780 return clang_getNullCursor();
5781 }
5782
Larisse Voufo39a1e502013-08-06 01:03:05 +00005783 case Decl::Var:
5784 case Decl::VarTemplateSpecialization:
Richard Smithbdb84f32016-07-22 23:36:59 +00005785 case Decl::VarTemplatePartialSpecialization:
5786 case Decl::Decomposition: {
Guy Benyei11169dd2012-12-18 14:30:41 +00005787 // Ask the variable if it has a definition.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005788 if (const VarDecl *Def = cast<VarDecl>(D)->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00005789 return MakeCXCursor(Def, TU);
5790 return clang_getNullCursor();
5791 }
5792
5793 case Decl::FunctionTemplate: {
Craig Topper69186e72014-06-08 08:38:04 +00005794 const FunctionDecl *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005795 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
5796 return MakeCXCursor(Def->getDescribedFunctionTemplate(), TU);
5797 return clang_getNullCursor();
5798 }
5799
5800 case Decl::ClassTemplate: {
5801 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
5802 ->getDefinition())
5803 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
5804 TU);
5805 return clang_getNullCursor();
5806 }
5807
Larisse Voufo39a1e502013-08-06 01:03:05 +00005808 case Decl::VarTemplate: {
5809 if (VarDecl *Def =
5810 cast<VarTemplateDecl>(D)->getTemplatedDecl()->getDefinition())
5811 return MakeCXCursor(cast<VarDecl>(Def)->getDescribedVarTemplate(), TU);
5812 return clang_getNullCursor();
5813 }
5814
Guy Benyei11169dd2012-12-18 14:30:41 +00005815 case Decl::Using:
5816 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
5817 D->getLocation(), TU);
5818
5819 case Decl::UsingShadow:
Richard Smith5179eb72016-06-28 19:03:57 +00005820 case Decl::ConstructorUsingShadow:
Guy Benyei11169dd2012-12-18 14:30:41 +00005821 return clang_getCursorDefinition(
5822 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
5823 TU));
5824
5825 case Decl::ObjCMethod: {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005826 const ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00005827 if (Method->isThisDeclarationADefinition())
5828 return C;
5829
5830 // Dig out the method definition in the associated
5831 // @implementation, if we have it.
5832 // FIXME: The ASTs should make finding the definition easier.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005833 if (const ObjCInterfaceDecl *Class
Guy Benyei11169dd2012-12-18 14:30:41 +00005834 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
5835 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
5836 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
5837 Method->isInstanceMethod()))
5838 if (Def->isThisDeclarationADefinition())
5839 return MakeCXCursor(Def, TU);
5840
5841 return clang_getNullCursor();
5842 }
5843
5844 case Decl::ObjCCategory:
5845 if (ObjCCategoryImplDecl *Impl
5846 = cast<ObjCCategoryDecl>(D)->getImplementation())
5847 return MakeCXCursor(Impl, TU);
5848 return clang_getNullCursor();
5849
5850 case Decl::ObjCProtocol:
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005851 if (const ObjCProtocolDecl *Def = cast<ObjCProtocolDecl>(D)->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00005852 return MakeCXCursor(Def, TU);
5853 return clang_getNullCursor();
5854
5855 case Decl::ObjCInterface: {
5856 // There are two notions of a "definition" for an Objective-C
5857 // class: the interface and its implementation. When we resolved a
5858 // reference to an Objective-C class, produce the @interface as
5859 // the definition; when we were provided with the interface,
5860 // produce the @implementation as the definition.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005861 const ObjCInterfaceDecl *IFace = cast<ObjCInterfaceDecl>(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00005862 if (WasReference) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005863 if (const ObjCInterfaceDecl *Def = IFace->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00005864 return MakeCXCursor(Def, TU);
5865 } else if (ObjCImplementationDecl *Impl = IFace->getImplementation())
5866 return MakeCXCursor(Impl, TU);
5867 return clang_getNullCursor();
5868 }
5869
5870 case Decl::ObjCProperty:
5871 // FIXME: We don't really know where to find the
5872 // ObjCPropertyImplDecls that implement this property.
5873 return clang_getNullCursor();
5874
5875 case Decl::ObjCCompatibleAlias:
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005876 if (const ObjCInterfaceDecl *Class
Guy Benyei11169dd2012-12-18 14:30:41 +00005877 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005878 if (const ObjCInterfaceDecl *Def = Class->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00005879 return MakeCXCursor(Def, TU);
5880
5881 return clang_getNullCursor();
5882
5883 case Decl::Friend:
5884 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
5885 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
5886 return clang_getNullCursor();
5887
5888 case Decl::FriendTemplate:
5889 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
5890 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
5891 return clang_getNullCursor();
5892 }
5893
5894 return clang_getNullCursor();
5895}
5896
5897unsigned clang_isCursorDefinition(CXCursor C) {
5898 if (!clang_isDeclaration(C.kind))
5899 return 0;
5900
5901 return clang_getCursorDefinition(C) == C;
5902}
5903
5904CXCursor clang_getCanonicalCursor(CXCursor C) {
5905 if (!clang_isDeclaration(C.kind))
5906 return C;
5907
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005908 if (const Decl *D = getCursorDecl(C)) {
5909 if (const ObjCCategoryImplDecl *CatImplD = dyn_cast<ObjCCategoryImplDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00005910 if (ObjCCategoryDecl *CatD = CatImplD->getCategoryDecl())
5911 return MakeCXCursor(CatD, getCursorTU(C));
5912
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005913 if (const ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
5914 if (const ObjCInterfaceDecl *IFD = ImplD->getClassInterface())
Guy Benyei11169dd2012-12-18 14:30:41 +00005915 return MakeCXCursor(IFD, getCursorTU(C));
5916
5917 return MakeCXCursor(D->getCanonicalDecl(), getCursorTU(C));
5918 }
5919
5920 return C;
5921}
5922
5923int clang_Cursor_getObjCSelectorIndex(CXCursor cursor) {
5924 return cxcursor::getSelectorIdentifierIndexAndLoc(cursor).first;
5925}
5926
5927unsigned clang_getNumOverloadedDecls(CXCursor C) {
5928 if (C.kind != CXCursor_OverloadedDeclRef)
5929 return 0;
5930
5931 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005932 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
Guy Benyei11169dd2012-12-18 14:30:41 +00005933 return E->getNumDecls();
5934
5935 if (OverloadedTemplateStorage *S
5936 = Storage.dyn_cast<OverloadedTemplateStorage*>())
5937 return S->size();
5938
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005939 const Decl *D = Storage.get<const Decl *>();
5940 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00005941 return Using->shadow_size();
5942
5943 return 0;
5944}
5945
5946CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
5947 if (cursor.kind != CXCursor_OverloadedDeclRef)
5948 return clang_getNullCursor();
5949
5950 if (index >= clang_getNumOverloadedDecls(cursor))
5951 return clang_getNullCursor();
5952
5953 CXTranslationUnit TU = getCursorTU(cursor);
5954 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005955 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
Guy Benyei11169dd2012-12-18 14:30:41 +00005956 return MakeCXCursor(E->decls_begin()[index], TU);
5957
5958 if (OverloadedTemplateStorage *S
5959 = Storage.dyn_cast<OverloadedTemplateStorage*>())
5960 return MakeCXCursor(S->begin()[index], TU);
5961
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005962 const Decl *D = Storage.get<const Decl *>();
5963 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005964 // FIXME: This is, unfortunately, linear time.
5965 UsingDecl::shadow_iterator Pos = Using->shadow_begin();
5966 std::advance(Pos, index);
5967 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), TU);
5968 }
5969
5970 return clang_getNullCursor();
5971}
5972
5973void clang_getDefinitionSpellingAndExtent(CXCursor C,
5974 const char **startBuf,
5975 const char **endBuf,
5976 unsigned *startLine,
5977 unsigned *startColumn,
5978 unsigned *endLine,
5979 unsigned *endColumn) {
5980 assert(getCursorDecl(C) && "CXCursor has null decl");
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005981 const FunctionDecl *FD = dyn_cast<FunctionDecl>(getCursorDecl(C));
Guy Benyei11169dd2012-12-18 14:30:41 +00005982 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
5983
5984 SourceManager &SM = FD->getASTContext().getSourceManager();
5985 *startBuf = SM.getCharacterData(Body->getLBracLoc());
5986 *endBuf = SM.getCharacterData(Body->getRBracLoc());
5987 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
5988 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
5989 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
5990 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
5991}
5992
5993
5994CXSourceRange clang_getCursorReferenceNameRange(CXCursor C, unsigned NameFlags,
5995 unsigned PieceIndex) {
5996 RefNamePieces Pieces;
5997
5998 switch (C.kind) {
5999 case CXCursor_MemberRefExpr:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006000 if (const MemberExpr *E = dyn_cast<MemberExpr>(getCursorExpr(C)))
Guy Benyei11169dd2012-12-18 14:30:41 +00006001 Pieces = buildPieces(NameFlags, true, E->getMemberNameInfo(),
6002 E->getQualifierLoc().getSourceRange());
6003 break;
6004
6005 case CXCursor_DeclRefExpr:
James Y Knight04ec5bf2015-12-24 02:59:37 +00006006 if (const DeclRefExpr *E = dyn_cast<DeclRefExpr>(getCursorExpr(C))) {
6007 SourceRange TemplateArgLoc(E->getLAngleLoc(), E->getRAngleLoc());
6008 Pieces =
6009 buildPieces(NameFlags, false, E->getNameInfo(),
6010 E->getQualifierLoc().getSourceRange(), &TemplateArgLoc);
6011 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006012 break;
6013
6014 case CXCursor_CallExpr:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006015 if (const CXXOperatorCallExpr *OCE =
Guy Benyei11169dd2012-12-18 14:30:41 +00006016 dyn_cast<CXXOperatorCallExpr>(getCursorExpr(C))) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006017 const Expr *Callee = OCE->getCallee();
6018 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Callee))
Guy Benyei11169dd2012-12-18 14:30:41 +00006019 Callee = ICE->getSubExpr();
6020
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006021 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Callee))
Guy Benyei11169dd2012-12-18 14:30:41 +00006022 Pieces = buildPieces(NameFlags, false, DRE->getNameInfo(),
6023 DRE->getQualifierLoc().getSourceRange());
6024 }
6025 break;
6026
6027 default:
6028 break;
6029 }
6030
6031 if (Pieces.empty()) {
6032 if (PieceIndex == 0)
6033 return clang_getCursorExtent(C);
6034 } else if (PieceIndex < Pieces.size()) {
6035 SourceRange R = Pieces[PieceIndex];
6036 if (R.isValid())
6037 return cxloc::translateSourceRange(getCursorContext(C), R);
6038 }
6039
6040 return clang_getNullRange();
6041}
6042
6043void clang_enableStackTraces(void) {
Richard Smithdfed58a2016-06-09 00:53:41 +00006044 // FIXME: Provide an argv0 here so we can find llvm-symbolizer.
6045 llvm::sys::PrintStackTraceOnErrorSignal(StringRef());
Guy Benyei11169dd2012-12-18 14:30:41 +00006046}
6047
6048void clang_executeOnThread(void (*fn)(void*), void *user_data,
6049 unsigned stack_size) {
6050 llvm::llvm_execute_on_thread(fn, user_data, stack_size);
6051}
6052
Guy Benyei11169dd2012-12-18 14:30:41 +00006053//===----------------------------------------------------------------------===//
6054// Token-based Operations.
6055//===----------------------------------------------------------------------===//
6056
6057/* CXToken layout:
6058 * int_data[0]: a CXTokenKind
6059 * int_data[1]: starting token location
6060 * int_data[2]: token length
6061 * int_data[3]: reserved
6062 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
6063 * otherwise unused.
6064 */
Guy Benyei11169dd2012-12-18 14:30:41 +00006065CXTokenKind clang_getTokenKind(CXToken CXTok) {
6066 return static_cast<CXTokenKind>(CXTok.int_data[0]);
6067}
6068
6069CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
6070 switch (clang_getTokenKind(CXTok)) {
6071 case CXToken_Identifier:
6072 case CXToken_Keyword:
6073 // We know we have an IdentifierInfo*, so use that.
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00006074 return cxstring::createRef(static_cast<IdentifierInfo *>(CXTok.ptr_data)
Guy Benyei11169dd2012-12-18 14:30:41 +00006075 ->getNameStart());
6076
6077 case CXToken_Literal: {
6078 // We have stashed the starting pointer in the ptr_data field. Use it.
6079 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00006080 return cxstring::createDup(StringRef(Text, CXTok.int_data[2]));
Guy Benyei11169dd2012-12-18 14:30:41 +00006081 }
6082
6083 case CXToken_Punctuation:
6084 case CXToken_Comment:
6085 break;
6086 }
6087
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006088 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006089 LOG_BAD_TU(TU);
6090 return cxstring::createEmpty();
6091 }
6092
Guy Benyei11169dd2012-12-18 14:30:41 +00006093 // We have to find the starting buffer pointer the hard way, by
6094 // deconstructing the source location.
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006095 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006096 if (!CXXUnit)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00006097 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00006098
6099 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
6100 std::pair<FileID, unsigned> LocInfo
6101 = CXXUnit->getSourceManager().getDecomposedSpellingLoc(Loc);
6102 bool Invalid = false;
6103 StringRef Buffer
6104 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
6105 if (Invalid)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00006106 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00006107
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00006108 return cxstring::createDup(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Guy Benyei11169dd2012-12-18 14:30:41 +00006109}
6110
6111CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006112 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006113 LOG_BAD_TU(TU);
6114 return clang_getNullLocation();
6115 }
6116
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006117 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006118 if (!CXXUnit)
6119 return clang_getNullLocation();
6120
6121 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
6122 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
6123}
6124
6125CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006126 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006127 LOG_BAD_TU(TU);
6128 return clang_getNullRange();
6129 }
6130
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006131 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006132 if (!CXXUnit)
6133 return clang_getNullRange();
6134
6135 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
6136 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
6137}
6138
6139static void getTokens(ASTUnit *CXXUnit, SourceRange Range,
6140 SmallVectorImpl<CXToken> &CXTokens) {
6141 SourceManager &SourceMgr = CXXUnit->getSourceManager();
6142 std::pair<FileID, unsigned> BeginLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00006143 = SourceMgr.getDecomposedSpellingLoc(Range.getBegin());
Guy Benyei11169dd2012-12-18 14:30:41 +00006144 std::pair<FileID, unsigned> EndLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00006145 = SourceMgr.getDecomposedSpellingLoc(Range.getEnd());
Guy Benyei11169dd2012-12-18 14:30:41 +00006146
6147 // Cannot tokenize across files.
6148 if (BeginLocInfo.first != EndLocInfo.first)
6149 return;
6150
6151 // Create a lexer
6152 bool Invalid = false;
6153 StringRef Buffer
6154 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
6155 if (Invalid)
6156 return;
6157
6158 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
6159 CXXUnit->getASTContext().getLangOpts(),
6160 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
6161 Lex.SetCommentRetentionState(true);
6162
6163 // Lex tokens until we hit the end of the range.
6164 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
6165 Token Tok;
6166 bool previousWasAt = false;
6167 do {
6168 // Lex the next token
6169 Lex.LexFromRawLexer(Tok);
6170 if (Tok.is(tok::eof))
6171 break;
6172
6173 // Initialize the CXToken.
6174 CXToken CXTok;
6175
6176 // - Common fields
6177 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
6178 CXTok.int_data[2] = Tok.getLength();
6179 CXTok.int_data[3] = 0;
6180
6181 // - Kind-specific fields
6182 if (Tok.isLiteral()) {
6183 CXTok.int_data[0] = CXToken_Literal;
Dmitri Gribenkof9304482013-01-23 15:56:07 +00006184 CXTok.ptr_data = const_cast<char *>(Tok.getLiteralData());
Guy Benyei11169dd2012-12-18 14:30:41 +00006185 } else if (Tok.is(tok::raw_identifier)) {
6186 // Lookup the identifier to determine whether we have a keyword.
6187 IdentifierInfo *II
6188 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok);
6189
6190 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
6191 CXTok.int_data[0] = CXToken_Keyword;
6192 }
6193 else {
6194 CXTok.int_data[0] = Tok.is(tok::identifier)
6195 ? CXToken_Identifier
6196 : CXToken_Keyword;
6197 }
6198 CXTok.ptr_data = II;
6199 } else if (Tok.is(tok::comment)) {
6200 CXTok.int_data[0] = CXToken_Comment;
Craig Topper69186e72014-06-08 08:38:04 +00006201 CXTok.ptr_data = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006202 } else {
6203 CXTok.int_data[0] = CXToken_Punctuation;
Craig Topper69186e72014-06-08 08:38:04 +00006204 CXTok.ptr_data = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006205 }
6206 CXTokens.push_back(CXTok);
6207 previousWasAt = Tok.is(tok::at);
Argyrios Kyrtzidisc7c6a072016-11-09 23:58:39 +00006208 } while (Lex.getBufferLocation() < EffectiveBufferEnd);
Guy Benyei11169dd2012-12-18 14:30:41 +00006209}
6210
6211void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
6212 CXToken **Tokens, unsigned *NumTokens) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00006213 LOG_FUNC_SECTION {
6214 *Log << TU << ' ' << Range;
6215 }
6216
Guy Benyei11169dd2012-12-18 14:30:41 +00006217 if (Tokens)
Craig Topper69186e72014-06-08 08:38:04 +00006218 *Tokens = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006219 if (NumTokens)
6220 *NumTokens = 0;
6221
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006222 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006223 LOG_BAD_TU(TU);
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00006224 return;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006225 }
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00006226
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006227 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006228 if (!CXXUnit || !Tokens || !NumTokens)
6229 return;
6230
6231 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
6232
6233 SourceRange R = cxloc::translateCXSourceRange(Range);
6234 if (R.isInvalid())
6235 return;
6236
6237 SmallVector<CXToken, 32> CXTokens;
6238 getTokens(CXXUnit, R, CXTokens);
6239
6240 if (CXTokens.empty())
6241 return;
6242
6243 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
6244 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
6245 *NumTokens = CXTokens.size();
6246}
6247
6248void clang_disposeTokens(CXTranslationUnit TU,
6249 CXToken *Tokens, unsigned NumTokens) {
6250 free(Tokens);
6251}
6252
Guy Benyei11169dd2012-12-18 14:30:41 +00006253//===----------------------------------------------------------------------===//
6254// Token annotation APIs.
6255//===----------------------------------------------------------------------===//
6256
Guy Benyei11169dd2012-12-18 14:30:41 +00006257static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
6258 CXCursor parent,
6259 CXClientData client_data);
6260static bool AnnotateTokensPostChildrenVisitor(CXCursor cursor,
6261 CXClientData client_data);
6262
6263namespace {
6264class AnnotateTokensWorker {
Guy Benyei11169dd2012-12-18 14:30:41 +00006265 CXToken *Tokens;
6266 CXCursor *Cursors;
6267 unsigned NumTokens;
6268 unsigned TokIdx;
6269 unsigned PreprocessingTokIdx;
6270 CursorVisitor AnnotateVis;
6271 SourceManager &SrcMgr;
6272 bool HasContextSensitiveKeywords;
6273
6274 struct PostChildrenInfo {
6275 CXCursor Cursor;
6276 SourceRange CursorRange;
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006277 unsigned BeforeReachingCursorIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00006278 unsigned BeforeChildrenTokenIdx;
6279 };
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006280 SmallVector<PostChildrenInfo, 8> PostChildrenInfos;
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006281
6282 CXToken &getTok(unsigned Idx) {
6283 assert(Idx < NumTokens);
6284 return Tokens[Idx];
6285 }
6286 const CXToken &getTok(unsigned Idx) const {
6287 assert(Idx < NumTokens);
6288 return Tokens[Idx];
6289 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006290 bool MoreTokens() const { return TokIdx < NumTokens; }
6291 unsigned NextToken() const { return TokIdx; }
6292 void AdvanceToken() { ++TokIdx; }
6293 SourceLocation GetTokenLoc(unsigned tokI) {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006294 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[1]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006295 }
6296 bool isFunctionMacroToken(unsigned tokI) const {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006297 return getTok(tokI).int_data[3] != 0;
Guy Benyei11169dd2012-12-18 14:30:41 +00006298 }
6299 SourceLocation getFunctionMacroTokenLoc(unsigned tokI) const {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006300 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[3]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006301 }
6302
6303 void annotateAndAdvanceTokens(CXCursor, RangeComparisonResult, SourceRange);
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006304 bool annotateAndAdvanceFunctionMacroTokens(CXCursor, RangeComparisonResult,
Guy Benyei11169dd2012-12-18 14:30:41 +00006305 SourceRange);
6306
6307public:
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006308 AnnotateTokensWorker(CXToken *tokens, CXCursor *cursors, unsigned numTokens,
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006309 CXTranslationUnit TU, SourceRange RegionOfInterest)
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006310 : Tokens(tokens), Cursors(cursors),
Guy Benyei11169dd2012-12-18 14:30:41 +00006311 NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006312 AnnotateVis(TU,
Guy Benyei11169dd2012-12-18 14:30:41 +00006313 AnnotateTokensVisitor, this,
6314 /*VisitPreprocessorLast=*/true,
6315 /*VisitIncludedEntities=*/false,
6316 RegionOfInterest,
6317 /*VisitDeclsOnly=*/false,
6318 AnnotateTokensPostChildrenVisitor),
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006319 SrcMgr(cxtu::getASTUnit(TU)->getSourceManager()),
Guy Benyei11169dd2012-12-18 14:30:41 +00006320 HasContextSensitiveKeywords(false) { }
6321
6322 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
6323 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
6324 bool postVisitChildren(CXCursor cursor);
6325 void AnnotateTokens();
6326
6327 /// \brief Determine whether the annotator saw any cursors that have
6328 /// context-sensitive keywords.
6329 bool hasContextSensitiveKeywords() const {
6330 return HasContextSensitiveKeywords;
6331 }
6332
6333 ~AnnotateTokensWorker() {
6334 assert(PostChildrenInfos.empty());
6335 }
6336};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006337}
Guy Benyei11169dd2012-12-18 14:30:41 +00006338
6339void AnnotateTokensWorker::AnnotateTokens() {
6340 // Walk the AST within the region of interest, annotating tokens
6341 // along the way.
6342 AnnotateVis.visitFileRegion();
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006343}
Guy Benyei11169dd2012-12-18 14:30:41 +00006344
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006345static inline void updateCursorAnnotation(CXCursor &Cursor,
6346 const CXCursor &updateC) {
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006347 if (clang_isInvalid(updateC.kind) || !clang_isInvalid(Cursor.kind))
Guy Benyei11169dd2012-12-18 14:30:41 +00006348 return;
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006349 Cursor = updateC;
Guy Benyei11169dd2012-12-18 14:30:41 +00006350}
6351
6352/// \brief It annotates and advances tokens with a cursor until the comparison
6353//// between the cursor location and the source range is the same as
6354/// \arg compResult.
6355///
6356/// Pass RangeBefore to annotate tokens with a cursor until a range is reached.
6357/// Pass RangeOverlap to annotate tokens inside a range.
6358void AnnotateTokensWorker::annotateAndAdvanceTokens(CXCursor updateC,
6359 RangeComparisonResult compResult,
6360 SourceRange range) {
6361 while (MoreTokens()) {
6362 const unsigned I = NextToken();
6363 if (isFunctionMacroToken(I))
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006364 if (!annotateAndAdvanceFunctionMacroTokens(updateC, compResult, range))
6365 return;
Guy Benyei11169dd2012-12-18 14:30:41 +00006366
6367 SourceLocation TokLoc = GetTokenLoc(I);
6368 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006369 updateCursorAnnotation(Cursors[I], updateC);
Guy Benyei11169dd2012-12-18 14:30:41 +00006370 AdvanceToken();
6371 continue;
6372 }
6373 break;
6374 }
6375}
6376
6377/// \brief Special annotation handling for macro argument tokens.
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006378/// \returns true if it advanced beyond all macro tokens, false otherwise.
6379bool AnnotateTokensWorker::annotateAndAdvanceFunctionMacroTokens(
Guy Benyei11169dd2012-12-18 14:30:41 +00006380 CXCursor updateC,
6381 RangeComparisonResult compResult,
6382 SourceRange range) {
6383 assert(MoreTokens());
6384 assert(isFunctionMacroToken(NextToken()) &&
6385 "Should be called only for macro arg tokens");
6386
6387 // This works differently than annotateAndAdvanceTokens; because expanded
6388 // macro arguments can have arbitrary translation-unit source order, we do not
6389 // advance the token index one by one until a token fails the range test.
6390 // We only advance once past all of the macro arg tokens if all of them
6391 // pass the range test. If one of them fails we keep the token index pointing
6392 // at the start of the macro arg tokens so that the failing token will be
6393 // annotated by a subsequent annotation try.
6394
6395 bool atLeastOneCompFail = false;
6396
6397 unsigned I = NextToken();
6398 for (; I < NumTokens && isFunctionMacroToken(I); ++I) {
6399 SourceLocation TokLoc = getFunctionMacroTokenLoc(I);
6400 if (TokLoc.isFileID())
6401 continue; // not macro arg token, it's parens or comma.
6402 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
6403 if (clang_isInvalid(clang_getCursorKind(Cursors[I])))
6404 Cursors[I] = updateC;
6405 } else
6406 atLeastOneCompFail = true;
6407 }
6408
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006409 if (atLeastOneCompFail)
6410 return false;
6411
6412 TokIdx = I; // All of the tokens were handled, advance beyond all of them.
6413 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00006414}
6415
6416enum CXChildVisitResult
6417AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006418 SourceRange cursorRange = getRawCursorExtent(cursor);
6419 if (cursorRange.isInvalid())
6420 return CXChildVisit_Recurse;
6421
6422 if (!HasContextSensitiveKeywords) {
6423 // Objective-C properties can have context-sensitive keywords.
6424 if (cursor.kind == CXCursor_ObjCPropertyDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006425 if (const ObjCPropertyDecl *Property
Guy Benyei11169dd2012-12-18 14:30:41 +00006426 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(cursor)))
6427 HasContextSensitiveKeywords = Property->getPropertyAttributesAsWritten() != 0;
6428 }
6429 // Objective-C methods can have context-sensitive keywords.
6430 else if (cursor.kind == CXCursor_ObjCInstanceMethodDecl ||
6431 cursor.kind == CXCursor_ObjCClassMethodDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006432 if (const ObjCMethodDecl *Method
Guy Benyei11169dd2012-12-18 14:30:41 +00006433 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
6434 if (Method->getObjCDeclQualifier())
6435 HasContextSensitiveKeywords = true;
6436 else {
David Majnemer59f77922016-06-24 04:05:48 +00006437 for (const auto *P : Method->parameters()) {
Aaron Ballman43b68be2014-03-07 17:50:17 +00006438 if (P->getObjCDeclQualifier()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006439 HasContextSensitiveKeywords = true;
6440 break;
6441 }
6442 }
6443 }
6444 }
6445 }
6446 // C++ methods can have context-sensitive keywords.
6447 else if (cursor.kind == CXCursor_CXXMethod) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006448 if (const CXXMethodDecl *Method
Guy Benyei11169dd2012-12-18 14:30:41 +00006449 = dyn_cast_or_null<CXXMethodDecl>(getCursorDecl(cursor))) {
6450 if (Method->hasAttr<FinalAttr>() || Method->hasAttr<OverrideAttr>())
6451 HasContextSensitiveKeywords = true;
6452 }
6453 }
6454 // C++ classes can have context-sensitive keywords.
6455 else if (cursor.kind == CXCursor_StructDecl ||
6456 cursor.kind == CXCursor_ClassDecl ||
6457 cursor.kind == CXCursor_ClassTemplate ||
6458 cursor.kind == CXCursor_ClassTemplatePartialSpecialization) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006459 if (const Decl *D = getCursorDecl(cursor))
Guy Benyei11169dd2012-12-18 14:30:41 +00006460 if (D->hasAttr<FinalAttr>())
6461 HasContextSensitiveKeywords = true;
6462 }
6463 }
Argyrios Kyrtzidis990b3862013-06-04 18:24:30 +00006464
6465 // Don't override a property annotation with its getter/setter method.
6466 if (cursor.kind == CXCursor_ObjCInstanceMethodDecl &&
6467 parent.kind == CXCursor_ObjCPropertyDecl)
6468 return CXChildVisit_Continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00006469
6470 if (clang_isPreprocessing(cursor.kind)) {
6471 // Items in the preprocessing record are kept separate from items in
6472 // declarations, so we keep a separate token index.
6473 unsigned SavedTokIdx = TokIdx;
6474 TokIdx = PreprocessingTokIdx;
6475
6476 // Skip tokens up until we catch up to the beginning of the preprocessing
6477 // entry.
6478 while (MoreTokens()) {
6479 const unsigned I = NextToken();
6480 SourceLocation TokLoc = GetTokenLoc(I);
6481 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
6482 case RangeBefore:
6483 AdvanceToken();
6484 continue;
6485 case RangeAfter:
6486 case RangeOverlap:
6487 break;
6488 }
6489 break;
6490 }
6491
6492 // Look at all of the tokens within this range.
6493 while (MoreTokens()) {
6494 const unsigned I = NextToken();
6495 SourceLocation TokLoc = GetTokenLoc(I);
6496 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
6497 case RangeBefore:
6498 llvm_unreachable("Infeasible");
6499 case RangeAfter:
6500 break;
6501 case RangeOverlap:
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00006502 // For macro expansions, just note where the beginning of the macro
6503 // expansion occurs.
6504 if (cursor.kind == CXCursor_MacroExpansion) {
6505 if (TokLoc == cursorRange.getBegin())
6506 Cursors[I] = cursor;
6507 AdvanceToken();
6508 break;
6509 }
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006510 // We may have already annotated macro names inside macro definitions.
6511 if (Cursors[I].kind != CXCursor_MacroExpansion)
6512 Cursors[I] = cursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00006513 AdvanceToken();
Guy Benyei11169dd2012-12-18 14:30:41 +00006514 continue;
6515 }
6516 break;
6517 }
6518
6519 // Save the preprocessing token index; restore the non-preprocessing
6520 // token index.
6521 PreprocessingTokIdx = TokIdx;
6522 TokIdx = SavedTokIdx;
6523 return CXChildVisit_Recurse;
6524 }
6525
6526 if (cursorRange.isInvalid())
6527 return CXChildVisit_Continue;
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006528
6529 unsigned BeforeReachingCursorIdx = NextToken();
Guy Benyei11169dd2012-12-18 14:30:41 +00006530 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00006531 const enum CXCursorKind K = clang_getCursorKind(parent);
6532 const CXCursor updateC =
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006533 (clang_isInvalid(K) || K == CXCursor_TranslationUnit ||
6534 // Attributes are annotated out-of-order, skip tokens until we reach it.
6535 clang_isAttribute(cursor.kind))
Guy Benyei11169dd2012-12-18 14:30:41 +00006536 ? clang_getNullCursor() : parent;
6537
6538 annotateAndAdvanceTokens(updateC, RangeBefore, cursorRange);
6539
6540 // Avoid having the cursor of an expression "overwrite" the annotation of the
6541 // variable declaration that it belongs to.
6542 // This can happen for C++ constructor expressions whose range generally
6543 // include the variable declaration, e.g.:
6544 // MyCXXClass foo; // Make sure we don't annotate 'foo' as a CallExpr cursor.
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006545 if (clang_isExpression(cursorK) && MoreTokens()) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006546 const Expr *E = getCursorExpr(cursor);
Dmitri Gribenkoa1691182013-01-26 18:12:08 +00006547 if (const Decl *D = getCursorParentDecl(cursor)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006548 const unsigned I = NextToken();
6549 if (E->getLocStart().isValid() && D->getLocation().isValid() &&
6550 E->getLocStart() == D->getLocation() &&
6551 E->getLocStart() == GetTokenLoc(I)) {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006552 updateCursorAnnotation(Cursors[I], updateC);
Guy Benyei11169dd2012-12-18 14:30:41 +00006553 AdvanceToken();
6554 }
6555 }
6556 }
6557
6558 // Before recursing into the children keep some state that we are going
6559 // to use in the AnnotateTokensWorker::postVisitChildren callback to do some
6560 // extra work after the child nodes are visited.
6561 // Note that we don't call VisitChildren here to avoid traversing statements
6562 // code-recursively which can blow the stack.
6563
6564 PostChildrenInfo Info;
6565 Info.Cursor = cursor;
6566 Info.CursorRange = cursorRange;
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006567 Info.BeforeReachingCursorIdx = BeforeReachingCursorIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00006568 Info.BeforeChildrenTokenIdx = NextToken();
6569 PostChildrenInfos.push_back(Info);
6570
6571 return CXChildVisit_Recurse;
6572}
6573
6574bool AnnotateTokensWorker::postVisitChildren(CXCursor cursor) {
6575 if (PostChildrenInfos.empty())
6576 return false;
6577 const PostChildrenInfo &Info = PostChildrenInfos.back();
6578 if (!clang_equalCursors(Info.Cursor, cursor))
6579 return false;
6580
6581 const unsigned BeforeChildren = Info.BeforeChildrenTokenIdx;
6582 const unsigned AfterChildren = NextToken();
6583 SourceRange cursorRange = Info.CursorRange;
6584
6585 // Scan the tokens that are at the end of the cursor, but are not captured
6586 // but the child cursors.
6587 annotateAndAdvanceTokens(cursor, RangeOverlap, cursorRange);
6588
6589 // Scan the tokens that are at the beginning of the cursor, but are not
6590 // capture by the child cursors.
6591 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
6592 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
6593 break;
6594
6595 Cursors[I] = cursor;
6596 }
6597
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006598 // Attributes are annotated out-of-order, rewind TokIdx to when we first
6599 // encountered the attribute cursor.
6600 if (clang_isAttribute(cursor.kind))
6601 TokIdx = Info.BeforeReachingCursorIdx;
6602
Guy Benyei11169dd2012-12-18 14:30:41 +00006603 PostChildrenInfos.pop_back();
6604 return false;
6605}
6606
6607static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
6608 CXCursor parent,
6609 CXClientData client_data) {
6610 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
6611}
6612
6613static bool AnnotateTokensPostChildrenVisitor(CXCursor cursor,
6614 CXClientData client_data) {
6615 return static_cast<AnnotateTokensWorker*>(client_data)->
6616 postVisitChildren(cursor);
6617}
6618
6619namespace {
6620
6621/// \brief Uses the macro expansions in the preprocessing record to find
6622/// and mark tokens that are macro arguments. This info is used by the
6623/// AnnotateTokensWorker.
6624class MarkMacroArgTokensVisitor {
6625 SourceManager &SM;
6626 CXToken *Tokens;
6627 unsigned NumTokens;
6628 unsigned CurIdx;
6629
6630public:
6631 MarkMacroArgTokensVisitor(SourceManager &SM,
6632 CXToken *tokens, unsigned numTokens)
6633 : SM(SM), Tokens(tokens), NumTokens(numTokens), CurIdx(0) { }
6634
6635 CXChildVisitResult visit(CXCursor cursor, CXCursor parent) {
6636 if (cursor.kind != CXCursor_MacroExpansion)
6637 return CXChildVisit_Continue;
6638
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00006639 SourceRange macroRange = getCursorMacroExpansion(cursor).getSourceRange();
Guy Benyei11169dd2012-12-18 14:30:41 +00006640 if (macroRange.getBegin() == macroRange.getEnd())
6641 return CXChildVisit_Continue; // it's not a function macro.
6642
6643 for (; CurIdx < NumTokens; ++CurIdx) {
6644 if (!SM.isBeforeInTranslationUnit(getTokenLoc(CurIdx),
6645 macroRange.getBegin()))
6646 break;
6647 }
6648
6649 if (CurIdx == NumTokens)
6650 return CXChildVisit_Break;
6651
6652 for (; CurIdx < NumTokens; ++CurIdx) {
6653 SourceLocation tokLoc = getTokenLoc(CurIdx);
6654 if (!SM.isBeforeInTranslationUnit(tokLoc, macroRange.getEnd()))
6655 break;
6656
6657 setFunctionMacroTokenLoc(CurIdx, SM.getMacroArgExpandedLocation(tokLoc));
6658 }
6659
6660 if (CurIdx == NumTokens)
6661 return CXChildVisit_Break;
6662
6663 return CXChildVisit_Continue;
6664 }
6665
6666private:
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006667 CXToken &getTok(unsigned Idx) {
6668 assert(Idx < NumTokens);
6669 return Tokens[Idx];
6670 }
6671 const CXToken &getTok(unsigned Idx) const {
6672 assert(Idx < NumTokens);
6673 return Tokens[Idx];
6674 }
6675
Guy Benyei11169dd2012-12-18 14:30:41 +00006676 SourceLocation getTokenLoc(unsigned tokI) {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006677 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[1]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006678 }
6679
6680 void setFunctionMacroTokenLoc(unsigned tokI, SourceLocation loc) {
6681 // The third field is reserved and currently not used. Use it here
6682 // to mark macro arg expanded tokens with their expanded locations.
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006683 getTok(tokI).int_data[3] = loc.getRawEncoding();
Guy Benyei11169dd2012-12-18 14:30:41 +00006684 }
6685};
6686
6687} // end anonymous namespace
6688
6689static CXChildVisitResult
6690MarkMacroArgTokensVisitorDelegate(CXCursor cursor, CXCursor parent,
6691 CXClientData client_data) {
6692 return static_cast<MarkMacroArgTokensVisitor*>(client_data)->visit(cursor,
6693 parent);
6694}
6695
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006696/// \brief Used by \c annotatePreprocessorTokens.
6697/// \returns true if lexing was finished, false otherwise.
6698static bool lexNext(Lexer &Lex, Token &Tok,
6699 unsigned &NextIdx, unsigned NumTokens) {
6700 if (NextIdx >= NumTokens)
6701 return true;
6702
6703 ++NextIdx;
6704 Lex.LexFromRawLexer(Tok);
Alexander Kornienko1a9f1842015-12-28 15:24:08 +00006705 return Tok.is(tok::eof);
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006706}
6707
Guy Benyei11169dd2012-12-18 14:30:41 +00006708static void annotatePreprocessorTokens(CXTranslationUnit TU,
6709 SourceRange RegionOfInterest,
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006710 CXCursor *Cursors,
6711 CXToken *Tokens,
6712 unsigned NumTokens) {
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006713 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006714
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00006715 Preprocessor &PP = CXXUnit->getPreprocessor();
Guy Benyei11169dd2012-12-18 14:30:41 +00006716 SourceManager &SourceMgr = CXXUnit->getSourceManager();
6717 std::pair<FileID, unsigned> BeginLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00006718 = SourceMgr.getDecomposedSpellingLoc(RegionOfInterest.getBegin());
Guy Benyei11169dd2012-12-18 14:30:41 +00006719 std::pair<FileID, unsigned> EndLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00006720 = SourceMgr.getDecomposedSpellingLoc(RegionOfInterest.getEnd());
Guy Benyei11169dd2012-12-18 14:30:41 +00006721
6722 if (BeginLocInfo.first != EndLocInfo.first)
6723 return;
6724
6725 StringRef Buffer;
6726 bool Invalid = false;
6727 Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
6728 if (Buffer.empty() || Invalid)
6729 return;
6730
6731 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
6732 CXXUnit->getASTContext().getLangOpts(),
6733 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
6734 Buffer.end());
6735 Lex.SetCommentRetentionState(true);
6736
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006737 unsigned NextIdx = 0;
Guy Benyei11169dd2012-12-18 14:30:41 +00006738 // Lex tokens in raw mode until we hit the end of the range, to avoid
6739 // entering #includes or expanding macros.
6740 while (true) {
6741 Token Tok;
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006742 if (lexNext(Lex, Tok, NextIdx, NumTokens))
6743 break;
6744 unsigned TokIdx = NextIdx-1;
6745 assert(Tok.getLocation() ==
6746 SourceLocation::getFromRawEncoding(Tokens[TokIdx].int_data[1]));
Guy Benyei11169dd2012-12-18 14:30:41 +00006747
6748 reprocess:
6749 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006750 // We have found a preprocessing directive. Annotate the tokens
6751 // appropriately.
Guy Benyei11169dd2012-12-18 14:30:41 +00006752 //
6753 // FIXME: Some simple tests here could identify macro definitions and
6754 // #undefs, to provide specific cursor kinds for those.
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006755
6756 SourceLocation BeginLoc = Tok.getLocation();
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00006757 if (lexNext(Lex, Tok, NextIdx, NumTokens))
6758 break;
6759
Craig Topper69186e72014-06-08 08:38:04 +00006760 MacroInfo *MI = nullptr;
Alp Toker2d57cea2014-05-17 04:53:25 +00006761 if (Tok.is(tok::raw_identifier) && Tok.getRawIdentifier() == "define") {
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00006762 if (lexNext(Lex, Tok, NextIdx, NumTokens))
6763 break;
6764
6765 if (Tok.is(tok::raw_identifier)) {
Alp Toker2d57cea2014-05-17 04:53:25 +00006766 IdentifierInfo &II =
6767 PP.getIdentifierTable().get(Tok.getRawIdentifier());
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00006768 SourceLocation MappedTokLoc =
6769 CXXUnit->mapLocationToPreamble(Tok.getLocation());
6770 MI = getMacroInfo(II, MappedTokLoc, TU);
6771 }
6772 }
6773
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006774 bool finished = false;
Guy Benyei11169dd2012-12-18 14:30:41 +00006775 do {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006776 if (lexNext(Lex, Tok, NextIdx, NumTokens)) {
6777 finished = true;
6778 break;
6779 }
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00006780 // If we are in a macro definition, check if the token was ever a
6781 // macro name and annotate it if that's the case.
6782 if (MI) {
6783 SourceLocation SaveLoc = Tok.getLocation();
6784 Tok.setLocation(CXXUnit->mapLocationToPreamble(SaveLoc));
Richard Smith66a81862015-05-04 02:25:31 +00006785 MacroDefinitionRecord *MacroDef =
6786 checkForMacroInMacroDefinition(MI, Tok, TU);
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00006787 Tok.setLocation(SaveLoc);
6788 if (MacroDef)
Richard Smith66a81862015-05-04 02:25:31 +00006789 Cursors[NextIdx - 1] =
6790 MakeMacroExpansionCursor(MacroDef, Tok.getLocation(), TU);
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00006791 }
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006792 } while (!Tok.isAtStartOfLine());
6793
6794 unsigned LastIdx = finished ? NextIdx-1 : NextIdx-2;
6795 assert(TokIdx <= LastIdx);
6796 SourceLocation EndLoc =
6797 SourceLocation::getFromRawEncoding(Tokens[LastIdx].int_data[1]);
6798 CXCursor Cursor =
6799 MakePreprocessingDirectiveCursor(SourceRange(BeginLoc, EndLoc), TU);
6800
6801 for (; TokIdx <= LastIdx; ++TokIdx)
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00006802 updateCursorAnnotation(Cursors[TokIdx], Cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00006803
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006804 if (finished)
6805 break;
6806 goto reprocess;
Guy Benyei11169dd2012-12-18 14:30:41 +00006807 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006808 }
6809}
6810
6811// This gets run a separate thread to avoid stack blowout.
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00006812static void clang_annotateTokensImpl(CXTranslationUnit TU, ASTUnit *CXXUnit,
6813 CXToken *Tokens, unsigned NumTokens,
6814 CXCursor *Cursors) {
Dmitri Gribenko183436e2013-01-26 21:49:50 +00006815 CIndexer *CXXIdx = TU->CIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00006816 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing))
6817 setThreadBackgroundPriority();
6818
6819 // Determine the region of interest, which contains all of the tokens.
6820 SourceRange RegionOfInterest;
6821 RegionOfInterest.setBegin(
6822 cxloc::translateSourceLocation(clang_getTokenLocation(TU, Tokens[0])));
6823 RegionOfInterest.setEnd(
6824 cxloc::translateSourceLocation(clang_getTokenLocation(TU,
6825 Tokens[NumTokens-1])));
6826
Guy Benyei11169dd2012-12-18 14:30:41 +00006827 // Relex the tokens within the source range to look for preprocessing
6828 // directives.
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006829 annotatePreprocessorTokens(TU, RegionOfInterest, Cursors, Tokens, NumTokens);
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00006830
6831 // If begin location points inside a macro argument, set it to the expansion
6832 // location so we can have the full context when annotating semantically.
6833 {
6834 SourceManager &SM = CXXUnit->getSourceManager();
6835 SourceLocation Loc =
6836 SM.getMacroArgExpandedLocation(RegionOfInterest.getBegin());
6837 if (Loc.isMacroID())
6838 RegionOfInterest.setBegin(SM.getExpansionLoc(Loc));
6839 }
6840
Guy Benyei11169dd2012-12-18 14:30:41 +00006841 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
6842 // Search and mark tokens that are macro argument expansions.
6843 MarkMacroArgTokensVisitor Visitor(CXXUnit->getSourceManager(),
6844 Tokens, NumTokens);
6845 CursorVisitor MacroArgMarker(TU,
6846 MarkMacroArgTokensVisitorDelegate, &Visitor,
6847 /*VisitPreprocessorLast=*/true,
6848 /*VisitIncludedEntities=*/false,
6849 RegionOfInterest);
6850 MacroArgMarker.visitPreprocessedEntitiesInRegion();
6851 }
6852
6853 // Annotate all of the source locations in the region of interest that map to
6854 // a specific cursor.
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006855 AnnotateTokensWorker W(Tokens, Cursors, NumTokens, TU, RegionOfInterest);
Guy Benyei11169dd2012-12-18 14:30:41 +00006856
6857 // FIXME: We use a ridiculous stack size here because the data-recursion
6858 // algorithm uses a large stack frame than the non-data recursive version,
6859 // and AnnotationTokensWorker currently transforms the data-recursion
6860 // algorithm back into a traditional recursion by explicitly calling
6861 // VisitChildren(). We will need to remove this explicit recursive call.
6862 W.AnnotateTokens();
6863
6864 // If we ran into any entities that involve context-sensitive keywords,
6865 // take another pass through the tokens to mark them as such.
6866 if (W.hasContextSensitiveKeywords()) {
6867 for (unsigned I = 0; I != NumTokens; ++I) {
6868 if (clang_getTokenKind(Tokens[I]) != CXToken_Identifier)
6869 continue;
6870
6871 if (Cursors[I].kind == CXCursor_ObjCPropertyDecl) {
6872 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006873 if (const ObjCPropertyDecl *Property
Guy Benyei11169dd2012-12-18 14:30:41 +00006874 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(Cursors[I]))) {
6875 if (Property->getPropertyAttributesAsWritten() != 0 &&
6876 llvm::StringSwitch<bool>(II->getName())
6877 .Case("readonly", true)
6878 .Case("assign", true)
6879 .Case("unsafe_unretained", true)
6880 .Case("readwrite", true)
6881 .Case("retain", true)
6882 .Case("copy", true)
6883 .Case("nonatomic", true)
6884 .Case("atomic", true)
6885 .Case("getter", true)
6886 .Case("setter", true)
6887 .Case("strong", true)
6888 .Case("weak", true)
Manman Ren04fd4d82016-05-31 23:22:04 +00006889 .Case("class", true)
Guy Benyei11169dd2012-12-18 14:30:41 +00006890 .Default(false))
6891 Tokens[I].int_data[0] = CXToken_Keyword;
6892 }
6893 continue;
6894 }
6895
6896 if (Cursors[I].kind == CXCursor_ObjCInstanceMethodDecl ||
6897 Cursors[I].kind == CXCursor_ObjCClassMethodDecl) {
6898 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
6899 if (llvm::StringSwitch<bool>(II->getName())
6900 .Case("in", true)
6901 .Case("out", true)
6902 .Case("inout", true)
6903 .Case("oneway", true)
6904 .Case("bycopy", true)
6905 .Case("byref", true)
6906 .Default(false))
6907 Tokens[I].int_data[0] = CXToken_Keyword;
6908 continue;
6909 }
6910
6911 if (Cursors[I].kind == CXCursor_CXXFinalAttr ||
6912 Cursors[I].kind == CXCursor_CXXOverrideAttr) {
6913 Tokens[I].int_data[0] = CXToken_Keyword;
6914 continue;
6915 }
6916 }
6917 }
6918}
6919
Guy Benyei11169dd2012-12-18 14:30:41 +00006920void clang_annotateTokens(CXTranslationUnit TU,
6921 CXToken *Tokens, unsigned NumTokens,
6922 CXCursor *Cursors) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006923 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006924 LOG_BAD_TU(TU);
6925 return;
6926 }
6927 if (NumTokens == 0 || !Tokens || !Cursors) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00006928 LOG_FUNC_SECTION { *Log << "<null input>"; }
Guy Benyei11169dd2012-12-18 14:30:41 +00006929 return;
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00006930 }
6931
6932 LOG_FUNC_SECTION {
6933 *Log << TU << ' ';
6934 CXSourceLocation bloc = clang_getTokenLocation(TU, Tokens[0]);
6935 CXSourceLocation eloc = clang_getTokenLocation(TU, Tokens[NumTokens-1]);
6936 *Log << clang_getRange(bloc, eloc);
6937 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006938
6939 // Any token we don't specifically annotate will have a NULL cursor.
6940 CXCursor C = clang_getNullCursor();
6941 for (unsigned I = 0; I != NumTokens; ++I)
6942 Cursors[I] = C;
6943
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006944 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006945 if (!CXXUnit)
6946 return;
6947
6948 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00006949
6950 auto AnnotateTokensImpl = [=]() {
6951 clang_annotateTokensImpl(TU, CXXUnit, Tokens, NumTokens, Cursors);
6952 };
Guy Benyei11169dd2012-12-18 14:30:41 +00006953 llvm::CrashRecoveryContext CRC;
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00006954 if (!RunSafely(CRC, AnnotateTokensImpl, GetSafetyThreadStackSize() * 2)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006955 fprintf(stderr, "libclang: crash detected while annotating tokens\n");
6956 }
6957}
6958
Guy Benyei11169dd2012-12-18 14:30:41 +00006959//===----------------------------------------------------------------------===//
6960// Operations for querying linkage of a cursor.
6961//===----------------------------------------------------------------------===//
6962
Guy Benyei11169dd2012-12-18 14:30:41 +00006963CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
6964 if (!clang_isDeclaration(cursor.kind))
6965 return CXLinkage_Invalid;
6966
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006967 const Decl *D = cxcursor::getCursorDecl(cursor);
6968 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
Rafael Espindola3ae00052013-05-13 00:12:11 +00006969 switch (ND->getLinkageInternal()) {
Rafael Espindola50df3a02013-05-25 17:16:20 +00006970 case NoLinkage:
6971 case VisibleNoLinkage: return CXLinkage_NoLinkage;
Guy Benyei11169dd2012-12-18 14:30:41 +00006972 case InternalLinkage: return CXLinkage_Internal;
6973 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
6974 case ExternalLinkage: return CXLinkage_External;
6975 };
6976
6977 return CXLinkage_Invalid;
6978}
Guy Benyei11169dd2012-12-18 14:30:41 +00006979
6980//===----------------------------------------------------------------------===//
Ehsan Akhgarib743de72016-05-31 15:55:51 +00006981// Operations for querying visibility of a cursor.
6982//===----------------------------------------------------------------------===//
6983
Ehsan Akhgarib743de72016-05-31 15:55:51 +00006984CXVisibilityKind clang_getCursorVisibility(CXCursor cursor) {
6985 if (!clang_isDeclaration(cursor.kind))
6986 return CXVisibility_Invalid;
6987
6988 const Decl *D = cxcursor::getCursorDecl(cursor);
6989 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
6990 switch (ND->getVisibility()) {
6991 case HiddenVisibility: return CXVisibility_Hidden;
6992 case ProtectedVisibility: return CXVisibility_Protected;
6993 case DefaultVisibility: return CXVisibility_Default;
6994 };
6995
6996 return CXVisibility_Invalid;
6997}
Ehsan Akhgarib743de72016-05-31 15:55:51 +00006998
6999//===----------------------------------------------------------------------===//
Guy Benyei11169dd2012-12-18 14:30:41 +00007000// Operations for querying language of a cursor.
7001//===----------------------------------------------------------------------===//
7002
7003static CXLanguageKind getDeclLanguage(const Decl *D) {
7004 if (!D)
7005 return CXLanguage_C;
7006
7007 switch (D->getKind()) {
7008 default:
7009 break;
7010 case Decl::ImplicitParam:
7011 case Decl::ObjCAtDefsField:
7012 case Decl::ObjCCategory:
7013 case Decl::ObjCCategoryImpl:
7014 case Decl::ObjCCompatibleAlias:
7015 case Decl::ObjCImplementation:
7016 case Decl::ObjCInterface:
7017 case Decl::ObjCIvar:
7018 case Decl::ObjCMethod:
7019 case Decl::ObjCProperty:
7020 case Decl::ObjCPropertyImpl:
7021 case Decl::ObjCProtocol:
Douglas Gregor85f3f952015-07-07 03:57:15 +00007022 case Decl::ObjCTypeParam:
Guy Benyei11169dd2012-12-18 14:30:41 +00007023 return CXLanguage_ObjC;
7024 case Decl::CXXConstructor:
7025 case Decl::CXXConversion:
7026 case Decl::CXXDestructor:
7027 case Decl::CXXMethod:
7028 case Decl::CXXRecord:
7029 case Decl::ClassTemplate:
7030 case Decl::ClassTemplatePartialSpecialization:
7031 case Decl::ClassTemplateSpecialization:
7032 case Decl::Friend:
7033 case Decl::FriendTemplate:
7034 case Decl::FunctionTemplate:
7035 case Decl::LinkageSpec:
7036 case Decl::Namespace:
7037 case Decl::NamespaceAlias:
7038 case Decl::NonTypeTemplateParm:
7039 case Decl::StaticAssert:
7040 case Decl::TemplateTemplateParm:
7041 case Decl::TemplateTypeParm:
7042 case Decl::UnresolvedUsingTypename:
7043 case Decl::UnresolvedUsingValue:
7044 case Decl::Using:
7045 case Decl::UsingDirective:
7046 case Decl::UsingShadow:
7047 return CXLanguage_CPlusPlus;
7048 }
7049
7050 return CXLanguage_C;
7051}
7052
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007053static CXAvailabilityKind getCursorAvailabilityForDecl(const Decl *D) {
7054 if (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted())
Manuel Klimek8e3a7ed2015-09-25 17:53:16 +00007055 return CXAvailability_NotAvailable;
Guy Benyei11169dd2012-12-18 14:30:41 +00007056
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007057 switch (D->getAvailability()) {
7058 case AR_Available:
7059 case AR_NotYetIntroduced:
7060 if (const EnumConstantDecl *EnumConst = dyn_cast<EnumConstantDecl>(D))
Benjamin Kramer656363d2013-10-15 18:53:18 +00007061 return getCursorAvailabilityForDecl(
7062 cast<Decl>(EnumConst->getDeclContext()));
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007063 return CXAvailability_Available;
7064
7065 case AR_Deprecated:
7066 return CXAvailability_Deprecated;
7067
7068 case AR_Unavailable:
7069 return CXAvailability_NotAvailable;
7070 }
Benjamin Kramer656363d2013-10-15 18:53:18 +00007071
7072 llvm_unreachable("Unknown availability kind!");
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007073}
7074
Guy Benyei11169dd2012-12-18 14:30:41 +00007075enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
7076 if (clang_isDeclaration(cursor.kind))
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007077 if (const Decl *D = cxcursor::getCursorDecl(cursor))
7078 return getCursorAvailabilityForDecl(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00007079
7080 return CXAvailability_Available;
7081}
7082
7083static CXVersion convertVersion(VersionTuple In) {
7084 CXVersion Out = { -1, -1, -1 };
7085 if (In.empty())
7086 return Out;
7087
7088 Out.Major = In.getMajor();
7089
NAKAMURA Takumic2b5d1f2013-02-21 02:32:34 +00007090 Optional<unsigned> Minor = In.getMinor();
7091 if (Minor.hasValue())
Guy Benyei11169dd2012-12-18 14:30:41 +00007092 Out.Minor = *Minor;
7093 else
7094 return Out;
7095
NAKAMURA Takumic2b5d1f2013-02-21 02:32:34 +00007096 Optional<unsigned> Subminor = In.getSubminor();
7097 if (Subminor.hasValue())
Guy Benyei11169dd2012-12-18 14:30:41 +00007098 Out.Subminor = *Subminor;
7099
7100 return Out;
7101}
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007102
7103static int getCursorPlatformAvailabilityForDecl(const Decl *D,
7104 int *always_deprecated,
7105 CXString *deprecated_message,
7106 int *always_unavailable,
7107 CXString *unavailable_message,
7108 CXPlatformAvailability *availability,
7109 int availability_size) {
7110 bool HadAvailAttr = false;
7111 int N = 0;
Aaron Ballmanb97112e2014-03-08 22:19:01 +00007112 for (auto A : D->attrs()) {
7113 if (DeprecatedAttr *Deprecated = dyn_cast<DeprecatedAttr>(A)) {
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007114 HadAvailAttr = true;
7115 if (always_deprecated)
7116 *always_deprecated = 1;
Nico Weberaacf0312014-04-24 05:16:45 +00007117 if (deprecated_message) {
Argyrios Kyrtzidisedfe07f2014-04-24 06:05:40 +00007118 clang_disposeString(*deprecated_message);
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007119 *deprecated_message = cxstring::createDup(Deprecated->getMessage());
Nico Weberaacf0312014-04-24 05:16:45 +00007120 }
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007121 continue;
7122 }
7123
Aaron Ballmanb97112e2014-03-08 22:19:01 +00007124 if (UnavailableAttr *Unavailable = dyn_cast<UnavailableAttr>(A)) {
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007125 HadAvailAttr = true;
7126 if (always_unavailable)
7127 *always_unavailable = 1;
7128 if (unavailable_message) {
Argyrios Kyrtzidisedfe07f2014-04-24 06:05:40 +00007129 clang_disposeString(*unavailable_message);
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007130 *unavailable_message = cxstring::createDup(Unavailable->getMessage());
7131 }
7132 continue;
7133 }
7134
Aaron Ballmanb97112e2014-03-08 22:19:01 +00007135 if (AvailabilityAttr *Avail = dyn_cast<AvailabilityAttr>(A)) {
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007136 HadAvailAttr = true;
7137 if (N < availability_size) {
7138 availability[N].Platform
7139 = cxstring::createDup(Avail->getPlatform()->getName());
7140 availability[N].Introduced = convertVersion(Avail->getIntroduced());
7141 availability[N].Deprecated = convertVersion(Avail->getDeprecated());
7142 availability[N].Obsoleted = convertVersion(Avail->getObsoleted());
7143 availability[N].Unavailable = Avail->getUnavailable();
7144 availability[N].Message = cxstring::createDup(Avail->getMessage());
7145 }
7146 ++N;
7147 }
7148 }
7149
7150 if (!HadAvailAttr)
7151 if (const EnumConstantDecl *EnumConst = dyn_cast<EnumConstantDecl>(D))
7152 return getCursorPlatformAvailabilityForDecl(
7153 cast<Decl>(EnumConst->getDeclContext()),
7154 always_deprecated,
7155 deprecated_message,
7156 always_unavailable,
7157 unavailable_message,
7158 availability,
7159 availability_size);
Guy Benyei11169dd2012-12-18 14:30:41 +00007160
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007161 return N;
7162}
7163
Guy Benyei11169dd2012-12-18 14:30:41 +00007164int clang_getCursorPlatformAvailability(CXCursor cursor,
7165 int *always_deprecated,
7166 CXString *deprecated_message,
7167 int *always_unavailable,
7168 CXString *unavailable_message,
7169 CXPlatformAvailability *availability,
7170 int availability_size) {
7171 if (always_deprecated)
7172 *always_deprecated = 0;
7173 if (deprecated_message)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00007174 *deprecated_message = cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00007175 if (always_unavailable)
7176 *always_unavailable = 0;
7177 if (unavailable_message)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00007178 *unavailable_message = cxstring::createEmpty();
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007179
Guy Benyei11169dd2012-12-18 14:30:41 +00007180 if (!clang_isDeclaration(cursor.kind))
7181 return 0;
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007182
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007183 const Decl *D = cxcursor::getCursorDecl(cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00007184 if (!D)
7185 return 0;
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007186
7187 return getCursorPlatformAvailabilityForDecl(D, always_deprecated,
7188 deprecated_message,
7189 always_unavailable,
7190 unavailable_message,
7191 availability,
7192 availability_size);
Guy Benyei11169dd2012-12-18 14:30:41 +00007193}
7194
7195void clang_disposeCXPlatformAvailability(CXPlatformAvailability *availability) {
7196 clang_disposeString(availability->Platform);
7197 clang_disposeString(availability->Message);
7198}
7199
7200CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
7201 if (clang_isDeclaration(cursor.kind))
7202 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
7203
7204 return CXLanguage_Invalid;
7205}
7206
7207 /// \brief If the given cursor is the "templated" declaration
7208 /// descibing a class or function template, return the class or
7209 /// function template.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007210static const Decl *maybeGetTemplateCursor(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007211 if (!D)
Craig Topper69186e72014-06-08 08:38:04 +00007212 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007213
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007214 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00007215 if (FunctionTemplateDecl *FunTmpl = FD->getDescribedFunctionTemplate())
7216 return FunTmpl;
7217
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007218 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00007219 if (ClassTemplateDecl *ClassTmpl = RD->getDescribedClassTemplate())
7220 return ClassTmpl;
7221
7222 return D;
7223}
7224
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00007225
7226enum CX_StorageClass clang_Cursor_getStorageClass(CXCursor C) {
7227 StorageClass sc = SC_None;
7228 const Decl *D = getCursorDecl(C);
7229 if (D) {
7230 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7231 sc = FD->getStorageClass();
7232 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7233 sc = VD->getStorageClass();
7234 } else {
7235 return CX_SC_Invalid;
7236 }
7237 } else {
7238 return CX_SC_Invalid;
7239 }
7240 switch (sc) {
7241 case SC_None:
7242 return CX_SC_None;
7243 case SC_Extern:
7244 return CX_SC_Extern;
7245 case SC_Static:
7246 return CX_SC_Static;
7247 case SC_PrivateExtern:
7248 return CX_SC_PrivateExtern;
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00007249 case SC_Auto:
7250 return CX_SC_Auto;
7251 case SC_Register:
7252 return CX_SC_Register;
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00007253 }
Kaelyn Takataab61e702014-10-15 18:03:26 +00007254 llvm_unreachable("Unhandled storage class!");
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00007255}
7256
Guy Benyei11169dd2012-12-18 14:30:41 +00007257CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
7258 if (clang_isDeclaration(cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007259 if (const Decl *D = getCursorDecl(cursor)) {
7260 const DeclContext *DC = D->getDeclContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00007261 if (!DC)
7262 return clang_getNullCursor();
7263
7264 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
7265 getCursorTU(cursor));
7266 }
7267 }
7268
7269 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007270 if (const Decl *D = getCursorDecl(cursor))
Guy Benyei11169dd2012-12-18 14:30:41 +00007271 return MakeCXCursor(D, getCursorTU(cursor));
7272 }
7273
7274 return clang_getNullCursor();
7275}
7276
7277CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
7278 if (clang_isDeclaration(cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007279 if (const Decl *D = getCursorDecl(cursor)) {
7280 const DeclContext *DC = D->getLexicalDeclContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00007281 if (!DC)
7282 return clang_getNullCursor();
7283
7284 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
7285 getCursorTU(cursor));
7286 }
7287 }
7288
7289 // FIXME: Note that we can't easily compute the lexical context of a
7290 // statement or expression, so we return nothing.
7291 return clang_getNullCursor();
7292}
7293
7294CXFile clang_getIncludedFile(CXCursor cursor) {
7295 if (cursor.kind != CXCursor_InclusionDirective)
Craig Topper69186e72014-06-08 08:38:04 +00007296 return nullptr;
7297
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00007298 const InclusionDirective *ID = getCursorInclusionDirective(cursor);
Dmitri Gribenkof9304482013-01-23 15:56:07 +00007299 return const_cast<FileEntry *>(ID->getFile());
Guy Benyei11169dd2012-12-18 14:30:41 +00007300}
7301
Argyrios Kyrtzidis9adfd8a2013-04-18 22:15:49 +00007302unsigned clang_Cursor_getObjCPropertyAttributes(CXCursor C, unsigned reserved) {
7303 if (C.kind != CXCursor_ObjCPropertyDecl)
7304 return CXObjCPropertyAttr_noattr;
7305
7306 unsigned Result = CXObjCPropertyAttr_noattr;
7307 const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(getCursorDecl(C));
7308 ObjCPropertyDecl::PropertyAttributeKind Attr =
7309 PD->getPropertyAttributesAsWritten();
7310
7311#define SET_CXOBJCPROP_ATTR(A) \
7312 if (Attr & ObjCPropertyDecl::OBJC_PR_##A) \
7313 Result |= CXObjCPropertyAttr_##A
7314 SET_CXOBJCPROP_ATTR(readonly);
7315 SET_CXOBJCPROP_ATTR(getter);
7316 SET_CXOBJCPROP_ATTR(assign);
7317 SET_CXOBJCPROP_ATTR(readwrite);
7318 SET_CXOBJCPROP_ATTR(retain);
7319 SET_CXOBJCPROP_ATTR(copy);
7320 SET_CXOBJCPROP_ATTR(nonatomic);
7321 SET_CXOBJCPROP_ATTR(setter);
7322 SET_CXOBJCPROP_ATTR(atomic);
7323 SET_CXOBJCPROP_ATTR(weak);
7324 SET_CXOBJCPROP_ATTR(strong);
7325 SET_CXOBJCPROP_ATTR(unsafe_unretained);
Manman Ren04fd4d82016-05-31 23:22:04 +00007326 SET_CXOBJCPROP_ATTR(class);
Argyrios Kyrtzidis9adfd8a2013-04-18 22:15:49 +00007327#undef SET_CXOBJCPROP_ATTR
7328
7329 return Result;
7330}
7331
Argyrios Kyrtzidis9d9bc012013-04-18 23:29:12 +00007332unsigned clang_Cursor_getObjCDeclQualifiers(CXCursor C) {
7333 if (!clang_isDeclaration(C.kind))
7334 return CXObjCDeclQualifier_None;
7335
7336 Decl::ObjCDeclQualifier QT = Decl::OBJC_TQ_None;
7337 const Decl *D = getCursorDecl(C);
7338 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
7339 QT = MD->getObjCDeclQualifier();
7340 else if (const ParmVarDecl *PD = dyn_cast<ParmVarDecl>(D))
7341 QT = PD->getObjCDeclQualifier();
7342 if (QT == Decl::OBJC_TQ_None)
7343 return CXObjCDeclQualifier_None;
7344
7345 unsigned Result = CXObjCDeclQualifier_None;
7346 if (QT & Decl::OBJC_TQ_In) Result |= CXObjCDeclQualifier_In;
7347 if (QT & Decl::OBJC_TQ_Inout) Result |= CXObjCDeclQualifier_Inout;
7348 if (QT & Decl::OBJC_TQ_Out) Result |= CXObjCDeclQualifier_Out;
7349 if (QT & Decl::OBJC_TQ_Bycopy) Result |= CXObjCDeclQualifier_Bycopy;
7350 if (QT & Decl::OBJC_TQ_Byref) Result |= CXObjCDeclQualifier_Byref;
7351 if (QT & Decl::OBJC_TQ_Oneway) Result |= CXObjCDeclQualifier_Oneway;
7352
7353 return Result;
7354}
7355
Argyrios Kyrtzidis7b50fc52013-07-05 20:44:37 +00007356unsigned clang_Cursor_isObjCOptional(CXCursor C) {
7357 if (!clang_isDeclaration(C.kind))
7358 return 0;
7359
7360 const Decl *D = getCursorDecl(C);
7361 if (const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D))
7362 return PD->getPropertyImplementation() == ObjCPropertyDecl::Optional;
7363 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
7364 return MD->getImplementationControl() == ObjCMethodDecl::Optional;
7365
7366 return 0;
7367}
7368
Argyrios Kyrtzidis23814e42013-04-18 23:53:05 +00007369unsigned clang_Cursor_isVariadic(CXCursor C) {
7370 if (!clang_isDeclaration(C.kind))
7371 return 0;
7372
7373 const Decl *D = getCursorDecl(C);
7374 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
7375 return FD->isVariadic();
7376 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
7377 return MD->isVariadic();
7378
7379 return 0;
7380}
7381
Guy Benyei11169dd2012-12-18 14:30:41 +00007382CXSourceRange clang_Cursor_getCommentRange(CXCursor C) {
7383 if (!clang_isDeclaration(C.kind))
7384 return clang_getNullRange();
7385
7386 const Decl *D = getCursorDecl(C);
7387 ASTContext &Context = getCursorContext(C);
7388 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
7389 if (!RC)
7390 return clang_getNullRange();
7391
7392 return cxloc::translateSourceRange(Context, RC->getSourceRange());
7393}
7394
7395CXString clang_Cursor_getRawCommentText(CXCursor C) {
7396 if (!clang_isDeclaration(C.kind))
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00007397 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00007398
7399 const Decl *D = getCursorDecl(C);
7400 ASTContext &Context = getCursorContext(C);
7401 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
7402 StringRef RawText = RC ? RC->getRawText(Context.getSourceManager()) :
7403 StringRef();
7404
7405 // Don't duplicate the string because RawText points directly into source
7406 // code.
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00007407 return cxstring::createRef(RawText);
Guy Benyei11169dd2012-12-18 14:30:41 +00007408}
7409
7410CXString clang_Cursor_getBriefCommentText(CXCursor C) {
7411 if (!clang_isDeclaration(C.kind))
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00007412 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00007413
7414 const Decl *D = getCursorDecl(C);
7415 const ASTContext &Context = getCursorContext(C);
7416 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
7417
7418 if (RC) {
7419 StringRef BriefText = RC->getBriefText(Context);
7420
7421 // Don't duplicate the string because RawComment ensures that this memory
7422 // will not go away.
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00007423 return cxstring::createRef(BriefText);
Guy Benyei11169dd2012-12-18 14:30:41 +00007424 }
7425
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00007426 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00007427}
7428
Guy Benyei11169dd2012-12-18 14:30:41 +00007429CXModule clang_Cursor_getModule(CXCursor C) {
7430 if (C.kind == CXCursor_ModuleImportDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007431 if (const ImportDecl *ImportD =
7432 dyn_cast_or_null<ImportDecl>(getCursorDecl(C)))
Guy Benyei11169dd2012-12-18 14:30:41 +00007433 return ImportD->getImportedModule();
7434 }
7435
Craig Topper69186e72014-06-08 08:38:04 +00007436 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007437}
7438
Argyrios Kyrtzidisf6d49c32014-05-14 23:14:37 +00007439CXModule clang_getModuleForFile(CXTranslationUnit TU, CXFile File) {
7440 if (isNotUsableTU(TU)) {
7441 LOG_BAD_TU(TU);
7442 return nullptr;
7443 }
7444 if (!File)
7445 return nullptr;
7446 FileEntry *FE = static_cast<FileEntry *>(File);
7447
7448 ASTUnit &Unit = *cxtu::getASTUnit(TU);
7449 HeaderSearch &HS = Unit.getPreprocessor().getHeaderSearchInfo();
7450 ModuleMap::KnownHeader Header = HS.findModuleForHeader(FE);
7451
Richard Smithfeb54b62014-10-23 02:01:19 +00007452 return Header.getModule();
Argyrios Kyrtzidisf6d49c32014-05-14 23:14:37 +00007453}
7454
Argyrios Kyrtzidis12fdb9e2013-04-26 22:47:49 +00007455CXFile clang_Module_getASTFile(CXModule CXMod) {
7456 if (!CXMod)
Craig Topper69186e72014-06-08 08:38:04 +00007457 return nullptr;
Argyrios Kyrtzidis12fdb9e2013-04-26 22:47:49 +00007458 Module *Mod = static_cast<Module*>(CXMod);
7459 return const_cast<FileEntry *>(Mod->getASTFile());
7460}
7461
Guy Benyei11169dd2012-12-18 14:30:41 +00007462CXModule clang_Module_getParent(CXModule CXMod) {
7463 if (!CXMod)
Craig Topper69186e72014-06-08 08:38:04 +00007464 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007465 Module *Mod = static_cast<Module*>(CXMod);
7466 return Mod->Parent;
7467}
7468
7469CXString clang_Module_getName(CXModule CXMod) {
7470 if (!CXMod)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00007471 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00007472 Module *Mod = static_cast<Module*>(CXMod);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00007473 return cxstring::createDup(Mod->Name);
Guy Benyei11169dd2012-12-18 14:30:41 +00007474}
7475
7476CXString clang_Module_getFullName(CXModule CXMod) {
7477 if (!CXMod)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00007478 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00007479 Module *Mod = static_cast<Module*>(CXMod);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00007480 return cxstring::createDup(Mod->getFullModuleName());
Guy Benyei11169dd2012-12-18 14:30:41 +00007481}
7482
Argyrios Kyrtzidis884337f2014-05-15 04:44:25 +00007483int clang_Module_isSystem(CXModule CXMod) {
7484 if (!CXMod)
7485 return 0;
7486 Module *Mod = static_cast<Module*>(CXMod);
7487 return Mod->IsSystem;
7488}
7489
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00007490unsigned clang_Module_getNumTopLevelHeaders(CXTranslationUnit TU,
7491 CXModule CXMod) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00007492 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00007493 LOG_BAD_TU(TU);
7494 return 0;
7495 }
7496 if (!CXMod)
Guy Benyei11169dd2012-12-18 14:30:41 +00007497 return 0;
7498 Module *Mod = static_cast<Module*>(CXMod);
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00007499 FileManager &FileMgr = cxtu::getASTUnit(TU)->getFileManager();
7500 ArrayRef<const FileEntry *> TopHeaders = Mod->getTopHeaders(FileMgr);
7501 return TopHeaders.size();
Guy Benyei11169dd2012-12-18 14:30:41 +00007502}
7503
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00007504CXFile clang_Module_getTopLevelHeader(CXTranslationUnit TU,
7505 CXModule CXMod, unsigned Index) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00007506 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00007507 LOG_BAD_TU(TU);
Craig Topper69186e72014-06-08 08:38:04 +00007508 return nullptr;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00007509 }
7510 if (!CXMod)
Craig Topper69186e72014-06-08 08:38:04 +00007511 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007512 Module *Mod = static_cast<Module*>(CXMod);
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00007513 FileManager &FileMgr = cxtu::getASTUnit(TU)->getFileManager();
Guy Benyei11169dd2012-12-18 14:30:41 +00007514
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00007515 ArrayRef<const FileEntry *> TopHeaders = Mod->getTopHeaders(FileMgr);
7516 if (Index < TopHeaders.size())
7517 return const_cast<FileEntry *>(TopHeaders[Index]);
Guy Benyei11169dd2012-12-18 14:30:41 +00007518
Craig Topper69186e72014-06-08 08:38:04 +00007519 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007520}
7521
Guy Benyei11169dd2012-12-18 14:30:41 +00007522//===----------------------------------------------------------------------===//
7523// C++ AST instrospection.
7524//===----------------------------------------------------------------------===//
7525
Jonathan Coe29565352016-04-27 12:48:25 +00007526unsigned clang_CXXConstructor_isDefaultConstructor(CXCursor C) {
7527 if (!clang_isDeclaration(C.kind))
7528 return 0;
7529
7530 const Decl *D = cxcursor::getCursorDecl(C);
7531 const CXXConstructorDecl *Constructor =
7532 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
7533 return (Constructor && Constructor->isDefaultConstructor()) ? 1 : 0;
7534}
7535
7536unsigned clang_CXXConstructor_isCopyConstructor(CXCursor C) {
7537 if (!clang_isDeclaration(C.kind))
7538 return 0;
7539
7540 const Decl *D = cxcursor::getCursorDecl(C);
7541 const CXXConstructorDecl *Constructor =
7542 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
7543 return (Constructor && Constructor->isCopyConstructor()) ? 1 : 0;
7544}
7545
7546unsigned clang_CXXConstructor_isMoveConstructor(CXCursor C) {
7547 if (!clang_isDeclaration(C.kind))
7548 return 0;
7549
7550 const Decl *D = cxcursor::getCursorDecl(C);
7551 const CXXConstructorDecl *Constructor =
7552 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
7553 return (Constructor && Constructor->isMoveConstructor()) ? 1 : 0;
7554}
7555
7556unsigned clang_CXXConstructor_isConvertingConstructor(CXCursor C) {
7557 if (!clang_isDeclaration(C.kind))
7558 return 0;
7559
7560 const Decl *D = cxcursor::getCursorDecl(C);
7561 const CXXConstructorDecl *Constructor =
7562 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
7563 // Passing 'false' excludes constructors marked 'explicit'.
7564 return (Constructor && Constructor->isConvertingConstructor(false)) ? 1 : 0;
7565}
7566
Saleem Abdulrasool6ea75db2015-10-27 15:50:22 +00007567unsigned clang_CXXField_isMutable(CXCursor C) {
7568 if (!clang_isDeclaration(C.kind))
7569 return 0;
7570
7571 if (const auto D = cxcursor::getCursorDecl(C))
7572 if (const auto FD = dyn_cast_or_null<FieldDecl>(D))
7573 return FD->isMutable() ? 1 : 0;
7574 return 0;
7575}
7576
Dmitri Gribenko62770be2013-05-17 18:38:35 +00007577unsigned clang_CXXMethod_isPureVirtual(CXCursor C) {
7578 if (!clang_isDeclaration(C.kind))
7579 return 0;
7580
Dmitri Gribenko62770be2013-05-17 18:38:35 +00007581 const Decl *D = cxcursor::getCursorDecl(C);
Alp Tokera2794f92014-01-22 07:29:52 +00007582 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00007583 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Dmitri Gribenko62770be2013-05-17 18:38:35 +00007584 return (Method && Method->isVirtual() && Method->isPure()) ? 1 : 0;
7585}
7586
Dmitri Gribenkoe570ede2014-04-07 14:59:13 +00007587unsigned clang_CXXMethod_isConst(CXCursor C) {
7588 if (!clang_isDeclaration(C.kind))
7589 return 0;
7590
7591 const Decl *D = cxcursor::getCursorDecl(C);
7592 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00007593 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Dmitri Gribenkoe570ede2014-04-07 14:59:13 +00007594 return (Method && (Method->getTypeQualifiers() & Qualifiers::Const)) ? 1 : 0;
7595}
7596
Jonathan Coe29565352016-04-27 12:48:25 +00007597unsigned clang_CXXMethod_isDefaulted(CXCursor C) {
7598 if (!clang_isDeclaration(C.kind))
7599 return 0;
7600
7601 const Decl *D = cxcursor::getCursorDecl(C);
7602 const CXXMethodDecl *Method =
7603 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
7604 return (Method && Method->isDefaulted()) ? 1 : 0;
7605}
7606
Guy Benyei11169dd2012-12-18 14:30:41 +00007607unsigned clang_CXXMethod_isStatic(CXCursor C) {
7608 if (!clang_isDeclaration(C.kind))
7609 return 0;
7610
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007611 const Decl *D = cxcursor::getCursorDecl(C);
Alp Tokera2794f92014-01-22 07:29:52 +00007612 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00007613 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007614 return (Method && Method->isStatic()) ? 1 : 0;
7615}
7616
7617unsigned clang_CXXMethod_isVirtual(CXCursor C) {
7618 if (!clang_isDeclaration(C.kind))
7619 return 0;
7620
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007621 const Decl *D = cxcursor::getCursorDecl(C);
Alp Tokera2794f92014-01-22 07:29:52 +00007622 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00007623 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007624 return (Method && Method->isVirtual()) ? 1 : 0;
7625}
Guy Benyei11169dd2012-12-18 14:30:41 +00007626
7627//===----------------------------------------------------------------------===//
7628// Attribute introspection.
7629//===----------------------------------------------------------------------===//
7630
Guy Benyei11169dd2012-12-18 14:30:41 +00007631CXType clang_getIBOutletCollectionType(CXCursor C) {
7632 if (C.kind != CXCursor_IBOutletCollectionAttr)
7633 return cxtype::MakeCXType(QualType(), cxcursor::getCursorTU(C));
7634
Dmitri Gribenkoe4baea62013-01-26 18:08:08 +00007635 const IBOutletCollectionAttr *A =
Guy Benyei11169dd2012-12-18 14:30:41 +00007636 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
7637
7638 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorTU(C));
7639}
Guy Benyei11169dd2012-12-18 14:30:41 +00007640
7641//===----------------------------------------------------------------------===//
7642// Inspecting memory usage.
7643//===----------------------------------------------------------------------===//
7644
7645typedef std::vector<CXTUResourceUsageEntry> MemUsageEntries;
7646
7647static inline void createCXTUResourceUsageEntry(MemUsageEntries &entries,
7648 enum CXTUResourceUsageKind k,
7649 unsigned long amount) {
7650 CXTUResourceUsageEntry entry = { k, amount };
7651 entries.push_back(entry);
7652}
7653
Guy Benyei11169dd2012-12-18 14:30:41 +00007654const char *clang_getTUResourceUsageName(CXTUResourceUsageKind kind) {
7655 const char *str = "";
7656 switch (kind) {
7657 case CXTUResourceUsage_AST:
7658 str = "ASTContext: expressions, declarations, and types";
7659 break;
7660 case CXTUResourceUsage_Identifiers:
7661 str = "ASTContext: identifiers";
7662 break;
7663 case CXTUResourceUsage_Selectors:
7664 str = "ASTContext: selectors";
7665 break;
7666 case CXTUResourceUsage_GlobalCompletionResults:
7667 str = "Code completion: cached global results";
7668 break;
7669 case CXTUResourceUsage_SourceManagerContentCache:
7670 str = "SourceManager: content cache allocator";
7671 break;
7672 case CXTUResourceUsage_AST_SideTables:
7673 str = "ASTContext: side tables";
7674 break;
7675 case CXTUResourceUsage_SourceManager_Membuffer_Malloc:
7676 str = "SourceManager: malloc'ed memory buffers";
7677 break;
7678 case CXTUResourceUsage_SourceManager_Membuffer_MMap:
7679 str = "SourceManager: mmap'ed memory buffers";
7680 break;
7681 case CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc:
7682 str = "ExternalASTSource: malloc'ed memory buffers";
7683 break;
7684 case CXTUResourceUsage_ExternalASTSource_Membuffer_MMap:
7685 str = "ExternalASTSource: mmap'ed memory buffers";
7686 break;
7687 case CXTUResourceUsage_Preprocessor:
7688 str = "Preprocessor: malloc'ed memory";
7689 break;
7690 case CXTUResourceUsage_PreprocessingRecord:
7691 str = "Preprocessor: PreprocessingRecord";
7692 break;
7693 case CXTUResourceUsage_SourceManager_DataStructures:
7694 str = "SourceManager: data structures and tables";
7695 break;
7696 case CXTUResourceUsage_Preprocessor_HeaderSearch:
7697 str = "Preprocessor: header search tables";
7698 break;
7699 }
7700 return str;
7701}
7702
7703CXTUResourceUsage clang_getCXTUResourceUsage(CXTranslationUnit TU) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00007704 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00007705 LOG_BAD_TU(TU);
Craig Topper69186e72014-06-08 08:38:04 +00007706 CXTUResourceUsage usage = { (void*) nullptr, 0, nullptr };
Guy Benyei11169dd2012-12-18 14:30:41 +00007707 return usage;
7708 }
7709
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00007710 ASTUnit *astUnit = cxtu::getASTUnit(TU);
Ahmed Charlesb8984322014-03-07 20:03:18 +00007711 std::unique_ptr<MemUsageEntries> entries(new MemUsageEntries());
Guy Benyei11169dd2012-12-18 14:30:41 +00007712 ASTContext &astContext = astUnit->getASTContext();
7713
7714 // How much memory is used by AST nodes and types?
7715 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST,
7716 (unsigned long) astContext.getASTAllocatedMemory());
7717
7718 // How much memory is used by identifiers?
7719 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Identifiers,
7720 (unsigned long) astContext.Idents.getAllocator().getTotalMemory());
7721
7722 // How much memory is used for selectors?
7723 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Selectors,
7724 (unsigned long) astContext.Selectors.getTotalMemory());
7725
7726 // How much memory is used by ASTContext's side tables?
7727 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST_SideTables,
7728 (unsigned long) astContext.getSideTableAllocatedMemory());
7729
7730 // How much memory is used for caching global code completion results?
7731 unsigned long completionBytes = 0;
7732 if (GlobalCodeCompletionAllocator *completionAllocator =
Alp Tokerf994cef2014-07-05 03:08:06 +00007733 astUnit->getCachedCompletionAllocator().get()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007734 completionBytes = completionAllocator->getTotalMemory();
7735 }
7736 createCXTUResourceUsageEntry(*entries,
7737 CXTUResourceUsage_GlobalCompletionResults,
7738 completionBytes);
7739
7740 // How much memory is being used by SourceManager's content cache?
7741 createCXTUResourceUsageEntry(*entries,
7742 CXTUResourceUsage_SourceManagerContentCache,
7743 (unsigned long) astContext.getSourceManager().getContentCacheSize());
7744
7745 // How much memory is being used by the MemoryBuffer's in SourceManager?
7746 const SourceManager::MemoryBufferSizes &srcBufs =
7747 astUnit->getSourceManager().getMemoryBufferSizes();
7748
7749 createCXTUResourceUsageEntry(*entries,
7750 CXTUResourceUsage_SourceManager_Membuffer_Malloc,
7751 (unsigned long) srcBufs.malloc_bytes);
7752 createCXTUResourceUsageEntry(*entries,
7753 CXTUResourceUsage_SourceManager_Membuffer_MMap,
7754 (unsigned long) srcBufs.mmap_bytes);
7755 createCXTUResourceUsageEntry(*entries,
7756 CXTUResourceUsage_SourceManager_DataStructures,
7757 (unsigned long) astContext.getSourceManager()
7758 .getDataStructureSizes());
7759
7760 // How much memory is being used by the ExternalASTSource?
7761 if (ExternalASTSource *esrc = astContext.getExternalSource()) {
7762 const ExternalASTSource::MemoryBufferSizes &sizes =
7763 esrc->getMemoryBufferSizes();
7764
7765 createCXTUResourceUsageEntry(*entries,
7766 CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc,
7767 (unsigned long) sizes.malloc_bytes);
7768 createCXTUResourceUsageEntry(*entries,
7769 CXTUResourceUsage_ExternalASTSource_Membuffer_MMap,
7770 (unsigned long) sizes.mmap_bytes);
7771 }
7772
7773 // How much memory is being used by the Preprocessor?
7774 Preprocessor &pp = astUnit->getPreprocessor();
7775 createCXTUResourceUsageEntry(*entries,
7776 CXTUResourceUsage_Preprocessor,
7777 pp.getTotalMemory());
7778
7779 if (PreprocessingRecord *pRec = pp.getPreprocessingRecord()) {
7780 createCXTUResourceUsageEntry(*entries,
7781 CXTUResourceUsage_PreprocessingRecord,
7782 pRec->getTotalMemory());
7783 }
7784
7785 createCXTUResourceUsageEntry(*entries,
7786 CXTUResourceUsage_Preprocessor_HeaderSearch,
7787 pp.getHeaderSearchInfo().getTotalMemory());
Craig Topper69186e72014-06-08 08:38:04 +00007788
Guy Benyei11169dd2012-12-18 14:30:41 +00007789 CXTUResourceUsage usage = { (void*) entries.get(),
7790 (unsigned) entries->size(),
Alexander Kornienko6ee521c2015-01-23 15:36:10 +00007791 !entries->empty() ? &(*entries)[0] : nullptr };
Eric Fiseliere95fc442016-11-14 07:03:50 +00007792 (void)entries.release();
Guy Benyei11169dd2012-12-18 14:30:41 +00007793 return usage;
7794}
7795
7796void clang_disposeCXTUResourceUsage(CXTUResourceUsage usage) {
7797 if (usage.data)
7798 delete (MemUsageEntries*) usage.data;
7799}
7800
Argyrios Kyrtzidis0e282ef2013-12-06 18:55:45 +00007801CXSourceRangeList *clang_getSkippedRanges(CXTranslationUnit TU, CXFile file) {
7802 CXSourceRangeList *skipped = new CXSourceRangeList;
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00007803 skipped->count = 0;
Craig Topper69186e72014-06-08 08:38:04 +00007804 skipped->ranges = nullptr;
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00007805
Dmitri Gribenko852d6222014-02-11 15:02:48 +00007806 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00007807 LOG_BAD_TU(TU);
7808 return skipped;
7809 }
7810
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00007811 if (!file)
7812 return skipped;
7813
7814 ASTUnit *astUnit = cxtu::getASTUnit(TU);
7815 PreprocessingRecord *ppRec = astUnit->getPreprocessor().getPreprocessingRecord();
7816 if (!ppRec)
7817 return skipped;
7818
7819 ASTContext &Ctx = astUnit->getASTContext();
7820 SourceManager &sm = Ctx.getSourceManager();
7821 FileEntry *fileEntry = static_cast<FileEntry *>(file);
7822 FileID wantedFileID = sm.translateFile(fileEntry);
7823
7824 const std::vector<SourceRange> &SkippedRanges = ppRec->getSkippedRanges();
7825 std::vector<SourceRange> wantedRanges;
7826 for (std::vector<SourceRange>::const_iterator i = SkippedRanges.begin(), ei = SkippedRanges.end();
7827 i != ei; ++i) {
7828 if (sm.getFileID(i->getBegin()) == wantedFileID || sm.getFileID(i->getEnd()) == wantedFileID)
7829 wantedRanges.push_back(*i);
7830 }
7831
7832 skipped->count = wantedRanges.size();
7833 skipped->ranges = new CXSourceRange[skipped->count];
7834 for (unsigned i = 0, ei = skipped->count; i != ei; ++i)
7835 skipped->ranges[i] = cxloc::translateSourceRange(Ctx, wantedRanges[i]);
7836
7837 return skipped;
7838}
7839
Cameron Desrochersd8091282016-08-18 15:43:55 +00007840CXSourceRangeList *clang_getAllSkippedRanges(CXTranslationUnit TU) {
7841 CXSourceRangeList *skipped = new CXSourceRangeList;
7842 skipped->count = 0;
7843 skipped->ranges = nullptr;
7844
7845 if (isNotUsableTU(TU)) {
7846 LOG_BAD_TU(TU);
7847 return skipped;
7848 }
7849
7850 ASTUnit *astUnit = cxtu::getASTUnit(TU);
7851 PreprocessingRecord *ppRec = astUnit->getPreprocessor().getPreprocessingRecord();
7852 if (!ppRec)
7853 return skipped;
7854
7855 ASTContext &Ctx = astUnit->getASTContext();
7856
7857 const std::vector<SourceRange> &SkippedRanges = ppRec->getSkippedRanges();
7858
7859 skipped->count = SkippedRanges.size();
7860 skipped->ranges = new CXSourceRange[skipped->count];
7861 for (unsigned i = 0, ei = skipped->count; i != ei; ++i)
7862 skipped->ranges[i] = cxloc::translateSourceRange(Ctx, SkippedRanges[i]);
7863
7864 return skipped;
7865}
7866
Argyrios Kyrtzidis0e282ef2013-12-06 18:55:45 +00007867void clang_disposeSourceRangeList(CXSourceRangeList *ranges) {
7868 if (ranges) {
7869 delete[] ranges->ranges;
7870 delete ranges;
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00007871 }
7872}
7873
Guy Benyei11169dd2012-12-18 14:30:41 +00007874void clang::PrintLibclangResourceUsage(CXTranslationUnit TU) {
7875 CXTUResourceUsage Usage = clang_getCXTUResourceUsage(TU);
7876 for (unsigned I = 0; I != Usage.numEntries; ++I)
7877 fprintf(stderr, " %s: %lu\n",
7878 clang_getTUResourceUsageName(Usage.entries[I].kind),
7879 Usage.entries[I].amount);
7880
7881 clang_disposeCXTUResourceUsage(Usage);
7882}
7883
7884//===----------------------------------------------------------------------===//
7885// Misc. utility functions.
7886//===----------------------------------------------------------------------===//
7887
7888/// Default to using an 8 MB stack size on "safety" threads.
7889static unsigned SafetyStackThreadSize = 8 << 20;
7890
7891namespace clang {
7892
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00007893bool RunSafely(llvm::CrashRecoveryContext &CRC, llvm::function_ref<void()> Fn,
Guy Benyei11169dd2012-12-18 14:30:41 +00007894 unsigned Size) {
7895 if (!Size)
7896 Size = GetSafetyThreadStackSize();
7897 if (Size)
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00007898 return CRC.RunSafelyOnThread(Fn, Size);
7899 return CRC.RunSafely(Fn);
Guy Benyei11169dd2012-12-18 14:30:41 +00007900}
7901
7902unsigned GetSafetyThreadStackSize() {
7903 return SafetyStackThreadSize;
7904}
7905
7906void SetSafetyThreadStackSize(unsigned Value) {
7907 SafetyStackThreadSize = Value;
7908}
7909
Alexander Kornienkoab9db512015-06-22 23:07:51 +00007910}
Guy Benyei11169dd2012-12-18 14:30:41 +00007911
7912void clang::setThreadBackgroundPriority() {
7913 if (getenv("LIBCLANG_BGPRIO_DISABLE"))
7914 return;
7915
Alp Toker1a86ad22014-07-06 06:24:00 +00007916#ifdef USE_DARWIN_THREADS
Guy Benyei11169dd2012-12-18 14:30:41 +00007917 setpriority(PRIO_DARWIN_THREAD, 0, PRIO_DARWIN_BG);
7918#endif
7919}
7920
7921void cxindex::printDiagsToStderr(ASTUnit *Unit) {
7922 if (!Unit)
7923 return;
7924
7925 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
7926 DEnd = Unit->stored_diag_end();
7927 D != DEnd; ++D) {
Ben Langmuir749323f2014-04-22 17:40:12 +00007928 CXStoredDiagnostic Diag(*D, Unit->getLangOpts());
Guy Benyei11169dd2012-12-18 14:30:41 +00007929 CXString Msg = clang_formatDiagnostic(&Diag,
7930 clang_defaultDiagnosticDisplayOptions());
7931 fprintf(stderr, "%s\n", clang_getCString(Msg));
7932 clang_disposeString(Msg);
7933 }
7934#ifdef LLVM_ON_WIN32
7935 // On Windows, force a flush, since there may be multiple copies of
7936 // stderr and stdout in the file system, all with different buffers
7937 // but writing to the same device.
7938 fflush(stderr);
7939#endif
7940}
7941
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007942MacroInfo *cxindex::getMacroInfo(const IdentifierInfo &II,
7943 SourceLocation MacroDefLoc,
7944 CXTranslationUnit TU){
7945 if (MacroDefLoc.isInvalid() || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00007946 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007947 if (!II.hadMacroDefinition())
Craig Topper69186e72014-06-08 08:38:04 +00007948 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007949
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00007950 ASTUnit *Unit = cxtu::getASTUnit(TU);
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007951 Preprocessor &PP = Unit->getPreprocessor();
Richard Smith20e883e2015-04-29 23:20:19 +00007952 MacroDirective *MD = PP.getLocalMacroDirectiveHistory(&II);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00007953 if (MD) {
7954 for (MacroDirective::DefInfo
7955 Def = MD->getDefinition(); Def; Def = Def.getPreviousDefinition()) {
7956 if (MacroDefLoc == Def.getMacroInfo()->getDefinitionLoc())
7957 return Def.getMacroInfo();
7958 }
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007959 }
7960
Craig Topper69186e72014-06-08 08:38:04 +00007961 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007962}
7963
Richard Smith66a81862015-05-04 02:25:31 +00007964const MacroInfo *cxindex::getMacroInfo(const MacroDefinitionRecord *MacroDef,
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00007965 CXTranslationUnit TU) {
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007966 if (!MacroDef || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00007967 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007968 const IdentifierInfo *II = MacroDef->getName();
7969 if (!II)
Craig Topper69186e72014-06-08 08:38:04 +00007970 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007971
7972 return getMacroInfo(*II, MacroDef->getLocation(), TU);
7973}
7974
Richard Smith66a81862015-05-04 02:25:31 +00007975MacroDefinitionRecord *
7976cxindex::checkForMacroInMacroDefinition(const MacroInfo *MI, const Token &Tok,
7977 CXTranslationUnit TU) {
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007978 if (!MI || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00007979 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007980 if (Tok.isNot(tok::raw_identifier))
Craig Topper69186e72014-06-08 08:38:04 +00007981 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007982
7983 if (MI->getNumTokens() == 0)
Craig Topper69186e72014-06-08 08:38:04 +00007984 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007985 SourceRange DefRange(MI->getReplacementToken(0).getLocation(),
7986 MI->getDefinitionEndLoc());
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00007987 ASTUnit *Unit = cxtu::getASTUnit(TU);
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007988
7989 // Check that the token is inside the definition and not its argument list.
7990 SourceManager &SM = Unit->getSourceManager();
7991 if (SM.isBeforeInTranslationUnit(Tok.getLocation(), DefRange.getBegin()))
Craig Topper69186e72014-06-08 08:38:04 +00007992 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007993 if (SM.isBeforeInTranslationUnit(DefRange.getEnd(), Tok.getLocation()))
Craig Topper69186e72014-06-08 08:38:04 +00007994 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007995
7996 Preprocessor &PP = Unit->getPreprocessor();
7997 PreprocessingRecord *PPRec = PP.getPreprocessingRecord();
7998 if (!PPRec)
Craig Topper69186e72014-06-08 08:38:04 +00007999 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008000
Alp Toker2d57cea2014-05-17 04:53:25 +00008001 IdentifierInfo &II = PP.getIdentifierTable().get(Tok.getRawIdentifier());
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008002 if (!II.hadMacroDefinition())
Craig Topper69186e72014-06-08 08:38:04 +00008003 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008004
8005 // Check that the identifier is not one of the macro arguments.
8006 if (std::find(MI->arg_begin(), MI->arg_end(), &II) != MI->arg_end())
Craig Topper69186e72014-06-08 08:38:04 +00008007 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008008
Richard Smith20e883e2015-04-29 23:20:19 +00008009 MacroDirective *InnerMD = PP.getLocalMacroDirectiveHistory(&II);
Argyrios Kyrtzidis09c9e812013-02-20 00:54:57 +00008010 if (!InnerMD)
Craig Topper69186e72014-06-08 08:38:04 +00008011 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008012
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00008013 return PPRec->findMacroDefinition(InnerMD->getMacroInfo());
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008014}
8015
Richard Smith66a81862015-05-04 02:25:31 +00008016MacroDefinitionRecord *
8017cxindex::checkForMacroInMacroDefinition(const MacroInfo *MI, SourceLocation Loc,
8018 CXTranslationUnit TU) {
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008019 if (Loc.isInvalid() || !MI || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00008020 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008021
8022 if (MI->getNumTokens() == 0)
Craig Topper69186e72014-06-08 08:38:04 +00008023 return nullptr;
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008024 ASTUnit *Unit = cxtu::getASTUnit(TU);
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008025 Preprocessor &PP = Unit->getPreprocessor();
8026 if (!PP.getPreprocessingRecord())
Craig Topper69186e72014-06-08 08:38:04 +00008027 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008028 Loc = Unit->getSourceManager().getSpellingLoc(Loc);
8029 Token Tok;
8030 if (PP.getRawToken(Loc, Tok))
Craig Topper69186e72014-06-08 08:38:04 +00008031 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008032
8033 return checkForMacroInMacroDefinition(MI, Tok, TU);
8034}
8035
Guy Benyei11169dd2012-12-18 14:30:41 +00008036CXString clang_getClangVersion() {
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00008037 return cxstring::createDup(getClangFullVersion());
Guy Benyei11169dd2012-12-18 14:30:41 +00008038}
8039
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008040Logger &cxindex::Logger::operator<<(CXTranslationUnit TU) {
8041 if (TU) {
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008042 if (ASTUnit *Unit = cxtu::getASTUnit(TU)) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008043 LogOS << '<' << Unit->getMainFileName() << '>';
Argyrios Kyrtzidis37f2ab42013-03-05 20:21:14 +00008044 if (Unit->isMainFileAST())
8045 LogOS << " (" << Unit->getASTFileName() << ')';
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008046 return *this;
8047 }
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00008048 } else {
8049 LogOS << "<NULL TU>";
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008050 }
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008051 return *this;
8052}
8053
Argyrios Kyrtzidisba4b5f82013-03-08 02:32:26 +00008054Logger &cxindex::Logger::operator<<(const FileEntry *FE) {
8055 *this << FE->getName();
8056 return *this;
8057}
8058
8059Logger &cxindex::Logger::operator<<(CXCursor cursor) {
8060 CXString cursorName = clang_getCursorDisplayName(cursor);
8061 *this << cursorName << "@" << clang_getCursorLocation(cursor);
8062 clang_disposeString(cursorName);
8063 return *this;
8064}
8065
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008066Logger &cxindex::Logger::operator<<(CXSourceLocation Loc) {
8067 CXFile File;
8068 unsigned Line, Column;
Craig Topper69186e72014-06-08 08:38:04 +00008069 clang_getFileLocation(Loc, &File, &Line, &Column, nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008070 CXString FileName = clang_getFileName(File);
8071 *this << llvm::format("(%s:%d:%d)", clang_getCString(FileName), Line, Column);
8072 clang_disposeString(FileName);
8073 return *this;
8074}
8075
8076Logger &cxindex::Logger::operator<<(CXSourceRange range) {
8077 CXSourceLocation BLoc = clang_getRangeStart(range);
8078 CXSourceLocation ELoc = clang_getRangeEnd(range);
8079
8080 CXFile BFile;
8081 unsigned BLine, BColumn;
Craig Topper69186e72014-06-08 08:38:04 +00008082 clang_getFileLocation(BLoc, &BFile, &BLine, &BColumn, nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008083
8084 CXFile EFile;
8085 unsigned ELine, EColumn;
Craig Topper69186e72014-06-08 08:38:04 +00008086 clang_getFileLocation(ELoc, &EFile, &ELine, &EColumn, nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008087
8088 CXString BFileName = clang_getFileName(BFile);
8089 if (BFile == EFile) {
8090 *this << llvm::format("[%s %d:%d-%d:%d]", clang_getCString(BFileName),
8091 BLine, BColumn, ELine, EColumn);
8092 } else {
8093 CXString EFileName = clang_getFileName(EFile);
8094 *this << llvm::format("[%s:%d:%d - ", clang_getCString(BFileName),
8095 BLine, BColumn)
8096 << llvm::format("%s:%d:%d]", clang_getCString(EFileName),
8097 ELine, EColumn);
8098 clang_disposeString(EFileName);
8099 }
8100 clang_disposeString(BFileName);
8101 return *this;
8102}
8103
8104Logger &cxindex::Logger::operator<<(CXString Str) {
8105 *this << clang_getCString(Str);
8106 return *this;
8107}
8108
8109Logger &cxindex::Logger::operator<<(const llvm::format_object_base &Fmt) {
8110 LogOS << Fmt;
8111 return *this;
8112}
8113
Chandler Carruth37ad2582014-06-27 15:14:39 +00008114static llvm::ManagedStatic<llvm::sys::Mutex> LoggingMutex;
8115
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008116cxindex::Logger::~Logger() {
Chandler Carruth37ad2582014-06-27 15:14:39 +00008117 llvm::sys::ScopedLock L(*LoggingMutex);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008118
8119 static llvm::TimeRecord sBeginTR = llvm::TimeRecord::getCurrentTime();
8120
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008121 raw_ostream &OS = llvm::errs();
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008122 OS << "[libclang:" << Name << ':';
8123
Alp Toker1a86ad22014-07-06 06:24:00 +00008124#ifdef USE_DARWIN_THREADS
8125 // TODO: Portability.
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008126 mach_port_t tid = pthread_mach_thread_np(pthread_self());
8127 OS << tid << ':';
8128#endif
8129
8130 llvm::TimeRecord TR = llvm::TimeRecord::getCurrentTime();
8131 OS << llvm::format("%7.4f] ", TR.getWallTime() - sBeginTR.getWallTime());
Yaron Keren09fb7c62015-03-10 07:33:23 +00008132 OS << Msg << '\n';
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008133
8134 if (Trace) {
Zachary Turner1fe2a8d2015-03-05 19:15:09 +00008135 llvm::sys::PrintStackTrace(OS);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008136 OS << "--------------------------------------------------\n";
8137 }
8138}
Benjamin Kramerc1ffdab2016-03-03 08:58:18 +00008139
8140#ifdef CLANG_TOOL_EXTRA_BUILD
8141// This anchor is used to force the linker to link the clang-tidy plugin.
8142extern volatile int ClangTidyPluginAnchorSource;
8143static int LLVM_ATTRIBUTE_UNUSED ClangTidyPluginAnchorDestination =
8144 ClangTidyPluginAnchorSource;
Benjamin Kramer9eba7352016-11-17 15:22:36 +00008145
8146// This anchor is used to force the linker to link the clang-include-fixer
8147// plugin.
8148extern volatile int ClangIncludeFixerPluginAnchorSource;
8149static int LLVM_ATTRIBUTE_UNUSED ClangIncludeFixerPluginAnchorDestination =
8150 ClangIncludeFixerPluginAnchorSource;
Benjamin Kramerc1ffdab2016-03-03 08:58:18 +00008151#endif