blob: 40eea39f3bdbf32877fadab0170db23b4bed9868 [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
David Blaikie81d08292017-01-06 17:47:10 +000071CXTranslationUnit cxtu::MakeCXTranslationUnit(CIndexer *CIdx, ASTUnit *AU) {
Dmitri Gribenkod36209e2013-01-26 21:32:42 +000072 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;
David Blaikie81d08292017-01-06 17:47:10 +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);
Kelvin Li83c451e2016-12-25 04:52:54 +00002012 void VisitOMPTargetTeamsDistributeDirective(
2013 const OMPTargetTeamsDistributeDirective *D);
Kelvin Li80e8f562016-12-29 22:16:30 +00002014 void VisitOMPTargetTeamsDistributeParallelForDirective(
2015 const OMPTargetTeamsDistributeParallelForDirective *D);
Kelvin Li1851df52017-01-03 05:23:48 +00002016 void VisitOMPTargetTeamsDistributeParallelForSimdDirective(
2017 const OMPTargetTeamsDistributeParallelForSimdDirective *D);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002018
Guy Benyei11169dd2012-12-18 14:30:41 +00002019private:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002020 void AddDeclarationNameInfo(const Stmt *S);
Guy Benyei11169dd2012-12-18 14:30:41 +00002021 void AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier);
James Y Knight04ec5bf2015-12-24 02:59:37 +00002022 void AddExplicitTemplateArgs(const TemplateArgumentLoc *A,
2023 unsigned NumTemplateArgs);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002024 void AddMemberRef(const FieldDecl *D, SourceLocation L);
2025 void AddStmt(const Stmt *S);
2026 void AddDecl(const Decl *D, bool isFirst = true);
Guy Benyei11169dd2012-12-18 14:30:41 +00002027 void AddTypeLoc(TypeSourceInfo *TI);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002028 void EnqueueChildren(const Stmt *S);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002029 void EnqueueChildren(const OMPClause *S);
Guy Benyei11169dd2012-12-18 14:30:41 +00002030};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002031} // end anonyous namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00002032
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002033void EnqueueVisitor::AddDeclarationNameInfo(const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002034 // 'S' should always be non-null, since it comes from the
2035 // statement we are visiting.
2036 WL.push_back(DeclarationNameInfoVisit(S, Parent));
2037}
2038
2039void
2040EnqueueVisitor::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
2041 if (Qualifier)
2042 WL.push_back(NestedNameSpecifierLocVisit(Qualifier, Parent));
2043}
2044
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002045void EnqueueVisitor::AddStmt(const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002046 if (S)
2047 WL.push_back(StmtVisit(S, Parent));
2048}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002049void EnqueueVisitor::AddDecl(const Decl *D, bool isFirst) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002050 if (D)
2051 WL.push_back(DeclVisit(D, Parent, isFirst));
2052}
James Y Knight04ec5bf2015-12-24 02:59:37 +00002053void EnqueueVisitor::AddExplicitTemplateArgs(const TemplateArgumentLoc *A,
2054 unsigned NumTemplateArgs) {
2055 WL.push_back(ExplicitTemplateArgsVisit(A, A + NumTemplateArgs, Parent));
Guy Benyei11169dd2012-12-18 14:30:41 +00002056}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002057void EnqueueVisitor::AddMemberRef(const FieldDecl *D, SourceLocation L) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002058 if (D)
2059 WL.push_back(MemberRefVisit(D, L, Parent));
2060}
2061void EnqueueVisitor::AddTypeLoc(TypeSourceInfo *TI) {
2062 if (TI)
2063 WL.push_back(TypeLocVisit(TI->getTypeLoc(), Parent));
2064 }
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002065void EnqueueVisitor::EnqueueChildren(const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002066 unsigned size = WL.size();
Benjamin Kramer642f1732015-07-02 21:03:14 +00002067 for (const Stmt *SubStmt : S->children()) {
2068 AddStmt(SubStmt);
Guy Benyei11169dd2012-12-18 14:30:41 +00002069 }
2070 if (size == WL.size())
2071 return;
2072 // Now reverse the entries we just added. This will match the DFS
2073 // ordering performed by the worklist.
2074 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2075 std::reverse(I, E);
2076}
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002077namespace {
2078class OMPClauseEnqueue : public ConstOMPClauseVisitor<OMPClauseEnqueue> {
2079 EnqueueVisitor *Visitor;
Alexey Bataev756c1962013-09-24 03:17:45 +00002080 /// \brief Process clauses with list of variables.
2081 template <typename T>
2082 void VisitOMPClauseList(T *Node);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002083public:
2084 OMPClauseEnqueue(EnqueueVisitor *Visitor) : Visitor(Visitor) { }
2085#define OPENMP_CLAUSE(Name, Class) \
2086 void Visit##Class(const Class *C);
2087#include "clang/Basic/OpenMPKinds.def"
Alexey Bataev3392d762016-02-16 11:18:12 +00002088 void VisitOMPClauseWithPreInit(const OMPClauseWithPreInit *C);
Alexey Bataev005248a2016-02-25 05:25:57 +00002089 void VisitOMPClauseWithPostUpdate(const OMPClauseWithPostUpdate *C);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002090};
2091
Alexey Bataev3392d762016-02-16 11:18:12 +00002092void OMPClauseEnqueue::VisitOMPClauseWithPreInit(
2093 const OMPClauseWithPreInit *C) {
2094 Visitor->AddStmt(C->getPreInitStmt());
2095}
2096
Alexey Bataev005248a2016-02-25 05:25:57 +00002097void OMPClauseEnqueue::VisitOMPClauseWithPostUpdate(
2098 const OMPClauseWithPostUpdate *C) {
Alexey Bataev37e594c2016-03-04 07:21:16 +00002099 VisitOMPClauseWithPreInit(C);
Alexey Bataev005248a2016-02-25 05:25:57 +00002100 Visitor->AddStmt(C->getPostUpdateExpr());
2101}
2102
Alexey Bataevaadd52e2014-02-13 05:29:23 +00002103void OMPClauseEnqueue::VisitOMPIfClause(const OMPIfClause *C) {
2104 Visitor->AddStmt(C->getCondition());
2105}
2106
Alexey Bataev3778b602014-07-17 07:32:53 +00002107void OMPClauseEnqueue::VisitOMPFinalClause(const OMPFinalClause *C) {
2108 Visitor->AddStmt(C->getCondition());
2109}
2110
Alexey Bataev568a8332014-03-06 06:15:19 +00002111void OMPClauseEnqueue::VisitOMPNumThreadsClause(const OMPNumThreadsClause *C) {
2112 Visitor->AddStmt(C->getNumThreads());
2113}
2114
Alexey Bataev62c87d22014-03-21 04:51:18 +00002115void OMPClauseEnqueue::VisitOMPSafelenClause(const OMPSafelenClause *C) {
2116 Visitor->AddStmt(C->getSafelen());
2117}
2118
Alexey Bataev66b15b52015-08-21 11:14:16 +00002119void OMPClauseEnqueue::VisitOMPSimdlenClause(const OMPSimdlenClause *C) {
2120 Visitor->AddStmt(C->getSimdlen());
2121}
2122
Alexander Musman8bd31e62014-05-27 15:12:19 +00002123void OMPClauseEnqueue::VisitOMPCollapseClause(const OMPCollapseClause *C) {
2124 Visitor->AddStmt(C->getNumForLoops());
2125}
2126
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002127void OMPClauseEnqueue::VisitOMPDefaultClause(const OMPDefaultClause *C) { }
Alexey Bataev756c1962013-09-24 03:17:45 +00002128
Alexey Bataevbcbadb62014-05-06 06:04:14 +00002129void OMPClauseEnqueue::VisitOMPProcBindClause(const OMPProcBindClause *C) { }
2130
Alexey Bataev56dafe82014-06-20 07:16:17 +00002131void OMPClauseEnqueue::VisitOMPScheduleClause(const OMPScheduleClause *C) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002132 VisitOMPClauseWithPreInit(C);
Alexey Bataev56dafe82014-06-20 07:16:17 +00002133 Visitor->AddStmt(C->getChunkSize());
2134}
2135
Alexey Bataev10e775f2015-07-30 11:36:16 +00002136void OMPClauseEnqueue::VisitOMPOrderedClause(const OMPOrderedClause *C) {
2137 Visitor->AddStmt(C->getNumForLoops());
2138}
Alexey Bataev142e1fc2014-06-20 09:44:06 +00002139
Alexey Bataev236070f2014-06-20 11:19:47 +00002140void OMPClauseEnqueue::VisitOMPNowaitClause(const OMPNowaitClause *) {}
2141
Alexey Bataev7aea99a2014-07-17 12:19:31 +00002142void OMPClauseEnqueue::VisitOMPUntiedClause(const OMPUntiedClause *) {}
2143
Alexey Bataev74ba3a52014-07-17 12:47:03 +00002144void OMPClauseEnqueue::VisitOMPMergeableClause(const OMPMergeableClause *) {}
2145
Alexey Bataevf98b00c2014-07-23 02:27:21 +00002146void OMPClauseEnqueue::VisitOMPReadClause(const OMPReadClause *) {}
2147
Alexey Bataevdea47612014-07-23 07:46:59 +00002148void OMPClauseEnqueue::VisitOMPWriteClause(const OMPWriteClause *) {}
2149
Alexey Bataev67a4f222014-07-23 10:25:33 +00002150void OMPClauseEnqueue::VisitOMPUpdateClause(const OMPUpdateClause *) {}
2151
Alexey Bataev459dec02014-07-24 06:46:57 +00002152void OMPClauseEnqueue::VisitOMPCaptureClause(const OMPCaptureClause *) {}
2153
Alexey Bataev82bad8b2014-07-24 08:55:34 +00002154void OMPClauseEnqueue::VisitOMPSeqCstClause(const OMPSeqCstClause *) {}
2155
Alexey Bataev346265e2015-09-25 10:37:12 +00002156void OMPClauseEnqueue::VisitOMPThreadsClause(const OMPThreadsClause *) {}
2157
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002158void OMPClauseEnqueue::VisitOMPSIMDClause(const OMPSIMDClause *) {}
2159
Alexey Bataevb825de12015-12-07 10:51:44 +00002160void OMPClauseEnqueue::VisitOMPNogroupClause(const OMPNogroupClause *) {}
2161
Michael Wonge710d542015-08-07 16:16:36 +00002162void OMPClauseEnqueue::VisitOMPDeviceClause(const OMPDeviceClause *C) {
2163 Visitor->AddStmt(C->getDevice());
2164}
2165
Kelvin Li099bb8c2015-11-24 20:50:12 +00002166void OMPClauseEnqueue::VisitOMPNumTeamsClause(const OMPNumTeamsClause *C) {
2167 Visitor->AddStmt(C->getNumTeams());
2168}
2169
Kelvin Lia15fb1a2015-11-27 18:47:36 +00002170void OMPClauseEnqueue::VisitOMPThreadLimitClause(const OMPThreadLimitClause *C) {
2171 Visitor->AddStmt(C->getThreadLimit());
2172}
2173
Alexey Bataeva0569352015-12-01 10:17:31 +00002174void OMPClauseEnqueue::VisitOMPPriorityClause(const OMPPriorityClause *C) {
2175 Visitor->AddStmt(C->getPriority());
2176}
2177
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00002178void OMPClauseEnqueue::VisitOMPGrainsizeClause(const OMPGrainsizeClause *C) {
2179 Visitor->AddStmt(C->getGrainsize());
2180}
2181
Alexey Bataev382967a2015-12-08 12:06:20 +00002182void OMPClauseEnqueue::VisitOMPNumTasksClause(const OMPNumTasksClause *C) {
2183 Visitor->AddStmt(C->getNumTasks());
2184}
2185
Alexey Bataev28c75412015-12-15 08:19:24 +00002186void OMPClauseEnqueue::VisitOMPHintClause(const OMPHintClause *C) {
2187 Visitor->AddStmt(C->getHint());
2188}
2189
Alexey Bataev756c1962013-09-24 03:17:45 +00002190template<typename T>
2191void OMPClauseEnqueue::VisitOMPClauseList(T *Node) {
Alexey Bataev03b340a2014-10-21 03:16:40 +00002192 for (const auto *I : Node->varlists()) {
Aaron Ballman2205d2a2014-03-14 15:55:35 +00002193 Visitor->AddStmt(I);
Alexey Bataev03b340a2014-10-21 03:16:40 +00002194 }
Alexey Bataev756c1962013-09-24 03:17:45 +00002195}
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002196
2197void OMPClauseEnqueue::VisitOMPPrivateClause(const OMPPrivateClause *C) {
Alexey Bataev756c1962013-09-24 03:17:45 +00002198 VisitOMPClauseList(C);
Alexey Bataev03b340a2014-10-21 03:16:40 +00002199 for (const auto *E : C->private_copies()) {
2200 Visitor->AddStmt(E);
2201 }
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002202}
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002203void OMPClauseEnqueue::VisitOMPFirstprivateClause(
2204 const OMPFirstprivateClause *C) {
2205 VisitOMPClauseList(C);
Alexey Bataev417089f2016-02-17 13:19:37 +00002206 VisitOMPClauseWithPreInit(C);
2207 for (const auto *E : C->private_copies()) {
2208 Visitor->AddStmt(E);
2209 }
2210 for (const auto *E : C->inits()) {
2211 Visitor->AddStmt(E);
2212 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002213}
Alexander Musman1bb328c2014-06-04 13:06:39 +00002214void OMPClauseEnqueue::VisitOMPLastprivateClause(
2215 const OMPLastprivateClause *C) {
2216 VisitOMPClauseList(C);
Alexey Bataev005248a2016-02-25 05:25:57 +00002217 VisitOMPClauseWithPostUpdate(C);
Alexey Bataev38e89532015-04-16 04:54:05 +00002218 for (auto *E : C->private_copies()) {
2219 Visitor->AddStmt(E);
2220 }
2221 for (auto *E : C->source_exprs()) {
2222 Visitor->AddStmt(E);
2223 }
2224 for (auto *E : C->destination_exprs()) {
2225 Visitor->AddStmt(E);
2226 }
2227 for (auto *E : C->assignment_ops()) {
2228 Visitor->AddStmt(E);
2229 }
Alexander Musman1bb328c2014-06-04 13:06:39 +00002230}
Alexey Bataev758e55e2013-09-06 18:03:48 +00002231void OMPClauseEnqueue::VisitOMPSharedClause(const OMPSharedClause *C) {
Alexey Bataev756c1962013-09-24 03:17:45 +00002232 VisitOMPClauseList(C);
Alexey Bataev758e55e2013-09-06 18:03:48 +00002233}
Alexey Bataevc5e02582014-06-16 07:08:35 +00002234void OMPClauseEnqueue::VisitOMPReductionClause(const OMPReductionClause *C) {
2235 VisitOMPClauseList(C);
Alexey Bataev61205072016-03-02 04:57:40 +00002236 VisitOMPClauseWithPostUpdate(C);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00002237 for (auto *E : C->privates()) {
2238 Visitor->AddStmt(E);
2239 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002240 for (auto *E : C->lhs_exprs()) {
2241 Visitor->AddStmt(E);
2242 }
2243 for (auto *E : C->rhs_exprs()) {
2244 Visitor->AddStmt(E);
2245 }
2246 for (auto *E : C->reduction_ops()) {
2247 Visitor->AddStmt(E);
2248 }
Alexey Bataevc5e02582014-06-16 07:08:35 +00002249}
Alexander Musman8dba6642014-04-22 13:09:42 +00002250void OMPClauseEnqueue::VisitOMPLinearClause(const OMPLinearClause *C) {
2251 VisitOMPClauseList(C);
Alexey Bataev78849fb2016-03-09 09:49:00 +00002252 VisitOMPClauseWithPostUpdate(C);
Alexey Bataevbd9fec12015-08-18 06:47:21 +00002253 for (const auto *E : C->privates()) {
2254 Visitor->AddStmt(E);
2255 }
Alexander Musman3276a272015-03-21 10:12:56 +00002256 for (const auto *E : C->inits()) {
2257 Visitor->AddStmt(E);
2258 }
2259 for (const auto *E : C->updates()) {
2260 Visitor->AddStmt(E);
2261 }
2262 for (const auto *E : C->finals()) {
2263 Visitor->AddStmt(E);
2264 }
Alexander Musman8dba6642014-04-22 13:09:42 +00002265 Visitor->AddStmt(C->getStep());
Alexander Musman3276a272015-03-21 10:12:56 +00002266 Visitor->AddStmt(C->getCalcStep());
Alexander Musman8dba6642014-04-22 13:09:42 +00002267}
Alexander Musmanf0d76e72014-05-29 14:36:25 +00002268void OMPClauseEnqueue::VisitOMPAlignedClause(const OMPAlignedClause *C) {
2269 VisitOMPClauseList(C);
2270 Visitor->AddStmt(C->getAlignment());
2271}
Alexey Bataevd48bcd82014-03-31 03:36:38 +00002272void OMPClauseEnqueue::VisitOMPCopyinClause(const OMPCopyinClause *C) {
2273 VisitOMPClauseList(C);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00002274 for (auto *E : C->source_exprs()) {
2275 Visitor->AddStmt(E);
2276 }
2277 for (auto *E : C->destination_exprs()) {
2278 Visitor->AddStmt(E);
2279 }
2280 for (auto *E : C->assignment_ops()) {
2281 Visitor->AddStmt(E);
2282 }
Alexey Bataevd48bcd82014-03-31 03:36:38 +00002283}
Alexey Bataevbae9a792014-06-27 10:37:06 +00002284void
2285OMPClauseEnqueue::VisitOMPCopyprivateClause(const OMPCopyprivateClause *C) {
2286 VisitOMPClauseList(C);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002287 for (auto *E : C->source_exprs()) {
2288 Visitor->AddStmt(E);
2289 }
2290 for (auto *E : C->destination_exprs()) {
2291 Visitor->AddStmt(E);
2292 }
2293 for (auto *E : C->assignment_ops()) {
2294 Visitor->AddStmt(E);
2295 }
Alexey Bataevbae9a792014-06-27 10:37:06 +00002296}
Alexey Bataev6125da92014-07-21 11:26:11 +00002297void OMPClauseEnqueue::VisitOMPFlushClause(const OMPFlushClause *C) {
2298 VisitOMPClauseList(C);
2299}
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00002300void OMPClauseEnqueue::VisitOMPDependClause(const OMPDependClause *C) {
2301 VisitOMPClauseList(C);
2302}
Kelvin Li0bff7af2015-11-23 05:32:03 +00002303void OMPClauseEnqueue::VisitOMPMapClause(const OMPMapClause *C) {
2304 VisitOMPClauseList(C);
2305}
Carlo Bertollib4adf552016-01-15 18:50:31 +00002306void OMPClauseEnqueue::VisitOMPDistScheduleClause(
2307 const OMPDistScheduleClause *C) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002308 VisitOMPClauseWithPreInit(C);
Carlo Bertollib4adf552016-01-15 18:50:31 +00002309 Visitor->AddStmt(C->getChunkSize());
Carlo Bertollib4adf552016-01-15 18:50:31 +00002310}
Alexey Bataev3392d762016-02-16 11:18:12 +00002311void OMPClauseEnqueue::VisitOMPDefaultmapClause(
2312 const OMPDefaultmapClause * /*C*/) {}
Samuel Antao661c0902016-05-26 17:39:58 +00002313void OMPClauseEnqueue::VisitOMPToClause(const OMPToClause *C) {
2314 VisitOMPClauseList(C);
2315}
Samuel Antaoec172c62016-05-26 17:49:04 +00002316void OMPClauseEnqueue::VisitOMPFromClause(const OMPFromClause *C) {
2317 VisitOMPClauseList(C);
2318}
Carlo Bertolli2404b172016-07-13 15:37:16 +00002319void OMPClauseEnqueue::VisitOMPUseDevicePtrClause(const OMPUseDevicePtrClause *C) {
2320 VisitOMPClauseList(C);
2321}
Carlo Bertolli70594e92016-07-13 17:16:49 +00002322void OMPClauseEnqueue::VisitOMPIsDevicePtrClause(const OMPIsDevicePtrClause *C) {
2323 VisitOMPClauseList(C);
2324}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002325}
Alexey Bataev756c1962013-09-24 03:17:45 +00002326
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002327void EnqueueVisitor::EnqueueChildren(const OMPClause *S) {
2328 unsigned size = WL.size();
2329 OMPClauseEnqueue Visitor(this);
2330 Visitor.Visit(S);
2331 if (size == WL.size())
2332 return;
2333 // Now reverse the entries we just added. This will match the DFS
2334 // ordering performed by the worklist.
2335 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2336 std::reverse(I, E);
2337}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002338void EnqueueVisitor::VisitAddrLabelExpr(const AddrLabelExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002339 WL.push_back(LabelRefVisit(E->getLabel(), E->getLabelLoc(), Parent));
2340}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002341void EnqueueVisitor::VisitBlockExpr(const BlockExpr *B) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002342 AddDecl(B->getBlockDecl());
2343}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002344void EnqueueVisitor::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002345 EnqueueChildren(E);
2346 AddTypeLoc(E->getTypeSourceInfo());
2347}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002348void EnqueueVisitor::VisitCompoundStmt(const CompoundStmt *S) {
Pete Cooper57d3f142015-07-30 17:22:52 +00002349 for (auto &I : llvm::reverse(S->body()))
2350 AddStmt(I);
Guy Benyei11169dd2012-12-18 14:30:41 +00002351}
2352void EnqueueVisitor::
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002353VisitMSDependentExistsStmt(const MSDependentExistsStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002354 AddStmt(S->getSubStmt());
2355 AddDeclarationNameInfo(S);
2356 if (NestedNameSpecifierLoc QualifierLoc = S->getQualifierLoc())
2357 AddNestedNameSpecifierLoc(QualifierLoc);
2358}
2359
2360void EnqueueVisitor::
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002361VisitCXXDependentScopeMemberExpr(const CXXDependentScopeMemberExpr *E) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002362 if (E->hasExplicitTemplateArgs())
2363 AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002364 AddDeclarationNameInfo(E);
2365 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
2366 AddNestedNameSpecifierLoc(QualifierLoc);
2367 if (!E->isImplicitAccess())
2368 AddStmt(E->getBase());
2369}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002370void EnqueueVisitor::VisitCXXNewExpr(const CXXNewExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002371 // Enqueue the initializer , if any.
2372 AddStmt(E->getInitializer());
2373 // Enqueue the array size, if any.
2374 AddStmt(E->getArraySize());
2375 // Enqueue the allocated type.
2376 AddTypeLoc(E->getAllocatedTypeSourceInfo());
2377 // Enqueue the placement arguments.
2378 for (unsigned I = E->getNumPlacementArgs(); I > 0; --I)
2379 AddStmt(E->getPlacementArg(I-1));
2380}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002381void EnqueueVisitor::VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CE) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002382 for (unsigned I = CE->getNumArgs(); I > 1 /* Yes, this is 1 */; --I)
2383 AddStmt(CE->getArg(I-1));
2384 AddStmt(CE->getCallee());
2385 AddStmt(CE->getArg(0));
2386}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002387void EnqueueVisitor::VisitCXXPseudoDestructorExpr(
2388 const CXXPseudoDestructorExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002389 // Visit the name of the type being destroyed.
2390 AddTypeLoc(E->getDestroyedTypeInfo());
2391 // Visit the scope type that looks disturbingly like the nested-name-specifier
2392 // but isn't.
2393 AddTypeLoc(E->getScopeTypeInfo());
2394 // Visit the nested-name-specifier.
2395 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
2396 AddNestedNameSpecifierLoc(QualifierLoc);
2397 // Visit base expression.
2398 AddStmt(E->getBase());
2399}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002400void EnqueueVisitor::VisitCXXScalarValueInitExpr(
2401 const CXXScalarValueInitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002402 AddTypeLoc(E->getTypeSourceInfo());
2403}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002404void EnqueueVisitor::VisitCXXTemporaryObjectExpr(
2405 const CXXTemporaryObjectExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002406 EnqueueChildren(E);
2407 AddTypeLoc(E->getTypeSourceInfo());
2408}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002409void EnqueueVisitor::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002410 EnqueueChildren(E);
2411 if (E->isTypeOperand())
2412 AddTypeLoc(E->getTypeOperandSourceInfo());
2413}
2414
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002415void EnqueueVisitor::VisitCXXUnresolvedConstructExpr(
2416 const CXXUnresolvedConstructExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002417 EnqueueChildren(E);
2418 AddTypeLoc(E->getTypeSourceInfo());
2419}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002420void EnqueueVisitor::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002421 EnqueueChildren(E);
2422 if (E->isTypeOperand())
2423 AddTypeLoc(E->getTypeOperandSourceInfo());
2424}
2425
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002426void EnqueueVisitor::VisitCXXCatchStmt(const CXXCatchStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002427 EnqueueChildren(S);
2428 AddDecl(S->getExceptionDecl());
2429}
2430
Argyrios Kyrtzidis99891242014-11-13 09:03:21 +00002431void EnqueueVisitor::VisitCXXForRangeStmt(const CXXForRangeStmt *S) {
Argyrios Kyrtzidiscde70692014-11-13 09:50:19 +00002432 AddStmt(S->getBody());
Argyrios Kyrtzidis99891242014-11-13 09:03:21 +00002433 AddStmt(S->getRangeInit());
Argyrios Kyrtzidiscde70692014-11-13 09:50:19 +00002434 AddDecl(S->getLoopVariable());
Argyrios Kyrtzidis99891242014-11-13 09:03:21 +00002435}
2436
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002437void EnqueueVisitor::VisitDeclRefExpr(const DeclRefExpr *DR) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002438 if (DR->hasExplicitTemplateArgs())
2439 AddExplicitTemplateArgs(DR->getTemplateArgs(), DR->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002440 WL.push_back(DeclRefExprParts(DR, Parent));
2441}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002442void EnqueueVisitor::VisitDependentScopeDeclRefExpr(
2443 const DependentScopeDeclRefExpr *E) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002444 if (E->hasExplicitTemplateArgs())
2445 AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002446 AddDeclarationNameInfo(E);
2447 AddNestedNameSpecifierLoc(E->getQualifierLoc());
2448}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002449void EnqueueVisitor::VisitDeclStmt(const DeclStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002450 unsigned size = WL.size();
2451 bool isFirst = true;
Aaron Ballman535bbcc2014-03-14 17:01:24 +00002452 for (const auto *D : S->decls()) {
2453 AddDecl(D, isFirst);
Guy Benyei11169dd2012-12-18 14:30:41 +00002454 isFirst = false;
2455 }
2456 if (size == WL.size())
2457 return;
2458 // Now reverse the entries we just added. This will match the DFS
2459 // ordering performed by the worklist.
2460 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2461 std::reverse(I, E);
2462}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002463void EnqueueVisitor::VisitDesignatedInitExpr(const DesignatedInitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002464 AddStmt(E->getInit());
David Majnemerf7e36092016-06-23 00:15:04 +00002465 for (const DesignatedInitExpr::Designator &D :
2466 llvm::reverse(E->designators())) {
2467 if (D.isFieldDesignator()) {
2468 if (FieldDecl *Field = D.getField())
2469 AddMemberRef(Field, D.getFieldLoc());
Guy Benyei11169dd2012-12-18 14:30:41 +00002470 continue;
2471 }
David Majnemerf7e36092016-06-23 00:15:04 +00002472 if (D.isArrayDesignator()) {
2473 AddStmt(E->getArrayIndex(D));
Guy Benyei11169dd2012-12-18 14:30:41 +00002474 continue;
2475 }
David Majnemerf7e36092016-06-23 00:15:04 +00002476 assert(D.isArrayRangeDesignator() && "Unknown designator kind");
2477 AddStmt(E->getArrayRangeEnd(D));
2478 AddStmt(E->getArrayRangeStart(D));
Guy Benyei11169dd2012-12-18 14:30:41 +00002479 }
2480}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002481void EnqueueVisitor::VisitExplicitCastExpr(const ExplicitCastExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002482 EnqueueChildren(E);
2483 AddTypeLoc(E->getTypeInfoAsWritten());
2484}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002485void EnqueueVisitor::VisitForStmt(const ForStmt *FS) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002486 AddStmt(FS->getBody());
2487 AddStmt(FS->getInc());
2488 AddStmt(FS->getCond());
2489 AddDecl(FS->getConditionVariable());
2490 AddStmt(FS->getInit());
2491}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002492void EnqueueVisitor::VisitGotoStmt(const GotoStmt *GS) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002493 WL.push_back(LabelRefVisit(GS->getLabel(), GS->getLabelLoc(), Parent));
2494}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002495void EnqueueVisitor::VisitIfStmt(const IfStmt *If) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002496 AddStmt(If->getElse());
2497 AddStmt(If->getThen());
2498 AddStmt(If->getCond());
2499 AddDecl(If->getConditionVariable());
2500}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002501void EnqueueVisitor::VisitInitListExpr(const InitListExpr *IE) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002502 // We care about the syntactic form of the initializer list, only.
2503 if (InitListExpr *Syntactic = IE->getSyntacticForm())
2504 IE = Syntactic;
2505 EnqueueChildren(IE);
2506}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002507void EnqueueVisitor::VisitMemberExpr(const MemberExpr *M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002508 WL.push_back(MemberExprParts(M, Parent));
2509
2510 // If the base of the member access expression is an implicit 'this', don't
2511 // visit it.
2512 // FIXME: If we ever want to show these implicit accesses, this will be
2513 // unfortunate. However, clang_getCursor() relies on this behavior.
Argyrios Kyrtzidis58d0e7a2015-03-13 04:40:07 +00002514 if (M->isImplicitAccess())
2515 return;
2516
2517 // Ignore base anonymous struct/union fields, otherwise they will shadow the
2518 // real field that that we are interested in.
2519 if (auto *SubME = dyn_cast<MemberExpr>(M->getBase())) {
2520 if (auto *FD = dyn_cast_or_null<FieldDecl>(SubME->getMemberDecl())) {
2521 if (FD->isAnonymousStructOrUnion()) {
2522 AddStmt(SubME->getBase());
2523 return;
2524 }
2525 }
2526 }
2527
2528 AddStmt(M->getBase());
Guy Benyei11169dd2012-12-18 14:30:41 +00002529}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002530void EnqueueVisitor::VisitObjCEncodeExpr(const ObjCEncodeExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002531 AddTypeLoc(E->getEncodedTypeSourceInfo());
2532}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002533void EnqueueVisitor::VisitObjCMessageExpr(const ObjCMessageExpr *M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002534 EnqueueChildren(M);
2535 AddTypeLoc(M->getClassReceiverTypeInfo());
2536}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002537void EnqueueVisitor::VisitOffsetOfExpr(const OffsetOfExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002538 // Visit the components of the offsetof expression.
2539 for (unsigned N = E->getNumComponents(), I = N; I > 0; --I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002540 const OffsetOfNode &Node = E->getComponent(I-1);
2541 switch (Node.getKind()) {
2542 case OffsetOfNode::Array:
2543 AddStmt(E->getIndexExpr(Node.getArrayExprIndex()));
2544 break;
2545 case OffsetOfNode::Field:
2546 AddMemberRef(Node.getField(), Node.getSourceRange().getEnd());
2547 break;
2548 case OffsetOfNode::Identifier:
2549 case OffsetOfNode::Base:
2550 continue;
2551 }
2552 }
2553 // Visit the type into which we're computing the offset.
2554 AddTypeLoc(E->getTypeSourceInfo());
2555}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002556void EnqueueVisitor::VisitOverloadExpr(const OverloadExpr *E) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002557 if (E->hasExplicitTemplateArgs())
2558 AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002559 WL.push_back(OverloadExprParts(E, Parent));
2560}
2561void EnqueueVisitor::VisitUnaryExprOrTypeTraitExpr(
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002562 const UnaryExprOrTypeTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002563 EnqueueChildren(E);
2564 if (E->isArgumentType())
2565 AddTypeLoc(E->getArgumentTypeInfo());
2566}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002567void EnqueueVisitor::VisitStmt(const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002568 EnqueueChildren(S);
2569}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002570void EnqueueVisitor::VisitSwitchStmt(const SwitchStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002571 AddStmt(S->getBody());
2572 AddStmt(S->getCond());
2573 AddDecl(S->getConditionVariable());
2574}
2575
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002576void EnqueueVisitor::VisitWhileStmt(const WhileStmt *W) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002577 AddStmt(W->getBody());
2578 AddStmt(W->getCond());
2579 AddDecl(W->getConditionVariable());
2580}
2581
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002582void EnqueueVisitor::VisitTypeTraitExpr(const TypeTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002583 for (unsigned I = E->getNumArgs(); I > 0; --I)
2584 AddTypeLoc(E->getArg(I-1));
2585}
2586
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002587void EnqueueVisitor::VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002588 AddTypeLoc(E->getQueriedTypeSourceInfo());
2589}
2590
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002591void EnqueueVisitor::VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002592 EnqueueChildren(E);
2593}
2594
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002595void EnqueueVisitor::VisitUnresolvedMemberExpr(const UnresolvedMemberExpr *U) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002596 VisitOverloadExpr(U);
2597 if (!U->isImplicitAccess())
2598 AddStmt(U->getBase());
2599}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002600void EnqueueVisitor::VisitVAArgExpr(const VAArgExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002601 AddStmt(E->getSubExpr());
2602 AddTypeLoc(E->getWrittenTypeInfo());
2603}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002604void EnqueueVisitor::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002605 WL.push_back(SizeOfPackExprParts(E, Parent));
2606}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002607void EnqueueVisitor::VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002608 // If the opaque value has a source expression, just transparently
2609 // visit that. This is useful for (e.g.) pseudo-object expressions.
2610 if (Expr *SourceExpr = E->getSourceExpr())
2611 return Visit(SourceExpr);
2612}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002613void EnqueueVisitor::VisitLambdaExpr(const LambdaExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002614 AddStmt(E->getBody());
2615 WL.push_back(LambdaExprParts(E, Parent));
2616}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002617void EnqueueVisitor::VisitPseudoObjectExpr(const PseudoObjectExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002618 // Treat the expression like its syntactic form.
2619 Visit(E->getSyntacticForm());
2620}
2621
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002622void EnqueueVisitor::VisitOMPExecutableDirective(
2623 const OMPExecutableDirective *D) {
2624 EnqueueChildren(D);
2625 for (ArrayRef<OMPClause *>::iterator I = D->clauses().begin(),
2626 E = D->clauses().end();
2627 I != E; ++I)
2628 EnqueueChildren(*I);
2629}
2630
Alexander Musman3aaab662014-08-19 11:27:13 +00002631void EnqueueVisitor::VisitOMPLoopDirective(const OMPLoopDirective *D) {
2632 VisitOMPExecutableDirective(D);
2633}
2634
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002635void EnqueueVisitor::VisitOMPParallelDirective(const OMPParallelDirective *D) {
2636 VisitOMPExecutableDirective(D);
2637}
2638
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002639void EnqueueVisitor::VisitOMPSimdDirective(const OMPSimdDirective *D) {
Alexander Musman3aaab662014-08-19 11:27:13 +00002640 VisitOMPLoopDirective(D);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002641}
2642
Alexey Bataevf29276e2014-06-18 04:14:57 +00002643void EnqueueVisitor::VisitOMPForDirective(const OMPForDirective *D) {
Alexander Musman3aaab662014-08-19 11:27:13 +00002644 VisitOMPLoopDirective(D);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002645}
2646
Alexander Musmanf82886e2014-09-18 05:12:34 +00002647void EnqueueVisitor::VisitOMPForSimdDirective(const OMPForSimdDirective *D) {
2648 VisitOMPLoopDirective(D);
2649}
2650
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002651void EnqueueVisitor::VisitOMPSectionsDirective(const OMPSectionsDirective *D) {
2652 VisitOMPExecutableDirective(D);
2653}
2654
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002655void EnqueueVisitor::VisitOMPSectionDirective(const OMPSectionDirective *D) {
2656 VisitOMPExecutableDirective(D);
2657}
2658
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00002659void EnqueueVisitor::VisitOMPSingleDirective(const OMPSingleDirective *D) {
2660 VisitOMPExecutableDirective(D);
2661}
2662
Alexander Musman80c22892014-07-17 08:54:58 +00002663void EnqueueVisitor::VisitOMPMasterDirective(const OMPMasterDirective *D) {
2664 VisitOMPExecutableDirective(D);
2665}
2666
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002667void EnqueueVisitor::VisitOMPCriticalDirective(const OMPCriticalDirective *D) {
2668 VisitOMPExecutableDirective(D);
2669 AddDeclarationNameInfo(D);
2670}
2671
Alexey Bataev4acb8592014-07-07 13:01:15 +00002672void
2673EnqueueVisitor::VisitOMPParallelForDirective(const OMPParallelForDirective *D) {
Alexander Musman3aaab662014-08-19 11:27:13 +00002674 VisitOMPLoopDirective(D);
Alexey Bataev4acb8592014-07-07 13:01:15 +00002675}
2676
Alexander Musmane4e893b2014-09-23 09:33:00 +00002677void EnqueueVisitor::VisitOMPParallelForSimdDirective(
2678 const OMPParallelForSimdDirective *D) {
2679 VisitOMPLoopDirective(D);
2680}
2681
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002682void EnqueueVisitor::VisitOMPParallelSectionsDirective(
2683 const OMPParallelSectionsDirective *D) {
2684 VisitOMPExecutableDirective(D);
2685}
2686
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002687void EnqueueVisitor::VisitOMPTaskDirective(const OMPTaskDirective *D) {
2688 VisitOMPExecutableDirective(D);
2689}
2690
Alexey Bataev68446b72014-07-18 07:47:19 +00002691void
2692EnqueueVisitor::VisitOMPTaskyieldDirective(const OMPTaskyieldDirective *D) {
2693 VisitOMPExecutableDirective(D);
2694}
2695
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002696void EnqueueVisitor::VisitOMPBarrierDirective(const OMPBarrierDirective *D) {
2697 VisitOMPExecutableDirective(D);
2698}
2699
Alexey Bataev2df347a2014-07-18 10:17:07 +00002700void EnqueueVisitor::VisitOMPTaskwaitDirective(const OMPTaskwaitDirective *D) {
2701 VisitOMPExecutableDirective(D);
2702}
2703
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002704void EnqueueVisitor::VisitOMPTaskgroupDirective(
2705 const OMPTaskgroupDirective *D) {
2706 VisitOMPExecutableDirective(D);
2707}
2708
Alexey Bataev6125da92014-07-21 11:26:11 +00002709void EnqueueVisitor::VisitOMPFlushDirective(const OMPFlushDirective *D) {
2710 VisitOMPExecutableDirective(D);
2711}
2712
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002713void EnqueueVisitor::VisitOMPOrderedDirective(const OMPOrderedDirective *D) {
2714 VisitOMPExecutableDirective(D);
2715}
2716
Alexey Bataev0162e452014-07-22 10:10:35 +00002717void EnqueueVisitor::VisitOMPAtomicDirective(const OMPAtomicDirective *D) {
2718 VisitOMPExecutableDirective(D);
2719}
2720
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002721void EnqueueVisitor::VisitOMPTargetDirective(const OMPTargetDirective *D) {
2722 VisitOMPExecutableDirective(D);
2723}
2724
Michael Wong65f367f2015-07-21 13:44:28 +00002725void EnqueueVisitor::VisitOMPTargetDataDirective(const
2726 OMPTargetDataDirective *D) {
2727 VisitOMPExecutableDirective(D);
2728}
2729
Samuel Antaodf67fc42016-01-19 19:15:56 +00002730void EnqueueVisitor::VisitOMPTargetEnterDataDirective(
2731 const OMPTargetEnterDataDirective *D) {
2732 VisitOMPExecutableDirective(D);
2733}
2734
Samuel Antao72590762016-01-19 20:04:50 +00002735void EnqueueVisitor::VisitOMPTargetExitDataDirective(
2736 const OMPTargetExitDataDirective *D) {
2737 VisitOMPExecutableDirective(D);
2738}
2739
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00002740void EnqueueVisitor::VisitOMPTargetParallelDirective(
2741 const OMPTargetParallelDirective *D) {
2742 VisitOMPExecutableDirective(D);
2743}
2744
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00002745void EnqueueVisitor::VisitOMPTargetParallelForDirective(
2746 const OMPTargetParallelForDirective *D) {
2747 VisitOMPLoopDirective(D);
2748}
2749
Alexey Bataev13314bf2014-10-09 04:18:56 +00002750void EnqueueVisitor::VisitOMPTeamsDirective(const OMPTeamsDirective *D) {
2751 VisitOMPExecutableDirective(D);
2752}
2753
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002754void EnqueueVisitor::VisitOMPCancellationPointDirective(
2755 const OMPCancellationPointDirective *D) {
2756 VisitOMPExecutableDirective(D);
2757}
2758
Alexey Bataev80909872015-07-02 11:25:17 +00002759void EnqueueVisitor::VisitOMPCancelDirective(const OMPCancelDirective *D) {
2760 VisitOMPExecutableDirective(D);
2761}
2762
Alexey Bataev49f6e782015-12-01 04:18:41 +00002763void EnqueueVisitor::VisitOMPTaskLoopDirective(const OMPTaskLoopDirective *D) {
2764 VisitOMPLoopDirective(D);
2765}
2766
Alexey Bataev0a6ed842015-12-03 09:40:15 +00002767void EnqueueVisitor::VisitOMPTaskLoopSimdDirective(
2768 const OMPTaskLoopSimdDirective *D) {
2769 VisitOMPLoopDirective(D);
2770}
2771
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002772void EnqueueVisitor::VisitOMPDistributeDirective(
2773 const OMPDistributeDirective *D) {
2774 VisitOMPLoopDirective(D);
2775}
2776
Carlo Bertolli9925f152016-06-27 14:55:37 +00002777void EnqueueVisitor::VisitOMPDistributeParallelForDirective(
2778 const OMPDistributeParallelForDirective *D) {
2779 VisitOMPLoopDirective(D);
2780}
2781
Kelvin Li4a39add2016-07-05 05:00:15 +00002782void EnqueueVisitor::VisitOMPDistributeParallelForSimdDirective(
2783 const OMPDistributeParallelForSimdDirective *D) {
2784 VisitOMPLoopDirective(D);
2785}
2786
Kelvin Li787f3fc2016-07-06 04:45:38 +00002787void EnqueueVisitor::VisitOMPDistributeSimdDirective(
2788 const OMPDistributeSimdDirective *D) {
2789 VisitOMPLoopDirective(D);
2790}
2791
Kelvin Lia579b912016-07-14 02:54:56 +00002792void EnqueueVisitor::VisitOMPTargetParallelForSimdDirective(
2793 const OMPTargetParallelForSimdDirective *D) {
2794 VisitOMPLoopDirective(D);
2795}
2796
Kelvin Li986330c2016-07-20 22:57:10 +00002797void EnqueueVisitor::VisitOMPTargetSimdDirective(
2798 const OMPTargetSimdDirective *D) {
2799 VisitOMPLoopDirective(D);
2800}
2801
Kelvin Li02532872016-08-05 14:37:37 +00002802void EnqueueVisitor::VisitOMPTeamsDistributeDirective(
2803 const OMPTeamsDistributeDirective *D) {
2804 VisitOMPLoopDirective(D);
2805}
2806
Kelvin Li4e325f72016-10-25 12:50:55 +00002807void EnqueueVisitor::VisitOMPTeamsDistributeSimdDirective(
2808 const OMPTeamsDistributeSimdDirective *D) {
2809 VisitOMPLoopDirective(D);
2810}
2811
Kelvin Li579e41c2016-11-30 23:51:03 +00002812void EnqueueVisitor::VisitOMPTeamsDistributeParallelForSimdDirective(
2813 const OMPTeamsDistributeParallelForSimdDirective *D) {
2814 VisitOMPLoopDirective(D);
2815}
2816
Kelvin Li7ade93f2016-12-09 03:24:30 +00002817void EnqueueVisitor::VisitOMPTeamsDistributeParallelForDirective(
2818 const OMPTeamsDistributeParallelForDirective *D) {
2819 VisitOMPLoopDirective(D);
2820}
2821
Kelvin Libf594a52016-12-17 05:48:59 +00002822void EnqueueVisitor::VisitOMPTargetTeamsDirective(
2823 const OMPTargetTeamsDirective *D) {
2824 VisitOMPExecutableDirective(D);
2825}
2826
Kelvin Li83c451e2016-12-25 04:52:54 +00002827void EnqueueVisitor::VisitOMPTargetTeamsDistributeDirective(
2828 const OMPTargetTeamsDistributeDirective *D) {
2829 VisitOMPLoopDirective(D);
2830}
2831
Kelvin Li80e8f562016-12-29 22:16:30 +00002832void EnqueueVisitor::VisitOMPTargetTeamsDistributeParallelForDirective(
2833 const OMPTargetTeamsDistributeParallelForDirective *D) {
2834 VisitOMPLoopDirective(D);
2835}
2836
Kelvin Li1851df52017-01-03 05:23:48 +00002837void EnqueueVisitor::VisitOMPTargetTeamsDistributeParallelForSimdDirective(
2838 const OMPTargetTeamsDistributeParallelForSimdDirective *D) {
2839 VisitOMPLoopDirective(D);
2840}
2841
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002842void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002843 EnqueueVisitor(WL, MakeCXCursor(S, StmtParent, TU,RegionOfInterest)).Visit(S);
2844}
2845
2846bool CursorVisitor::IsInRegionOfInterest(CXCursor C) {
2847 if (RegionOfInterest.isValid()) {
2848 SourceRange Range = getRawCursorExtent(C);
2849 if (Range.isInvalid() || CompareRegionOfInterest(Range))
2850 return false;
2851 }
2852 return true;
2853}
2854
2855bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) {
2856 while (!WL.empty()) {
2857 // Dequeue the worklist item.
Robert Wilhelm25284cc2013-08-23 16:11:15 +00002858 VisitorJob LI = WL.pop_back_val();
Guy Benyei11169dd2012-12-18 14:30:41 +00002859
2860 // Set the Parent field, then back to its old value once we're done.
2861 SetParentRAII SetParent(Parent, StmtParent, LI.getParent());
2862
2863 switch (LI.getKind()) {
2864 case VisitorJob::DeclVisitKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002865 const Decl *D = cast<DeclVisit>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00002866 if (!D)
2867 continue;
2868
2869 // For now, perform default visitation for Decls.
2870 if (Visit(MakeCXCursor(D, TU, RegionOfInterest,
2871 cast<DeclVisit>(&LI)->isFirst())))
2872 return true;
2873
2874 continue;
2875 }
2876 case VisitorJob::ExplicitTemplateArgsVisitKind: {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002877 for (const TemplateArgumentLoc &Arg :
2878 *cast<ExplicitTemplateArgsVisit>(&LI)) {
2879 if (VisitTemplateArgumentLoc(Arg))
Guy Benyei11169dd2012-12-18 14:30:41 +00002880 return true;
2881 }
2882 continue;
2883 }
2884 case VisitorJob::TypeLocVisitKind: {
2885 // Perform default visitation for TypeLocs.
2886 if (Visit(cast<TypeLocVisit>(&LI)->get()))
2887 return true;
2888 continue;
2889 }
2890 case VisitorJob::LabelRefVisitKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002891 const LabelDecl *LS = cast<LabelRefVisit>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00002892 if (LabelStmt *stmt = LS->getStmt()) {
2893 if (Visit(MakeCursorLabelRef(stmt, cast<LabelRefVisit>(&LI)->getLoc(),
2894 TU))) {
2895 return true;
2896 }
2897 }
2898 continue;
2899 }
2900
2901 case VisitorJob::NestedNameSpecifierLocVisitKind: {
2902 NestedNameSpecifierLocVisit *V = cast<NestedNameSpecifierLocVisit>(&LI);
2903 if (VisitNestedNameSpecifierLoc(V->get()))
2904 return true;
2905 continue;
2906 }
2907
2908 case VisitorJob::DeclarationNameInfoVisitKind: {
2909 if (VisitDeclarationNameInfo(cast<DeclarationNameInfoVisit>(&LI)
2910 ->get()))
2911 return true;
2912 continue;
2913 }
2914 case VisitorJob::MemberRefVisitKind: {
2915 MemberRefVisit *V = cast<MemberRefVisit>(&LI);
2916 if (Visit(MakeCursorMemberRef(V->get(), V->getLoc(), TU)))
2917 return true;
2918 continue;
2919 }
2920 case VisitorJob::StmtVisitKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002921 const Stmt *S = cast<StmtVisit>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00002922 if (!S)
2923 continue;
2924
2925 // Update the current cursor.
2926 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU, RegionOfInterest);
2927 if (!IsInRegionOfInterest(Cursor))
2928 continue;
2929 switch (Visitor(Cursor, Parent, ClientData)) {
2930 case CXChildVisit_Break: return true;
2931 case CXChildVisit_Continue: break;
2932 case CXChildVisit_Recurse:
2933 if (PostChildrenVisitor)
Craig Topper69186e72014-06-08 08:38:04 +00002934 WL.push_back(PostChildrenVisit(nullptr, Cursor));
Guy Benyei11169dd2012-12-18 14:30:41 +00002935 EnqueueWorkList(WL, S);
2936 break;
2937 }
2938 continue;
2939 }
2940 case VisitorJob::MemberExprPartsKind: {
2941 // Handle the other pieces in the MemberExpr besides the base.
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002942 const MemberExpr *M = cast<MemberExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00002943
2944 // Visit the nested-name-specifier
2945 if (NestedNameSpecifierLoc QualifierLoc = M->getQualifierLoc())
2946 if (VisitNestedNameSpecifierLoc(QualifierLoc))
2947 return true;
2948
2949 // Visit the declaration name.
2950 if (VisitDeclarationNameInfo(M->getMemberNameInfo()))
2951 return true;
2952
2953 // Visit the explicitly-specified template arguments, if any.
2954 if (M->hasExplicitTemplateArgs()) {
2955 for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(),
2956 *ArgEnd = Arg + M->getNumTemplateArgs();
2957 Arg != ArgEnd; ++Arg) {
2958 if (VisitTemplateArgumentLoc(*Arg))
2959 return true;
2960 }
2961 }
2962 continue;
2963 }
2964 case VisitorJob::DeclRefExprPartsKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002965 const DeclRefExpr *DR = cast<DeclRefExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00002966 // Visit nested-name-specifier, if present.
2967 if (NestedNameSpecifierLoc QualifierLoc = DR->getQualifierLoc())
2968 if (VisitNestedNameSpecifierLoc(QualifierLoc))
2969 return true;
2970 // Visit declaration name.
2971 if (VisitDeclarationNameInfo(DR->getNameInfo()))
2972 return true;
2973 continue;
2974 }
2975 case VisitorJob::OverloadExprPartsKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002976 const OverloadExpr *O = cast<OverloadExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00002977 // Visit the nested-name-specifier.
2978 if (NestedNameSpecifierLoc QualifierLoc = O->getQualifierLoc())
2979 if (VisitNestedNameSpecifierLoc(QualifierLoc))
2980 return true;
2981 // Visit the declaration name.
2982 if (VisitDeclarationNameInfo(O->getNameInfo()))
2983 return true;
2984 // Visit the overloaded declaration reference.
2985 if (Visit(MakeCursorOverloadedDeclRef(O, TU)))
2986 return true;
2987 continue;
2988 }
2989 case VisitorJob::SizeOfPackExprPartsKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002990 const SizeOfPackExpr *E = cast<SizeOfPackExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00002991 NamedDecl *Pack = E->getPack();
2992 if (isa<TemplateTypeParmDecl>(Pack)) {
2993 if (Visit(MakeCursorTypeRef(cast<TemplateTypeParmDecl>(Pack),
2994 E->getPackLoc(), TU)))
2995 return true;
2996
2997 continue;
2998 }
2999
3000 if (isa<TemplateTemplateParmDecl>(Pack)) {
3001 if (Visit(MakeCursorTemplateRef(cast<TemplateTemplateParmDecl>(Pack),
3002 E->getPackLoc(), TU)))
3003 return true;
3004
3005 continue;
3006 }
3007
3008 // Non-type template parameter packs and function parameter packs are
3009 // treated like DeclRefExpr cursors.
3010 continue;
3011 }
3012
3013 case VisitorJob::LambdaExprPartsKind: {
3014 // Visit captures.
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003015 const LambdaExpr *E = cast<LambdaExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003016 for (LambdaExpr::capture_iterator C = E->explicit_capture_begin(),
3017 CEnd = E->explicit_capture_end();
3018 C != CEnd; ++C) {
Richard Smithba71c082013-05-16 06:20:58 +00003019 // FIXME: Lambda init-captures.
3020 if (!C->capturesVariable())
Guy Benyei11169dd2012-12-18 14:30:41 +00003021 continue;
Richard Smithba71c082013-05-16 06:20:58 +00003022
Guy Benyei11169dd2012-12-18 14:30:41 +00003023 if (Visit(MakeCursorVariableRef(C->getCapturedVar(),
3024 C->getLocation(),
3025 TU)))
3026 return true;
3027 }
3028
3029 // Visit parameters and return type, if present.
3030 if (E->hasExplicitParameters() || E->hasExplicitResultType()) {
3031 TypeLoc TL = E->getCallOperator()->getTypeSourceInfo()->getTypeLoc();
3032 if (E->hasExplicitParameters() && E->hasExplicitResultType()) {
3033 // Visit the whole type.
3034 if (Visit(TL))
3035 return true;
David Blaikie6adc78e2013-02-18 22:06:02 +00003036 } else if (FunctionProtoTypeLoc Proto =
3037 TL.getAs<FunctionProtoTypeLoc>()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003038 if (E->hasExplicitParameters()) {
3039 // Visit parameters.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00003040 for (unsigned I = 0, N = Proto.getNumParams(); I != N; ++I)
3041 if (Visit(MakeCXCursor(Proto.getParam(I), TU)))
Guy Benyei11169dd2012-12-18 14:30:41 +00003042 return true;
3043 } else {
3044 // Visit result type.
Alp Toker42a16a62014-01-25 23:51:36 +00003045 if (Visit(Proto.getReturnLoc()))
Guy Benyei11169dd2012-12-18 14:30:41 +00003046 return true;
3047 }
3048 }
3049 }
3050 break;
3051 }
3052
3053 case VisitorJob::PostChildrenVisitKind:
3054 if (PostChildrenVisitor(Parent, ClientData))
3055 return true;
3056 break;
3057 }
3058 }
3059 return false;
3060}
3061
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003062bool CursorVisitor::Visit(const Stmt *S) {
Craig Topper69186e72014-06-08 08:38:04 +00003063 VisitorWorkList *WL = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00003064 if (!WorkListFreeList.empty()) {
3065 WL = WorkListFreeList.back();
3066 WL->clear();
3067 WorkListFreeList.pop_back();
3068 }
3069 else {
3070 WL = new VisitorWorkList();
3071 WorkListCache.push_back(WL);
3072 }
3073 EnqueueWorkList(*WL, S);
3074 bool result = RunVisitorWorkList(*WL);
3075 WorkListFreeList.push_back(WL);
3076 return result;
3077}
3078
3079namespace {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003080typedef SmallVector<SourceRange, 4> RefNamePieces;
James Y Knight04ec5bf2015-12-24 02:59:37 +00003081RefNamePieces buildPieces(unsigned NameFlags, bool IsMemberRefExpr,
3082 const DeclarationNameInfo &NI, SourceRange QLoc,
3083 const SourceRange *TemplateArgsLoc = nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003084 const bool WantQualifier = NameFlags & CXNameRange_WantQualifier;
3085 const bool WantTemplateArgs = NameFlags & CXNameRange_WantTemplateArgs;
3086 const bool WantSinglePiece = NameFlags & CXNameRange_WantSinglePiece;
3087
3088 const DeclarationName::NameKind Kind = NI.getName().getNameKind();
3089
3090 RefNamePieces Pieces;
3091
3092 if (WantQualifier && QLoc.isValid())
3093 Pieces.push_back(QLoc);
3094
3095 if (Kind != DeclarationName::CXXOperatorName || IsMemberRefExpr)
3096 Pieces.push_back(NI.getLoc());
James Y Knight04ec5bf2015-12-24 02:59:37 +00003097
3098 if (WantTemplateArgs && TemplateArgsLoc && TemplateArgsLoc->isValid())
3099 Pieces.push_back(*TemplateArgsLoc);
3100
Guy Benyei11169dd2012-12-18 14:30:41 +00003101 if (Kind == DeclarationName::CXXOperatorName) {
3102 Pieces.push_back(SourceLocation::getFromRawEncoding(
3103 NI.getInfo().CXXOperatorName.BeginOpNameLoc));
3104 Pieces.push_back(SourceLocation::getFromRawEncoding(
3105 NI.getInfo().CXXOperatorName.EndOpNameLoc));
3106 }
3107
3108 if (WantSinglePiece) {
3109 SourceRange R(Pieces.front().getBegin(), Pieces.back().getEnd());
3110 Pieces.clear();
3111 Pieces.push_back(R);
3112 }
3113
3114 return Pieces;
3115}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003116}
Guy Benyei11169dd2012-12-18 14:30:41 +00003117
3118//===----------------------------------------------------------------------===//
3119// Misc. API hooks.
3120//===----------------------------------------------------------------------===//
3121
Chad Rosier05c71aa2013-03-27 18:28:23 +00003122static void fatal_error_handler(void *user_data, const std::string& reason,
3123 bool gen_crash_diag) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003124 // Write the result out to stderr avoiding errs() because raw_ostreams can
3125 // call report_fatal_error.
3126 fprintf(stderr, "LIBCLANG FATAL ERROR: %s\n", reason.c_str());
3127 ::abort();
3128}
3129
Chandler Carruth66660742014-06-27 16:37:27 +00003130namespace {
3131struct RegisterFatalErrorHandler {
3132 RegisterFatalErrorHandler() {
3133 llvm::install_fatal_error_handler(fatal_error_handler, nullptr);
3134 }
3135};
3136}
3137
3138static llvm::ManagedStatic<RegisterFatalErrorHandler> RegisterFatalErrorHandlerOnce;
3139
Guy Benyei11169dd2012-12-18 14:30:41 +00003140CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
3141 int displayDiagnostics) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003142 // We use crash recovery to make some of our APIs more reliable, implicitly
3143 // enable it.
Argyrios Kyrtzidis3701f542013-11-27 08:58:09 +00003144 if (!getenv("LIBCLANG_DISABLE_CRASH_RECOVERY"))
3145 llvm::CrashRecoveryContext::Enable();
Guy Benyei11169dd2012-12-18 14:30:41 +00003146
Chandler Carruth66660742014-06-27 16:37:27 +00003147 // Look through the managed static to trigger construction of the managed
3148 // static which registers our fatal error handler. This ensures it is only
3149 // registered once.
3150 (void)*RegisterFatalErrorHandlerOnce;
Guy Benyei11169dd2012-12-18 14:30:41 +00003151
Adrian Prantlbc068582015-07-08 01:00:30 +00003152 // Initialize targets for clang module support.
3153 llvm::InitializeAllTargets();
3154 llvm::InitializeAllTargetMCs();
3155 llvm::InitializeAllAsmPrinters();
3156 llvm::InitializeAllAsmParsers();
3157
Adrian Prantlfb2398d2015-07-17 01:19:54 +00003158 CIndexer *CIdxr = new CIndexer();
3159
Guy Benyei11169dd2012-12-18 14:30:41 +00003160 if (excludeDeclarationsFromPCH)
3161 CIdxr->setOnlyLocalDecls();
3162 if (displayDiagnostics)
3163 CIdxr->setDisplayDiagnostics();
3164
3165 if (getenv("LIBCLANG_BGPRIO_INDEX"))
3166 CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() |
3167 CXGlobalOpt_ThreadBackgroundPriorityForIndexing);
3168 if (getenv("LIBCLANG_BGPRIO_EDIT"))
3169 CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() |
3170 CXGlobalOpt_ThreadBackgroundPriorityForEditing);
3171
3172 return CIdxr;
3173}
3174
3175void clang_disposeIndex(CXIndex CIdx) {
3176 if (CIdx)
3177 delete static_cast<CIndexer *>(CIdx);
3178}
3179
3180void clang_CXIndex_setGlobalOptions(CXIndex CIdx, unsigned options) {
3181 if (CIdx)
3182 static_cast<CIndexer *>(CIdx)->setCXGlobalOptFlags(options);
3183}
3184
3185unsigned clang_CXIndex_getGlobalOptions(CXIndex CIdx) {
3186 if (CIdx)
3187 return static_cast<CIndexer *>(CIdx)->getCXGlobalOptFlags();
3188 return 0;
3189}
3190
3191void clang_toggleCrashRecovery(unsigned isEnabled) {
3192 if (isEnabled)
3193 llvm::CrashRecoveryContext::Enable();
3194 else
3195 llvm::CrashRecoveryContext::Disable();
3196}
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003197
Guy Benyei11169dd2012-12-18 14:30:41 +00003198CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
3199 const char *ast_filename) {
Dmitri Gribenko8850cda2014-02-19 10:24:00 +00003200 CXTranslationUnit TU;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003201 enum CXErrorCode Result =
3202 clang_createTranslationUnit2(CIdx, ast_filename, &TU);
Reid Klecknerfd48fc62014-02-12 23:56:20 +00003203 (void)Result;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003204 assert((TU && Result == CXError_Success) ||
3205 (!TU && Result != CXError_Success));
3206 return TU;
3207}
3208
3209enum CXErrorCode clang_createTranslationUnit2(CXIndex CIdx,
3210 const char *ast_filename,
3211 CXTranslationUnit *out_TU) {
Dmitri Gribenko8850cda2014-02-19 10:24:00 +00003212 if (out_TU)
Craig Topper69186e72014-06-08 08:38:04 +00003213 *out_TU = nullptr;
Dmitri Gribenko8850cda2014-02-19 10:24:00 +00003214
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003215 if (!CIdx || !ast_filename || !out_TU)
3216 return CXError_InvalidArguments;
Guy Benyei11169dd2012-12-18 14:30:41 +00003217
Argyrios Kyrtzidis27021012013-05-24 22:24:07 +00003218 LOG_FUNC_SECTION {
3219 *Log << ast_filename;
3220 }
3221
Guy Benyei11169dd2012-12-18 14:30:41 +00003222 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
3223 FileSystemOptions FileSystemOpts;
3224
Justin Bognerd512c1e2014-10-15 00:33:06 +00003225 IntrusiveRefCntPtr<DiagnosticsEngine> Diags =
3226 CompilerInstance::createDiagnostics(new DiagnosticOptions());
David Blaikie6f7382d2014-08-10 19:08:04 +00003227 std::unique_ptr<ASTUnit> AU = ASTUnit::LoadFromASTFile(
Adrian Prantlfb2398d2015-07-17 01:19:54 +00003228 ast_filename, CXXIdx->getPCHContainerOperations()->getRawReader(), Diags,
Adrian Prantl6b21ab22015-08-27 19:46:20 +00003229 FileSystemOpts, /*UseDebugInfo=*/false,
3230 CXXIdx->getOnlyLocalDecls(), None,
David Blaikie6f7382d2014-08-10 19:08:04 +00003231 /*CaptureDiagnostics=*/true,
3232 /*AllowPCHWithCompilerErrors=*/true,
3233 /*UserFilesAreVolatile=*/true);
David Blaikie81d08292017-01-06 17:47:10 +00003234 *out_TU = MakeCXTranslationUnit(CXXIdx, AU.release());
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003235 return *out_TU ? CXError_Success : CXError_Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003236}
3237
3238unsigned clang_defaultEditingTranslationUnitOptions() {
3239 return CXTranslationUnit_PrecompiledPreamble |
3240 CXTranslationUnit_CacheCompletionResults;
3241}
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003242
Guy Benyei11169dd2012-12-18 14:30:41 +00003243CXTranslationUnit
3244clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
3245 const char *source_filename,
3246 int num_command_line_args,
3247 const char * const *command_line_args,
3248 unsigned num_unsaved_files,
3249 struct CXUnsavedFile *unsaved_files) {
3250 unsigned Options = CXTranslationUnit_DetailedPreprocessingRecord;
3251 return clang_parseTranslationUnit(CIdx, source_filename,
3252 command_line_args, num_command_line_args,
3253 unsaved_files, num_unsaved_files,
3254 Options);
3255}
3256
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003257static CXErrorCode
3258clang_parseTranslationUnit_Impl(CXIndex CIdx, const char *source_filename,
3259 const char *const *command_line_args,
3260 int num_command_line_args,
3261 ArrayRef<CXUnsavedFile> unsaved_files,
3262 unsigned options, CXTranslationUnit *out_TU) {
Dmitri Gribenko1bf8d912014-02-18 15:20:02 +00003263 // Set up the initial return values.
3264 if (out_TU)
Craig Topper69186e72014-06-08 08:38:04 +00003265 *out_TU = nullptr;
Dmitri Gribenko1bf8d912014-02-18 15:20:02 +00003266
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003267 // Check arguments.
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003268 if (!CIdx || !out_TU)
3269 return CXError_InvalidArguments;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003270
Guy Benyei11169dd2012-12-18 14:30:41 +00003271 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
3272
3273 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
3274 setThreadBackgroundPriority();
3275
3276 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Benjamin Kramer5c248d82015-12-15 09:30:31 +00003277 bool CreatePreambleOnFirstParse =
3278 options & CXTranslationUnit_CreatePreambleOnFirstParse;
Guy Benyei11169dd2012-12-18 14:30:41 +00003279 // FIXME: Add a flag for modules.
3280 TranslationUnitKind TUKind
3281 = (options & CXTranslationUnit_Incomplete)? TU_Prefix : TU_Complete;
Alp Toker8c8a8752013-12-03 06:53:35 +00003282 bool CacheCodeCompletionResults
Guy Benyei11169dd2012-12-18 14:30:41 +00003283 = options & CXTranslationUnit_CacheCompletionResults;
3284 bool IncludeBriefCommentsInCodeCompletion
3285 = options & CXTranslationUnit_IncludeBriefCommentsInCodeCompletion;
3286 bool SkipFunctionBodies = options & CXTranslationUnit_SkipFunctionBodies;
3287 bool ForSerialization = options & CXTranslationUnit_ForSerialization;
3288
3289 // Configure the diagnostics.
3290 IntrusiveRefCntPtr<DiagnosticsEngine>
Sean Silvaf1b49e22013-01-20 01:58:28 +00003291 Diags(CompilerInstance::createDiagnostics(new DiagnosticOptions));
Guy Benyei11169dd2012-12-18 14:30:41 +00003292
Manuel Klimek016c0242016-03-01 10:56:19 +00003293 if (options & CXTranslationUnit_KeepGoing)
3294 Diags->setFatalsAsError(true);
3295
Guy Benyei11169dd2012-12-18 14:30:41 +00003296 // Recover resources if we crash before exiting this function.
3297 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
3298 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Alp Tokerf994cef2014-07-05 03:08:06 +00003299 DiagCleanup(Diags.get());
Guy Benyei11169dd2012-12-18 14:30:41 +00003300
Ahmed Charlesb8984322014-03-07 20:03:18 +00003301 std::unique_ptr<std::vector<ASTUnit::RemappedFile>> RemappedFiles(
3302 new std::vector<ASTUnit::RemappedFile>());
Guy Benyei11169dd2012-12-18 14:30:41 +00003303
3304 // Recover resources if we crash before exiting this function.
3305 llvm::CrashRecoveryContextCleanupRegistrar<
3306 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
3307
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003308 for (auto &UF : unsaved_files) {
Rafael Espindolad87f8d72014-08-27 20:03:29 +00003309 std::unique_ptr<llvm::MemoryBuffer> MB =
Alp Toker9d85b182014-07-07 01:23:14 +00003310 llvm::MemoryBuffer::getMemBufferCopy(getContents(UF), UF.Filename);
Rafael Espindolad87f8d72014-08-27 20:03:29 +00003311 RemappedFiles->push_back(std::make_pair(UF.Filename, MB.release()));
Guy Benyei11169dd2012-12-18 14:30:41 +00003312 }
3313
Ahmed Charlesb8984322014-03-07 20:03:18 +00003314 std::unique_ptr<std::vector<const char *>> Args(
3315 new std::vector<const char *>());
Guy Benyei11169dd2012-12-18 14:30:41 +00003316
3317 // Recover resources if we crash before exiting this method.
3318 llvm::CrashRecoveryContextCleanupRegistrar<std::vector<const char*> >
3319 ArgsCleanup(Args.get());
3320
3321 // Since the Clang C library is primarily used by batch tools dealing with
3322 // (often very broken) source code, where spell-checking can have a
3323 // significant negative impact on performance (particularly when
3324 // precompiled headers are involved), we disable it by default.
3325 // Only do this if we haven't found a spell-checking-related argument.
3326 bool FoundSpellCheckingArgument = false;
3327 for (int I = 0; I != num_command_line_args; ++I) {
3328 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
3329 strcmp(command_line_args[I], "-fspell-checking") == 0) {
3330 FoundSpellCheckingArgument = true;
3331 break;
3332 }
3333 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003334 Args->insert(Args->end(), command_line_args,
3335 command_line_args + num_command_line_args);
3336
Benjamin Kramerc02670e2015-11-18 16:14:27 +00003337 if (!FoundSpellCheckingArgument)
3338 Args->insert(Args->begin() + 1, "-fno-spell-checking");
3339
Guy Benyei11169dd2012-12-18 14:30:41 +00003340 // The 'source_filename' argument is optional. If the caller does not
3341 // specify it then it is assumed that the source file is specified
3342 // in the actual argument list.
3343 // Put the source file after command_line_args otherwise if '-x' flag is
3344 // present it will be unused.
3345 if (source_filename)
3346 Args->push_back(source_filename);
3347
3348 // Do we need the detailed preprocessing record?
3349 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
3350 Args->push_back("-Xclang");
3351 Args->push_back("-detailed-preprocessing-record");
3352 }
3353
3354 unsigned NumErrors = Diags->getClient()->getNumErrors();
Ahmed Charlesb8984322014-03-07 20:03:18 +00003355 std::unique_ptr<ASTUnit> ErrUnit;
Benjamin Kramer5c248d82015-12-15 09:30:31 +00003356 // Unless the user specified that they want the preamble on the first parse
3357 // set it up to be created on the first reparse. This makes the first parse
3358 // faster, trading for a slower (first) reparse.
3359 unsigned PrecompilePreambleAfterNParses =
3360 !PrecompilePreamble ? 0 : 2 - CreatePreambleOnFirstParse;
Ahmed Charlesb8984322014-03-07 20:03:18 +00003361 std::unique_ptr<ASTUnit> Unit(ASTUnit::LoadFromCommandLine(
Adrian Prantlbb165fb2015-06-20 18:53:08 +00003362 Args->data(), Args->data() + Args->size(),
3363 CXXIdx->getPCHContainerOperations(), Diags,
Ahmed Charlesb8984322014-03-07 20:03:18 +00003364 CXXIdx->getClangResourcesPath(), CXXIdx->getOnlyLocalDecls(),
3365 /*CaptureDiagnostics=*/true, *RemappedFiles.get(),
Benjamin Kramer5c248d82015-12-15 09:30:31 +00003366 /*RemappedFilesKeepOriginalName=*/true, PrecompilePreambleAfterNParses,
3367 TUKind, CacheCodeCompletionResults, IncludeBriefCommentsInCodeCompletion,
Ahmed Charlesb8984322014-03-07 20:03:18 +00003368 /*AllowPCHWithCompilerErrors=*/true, SkipFunctionBodies,
Argyrios Kyrtzidisa3e2ff12015-11-20 03:36:21 +00003369 /*UserFilesAreVolatile=*/true, ForSerialization,
3370 CXXIdx->getPCHContainerOperations()->getRawReader().getFormat(),
3371 &ErrUnit));
Guy Benyei11169dd2012-12-18 14:30:41 +00003372
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003373 // Early failures in LoadFromCommandLine may return with ErrUnit unset.
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003374 if (!Unit && !ErrUnit)
3375 return CXError_ASTReadError;
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003376
Guy Benyei11169dd2012-12-18 14:30:41 +00003377 if (NumErrors != Diags->getClient()->getNumErrors()) {
3378 // Make sure to check that 'Unit' is non-NULL.
3379 if (CXXIdx->getDisplayDiagnostics())
3380 printDiagsToStderr(Unit ? Unit.get() : ErrUnit.get());
3381 }
3382
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003383 if (isASTReadError(Unit ? Unit.get() : ErrUnit.get()))
3384 return CXError_ASTReadError;
3385
David Blaikie81d08292017-01-06 17:47:10 +00003386 *out_TU = MakeCXTranslationUnit(CXXIdx, Unit.release());
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003387 return *out_TU ? CXError_Success : CXError_Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003388}
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003389
3390CXTranslationUnit
3391clang_parseTranslationUnit(CXIndex CIdx,
3392 const char *source_filename,
3393 const char *const *command_line_args,
3394 int num_command_line_args,
3395 struct CXUnsavedFile *unsaved_files,
3396 unsigned num_unsaved_files,
3397 unsigned options) {
3398 CXTranslationUnit TU;
3399 enum CXErrorCode Result = clang_parseTranslationUnit2(
3400 CIdx, source_filename, command_line_args, num_command_line_args,
3401 unsaved_files, num_unsaved_files, options, &TU);
Reid Kleckner6eaf05a2014-02-13 01:19:59 +00003402 (void)Result;
Dmitri Gribenko1bf8d912014-02-18 15:20:02 +00003403 assert((TU && Result == CXError_Success) ||
3404 (!TU && Result != CXError_Success));
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003405 return TU;
3406}
3407
3408enum CXErrorCode clang_parseTranslationUnit2(
Benjamin Kramerc02670e2015-11-18 16:14:27 +00003409 CXIndex CIdx, const char *source_filename,
3410 const char *const *command_line_args, int num_command_line_args,
3411 struct CXUnsavedFile *unsaved_files, unsigned num_unsaved_files,
3412 unsigned options, CXTranslationUnit *out_TU) {
3413 SmallVector<const char *, 4> Args;
3414 Args.push_back("clang");
3415 Args.append(command_line_args, command_line_args + num_command_line_args);
3416 return clang_parseTranslationUnit2FullArgv(
3417 CIdx, source_filename, Args.data(), Args.size(), unsaved_files,
3418 num_unsaved_files, options, out_TU);
3419}
3420
3421enum CXErrorCode clang_parseTranslationUnit2FullArgv(
3422 CXIndex CIdx, const char *source_filename,
3423 const char *const *command_line_args, int num_command_line_args,
3424 struct CXUnsavedFile *unsaved_files, unsigned num_unsaved_files,
3425 unsigned options, CXTranslationUnit *out_TU) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00003426 LOG_FUNC_SECTION {
3427 *Log << source_filename << ": ";
3428 for (int i = 0; i != num_command_line_args; ++i)
3429 *Log << command_line_args[i] << " ";
3430 }
3431
Alp Toker9d85b182014-07-07 01:23:14 +00003432 if (num_unsaved_files && !unsaved_files)
3433 return CXError_InvalidArguments;
3434
Alp Toker5c532982014-07-07 22:42:03 +00003435 CXErrorCode result = CXError_Failure;
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003436 auto ParseTranslationUnitImpl = [=, &result] {
3437 result = clang_parseTranslationUnit_Impl(
3438 CIdx, source_filename, command_line_args, num_command_line_args,
3439 llvm::makeArrayRef(unsaved_files, num_unsaved_files), options, out_TU);
3440 };
Guy Benyei11169dd2012-12-18 14:30:41 +00003441 llvm::CrashRecoveryContext CRC;
3442
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003443 if (!RunSafely(CRC, ParseTranslationUnitImpl)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003444 fprintf(stderr, "libclang: crash detected during parsing: {\n");
3445 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
3446 fprintf(stderr, " 'command_line_args' : [");
3447 for (int i = 0; i != num_command_line_args; ++i) {
3448 if (i)
3449 fprintf(stderr, ", ");
3450 fprintf(stderr, "'%s'", command_line_args[i]);
3451 }
3452 fprintf(stderr, "],\n");
3453 fprintf(stderr, " 'unsaved_files' : [");
3454 for (unsigned i = 0; i != num_unsaved_files; ++i) {
3455 if (i)
3456 fprintf(stderr, ", ");
3457 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
3458 unsaved_files[i].Length);
3459 }
3460 fprintf(stderr, "],\n");
3461 fprintf(stderr, " 'options' : %d,\n", options);
3462 fprintf(stderr, "}\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003463
3464 return CXError_Crashed;
Guy Benyei11169dd2012-12-18 14:30:41 +00003465 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003466 if (CXTranslationUnit *TU = out_TU)
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003467 PrintLibclangResourceUsage(*TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00003468 }
Alp Toker5c532982014-07-07 22:42:03 +00003469
3470 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003471}
3472
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003473CXString clang_Type_getObjCEncoding(CXType CT) {
3474 CXTranslationUnit tu = static_cast<CXTranslationUnit>(CT.data[1]);
3475 ASTContext &Ctx = getASTUnit(tu)->getASTContext();
3476 std::string encoding;
3477 Ctx.getObjCEncodingForType(QualType::getFromOpaquePtr(CT.data[0]),
3478 encoding);
3479
3480 return cxstring::createDup(encoding);
3481}
3482
3483static const IdentifierInfo *getMacroIdentifier(CXCursor C) {
3484 if (C.kind == CXCursor_MacroDefinition) {
3485 if (const MacroDefinitionRecord *MDR = getCursorMacroDefinition(C))
3486 return MDR->getName();
3487 } else if (C.kind == CXCursor_MacroExpansion) {
3488 MacroExpansionCursor ME = getCursorMacroExpansion(C);
3489 return ME.getName();
3490 }
3491 return nullptr;
3492}
3493
3494unsigned clang_Cursor_isMacroFunctionLike(CXCursor C) {
3495 const IdentifierInfo *II = getMacroIdentifier(C);
3496 if (!II) {
3497 return false;
3498 }
3499 ASTUnit *ASTU = getCursorASTUnit(C);
3500 Preprocessor &PP = ASTU->getPreprocessor();
3501 if (const MacroInfo *MI = PP.getMacroInfo(II))
3502 return MI->isFunctionLike();
3503 return false;
3504}
3505
3506unsigned clang_Cursor_isMacroBuiltin(CXCursor C) {
3507 const IdentifierInfo *II = getMacroIdentifier(C);
3508 if (!II) {
3509 return false;
3510 }
3511 ASTUnit *ASTU = getCursorASTUnit(C);
3512 Preprocessor &PP = ASTU->getPreprocessor();
3513 if (const MacroInfo *MI = PP.getMacroInfo(II))
3514 return MI->isBuiltinMacro();
3515 return false;
3516}
3517
3518unsigned clang_Cursor_isFunctionInlined(CXCursor C) {
3519 const Decl *D = getCursorDecl(C);
3520 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
3521 if (!FD) {
3522 return false;
3523 }
3524 return FD->isInlined();
3525}
3526
3527static StringLiteral* getCFSTR_value(CallExpr *callExpr) {
3528 if (callExpr->getNumArgs() != 1) {
3529 return nullptr;
3530 }
3531
3532 StringLiteral *S = nullptr;
3533 auto *arg = callExpr->getArg(0);
3534 if (arg->getStmtClass() == Stmt::ImplicitCastExprClass) {
3535 ImplicitCastExpr *I = static_cast<ImplicitCastExpr *>(arg);
3536 auto *subExpr = I->getSubExprAsWritten();
3537
3538 if(subExpr->getStmtClass() != Stmt::StringLiteralClass){
3539 return nullptr;
3540 }
3541
3542 S = static_cast<StringLiteral *>(I->getSubExprAsWritten());
3543 } else if (arg->getStmtClass() == Stmt::StringLiteralClass) {
3544 S = static_cast<StringLiteral *>(callExpr->getArg(0));
3545 } else {
3546 return nullptr;
3547 }
3548 return S;
3549}
3550
David Blaikie59272572016-04-13 18:23:33 +00003551struct ExprEvalResult {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003552 CXEvalResultKind EvalType;
3553 union {
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003554 unsigned long long unsignedVal;
3555 long long intVal;
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003556 double floatVal;
3557 char *stringVal;
3558 } EvalData;
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003559 bool IsUnsignedInt;
David Blaikie59272572016-04-13 18:23:33 +00003560 ~ExprEvalResult() {
3561 if (EvalType != CXEval_UnExposed && EvalType != CXEval_Float &&
3562 EvalType != CXEval_Int) {
3563 delete EvalData.stringVal;
3564 }
3565 }
3566};
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003567
3568void clang_EvalResult_dispose(CXEvalResult E) {
David Blaikie59272572016-04-13 18:23:33 +00003569 delete static_cast<ExprEvalResult *>(E);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003570}
3571
3572CXEvalResultKind clang_EvalResult_getKind(CXEvalResult E) {
3573 if (!E) {
3574 return CXEval_UnExposed;
3575 }
3576 return ((ExprEvalResult *)E)->EvalType;
3577}
3578
3579int clang_EvalResult_getAsInt(CXEvalResult E) {
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003580 return clang_EvalResult_getAsLongLong(E);
3581}
3582
3583long long clang_EvalResult_getAsLongLong(CXEvalResult E) {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003584 if (!E) {
3585 return 0;
3586 }
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003587 ExprEvalResult *Result = (ExprEvalResult*)E;
3588 if (Result->IsUnsignedInt)
3589 return Result->EvalData.unsignedVal;
3590 return Result->EvalData.intVal;
3591}
3592
3593unsigned clang_EvalResult_isUnsignedInt(CXEvalResult E) {
3594 return ((ExprEvalResult *)E)->IsUnsignedInt;
3595}
3596
3597unsigned long long clang_EvalResult_getAsUnsigned(CXEvalResult E) {
3598 if (!E) {
3599 return 0;
3600 }
3601
3602 ExprEvalResult *Result = (ExprEvalResult*)E;
3603 if (Result->IsUnsignedInt)
3604 return Result->EvalData.unsignedVal;
3605 return Result->EvalData.intVal;
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003606}
3607
3608double clang_EvalResult_getAsDouble(CXEvalResult E) {
3609 if (!E) {
3610 return 0;
3611 }
3612 return ((ExprEvalResult *)E)->EvalData.floatVal;
3613}
3614
3615const char* clang_EvalResult_getAsStr(CXEvalResult E) {
3616 if (!E) {
3617 return nullptr;
3618 }
3619 return ((ExprEvalResult *)E)->EvalData.stringVal;
3620}
3621
3622static const ExprEvalResult* evaluateExpr(Expr *expr, CXCursor C) {
3623 Expr::EvalResult ER;
3624 ASTContext &ctx = getCursorContext(C);
David Blaikiebbc00882016-04-13 18:36:19 +00003625 if (!expr)
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003626 return nullptr;
David Blaikiebbc00882016-04-13 18:36:19 +00003627
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003628 expr = expr->IgnoreParens();
David Blaikiebbc00882016-04-13 18:36:19 +00003629 if (!expr->EvaluateAsRValue(ER, ctx))
3630 return nullptr;
3631
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003632 QualType rettype;
3633 CallExpr *callExpr;
David Blaikie59272572016-04-13 18:23:33 +00003634 auto result = llvm::make_unique<ExprEvalResult>();
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003635 result->EvalType = CXEval_UnExposed;
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003636 result->IsUnsignedInt = false;
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003637
David Blaikiebbc00882016-04-13 18:36:19 +00003638 if (ER.Val.isInt()) {
3639 result->EvalType = CXEval_Int;
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003640
3641 auto& val = ER.Val.getInt();
3642 if (val.isUnsigned()) {
3643 result->IsUnsignedInt = true;
3644 result->EvalData.unsignedVal = val.getZExtValue();
3645 } else {
3646 result->EvalData.intVal = val.getExtValue();
3647 }
3648
David Blaikiebbc00882016-04-13 18:36:19 +00003649 return result.release();
3650 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003651
David Blaikiebbc00882016-04-13 18:36:19 +00003652 if (ER.Val.isFloat()) {
3653 llvm::SmallVector<char, 100> Buffer;
3654 ER.Val.getFloat().toString(Buffer);
3655 std::string floatStr(Buffer.data(), Buffer.size());
3656 result->EvalType = CXEval_Float;
3657 bool ignored;
3658 llvm::APFloat apFloat = ER.Val.getFloat();
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003659 apFloat.convert(llvm::APFloat::IEEEdouble(),
David Blaikiebbc00882016-04-13 18:36:19 +00003660 llvm::APFloat::rmNearestTiesToEven, &ignored);
3661 result->EvalData.floatVal = apFloat.convertToDouble();
3662 return result.release();
3663 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003664
David Blaikiebbc00882016-04-13 18:36:19 +00003665 if (expr->getStmtClass() == Stmt::ImplicitCastExprClass) {
3666 const ImplicitCastExpr *I = dyn_cast<ImplicitCastExpr>(expr);
3667 auto *subExpr = I->getSubExprAsWritten();
3668 if (subExpr->getStmtClass() == Stmt::StringLiteralClass ||
3669 subExpr->getStmtClass() == Stmt::ObjCStringLiteralClass) {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003670 const StringLiteral *StrE = nullptr;
3671 const ObjCStringLiteral *ObjCExpr;
David Blaikiebbc00882016-04-13 18:36:19 +00003672 ObjCExpr = dyn_cast<ObjCStringLiteral>(subExpr);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003673
3674 if (ObjCExpr) {
3675 StrE = ObjCExpr->getString();
3676 result->EvalType = CXEval_ObjCStrLiteral;
3677 } else {
David Blaikiebbc00882016-04-13 18:36:19 +00003678 StrE = cast<StringLiteral>(I->getSubExprAsWritten());
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003679 result->EvalType = CXEval_StrLiteral;
3680 }
3681
3682 std::string strRef(StrE->getString().str());
David Blaikie59272572016-04-13 18:23:33 +00003683 result->EvalData.stringVal = new char[strRef.size() + 1];
David Blaikiebbc00882016-04-13 18:36:19 +00003684 strncpy((char *)result->EvalData.stringVal, strRef.c_str(),
3685 strRef.size());
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003686 result->EvalData.stringVal[strRef.size()] = '\0';
David Blaikie59272572016-04-13 18:23:33 +00003687 return result.release();
David Blaikiebbc00882016-04-13 18:36:19 +00003688 }
3689 } else if (expr->getStmtClass() == Stmt::ObjCStringLiteralClass ||
3690 expr->getStmtClass() == Stmt::StringLiteralClass) {
3691 const StringLiteral *StrE = nullptr;
3692 const ObjCStringLiteral *ObjCExpr;
3693 ObjCExpr = dyn_cast<ObjCStringLiteral>(expr);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003694
David Blaikiebbc00882016-04-13 18:36:19 +00003695 if (ObjCExpr) {
3696 StrE = ObjCExpr->getString();
3697 result->EvalType = CXEval_ObjCStrLiteral;
3698 } else {
3699 StrE = cast<StringLiteral>(expr);
3700 result->EvalType = CXEval_StrLiteral;
3701 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003702
David Blaikiebbc00882016-04-13 18:36:19 +00003703 std::string strRef(StrE->getString().str());
3704 result->EvalData.stringVal = new char[strRef.size() + 1];
3705 strncpy((char *)result->EvalData.stringVal, strRef.c_str(), strRef.size());
3706 result->EvalData.stringVal[strRef.size()] = '\0';
3707 return result.release();
3708 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003709
David Blaikiebbc00882016-04-13 18:36:19 +00003710 if (expr->getStmtClass() == Stmt::CStyleCastExprClass) {
3711 CStyleCastExpr *CC = static_cast<CStyleCastExpr *>(expr);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003712
David Blaikiebbc00882016-04-13 18:36:19 +00003713 rettype = CC->getType();
3714 if (rettype.getAsString() == "CFStringRef" &&
3715 CC->getSubExpr()->getStmtClass() == Stmt::CallExprClass) {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003716
David Blaikiebbc00882016-04-13 18:36:19 +00003717 callExpr = static_cast<CallExpr *>(CC->getSubExpr());
3718 StringLiteral *S = getCFSTR_value(callExpr);
3719 if (S) {
3720 std::string strLiteral(S->getString().str());
3721 result->EvalType = CXEval_CFStr;
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003722
David Blaikiebbc00882016-04-13 18:36:19 +00003723 result->EvalData.stringVal = new char[strLiteral.size() + 1];
3724 strncpy((char *)result->EvalData.stringVal, strLiteral.c_str(),
3725 strLiteral.size());
3726 result->EvalData.stringVal[strLiteral.size()] = '\0';
David Blaikie59272572016-04-13 18:23:33 +00003727 return result.release();
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003728 }
3729 }
3730
David Blaikiebbc00882016-04-13 18:36:19 +00003731 } else if (expr->getStmtClass() == Stmt::CallExprClass) {
3732 callExpr = static_cast<CallExpr *>(expr);
3733 rettype = callExpr->getCallReturnType(ctx);
3734
3735 if (rettype->isVectorType() || callExpr->getNumArgs() > 1)
3736 return nullptr;
3737
3738 if (rettype->isIntegralType(ctx) || rettype->isRealFloatingType()) {
3739 if (callExpr->getNumArgs() == 1 &&
3740 !callExpr->getArg(0)->getType()->isIntegralType(ctx))
3741 return nullptr;
3742 } else if (rettype.getAsString() == "CFStringRef") {
3743
3744 StringLiteral *S = getCFSTR_value(callExpr);
3745 if (S) {
3746 std::string strLiteral(S->getString().str());
3747 result->EvalType = CXEval_CFStr;
3748 result->EvalData.stringVal = new char[strLiteral.size() + 1];
3749 strncpy((char *)result->EvalData.stringVal, strLiteral.c_str(),
3750 strLiteral.size());
3751 result->EvalData.stringVal[strLiteral.size()] = '\0';
3752 return result.release();
3753 }
3754 }
3755 } else if (expr->getStmtClass() == Stmt::DeclRefExprClass) {
3756 DeclRefExpr *D = static_cast<DeclRefExpr *>(expr);
3757 ValueDecl *V = D->getDecl();
3758 if (V->getKind() == Decl::Function) {
3759 std::string strName = V->getNameAsString();
3760 result->EvalType = CXEval_Other;
3761 result->EvalData.stringVal = new char[strName.size() + 1];
3762 strncpy(result->EvalData.stringVal, strName.c_str(), strName.size());
3763 result->EvalData.stringVal[strName.size()] = '\0';
3764 return result.release();
3765 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003766 }
3767
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003768 return nullptr;
3769}
3770
3771CXEvalResult clang_Cursor_Evaluate(CXCursor C) {
3772 const Decl *D = getCursorDecl(C);
3773 if (D) {
3774 const Expr *expr = nullptr;
3775 if (auto *Var = dyn_cast<VarDecl>(D)) {
3776 expr = Var->getInit();
3777 } else if (auto *Field = dyn_cast<FieldDecl>(D)) {
3778 expr = Field->getInClassInitializer();
3779 }
3780 if (expr)
Aaron Ballman01dc1572016-01-20 15:25:30 +00003781 return const_cast<CXEvalResult>(reinterpret_cast<const void *>(
3782 evaluateExpr(const_cast<Expr *>(expr), C)));
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003783 return nullptr;
3784 }
3785
3786 const CompoundStmt *compoundStmt = dyn_cast_or_null<CompoundStmt>(getCursorStmt(C));
3787 if (compoundStmt) {
3788 Expr *expr = nullptr;
3789 for (auto *bodyIterator : compoundStmt->body()) {
3790 if ((expr = dyn_cast<Expr>(bodyIterator))) {
3791 break;
3792 }
3793 }
3794 if (expr)
Aaron Ballman01dc1572016-01-20 15:25:30 +00003795 return const_cast<CXEvalResult>(
3796 reinterpret_cast<const void *>(evaluateExpr(expr, C)));
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003797 }
3798 return nullptr;
3799}
3800
3801unsigned clang_Cursor_hasAttrs(CXCursor C) {
3802 const Decl *D = getCursorDecl(C);
3803 if (!D) {
3804 return 0;
3805 }
3806
3807 if (D->hasAttrs()) {
3808 return 1;
3809 }
3810
3811 return 0;
3812}
Guy Benyei11169dd2012-12-18 14:30:41 +00003813unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
3814 return CXSaveTranslationUnit_None;
3815}
3816
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003817static CXSaveError clang_saveTranslationUnit_Impl(CXTranslationUnit TU,
3818 const char *FileName,
3819 unsigned options) {
3820 CIndexer *CXXIdx = TU->CIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00003821 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
3822 setThreadBackgroundPriority();
3823
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003824 bool hadError = cxtu::getASTUnit(TU)->Save(FileName);
3825 return hadError ? CXSaveError_Unknown : CXSaveError_None;
Guy Benyei11169dd2012-12-18 14:30:41 +00003826}
3827
3828int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
3829 unsigned options) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00003830 LOG_FUNC_SECTION {
3831 *Log << TU << ' ' << FileName;
3832 }
3833
Dmitri Gribenko852d6222014-02-11 15:02:48 +00003834 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00003835 LOG_BAD_TU(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00003836 return CXSaveError_InvalidTU;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00003837 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003838
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00003839 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00003840 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3841 if (!CXXUnit->hasSema())
3842 return CXSaveError_InvalidTU;
3843
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003844 CXSaveError result;
3845 auto SaveTranslationUnitImpl = [=, &result]() {
3846 result = clang_saveTranslationUnit_Impl(TU, FileName, options);
3847 };
Guy Benyei11169dd2012-12-18 14:30:41 +00003848
3849 if (!CXXUnit->getDiagnostics().hasUnrecoverableErrorOccurred() ||
3850 getenv("LIBCLANG_NOTHREADS")) {
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003851 SaveTranslationUnitImpl();
Guy Benyei11169dd2012-12-18 14:30:41 +00003852
3853 if (getenv("LIBCLANG_RESOURCE_USAGE"))
3854 PrintLibclangResourceUsage(TU);
3855
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003856 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003857 }
3858
3859 // We have an AST that has invalid nodes due to compiler errors.
3860 // Use a crash recovery thread for protection.
3861
3862 llvm::CrashRecoveryContext CRC;
3863
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003864 if (!RunSafely(CRC, SaveTranslationUnitImpl)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003865 fprintf(stderr, "libclang: crash detected during AST saving: {\n");
3866 fprintf(stderr, " 'filename' : '%s'\n", FileName);
3867 fprintf(stderr, " 'options' : %d,\n", options);
3868 fprintf(stderr, "}\n");
3869
3870 return CXSaveError_Unknown;
3871
3872 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
3873 PrintLibclangResourceUsage(TU);
3874 }
3875
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003876 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003877}
3878
3879void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
3880 if (CTUnit) {
3881 // If the translation unit has been marked as unsafe to free, just discard
3882 // it.
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003883 ASTUnit *Unit = cxtu::getASTUnit(CTUnit);
3884 if (Unit && Unit->isUnsafeToFree())
Guy Benyei11169dd2012-12-18 14:30:41 +00003885 return;
3886
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00003887 delete cxtu::getASTUnit(CTUnit);
Dmitri Gribenkob95b3f12013-01-26 22:44:19 +00003888 delete CTUnit->StringPool;
Guy Benyei11169dd2012-12-18 14:30:41 +00003889 delete static_cast<CXDiagnosticSetImpl *>(CTUnit->Diagnostics);
3890 disposeOverridenCXCursorsPool(CTUnit->OverridenCursorsPool);
Dmitri Gribenko9e605112013-11-13 22:16:51 +00003891 delete CTUnit->CommentToXML;
Guy Benyei11169dd2012-12-18 14:30:41 +00003892 delete CTUnit;
3893 }
3894}
3895
3896unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
3897 return CXReparse_None;
3898}
3899
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003900static CXErrorCode
3901clang_reparseTranslationUnit_Impl(CXTranslationUnit TU,
3902 ArrayRef<CXUnsavedFile> unsaved_files,
3903 unsigned options) {
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003904 // Check arguments.
Dmitri Gribenko852d6222014-02-11 15:02:48 +00003905 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00003906 LOG_BAD_TU(TU);
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003907 return CXError_InvalidArguments;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003908 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003909
3910 // Reset the associated diagnostics.
3911 delete static_cast<CXDiagnosticSetImpl*>(TU->Diagnostics);
Craig Topper69186e72014-06-08 08:38:04 +00003912 TU->Diagnostics = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00003913
Dmitri Gribenko183436e2013-01-26 21:49:50 +00003914 CIndexer *CXXIdx = TU->CIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00003915 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing))
3916 setThreadBackgroundPriority();
3917
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00003918 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00003919 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ahmed Charlesb8984322014-03-07 20:03:18 +00003920
3921 std::unique_ptr<std::vector<ASTUnit::RemappedFile>> RemappedFiles(
3922 new std::vector<ASTUnit::RemappedFile>());
3923
Guy Benyei11169dd2012-12-18 14:30:41 +00003924 // Recover resources if we crash before exiting this function.
3925 llvm::CrashRecoveryContextCleanupRegistrar<
3926 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
Alp Toker9d85b182014-07-07 01:23:14 +00003927
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003928 for (auto &UF : unsaved_files) {
Rafael Espindolad87f8d72014-08-27 20:03:29 +00003929 std::unique_ptr<llvm::MemoryBuffer> MB =
Alp Toker9d85b182014-07-07 01:23:14 +00003930 llvm::MemoryBuffer::getMemBufferCopy(getContents(UF), UF.Filename);
Rafael Espindolad87f8d72014-08-27 20:03:29 +00003931 RemappedFiles->push_back(std::make_pair(UF.Filename, MB.release()));
Guy Benyei11169dd2012-12-18 14:30:41 +00003932 }
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003933
Adrian Prantlbb165fb2015-06-20 18:53:08 +00003934 if (!CXXUnit->Reparse(CXXIdx->getPCHContainerOperations(),
3935 *RemappedFiles.get()))
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003936 return CXError_Success;
3937 if (isASTReadError(CXXUnit))
3938 return CXError_ASTReadError;
3939 return CXError_Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003940}
3941
3942int clang_reparseTranslationUnit(CXTranslationUnit TU,
3943 unsigned num_unsaved_files,
3944 struct CXUnsavedFile *unsaved_files,
3945 unsigned options) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00003946 LOG_FUNC_SECTION {
3947 *Log << TU;
3948 }
3949
Alp Toker9d85b182014-07-07 01:23:14 +00003950 if (num_unsaved_files && !unsaved_files)
3951 return CXError_InvalidArguments;
3952
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003953 CXErrorCode result;
3954 auto ReparseTranslationUnitImpl = [=, &result]() {
3955 result = clang_reparseTranslationUnit_Impl(
3956 TU, llvm::makeArrayRef(unsaved_files, num_unsaved_files), options);
3957 };
Guy Benyei11169dd2012-12-18 14:30:41 +00003958
3959 if (getenv("LIBCLANG_NOTHREADS")) {
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003960 ReparseTranslationUnitImpl();
Alp Toker5c532982014-07-07 22:42:03 +00003961 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003962 }
3963
3964 llvm::CrashRecoveryContext CRC;
3965
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003966 if (!RunSafely(CRC, ReparseTranslationUnitImpl)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003967 fprintf(stderr, "libclang: crash detected during reparsing\n");
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00003968 cxtu::getASTUnit(TU)->setUnsafeToFree(true);
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003969 return CXError_Crashed;
Guy Benyei11169dd2012-12-18 14:30:41 +00003970 } else if (getenv("LIBCLANG_RESOURCE_USAGE"))
3971 PrintLibclangResourceUsage(TU);
3972
Alp Toker5c532982014-07-07 22:42:03 +00003973 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003974}
3975
3976
3977CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00003978 if (isNotUsableTU(CTUnit)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00003979 LOG_BAD_TU(CTUnit);
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00003980 return cxstring::createEmpty();
Dmitri Gribenko256454f2014-02-11 14:34:14 +00003981 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003982
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00003983 ASTUnit *CXXUnit = cxtu::getASTUnit(CTUnit);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00003984 return cxstring::createDup(CXXUnit->getOriginalSourceFileName());
Guy Benyei11169dd2012-12-18 14:30:41 +00003985}
3986
3987CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00003988 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00003989 LOG_BAD_TU(TU);
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00003990 return clang_getNullCursor();
Dmitri Gribenko256454f2014-02-11 14:34:14 +00003991 }
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00003992
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00003993 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00003994 return MakeCXCursor(CXXUnit->getASTContext().getTranslationUnitDecl(), TU);
3995}
3996
Guy Benyei11169dd2012-12-18 14:30:41 +00003997//===----------------------------------------------------------------------===//
3998// CXFile Operations.
3999//===----------------------------------------------------------------------===//
4000
Guy Benyei11169dd2012-12-18 14:30:41 +00004001CXString clang_getFileName(CXFile SFile) {
4002 if (!SFile)
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00004003 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00004004
4005 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004006 return cxstring::createRef(FEnt->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004007}
4008
4009time_t clang_getFileTime(CXFile SFile) {
4010 if (!SFile)
4011 return 0;
4012
4013 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
4014 return FEnt->getModificationTime();
4015}
4016
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004017CXFile clang_getFile(CXTranslationUnit TU, const char *file_name) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004018 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004019 LOG_BAD_TU(TU);
Craig Topper69186e72014-06-08 08:38:04 +00004020 return nullptr;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004021 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004022
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004023 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004024
4025 FileManager &FMgr = CXXUnit->getFileManager();
4026 return const_cast<FileEntry *>(FMgr.getFile(file_name));
4027}
4028
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004029unsigned clang_isFileMultipleIncludeGuarded(CXTranslationUnit TU,
4030 CXFile file) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004031 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004032 LOG_BAD_TU(TU);
4033 return 0;
4034 }
4035
4036 if (!file)
Guy Benyei11169dd2012-12-18 14:30:41 +00004037 return 0;
4038
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004039 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004040 FileEntry *FEnt = static_cast<FileEntry *>(file);
4041 return CXXUnit->getPreprocessor().getHeaderSearchInfo()
4042 .isFileMultipleIncludeGuarded(FEnt);
4043}
4044
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00004045int clang_getFileUniqueID(CXFile file, CXFileUniqueID *outID) {
4046 if (!file || !outID)
4047 return 1;
4048
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00004049 FileEntry *FEnt = static_cast<FileEntry *>(file);
Rafael Espindolaf8f91b82013-08-01 21:42:11 +00004050 const llvm::sys::fs::UniqueID &ID = FEnt->getUniqueID();
4051 outID->data[0] = ID.getDevice();
4052 outID->data[1] = ID.getFile();
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00004053 outID->data[2] = FEnt->getModificationTime();
4054 return 0;
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00004055}
4056
Argyrios Kyrtzidisac3997e2014-08-16 00:26:19 +00004057int clang_File_isEqual(CXFile file1, CXFile file2) {
4058 if (file1 == file2)
4059 return true;
4060
4061 if (!file1 || !file2)
4062 return false;
4063
4064 FileEntry *FEnt1 = static_cast<FileEntry *>(file1);
4065 FileEntry *FEnt2 = static_cast<FileEntry *>(file2);
4066 return FEnt1->getUniqueID() == FEnt2->getUniqueID();
4067}
4068
Guy Benyei11169dd2012-12-18 14:30:41 +00004069//===----------------------------------------------------------------------===//
4070// CXCursor Operations.
4071//===----------------------------------------------------------------------===//
4072
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004073static const Decl *getDeclFromExpr(const Stmt *E) {
4074 if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004075 return getDeclFromExpr(CE->getSubExpr());
4076
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004077 if (const DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004078 return RefExpr->getDecl();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004079 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004080 return ME->getMemberDecl();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004081 if (const ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004082 return RE->getDecl();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004083 if (const ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004084 if (PRE->isExplicitProperty())
4085 return PRE->getExplicitProperty();
4086 // It could be messaging both getter and setter as in:
4087 // ++myobj.myprop;
4088 // in which case prefer to associate the setter since it is less obvious
4089 // from inspecting the source that the setter is going to get called.
4090 if (PRE->isMessagingSetter())
4091 return PRE->getImplicitPropertySetter();
4092 return PRE->getImplicitPropertyGetter();
4093 }
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004094 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004095 return getDeclFromExpr(POE->getSyntacticForm());
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004096 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004097 if (Expr *Src = OVE->getSourceExpr())
4098 return getDeclFromExpr(Src);
4099
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004100 if (const CallExpr *CE = dyn_cast<CallExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004101 return getDeclFromExpr(CE->getCallee());
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004102 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004103 if (!CE->isElidable())
4104 return CE->getConstructor();
Richard Smith5179eb72016-06-28 19:03:57 +00004105 if (const CXXInheritedCtorInitExpr *CE =
4106 dyn_cast<CXXInheritedCtorInitExpr>(E))
4107 return CE->getConstructor();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004108 if (const ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004109 return OME->getMethodDecl();
4110
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004111 if (const ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004112 return PE->getProtocol();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004113 if (const SubstNonTypeTemplateParmPackExpr *NTTP
Guy Benyei11169dd2012-12-18 14:30:41 +00004114 = dyn_cast<SubstNonTypeTemplateParmPackExpr>(E))
4115 return NTTP->getParameterPack();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004116 if (const SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004117 if (isa<NonTypeTemplateParmDecl>(SizeOfPack->getPack()) ||
4118 isa<ParmVarDecl>(SizeOfPack->getPack()))
4119 return SizeOfPack->getPack();
Craig Topper69186e72014-06-08 08:38:04 +00004120
4121 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004122}
4123
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004124static SourceLocation getLocationFromExpr(const Expr *E) {
4125 if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004126 return getLocationFromExpr(CE->getSubExpr());
4127
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004128 if (const ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004129 return /*FIXME:*/Msg->getLeftLoc();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004130 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004131 return DRE->getLocation();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004132 if (const MemberExpr *Member = dyn_cast<MemberExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004133 return Member->getMemberLoc();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004134 if (const ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004135 return Ivar->getLocation();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004136 if (const SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004137 return SizeOfPack->getPackLoc();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004138 if (const ObjCPropertyRefExpr *PropRef = dyn_cast<ObjCPropertyRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004139 return PropRef->getLocation();
4140
4141 return E->getLocStart();
4142}
4143
NAKAMURA Takumia01f4c32016-12-19 16:50:43 +00004144extern "C" {
4145
Guy Benyei11169dd2012-12-18 14:30:41 +00004146unsigned clang_visitChildren(CXCursor parent,
4147 CXCursorVisitor visitor,
4148 CXClientData client_data) {
4149 CursorVisitor CursorVis(getCursorTU(parent), visitor, client_data,
4150 /*VisitPreprocessorLast=*/false);
4151 return CursorVis.VisitChildren(parent);
4152}
4153
4154#ifndef __has_feature
4155#define __has_feature(x) 0
4156#endif
4157#if __has_feature(blocks)
4158typedef enum CXChildVisitResult
4159 (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
4160
4161static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
4162 CXClientData client_data) {
4163 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
4164 return block(cursor, parent);
4165}
4166#else
4167// If we are compiled with a compiler that doesn't have native blocks support,
4168// define and call the block manually, so the
4169typedef struct _CXChildVisitResult
4170{
4171 void *isa;
4172 int flags;
4173 int reserved;
4174 enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor,
4175 CXCursor);
4176} *CXCursorVisitorBlock;
4177
4178static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
4179 CXClientData client_data) {
4180 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
4181 return block->invoke(block, cursor, parent);
4182}
4183#endif
4184
4185
4186unsigned clang_visitChildrenWithBlock(CXCursor parent,
4187 CXCursorVisitorBlock block) {
4188 return clang_visitChildren(parent, visitWithBlock, block);
4189}
4190
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004191static CXString getDeclSpelling(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004192 if (!D)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004193 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004194
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004195 const NamedDecl *ND = dyn_cast<NamedDecl>(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00004196 if (!ND) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004197 if (const ObjCPropertyImplDecl *PropImpl =
4198 dyn_cast<ObjCPropertyImplDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00004199 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004200 return cxstring::createDup(Property->getIdentifier()->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004201
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004202 if (const ImportDecl *ImportD = dyn_cast<ImportDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00004203 if (Module *Mod = ImportD->getImportedModule())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004204 return cxstring::createDup(Mod->getFullModuleName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004205
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004206 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004207 }
4208
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004209 if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004210 return cxstring::createDup(OMD->getSelector().getAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004211
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004212 if (const ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
Guy Benyei11169dd2012-12-18 14:30:41 +00004213 // No, this isn't the same as the code below. getIdentifier() is non-virtual
4214 // and returns different names. NamedDecl returns the class name and
4215 // ObjCCategoryImplDecl returns the category name.
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004216 return cxstring::createRef(CIMP->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004217
4218 if (isa<UsingDirectiveDecl>(D))
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004219 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004220
4221 SmallString<1024> S;
4222 llvm::raw_svector_ostream os(S);
4223 ND->printName(os);
4224
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004225 return cxstring::createDup(os.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00004226}
4227
4228CXString clang_getCursorSpelling(CXCursor C) {
4229 if (clang_isTranslationUnit(C.kind))
Dmitri Gribenko2c173b42013-01-11 19:28:44 +00004230 return clang_getTranslationUnitSpelling(getCursorTU(C));
Guy Benyei11169dd2012-12-18 14:30:41 +00004231
4232 if (clang_isReference(C.kind)) {
4233 switch (C.kind) {
4234 case CXCursor_ObjCSuperClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004235 const ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004236 return cxstring::createRef(Super->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004237 }
4238 case CXCursor_ObjCClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004239 const ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004240 return cxstring::createRef(Class->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004241 }
4242 case CXCursor_ObjCProtocolRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004243 const ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004244 assert(OID && "getCursorSpelling(): Missing protocol decl");
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004245 return cxstring::createRef(OID->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004246 }
4247 case CXCursor_CXXBaseSpecifier: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004248 const CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004249 return cxstring::createDup(B->getType().getAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004250 }
4251 case CXCursor_TypeRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004252 const TypeDecl *Type = getCursorTypeRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004253 assert(Type && "Missing type decl");
4254
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004255 return cxstring::createDup(getCursorContext(C).getTypeDeclType(Type).
Guy Benyei11169dd2012-12-18 14:30:41 +00004256 getAsString());
4257 }
4258 case CXCursor_TemplateRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004259 const TemplateDecl *Template = getCursorTemplateRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004260 assert(Template && "Missing template decl");
4261
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004262 return cxstring::createDup(Template->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004263 }
4264
4265 case CXCursor_NamespaceRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004266 const NamedDecl *NS = getCursorNamespaceRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004267 assert(NS && "Missing namespace decl");
4268
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004269 return cxstring::createDup(NS->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004270 }
4271
4272 case CXCursor_MemberRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004273 const FieldDecl *Field = getCursorMemberRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004274 assert(Field && "Missing member decl");
4275
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004276 return cxstring::createDup(Field->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004277 }
4278
4279 case CXCursor_LabelRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004280 const LabelStmt *Label = getCursorLabelRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004281 assert(Label && "Missing label");
4282
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004283 return cxstring::createRef(Label->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004284 }
4285
4286 case CXCursor_OverloadedDeclRef: {
4287 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004288 if (const Decl *D = Storage.dyn_cast<const Decl *>()) {
4289 if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004290 return cxstring::createDup(ND->getNameAsString());
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004291 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004292 }
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004293 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004294 return cxstring::createDup(E->getName().getAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004295 OverloadedTemplateStorage *Ovl
4296 = Storage.get<OverloadedTemplateStorage*>();
4297 if (Ovl->size() == 0)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004298 return cxstring::createEmpty();
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004299 return cxstring::createDup((*Ovl->begin())->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004300 }
4301
4302 case CXCursor_VariableRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004303 const VarDecl *Var = getCursorVariableRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004304 assert(Var && "Missing variable decl");
4305
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004306 return cxstring::createDup(Var->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004307 }
4308
4309 default:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004310 return cxstring::createRef("<not implemented>");
Guy Benyei11169dd2012-12-18 14:30:41 +00004311 }
4312 }
4313
4314 if (clang_isExpression(C.kind)) {
Argyrios Kyrtzidis3227d862014-03-03 19:40:52 +00004315 const Expr *E = getCursorExpr(C);
4316
4317 if (C.kind == CXCursor_ObjCStringLiteral ||
4318 C.kind == CXCursor_StringLiteral) {
4319 const StringLiteral *SLit;
4320 if (const ObjCStringLiteral *OSL = dyn_cast<ObjCStringLiteral>(E)) {
4321 SLit = OSL->getString();
4322 } else {
4323 SLit = cast<StringLiteral>(E);
4324 }
4325 SmallString<256> Buf;
4326 llvm::raw_svector_ostream OS(Buf);
4327 SLit->outputString(OS);
4328 return cxstring::createDup(OS.str());
4329 }
4330
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004331 const Decl *D = getDeclFromExpr(getCursorExpr(C));
Guy Benyei11169dd2012-12-18 14:30:41 +00004332 if (D)
4333 return getDeclSpelling(D);
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004334 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004335 }
4336
4337 if (clang_isStatement(C.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004338 const Stmt *S = getCursorStmt(C);
4339 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004340 return cxstring::createRef(Label->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004341
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004342 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004343 }
4344
4345 if (C.kind == CXCursor_MacroExpansion)
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004346 return cxstring::createRef(getCursorMacroExpansion(C).getName()
Guy Benyei11169dd2012-12-18 14:30:41 +00004347 ->getNameStart());
4348
4349 if (C.kind == CXCursor_MacroDefinition)
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004350 return cxstring::createRef(getCursorMacroDefinition(C)->getName()
Guy Benyei11169dd2012-12-18 14:30:41 +00004351 ->getNameStart());
4352
4353 if (C.kind == CXCursor_InclusionDirective)
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004354 return cxstring::createDup(getCursorInclusionDirective(C)->getFileName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004355
4356 if (clang_isDeclaration(C.kind))
4357 return getDeclSpelling(getCursorDecl(C));
4358
4359 if (C.kind == CXCursor_AnnotateAttr) {
Dmitri Gribenkoe4baea62013-01-26 18:08:08 +00004360 const AnnotateAttr *AA = cast<AnnotateAttr>(cxcursor::getCursorAttr(C));
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004361 return cxstring::createDup(AA->getAnnotation());
Guy Benyei11169dd2012-12-18 14:30:41 +00004362 }
4363
4364 if (C.kind == CXCursor_AsmLabelAttr) {
Dmitri Gribenkoe4baea62013-01-26 18:08:08 +00004365 const AsmLabelAttr *AA = cast<AsmLabelAttr>(cxcursor::getCursorAttr(C));
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004366 return cxstring::createDup(AA->getLabel());
Guy Benyei11169dd2012-12-18 14:30:41 +00004367 }
4368
Argyrios Kyrtzidis16834f12013-09-25 00:14:38 +00004369 if (C.kind == CXCursor_PackedAttr) {
4370 return cxstring::createRef("packed");
4371 }
4372
Saleem Abdulrasool79c69712015-09-05 18:53:43 +00004373 if (C.kind == CXCursor_VisibilityAttr) {
4374 const VisibilityAttr *AA = cast<VisibilityAttr>(cxcursor::getCursorAttr(C));
4375 switch (AA->getVisibility()) {
4376 case VisibilityAttr::VisibilityType::Default:
4377 return cxstring::createRef("default");
4378 case VisibilityAttr::VisibilityType::Hidden:
4379 return cxstring::createRef("hidden");
4380 case VisibilityAttr::VisibilityType::Protected:
4381 return cxstring::createRef("protected");
4382 }
4383 llvm_unreachable("unknown visibility type");
4384 }
4385
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004386 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004387}
4388
4389CXSourceRange clang_Cursor_getSpellingNameRange(CXCursor C,
4390 unsigned pieceIndex,
4391 unsigned options) {
4392 if (clang_Cursor_isNull(C))
4393 return clang_getNullRange();
4394
4395 ASTContext &Ctx = getCursorContext(C);
4396
4397 if (clang_isStatement(C.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004398 const Stmt *S = getCursorStmt(C);
4399 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004400 if (pieceIndex > 0)
4401 return clang_getNullRange();
4402 return cxloc::translateSourceRange(Ctx, Label->getIdentLoc());
4403 }
4404
4405 return clang_getNullRange();
4406 }
4407
4408 if (C.kind == CXCursor_ObjCMessageExpr) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004409 if (const ObjCMessageExpr *
Guy Benyei11169dd2012-12-18 14:30:41 +00004410 ME = dyn_cast_or_null<ObjCMessageExpr>(getCursorExpr(C))) {
4411 if (pieceIndex >= ME->getNumSelectorLocs())
4412 return clang_getNullRange();
4413 return cxloc::translateSourceRange(Ctx, ME->getSelectorLoc(pieceIndex));
4414 }
4415 }
4416
4417 if (C.kind == CXCursor_ObjCInstanceMethodDecl ||
4418 C.kind == CXCursor_ObjCClassMethodDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004419 if (const ObjCMethodDecl *
Guy Benyei11169dd2012-12-18 14:30:41 +00004420 MD = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(C))) {
4421 if (pieceIndex >= MD->getNumSelectorLocs())
4422 return clang_getNullRange();
4423 return cxloc::translateSourceRange(Ctx, MD->getSelectorLoc(pieceIndex));
4424 }
4425 }
4426
4427 if (C.kind == CXCursor_ObjCCategoryDecl ||
4428 C.kind == CXCursor_ObjCCategoryImplDecl) {
4429 if (pieceIndex > 0)
4430 return clang_getNullRange();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004431 if (const ObjCCategoryDecl *
Guy Benyei11169dd2012-12-18 14:30:41 +00004432 CD = dyn_cast_or_null<ObjCCategoryDecl>(getCursorDecl(C)))
4433 return cxloc::translateSourceRange(Ctx, CD->getCategoryNameLoc());
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004434 if (const ObjCCategoryImplDecl *
Guy Benyei11169dd2012-12-18 14:30:41 +00004435 CID = dyn_cast_or_null<ObjCCategoryImplDecl>(getCursorDecl(C)))
4436 return cxloc::translateSourceRange(Ctx, CID->getCategoryNameLoc());
4437 }
4438
4439 if (C.kind == CXCursor_ModuleImportDecl) {
4440 if (pieceIndex > 0)
4441 return clang_getNullRange();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004442 if (const ImportDecl *ImportD =
4443 dyn_cast_or_null<ImportDecl>(getCursorDecl(C))) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004444 ArrayRef<SourceLocation> Locs = ImportD->getIdentifierLocs();
4445 if (!Locs.empty())
4446 return cxloc::translateSourceRange(Ctx,
4447 SourceRange(Locs.front(), Locs.back()));
4448 }
4449 return clang_getNullRange();
4450 }
4451
Argyrios Kyrtzidisa2a1e532014-08-26 20:23:26 +00004452 if (C.kind == CXCursor_CXXMethod || C.kind == CXCursor_Destructor ||
Kevin Funk4be5d672016-12-20 09:56:56 +00004453 C.kind == CXCursor_ConversionFunction ||
4454 C.kind == CXCursor_FunctionDecl) {
Argyrios Kyrtzidisa2a1e532014-08-26 20:23:26 +00004455 if (pieceIndex > 0)
4456 return clang_getNullRange();
4457 if (const FunctionDecl *FD =
4458 dyn_cast_or_null<FunctionDecl>(getCursorDecl(C))) {
4459 DeclarationNameInfo FunctionName = FD->getNameInfo();
4460 return cxloc::translateSourceRange(Ctx, FunctionName.getSourceRange());
4461 }
4462 return clang_getNullRange();
4463 }
4464
Guy Benyei11169dd2012-12-18 14:30:41 +00004465 // FIXME: A CXCursor_InclusionDirective should give the location of the
4466 // filename, but we don't keep track of this.
4467
4468 // FIXME: A CXCursor_AnnotateAttr should give the location of the annotation
4469 // but we don't keep track of this.
4470
4471 // FIXME: A CXCursor_AsmLabelAttr should give the location of the label
4472 // but we don't keep track of this.
4473
4474 // Default handling, give the location of the cursor.
4475
4476 if (pieceIndex > 0)
4477 return clang_getNullRange();
4478
4479 CXSourceLocation CXLoc = clang_getCursorLocation(C);
4480 SourceLocation Loc = cxloc::translateSourceLocation(CXLoc);
4481 return cxloc::translateSourceRange(Ctx, Loc);
4482}
4483
Eli Bendersky44a206f2014-07-31 18:04:56 +00004484CXString clang_Cursor_getMangling(CXCursor C) {
4485 if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
4486 return cxstring::createEmpty();
4487
Eli Bendersky44a206f2014-07-31 18:04:56 +00004488 // Mangling only works for functions and variables.
Eli Bendersky79759592014-08-01 15:01:10 +00004489 const Decl *D = getCursorDecl(C);
Eli Bendersky44a206f2014-07-31 18:04:56 +00004490 if (!D || !(isa<FunctionDecl>(D) || isa<VarDecl>(D)))
4491 return cxstring::createEmpty();
4492
Argyrios Kyrtzidisca741ce2016-02-14 22:30:14 +00004493 ASTContext &Ctx = D->getASTContext();
4494 index::CodegenNameGenerator CGNameGen(Ctx);
4495 return cxstring::createDup(CGNameGen.getName(D));
Eli Bendersky44a206f2014-07-31 18:04:56 +00004496}
4497
Saleem Abdulrasool60034432015-11-12 03:57:22 +00004498CXStringSet *clang_Cursor_getCXXManglings(CXCursor C) {
4499 if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
4500 return nullptr;
4501
4502 const Decl *D = getCursorDecl(C);
4503 if (!(isa<CXXRecordDecl>(D) || isa<CXXMethodDecl>(D)))
4504 return nullptr;
4505
Argyrios Kyrtzidisca741ce2016-02-14 22:30:14 +00004506 ASTContext &Ctx = D->getASTContext();
4507 index::CodegenNameGenerator CGNameGen(Ctx);
4508 std::vector<std::string> Manglings = CGNameGen.getAllManglings(D);
Saleem Abdulrasool60034432015-11-12 03:57:22 +00004509 return cxstring::createSet(Manglings);
4510}
4511
Guy Benyei11169dd2012-12-18 14:30:41 +00004512CXString clang_getCursorDisplayName(CXCursor C) {
4513 if (!clang_isDeclaration(C.kind))
4514 return clang_getCursorSpelling(C);
4515
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004516 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00004517 if (!D)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004518 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004519
4520 PrintingPolicy Policy = getCursorContext(C).getPrintingPolicy();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004521 if (const FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00004522 D = FunTmpl->getTemplatedDecl();
4523
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004524 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004525 SmallString<64> Str;
4526 llvm::raw_svector_ostream OS(Str);
4527 OS << *Function;
4528 if (Function->getPrimaryTemplate())
4529 OS << "<>";
4530 OS << "(";
4531 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
4532 if (I)
4533 OS << ", ";
4534 OS << Function->getParamDecl(I)->getType().getAsString(Policy);
4535 }
4536
4537 if (Function->isVariadic()) {
4538 if (Function->getNumParams())
4539 OS << ", ";
4540 OS << "...";
4541 }
4542 OS << ")";
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004543 return cxstring::createDup(OS.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00004544 }
4545
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004546 if (const ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004547 SmallString<64> Str;
4548 llvm::raw_svector_ostream OS(Str);
4549 OS << *ClassTemplate;
4550 OS << "<";
4551 TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
4552 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
4553 if (I)
4554 OS << ", ";
4555
4556 NamedDecl *Param = Params->getParam(I);
4557 if (Param->getIdentifier()) {
4558 OS << Param->getIdentifier()->getName();
4559 continue;
4560 }
4561
4562 // There is no parameter name, which makes this tricky. Try to come up
4563 // with something useful that isn't too long.
4564 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
4565 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
4566 else if (NonTypeTemplateParmDecl *NTTP
4567 = dyn_cast<NonTypeTemplateParmDecl>(Param))
4568 OS << NTTP->getType().getAsString(Policy);
4569 else
4570 OS << "template<...> class";
4571 }
4572
4573 OS << ">";
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004574 return cxstring::createDup(OS.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00004575 }
4576
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004577 if (const ClassTemplateSpecializationDecl *ClassSpec
Guy Benyei11169dd2012-12-18 14:30:41 +00004578 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
4579 // If the type was explicitly written, use that.
4580 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004581 return cxstring::createDup(TSInfo->getType().getAsString(Policy));
Guy Benyei11169dd2012-12-18 14:30:41 +00004582
Benjamin Kramer9170e912013-02-22 15:46:01 +00004583 SmallString<128> Str;
Guy Benyei11169dd2012-12-18 14:30:41 +00004584 llvm::raw_svector_ostream OS(Str);
4585 OS << *ClassSpec;
David Majnemer6fbeee32016-07-07 04:43:07 +00004586 TemplateSpecializationType::PrintTemplateArgumentList(
4587 OS, ClassSpec->getTemplateArgs().asArray(), Policy);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004588 return cxstring::createDup(OS.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00004589 }
4590
4591 return clang_getCursorSpelling(C);
4592}
4593
4594CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
4595 switch (Kind) {
4596 case CXCursor_FunctionDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004597 return cxstring::createRef("FunctionDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004598 case CXCursor_TypedefDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004599 return cxstring::createRef("TypedefDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004600 case CXCursor_EnumDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004601 return cxstring::createRef("EnumDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004602 case CXCursor_EnumConstantDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004603 return cxstring::createRef("EnumConstantDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004604 case CXCursor_StructDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004605 return cxstring::createRef("StructDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004606 case CXCursor_UnionDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004607 return cxstring::createRef("UnionDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004608 case CXCursor_ClassDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004609 return cxstring::createRef("ClassDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004610 case CXCursor_FieldDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004611 return cxstring::createRef("FieldDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004612 case CXCursor_VarDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004613 return cxstring::createRef("VarDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004614 case CXCursor_ParmDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004615 return cxstring::createRef("ParmDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004616 case CXCursor_ObjCInterfaceDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004617 return cxstring::createRef("ObjCInterfaceDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004618 case CXCursor_ObjCCategoryDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004619 return cxstring::createRef("ObjCCategoryDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004620 case CXCursor_ObjCProtocolDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004621 return cxstring::createRef("ObjCProtocolDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004622 case CXCursor_ObjCPropertyDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004623 return cxstring::createRef("ObjCPropertyDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004624 case CXCursor_ObjCIvarDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004625 return cxstring::createRef("ObjCIvarDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004626 case CXCursor_ObjCInstanceMethodDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004627 return cxstring::createRef("ObjCInstanceMethodDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004628 case CXCursor_ObjCClassMethodDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004629 return cxstring::createRef("ObjCClassMethodDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004630 case CXCursor_ObjCImplementationDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004631 return cxstring::createRef("ObjCImplementationDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004632 case CXCursor_ObjCCategoryImplDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004633 return cxstring::createRef("ObjCCategoryImplDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004634 case CXCursor_CXXMethod:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004635 return cxstring::createRef("CXXMethod");
Guy Benyei11169dd2012-12-18 14:30:41 +00004636 case CXCursor_UnexposedDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004637 return cxstring::createRef("UnexposedDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004638 case CXCursor_ObjCSuperClassRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004639 return cxstring::createRef("ObjCSuperClassRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00004640 case CXCursor_ObjCProtocolRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004641 return cxstring::createRef("ObjCProtocolRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00004642 case CXCursor_ObjCClassRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004643 return cxstring::createRef("ObjCClassRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00004644 case CXCursor_TypeRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004645 return cxstring::createRef("TypeRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00004646 case CXCursor_TemplateRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004647 return cxstring::createRef("TemplateRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00004648 case CXCursor_NamespaceRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004649 return cxstring::createRef("NamespaceRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00004650 case CXCursor_MemberRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004651 return cxstring::createRef("MemberRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00004652 case CXCursor_LabelRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004653 return cxstring::createRef("LabelRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00004654 case CXCursor_OverloadedDeclRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004655 return cxstring::createRef("OverloadedDeclRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00004656 case CXCursor_VariableRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004657 return cxstring::createRef("VariableRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00004658 case CXCursor_IntegerLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004659 return cxstring::createRef("IntegerLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00004660 case CXCursor_FloatingLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004661 return cxstring::createRef("FloatingLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00004662 case CXCursor_ImaginaryLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004663 return cxstring::createRef("ImaginaryLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00004664 case CXCursor_StringLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004665 return cxstring::createRef("StringLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00004666 case CXCursor_CharacterLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004667 return cxstring::createRef("CharacterLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00004668 case CXCursor_ParenExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004669 return cxstring::createRef("ParenExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004670 case CXCursor_UnaryOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004671 return cxstring::createRef("UnaryOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00004672 case CXCursor_ArraySubscriptExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004673 return cxstring::createRef("ArraySubscriptExpr");
Alexey Bataev1a3320e2015-08-25 14:24:04 +00004674 case CXCursor_OMPArraySectionExpr:
4675 return cxstring::createRef("OMPArraySectionExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004676 case CXCursor_BinaryOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004677 return cxstring::createRef("BinaryOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00004678 case CXCursor_CompoundAssignOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004679 return cxstring::createRef("CompoundAssignOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00004680 case CXCursor_ConditionalOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004681 return cxstring::createRef("ConditionalOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00004682 case CXCursor_CStyleCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004683 return cxstring::createRef("CStyleCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004684 case CXCursor_CompoundLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004685 return cxstring::createRef("CompoundLiteralExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004686 case CXCursor_InitListExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004687 return cxstring::createRef("InitListExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004688 case CXCursor_AddrLabelExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004689 return cxstring::createRef("AddrLabelExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004690 case CXCursor_StmtExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004691 return cxstring::createRef("StmtExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004692 case CXCursor_GenericSelectionExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004693 return cxstring::createRef("GenericSelectionExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004694 case CXCursor_GNUNullExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004695 return cxstring::createRef("GNUNullExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004696 case CXCursor_CXXStaticCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004697 return cxstring::createRef("CXXStaticCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004698 case CXCursor_CXXDynamicCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004699 return cxstring::createRef("CXXDynamicCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004700 case CXCursor_CXXReinterpretCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004701 return cxstring::createRef("CXXReinterpretCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004702 case CXCursor_CXXConstCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004703 return cxstring::createRef("CXXConstCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004704 case CXCursor_CXXFunctionalCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004705 return cxstring::createRef("CXXFunctionalCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004706 case CXCursor_CXXTypeidExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004707 return cxstring::createRef("CXXTypeidExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004708 case CXCursor_CXXBoolLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004709 return cxstring::createRef("CXXBoolLiteralExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004710 case CXCursor_CXXNullPtrLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004711 return cxstring::createRef("CXXNullPtrLiteralExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004712 case CXCursor_CXXThisExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004713 return cxstring::createRef("CXXThisExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004714 case CXCursor_CXXThrowExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004715 return cxstring::createRef("CXXThrowExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004716 case CXCursor_CXXNewExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004717 return cxstring::createRef("CXXNewExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004718 case CXCursor_CXXDeleteExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004719 return cxstring::createRef("CXXDeleteExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004720 case CXCursor_UnaryExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004721 return cxstring::createRef("UnaryExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004722 case CXCursor_ObjCStringLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004723 return cxstring::createRef("ObjCStringLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00004724 case CXCursor_ObjCBoolLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004725 return cxstring::createRef("ObjCBoolLiteralExpr");
Erik Pilkington29099de2016-07-16 00:35:23 +00004726 case CXCursor_ObjCAvailabilityCheckExpr:
4727 return cxstring::createRef("ObjCAvailabilityCheckExpr");
Argyrios Kyrtzidisc2233be2013-04-23 17:57:17 +00004728 case CXCursor_ObjCSelfExpr:
4729 return cxstring::createRef("ObjCSelfExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004730 case CXCursor_ObjCEncodeExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004731 return cxstring::createRef("ObjCEncodeExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004732 case CXCursor_ObjCSelectorExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004733 return cxstring::createRef("ObjCSelectorExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004734 case CXCursor_ObjCProtocolExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004735 return cxstring::createRef("ObjCProtocolExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004736 case CXCursor_ObjCBridgedCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004737 return cxstring::createRef("ObjCBridgedCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004738 case CXCursor_BlockExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004739 return cxstring::createRef("BlockExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004740 case CXCursor_PackExpansionExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004741 return cxstring::createRef("PackExpansionExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004742 case CXCursor_SizeOfPackExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004743 return cxstring::createRef("SizeOfPackExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004744 case CXCursor_LambdaExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004745 return cxstring::createRef("LambdaExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004746 case CXCursor_UnexposedExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004747 return cxstring::createRef("UnexposedExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004748 case CXCursor_DeclRefExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004749 return cxstring::createRef("DeclRefExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004750 case CXCursor_MemberRefExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004751 return cxstring::createRef("MemberRefExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004752 case CXCursor_CallExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004753 return cxstring::createRef("CallExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004754 case CXCursor_ObjCMessageExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004755 return cxstring::createRef("ObjCMessageExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004756 case CXCursor_UnexposedStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004757 return cxstring::createRef("UnexposedStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004758 case CXCursor_DeclStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004759 return cxstring::createRef("DeclStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004760 case CXCursor_LabelStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004761 return cxstring::createRef("LabelStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004762 case CXCursor_CompoundStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004763 return cxstring::createRef("CompoundStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004764 case CXCursor_CaseStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004765 return cxstring::createRef("CaseStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004766 case CXCursor_DefaultStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004767 return cxstring::createRef("DefaultStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004768 case CXCursor_IfStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004769 return cxstring::createRef("IfStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004770 case CXCursor_SwitchStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004771 return cxstring::createRef("SwitchStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004772 case CXCursor_WhileStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004773 return cxstring::createRef("WhileStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004774 case CXCursor_DoStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004775 return cxstring::createRef("DoStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004776 case CXCursor_ForStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004777 return cxstring::createRef("ForStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004778 case CXCursor_GotoStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004779 return cxstring::createRef("GotoStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004780 case CXCursor_IndirectGotoStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004781 return cxstring::createRef("IndirectGotoStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004782 case CXCursor_ContinueStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004783 return cxstring::createRef("ContinueStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004784 case CXCursor_BreakStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004785 return cxstring::createRef("BreakStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004786 case CXCursor_ReturnStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004787 return cxstring::createRef("ReturnStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004788 case CXCursor_GCCAsmStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004789 return cxstring::createRef("GCCAsmStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004790 case CXCursor_MSAsmStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004791 return cxstring::createRef("MSAsmStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004792 case CXCursor_ObjCAtTryStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004793 return cxstring::createRef("ObjCAtTryStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004794 case CXCursor_ObjCAtCatchStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004795 return cxstring::createRef("ObjCAtCatchStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004796 case CXCursor_ObjCAtFinallyStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004797 return cxstring::createRef("ObjCAtFinallyStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004798 case CXCursor_ObjCAtThrowStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004799 return cxstring::createRef("ObjCAtThrowStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004800 case CXCursor_ObjCAtSynchronizedStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004801 return cxstring::createRef("ObjCAtSynchronizedStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004802 case CXCursor_ObjCAutoreleasePoolStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004803 return cxstring::createRef("ObjCAutoreleasePoolStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004804 case CXCursor_ObjCForCollectionStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004805 return cxstring::createRef("ObjCForCollectionStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004806 case CXCursor_CXXCatchStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004807 return cxstring::createRef("CXXCatchStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004808 case CXCursor_CXXTryStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004809 return cxstring::createRef("CXXTryStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004810 case CXCursor_CXXForRangeStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004811 return cxstring::createRef("CXXForRangeStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004812 case CXCursor_SEHTryStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004813 return cxstring::createRef("SEHTryStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004814 case CXCursor_SEHExceptStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004815 return cxstring::createRef("SEHExceptStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004816 case CXCursor_SEHFinallyStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004817 return cxstring::createRef("SEHFinallyStmt");
Nico Weber9b982072014-07-07 00:12:30 +00004818 case CXCursor_SEHLeaveStmt:
4819 return cxstring::createRef("SEHLeaveStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004820 case CXCursor_NullStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004821 return cxstring::createRef("NullStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004822 case CXCursor_InvalidFile:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004823 return cxstring::createRef("InvalidFile");
Guy Benyei11169dd2012-12-18 14:30:41 +00004824 case CXCursor_InvalidCode:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004825 return cxstring::createRef("InvalidCode");
Guy Benyei11169dd2012-12-18 14:30:41 +00004826 case CXCursor_NoDeclFound:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004827 return cxstring::createRef("NoDeclFound");
Guy Benyei11169dd2012-12-18 14:30:41 +00004828 case CXCursor_NotImplemented:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004829 return cxstring::createRef("NotImplemented");
Guy Benyei11169dd2012-12-18 14:30:41 +00004830 case CXCursor_TranslationUnit:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004831 return cxstring::createRef("TranslationUnit");
Guy Benyei11169dd2012-12-18 14:30:41 +00004832 case CXCursor_UnexposedAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004833 return cxstring::createRef("UnexposedAttr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004834 case CXCursor_IBActionAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004835 return cxstring::createRef("attribute(ibaction)");
Guy Benyei11169dd2012-12-18 14:30:41 +00004836 case CXCursor_IBOutletAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004837 return cxstring::createRef("attribute(iboutlet)");
Guy Benyei11169dd2012-12-18 14:30:41 +00004838 case CXCursor_IBOutletCollectionAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004839 return cxstring::createRef("attribute(iboutletcollection)");
Guy Benyei11169dd2012-12-18 14:30:41 +00004840 case CXCursor_CXXFinalAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004841 return cxstring::createRef("attribute(final)");
Guy Benyei11169dd2012-12-18 14:30:41 +00004842 case CXCursor_CXXOverrideAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004843 return cxstring::createRef("attribute(override)");
Guy Benyei11169dd2012-12-18 14:30:41 +00004844 case CXCursor_AnnotateAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004845 return cxstring::createRef("attribute(annotate)");
Guy Benyei11169dd2012-12-18 14:30:41 +00004846 case CXCursor_AsmLabelAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004847 return cxstring::createRef("asm label");
Argyrios Kyrtzidis16834f12013-09-25 00:14:38 +00004848 case CXCursor_PackedAttr:
4849 return cxstring::createRef("attribute(packed)");
Joey Gouly81228382014-05-01 15:41:58 +00004850 case CXCursor_PureAttr:
4851 return cxstring::createRef("attribute(pure)");
4852 case CXCursor_ConstAttr:
4853 return cxstring::createRef("attribute(const)");
4854 case CXCursor_NoDuplicateAttr:
4855 return cxstring::createRef("attribute(noduplicate)");
Eli Bendersky2581e662014-05-28 19:29:58 +00004856 case CXCursor_CUDAConstantAttr:
4857 return cxstring::createRef("attribute(constant)");
4858 case CXCursor_CUDADeviceAttr:
4859 return cxstring::createRef("attribute(device)");
4860 case CXCursor_CUDAGlobalAttr:
4861 return cxstring::createRef("attribute(global)");
4862 case CXCursor_CUDAHostAttr:
4863 return cxstring::createRef("attribute(host)");
Eli Bendersky9b071472014-08-08 14:59:00 +00004864 case CXCursor_CUDASharedAttr:
4865 return cxstring::createRef("attribute(shared)");
Saleem Abdulrasool79c69712015-09-05 18:53:43 +00004866 case CXCursor_VisibilityAttr:
4867 return cxstring::createRef("attribute(visibility)");
Saleem Abdulrasool8aa0b802015-12-10 18:45:18 +00004868 case CXCursor_DLLExport:
4869 return cxstring::createRef("attribute(dllexport)");
4870 case CXCursor_DLLImport:
4871 return cxstring::createRef("attribute(dllimport)");
Guy Benyei11169dd2012-12-18 14:30:41 +00004872 case CXCursor_PreprocessingDirective:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004873 return cxstring::createRef("preprocessing directive");
Guy Benyei11169dd2012-12-18 14:30:41 +00004874 case CXCursor_MacroDefinition:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004875 return cxstring::createRef("macro definition");
Guy Benyei11169dd2012-12-18 14:30:41 +00004876 case CXCursor_MacroExpansion:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004877 return cxstring::createRef("macro expansion");
Guy Benyei11169dd2012-12-18 14:30:41 +00004878 case CXCursor_InclusionDirective:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004879 return cxstring::createRef("inclusion directive");
Guy Benyei11169dd2012-12-18 14:30:41 +00004880 case CXCursor_Namespace:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004881 return cxstring::createRef("Namespace");
Guy Benyei11169dd2012-12-18 14:30:41 +00004882 case CXCursor_LinkageSpec:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004883 return cxstring::createRef("LinkageSpec");
Guy Benyei11169dd2012-12-18 14:30:41 +00004884 case CXCursor_CXXBaseSpecifier:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004885 return cxstring::createRef("C++ base class specifier");
Guy Benyei11169dd2012-12-18 14:30:41 +00004886 case CXCursor_Constructor:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004887 return cxstring::createRef("CXXConstructor");
Guy Benyei11169dd2012-12-18 14:30:41 +00004888 case CXCursor_Destructor:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004889 return cxstring::createRef("CXXDestructor");
Guy Benyei11169dd2012-12-18 14:30:41 +00004890 case CXCursor_ConversionFunction:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004891 return cxstring::createRef("CXXConversion");
Guy Benyei11169dd2012-12-18 14:30:41 +00004892 case CXCursor_TemplateTypeParameter:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004893 return cxstring::createRef("TemplateTypeParameter");
Guy Benyei11169dd2012-12-18 14:30:41 +00004894 case CXCursor_NonTypeTemplateParameter:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004895 return cxstring::createRef("NonTypeTemplateParameter");
Guy Benyei11169dd2012-12-18 14:30:41 +00004896 case CXCursor_TemplateTemplateParameter:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004897 return cxstring::createRef("TemplateTemplateParameter");
Guy Benyei11169dd2012-12-18 14:30:41 +00004898 case CXCursor_FunctionTemplate:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004899 return cxstring::createRef("FunctionTemplate");
Guy Benyei11169dd2012-12-18 14:30:41 +00004900 case CXCursor_ClassTemplate:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004901 return cxstring::createRef("ClassTemplate");
Guy Benyei11169dd2012-12-18 14:30:41 +00004902 case CXCursor_ClassTemplatePartialSpecialization:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004903 return cxstring::createRef("ClassTemplatePartialSpecialization");
Guy Benyei11169dd2012-12-18 14:30:41 +00004904 case CXCursor_NamespaceAlias:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004905 return cxstring::createRef("NamespaceAlias");
Guy Benyei11169dd2012-12-18 14:30:41 +00004906 case CXCursor_UsingDirective:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004907 return cxstring::createRef("UsingDirective");
Guy Benyei11169dd2012-12-18 14:30:41 +00004908 case CXCursor_UsingDeclaration:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004909 return cxstring::createRef("UsingDeclaration");
Guy Benyei11169dd2012-12-18 14:30:41 +00004910 case CXCursor_TypeAliasDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004911 return cxstring::createRef("TypeAliasDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004912 case CXCursor_ObjCSynthesizeDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004913 return cxstring::createRef("ObjCSynthesizeDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004914 case CXCursor_ObjCDynamicDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004915 return cxstring::createRef("ObjCDynamicDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004916 case CXCursor_CXXAccessSpecifier:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004917 return cxstring::createRef("CXXAccessSpecifier");
Guy Benyei11169dd2012-12-18 14:30:41 +00004918 case CXCursor_ModuleImportDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004919 return cxstring::createRef("ModuleImport");
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004920 case CXCursor_OMPParallelDirective:
Alexey Bataev1b59ab52014-02-27 08:29:12 +00004921 return cxstring::createRef("OMPParallelDirective");
4922 case CXCursor_OMPSimdDirective:
4923 return cxstring::createRef("OMPSimdDirective");
Alexey Bataevf29276e2014-06-18 04:14:57 +00004924 case CXCursor_OMPForDirective:
4925 return cxstring::createRef("OMPForDirective");
Alexander Musmanf82886e2014-09-18 05:12:34 +00004926 case CXCursor_OMPForSimdDirective:
4927 return cxstring::createRef("OMPForSimdDirective");
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004928 case CXCursor_OMPSectionsDirective:
4929 return cxstring::createRef("OMPSectionsDirective");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004930 case CXCursor_OMPSectionDirective:
4931 return cxstring::createRef("OMPSectionDirective");
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00004932 case CXCursor_OMPSingleDirective:
4933 return cxstring::createRef("OMPSingleDirective");
Alexander Musman80c22892014-07-17 08:54:58 +00004934 case CXCursor_OMPMasterDirective:
4935 return cxstring::createRef("OMPMasterDirective");
Alexander Musmand9ed09f2014-07-21 09:42:05 +00004936 case CXCursor_OMPCriticalDirective:
4937 return cxstring::createRef("OMPCriticalDirective");
Alexey Bataev4acb8592014-07-07 13:01:15 +00004938 case CXCursor_OMPParallelForDirective:
4939 return cxstring::createRef("OMPParallelForDirective");
Alexander Musmane4e893b2014-09-23 09:33:00 +00004940 case CXCursor_OMPParallelForSimdDirective:
4941 return cxstring::createRef("OMPParallelForSimdDirective");
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004942 case CXCursor_OMPParallelSectionsDirective:
4943 return cxstring::createRef("OMPParallelSectionsDirective");
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004944 case CXCursor_OMPTaskDirective:
4945 return cxstring::createRef("OMPTaskDirective");
Alexey Bataev68446b72014-07-18 07:47:19 +00004946 case CXCursor_OMPTaskyieldDirective:
4947 return cxstring::createRef("OMPTaskyieldDirective");
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00004948 case CXCursor_OMPBarrierDirective:
4949 return cxstring::createRef("OMPBarrierDirective");
Alexey Bataev2df347a2014-07-18 10:17:07 +00004950 case CXCursor_OMPTaskwaitDirective:
4951 return cxstring::createRef("OMPTaskwaitDirective");
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00004952 case CXCursor_OMPTaskgroupDirective:
4953 return cxstring::createRef("OMPTaskgroupDirective");
Alexey Bataev6125da92014-07-21 11:26:11 +00004954 case CXCursor_OMPFlushDirective:
4955 return cxstring::createRef("OMPFlushDirective");
Alexey Bataev9fb6e642014-07-22 06:45:04 +00004956 case CXCursor_OMPOrderedDirective:
4957 return cxstring::createRef("OMPOrderedDirective");
Alexey Bataev0162e452014-07-22 10:10:35 +00004958 case CXCursor_OMPAtomicDirective:
4959 return cxstring::createRef("OMPAtomicDirective");
Alexey Bataev0bd520b2014-09-19 08:19:49 +00004960 case CXCursor_OMPTargetDirective:
4961 return cxstring::createRef("OMPTargetDirective");
Michael Wong65f367f2015-07-21 13:44:28 +00004962 case CXCursor_OMPTargetDataDirective:
4963 return cxstring::createRef("OMPTargetDataDirective");
Samuel Antaodf67fc42016-01-19 19:15:56 +00004964 case CXCursor_OMPTargetEnterDataDirective:
4965 return cxstring::createRef("OMPTargetEnterDataDirective");
Samuel Antao72590762016-01-19 20:04:50 +00004966 case CXCursor_OMPTargetExitDataDirective:
4967 return cxstring::createRef("OMPTargetExitDataDirective");
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00004968 case CXCursor_OMPTargetParallelDirective:
4969 return cxstring::createRef("OMPTargetParallelDirective");
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00004970 case CXCursor_OMPTargetParallelForDirective:
4971 return cxstring::createRef("OMPTargetParallelForDirective");
Samuel Antao686c70c2016-05-26 17:30:50 +00004972 case CXCursor_OMPTargetUpdateDirective:
4973 return cxstring::createRef("OMPTargetUpdateDirective");
Alexey Bataev13314bf2014-10-09 04:18:56 +00004974 case CXCursor_OMPTeamsDirective:
4975 return cxstring::createRef("OMPTeamsDirective");
Alexey Bataev6d4ed052015-07-01 06:57:41 +00004976 case CXCursor_OMPCancellationPointDirective:
4977 return cxstring::createRef("OMPCancellationPointDirective");
Alexey Bataev80909872015-07-02 11:25:17 +00004978 case CXCursor_OMPCancelDirective:
4979 return cxstring::createRef("OMPCancelDirective");
Alexey Bataev49f6e782015-12-01 04:18:41 +00004980 case CXCursor_OMPTaskLoopDirective:
4981 return cxstring::createRef("OMPTaskLoopDirective");
Alexey Bataev0a6ed842015-12-03 09:40:15 +00004982 case CXCursor_OMPTaskLoopSimdDirective:
4983 return cxstring::createRef("OMPTaskLoopSimdDirective");
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004984 case CXCursor_OMPDistributeDirective:
4985 return cxstring::createRef("OMPDistributeDirective");
Carlo Bertolli9925f152016-06-27 14:55:37 +00004986 case CXCursor_OMPDistributeParallelForDirective:
4987 return cxstring::createRef("OMPDistributeParallelForDirective");
Kelvin Li4a39add2016-07-05 05:00:15 +00004988 case CXCursor_OMPDistributeParallelForSimdDirective:
4989 return cxstring::createRef("OMPDistributeParallelForSimdDirective");
Kelvin Li787f3fc2016-07-06 04:45:38 +00004990 case CXCursor_OMPDistributeSimdDirective:
4991 return cxstring::createRef("OMPDistributeSimdDirective");
Kelvin Lia579b912016-07-14 02:54:56 +00004992 case CXCursor_OMPTargetParallelForSimdDirective:
4993 return cxstring::createRef("OMPTargetParallelForSimdDirective");
Kelvin Li986330c2016-07-20 22:57:10 +00004994 case CXCursor_OMPTargetSimdDirective:
4995 return cxstring::createRef("OMPTargetSimdDirective");
Kelvin Li02532872016-08-05 14:37:37 +00004996 case CXCursor_OMPTeamsDistributeDirective:
4997 return cxstring::createRef("OMPTeamsDistributeDirective");
Kelvin Li4e325f72016-10-25 12:50:55 +00004998 case CXCursor_OMPTeamsDistributeSimdDirective:
4999 return cxstring::createRef("OMPTeamsDistributeSimdDirective");
Kelvin Li579e41c2016-11-30 23:51:03 +00005000 case CXCursor_OMPTeamsDistributeParallelForSimdDirective:
5001 return cxstring::createRef("OMPTeamsDistributeParallelForSimdDirective");
Kelvin Li7ade93f2016-12-09 03:24:30 +00005002 case CXCursor_OMPTeamsDistributeParallelForDirective:
5003 return cxstring::createRef("OMPTeamsDistributeParallelForDirective");
Kelvin Libf594a52016-12-17 05:48:59 +00005004 case CXCursor_OMPTargetTeamsDirective:
5005 return cxstring::createRef("OMPTargetTeamsDirective");
Kelvin Li83c451e2016-12-25 04:52:54 +00005006 case CXCursor_OMPTargetTeamsDistributeDirective:
5007 return cxstring::createRef("OMPTargetTeamsDistributeDirective");
Kelvin Li80e8f562016-12-29 22:16:30 +00005008 case CXCursor_OMPTargetTeamsDistributeParallelForDirective:
5009 return cxstring::createRef("OMPTargetTeamsDistributeParallelForDirective");
Kelvin Li1851df52017-01-03 05:23:48 +00005010 case CXCursor_OMPTargetTeamsDistributeParallelForSimdDirective:
5011 return cxstring::createRef(
5012 "OMPTargetTeamsDistributeParallelForSimdDirective");
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005013 case CXCursor_OverloadCandidate:
5014 return cxstring::createRef("OverloadCandidate");
Sergey Kalinichev8f3b1872015-11-15 13:48:32 +00005015 case CXCursor_TypeAliasTemplateDecl:
5016 return cxstring::createRef("TypeAliasTemplateDecl");
Olivier Goffart81978012016-06-09 16:15:55 +00005017 case CXCursor_StaticAssert:
5018 return cxstring::createRef("StaticAssert");
Olivier Goffartd211c642016-11-04 06:29:27 +00005019 case CXCursor_FriendDecl:
5020 return cxstring::createRef("FriendDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005021 }
5022
5023 llvm_unreachable("Unhandled CXCursorKind");
5024}
5025
5026struct GetCursorData {
5027 SourceLocation TokenBeginLoc;
5028 bool PointsAtMacroArgExpansion;
5029 bool VisitedObjCPropertyImplDecl;
5030 SourceLocation VisitedDeclaratorDeclStartLoc;
5031 CXCursor &BestCursor;
5032
5033 GetCursorData(SourceManager &SM,
5034 SourceLocation tokenBegin, CXCursor &outputCursor)
5035 : TokenBeginLoc(tokenBegin), BestCursor(outputCursor) {
5036 PointsAtMacroArgExpansion = SM.isMacroArgExpansion(tokenBegin);
5037 VisitedObjCPropertyImplDecl = false;
5038 }
5039};
5040
5041static enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
5042 CXCursor parent,
5043 CXClientData client_data) {
5044 GetCursorData *Data = static_cast<GetCursorData *>(client_data);
5045 CXCursor *BestCursor = &Data->BestCursor;
5046
5047 // If we point inside a macro argument we should provide info of what the
5048 // token is so use the actual cursor, don't replace it with a macro expansion
5049 // cursor.
5050 if (cursor.kind == CXCursor_MacroExpansion && Data->PointsAtMacroArgExpansion)
5051 return CXChildVisit_Recurse;
5052
5053 if (clang_isDeclaration(cursor.kind)) {
5054 // Avoid having the implicit methods override the property decls.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005055 if (const ObjCMethodDecl *MD
Guy Benyei11169dd2012-12-18 14:30:41 +00005056 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
5057 if (MD->isImplicit())
5058 return CXChildVisit_Break;
5059
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005060 } else if (const ObjCInterfaceDecl *ID
Guy Benyei11169dd2012-12-18 14:30:41 +00005061 = dyn_cast_or_null<ObjCInterfaceDecl>(getCursorDecl(cursor))) {
5062 // Check that when we have multiple @class references in the same line,
5063 // that later ones do not override the previous ones.
5064 // If we have:
5065 // @class Foo, Bar;
5066 // source ranges for both start at '@', so 'Bar' will end up overriding
5067 // 'Foo' even though the cursor location was at 'Foo'.
5068 if (BestCursor->kind == CXCursor_ObjCInterfaceDecl ||
5069 BestCursor->kind == CXCursor_ObjCClassRef)
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005070 if (const ObjCInterfaceDecl *PrevID
Guy Benyei11169dd2012-12-18 14:30:41 +00005071 = dyn_cast_or_null<ObjCInterfaceDecl>(getCursorDecl(*BestCursor))){
5072 if (PrevID != ID &&
5073 !PrevID->isThisDeclarationADefinition() &&
5074 !ID->isThisDeclarationADefinition())
5075 return CXChildVisit_Break;
5076 }
5077
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005078 } else if (const DeclaratorDecl *DD
Guy Benyei11169dd2012-12-18 14:30:41 +00005079 = dyn_cast_or_null<DeclaratorDecl>(getCursorDecl(cursor))) {
5080 SourceLocation StartLoc = DD->getSourceRange().getBegin();
5081 // Check that when we have multiple declarators in the same line,
5082 // that later ones do not override the previous ones.
5083 // If we have:
5084 // int Foo, Bar;
5085 // source ranges for both start at 'int', so 'Bar' will end up overriding
5086 // 'Foo' even though the cursor location was at 'Foo'.
5087 if (Data->VisitedDeclaratorDeclStartLoc == StartLoc)
5088 return CXChildVisit_Break;
5089 Data->VisitedDeclaratorDeclStartLoc = StartLoc;
5090
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005091 } else if (const ObjCPropertyImplDecl *PropImp
Guy Benyei11169dd2012-12-18 14:30:41 +00005092 = dyn_cast_or_null<ObjCPropertyImplDecl>(getCursorDecl(cursor))) {
5093 (void)PropImp;
5094 // Check that when we have multiple @synthesize in the same line,
5095 // that later ones do not override the previous ones.
5096 // If we have:
5097 // @synthesize Foo, Bar;
5098 // source ranges for both start at '@', so 'Bar' will end up overriding
5099 // 'Foo' even though the cursor location was at 'Foo'.
5100 if (Data->VisitedObjCPropertyImplDecl)
5101 return CXChildVisit_Break;
5102 Data->VisitedObjCPropertyImplDecl = true;
5103 }
5104 }
5105
5106 if (clang_isExpression(cursor.kind) &&
5107 clang_isDeclaration(BestCursor->kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005108 if (const Decl *D = getCursorDecl(*BestCursor)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005109 // Avoid having the cursor of an expression replace the declaration cursor
5110 // when the expression source range overlaps the declaration range.
5111 // This can happen for C++ constructor expressions whose range generally
5112 // include the variable declaration, e.g.:
5113 // MyCXXClass foo; // Make sure pointing at 'foo' returns a VarDecl cursor.
5114 if (D->getLocation().isValid() && Data->TokenBeginLoc.isValid() &&
5115 D->getLocation() == Data->TokenBeginLoc)
5116 return CXChildVisit_Break;
5117 }
5118 }
5119
5120 // If our current best cursor is the construction of a temporary object,
5121 // don't replace that cursor with a type reference, because we want
5122 // clang_getCursor() to point at the constructor.
5123 if (clang_isExpression(BestCursor->kind) &&
5124 isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
5125 cursor.kind == CXCursor_TypeRef) {
5126 // Keep the cursor pointing at CXXTemporaryObjectExpr but also mark it
5127 // as having the actual point on the type reference.
5128 *BestCursor = getTypeRefedCallExprCursor(*BestCursor);
5129 return CXChildVisit_Recurse;
5130 }
Douglas Gregore9d95f12015-07-07 03:57:35 +00005131
5132 // If we already have an Objective-C superclass reference, don't
5133 // update it further.
5134 if (BestCursor->kind == CXCursor_ObjCSuperClassRef)
5135 return CXChildVisit_Break;
5136
Guy Benyei11169dd2012-12-18 14:30:41 +00005137 *BestCursor = cursor;
5138 return CXChildVisit_Recurse;
5139}
5140
5141CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00005142 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00005143 LOG_BAD_TU(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00005144 return clang_getNullCursor();
Dmitri Gribenko256454f2014-02-11 14:34:14 +00005145 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005146
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00005147 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00005148 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
5149
5150 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
5151 CXCursor Result = cxcursor::getCursor(TU, SLoc);
5152
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005153 LOG_FUNC_SECTION {
Guy Benyei11169dd2012-12-18 14:30:41 +00005154 CXFile SearchFile;
5155 unsigned SearchLine, SearchColumn;
5156 CXFile ResultFile;
5157 unsigned ResultLine, ResultColumn;
5158 CXString SearchFileName, ResultFileName, KindSpelling, USR;
5159 const char *IsDef = clang_isCursorDefinition(Result)? " (Definition)" : "";
5160 CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
Craig Topper69186e72014-06-08 08:38:04 +00005161
5162 clang_getFileLocation(Loc, &SearchFile, &SearchLine, &SearchColumn,
5163 nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005164 clang_getFileLocation(ResultLoc, &ResultFile, &ResultLine,
Craig Topper69186e72014-06-08 08:38:04 +00005165 &ResultColumn, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005166 SearchFileName = clang_getFileName(SearchFile);
5167 ResultFileName = clang_getFileName(ResultFile);
5168 KindSpelling = clang_getCursorKindSpelling(Result.kind);
5169 USR = clang_getCursorUSR(Result);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005170 *Log << llvm::format("(%s:%d:%d) = %s",
5171 clang_getCString(SearchFileName), SearchLine, SearchColumn,
5172 clang_getCString(KindSpelling))
5173 << llvm::format("(%s:%d:%d):%s%s",
5174 clang_getCString(ResultFileName), ResultLine, ResultColumn,
5175 clang_getCString(USR), IsDef);
Guy Benyei11169dd2012-12-18 14:30:41 +00005176 clang_disposeString(SearchFileName);
5177 clang_disposeString(ResultFileName);
5178 clang_disposeString(KindSpelling);
5179 clang_disposeString(USR);
5180
5181 CXCursor Definition = clang_getCursorDefinition(Result);
5182 if (!clang_equalCursors(Definition, clang_getNullCursor())) {
5183 CXSourceLocation DefinitionLoc = clang_getCursorLocation(Definition);
5184 CXString DefinitionKindSpelling
5185 = clang_getCursorKindSpelling(Definition.kind);
5186 CXFile DefinitionFile;
5187 unsigned DefinitionLine, DefinitionColumn;
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005188 clang_getFileLocation(DefinitionLoc, &DefinitionFile,
Craig Topper69186e72014-06-08 08:38:04 +00005189 &DefinitionLine, &DefinitionColumn, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005190 CXString DefinitionFileName = clang_getFileName(DefinitionFile);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005191 *Log << llvm::format(" -> %s(%s:%d:%d)",
5192 clang_getCString(DefinitionKindSpelling),
5193 clang_getCString(DefinitionFileName),
5194 DefinitionLine, DefinitionColumn);
Guy Benyei11169dd2012-12-18 14:30:41 +00005195 clang_disposeString(DefinitionFileName);
5196 clang_disposeString(DefinitionKindSpelling);
5197 }
5198 }
5199
5200 return Result;
5201}
5202
5203CXCursor clang_getNullCursor(void) {
5204 return MakeCXCursorInvalid(CXCursor_InvalidFile);
5205}
5206
5207unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Argyrios Kyrtzidisbf1be592013-01-08 18:23:28 +00005208 // Clear out the "FirstInDeclGroup" part in a declaration cursor, since we
5209 // can't set consistently. For example, when visiting a DeclStmt we will set
5210 // it but we don't set it on the result of clang_getCursorDefinition for
5211 // a reference of the same declaration.
5212 // FIXME: Setting "FirstInDeclGroup" in CXCursors is a hack that only works
5213 // when visiting a DeclStmt currently, the AST should be enhanced to be able
5214 // to provide that kind of info.
5215 if (clang_isDeclaration(X.kind))
Craig Topper69186e72014-06-08 08:38:04 +00005216 X.data[1] = nullptr;
Argyrios Kyrtzidisbf1be592013-01-08 18:23:28 +00005217 if (clang_isDeclaration(Y.kind))
Craig Topper69186e72014-06-08 08:38:04 +00005218 Y.data[1] = nullptr;
Argyrios Kyrtzidisbf1be592013-01-08 18:23:28 +00005219
Guy Benyei11169dd2012-12-18 14:30:41 +00005220 return X == Y;
5221}
5222
5223unsigned clang_hashCursor(CXCursor C) {
5224 unsigned Index = 0;
5225 if (clang_isExpression(C.kind) || clang_isStatement(C.kind))
5226 Index = 1;
5227
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005228 return llvm::DenseMapInfo<std::pair<unsigned, const void*> >::getHashValue(
Guy Benyei11169dd2012-12-18 14:30:41 +00005229 std::make_pair(C.kind, C.data[Index]));
5230}
5231
5232unsigned clang_isInvalid(enum CXCursorKind K) {
5233 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
5234}
5235
5236unsigned clang_isDeclaration(enum CXCursorKind K) {
5237 return (K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl) ||
5238 (K >= CXCursor_FirstExtraDecl && K <= CXCursor_LastExtraDecl);
5239}
5240
5241unsigned clang_isReference(enum CXCursorKind K) {
5242 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
5243}
5244
5245unsigned clang_isExpression(enum CXCursorKind K) {
5246 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
5247}
5248
5249unsigned clang_isStatement(enum CXCursorKind K) {
5250 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
5251}
5252
5253unsigned clang_isAttribute(enum CXCursorKind K) {
5254 return K >= CXCursor_FirstAttr && K <= CXCursor_LastAttr;
5255}
5256
5257unsigned clang_isTranslationUnit(enum CXCursorKind K) {
5258 return K == CXCursor_TranslationUnit;
5259}
5260
5261unsigned clang_isPreprocessing(enum CXCursorKind K) {
5262 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
5263}
5264
5265unsigned clang_isUnexposed(enum CXCursorKind K) {
5266 switch (K) {
5267 case CXCursor_UnexposedDecl:
5268 case CXCursor_UnexposedExpr:
5269 case CXCursor_UnexposedStmt:
5270 case CXCursor_UnexposedAttr:
5271 return true;
5272 default:
5273 return false;
5274 }
5275}
5276
5277CXCursorKind clang_getCursorKind(CXCursor C) {
5278 return C.kind;
5279}
5280
5281CXSourceLocation clang_getCursorLocation(CXCursor C) {
5282 if (clang_isReference(C.kind)) {
5283 switch (C.kind) {
5284 case CXCursor_ObjCSuperClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005285 std::pair<const ObjCInterfaceDecl *, SourceLocation> P
Guy Benyei11169dd2012-12-18 14:30:41 +00005286 = getCursorObjCSuperClassRef(C);
5287 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5288 }
5289
5290 case CXCursor_ObjCProtocolRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005291 std::pair<const ObjCProtocolDecl *, SourceLocation> P
Guy Benyei11169dd2012-12-18 14:30:41 +00005292 = getCursorObjCProtocolRef(C);
5293 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5294 }
5295
5296 case CXCursor_ObjCClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005297 std::pair<const ObjCInterfaceDecl *, SourceLocation> P
Guy Benyei11169dd2012-12-18 14:30:41 +00005298 = getCursorObjCClassRef(C);
5299 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5300 }
5301
5302 case CXCursor_TypeRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005303 std::pair<const TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005304 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5305 }
5306
5307 case CXCursor_TemplateRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005308 std::pair<const TemplateDecl *, SourceLocation> P =
5309 getCursorTemplateRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005310 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5311 }
5312
5313 case CXCursor_NamespaceRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005314 std::pair<const NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005315 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5316 }
5317
5318 case CXCursor_MemberRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005319 std::pair<const FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005320 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5321 }
5322
5323 case CXCursor_VariableRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005324 std::pair<const VarDecl *, SourceLocation> P = getCursorVariableRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005325 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5326 }
5327
5328 case CXCursor_CXXBaseSpecifier: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005329 const CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005330 if (!BaseSpec)
5331 return clang_getNullLocation();
5332
5333 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
5334 return cxloc::translateSourceLocation(getCursorContext(C),
5335 TSInfo->getTypeLoc().getBeginLoc());
5336
5337 return cxloc::translateSourceLocation(getCursorContext(C),
5338 BaseSpec->getLocStart());
5339 }
5340
5341 case CXCursor_LabelRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005342 std::pair<const LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005343 return cxloc::translateSourceLocation(getCursorContext(C), P.second);
5344 }
5345
5346 case CXCursor_OverloadedDeclRef:
5347 return cxloc::translateSourceLocation(getCursorContext(C),
5348 getCursorOverloadedDeclRef(C).second);
5349
5350 default:
5351 // FIXME: Need a way to enumerate all non-reference cases.
5352 llvm_unreachable("Missed a reference kind");
5353 }
5354 }
5355
5356 if (clang_isExpression(C.kind))
5357 return cxloc::translateSourceLocation(getCursorContext(C),
5358 getLocationFromExpr(getCursorExpr(C)));
5359
5360 if (clang_isStatement(C.kind))
5361 return cxloc::translateSourceLocation(getCursorContext(C),
5362 getCursorStmt(C)->getLocStart());
5363
5364 if (C.kind == CXCursor_PreprocessingDirective) {
5365 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
5366 return cxloc::translateSourceLocation(getCursorContext(C), L);
5367 }
5368
5369 if (C.kind == CXCursor_MacroExpansion) {
5370 SourceLocation L
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00005371 = cxcursor::getCursorMacroExpansion(C).getSourceRange().getBegin();
Guy Benyei11169dd2012-12-18 14:30:41 +00005372 return cxloc::translateSourceLocation(getCursorContext(C), L);
5373 }
5374
5375 if (C.kind == CXCursor_MacroDefinition) {
5376 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
5377 return cxloc::translateSourceLocation(getCursorContext(C), L);
5378 }
5379
5380 if (C.kind == CXCursor_InclusionDirective) {
5381 SourceLocation L
5382 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
5383 return cxloc::translateSourceLocation(getCursorContext(C), L);
5384 }
5385
Argyrios Kyrtzidis16834f12013-09-25 00:14:38 +00005386 if (clang_isAttribute(C.kind)) {
5387 SourceLocation L
5388 = cxcursor::getCursorAttr(C)->getLocation();
5389 return cxloc::translateSourceLocation(getCursorContext(C), L);
5390 }
5391
Guy Benyei11169dd2012-12-18 14:30:41 +00005392 if (!clang_isDeclaration(C.kind))
5393 return clang_getNullLocation();
5394
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005395 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005396 if (!D)
5397 return clang_getNullLocation();
5398
5399 SourceLocation Loc = D->getLocation();
5400 // FIXME: Multiple variables declared in a single declaration
5401 // currently lack the information needed to correctly determine their
5402 // ranges when accounting for the type-specifier. We use context
5403 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
5404 // and if so, whether it is the first decl.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005405 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005406 if (!cxcursor::isFirstInDeclGroup(C))
5407 Loc = VD->getLocation();
5408 }
5409
5410 // For ObjC methods, give the start location of the method name.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005411 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00005412 Loc = MD->getSelectorStartLoc();
5413
5414 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
5415}
5416
NAKAMURA Takumia01f4c32016-12-19 16:50:43 +00005417} // end extern "C"
5418
Guy Benyei11169dd2012-12-18 14:30:41 +00005419CXCursor cxcursor::getCursor(CXTranslationUnit TU, SourceLocation SLoc) {
5420 assert(TU);
5421
5422 // Guard against an invalid SourceLocation, or we may assert in one
5423 // of the following calls.
5424 if (SLoc.isInvalid())
5425 return clang_getNullCursor();
5426
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00005427 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00005428
5429 // Translate the given source location to make it point at the beginning of
5430 // the token under the cursor.
5431 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
5432 CXXUnit->getASTContext().getLangOpts());
5433
5434 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
5435 if (SLoc.isValid()) {
5436 GetCursorData ResultData(CXXUnit->getSourceManager(), SLoc, Result);
5437 CursorVisitor CursorVis(TU, GetCursorVisitor, &ResultData,
5438 /*VisitPreprocessorLast=*/true,
5439 /*VisitIncludedEntities=*/false,
5440 SourceLocation(SLoc));
5441 CursorVis.visitFileRegion();
5442 }
5443
5444 return Result;
5445}
5446
5447static SourceRange getRawCursorExtent(CXCursor C) {
5448 if (clang_isReference(C.kind)) {
5449 switch (C.kind) {
5450 case CXCursor_ObjCSuperClassRef:
5451 return getCursorObjCSuperClassRef(C).second;
5452
5453 case CXCursor_ObjCProtocolRef:
5454 return getCursorObjCProtocolRef(C).second;
5455
5456 case CXCursor_ObjCClassRef:
5457 return getCursorObjCClassRef(C).second;
5458
5459 case CXCursor_TypeRef:
5460 return getCursorTypeRef(C).second;
5461
5462 case CXCursor_TemplateRef:
5463 return getCursorTemplateRef(C).second;
5464
5465 case CXCursor_NamespaceRef:
5466 return getCursorNamespaceRef(C).second;
5467
5468 case CXCursor_MemberRef:
5469 return getCursorMemberRef(C).second;
5470
5471 case CXCursor_CXXBaseSpecifier:
5472 return getCursorCXXBaseSpecifier(C)->getSourceRange();
5473
5474 case CXCursor_LabelRef:
5475 return getCursorLabelRef(C).second;
5476
5477 case CXCursor_OverloadedDeclRef:
5478 return getCursorOverloadedDeclRef(C).second;
5479
5480 case CXCursor_VariableRef:
5481 return getCursorVariableRef(C).second;
5482
5483 default:
5484 // FIXME: Need a way to enumerate all non-reference cases.
5485 llvm_unreachable("Missed a reference kind");
5486 }
5487 }
5488
5489 if (clang_isExpression(C.kind))
5490 return getCursorExpr(C)->getSourceRange();
5491
5492 if (clang_isStatement(C.kind))
5493 return getCursorStmt(C)->getSourceRange();
5494
5495 if (clang_isAttribute(C.kind))
5496 return getCursorAttr(C)->getRange();
5497
5498 if (C.kind == CXCursor_PreprocessingDirective)
5499 return cxcursor::getCursorPreprocessingDirective(C);
5500
5501 if (C.kind == CXCursor_MacroExpansion) {
5502 ASTUnit *TU = getCursorASTUnit(C);
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00005503 SourceRange Range = cxcursor::getCursorMacroExpansion(C).getSourceRange();
Guy Benyei11169dd2012-12-18 14:30:41 +00005504 return TU->mapRangeFromPreamble(Range);
5505 }
5506
5507 if (C.kind == CXCursor_MacroDefinition) {
5508 ASTUnit *TU = getCursorASTUnit(C);
5509 SourceRange Range = cxcursor::getCursorMacroDefinition(C)->getSourceRange();
5510 return TU->mapRangeFromPreamble(Range);
5511 }
5512
5513 if (C.kind == CXCursor_InclusionDirective) {
5514 ASTUnit *TU = getCursorASTUnit(C);
5515 SourceRange Range = cxcursor::getCursorInclusionDirective(C)->getSourceRange();
5516 return TU->mapRangeFromPreamble(Range);
5517 }
5518
5519 if (C.kind == CXCursor_TranslationUnit) {
5520 ASTUnit *TU = getCursorASTUnit(C);
5521 FileID MainID = TU->getSourceManager().getMainFileID();
5522 SourceLocation Start = TU->getSourceManager().getLocForStartOfFile(MainID);
5523 SourceLocation End = TU->getSourceManager().getLocForEndOfFile(MainID);
5524 return SourceRange(Start, End);
5525 }
5526
5527 if (clang_isDeclaration(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005528 const Decl *D = cxcursor::getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005529 if (!D)
5530 return SourceRange();
5531
5532 SourceRange R = D->getSourceRange();
5533 // FIXME: Multiple variables declared in a single declaration
5534 // currently lack the information needed to correctly determine their
5535 // ranges when accounting for the type-specifier. We use context
5536 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
5537 // and if so, whether it is the first decl.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005538 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005539 if (!cxcursor::isFirstInDeclGroup(C))
5540 R.setBegin(VD->getLocation());
5541 }
5542 return R;
5543 }
5544 return SourceRange();
5545}
5546
5547/// \brief Retrieves the "raw" cursor extent, which is then extended to include
5548/// the decl-specifier-seq for declarations.
5549static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr) {
5550 if (clang_isDeclaration(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005551 const Decl *D = cxcursor::getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005552 if (!D)
5553 return SourceRange();
5554
5555 SourceRange R = D->getSourceRange();
5556
5557 // Adjust the start of the location for declarations preceded by
5558 // declaration specifiers.
5559 SourceLocation StartLoc;
5560 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
5561 if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
5562 StartLoc = TI->getTypeLoc().getLocStart();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005563 } else if (const TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005564 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
5565 StartLoc = TI->getTypeLoc().getLocStart();
5566 }
5567
5568 if (StartLoc.isValid() && R.getBegin().isValid() &&
5569 SrcMgr.isBeforeInTranslationUnit(StartLoc, R.getBegin()))
5570 R.setBegin(StartLoc);
5571
5572 // FIXME: Multiple variables declared in a single declaration
5573 // currently lack the information needed to correctly determine their
5574 // ranges when accounting for the type-specifier. We use context
5575 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
5576 // and if so, whether it is the first decl.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005577 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005578 if (!cxcursor::isFirstInDeclGroup(C))
5579 R.setBegin(VD->getLocation());
5580 }
5581
5582 return R;
5583 }
5584
5585 return getRawCursorExtent(C);
5586}
5587
Guy Benyei11169dd2012-12-18 14:30:41 +00005588CXSourceRange clang_getCursorExtent(CXCursor C) {
5589 SourceRange R = getRawCursorExtent(C);
5590 if (R.isInvalid())
5591 return clang_getNullRange();
5592
5593 return cxloc::translateSourceRange(getCursorContext(C), R);
5594}
5595
5596CXCursor clang_getCursorReferenced(CXCursor C) {
5597 if (clang_isInvalid(C.kind))
5598 return clang_getNullCursor();
5599
5600 CXTranslationUnit tu = getCursorTU(C);
5601 if (clang_isDeclaration(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005602 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005603 if (!D)
5604 return clang_getNullCursor();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005605 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00005606 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), tu);
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005607 if (const ObjCPropertyImplDecl *PropImpl =
5608 dyn_cast<ObjCPropertyImplDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00005609 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
5610 return MakeCXCursor(Property, tu);
5611
5612 return C;
5613 }
5614
5615 if (clang_isExpression(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005616 const Expr *E = getCursorExpr(C);
5617 const Decl *D = getDeclFromExpr(E);
Guy Benyei11169dd2012-12-18 14:30:41 +00005618 if (D) {
5619 CXCursor declCursor = MakeCXCursor(D, tu);
5620 declCursor = getSelectorIdentifierCursor(getSelectorIdentifierIndex(C),
5621 declCursor);
5622 return declCursor;
5623 }
5624
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005625 if (const OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00005626 return MakeCursorOverloadedDeclRef(Ovl, tu);
5627
5628 return clang_getNullCursor();
5629 }
5630
5631 if (clang_isStatement(C.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00005632 const Stmt *S = getCursorStmt(C);
5633 if (const GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
Guy Benyei11169dd2012-12-18 14:30:41 +00005634 if (LabelDecl *label = Goto->getLabel())
5635 if (LabelStmt *labelS = label->getStmt())
5636 return MakeCXCursor(labelS, getCursorDecl(C), tu);
5637
5638 return clang_getNullCursor();
5639 }
Richard Smith66a81862015-05-04 02:25:31 +00005640
Guy Benyei11169dd2012-12-18 14:30:41 +00005641 if (C.kind == CXCursor_MacroExpansion) {
Richard Smith66a81862015-05-04 02:25:31 +00005642 if (const MacroDefinitionRecord *Def =
5643 getCursorMacroExpansion(C).getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00005644 return MakeMacroDefinitionCursor(Def, tu);
5645 }
5646
5647 if (!clang_isReference(C.kind))
5648 return clang_getNullCursor();
5649
5650 switch (C.kind) {
5651 case CXCursor_ObjCSuperClassRef:
5652 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, tu);
5653
5654 case CXCursor_ObjCProtocolRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005655 const ObjCProtocolDecl *Prot = getCursorObjCProtocolRef(C).first;
5656 if (const ObjCProtocolDecl *Def = Prot->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00005657 return MakeCXCursor(Def, tu);
5658
5659 return MakeCXCursor(Prot, tu);
5660 }
5661
5662 case CXCursor_ObjCClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005663 const ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
5664 if (const ObjCInterfaceDecl *Def = Class->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00005665 return MakeCXCursor(Def, tu);
5666
5667 return MakeCXCursor(Class, tu);
5668 }
5669
5670 case CXCursor_TypeRef:
5671 return MakeCXCursor(getCursorTypeRef(C).first, tu );
5672
5673 case CXCursor_TemplateRef:
5674 return MakeCXCursor(getCursorTemplateRef(C).first, tu );
5675
5676 case CXCursor_NamespaceRef:
5677 return MakeCXCursor(getCursorNamespaceRef(C).first, tu );
5678
5679 case CXCursor_MemberRef:
5680 return MakeCXCursor(getCursorMemberRef(C).first, tu );
5681
5682 case CXCursor_CXXBaseSpecifier: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005683 const CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005684 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
5685 tu ));
5686 }
5687
5688 case CXCursor_LabelRef:
5689 // FIXME: We end up faking the "parent" declaration here because we
5690 // don't want to make CXCursor larger.
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00005691 return MakeCXCursor(getCursorLabelRef(C).first,
5692 cxtu::getASTUnit(tu)->getASTContext()
5693 .getTranslationUnitDecl(),
Guy Benyei11169dd2012-12-18 14:30:41 +00005694 tu);
5695
5696 case CXCursor_OverloadedDeclRef:
5697 return C;
5698
5699 case CXCursor_VariableRef:
5700 return MakeCXCursor(getCursorVariableRef(C).first, tu);
5701
5702 default:
5703 // We would prefer to enumerate all non-reference cursor kinds here.
5704 llvm_unreachable("Unhandled reference cursor kind");
5705 }
5706}
5707
5708CXCursor clang_getCursorDefinition(CXCursor C) {
5709 if (clang_isInvalid(C.kind))
5710 return clang_getNullCursor();
5711
5712 CXTranslationUnit TU = getCursorTU(C);
5713
5714 bool WasReference = false;
5715 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
5716 C = clang_getCursorReferenced(C);
5717 WasReference = true;
5718 }
5719
5720 if (C.kind == CXCursor_MacroExpansion)
5721 return clang_getCursorReferenced(C);
5722
5723 if (!clang_isDeclaration(C.kind))
5724 return clang_getNullCursor();
5725
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005726 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005727 if (!D)
5728 return clang_getNullCursor();
5729
5730 switch (D->getKind()) {
5731 // Declaration kinds that don't really separate the notions of
5732 // declaration and definition.
5733 case Decl::Namespace:
5734 case Decl::Typedef:
5735 case Decl::TypeAlias:
5736 case Decl::TypeAliasTemplate:
5737 case Decl::TemplateTypeParm:
5738 case Decl::EnumConstant:
5739 case Decl::Field:
Richard Smithbdb84f32016-07-22 23:36:59 +00005740 case Decl::Binding:
John McCall5e77d762013-04-16 07:28:30 +00005741 case Decl::MSProperty:
Guy Benyei11169dd2012-12-18 14:30:41 +00005742 case Decl::IndirectField:
5743 case Decl::ObjCIvar:
5744 case Decl::ObjCAtDefsField:
5745 case Decl::ImplicitParam:
5746 case Decl::ParmVar:
5747 case Decl::NonTypeTemplateParm:
5748 case Decl::TemplateTemplateParm:
5749 case Decl::ObjCCategoryImpl:
5750 case Decl::ObjCImplementation:
5751 case Decl::AccessSpec:
5752 case Decl::LinkageSpec:
Richard Smith8df390f2016-09-08 23:14:54 +00005753 case Decl::Export:
Guy Benyei11169dd2012-12-18 14:30:41 +00005754 case Decl::ObjCPropertyImpl:
5755 case Decl::FileScopeAsm:
5756 case Decl::StaticAssert:
5757 case Decl::Block:
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00005758 case Decl::Captured:
Alexey Bataev4244be22016-02-11 05:35:55 +00005759 case Decl::OMPCapturedExpr:
Guy Benyei11169dd2012-12-18 14:30:41 +00005760 case Decl::Label: // FIXME: Is this right??
5761 case Decl::ClassScopeFunctionSpecialization:
5762 case Decl::Import:
Alexey Bataeva769e072013-03-22 06:34:35 +00005763 case Decl::OMPThreadPrivate:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00005764 case Decl::OMPDeclareReduction:
Douglas Gregor85f3f952015-07-07 03:57:15 +00005765 case Decl::ObjCTypeParam:
David Majnemerd9b1a4f2015-11-04 03:40:30 +00005766 case Decl::BuiltinTemplate:
Nico Weber66220292016-03-02 17:28:48 +00005767 case Decl::PragmaComment:
Nico Webercbbaeb12016-03-02 19:28:54 +00005768 case Decl::PragmaDetectMismatch:
Richard Smith151c4562016-12-20 21:35:28 +00005769 case Decl::UsingPack:
Guy Benyei11169dd2012-12-18 14:30:41 +00005770 return C;
5771
5772 // Declaration kinds that don't make any sense here, but are
5773 // nonetheless harmless.
David Blaikief005d3c2013-02-22 17:44:58 +00005774 case Decl::Empty:
Guy Benyei11169dd2012-12-18 14:30:41 +00005775 case Decl::TranslationUnit:
Richard Smithf19e1272015-03-07 00:04:49 +00005776 case Decl::ExternCContext:
Guy Benyei11169dd2012-12-18 14:30:41 +00005777 break;
5778
5779 // Declaration kinds for which the definition is not resolvable.
5780 case Decl::UnresolvedUsingTypename:
5781 case Decl::UnresolvedUsingValue:
5782 break;
5783
5784 case Decl::UsingDirective:
5785 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
5786 TU);
5787
5788 case Decl::NamespaceAlias:
5789 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), TU);
5790
5791 case Decl::Enum:
5792 case Decl::Record:
5793 case Decl::CXXRecord:
5794 case Decl::ClassTemplateSpecialization:
5795 case Decl::ClassTemplatePartialSpecialization:
5796 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
5797 return MakeCXCursor(Def, TU);
5798 return clang_getNullCursor();
5799
5800 case Decl::Function:
5801 case Decl::CXXMethod:
5802 case Decl::CXXConstructor:
5803 case Decl::CXXDestructor:
5804 case Decl::CXXConversion: {
Craig Topper69186e72014-06-08 08:38:04 +00005805 const FunctionDecl *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005806 if (cast<FunctionDecl>(D)->getBody(Def))
Dmitri Gribenko9c256e32013-01-14 00:46:27 +00005807 return MakeCXCursor(Def, TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00005808 return clang_getNullCursor();
5809 }
5810
Larisse Voufo39a1e502013-08-06 01:03:05 +00005811 case Decl::Var:
5812 case Decl::VarTemplateSpecialization:
Richard Smithbdb84f32016-07-22 23:36:59 +00005813 case Decl::VarTemplatePartialSpecialization:
5814 case Decl::Decomposition: {
Guy Benyei11169dd2012-12-18 14:30:41 +00005815 // Ask the variable if it has a definition.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005816 if (const VarDecl *Def = cast<VarDecl>(D)->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00005817 return MakeCXCursor(Def, TU);
5818 return clang_getNullCursor();
5819 }
5820
5821 case Decl::FunctionTemplate: {
Craig Topper69186e72014-06-08 08:38:04 +00005822 const FunctionDecl *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005823 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
5824 return MakeCXCursor(Def->getDescribedFunctionTemplate(), TU);
5825 return clang_getNullCursor();
5826 }
5827
5828 case Decl::ClassTemplate: {
5829 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
5830 ->getDefinition())
5831 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
5832 TU);
5833 return clang_getNullCursor();
5834 }
5835
Larisse Voufo39a1e502013-08-06 01:03:05 +00005836 case Decl::VarTemplate: {
5837 if (VarDecl *Def =
5838 cast<VarTemplateDecl>(D)->getTemplatedDecl()->getDefinition())
5839 return MakeCXCursor(cast<VarDecl>(Def)->getDescribedVarTemplate(), TU);
5840 return clang_getNullCursor();
5841 }
5842
Guy Benyei11169dd2012-12-18 14:30:41 +00005843 case Decl::Using:
5844 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
5845 D->getLocation(), TU);
5846
5847 case Decl::UsingShadow:
Richard Smith5179eb72016-06-28 19:03:57 +00005848 case Decl::ConstructorUsingShadow:
Guy Benyei11169dd2012-12-18 14:30:41 +00005849 return clang_getCursorDefinition(
5850 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
5851 TU));
5852
5853 case Decl::ObjCMethod: {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005854 const ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00005855 if (Method->isThisDeclarationADefinition())
5856 return C;
5857
5858 // Dig out the method definition in the associated
5859 // @implementation, if we have it.
5860 // FIXME: The ASTs should make finding the definition easier.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005861 if (const ObjCInterfaceDecl *Class
Guy Benyei11169dd2012-12-18 14:30:41 +00005862 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
5863 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
5864 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
5865 Method->isInstanceMethod()))
5866 if (Def->isThisDeclarationADefinition())
5867 return MakeCXCursor(Def, TU);
5868
5869 return clang_getNullCursor();
5870 }
5871
5872 case Decl::ObjCCategory:
5873 if (ObjCCategoryImplDecl *Impl
5874 = cast<ObjCCategoryDecl>(D)->getImplementation())
5875 return MakeCXCursor(Impl, TU);
5876 return clang_getNullCursor();
5877
5878 case Decl::ObjCProtocol:
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005879 if (const ObjCProtocolDecl *Def = cast<ObjCProtocolDecl>(D)->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00005880 return MakeCXCursor(Def, TU);
5881 return clang_getNullCursor();
5882
5883 case Decl::ObjCInterface: {
5884 // There are two notions of a "definition" for an Objective-C
5885 // class: the interface and its implementation. When we resolved a
5886 // reference to an Objective-C class, produce the @interface as
5887 // the definition; when we were provided with the interface,
5888 // produce the @implementation as the definition.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005889 const ObjCInterfaceDecl *IFace = cast<ObjCInterfaceDecl>(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00005890 if (WasReference) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005891 if (const ObjCInterfaceDecl *Def = IFace->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00005892 return MakeCXCursor(Def, TU);
5893 } else if (ObjCImplementationDecl *Impl = IFace->getImplementation())
5894 return MakeCXCursor(Impl, TU);
5895 return clang_getNullCursor();
5896 }
5897
5898 case Decl::ObjCProperty:
5899 // FIXME: We don't really know where to find the
5900 // ObjCPropertyImplDecls that implement this property.
5901 return clang_getNullCursor();
5902
5903 case Decl::ObjCCompatibleAlias:
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005904 if (const ObjCInterfaceDecl *Class
Guy Benyei11169dd2012-12-18 14:30:41 +00005905 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005906 if (const ObjCInterfaceDecl *Def = Class->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00005907 return MakeCXCursor(Def, TU);
5908
5909 return clang_getNullCursor();
5910
5911 case Decl::Friend:
5912 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
5913 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
5914 return clang_getNullCursor();
5915
5916 case Decl::FriendTemplate:
5917 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
5918 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
5919 return clang_getNullCursor();
5920 }
5921
5922 return clang_getNullCursor();
5923}
5924
5925unsigned clang_isCursorDefinition(CXCursor C) {
5926 if (!clang_isDeclaration(C.kind))
5927 return 0;
5928
5929 return clang_getCursorDefinition(C) == C;
5930}
5931
5932CXCursor clang_getCanonicalCursor(CXCursor C) {
5933 if (!clang_isDeclaration(C.kind))
5934 return C;
5935
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005936 if (const Decl *D = getCursorDecl(C)) {
5937 if (const ObjCCategoryImplDecl *CatImplD = dyn_cast<ObjCCategoryImplDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00005938 if (ObjCCategoryDecl *CatD = CatImplD->getCategoryDecl())
5939 return MakeCXCursor(CatD, getCursorTU(C));
5940
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005941 if (const ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
5942 if (const ObjCInterfaceDecl *IFD = ImplD->getClassInterface())
Guy Benyei11169dd2012-12-18 14:30:41 +00005943 return MakeCXCursor(IFD, getCursorTU(C));
5944
5945 return MakeCXCursor(D->getCanonicalDecl(), getCursorTU(C));
5946 }
5947
5948 return C;
5949}
5950
5951int clang_Cursor_getObjCSelectorIndex(CXCursor cursor) {
5952 return cxcursor::getSelectorIdentifierIndexAndLoc(cursor).first;
5953}
5954
5955unsigned clang_getNumOverloadedDecls(CXCursor C) {
5956 if (C.kind != CXCursor_OverloadedDeclRef)
5957 return 0;
5958
5959 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005960 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
Guy Benyei11169dd2012-12-18 14:30:41 +00005961 return E->getNumDecls();
5962
5963 if (OverloadedTemplateStorage *S
5964 = Storage.dyn_cast<OverloadedTemplateStorage*>())
5965 return S->size();
5966
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005967 const Decl *D = Storage.get<const Decl *>();
5968 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00005969 return Using->shadow_size();
5970
5971 return 0;
5972}
5973
5974CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
5975 if (cursor.kind != CXCursor_OverloadedDeclRef)
5976 return clang_getNullCursor();
5977
5978 if (index >= clang_getNumOverloadedDecls(cursor))
5979 return clang_getNullCursor();
5980
5981 CXTranslationUnit TU = getCursorTU(cursor);
5982 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005983 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
Guy Benyei11169dd2012-12-18 14:30:41 +00005984 return MakeCXCursor(E->decls_begin()[index], TU);
5985
5986 if (OverloadedTemplateStorage *S
5987 = Storage.dyn_cast<OverloadedTemplateStorage*>())
5988 return MakeCXCursor(S->begin()[index], TU);
5989
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005990 const Decl *D = Storage.get<const Decl *>();
5991 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005992 // FIXME: This is, unfortunately, linear time.
5993 UsingDecl::shadow_iterator Pos = Using->shadow_begin();
5994 std::advance(Pos, index);
5995 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), TU);
5996 }
5997
5998 return clang_getNullCursor();
5999}
6000
6001void clang_getDefinitionSpellingAndExtent(CXCursor C,
6002 const char **startBuf,
6003 const char **endBuf,
6004 unsigned *startLine,
6005 unsigned *startColumn,
6006 unsigned *endLine,
6007 unsigned *endColumn) {
6008 assert(getCursorDecl(C) && "CXCursor has null decl");
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006009 const FunctionDecl *FD = dyn_cast<FunctionDecl>(getCursorDecl(C));
Guy Benyei11169dd2012-12-18 14:30:41 +00006010 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
6011
6012 SourceManager &SM = FD->getASTContext().getSourceManager();
6013 *startBuf = SM.getCharacterData(Body->getLBracLoc());
6014 *endBuf = SM.getCharacterData(Body->getRBracLoc());
6015 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
6016 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
6017 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
6018 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
6019}
6020
6021
6022CXSourceRange clang_getCursorReferenceNameRange(CXCursor C, unsigned NameFlags,
6023 unsigned PieceIndex) {
6024 RefNamePieces Pieces;
6025
6026 switch (C.kind) {
6027 case CXCursor_MemberRefExpr:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006028 if (const MemberExpr *E = dyn_cast<MemberExpr>(getCursorExpr(C)))
Guy Benyei11169dd2012-12-18 14:30:41 +00006029 Pieces = buildPieces(NameFlags, true, E->getMemberNameInfo(),
6030 E->getQualifierLoc().getSourceRange());
6031 break;
6032
6033 case CXCursor_DeclRefExpr:
James Y Knight04ec5bf2015-12-24 02:59:37 +00006034 if (const DeclRefExpr *E = dyn_cast<DeclRefExpr>(getCursorExpr(C))) {
6035 SourceRange TemplateArgLoc(E->getLAngleLoc(), E->getRAngleLoc());
6036 Pieces =
6037 buildPieces(NameFlags, false, E->getNameInfo(),
6038 E->getQualifierLoc().getSourceRange(), &TemplateArgLoc);
6039 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006040 break;
6041
6042 case CXCursor_CallExpr:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006043 if (const CXXOperatorCallExpr *OCE =
Guy Benyei11169dd2012-12-18 14:30:41 +00006044 dyn_cast<CXXOperatorCallExpr>(getCursorExpr(C))) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006045 const Expr *Callee = OCE->getCallee();
6046 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Callee))
Guy Benyei11169dd2012-12-18 14:30:41 +00006047 Callee = ICE->getSubExpr();
6048
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006049 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Callee))
Guy Benyei11169dd2012-12-18 14:30:41 +00006050 Pieces = buildPieces(NameFlags, false, DRE->getNameInfo(),
6051 DRE->getQualifierLoc().getSourceRange());
6052 }
6053 break;
6054
6055 default:
6056 break;
6057 }
6058
6059 if (Pieces.empty()) {
6060 if (PieceIndex == 0)
6061 return clang_getCursorExtent(C);
6062 } else if (PieceIndex < Pieces.size()) {
6063 SourceRange R = Pieces[PieceIndex];
6064 if (R.isValid())
6065 return cxloc::translateSourceRange(getCursorContext(C), R);
6066 }
6067
6068 return clang_getNullRange();
6069}
6070
6071void clang_enableStackTraces(void) {
Richard Smithdfed58a2016-06-09 00:53:41 +00006072 // FIXME: Provide an argv0 here so we can find llvm-symbolizer.
6073 llvm::sys::PrintStackTraceOnErrorSignal(StringRef());
Guy Benyei11169dd2012-12-18 14:30:41 +00006074}
6075
6076void clang_executeOnThread(void (*fn)(void*), void *user_data,
6077 unsigned stack_size) {
6078 llvm::llvm_execute_on_thread(fn, user_data, stack_size);
6079}
6080
Guy Benyei11169dd2012-12-18 14:30:41 +00006081//===----------------------------------------------------------------------===//
6082// Token-based Operations.
6083//===----------------------------------------------------------------------===//
6084
6085/* CXToken layout:
6086 * int_data[0]: a CXTokenKind
6087 * int_data[1]: starting token location
6088 * int_data[2]: token length
6089 * int_data[3]: reserved
6090 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
6091 * otherwise unused.
6092 */
Guy Benyei11169dd2012-12-18 14:30:41 +00006093CXTokenKind clang_getTokenKind(CXToken CXTok) {
6094 return static_cast<CXTokenKind>(CXTok.int_data[0]);
6095}
6096
6097CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
6098 switch (clang_getTokenKind(CXTok)) {
6099 case CXToken_Identifier:
6100 case CXToken_Keyword:
6101 // We know we have an IdentifierInfo*, so use that.
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00006102 return cxstring::createRef(static_cast<IdentifierInfo *>(CXTok.ptr_data)
Guy Benyei11169dd2012-12-18 14:30:41 +00006103 ->getNameStart());
6104
6105 case CXToken_Literal: {
6106 // We have stashed the starting pointer in the ptr_data field. Use it.
6107 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00006108 return cxstring::createDup(StringRef(Text, CXTok.int_data[2]));
Guy Benyei11169dd2012-12-18 14:30:41 +00006109 }
6110
6111 case CXToken_Punctuation:
6112 case CXToken_Comment:
6113 break;
6114 }
6115
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006116 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006117 LOG_BAD_TU(TU);
6118 return cxstring::createEmpty();
6119 }
6120
Guy Benyei11169dd2012-12-18 14:30:41 +00006121 // We have to find the starting buffer pointer the hard way, by
6122 // deconstructing the source location.
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006123 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006124 if (!CXXUnit)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00006125 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00006126
6127 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
6128 std::pair<FileID, unsigned> LocInfo
6129 = CXXUnit->getSourceManager().getDecomposedSpellingLoc(Loc);
6130 bool Invalid = false;
6131 StringRef Buffer
6132 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
6133 if (Invalid)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00006134 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00006135
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00006136 return cxstring::createDup(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Guy Benyei11169dd2012-12-18 14:30:41 +00006137}
6138
6139CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006140 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006141 LOG_BAD_TU(TU);
6142 return clang_getNullLocation();
6143 }
6144
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006145 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006146 if (!CXXUnit)
6147 return clang_getNullLocation();
6148
6149 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
6150 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
6151}
6152
6153CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006154 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006155 LOG_BAD_TU(TU);
6156 return clang_getNullRange();
6157 }
6158
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006159 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006160 if (!CXXUnit)
6161 return clang_getNullRange();
6162
6163 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
6164 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
6165}
6166
6167static void getTokens(ASTUnit *CXXUnit, SourceRange Range,
6168 SmallVectorImpl<CXToken> &CXTokens) {
6169 SourceManager &SourceMgr = CXXUnit->getSourceManager();
6170 std::pair<FileID, unsigned> BeginLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00006171 = SourceMgr.getDecomposedSpellingLoc(Range.getBegin());
Guy Benyei11169dd2012-12-18 14:30:41 +00006172 std::pair<FileID, unsigned> EndLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00006173 = SourceMgr.getDecomposedSpellingLoc(Range.getEnd());
Guy Benyei11169dd2012-12-18 14:30:41 +00006174
6175 // Cannot tokenize across files.
6176 if (BeginLocInfo.first != EndLocInfo.first)
6177 return;
6178
6179 // Create a lexer
6180 bool Invalid = false;
6181 StringRef Buffer
6182 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
6183 if (Invalid)
6184 return;
6185
6186 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
6187 CXXUnit->getASTContext().getLangOpts(),
6188 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
6189 Lex.SetCommentRetentionState(true);
6190
6191 // Lex tokens until we hit the end of the range.
6192 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
6193 Token Tok;
6194 bool previousWasAt = false;
6195 do {
6196 // Lex the next token
6197 Lex.LexFromRawLexer(Tok);
6198 if (Tok.is(tok::eof))
6199 break;
6200
6201 // Initialize the CXToken.
6202 CXToken CXTok;
6203
6204 // - Common fields
6205 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
6206 CXTok.int_data[2] = Tok.getLength();
6207 CXTok.int_data[3] = 0;
6208
6209 // - Kind-specific fields
6210 if (Tok.isLiteral()) {
6211 CXTok.int_data[0] = CXToken_Literal;
Dmitri Gribenkof9304482013-01-23 15:56:07 +00006212 CXTok.ptr_data = const_cast<char *>(Tok.getLiteralData());
Guy Benyei11169dd2012-12-18 14:30:41 +00006213 } else if (Tok.is(tok::raw_identifier)) {
6214 // Lookup the identifier to determine whether we have a keyword.
6215 IdentifierInfo *II
6216 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok);
6217
6218 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
6219 CXTok.int_data[0] = CXToken_Keyword;
6220 }
6221 else {
6222 CXTok.int_data[0] = Tok.is(tok::identifier)
6223 ? CXToken_Identifier
6224 : CXToken_Keyword;
6225 }
6226 CXTok.ptr_data = II;
6227 } else if (Tok.is(tok::comment)) {
6228 CXTok.int_data[0] = CXToken_Comment;
Craig Topper69186e72014-06-08 08:38:04 +00006229 CXTok.ptr_data = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006230 } else {
6231 CXTok.int_data[0] = CXToken_Punctuation;
Craig Topper69186e72014-06-08 08:38:04 +00006232 CXTok.ptr_data = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006233 }
6234 CXTokens.push_back(CXTok);
6235 previousWasAt = Tok.is(tok::at);
Argyrios Kyrtzidisc7c6a072016-11-09 23:58:39 +00006236 } while (Lex.getBufferLocation() < EffectiveBufferEnd);
Guy Benyei11169dd2012-12-18 14:30:41 +00006237}
6238
6239void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
6240 CXToken **Tokens, unsigned *NumTokens) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00006241 LOG_FUNC_SECTION {
6242 *Log << TU << ' ' << Range;
6243 }
6244
Guy Benyei11169dd2012-12-18 14:30:41 +00006245 if (Tokens)
Craig Topper69186e72014-06-08 08:38:04 +00006246 *Tokens = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006247 if (NumTokens)
6248 *NumTokens = 0;
6249
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006250 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006251 LOG_BAD_TU(TU);
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00006252 return;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006253 }
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00006254
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006255 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006256 if (!CXXUnit || !Tokens || !NumTokens)
6257 return;
6258
6259 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
6260
6261 SourceRange R = cxloc::translateCXSourceRange(Range);
6262 if (R.isInvalid())
6263 return;
6264
6265 SmallVector<CXToken, 32> CXTokens;
6266 getTokens(CXXUnit, R, CXTokens);
6267
6268 if (CXTokens.empty())
6269 return;
6270
6271 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
6272 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
6273 *NumTokens = CXTokens.size();
6274}
6275
6276void clang_disposeTokens(CXTranslationUnit TU,
6277 CXToken *Tokens, unsigned NumTokens) {
6278 free(Tokens);
6279}
6280
Guy Benyei11169dd2012-12-18 14:30:41 +00006281//===----------------------------------------------------------------------===//
6282// Token annotation APIs.
6283//===----------------------------------------------------------------------===//
6284
Guy Benyei11169dd2012-12-18 14:30:41 +00006285static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
6286 CXCursor parent,
6287 CXClientData client_data);
6288static bool AnnotateTokensPostChildrenVisitor(CXCursor cursor,
6289 CXClientData client_data);
6290
6291namespace {
6292class AnnotateTokensWorker {
Guy Benyei11169dd2012-12-18 14:30:41 +00006293 CXToken *Tokens;
6294 CXCursor *Cursors;
6295 unsigned NumTokens;
6296 unsigned TokIdx;
6297 unsigned PreprocessingTokIdx;
6298 CursorVisitor AnnotateVis;
6299 SourceManager &SrcMgr;
6300 bool HasContextSensitiveKeywords;
6301
6302 struct PostChildrenInfo {
6303 CXCursor Cursor;
6304 SourceRange CursorRange;
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006305 unsigned BeforeReachingCursorIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00006306 unsigned BeforeChildrenTokenIdx;
6307 };
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006308 SmallVector<PostChildrenInfo, 8> PostChildrenInfos;
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006309
6310 CXToken &getTok(unsigned Idx) {
6311 assert(Idx < NumTokens);
6312 return Tokens[Idx];
6313 }
6314 const CXToken &getTok(unsigned Idx) const {
6315 assert(Idx < NumTokens);
6316 return Tokens[Idx];
6317 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006318 bool MoreTokens() const { return TokIdx < NumTokens; }
6319 unsigned NextToken() const { return TokIdx; }
6320 void AdvanceToken() { ++TokIdx; }
6321 SourceLocation GetTokenLoc(unsigned tokI) {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006322 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[1]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006323 }
6324 bool isFunctionMacroToken(unsigned tokI) const {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006325 return getTok(tokI).int_data[3] != 0;
Guy Benyei11169dd2012-12-18 14:30:41 +00006326 }
6327 SourceLocation getFunctionMacroTokenLoc(unsigned tokI) const {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006328 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[3]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006329 }
6330
6331 void annotateAndAdvanceTokens(CXCursor, RangeComparisonResult, SourceRange);
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006332 bool annotateAndAdvanceFunctionMacroTokens(CXCursor, RangeComparisonResult,
Guy Benyei11169dd2012-12-18 14:30:41 +00006333 SourceRange);
6334
6335public:
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006336 AnnotateTokensWorker(CXToken *tokens, CXCursor *cursors, unsigned numTokens,
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006337 CXTranslationUnit TU, SourceRange RegionOfInterest)
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006338 : Tokens(tokens), Cursors(cursors),
Guy Benyei11169dd2012-12-18 14:30:41 +00006339 NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006340 AnnotateVis(TU,
Guy Benyei11169dd2012-12-18 14:30:41 +00006341 AnnotateTokensVisitor, this,
6342 /*VisitPreprocessorLast=*/true,
6343 /*VisitIncludedEntities=*/false,
6344 RegionOfInterest,
6345 /*VisitDeclsOnly=*/false,
6346 AnnotateTokensPostChildrenVisitor),
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006347 SrcMgr(cxtu::getASTUnit(TU)->getSourceManager()),
Guy Benyei11169dd2012-12-18 14:30:41 +00006348 HasContextSensitiveKeywords(false) { }
6349
6350 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
6351 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
6352 bool postVisitChildren(CXCursor cursor);
6353 void AnnotateTokens();
6354
6355 /// \brief Determine whether the annotator saw any cursors that have
6356 /// context-sensitive keywords.
6357 bool hasContextSensitiveKeywords() const {
6358 return HasContextSensitiveKeywords;
6359 }
6360
6361 ~AnnotateTokensWorker() {
6362 assert(PostChildrenInfos.empty());
6363 }
6364};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006365}
Guy Benyei11169dd2012-12-18 14:30:41 +00006366
6367void AnnotateTokensWorker::AnnotateTokens() {
6368 // Walk the AST within the region of interest, annotating tokens
6369 // along the way.
6370 AnnotateVis.visitFileRegion();
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006371}
Guy Benyei11169dd2012-12-18 14:30:41 +00006372
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006373static inline void updateCursorAnnotation(CXCursor &Cursor,
6374 const CXCursor &updateC) {
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006375 if (clang_isInvalid(updateC.kind) || !clang_isInvalid(Cursor.kind))
Guy Benyei11169dd2012-12-18 14:30:41 +00006376 return;
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006377 Cursor = updateC;
Guy Benyei11169dd2012-12-18 14:30:41 +00006378}
6379
6380/// \brief It annotates and advances tokens with a cursor until the comparison
6381//// between the cursor location and the source range is the same as
6382/// \arg compResult.
6383///
6384/// Pass RangeBefore to annotate tokens with a cursor until a range is reached.
6385/// Pass RangeOverlap to annotate tokens inside a range.
6386void AnnotateTokensWorker::annotateAndAdvanceTokens(CXCursor updateC,
6387 RangeComparisonResult compResult,
6388 SourceRange range) {
6389 while (MoreTokens()) {
6390 const unsigned I = NextToken();
6391 if (isFunctionMacroToken(I))
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006392 if (!annotateAndAdvanceFunctionMacroTokens(updateC, compResult, range))
6393 return;
Guy Benyei11169dd2012-12-18 14:30:41 +00006394
6395 SourceLocation TokLoc = GetTokenLoc(I);
6396 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006397 updateCursorAnnotation(Cursors[I], updateC);
Guy Benyei11169dd2012-12-18 14:30:41 +00006398 AdvanceToken();
6399 continue;
6400 }
6401 break;
6402 }
6403}
6404
6405/// \brief Special annotation handling for macro argument tokens.
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006406/// \returns true if it advanced beyond all macro tokens, false otherwise.
6407bool AnnotateTokensWorker::annotateAndAdvanceFunctionMacroTokens(
Guy Benyei11169dd2012-12-18 14:30:41 +00006408 CXCursor updateC,
6409 RangeComparisonResult compResult,
6410 SourceRange range) {
6411 assert(MoreTokens());
6412 assert(isFunctionMacroToken(NextToken()) &&
6413 "Should be called only for macro arg tokens");
6414
6415 // This works differently than annotateAndAdvanceTokens; because expanded
6416 // macro arguments can have arbitrary translation-unit source order, we do not
6417 // advance the token index one by one until a token fails the range test.
6418 // We only advance once past all of the macro arg tokens if all of them
6419 // pass the range test. If one of them fails we keep the token index pointing
6420 // at the start of the macro arg tokens so that the failing token will be
6421 // annotated by a subsequent annotation try.
6422
6423 bool atLeastOneCompFail = false;
6424
6425 unsigned I = NextToken();
6426 for (; I < NumTokens && isFunctionMacroToken(I); ++I) {
6427 SourceLocation TokLoc = getFunctionMacroTokenLoc(I);
6428 if (TokLoc.isFileID())
6429 continue; // not macro arg token, it's parens or comma.
6430 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
6431 if (clang_isInvalid(clang_getCursorKind(Cursors[I])))
6432 Cursors[I] = updateC;
6433 } else
6434 atLeastOneCompFail = true;
6435 }
6436
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006437 if (atLeastOneCompFail)
6438 return false;
6439
6440 TokIdx = I; // All of the tokens were handled, advance beyond all of them.
6441 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00006442}
6443
6444enum CXChildVisitResult
6445AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006446 SourceRange cursorRange = getRawCursorExtent(cursor);
6447 if (cursorRange.isInvalid())
6448 return CXChildVisit_Recurse;
6449
6450 if (!HasContextSensitiveKeywords) {
6451 // Objective-C properties can have context-sensitive keywords.
6452 if (cursor.kind == CXCursor_ObjCPropertyDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006453 if (const ObjCPropertyDecl *Property
Guy Benyei11169dd2012-12-18 14:30:41 +00006454 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(cursor)))
6455 HasContextSensitiveKeywords = Property->getPropertyAttributesAsWritten() != 0;
6456 }
6457 // Objective-C methods can have context-sensitive keywords.
6458 else if (cursor.kind == CXCursor_ObjCInstanceMethodDecl ||
6459 cursor.kind == CXCursor_ObjCClassMethodDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006460 if (const ObjCMethodDecl *Method
Guy Benyei11169dd2012-12-18 14:30:41 +00006461 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
6462 if (Method->getObjCDeclQualifier())
6463 HasContextSensitiveKeywords = true;
6464 else {
David Majnemer59f77922016-06-24 04:05:48 +00006465 for (const auto *P : Method->parameters()) {
Aaron Ballman43b68be2014-03-07 17:50:17 +00006466 if (P->getObjCDeclQualifier()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006467 HasContextSensitiveKeywords = true;
6468 break;
6469 }
6470 }
6471 }
6472 }
6473 }
6474 // C++ methods can have context-sensitive keywords.
6475 else if (cursor.kind == CXCursor_CXXMethod) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006476 if (const CXXMethodDecl *Method
Guy Benyei11169dd2012-12-18 14:30:41 +00006477 = dyn_cast_or_null<CXXMethodDecl>(getCursorDecl(cursor))) {
6478 if (Method->hasAttr<FinalAttr>() || Method->hasAttr<OverrideAttr>())
6479 HasContextSensitiveKeywords = true;
6480 }
6481 }
6482 // C++ classes can have context-sensitive keywords.
6483 else if (cursor.kind == CXCursor_StructDecl ||
6484 cursor.kind == CXCursor_ClassDecl ||
6485 cursor.kind == CXCursor_ClassTemplate ||
6486 cursor.kind == CXCursor_ClassTemplatePartialSpecialization) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006487 if (const Decl *D = getCursorDecl(cursor))
Guy Benyei11169dd2012-12-18 14:30:41 +00006488 if (D->hasAttr<FinalAttr>())
6489 HasContextSensitiveKeywords = true;
6490 }
6491 }
Argyrios Kyrtzidis990b3862013-06-04 18:24:30 +00006492
6493 // Don't override a property annotation with its getter/setter method.
6494 if (cursor.kind == CXCursor_ObjCInstanceMethodDecl &&
6495 parent.kind == CXCursor_ObjCPropertyDecl)
6496 return CXChildVisit_Continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00006497
6498 if (clang_isPreprocessing(cursor.kind)) {
6499 // Items in the preprocessing record are kept separate from items in
6500 // declarations, so we keep a separate token index.
6501 unsigned SavedTokIdx = TokIdx;
6502 TokIdx = PreprocessingTokIdx;
6503
6504 // Skip tokens up until we catch up to the beginning of the preprocessing
6505 // entry.
6506 while (MoreTokens()) {
6507 const unsigned I = NextToken();
6508 SourceLocation TokLoc = GetTokenLoc(I);
6509 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
6510 case RangeBefore:
6511 AdvanceToken();
6512 continue;
6513 case RangeAfter:
6514 case RangeOverlap:
6515 break;
6516 }
6517 break;
6518 }
6519
6520 // Look at all of the tokens within this range.
6521 while (MoreTokens()) {
6522 const unsigned I = NextToken();
6523 SourceLocation TokLoc = GetTokenLoc(I);
6524 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
6525 case RangeBefore:
6526 llvm_unreachable("Infeasible");
6527 case RangeAfter:
6528 break;
6529 case RangeOverlap:
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00006530 // For macro expansions, just note where the beginning of the macro
6531 // expansion occurs.
6532 if (cursor.kind == CXCursor_MacroExpansion) {
6533 if (TokLoc == cursorRange.getBegin())
6534 Cursors[I] = cursor;
6535 AdvanceToken();
6536 break;
6537 }
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006538 // We may have already annotated macro names inside macro definitions.
6539 if (Cursors[I].kind != CXCursor_MacroExpansion)
6540 Cursors[I] = cursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00006541 AdvanceToken();
Guy Benyei11169dd2012-12-18 14:30:41 +00006542 continue;
6543 }
6544 break;
6545 }
6546
6547 // Save the preprocessing token index; restore the non-preprocessing
6548 // token index.
6549 PreprocessingTokIdx = TokIdx;
6550 TokIdx = SavedTokIdx;
6551 return CXChildVisit_Recurse;
6552 }
6553
6554 if (cursorRange.isInvalid())
6555 return CXChildVisit_Continue;
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006556
6557 unsigned BeforeReachingCursorIdx = NextToken();
Guy Benyei11169dd2012-12-18 14:30:41 +00006558 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00006559 const enum CXCursorKind K = clang_getCursorKind(parent);
6560 const CXCursor updateC =
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006561 (clang_isInvalid(K) || K == CXCursor_TranslationUnit ||
6562 // Attributes are annotated out-of-order, skip tokens until we reach it.
6563 clang_isAttribute(cursor.kind))
Guy Benyei11169dd2012-12-18 14:30:41 +00006564 ? clang_getNullCursor() : parent;
6565
6566 annotateAndAdvanceTokens(updateC, RangeBefore, cursorRange);
6567
6568 // Avoid having the cursor of an expression "overwrite" the annotation of the
6569 // variable declaration that it belongs to.
6570 // This can happen for C++ constructor expressions whose range generally
6571 // include the variable declaration, e.g.:
6572 // MyCXXClass foo; // Make sure we don't annotate 'foo' as a CallExpr cursor.
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006573 if (clang_isExpression(cursorK) && MoreTokens()) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006574 const Expr *E = getCursorExpr(cursor);
Dmitri Gribenkoa1691182013-01-26 18:12:08 +00006575 if (const Decl *D = getCursorParentDecl(cursor)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006576 const unsigned I = NextToken();
6577 if (E->getLocStart().isValid() && D->getLocation().isValid() &&
6578 E->getLocStart() == D->getLocation() &&
6579 E->getLocStart() == GetTokenLoc(I)) {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006580 updateCursorAnnotation(Cursors[I], updateC);
Guy Benyei11169dd2012-12-18 14:30:41 +00006581 AdvanceToken();
6582 }
6583 }
6584 }
6585
6586 // Before recursing into the children keep some state that we are going
6587 // to use in the AnnotateTokensWorker::postVisitChildren callback to do some
6588 // extra work after the child nodes are visited.
6589 // Note that we don't call VisitChildren here to avoid traversing statements
6590 // code-recursively which can blow the stack.
6591
6592 PostChildrenInfo Info;
6593 Info.Cursor = cursor;
6594 Info.CursorRange = cursorRange;
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006595 Info.BeforeReachingCursorIdx = BeforeReachingCursorIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00006596 Info.BeforeChildrenTokenIdx = NextToken();
6597 PostChildrenInfos.push_back(Info);
6598
6599 return CXChildVisit_Recurse;
6600}
6601
6602bool AnnotateTokensWorker::postVisitChildren(CXCursor cursor) {
6603 if (PostChildrenInfos.empty())
6604 return false;
6605 const PostChildrenInfo &Info = PostChildrenInfos.back();
6606 if (!clang_equalCursors(Info.Cursor, cursor))
6607 return false;
6608
6609 const unsigned BeforeChildren = Info.BeforeChildrenTokenIdx;
6610 const unsigned AfterChildren = NextToken();
6611 SourceRange cursorRange = Info.CursorRange;
6612
6613 // Scan the tokens that are at the end of the cursor, but are not captured
6614 // but the child cursors.
6615 annotateAndAdvanceTokens(cursor, RangeOverlap, cursorRange);
6616
6617 // Scan the tokens that are at the beginning of the cursor, but are not
6618 // capture by the child cursors.
6619 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
6620 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
6621 break;
6622
6623 Cursors[I] = cursor;
6624 }
6625
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006626 // Attributes are annotated out-of-order, rewind TokIdx to when we first
6627 // encountered the attribute cursor.
6628 if (clang_isAttribute(cursor.kind))
6629 TokIdx = Info.BeforeReachingCursorIdx;
6630
Guy Benyei11169dd2012-12-18 14:30:41 +00006631 PostChildrenInfos.pop_back();
6632 return false;
6633}
6634
6635static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
6636 CXCursor parent,
6637 CXClientData client_data) {
6638 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
6639}
6640
6641static bool AnnotateTokensPostChildrenVisitor(CXCursor cursor,
6642 CXClientData client_data) {
6643 return static_cast<AnnotateTokensWorker*>(client_data)->
6644 postVisitChildren(cursor);
6645}
6646
6647namespace {
6648
6649/// \brief Uses the macro expansions in the preprocessing record to find
6650/// and mark tokens that are macro arguments. This info is used by the
6651/// AnnotateTokensWorker.
6652class MarkMacroArgTokensVisitor {
6653 SourceManager &SM;
6654 CXToken *Tokens;
6655 unsigned NumTokens;
6656 unsigned CurIdx;
6657
6658public:
6659 MarkMacroArgTokensVisitor(SourceManager &SM,
6660 CXToken *tokens, unsigned numTokens)
6661 : SM(SM), Tokens(tokens), NumTokens(numTokens), CurIdx(0) { }
6662
6663 CXChildVisitResult visit(CXCursor cursor, CXCursor parent) {
6664 if (cursor.kind != CXCursor_MacroExpansion)
6665 return CXChildVisit_Continue;
6666
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00006667 SourceRange macroRange = getCursorMacroExpansion(cursor).getSourceRange();
Guy Benyei11169dd2012-12-18 14:30:41 +00006668 if (macroRange.getBegin() == macroRange.getEnd())
6669 return CXChildVisit_Continue; // it's not a function macro.
6670
6671 for (; CurIdx < NumTokens; ++CurIdx) {
6672 if (!SM.isBeforeInTranslationUnit(getTokenLoc(CurIdx),
6673 macroRange.getBegin()))
6674 break;
6675 }
6676
6677 if (CurIdx == NumTokens)
6678 return CXChildVisit_Break;
6679
6680 for (; CurIdx < NumTokens; ++CurIdx) {
6681 SourceLocation tokLoc = getTokenLoc(CurIdx);
6682 if (!SM.isBeforeInTranslationUnit(tokLoc, macroRange.getEnd()))
6683 break;
6684
6685 setFunctionMacroTokenLoc(CurIdx, SM.getMacroArgExpandedLocation(tokLoc));
6686 }
6687
6688 if (CurIdx == NumTokens)
6689 return CXChildVisit_Break;
6690
6691 return CXChildVisit_Continue;
6692 }
6693
6694private:
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006695 CXToken &getTok(unsigned Idx) {
6696 assert(Idx < NumTokens);
6697 return Tokens[Idx];
6698 }
6699 const CXToken &getTok(unsigned Idx) const {
6700 assert(Idx < NumTokens);
6701 return Tokens[Idx];
6702 }
6703
Guy Benyei11169dd2012-12-18 14:30:41 +00006704 SourceLocation getTokenLoc(unsigned tokI) {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006705 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[1]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006706 }
6707
6708 void setFunctionMacroTokenLoc(unsigned tokI, SourceLocation loc) {
6709 // The third field is reserved and currently not used. Use it here
6710 // to mark macro arg expanded tokens with their expanded locations.
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006711 getTok(tokI).int_data[3] = loc.getRawEncoding();
Guy Benyei11169dd2012-12-18 14:30:41 +00006712 }
6713};
6714
6715} // end anonymous namespace
6716
6717static CXChildVisitResult
6718MarkMacroArgTokensVisitorDelegate(CXCursor cursor, CXCursor parent,
6719 CXClientData client_data) {
6720 return static_cast<MarkMacroArgTokensVisitor*>(client_data)->visit(cursor,
6721 parent);
6722}
6723
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006724/// \brief Used by \c annotatePreprocessorTokens.
6725/// \returns true if lexing was finished, false otherwise.
6726static bool lexNext(Lexer &Lex, Token &Tok,
6727 unsigned &NextIdx, unsigned NumTokens) {
6728 if (NextIdx >= NumTokens)
6729 return true;
6730
6731 ++NextIdx;
6732 Lex.LexFromRawLexer(Tok);
Alexander Kornienko1a9f1842015-12-28 15:24:08 +00006733 return Tok.is(tok::eof);
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006734}
6735
Guy Benyei11169dd2012-12-18 14:30:41 +00006736static void annotatePreprocessorTokens(CXTranslationUnit TU,
6737 SourceRange RegionOfInterest,
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006738 CXCursor *Cursors,
6739 CXToken *Tokens,
6740 unsigned NumTokens) {
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006741 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006742
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00006743 Preprocessor &PP = CXXUnit->getPreprocessor();
Guy Benyei11169dd2012-12-18 14:30:41 +00006744 SourceManager &SourceMgr = CXXUnit->getSourceManager();
6745 std::pair<FileID, unsigned> BeginLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00006746 = SourceMgr.getDecomposedSpellingLoc(RegionOfInterest.getBegin());
Guy Benyei11169dd2012-12-18 14:30:41 +00006747 std::pair<FileID, unsigned> EndLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00006748 = SourceMgr.getDecomposedSpellingLoc(RegionOfInterest.getEnd());
Guy Benyei11169dd2012-12-18 14:30:41 +00006749
6750 if (BeginLocInfo.first != EndLocInfo.first)
6751 return;
6752
6753 StringRef Buffer;
6754 bool Invalid = false;
6755 Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
6756 if (Buffer.empty() || Invalid)
6757 return;
6758
6759 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
6760 CXXUnit->getASTContext().getLangOpts(),
6761 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
6762 Buffer.end());
6763 Lex.SetCommentRetentionState(true);
6764
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006765 unsigned NextIdx = 0;
Guy Benyei11169dd2012-12-18 14:30:41 +00006766 // Lex tokens in raw mode until we hit the end of the range, to avoid
6767 // entering #includes or expanding macros.
6768 while (true) {
6769 Token Tok;
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006770 if (lexNext(Lex, Tok, NextIdx, NumTokens))
6771 break;
6772 unsigned TokIdx = NextIdx-1;
6773 assert(Tok.getLocation() ==
6774 SourceLocation::getFromRawEncoding(Tokens[TokIdx].int_data[1]));
Guy Benyei11169dd2012-12-18 14:30:41 +00006775
6776 reprocess:
6777 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006778 // We have found a preprocessing directive. Annotate the tokens
6779 // appropriately.
Guy Benyei11169dd2012-12-18 14:30:41 +00006780 //
6781 // FIXME: Some simple tests here could identify macro definitions and
6782 // #undefs, to provide specific cursor kinds for those.
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006783
6784 SourceLocation BeginLoc = Tok.getLocation();
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00006785 if (lexNext(Lex, Tok, NextIdx, NumTokens))
6786 break;
6787
Craig Topper69186e72014-06-08 08:38:04 +00006788 MacroInfo *MI = nullptr;
Alp Toker2d57cea2014-05-17 04:53:25 +00006789 if (Tok.is(tok::raw_identifier) && Tok.getRawIdentifier() == "define") {
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00006790 if (lexNext(Lex, Tok, NextIdx, NumTokens))
6791 break;
6792
6793 if (Tok.is(tok::raw_identifier)) {
Alp Toker2d57cea2014-05-17 04:53:25 +00006794 IdentifierInfo &II =
6795 PP.getIdentifierTable().get(Tok.getRawIdentifier());
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00006796 SourceLocation MappedTokLoc =
6797 CXXUnit->mapLocationToPreamble(Tok.getLocation());
6798 MI = getMacroInfo(II, MappedTokLoc, TU);
6799 }
6800 }
6801
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006802 bool finished = false;
Guy Benyei11169dd2012-12-18 14:30:41 +00006803 do {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006804 if (lexNext(Lex, Tok, NextIdx, NumTokens)) {
6805 finished = true;
6806 break;
6807 }
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00006808 // If we are in a macro definition, check if the token was ever a
6809 // macro name and annotate it if that's the case.
6810 if (MI) {
6811 SourceLocation SaveLoc = Tok.getLocation();
6812 Tok.setLocation(CXXUnit->mapLocationToPreamble(SaveLoc));
Richard Smith66a81862015-05-04 02:25:31 +00006813 MacroDefinitionRecord *MacroDef =
6814 checkForMacroInMacroDefinition(MI, Tok, TU);
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00006815 Tok.setLocation(SaveLoc);
6816 if (MacroDef)
Richard Smith66a81862015-05-04 02:25:31 +00006817 Cursors[NextIdx - 1] =
6818 MakeMacroExpansionCursor(MacroDef, Tok.getLocation(), TU);
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00006819 }
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006820 } while (!Tok.isAtStartOfLine());
6821
6822 unsigned LastIdx = finished ? NextIdx-1 : NextIdx-2;
6823 assert(TokIdx <= LastIdx);
6824 SourceLocation EndLoc =
6825 SourceLocation::getFromRawEncoding(Tokens[LastIdx].int_data[1]);
6826 CXCursor Cursor =
6827 MakePreprocessingDirectiveCursor(SourceRange(BeginLoc, EndLoc), TU);
6828
6829 for (; TokIdx <= LastIdx; ++TokIdx)
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00006830 updateCursorAnnotation(Cursors[TokIdx], Cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00006831
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006832 if (finished)
6833 break;
6834 goto reprocess;
Guy Benyei11169dd2012-12-18 14:30:41 +00006835 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006836 }
6837}
6838
6839// This gets run a separate thread to avoid stack blowout.
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00006840static void clang_annotateTokensImpl(CXTranslationUnit TU, ASTUnit *CXXUnit,
6841 CXToken *Tokens, unsigned NumTokens,
6842 CXCursor *Cursors) {
Dmitri Gribenko183436e2013-01-26 21:49:50 +00006843 CIndexer *CXXIdx = TU->CIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00006844 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing))
6845 setThreadBackgroundPriority();
6846
6847 // Determine the region of interest, which contains all of the tokens.
6848 SourceRange RegionOfInterest;
6849 RegionOfInterest.setBegin(
6850 cxloc::translateSourceLocation(clang_getTokenLocation(TU, Tokens[0])));
6851 RegionOfInterest.setEnd(
6852 cxloc::translateSourceLocation(clang_getTokenLocation(TU,
6853 Tokens[NumTokens-1])));
6854
Guy Benyei11169dd2012-12-18 14:30:41 +00006855 // Relex the tokens within the source range to look for preprocessing
6856 // directives.
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006857 annotatePreprocessorTokens(TU, RegionOfInterest, Cursors, Tokens, NumTokens);
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00006858
6859 // If begin location points inside a macro argument, set it to the expansion
6860 // location so we can have the full context when annotating semantically.
6861 {
6862 SourceManager &SM = CXXUnit->getSourceManager();
6863 SourceLocation Loc =
6864 SM.getMacroArgExpandedLocation(RegionOfInterest.getBegin());
6865 if (Loc.isMacroID())
6866 RegionOfInterest.setBegin(SM.getExpansionLoc(Loc));
6867 }
6868
Guy Benyei11169dd2012-12-18 14:30:41 +00006869 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
6870 // Search and mark tokens that are macro argument expansions.
6871 MarkMacroArgTokensVisitor Visitor(CXXUnit->getSourceManager(),
6872 Tokens, NumTokens);
6873 CursorVisitor MacroArgMarker(TU,
6874 MarkMacroArgTokensVisitorDelegate, &Visitor,
6875 /*VisitPreprocessorLast=*/true,
6876 /*VisitIncludedEntities=*/false,
6877 RegionOfInterest);
6878 MacroArgMarker.visitPreprocessedEntitiesInRegion();
6879 }
6880
6881 // Annotate all of the source locations in the region of interest that map to
6882 // a specific cursor.
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006883 AnnotateTokensWorker W(Tokens, Cursors, NumTokens, TU, RegionOfInterest);
Guy Benyei11169dd2012-12-18 14:30:41 +00006884
6885 // FIXME: We use a ridiculous stack size here because the data-recursion
6886 // algorithm uses a large stack frame than the non-data recursive version,
6887 // and AnnotationTokensWorker currently transforms the data-recursion
6888 // algorithm back into a traditional recursion by explicitly calling
6889 // VisitChildren(). We will need to remove this explicit recursive call.
6890 W.AnnotateTokens();
6891
6892 // If we ran into any entities that involve context-sensitive keywords,
6893 // take another pass through the tokens to mark them as such.
6894 if (W.hasContextSensitiveKeywords()) {
6895 for (unsigned I = 0; I != NumTokens; ++I) {
6896 if (clang_getTokenKind(Tokens[I]) != CXToken_Identifier)
6897 continue;
6898
6899 if (Cursors[I].kind == CXCursor_ObjCPropertyDecl) {
6900 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006901 if (const ObjCPropertyDecl *Property
Guy Benyei11169dd2012-12-18 14:30:41 +00006902 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(Cursors[I]))) {
6903 if (Property->getPropertyAttributesAsWritten() != 0 &&
6904 llvm::StringSwitch<bool>(II->getName())
6905 .Case("readonly", true)
6906 .Case("assign", true)
6907 .Case("unsafe_unretained", true)
6908 .Case("readwrite", true)
6909 .Case("retain", true)
6910 .Case("copy", true)
6911 .Case("nonatomic", true)
6912 .Case("atomic", true)
6913 .Case("getter", true)
6914 .Case("setter", true)
6915 .Case("strong", true)
6916 .Case("weak", true)
Manman Ren04fd4d82016-05-31 23:22:04 +00006917 .Case("class", true)
Guy Benyei11169dd2012-12-18 14:30:41 +00006918 .Default(false))
6919 Tokens[I].int_data[0] = CXToken_Keyword;
6920 }
6921 continue;
6922 }
6923
6924 if (Cursors[I].kind == CXCursor_ObjCInstanceMethodDecl ||
6925 Cursors[I].kind == CXCursor_ObjCClassMethodDecl) {
6926 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
6927 if (llvm::StringSwitch<bool>(II->getName())
6928 .Case("in", true)
6929 .Case("out", true)
6930 .Case("inout", true)
6931 .Case("oneway", true)
6932 .Case("bycopy", true)
6933 .Case("byref", true)
6934 .Default(false))
6935 Tokens[I].int_data[0] = CXToken_Keyword;
6936 continue;
6937 }
6938
6939 if (Cursors[I].kind == CXCursor_CXXFinalAttr ||
6940 Cursors[I].kind == CXCursor_CXXOverrideAttr) {
6941 Tokens[I].int_data[0] = CXToken_Keyword;
6942 continue;
6943 }
6944 }
6945 }
6946}
6947
Guy Benyei11169dd2012-12-18 14:30:41 +00006948void clang_annotateTokens(CXTranslationUnit TU,
6949 CXToken *Tokens, unsigned NumTokens,
6950 CXCursor *Cursors) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006951 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006952 LOG_BAD_TU(TU);
6953 return;
6954 }
6955 if (NumTokens == 0 || !Tokens || !Cursors) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00006956 LOG_FUNC_SECTION { *Log << "<null input>"; }
Guy Benyei11169dd2012-12-18 14:30:41 +00006957 return;
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00006958 }
6959
6960 LOG_FUNC_SECTION {
6961 *Log << TU << ' ';
6962 CXSourceLocation bloc = clang_getTokenLocation(TU, Tokens[0]);
6963 CXSourceLocation eloc = clang_getTokenLocation(TU, Tokens[NumTokens-1]);
6964 *Log << clang_getRange(bloc, eloc);
6965 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006966
6967 // Any token we don't specifically annotate will have a NULL cursor.
6968 CXCursor C = clang_getNullCursor();
6969 for (unsigned I = 0; I != NumTokens; ++I)
6970 Cursors[I] = C;
6971
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006972 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006973 if (!CXXUnit)
6974 return;
6975
6976 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00006977
6978 auto AnnotateTokensImpl = [=]() {
6979 clang_annotateTokensImpl(TU, CXXUnit, Tokens, NumTokens, Cursors);
6980 };
Guy Benyei11169dd2012-12-18 14:30:41 +00006981 llvm::CrashRecoveryContext CRC;
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00006982 if (!RunSafely(CRC, AnnotateTokensImpl, GetSafetyThreadStackSize() * 2)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006983 fprintf(stderr, "libclang: crash detected while annotating tokens\n");
6984 }
6985}
6986
Guy Benyei11169dd2012-12-18 14:30:41 +00006987//===----------------------------------------------------------------------===//
6988// Operations for querying linkage of a cursor.
6989//===----------------------------------------------------------------------===//
6990
Guy Benyei11169dd2012-12-18 14:30:41 +00006991CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
6992 if (!clang_isDeclaration(cursor.kind))
6993 return CXLinkage_Invalid;
6994
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006995 const Decl *D = cxcursor::getCursorDecl(cursor);
6996 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
Rafael Espindola3ae00052013-05-13 00:12:11 +00006997 switch (ND->getLinkageInternal()) {
Rafael Espindola50df3a02013-05-25 17:16:20 +00006998 case NoLinkage:
6999 case VisibleNoLinkage: return CXLinkage_NoLinkage;
Guy Benyei11169dd2012-12-18 14:30:41 +00007000 case InternalLinkage: return CXLinkage_Internal;
7001 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
7002 case ExternalLinkage: return CXLinkage_External;
7003 };
7004
7005 return CXLinkage_Invalid;
7006}
Guy Benyei11169dd2012-12-18 14:30:41 +00007007
7008//===----------------------------------------------------------------------===//
Ehsan Akhgarib743de72016-05-31 15:55:51 +00007009// Operations for querying visibility of a cursor.
7010//===----------------------------------------------------------------------===//
7011
Ehsan Akhgarib743de72016-05-31 15:55:51 +00007012CXVisibilityKind clang_getCursorVisibility(CXCursor cursor) {
7013 if (!clang_isDeclaration(cursor.kind))
7014 return CXVisibility_Invalid;
7015
7016 const Decl *D = cxcursor::getCursorDecl(cursor);
7017 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
7018 switch (ND->getVisibility()) {
7019 case HiddenVisibility: return CXVisibility_Hidden;
7020 case ProtectedVisibility: return CXVisibility_Protected;
7021 case DefaultVisibility: return CXVisibility_Default;
7022 };
7023
7024 return CXVisibility_Invalid;
7025}
Ehsan Akhgarib743de72016-05-31 15:55:51 +00007026
7027//===----------------------------------------------------------------------===//
Guy Benyei11169dd2012-12-18 14:30:41 +00007028// Operations for querying language of a cursor.
7029//===----------------------------------------------------------------------===//
7030
7031static CXLanguageKind getDeclLanguage(const Decl *D) {
7032 if (!D)
7033 return CXLanguage_C;
7034
7035 switch (D->getKind()) {
7036 default:
7037 break;
7038 case Decl::ImplicitParam:
7039 case Decl::ObjCAtDefsField:
7040 case Decl::ObjCCategory:
7041 case Decl::ObjCCategoryImpl:
7042 case Decl::ObjCCompatibleAlias:
7043 case Decl::ObjCImplementation:
7044 case Decl::ObjCInterface:
7045 case Decl::ObjCIvar:
7046 case Decl::ObjCMethod:
7047 case Decl::ObjCProperty:
7048 case Decl::ObjCPropertyImpl:
7049 case Decl::ObjCProtocol:
Douglas Gregor85f3f952015-07-07 03:57:15 +00007050 case Decl::ObjCTypeParam:
Guy Benyei11169dd2012-12-18 14:30:41 +00007051 return CXLanguage_ObjC;
7052 case Decl::CXXConstructor:
7053 case Decl::CXXConversion:
7054 case Decl::CXXDestructor:
7055 case Decl::CXXMethod:
7056 case Decl::CXXRecord:
7057 case Decl::ClassTemplate:
7058 case Decl::ClassTemplatePartialSpecialization:
7059 case Decl::ClassTemplateSpecialization:
7060 case Decl::Friend:
7061 case Decl::FriendTemplate:
7062 case Decl::FunctionTemplate:
7063 case Decl::LinkageSpec:
7064 case Decl::Namespace:
7065 case Decl::NamespaceAlias:
7066 case Decl::NonTypeTemplateParm:
7067 case Decl::StaticAssert:
7068 case Decl::TemplateTemplateParm:
7069 case Decl::TemplateTypeParm:
7070 case Decl::UnresolvedUsingTypename:
7071 case Decl::UnresolvedUsingValue:
7072 case Decl::Using:
7073 case Decl::UsingDirective:
7074 case Decl::UsingShadow:
7075 return CXLanguage_CPlusPlus;
7076 }
7077
7078 return CXLanguage_C;
7079}
7080
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007081static CXAvailabilityKind getCursorAvailabilityForDecl(const Decl *D) {
7082 if (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted())
Manuel Klimek8e3a7ed2015-09-25 17:53:16 +00007083 return CXAvailability_NotAvailable;
Guy Benyei11169dd2012-12-18 14:30:41 +00007084
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007085 switch (D->getAvailability()) {
7086 case AR_Available:
7087 case AR_NotYetIntroduced:
7088 if (const EnumConstantDecl *EnumConst = dyn_cast<EnumConstantDecl>(D))
Benjamin Kramer656363d2013-10-15 18:53:18 +00007089 return getCursorAvailabilityForDecl(
7090 cast<Decl>(EnumConst->getDeclContext()));
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007091 return CXAvailability_Available;
7092
7093 case AR_Deprecated:
7094 return CXAvailability_Deprecated;
7095
7096 case AR_Unavailable:
7097 return CXAvailability_NotAvailable;
7098 }
Benjamin Kramer656363d2013-10-15 18:53:18 +00007099
7100 llvm_unreachable("Unknown availability kind!");
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007101}
7102
Guy Benyei11169dd2012-12-18 14:30:41 +00007103enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
7104 if (clang_isDeclaration(cursor.kind))
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007105 if (const Decl *D = cxcursor::getCursorDecl(cursor))
7106 return getCursorAvailabilityForDecl(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00007107
7108 return CXAvailability_Available;
7109}
7110
7111static CXVersion convertVersion(VersionTuple In) {
7112 CXVersion Out = { -1, -1, -1 };
7113 if (In.empty())
7114 return Out;
7115
7116 Out.Major = In.getMajor();
7117
NAKAMURA Takumic2b5d1f2013-02-21 02:32:34 +00007118 Optional<unsigned> Minor = In.getMinor();
7119 if (Minor.hasValue())
Guy Benyei11169dd2012-12-18 14:30:41 +00007120 Out.Minor = *Minor;
7121 else
7122 return Out;
7123
NAKAMURA Takumic2b5d1f2013-02-21 02:32:34 +00007124 Optional<unsigned> Subminor = In.getSubminor();
7125 if (Subminor.hasValue())
Guy Benyei11169dd2012-12-18 14:30:41 +00007126 Out.Subminor = *Subminor;
7127
7128 return Out;
7129}
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007130
7131static int getCursorPlatformAvailabilityForDecl(const Decl *D,
7132 int *always_deprecated,
7133 CXString *deprecated_message,
7134 int *always_unavailable,
7135 CXString *unavailable_message,
7136 CXPlatformAvailability *availability,
7137 int availability_size) {
7138 bool HadAvailAttr = false;
7139 int N = 0;
Aaron Ballmanb97112e2014-03-08 22:19:01 +00007140 for (auto A : D->attrs()) {
7141 if (DeprecatedAttr *Deprecated = dyn_cast<DeprecatedAttr>(A)) {
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007142 HadAvailAttr = true;
7143 if (always_deprecated)
7144 *always_deprecated = 1;
Nico Weberaacf0312014-04-24 05:16:45 +00007145 if (deprecated_message) {
Argyrios Kyrtzidisedfe07f2014-04-24 06:05:40 +00007146 clang_disposeString(*deprecated_message);
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007147 *deprecated_message = cxstring::createDup(Deprecated->getMessage());
Nico Weberaacf0312014-04-24 05:16:45 +00007148 }
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007149 continue;
7150 }
7151
Aaron Ballmanb97112e2014-03-08 22:19:01 +00007152 if (UnavailableAttr *Unavailable = dyn_cast<UnavailableAttr>(A)) {
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007153 HadAvailAttr = true;
7154 if (always_unavailable)
7155 *always_unavailable = 1;
7156 if (unavailable_message) {
Argyrios Kyrtzidisedfe07f2014-04-24 06:05:40 +00007157 clang_disposeString(*unavailable_message);
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007158 *unavailable_message = cxstring::createDup(Unavailable->getMessage());
7159 }
7160 continue;
7161 }
7162
Aaron Ballmanb97112e2014-03-08 22:19:01 +00007163 if (AvailabilityAttr *Avail = dyn_cast<AvailabilityAttr>(A)) {
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007164 HadAvailAttr = true;
7165 if (N < availability_size) {
7166 availability[N].Platform
7167 = cxstring::createDup(Avail->getPlatform()->getName());
7168 availability[N].Introduced = convertVersion(Avail->getIntroduced());
7169 availability[N].Deprecated = convertVersion(Avail->getDeprecated());
7170 availability[N].Obsoleted = convertVersion(Avail->getObsoleted());
7171 availability[N].Unavailable = Avail->getUnavailable();
7172 availability[N].Message = cxstring::createDup(Avail->getMessage());
7173 }
7174 ++N;
7175 }
7176 }
7177
7178 if (!HadAvailAttr)
7179 if (const EnumConstantDecl *EnumConst = dyn_cast<EnumConstantDecl>(D))
7180 return getCursorPlatformAvailabilityForDecl(
7181 cast<Decl>(EnumConst->getDeclContext()),
7182 always_deprecated,
7183 deprecated_message,
7184 always_unavailable,
7185 unavailable_message,
7186 availability,
7187 availability_size);
Guy Benyei11169dd2012-12-18 14:30:41 +00007188
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007189 return N;
7190}
7191
Guy Benyei11169dd2012-12-18 14:30:41 +00007192int clang_getCursorPlatformAvailability(CXCursor cursor,
7193 int *always_deprecated,
7194 CXString *deprecated_message,
7195 int *always_unavailable,
7196 CXString *unavailable_message,
7197 CXPlatformAvailability *availability,
7198 int availability_size) {
7199 if (always_deprecated)
7200 *always_deprecated = 0;
7201 if (deprecated_message)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00007202 *deprecated_message = cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00007203 if (always_unavailable)
7204 *always_unavailable = 0;
7205 if (unavailable_message)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00007206 *unavailable_message = cxstring::createEmpty();
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007207
Guy Benyei11169dd2012-12-18 14:30:41 +00007208 if (!clang_isDeclaration(cursor.kind))
7209 return 0;
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007210
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007211 const Decl *D = cxcursor::getCursorDecl(cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00007212 if (!D)
7213 return 0;
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007214
7215 return getCursorPlatformAvailabilityForDecl(D, always_deprecated,
7216 deprecated_message,
7217 always_unavailable,
7218 unavailable_message,
7219 availability,
7220 availability_size);
Guy Benyei11169dd2012-12-18 14:30:41 +00007221}
7222
7223void clang_disposeCXPlatformAvailability(CXPlatformAvailability *availability) {
7224 clang_disposeString(availability->Platform);
7225 clang_disposeString(availability->Message);
7226}
7227
7228CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
7229 if (clang_isDeclaration(cursor.kind))
7230 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
7231
7232 return CXLanguage_Invalid;
7233}
7234
7235 /// \brief If the given cursor is the "templated" declaration
7236 /// descibing a class or function template, return the class or
7237 /// function template.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007238static const Decl *maybeGetTemplateCursor(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007239 if (!D)
Craig Topper69186e72014-06-08 08:38:04 +00007240 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007241
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007242 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00007243 if (FunctionTemplateDecl *FunTmpl = FD->getDescribedFunctionTemplate())
7244 return FunTmpl;
7245
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007246 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00007247 if (ClassTemplateDecl *ClassTmpl = RD->getDescribedClassTemplate())
7248 return ClassTmpl;
7249
7250 return D;
7251}
7252
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00007253
7254enum CX_StorageClass clang_Cursor_getStorageClass(CXCursor C) {
7255 StorageClass sc = SC_None;
7256 const Decl *D = getCursorDecl(C);
7257 if (D) {
7258 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7259 sc = FD->getStorageClass();
7260 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7261 sc = VD->getStorageClass();
7262 } else {
7263 return CX_SC_Invalid;
7264 }
7265 } else {
7266 return CX_SC_Invalid;
7267 }
7268 switch (sc) {
7269 case SC_None:
7270 return CX_SC_None;
7271 case SC_Extern:
7272 return CX_SC_Extern;
7273 case SC_Static:
7274 return CX_SC_Static;
7275 case SC_PrivateExtern:
7276 return CX_SC_PrivateExtern;
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00007277 case SC_Auto:
7278 return CX_SC_Auto;
7279 case SC_Register:
7280 return CX_SC_Register;
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00007281 }
Kaelyn Takataab61e702014-10-15 18:03:26 +00007282 llvm_unreachable("Unhandled storage class!");
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00007283}
7284
Guy Benyei11169dd2012-12-18 14:30:41 +00007285CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
7286 if (clang_isDeclaration(cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007287 if (const Decl *D = getCursorDecl(cursor)) {
7288 const DeclContext *DC = D->getDeclContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00007289 if (!DC)
7290 return clang_getNullCursor();
7291
7292 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
7293 getCursorTU(cursor));
7294 }
7295 }
7296
7297 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007298 if (const Decl *D = getCursorDecl(cursor))
Guy Benyei11169dd2012-12-18 14:30:41 +00007299 return MakeCXCursor(D, getCursorTU(cursor));
7300 }
7301
7302 return clang_getNullCursor();
7303}
7304
7305CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
7306 if (clang_isDeclaration(cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007307 if (const Decl *D = getCursorDecl(cursor)) {
7308 const DeclContext *DC = D->getLexicalDeclContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00007309 if (!DC)
7310 return clang_getNullCursor();
7311
7312 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
7313 getCursorTU(cursor));
7314 }
7315 }
7316
7317 // FIXME: Note that we can't easily compute the lexical context of a
7318 // statement or expression, so we return nothing.
7319 return clang_getNullCursor();
7320}
7321
7322CXFile clang_getIncludedFile(CXCursor cursor) {
7323 if (cursor.kind != CXCursor_InclusionDirective)
Craig Topper69186e72014-06-08 08:38:04 +00007324 return nullptr;
7325
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00007326 const InclusionDirective *ID = getCursorInclusionDirective(cursor);
Dmitri Gribenkof9304482013-01-23 15:56:07 +00007327 return const_cast<FileEntry *>(ID->getFile());
Guy Benyei11169dd2012-12-18 14:30:41 +00007328}
7329
Argyrios Kyrtzidis9adfd8a2013-04-18 22:15:49 +00007330unsigned clang_Cursor_getObjCPropertyAttributes(CXCursor C, unsigned reserved) {
7331 if (C.kind != CXCursor_ObjCPropertyDecl)
7332 return CXObjCPropertyAttr_noattr;
7333
7334 unsigned Result = CXObjCPropertyAttr_noattr;
7335 const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(getCursorDecl(C));
7336 ObjCPropertyDecl::PropertyAttributeKind Attr =
7337 PD->getPropertyAttributesAsWritten();
7338
7339#define SET_CXOBJCPROP_ATTR(A) \
7340 if (Attr & ObjCPropertyDecl::OBJC_PR_##A) \
7341 Result |= CXObjCPropertyAttr_##A
7342 SET_CXOBJCPROP_ATTR(readonly);
7343 SET_CXOBJCPROP_ATTR(getter);
7344 SET_CXOBJCPROP_ATTR(assign);
7345 SET_CXOBJCPROP_ATTR(readwrite);
7346 SET_CXOBJCPROP_ATTR(retain);
7347 SET_CXOBJCPROP_ATTR(copy);
7348 SET_CXOBJCPROP_ATTR(nonatomic);
7349 SET_CXOBJCPROP_ATTR(setter);
7350 SET_CXOBJCPROP_ATTR(atomic);
7351 SET_CXOBJCPROP_ATTR(weak);
7352 SET_CXOBJCPROP_ATTR(strong);
7353 SET_CXOBJCPROP_ATTR(unsafe_unretained);
Manman Ren04fd4d82016-05-31 23:22:04 +00007354 SET_CXOBJCPROP_ATTR(class);
Argyrios Kyrtzidis9adfd8a2013-04-18 22:15:49 +00007355#undef SET_CXOBJCPROP_ATTR
7356
7357 return Result;
7358}
7359
Argyrios Kyrtzidis9d9bc012013-04-18 23:29:12 +00007360unsigned clang_Cursor_getObjCDeclQualifiers(CXCursor C) {
7361 if (!clang_isDeclaration(C.kind))
7362 return CXObjCDeclQualifier_None;
7363
7364 Decl::ObjCDeclQualifier QT = Decl::OBJC_TQ_None;
7365 const Decl *D = getCursorDecl(C);
7366 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
7367 QT = MD->getObjCDeclQualifier();
7368 else if (const ParmVarDecl *PD = dyn_cast<ParmVarDecl>(D))
7369 QT = PD->getObjCDeclQualifier();
7370 if (QT == Decl::OBJC_TQ_None)
7371 return CXObjCDeclQualifier_None;
7372
7373 unsigned Result = CXObjCDeclQualifier_None;
7374 if (QT & Decl::OBJC_TQ_In) Result |= CXObjCDeclQualifier_In;
7375 if (QT & Decl::OBJC_TQ_Inout) Result |= CXObjCDeclQualifier_Inout;
7376 if (QT & Decl::OBJC_TQ_Out) Result |= CXObjCDeclQualifier_Out;
7377 if (QT & Decl::OBJC_TQ_Bycopy) Result |= CXObjCDeclQualifier_Bycopy;
7378 if (QT & Decl::OBJC_TQ_Byref) Result |= CXObjCDeclQualifier_Byref;
7379 if (QT & Decl::OBJC_TQ_Oneway) Result |= CXObjCDeclQualifier_Oneway;
7380
7381 return Result;
7382}
7383
Argyrios Kyrtzidis7b50fc52013-07-05 20:44:37 +00007384unsigned clang_Cursor_isObjCOptional(CXCursor C) {
7385 if (!clang_isDeclaration(C.kind))
7386 return 0;
7387
7388 const Decl *D = getCursorDecl(C);
7389 if (const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D))
7390 return PD->getPropertyImplementation() == ObjCPropertyDecl::Optional;
7391 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
7392 return MD->getImplementationControl() == ObjCMethodDecl::Optional;
7393
7394 return 0;
7395}
7396
Argyrios Kyrtzidis23814e42013-04-18 23:53:05 +00007397unsigned clang_Cursor_isVariadic(CXCursor C) {
7398 if (!clang_isDeclaration(C.kind))
7399 return 0;
7400
7401 const Decl *D = getCursorDecl(C);
7402 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
7403 return FD->isVariadic();
7404 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
7405 return MD->isVariadic();
7406
7407 return 0;
7408}
7409
Guy Benyei11169dd2012-12-18 14:30:41 +00007410CXSourceRange clang_Cursor_getCommentRange(CXCursor C) {
7411 if (!clang_isDeclaration(C.kind))
7412 return clang_getNullRange();
7413
7414 const Decl *D = getCursorDecl(C);
7415 ASTContext &Context = getCursorContext(C);
7416 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
7417 if (!RC)
7418 return clang_getNullRange();
7419
7420 return cxloc::translateSourceRange(Context, RC->getSourceRange());
7421}
7422
7423CXString clang_Cursor_getRawCommentText(CXCursor C) {
7424 if (!clang_isDeclaration(C.kind))
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00007425 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00007426
7427 const Decl *D = getCursorDecl(C);
7428 ASTContext &Context = getCursorContext(C);
7429 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
7430 StringRef RawText = RC ? RC->getRawText(Context.getSourceManager()) :
7431 StringRef();
7432
7433 // Don't duplicate the string because RawText points directly into source
7434 // code.
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00007435 return cxstring::createRef(RawText);
Guy Benyei11169dd2012-12-18 14:30:41 +00007436}
7437
7438CXString clang_Cursor_getBriefCommentText(CXCursor C) {
7439 if (!clang_isDeclaration(C.kind))
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00007440 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00007441
7442 const Decl *D = getCursorDecl(C);
7443 const ASTContext &Context = getCursorContext(C);
7444 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
7445
7446 if (RC) {
7447 StringRef BriefText = RC->getBriefText(Context);
7448
7449 // Don't duplicate the string because RawComment ensures that this memory
7450 // will not go away.
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00007451 return cxstring::createRef(BriefText);
Guy Benyei11169dd2012-12-18 14:30:41 +00007452 }
7453
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00007454 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00007455}
7456
Guy Benyei11169dd2012-12-18 14:30:41 +00007457CXModule clang_Cursor_getModule(CXCursor C) {
7458 if (C.kind == CXCursor_ModuleImportDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007459 if (const ImportDecl *ImportD =
7460 dyn_cast_or_null<ImportDecl>(getCursorDecl(C)))
Guy Benyei11169dd2012-12-18 14:30:41 +00007461 return ImportD->getImportedModule();
7462 }
7463
Craig Topper69186e72014-06-08 08:38:04 +00007464 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007465}
7466
Argyrios Kyrtzidisf6d49c32014-05-14 23:14:37 +00007467CXModule clang_getModuleForFile(CXTranslationUnit TU, CXFile File) {
7468 if (isNotUsableTU(TU)) {
7469 LOG_BAD_TU(TU);
7470 return nullptr;
7471 }
7472 if (!File)
7473 return nullptr;
7474 FileEntry *FE = static_cast<FileEntry *>(File);
7475
7476 ASTUnit &Unit = *cxtu::getASTUnit(TU);
7477 HeaderSearch &HS = Unit.getPreprocessor().getHeaderSearchInfo();
7478 ModuleMap::KnownHeader Header = HS.findModuleForHeader(FE);
7479
Richard Smithfeb54b62014-10-23 02:01:19 +00007480 return Header.getModule();
Argyrios Kyrtzidisf6d49c32014-05-14 23:14:37 +00007481}
7482
Argyrios Kyrtzidis12fdb9e2013-04-26 22:47:49 +00007483CXFile clang_Module_getASTFile(CXModule CXMod) {
7484 if (!CXMod)
Craig Topper69186e72014-06-08 08:38:04 +00007485 return nullptr;
Argyrios Kyrtzidis12fdb9e2013-04-26 22:47:49 +00007486 Module *Mod = static_cast<Module*>(CXMod);
7487 return const_cast<FileEntry *>(Mod->getASTFile());
7488}
7489
Guy Benyei11169dd2012-12-18 14:30:41 +00007490CXModule clang_Module_getParent(CXModule CXMod) {
7491 if (!CXMod)
Craig Topper69186e72014-06-08 08:38:04 +00007492 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007493 Module *Mod = static_cast<Module*>(CXMod);
7494 return Mod->Parent;
7495}
7496
7497CXString clang_Module_getName(CXModule CXMod) {
7498 if (!CXMod)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00007499 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00007500 Module *Mod = static_cast<Module*>(CXMod);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00007501 return cxstring::createDup(Mod->Name);
Guy Benyei11169dd2012-12-18 14:30:41 +00007502}
7503
7504CXString clang_Module_getFullName(CXModule CXMod) {
7505 if (!CXMod)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00007506 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00007507 Module *Mod = static_cast<Module*>(CXMod);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00007508 return cxstring::createDup(Mod->getFullModuleName());
Guy Benyei11169dd2012-12-18 14:30:41 +00007509}
7510
Argyrios Kyrtzidis884337f2014-05-15 04:44:25 +00007511int clang_Module_isSystem(CXModule CXMod) {
7512 if (!CXMod)
7513 return 0;
7514 Module *Mod = static_cast<Module*>(CXMod);
7515 return Mod->IsSystem;
7516}
7517
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00007518unsigned clang_Module_getNumTopLevelHeaders(CXTranslationUnit TU,
7519 CXModule CXMod) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00007520 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00007521 LOG_BAD_TU(TU);
7522 return 0;
7523 }
7524 if (!CXMod)
Guy Benyei11169dd2012-12-18 14:30:41 +00007525 return 0;
7526 Module *Mod = static_cast<Module*>(CXMod);
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00007527 FileManager &FileMgr = cxtu::getASTUnit(TU)->getFileManager();
7528 ArrayRef<const FileEntry *> TopHeaders = Mod->getTopHeaders(FileMgr);
7529 return TopHeaders.size();
Guy Benyei11169dd2012-12-18 14:30:41 +00007530}
7531
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00007532CXFile clang_Module_getTopLevelHeader(CXTranslationUnit TU,
7533 CXModule CXMod, unsigned Index) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00007534 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00007535 LOG_BAD_TU(TU);
Craig Topper69186e72014-06-08 08:38:04 +00007536 return nullptr;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00007537 }
7538 if (!CXMod)
Craig Topper69186e72014-06-08 08:38:04 +00007539 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007540 Module *Mod = static_cast<Module*>(CXMod);
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00007541 FileManager &FileMgr = cxtu::getASTUnit(TU)->getFileManager();
Guy Benyei11169dd2012-12-18 14:30:41 +00007542
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00007543 ArrayRef<const FileEntry *> TopHeaders = Mod->getTopHeaders(FileMgr);
7544 if (Index < TopHeaders.size())
7545 return const_cast<FileEntry *>(TopHeaders[Index]);
Guy Benyei11169dd2012-12-18 14:30:41 +00007546
Craig Topper69186e72014-06-08 08:38:04 +00007547 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007548}
7549
Guy Benyei11169dd2012-12-18 14:30:41 +00007550//===----------------------------------------------------------------------===//
7551// C++ AST instrospection.
7552//===----------------------------------------------------------------------===//
7553
Jonathan Coe29565352016-04-27 12:48:25 +00007554unsigned clang_CXXConstructor_isDefaultConstructor(CXCursor C) {
7555 if (!clang_isDeclaration(C.kind))
7556 return 0;
7557
7558 const Decl *D = cxcursor::getCursorDecl(C);
7559 const CXXConstructorDecl *Constructor =
7560 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
7561 return (Constructor && Constructor->isDefaultConstructor()) ? 1 : 0;
7562}
7563
7564unsigned clang_CXXConstructor_isCopyConstructor(CXCursor C) {
7565 if (!clang_isDeclaration(C.kind))
7566 return 0;
7567
7568 const Decl *D = cxcursor::getCursorDecl(C);
7569 const CXXConstructorDecl *Constructor =
7570 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
7571 return (Constructor && Constructor->isCopyConstructor()) ? 1 : 0;
7572}
7573
7574unsigned clang_CXXConstructor_isMoveConstructor(CXCursor C) {
7575 if (!clang_isDeclaration(C.kind))
7576 return 0;
7577
7578 const Decl *D = cxcursor::getCursorDecl(C);
7579 const CXXConstructorDecl *Constructor =
7580 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
7581 return (Constructor && Constructor->isMoveConstructor()) ? 1 : 0;
7582}
7583
7584unsigned clang_CXXConstructor_isConvertingConstructor(CXCursor C) {
7585 if (!clang_isDeclaration(C.kind))
7586 return 0;
7587
7588 const Decl *D = cxcursor::getCursorDecl(C);
7589 const CXXConstructorDecl *Constructor =
7590 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
7591 // Passing 'false' excludes constructors marked 'explicit'.
7592 return (Constructor && Constructor->isConvertingConstructor(false)) ? 1 : 0;
7593}
7594
Saleem Abdulrasool6ea75db2015-10-27 15:50:22 +00007595unsigned clang_CXXField_isMutable(CXCursor C) {
7596 if (!clang_isDeclaration(C.kind))
7597 return 0;
7598
7599 if (const auto D = cxcursor::getCursorDecl(C))
7600 if (const auto FD = dyn_cast_or_null<FieldDecl>(D))
7601 return FD->isMutable() ? 1 : 0;
7602 return 0;
7603}
7604
Dmitri Gribenko62770be2013-05-17 18:38:35 +00007605unsigned clang_CXXMethod_isPureVirtual(CXCursor C) {
7606 if (!clang_isDeclaration(C.kind))
7607 return 0;
7608
Dmitri Gribenko62770be2013-05-17 18:38:35 +00007609 const Decl *D = cxcursor::getCursorDecl(C);
Alp Tokera2794f92014-01-22 07:29:52 +00007610 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00007611 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Dmitri Gribenko62770be2013-05-17 18:38:35 +00007612 return (Method && Method->isVirtual() && Method->isPure()) ? 1 : 0;
7613}
7614
Dmitri Gribenkoe570ede2014-04-07 14:59:13 +00007615unsigned clang_CXXMethod_isConst(CXCursor C) {
7616 if (!clang_isDeclaration(C.kind))
7617 return 0;
7618
7619 const Decl *D = cxcursor::getCursorDecl(C);
7620 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00007621 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Dmitri Gribenkoe570ede2014-04-07 14:59:13 +00007622 return (Method && (Method->getTypeQualifiers() & Qualifiers::Const)) ? 1 : 0;
7623}
7624
Jonathan Coe29565352016-04-27 12:48:25 +00007625unsigned clang_CXXMethod_isDefaulted(CXCursor C) {
7626 if (!clang_isDeclaration(C.kind))
7627 return 0;
7628
7629 const Decl *D = cxcursor::getCursorDecl(C);
7630 const CXXMethodDecl *Method =
7631 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
7632 return (Method && Method->isDefaulted()) ? 1 : 0;
7633}
7634
Guy Benyei11169dd2012-12-18 14:30:41 +00007635unsigned clang_CXXMethod_isStatic(CXCursor C) {
7636 if (!clang_isDeclaration(C.kind))
7637 return 0;
7638
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007639 const Decl *D = cxcursor::getCursorDecl(C);
Alp Tokera2794f92014-01-22 07:29:52 +00007640 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00007641 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007642 return (Method && Method->isStatic()) ? 1 : 0;
7643}
7644
7645unsigned clang_CXXMethod_isVirtual(CXCursor C) {
7646 if (!clang_isDeclaration(C.kind))
7647 return 0;
7648
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007649 const Decl *D = cxcursor::getCursorDecl(C);
Alp Tokera2794f92014-01-22 07:29:52 +00007650 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00007651 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007652 return (Method && Method->isVirtual()) ? 1 : 0;
7653}
Guy Benyei11169dd2012-12-18 14:30:41 +00007654
7655//===----------------------------------------------------------------------===//
7656// Attribute introspection.
7657//===----------------------------------------------------------------------===//
7658
Guy Benyei11169dd2012-12-18 14:30:41 +00007659CXType clang_getIBOutletCollectionType(CXCursor C) {
7660 if (C.kind != CXCursor_IBOutletCollectionAttr)
7661 return cxtype::MakeCXType(QualType(), cxcursor::getCursorTU(C));
7662
Dmitri Gribenkoe4baea62013-01-26 18:08:08 +00007663 const IBOutletCollectionAttr *A =
Guy Benyei11169dd2012-12-18 14:30:41 +00007664 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
7665
7666 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorTU(C));
7667}
Guy Benyei11169dd2012-12-18 14:30:41 +00007668
7669//===----------------------------------------------------------------------===//
7670// Inspecting memory usage.
7671//===----------------------------------------------------------------------===//
7672
7673typedef std::vector<CXTUResourceUsageEntry> MemUsageEntries;
7674
7675static inline void createCXTUResourceUsageEntry(MemUsageEntries &entries,
7676 enum CXTUResourceUsageKind k,
7677 unsigned long amount) {
7678 CXTUResourceUsageEntry entry = { k, amount };
7679 entries.push_back(entry);
7680}
7681
Guy Benyei11169dd2012-12-18 14:30:41 +00007682const char *clang_getTUResourceUsageName(CXTUResourceUsageKind kind) {
7683 const char *str = "";
7684 switch (kind) {
7685 case CXTUResourceUsage_AST:
7686 str = "ASTContext: expressions, declarations, and types";
7687 break;
7688 case CXTUResourceUsage_Identifiers:
7689 str = "ASTContext: identifiers";
7690 break;
7691 case CXTUResourceUsage_Selectors:
7692 str = "ASTContext: selectors";
7693 break;
7694 case CXTUResourceUsage_GlobalCompletionResults:
7695 str = "Code completion: cached global results";
7696 break;
7697 case CXTUResourceUsage_SourceManagerContentCache:
7698 str = "SourceManager: content cache allocator";
7699 break;
7700 case CXTUResourceUsage_AST_SideTables:
7701 str = "ASTContext: side tables";
7702 break;
7703 case CXTUResourceUsage_SourceManager_Membuffer_Malloc:
7704 str = "SourceManager: malloc'ed memory buffers";
7705 break;
7706 case CXTUResourceUsage_SourceManager_Membuffer_MMap:
7707 str = "SourceManager: mmap'ed memory buffers";
7708 break;
7709 case CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc:
7710 str = "ExternalASTSource: malloc'ed memory buffers";
7711 break;
7712 case CXTUResourceUsage_ExternalASTSource_Membuffer_MMap:
7713 str = "ExternalASTSource: mmap'ed memory buffers";
7714 break;
7715 case CXTUResourceUsage_Preprocessor:
7716 str = "Preprocessor: malloc'ed memory";
7717 break;
7718 case CXTUResourceUsage_PreprocessingRecord:
7719 str = "Preprocessor: PreprocessingRecord";
7720 break;
7721 case CXTUResourceUsage_SourceManager_DataStructures:
7722 str = "SourceManager: data structures and tables";
7723 break;
7724 case CXTUResourceUsage_Preprocessor_HeaderSearch:
7725 str = "Preprocessor: header search tables";
7726 break;
7727 }
7728 return str;
7729}
7730
7731CXTUResourceUsage clang_getCXTUResourceUsage(CXTranslationUnit TU) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00007732 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00007733 LOG_BAD_TU(TU);
Craig Topper69186e72014-06-08 08:38:04 +00007734 CXTUResourceUsage usage = { (void*) nullptr, 0, nullptr };
Guy Benyei11169dd2012-12-18 14:30:41 +00007735 return usage;
7736 }
7737
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00007738 ASTUnit *astUnit = cxtu::getASTUnit(TU);
Ahmed Charlesb8984322014-03-07 20:03:18 +00007739 std::unique_ptr<MemUsageEntries> entries(new MemUsageEntries());
Guy Benyei11169dd2012-12-18 14:30:41 +00007740 ASTContext &astContext = astUnit->getASTContext();
7741
7742 // How much memory is used by AST nodes and types?
7743 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST,
7744 (unsigned long) astContext.getASTAllocatedMemory());
7745
7746 // How much memory is used by identifiers?
7747 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Identifiers,
7748 (unsigned long) astContext.Idents.getAllocator().getTotalMemory());
7749
7750 // How much memory is used for selectors?
7751 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Selectors,
7752 (unsigned long) astContext.Selectors.getTotalMemory());
7753
7754 // How much memory is used by ASTContext's side tables?
7755 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST_SideTables,
7756 (unsigned long) astContext.getSideTableAllocatedMemory());
7757
7758 // How much memory is used for caching global code completion results?
7759 unsigned long completionBytes = 0;
7760 if (GlobalCodeCompletionAllocator *completionAllocator =
Alp Tokerf994cef2014-07-05 03:08:06 +00007761 astUnit->getCachedCompletionAllocator().get()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007762 completionBytes = completionAllocator->getTotalMemory();
7763 }
7764 createCXTUResourceUsageEntry(*entries,
7765 CXTUResourceUsage_GlobalCompletionResults,
7766 completionBytes);
7767
7768 // How much memory is being used by SourceManager's content cache?
7769 createCXTUResourceUsageEntry(*entries,
7770 CXTUResourceUsage_SourceManagerContentCache,
7771 (unsigned long) astContext.getSourceManager().getContentCacheSize());
7772
7773 // How much memory is being used by the MemoryBuffer's in SourceManager?
7774 const SourceManager::MemoryBufferSizes &srcBufs =
7775 astUnit->getSourceManager().getMemoryBufferSizes();
7776
7777 createCXTUResourceUsageEntry(*entries,
7778 CXTUResourceUsage_SourceManager_Membuffer_Malloc,
7779 (unsigned long) srcBufs.malloc_bytes);
7780 createCXTUResourceUsageEntry(*entries,
7781 CXTUResourceUsage_SourceManager_Membuffer_MMap,
7782 (unsigned long) srcBufs.mmap_bytes);
7783 createCXTUResourceUsageEntry(*entries,
7784 CXTUResourceUsage_SourceManager_DataStructures,
7785 (unsigned long) astContext.getSourceManager()
7786 .getDataStructureSizes());
7787
7788 // How much memory is being used by the ExternalASTSource?
7789 if (ExternalASTSource *esrc = astContext.getExternalSource()) {
7790 const ExternalASTSource::MemoryBufferSizes &sizes =
7791 esrc->getMemoryBufferSizes();
7792
7793 createCXTUResourceUsageEntry(*entries,
7794 CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc,
7795 (unsigned long) sizes.malloc_bytes);
7796 createCXTUResourceUsageEntry(*entries,
7797 CXTUResourceUsage_ExternalASTSource_Membuffer_MMap,
7798 (unsigned long) sizes.mmap_bytes);
7799 }
7800
7801 // How much memory is being used by the Preprocessor?
7802 Preprocessor &pp = astUnit->getPreprocessor();
7803 createCXTUResourceUsageEntry(*entries,
7804 CXTUResourceUsage_Preprocessor,
7805 pp.getTotalMemory());
7806
7807 if (PreprocessingRecord *pRec = pp.getPreprocessingRecord()) {
7808 createCXTUResourceUsageEntry(*entries,
7809 CXTUResourceUsage_PreprocessingRecord,
7810 pRec->getTotalMemory());
7811 }
7812
7813 createCXTUResourceUsageEntry(*entries,
7814 CXTUResourceUsage_Preprocessor_HeaderSearch,
7815 pp.getHeaderSearchInfo().getTotalMemory());
Craig Topper69186e72014-06-08 08:38:04 +00007816
Guy Benyei11169dd2012-12-18 14:30:41 +00007817 CXTUResourceUsage usage = { (void*) entries.get(),
7818 (unsigned) entries->size(),
Alexander Kornienko6ee521c2015-01-23 15:36:10 +00007819 !entries->empty() ? &(*entries)[0] : nullptr };
Eric Fiseliere95fc442016-11-14 07:03:50 +00007820 (void)entries.release();
Guy Benyei11169dd2012-12-18 14:30:41 +00007821 return usage;
7822}
7823
7824void clang_disposeCXTUResourceUsage(CXTUResourceUsage usage) {
7825 if (usage.data)
7826 delete (MemUsageEntries*) usage.data;
7827}
7828
Argyrios Kyrtzidis0e282ef2013-12-06 18:55:45 +00007829CXSourceRangeList *clang_getSkippedRanges(CXTranslationUnit TU, CXFile file) {
7830 CXSourceRangeList *skipped = new CXSourceRangeList;
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00007831 skipped->count = 0;
Craig Topper69186e72014-06-08 08:38:04 +00007832 skipped->ranges = nullptr;
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00007833
Dmitri Gribenko852d6222014-02-11 15:02:48 +00007834 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00007835 LOG_BAD_TU(TU);
7836 return skipped;
7837 }
7838
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00007839 if (!file)
7840 return skipped;
7841
7842 ASTUnit *astUnit = cxtu::getASTUnit(TU);
7843 PreprocessingRecord *ppRec = astUnit->getPreprocessor().getPreprocessingRecord();
7844 if (!ppRec)
7845 return skipped;
7846
7847 ASTContext &Ctx = astUnit->getASTContext();
7848 SourceManager &sm = Ctx.getSourceManager();
7849 FileEntry *fileEntry = static_cast<FileEntry *>(file);
7850 FileID wantedFileID = sm.translateFile(fileEntry);
7851
7852 const std::vector<SourceRange> &SkippedRanges = ppRec->getSkippedRanges();
7853 std::vector<SourceRange> wantedRanges;
7854 for (std::vector<SourceRange>::const_iterator i = SkippedRanges.begin(), ei = SkippedRanges.end();
7855 i != ei; ++i) {
7856 if (sm.getFileID(i->getBegin()) == wantedFileID || sm.getFileID(i->getEnd()) == wantedFileID)
7857 wantedRanges.push_back(*i);
7858 }
7859
7860 skipped->count = wantedRanges.size();
7861 skipped->ranges = new CXSourceRange[skipped->count];
7862 for (unsigned i = 0, ei = skipped->count; i != ei; ++i)
7863 skipped->ranges[i] = cxloc::translateSourceRange(Ctx, wantedRanges[i]);
7864
7865 return skipped;
7866}
7867
Cameron Desrochersd8091282016-08-18 15:43:55 +00007868CXSourceRangeList *clang_getAllSkippedRanges(CXTranslationUnit TU) {
7869 CXSourceRangeList *skipped = new CXSourceRangeList;
7870 skipped->count = 0;
7871 skipped->ranges = nullptr;
7872
7873 if (isNotUsableTU(TU)) {
7874 LOG_BAD_TU(TU);
7875 return skipped;
7876 }
7877
7878 ASTUnit *astUnit = cxtu::getASTUnit(TU);
7879 PreprocessingRecord *ppRec = astUnit->getPreprocessor().getPreprocessingRecord();
7880 if (!ppRec)
7881 return skipped;
7882
7883 ASTContext &Ctx = astUnit->getASTContext();
7884
7885 const std::vector<SourceRange> &SkippedRanges = ppRec->getSkippedRanges();
7886
7887 skipped->count = SkippedRanges.size();
7888 skipped->ranges = new CXSourceRange[skipped->count];
7889 for (unsigned i = 0, ei = skipped->count; i != ei; ++i)
7890 skipped->ranges[i] = cxloc::translateSourceRange(Ctx, SkippedRanges[i]);
7891
7892 return skipped;
7893}
7894
Argyrios Kyrtzidis0e282ef2013-12-06 18:55:45 +00007895void clang_disposeSourceRangeList(CXSourceRangeList *ranges) {
7896 if (ranges) {
7897 delete[] ranges->ranges;
7898 delete ranges;
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00007899 }
7900}
7901
Guy Benyei11169dd2012-12-18 14:30:41 +00007902void clang::PrintLibclangResourceUsage(CXTranslationUnit TU) {
7903 CXTUResourceUsage Usage = clang_getCXTUResourceUsage(TU);
7904 for (unsigned I = 0; I != Usage.numEntries; ++I)
7905 fprintf(stderr, " %s: %lu\n",
7906 clang_getTUResourceUsageName(Usage.entries[I].kind),
7907 Usage.entries[I].amount);
7908
7909 clang_disposeCXTUResourceUsage(Usage);
7910}
7911
7912//===----------------------------------------------------------------------===//
7913// Misc. utility functions.
7914//===----------------------------------------------------------------------===//
7915
7916/// Default to using an 8 MB stack size on "safety" threads.
7917static unsigned SafetyStackThreadSize = 8 << 20;
7918
7919namespace clang {
7920
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00007921bool RunSafely(llvm::CrashRecoveryContext &CRC, llvm::function_ref<void()> Fn,
Guy Benyei11169dd2012-12-18 14:30:41 +00007922 unsigned Size) {
7923 if (!Size)
7924 Size = GetSafetyThreadStackSize();
7925 if (Size)
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00007926 return CRC.RunSafelyOnThread(Fn, Size);
7927 return CRC.RunSafely(Fn);
Guy Benyei11169dd2012-12-18 14:30:41 +00007928}
7929
7930unsigned GetSafetyThreadStackSize() {
7931 return SafetyStackThreadSize;
7932}
7933
7934void SetSafetyThreadStackSize(unsigned Value) {
7935 SafetyStackThreadSize = Value;
7936}
7937
Alexander Kornienkoab9db512015-06-22 23:07:51 +00007938}
Guy Benyei11169dd2012-12-18 14:30:41 +00007939
7940void clang::setThreadBackgroundPriority() {
7941 if (getenv("LIBCLANG_BGPRIO_DISABLE"))
7942 return;
7943
Alp Toker1a86ad22014-07-06 06:24:00 +00007944#ifdef USE_DARWIN_THREADS
Guy Benyei11169dd2012-12-18 14:30:41 +00007945 setpriority(PRIO_DARWIN_THREAD, 0, PRIO_DARWIN_BG);
7946#endif
7947}
7948
7949void cxindex::printDiagsToStderr(ASTUnit *Unit) {
7950 if (!Unit)
7951 return;
7952
7953 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
7954 DEnd = Unit->stored_diag_end();
7955 D != DEnd; ++D) {
Ben Langmuir749323f2014-04-22 17:40:12 +00007956 CXStoredDiagnostic Diag(*D, Unit->getLangOpts());
Guy Benyei11169dd2012-12-18 14:30:41 +00007957 CXString Msg = clang_formatDiagnostic(&Diag,
7958 clang_defaultDiagnosticDisplayOptions());
7959 fprintf(stderr, "%s\n", clang_getCString(Msg));
7960 clang_disposeString(Msg);
7961 }
7962#ifdef LLVM_ON_WIN32
7963 // On Windows, force a flush, since there may be multiple copies of
7964 // stderr and stdout in the file system, all with different buffers
7965 // but writing to the same device.
7966 fflush(stderr);
7967#endif
7968}
7969
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007970MacroInfo *cxindex::getMacroInfo(const IdentifierInfo &II,
7971 SourceLocation MacroDefLoc,
7972 CXTranslationUnit TU){
7973 if (MacroDefLoc.isInvalid() || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00007974 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007975 if (!II.hadMacroDefinition())
Craig Topper69186e72014-06-08 08:38:04 +00007976 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007977
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00007978 ASTUnit *Unit = cxtu::getASTUnit(TU);
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007979 Preprocessor &PP = Unit->getPreprocessor();
Richard Smith20e883e2015-04-29 23:20:19 +00007980 MacroDirective *MD = PP.getLocalMacroDirectiveHistory(&II);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00007981 if (MD) {
7982 for (MacroDirective::DefInfo
7983 Def = MD->getDefinition(); Def; Def = Def.getPreviousDefinition()) {
7984 if (MacroDefLoc == Def.getMacroInfo()->getDefinitionLoc())
7985 return Def.getMacroInfo();
7986 }
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007987 }
7988
Craig Topper69186e72014-06-08 08:38:04 +00007989 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007990}
7991
Richard Smith66a81862015-05-04 02:25:31 +00007992const MacroInfo *cxindex::getMacroInfo(const MacroDefinitionRecord *MacroDef,
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00007993 CXTranslationUnit TU) {
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007994 if (!MacroDef || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00007995 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007996 const IdentifierInfo *II = MacroDef->getName();
7997 if (!II)
Craig Topper69186e72014-06-08 08:38:04 +00007998 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007999
8000 return getMacroInfo(*II, MacroDef->getLocation(), TU);
8001}
8002
Richard Smith66a81862015-05-04 02:25:31 +00008003MacroDefinitionRecord *
8004cxindex::checkForMacroInMacroDefinition(const MacroInfo *MI, const Token &Tok,
8005 CXTranslationUnit TU) {
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008006 if (!MI || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00008007 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008008 if (Tok.isNot(tok::raw_identifier))
Craig Topper69186e72014-06-08 08:38:04 +00008009 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008010
8011 if (MI->getNumTokens() == 0)
Craig Topper69186e72014-06-08 08:38:04 +00008012 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008013 SourceRange DefRange(MI->getReplacementToken(0).getLocation(),
8014 MI->getDefinitionEndLoc());
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008015 ASTUnit *Unit = cxtu::getASTUnit(TU);
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008016
8017 // Check that the token is inside the definition and not its argument list.
8018 SourceManager &SM = Unit->getSourceManager();
8019 if (SM.isBeforeInTranslationUnit(Tok.getLocation(), DefRange.getBegin()))
Craig Topper69186e72014-06-08 08:38:04 +00008020 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008021 if (SM.isBeforeInTranslationUnit(DefRange.getEnd(), Tok.getLocation()))
Craig Topper69186e72014-06-08 08:38:04 +00008022 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008023
8024 Preprocessor &PP = Unit->getPreprocessor();
8025 PreprocessingRecord *PPRec = PP.getPreprocessingRecord();
8026 if (!PPRec)
Craig Topper69186e72014-06-08 08:38:04 +00008027 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008028
Alp Toker2d57cea2014-05-17 04:53:25 +00008029 IdentifierInfo &II = PP.getIdentifierTable().get(Tok.getRawIdentifier());
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008030 if (!II.hadMacroDefinition())
Craig Topper69186e72014-06-08 08:38:04 +00008031 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008032
8033 // Check that the identifier is not one of the macro arguments.
8034 if (std::find(MI->arg_begin(), MI->arg_end(), &II) != MI->arg_end())
Craig Topper69186e72014-06-08 08:38:04 +00008035 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008036
Richard Smith20e883e2015-04-29 23:20:19 +00008037 MacroDirective *InnerMD = PP.getLocalMacroDirectiveHistory(&II);
Argyrios Kyrtzidis09c9e812013-02-20 00:54:57 +00008038 if (!InnerMD)
Craig Topper69186e72014-06-08 08:38:04 +00008039 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008040
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00008041 return PPRec->findMacroDefinition(InnerMD->getMacroInfo());
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008042}
8043
Richard Smith66a81862015-05-04 02:25:31 +00008044MacroDefinitionRecord *
8045cxindex::checkForMacroInMacroDefinition(const MacroInfo *MI, SourceLocation Loc,
8046 CXTranslationUnit TU) {
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008047 if (Loc.isInvalid() || !MI || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00008048 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008049
8050 if (MI->getNumTokens() == 0)
Craig Topper69186e72014-06-08 08:38:04 +00008051 return nullptr;
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008052 ASTUnit *Unit = cxtu::getASTUnit(TU);
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008053 Preprocessor &PP = Unit->getPreprocessor();
8054 if (!PP.getPreprocessingRecord())
Craig Topper69186e72014-06-08 08:38:04 +00008055 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008056 Loc = Unit->getSourceManager().getSpellingLoc(Loc);
8057 Token Tok;
8058 if (PP.getRawToken(Loc, Tok))
Craig Topper69186e72014-06-08 08:38:04 +00008059 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008060
8061 return checkForMacroInMacroDefinition(MI, Tok, TU);
8062}
8063
Guy Benyei11169dd2012-12-18 14:30:41 +00008064CXString clang_getClangVersion() {
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00008065 return cxstring::createDup(getClangFullVersion());
Guy Benyei11169dd2012-12-18 14:30:41 +00008066}
8067
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008068Logger &cxindex::Logger::operator<<(CXTranslationUnit TU) {
8069 if (TU) {
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008070 if (ASTUnit *Unit = cxtu::getASTUnit(TU)) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008071 LogOS << '<' << Unit->getMainFileName() << '>';
Argyrios Kyrtzidis37f2ab42013-03-05 20:21:14 +00008072 if (Unit->isMainFileAST())
8073 LogOS << " (" << Unit->getASTFileName() << ')';
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008074 return *this;
8075 }
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00008076 } else {
8077 LogOS << "<NULL TU>";
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008078 }
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008079 return *this;
8080}
8081
Argyrios Kyrtzidisba4b5f82013-03-08 02:32:26 +00008082Logger &cxindex::Logger::operator<<(const FileEntry *FE) {
8083 *this << FE->getName();
8084 return *this;
8085}
8086
8087Logger &cxindex::Logger::operator<<(CXCursor cursor) {
8088 CXString cursorName = clang_getCursorDisplayName(cursor);
8089 *this << cursorName << "@" << clang_getCursorLocation(cursor);
8090 clang_disposeString(cursorName);
8091 return *this;
8092}
8093
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008094Logger &cxindex::Logger::operator<<(CXSourceLocation Loc) {
8095 CXFile File;
8096 unsigned Line, Column;
Craig Topper69186e72014-06-08 08:38:04 +00008097 clang_getFileLocation(Loc, &File, &Line, &Column, nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008098 CXString FileName = clang_getFileName(File);
8099 *this << llvm::format("(%s:%d:%d)", clang_getCString(FileName), Line, Column);
8100 clang_disposeString(FileName);
8101 return *this;
8102}
8103
8104Logger &cxindex::Logger::operator<<(CXSourceRange range) {
8105 CXSourceLocation BLoc = clang_getRangeStart(range);
8106 CXSourceLocation ELoc = clang_getRangeEnd(range);
8107
8108 CXFile BFile;
8109 unsigned BLine, BColumn;
Craig Topper69186e72014-06-08 08:38:04 +00008110 clang_getFileLocation(BLoc, &BFile, &BLine, &BColumn, nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008111
8112 CXFile EFile;
8113 unsigned ELine, EColumn;
Craig Topper69186e72014-06-08 08:38:04 +00008114 clang_getFileLocation(ELoc, &EFile, &ELine, &EColumn, nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008115
8116 CXString BFileName = clang_getFileName(BFile);
8117 if (BFile == EFile) {
8118 *this << llvm::format("[%s %d:%d-%d:%d]", clang_getCString(BFileName),
8119 BLine, BColumn, ELine, EColumn);
8120 } else {
8121 CXString EFileName = clang_getFileName(EFile);
8122 *this << llvm::format("[%s:%d:%d - ", clang_getCString(BFileName),
8123 BLine, BColumn)
8124 << llvm::format("%s:%d:%d]", clang_getCString(EFileName),
8125 ELine, EColumn);
8126 clang_disposeString(EFileName);
8127 }
8128 clang_disposeString(BFileName);
8129 return *this;
8130}
8131
8132Logger &cxindex::Logger::operator<<(CXString Str) {
8133 *this << clang_getCString(Str);
8134 return *this;
8135}
8136
8137Logger &cxindex::Logger::operator<<(const llvm::format_object_base &Fmt) {
8138 LogOS << Fmt;
8139 return *this;
8140}
8141
Chandler Carruth37ad2582014-06-27 15:14:39 +00008142static llvm::ManagedStatic<llvm::sys::Mutex> LoggingMutex;
8143
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008144cxindex::Logger::~Logger() {
Chandler Carruth37ad2582014-06-27 15:14:39 +00008145 llvm::sys::ScopedLock L(*LoggingMutex);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008146
8147 static llvm::TimeRecord sBeginTR = llvm::TimeRecord::getCurrentTime();
8148
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008149 raw_ostream &OS = llvm::errs();
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008150 OS << "[libclang:" << Name << ':';
8151
Alp Toker1a86ad22014-07-06 06:24:00 +00008152#ifdef USE_DARWIN_THREADS
8153 // TODO: Portability.
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008154 mach_port_t tid = pthread_mach_thread_np(pthread_self());
8155 OS << tid << ':';
8156#endif
8157
8158 llvm::TimeRecord TR = llvm::TimeRecord::getCurrentTime();
8159 OS << llvm::format("%7.4f] ", TR.getWallTime() - sBeginTR.getWallTime());
Yaron Keren09fb7c62015-03-10 07:33:23 +00008160 OS << Msg << '\n';
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008161
8162 if (Trace) {
Zachary Turner1fe2a8d2015-03-05 19:15:09 +00008163 llvm::sys::PrintStackTrace(OS);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008164 OS << "--------------------------------------------------\n";
8165 }
8166}
Benjamin Kramerc1ffdab2016-03-03 08:58:18 +00008167
8168#ifdef CLANG_TOOL_EXTRA_BUILD
8169// This anchor is used to force the linker to link the clang-tidy plugin.
8170extern volatile int ClangTidyPluginAnchorSource;
8171static int LLVM_ATTRIBUTE_UNUSED ClangTidyPluginAnchorDestination =
8172 ClangTidyPluginAnchorSource;
Benjamin Kramer9eba7352016-11-17 15:22:36 +00008173
8174// This anchor is used to force the linker to link the clang-include-fixer
8175// plugin.
8176extern volatile int ClangIncludeFixerPluginAnchorSource;
8177static int LLVM_ATTRIBUTE_UNUSED ClangIncludeFixerPluginAnchorDestination =
8178 ClangIncludeFixerPluginAnchorSource;
Benjamin Kramerc1ffdab2016-03-03 08:58:18 +00008179#endif