blob: 4fa540d33c9120c6dc389c382666e9d936452c13 [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 Blaikieea4395e2017-01-06 19:49:01 +000071CXTranslationUnit cxtu::MakeCXTranslationUnit(CIndexer *CIdx,
72 std::unique_ptr<ASTUnit> AU) {
Dmitri Gribenkod36209e2013-01-26 21:32:42 +000073 if (!AU)
Craig Topper69186e72014-06-08 08:38:04 +000074 return nullptr;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +000075 assert(CIdx);
Guy Benyei11169dd2012-12-18 14:30:41 +000076 CXTranslationUnit D = new CXTranslationUnitImpl();
77 D->CIdx = CIdx;
David Blaikieea4395e2017-01-06 19:49:01 +000078 D->TheASTUnit = AU.release();
Dmitri Gribenko74895212013-02-03 13:52:47 +000079 D->StringPool = new cxstring::CXStringPool();
Craig Topper69186e72014-06-08 08:38:04 +000080 D->Diagnostics = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +000081 D->OverridenCursorsPool = createOverridenCXCursorsPool();
Craig Topper69186e72014-06-08 08:38:04 +000082 D->CommentToXML = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +000083 return D;
84}
85
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +000086bool cxtu::isASTReadError(ASTUnit *AU) {
87 for (ASTUnit::stored_diag_iterator D = AU->stored_diag_begin(),
88 DEnd = AU->stored_diag_end();
89 D != DEnd; ++D) {
90 if (D->getLevel() >= DiagnosticsEngine::Error &&
91 DiagnosticIDs::getCategoryNumberForDiag(D->getID()) ==
92 diag::DiagCat_AST_Deserialization_Issue)
93 return true;
94 }
95 return false;
96}
97
Guy Benyei11169dd2012-12-18 14:30:41 +000098cxtu::CXTUOwner::~CXTUOwner() {
99 if (TU)
100 clang_disposeTranslationUnit(TU);
101}
102
103/// \brief Compare two source ranges to determine their relative position in
104/// the translation unit.
105static RangeComparisonResult RangeCompare(SourceManager &SM,
106 SourceRange R1,
107 SourceRange R2) {
108 assert(R1.isValid() && "First range is invalid?");
109 assert(R2.isValid() && "Second range is invalid?");
110 if (R1.getEnd() != R2.getBegin() &&
111 SM.isBeforeInTranslationUnit(R1.getEnd(), R2.getBegin()))
112 return RangeBefore;
113 if (R2.getEnd() != R1.getBegin() &&
114 SM.isBeforeInTranslationUnit(R2.getEnd(), R1.getBegin()))
115 return RangeAfter;
116 return RangeOverlap;
117}
118
119/// \brief Determine if a source location falls within, before, or after a
120/// a given source range.
121static RangeComparisonResult LocationCompare(SourceManager &SM,
122 SourceLocation L, SourceRange R) {
123 assert(R.isValid() && "First range is invalid?");
124 assert(L.isValid() && "Second range is invalid?");
125 if (L == R.getBegin() || L == R.getEnd())
126 return RangeOverlap;
127 if (SM.isBeforeInTranslationUnit(L, R.getBegin()))
128 return RangeBefore;
129 if (SM.isBeforeInTranslationUnit(R.getEnd(), L))
130 return RangeAfter;
131 return RangeOverlap;
132}
133
134/// \brief Translate a Clang source range into a CIndex source range.
135///
136/// Clang internally represents ranges where the end location points to the
137/// start of the token at the end. However, for external clients it is more
138/// useful to have a CXSourceRange be a proper half-open interval. This routine
139/// does the appropriate translation.
140CXSourceRange cxloc::translateSourceRange(const SourceManager &SM,
141 const LangOptions &LangOpts,
142 const CharSourceRange &R) {
143 // We want the last character in this location, so we will adjust the
144 // location accordingly.
145 SourceLocation EndLoc = R.getEnd();
146 if (EndLoc.isValid() && EndLoc.isMacroID() && !SM.isMacroArgExpansion(EndLoc))
147 EndLoc = SM.getExpansionRange(EndLoc).second;
Yaron Keren8b563662015-10-03 10:46:20 +0000148 if (R.isTokenRange() && EndLoc.isValid()) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000149 unsigned Length = Lexer::MeasureTokenLength(SM.getSpellingLoc(EndLoc),
150 SM, LangOpts);
151 EndLoc = EndLoc.getLocWithOffset(Length);
152 }
153
Bill Wendlingeade3622013-01-23 08:25:41 +0000154 CXSourceRange Result = {
Dmitri Gribenkof9304482013-01-23 15:56:07 +0000155 { &SM, &LangOpts },
Bill Wendlingeade3622013-01-23 08:25:41 +0000156 R.getBegin().getRawEncoding(),
157 EndLoc.getRawEncoding()
158 };
Guy Benyei11169dd2012-12-18 14:30:41 +0000159 return Result;
160}
161
162//===----------------------------------------------------------------------===//
163// Cursor visitor.
164//===----------------------------------------------------------------------===//
165
166static SourceRange getRawCursorExtent(CXCursor C);
167static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr);
168
169
170RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
171 return RangeCompare(AU->getSourceManager(), R, RegionOfInterest);
172}
173
174/// \brief Visit the given cursor and, if requested by the visitor,
175/// its children.
176///
177/// \param Cursor the cursor to visit.
178///
179/// \param CheckedRegionOfInterest if true, then the caller already checked
180/// that this cursor is within the region of interest.
181///
182/// \returns true if the visitation should be aborted, false if it
183/// should continue.
184bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
185 if (clang_isInvalid(Cursor.kind))
186 return false;
187
188 if (clang_isDeclaration(Cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +0000189 const Decl *D = getCursorDecl(Cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +0000190 if (!D) {
191 assert(0 && "Invalid declaration cursor");
192 return true; // abort.
193 }
194
195 // Ignore implicit declarations, unless it's an objc method because
196 // currently we should report implicit methods for properties when indexing.
197 if (D->isImplicit() && !isa<ObjCMethodDecl>(D))
198 return false;
199 }
200
201 // If we have a range of interest, and this cursor doesn't intersect with it,
202 // we're done.
203 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
204 SourceRange Range = getRawCursorExtent(Cursor);
205 if (Range.isInvalid() || CompareRegionOfInterest(Range))
206 return false;
207 }
208
209 switch (Visitor(Cursor, Parent, ClientData)) {
210 case CXChildVisit_Break:
211 return true;
212
213 case CXChildVisit_Continue:
214 return false;
215
216 case CXChildVisit_Recurse: {
217 bool ret = VisitChildren(Cursor);
218 if (PostChildrenVisitor)
219 if (PostChildrenVisitor(Cursor, ClientData))
220 return true;
221 return ret;
222 }
223 }
224
225 llvm_unreachable("Invalid CXChildVisitResult!");
226}
227
228static bool visitPreprocessedEntitiesInRange(SourceRange R,
229 PreprocessingRecord &PPRec,
230 CursorVisitor &Visitor) {
231 SourceManager &SM = Visitor.getASTUnit()->getSourceManager();
232 FileID FID;
233
234 if (!Visitor.shouldVisitIncludedEntities()) {
235 // If the begin/end of the range lie in the same FileID, do the optimization
236 // where we skip preprocessed entities that do not come from the same FileID.
237 FID = SM.getFileID(SM.getFileLoc(R.getBegin()));
238 if (FID != SM.getFileID(SM.getFileLoc(R.getEnd())))
239 FID = FileID();
240 }
241
Benjamin Kramerb4ef6682015-02-06 17:25:10 +0000242 const auto &Entities = PPRec.getPreprocessedEntitiesInRange(R);
243 return Visitor.visitPreprocessedEntities(Entities.begin(), Entities.end(),
Guy Benyei11169dd2012-12-18 14:30:41 +0000244 PPRec, FID);
245}
246
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000247bool CursorVisitor::visitFileRegion() {
Guy Benyei11169dd2012-12-18 14:30:41 +0000248 if (RegionOfInterest.isInvalid())
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000249 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000250
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +0000251 ASTUnit *Unit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +0000252 SourceManager &SM = Unit->getSourceManager();
253
254 std::pair<FileID, unsigned>
255 Begin = SM.getDecomposedLoc(SM.getFileLoc(RegionOfInterest.getBegin())),
256 End = SM.getDecomposedLoc(SM.getFileLoc(RegionOfInterest.getEnd()));
257
258 if (End.first != Begin.first) {
259 // If the end does not reside in the same file, try to recover by
260 // picking the end of the file of begin location.
261 End.first = Begin.first;
262 End.second = SM.getFileIDSize(Begin.first);
263 }
264
265 assert(Begin.first == End.first);
266 if (Begin.second > End.second)
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000267 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000268
269 FileID File = Begin.first;
270 unsigned Offset = Begin.second;
271 unsigned Length = End.second - Begin.second;
272
273 if (!VisitDeclsOnly && !VisitPreprocessorLast)
274 if (visitPreprocessedEntitiesInRegion())
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000275 return true; // visitation break.
Guy Benyei11169dd2012-12-18 14:30:41 +0000276
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000277 if (visitDeclsFromFileRegion(File, Offset, Length))
278 return true; // visitation break.
Guy Benyei11169dd2012-12-18 14:30:41 +0000279
280 if (!VisitDeclsOnly && VisitPreprocessorLast)
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000281 return visitPreprocessedEntitiesInRegion();
282
283 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000284}
285
286static bool isInLexicalContext(Decl *D, DeclContext *DC) {
287 if (!DC)
288 return false;
289
290 for (DeclContext *DeclDC = D->getLexicalDeclContext();
291 DeclDC; DeclDC = DeclDC->getLexicalParent()) {
292 if (DeclDC == DC)
293 return true;
294 }
295 return false;
296}
297
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000298bool CursorVisitor::visitDeclsFromFileRegion(FileID File,
Guy Benyei11169dd2012-12-18 14:30:41 +0000299 unsigned Offset, unsigned Length) {
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +0000300 ASTUnit *Unit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +0000301 SourceManager &SM = Unit->getSourceManager();
302 SourceRange Range = RegionOfInterest;
303
304 SmallVector<Decl *, 16> Decls;
305 Unit->findFileRegionDecls(File, Offset, Length, Decls);
306
307 // If we didn't find any file level decls for the file, try looking at the
308 // file that it was included from.
309 while (Decls.empty() || Decls.front()->isTopLevelDeclInObjCContainer()) {
310 bool Invalid = false;
311 const SrcMgr::SLocEntry &SLEntry = SM.getSLocEntry(File, &Invalid);
312 if (Invalid)
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000313 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000314
315 SourceLocation Outer;
316 if (SLEntry.isFile())
317 Outer = SLEntry.getFile().getIncludeLoc();
318 else
319 Outer = SLEntry.getExpansion().getExpansionLocStart();
320 if (Outer.isInvalid())
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000321 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000322
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000323 std::tie(File, Offset) = SM.getDecomposedExpansionLoc(Outer);
Guy Benyei11169dd2012-12-18 14:30:41 +0000324 Length = 0;
325 Unit->findFileRegionDecls(File, Offset, Length, Decls);
326 }
327
328 assert(!Decls.empty());
329
330 bool VisitedAtLeastOnce = false;
Craig Topper69186e72014-06-08 08:38:04 +0000331 DeclContext *CurDC = nullptr;
Craig Topper2341c0d2013-07-04 03:08:24 +0000332 SmallVectorImpl<Decl *>::iterator DIt = Decls.begin();
333 for (SmallVectorImpl<Decl *>::iterator DE = Decls.end(); DIt != DE; ++DIt) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000334 Decl *D = *DIt;
335 if (D->getSourceRange().isInvalid())
336 continue;
337
338 if (isInLexicalContext(D, CurDC))
339 continue;
340
341 CurDC = dyn_cast<DeclContext>(D);
342
343 if (TagDecl *TD = dyn_cast<TagDecl>(D))
344 if (!TD->isFreeStanding())
345 continue;
346
347 RangeComparisonResult CompRes = RangeCompare(SM, D->getSourceRange(),Range);
348 if (CompRes == RangeBefore)
349 continue;
350 if (CompRes == RangeAfter)
351 break;
352
353 assert(CompRes == RangeOverlap);
354 VisitedAtLeastOnce = true;
355
356 if (isa<ObjCContainerDecl>(D)) {
357 FileDI_current = &DIt;
358 FileDE_current = DE;
359 } else {
Craig Topper69186e72014-06-08 08:38:04 +0000360 FileDI_current = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +0000361 }
362
363 if (Visit(MakeCXCursor(D, TU, Range), /*CheckedRegionOfInterest=*/true))
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000364 return true; // visitation break.
Guy Benyei11169dd2012-12-18 14:30:41 +0000365 }
366
367 if (VisitedAtLeastOnce)
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000368 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000369
370 // No Decls overlapped with the range. Move up the lexical context until there
371 // is a context that contains the range or we reach the translation unit
372 // level.
373 DeclContext *DC = DIt == Decls.begin() ? (*DIt)->getLexicalDeclContext()
374 : (*(DIt-1))->getLexicalDeclContext();
375
376 while (DC && !DC->isTranslationUnit()) {
377 Decl *D = cast<Decl>(DC);
378 SourceRange CurDeclRange = D->getSourceRange();
379 if (CurDeclRange.isInvalid())
380 break;
381
382 if (RangeCompare(SM, CurDeclRange, Range) == RangeOverlap) {
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000383 if (Visit(MakeCXCursor(D, TU, Range), /*CheckedRegionOfInterest=*/true))
384 return true; // visitation break.
Guy Benyei11169dd2012-12-18 14:30:41 +0000385 }
386
387 DC = D->getLexicalDeclContext();
388 }
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000389
390 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000391}
392
393bool CursorVisitor::visitPreprocessedEntitiesInRegion() {
394 if (!AU->getPreprocessor().getPreprocessingRecord())
395 return false;
396
397 PreprocessingRecord &PPRec
398 = *AU->getPreprocessor().getPreprocessingRecord();
399 SourceManager &SM = AU->getSourceManager();
400
401 if (RegionOfInterest.isValid()) {
402 SourceRange MappedRange = AU->mapRangeToPreamble(RegionOfInterest);
403 SourceLocation B = MappedRange.getBegin();
404 SourceLocation E = MappedRange.getEnd();
405
406 if (AU->isInPreambleFileID(B)) {
407 if (SM.isLoadedSourceLocation(E))
408 return visitPreprocessedEntitiesInRange(SourceRange(B, E),
409 PPRec, *this);
410
411 // Beginning of range lies in the preamble but it also extends beyond
412 // it into the main file. Split the range into 2 parts, one covering
413 // the preamble and another covering the main file. This allows subsequent
414 // calls to visitPreprocessedEntitiesInRange to accept a source range that
415 // lies in the same FileID, allowing it to skip preprocessed entities that
416 // do not come from the same FileID.
417 bool breaked =
418 visitPreprocessedEntitiesInRange(
419 SourceRange(B, AU->getEndOfPreambleFileID()),
420 PPRec, *this);
421 if (breaked) return true;
422 return visitPreprocessedEntitiesInRange(
423 SourceRange(AU->getStartOfMainFileID(), E),
424 PPRec, *this);
425 }
426
427 return visitPreprocessedEntitiesInRange(SourceRange(B, E), PPRec, *this);
428 }
429
430 bool OnlyLocalDecls
431 = !AU->isMainFileAST() && AU->getOnlyLocalDecls();
432
433 if (OnlyLocalDecls)
434 return visitPreprocessedEntities(PPRec.local_begin(), PPRec.local_end(),
435 PPRec);
436
437 return visitPreprocessedEntities(PPRec.begin(), PPRec.end(), PPRec);
438}
439
440template<typename InputIterator>
441bool CursorVisitor::visitPreprocessedEntities(InputIterator First,
442 InputIterator Last,
443 PreprocessingRecord &PPRec,
444 FileID FID) {
445 for (; First != Last; ++First) {
446 if (!FID.isInvalid() && !PPRec.isEntityInFileID(First, FID))
447 continue;
448
449 PreprocessedEntity *PPE = *First;
Argyrios Kyrtzidis1030f262013-05-07 20:37:17 +0000450 if (!PPE)
451 continue;
452
Guy Benyei11169dd2012-12-18 14:30:41 +0000453 if (MacroExpansion *ME = dyn_cast<MacroExpansion>(PPE)) {
454 if (Visit(MakeMacroExpansionCursor(ME, TU)))
455 return true;
Richard Smith66a81862015-05-04 02:25:31 +0000456
Guy Benyei11169dd2012-12-18 14:30:41 +0000457 continue;
458 }
Richard Smith66a81862015-05-04 02:25:31 +0000459
460 if (MacroDefinitionRecord *MD = dyn_cast<MacroDefinitionRecord>(PPE)) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000461 if (Visit(MakeMacroDefinitionCursor(MD, TU)))
462 return true;
Richard Smith66a81862015-05-04 02:25:31 +0000463
Guy Benyei11169dd2012-12-18 14:30:41 +0000464 continue;
465 }
466
467 if (InclusionDirective *ID = dyn_cast<InclusionDirective>(PPE)) {
468 if (Visit(MakeInclusionDirectiveCursor(ID, TU)))
469 return true;
470
471 continue;
472 }
473 }
474
475 return false;
476}
477
478/// \brief Visit the children of the given cursor.
479///
480/// \returns true if the visitation should be aborted, false if it
481/// should continue.
482bool CursorVisitor::VisitChildren(CXCursor Cursor) {
483 if (clang_isReference(Cursor.kind) &&
484 Cursor.kind != CXCursor_CXXBaseSpecifier) {
485 // By definition, references have no children.
486 return false;
487 }
488
489 // Set the Parent field to Cursor, then back to its old value once we're
490 // done.
491 SetParentRAII SetParent(Parent, StmtParent, Cursor);
492
493 if (clang_isDeclaration(Cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +0000494 Decl *D = const_cast<Decl *>(getCursorDecl(Cursor));
Guy Benyei11169dd2012-12-18 14:30:41 +0000495 if (!D)
496 return false;
497
498 return VisitAttributes(D) || Visit(D);
499 }
500
501 if (clang_isStatement(Cursor.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +0000502 if (const Stmt *S = getCursorStmt(Cursor))
Guy Benyei11169dd2012-12-18 14:30:41 +0000503 return Visit(S);
504
505 return false;
506 }
507
508 if (clang_isExpression(Cursor.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +0000509 if (const Expr *E = getCursorExpr(Cursor))
Guy Benyei11169dd2012-12-18 14:30:41 +0000510 return Visit(E);
511
512 return false;
513 }
514
515 if (clang_isTranslationUnit(Cursor.kind)) {
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +0000516 CXTranslationUnit TU = getCursorTU(Cursor);
517 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +0000518
519 int VisitOrder[2] = { VisitPreprocessorLast, !VisitPreprocessorLast };
520 for (unsigned I = 0; I != 2; ++I) {
521 if (VisitOrder[I]) {
522 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
523 RegionOfInterest.isInvalid()) {
524 for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
525 TLEnd = CXXUnit->top_level_end();
526 TL != TLEnd; ++TL) {
Argyrios Kyrtzidise7c91042016-07-01 19:10:54 +0000527 const Optional<bool> V = handleDeclForVisitation(*TL);
528 if (!V.hasValue())
529 continue;
530 return V.getValue();
Guy Benyei11169dd2012-12-18 14:30:41 +0000531 }
532 } else if (VisitDeclContext(
533 CXXUnit->getASTContext().getTranslationUnitDecl()))
534 return true;
535 continue;
536 }
537
538 // Walk the preprocessing record.
539 if (CXXUnit->getPreprocessor().getPreprocessingRecord())
540 visitPreprocessedEntitiesInRegion();
541 }
542
543 return false;
544 }
545
546 if (Cursor.kind == CXCursor_CXXBaseSpecifier) {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +0000547 if (const CXXBaseSpecifier *Base = getCursorCXXBaseSpecifier(Cursor)) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000548 if (TypeSourceInfo *BaseTSInfo = Base->getTypeSourceInfo()) {
549 return Visit(BaseTSInfo->getTypeLoc());
550 }
551 }
552 }
553
554 if (Cursor.kind == CXCursor_IBOutletCollectionAttr) {
Dmitri Gribenkoe4baea62013-01-26 18:08:08 +0000555 const IBOutletCollectionAttr *A =
Guy Benyei11169dd2012-12-18 14:30:41 +0000556 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(Cursor));
Richard Smithb1f9a282013-10-31 01:56:18 +0000557 if (const ObjCObjectType *ObjT = A->getInterface()->getAs<ObjCObjectType>())
Richard Smithb87c4652013-10-31 21:23:20 +0000558 return Visit(cxcursor::MakeCursorObjCClassRef(
559 ObjT->getInterface(),
560 A->getInterfaceLoc()->getTypeLoc().getLocStart(), TU));
Guy Benyei11169dd2012-12-18 14:30:41 +0000561 }
562
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +0000563 // If pointing inside a macro definition, check if the token is an identifier
564 // that was ever defined as a macro. In such a case, create a "pseudo" macro
565 // expansion cursor for that token.
566 SourceLocation BeginLoc = RegionOfInterest.getBegin();
567 if (Cursor.kind == CXCursor_MacroDefinition &&
568 BeginLoc == RegionOfInterest.getEnd()) {
569 SourceLocation Loc = AU->mapLocationToPreamble(BeginLoc);
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +0000570 const MacroInfo *MI =
571 getMacroInfo(cxcursor::getCursorMacroDefinition(Cursor), TU);
Richard Smith66a81862015-05-04 02:25:31 +0000572 if (MacroDefinitionRecord *MacroDef =
573 checkForMacroInMacroDefinition(MI, Loc, TU))
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +0000574 return Visit(cxcursor::MakeMacroExpansionCursor(MacroDef, BeginLoc, TU));
575 }
576
Guy Benyei11169dd2012-12-18 14:30:41 +0000577 // Nothing to visit at the moment.
578 return false;
579}
580
581bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
582 if (TypeSourceInfo *TSInfo = B->getSignatureAsWritten())
583 if (Visit(TSInfo->getTypeLoc()))
584 return true;
585
586 if (Stmt *Body = B->getBody())
587 return Visit(MakeCXCursor(Body, StmtParent, TU, RegionOfInterest));
588
589 return false;
590}
591
Ted Kremenek03325582013-02-21 01:29:01 +0000592Optional<bool> CursorVisitor::shouldVisitCursor(CXCursor Cursor) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000593 if (RegionOfInterest.isValid()) {
594 SourceRange Range = getFullCursorExtent(Cursor, AU->getSourceManager());
595 if (Range.isInvalid())
David Blaikie7a30dc52013-02-21 01:47:18 +0000596 return None;
Guy Benyei11169dd2012-12-18 14:30:41 +0000597
598 switch (CompareRegionOfInterest(Range)) {
599 case RangeBefore:
600 // This declaration comes before the region of interest; skip it.
David Blaikie7a30dc52013-02-21 01:47:18 +0000601 return None;
Guy Benyei11169dd2012-12-18 14:30:41 +0000602
603 case RangeAfter:
604 // This declaration comes after the region of interest; we're done.
605 return false;
606
607 case RangeOverlap:
608 // This declaration overlaps the region of interest; visit it.
609 break;
610 }
611 }
612 return true;
613}
614
615bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
616 DeclContext::decl_iterator I = DC->decls_begin(), E = DC->decls_end();
617
618 // FIXME: Eventually remove. This part of a hack to support proper
619 // iteration over all Decls contained lexically within an ObjC container.
620 SaveAndRestore<DeclContext::decl_iterator*> DI_saved(DI_current, &I);
621 SaveAndRestore<DeclContext::decl_iterator> DE_saved(DE_current, E);
622
623 for ( ; I != E; ++I) {
624 Decl *D = *I;
625 if (D->getLexicalDeclContext() != DC)
626 continue;
Argyrios Kyrtzidise7c91042016-07-01 19:10:54 +0000627 const Optional<bool> V = handleDeclForVisitation(D);
Guy Benyei11169dd2012-12-18 14:30:41 +0000628 if (!V.hasValue())
629 continue;
Argyrios Kyrtzidise7c91042016-07-01 19:10:54 +0000630 return V.getValue();
Guy Benyei11169dd2012-12-18 14:30:41 +0000631 }
632 return false;
633}
634
Argyrios Kyrtzidise7c91042016-07-01 19:10:54 +0000635Optional<bool> CursorVisitor::handleDeclForVisitation(const Decl *D) {
636 CXCursor Cursor = MakeCXCursor(D, TU, RegionOfInterest);
637
638 // Ignore synthesized ivars here, otherwise if we have something like:
639 // @synthesize prop = _prop;
640 // and '_prop' is not declared, we will encounter a '_prop' ivar before
641 // encountering the 'prop' synthesize declaration and we will think that
642 // we passed the region-of-interest.
643 if (auto *ivarD = dyn_cast<ObjCIvarDecl>(D)) {
644 if (ivarD->getSynthesize())
645 return None;
646 }
647
648 // FIXME: ObjCClassRef/ObjCProtocolRef for forward class/protocol
649 // declarations is a mismatch with the compiler semantics.
650 if (Cursor.kind == CXCursor_ObjCInterfaceDecl) {
651 auto *ID = cast<ObjCInterfaceDecl>(D);
652 if (!ID->isThisDeclarationADefinition())
653 Cursor = MakeCursorObjCClassRef(ID, ID->getLocation(), TU);
654
655 } else if (Cursor.kind == CXCursor_ObjCProtocolDecl) {
656 auto *PD = cast<ObjCProtocolDecl>(D);
657 if (!PD->isThisDeclarationADefinition())
658 Cursor = MakeCursorObjCProtocolRef(PD, PD->getLocation(), TU);
659 }
660
661 const Optional<bool> V = shouldVisitCursor(Cursor);
662 if (!V.hasValue())
663 return None;
664 if (!V.getValue())
665 return false;
666 if (Visit(Cursor, true))
667 return true;
668 return None;
669}
670
Guy Benyei11169dd2012-12-18 14:30:41 +0000671bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
672 llvm_unreachable("Translation units are visited directly by Visit()");
673}
674
Sergey Kalinichev8f3b1872015-11-15 13:48:32 +0000675bool CursorVisitor::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
676 if (VisitTemplateParameters(D->getTemplateParameters()))
677 return true;
678
679 return Visit(MakeCXCursor(D->getTemplatedDecl(), TU, RegionOfInterest));
680}
681
Guy Benyei11169dd2012-12-18 14:30:41 +0000682bool CursorVisitor::VisitTypeAliasDecl(TypeAliasDecl *D) {
683 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
684 return Visit(TSInfo->getTypeLoc());
685
686 return false;
687}
688
689bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
690 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
691 return Visit(TSInfo->getTypeLoc());
692
693 return false;
694}
695
696bool CursorVisitor::VisitTagDecl(TagDecl *D) {
697 return VisitDeclContext(D);
698}
699
700bool CursorVisitor::VisitClassTemplateSpecializationDecl(
701 ClassTemplateSpecializationDecl *D) {
702 bool ShouldVisitBody = false;
703 switch (D->getSpecializationKind()) {
704 case TSK_Undeclared:
705 case TSK_ImplicitInstantiation:
706 // Nothing to visit
707 return false;
708
709 case TSK_ExplicitInstantiationDeclaration:
710 case TSK_ExplicitInstantiationDefinition:
711 break;
712
713 case TSK_ExplicitSpecialization:
714 ShouldVisitBody = true;
715 break;
716 }
717
718 // Visit the template arguments used in the specialization.
719 if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) {
720 TypeLoc TL = SpecType->getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +0000721 if (TemplateSpecializationTypeLoc TSTLoc =
722 TL.getAs<TemplateSpecializationTypeLoc>()) {
723 for (unsigned I = 0, N = TSTLoc.getNumArgs(); I != N; ++I)
724 if (VisitTemplateArgumentLoc(TSTLoc.getArgLoc(I)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000725 return true;
726 }
727 }
Alexander Kornienko1a9f1842015-12-28 15:24:08 +0000728
729 return ShouldVisitBody && VisitCXXRecordDecl(D);
Guy Benyei11169dd2012-12-18 14:30:41 +0000730}
731
732bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl(
733 ClassTemplatePartialSpecializationDecl *D) {
734 // FIXME: Visit the "outer" template parameter lists on the TagDecl
735 // before visiting these template parameters.
736 if (VisitTemplateParameters(D->getTemplateParameters()))
737 return true;
738
739 // Visit the partial specialization arguments.
Enea Zaffanella6dbe1872013-08-10 07:24:53 +0000740 const ASTTemplateArgumentListInfo *Info = D->getTemplateArgsAsWritten();
741 const TemplateArgumentLoc *TemplateArgs = Info->getTemplateArgs();
742 for (unsigned I = 0, N = Info->NumTemplateArgs; I != N; ++I)
Guy Benyei11169dd2012-12-18 14:30:41 +0000743 if (VisitTemplateArgumentLoc(TemplateArgs[I]))
744 return true;
745
746 return VisitCXXRecordDecl(D);
747}
748
749bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
750 // Visit the default argument.
751 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
752 if (TypeSourceInfo *DefArg = D->getDefaultArgumentInfo())
753 if (Visit(DefArg->getTypeLoc()))
754 return true;
755
756 return false;
757}
758
759bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
760 if (Expr *Init = D->getInitExpr())
761 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
762 return false;
763}
764
765bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
Argyrios Kyrtzidis2ec76742013-04-05 21:04:10 +0000766 unsigned NumParamList = DD->getNumTemplateParameterLists();
767 for (unsigned i = 0; i < NumParamList; i++) {
768 TemplateParameterList* Params = DD->getTemplateParameterList(i);
769 if (VisitTemplateParameters(Params))
770 return true;
771 }
772
Guy Benyei11169dd2012-12-18 14:30:41 +0000773 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
774 if (Visit(TSInfo->getTypeLoc()))
775 return true;
776
777 // Visit the nested-name-specifier, if present.
778 if (NestedNameSpecifierLoc QualifierLoc = DD->getQualifierLoc())
779 if (VisitNestedNameSpecifierLoc(QualifierLoc))
780 return true;
781
782 return false;
783}
784
Benjamin Kramer4cadf292014-03-07 21:51:58 +0000785/// \brief Compare two base or member initializers based on their source order.
786static int CompareCXXCtorInitializers(CXXCtorInitializer *const *X,
787 CXXCtorInitializer *const *Y) {
788 return (*X)->getSourceOrder() - (*Y)->getSourceOrder();
789}
790
Guy Benyei11169dd2012-12-18 14:30:41 +0000791bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Argyrios Kyrtzidis2ec76742013-04-05 21:04:10 +0000792 unsigned NumParamList = ND->getNumTemplateParameterLists();
793 for (unsigned i = 0; i < NumParamList; i++) {
794 TemplateParameterList* Params = ND->getTemplateParameterList(i);
795 if (VisitTemplateParameters(Params))
796 return true;
797 }
798
Guy Benyei11169dd2012-12-18 14:30:41 +0000799 if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
800 // Visit the function declaration's syntactic components in the order
801 // written. This requires a bit of work.
802 TypeLoc TL = TSInfo->getTypeLoc().IgnoreParens();
David Blaikie6adc78e2013-02-18 22:06:02 +0000803 FunctionTypeLoc FTL = TL.getAs<FunctionTypeLoc>();
Guy Benyei11169dd2012-12-18 14:30:41 +0000804
805 // If we have a function declared directly (without the use of a typedef),
806 // visit just the return type. Otherwise, just visit the function's type
807 // now.
Alp Toker42a16a62014-01-25 23:51:36 +0000808 if ((FTL && !isa<CXXConversionDecl>(ND) && Visit(FTL.getReturnLoc())) ||
Guy Benyei11169dd2012-12-18 14:30:41 +0000809 (!FTL && Visit(TL)))
810 return true;
811
812 // Visit the nested-name-specifier, if present.
813 if (NestedNameSpecifierLoc QualifierLoc = ND->getQualifierLoc())
814 if (VisitNestedNameSpecifierLoc(QualifierLoc))
815 return true;
816
817 // Visit the declaration name.
Argyrios Kyrtzidis4a4d2b42014-02-09 08:13:47 +0000818 if (!isa<CXXDestructorDecl>(ND))
819 if (VisitDeclarationNameInfo(ND->getNameInfo()))
820 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +0000821
822 // FIXME: Visit explicitly-specified template arguments!
823
824 // Visit the function parameters, if we have a function type.
David Blaikie6adc78e2013-02-18 22:06:02 +0000825 if (FTL && VisitFunctionTypeLoc(FTL, true))
Guy Benyei11169dd2012-12-18 14:30:41 +0000826 return true;
827
Bill Wendling44426052012-12-20 19:22:21 +0000828 // FIXME: Attributes?
Guy Benyei11169dd2012-12-18 14:30:41 +0000829 }
830
831 if (ND->doesThisDeclarationHaveABody() && !ND->isLateTemplateParsed()) {
832 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ND)) {
833 // Find the initializers that were written in the source.
834 SmallVector<CXXCtorInitializer *, 4> WrittenInits;
Aaron Ballman0ad78302014-03-13 17:34:31 +0000835 for (auto *I : Constructor->inits()) {
836 if (!I->isWritten())
Guy Benyei11169dd2012-12-18 14:30:41 +0000837 continue;
838
Aaron Ballman0ad78302014-03-13 17:34:31 +0000839 WrittenInits.push_back(I);
Guy Benyei11169dd2012-12-18 14:30:41 +0000840 }
841
842 // Sort the initializers in source order
Benjamin Kramer4cadf292014-03-07 21:51:58 +0000843 llvm::array_pod_sort(WrittenInits.begin(), WrittenInits.end(),
844 &CompareCXXCtorInitializers);
845
Guy Benyei11169dd2012-12-18 14:30:41 +0000846 // Visit the initializers in source order
847 for (unsigned I = 0, N = WrittenInits.size(); I != N; ++I) {
848 CXXCtorInitializer *Init = WrittenInits[I];
849 if (Init->isAnyMemberInitializer()) {
850 if (Visit(MakeCursorMemberRef(Init->getAnyMember(),
851 Init->getMemberLocation(), TU)))
852 return true;
853 } else if (TypeSourceInfo *TInfo = Init->getTypeSourceInfo()) {
854 if (Visit(TInfo->getTypeLoc()))
855 return true;
856 }
857
858 // Visit the initializer value.
859 if (Expr *Initializer = Init->getInit())
860 if (Visit(MakeCXCursor(Initializer, ND, TU, RegionOfInterest)))
861 return true;
862 }
863 }
864
865 if (Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest)))
866 return true;
867 }
868
869 return false;
870}
871
872bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
873 if (VisitDeclaratorDecl(D))
874 return true;
875
876 if (Expr *BitWidth = D->getBitWidth())
877 return Visit(MakeCXCursor(BitWidth, StmtParent, TU, RegionOfInterest));
878
879 return false;
880}
881
882bool CursorVisitor::VisitVarDecl(VarDecl *D) {
883 if (VisitDeclaratorDecl(D))
884 return true;
885
886 if (Expr *Init = D->getInit())
887 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
888
889 return false;
890}
891
892bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
893 if (VisitDeclaratorDecl(D))
894 return true;
895
896 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
897 if (Expr *DefArg = D->getDefaultArgument())
898 return Visit(MakeCXCursor(DefArg, StmtParent, TU, RegionOfInterest));
899
900 return false;
901}
902
903bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
904 // FIXME: Visit the "outer" template parameter lists on the FunctionDecl
905 // before visiting these template parameters.
906 if (VisitTemplateParameters(D->getTemplateParameters()))
907 return true;
908
909 return VisitFunctionDecl(D->getTemplatedDecl());
910}
911
912bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) {
913 // FIXME: Visit the "outer" template parameter lists on the TagDecl
914 // before visiting these template parameters.
915 if (VisitTemplateParameters(D->getTemplateParameters()))
916 return true;
917
918 return VisitCXXRecordDecl(D->getTemplatedDecl());
919}
920
921bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
922 if (VisitTemplateParameters(D->getTemplateParameters()))
923 return true;
924
925 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() &&
926 VisitTemplateArgumentLoc(D->getDefaultArgument()))
927 return true;
928
929 return false;
930}
931
Douglas Gregor9bda6cf2015-07-07 03:58:14 +0000932bool CursorVisitor::VisitObjCTypeParamDecl(ObjCTypeParamDecl *D) {
933 // Visit the bound, if it's explicit.
934 if (D->hasExplicitBound()) {
935 if (auto TInfo = D->getTypeSourceInfo()) {
936 if (Visit(TInfo->getTypeLoc()))
937 return true;
938 }
939 }
940
941 return false;
942}
943
Guy Benyei11169dd2012-12-18 14:30:41 +0000944bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Alp Toker314cc812014-01-25 16:55:45 +0000945 if (TypeSourceInfo *TSInfo = ND->getReturnTypeSourceInfo())
Guy Benyei11169dd2012-12-18 14:30:41 +0000946 if (Visit(TSInfo->getTypeLoc()))
947 return true;
948
David Majnemer59f77922016-06-24 04:05:48 +0000949 for (const auto *P : ND->parameters()) {
Aaron Ballman43b68be2014-03-07 17:50:17 +0000950 if (Visit(MakeCXCursor(P, TU, RegionOfInterest)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000951 return true;
952 }
953
Alexander Kornienko1a9f1842015-12-28 15:24:08 +0000954 return ND->isThisDeclarationADefinition() &&
955 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest));
Guy Benyei11169dd2012-12-18 14:30:41 +0000956}
957
958template <typename DeclIt>
959static void addRangedDeclsInContainer(DeclIt *DI_current, DeclIt DE_current,
960 SourceManager &SM, SourceLocation EndLoc,
961 SmallVectorImpl<Decl *> &Decls) {
962 DeclIt next = *DI_current;
963 while (++next != DE_current) {
964 Decl *D_next = *next;
965 if (!D_next)
966 break;
967 SourceLocation L = D_next->getLocStart();
968 if (!L.isValid())
969 break;
970 if (SM.isBeforeInTranslationUnit(L, EndLoc)) {
971 *DI_current = next;
972 Decls.push_back(D_next);
973 continue;
974 }
975 break;
976 }
977}
978
Guy Benyei11169dd2012-12-18 14:30:41 +0000979bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
980 // FIXME: Eventually convert back to just 'VisitDeclContext()'. Essentially
981 // an @implementation can lexically contain Decls that are not properly
982 // nested in the AST. When we identify such cases, we need to retrofit
983 // this nesting here.
984 if (!DI_current && !FileDI_current)
985 return VisitDeclContext(D);
986
987 // Scan the Decls that immediately come after the container
988 // in the current DeclContext. If any fall within the
989 // container's lexical region, stash them into a vector
990 // for later processing.
991 SmallVector<Decl *, 24> DeclsInContainer;
992 SourceLocation EndLoc = D->getSourceRange().getEnd();
993 SourceManager &SM = AU->getSourceManager();
994 if (EndLoc.isValid()) {
995 if (DI_current) {
996 addRangedDeclsInContainer(DI_current, DE_current, SM, EndLoc,
997 DeclsInContainer);
998 } else {
999 addRangedDeclsInContainer(FileDI_current, FileDE_current, SM, EndLoc,
1000 DeclsInContainer);
1001 }
1002 }
1003
1004 // The common case.
1005 if (DeclsInContainer.empty())
1006 return VisitDeclContext(D);
1007
1008 // Get all the Decls in the DeclContext, and sort them with the
1009 // additional ones we've collected. Then visit them.
Aaron Ballman629afae2014-03-07 19:56:05 +00001010 for (auto *SubDecl : D->decls()) {
1011 if (!SubDecl || SubDecl->getLexicalDeclContext() != D ||
1012 SubDecl->getLocStart().isInvalid())
Guy Benyei11169dd2012-12-18 14:30:41 +00001013 continue;
Aaron Ballman629afae2014-03-07 19:56:05 +00001014 DeclsInContainer.push_back(SubDecl);
Guy Benyei11169dd2012-12-18 14:30:41 +00001015 }
1016
1017 // Now sort the Decls so that they appear in lexical order.
1018 std::sort(DeclsInContainer.begin(), DeclsInContainer.end(),
Benjamin Kramerbbdd7642014-03-01 14:48:57 +00001019 [&SM](Decl *A, Decl *B) {
1020 SourceLocation L_A = A->getLocStart();
1021 SourceLocation L_B = B->getLocStart();
1022 assert(L_A.isValid() && L_B.isValid());
1023 return SM.isBeforeInTranslationUnit(L_A, L_B);
1024 });
Guy Benyei11169dd2012-12-18 14:30:41 +00001025
1026 // Now visit the decls.
1027 for (SmallVectorImpl<Decl*>::iterator I = DeclsInContainer.begin(),
1028 E = DeclsInContainer.end(); I != E; ++I) {
1029 CXCursor Cursor = MakeCXCursor(*I, TU, RegionOfInterest);
Ted Kremenek03325582013-02-21 01:29:01 +00001030 const Optional<bool> &V = shouldVisitCursor(Cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00001031 if (!V.hasValue())
1032 continue;
1033 if (!V.getValue())
1034 return false;
1035 if (Visit(Cursor, true))
1036 return true;
1037 }
1038 return false;
1039}
1040
1041bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
1042 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
1043 TU)))
1044 return true;
1045
Douglas Gregore9d95f12015-07-07 03:57:35 +00001046 if (VisitObjCTypeParamList(ND->getTypeParamList()))
1047 return true;
1048
Guy Benyei11169dd2012-12-18 14:30:41 +00001049 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
1050 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
1051 E = ND->protocol_end(); I != E; ++I, ++PL)
1052 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
1053 return true;
1054
1055 return VisitObjCContainerDecl(ND);
1056}
1057
1058bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
1059 if (!PID->isThisDeclarationADefinition())
1060 return Visit(MakeCursorObjCProtocolRef(PID, PID->getLocation(), TU));
1061
1062 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
1063 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
1064 E = PID->protocol_end(); I != E; ++I, ++PL)
1065 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
1066 return true;
1067
1068 return VisitObjCContainerDecl(PID);
1069}
1070
1071bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
1072 if (PD->getTypeSourceInfo() && Visit(PD->getTypeSourceInfo()->getTypeLoc()))
1073 return true;
1074
1075 // FIXME: This implements a workaround with @property declarations also being
1076 // installed in the DeclContext for the @interface. Eventually this code
1077 // should be removed.
1078 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
1079 if (!CDecl || !CDecl->IsClassExtension())
1080 return false;
1081
1082 ObjCInterfaceDecl *ID = CDecl->getClassInterface();
1083 if (!ID)
1084 return false;
1085
1086 IdentifierInfo *PropertyId = PD->getIdentifier();
1087 ObjCPropertyDecl *prevDecl =
Manman Ren5b786402016-01-28 18:49:28 +00001088 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId,
1089 PD->getQueryKind());
Guy Benyei11169dd2012-12-18 14:30:41 +00001090
1091 if (!prevDecl)
1092 return false;
1093
1094 // Visit synthesized methods since they will be skipped when visiting
1095 // the @interface.
1096 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
1097 if (MD->isPropertyAccessor() && MD->getLexicalDeclContext() == CDecl)
1098 if (Visit(MakeCXCursor(MD, TU, RegionOfInterest)))
1099 return true;
1100
1101 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
1102 if (MD->isPropertyAccessor() && MD->getLexicalDeclContext() == CDecl)
1103 if (Visit(MakeCXCursor(MD, TU, RegionOfInterest)))
1104 return true;
1105
1106 return false;
1107}
1108
Douglas Gregore9d95f12015-07-07 03:57:35 +00001109bool CursorVisitor::VisitObjCTypeParamList(ObjCTypeParamList *typeParamList) {
1110 if (!typeParamList)
1111 return false;
1112
1113 for (auto *typeParam : *typeParamList) {
1114 // Visit the type parameter.
1115 if (Visit(MakeCXCursor(typeParam, TU, RegionOfInterest)))
1116 return true;
Douglas Gregore9d95f12015-07-07 03:57:35 +00001117 }
1118
1119 return false;
1120}
1121
Guy Benyei11169dd2012-12-18 14:30:41 +00001122bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
1123 if (!D->isThisDeclarationADefinition()) {
1124 // Forward declaration is treated like a reference.
1125 return Visit(MakeCursorObjCClassRef(D, D->getLocation(), TU));
1126 }
1127
Douglas Gregore9d95f12015-07-07 03:57:35 +00001128 // Objective-C type parameters.
1129 if (VisitObjCTypeParamList(D->getTypeParamListAsWritten()))
1130 return true;
1131
Guy Benyei11169dd2012-12-18 14:30:41 +00001132 // Issue callbacks for super class.
1133 if (D->getSuperClass() &&
1134 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
1135 D->getSuperClassLoc(),
1136 TU)))
1137 return true;
1138
Douglas Gregore9d95f12015-07-07 03:57:35 +00001139 if (TypeSourceInfo *SuperClassTInfo = D->getSuperClassTInfo())
1140 if (Visit(SuperClassTInfo->getTypeLoc()))
1141 return true;
1142
Guy Benyei11169dd2012-12-18 14:30:41 +00001143 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1144 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
1145 E = D->protocol_end(); I != E; ++I, ++PL)
1146 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
1147 return true;
1148
1149 return VisitObjCContainerDecl(D);
1150}
1151
1152bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
1153 return VisitObjCContainerDecl(D);
1154}
1155
1156bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
1157 // 'ID' could be null when dealing with invalid code.
1158 if (ObjCInterfaceDecl *ID = D->getClassInterface())
1159 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
1160 return true;
1161
1162 return VisitObjCImplDecl(D);
1163}
1164
1165bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
1166#if 0
1167 // Issue callbacks for super class.
1168 // FIXME: No source location information!
1169 if (D->getSuperClass() &&
1170 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
1171 D->getSuperClassLoc(),
1172 TU)))
1173 return true;
1174#endif
1175
1176 return VisitObjCImplDecl(D);
1177}
1178
1179bool CursorVisitor::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *PD) {
1180 if (ObjCIvarDecl *Ivar = PD->getPropertyIvarDecl())
1181 if (PD->isIvarNameSpecified())
1182 return Visit(MakeCursorMemberRef(Ivar, PD->getPropertyIvarDeclLoc(), TU));
1183
1184 return false;
1185}
1186
1187bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
1188 return VisitDeclContext(D);
1189}
1190
1191bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
1192 // Visit nested-name-specifier.
1193 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1194 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1195 return true;
1196
1197 return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(),
1198 D->getTargetNameLoc(), TU));
1199}
1200
1201bool CursorVisitor::VisitUsingDecl(UsingDecl *D) {
1202 // Visit nested-name-specifier.
1203 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1204 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1205 return true;
1206 }
1207
1208 if (Visit(MakeCursorOverloadedDeclRef(D, D->getLocation(), TU)))
1209 return true;
1210
1211 return VisitDeclarationNameInfo(D->getNameInfo());
1212}
1213
1214bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
1215 // Visit nested-name-specifier.
1216 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1217 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1218 return true;
1219
1220 return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(),
1221 D->getIdentLocation(), TU));
1222}
1223
1224bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
1225 // Visit nested-name-specifier.
1226 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1227 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1228 return true;
1229 }
1230
1231 return VisitDeclarationNameInfo(D->getNameInfo());
1232}
1233
1234bool CursorVisitor::VisitUnresolvedUsingTypenameDecl(
1235 UnresolvedUsingTypenameDecl *D) {
1236 // Visit nested-name-specifier.
1237 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1238 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1239 return true;
1240
1241 return false;
1242}
1243
Olivier Goffart81978012016-06-09 16:15:55 +00001244bool CursorVisitor::VisitStaticAssertDecl(StaticAssertDecl *D) {
1245 if (Visit(MakeCXCursor(D->getAssertExpr(), StmtParent, TU, RegionOfInterest)))
1246 return true;
Richard Trieuf3b77662016-09-13 01:37:01 +00001247 if (StringLiteral *Message = D->getMessage())
1248 if (Visit(MakeCXCursor(Message, StmtParent, TU, RegionOfInterest)))
1249 return true;
Olivier Goffart81978012016-06-09 16:15:55 +00001250 return false;
1251}
1252
Olivier Goffartd211c642016-11-04 06:29:27 +00001253bool CursorVisitor::VisitFriendDecl(FriendDecl *D) {
1254 if (NamedDecl *FriendD = D->getFriendDecl()) {
1255 if (Visit(MakeCXCursor(FriendD, TU, RegionOfInterest)))
1256 return true;
1257 } else if (TypeSourceInfo *TI = D->getFriendType()) {
1258 if (Visit(TI->getTypeLoc()))
1259 return true;
1260 }
1261 return false;
1262}
1263
Guy Benyei11169dd2012-12-18 14:30:41 +00001264bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
1265 switch (Name.getName().getNameKind()) {
1266 case clang::DeclarationName::Identifier:
1267 case clang::DeclarationName::CXXLiteralOperatorName:
1268 case clang::DeclarationName::CXXOperatorName:
1269 case clang::DeclarationName::CXXUsingDirective:
1270 return false;
1271
1272 case clang::DeclarationName::CXXConstructorName:
1273 case clang::DeclarationName::CXXDestructorName:
1274 case clang::DeclarationName::CXXConversionFunctionName:
1275 if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
1276 return Visit(TSInfo->getTypeLoc());
1277 return false;
1278
1279 case clang::DeclarationName::ObjCZeroArgSelector:
1280 case clang::DeclarationName::ObjCOneArgSelector:
1281 case clang::DeclarationName::ObjCMultiArgSelector:
1282 // FIXME: Per-identifier location info?
1283 return false;
1284 }
1285
1286 llvm_unreachable("Invalid DeclarationName::Kind!");
1287}
1288
1289bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS,
1290 SourceRange Range) {
1291 // FIXME: This whole routine is a hack to work around the lack of proper
1292 // source information in nested-name-specifiers (PR5791). Since we do have
1293 // a beginning source location, we can visit the first component of the
1294 // nested-name-specifier, if it's a single-token component.
1295 if (!NNS)
1296 return false;
1297
1298 // Get the first component in the nested-name-specifier.
1299 while (NestedNameSpecifier *Prefix = NNS->getPrefix())
1300 NNS = Prefix;
1301
1302 switch (NNS->getKind()) {
1303 case NestedNameSpecifier::Namespace:
1304 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(),
1305 TU));
1306
1307 case NestedNameSpecifier::NamespaceAlias:
1308 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
1309 Range.getBegin(), TU));
1310
1311 case NestedNameSpecifier::TypeSpec: {
1312 // If the type has a form where we know that the beginning of the source
1313 // range matches up with a reference cursor. Visit the appropriate reference
1314 // cursor.
1315 const Type *T = NNS->getAsType();
1316 if (const TypedefType *Typedef = dyn_cast<TypedefType>(T))
1317 return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU));
1318 if (const TagType *Tag = dyn_cast<TagType>(T))
1319 return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU));
1320 if (const TemplateSpecializationType *TST
1321 = dyn_cast<TemplateSpecializationType>(T))
1322 return VisitTemplateName(TST->getTemplateName(), Range.getBegin());
1323 break;
1324 }
1325
1326 case NestedNameSpecifier::TypeSpecWithTemplate:
1327 case NestedNameSpecifier::Global:
1328 case NestedNameSpecifier::Identifier:
Nikola Smiljanic67860242014-09-26 00:28:20 +00001329 case NestedNameSpecifier::Super:
Guy Benyei11169dd2012-12-18 14:30:41 +00001330 break;
1331 }
1332
1333 return false;
1334}
1335
1336bool
1337CursorVisitor::VisitNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
1338 SmallVector<NestedNameSpecifierLoc, 4> Qualifiers;
1339 for (; Qualifier; Qualifier = Qualifier.getPrefix())
1340 Qualifiers.push_back(Qualifier);
1341
1342 while (!Qualifiers.empty()) {
1343 NestedNameSpecifierLoc Q = Qualifiers.pop_back_val();
1344 NestedNameSpecifier *NNS = Q.getNestedNameSpecifier();
1345 switch (NNS->getKind()) {
1346 case NestedNameSpecifier::Namespace:
1347 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(),
1348 Q.getLocalBeginLoc(),
1349 TU)))
1350 return true;
1351
1352 break;
1353
1354 case NestedNameSpecifier::NamespaceAlias:
1355 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
1356 Q.getLocalBeginLoc(),
1357 TU)))
1358 return true;
1359
1360 break;
1361
1362 case NestedNameSpecifier::TypeSpec:
1363 case NestedNameSpecifier::TypeSpecWithTemplate:
1364 if (Visit(Q.getTypeLoc()))
1365 return true;
1366
1367 break;
1368
1369 case NestedNameSpecifier::Global:
1370 case NestedNameSpecifier::Identifier:
Nikola Smiljanic67860242014-09-26 00:28:20 +00001371 case NestedNameSpecifier::Super:
Guy Benyei11169dd2012-12-18 14:30:41 +00001372 break;
1373 }
1374 }
1375
1376 return false;
1377}
1378
1379bool CursorVisitor::VisitTemplateParameters(
1380 const TemplateParameterList *Params) {
1381 if (!Params)
1382 return false;
1383
1384 for (TemplateParameterList::const_iterator P = Params->begin(),
1385 PEnd = Params->end();
1386 P != PEnd; ++P) {
1387 if (Visit(MakeCXCursor(*P, TU, RegionOfInterest)))
1388 return true;
1389 }
1390
1391 return false;
1392}
1393
1394bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) {
1395 switch (Name.getKind()) {
1396 case TemplateName::Template:
1397 return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
1398
1399 case TemplateName::OverloadedTemplate:
1400 // Visit the overloaded template set.
1401 if (Visit(MakeCursorOverloadedDeclRef(Name, Loc, TU)))
1402 return true;
1403
1404 return false;
1405
1406 case TemplateName::DependentTemplate:
1407 // FIXME: Visit nested-name-specifier.
1408 return false;
1409
1410 case TemplateName::QualifiedTemplate:
1411 // FIXME: Visit nested-name-specifier.
1412 return Visit(MakeCursorTemplateRef(
1413 Name.getAsQualifiedTemplateName()->getDecl(),
1414 Loc, TU));
1415
1416 case TemplateName::SubstTemplateTemplateParm:
1417 return Visit(MakeCursorTemplateRef(
1418 Name.getAsSubstTemplateTemplateParm()->getParameter(),
1419 Loc, TU));
1420
1421 case TemplateName::SubstTemplateTemplateParmPack:
1422 return Visit(MakeCursorTemplateRef(
1423 Name.getAsSubstTemplateTemplateParmPack()->getParameterPack(),
1424 Loc, TU));
1425 }
1426
1427 llvm_unreachable("Invalid TemplateName::Kind!");
1428}
1429
1430bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
1431 switch (TAL.getArgument().getKind()) {
1432 case TemplateArgument::Null:
1433 case TemplateArgument::Integral:
1434 case TemplateArgument::Pack:
1435 return false;
1436
1437 case TemplateArgument::Type:
1438 if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
1439 return Visit(TSInfo->getTypeLoc());
1440 return false;
1441
1442 case TemplateArgument::Declaration:
1443 if (Expr *E = TAL.getSourceDeclExpression())
1444 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
1445 return false;
1446
1447 case TemplateArgument::NullPtr:
1448 if (Expr *E = TAL.getSourceNullPtrExpression())
1449 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
1450 return false;
1451
1452 case TemplateArgument::Expression:
1453 if (Expr *E = TAL.getSourceExpression())
1454 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
1455 return false;
1456
1457 case TemplateArgument::Template:
1458 case TemplateArgument::TemplateExpansion:
1459 if (VisitNestedNameSpecifierLoc(TAL.getTemplateQualifierLoc()))
1460 return true;
1461
1462 return VisitTemplateName(TAL.getArgument().getAsTemplateOrTemplatePattern(),
1463 TAL.getTemplateNameLoc());
1464 }
1465
1466 llvm_unreachable("Invalid TemplateArgument::Kind!");
1467}
1468
1469bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1470 return VisitDeclContext(D);
1471}
1472
1473bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1474 return Visit(TL.getUnqualifiedLoc());
1475}
1476
1477bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
1478 ASTContext &Context = AU->getASTContext();
1479
1480 // Some builtin types (such as Objective-C's "id", "sel", and
1481 // "Class") have associated declarations. Create cursors for those.
1482 QualType VisitType;
1483 switch (TL.getTypePtr()->getKind()) {
1484
1485 case BuiltinType::Void:
1486 case BuiltinType::NullPtr:
1487 case BuiltinType::Dependent:
Alexey Bader954ba212016-04-08 13:40:33 +00001488#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1489 case BuiltinType::Id:
Alexey Baderb62f1442016-04-13 08:33:41 +00001490#include "clang/Basic/OpenCLImageTypes.def"
NAKAMURA Takumi288c42e2013-02-07 12:47:42 +00001491 case BuiltinType::OCLSampler:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001492 case BuiltinType::OCLEvent:
Alexey Bader9c8453f2015-09-15 11:18:52 +00001493 case BuiltinType::OCLClkEvent:
1494 case BuiltinType::OCLQueue:
1495 case BuiltinType::OCLNDRange:
1496 case BuiltinType::OCLReserveID:
Guy Benyei11169dd2012-12-18 14:30:41 +00001497#define BUILTIN_TYPE(Id, SingletonId)
1498#define SIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
1499#define UNSIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
1500#define FLOATING_TYPE(Id, SingletonId) case BuiltinType::Id:
1501#define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id:
1502#include "clang/AST/BuiltinTypes.def"
1503 break;
1504
1505 case BuiltinType::ObjCId:
1506 VisitType = Context.getObjCIdType();
1507 break;
1508
1509 case BuiltinType::ObjCClass:
1510 VisitType = Context.getObjCClassType();
1511 break;
1512
1513 case BuiltinType::ObjCSel:
1514 VisitType = Context.getObjCSelType();
1515 break;
1516 }
1517
1518 if (!VisitType.isNull()) {
1519 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
1520 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
1521 TU));
1522 }
1523
1524 return false;
1525}
1526
1527bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
1528 return Visit(MakeCursorTypeRef(TL.getTypedefNameDecl(), TL.getNameLoc(), TU));
1529}
1530
1531bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
1532 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1533}
1534
1535bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
1536 if (TL.isDefinition())
1537 return Visit(MakeCXCursor(TL.getDecl(), TU, RegionOfInterest));
1538
1539 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1540}
1541
1542bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
1543 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1544}
1545
1546bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
Hans Wennborg59dbe862015-09-29 20:56:43 +00001547 return Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU));
Guy Benyei11169dd2012-12-18 14:30:41 +00001548}
1549
Manman Rene6be26c2016-09-13 17:25:08 +00001550bool CursorVisitor::VisitObjCTypeParamTypeLoc(ObjCTypeParamTypeLoc TL) {
1551 if (Visit(MakeCursorTypeRef(TL.getDecl(), TL.getLocStart(), TU)))
1552 return true;
1553 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1554 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1555 TU)))
1556 return true;
1557 }
1558
1559 return false;
1560}
1561
Guy Benyei11169dd2012-12-18 14:30:41 +00001562bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1563 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
1564 return true;
1565
Douglas Gregore9d95f12015-07-07 03:57:35 +00001566 for (unsigned I = 0, N = TL.getNumTypeArgs(); I != N; ++I) {
1567 if (Visit(TL.getTypeArgTInfo(I)->getTypeLoc()))
1568 return true;
1569 }
1570
Guy Benyei11169dd2012-12-18 14:30:41 +00001571 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1572 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1573 TU)))
1574 return true;
1575 }
1576
1577 return false;
1578}
1579
1580bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
1581 return Visit(TL.getPointeeLoc());
1582}
1583
1584bool CursorVisitor::VisitParenTypeLoc(ParenTypeLoc TL) {
1585 return Visit(TL.getInnerLoc());
1586}
1587
1588bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
1589 return Visit(TL.getPointeeLoc());
1590}
1591
1592bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1593 return Visit(TL.getPointeeLoc());
1594}
1595
1596bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1597 return Visit(TL.getPointeeLoc());
1598}
1599
1600bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
1601 return Visit(TL.getPointeeLoc());
1602}
1603
1604bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
1605 return Visit(TL.getPointeeLoc());
1606}
1607
1608bool CursorVisitor::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
1609 return Visit(TL.getModifiedLoc());
1610}
1611
1612bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
1613 bool SkipResultType) {
Alp Toker42a16a62014-01-25 23:51:36 +00001614 if (!SkipResultType && Visit(TL.getReturnLoc()))
Guy Benyei11169dd2012-12-18 14:30:41 +00001615 return true;
1616
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00001617 for (unsigned I = 0, N = TL.getNumParams(); I != N; ++I)
1618 if (Decl *D = TL.getParam(I))
Guy Benyei11169dd2012-12-18 14:30:41 +00001619 if (Visit(MakeCXCursor(D, TU, RegionOfInterest)))
1620 return true;
1621
1622 return false;
1623}
1624
1625bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
1626 if (Visit(TL.getElementLoc()))
1627 return true;
1628
1629 if (Expr *Size = TL.getSizeExpr())
1630 return Visit(MakeCXCursor(Size, StmtParent, TU, RegionOfInterest));
1631
1632 return false;
1633}
1634
Reid Kleckner8a365022013-06-24 17:51:48 +00001635bool CursorVisitor::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
1636 return Visit(TL.getOriginalLoc());
1637}
1638
Reid Kleckner0503a872013-12-05 01:23:43 +00001639bool CursorVisitor::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
1640 return Visit(TL.getOriginalLoc());
1641}
1642
Guy Benyei11169dd2012-12-18 14:30:41 +00001643bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
1644 TemplateSpecializationTypeLoc TL) {
1645 // Visit the template name.
1646 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1647 TL.getTemplateNameLoc()))
1648 return true;
1649
1650 // Visit the template arguments.
1651 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1652 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1653 return true;
1654
1655 return false;
1656}
1657
1658bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1659 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
1660}
1661
1662bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1663 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1664 return Visit(TSInfo->getTypeLoc());
1665
1666 return false;
1667}
1668
1669bool CursorVisitor::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
1670 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1671 return Visit(TSInfo->getTypeLoc());
1672
1673 return false;
1674}
1675
1676bool CursorVisitor::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
Hans Wennborg59dbe862015-09-29 20:56:43 +00001677 return VisitNestedNameSpecifierLoc(TL.getQualifierLoc());
Guy Benyei11169dd2012-12-18 14:30:41 +00001678}
1679
1680bool CursorVisitor::VisitDependentTemplateSpecializationTypeLoc(
1681 DependentTemplateSpecializationTypeLoc TL) {
1682 // Visit the nested-name-specifier, if there is one.
1683 if (TL.getQualifierLoc() &&
1684 VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1685 return true;
1686
1687 // Visit the template arguments.
1688 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1689 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1690 return true;
1691
1692 return false;
1693}
1694
1695bool CursorVisitor::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
1696 if (VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1697 return true;
1698
1699 return Visit(TL.getNamedTypeLoc());
1700}
1701
1702bool CursorVisitor::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
1703 return Visit(TL.getPatternLoc());
1704}
1705
1706bool CursorVisitor::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
1707 if (Expr *E = TL.getUnderlyingExpr())
1708 return Visit(MakeCXCursor(E, StmtParent, TU));
1709
1710 return false;
1711}
1712
1713bool CursorVisitor::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
1714 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1715}
1716
1717bool CursorVisitor::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
1718 return Visit(TL.getValueLoc());
1719}
1720
Xiuli Pan9c14e282016-01-09 12:53:17 +00001721bool CursorVisitor::VisitPipeTypeLoc(PipeTypeLoc TL) {
1722 return Visit(TL.getValueLoc());
1723}
1724
Guy Benyei11169dd2012-12-18 14:30:41 +00001725#define DEFAULT_TYPELOC_IMPL(CLASS, PARENT) \
1726bool CursorVisitor::Visit##CLASS##TypeLoc(CLASS##TypeLoc TL) { \
1727 return Visit##PARENT##Loc(TL); \
1728}
1729
1730DEFAULT_TYPELOC_IMPL(Complex, Type)
1731DEFAULT_TYPELOC_IMPL(ConstantArray, ArrayType)
1732DEFAULT_TYPELOC_IMPL(IncompleteArray, ArrayType)
1733DEFAULT_TYPELOC_IMPL(VariableArray, ArrayType)
1734DEFAULT_TYPELOC_IMPL(DependentSizedArray, ArrayType)
1735DEFAULT_TYPELOC_IMPL(DependentSizedExtVector, Type)
1736DEFAULT_TYPELOC_IMPL(Vector, Type)
1737DEFAULT_TYPELOC_IMPL(ExtVector, VectorType)
1738DEFAULT_TYPELOC_IMPL(FunctionProto, FunctionType)
1739DEFAULT_TYPELOC_IMPL(FunctionNoProto, FunctionType)
1740DEFAULT_TYPELOC_IMPL(Record, TagType)
1741DEFAULT_TYPELOC_IMPL(Enum, TagType)
1742DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParm, Type)
1743DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParmPack, Type)
1744DEFAULT_TYPELOC_IMPL(Auto, Type)
1745
1746bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
1747 // Visit the nested-name-specifier, if present.
1748 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1749 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1750 return true;
1751
1752 if (D->isCompleteDefinition()) {
Aaron Ballman574705e2014-03-13 15:41:46 +00001753 for (const auto &I : D->bases()) {
1754 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(&I, TU)))
Guy Benyei11169dd2012-12-18 14:30:41 +00001755 return true;
1756 }
1757 }
1758
1759 return VisitTagDecl(D);
1760}
1761
1762bool CursorVisitor::VisitAttributes(Decl *D) {
Aaron Ballmanb97112e2014-03-08 22:19:01 +00001763 for (const auto *I : D->attrs())
1764 if (Visit(MakeCXCursor(I, D, TU)))
Guy Benyei11169dd2012-12-18 14:30:41 +00001765 return true;
1766
1767 return false;
1768}
1769
1770//===----------------------------------------------------------------------===//
1771// Data-recursive visitor methods.
1772//===----------------------------------------------------------------------===//
1773
1774namespace {
1775#define DEF_JOB(NAME, DATA, KIND)\
1776class NAME : public VisitorJob {\
1777public:\
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001778 NAME(const DATA *d, CXCursor parent) : \
1779 VisitorJob(parent, VisitorJob::KIND, d) {} \
Guy Benyei11169dd2012-12-18 14:30:41 +00001780 static bool classof(const VisitorJob *VJ) { return VJ->getKind() == KIND; }\
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001781 const DATA *get() const { return static_cast<const DATA*>(data[0]); }\
Guy Benyei11169dd2012-12-18 14:30:41 +00001782};
1783
1784DEF_JOB(StmtVisit, Stmt, StmtVisitKind)
1785DEF_JOB(MemberExprParts, MemberExpr, MemberExprPartsKind)
1786DEF_JOB(DeclRefExprParts, DeclRefExpr, DeclRefExprPartsKind)
1787DEF_JOB(OverloadExprParts, OverloadExpr, OverloadExprPartsKind)
Guy Benyei11169dd2012-12-18 14:30:41 +00001788DEF_JOB(SizeOfPackExprParts, SizeOfPackExpr, SizeOfPackExprPartsKind)
1789DEF_JOB(LambdaExprParts, LambdaExpr, LambdaExprPartsKind)
1790DEF_JOB(PostChildrenVisit, void, PostChildrenVisitKind)
1791#undef DEF_JOB
1792
James Y Knight04ec5bf2015-12-24 02:59:37 +00001793class ExplicitTemplateArgsVisit : public VisitorJob {
1794public:
1795 ExplicitTemplateArgsVisit(const TemplateArgumentLoc *Begin,
1796 const TemplateArgumentLoc *End, CXCursor parent)
1797 : VisitorJob(parent, VisitorJob::ExplicitTemplateArgsVisitKind, Begin,
1798 End) {}
1799 static bool classof(const VisitorJob *VJ) {
1800 return VJ->getKind() == ExplicitTemplateArgsVisitKind;
1801 }
1802 const TemplateArgumentLoc *begin() const {
1803 return static_cast<const TemplateArgumentLoc *>(data[0]);
1804 }
1805 const TemplateArgumentLoc *end() {
1806 return static_cast<const TemplateArgumentLoc *>(data[1]);
1807 }
1808};
Guy Benyei11169dd2012-12-18 14:30:41 +00001809class DeclVisit : public VisitorJob {
1810public:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001811 DeclVisit(const Decl *D, CXCursor parent, bool isFirst) :
Guy Benyei11169dd2012-12-18 14:30:41 +00001812 VisitorJob(parent, VisitorJob::DeclVisitKind,
Craig Topper69186e72014-06-08 08:38:04 +00001813 D, isFirst ? (void*) 1 : (void*) nullptr) {}
Guy Benyei11169dd2012-12-18 14:30:41 +00001814 static bool classof(const VisitorJob *VJ) {
1815 return VJ->getKind() == DeclVisitKind;
1816 }
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001817 const Decl *get() const { return static_cast<const Decl *>(data[0]); }
Dmitri Gribenkoe5423a72015-03-23 19:23:50 +00001818 bool isFirst() const { return data[1] != nullptr; }
Guy Benyei11169dd2012-12-18 14:30:41 +00001819};
1820class TypeLocVisit : public VisitorJob {
1821public:
1822 TypeLocVisit(TypeLoc tl, CXCursor parent) :
1823 VisitorJob(parent, VisitorJob::TypeLocVisitKind,
1824 tl.getType().getAsOpaquePtr(), tl.getOpaqueData()) {}
1825
1826 static bool classof(const VisitorJob *VJ) {
1827 return VJ->getKind() == TypeLocVisitKind;
1828 }
1829
1830 TypeLoc get() const {
1831 QualType T = QualType::getFromOpaquePtr(data[0]);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001832 return TypeLoc(T, const_cast<void *>(data[1]));
Guy Benyei11169dd2012-12-18 14:30:41 +00001833 }
1834};
1835
1836class LabelRefVisit : public VisitorJob {
1837public:
1838 LabelRefVisit(LabelDecl *LD, SourceLocation labelLoc, CXCursor parent)
1839 : VisitorJob(parent, VisitorJob::LabelRefVisitKind, LD,
1840 labelLoc.getPtrEncoding()) {}
1841
1842 static bool classof(const VisitorJob *VJ) {
1843 return VJ->getKind() == VisitorJob::LabelRefVisitKind;
1844 }
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001845 const LabelDecl *get() const {
1846 return static_cast<const LabelDecl *>(data[0]);
1847 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001848 SourceLocation getLoc() const {
1849 return SourceLocation::getFromPtrEncoding(data[1]); }
1850};
1851
1852class NestedNameSpecifierLocVisit : public VisitorJob {
1853public:
1854 NestedNameSpecifierLocVisit(NestedNameSpecifierLoc Qualifier, CXCursor parent)
1855 : VisitorJob(parent, VisitorJob::NestedNameSpecifierLocVisitKind,
1856 Qualifier.getNestedNameSpecifier(),
1857 Qualifier.getOpaqueData()) { }
1858
1859 static bool classof(const VisitorJob *VJ) {
1860 return VJ->getKind() == VisitorJob::NestedNameSpecifierLocVisitKind;
1861 }
1862
1863 NestedNameSpecifierLoc get() const {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001864 return NestedNameSpecifierLoc(
1865 const_cast<NestedNameSpecifier *>(
1866 static_cast<const NestedNameSpecifier *>(data[0])),
1867 const_cast<void *>(data[1]));
Guy Benyei11169dd2012-12-18 14:30:41 +00001868 }
1869};
1870
1871class DeclarationNameInfoVisit : public VisitorJob {
1872public:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001873 DeclarationNameInfoVisit(const Stmt *S, CXCursor parent)
Dmitri Gribenkodd7dacf2013-02-03 13:19:54 +00001874 : VisitorJob(parent, VisitorJob::DeclarationNameInfoVisitKind, S) {}
Guy Benyei11169dd2012-12-18 14:30:41 +00001875 static bool classof(const VisitorJob *VJ) {
1876 return VJ->getKind() == VisitorJob::DeclarationNameInfoVisitKind;
1877 }
1878 DeclarationNameInfo get() const {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001879 const Stmt *S = static_cast<const Stmt *>(data[0]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001880 switch (S->getStmtClass()) {
1881 default:
1882 llvm_unreachable("Unhandled Stmt");
1883 case clang::Stmt::MSDependentExistsStmtClass:
1884 return cast<MSDependentExistsStmt>(S)->getNameInfo();
1885 case Stmt::CXXDependentScopeMemberExprClass:
1886 return cast<CXXDependentScopeMemberExpr>(S)->getMemberNameInfo();
1887 case Stmt::DependentScopeDeclRefExprClass:
1888 return cast<DependentScopeDeclRefExpr>(S)->getNameInfo();
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001889 case Stmt::OMPCriticalDirectiveClass:
1890 return cast<OMPCriticalDirective>(S)->getDirectiveName();
Guy Benyei11169dd2012-12-18 14:30:41 +00001891 }
1892 }
1893};
1894class MemberRefVisit : public VisitorJob {
1895public:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001896 MemberRefVisit(const FieldDecl *D, SourceLocation L, CXCursor parent)
Guy Benyei11169dd2012-12-18 14:30:41 +00001897 : VisitorJob(parent, VisitorJob::MemberRefVisitKind, D,
1898 L.getPtrEncoding()) {}
1899 static bool classof(const VisitorJob *VJ) {
1900 return VJ->getKind() == VisitorJob::MemberRefVisitKind;
1901 }
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001902 const FieldDecl *get() const {
1903 return static_cast<const FieldDecl *>(data[0]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001904 }
1905 SourceLocation getLoc() const {
1906 return SourceLocation::getFromRawEncoding((unsigned)(uintptr_t) data[1]);
1907 }
1908};
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001909class EnqueueVisitor : public ConstStmtVisitor<EnqueueVisitor, void> {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001910 friend class OMPClauseEnqueue;
Guy Benyei11169dd2012-12-18 14:30:41 +00001911 VisitorWorkList &WL;
1912 CXCursor Parent;
1913public:
1914 EnqueueVisitor(VisitorWorkList &wl, CXCursor parent)
1915 : WL(wl), Parent(parent) {}
1916
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001917 void VisitAddrLabelExpr(const AddrLabelExpr *E);
1918 void VisitBlockExpr(const BlockExpr *B);
1919 void VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
1920 void VisitCompoundStmt(const CompoundStmt *S);
1921 void VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) { /* Do nothing. */ }
1922 void VisitMSDependentExistsStmt(const MSDependentExistsStmt *S);
1923 void VisitCXXDependentScopeMemberExpr(const CXXDependentScopeMemberExpr *E);
1924 void VisitCXXNewExpr(const CXXNewExpr *E);
1925 void VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E);
1926 void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *E);
1927 void VisitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *E);
1928 void VisitCXXTemporaryObjectExpr(const CXXTemporaryObjectExpr *E);
1929 void VisitCXXTypeidExpr(const CXXTypeidExpr *E);
1930 void VisitCXXUnresolvedConstructExpr(const CXXUnresolvedConstructExpr *E);
1931 void VisitCXXUuidofExpr(const CXXUuidofExpr *E);
1932 void VisitCXXCatchStmt(const CXXCatchStmt *S);
Argyrios Kyrtzidis99891242014-11-13 09:03:21 +00001933 void VisitCXXForRangeStmt(const CXXForRangeStmt *S);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001934 void VisitDeclRefExpr(const DeclRefExpr *D);
1935 void VisitDeclStmt(const DeclStmt *S);
1936 void VisitDependentScopeDeclRefExpr(const DependentScopeDeclRefExpr *E);
1937 void VisitDesignatedInitExpr(const DesignatedInitExpr *E);
1938 void VisitExplicitCastExpr(const ExplicitCastExpr *E);
1939 void VisitForStmt(const ForStmt *FS);
1940 void VisitGotoStmt(const GotoStmt *GS);
1941 void VisitIfStmt(const IfStmt *If);
1942 void VisitInitListExpr(const InitListExpr *IE);
1943 void VisitMemberExpr(const MemberExpr *M);
1944 void VisitOffsetOfExpr(const OffsetOfExpr *E);
1945 void VisitObjCEncodeExpr(const ObjCEncodeExpr *E);
1946 void VisitObjCMessageExpr(const ObjCMessageExpr *M);
1947 void VisitOverloadExpr(const OverloadExpr *E);
1948 void VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
1949 void VisitStmt(const Stmt *S);
1950 void VisitSwitchStmt(const SwitchStmt *S);
1951 void VisitWhileStmt(const WhileStmt *W);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001952 void VisitTypeTraitExpr(const TypeTraitExpr *E);
1953 void VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E);
1954 void VisitExpressionTraitExpr(const ExpressionTraitExpr *E);
1955 void VisitUnresolvedMemberExpr(const UnresolvedMemberExpr *U);
1956 void VisitVAArgExpr(const VAArgExpr *E);
1957 void VisitSizeOfPackExpr(const SizeOfPackExpr *E);
1958 void VisitPseudoObjectExpr(const PseudoObjectExpr *E);
1959 void VisitOpaqueValueExpr(const OpaqueValueExpr *E);
1960 void VisitLambdaExpr(const LambdaExpr *E);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001961 void VisitOMPExecutableDirective(const OMPExecutableDirective *D);
Alexander Musman3aaab662014-08-19 11:27:13 +00001962 void VisitOMPLoopDirective(const OMPLoopDirective *D);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001963 void VisitOMPParallelDirective(const OMPParallelDirective *D);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00001964 void VisitOMPSimdDirective(const OMPSimdDirective *D);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001965 void VisitOMPForDirective(const OMPForDirective *D);
Alexander Musmanf82886e2014-09-18 05:12:34 +00001966 void VisitOMPForSimdDirective(const OMPForSimdDirective *D);
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00001967 void VisitOMPSectionsDirective(const OMPSectionsDirective *D);
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001968 void VisitOMPSectionDirective(const OMPSectionDirective *D);
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00001969 void VisitOMPSingleDirective(const OMPSingleDirective *D);
Alexander Musman80c22892014-07-17 08:54:58 +00001970 void VisitOMPMasterDirective(const OMPMasterDirective *D);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001971 void VisitOMPCriticalDirective(const OMPCriticalDirective *D);
Alexey Bataev4acb8592014-07-07 13:01:15 +00001972 void VisitOMPParallelForDirective(const OMPParallelForDirective *D);
Alexander Musmane4e893b2014-09-23 09:33:00 +00001973 void VisitOMPParallelForSimdDirective(const OMPParallelForSimdDirective *D);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001974 void VisitOMPParallelSectionsDirective(const OMPParallelSectionsDirective *D);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001975 void VisitOMPTaskDirective(const OMPTaskDirective *D);
Alexey Bataev68446b72014-07-18 07:47:19 +00001976 void VisitOMPTaskyieldDirective(const OMPTaskyieldDirective *D);
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001977 void VisitOMPBarrierDirective(const OMPBarrierDirective *D);
Alexey Bataev2df347a2014-07-18 10:17:07 +00001978 void VisitOMPTaskwaitDirective(const OMPTaskwaitDirective *D);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001979 void VisitOMPTaskgroupDirective(const OMPTaskgroupDirective *D);
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001980 void
1981 VisitOMPCancellationPointDirective(const OMPCancellationPointDirective *D);
Alexey Bataev80909872015-07-02 11:25:17 +00001982 void VisitOMPCancelDirective(const OMPCancelDirective *D);
Alexey Bataev6125da92014-07-21 11:26:11 +00001983 void VisitOMPFlushDirective(const OMPFlushDirective *D);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001984 void VisitOMPOrderedDirective(const OMPOrderedDirective *D);
Alexey Bataev0162e452014-07-22 10:10:35 +00001985 void VisitOMPAtomicDirective(const OMPAtomicDirective *D);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001986 void VisitOMPTargetDirective(const OMPTargetDirective *D);
Michael Wong65f367f2015-07-21 13:44:28 +00001987 void VisitOMPTargetDataDirective(const OMPTargetDataDirective *D);
Samuel Antaodf67fc42016-01-19 19:15:56 +00001988 void VisitOMPTargetEnterDataDirective(const OMPTargetEnterDataDirective *D);
Samuel Antao72590762016-01-19 20:04:50 +00001989 void VisitOMPTargetExitDataDirective(const OMPTargetExitDataDirective *D);
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00001990 void VisitOMPTargetParallelDirective(const OMPTargetParallelDirective *D);
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00001991 void
1992 VisitOMPTargetParallelForDirective(const OMPTargetParallelForDirective *D);
Alexey Bataev13314bf2014-10-09 04:18:56 +00001993 void VisitOMPTeamsDirective(const OMPTeamsDirective *D);
Alexey Bataev49f6e782015-12-01 04:18:41 +00001994 void VisitOMPTaskLoopDirective(const OMPTaskLoopDirective *D);
Alexey Bataev0a6ed842015-12-03 09:40:15 +00001995 void VisitOMPTaskLoopSimdDirective(const OMPTaskLoopSimdDirective *D);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00001996 void VisitOMPDistributeDirective(const OMPDistributeDirective *D);
Carlo Bertolli9925f152016-06-27 14:55:37 +00001997 void VisitOMPDistributeParallelForDirective(
1998 const OMPDistributeParallelForDirective *D);
Kelvin Li4a39add2016-07-05 05:00:15 +00001999 void VisitOMPDistributeParallelForSimdDirective(
2000 const OMPDistributeParallelForSimdDirective *D);
Kelvin Li787f3fc2016-07-06 04:45:38 +00002001 void VisitOMPDistributeSimdDirective(const OMPDistributeSimdDirective *D);
Kelvin Lia579b912016-07-14 02:54:56 +00002002 void VisitOMPTargetParallelForSimdDirective(
2003 const OMPTargetParallelForSimdDirective *D);
Kelvin Li986330c2016-07-20 22:57:10 +00002004 void VisitOMPTargetSimdDirective(const OMPTargetSimdDirective *D);
Kelvin Li02532872016-08-05 14:37:37 +00002005 void VisitOMPTeamsDistributeDirective(const OMPTeamsDistributeDirective *D);
Kelvin Li4e325f72016-10-25 12:50:55 +00002006 void VisitOMPTeamsDistributeSimdDirective(
2007 const OMPTeamsDistributeSimdDirective *D);
Kelvin Li579e41c2016-11-30 23:51:03 +00002008 void VisitOMPTeamsDistributeParallelForSimdDirective(
2009 const OMPTeamsDistributeParallelForSimdDirective *D);
Kelvin Li7ade93f2016-12-09 03:24:30 +00002010 void VisitOMPTeamsDistributeParallelForDirective(
2011 const OMPTeamsDistributeParallelForDirective *D);
Kelvin Libf594a52016-12-17 05:48:59 +00002012 void VisitOMPTargetTeamsDirective(const OMPTargetTeamsDirective *D);
Kelvin Li83c451e2016-12-25 04:52:54 +00002013 void VisitOMPTargetTeamsDistributeDirective(
2014 const OMPTargetTeamsDistributeDirective *D);
Kelvin Li80e8f562016-12-29 22:16:30 +00002015 void VisitOMPTargetTeamsDistributeParallelForDirective(
2016 const OMPTargetTeamsDistributeParallelForDirective *D);
Kelvin Li1851df52017-01-03 05:23:48 +00002017 void VisitOMPTargetTeamsDistributeParallelForSimdDirective(
2018 const OMPTargetTeamsDistributeParallelForSimdDirective *D);
Kelvin Lida681182017-01-10 18:08:18 +00002019 void VisitOMPTargetTeamsDistributeSimdDirective(
2020 const OMPTargetTeamsDistributeSimdDirective *D);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002021
Guy Benyei11169dd2012-12-18 14:30:41 +00002022private:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002023 void AddDeclarationNameInfo(const Stmt *S);
Guy Benyei11169dd2012-12-18 14:30:41 +00002024 void AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier);
James Y Knight04ec5bf2015-12-24 02:59:37 +00002025 void AddExplicitTemplateArgs(const TemplateArgumentLoc *A,
2026 unsigned NumTemplateArgs);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002027 void AddMemberRef(const FieldDecl *D, SourceLocation L);
2028 void AddStmt(const Stmt *S);
2029 void AddDecl(const Decl *D, bool isFirst = true);
Guy Benyei11169dd2012-12-18 14:30:41 +00002030 void AddTypeLoc(TypeSourceInfo *TI);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002031 void EnqueueChildren(const Stmt *S);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002032 void EnqueueChildren(const OMPClause *S);
Guy Benyei11169dd2012-12-18 14:30:41 +00002033};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002034} // end anonyous namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00002035
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002036void EnqueueVisitor::AddDeclarationNameInfo(const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002037 // 'S' should always be non-null, since it comes from the
2038 // statement we are visiting.
2039 WL.push_back(DeclarationNameInfoVisit(S, Parent));
2040}
2041
2042void
2043EnqueueVisitor::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
2044 if (Qualifier)
2045 WL.push_back(NestedNameSpecifierLocVisit(Qualifier, Parent));
2046}
2047
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002048void EnqueueVisitor::AddStmt(const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002049 if (S)
2050 WL.push_back(StmtVisit(S, Parent));
2051}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002052void EnqueueVisitor::AddDecl(const Decl *D, bool isFirst) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002053 if (D)
2054 WL.push_back(DeclVisit(D, Parent, isFirst));
2055}
James Y Knight04ec5bf2015-12-24 02:59:37 +00002056void EnqueueVisitor::AddExplicitTemplateArgs(const TemplateArgumentLoc *A,
2057 unsigned NumTemplateArgs) {
2058 WL.push_back(ExplicitTemplateArgsVisit(A, A + NumTemplateArgs, Parent));
Guy Benyei11169dd2012-12-18 14:30:41 +00002059}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002060void EnqueueVisitor::AddMemberRef(const FieldDecl *D, SourceLocation L) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002061 if (D)
2062 WL.push_back(MemberRefVisit(D, L, Parent));
2063}
2064void EnqueueVisitor::AddTypeLoc(TypeSourceInfo *TI) {
2065 if (TI)
2066 WL.push_back(TypeLocVisit(TI->getTypeLoc(), Parent));
2067 }
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002068void EnqueueVisitor::EnqueueChildren(const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002069 unsigned size = WL.size();
Benjamin Kramer642f1732015-07-02 21:03:14 +00002070 for (const Stmt *SubStmt : S->children()) {
2071 AddStmt(SubStmt);
Guy Benyei11169dd2012-12-18 14:30:41 +00002072 }
2073 if (size == WL.size())
2074 return;
2075 // Now reverse the entries we just added. This will match the DFS
2076 // ordering performed by the worklist.
2077 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2078 std::reverse(I, E);
2079}
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002080namespace {
2081class OMPClauseEnqueue : public ConstOMPClauseVisitor<OMPClauseEnqueue> {
2082 EnqueueVisitor *Visitor;
Alexey Bataev756c1962013-09-24 03:17:45 +00002083 /// \brief Process clauses with list of variables.
2084 template <typename T>
2085 void VisitOMPClauseList(T *Node);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002086public:
2087 OMPClauseEnqueue(EnqueueVisitor *Visitor) : Visitor(Visitor) { }
2088#define OPENMP_CLAUSE(Name, Class) \
2089 void Visit##Class(const Class *C);
2090#include "clang/Basic/OpenMPKinds.def"
Alexey Bataev3392d762016-02-16 11:18:12 +00002091 void VisitOMPClauseWithPreInit(const OMPClauseWithPreInit *C);
Alexey Bataev005248a2016-02-25 05:25:57 +00002092 void VisitOMPClauseWithPostUpdate(const OMPClauseWithPostUpdate *C);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002093};
2094
Alexey Bataev3392d762016-02-16 11:18:12 +00002095void OMPClauseEnqueue::VisitOMPClauseWithPreInit(
2096 const OMPClauseWithPreInit *C) {
2097 Visitor->AddStmt(C->getPreInitStmt());
2098}
2099
Alexey Bataev005248a2016-02-25 05:25:57 +00002100void OMPClauseEnqueue::VisitOMPClauseWithPostUpdate(
2101 const OMPClauseWithPostUpdate *C) {
Alexey Bataev37e594c2016-03-04 07:21:16 +00002102 VisitOMPClauseWithPreInit(C);
Alexey Bataev005248a2016-02-25 05:25:57 +00002103 Visitor->AddStmt(C->getPostUpdateExpr());
2104}
2105
Alexey Bataevaadd52e2014-02-13 05:29:23 +00002106void OMPClauseEnqueue::VisitOMPIfClause(const OMPIfClause *C) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00002107 VisitOMPClauseWithPreInit(C);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00002108 Visitor->AddStmt(C->getCondition());
2109}
2110
Alexey Bataev3778b602014-07-17 07:32:53 +00002111void OMPClauseEnqueue::VisitOMPFinalClause(const OMPFinalClause *C) {
2112 Visitor->AddStmt(C->getCondition());
2113}
2114
Alexey Bataev568a8332014-03-06 06:15:19 +00002115void OMPClauseEnqueue::VisitOMPNumThreadsClause(const OMPNumThreadsClause *C) {
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00002116 VisitOMPClauseWithPreInit(C);
Alexey Bataev568a8332014-03-06 06:15:19 +00002117 Visitor->AddStmt(C->getNumThreads());
2118}
2119
Alexey Bataev62c87d22014-03-21 04:51:18 +00002120void OMPClauseEnqueue::VisitOMPSafelenClause(const OMPSafelenClause *C) {
2121 Visitor->AddStmt(C->getSafelen());
2122}
2123
Alexey Bataev66b15b52015-08-21 11:14:16 +00002124void OMPClauseEnqueue::VisitOMPSimdlenClause(const OMPSimdlenClause *C) {
2125 Visitor->AddStmt(C->getSimdlen());
2126}
2127
Alexander Musman8bd31e62014-05-27 15:12:19 +00002128void OMPClauseEnqueue::VisitOMPCollapseClause(const OMPCollapseClause *C) {
2129 Visitor->AddStmt(C->getNumForLoops());
2130}
2131
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002132void OMPClauseEnqueue::VisitOMPDefaultClause(const OMPDefaultClause *C) { }
Alexey Bataev756c1962013-09-24 03:17:45 +00002133
Alexey Bataevbcbadb62014-05-06 06:04:14 +00002134void OMPClauseEnqueue::VisitOMPProcBindClause(const OMPProcBindClause *C) { }
2135
Alexey Bataev56dafe82014-06-20 07:16:17 +00002136void OMPClauseEnqueue::VisitOMPScheduleClause(const OMPScheduleClause *C) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002137 VisitOMPClauseWithPreInit(C);
Alexey Bataev56dafe82014-06-20 07:16:17 +00002138 Visitor->AddStmt(C->getChunkSize());
2139}
2140
Alexey Bataev10e775f2015-07-30 11:36:16 +00002141void OMPClauseEnqueue::VisitOMPOrderedClause(const OMPOrderedClause *C) {
2142 Visitor->AddStmt(C->getNumForLoops());
2143}
Alexey Bataev142e1fc2014-06-20 09:44:06 +00002144
Alexey Bataev236070f2014-06-20 11:19:47 +00002145void OMPClauseEnqueue::VisitOMPNowaitClause(const OMPNowaitClause *) {}
2146
Alexey Bataev7aea99a2014-07-17 12:19:31 +00002147void OMPClauseEnqueue::VisitOMPUntiedClause(const OMPUntiedClause *) {}
2148
Alexey Bataev74ba3a52014-07-17 12:47:03 +00002149void OMPClauseEnqueue::VisitOMPMergeableClause(const OMPMergeableClause *) {}
2150
Alexey Bataevf98b00c2014-07-23 02:27:21 +00002151void OMPClauseEnqueue::VisitOMPReadClause(const OMPReadClause *) {}
2152
Alexey Bataevdea47612014-07-23 07:46:59 +00002153void OMPClauseEnqueue::VisitOMPWriteClause(const OMPWriteClause *) {}
2154
Alexey Bataev67a4f222014-07-23 10:25:33 +00002155void OMPClauseEnqueue::VisitOMPUpdateClause(const OMPUpdateClause *) {}
2156
Alexey Bataev459dec02014-07-24 06:46:57 +00002157void OMPClauseEnqueue::VisitOMPCaptureClause(const OMPCaptureClause *) {}
2158
Alexey Bataev82bad8b2014-07-24 08:55:34 +00002159void OMPClauseEnqueue::VisitOMPSeqCstClause(const OMPSeqCstClause *) {}
2160
Alexey Bataev346265e2015-09-25 10:37:12 +00002161void OMPClauseEnqueue::VisitOMPThreadsClause(const OMPThreadsClause *) {}
2162
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002163void OMPClauseEnqueue::VisitOMPSIMDClause(const OMPSIMDClause *) {}
2164
Alexey Bataevb825de12015-12-07 10:51:44 +00002165void OMPClauseEnqueue::VisitOMPNogroupClause(const OMPNogroupClause *) {}
2166
Michael Wonge710d542015-08-07 16:16:36 +00002167void OMPClauseEnqueue::VisitOMPDeviceClause(const OMPDeviceClause *C) {
2168 Visitor->AddStmt(C->getDevice());
2169}
2170
Kelvin Li099bb8c2015-11-24 20:50:12 +00002171void OMPClauseEnqueue::VisitOMPNumTeamsClause(const OMPNumTeamsClause *C) {
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00002172 VisitOMPClauseWithPreInit(C);
Kelvin Li099bb8c2015-11-24 20:50:12 +00002173 Visitor->AddStmt(C->getNumTeams());
2174}
2175
Kelvin Lia15fb1a2015-11-27 18:47:36 +00002176void OMPClauseEnqueue::VisitOMPThreadLimitClause(const OMPThreadLimitClause *C) {
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00002177 VisitOMPClauseWithPreInit(C);
Kelvin Lia15fb1a2015-11-27 18:47:36 +00002178 Visitor->AddStmt(C->getThreadLimit());
2179}
2180
Alexey Bataeva0569352015-12-01 10:17:31 +00002181void OMPClauseEnqueue::VisitOMPPriorityClause(const OMPPriorityClause *C) {
2182 Visitor->AddStmt(C->getPriority());
2183}
2184
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00002185void OMPClauseEnqueue::VisitOMPGrainsizeClause(const OMPGrainsizeClause *C) {
2186 Visitor->AddStmt(C->getGrainsize());
2187}
2188
Alexey Bataev382967a2015-12-08 12:06:20 +00002189void OMPClauseEnqueue::VisitOMPNumTasksClause(const OMPNumTasksClause *C) {
2190 Visitor->AddStmt(C->getNumTasks());
2191}
2192
Alexey Bataev28c75412015-12-15 08:19:24 +00002193void OMPClauseEnqueue::VisitOMPHintClause(const OMPHintClause *C) {
2194 Visitor->AddStmt(C->getHint());
2195}
2196
Alexey Bataev756c1962013-09-24 03:17:45 +00002197template<typename T>
2198void OMPClauseEnqueue::VisitOMPClauseList(T *Node) {
Alexey Bataev03b340a2014-10-21 03:16:40 +00002199 for (const auto *I : Node->varlists()) {
Aaron Ballman2205d2a2014-03-14 15:55:35 +00002200 Visitor->AddStmt(I);
Alexey Bataev03b340a2014-10-21 03:16:40 +00002201 }
Alexey Bataev756c1962013-09-24 03:17:45 +00002202}
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002203
2204void OMPClauseEnqueue::VisitOMPPrivateClause(const OMPPrivateClause *C) {
Alexey Bataev756c1962013-09-24 03:17:45 +00002205 VisitOMPClauseList(C);
Alexey Bataev03b340a2014-10-21 03:16:40 +00002206 for (const auto *E : C->private_copies()) {
2207 Visitor->AddStmt(E);
2208 }
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002209}
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002210void OMPClauseEnqueue::VisitOMPFirstprivateClause(
2211 const OMPFirstprivateClause *C) {
2212 VisitOMPClauseList(C);
Alexey Bataev417089f2016-02-17 13:19:37 +00002213 VisitOMPClauseWithPreInit(C);
2214 for (const auto *E : C->private_copies()) {
2215 Visitor->AddStmt(E);
2216 }
2217 for (const auto *E : C->inits()) {
2218 Visitor->AddStmt(E);
2219 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002220}
Alexander Musman1bb328c2014-06-04 13:06:39 +00002221void OMPClauseEnqueue::VisitOMPLastprivateClause(
2222 const OMPLastprivateClause *C) {
2223 VisitOMPClauseList(C);
Alexey Bataev005248a2016-02-25 05:25:57 +00002224 VisitOMPClauseWithPostUpdate(C);
Alexey Bataev38e89532015-04-16 04:54:05 +00002225 for (auto *E : C->private_copies()) {
2226 Visitor->AddStmt(E);
2227 }
2228 for (auto *E : C->source_exprs()) {
2229 Visitor->AddStmt(E);
2230 }
2231 for (auto *E : C->destination_exprs()) {
2232 Visitor->AddStmt(E);
2233 }
2234 for (auto *E : C->assignment_ops()) {
2235 Visitor->AddStmt(E);
2236 }
Alexander Musman1bb328c2014-06-04 13:06:39 +00002237}
Alexey Bataev758e55e2013-09-06 18:03:48 +00002238void OMPClauseEnqueue::VisitOMPSharedClause(const OMPSharedClause *C) {
Alexey Bataev756c1962013-09-24 03:17:45 +00002239 VisitOMPClauseList(C);
Alexey Bataev758e55e2013-09-06 18:03:48 +00002240}
Alexey Bataevc5e02582014-06-16 07:08:35 +00002241void OMPClauseEnqueue::VisitOMPReductionClause(const OMPReductionClause *C) {
2242 VisitOMPClauseList(C);
Alexey Bataev61205072016-03-02 04:57:40 +00002243 VisitOMPClauseWithPostUpdate(C);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00002244 for (auto *E : C->privates()) {
2245 Visitor->AddStmt(E);
2246 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002247 for (auto *E : C->lhs_exprs()) {
2248 Visitor->AddStmt(E);
2249 }
2250 for (auto *E : C->rhs_exprs()) {
2251 Visitor->AddStmt(E);
2252 }
2253 for (auto *E : C->reduction_ops()) {
2254 Visitor->AddStmt(E);
2255 }
Alexey Bataevc5e02582014-06-16 07:08:35 +00002256}
Alexander Musman8dba6642014-04-22 13:09:42 +00002257void OMPClauseEnqueue::VisitOMPLinearClause(const OMPLinearClause *C) {
2258 VisitOMPClauseList(C);
Alexey Bataev78849fb2016-03-09 09:49:00 +00002259 VisitOMPClauseWithPostUpdate(C);
Alexey Bataevbd9fec12015-08-18 06:47:21 +00002260 for (const auto *E : C->privates()) {
2261 Visitor->AddStmt(E);
2262 }
Alexander Musman3276a272015-03-21 10:12:56 +00002263 for (const auto *E : C->inits()) {
2264 Visitor->AddStmt(E);
2265 }
2266 for (const auto *E : C->updates()) {
2267 Visitor->AddStmt(E);
2268 }
2269 for (const auto *E : C->finals()) {
2270 Visitor->AddStmt(E);
2271 }
Alexander Musman8dba6642014-04-22 13:09:42 +00002272 Visitor->AddStmt(C->getStep());
Alexander Musman3276a272015-03-21 10:12:56 +00002273 Visitor->AddStmt(C->getCalcStep());
Alexander Musman8dba6642014-04-22 13:09:42 +00002274}
Alexander Musmanf0d76e72014-05-29 14:36:25 +00002275void OMPClauseEnqueue::VisitOMPAlignedClause(const OMPAlignedClause *C) {
2276 VisitOMPClauseList(C);
2277 Visitor->AddStmt(C->getAlignment());
2278}
Alexey Bataevd48bcd82014-03-31 03:36:38 +00002279void OMPClauseEnqueue::VisitOMPCopyinClause(const OMPCopyinClause *C) {
2280 VisitOMPClauseList(C);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00002281 for (auto *E : C->source_exprs()) {
2282 Visitor->AddStmt(E);
2283 }
2284 for (auto *E : C->destination_exprs()) {
2285 Visitor->AddStmt(E);
2286 }
2287 for (auto *E : C->assignment_ops()) {
2288 Visitor->AddStmt(E);
2289 }
Alexey Bataevd48bcd82014-03-31 03:36:38 +00002290}
Alexey Bataevbae9a792014-06-27 10:37:06 +00002291void
2292OMPClauseEnqueue::VisitOMPCopyprivateClause(const OMPCopyprivateClause *C) {
2293 VisitOMPClauseList(C);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002294 for (auto *E : C->source_exprs()) {
2295 Visitor->AddStmt(E);
2296 }
2297 for (auto *E : C->destination_exprs()) {
2298 Visitor->AddStmt(E);
2299 }
2300 for (auto *E : C->assignment_ops()) {
2301 Visitor->AddStmt(E);
2302 }
Alexey Bataevbae9a792014-06-27 10:37:06 +00002303}
Alexey Bataev6125da92014-07-21 11:26:11 +00002304void OMPClauseEnqueue::VisitOMPFlushClause(const OMPFlushClause *C) {
2305 VisitOMPClauseList(C);
2306}
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00002307void OMPClauseEnqueue::VisitOMPDependClause(const OMPDependClause *C) {
2308 VisitOMPClauseList(C);
2309}
Kelvin Li0bff7af2015-11-23 05:32:03 +00002310void OMPClauseEnqueue::VisitOMPMapClause(const OMPMapClause *C) {
2311 VisitOMPClauseList(C);
2312}
Carlo Bertollib4adf552016-01-15 18:50:31 +00002313void OMPClauseEnqueue::VisitOMPDistScheduleClause(
2314 const OMPDistScheduleClause *C) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002315 VisitOMPClauseWithPreInit(C);
Carlo Bertollib4adf552016-01-15 18:50:31 +00002316 Visitor->AddStmt(C->getChunkSize());
Carlo Bertollib4adf552016-01-15 18:50:31 +00002317}
Alexey Bataev3392d762016-02-16 11:18:12 +00002318void OMPClauseEnqueue::VisitOMPDefaultmapClause(
2319 const OMPDefaultmapClause * /*C*/) {}
Samuel Antao661c0902016-05-26 17:39:58 +00002320void OMPClauseEnqueue::VisitOMPToClause(const OMPToClause *C) {
2321 VisitOMPClauseList(C);
2322}
Samuel Antaoec172c62016-05-26 17:49:04 +00002323void OMPClauseEnqueue::VisitOMPFromClause(const OMPFromClause *C) {
2324 VisitOMPClauseList(C);
2325}
Carlo Bertolli2404b172016-07-13 15:37:16 +00002326void OMPClauseEnqueue::VisitOMPUseDevicePtrClause(const OMPUseDevicePtrClause *C) {
2327 VisitOMPClauseList(C);
2328}
Carlo Bertolli70594e92016-07-13 17:16:49 +00002329void OMPClauseEnqueue::VisitOMPIsDevicePtrClause(const OMPIsDevicePtrClause *C) {
2330 VisitOMPClauseList(C);
2331}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002332}
Alexey Bataev756c1962013-09-24 03:17:45 +00002333
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002334void EnqueueVisitor::EnqueueChildren(const OMPClause *S) {
2335 unsigned size = WL.size();
2336 OMPClauseEnqueue Visitor(this);
2337 Visitor.Visit(S);
2338 if (size == WL.size())
2339 return;
2340 // Now reverse the entries we just added. This will match the DFS
2341 // ordering performed by the worklist.
2342 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2343 std::reverse(I, E);
2344}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002345void EnqueueVisitor::VisitAddrLabelExpr(const AddrLabelExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002346 WL.push_back(LabelRefVisit(E->getLabel(), E->getLabelLoc(), Parent));
2347}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002348void EnqueueVisitor::VisitBlockExpr(const BlockExpr *B) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002349 AddDecl(B->getBlockDecl());
2350}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002351void EnqueueVisitor::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002352 EnqueueChildren(E);
2353 AddTypeLoc(E->getTypeSourceInfo());
2354}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002355void EnqueueVisitor::VisitCompoundStmt(const CompoundStmt *S) {
Pete Cooper57d3f142015-07-30 17:22:52 +00002356 for (auto &I : llvm::reverse(S->body()))
2357 AddStmt(I);
Guy Benyei11169dd2012-12-18 14:30:41 +00002358}
2359void EnqueueVisitor::
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002360VisitMSDependentExistsStmt(const MSDependentExistsStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002361 AddStmt(S->getSubStmt());
2362 AddDeclarationNameInfo(S);
2363 if (NestedNameSpecifierLoc QualifierLoc = S->getQualifierLoc())
2364 AddNestedNameSpecifierLoc(QualifierLoc);
2365}
2366
2367void EnqueueVisitor::
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002368VisitCXXDependentScopeMemberExpr(const CXXDependentScopeMemberExpr *E) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002369 if (E->hasExplicitTemplateArgs())
2370 AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002371 AddDeclarationNameInfo(E);
2372 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
2373 AddNestedNameSpecifierLoc(QualifierLoc);
2374 if (!E->isImplicitAccess())
2375 AddStmt(E->getBase());
2376}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002377void EnqueueVisitor::VisitCXXNewExpr(const CXXNewExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002378 // Enqueue the initializer , if any.
2379 AddStmt(E->getInitializer());
2380 // Enqueue the array size, if any.
2381 AddStmt(E->getArraySize());
2382 // Enqueue the allocated type.
2383 AddTypeLoc(E->getAllocatedTypeSourceInfo());
2384 // Enqueue the placement arguments.
2385 for (unsigned I = E->getNumPlacementArgs(); I > 0; --I)
2386 AddStmt(E->getPlacementArg(I-1));
2387}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002388void EnqueueVisitor::VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CE) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002389 for (unsigned I = CE->getNumArgs(); I > 1 /* Yes, this is 1 */; --I)
2390 AddStmt(CE->getArg(I-1));
2391 AddStmt(CE->getCallee());
2392 AddStmt(CE->getArg(0));
2393}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002394void EnqueueVisitor::VisitCXXPseudoDestructorExpr(
2395 const CXXPseudoDestructorExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002396 // Visit the name of the type being destroyed.
2397 AddTypeLoc(E->getDestroyedTypeInfo());
2398 // Visit the scope type that looks disturbingly like the nested-name-specifier
2399 // but isn't.
2400 AddTypeLoc(E->getScopeTypeInfo());
2401 // Visit the nested-name-specifier.
2402 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
2403 AddNestedNameSpecifierLoc(QualifierLoc);
2404 // Visit base expression.
2405 AddStmt(E->getBase());
2406}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002407void EnqueueVisitor::VisitCXXScalarValueInitExpr(
2408 const CXXScalarValueInitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002409 AddTypeLoc(E->getTypeSourceInfo());
2410}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002411void EnqueueVisitor::VisitCXXTemporaryObjectExpr(
2412 const CXXTemporaryObjectExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002413 EnqueueChildren(E);
2414 AddTypeLoc(E->getTypeSourceInfo());
2415}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002416void EnqueueVisitor::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002417 EnqueueChildren(E);
2418 if (E->isTypeOperand())
2419 AddTypeLoc(E->getTypeOperandSourceInfo());
2420}
2421
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002422void EnqueueVisitor::VisitCXXUnresolvedConstructExpr(
2423 const CXXUnresolvedConstructExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002424 EnqueueChildren(E);
2425 AddTypeLoc(E->getTypeSourceInfo());
2426}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002427void EnqueueVisitor::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002428 EnqueueChildren(E);
2429 if (E->isTypeOperand())
2430 AddTypeLoc(E->getTypeOperandSourceInfo());
2431}
2432
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002433void EnqueueVisitor::VisitCXXCatchStmt(const CXXCatchStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002434 EnqueueChildren(S);
2435 AddDecl(S->getExceptionDecl());
2436}
2437
Argyrios Kyrtzidis99891242014-11-13 09:03:21 +00002438void EnqueueVisitor::VisitCXXForRangeStmt(const CXXForRangeStmt *S) {
Argyrios Kyrtzidiscde70692014-11-13 09:50:19 +00002439 AddStmt(S->getBody());
Argyrios Kyrtzidis99891242014-11-13 09:03:21 +00002440 AddStmt(S->getRangeInit());
Argyrios Kyrtzidiscde70692014-11-13 09:50:19 +00002441 AddDecl(S->getLoopVariable());
Argyrios Kyrtzidis99891242014-11-13 09:03:21 +00002442}
2443
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002444void EnqueueVisitor::VisitDeclRefExpr(const DeclRefExpr *DR) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002445 if (DR->hasExplicitTemplateArgs())
2446 AddExplicitTemplateArgs(DR->getTemplateArgs(), DR->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002447 WL.push_back(DeclRefExprParts(DR, Parent));
2448}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002449void EnqueueVisitor::VisitDependentScopeDeclRefExpr(
2450 const DependentScopeDeclRefExpr *E) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002451 if (E->hasExplicitTemplateArgs())
2452 AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002453 AddDeclarationNameInfo(E);
2454 AddNestedNameSpecifierLoc(E->getQualifierLoc());
2455}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002456void EnqueueVisitor::VisitDeclStmt(const DeclStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002457 unsigned size = WL.size();
2458 bool isFirst = true;
Aaron Ballman535bbcc2014-03-14 17:01:24 +00002459 for (const auto *D : S->decls()) {
2460 AddDecl(D, isFirst);
Guy Benyei11169dd2012-12-18 14:30:41 +00002461 isFirst = false;
2462 }
2463 if (size == WL.size())
2464 return;
2465 // Now reverse the entries we just added. This will match the DFS
2466 // ordering performed by the worklist.
2467 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2468 std::reverse(I, E);
2469}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002470void EnqueueVisitor::VisitDesignatedInitExpr(const DesignatedInitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002471 AddStmt(E->getInit());
David Majnemerf7e36092016-06-23 00:15:04 +00002472 for (const DesignatedInitExpr::Designator &D :
2473 llvm::reverse(E->designators())) {
2474 if (D.isFieldDesignator()) {
2475 if (FieldDecl *Field = D.getField())
2476 AddMemberRef(Field, D.getFieldLoc());
Guy Benyei11169dd2012-12-18 14:30:41 +00002477 continue;
2478 }
David Majnemerf7e36092016-06-23 00:15:04 +00002479 if (D.isArrayDesignator()) {
2480 AddStmt(E->getArrayIndex(D));
Guy Benyei11169dd2012-12-18 14:30:41 +00002481 continue;
2482 }
David Majnemerf7e36092016-06-23 00:15:04 +00002483 assert(D.isArrayRangeDesignator() && "Unknown designator kind");
2484 AddStmt(E->getArrayRangeEnd(D));
2485 AddStmt(E->getArrayRangeStart(D));
Guy Benyei11169dd2012-12-18 14:30:41 +00002486 }
2487}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002488void EnqueueVisitor::VisitExplicitCastExpr(const ExplicitCastExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002489 EnqueueChildren(E);
2490 AddTypeLoc(E->getTypeInfoAsWritten());
2491}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002492void EnqueueVisitor::VisitForStmt(const ForStmt *FS) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002493 AddStmt(FS->getBody());
2494 AddStmt(FS->getInc());
2495 AddStmt(FS->getCond());
2496 AddDecl(FS->getConditionVariable());
2497 AddStmt(FS->getInit());
2498}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002499void EnqueueVisitor::VisitGotoStmt(const GotoStmt *GS) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002500 WL.push_back(LabelRefVisit(GS->getLabel(), GS->getLabelLoc(), Parent));
2501}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002502void EnqueueVisitor::VisitIfStmt(const IfStmt *If) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002503 AddStmt(If->getElse());
2504 AddStmt(If->getThen());
2505 AddStmt(If->getCond());
2506 AddDecl(If->getConditionVariable());
2507}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002508void EnqueueVisitor::VisitInitListExpr(const InitListExpr *IE) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002509 // We care about the syntactic form of the initializer list, only.
2510 if (InitListExpr *Syntactic = IE->getSyntacticForm())
2511 IE = Syntactic;
2512 EnqueueChildren(IE);
2513}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002514void EnqueueVisitor::VisitMemberExpr(const MemberExpr *M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002515 WL.push_back(MemberExprParts(M, Parent));
2516
2517 // If the base of the member access expression is an implicit 'this', don't
2518 // visit it.
2519 // FIXME: If we ever want to show these implicit accesses, this will be
2520 // unfortunate. However, clang_getCursor() relies on this behavior.
Argyrios Kyrtzidis58d0e7a2015-03-13 04:40:07 +00002521 if (M->isImplicitAccess())
2522 return;
2523
2524 // Ignore base anonymous struct/union fields, otherwise they will shadow the
2525 // real field that that we are interested in.
2526 if (auto *SubME = dyn_cast<MemberExpr>(M->getBase())) {
2527 if (auto *FD = dyn_cast_or_null<FieldDecl>(SubME->getMemberDecl())) {
2528 if (FD->isAnonymousStructOrUnion()) {
2529 AddStmt(SubME->getBase());
2530 return;
2531 }
2532 }
2533 }
2534
2535 AddStmt(M->getBase());
Guy Benyei11169dd2012-12-18 14:30:41 +00002536}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002537void EnqueueVisitor::VisitObjCEncodeExpr(const ObjCEncodeExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002538 AddTypeLoc(E->getEncodedTypeSourceInfo());
2539}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002540void EnqueueVisitor::VisitObjCMessageExpr(const ObjCMessageExpr *M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002541 EnqueueChildren(M);
2542 AddTypeLoc(M->getClassReceiverTypeInfo());
2543}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002544void EnqueueVisitor::VisitOffsetOfExpr(const OffsetOfExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002545 // Visit the components of the offsetof expression.
2546 for (unsigned N = E->getNumComponents(), I = N; I > 0; --I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002547 const OffsetOfNode &Node = E->getComponent(I-1);
2548 switch (Node.getKind()) {
2549 case OffsetOfNode::Array:
2550 AddStmt(E->getIndexExpr(Node.getArrayExprIndex()));
2551 break;
2552 case OffsetOfNode::Field:
2553 AddMemberRef(Node.getField(), Node.getSourceRange().getEnd());
2554 break;
2555 case OffsetOfNode::Identifier:
2556 case OffsetOfNode::Base:
2557 continue;
2558 }
2559 }
2560 // Visit the type into which we're computing the offset.
2561 AddTypeLoc(E->getTypeSourceInfo());
2562}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002563void EnqueueVisitor::VisitOverloadExpr(const OverloadExpr *E) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002564 if (E->hasExplicitTemplateArgs())
2565 AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002566 WL.push_back(OverloadExprParts(E, Parent));
2567}
2568void EnqueueVisitor::VisitUnaryExprOrTypeTraitExpr(
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002569 const UnaryExprOrTypeTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002570 EnqueueChildren(E);
2571 if (E->isArgumentType())
2572 AddTypeLoc(E->getArgumentTypeInfo());
2573}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002574void EnqueueVisitor::VisitStmt(const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002575 EnqueueChildren(S);
2576}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002577void EnqueueVisitor::VisitSwitchStmt(const SwitchStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002578 AddStmt(S->getBody());
2579 AddStmt(S->getCond());
2580 AddDecl(S->getConditionVariable());
2581}
2582
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002583void EnqueueVisitor::VisitWhileStmt(const WhileStmt *W) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002584 AddStmt(W->getBody());
2585 AddStmt(W->getCond());
2586 AddDecl(W->getConditionVariable());
2587}
2588
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002589void EnqueueVisitor::VisitTypeTraitExpr(const TypeTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002590 for (unsigned I = E->getNumArgs(); I > 0; --I)
2591 AddTypeLoc(E->getArg(I-1));
2592}
2593
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002594void EnqueueVisitor::VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002595 AddTypeLoc(E->getQueriedTypeSourceInfo());
2596}
2597
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002598void EnqueueVisitor::VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002599 EnqueueChildren(E);
2600}
2601
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002602void EnqueueVisitor::VisitUnresolvedMemberExpr(const UnresolvedMemberExpr *U) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002603 VisitOverloadExpr(U);
2604 if (!U->isImplicitAccess())
2605 AddStmt(U->getBase());
2606}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002607void EnqueueVisitor::VisitVAArgExpr(const VAArgExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002608 AddStmt(E->getSubExpr());
2609 AddTypeLoc(E->getWrittenTypeInfo());
2610}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002611void EnqueueVisitor::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002612 WL.push_back(SizeOfPackExprParts(E, Parent));
2613}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002614void EnqueueVisitor::VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002615 // If the opaque value has a source expression, just transparently
2616 // visit that. This is useful for (e.g.) pseudo-object expressions.
2617 if (Expr *SourceExpr = E->getSourceExpr())
2618 return Visit(SourceExpr);
2619}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002620void EnqueueVisitor::VisitLambdaExpr(const LambdaExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002621 AddStmt(E->getBody());
2622 WL.push_back(LambdaExprParts(E, Parent));
2623}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002624void EnqueueVisitor::VisitPseudoObjectExpr(const PseudoObjectExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002625 // Treat the expression like its syntactic form.
2626 Visit(E->getSyntacticForm());
2627}
2628
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002629void EnqueueVisitor::VisitOMPExecutableDirective(
2630 const OMPExecutableDirective *D) {
2631 EnqueueChildren(D);
2632 for (ArrayRef<OMPClause *>::iterator I = D->clauses().begin(),
2633 E = D->clauses().end();
2634 I != E; ++I)
2635 EnqueueChildren(*I);
2636}
2637
Alexander Musman3aaab662014-08-19 11:27:13 +00002638void EnqueueVisitor::VisitOMPLoopDirective(const OMPLoopDirective *D) {
2639 VisitOMPExecutableDirective(D);
2640}
2641
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002642void EnqueueVisitor::VisitOMPParallelDirective(const OMPParallelDirective *D) {
2643 VisitOMPExecutableDirective(D);
2644}
2645
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002646void EnqueueVisitor::VisitOMPSimdDirective(const OMPSimdDirective *D) {
Alexander Musman3aaab662014-08-19 11:27:13 +00002647 VisitOMPLoopDirective(D);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002648}
2649
Alexey Bataevf29276e2014-06-18 04:14:57 +00002650void EnqueueVisitor::VisitOMPForDirective(const OMPForDirective *D) {
Alexander Musman3aaab662014-08-19 11:27:13 +00002651 VisitOMPLoopDirective(D);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002652}
2653
Alexander Musmanf82886e2014-09-18 05:12:34 +00002654void EnqueueVisitor::VisitOMPForSimdDirective(const OMPForSimdDirective *D) {
2655 VisitOMPLoopDirective(D);
2656}
2657
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002658void EnqueueVisitor::VisitOMPSectionsDirective(const OMPSectionsDirective *D) {
2659 VisitOMPExecutableDirective(D);
2660}
2661
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002662void EnqueueVisitor::VisitOMPSectionDirective(const OMPSectionDirective *D) {
2663 VisitOMPExecutableDirective(D);
2664}
2665
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00002666void EnqueueVisitor::VisitOMPSingleDirective(const OMPSingleDirective *D) {
2667 VisitOMPExecutableDirective(D);
2668}
2669
Alexander Musman80c22892014-07-17 08:54:58 +00002670void EnqueueVisitor::VisitOMPMasterDirective(const OMPMasterDirective *D) {
2671 VisitOMPExecutableDirective(D);
2672}
2673
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002674void EnqueueVisitor::VisitOMPCriticalDirective(const OMPCriticalDirective *D) {
2675 VisitOMPExecutableDirective(D);
2676 AddDeclarationNameInfo(D);
2677}
2678
Alexey Bataev4acb8592014-07-07 13:01:15 +00002679void
2680EnqueueVisitor::VisitOMPParallelForDirective(const OMPParallelForDirective *D) {
Alexander Musman3aaab662014-08-19 11:27:13 +00002681 VisitOMPLoopDirective(D);
Alexey Bataev4acb8592014-07-07 13:01:15 +00002682}
2683
Alexander Musmane4e893b2014-09-23 09:33:00 +00002684void EnqueueVisitor::VisitOMPParallelForSimdDirective(
2685 const OMPParallelForSimdDirective *D) {
2686 VisitOMPLoopDirective(D);
2687}
2688
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002689void EnqueueVisitor::VisitOMPParallelSectionsDirective(
2690 const OMPParallelSectionsDirective *D) {
2691 VisitOMPExecutableDirective(D);
2692}
2693
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002694void EnqueueVisitor::VisitOMPTaskDirective(const OMPTaskDirective *D) {
2695 VisitOMPExecutableDirective(D);
2696}
2697
Alexey Bataev68446b72014-07-18 07:47:19 +00002698void
2699EnqueueVisitor::VisitOMPTaskyieldDirective(const OMPTaskyieldDirective *D) {
2700 VisitOMPExecutableDirective(D);
2701}
2702
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002703void EnqueueVisitor::VisitOMPBarrierDirective(const OMPBarrierDirective *D) {
2704 VisitOMPExecutableDirective(D);
2705}
2706
Alexey Bataev2df347a2014-07-18 10:17:07 +00002707void EnqueueVisitor::VisitOMPTaskwaitDirective(const OMPTaskwaitDirective *D) {
2708 VisitOMPExecutableDirective(D);
2709}
2710
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002711void EnqueueVisitor::VisitOMPTaskgroupDirective(
2712 const OMPTaskgroupDirective *D) {
2713 VisitOMPExecutableDirective(D);
2714}
2715
Alexey Bataev6125da92014-07-21 11:26:11 +00002716void EnqueueVisitor::VisitOMPFlushDirective(const OMPFlushDirective *D) {
2717 VisitOMPExecutableDirective(D);
2718}
2719
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002720void EnqueueVisitor::VisitOMPOrderedDirective(const OMPOrderedDirective *D) {
2721 VisitOMPExecutableDirective(D);
2722}
2723
Alexey Bataev0162e452014-07-22 10:10:35 +00002724void EnqueueVisitor::VisitOMPAtomicDirective(const OMPAtomicDirective *D) {
2725 VisitOMPExecutableDirective(D);
2726}
2727
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002728void EnqueueVisitor::VisitOMPTargetDirective(const OMPTargetDirective *D) {
2729 VisitOMPExecutableDirective(D);
2730}
2731
Michael Wong65f367f2015-07-21 13:44:28 +00002732void EnqueueVisitor::VisitOMPTargetDataDirective(const
2733 OMPTargetDataDirective *D) {
2734 VisitOMPExecutableDirective(D);
2735}
2736
Samuel Antaodf67fc42016-01-19 19:15:56 +00002737void EnqueueVisitor::VisitOMPTargetEnterDataDirective(
2738 const OMPTargetEnterDataDirective *D) {
2739 VisitOMPExecutableDirective(D);
2740}
2741
Samuel Antao72590762016-01-19 20:04:50 +00002742void EnqueueVisitor::VisitOMPTargetExitDataDirective(
2743 const OMPTargetExitDataDirective *D) {
2744 VisitOMPExecutableDirective(D);
2745}
2746
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00002747void EnqueueVisitor::VisitOMPTargetParallelDirective(
2748 const OMPTargetParallelDirective *D) {
2749 VisitOMPExecutableDirective(D);
2750}
2751
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00002752void EnqueueVisitor::VisitOMPTargetParallelForDirective(
2753 const OMPTargetParallelForDirective *D) {
2754 VisitOMPLoopDirective(D);
2755}
2756
Alexey Bataev13314bf2014-10-09 04:18:56 +00002757void EnqueueVisitor::VisitOMPTeamsDirective(const OMPTeamsDirective *D) {
2758 VisitOMPExecutableDirective(D);
2759}
2760
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002761void EnqueueVisitor::VisitOMPCancellationPointDirective(
2762 const OMPCancellationPointDirective *D) {
2763 VisitOMPExecutableDirective(D);
2764}
2765
Alexey Bataev80909872015-07-02 11:25:17 +00002766void EnqueueVisitor::VisitOMPCancelDirective(const OMPCancelDirective *D) {
2767 VisitOMPExecutableDirective(D);
2768}
2769
Alexey Bataev49f6e782015-12-01 04:18:41 +00002770void EnqueueVisitor::VisitOMPTaskLoopDirective(const OMPTaskLoopDirective *D) {
2771 VisitOMPLoopDirective(D);
2772}
2773
Alexey Bataev0a6ed842015-12-03 09:40:15 +00002774void EnqueueVisitor::VisitOMPTaskLoopSimdDirective(
2775 const OMPTaskLoopSimdDirective *D) {
2776 VisitOMPLoopDirective(D);
2777}
2778
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002779void EnqueueVisitor::VisitOMPDistributeDirective(
2780 const OMPDistributeDirective *D) {
2781 VisitOMPLoopDirective(D);
2782}
2783
Carlo Bertolli9925f152016-06-27 14:55:37 +00002784void EnqueueVisitor::VisitOMPDistributeParallelForDirective(
2785 const OMPDistributeParallelForDirective *D) {
2786 VisitOMPLoopDirective(D);
2787}
2788
Kelvin Li4a39add2016-07-05 05:00:15 +00002789void EnqueueVisitor::VisitOMPDistributeParallelForSimdDirective(
2790 const OMPDistributeParallelForSimdDirective *D) {
2791 VisitOMPLoopDirective(D);
2792}
2793
Kelvin Li787f3fc2016-07-06 04:45:38 +00002794void EnqueueVisitor::VisitOMPDistributeSimdDirective(
2795 const OMPDistributeSimdDirective *D) {
2796 VisitOMPLoopDirective(D);
2797}
2798
Kelvin Lia579b912016-07-14 02:54:56 +00002799void EnqueueVisitor::VisitOMPTargetParallelForSimdDirective(
2800 const OMPTargetParallelForSimdDirective *D) {
2801 VisitOMPLoopDirective(D);
2802}
2803
Kelvin Li986330c2016-07-20 22:57:10 +00002804void EnqueueVisitor::VisitOMPTargetSimdDirective(
2805 const OMPTargetSimdDirective *D) {
2806 VisitOMPLoopDirective(D);
2807}
2808
Kelvin Li02532872016-08-05 14:37:37 +00002809void EnqueueVisitor::VisitOMPTeamsDistributeDirective(
2810 const OMPTeamsDistributeDirective *D) {
2811 VisitOMPLoopDirective(D);
2812}
2813
Kelvin Li4e325f72016-10-25 12:50:55 +00002814void EnqueueVisitor::VisitOMPTeamsDistributeSimdDirective(
2815 const OMPTeamsDistributeSimdDirective *D) {
2816 VisitOMPLoopDirective(D);
2817}
2818
Kelvin Li579e41c2016-11-30 23:51:03 +00002819void EnqueueVisitor::VisitOMPTeamsDistributeParallelForSimdDirective(
2820 const OMPTeamsDistributeParallelForSimdDirective *D) {
2821 VisitOMPLoopDirective(D);
2822}
2823
Kelvin Li7ade93f2016-12-09 03:24:30 +00002824void EnqueueVisitor::VisitOMPTeamsDistributeParallelForDirective(
2825 const OMPTeamsDistributeParallelForDirective *D) {
2826 VisitOMPLoopDirective(D);
2827}
2828
Kelvin Libf594a52016-12-17 05:48:59 +00002829void EnqueueVisitor::VisitOMPTargetTeamsDirective(
2830 const OMPTargetTeamsDirective *D) {
2831 VisitOMPExecutableDirective(D);
2832}
2833
Kelvin Li83c451e2016-12-25 04:52:54 +00002834void EnqueueVisitor::VisitOMPTargetTeamsDistributeDirective(
2835 const OMPTargetTeamsDistributeDirective *D) {
2836 VisitOMPLoopDirective(D);
2837}
2838
Kelvin Li80e8f562016-12-29 22:16:30 +00002839void EnqueueVisitor::VisitOMPTargetTeamsDistributeParallelForDirective(
2840 const OMPTargetTeamsDistributeParallelForDirective *D) {
2841 VisitOMPLoopDirective(D);
2842}
2843
Kelvin Li1851df52017-01-03 05:23:48 +00002844void EnqueueVisitor::VisitOMPTargetTeamsDistributeParallelForSimdDirective(
2845 const OMPTargetTeamsDistributeParallelForSimdDirective *D) {
2846 VisitOMPLoopDirective(D);
2847}
2848
Kelvin Lida681182017-01-10 18:08:18 +00002849void EnqueueVisitor::VisitOMPTargetTeamsDistributeSimdDirective(
2850 const OMPTargetTeamsDistributeSimdDirective *D) {
2851 VisitOMPLoopDirective(D);
2852}
2853
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002854void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002855 EnqueueVisitor(WL, MakeCXCursor(S, StmtParent, TU,RegionOfInterest)).Visit(S);
2856}
2857
2858bool CursorVisitor::IsInRegionOfInterest(CXCursor C) {
2859 if (RegionOfInterest.isValid()) {
2860 SourceRange Range = getRawCursorExtent(C);
2861 if (Range.isInvalid() || CompareRegionOfInterest(Range))
2862 return false;
2863 }
2864 return true;
2865}
2866
2867bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) {
2868 while (!WL.empty()) {
2869 // Dequeue the worklist item.
Robert Wilhelm25284cc2013-08-23 16:11:15 +00002870 VisitorJob LI = WL.pop_back_val();
Guy Benyei11169dd2012-12-18 14:30:41 +00002871
2872 // Set the Parent field, then back to its old value once we're done.
2873 SetParentRAII SetParent(Parent, StmtParent, LI.getParent());
2874
2875 switch (LI.getKind()) {
2876 case VisitorJob::DeclVisitKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002877 const Decl *D = cast<DeclVisit>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00002878 if (!D)
2879 continue;
2880
2881 // For now, perform default visitation for Decls.
2882 if (Visit(MakeCXCursor(D, TU, RegionOfInterest,
2883 cast<DeclVisit>(&LI)->isFirst())))
2884 return true;
2885
2886 continue;
2887 }
2888 case VisitorJob::ExplicitTemplateArgsVisitKind: {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002889 for (const TemplateArgumentLoc &Arg :
2890 *cast<ExplicitTemplateArgsVisit>(&LI)) {
2891 if (VisitTemplateArgumentLoc(Arg))
Guy Benyei11169dd2012-12-18 14:30:41 +00002892 return true;
2893 }
2894 continue;
2895 }
2896 case VisitorJob::TypeLocVisitKind: {
2897 // Perform default visitation for TypeLocs.
2898 if (Visit(cast<TypeLocVisit>(&LI)->get()))
2899 return true;
2900 continue;
2901 }
2902 case VisitorJob::LabelRefVisitKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002903 const LabelDecl *LS = cast<LabelRefVisit>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00002904 if (LabelStmt *stmt = LS->getStmt()) {
2905 if (Visit(MakeCursorLabelRef(stmt, cast<LabelRefVisit>(&LI)->getLoc(),
2906 TU))) {
2907 return true;
2908 }
2909 }
2910 continue;
2911 }
2912
2913 case VisitorJob::NestedNameSpecifierLocVisitKind: {
2914 NestedNameSpecifierLocVisit *V = cast<NestedNameSpecifierLocVisit>(&LI);
2915 if (VisitNestedNameSpecifierLoc(V->get()))
2916 return true;
2917 continue;
2918 }
2919
2920 case VisitorJob::DeclarationNameInfoVisitKind: {
2921 if (VisitDeclarationNameInfo(cast<DeclarationNameInfoVisit>(&LI)
2922 ->get()))
2923 return true;
2924 continue;
2925 }
2926 case VisitorJob::MemberRefVisitKind: {
2927 MemberRefVisit *V = cast<MemberRefVisit>(&LI);
2928 if (Visit(MakeCursorMemberRef(V->get(), V->getLoc(), TU)))
2929 return true;
2930 continue;
2931 }
2932 case VisitorJob::StmtVisitKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002933 const Stmt *S = cast<StmtVisit>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00002934 if (!S)
2935 continue;
2936
2937 // Update the current cursor.
2938 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU, RegionOfInterest);
2939 if (!IsInRegionOfInterest(Cursor))
2940 continue;
2941 switch (Visitor(Cursor, Parent, ClientData)) {
2942 case CXChildVisit_Break: return true;
2943 case CXChildVisit_Continue: break;
2944 case CXChildVisit_Recurse:
2945 if (PostChildrenVisitor)
Craig Topper69186e72014-06-08 08:38:04 +00002946 WL.push_back(PostChildrenVisit(nullptr, Cursor));
Guy Benyei11169dd2012-12-18 14:30:41 +00002947 EnqueueWorkList(WL, S);
2948 break;
2949 }
2950 continue;
2951 }
2952 case VisitorJob::MemberExprPartsKind: {
2953 // Handle the other pieces in the MemberExpr besides the base.
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002954 const MemberExpr *M = cast<MemberExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00002955
2956 // Visit the nested-name-specifier
2957 if (NestedNameSpecifierLoc QualifierLoc = M->getQualifierLoc())
2958 if (VisitNestedNameSpecifierLoc(QualifierLoc))
2959 return true;
2960
2961 // Visit the declaration name.
2962 if (VisitDeclarationNameInfo(M->getMemberNameInfo()))
2963 return true;
2964
2965 // Visit the explicitly-specified template arguments, if any.
2966 if (M->hasExplicitTemplateArgs()) {
2967 for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(),
2968 *ArgEnd = Arg + M->getNumTemplateArgs();
2969 Arg != ArgEnd; ++Arg) {
2970 if (VisitTemplateArgumentLoc(*Arg))
2971 return true;
2972 }
2973 }
2974 continue;
2975 }
2976 case VisitorJob::DeclRefExprPartsKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002977 const DeclRefExpr *DR = cast<DeclRefExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00002978 // Visit nested-name-specifier, if present.
2979 if (NestedNameSpecifierLoc QualifierLoc = DR->getQualifierLoc())
2980 if (VisitNestedNameSpecifierLoc(QualifierLoc))
2981 return true;
2982 // Visit declaration name.
2983 if (VisitDeclarationNameInfo(DR->getNameInfo()))
2984 return true;
2985 continue;
2986 }
2987 case VisitorJob::OverloadExprPartsKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002988 const OverloadExpr *O = cast<OverloadExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00002989 // Visit the nested-name-specifier.
2990 if (NestedNameSpecifierLoc QualifierLoc = O->getQualifierLoc())
2991 if (VisitNestedNameSpecifierLoc(QualifierLoc))
2992 return true;
2993 // Visit the declaration name.
2994 if (VisitDeclarationNameInfo(O->getNameInfo()))
2995 return true;
2996 // Visit the overloaded declaration reference.
2997 if (Visit(MakeCursorOverloadedDeclRef(O, TU)))
2998 return true;
2999 continue;
3000 }
3001 case VisitorJob::SizeOfPackExprPartsKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003002 const SizeOfPackExpr *E = cast<SizeOfPackExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003003 NamedDecl *Pack = E->getPack();
3004 if (isa<TemplateTypeParmDecl>(Pack)) {
3005 if (Visit(MakeCursorTypeRef(cast<TemplateTypeParmDecl>(Pack),
3006 E->getPackLoc(), TU)))
3007 return true;
3008
3009 continue;
3010 }
3011
3012 if (isa<TemplateTemplateParmDecl>(Pack)) {
3013 if (Visit(MakeCursorTemplateRef(cast<TemplateTemplateParmDecl>(Pack),
3014 E->getPackLoc(), TU)))
3015 return true;
3016
3017 continue;
3018 }
3019
3020 // Non-type template parameter packs and function parameter packs are
3021 // treated like DeclRefExpr cursors.
3022 continue;
3023 }
3024
3025 case VisitorJob::LambdaExprPartsKind: {
3026 // Visit captures.
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003027 const LambdaExpr *E = cast<LambdaExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003028 for (LambdaExpr::capture_iterator C = E->explicit_capture_begin(),
3029 CEnd = E->explicit_capture_end();
3030 C != CEnd; ++C) {
Richard Smithba71c082013-05-16 06:20:58 +00003031 // FIXME: Lambda init-captures.
3032 if (!C->capturesVariable())
Guy Benyei11169dd2012-12-18 14:30:41 +00003033 continue;
Richard Smithba71c082013-05-16 06:20:58 +00003034
Guy Benyei11169dd2012-12-18 14:30:41 +00003035 if (Visit(MakeCursorVariableRef(C->getCapturedVar(),
3036 C->getLocation(),
3037 TU)))
3038 return true;
3039 }
3040
3041 // Visit parameters and return type, if present.
3042 if (E->hasExplicitParameters() || E->hasExplicitResultType()) {
3043 TypeLoc TL = E->getCallOperator()->getTypeSourceInfo()->getTypeLoc();
3044 if (E->hasExplicitParameters() && E->hasExplicitResultType()) {
3045 // Visit the whole type.
3046 if (Visit(TL))
3047 return true;
David Blaikie6adc78e2013-02-18 22:06:02 +00003048 } else if (FunctionProtoTypeLoc Proto =
3049 TL.getAs<FunctionProtoTypeLoc>()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003050 if (E->hasExplicitParameters()) {
3051 // Visit parameters.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00003052 for (unsigned I = 0, N = Proto.getNumParams(); I != N; ++I)
3053 if (Visit(MakeCXCursor(Proto.getParam(I), TU)))
Guy Benyei11169dd2012-12-18 14:30:41 +00003054 return true;
3055 } else {
3056 // Visit result type.
Alp Toker42a16a62014-01-25 23:51:36 +00003057 if (Visit(Proto.getReturnLoc()))
Guy Benyei11169dd2012-12-18 14:30:41 +00003058 return true;
3059 }
3060 }
3061 }
3062 break;
3063 }
3064
3065 case VisitorJob::PostChildrenVisitKind:
3066 if (PostChildrenVisitor(Parent, ClientData))
3067 return true;
3068 break;
3069 }
3070 }
3071 return false;
3072}
3073
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003074bool CursorVisitor::Visit(const Stmt *S) {
Craig Topper69186e72014-06-08 08:38:04 +00003075 VisitorWorkList *WL = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00003076 if (!WorkListFreeList.empty()) {
3077 WL = WorkListFreeList.back();
3078 WL->clear();
3079 WorkListFreeList.pop_back();
3080 }
3081 else {
3082 WL = new VisitorWorkList();
3083 WorkListCache.push_back(WL);
3084 }
3085 EnqueueWorkList(*WL, S);
3086 bool result = RunVisitorWorkList(*WL);
3087 WorkListFreeList.push_back(WL);
3088 return result;
3089}
3090
3091namespace {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003092typedef SmallVector<SourceRange, 4> RefNamePieces;
James Y Knight04ec5bf2015-12-24 02:59:37 +00003093RefNamePieces buildPieces(unsigned NameFlags, bool IsMemberRefExpr,
3094 const DeclarationNameInfo &NI, SourceRange QLoc,
3095 const SourceRange *TemplateArgsLoc = nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003096 const bool WantQualifier = NameFlags & CXNameRange_WantQualifier;
3097 const bool WantTemplateArgs = NameFlags & CXNameRange_WantTemplateArgs;
3098 const bool WantSinglePiece = NameFlags & CXNameRange_WantSinglePiece;
3099
3100 const DeclarationName::NameKind Kind = NI.getName().getNameKind();
3101
3102 RefNamePieces Pieces;
3103
3104 if (WantQualifier && QLoc.isValid())
3105 Pieces.push_back(QLoc);
3106
3107 if (Kind != DeclarationName::CXXOperatorName || IsMemberRefExpr)
3108 Pieces.push_back(NI.getLoc());
James Y Knight04ec5bf2015-12-24 02:59:37 +00003109
3110 if (WantTemplateArgs && TemplateArgsLoc && TemplateArgsLoc->isValid())
3111 Pieces.push_back(*TemplateArgsLoc);
3112
Guy Benyei11169dd2012-12-18 14:30:41 +00003113 if (Kind == DeclarationName::CXXOperatorName) {
3114 Pieces.push_back(SourceLocation::getFromRawEncoding(
3115 NI.getInfo().CXXOperatorName.BeginOpNameLoc));
3116 Pieces.push_back(SourceLocation::getFromRawEncoding(
3117 NI.getInfo().CXXOperatorName.EndOpNameLoc));
3118 }
3119
3120 if (WantSinglePiece) {
3121 SourceRange R(Pieces.front().getBegin(), Pieces.back().getEnd());
3122 Pieces.clear();
3123 Pieces.push_back(R);
3124 }
3125
3126 return Pieces;
3127}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003128}
Guy Benyei11169dd2012-12-18 14:30:41 +00003129
3130//===----------------------------------------------------------------------===//
3131// Misc. API hooks.
3132//===----------------------------------------------------------------------===//
3133
Chad Rosier05c71aa2013-03-27 18:28:23 +00003134static void fatal_error_handler(void *user_data, const std::string& reason,
3135 bool gen_crash_diag) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003136 // Write the result out to stderr avoiding errs() because raw_ostreams can
3137 // call report_fatal_error.
3138 fprintf(stderr, "LIBCLANG FATAL ERROR: %s\n", reason.c_str());
3139 ::abort();
3140}
3141
Chandler Carruth66660742014-06-27 16:37:27 +00003142namespace {
3143struct RegisterFatalErrorHandler {
3144 RegisterFatalErrorHandler() {
3145 llvm::install_fatal_error_handler(fatal_error_handler, nullptr);
3146 }
3147};
3148}
3149
3150static llvm::ManagedStatic<RegisterFatalErrorHandler> RegisterFatalErrorHandlerOnce;
3151
Guy Benyei11169dd2012-12-18 14:30:41 +00003152CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
3153 int displayDiagnostics) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003154 // We use crash recovery to make some of our APIs more reliable, implicitly
3155 // enable it.
Argyrios Kyrtzidis3701f542013-11-27 08:58:09 +00003156 if (!getenv("LIBCLANG_DISABLE_CRASH_RECOVERY"))
3157 llvm::CrashRecoveryContext::Enable();
Guy Benyei11169dd2012-12-18 14:30:41 +00003158
Chandler Carruth66660742014-06-27 16:37:27 +00003159 // Look through the managed static to trigger construction of the managed
3160 // static which registers our fatal error handler. This ensures it is only
3161 // registered once.
3162 (void)*RegisterFatalErrorHandlerOnce;
Guy Benyei11169dd2012-12-18 14:30:41 +00003163
Adrian Prantlbc068582015-07-08 01:00:30 +00003164 // Initialize targets for clang module support.
3165 llvm::InitializeAllTargets();
3166 llvm::InitializeAllTargetMCs();
3167 llvm::InitializeAllAsmPrinters();
3168 llvm::InitializeAllAsmParsers();
3169
Adrian Prantlfb2398d2015-07-17 01:19:54 +00003170 CIndexer *CIdxr = new CIndexer();
3171
Guy Benyei11169dd2012-12-18 14:30:41 +00003172 if (excludeDeclarationsFromPCH)
3173 CIdxr->setOnlyLocalDecls();
3174 if (displayDiagnostics)
3175 CIdxr->setDisplayDiagnostics();
3176
3177 if (getenv("LIBCLANG_BGPRIO_INDEX"))
3178 CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() |
3179 CXGlobalOpt_ThreadBackgroundPriorityForIndexing);
3180 if (getenv("LIBCLANG_BGPRIO_EDIT"))
3181 CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() |
3182 CXGlobalOpt_ThreadBackgroundPriorityForEditing);
3183
3184 return CIdxr;
3185}
3186
3187void clang_disposeIndex(CXIndex CIdx) {
3188 if (CIdx)
3189 delete static_cast<CIndexer *>(CIdx);
3190}
3191
3192void clang_CXIndex_setGlobalOptions(CXIndex CIdx, unsigned options) {
3193 if (CIdx)
3194 static_cast<CIndexer *>(CIdx)->setCXGlobalOptFlags(options);
3195}
3196
3197unsigned clang_CXIndex_getGlobalOptions(CXIndex CIdx) {
3198 if (CIdx)
3199 return static_cast<CIndexer *>(CIdx)->getCXGlobalOptFlags();
3200 return 0;
3201}
3202
3203void clang_toggleCrashRecovery(unsigned isEnabled) {
3204 if (isEnabled)
3205 llvm::CrashRecoveryContext::Enable();
3206 else
3207 llvm::CrashRecoveryContext::Disable();
3208}
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003209
Guy Benyei11169dd2012-12-18 14:30:41 +00003210CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
3211 const char *ast_filename) {
Dmitri Gribenko8850cda2014-02-19 10:24:00 +00003212 CXTranslationUnit TU;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003213 enum CXErrorCode Result =
3214 clang_createTranslationUnit2(CIdx, ast_filename, &TU);
Reid Klecknerfd48fc62014-02-12 23:56:20 +00003215 (void)Result;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003216 assert((TU && Result == CXError_Success) ||
3217 (!TU && Result != CXError_Success));
3218 return TU;
3219}
3220
3221enum CXErrorCode clang_createTranslationUnit2(CXIndex CIdx,
3222 const char *ast_filename,
3223 CXTranslationUnit *out_TU) {
Dmitri Gribenko8850cda2014-02-19 10:24:00 +00003224 if (out_TU)
Craig Topper69186e72014-06-08 08:38:04 +00003225 *out_TU = nullptr;
Dmitri Gribenko8850cda2014-02-19 10:24:00 +00003226
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003227 if (!CIdx || !ast_filename || !out_TU)
3228 return CXError_InvalidArguments;
Guy Benyei11169dd2012-12-18 14:30:41 +00003229
Argyrios Kyrtzidis27021012013-05-24 22:24:07 +00003230 LOG_FUNC_SECTION {
3231 *Log << ast_filename;
3232 }
3233
Guy Benyei11169dd2012-12-18 14:30:41 +00003234 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
3235 FileSystemOptions FileSystemOpts;
3236
Justin Bognerd512c1e2014-10-15 00:33:06 +00003237 IntrusiveRefCntPtr<DiagnosticsEngine> Diags =
3238 CompilerInstance::createDiagnostics(new DiagnosticOptions());
David Blaikie6f7382d2014-08-10 19:08:04 +00003239 std::unique_ptr<ASTUnit> AU = ASTUnit::LoadFromASTFile(
Adrian Prantlfb2398d2015-07-17 01:19:54 +00003240 ast_filename, CXXIdx->getPCHContainerOperations()->getRawReader(), Diags,
Adrian Prantl6b21ab22015-08-27 19:46:20 +00003241 FileSystemOpts, /*UseDebugInfo=*/false,
3242 CXXIdx->getOnlyLocalDecls(), None,
David Blaikie6f7382d2014-08-10 19:08:04 +00003243 /*CaptureDiagnostics=*/true,
3244 /*AllowPCHWithCompilerErrors=*/true,
3245 /*UserFilesAreVolatile=*/true);
David Blaikieea4395e2017-01-06 19:49:01 +00003246 *out_TU = MakeCXTranslationUnit(CXXIdx, std::move(AU));
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003247 return *out_TU ? CXError_Success : CXError_Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003248}
3249
3250unsigned clang_defaultEditingTranslationUnitOptions() {
3251 return CXTranslationUnit_PrecompiledPreamble |
3252 CXTranslationUnit_CacheCompletionResults;
3253}
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003254
Guy Benyei11169dd2012-12-18 14:30:41 +00003255CXTranslationUnit
3256clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
3257 const char *source_filename,
3258 int num_command_line_args,
3259 const char * const *command_line_args,
3260 unsigned num_unsaved_files,
3261 struct CXUnsavedFile *unsaved_files) {
3262 unsigned Options = CXTranslationUnit_DetailedPreprocessingRecord;
3263 return clang_parseTranslationUnit(CIdx, source_filename,
3264 command_line_args, num_command_line_args,
3265 unsaved_files, num_unsaved_files,
3266 Options);
3267}
3268
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003269static CXErrorCode
3270clang_parseTranslationUnit_Impl(CXIndex CIdx, const char *source_filename,
3271 const char *const *command_line_args,
3272 int num_command_line_args,
3273 ArrayRef<CXUnsavedFile> unsaved_files,
3274 unsigned options, CXTranslationUnit *out_TU) {
Dmitri Gribenko1bf8d912014-02-18 15:20:02 +00003275 // Set up the initial return values.
3276 if (out_TU)
Craig Topper69186e72014-06-08 08:38:04 +00003277 *out_TU = nullptr;
Dmitri Gribenko1bf8d912014-02-18 15:20:02 +00003278
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003279 // Check arguments.
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003280 if (!CIdx || !out_TU)
3281 return CXError_InvalidArguments;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003282
Guy Benyei11169dd2012-12-18 14:30:41 +00003283 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
3284
3285 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
3286 setThreadBackgroundPriority();
3287
3288 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Benjamin Kramer5c248d82015-12-15 09:30:31 +00003289 bool CreatePreambleOnFirstParse =
3290 options & CXTranslationUnit_CreatePreambleOnFirstParse;
Guy Benyei11169dd2012-12-18 14:30:41 +00003291 // FIXME: Add a flag for modules.
3292 TranslationUnitKind TUKind
3293 = (options & CXTranslationUnit_Incomplete)? TU_Prefix : TU_Complete;
Alp Toker8c8a8752013-12-03 06:53:35 +00003294 bool CacheCodeCompletionResults
Guy Benyei11169dd2012-12-18 14:30:41 +00003295 = options & CXTranslationUnit_CacheCompletionResults;
3296 bool IncludeBriefCommentsInCodeCompletion
3297 = options & CXTranslationUnit_IncludeBriefCommentsInCodeCompletion;
3298 bool SkipFunctionBodies = options & CXTranslationUnit_SkipFunctionBodies;
3299 bool ForSerialization = options & CXTranslationUnit_ForSerialization;
3300
3301 // Configure the diagnostics.
3302 IntrusiveRefCntPtr<DiagnosticsEngine>
Sean Silvaf1b49e22013-01-20 01:58:28 +00003303 Diags(CompilerInstance::createDiagnostics(new DiagnosticOptions));
Guy Benyei11169dd2012-12-18 14:30:41 +00003304
Manuel Klimek016c0242016-03-01 10:56:19 +00003305 if (options & CXTranslationUnit_KeepGoing)
3306 Diags->setFatalsAsError(true);
3307
Guy Benyei11169dd2012-12-18 14:30:41 +00003308 // Recover resources if we crash before exiting this function.
3309 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
3310 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Alp Tokerf994cef2014-07-05 03:08:06 +00003311 DiagCleanup(Diags.get());
Guy Benyei11169dd2012-12-18 14:30:41 +00003312
Ahmed Charlesb8984322014-03-07 20:03:18 +00003313 std::unique_ptr<std::vector<ASTUnit::RemappedFile>> RemappedFiles(
3314 new std::vector<ASTUnit::RemappedFile>());
Guy Benyei11169dd2012-12-18 14:30:41 +00003315
3316 // Recover resources if we crash before exiting this function.
3317 llvm::CrashRecoveryContextCleanupRegistrar<
3318 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
3319
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003320 for (auto &UF : unsaved_files) {
Rafael Espindolad87f8d72014-08-27 20:03:29 +00003321 std::unique_ptr<llvm::MemoryBuffer> MB =
Alp Toker9d85b182014-07-07 01:23:14 +00003322 llvm::MemoryBuffer::getMemBufferCopy(getContents(UF), UF.Filename);
Rafael Espindolad87f8d72014-08-27 20:03:29 +00003323 RemappedFiles->push_back(std::make_pair(UF.Filename, MB.release()));
Guy Benyei11169dd2012-12-18 14:30:41 +00003324 }
3325
Ahmed Charlesb8984322014-03-07 20:03:18 +00003326 std::unique_ptr<std::vector<const char *>> Args(
3327 new std::vector<const char *>());
Guy Benyei11169dd2012-12-18 14:30:41 +00003328
3329 // Recover resources if we crash before exiting this method.
3330 llvm::CrashRecoveryContextCleanupRegistrar<std::vector<const char*> >
3331 ArgsCleanup(Args.get());
3332
3333 // Since the Clang C library is primarily used by batch tools dealing with
3334 // (often very broken) source code, where spell-checking can have a
3335 // significant negative impact on performance (particularly when
3336 // precompiled headers are involved), we disable it by default.
3337 // Only do this if we haven't found a spell-checking-related argument.
3338 bool FoundSpellCheckingArgument = false;
3339 for (int I = 0; I != num_command_line_args; ++I) {
3340 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
3341 strcmp(command_line_args[I], "-fspell-checking") == 0) {
3342 FoundSpellCheckingArgument = true;
3343 break;
3344 }
3345 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003346 Args->insert(Args->end(), command_line_args,
3347 command_line_args + num_command_line_args);
3348
Benjamin Kramerc02670e2015-11-18 16:14:27 +00003349 if (!FoundSpellCheckingArgument)
3350 Args->insert(Args->begin() + 1, "-fno-spell-checking");
3351
Guy Benyei11169dd2012-12-18 14:30:41 +00003352 // The 'source_filename' argument is optional. If the caller does not
3353 // specify it then it is assumed that the source file is specified
3354 // in the actual argument list.
3355 // Put the source file after command_line_args otherwise if '-x' flag is
3356 // present it will be unused.
3357 if (source_filename)
3358 Args->push_back(source_filename);
3359
3360 // Do we need the detailed preprocessing record?
3361 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
3362 Args->push_back("-Xclang");
3363 Args->push_back("-detailed-preprocessing-record");
3364 }
3365
3366 unsigned NumErrors = Diags->getClient()->getNumErrors();
Ahmed Charlesb8984322014-03-07 20:03:18 +00003367 std::unique_ptr<ASTUnit> ErrUnit;
Benjamin Kramer5c248d82015-12-15 09:30:31 +00003368 // Unless the user specified that they want the preamble on the first parse
3369 // set it up to be created on the first reparse. This makes the first parse
3370 // faster, trading for a slower (first) reparse.
3371 unsigned PrecompilePreambleAfterNParses =
3372 !PrecompilePreamble ? 0 : 2 - CreatePreambleOnFirstParse;
Ahmed Charlesb8984322014-03-07 20:03:18 +00003373 std::unique_ptr<ASTUnit> Unit(ASTUnit::LoadFromCommandLine(
Adrian Prantlbb165fb2015-06-20 18:53:08 +00003374 Args->data(), Args->data() + Args->size(),
3375 CXXIdx->getPCHContainerOperations(), Diags,
Ahmed Charlesb8984322014-03-07 20:03:18 +00003376 CXXIdx->getClangResourcesPath(), CXXIdx->getOnlyLocalDecls(),
3377 /*CaptureDiagnostics=*/true, *RemappedFiles.get(),
Benjamin Kramer5c248d82015-12-15 09:30:31 +00003378 /*RemappedFilesKeepOriginalName=*/true, PrecompilePreambleAfterNParses,
3379 TUKind, CacheCodeCompletionResults, IncludeBriefCommentsInCodeCompletion,
Ahmed Charlesb8984322014-03-07 20:03:18 +00003380 /*AllowPCHWithCompilerErrors=*/true, SkipFunctionBodies,
Argyrios Kyrtzidisa3e2ff12015-11-20 03:36:21 +00003381 /*UserFilesAreVolatile=*/true, ForSerialization,
3382 CXXIdx->getPCHContainerOperations()->getRawReader().getFormat(),
3383 &ErrUnit));
Guy Benyei11169dd2012-12-18 14:30:41 +00003384
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003385 // Early failures in LoadFromCommandLine may return with ErrUnit unset.
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003386 if (!Unit && !ErrUnit)
3387 return CXError_ASTReadError;
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003388
Guy Benyei11169dd2012-12-18 14:30:41 +00003389 if (NumErrors != Diags->getClient()->getNumErrors()) {
3390 // Make sure to check that 'Unit' is non-NULL.
3391 if (CXXIdx->getDisplayDiagnostics())
3392 printDiagsToStderr(Unit ? Unit.get() : ErrUnit.get());
3393 }
3394
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003395 if (isASTReadError(Unit ? Unit.get() : ErrUnit.get()))
3396 return CXError_ASTReadError;
3397
David Blaikieea4395e2017-01-06 19:49:01 +00003398 *out_TU = MakeCXTranslationUnit(CXXIdx, std::move(Unit));
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003399 return *out_TU ? CXError_Success : CXError_Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003400}
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003401
3402CXTranslationUnit
3403clang_parseTranslationUnit(CXIndex CIdx,
3404 const char *source_filename,
3405 const char *const *command_line_args,
3406 int num_command_line_args,
3407 struct CXUnsavedFile *unsaved_files,
3408 unsigned num_unsaved_files,
3409 unsigned options) {
3410 CXTranslationUnit TU;
3411 enum CXErrorCode Result = clang_parseTranslationUnit2(
3412 CIdx, source_filename, command_line_args, num_command_line_args,
3413 unsaved_files, num_unsaved_files, options, &TU);
Reid Kleckner6eaf05a2014-02-13 01:19:59 +00003414 (void)Result;
Dmitri Gribenko1bf8d912014-02-18 15:20:02 +00003415 assert((TU && Result == CXError_Success) ||
3416 (!TU && Result != CXError_Success));
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003417 return TU;
3418}
3419
3420enum CXErrorCode clang_parseTranslationUnit2(
Benjamin Kramerc02670e2015-11-18 16:14:27 +00003421 CXIndex CIdx, const char *source_filename,
3422 const char *const *command_line_args, int num_command_line_args,
3423 struct CXUnsavedFile *unsaved_files, unsigned num_unsaved_files,
3424 unsigned options, CXTranslationUnit *out_TU) {
3425 SmallVector<const char *, 4> Args;
3426 Args.push_back("clang");
3427 Args.append(command_line_args, command_line_args + num_command_line_args);
3428 return clang_parseTranslationUnit2FullArgv(
3429 CIdx, source_filename, Args.data(), Args.size(), unsaved_files,
3430 num_unsaved_files, options, out_TU);
3431}
3432
3433enum CXErrorCode clang_parseTranslationUnit2FullArgv(
3434 CXIndex CIdx, const char *source_filename,
3435 const char *const *command_line_args, int num_command_line_args,
3436 struct CXUnsavedFile *unsaved_files, unsigned num_unsaved_files,
3437 unsigned options, CXTranslationUnit *out_TU) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00003438 LOG_FUNC_SECTION {
3439 *Log << source_filename << ": ";
3440 for (int i = 0; i != num_command_line_args; ++i)
3441 *Log << command_line_args[i] << " ";
3442 }
3443
Alp Toker9d85b182014-07-07 01:23:14 +00003444 if (num_unsaved_files && !unsaved_files)
3445 return CXError_InvalidArguments;
3446
Alp Toker5c532982014-07-07 22:42:03 +00003447 CXErrorCode result = CXError_Failure;
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003448 auto ParseTranslationUnitImpl = [=, &result] {
3449 result = clang_parseTranslationUnit_Impl(
3450 CIdx, source_filename, command_line_args, num_command_line_args,
3451 llvm::makeArrayRef(unsaved_files, num_unsaved_files), options, out_TU);
3452 };
Guy Benyei11169dd2012-12-18 14:30:41 +00003453 llvm::CrashRecoveryContext CRC;
3454
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003455 if (!RunSafely(CRC, ParseTranslationUnitImpl)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003456 fprintf(stderr, "libclang: crash detected during parsing: {\n");
3457 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
3458 fprintf(stderr, " 'command_line_args' : [");
3459 for (int i = 0; i != num_command_line_args; ++i) {
3460 if (i)
3461 fprintf(stderr, ", ");
3462 fprintf(stderr, "'%s'", command_line_args[i]);
3463 }
3464 fprintf(stderr, "],\n");
3465 fprintf(stderr, " 'unsaved_files' : [");
3466 for (unsigned i = 0; i != num_unsaved_files; ++i) {
3467 if (i)
3468 fprintf(stderr, ", ");
3469 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
3470 unsaved_files[i].Length);
3471 }
3472 fprintf(stderr, "],\n");
3473 fprintf(stderr, " 'options' : %d,\n", options);
3474 fprintf(stderr, "}\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003475
3476 return CXError_Crashed;
Guy Benyei11169dd2012-12-18 14:30:41 +00003477 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003478 if (CXTranslationUnit *TU = out_TU)
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003479 PrintLibclangResourceUsage(*TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00003480 }
Alp Toker5c532982014-07-07 22:42:03 +00003481
3482 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003483}
3484
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003485CXString clang_Type_getObjCEncoding(CXType CT) {
3486 CXTranslationUnit tu = static_cast<CXTranslationUnit>(CT.data[1]);
3487 ASTContext &Ctx = getASTUnit(tu)->getASTContext();
3488 std::string encoding;
3489 Ctx.getObjCEncodingForType(QualType::getFromOpaquePtr(CT.data[0]),
3490 encoding);
3491
3492 return cxstring::createDup(encoding);
3493}
3494
3495static const IdentifierInfo *getMacroIdentifier(CXCursor C) {
3496 if (C.kind == CXCursor_MacroDefinition) {
3497 if (const MacroDefinitionRecord *MDR = getCursorMacroDefinition(C))
3498 return MDR->getName();
3499 } else if (C.kind == CXCursor_MacroExpansion) {
3500 MacroExpansionCursor ME = getCursorMacroExpansion(C);
3501 return ME.getName();
3502 }
3503 return nullptr;
3504}
3505
3506unsigned clang_Cursor_isMacroFunctionLike(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->isFunctionLike();
3515 return false;
3516}
3517
3518unsigned clang_Cursor_isMacroBuiltin(CXCursor C) {
3519 const IdentifierInfo *II = getMacroIdentifier(C);
3520 if (!II) {
3521 return false;
3522 }
3523 ASTUnit *ASTU = getCursorASTUnit(C);
3524 Preprocessor &PP = ASTU->getPreprocessor();
3525 if (const MacroInfo *MI = PP.getMacroInfo(II))
3526 return MI->isBuiltinMacro();
3527 return false;
3528}
3529
3530unsigned clang_Cursor_isFunctionInlined(CXCursor C) {
3531 const Decl *D = getCursorDecl(C);
3532 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
3533 if (!FD) {
3534 return false;
3535 }
3536 return FD->isInlined();
3537}
3538
3539static StringLiteral* getCFSTR_value(CallExpr *callExpr) {
3540 if (callExpr->getNumArgs() != 1) {
3541 return nullptr;
3542 }
3543
3544 StringLiteral *S = nullptr;
3545 auto *arg = callExpr->getArg(0);
3546 if (arg->getStmtClass() == Stmt::ImplicitCastExprClass) {
3547 ImplicitCastExpr *I = static_cast<ImplicitCastExpr *>(arg);
3548 auto *subExpr = I->getSubExprAsWritten();
3549
3550 if(subExpr->getStmtClass() != Stmt::StringLiteralClass){
3551 return nullptr;
3552 }
3553
3554 S = static_cast<StringLiteral *>(I->getSubExprAsWritten());
3555 } else if (arg->getStmtClass() == Stmt::StringLiteralClass) {
3556 S = static_cast<StringLiteral *>(callExpr->getArg(0));
3557 } else {
3558 return nullptr;
3559 }
3560 return S;
3561}
3562
David Blaikie59272572016-04-13 18:23:33 +00003563struct ExprEvalResult {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003564 CXEvalResultKind EvalType;
3565 union {
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003566 unsigned long long unsignedVal;
3567 long long intVal;
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003568 double floatVal;
3569 char *stringVal;
3570 } EvalData;
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003571 bool IsUnsignedInt;
David Blaikie59272572016-04-13 18:23:33 +00003572 ~ExprEvalResult() {
3573 if (EvalType != CXEval_UnExposed && EvalType != CXEval_Float &&
3574 EvalType != CXEval_Int) {
3575 delete EvalData.stringVal;
3576 }
3577 }
3578};
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003579
3580void clang_EvalResult_dispose(CXEvalResult E) {
David Blaikie59272572016-04-13 18:23:33 +00003581 delete static_cast<ExprEvalResult *>(E);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003582}
3583
3584CXEvalResultKind clang_EvalResult_getKind(CXEvalResult E) {
3585 if (!E) {
3586 return CXEval_UnExposed;
3587 }
3588 return ((ExprEvalResult *)E)->EvalType;
3589}
3590
3591int clang_EvalResult_getAsInt(CXEvalResult E) {
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003592 return clang_EvalResult_getAsLongLong(E);
3593}
3594
3595long long clang_EvalResult_getAsLongLong(CXEvalResult E) {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003596 if (!E) {
3597 return 0;
3598 }
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003599 ExprEvalResult *Result = (ExprEvalResult*)E;
3600 if (Result->IsUnsignedInt)
3601 return Result->EvalData.unsignedVal;
3602 return Result->EvalData.intVal;
3603}
3604
3605unsigned clang_EvalResult_isUnsignedInt(CXEvalResult E) {
3606 return ((ExprEvalResult *)E)->IsUnsignedInt;
3607}
3608
3609unsigned long long clang_EvalResult_getAsUnsigned(CXEvalResult E) {
3610 if (!E) {
3611 return 0;
3612 }
3613
3614 ExprEvalResult *Result = (ExprEvalResult*)E;
3615 if (Result->IsUnsignedInt)
3616 return Result->EvalData.unsignedVal;
3617 return Result->EvalData.intVal;
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003618}
3619
3620double clang_EvalResult_getAsDouble(CXEvalResult E) {
3621 if (!E) {
3622 return 0;
3623 }
3624 return ((ExprEvalResult *)E)->EvalData.floatVal;
3625}
3626
3627const char* clang_EvalResult_getAsStr(CXEvalResult E) {
3628 if (!E) {
3629 return nullptr;
3630 }
3631 return ((ExprEvalResult *)E)->EvalData.stringVal;
3632}
3633
3634static const ExprEvalResult* evaluateExpr(Expr *expr, CXCursor C) {
3635 Expr::EvalResult ER;
3636 ASTContext &ctx = getCursorContext(C);
David Blaikiebbc00882016-04-13 18:36:19 +00003637 if (!expr)
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003638 return nullptr;
David Blaikiebbc00882016-04-13 18:36:19 +00003639
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003640 expr = expr->IgnoreParens();
David Blaikiebbc00882016-04-13 18:36:19 +00003641 if (!expr->EvaluateAsRValue(ER, ctx))
3642 return nullptr;
3643
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003644 QualType rettype;
3645 CallExpr *callExpr;
David Blaikie59272572016-04-13 18:23:33 +00003646 auto result = llvm::make_unique<ExprEvalResult>();
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003647 result->EvalType = CXEval_UnExposed;
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003648 result->IsUnsignedInt = false;
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003649
David Blaikiebbc00882016-04-13 18:36:19 +00003650 if (ER.Val.isInt()) {
3651 result->EvalType = CXEval_Int;
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003652
3653 auto& val = ER.Val.getInt();
3654 if (val.isUnsigned()) {
3655 result->IsUnsignedInt = true;
3656 result->EvalData.unsignedVal = val.getZExtValue();
3657 } else {
3658 result->EvalData.intVal = val.getExtValue();
3659 }
3660
David Blaikiebbc00882016-04-13 18:36:19 +00003661 return result.release();
3662 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003663
David Blaikiebbc00882016-04-13 18:36:19 +00003664 if (ER.Val.isFloat()) {
3665 llvm::SmallVector<char, 100> Buffer;
3666 ER.Val.getFloat().toString(Buffer);
3667 std::string floatStr(Buffer.data(), Buffer.size());
3668 result->EvalType = CXEval_Float;
3669 bool ignored;
3670 llvm::APFloat apFloat = ER.Val.getFloat();
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003671 apFloat.convert(llvm::APFloat::IEEEdouble(),
David Blaikiebbc00882016-04-13 18:36:19 +00003672 llvm::APFloat::rmNearestTiesToEven, &ignored);
3673 result->EvalData.floatVal = apFloat.convertToDouble();
3674 return result.release();
3675 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003676
David Blaikiebbc00882016-04-13 18:36:19 +00003677 if (expr->getStmtClass() == Stmt::ImplicitCastExprClass) {
3678 const ImplicitCastExpr *I = dyn_cast<ImplicitCastExpr>(expr);
3679 auto *subExpr = I->getSubExprAsWritten();
3680 if (subExpr->getStmtClass() == Stmt::StringLiteralClass ||
3681 subExpr->getStmtClass() == Stmt::ObjCStringLiteralClass) {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003682 const StringLiteral *StrE = nullptr;
3683 const ObjCStringLiteral *ObjCExpr;
David Blaikiebbc00882016-04-13 18:36:19 +00003684 ObjCExpr = dyn_cast<ObjCStringLiteral>(subExpr);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003685
3686 if (ObjCExpr) {
3687 StrE = ObjCExpr->getString();
3688 result->EvalType = CXEval_ObjCStrLiteral;
3689 } else {
David Blaikiebbc00882016-04-13 18:36:19 +00003690 StrE = cast<StringLiteral>(I->getSubExprAsWritten());
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003691 result->EvalType = CXEval_StrLiteral;
3692 }
3693
3694 std::string strRef(StrE->getString().str());
David Blaikie59272572016-04-13 18:23:33 +00003695 result->EvalData.stringVal = new char[strRef.size() + 1];
David Blaikiebbc00882016-04-13 18:36:19 +00003696 strncpy((char *)result->EvalData.stringVal, strRef.c_str(),
3697 strRef.size());
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003698 result->EvalData.stringVal[strRef.size()] = '\0';
David Blaikie59272572016-04-13 18:23:33 +00003699 return result.release();
David Blaikiebbc00882016-04-13 18:36:19 +00003700 }
3701 } else if (expr->getStmtClass() == Stmt::ObjCStringLiteralClass ||
3702 expr->getStmtClass() == Stmt::StringLiteralClass) {
3703 const StringLiteral *StrE = nullptr;
3704 const ObjCStringLiteral *ObjCExpr;
3705 ObjCExpr = dyn_cast<ObjCStringLiteral>(expr);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003706
David Blaikiebbc00882016-04-13 18:36:19 +00003707 if (ObjCExpr) {
3708 StrE = ObjCExpr->getString();
3709 result->EvalType = CXEval_ObjCStrLiteral;
3710 } else {
3711 StrE = cast<StringLiteral>(expr);
3712 result->EvalType = CXEval_StrLiteral;
3713 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003714
David Blaikiebbc00882016-04-13 18:36:19 +00003715 std::string strRef(StrE->getString().str());
3716 result->EvalData.stringVal = new char[strRef.size() + 1];
3717 strncpy((char *)result->EvalData.stringVal, strRef.c_str(), strRef.size());
3718 result->EvalData.stringVal[strRef.size()] = '\0';
3719 return result.release();
3720 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003721
David Blaikiebbc00882016-04-13 18:36:19 +00003722 if (expr->getStmtClass() == Stmt::CStyleCastExprClass) {
3723 CStyleCastExpr *CC = static_cast<CStyleCastExpr *>(expr);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003724
David Blaikiebbc00882016-04-13 18:36:19 +00003725 rettype = CC->getType();
3726 if (rettype.getAsString() == "CFStringRef" &&
3727 CC->getSubExpr()->getStmtClass() == Stmt::CallExprClass) {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003728
David Blaikiebbc00882016-04-13 18:36:19 +00003729 callExpr = static_cast<CallExpr *>(CC->getSubExpr());
3730 StringLiteral *S = getCFSTR_value(callExpr);
3731 if (S) {
3732 std::string strLiteral(S->getString().str());
3733 result->EvalType = CXEval_CFStr;
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003734
David Blaikiebbc00882016-04-13 18:36:19 +00003735 result->EvalData.stringVal = new char[strLiteral.size() + 1];
3736 strncpy((char *)result->EvalData.stringVal, strLiteral.c_str(),
3737 strLiteral.size());
3738 result->EvalData.stringVal[strLiteral.size()] = '\0';
David Blaikie59272572016-04-13 18:23:33 +00003739 return result.release();
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003740 }
3741 }
3742
David Blaikiebbc00882016-04-13 18:36:19 +00003743 } else if (expr->getStmtClass() == Stmt::CallExprClass) {
3744 callExpr = static_cast<CallExpr *>(expr);
3745 rettype = callExpr->getCallReturnType(ctx);
3746
3747 if (rettype->isVectorType() || callExpr->getNumArgs() > 1)
3748 return nullptr;
3749
3750 if (rettype->isIntegralType(ctx) || rettype->isRealFloatingType()) {
3751 if (callExpr->getNumArgs() == 1 &&
3752 !callExpr->getArg(0)->getType()->isIntegralType(ctx))
3753 return nullptr;
3754 } else if (rettype.getAsString() == "CFStringRef") {
3755
3756 StringLiteral *S = getCFSTR_value(callExpr);
3757 if (S) {
3758 std::string strLiteral(S->getString().str());
3759 result->EvalType = CXEval_CFStr;
3760 result->EvalData.stringVal = new char[strLiteral.size() + 1];
3761 strncpy((char *)result->EvalData.stringVal, strLiteral.c_str(),
3762 strLiteral.size());
3763 result->EvalData.stringVal[strLiteral.size()] = '\0';
3764 return result.release();
3765 }
3766 }
3767 } else if (expr->getStmtClass() == Stmt::DeclRefExprClass) {
3768 DeclRefExpr *D = static_cast<DeclRefExpr *>(expr);
3769 ValueDecl *V = D->getDecl();
3770 if (V->getKind() == Decl::Function) {
3771 std::string strName = V->getNameAsString();
3772 result->EvalType = CXEval_Other;
3773 result->EvalData.stringVal = new char[strName.size() + 1];
3774 strncpy(result->EvalData.stringVal, strName.c_str(), strName.size());
3775 result->EvalData.stringVal[strName.size()] = '\0';
3776 return result.release();
3777 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003778 }
3779
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003780 return nullptr;
3781}
3782
3783CXEvalResult clang_Cursor_Evaluate(CXCursor C) {
3784 const Decl *D = getCursorDecl(C);
3785 if (D) {
3786 const Expr *expr = nullptr;
3787 if (auto *Var = dyn_cast<VarDecl>(D)) {
3788 expr = Var->getInit();
3789 } else if (auto *Field = dyn_cast<FieldDecl>(D)) {
3790 expr = Field->getInClassInitializer();
3791 }
3792 if (expr)
Aaron Ballman01dc1572016-01-20 15:25:30 +00003793 return const_cast<CXEvalResult>(reinterpret_cast<const void *>(
3794 evaluateExpr(const_cast<Expr *>(expr), C)));
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003795 return nullptr;
3796 }
3797
3798 const CompoundStmt *compoundStmt = dyn_cast_or_null<CompoundStmt>(getCursorStmt(C));
3799 if (compoundStmt) {
3800 Expr *expr = nullptr;
3801 for (auto *bodyIterator : compoundStmt->body()) {
3802 if ((expr = dyn_cast<Expr>(bodyIterator))) {
3803 break;
3804 }
3805 }
3806 if (expr)
Aaron Ballman01dc1572016-01-20 15:25:30 +00003807 return const_cast<CXEvalResult>(
3808 reinterpret_cast<const void *>(evaluateExpr(expr, C)));
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003809 }
3810 return nullptr;
3811}
3812
3813unsigned clang_Cursor_hasAttrs(CXCursor C) {
3814 const Decl *D = getCursorDecl(C);
3815 if (!D) {
3816 return 0;
3817 }
3818
3819 if (D->hasAttrs()) {
3820 return 1;
3821 }
3822
3823 return 0;
3824}
Guy Benyei11169dd2012-12-18 14:30:41 +00003825unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
3826 return CXSaveTranslationUnit_None;
3827}
3828
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003829static CXSaveError clang_saveTranslationUnit_Impl(CXTranslationUnit TU,
3830 const char *FileName,
3831 unsigned options) {
3832 CIndexer *CXXIdx = TU->CIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00003833 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
3834 setThreadBackgroundPriority();
3835
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003836 bool hadError = cxtu::getASTUnit(TU)->Save(FileName);
3837 return hadError ? CXSaveError_Unknown : CXSaveError_None;
Guy Benyei11169dd2012-12-18 14:30:41 +00003838}
3839
3840int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
3841 unsigned options) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00003842 LOG_FUNC_SECTION {
3843 *Log << TU << ' ' << FileName;
3844 }
3845
Dmitri Gribenko852d6222014-02-11 15:02:48 +00003846 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00003847 LOG_BAD_TU(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00003848 return CXSaveError_InvalidTU;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00003849 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003850
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00003851 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00003852 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3853 if (!CXXUnit->hasSema())
3854 return CXSaveError_InvalidTU;
3855
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003856 CXSaveError result;
3857 auto SaveTranslationUnitImpl = [=, &result]() {
3858 result = clang_saveTranslationUnit_Impl(TU, FileName, options);
3859 };
Guy Benyei11169dd2012-12-18 14:30:41 +00003860
3861 if (!CXXUnit->getDiagnostics().hasUnrecoverableErrorOccurred() ||
3862 getenv("LIBCLANG_NOTHREADS")) {
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003863 SaveTranslationUnitImpl();
Guy Benyei11169dd2012-12-18 14:30:41 +00003864
3865 if (getenv("LIBCLANG_RESOURCE_USAGE"))
3866 PrintLibclangResourceUsage(TU);
3867
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003868 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003869 }
3870
3871 // We have an AST that has invalid nodes due to compiler errors.
3872 // Use a crash recovery thread for protection.
3873
3874 llvm::CrashRecoveryContext CRC;
3875
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003876 if (!RunSafely(CRC, SaveTranslationUnitImpl)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003877 fprintf(stderr, "libclang: crash detected during AST saving: {\n");
3878 fprintf(stderr, " 'filename' : '%s'\n", FileName);
3879 fprintf(stderr, " 'options' : %d,\n", options);
3880 fprintf(stderr, "}\n");
3881
3882 return CXSaveError_Unknown;
3883
3884 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
3885 PrintLibclangResourceUsage(TU);
3886 }
3887
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003888 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003889}
3890
3891void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
3892 if (CTUnit) {
3893 // If the translation unit has been marked as unsafe to free, just discard
3894 // it.
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003895 ASTUnit *Unit = cxtu::getASTUnit(CTUnit);
3896 if (Unit && Unit->isUnsafeToFree())
Guy Benyei11169dd2012-12-18 14:30:41 +00003897 return;
3898
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00003899 delete cxtu::getASTUnit(CTUnit);
Dmitri Gribenkob95b3f12013-01-26 22:44:19 +00003900 delete CTUnit->StringPool;
Guy Benyei11169dd2012-12-18 14:30:41 +00003901 delete static_cast<CXDiagnosticSetImpl *>(CTUnit->Diagnostics);
3902 disposeOverridenCXCursorsPool(CTUnit->OverridenCursorsPool);
Dmitri Gribenko9e605112013-11-13 22:16:51 +00003903 delete CTUnit->CommentToXML;
Guy Benyei11169dd2012-12-18 14:30:41 +00003904 delete CTUnit;
3905 }
3906}
3907
3908unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
3909 return CXReparse_None;
3910}
3911
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003912static CXErrorCode
3913clang_reparseTranslationUnit_Impl(CXTranslationUnit TU,
3914 ArrayRef<CXUnsavedFile> unsaved_files,
3915 unsigned options) {
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003916 // Check arguments.
Dmitri Gribenko852d6222014-02-11 15:02:48 +00003917 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00003918 LOG_BAD_TU(TU);
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003919 return CXError_InvalidArguments;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003920 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003921
3922 // Reset the associated diagnostics.
3923 delete static_cast<CXDiagnosticSetImpl*>(TU->Diagnostics);
Craig Topper69186e72014-06-08 08:38:04 +00003924 TU->Diagnostics = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00003925
Dmitri Gribenko183436e2013-01-26 21:49:50 +00003926 CIndexer *CXXIdx = TU->CIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00003927 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing))
3928 setThreadBackgroundPriority();
3929
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00003930 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00003931 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ahmed Charlesb8984322014-03-07 20:03:18 +00003932
3933 std::unique_ptr<std::vector<ASTUnit::RemappedFile>> RemappedFiles(
3934 new std::vector<ASTUnit::RemappedFile>());
3935
Guy Benyei11169dd2012-12-18 14:30:41 +00003936 // Recover resources if we crash before exiting this function.
3937 llvm::CrashRecoveryContextCleanupRegistrar<
3938 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
Alp Toker9d85b182014-07-07 01:23:14 +00003939
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003940 for (auto &UF : unsaved_files) {
Rafael Espindolad87f8d72014-08-27 20:03:29 +00003941 std::unique_ptr<llvm::MemoryBuffer> MB =
Alp Toker9d85b182014-07-07 01:23:14 +00003942 llvm::MemoryBuffer::getMemBufferCopy(getContents(UF), UF.Filename);
Rafael Espindolad87f8d72014-08-27 20:03:29 +00003943 RemappedFiles->push_back(std::make_pair(UF.Filename, MB.release()));
Guy Benyei11169dd2012-12-18 14:30:41 +00003944 }
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003945
Adrian Prantlbb165fb2015-06-20 18:53:08 +00003946 if (!CXXUnit->Reparse(CXXIdx->getPCHContainerOperations(),
3947 *RemappedFiles.get()))
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003948 return CXError_Success;
3949 if (isASTReadError(CXXUnit))
3950 return CXError_ASTReadError;
3951 return CXError_Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003952}
3953
3954int clang_reparseTranslationUnit(CXTranslationUnit TU,
3955 unsigned num_unsaved_files,
3956 struct CXUnsavedFile *unsaved_files,
3957 unsigned options) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00003958 LOG_FUNC_SECTION {
3959 *Log << TU;
3960 }
3961
Alp Toker9d85b182014-07-07 01:23:14 +00003962 if (num_unsaved_files && !unsaved_files)
3963 return CXError_InvalidArguments;
3964
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003965 CXErrorCode result;
3966 auto ReparseTranslationUnitImpl = [=, &result]() {
3967 result = clang_reparseTranslationUnit_Impl(
3968 TU, llvm::makeArrayRef(unsaved_files, num_unsaved_files), options);
3969 };
Guy Benyei11169dd2012-12-18 14:30:41 +00003970
3971 if (getenv("LIBCLANG_NOTHREADS")) {
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003972 ReparseTranslationUnitImpl();
Alp Toker5c532982014-07-07 22:42:03 +00003973 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003974 }
3975
3976 llvm::CrashRecoveryContext CRC;
3977
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003978 if (!RunSafely(CRC, ReparseTranslationUnitImpl)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003979 fprintf(stderr, "libclang: crash detected during reparsing\n");
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00003980 cxtu::getASTUnit(TU)->setUnsafeToFree(true);
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003981 return CXError_Crashed;
Guy Benyei11169dd2012-12-18 14:30:41 +00003982 } else if (getenv("LIBCLANG_RESOURCE_USAGE"))
3983 PrintLibclangResourceUsage(TU);
3984
Alp Toker5c532982014-07-07 22:42:03 +00003985 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003986}
3987
3988
3989CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00003990 if (isNotUsableTU(CTUnit)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00003991 LOG_BAD_TU(CTUnit);
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00003992 return cxstring::createEmpty();
Dmitri Gribenko256454f2014-02-11 14:34:14 +00003993 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003994
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00003995 ASTUnit *CXXUnit = cxtu::getASTUnit(CTUnit);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00003996 return cxstring::createDup(CXXUnit->getOriginalSourceFileName());
Guy Benyei11169dd2012-12-18 14:30:41 +00003997}
3998
3999CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004000 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004001 LOG_BAD_TU(TU);
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00004002 return clang_getNullCursor();
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004003 }
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00004004
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004005 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004006 return MakeCXCursor(CXXUnit->getASTContext().getTranslationUnitDecl(), TU);
4007}
4008
Guy Benyei11169dd2012-12-18 14:30:41 +00004009//===----------------------------------------------------------------------===//
4010// CXFile Operations.
4011//===----------------------------------------------------------------------===//
4012
Guy Benyei11169dd2012-12-18 14:30:41 +00004013CXString clang_getFileName(CXFile SFile) {
4014 if (!SFile)
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00004015 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00004016
4017 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004018 return cxstring::createRef(FEnt->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004019}
4020
4021time_t clang_getFileTime(CXFile SFile) {
4022 if (!SFile)
4023 return 0;
4024
4025 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
4026 return FEnt->getModificationTime();
4027}
4028
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004029CXFile clang_getFile(CXTranslationUnit TU, const char *file_name) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004030 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004031 LOG_BAD_TU(TU);
Craig Topper69186e72014-06-08 08:38:04 +00004032 return nullptr;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004033 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004034
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004035 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004036
4037 FileManager &FMgr = CXXUnit->getFileManager();
4038 return const_cast<FileEntry *>(FMgr.getFile(file_name));
4039}
4040
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004041unsigned clang_isFileMultipleIncludeGuarded(CXTranslationUnit TU,
4042 CXFile file) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004043 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004044 LOG_BAD_TU(TU);
4045 return 0;
4046 }
4047
4048 if (!file)
Guy Benyei11169dd2012-12-18 14:30:41 +00004049 return 0;
4050
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004051 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004052 FileEntry *FEnt = static_cast<FileEntry *>(file);
4053 return CXXUnit->getPreprocessor().getHeaderSearchInfo()
4054 .isFileMultipleIncludeGuarded(FEnt);
4055}
4056
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00004057int clang_getFileUniqueID(CXFile file, CXFileUniqueID *outID) {
4058 if (!file || !outID)
4059 return 1;
4060
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00004061 FileEntry *FEnt = static_cast<FileEntry *>(file);
Rafael Espindolaf8f91b82013-08-01 21:42:11 +00004062 const llvm::sys::fs::UniqueID &ID = FEnt->getUniqueID();
4063 outID->data[0] = ID.getDevice();
4064 outID->data[1] = ID.getFile();
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00004065 outID->data[2] = FEnt->getModificationTime();
4066 return 0;
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00004067}
4068
Argyrios Kyrtzidisac3997e2014-08-16 00:26:19 +00004069int clang_File_isEqual(CXFile file1, CXFile file2) {
4070 if (file1 == file2)
4071 return true;
4072
4073 if (!file1 || !file2)
4074 return false;
4075
4076 FileEntry *FEnt1 = static_cast<FileEntry *>(file1);
4077 FileEntry *FEnt2 = static_cast<FileEntry *>(file2);
4078 return FEnt1->getUniqueID() == FEnt2->getUniqueID();
4079}
4080
Guy Benyei11169dd2012-12-18 14:30:41 +00004081//===----------------------------------------------------------------------===//
4082// CXCursor Operations.
4083//===----------------------------------------------------------------------===//
4084
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004085static const Decl *getDeclFromExpr(const Stmt *E) {
4086 if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004087 return getDeclFromExpr(CE->getSubExpr());
4088
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004089 if (const DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004090 return RefExpr->getDecl();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004091 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004092 return ME->getMemberDecl();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004093 if (const ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004094 return RE->getDecl();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004095 if (const ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004096 if (PRE->isExplicitProperty())
4097 return PRE->getExplicitProperty();
4098 // It could be messaging both getter and setter as in:
4099 // ++myobj.myprop;
4100 // in which case prefer to associate the setter since it is less obvious
4101 // from inspecting the source that the setter is going to get called.
4102 if (PRE->isMessagingSetter())
4103 return PRE->getImplicitPropertySetter();
4104 return PRE->getImplicitPropertyGetter();
4105 }
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004106 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004107 return getDeclFromExpr(POE->getSyntacticForm());
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004108 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004109 if (Expr *Src = OVE->getSourceExpr())
4110 return getDeclFromExpr(Src);
4111
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004112 if (const CallExpr *CE = dyn_cast<CallExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004113 return getDeclFromExpr(CE->getCallee());
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004114 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004115 if (!CE->isElidable())
4116 return CE->getConstructor();
Richard Smith5179eb72016-06-28 19:03:57 +00004117 if (const CXXInheritedCtorInitExpr *CE =
4118 dyn_cast<CXXInheritedCtorInitExpr>(E))
4119 return CE->getConstructor();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004120 if (const ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004121 return OME->getMethodDecl();
4122
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004123 if (const ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004124 return PE->getProtocol();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004125 if (const SubstNonTypeTemplateParmPackExpr *NTTP
Guy Benyei11169dd2012-12-18 14:30:41 +00004126 = dyn_cast<SubstNonTypeTemplateParmPackExpr>(E))
4127 return NTTP->getParameterPack();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004128 if (const SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004129 if (isa<NonTypeTemplateParmDecl>(SizeOfPack->getPack()) ||
4130 isa<ParmVarDecl>(SizeOfPack->getPack()))
4131 return SizeOfPack->getPack();
Craig Topper69186e72014-06-08 08:38:04 +00004132
4133 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004134}
4135
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004136static SourceLocation getLocationFromExpr(const Expr *E) {
4137 if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004138 return getLocationFromExpr(CE->getSubExpr());
4139
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004140 if (const ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004141 return /*FIXME:*/Msg->getLeftLoc();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004142 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004143 return DRE->getLocation();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004144 if (const MemberExpr *Member = dyn_cast<MemberExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004145 return Member->getMemberLoc();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004146 if (const ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004147 return Ivar->getLocation();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004148 if (const SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004149 return SizeOfPack->getPackLoc();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004150 if (const ObjCPropertyRefExpr *PropRef = dyn_cast<ObjCPropertyRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004151 return PropRef->getLocation();
4152
4153 return E->getLocStart();
4154}
4155
NAKAMURA Takumia01f4c32016-12-19 16:50:43 +00004156extern "C" {
4157
Guy Benyei11169dd2012-12-18 14:30:41 +00004158unsigned clang_visitChildren(CXCursor parent,
4159 CXCursorVisitor visitor,
4160 CXClientData client_data) {
4161 CursorVisitor CursorVis(getCursorTU(parent), visitor, client_data,
4162 /*VisitPreprocessorLast=*/false);
4163 return CursorVis.VisitChildren(parent);
4164}
4165
4166#ifndef __has_feature
4167#define __has_feature(x) 0
4168#endif
4169#if __has_feature(blocks)
4170typedef enum CXChildVisitResult
4171 (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
4172
4173static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
4174 CXClientData client_data) {
4175 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
4176 return block(cursor, parent);
4177}
4178#else
4179// If we are compiled with a compiler that doesn't have native blocks support,
4180// define and call the block manually, so the
4181typedef struct _CXChildVisitResult
4182{
4183 void *isa;
4184 int flags;
4185 int reserved;
4186 enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor,
4187 CXCursor);
4188} *CXCursorVisitorBlock;
4189
4190static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
4191 CXClientData client_data) {
4192 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
4193 return block->invoke(block, cursor, parent);
4194}
4195#endif
4196
4197
4198unsigned clang_visitChildrenWithBlock(CXCursor parent,
4199 CXCursorVisitorBlock block) {
4200 return clang_visitChildren(parent, visitWithBlock, block);
4201}
4202
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004203static CXString getDeclSpelling(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004204 if (!D)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004205 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004206
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004207 const NamedDecl *ND = dyn_cast<NamedDecl>(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00004208 if (!ND) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004209 if (const ObjCPropertyImplDecl *PropImpl =
4210 dyn_cast<ObjCPropertyImplDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00004211 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004212 return cxstring::createDup(Property->getIdentifier()->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004213
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004214 if (const ImportDecl *ImportD = dyn_cast<ImportDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00004215 if (Module *Mod = ImportD->getImportedModule())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004216 return cxstring::createDup(Mod->getFullModuleName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004217
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004218 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004219 }
4220
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004221 if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004222 return cxstring::createDup(OMD->getSelector().getAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004223
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004224 if (const ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
Guy Benyei11169dd2012-12-18 14:30:41 +00004225 // No, this isn't the same as the code below. getIdentifier() is non-virtual
4226 // and returns different names. NamedDecl returns the class name and
4227 // ObjCCategoryImplDecl returns the category name.
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004228 return cxstring::createRef(CIMP->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004229
4230 if (isa<UsingDirectiveDecl>(D))
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004231 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004232
4233 SmallString<1024> S;
4234 llvm::raw_svector_ostream os(S);
4235 ND->printName(os);
4236
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004237 return cxstring::createDup(os.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00004238}
4239
4240CXString clang_getCursorSpelling(CXCursor C) {
4241 if (clang_isTranslationUnit(C.kind))
Dmitri Gribenko2c173b42013-01-11 19:28:44 +00004242 return clang_getTranslationUnitSpelling(getCursorTU(C));
Guy Benyei11169dd2012-12-18 14:30:41 +00004243
4244 if (clang_isReference(C.kind)) {
4245 switch (C.kind) {
4246 case CXCursor_ObjCSuperClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004247 const ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004248 return cxstring::createRef(Super->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004249 }
4250 case CXCursor_ObjCClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004251 const ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004252 return cxstring::createRef(Class->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004253 }
4254 case CXCursor_ObjCProtocolRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004255 const ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004256 assert(OID && "getCursorSpelling(): Missing protocol decl");
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004257 return cxstring::createRef(OID->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004258 }
4259 case CXCursor_CXXBaseSpecifier: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004260 const CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004261 return cxstring::createDup(B->getType().getAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004262 }
4263 case CXCursor_TypeRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004264 const TypeDecl *Type = getCursorTypeRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004265 assert(Type && "Missing type decl");
4266
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004267 return cxstring::createDup(getCursorContext(C).getTypeDeclType(Type).
Guy Benyei11169dd2012-12-18 14:30:41 +00004268 getAsString());
4269 }
4270 case CXCursor_TemplateRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004271 const TemplateDecl *Template = getCursorTemplateRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004272 assert(Template && "Missing template decl");
4273
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004274 return cxstring::createDup(Template->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004275 }
4276
4277 case CXCursor_NamespaceRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004278 const NamedDecl *NS = getCursorNamespaceRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004279 assert(NS && "Missing namespace decl");
4280
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004281 return cxstring::createDup(NS->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004282 }
4283
4284 case CXCursor_MemberRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004285 const FieldDecl *Field = getCursorMemberRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004286 assert(Field && "Missing member decl");
4287
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004288 return cxstring::createDup(Field->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004289 }
4290
4291 case CXCursor_LabelRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004292 const LabelStmt *Label = getCursorLabelRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004293 assert(Label && "Missing label");
4294
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004295 return cxstring::createRef(Label->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004296 }
4297
4298 case CXCursor_OverloadedDeclRef: {
4299 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004300 if (const Decl *D = Storage.dyn_cast<const Decl *>()) {
4301 if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004302 return cxstring::createDup(ND->getNameAsString());
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004303 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004304 }
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004305 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004306 return cxstring::createDup(E->getName().getAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004307 OverloadedTemplateStorage *Ovl
4308 = Storage.get<OverloadedTemplateStorage*>();
4309 if (Ovl->size() == 0)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004310 return cxstring::createEmpty();
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004311 return cxstring::createDup((*Ovl->begin())->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004312 }
4313
4314 case CXCursor_VariableRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004315 const VarDecl *Var = getCursorVariableRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004316 assert(Var && "Missing variable decl");
4317
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004318 return cxstring::createDup(Var->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004319 }
4320
4321 default:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004322 return cxstring::createRef("<not implemented>");
Guy Benyei11169dd2012-12-18 14:30:41 +00004323 }
4324 }
4325
4326 if (clang_isExpression(C.kind)) {
Argyrios Kyrtzidis3227d862014-03-03 19:40:52 +00004327 const Expr *E = getCursorExpr(C);
4328
4329 if (C.kind == CXCursor_ObjCStringLiteral ||
4330 C.kind == CXCursor_StringLiteral) {
4331 const StringLiteral *SLit;
4332 if (const ObjCStringLiteral *OSL = dyn_cast<ObjCStringLiteral>(E)) {
4333 SLit = OSL->getString();
4334 } else {
4335 SLit = cast<StringLiteral>(E);
4336 }
4337 SmallString<256> Buf;
4338 llvm::raw_svector_ostream OS(Buf);
4339 SLit->outputString(OS);
4340 return cxstring::createDup(OS.str());
4341 }
4342
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004343 const Decl *D = getDeclFromExpr(getCursorExpr(C));
Guy Benyei11169dd2012-12-18 14:30:41 +00004344 if (D)
4345 return getDeclSpelling(D);
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004346 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004347 }
4348
4349 if (clang_isStatement(C.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004350 const Stmt *S = getCursorStmt(C);
4351 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004352 return cxstring::createRef(Label->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004353
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004354 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004355 }
4356
4357 if (C.kind == CXCursor_MacroExpansion)
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004358 return cxstring::createRef(getCursorMacroExpansion(C).getName()
Guy Benyei11169dd2012-12-18 14:30:41 +00004359 ->getNameStart());
4360
4361 if (C.kind == CXCursor_MacroDefinition)
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004362 return cxstring::createRef(getCursorMacroDefinition(C)->getName()
Guy Benyei11169dd2012-12-18 14:30:41 +00004363 ->getNameStart());
4364
4365 if (C.kind == CXCursor_InclusionDirective)
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004366 return cxstring::createDup(getCursorInclusionDirective(C)->getFileName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004367
4368 if (clang_isDeclaration(C.kind))
4369 return getDeclSpelling(getCursorDecl(C));
4370
4371 if (C.kind == CXCursor_AnnotateAttr) {
Dmitri Gribenkoe4baea62013-01-26 18:08:08 +00004372 const AnnotateAttr *AA = cast<AnnotateAttr>(cxcursor::getCursorAttr(C));
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004373 return cxstring::createDup(AA->getAnnotation());
Guy Benyei11169dd2012-12-18 14:30:41 +00004374 }
4375
4376 if (C.kind == CXCursor_AsmLabelAttr) {
Dmitri Gribenkoe4baea62013-01-26 18:08:08 +00004377 const AsmLabelAttr *AA = cast<AsmLabelAttr>(cxcursor::getCursorAttr(C));
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004378 return cxstring::createDup(AA->getLabel());
Guy Benyei11169dd2012-12-18 14:30:41 +00004379 }
4380
Argyrios Kyrtzidis16834f12013-09-25 00:14:38 +00004381 if (C.kind == CXCursor_PackedAttr) {
4382 return cxstring::createRef("packed");
4383 }
4384
Saleem Abdulrasool79c69712015-09-05 18:53:43 +00004385 if (C.kind == CXCursor_VisibilityAttr) {
4386 const VisibilityAttr *AA = cast<VisibilityAttr>(cxcursor::getCursorAttr(C));
4387 switch (AA->getVisibility()) {
4388 case VisibilityAttr::VisibilityType::Default:
4389 return cxstring::createRef("default");
4390 case VisibilityAttr::VisibilityType::Hidden:
4391 return cxstring::createRef("hidden");
4392 case VisibilityAttr::VisibilityType::Protected:
4393 return cxstring::createRef("protected");
4394 }
4395 llvm_unreachable("unknown visibility type");
4396 }
4397
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004398 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004399}
4400
4401CXSourceRange clang_Cursor_getSpellingNameRange(CXCursor C,
4402 unsigned pieceIndex,
4403 unsigned options) {
4404 if (clang_Cursor_isNull(C))
4405 return clang_getNullRange();
4406
4407 ASTContext &Ctx = getCursorContext(C);
4408
4409 if (clang_isStatement(C.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004410 const Stmt *S = getCursorStmt(C);
4411 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004412 if (pieceIndex > 0)
4413 return clang_getNullRange();
4414 return cxloc::translateSourceRange(Ctx, Label->getIdentLoc());
4415 }
4416
4417 return clang_getNullRange();
4418 }
4419
4420 if (C.kind == CXCursor_ObjCMessageExpr) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004421 if (const ObjCMessageExpr *
Guy Benyei11169dd2012-12-18 14:30:41 +00004422 ME = dyn_cast_or_null<ObjCMessageExpr>(getCursorExpr(C))) {
4423 if (pieceIndex >= ME->getNumSelectorLocs())
4424 return clang_getNullRange();
4425 return cxloc::translateSourceRange(Ctx, ME->getSelectorLoc(pieceIndex));
4426 }
4427 }
4428
4429 if (C.kind == CXCursor_ObjCInstanceMethodDecl ||
4430 C.kind == CXCursor_ObjCClassMethodDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004431 if (const ObjCMethodDecl *
Guy Benyei11169dd2012-12-18 14:30:41 +00004432 MD = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(C))) {
4433 if (pieceIndex >= MD->getNumSelectorLocs())
4434 return clang_getNullRange();
4435 return cxloc::translateSourceRange(Ctx, MD->getSelectorLoc(pieceIndex));
4436 }
4437 }
4438
4439 if (C.kind == CXCursor_ObjCCategoryDecl ||
4440 C.kind == CXCursor_ObjCCategoryImplDecl) {
4441 if (pieceIndex > 0)
4442 return clang_getNullRange();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004443 if (const ObjCCategoryDecl *
Guy Benyei11169dd2012-12-18 14:30:41 +00004444 CD = dyn_cast_or_null<ObjCCategoryDecl>(getCursorDecl(C)))
4445 return cxloc::translateSourceRange(Ctx, CD->getCategoryNameLoc());
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004446 if (const ObjCCategoryImplDecl *
Guy Benyei11169dd2012-12-18 14:30:41 +00004447 CID = dyn_cast_or_null<ObjCCategoryImplDecl>(getCursorDecl(C)))
4448 return cxloc::translateSourceRange(Ctx, CID->getCategoryNameLoc());
4449 }
4450
4451 if (C.kind == CXCursor_ModuleImportDecl) {
4452 if (pieceIndex > 0)
4453 return clang_getNullRange();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004454 if (const ImportDecl *ImportD =
4455 dyn_cast_or_null<ImportDecl>(getCursorDecl(C))) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004456 ArrayRef<SourceLocation> Locs = ImportD->getIdentifierLocs();
4457 if (!Locs.empty())
4458 return cxloc::translateSourceRange(Ctx,
4459 SourceRange(Locs.front(), Locs.back()));
4460 }
4461 return clang_getNullRange();
4462 }
4463
Argyrios Kyrtzidisa2a1e532014-08-26 20:23:26 +00004464 if (C.kind == CXCursor_CXXMethod || C.kind == CXCursor_Destructor ||
Kevin Funk4be5d672016-12-20 09:56:56 +00004465 C.kind == CXCursor_ConversionFunction ||
4466 C.kind == CXCursor_FunctionDecl) {
Argyrios Kyrtzidisa2a1e532014-08-26 20:23:26 +00004467 if (pieceIndex > 0)
4468 return clang_getNullRange();
4469 if (const FunctionDecl *FD =
4470 dyn_cast_or_null<FunctionDecl>(getCursorDecl(C))) {
4471 DeclarationNameInfo FunctionName = FD->getNameInfo();
4472 return cxloc::translateSourceRange(Ctx, FunctionName.getSourceRange());
4473 }
4474 return clang_getNullRange();
4475 }
4476
Guy Benyei11169dd2012-12-18 14:30:41 +00004477 // FIXME: A CXCursor_InclusionDirective should give the location of the
4478 // filename, but we don't keep track of this.
4479
4480 // FIXME: A CXCursor_AnnotateAttr should give the location of the annotation
4481 // but we don't keep track of this.
4482
4483 // FIXME: A CXCursor_AsmLabelAttr should give the location of the label
4484 // but we don't keep track of this.
4485
4486 // Default handling, give the location of the cursor.
4487
4488 if (pieceIndex > 0)
4489 return clang_getNullRange();
4490
4491 CXSourceLocation CXLoc = clang_getCursorLocation(C);
4492 SourceLocation Loc = cxloc::translateSourceLocation(CXLoc);
4493 return cxloc::translateSourceRange(Ctx, Loc);
4494}
4495
Eli Bendersky44a206f2014-07-31 18:04:56 +00004496CXString clang_Cursor_getMangling(CXCursor C) {
4497 if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
4498 return cxstring::createEmpty();
4499
Eli Bendersky44a206f2014-07-31 18:04:56 +00004500 // Mangling only works for functions and variables.
Eli Bendersky79759592014-08-01 15:01:10 +00004501 const Decl *D = getCursorDecl(C);
Eli Bendersky44a206f2014-07-31 18:04:56 +00004502 if (!D || !(isa<FunctionDecl>(D) || isa<VarDecl>(D)))
4503 return cxstring::createEmpty();
4504
Argyrios Kyrtzidisca741ce2016-02-14 22:30:14 +00004505 ASTContext &Ctx = D->getASTContext();
4506 index::CodegenNameGenerator CGNameGen(Ctx);
4507 return cxstring::createDup(CGNameGen.getName(D));
Eli Bendersky44a206f2014-07-31 18:04:56 +00004508}
4509
Saleem Abdulrasool60034432015-11-12 03:57:22 +00004510CXStringSet *clang_Cursor_getCXXManglings(CXCursor C) {
4511 if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
4512 return nullptr;
4513
4514 const Decl *D = getCursorDecl(C);
4515 if (!(isa<CXXRecordDecl>(D) || isa<CXXMethodDecl>(D)))
4516 return nullptr;
4517
Argyrios Kyrtzidisca741ce2016-02-14 22:30:14 +00004518 ASTContext &Ctx = D->getASTContext();
4519 index::CodegenNameGenerator CGNameGen(Ctx);
4520 std::vector<std::string> Manglings = CGNameGen.getAllManglings(D);
Saleem Abdulrasool60034432015-11-12 03:57:22 +00004521 return cxstring::createSet(Manglings);
4522}
4523
Guy Benyei11169dd2012-12-18 14:30:41 +00004524CXString clang_getCursorDisplayName(CXCursor C) {
4525 if (!clang_isDeclaration(C.kind))
4526 return clang_getCursorSpelling(C);
4527
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004528 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00004529 if (!D)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004530 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004531
4532 PrintingPolicy Policy = getCursorContext(C).getPrintingPolicy();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004533 if (const FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00004534 D = FunTmpl->getTemplatedDecl();
4535
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004536 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004537 SmallString<64> Str;
4538 llvm::raw_svector_ostream OS(Str);
4539 OS << *Function;
4540 if (Function->getPrimaryTemplate())
4541 OS << "<>";
4542 OS << "(";
4543 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
4544 if (I)
4545 OS << ", ";
4546 OS << Function->getParamDecl(I)->getType().getAsString(Policy);
4547 }
4548
4549 if (Function->isVariadic()) {
4550 if (Function->getNumParams())
4551 OS << ", ";
4552 OS << "...";
4553 }
4554 OS << ")";
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004555 return cxstring::createDup(OS.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00004556 }
4557
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004558 if (const ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004559 SmallString<64> Str;
4560 llvm::raw_svector_ostream OS(Str);
4561 OS << *ClassTemplate;
4562 OS << "<";
4563 TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
4564 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
4565 if (I)
4566 OS << ", ";
4567
4568 NamedDecl *Param = Params->getParam(I);
4569 if (Param->getIdentifier()) {
4570 OS << Param->getIdentifier()->getName();
4571 continue;
4572 }
4573
4574 // There is no parameter name, which makes this tricky. Try to come up
4575 // with something useful that isn't too long.
4576 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
4577 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
4578 else if (NonTypeTemplateParmDecl *NTTP
4579 = dyn_cast<NonTypeTemplateParmDecl>(Param))
4580 OS << NTTP->getType().getAsString(Policy);
4581 else
4582 OS << "template<...> class";
4583 }
4584
4585 OS << ">";
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004586 return cxstring::createDup(OS.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00004587 }
4588
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004589 if (const ClassTemplateSpecializationDecl *ClassSpec
Guy Benyei11169dd2012-12-18 14:30:41 +00004590 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
4591 // If the type was explicitly written, use that.
4592 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004593 return cxstring::createDup(TSInfo->getType().getAsString(Policy));
Guy Benyei11169dd2012-12-18 14:30:41 +00004594
Benjamin Kramer9170e912013-02-22 15:46:01 +00004595 SmallString<128> Str;
Guy Benyei11169dd2012-12-18 14:30:41 +00004596 llvm::raw_svector_ostream OS(Str);
4597 OS << *ClassSpec;
David Majnemer6fbeee32016-07-07 04:43:07 +00004598 TemplateSpecializationType::PrintTemplateArgumentList(
4599 OS, ClassSpec->getTemplateArgs().asArray(), Policy);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004600 return cxstring::createDup(OS.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00004601 }
4602
4603 return clang_getCursorSpelling(C);
4604}
4605
4606CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
4607 switch (Kind) {
4608 case CXCursor_FunctionDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004609 return cxstring::createRef("FunctionDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004610 case CXCursor_TypedefDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004611 return cxstring::createRef("TypedefDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004612 case CXCursor_EnumDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004613 return cxstring::createRef("EnumDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004614 case CXCursor_EnumConstantDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004615 return cxstring::createRef("EnumConstantDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004616 case CXCursor_StructDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004617 return cxstring::createRef("StructDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004618 case CXCursor_UnionDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004619 return cxstring::createRef("UnionDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004620 case CXCursor_ClassDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004621 return cxstring::createRef("ClassDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004622 case CXCursor_FieldDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004623 return cxstring::createRef("FieldDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004624 case CXCursor_VarDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004625 return cxstring::createRef("VarDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004626 case CXCursor_ParmDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004627 return cxstring::createRef("ParmDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004628 case CXCursor_ObjCInterfaceDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004629 return cxstring::createRef("ObjCInterfaceDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004630 case CXCursor_ObjCCategoryDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004631 return cxstring::createRef("ObjCCategoryDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004632 case CXCursor_ObjCProtocolDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004633 return cxstring::createRef("ObjCProtocolDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004634 case CXCursor_ObjCPropertyDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004635 return cxstring::createRef("ObjCPropertyDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004636 case CXCursor_ObjCIvarDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004637 return cxstring::createRef("ObjCIvarDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004638 case CXCursor_ObjCInstanceMethodDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004639 return cxstring::createRef("ObjCInstanceMethodDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004640 case CXCursor_ObjCClassMethodDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004641 return cxstring::createRef("ObjCClassMethodDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004642 case CXCursor_ObjCImplementationDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004643 return cxstring::createRef("ObjCImplementationDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004644 case CXCursor_ObjCCategoryImplDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004645 return cxstring::createRef("ObjCCategoryImplDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004646 case CXCursor_CXXMethod:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004647 return cxstring::createRef("CXXMethod");
Guy Benyei11169dd2012-12-18 14:30:41 +00004648 case CXCursor_UnexposedDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004649 return cxstring::createRef("UnexposedDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004650 case CXCursor_ObjCSuperClassRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004651 return cxstring::createRef("ObjCSuperClassRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00004652 case CXCursor_ObjCProtocolRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004653 return cxstring::createRef("ObjCProtocolRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00004654 case CXCursor_ObjCClassRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004655 return cxstring::createRef("ObjCClassRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00004656 case CXCursor_TypeRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004657 return cxstring::createRef("TypeRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00004658 case CXCursor_TemplateRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004659 return cxstring::createRef("TemplateRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00004660 case CXCursor_NamespaceRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004661 return cxstring::createRef("NamespaceRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00004662 case CXCursor_MemberRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004663 return cxstring::createRef("MemberRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00004664 case CXCursor_LabelRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004665 return cxstring::createRef("LabelRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00004666 case CXCursor_OverloadedDeclRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004667 return cxstring::createRef("OverloadedDeclRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00004668 case CXCursor_VariableRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004669 return cxstring::createRef("VariableRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00004670 case CXCursor_IntegerLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004671 return cxstring::createRef("IntegerLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00004672 case CXCursor_FloatingLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004673 return cxstring::createRef("FloatingLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00004674 case CXCursor_ImaginaryLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004675 return cxstring::createRef("ImaginaryLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00004676 case CXCursor_StringLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004677 return cxstring::createRef("StringLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00004678 case CXCursor_CharacterLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004679 return cxstring::createRef("CharacterLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00004680 case CXCursor_ParenExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004681 return cxstring::createRef("ParenExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004682 case CXCursor_UnaryOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004683 return cxstring::createRef("UnaryOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00004684 case CXCursor_ArraySubscriptExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004685 return cxstring::createRef("ArraySubscriptExpr");
Alexey Bataev1a3320e2015-08-25 14:24:04 +00004686 case CXCursor_OMPArraySectionExpr:
4687 return cxstring::createRef("OMPArraySectionExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004688 case CXCursor_BinaryOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004689 return cxstring::createRef("BinaryOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00004690 case CXCursor_CompoundAssignOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004691 return cxstring::createRef("CompoundAssignOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00004692 case CXCursor_ConditionalOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004693 return cxstring::createRef("ConditionalOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00004694 case CXCursor_CStyleCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004695 return cxstring::createRef("CStyleCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004696 case CXCursor_CompoundLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004697 return cxstring::createRef("CompoundLiteralExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004698 case CXCursor_InitListExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004699 return cxstring::createRef("InitListExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004700 case CXCursor_AddrLabelExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004701 return cxstring::createRef("AddrLabelExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004702 case CXCursor_StmtExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004703 return cxstring::createRef("StmtExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004704 case CXCursor_GenericSelectionExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004705 return cxstring::createRef("GenericSelectionExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004706 case CXCursor_GNUNullExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004707 return cxstring::createRef("GNUNullExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004708 case CXCursor_CXXStaticCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004709 return cxstring::createRef("CXXStaticCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004710 case CXCursor_CXXDynamicCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004711 return cxstring::createRef("CXXDynamicCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004712 case CXCursor_CXXReinterpretCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004713 return cxstring::createRef("CXXReinterpretCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004714 case CXCursor_CXXConstCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004715 return cxstring::createRef("CXXConstCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004716 case CXCursor_CXXFunctionalCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004717 return cxstring::createRef("CXXFunctionalCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004718 case CXCursor_CXXTypeidExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004719 return cxstring::createRef("CXXTypeidExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004720 case CXCursor_CXXBoolLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004721 return cxstring::createRef("CXXBoolLiteralExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004722 case CXCursor_CXXNullPtrLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004723 return cxstring::createRef("CXXNullPtrLiteralExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004724 case CXCursor_CXXThisExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004725 return cxstring::createRef("CXXThisExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004726 case CXCursor_CXXThrowExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004727 return cxstring::createRef("CXXThrowExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004728 case CXCursor_CXXNewExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004729 return cxstring::createRef("CXXNewExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004730 case CXCursor_CXXDeleteExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004731 return cxstring::createRef("CXXDeleteExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004732 case CXCursor_UnaryExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004733 return cxstring::createRef("UnaryExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004734 case CXCursor_ObjCStringLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004735 return cxstring::createRef("ObjCStringLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00004736 case CXCursor_ObjCBoolLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004737 return cxstring::createRef("ObjCBoolLiteralExpr");
Erik Pilkington29099de2016-07-16 00:35:23 +00004738 case CXCursor_ObjCAvailabilityCheckExpr:
4739 return cxstring::createRef("ObjCAvailabilityCheckExpr");
Argyrios Kyrtzidisc2233be2013-04-23 17:57:17 +00004740 case CXCursor_ObjCSelfExpr:
4741 return cxstring::createRef("ObjCSelfExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004742 case CXCursor_ObjCEncodeExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004743 return cxstring::createRef("ObjCEncodeExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004744 case CXCursor_ObjCSelectorExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004745 return cxstring::createRef("ObjCSelectorExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004746 case CXCursor_ObjCProtocolExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004747 return cxstring::createRef("ObjCProtocolExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004748 case CXCursor_ObjCBridgedCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004749 return cxstring::createRef("ObjCBridgedCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004750 case CXCursor_BlockExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004751 return cxstring::createRef("BlockExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004752 case CXCursor_PackExpansionExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004753 return cxstring::createRef("PackExpansionExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004754 case CXCursor_SizeOfPackExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004755 return cxstring::createRef("SizeOfPackExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004756 case CXCursor_LambdaExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004757 return cxstring::createRef("LambdaExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004758 case CXCursor_UnexposedExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004759 return cxstring::createRef("UnexposedExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004760 case CXCursor_DeclRefExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004761 return cxstring::createRef("DeclRefExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004762 case CXCursor_MemberRefExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004763 return cxstring::createRef("MemberRefExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004764 case CXCursor_CallExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004765 return cxstring::createRef("CallExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004766 case CXCursor_ObjCMessageExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004767 return cxstring::createRef("ObjCMessageExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004768 case CXCursor_UnexposedStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004769 return cxstring::createRef("UnexposedStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004770 case CXCursor_DeclStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004771 return cxstring::createRef("DeclStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004772 case CXCursor_LabelStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004773 return cxstring::createRef("LabelStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004774 case CXCursor_CompoundStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004775 return cxstring::createRef("CompoundStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004776 case CXCursor_CaseStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004777 return cxstring::createRef("CaseStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004778 case CXCursor_DefaultStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004779 return cxstring::createRef("DefaultStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004780 case CXCursor_IfStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004781 return cxstring::createRef("IfStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004782 case CXCursor_SwitchStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004783 return cxstring::createRef("SwitchStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004784 case CXCursor_WhileStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004785 return cxstring::createRef("WhileStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004786 case CXCursor_DoStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004787 return cxstring::createRef("DoStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004788 case CXCursor_ForStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004789 return cxstring::createRef("ForStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004790 case CXCursor_GotoStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004791 return cxstring::createRef("GotoStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004792 case CXCursor_IndirectGotoStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004793 return cxstring::createRef("IndirectGotoStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004794 case CXCursor_ContinueStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004795 return cxstring::createRef("ContinueStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004796 case CXCursor_BreakStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004797 return cxstring::createRef("BreakStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004798 case CXCursor_ReturnStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004799 return cxstring::createRef("ReturnStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004800 case CXCursor_GCCAsmStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004801 return cxstring::createRef("GCCAsmStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004802 case CXCursor_MSAsmStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004803 return cxstring::createRef("MSAsmStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004804 case CXCursor_ObjCAtTryStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004805 return cxstring::createRef("ObjCAtTryStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004806 case CXCursor_ObjCAtCatchStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004807 return cxstring::createRef("ObjCAtCatchStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004808 case CXCursor_ObjCAtFinallyStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004809 return cxstring::createRef("ObjCAtFinallyStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004810 case CXCursor_ObjCAtThrowStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004811 return cxstring::createRef("ObjCAtThrowStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004812 case CXCursor_ObjCAtSynchronizedStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004813 return cxstring::createRef("ObjCAtSynchronizedStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004814 case CXCursor_ObjCAutoreleasePoolStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004815 return cxstring::createRef("ObjCAutoreleasePoolStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004816 case CXCursor_ObjCForCollectionStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004817 return cxstring::createRef("ObjCForCollectionStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004818 case CXCursor_CXXCatchStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004819 return cxstring::createRef("CXXCatchStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004820 case CXCursor_CXXTryStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004821 return cxstring::createRef("CXXTryStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004822 case CXCursor_CXXForRangeStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004823 return cxstring::createRef("CXXForRangeStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004824 case CXCursor_SEHTryStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004825 return cxstring::createRef("SEHTryStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004826 case CXCursor_SEHExceptStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004827 return cxstring::createRef("SEHExceptStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004828 case CXCursor_SEHFinallyStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004829 return cxstring::createRef("SEHFinallyStmt");
Nico Weber9b982072014-07-07 00:12:30 +00004830 case CXCursor_SEHLeaveStmt:
4831 return cxstring::createRef("SEHLeaveStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004832 case CXCursor_NullStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004833 return cxstring::createRef("NullStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004834 case CXCursor_InvalidFile:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004835 return cxstring::createRef("InvalidFile");
Guy Benyei11169dd2012-12-18 14:30:41 +00004836 case CXCursor_InvalidCode:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004837 return cxstring::createRef("InvalidCode");
Guy Benyei11169dd2012-12-18 14:30:41 +00004838 case CXCursor_NoDeclFound:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004839 return cxstring::createRef("NoDeclFound");
Guy Benyei11169dd2012-12-18 14:30:41 +00004840 case CXCursor_NotImplemented:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004841 return cxstring::createRef("NotImplemented");
Guy Benyei11169dd2012-12-18 14:30:41 +00004842 case CXCursor_TranslationUnit:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004843 return cxstring::createRef("TranslationUnit");
Guy Benyei11169dd2012-12-18 14:30:41 +00004844 case CXCursor_UnexposedAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004845 return cxstring::createRef("UnexposedAttr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004846 case CXCursor_IBActionAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004847 return cxstring::createRef("attribute(ibaction)");
Guy Benyei11169dd2012-12-18 14:30:41 +00004848 case CXCursor_IBOutletAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004849 return cxstring::createRef("attribute(iboutlet)");
Guy Benyei11169dd2012-12-18 14:30:41 +00004850 case CXCursor_IBOutletCollectionAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004851 return cxstring::createRef("attribute(iboutletcollection)");
Guy Benyei11169dd2012-12-18 14:30:41 +00004852 case CXCursor_CXXFinalAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004853 return cxstring::createRef("attribute(final)");
Guy Benyei11169dd2012-12-18 14:30:41 +00004854 case CXCursor_CXXOverrideAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004855 return cxstring::createRef("attribute(override)");
Guy Benyei11169dd2012-12-18 14:30:41 +00004856 case CXCursor_AnnotateAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004857 return cxstring::createRef("attribute(annotate)");
Guy Benyei11169dd2012-12-18 14:30:41 +00004858 case CXCursor_AsmLabelAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004859 return cxstring::createRef("asm label");
Argyrios Kyrtzidis16834f12013-09-25 00:14:38 +00004860 case CXCursor_PackedAttr:
4861 return cxstring::createRef("attribute(packed)");
Joey Gouly81228382014-05-01 15:41:58 +00004862 case CXCursor_PureAttr:
4863 return cxstring::createRef("attribute(pure)");
4864 case CXCursor_ConstAttr:
4865 return cxstring::createRef("attribute(const)");
4866 case CXCursor_NoDuplicateAttr:
4867 return cxstring::createRef("attribute(noduplicate)");
Eli Bendersky2581e662014-05-28 19:29:58 +00004868 case CXCursor_CUDAConstantAttr:
4869 return cxstring::createRef("attribute(constant)");
4870 case CXCursor_CUDADeviceAttr:
4871 return cxstring::createRef("attribute(device)");
4872 case CXCursor_CUDAGlobalAttr:
4873 return cxstring::createRef("attribute(global)");
4874 case CXCursor_CUDAHostAttr:
4875 return cxstring::createRef("attribute(host)");
Eli Bendersky9b071472014-08-08 14:59:00 +00004876 case CXCursor_CUDASharedAttr:
4877 return cxstring::createRef("attribute(shared)");
Saleem Abdulrasool79c69712015-09-05 18:53:43 +00004878 case CXCursor_VisibilityAttr:
4879 return cxstring::createRef("attribute(visibility)");
Saleem Abdulrasool8aa0b802015-12-10 18:45:18 +00004880 case CXCursor_DLLExport:
4881 return cxstring::createRef("attribute(dllexport)");
4882 case CXCursor_DLLImport:
4883 return cxstring::createRef("attribute(dllimport)");
Guy Benyei11169dd2012-12-18 14:30:41 +00004884 case CXCursor_PreprocessingDirective:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004885 return cxstring::createRef("preprocessing directive");
Guy Benyei11169dd2012-12-18 14:30:41 +00004886 case CXCursor_MacroDefinition:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004887 return cxstring::createRef("macro definition");
Guy Benyei11169dd2012-12-18 14:30:41 +00004888 case CXCursor_MacroExpansion:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004889 return cxstring::createRef("macro expansion");
Guy Benyei11169dd2012-12-18 14:30:41 +00004890 case CXCursor_InclusionDirective:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004891 return cxstring::createRef("inclusion directive");
Guy Benyei11169dd2012-12-18 14:30:41 +00004892 case CXCursor_Namespace:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004893 return cxstring::createRef("Namespace");
Guy Benyei11169dd2012-12-18 14:30:41 +00004894 case CXCursor_LinkageSpec:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004895 return cxstring::createRef("LinkageSpec");
Guy Benyei11169dd2012-12-18 14:30:41 +00004896 case CXCursor_CXXBaseSpecifier:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004897 return cxstring::createRef("C++ base class specifier");
Guy Benyei11169dd2012-12-18 14:30:41 +00004898 case CXCursor_Constructor:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004899 return cxstring::createRef("CXXConstructor");
Guy Benyei11169dd2012-12-18 14:30:41 +00004900 case CXCursor_Destructor:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004901 return cxstring::createRef("CXXDestructor");
Guy Benyei11169dd2012-12-18 14:30:41 +00004902 case CXCursor_ConversionFunction:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004903 return cxstring::createRef("CXXConversion");
Guy Benyei11169dd2012-12-18 14:30:41 +00004904 case CXCursor_TemplateTypeParameter:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004905 return cxstring::createRef("TemplateTypeParameter");
Guy Benyei11169dd2012-12-18 14:30:41 +00004906 case CXCursor_NonTypeTemplateParameter:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004907 return cxstring::createRef("NonTypeTemplateParameter");
Guy Benyei11169dd2012-12-18 14:30:41 +00004908 case CXCursor_TemplateTemplateParameter:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004909 return cxstring::createRef("TemplateTemplateParameter");
Guy Benyei11169dd2012-12-18 14:30:41 +00004910 case CXCursor_FunctionTemplate:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004911 return cxstring::createRef("FunctionTemplate");
Guy Benyei11169dd2012-12-18 14:30:41 +00004912 case CXCursor_ClassTemplate:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004913 return cxstring::createRef("ClassTemplate");
Guy Benyei11169dd2012-12-18 14:30:41 +00004914 case CXCursor_ClassTemplatePartialSpecialization:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004915 return cxstring::createRef("ClassTemplatePartialSpecialization");
Guy Benyei11169dd2012-12-18 14:30:41 +00004916 case CXCursor_NamespaceAlias:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004917 return cxstring::createRef("NamespaceAlias");
Guy Benyei11169dd2012-12-18 14:30:41 +00004918 case CXCursor_UsingDirective:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004919 return cxstring::createRef("UsingDirective");
Guy Benyei11169dd2012-12-18 14:30:41 +00004920 case CXCursor_UsingDeclaration:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004921 return cxstring::createRef("UsingDeclaration");
Guy Benyei11169dd2012-12-18 14:30:41 +00004922 case CXCursor_TypeAliasDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004923 return cxstring::createRef("TypeAliasDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004924 case CXCursor_ObjCSynthesizeDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004925 return cxstring::createRef("ObjCSynthesizeDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004926 case CXCursor_ObjCDynamicDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004927 return cxstring::createRef("ObjCDynamicDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004928 case CXCursor_CXXAccessSpecifier:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004929 return cxstring::createRef("CXXAccessSpecifier");
Guy Benyei11169dd2012-12-18 14:30:41 +00004930 case CXCursor_ModuleImportDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004931 return cxstring::createRef("ModuleImport");
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004932 case CXCursor_OMPParallelDirective:
Alexey Bataev1b59ab52014-02-27 08:29:12 +00004933 return cxstring::createRef("OMPParallelDirective");
4934 case CXCursor_OMPSimdDirective:
4935 return cxstring::createRef("OMPSimdDirective");
Alexey Bataevf29276e2014-06-18 04:14:57 +00004936 case CXCursor_OMPForDirective:
4937 return cxstring::createRef("OMPForDirective");
Alexander Musmanf82886e2014-09-18 05:12:34 +00004938 case CXCursor_OMPForSimdDirective:
4939 return cxstring::createRef("OMPForSimdDirective");
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004940 case CXCursor_OMPSectionsDirective:
4941 return cxstring::createRef("OMPSectionsDirective");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004942 case CXCursor_OMPSectionDirective:
4943 return cxstring::createRef("OMPSectionDirective");
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00004944 case CXCursor_OMPSingleDirective:
4945 return cxstring::createRef("OMPSingleDirective");
Alexander Musman80c22892014-07-17 08:54:58 +00004946 case CXCursor_OMPMasterDirective:
4947 return cxstring::createRef("OMPMasterDirective");
Alexander Musmand9ed09f2014-07-21 09:42:05 +00004948 case CXCursor_OMPCriticalDirective:
4949 return cxstring::createRef("OMPCriticalDirective");
Alexey Bataev4acb8592014-07-07 13:01:15 +00004950 case CXCursor_OMPParallelForDirective:
4951 return cxstring::createRef("OMPParallelForDirective");
Alexander Musmane4e893b2014-09-23 09:33:00 +00004952 case CXCursor_OMPParallelForSimdDirective:
4953 return cxstring::createRef("OMPParallelForSimdDirective");
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004954 case CXCursor_OMPParallelSectionsDirective:
4955 return cxstring::createRef("OMPParallelSectionsDirective");
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004956 case CXCursor_OMPTaskDirective:
4957 return cxstring::createRef("OMPTaskDirective");
Alexey Bataev68446b72014-07-18 07:47:19 +00004958 case CXCursor_OMPTaskyieldDirective:
4959 return cxstring::createRef("OMPTaskyieldDirective");
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00004960 case CXCursor_OMPBarrierDirective:
4961 return cxstring::createRef("OMPBarrierDirective");
Alexey Bataev2df347a2014-07-18 10:17:07 +00004962 case CXCursor_OMPTaskwaitDirective:
4963 return cxstring::createRef("OMPTaskwaitDirective");
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00004964 case CXCursor_OMPTaskgroupDirective:
4965 return cxstring::createRef("OMPTaskgroupDirective");
Alexey Bataev6125da92014-07-21 11:26:11 +00004966 case CXCursor_OMPFlushDirective:
4967 return cxstring::createRef("OMPFlushDirective");
Alexey Bataev9fb6e642014-07-22 06:45:04 +00004968 case CXCursor_OMPOrderedDirective:
4969 return cxstring::createRef("OMPOrderedDirective");
Alexey Bataev0162e452014-07-22 10:10:35 +00004970 case CXCursor_OMPAtomicDirective:
4971 return cxstring::createRef("OMPAtomicDirective");
Alexey Bataev0bd520b2014-09-19 08:19:49 +00004972 case CXCursor_OMPTargetDirective:
4973 return cxstring::createRef("OMPTargetDirective");
Michael Wong65f367f2015-07-21 13:44:28 +00004974 case CXCursor_OMPTargetDataDirective:
4975 return cxstring::createRef("OMPTargetDataDirective");
Samuel Antaodf67fc42016-01-19 19:15:56 +00004976 case CXCursor_OMPTargetEnterDataDirective:
4977 return cxstring::createRef("OMPTargetEnterDataDirective");
Samuel Antao72590762016-01-19 20:04:50 +00004978 case CXCursor_OMPTargetExitDataDirective:
4979 return cxstring::createRef("OMPTargetExitDataDirective");
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00004980 case CXCursor_OMPTargetParallelDirective:
4981 return cxstring::createRef("OMPTargetParallelDirective");
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00004982 case CXCursor_OMPTargetParallelForDirective:
4983 return cxstring::createRef("OMPTargetParallelForDirective");
Samuel Antao686c70c2016-05-26 17:30:50 +00004984 case CXCursor_OMPTargetUpdateDirective:
4985 return cxstring::createRef("OMPTargetUpdateDirective");
Alexey Bataev13314bf2014-10-09 04:18:56 +00004986 case CXCursor_OMPTeamsDirective:
4987 return cxstring::createRef("OMPTeamsDirective");
Alexey Bataev6d4ed052015-07-01 06:57:41 +00004988 case CXCursor_OMPCancellationPointDirective:
4989 return cxstring::createRef("OMPCancellationPointDirective");
Alexey Bataev80909872015-07-02 11:25:17 +00004990 case CXCursor_OMPCancelDirective:
4991 return cxstring::createRef("OMPCancelDirective");
Alexey Bataev49f6e782015-12-01 04:18:41 +00004992 case CXCursor_OMPTaskLoopDirective:
4993 return cxstring::createRef("OMPTaskLoopDirective");
Alexey Bataev0a6ed842015-12-03 09:40:15 +00004994 case CXCursor_OMPTaskLoopSimdDirective:
4995 return cxstring::createRef("OMPTaskLoopSimdDirective");
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004996 case CXCursor_OMPDistributeDirective:
4997 return cxstring::createRef("OMPDistributeDirective");
Carlo Bertolli9925f152016-06-27 14:55:37 +00004998 case CXCursor_OMPDistributeParallelForDirective:
4999 return cxstring::createRef("OMPDistributeParallelForDirective");
Kelvin Li4a39add2016-07-05 05:00:15 +00005000 case CXCursor_OMPDistributeParallelForSimdDirective:
5001 return cxstring::createRef("OMPDistributeParallelForSimdDirective");
Kelvin Li787f3fc2016-07-06 04:45:38 +00005002 case CXCursor_OMPDistributeSimdDirective:
5003 return cxstring::createRef("OMPDistributeSimdDirective");
Kelvin Lia579b912016-07-14 02:54:56 +00005004 case CXCursor_OMPTargetParallelForSimdDirective:
5005 return cxstring::createRef("OMPTargetParallelForSimdDirective");
Kelvin Li986330c2016-07-20 22:57:10 +00005006 case CXCursor_OMPTargetSimdDirective:
5007 return cxstring::createRef("OMPTargetSimdDirective");
Kelvin Li02532872016-08-05 14:37:37 +00005008 case CXCursor_OMPTeamsDistributeDirective:
5009 return cxstring::createRef("OMPTeamsDistributeDirective");
Kelvin Li4e325f72016-10-25 12:50:55 +00005010 case CXCursor_OMPTeamsDistributeSimdDirective:
5011 return cxstring::createRef("OMPTeamsDistributeSimdDirective");
Kelvin Li579e41c2016-11-30 23:51:03 +00005012 case CXCursor_OMPTeamsDistributeParallelForSimdDirective:
5013 return cxstring::createRef("OMPTeamsDistributeParallelForSimdDirective");
Kelvin Li7ade93f2016-12-09 03:24:30 +00005014 case CXCursor_OMPTeamsDistributeParallelForDirective:
5015 return cxstring::createRef("OMPTeamsDistributeParallelForDirective");
Kelvin Libf594a52016-12-17 05:48:59 +00005016 case CXCursor_OMPTargetTeamsDirective:
5017 return cxstring::createRef("OMPTargetTeamsDirective");
Kelvin Li83c451e2016-12-25 04:52:54 +00005018 case CXCursor_OMPTargetTeamsDistributeDirective:
5019 return cxstring::createRef("OMPTargetTeamsDistributeDirective");
Kelvin Li80e8f562016-12-29 22:16:30 +00005020 case CXCursor_OMPTargetTeamsDistributeParallelForDirective:
5021 return cxstring::createRef("OMPTargetTeamsDistributeParallelForDirective");
Kelvin Li1851df52017-01-03 05:23:48 +00005022 case CXCursor_OMPTargetTeamsDistributeParallelForSimdDirective:
5023 return cxstring::createRef(
5024 "OMPTargetTeamsDistributeParallelForSimdDirective");
Kelvin Lida681182017-01-10 18:08:18 +00005025 case CXCursor_OMPTargetTeamsDistributeSimdDirective:
5026 return cxstring::createRef("OMPTargetTeamsDistributeSimdDirective");
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005027 case CXCursor_OverloadCandidate:
5028 return cxstring::createRef("OverloadCandidate");
Sergey Kalinichev8f3b1872015-11-15 13:48:32 +00005029 case CXCursor_TypeAliasTemplateDecl:
5030 return cxstring::createRef("TypeAliasTemplateDecl");
Olivier Goffart81978012016-06-09 16:15:55 +00005031 case CXCursor_StaticAssert:
5032 return cxstring::createRef("StaticAssert");
Olivier Goffartd211c642016-11-04 06:29:27 +00005033 case CXCursor_FriendDecl:
5034 return cxstring::createRef("FriendDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005035 }
5036
5037 llvm_unreachable("Unhandled CXCursorKind");
5038}
5039
5040struct GetCursorData {
5041 SourceLocation TokenBeginLoc;
5042 bool PointsAtMacroArgExpansion;
5043 bool VisitedObjCPropertyImplDecl;
5044 SourceLocation VisitedDeclaratorDeclStartLoc;
5045 CXCursor &BestCursor;
5046
5047 GetCursorData(SourceManager &SM,
5048 SourceLocation tokenBegin, CXCursor &outputCursor)
5049 : TokenBeginLoc(tokenBegin), BestCursor(outputCursor) {
5050 PointsAtMacroArgExpansion = SM.isMacroArgExpansion(tokenBegin);
5051 VisitedObjCPropertyImplDecl = false;
5052 }
5053};
5054
5055static enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
5056 CXCursor parent,
5057 CXClientData client_data) {
5058 GetCursorData *Data = static_cast<GetCursorData *>(client_data);
5059 CXCursor *BestCursor = &Data->BestCursor;
5060
5061 // If we point inside a macro argument we should provide info of what the
5062 // token is so use the actual cursor, don't replace it with a macro expansion
5063 // cursor.
5064 if (cursor.kind == CXCursor_MacroExpansion && Data->PointsAtMacroArgExpansion)
5065 return CXChildVisit_Recurse;
5066
5067 if (clang_isDeclaration(cursor.kind)) {
5068 // Avoid having the implicit methods override the property decls.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005069 if (const ObjCMethodDecl *MD
Guy Benyei11169dd2012-12-18 14:30:41 +00005070 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
5071 if (MD->isImplicit())
5072 return CXChildVisit_Break;
5073
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005074 } else if (const ObjCInterfaceDecl *ID
Guy Benyei11169dd2012-12-18 14:30:41 +00005075 = dyn_cast_or_null<ObjCInterfaceDecl>(getCursorDecl(cursor))) {
5076 // Check that when we have multiple @class references in the same line,
5077 // that later ones do not override the previous ones.
5078 // If we have:
5079 // @class Foo, Bar;
5080 // source ranges for both start at '@', so 'Bar' will end up overriding
5081 // 'Foo' even though the cursor location was at 'Foo'.
5082 if (BestCursor->kind == CXCursor_ObjCInterfaceDecl ||
5083 BestCursor->kind == CXCursor_ObjCClassRef)
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005084 if (const ObjCInterfaceDecl *PrevID
Guy Benyei11169dd2012-12-18 14:30:41 +00005085 = dyn_cast_or_null<ObjCInterfaceDecl>(getCursorDecl(*BestCursor))){
5086 if (PrevID != ID &&
5087 !PrevID->isThisDeclarationADefinition() &&
5088 !ID->isThisDeclarationADefinition())
5089 return CXChildVisit_Break;
5090 }
5091
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005092 } else if (const DeclaratorDecl *DD
Guy Benyei11169dd2012-12-18 14:30:41 +00005093 = dyn_cast_or_null<DeclaratorDecl>(getCursorDecl(cursor))) {
5094 SourceLocation StartLoc = DD->getSourceRange().getBegin();
5095 // Check that when we have multiple declarators in the same line,
5096 // that later ones do not override the previous ones.
5097 // If we have:
5098 // int Foo, Bar;
5099 // source ranges for both start at 'int', so 'Bar' will end up overriding
5100 // 'Foo' even though the cursor location was at 'Foo'.
5101 if (Data->VisitedDeclaratorDeclStartLoc == StartLoc)
5102 return CXChildVisit_Break;
5103 Data->VisitedDeclaratorDeclStartLoc = StartLoc;
5104
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005105 } else if (const ObjCPropertyImplDecl *PropImp
Guy Benyei11169dd2012-12-18 14:30:41 +00005106 = dyn_cast_or_null<ObjCPropertyImplDecl>(getCursorDecl(cursor))) {
5107 (void)PropImp;
5108 // Check that when we have multiple @synthesize in the same line,
5109 // that later ones do not override the previous ones.
5110 // If we have:
5111 // @synthesize Foo, Bar;
5112 // source ranges for both start at '@', so 'Bar' will end up overriding
5113 // 'Foo' even though the cursor location was at 'Foo'.
5114 if (Data->VisitedObjCPropertyImplDecl)
5115 return CXChildVisit_Break;
5116 Data->VisitedObjCPropertyImplDecl = true;
5117 }
5118 }
5119
5120 if (clang_isExpression(cursor.kind) &&
5121 clang_isDeclaration(BestCursor->kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005122 if (const Decl *D = getCursorDecl(*BestCursor)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005123 // Avoid having the cursor of an expression replace the declaration cursor
5124 // when the expression source range overlaps the declaration range.
5125 // This can happen for C++ constructor expressions whose range generally
5126 // include the variable declaration, e.g.:
5127 // MyCXXClass foo; // Make sure pointing at 'foo' returns a VarDecl cursor.
5128 if (D->getLocation().isValid() && Data->TokenBeginLoc.isValid() &&
5129 D->getLocation() == Data->TokenBeginLoc)
5130 return CXChildVisit_Break;
5131 }
5132 }
5133
5134 // If our current best cursor is the construction of a temporary object,
5135 // don't replace that cursor with a type reference, because we want
5136 // clang_getCursor() to point at the constructor.
5137 if (clang_isExpression(BestCursor->kind) &&
5138 isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
5139 cursor.kind == CXCursor_TypeRef) {
5140 // Keep the cursor pointing at CXXTemporaryObjectExpr but also mark it
5141 // as having the actual point on the type reference.
5142 *BestCursor = getTypeRefedCallExprCursor(*BestCursor);
5143 return CXChildVisit_Recurse;
5144 }
Douglas Gregore9d95f12015-07-07 03:57:35 +00005145
5146 // If we already have an Objective-C superclass reference, don't
5147 // update it further.
5148 if (BestCursor->kind == CXCursor_ObjCSuperClassRef)
5149 return CXChildVisit_Break;
5150
Guy Benyei11169dd2012-12-18 14:30:41 +00005151 *BestCursor = cursor;
5152 return CXChildVisit_Recurse;
5153}
5154
5155CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00005156 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00005157 LOG_BAD_TU(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00005158 return clang_getNullCursor();
Dmitri Gribenko256454f2014-02-11 14:34:14 +00005159 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005160
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00005161 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00005162 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
5163
5164 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
5165 CXCursor Result = cxcursor::getCursor(TU, SLoc);
5166
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005167 LOG_FUNC_SECTION {
Guy Benyei11169dd2012-12-18 14:30:41 +00005168 CXFile SearchFile;
5169 unsigned SearchLine, SearchColumn;
5170 CXFile ResultFile;
5171 unsigned ResultLine, ResultColumn;
5172 CXString SearchFileName, ResultFileName, KindSpelling, USR;
5173 const char *IsDef = clang_isCursorDefinition(Result)? " (Definition)" : "";
5174 CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
Craig Topper69186e72014-06-08 08:38:04 +00005175
5176 clang_getFileLocation(Loc, &SearchFile, &SearchLine, &SearchColumn,
5177 nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005178 clang_getFileLocation(ResultLoc, &ResultFile, &ResultLine,
Craig Topper69186e72014-06-08 08:38:04 +00005179 &ResultColumn, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005180 SearchFileName = clang_getFileName(SearchFile);
5181 ResultFileName = clang_getFileName(ResultFile);
5182 KindSpelling = clang_getCursorKindSpelling(Result.kind);
5183 USR = clang_getCursorUSR(Result);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005184 *Log << llvm::format("(%s:%d:%d) = %s",
5185 clang_getCString(SearchFileName), SearchLine, SearchColumn,
5186 clang_getCString(KindSpelling))
5187 << llvm::format("(%s:%d:%d):%s%s",
5188 clang_getCString(ResultFileName), ResultLine, ResultColumn,
5189 clang_getCString(USR), IsDef);
Guy Benyei11169dd2012-12-18 14:30:41 +00005190 clang_disposeString(SearchFileName);
5191 clang_disposeString(ResultFileName);
5192 clang_disposeString(KindSpelling);
5193 clang_disposeString(USR);
5194
5195 CXCursor Definition = clang_getCursorDefinition(Result);
5196 if (!clang_equalCursors(Definition, clang_getNullCursor())) {
5197 CXSourceLocation DefinitionLoc = clang_getCursorLocation(Definition);
5198 CXString DefinitionKindSpelling
5199 = clang_getCursorKindSpelling(Definition.kind);
5200 CXFile DefinitionFile;
5201 unsigned DefinitionLine, DefinitionColumn;
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005202 clang_getFileLocation(DefinitionLoc, &DefinitionFile,
Craig Topper69186e72014-06-08 08:38:04 +00005203 &DefinitionLine, &DefinitionColumn, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005204 CXString DefinitionFileName = clang_getFileName(DefinitionFile);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005205 *Log << llvm::format(" -> %s(%s:%d:%d)",
5206 clang_getCString(DefinitionKindSpelling),
5207 clang_getCString(DefinitionFileName),
5208 DefinitionLine, DefinitionColumn);
Guy Benyei11169dd2012-12-18 14:30:41 +00005209 clang_disposeString(DefinitionFileName);
5210 clang_disposeString(DefinitionKindSpelling);
5211 }
5212 }
5213
5214 return Result;
5215}
5216
5217CXCursor clang_getNullCursor(void) {
5218 return MakeCXCursorInvalid(CXCursor_InvalidFile);
5219}
5220
5221unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Argyrios Kyrtzidisbf1be592013-01-08 18:23:28 +00005222 // Clear out the "FirstInDeclGroup" part in a declaration cursor, since we
5223 // can't set consistently. For example, when visiting a DeclStmt we will set
5224 // it but we don't set it on the result of clang_getCursorDefinition for
5225 // a reference of the same declaration.
5226 // FIXME: Setting "FirstInDeclGroup" in CXCursors is a hack that only works
5227 // when visiting a DeclStmt currently, the AST should be enhanced to be able
5228 // to provide that kind of info.
5229 if (clang_isDeclaration(X.kind))
Craig Topper69186e72014-06-08 08:38:04 +00005230 X.data[1] = nullptr;
Argyrios Kyrtzidisbf1be592013-01-08 18:23:28 +00005231 if (clang_isDeclaration(Y.kind))
Craig Topper69186e72014-06-08 08:38:04 +00005232 Y.data[1] = nullptr;
Argyrios Kyrtzidisbf1be592013-01-08 18:23:28 +00005233
Guy Benyei11169dd2012-12-18 14:30:41 +00005234 return X == Y;
5235}
5236
5237unsigned clang_hashCursor(CXCursor C) {
5238 unsigned Index = 0;
5239 if (clang_isExpression(C.kind) || clang_isStatement(C.kind))
5240 Index = 1;
5241
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005242 return llvm::DenseMapInfo<std::pair<unsigned, const void*> >::getHashValue(
Guy Benyei11169dd2012-12-18 14:30:41 +00005243 std::make_pair(C.kind, C.data[Index]));
5244}
5245
5246unsigned clang_isInvalid(enum CXCursorKind K) {
5247 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
5248}
5249
5250unsigned clang_isDeclaration(enum CXCursorKind K) {
5251 return (K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl) ||
5252 (K >= CXCursor_FirstExtraDecl && K <= CXCursor_LastExtraDecl);
5253}
5254
5255unsigned clang_isReference(enum CXCursorKind K) {
5256 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
5257}
5258
5259unsigned clang_isExpression(enum CXCursorKind K) {
5260 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
5261}
5262
5263unsigned clang_isStatement(enum CXCursorKind K) {
5264 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
5265}
5266
5267unsigned clang_isAttribute(enum CXCursorKind K) {
5268 return K >= CXCursor_FirstAttr && K <= CXCursor_LastAttr;
5269}
5270
5271unsigned clang_isTranslationUnit(enum CXCursorKind K) {
5272 return K == CXCursor_TranslationUnit;
5273}
5274
5275unsigned clang_isPreprocessing(enum CXCursorKind K) {
5276 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
5277}
5278
5279unsigned clang_isUnexposed(enum CXCursorKind K) {
5280 switch (K) {
5281 case CXCursor_UnexposedDecl:
5282 case CXCursor_UnexposedExpr:
5283 case CXCursor_UnexposedStmt:
5284 case CXCursor_UnexposedAttr:
5285 return true;
5286 default:
5287 return false;
5288 }
5289}
5290
5291CXCursorKind clang_getCursorKind(CXCursor C) {
5292 return C.kind;
5293}
5294
5295CXSourceLocation clang_getCursorLocation(CXCursor C) {
5296 if (clang_isReference(C.kind)) {
5297 switch (C.kind) {
5298 case CXCursor_ObjCSuperClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005299 std::pair<const ObjCInterfaceDecl *, SourceLocation> P
Guy Benyei11169dd2012-12-18 14:30:41 +00005300 = getCursorObjCSuperClassRef(C);
5301 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5302 }
5303
5304 case CXCursor_ObjCProtocolRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005305 std::pair<const ObjCProtocolDecl *, SourceLocation> P
Guy Benyei11169dd2012-12-18 14:30:41 +00005306 = getCursorObjCProtocolRef(C);
5307 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5308 }
5309
5310 case CXCursor_ObjCClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005311 std::pair<const ObjCInterfaceDecl *, SourceLocation> P
Guy Benyei11169dd2012-12-18 14:30:41 +00005312 = getCursorObjCClassRef(C);
5313 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5314 }
5315
5316 case CXCursor_TypeRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005317 std::pair<const TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005318 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5319 }
5320
5321 case CXCursor_TemplateRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005322 std::pair<const TemplateDecl *, SourceLocation> P =
5323 getCursorTemplateRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005324 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5325 }
5326
5327 case CXCursor_NamespaceRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005328 std::pair<const NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005329 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5330 }
5331
5332 case CXCursor_MemberRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005333 std::pair<const FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005334 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5335 }
5336
5337 case CXCursor_VariableRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005338 std::pair<const VarDecl *, SourceLocation> P = getCursorVariableRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005339 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5340 }
5341
5342 case CXCursor_CXXBaseSpecifier: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005343 const CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005344 if (!BaseSpec)
5345 return clang_getNullLocation();
5346
5347 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
5348 return cxloc::translateSourceLocation(getCursorContext(C),
5349 TSInfo->getTypeLoc().getBeginLoc());
5350
5351 return cxloc::translateSourceLocation(getCursorContext(C),
5352 BaseSpec->getLocStart());
5353 }
5354
5355 case CXCursor_LabelRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005356 std::pair<const LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005357 return cxloc::translateSourceLocation(getCursorContext(C), P.second);
5358 }
5359
5360 case CXCursor_OverloadedDeclRef:
5361 return cxloc::translateSourceLocation(getCursorContext(C),
5362 getCursorOverloadedDeclRef(C).second);
5363
5364 default:
5365 // FIXME: Need a way to enumerate all non-reference cases.
5366 llvm_unreachable("Missed a reference kind");
5367 }
5368 }
5369
5370 if (clang_isExpression(C.kind))
5371 return cxloc::translateSourceLocation(getCursorContext(C),
5372 getLocationFromExpr(getCursorExpr(C)));
5373
5374 if (clang_isStatement(C.kind))
5375 return cxloc::translateSourceLocation(getCursorContext(C),
5376 getCursorStmt(C)->getLocStart());
5377
5378 if (C.kind == CXCursor_PreprocessingDirective) {
5379 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
5380 return cxloc::translateSourceLocation(getCursorContext(C), L);
5381 }
5382
5383 if (C.kind == CXCursor_MacroExpansion) {
5384 SourceLocation L
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00005385 = cxcursor::getCursorMacroExpansion(C).getSourceRange().getBegin();
Guy Benyei11169dd2012-12-18 14:30:41 +00005386 return cxloc::translateSourceLocation(getCursorContext(C), L);
5387 }
5388
5389 if (C.kind == CXCursor_MacroDefinition) {
5390 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
5391 return cxloc::translateSourceLocation(getCursorContext(C), L);
5392 }
5393
5394 if (C.kind == CXCursor_InclusionDirective) {
5395 SourceLocation L
5396 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
5397 return cxloc::translateSourceLocation(getCursorContext(C), L);
5398 }
5399
Argyrios Kyrtzidis16834f12013-09-25 00:14:38 +00005400 if (clang_isAttribute(C.kind)) {
5401 SourceLocation L
5402 = cxcursor::getCursorAttr(C)->getLocation();
5403 return cxloc::translateSourceLocation(getCursorContext(C), L);
5404 }
5405
Guy Benyei11169dd2012-12-18 14:30:41 +00005406 if (!clang_isDeclaration(C.kind))
5407 return clang_getNullLocation();
5408
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005409 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005410 if (!D)
5411 return clang_getNullLocation();
5412
5413 SourceLocation Loc = D->getLocation();
5414 // FIXME: Multiple variables declared in a single declaration
5415 // currently lack the information needed to correctly determine their
5416 // ranges when accounting for the type-specifier. We use context
5417 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
5418 // and if so, whether it is the first decl.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005419 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005420 if (!cxcursor::isFirstInDeclGroup(C))
5421 Loc = VD->getLocation();
5422 }
5423
5424 // For ObjC methods, give the start location of the method name.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005425 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00005426 Loc = MD->getSelectorStartLoc();
5427
5428 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
5429}
5430
NAKAMURA Takumia01f4c32016-12-19 16:50:43 +00005431} // end extern "C"
5432
Guy Benyei11169dd2012-12-18 14:30:41 +00005433CXCursor cxcursor::getCursor(CXTranslationUnit TU, SourceLocation SLoc) {
5434 assert(TU);
5435
5436 // Guard against an invalid SourceLocation, or we may assert in one
5437 // of the following calls.
5438 if (SLoc.isInvalid())
5439 return clang_getNullCursor();
5440
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00005441 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00005442
5443 // Translate the given source location to make it point at the beginning of
5444 // the token under the cursor.
5445 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
5446 CXXUnit->getASTContext().getLangOpts());
5447
5448 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
5449 if (SLoc.isValid()) {
5450 GetCursorData ResultData(CXXUnit->getSourceManager(), SLoc, Result);
5451 CursorVisitor CursorVis(TU, GetCursorVisitor, &ResultData,
5452 /*VisitPreprocessorLast=*/true,
5453 /*VisitIncludedEntities=*/false,
5454 SourceLocation(SLoc));
5455 CursorVis.visitFileRegion();
5456 }
5457
5458 return Result;
5459}
5460
5461static SourceRange getRawCursorExtent(CXCursor C) {
5462 if (clang_isReference(C.kind)) {
5463 switch (C.kind) {
5464 case CXCursor_ObjCSuperClassRef:
5465 return getCursorObjCSuperClassRef(C).second;
5466
5467 case CXCursor_ObjCProtocolRef:
5468 return getCursorObjCProtocolRef(C).second;
5469
5470 case CXCursor_ObjCClassRef:
5471 return getCursorObjCClassRef(C).second;
5472
5473 case CXCursor_TypeRef:
5474 return getCursorTypeRef(C).second;
5475
5476 case CXCursor_TemplateRef:
5477 return getCursorTemplateRef(C).second;
5478
5479 case CXCursor_NamespaceRef:
5480 return getCursorNamespaceRef(C).second;
5481
5482 case CXCursor_MemberRef:
5483 return getCursorMemberRef(C).second;
5484
5485 case CXCursor_CXXBaseSpecifier:
5486 return getCursorCXXBaseSpecifier(C)->getSourceRange();
5487
5488 case CXCursor_LabelRef:
5489 return getCursorLabelRef(C).second;
5490
5491 case CXCursor_OverloadedDeclRef:
5492 return getCursorOverloadedDeclRef(C).second;
5493
5494 case CXCursor_VariableRef:
5495 return getCursorVariableRef(C).second;
5496
5497 default:
5498 // FIXME: Need a way to enumerate all non-reference cases.
5499 llvm_unreachable("Missed a reference kind");
5500 }
5501 }
5502
5503 if (clang_isExpression(C.kind))
5504 return getCursorExpr(C)->getSourceRange();
5505
5506 if (clang_isStatement(C.kind))
5507 return getCursorStmt(C)->getSourceRange();
5508
5509 if (clang_isAttribute(C.kind))
5510 return getCursorAttr(C)->getRange();
5511
5512 if (C.kind == CXCursor_PreprocessingDirective)
5513 return cxcursor::getCursorPreprocessingDirective(C);
5514
5515 if (C.kind == CXCursor_MacroExpansion) {
5516 ASTUnit *TU = getCursorASTUnit(C);
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00005517 SourceRange Range = cxcursor::getCursorMacroExpansion(C).getSourceRange();
Guy Benyei11169dd2012-12-18 14:30:41 +00005518 return TU->mapRangeFromPreamble(Range);
5519 }
5520
5521 if (C.kind == CXCursor_MacroDefinition) {
5522 ASTUnit *TU = getCursorASTUnit(C);
5523 SourceRange Range = cxcursor::getCursorMacroDefinition(C)->getSourceRange();
5524 return TU->mapRangeFromPreamble(Range);
5525 }
5526
5527 if (C.kind == CXCursor_InclusionDirective) {
5528 ASTUnit *TU = getCursorASTUnit(C);
5529 SourceRange Range = cxcursor::getCursorInclusionDirective(C)->getSourceRange();
5530 return TU->mapRangeFromPreamble(Range);
5531 }
5532
5533 if (C.kind == CXCursor_TranslationUnit) {
5534 ASTUnit *TU = getCursorASTUnit(C);
5535 FileID MainID = TU->getSourceManager().getMainFileID();
5536 SourceLocation Start = TU->getSourceManager().getLocForStartOfFile(MainID);
5537 SourceLocation End = TU->getSourceManager().getLocForEndOfFile(MainID);
5538 return SourceRange(Start, End);
5539 }
5540
5541 if (clang_isDeclaration(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005542 const Decl *D = cxcursor::getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005543 if (!D)
5544 return SourceRange();
5545
5546 SourceRange R = D->getSourceRange();
5547 // FIXME: Multiple variables declared in a single declaration
5548 // currently lack the information needed to correctly determine their
5549 // ranges when accounting for the type-specifier. We use context
5550 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
5551 // and if so, whether it is the first decl.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005552 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005553 if (!cxcursor::isFirstInDeclGroup(C))
5554 R.setBegin(VD->getLocation());
5555 }
5556 return R;
5557 }
5558 return SourceRange();
5559}
5560
5561/// \brief Retrieves the "raw" cursor extent, which is then extended to include
5562/// the decl-specifier-seq for declarations.
5563static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr) {
5564 if (clang_isDeclaration(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005565 const Decl *D = cxcursor::getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005566 if (!D)
5567 return SourceRange();
5568
5569 SourceRange R = D->getSourceRange();
5570
5571 // Adjust the start of the location for declarations preceded by
5572 // declaration specifiers.
5573 SourceLocation StartLoc;
5574 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
5575 if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
5576 StartLoc = TI->getTypeLoc().getLocStart();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005577 } else if (const TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005578 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
5579 StartLoc = TI->getTypeLoc().getLocStart();
5580 }
5581
5582 if (StartLoc.isValid() && R.getBegin().isValid() &&
5583 SrcMgr.isBeforeInTranslationUnit(StartLoc, R.getBegin()))
5584 R.setBegin(StartLoc);
5585
5586 // FIXME: Multiple variables declared in a single declaration
5587 // currently lack the information needed to correctly determine their
5588 // ranges when accounting for the type-specifier. We use context
5589 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
5590 // and if so, whether it is the first decl.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005591 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005592 if (!cxcursor::isFirstInDeclGroup(C))
5593 R.setBegin(VD->getLocation());
5594 }
5595
5596 return R;
5597 }
5598
5599 return getRawCursorExtent(C);
5600}
5601
Guy Benyei11169dd2012-12-18 14:30:41 +00005602CXSourceRange clang_getCursorExtent(CXCursor C) {
5603 SourceRange R = getRawCursorExtent(C);
5604 if (R.isInvalid())
5605 return clang_getNullRange();
5606
5607 return cxloc::translateSourceRange(getCursorContext(C), R);
5608}
5609
5610CXCursor clang_getCursorReferenced(CXCursor C) {
5611 if (clang_isInvalid(C.kind))
5612 return clang_getNullCursor();
5613
5614 CXTranslationUnit tu = getCursorTU(C);
5615 if (clang_isDeclaration(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005616 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005617 if (!D)
5618 return clang_getNullCursor();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005619 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00005620 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), tu);
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005621 if (const ObjCPropertyImplDecl *PropImpl =
5622 dyn_cast<ObjCPropertyImplDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00005623 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
5624 return MakeCXCursor(Property, tu);
5625
5626 return C;
5627 }
5628
5629 if (clang_isExpression(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005630 const Expr *E = getCursorExpr(C);
5631 const Decl *D = getDeclFromExpr(E);
Guy Benyei11169dd2012-12-18 14:30:41 +00005632 if (D) {
5633 CXCursor declCursor = MakeCXCursor(D, tu);
5634 declCursor = getSelectorIdentifierCursor(getSelectorIdentifierIndex(C),
5635 declCursor);
5636 return declCursor;
5637 }
5638
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005639 if (const OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00005640 return MakeCursorOverloadedDeclRef(Ovl, tu);
5641
5642 return clang_getNullCursor();
5643 }
5644
5645 if (clang_isStatement(C.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00005646 const Stmt *S = getCursorStmt(C);
5647 if (const GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
Guy Benyei11169dd2012-12-18 14:30:41 +00005648 if (LabelDecl *label = Goto->getLabel())
5649 if (LabelStmt *labelS = label->getStmt())
5650 return MakeCXCursor(labelS, getCursorDecl(C), tu);
5651
5652 return clang_getNullCursor();
5653 }
Richard Smith66a81862015-05-04 02:25:31 +00005654
Guy Benyei11169dd2012-12-18 14:30:41 +00005655 if (C.kind == CXCursor_MacroExpansion) {
Richard Smith66a81862015-05-04 02:25:31 +00005656 if (const MacroDefinitionRecord *Def =
5657 getCursorMacroExpansion(C).getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00005658 return MakeMacroDefinitionCursor(Def, tu);
5659 }
5660
5661 if (!clang_isReference(C.kind))
5662 return clang_getNullCursor();
5663
5664 switch (C.kind) {
5665 case CXCursor_ObjCSuperClassRef:
5666 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, tu);
5667
5668 case CXCursor_ObjCProtocolRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005669 const ObjCProtocolDecl *Prot = getCursorObjCProtocolRef(C).first;
5670 if (const ObjCProtocolDecl *Def = Prot->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00005671 return MakeCXCursor(Def, tu);
5672
5673 return MakeCXCursor(Prot, tu);
5674 }
5675
5676 case CXCursor_ObjCClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005677 const ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
5678 if (const ObjCInterfaceDecl *Def = Class->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00005679 return MakeCXCursor(Def, tu);
5680
5681 return MakeCXCursor(Class, tu);
5682 }
5683
5684 case CXCursor_TypeRef:
5685 return MakeCXCursor(getCursorTypeRef(C).first, tu );
5686
5687 case CXCursor_TemplateRef:
5688 return MakeCXCursor(getCursorTemplateRef(C).first, tu );
5689
5690 case CXCursor_NamespaceRef:
5691 return MakeCXCursor(getCursorNamespaceRef(C).first, tu );
5692
5693 case CXCursor_MemberRef:
5694 return MakeCXCursor(getCursorMemberRef(C).first, tu );
5695
5696 case CXCursor_CXXBaseSpecifier: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005697 const CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005698 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
5699 tu ));
5700 }
5701
5702 case CXCursor_LabelRef:
5703 // FIXME: We end up faking the "parent" declaration here because we
5704 // don't want to make CXCursor larger.
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00005705 return MakeCXCursor(getCursorLabelRef(C).first,
5706 cxtu::getASTUnit(tu)->getASTContext()
5707 .getTranslationUnitDecl(),
Guy Benyei11169dd2012-12-18 14:30:41 +00005708 tu);
5709
5710 case CXCursor_OverloadedDeclRef:
5711 return C;
5712
5713 case CXCursor_VariableRef:
5714 return MakeCXCursor(getCursorVariableRef(C).first, tu);
5715
5716 default:
5717 // We would prefer to enumerate all non-reference cursor kinds here.
5718 llvm_unreachable("Unhandled reference cursor kind");
5719 }
5720}
5721
5722CXCursor clang_getCursorDefinition(CXCursor C) {
5723 if (clang_isInvalid(C.kind))
5724 return clang_getNullCursor();
5725
5726 CXTranslationUnit TU = getCursorTU(C);
5727
5728 bool WasReference = false;
5729 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
5730 C = clang_getCursorReferenced(C);
5731 WasReference = true;
5732 }
5733
5734 if (C.kind == CXCursor_MacroExpansion)
5735 return clang_getCursorReferenced(C);
5736
5737 if (!clang_isDeclaration(C.kind))
5738 return clang_getNullCursor();
5739
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005740 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005741 if (!D)
5742 return clang_getNullCursor();
5743
5744 switch (D->getKind()) {
5745 // Declaration kinds that don't really separate the notions of
5746 // declaration and definition.
5747 case Decl::Namespace:
5748 case Decl::Typedef:
5749 case Decl::TypeAlias:
5750 case Decl::TypeAliasTemplate:
5751 case Decl::TemplateTypeParm:
5752 case Decl::EnumConstant:
5753 case Decl::Field:
Richard Smithbdb84f32016-07-22 23:36:59 +00005754 case Decl::Binding:
John McCall5e77d762013-04-16 07:28:30 +00005755 case Decl::MSProperty:
Guy Benyei11169dd2012-12-18 14:30:41 +00005756 case Decl::IndirectField:
5757 case Decl::ObjCIvar:
5758 case Decl::ObjCAtDefsField:
5759 case Decl::ImplicitParam:
5760 case Decl::ParmVar:
5761 case Decl::NonTypeTemplateParm:
5762 case Decl::TemplateTemplateParm:
5763 case Decl::ObjCCategoryImpl:
5764 case Decl::ObjCImplementation:
5765 case Decl::AccessSpec:
5766 case Decl::LinkageSpec:
Richard Smith8df390f2016-09-08 23:14:54 +00005767 case Decl::Export:
Guy Benyei11169dd2012-12-18 14:30:41 +00005768 case Decl::ObjCPropertyImpl:
5769 case Decl::FileScopeAsm:
5770 case Decl::StaticAssert:
5771 case Decl::Block:
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00005772 case Decl::Captured:
Alexey Bataev4244be22016-02-11 05:35:55 +00005773 case Decl::OMPCapturedExpr:
Guy Benyei11169dd2012-12-18 14:30:41 +00005774 case Decl::Label: // FIXME: Is this right??
5775 case Decl::ClassScopeFunctionSpecialization:
5776 case Decl::Import:
Alexey Bataeva769e072013-03-22 06:34:35 +00005777 case Decl::OMPThreadPrivate:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00005778 case Decl::OMPDeclareReduction:
Douglas Gregor85f3f952015-07-07 03:57:15 +00005779 case Decl::ObjCTypeParam:
David Majnemerd9b1a4f2015-11-04 03:40:30 +00005780 case Decl::BuiltinTemplate:
Nico Weber66220292016-03-02 17:28:48 +00005781 case Decl::PragmaComment:
Nico Webercbbaeb12016-03-02 19:28:54 +00005782 case Decl::PragmaDetectMismatch:
Richard Smith151c4562016-12-20 21:35:28 +00005783 case Decl::UsingPack:
Guy Benyei11169dd2012-12-18 14:30:41 +00005784 return C;
5785
5786 // Declaration kinds that don't make any sense here, but are
5787 // nonetheless harmless.
David Blaikief005d3c2013-02-22 17:44:58 +00005788 case Decl::Empty:
Guy Benyei11169dd2012-12-18 14:30:41 +00005789 case Decl::TranslationUnit:
Richard Smithf19e1272015-03-07 00:04:49 +00005790 case Decl::ExternCContext:
Guy Benyei11169dd2012-12-18 14:30:41 +00005791 break;
5792
5793 // Declaration kinds for which the definition is not resolvable.
5794 case Decl::UnresolvedUsingTypename:
5795 case Decl::UnresolvedUsingValue:
5796 break;
5797
5798 case Decl::UsingDirective:
5799 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
5800 TU);
5801
5802 case Decl::NamespaceAlias:
5803 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), TU);
5804
5805 case Decl::Enum:
5806 case Decl::Record:
5807 case Decl::CXXRecord:
5808 case Decl::ClassTemplateSpecialization:
5809 case Decl::ClassTemplatePartialSpecialization:
5810 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
5811 return MakeCXCursor(Def, TU);
5812 return clang_getNullCursor();
5813
5814 case Decl::Function:
5815 case Decl::CXXMethod:
5816 case Decl::CXXConstructor:
5817 case Decl::CXXDestructor:
5818 case Decl::CXXConversion: {
Craig Topper69186e72014-06-08 08:38:04 +00005819 const FunctionDecl *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005820 if (cast<FunctionDecl>(D)->getBody(Def))
Dmitri Gribenko9c256e32013-01-14 00:46:27 +00005821 return MakeCXCursor(Def, TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00005822 return clang_getNullCursor();
5823 }
5824
Larisse Voufo39a1e502013-08-06 01:03:05 +00005825 case Decl::Var:
5826 case Decl::VarTemplateSpecialization:
Richard Smithbdb84f32016-07-22 23:36:59 +00005827 case Decl::VarTemplatePartialSpecialization:
5828 case Decl::Decomposition: {
Guy Benyei11169dd2012-12-18 14:30:41 +00005829 // Ask the variable if it has a definition.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005830 if (const VarDecl *Def = cast<VarDecl>(D)->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00005831 return MakeCXCursor(Def, TU);
5832 return clang_getNullCursor();
5833 }
5834
5835 case Decl::FunctionTemplate: {
Craig Topper69186e72014-06-08 08:38:04 +00005836 const FunctionDecl *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005837 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
5838 return MakeCXCursor(Def->getDescribedFunctionTemplate(), TU);
5839 return clang_getNullCursor();
5840 }
5841
5842 case Decl::ClassTemplate: {
5843 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
5844 ->getDefinition())
5845 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
5846 TU);
5847 return clang_getNullCursor();
5848 }
5849
Larisse Voufo39a1e502013-08-06 01:03:05 +00005850 case Decl::VarTemplate: {
5851 if (VarDecl *Def =
5852 cast<VarTemplateDecl>(D)->getTemplatedDecl()->getDefinition())
5853 return MakeCXCursor(cast<VarDecl>(Def)->getDescribedVarTemplate(), TU);
5854 return clang_getNullCursor();
5855 }
5856
Guy Benyei11169dd2012-12-18 14:30:41 +00005857 case Decl::Using:
5858 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
5859 D->getLocation(), TU);
5860
5861 case Decl::UsingShadow:
Richard Smith5179eb72016-06-28 19:03:57 +00005862 case Decl::ConstructorUsingShadow:
Guy Benyei11169dd2012-12-18 14:30:41 +00005863 return clang_getCursorDefinition(
5864 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
5865 TU));
5866
5867 case Decl::ObjCMethod: {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005868 const ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00005869 if (Method->isThisDeclarationADefinition())
5870 return C;
5871
5872 // Dig out the method definition in the associated
5873 // @implementation, if we have it.
5874 // FIXME: The ASTs should make finding the definition easier.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005875 if (const ObjCInterfaceDecl *Class
Guy Benyei11169dd2012-12-18 14:30:41 +00005876 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
5877 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
5878 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
5879 Method->isInstanceMethod()))
5880 if (Def->isThisDeclarationADefinition())
5881 return MakeCXCursor(Def, TU);
5882
5883 return clang_getNullCursor();
5884 }
5885
5886 case Decl::ObjCCategory:
5887 if (ObjCCategoryImplDecl *Impl
5888 = cast<ObjCCategoryDecl>(D)->getImplementation())
5889 return MakeCXCursor(Impl, TU);
5890 return clang_getNullCursor();
5891
5892 case Decl::ObjCProtocol:
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005893 if (const ObjCProtocolDecl *Def = cast<ObjCProtocolDecl>(D)->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00005894 return MakeCXCursor(Def, TU);
5895 return clang_getNullCursor();
5896
5897 case Decl::ObjCInterface: {
5898 // There are two notions of a "definition" for an Objective-C
5899 // class: the interface and its implementation. When we resolved a
5900 // reference to an Objective-C class, produce the @interface as
5901 // the definition; when we were provided with the interface,
5902 // produce the @implementation as the definition.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005903 const ObjCInterfaceDecl *IFace = cast<ObjCInterfaceDecl>(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00005904 if (WasReference) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005905 if (const ObjCInterfaceDecl *Def = IFace->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00005906 return MakeCXCursor(Def, TU);
5907 } else if (ObjCImplementationDecl *Impl = IFace->getImplementation())
5908 return MakeCXCursor(Impl, TU);
5909 return clang_getNullCursor();
5910 }
5911
5912 case Decl::ObjCProperty:
5913 // FIXME: We don't really know where to find the
5914 // ObjCPropertyImplDecls that implement this property.
5915 return clang_getNullCursor();
5916
5917 case Decl::ObjCCompatibleAlias:
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005918 if (const ObjCInterfaceDecl *Class
Guy Benyei11169dd2012-12-18 14:30:41 +00005919 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005920 if (const ObjCInterfaceDecl *Def = Class->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00005921 return MakeCXCursor(Def, TU);
5922
5923 return clang_getNullCursor();
5924
5925 case Decl::Friend:
5926 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
5927 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
5928 return clang_getNullCursor();
5929
5930 case Decl::FriendTemplate:
5931 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
5932 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
5933 return clang_getNullCursor();
5934 }
5935
5936 return clang_getNullCursor();
5937}
5938
5939unsigned clang_isCursorDefinition(CXCursor C) {
5940 if (!clang_isDeclaration(C.kind))
5941 return 0;
5942
5943 return clang_getCursorDefinition(C) == C;
5944}
5945
5946CXCursor clang_getCanonicalCursor(CXCursor C) {
5947 if (!clang_isDeclaration(C.kind))
5948 return C;
5949
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005950 if (const Decl *D = getCursorDecl(C)) {
5951 if (const ObjCCategoryImplDecl *CatImplD = dyn_cast<ObjCCategoryImplDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00005952 if (ObjCCategoryDecl *CatD = CatImplD->getCategoryDecl())
5953 return MakeCXCursor(CatD, getCursorTU(C));
5954
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005955 if (const ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
5956 if (const ObjCInterfaceDecl *IFD = ImplD->getClassInterface())
Guy Benyei11169dd2012-12-18 14:30:41 +00005957 return MakeCXCursor(IFD, getCursorTU(C));
5958
5959 return MakeCXCursor(D->getCanonicalDecl(), getCursorTU(C));
5960 }
5961
5962 return C;
5963}
5964
5965int clang_Cursor_getObjCSelectorIndex(CXCursor cursor) {
5966 return cxcursor::getSelectorIdentifierIndexAndLoc(cursor).first;
5967}
5968
5969unsigned clang_getNumOverloadedDecls(CXCursor C) {
5970 if (C.kind != CXCursor_OverloadedDeclRef)
5971 return 0;
5972
5973 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005974 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
Guy Benyei11169dd2012-12-18 14:30:41 +00005975 return E->getNumDecls();
5976
5977 if (OverloadedTemplateStorage *S
5978 = Storage.dyn_cast<OverloadedTemplateStorage*>())
5979 return S->size();
5980
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005981 const Decl *D = Storage.get<const Decl *>();
5982 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00005983 return Using->shadow_size();
5984
5985 return 0;
5986}
5987
5988CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
5989 if (cursor.kind != CXCursor_OverloadedDeclRef)
5990 return clang_getNullCursor();
5991
5992 if (index >= clang_getNumOverloadedDecls(cursor))
5993 return clang_getNullCursor();
5994
5995 CXTranslationUnit TU = getCursorTU(cursor);
5996 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005997 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
Guy Benyei11169dd2012-12-18 14:30:41 +00005998 return MakeCXCursor(E->decls_begin()[index], TU);
5999
6000 if (OverloadedTemplateStorage *S
6001 = Storage.dyn_cast<OverloadedTemplateStorage*>())
6002 return MakeCXCursor(S->begin()[index], TU);
6003
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006004 const Decl *D = Storage.get<const Decl *>();
6005 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006006 // FIXME: This is, unfortunately, linear time.
6007 UsingDecl::shadow_iterator Pos = Using->shadow_begin();
6008 std::advance(Pos, index);
6009 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), TU);
6010 }
6011
6012 return clang_getNullCursor();
6013}
6014
6015void clang_getDefinitionSpellingAndExtent(CXCursor C,
6016 const char **startBuf,
6017 const char **endBuf,
6018 unsigned *startLine,
6019 unsigned *startColumn,
6020 unsigned *endLine,
6021 unsigned *endColumn) {
6022 assert(getCursorDecl(C) && "CXCursor has null decl");
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006023 const FunctionDecl *FD = dyn_cast<FunctionDecl>(getCursorDecl(C));
Guy Benyei11169dd2012-12-18 14:30:41 +00006024 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
6025
6026 SourceManager &SM = FD->getASTContext().getSourceManager();
6027 *startBuf = SM.getCharacterData(Body->getLBracLoc());
6028 *endBuf = SM.getCharacterData(Body->getRBracLoc());
6029 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
6030 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
6031 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
6032 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
6033}
6034
6035
6036CXSourceRange clang_getCursorReferenceNameRange(CXCursor C, unsigned NameFlags,
6037 unsigned PieceIndex) {
6038 RefNamePieces Pieces;
6039
6040 switch (C.kind) {
6041 case CXCursor_MemberRefExpr:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006042 if (const MemberExpr *E = dyn_cast<MemberExpr>(getCursorExpr(C)))
Guy Benyei11169dd2012-12-18 14:30:41 +00006043 Pieces = buildPieces(NameFlags, true, E->getMemberNameInfo(),
6044 E->getQualifierLoc().getSourceRange());
6045 break;
6046
6047 case CXCursor_DeclRefExpr:
James Y Knight04ec5bf2015-12-24 02:59:37 +00006048 if (const DeclRefExpr *E = dyn_cast<DeclRefExpr>(getCursorExpr(C))) {
6049 SourceRange TemplateArgLoc(E->getLAngleLoc(), E->getRAngleLoc());
6050 Pieces =
6051 buildPieces(NameFlags, false, E->getNameInfo(),
6052 E->getQualifierLoc().getSourceRange(), &TemplateArgLoc);
6053 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006054 break;
6055
6056 case CXCursor_CallExpr:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006057 if (const CXXOperatorCallExpr *OCE =
Guy Benyei11169dd2012-12-18 14:30:41 +00006058 dyn_cast<CXXOperatorCallExpr>(getCursorExpr(C))) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006059 const Expr *Callee = OCE->getCallee();
6060 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Callee))
Guy Benyei11169dd2012-12-18 14:30:41 +00006061 Callee = ICE->getSubExpr();
6062
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006063 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Callee))
Guy Benyei11169dd2012-12-18 14:30:41 +00006064 Pieces = buildPieces(NameFlags, false, DRE->getNameInfo(),
6065 DRE->getQualifierLoc().getSourceRange());
6066 }
6067 break;
6068
6069 default:
6070 break;
6071 }
6072
6073 if (Pieces.empty()) {
6074 if (PieceIndex == 0)
6075 return clang_getCursorExtent(C);
6076 } else if (PieceIndex < Pieces.size()) {
6077 SourceRange R = Pieces[PieceIndex];
6078 if (R.isValid())
6079 return cxloc::translateSourceRange(getCursorContext(C), R);
6080 }
6081
6082 return clang_getNullRange();
6083}
6084
6085void clang_enableStackTraces(void) {
Richard Smithdfed58a2016-06-09 00:53:41 +00006086 // FIXME: Provide an argv0 here so we can find llvm-symbolizer.
6087 llvm::sys::PrintStackTraceOnErrorSignal(StringRef());
Guy Benyei11169dd2012-12-18 14:30:41 +00006088}
6089
6090void clang_executeOnThread(void (*fn)(void*), void *user_data,
6091 unsigned stack_size) {
6092 llvm::llvm_execute_on_thread(fn, user_data, stack_size);
6093}
6094
Guy Benyei11169dd2012-12-18 14:30:41 +00006095//===----------------------------------------------------------------------===//
6096// Token-based Operations.
6097//===----------------------------------------------------------------------===//
6098
6099/* CXToken layout:
6100 * int_data[0]: a CXTokenKind
6101 * int_data[1]: starting token location
6102 * int_data[2]: token length
6103 * int_data[3]: reserved
6104 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
6105 * otherwise unused.
6106 */
Guy Benyei11169dd2012-12-18 14:30:41 +00006107CXTokenKind clang_getTokenKind(CXToken CXTok) {
6108 return static_cast<CXTokenKind>(CXTok.int_data[0]);
6109}
6110
6111CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
6112 switch (clang_getTokenKind(CXTok)) {
6113 case CXToken_Identifier:
6114 case CXToken_Keyword:
6115 // We know we have an IdentifierInfo*, so use that.
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00006116 return cxstring::createRef(static_cast<IdentifierInfo *>(CXTok.ptr_data)
Guy Benyei11169dd2012-12-18 14:30:41 +00006117 ->getNameStart());
6118
6119 case CXToken_Literal: {
6120 // We have stashed the starting pointer in the ptr_data field. Use it.
6121 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00006122 return cxstring::createDup(StringRef(Text, CXTok.int_data[2]));
Guy Benyei11169dd2012-12-18 14:30:41 +00006123 }
6124
6125 case CXToken_Punctuation:
6126 case CXToken_Comment:
6127 break;
6128 }
6129
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006130 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006131 LOG_BAD_TU(TU);
6132 return cxstring::createEmpty();
6133 }
6134
Guy Benyei11169dd2012-12-18 14:30:41 +00006135 // We have to find the starting buffer pointer the hard way, by
6136 // deconstructing the source location.
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006137 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006138 if (!CXXUnit)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00006139 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00006140
6141 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
6142 std::pair<FileID, unsigned> LocInfo
6143 = CXXUnit->getSourceManager().getDecomposedSpellingLoc(Loc);
6144 bool Invalid = false;
6145 StringRef Buffer
6146 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
6147 if (Invalid)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00006148 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00006149
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00006150 return cxstring::createDup(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Guy Benyei11169dd2012-12-18 14:30:41 +00006151}
6152
6153CXSourceLocation clang_getTokenLocation(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_getNullLocation();
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_getNullLocation();
6162
6163 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
6164 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
6165}
6166
6167CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006168 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006169 LOG_BAD_TU(TU);
6170 return clang_getNullRange();
6171 }
6172
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006173 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006174 if (!CXXUnit)
6175 return clang_getNullRange();
6176
6177 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
6178 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
6179}
6180
6181static void getTokens(ASTUnit *CXXUnit, SourceRange Range,
6182 SmallVectorImpl<CXToken> &CXTokens) {
6183 SourceManager &SourceMgr = CXXUnit->getSourceManager();
6184 std::pair<FileID, unsigned> BeginLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00006185 = SourceMgr.getDecomposedSpellingLoc(Range.getBegin());
Guy Benyei11169dd2012-12-18 14:30:41 +00006186 std::pair<FileID, unsigned> EndLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00006187 = SourceMgr.getDecomposedSpellingLoc(Range.getEnd());
Guy Benyei11169dd2012-12-18 14:30:41 +00006188
6189 // Cannot tokenize across files.
6190 if (BeginLocInfo.first != EndLocInfo.first)
6191 return;
6192
6193 // Create a lexer
6194 bool Invalid = false;
6195 StringRef Buffer
6196 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
6197 if (Invalid)
6198 return;
6199
6200 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
6201 CXXUnit->getASTContext().getLangOpts(),
6202 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
6203 Lex.SetCommentRetentionState(true);
6204
6205 // Lex tokens until we hit the end of the range.
6206 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
6207 Token Tok;
6208 bool previousWasAt = false;
6209 do {
6210 // Lex the next token
6211 Lex.LexFromRawLexer(Tok);
6212 if (Tok.is(tok::eof))
6213 break;
6214
6215 // Initialize the CXToken.
6216 CXToken CXTok;
6217
6218 // - Common fields
6219 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
6220 CXTok.int_data[2] = Tok.getLength();
6221 CXTok.int_data[3] = 0;
6222
6223 // - Kind-specific fields
6224 if (Tok.isLiteral()) {
6225 CXTok.int_data[0] = CXToken_Literal;
Dmitri Gribenkof9304482013-01-23 15:56:07 +00006226 CXTok.ptr_data = const_cast<char *>(Tok.getLiteralData());
Guy Benyei11169dd2012-12-18 14:30:41 +00006227 } else if (Tok.is(tok::raw_identifier)) {
6228 // Lookup the identifier to determine whether we have a keyword.
6229 IdentifierInfo *II
6230 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok);
6231
6232 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
6233 CXTok.int_data[0] = CXToken_Keyword;
6234 }
6235 else {
6236 CXTok.int_data[0] = Tok.is(tok::identifier)
6237 ? CXToken_Identifier
6238 : CXToken_Keyword;
6239 }
6240 CXTok.ptr_data = II;
6241 } else if (Tok.is(tok::comment)) {
6242 CXTok.int_data[0] = CXToken_Comment;
Craig Topper69186e72014-06-08 08:38:04 +00006243 CXTok.ptr_data = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006244 } else {
6245 CXTok.int_data[0] = CXToken_Punctuation;
Craig Topper69186e72014-06-08 08:38:04 +00006246 CXTok.ptr_data = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006247 }
6248 CXTokens.push_back(CXTok);
6249 previousWasAt = Tok.is(tok::at);
Argyrios Kyrtzidisc7c6a072016-11-09 23:58:39 +00006250 } while (Lex.getBufferLocation() < EffectiveBufferEnd);
Guy Benyei11169dd2012-12-18 14:30:41 +00006251}
6252
6253void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
6254 CXToken **Tokens, unsigned *NumTokens) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00006255 LOG_FUNC_SECTION {
6256 *Log << TU << ' ' << Range;
6257 }
6258
Guy Benyei11169dd2012-12-18 14:30:41 +00006259 if (Tokens)
Craig Topper69186e72014-06-08 08:38:04 +00006260 *Tokens = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006261 if (NumTokens)
6262 *NumTokens = 0;
6263
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006264 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006265 LOG_BAD_TU(TU);
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00006266 return;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006267 }
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00006268
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006269 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006270 if (!CXXUnit || !Tokens || !NumTokens)
6271 return;
6272
6273 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
6274
6275 SourceRange R = cxloc::translateCXSourceRange(Range);
6276 if (R.isInvalid())
6277 return;
6278
6279 SmallVector<CXToken, 32> CXTokens;
6280 getTokens(CXXUnit, R, CXTokens);
6281
6282 if (CXTokens.empty())
6283 return;
6284
6285 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
6286 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
6287 *NumTokens = CXTokens.size();
6288}
6289
6290void clang_disposeTokens(CXTranslationUnit TU,
6291 CXToken *Tokens, unsigned NumTokens) {
6292 free(Tokens);
6293}
6294
Guy Benyei11169dd2012-12-18 14:30:41 +00006295//===----------------------------------------------------------------------===//
6296// Token annotation APIs.
6297//===----------------------------------------------------------------------===//
6298
Guy Benyei11169dd2012-12-18 14:30:41 +00006299static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
6300 CXCursor parent,
6301 CXClientData client_data);
6302static bool AnnotateTokensPostChildrenVisitor(CXCursor cursor,
6303 CXClientData client_data);
6304
6305namespace {
6306class AnnotateTokensWorker {
Guy Benyei11169dd2012-12-18 14:30:41 +00006307 CXToken *Tokens;
6308 CXCursor *Cursors;
6309 unsigned NumTokens;
6310 unsigned TokIdx;
6311 unsigned PreprocessingTokIdx;
6312 CursorVisitor AnnotateVis;
6313 SourceManager &SrcMgr;
6314 bool HasContextSensitiveKeywords;
6315
6316 struct PostChildrenInfo {
6317 CXCursor Cursor;
6318 SourceRange CursorRange;
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006319 unsigned BeforeReachingCursorIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00006320 unsigned BeforeChildrenTokenIdx;
6321 };
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006322 SmallVector<PostChildrenInfo, 8> PostChildrenInfos;
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006323
6324 CXToken &getTok(unsigned Idx) {
6325 assert(Idx < NumTokens);
6326 return Tokens[Idx];
6327 }
6328 const CXToken &getTok(unsigned Idx) const {
6329 assert(Idx < NumTokens);
6330 return Tokens[Idx];
6331 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006332 bool MoreTokens() const { return TokIdx < NumTokens; }
6333 unsigned NextToken() const { return TokIdx; }
6334 void AdvanceToken() { ++TokIdx; }
6335 SourceLocation GetTokenLoc(unsigned tokI) {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006336 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[1]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006337 }
6338 bool isFunctionMacroToken(unsigned tokI) const {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006339 return getTok(tokI).int_data[3] != 0;
Guy Benyei11169dd2012-12-18 14:30:41 +00006340 }
6341 SourceLocation getFunctionMacroTokenLoc(unsigned tokI) const {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006342 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[3]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006343 }
6344
6345 void annotateAndAdvanceTokens(CXCursor, RangeComparisonResult, SourceRange);
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006346 bool annotateAndAdvanceFunctionMacroTokens(CXCursor, RangeComparisonResult,
Guy Benyei11169dd2012-12-18 14:30:41 +00006347 SourceRange);
6348
6349public:
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006350 AnnotateTokensWorker(CXToken *tokens, CXCursor *cursors, unsigned numTokens,
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006351 CXTranslationUnit TU, SourceRange RegionOfInterest)
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006352 : Tokens(tokens), Cursors(cursors),
Guy Benyei11169dd2012-12-18 14:30:41 +00006353 NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006354 AnnotateVis(TU,
Guy Benyei11169dd2012-12-18 14:30:41 +00006355 AnnotateTokensVisitor, this,
6356 /*VisitPreprocessorLast=*/true,
6357 /*VisitIncludedEntities=*/false,
6358 RegionOfInterest,
6359 /*VisitDeclsOnly=*/false,
6360 AnnotateTokensPostChildrenVisitor),
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006361 SrcMgr(cxtu::getASTUnit(TU)->getSourceManager()),
Guy Benyei11169dd2012-12-18 14:30:41 +00006362 HasContextSensitiveKeywords(false) { }
6363
6364 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
6365 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
6366 bool postVisitChildren(CXCursor cursor);
6367 void AnnotateTokens();
6368
6369 /// \brief Determine whether the annotator saw any cursors that have
6370 /// context-sensitive keywords.
6371 bool hasContextSensitiveKeywords() const {
6372 return HasContextSensitiveKeywords;
6373 }
6374
6375 ~AnnotateTokensWorker() {
6376 assert(PostChildrenInfos.empty());
6377 }
6378};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006379}
Guy Benyei11169dd2012-12-18 14:30:41 +00006380
6381void AnnotateTokensWorker::AnnotateTokens() {
6382 // Walk the AST within the region of interest, annotating tokens
6383 // along the way.
6384 AnnotateVis.visitFileRegion();
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006385}
Guy Benyei11169dd2012-12-18 14:30:41 +00006386
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006387static inline void updateCursorAnnotation(CXCursor &Cursor,
6388 const CXCursor &updateC) {
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006389 if (clang_isInvalid(updateC.kind) || !clang_isInvalid(Cursor.kind))
Guy Benyei11169dd2012-12-18 14:30:41 +00006390 return;
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006391 Cursor = updateC;
Guy Benyei11169dd2012-12-18 14:30:41 +00006392}
6393
6394/// \brief It annotates and advances tokens with a cursor until the comparison
6395//// between the cursor location and the source range is the same as
6396/// \arg compResult.
6397///
6398/// Pass RangeBefore to annotate tokens with a cursor until a range is reached.
6399/// Pass RangeOverlap to annotate tokens inside a range.
6400void AnnotateTokensWorker::annotateAndAdvanceTokens(CXCursor updateC,
6401 RangeComparisonResult compResult,
6402 SourceRange range) {
6403 while (MoreTokens()) {
6404 const unsigned I = NextToken();
6405 if (isFunctionMacroToken(I))
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006406 if (!annotateAndAdvanceFunctionMacroTokens(updateC, compResult, range))
6407 return;
Guy Benyei11169dd2012-12-18 14:30:41 +00006408
6409 SourceLocation TokLoc = GetTokenLoc(I);
6410 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006411 updateCursorAnnotation(Cursors[I], updateC);
Guy Benyei11169dd2012-12-18 14:30:41 +00006412 AdvanceToken();
6413 continue;
6414 }
6415 break;
6416 }
6417}
6418
6419/// \brief Special annotation handling for macro argument tokens.
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006420/// \returns true if it advanced beyond all macro tokens, false otherwise.
6421bool AnnotateTokensWorker::annotateAndAdvanceFunctionMacroTokens(
Guy Benyei11169dd2012-12-18 14:30:41 +00006422 CXCursor updateC,
6423 RangeComparisonResult compResult,
6424 SourceRange range) {
6425 assert(MoreTokens());
6426 assert(isFunctionMacroToken(NextToken()) &&
6427 "Should be called only for macro arg tokens");
6428
6429 // This works differently than annotateAndAdvanceTokens; because expanded
6430 // macro arguments can have arbitrary translation-unit source order, we do not
6431 // advance the token index one by one until a token fails the range test.
6432 // We only advance once past all of the macro arg tokens if all of them
6433 // pass the range test. If one of them fails we keep the token index pointing
6434 // at the start of the macro arg tokens so that the failing token will be
6435 // annotated by a subsequent annotation try.
6436
6437 bool atLeastOneCompFail = false;
6438
6439 unsigned I = NextToken();
6440 for (; I < NumTokens && isFunctionMacroToken(I); ++I) {
6441 SourceLocation TokLoc = getFunctionMacroTokenLoc(I);
6442 if (TokLoc.isFileID())
6443 continue; // not macro arg token, it's parens or comma.
6444 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
6445 if (clang_isInvalid(clang_getCursorKind(Cursors[I])))
6446 Cursors[I] = updateC;
6447 } else
6448 atLeastOneCompFail = true;
6449 }
6450
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006451 if (atLeastOneCompFail)
6452 return false;
6453
6454 TokIdx = I; // All of the tokens were handled, advance beyond all of them.
6455 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00006456}
6457
6458enum CXChildVisitResult
6459AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006460 SourceRange cursorRange = getRawCursorExtent(cursor);
6461 if (cursorRange.isInvalid())
6462 return CXChildVisit_Recurse;
6463
6464 if (!HasContextSensitiveKeywords) {
6465 // Objective-C properties can have context-sensitive keywords.
6466 if (cursor.kind == CXCursor_ObjCPropertyDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006467 if (const ObjCPropertyDecl *Property
Guy Benyei11169dd2012-12-18 14:30:41 +00006468 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(cursor)))
6469 HasContextSensitiveKeywords = Property->getPropertyAttributesAsWritten() != 0;
6470 }
6471 // Objective-C methods can have context-sensitive keywords.
6472 else if (cursor.kind == CXCursor_ObjCInstanceMethodDecl ||
6473 cursor.kind == CXCursor_ObjCClassMethodDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006474 if (const ObjCMethodDecl *Method
Guy Benyei11169dd2012-12-18 14:30:41 +00006475 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
6476 if (Method->getObjCDeclQualifier())
6477 HasContextSensitiveKeywords = true;
6478 else {
David Majnemer59f77922016-06-24 04:05:48 +00006479 for (const auto *P : Method->parameters()) {
Aaron Ballman43b68be2014-03-07 17:50:17 +00006480 if (P->getObjCDeclQualifier()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006481 HasContextSensitiveKeywords = true;
6482 break;
6483 }
6484 }
6485 }
6486 }
6487 }
6488 // C++ methods can have context-sensitive keywords.
6489 else if (cursor.kind == CXCursor_CXXMethod) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006490 if (const CXXMethodDecl *Method
Guy Benyei11169dd2012-12-18 14:30:41 +00006491 = dyn_cast_or_null<CXXMethodDecl>(getCursorDecl(cursor))) {
6492 if (Method->hasAttr<FinalAttr>() || Method->hasAttr<OverrideAttr>())
6493 HasContextSensitiveKeywords = true;
6494 }
6495 }
6496 // C++ classes can have context-sensitive keywords.
6497 else if (cursor.kind == CXCursor_StructDecl ||
6498 cursor.kind == CXCursor_ClassDecl ||
6499 cursor.kind == CXCursor_ClassTemplate ||
6500 cursor.kind == CXCursor_ClassTemplatePartialSpecialization) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006501 if (const Decl *D = getCursorDecl(cursor))
Guy Benyei11169dd2012-12-18 14:30:41 +00006502 if (D->hasAttr<FinalAttr>())
6503 HasContextSensitiveKeywords = true;
6504 }
6505 }
Argyrios Kyrtzidis990b3862013-06-04 18:24:30 +00006506
6507 // Don't override a property annotation with its getter/setter method.
6508 if (cursor.kind == CXCursor_ObjCInstanceMethodDecl &&
6509 parent.kind == CXCursor_ObjCPropertyDecl)
6510 return CXChildVisit_Continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00006511
6512 if (clang_isPreprocessing(cursor.kind)) {
6513 // Items in the preprocessing record are kept separate from items in
6514 // declarations, so we keep a separate token index.
6515 unsigned SavedTokIdx = TokIdx;
6516 TokIdx = PreprocessingTokIdx;
6517
6518 // Skip tokens up until we catch up to the beginning of the preprocessing
6519 // entry.
6520 while (MoreTokens()) {
6521 const unsigned I = NextToken();
6522 SourceLocation TokLoc = GetTokenLoc(I);
6523 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
6524 case RangeBefore:
6525 AdvanceToken();
6526 continue;
6527 case RangeAfter:
6528 case RangeOverlap:
6529 break;
6530 }
6531 break;
6532 }
6533
6534 // Look at all of the tokens within this range.
6535 while (MoreTokens()) {
6536 const unsigned I = NextToken();
6537 SourceLocation TokLoc = GetTokenLoc(I);
6538 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
6539 case RangeBefore:
6540 llvm_unreachable("Infeasible");
6541 case RangeAfter:
6542 break;
6543 case RangeOverlap:
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00006544 // For macro expansions, just note where the beginning of the macro
6545 // expansion occurs.
6546 if (cursor.kind == CXCursor_MacroExpansion) {
6547 if (TokLoc == cursorRange.getBegin())
6548 Cursors[I] = cursor;
6549 AdvanceToken();
6550 break;
6551 }
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006552 // We may have already annotated macro names inside macro definitions.
6553 if (Cursors[I].kind != CXCursor_MacroExpansion)
6554 Cursors[I] = cursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00006555 AdvanceToken();
Guy Benyei11169dd2012-12-18 14:30:41 +00006556 continue;
6557 }
6558 break;
6559 }
6560
6561 // Save the preprocessing token index; restore the non-preprocessing
6562 // token index.
6563 PreprocessingTokIdx = TokIdx;
6564 TokIdx = SavedTokIdx;
6565 return CXChildVisit_Recurse;
6566 }
6567
6568 if (cursorRange.isInvalid())
6569 return CXChildVisit_Continue;
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006570
6571 unsigned BeforeReachingCursorIdx = NextToken();
Guy Benyei11169dd2012-12-18 14:30:41 +00006572 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00006573 const enum CXCursorKind K = clang_getCursorKind(parent);
6574 const CXCursor updateC =
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006575 (clang_isInvalid(K) || K == CXCursor_TranslationUnit ||
6576 // Attributes are annotated out-of-order, skip tokens until we reach it.
6577 clang_isAttribute(cursor.kind))
Guy Benyei11169dd2012-12-18 14:30:41 +00006578 ? clang_getNullCursor() : parent;
6579
6580 annotateAndAdvanceTokens(updateC, RangeBefore, cursorRange);
6581
6582 // Avoid having the cursor of an expression "overwrite" the annotation of the
6583 // variable declaration that it belongs to.
6584 // This can happen for C++ constructor expressions whose range generally
6585 // include the variable declaration, e.g.:
6586 // MyCXXClass foo; // Make sure we don't annotate 'foo' as a CallExpr cursor.
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006587 if (clang_isExpression(cursorK) && MoreTokens()) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006588 const Expr *E = getCursorExpr(cursor);
Dmitri Gribenkoa1691182013-01-26 18:12:08 +00006589 if (const Decl *D = getCursorParentDecl(cursor)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006590 const unsigned I = NextToken();
6591 if (E->getLocStart().isValid() && D->getLocation().isValid() &&
6592 E->getLocStart() == D->getLocation() &&
6593 E->getLocStart() == GetTokenLoc(I)) {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006594 updateCursorAnnotation(Cursors[I], updateC);
Guy Benyei11169dd2012-12-18 14:30:41 +00006595 AdvanceToken();
6596 }
6597 }
6598 }
6599
6600 // Before recursing into the children keep some state that we are going
6601 // to use in the AnnotateTokensWorker::postVisitChildren callback to do some
6602 // extra work after the child nodes are visited.
6603 // Note that we don't call VisitChildren here to avoid traversing statements
6604 // code-recursively which can blow the stack.
6605
6606 PostChildrenInfo Info;
6607 Info.Cursor = cursor;
6608 Info.CursorRange = cursorRange;
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006609 Info.BeforeReachingCursorIdx = BeforeReachingCursorIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00006610 Info.BeforeChildrenTokenIdx = NextToken();
6611 PostChildrenInfos.push_back(Info);
6612
6613 return CXChildVisit_Recurse;
6614}
6615
6616bool AnnotateTokensWorker::postVisitChildren(CXCursor cursor) {
6617 if (PostChildrenInfos.empty())
6618 return false;
6619 const PostChildrenInfo &Info = PostChildrenInfos.back();
6620 if (!clang_equalCursors(Info.Cursor, cursor))
6621 return false;
6622
6623 const unsigned BeforeChildren = Info.BeforeChildrenTokenIdx;
6624 const unsigned AfterChildren = NextToken();
6625 SourceRange cursorRange = Info.CursorRange;
6626
6627 // Scan the tokens that are at the end of the cursor, but are not captured
6628 // but the child cursors.
6629 annotateAndAdvanceTokens(cursor, RangeOverlap, cursorRange);
6630
6631 // Scan the tokens that are at the beginning of the cursor, but are not
6632 // capture by the child cursors.
6633 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
6634 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
6635 break;
6636
6637 Cursors[I] = cursor;
6638 }
6639
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006640 // Attributes are annotated out-of-order, rewind TokIdx to when we first
6641 // encountered the attribute cursor.
6642 if (clang_isAttribute(cursor.kind))
6643 TokIdx = Info.BeforeReachingCursorIdx;
6644
Guy Benyei11169dd2012-12-18 14:30:41 +00006645 PostChildrenInfos.pop_back();
6646 return false;
6647}
6648
6649static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
6650 CXCursor parent,
6651 CXClientData client_data) {
6652 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
6653}
6654
6655static bool AnnotateTokensPostChildrenVisitor(CXCursor cursor,
6656 CXClientData client_data) {
6657 return static_cast<AnnotateTokensWorker*>(client_data)->
6658 postVisitChildren(cursor);
6659}
6660
6661namespace {
6662
6663/// \brief Uses the macro expansions in the preprocessing record to find
6664/// and mark tokens that are macro arguments. This info is used by the
6665/// AnnotateTokensWorker.
6666class MarkMacroArgTokensVisitor {
6667 SourceManager &SM;
6668 CXToken *Tokens;
6669 unsigned NumTokens;
6670 unsigned CurIdx;
6671
6672public:
6673 MarkMacroArgTokensVisitor(SourceManager &SM,
6674 CXToken *tokens, unsigned numTokens)
6675 : SM(SM), Tokens(tokens), NumTokens(numTokens), CurIdx(0) { }
6676
6677 CXChildVisitResult visit(CXCursor cursor, CXCursor parent) {
6678 if (cursor.kind != CXCursor_MacroExpansion)
6679 return CXChildVisit_Continue;
6680
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00006681 SourceRange macroRange = getCursorMacroExpansion(cursor).getSourceRange();
Guy Benyei11169dd2012-12-18 14:30:41 +00006682 if (macroRange.getBegin() == macroRange.getEnd())
6683 return CXChildVisit_Continue; // it's not a function macro.
6684
6685 for (; CurIdx < NumTokens; ++CurIdx) {
6686 if (!SM.isBeforeInTranslationUnit(getTokenLoc(CurIdx),
6687 macroRange.getBegin()))
6688 break;
6689 }
6690
6691 if (CurIdx == NumTokens)
6692 return CXChildVisit_Break;
6693
6694 for (; CurIdx < NumTokens; ++CurIdx) {
6695 SourceLocation tokLoc = getTokenLoc(CurIdx);
6696 if (!SM.isBeforeInTranslationUnit(tokLoc, macroRange.getEnd()))
6697 break;
6698
6699 setFunctionMacroTokenLoc(CurIdx, SM.getMacroArgExpandedLocation(tokLoc));
6700 }
6701
6702 if (CurIdx == NumTokens)
6703 return CXChildVisit_Break;
6704
6705 return CXChildVisit_Continue;
6706 }
6707
6708private:
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006709 CXToken &getTok(unsigned Idx) {
6710 assert(Idx < NumTokens);
6711 return Tokens[Idx];
6712 }
6713 const CXToken &getTok(unsigned Idx) const {
6714 assert(Idx < NumTokens);
6715 return Tokens[Idx];
6716 }
6717
Guy Benyei11169dd2012-12-18 14:30:41 +00006718 SourceLocation getTokenLoc(unsigned tokI) {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006719 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[1]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006720 }
6721
6722 void setFunctionMacroTokenLoc(unsigned tokI, SourceLocation loc) {
6723 // The third field is reserved and currently not used. Use it here
6724 // to mark macro arg expanded tokens with their expanded locations.
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006725 getTok(tokI).int_data[3] = loc.getRawEncoding();
Guy Benyei11169dd2012-12-18 14:30:41 +00006726 }
6727};
6728
6729} // end anonymous namespace
6730
6731static CXChildVisitResult
6732MarkMacroArgTokensVisitorDelegate(CXCursor cursor, CXCursor parent,
6733 CXClientData client_data) {
6734 return static_cast<MarkMacroArgTokensVisitor*>(client_data)->visit(cursor,
6735 parent);
6736}
6737
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006738/// \brief Used by \c annotatePreprocessorTokens.
6739/// \returns true if lexing was finished, false otherwise.
6740static bool lexNext(Lexer &Lex, Token &Tok,
6741 unsigned &NextIdx, unsigned NumTokens) {
6742 if (NextIdx >= NumTokens)
6743 return true;
6744
6745 ++NextIdx;
6746 Lex.LexFromRawLexer(Tok);
Alexander Kornienko1a9f1842015-12-28 15:24:08 +00006747 return Tok.is(tok::eof);
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006748}
6749
Guy Benyei11169dd2012-12-18 14:30:41 +00006750static void annotatePreprocessorTokens(CXTranslationUnit TU,
6751 SourceRange RegionOfInterest,
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006752 CXCursor *Cursors,
6753 CXToken *Tokens,
6754 unsigned NumTokens) {
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006755 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006756
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00006757 Preprocessor &PP = CXXUnit->getPreprocessor();
Guy Benyei11169dd2012-12-18 14:30:41 +00006758 SourceManager &SourceMgr = CXXUnit->getSourceManager();
6759 std::pair<FileID, unsigned> BeginLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00006760 = SourceMgr.getDecomposedSpellingLoc(RegionOfInterest.getBegin());
Guy Benyei11169dd2012-12-18 14:30:41 +00006761 std::pair<FileID, unsigned> EndLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00006762 = SourceMgr.getDecomposedSpellingLoc(RegionOfInterest.getEnd());
Guy Benyei11169dd2012-12-18 14:30:41 +00006763
6764 if (BeginLocInfo.first != EndLocInfo.first)
6765 return;
6766
6767 StringRef Buffer;
6768 bool Invalid = false;
6769 Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
6770 if (Buffer.empty() || Invalid)
6771 return;
6772
6773 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
6774 CXXUnit->getASTContext().getLangOpts(),
6775 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
6776 Buffer.end());
6777 Lex.SetCommentRetentionState(true);
6778
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006779 unsigned NextIdx = 0;
Guy Benyei11169dd2012-12-18 14:30:41 +00006780 // Lex tokens in raw mode until we hit the end of the range, to avoid
6781 // entering #includes or expanding macros.
6782 while (true) {
6783 Token Tok;
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006784 if (lexNext(Lex, Tok, NextIdx, NumTokens))
6785 break;
6786 unsigned TokIdx = NextIdx-1;
6787 assert(Tok.getLocation() ==
6788 SourceLocation::getFromRawEncoding(Tokens[TokIdx].int_data[1]));
Guy Benyei11169dd2012-12-18 14:30:41 +00006789
6790 reprocess:
6791 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006792 // We have found a preprocessing directive. Annotate the tokens
6793 // appropriately.
Guy Benyei11169dd2012-12-18 14:30:41 +00006794 //
6795 // FIXME: Some simple tests here could identify macro definitions and
6796 // #undefs, to provide specific cursor kinds for those.
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006797
6798 SourceLocation BeginLoc = Tok.getLocation();
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00006799 if (lexNext(Lex, Tok, NextIdx, NumTokens))
6800 break;
6801
Craig Topper69186e72014-06-08 08:38:04 +00006802 MacroInfo *MI = nullptr;
Alp Toker2d57cea2014-05-17 04:53:25 +00006803 if (Tok.is(tok::raw_identifier) && Tok.getRawIdentifier() == "define") {
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00006804 if (lexNext(Lex, Tok, NextIdx, NumTokens))
6805 break;
6806
6807 if (Tok.is(tok::raw_identifier)) {
Alp Toker2d57cea2014-05-17 04:53:25 +00006808 IdentifierInfo &II =
6809 PP.getIdentifierTable().get(Tok.getRawIdentifier());
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00006810 SourceLocation MappedTokLoc =
6811 CXXUnit->mapLocationToPreamble(Tok.getLocation());
6812 MI = getMacroInfo(II, MappedTokLoc, TU);
6813 }
6814 }
6815
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006816 bool finished = false;
Guy Benyei11169dd2012-12-18 14:30:41 +00006817 do {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006818 if (lexNext(Lex, Tok, NextIdx, NumTokens)) {
6819 finished = true;
6820 break;
6821 }
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00006822 // If we are in a macro definition, check if the token was ever a
6823 // macro name and annotate it if that's the case.
6824 if (MI) {
6825 SourceLocation SaveLoc = Tok.getLocation();
6826 Tok.setLocation(CXXUnit->mapLocationToPreamble(SaveLoc));
Richard Smith66a81862015-05-04 02:25:31 +00006827 MacroDefinitionRecord *MacroDef =
6828 checkForMacroInMacroDefinition(MI, Tok, TU);
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00006829 Tok.setLocation(SaveLoc);
6830 if (MacroDef)
Richard Smith66a81862015-05-04 02:25:31 +00006831 Cursors[NextIdx - 1] =
6832 MakeMacroExpansionCursor(MacroDef, Tok.getLocation(), TU);
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00006833 }
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006834 } while (!Tok.isAtStartOfLine());
6835
6836 unsigned LastIdx = finished ? NextIdx-1 : NextIdx-2;
6837 assert(TokIdx <= LastIdx);
6838 SourceLocation EndLoc =
6839 SourceLocation::getFromRawEncoding(Tokens[LastIdx].int_data[1]);
6840 CXCursor Cursor =
6841 MakePreprocessingDirectiveCursor(SourceRange(BeginLoc, EndLoc), TU);
6842
6843 for (; TokIdx <= LastIdx; ++TokIdx)
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00006844 updateCursorAnnotation(Cursors[TokIdx], Cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00006845
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006846 if (finished)
6847 break;
6848 goto reprocess;
Guy Benyei11169dd2012-12-18 14:30:41 +00006849 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006850 }
6851}
6852
6853// This gets run a separate thread to avoid stack blowout.
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00006854static void clang_annotateTokensImpl(CXTranslationUnit TU, ASTUnit *CXXUnit,
6855 CXToken *Tokens, unsigned NumTokens,
6856 CXCursor *Cursors) {
Dmitri Gribenko183436e2013-01-26 21:49:50 +00006857 CIndexer *CXXIdx = TU->CIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00006858 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing))
6859 setThreadBackgroundPriority();
6860
6861 // Determine the region of interest, which contains all of the tokens.
6862 SourceRange RegionOfInterest;
6863 RegionOfInterest.setBegin(
6864 cxloc::translateSourceLocation(clang_getTokenLocation(TU, Tokens[0])));
6865 RegionOfInterest.setEnd(
6866 cxloc::translateSourceLocation(clang_getTokenLocation(TU,
6867 Tokens[NumTokens-1])));
6868
Guy Benyei11169dd2012-12-18 14:30:41 +00006869 // Relex the tokens within the source range to look for preprocessing
6870 // directives.
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006871 annotatePreprocessorTokens(TU, RegionOfInterest, Cursors, Tokens, NumTokens);
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00006872
6873 // If begin location points inside a macro argument, set it to the expansion
6874 // location so we can have the full context when annotating semantically.
6875 {
6876 SourceManager &SM = CXXUnit->getSourceManager();
6877 SourceLocation Loc =
6878 SM.getMacroArgExpandedLocation(RegionOfInterest.getBegin());
6879 if (Loc.isMacroID())
6880 RegionOfInterest.setBegin(SM.getExpansionLoc(Loc));
6881 }
6882
Guy Benyei11169dd2012-12-18 14:30:41 +00006883 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
6884 // Search and mark tokens that are macro argument expansions.
6885 MarkMacroArgTokensVisitor Visitor(CXXUnit->getSourceManager(),
6886 Tokens, NumTokens);
6887 CursorVisitor MacroArgMarker(TU,
6888 MarkMacroArgTokensVisitorDelegate, &Visitor,
6889 /*VisitPreprocessorLast=*/true,
6890 /*VisitIncludedEntities=*/false,
6891 RegionOfInterest);
6892 MacroArgMarker.visitPreprocessedEntitiesInRegion();
6893 }
6894
6895 // Annotate all of the source locations in the region of interest that map to
6896 // a specific cursor.
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006897 AnnotateTokensWorker W(Tokens, Cursors, NumTokens, TU, RegionOfInterest);
Guy Benyei11169dd2012-12-18 14:30:41 +00006898
6899 // FIXME: We use a ridiculous stack size here because the data-recursion
6900 // algorithm uses a large stack frame than the non-data recursive version,
6901 // and AnnotationTokensWorker currently transforms the data-recursion
6902 // algorithm back into a traditional recursion by explicitly calling
6903 // VisitChildren(). We will need to remove this explicit recursive call.
6904 W.AnnotateTokens();
6905
6906 // If we ran into any entities that involve context-sensitive keywords,
6907 // take another pass through the tokens to mark them as such.
6908 if (W.hasContextSensitiveKeywords()) {
6909 for (unsigned I = 0; I != NumTokens; ++I) {
6910 if (clang_getTokenKind(Tokens[I]) != CXToken_Identifier)
6911 continue;
6912
6913 if (Cursors[I].kind == CXCursor_ObjCPropertyDecl) {
6914 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006915 if (const ObjCPropertyDecl *Property
Guy Benyei11169dd2012-12-18 14:30:41 +00006916 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(Cursors[I]))) {
6917 if (Property->getPropertyAttributesAsWritten() != 0 &&
6918 llvm::StringSwitch<bool>(II->getName())
6919 .Case("readonly", true)
6920 .Case("assign", true)
6921 .Case("unsafe_unretained", true)
6922 .Case("readwrite", true)
6923 .Case("retain", true)
6924 .Case("copy", true)
6925 .Case("nonatomic", true)
6926 .Case("atomic", true)
6927 .Case("getter", true)
6928 .Case("setter", true)
6929 .Case("strong", true)
6930 .Case("weak", true)
Manman Ren04fd4d82016-05-31 23:22:04 +00006931 .Case("class", true)
Guy Benyei11169dd2012-12-18 14:30:41 +00006932 .Default(false))
6933 Tokens[I].int_data[0] = CXToken_Keyword;
6934 }
6935 continue;
6936 }
6937
6938 if (Cursors[I].kind == CXCursor_ObjCInstanceMethodDecl ||
6939 Cursors[I].kind == CXCursor_ObjCClassMethodDecl) {
6940 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
6941 if (llvm::StringSwitch<bool>(II->getName())
6942 .Case("in", true)
6943 .Case("out", true)
6944 .Case("inout", true)
6945 .Case("oneway", true)
6946 .Case("bycopy", true)
6947 .Case("byref", true)
6948 .Default(false))
6949 Tokens[I].int_data[0] = CXToken_Keyword;
6950 continue;
6951 }
6952
6953 if (Cursors[I].kind == CXCursor_CXXFinalAttr ||
6954 Cursors[I].kind == CXCursor_CXXOverrideAttr) {
6955 Tokens[I].int_data[0] = CXToken_Keyword;
6956 continue;
6957 }
6958 }
6959 }
6960}
6961
Guy Benyei11169dd2012-12-18 14:30:41 +00006962void clang_annotateTokens(CXTranslationUnit TU,
6963 CXToken *Tokens, unsigned NumTokens,
6964 CXCursor *Cursors) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006965 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006966 LOG_BAD_TU(TU);
6967 return;
6968 }
6969 if (NumTokens == 0 || !Tokens || !Cursors) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00006970 LOG_FUNC_SECTION { *Log << "<null input>"; }
Guy Benyei11169dd2012-12-18 14:30:41 +00006971 return;
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00006972 }
6973
6974 LOG_FUNC_SECTION {
6975 *Log << TU << ' ';
6976 CXSourceLocation bloc = clang_getTokenLocation(TU, Tokens[0]);
6977 CXSourceLocation eloc = clang_getTokenLocation(TU, Tokens[NumTokens-1]);
6978 *Log << clang_getRange(bloc, eloc);
6979 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006980
6981 // Any token we don't specifically annotate will have a NULL cursor.
6982 CXCursor C = clang_getNullCursor();
6983 for (unsigned I = 0; I != NumTokens; ++I)
6984 Cursors[I] = C;
6985
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006986 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006987 if (!CXXUnit)
6988 return;
6989
6990 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00006991
6992 auto AnnotateTokensImpl = [=]() {
6993 clang_annotateTokensImpl(TU, CXXUnit, Tokens, NumTokens, Cursors);
6994 };
Guy Benyei11169dd2012-12-18 14:30:41 +00006995 llvm::CrashRecoveryContext CRC;
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00006996 if (!RunSafely(CRC, AnnotateTokensImpl, GetSafetyThreadStackSize() * 2)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006997 fprintf(stderr, "libclang: crash detected while annotating tokens\n");
6998 }
6999}
7000
Guy Benyei11169dd2012-12-18 14:30:41 +00007001//===----------------------------------------------------------------------===//
7002// Operations for querying linkage of a cursor.
7003//===----------------------------------------------------------------------===//
7004
Guy Benyei11169dd2012-12-18 14:30:41 +00007005CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
7006 if (!clang_isDeclaration(cursor.kind))
7007 return CXLinkage_Invalid;
7008
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007009 const Decl *D = cxcursor::getCursorDecl(cursor);
7010 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
Rafael Espindola3ae00052013-05-13 00:12:11 +00007011 switch (ND->getLinkageInternal()) {
Rafael Espindola50df3a02013-05-25 17:16:20 +00007012 case NoLinkage:
7013 case VisibleNoLinkage: return CXLinkage_NoLinkage;
Guy Benyei11169dd2012-12-18 14:30:41 +00007014 case InternalLinkage: return CXLinkage_Internal;
7015 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
7016 case ExternalLinkage: return CXLinkage_External;
7017 };
7018
7019 return CXLinkage_Invalid;
7020}
Guy Benyei11169dd2012-12-18 14:30:41 +00007021
7022//===----------------------------------------------------------------------===//
Ehsan Akhgarib743de72016-05-31 15:55:51 +00007023// Operations for querying visibility of a cursor.
7024//===----------------------------------------------------------------------===//
7025
Ehsan Akhgarib743de72016-05-31 15:55:51 +00007026CXVisibilityKind clang_getCursorVisibility(CXCursor cursor) {
7027 if (!clang_isDeclaration(cursor.kind))
7028 return CXVisibility_Invalid;
7029
7030 const Decl *D = cxcursor::getCursorDecl(cursor);
7031 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
7032 switch (ND->getVisibility()) {
7033 case HiddenVisibility: return CXVisibility_Hidden;
7034 case ProtectedVisibility: return CXVisibility_Protected;
7035 case DefaultVisibility: return CXVisibility_Default;
7036 };
7037
7038 return CXVisibility_Invalid;
7039}
Ehsan Akhgarib743de72016-05-31 15:55:51 +00007040
7041//===----------------------------------------------------------------------===//
Guy Benyei11169dd2012-12-18 14:30:41 +00007042// Operations for querying language of a cursor.
7043//===----------------------------------------------------------------------===//
7044
7045static CXLanguageKind getDeclLanguage(const Decl *D) {
7046 if (!D)
7047 return CXLanguage_C;
7048
7049 switch (D->getKind()) {
7050 default:
7051 break;
7052 case Decl::ImplicitParam:
7053 case Decl::ObjCAtDefsField:
7054 case Decl::ObjCCategory:
7055 case Decl::ObjCCategoryImpl:
7056 case Decl::ObjCCompatibleAlias:
7057 case Decl::ObjCImplementation:
7058 case Decl::ObjCInterface:
7059 case Decl::ObjCIvar:
7060 case Decl::ObjCMethod:
7061 case Decl::ObjCProperty:
7062 case Decl::ObjCPropertyImpl:
7063 case Decl::ObjCProtocol:
Douglas Gregor85f3f952015-07-07 03:57:15 +00007064 case Decl::ObjCTypeParam:
Guy Benyei11169dd2012-12-18 14:30:41 +00007065 return CXLanguage_ObjC;
7066 case Decl::CXXConstructor:
7067 case Decl::CXXConversion:
7068 case Decl::CXXDestructor:
7069 case Decl::CXXMethod:
7070 case Decl::CXXRecord:
7071 case Decl::ClassTemplate:
7072 case Decl::ClassTemplatePartialSpecialization:
7073 case Decl::ClassTemplateSpecialization:
7074 case Decl::Friend:
7075 case Decl::FriendTemplate:
7076 case Decl::FunctionTemplate:
7077 case Decl::LinkageSpec:
7078 case Decl::Namespace:
7079 case Decl::NamespaceAlias:
7080 case Decl::NonTypeTemplateParm:
7081 case Decl::StaticAssert:
7082 case Decl::TemplateTemplateParm:
7083 case Decl::TemplateTypeParm:
7084 case Decl::UnresolvedUsingTypename:
7085 case Decl::UnresolvedUsingValue:
7086 case Decl::Using:
7087 case Decl::UsingDirective:
7088 case Decl::UsingShadow:
7089 return CXLanguage_CPlusPlus;
7090 }
7091
7092 return CXLanguage_C;
7093}
7094
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007095static CXAvailabilityKind getCursorAvailabilityForDecl(const Decl *D) {
7096 if (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted())
Manuel Klimek8e3a7ed2015-09-25 17:53:16 +00007097 return CXAvailability_NotAvailable;
Guy Benyei11169dd2012-12-18 14:30:41 +00007098
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007099 switch (D->getAvailability()) {
7100 case AR_Available:
7101 case AR_NotYetIntroduced:
7102 if (const EnumConstantDecl *EnumConst = dyn_cast<EnumConstantDecl>(D))
Benjamin Kramer656363d2013-10-15 18:53:18 +00007103 return getCursorAvailabilityForDecl(
7104 cast<Decl>(EnumConst->getDeclContext()));
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007105 return CXAvailability_Available;
7106
7107 case AR_Deprecated:
7108 return CXAvailability_Deprecated;
7109
7110 case AR_Unavailable:
7111 return CXAvailability_NotAvailable;
7112 }
Benjamin Kramer656363d2013-10-15 18:53:18 +00007113
7114 llvm_unreachable("Unknown availability kind!");
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007115}
7116
Guy Benyei11169dd2012-12-18 14:30:41 +00007117enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
7118 if (clang_isDeclaration(cursor.kind))
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007119 if (const Decl *D = cxcursor::getCursorDecl(cursor))
7120 return getCursorAvailabilityForDecl(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00007121
7122 return CXAvailability_Available;
7123}
7124
7125static CXVersion convertVersion(VersionTuple In) {
7126 CXVersion Out = { -1, -1, -1 };
7127 if (In.empty())
7128 return Out;
7129
7130 Out.Major = In.getMajor();
7131
NAKAMURA Takumic2b5d1f2013-02-21 02:32:34 +00007132 Optional<unsigned> Minor = In.getMinor();
7133 if (Minor.hasValue())
Guy Benyei11169dd2012-12-18 14:30:41 +00007134 Out.Minor = *Minor;
7135 else
7136 return Out;
7137
NAKAMURA Takumic2b5d1f2013-02-21 02:32:34 +00007138 Optional<unsigned> Subminor = In.getSubminor();
7139 if (Subminor.hasValue())
Guy Benyei11169dd2012-12-18 14:30:41 +00007140 Out.Subminor = *Subminor;
7141
7142 return Out;
7143}
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007144
7145static int getCursorPlatformAvailabilityForDecl(const Decl *D,
7146 int *always_deprecated,
7147 CXString *deprecated_message,
7148 int *always_unavailable,
7149 CXString *unavailable_message,
7150 CXPlatformAvailability *availability,
7151 int availability_size) {
7152 bool HadAvailAttr = false;
7153 int N = 0;
Aaron Ballmanb97112e2014-03-08 22:19:01 +00007154 for (auto A : D->attrs()) {
7155 if (DeprecatedAttr *Deprecated = dyn_cast<DeprecatedAttr>(A)) {
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007156 HadAvailAttr = true;
7157 if (always_deprecated)
7158 *always_deprecated = 1;
Nico Weberaacf0312014-04-24 05:16:45 +00007159 if (deprecated_message) {
Argyrios Kyrtzidisedfe07f2014-04-24 06:05:40 +00007160 clang_disposeString(*deprecated_message);
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007161 *deprecated_message = cxstring::createDup(Deprecated->getMessage());
Nico Weberaacf0312014-04-24 05:16:45 +00007162 }
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007163 continue;
7164 }
7165
Aaron Ballmanb97112e2014-03-08 22:19:01 +00007166 if (UnavailableAttr *Unavailable = dyn_cast<UnavailableAttr>(A)) {
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007167 HadAvailAttr = true;
7168 if (always_unavailable)
7169 *always_unavailable = 1;
7170 if (unavailable_message) {
Argyrios Kyrtzidisedfe07f2014-04-24 06:05:40 +00007171 clang_disposeString(*unavailable_message);
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007172 *unavailable_message = cxstring::createDup(Unavailable->getMessage());
7173 }
7174 continue;
7175 }
7176
Aaron Ballmanb97112e2014-03-08 22:19:01 +00007177 if (AvailabilityAttr *Avail = dyn_cast<AvailabilityAttr>(A)) {
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007178 HadAvailAttr = true;
7179 if (N < availability_size) {
7180 availability[N].Platform
7181 = cxstring::createDup(Avail->getPlatform()->getName());
7182 availability[N].Introduced = convertVersion(Avail->getIntroduced());
7183 availability[N].Deprecated = convertVersion(Avail->getDeprecated());
7184 availability[N].Obsoleted = convertVersion(Avail->getObsoleted());
7185 availability[N].Unavailable = Avail->getUnavailable();
7186 availability[N].Message = cxstring::createDup(Avail->getMessage());
7187 }
7188 ++N;
7189 }
7190 }
7191
7192 if (!HadAvailAttr)
7193 if (const EnumConstantDecl *EnumConst = dyn_cast<EnumConstantDecl>(D))
7194 return getCursorPlatformAvailabilityForDecl(
7195 cast<Decl>(EnumConst->getDeclContext()),
7196 always_deprecated,
7197 deprecated_message,
7198 always_unavailable,
7199 unavailable_message,
7200 availability,
7201 availability_size);
Guy Benyei11169dd2012-12-18 14:30:41 +00007202
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007203 return N;
7204}
7205
Guy Benyei11169dd2012-12-18 14:30:41 +00007206int clang_getCursorPlatformAvailability(CXCursor cursor,
7207 int *always_deprecated,
7208 CXString *deprecated_message,
7209 int *always_unavailable,
7210 CXString *unavailable_message,
7211 CXPlatformAvailability *availability,
7212 int availability_size) {
7213 if (always_deprecated)
7214 *always_deprecated = 0;
7215 if (deprecated_message)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00007216 *deprecated_message = cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00007217 if (always_unavailable)
7218 *always_unavailable = 0;
7219 if (unavailable_message)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00007220 *unavailable_message = cxstring::createEmpty();
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007221
Guy Benyei11169dd2012-12-18 14:30:41 +00007222 if (!clang_isDeclaration(cursor.kind))
7223 return 0;
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007224
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007225 const Decl *D = cxcursor::getCursorDecl(cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00007226 if (!D)
7227 return 0;
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007228
7229 return getCursorPlatformAvailabilityForDecl(D, always_deprecated,
7230 deprecated_message,
7231 always_unavailable,
7232 unavailable_message,
7233 availability,
7234 availability_size);
Guy Benyei11169dd2012-12-18 14:30:41 +00007235}
7236
7237void clang_disposeCXPlatformAvailability(CXPlatformAvailability *availability) {
7238 clang_disposeString(availability->Platform);
7239 clang_disposeString(availability->Message);
7240}
7241
7242CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
7243 if (clang_isDeclaration(cursor.kind))
7244 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
7245
7246 return CXLanguage_Invalid;
7247}
7248
7249 /// \brief If the given cursor is the "templated" declaration
7250 /// descibing a class or function template, return the class or
7251 /// function template.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007252static const Decl *maybeGetTemplateCursor(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007253 if (!D)
Craig Topper69186e72014-06-08 08:38:04 +00007254 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007255
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007256 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00007257 if (FunctionTemplateDecl *FunTmpl = FD->getDescribedFunctionTemplate())
7258 return FunTmpl;
7259
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007260 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00007261 if (ClassTemplateDecl *ClassTmpl = RD->getDescribedClassTemplate())
7262 return ClassTmpl;
7263
7264 return D;
7265}
7266
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00007267
7268enum CX_StorageClass clang_Cursor_getStorageClass(CXCursor C) {
7269 StorageClass sc = SC_None;
7270 const Decl *D = getCursorDecl(C);
7271 if (D) {
7272 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7273 sc = FD->getStorageClass();
7274 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7275 sc = VD->getStorageClass();
7276 } else {
7277 return CX_SC_Invalid;
7278 }
7279 } else {
7280 return CX_SC_Invalid;
7281 }
7282 switch (sc) {
7283 case SC_None:
7284 return CX_SC_None;
7285 case SC_Extern:
7286 return CX_SC_Extern;
7287 case SC_Static:
7288 return CX_SC_Static;
7289 case SC_PrivateExtern:
7290 return CX_SC_PrivateExtern;
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00007291 case SC_Auto:
7292 return CX_SC_Auto;
7293 case SC_Register:
7294 return CX_SC_Register;
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00007295 }
Kaelyn Takataab61e702014-10-15 18:03:26 +00007296 llvm_unreachable("Unhandled storage class!");
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00007297}
7298
Guy Benyei11169dd2012-12-18 14:30:41 +00007299CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
7300 if (clang_isDeclaration(cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007301 if (const Decl *D = getCursorDecl(cursor)) {
7302 const DeclContext *DC = D->getDeclContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00007303 if (!DC)
7304 return clang_getNullCursor();
7305
7306 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
7307 getCursorTU(cursor));
7308 }
7309 }
7310
7311 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007312 if (const Decl *D = getCursorDecl(cursor))
Guy Benyei11169dd2012-12-18 14:30:41 +00007313 return MakeCXCursor(D, getCursorTU(cursor));
7314 }
7315
7316 return clang_getNullCursor();
7317}
7318
7319CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
7320 if (clang_isDeclaration(cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007321 if (const Decl *D = getCursorDecl(cursor)) {
7322 const DeclContext *DC = D->getLexicalDeclContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00007323 if (!DC)
7324 return clang_getNullCursor();
7325
7326 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
7327 getCursorTU(cursor));
7328 }
7329 }
7330
7331 // FIXME: Note that we can't easily compute the lexical context of a
7332 // statement or expression, so we return nothing.
7333 return clang_getNullCursor();
7334}
7335
7336CXFile clang_getIncludedFile(CXCursor cursor) {
7337 if (cursor.kind != CXCursor_InclusionDirective)
Craig Topper69186e72014-06-08 08:38:04 +00007338 return nullptr;
7339
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00007340 const InclusionDirective *ID = getCursorInclusionDirective(cursor);
Dmitri Gribenkof9304482013-01-23 15:56:07 +00007341 return const_cast<FileEntry *>(ID->getFile());
Guy Benyei11169dd2012-12-18 14:30:41 +00007342}
7343
Argyrios Kyrtzidis9adfd8a2013-04-18 22:15:49 +00007344unsigned clang_Cursor_getObjCPropertyAttributes(CXCursor C, unsigned reserved) {
7345 if (C.kind != CXCursor_ObjCPropertyDecl)
7346 return CXObjCPropertyAttr_noattr;
7347
7348 unsigned Result = CXObjCPropertyAttr_noattr;
7349 const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(getCursorDecl(C));
7350 ObjCPropertyDecl::PropertyAttributeKind Attr =
7351 PD->getPropertyAttributesAsWritten();
7352
7353#define SET_CXOBJCPROP_ATTR(A) \
7354 if (Attr & ObjCPropertyDecl::OBJC_PR_##A) \
7355 Result |= CXObjCPropertyAttr_##A
7356 SET_CXOBJCPROP_ATTR(readonly);
7357 SET_CXOBJCPROP_ATTR(getter);
7358 SET_CXOBJCPROP_ATTR(assign);
7359 SET_CXOBJCPROP_ATTR(readwrite);
7360 SET_CXOBJCPROP_ATTR(retain);
7361 SET_CXOBJCPROP_ATTR(copy);
7362 SET_CXOBJCPROP_ATTR(nonatomic);
7363 SET_CXOBJCPROP_ATTR(setter);
7364 SET_CXOBJCPROP_ATTR(atomic);
7365 SET_CXOBJCPROP_ATTR(weak);
7366 SET_CXOBJCPROP_ATTR(strong);
7367 SET_CXOBJCPROP_ATTR(unsafe_unretained);
Manman Ren04fd4d82016-05-31 23:22:04 +00007368 SET_CXOBJCPROP_ATTR(class);
Argyrios Kyrtzidis9adfd8a2013-04-18 22:15:49 +00007369#undef SET_CXOBJCPROP_ATTR
7370
7371 return Result;
7372}
7373
Argyrios Kyrtzidis9d9bc012013-04-18 23:29:12 +00007374unsigned clang_Cursor_getObjCDeclQualifiers(CXCursor C) {
7375 if (!clang_isDeclaration(C.kind))
7376 return CXObjCDeclQualifier_None;
7377
7378 Decl::ObjCDeclQualifier QT = Decl::OBJC_TQ_None;
7379 const Decl *D = getCursorDecl(C);
7380 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
7381 QT = MD->getObjCDeclQualifier();
7382 else if (const ParmVarDecl *PD = dyn_cast<ParmVarDecl>(D))
7383 QT = PD->getObjCDeclQualifier();
7384 if (QT == Decl::OBJC_TQ_None)
7385 return CXObjCDeclQualifier_None;
7386
7387 unsigned Result = CXObjCDeclQualifier_None;
7388 if (QT & Decl::OBJC_TQ_In) Result |= CXObjCDeclQualifier_In;
7389 if (QT & Decl::OBJC_TQ_Inout) Result |= CXObjCDeclQualifier_Inout;
7390 if (QT & Decl::OBJC_TQ_Out) Result |= CXObjCDeclQualifier_Out;
7391 if (QT & Decl::OBJC_TQ_Bycopy) Result |= CXObjCDeclQualifier_Bycopy;
7392 if (QT & Decl::OBJC_TQ_Byref) Result |= CXObjCDeclQualifier_Byref;
7393 if (QT & Decl::OBJC_TQ_Oneway) Result |= CXObjCDeclQualifier_Oneway;
7394
7395 return Result;
7396}
7397
Argyrios Kyrtzidis7b50fc52013-07-05 20:44:37 +00007398unsigned clang_Cursor_isObjCOptional(CXCursor C) {
7399 if (!clang_isDeclaration(C.kind))
7400 return 0;
7401
7402 const Decl *D = getCursorDecl(C);
7403 if (const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D))
7404 return PD->getPropertyImplementation() == ObjCPropertyDecl::Optional;
7405 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
7406 return MD->getImplementationControl() == ObjCMethodDecl::Optional;
7407
7408 return 0;
7409}
7410
Argyrios Kyrtzidis23814e42013-04-18 23:53:05 +00007411unsigned clang_Cursor_isVariadic(CXCursor C) {
7412 if (!clang_isDeclaration(C.kind))
7413 return 0;
7414
7415 const Decl *D = getCursorDecl(C);
7416 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
7417 return FD->isVariadic();
7418 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
7419 return MD->isVariadic();
7420
7421 return 0;
7422}
7423
Guy Benyei11169dd2012-12-18 14:30:41 +00007424CXSourceRange clang_Cursor_getCommentRange(CXCursor C) {
7425 if (!clang_isDeclaration(C.kind))
7426 return clang_getNullRange();
7427
7428 const Decl *D = getCursorDecl(C);
7429 ASTContext &Context = getCursorContext(C);
7430 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
7431 if (!RC)
7432 return clang_getNullRange();
7433
7434 return cxloc::translateSourceRange(Context, RC->getSourceRange());
7435}
7436
7437CXString clang_Cursor_getRawCommentText(CXCursor C) {
7438 if (!clang_isDeclaration(C.kind))
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00007439 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00007440
7441 const Decl *D = getCursorDecl(C);
7442 ASTContext &Context = getCursorContext(C);
7443 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
7444 StringRef RawText = RC ? RC->getRawText(Context.getSourceManager()) :
7445 StringRef();
7446
7447 // Don't duplicate the string because RawText points directly into source
7448 // code.
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00007449 return cxstring::createRef(RawText);
Guy Benyei11169dd2012-12-18 14:30:41 +00007450}
7451
7452CXString clang_Cursor_getBriefCommentText(CXCursor C) {
7453 if (!clang_isDeclaration(C.kind))
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00007454 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00007455
7456 const Decl *D = getCursorDecl(C);
7457 const ASTContext &Context = getCursorContext(C);
7458 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
7459
7460 if (RC) {
7461 StringRef BriefText = RC->getBriefText(Context);
7462
7463 // Don't duplicate the string because RawComment ensures that this memory
7464 // will not go away.
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00007465 return cxstring::createRef(BriefText);
Guy Benyei11169dd2012-12-18 14:30:41 +00007466 }
7467
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00007468 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00007469}
7470
Guy Benyei11169dd2012-12-18 14:30:41 +00007471CXModule clang_Cursor_getModule(CXCursor C) {
7472 if (C.kind == CXCursor_ModuleImportDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007473 if (const ImportDecl *ImportD =
7474 dyn_cast_or_null<ImportDecl>(getCursorDecl(C)))
Guy Benyei11169dd2012-12-18 14:30:41 +00007475 return ImportD->getImportedModule();
7476 }
7477
Craig Topper69186e72014-06-08 08:38:04 +00007478 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007479}
7480
Argyrios Kyrtzidisf6d49c32014-05-14 23:14:37 +00007481CXModule clang_getModuleForFile(CXTranslationUnit TU, CXFile File) {
7482 if (isNotUsableTU(TU)) {
7483 LOG_BAD_TU(TU);
7484 return nullptr;
7485 }
7486 if (!File)
7487 return nullptr;
7488 FileEntry *FE = static_cast<FileEntry *>(File);
7489
7490 ASTUnit &Unit = *cxtu::getASTUnit(TU);
7491 HeaderSearch &HS = Unit.getPreprocessor().getHeaderSearchInfo();
7492 ModuleMap::KnownHeader Header = HS.findModuleForHeader(FE);
7493
Richard Smithfeb54b62014-10-23 02:01:19 +00007494 return Header.getModule();
Argyrios Kyrtzidisf6d49c32014-05-14 23:14:37 +00007495}
7496
Argyrios Kyrtzidis12fdb9e2013-04-26 22:47:49 +00007497CXFile clang_Module_getASTFile(CXModule CXMod) {
7498 if (!CXMod)
Craig Topper69186e72014-06-08 08:38:04 +00007499 return nullptr;
Argyrios Kyrtzidis12fdb9e2013-04-26 22:47:49 +00007500 Module *Mod = static_cast<Module*>(CXMod);
7501 return const_cast<FileEntry *>(Mod->getASTFile());
7502}
7503
Guy Benyei11169dd2012-12-18 14:30:41 +00007504CXModule clang_Module_getParent(CXModule CXMod) {
7505 if (!CXMod)
Craig Topper69186e72014-06-08 08:38:04 +00007506 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007507 Module *Mod = static_cast<Module*>(CXMod);
7508 return Mod->Parent;
7509}
7510
7511CXString clang_Module_getName(CXModule CXMod) {
7512 if (!CXMod)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00007513 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00007514 Module *Mod = static_cast<Module*>(CXMod);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00007515 return cxstring::createDup(Mod->Name);
Guy Benyei11169dd2012-12-18 14:30:41 +00007516}
7517
7518CXString clang_Module_getFullName(CXModule CXMod) {
7519 if (!CXMod)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00007520 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00007521 Module *Mod = static_cast<Module*>(CXMod);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00007522 return cxstring::createDup(Mod->getFullModuleName());
Guy Benyei11169dd2012-12-18 14:30:41 +00007523}
7524
Argyrios Kyrtzidis884337f2014-05-15 04:44:25 +00007525int clang_Module_isSystem(CXModule CXMod) {
7526 if (!CXMod)
7527 return 0;
7528 Module *Mod = static_cast<Module*>(CXMod);
7529 return Mod->IsSystem;
7530}
7531
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00007532unsigned clang_Module_getNumTopLevelHeaders(CXTranslationUnit TU,
7533 CXModule CXMod) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00007534 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00007535 LOG_BAD_TU(TU);
7536 return 0;
7537 }
7538 if (!CXMod)
Guy Benyei11169dd2012-12-18 14:30:41 +00007539 return 0;
7540 Module *Mod = static_cast<Module*>(CXMod);
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00007541 FileManager &FileMgr = cxtu::getASTUnit(TU)->getFileManager();
7542 ArrayRef<const FileEntry *> TopHeaders = Mod->getTopHeaders(FileMgr);
7543 return TopHeaders.size();
Guy Benyei11169dd2012-12-18 14:30:41 +00007544}
7545
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00007546CXFile clang_Module_getTopLevelHeader(CXTranslationUnit TU,
7547 CXModule CXMod, unsigned Index) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00007548 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00007549 LOG_BAD_TU(TU);
Craig Topper69186e72014-06-08 08:38:04 +00007550 return nullptr;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00007551 }
7552 if (!CXMod)
Craig Topper69186e72014-06-08 08:38:04 +00007553 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007554 Module *Mod = static_cast<Module*>(CXMod);
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00007555 FileManager &FileMgr = cxtu::getASTUnit(TU)->getFileManager();
Guy Benyei11169dd2012-12-18 14:30:41 +00007556
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00007557 ArrayRef<const FileEntry *> TopHeaders = Mod->getTopHeaders(FileMgr);
7558 if (Index < TopHeaders.size())
7559 return const_cast<FileEntry *>(TopHeaders[Index]);
Guy Benyei11169dd2012-12-18 14:30:41 +00007560
Craig Topper69186e72014-06-08 08:38:04 +00007561 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007562}
7563
Guy Benyei11169dd2012-12-18 14:30:41 +00007564//===----------------------------------------------------------------------===//
7565// C++ AST instrospection.
7566//===----------------------------------------------------------------------===//
7567
Jonathan Coe29565352016-04-27 12:48:25 +00007568unsigned clang_CXXConstructor_isDefaultConstructor(CXCursor C) {
7569 if (!clang_isDeclaration(C.kind))
7570 return 0;
7571
7572 const Decl *D = cxcursor::getCursorDecl(C);
7573 const CXXConstructorDecl *Constructor =
7574 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
7575 return (Constructor && Constructor->isDefaultConstructor()) ? 1 : 0;
7576}
7577
7578unsigned clang_CXXConstructor_isCopyConstructor(CXCursor C) {
7579 if (!clang_isDeclaration(C.kind))
7580 return 0;
7581
7582 const Decl *D = cxcursor::getCursorDecl(C);
7583 const CXXConstructorDecl *Constructor =
7584 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
7585 return (Constructor && Constructor->isCopyConstructor()) ? 1 : 0;
7586}
7587
7588unsigned clang_CXXConstructor_isMoveConstructor(CXCursor C) {
7589 if (!clang_isDeclaration(C.kind))
7590 return 0;
7591
7592 const Decl *D = cxcursor::getCursorDecl(C);
7593 const CXXConstructorDecl *Constructor =
7594 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
7595 return (Constructor && Constructor->isMoveConstructor()) ? 1 : 0;
7596}
7597
7598unsigned clang_CXXConstructor_isConvertingConstructor(CXCursor C) {
7599 if (!clang_isDeclaration(C.kind))
7600 return 0;
7601
7602 const Decl *D = cxcursor::getCursorDecl(C);
7603 const CXXConstructorDecl *Constructor =
7604 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
7605 // Passing 'false' excludes constructors marked 'explicit'.
7606 return (Constructor && Constructor->isConvertingConstructor(false)) ? 1 : 0;
7607}
7608
Saleem Abdulrasool6ea75db2015-10-27 15:50:22 +00007609unsigned clang_CXXField_isMutable(CXCursor C) {
7610 if (!clang_isDeclaration(C.kind))
7611 return 0;
7612
7613 if (const auto D = cxcursor::getCursorDecl(C))
7614 if (const auto FD = dyn_cast_or_null<FieldDecl>(D))
7615 return FD->isMutable() ? 1 : 0;
7616 return 0;
7617}
7618
Dmitri Gribenko62770be2013-05-17 18:38:35 +00007619unsigned clang_CXXMethod_isPureVirtual(CXCursor C) {
7620 if (!clang_isDeclaration(C.kind))
7621 return 0;
7622
Dmitri Gribenko62770be2013-05-17 18:38:35 +00007623 const Decl *D = cxcursor::getCursorDecl(C);
Alp Tokera2794f92014-01-22 07:29:52 +00007624 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00007625 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Dmitri Gribenko62770be2013-05-17 18:38:35 +00007626 return (Method && Method->isVirtual() && Method->isPure()) ? 1 : 0;
7627}
7628
Dmitri Gribenkoe570ede2014-04-07 14:59:13 +00007629unsigned clang_CXXMethod_isConst(CXCursor C) {
7630 if (!clang_isDeclaration(C.kind))
7631 return 0;
7632
7633 const Decl *D = cxcursor::getCursorDecl(C);
7634 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00007635 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Dmitri Gribenkoe570ede2014-04-07 14:59:13 +00007636 return (Method && (Method->getTypeQualifiers() & Qualifiers::Const)) ? 1 : 0;
7637}
7638
Jonathan Coe29565352016-04-27 12:48:25 +00007639unsigned clang_CXXMethod_isDefaulted(CXCursor C) {
7640 if (!clang_isDeclaration(C.kind))
7641 return 0;
7642
7643 const Decl *D = cxcursor::getCursorDecl(C);
7644 const CXXMethodDecl *Method =
7645 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
7646 return (Method && Method->isDefaulted()) ? 1 : 0;
7647}
7648
Guy Benyei11169dd2012-12-18 14:30:41 +00007649unsigned clang_CXXMethod_isStatic(CXCursor C) {
7650 if (!clang_isDeclaration(C.kind))
7651 return 0;
7652
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007653 const Decl *D = cxcursor::getCursorDecl(C);
Alp Tokera2794f92014-01-22 07:29:52 +00007654 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00007655 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007656 return (Method && Method->isStatic()) ? 1 : 0;
7657}
7658
7659unsigned clang_CXXMethod_isVirtual(CXCursor C) {
7660 if (!clang_isDeclaration(C.kind))
7661 return 0;
7662
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007663 const Decl *D = cxcursor::getCursorDecl(C);
Alp Tokera2794f92014-01-22 07:29:52 +00007664 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00007665 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007666 return (Method && Method->isVirtual()) ? 1 : 0;
7667}
Guy Benyei11169dd2012-12-18 14:30:41 +00007668
7669//===----------------------------------------------------------------------===//
7670// Attribute introspection.
7671//===----------------------------------------------------------------------===//
7672
Guy Benyei11169dd2012-12-18 14:30:41 +00007673CXType clang_getIBOutletCollectionType(CXCursor C) {
7674 if (C.kind != CXCursor_IBOutletCollectionAttr)
7675 return cxtype::MakeCXType(QualType(), cxcursor::getCursorTU(C));
7676
Dmitri Gribenkoe4baea62013-01-26 18:08:08 +00007677 const IBOutletCollectionAttr *A =
Guy Benyei11169dd2012-12-18 14:30:41 +00007678 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
7679
7680 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorTU(C));
7681}
Guy Benyei11169dd2012-12-18 14:30:41 +00007682
7683//===----------------------------------------------------------------------===//
7684// Inspecting memory usage.
7685//===----------------------------------------------------------------------===//
7686
7687typedef std::vector<CXTUResourceUsageEntry> MemUsageEntries;
7688
7689static inline void createCXTUResourceUsageEntry(MemUsageEntries &entries,
7690 enum CXTUResourceUsageKind k,
7691 unsigned long amount) {
7692 CXTUResourceUsageEntry entry = { k, amount };
7693 entries.push_back(entry);
7694}
7695
Guy Benyei11169dd2012-12-18 14:30:41 +00007696const char *clang_getTUResourceUsageName(CXTUResourceUsageKind kind) {
7697 const char *str = "";
7698 switch (kind) {
7699 case CXTUResourceUsage_AST:
7700 str = "ASTContext: expressions, declarations, and types";
7701 break;
7702 case CXTUResourceUsage_Identifiers:
7703 str = "ASTContext: identifiers";
7704 break;
7705 case CXTUResourceUsage_Selectors:
7706 str = "ASTContext: selectors";
7707 break;
7708 case CXTUResourceUsage_GlobalCompletionResults:
7709 str = "Code completion: cached global results";
7710 break;
7711 case CXTUResourceUsage_SourceManagerContentCache:
7712 str = "SourceManager: content cache allocator";
7713 break;
7714 case CXTUResourceUsage_AST_SideTables:
7715 str = "ASTContext: side tables";
7716 break;
7717 case CXTUResourceUsage_SourceManager_Membuffer_Malloc:
7718 str = "SourceManager: malloc'ed memory buffers";
7719 break;
7720 case CXTUResourceUsage_SourceManager_Membuffer_MMap:
7721 str = "SourceManager: mmap'ed memory buffers";
7722 break;
7723 case CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc:
7724 str = "ExternalASTSource: malloc'ed memory buffers";
7725 break;
7726 case CXTUResourceUsage_ExternalASTSource_Membuffer_MMap:
7727 str = "ExternalASTSource: mmap'ed memory buffers";
7728 break;
7729 case CXTUResourceUsage_Preprocessor:
7730 str = "Preprocessor: malloc'ed memory";
7731 break;
7732 case CXTUResourceUsage_PreprocessingRecord:
7733 str = "Preprocessor: PreprocessingRecord";
7734 break;
7735 case CXTUResourceUsage_SourceManager_DataStructures:
7736 str = "SourceManager: data structures and tables";
7737 break;
7738 case CXTUResourceUsage_Preprocessor_HeaderSearch:
7739 str = "Preprocessor: header search tables";
7740 break;
7741 }
7742 return str;
7743}
7744
7745CXTUResourceUsage clang_getCXTUResourceUsage(CXTranslationUnit TU) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00007746 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00007747 LOG_BAD_TU(TU);
Craig Topper69186e72014-06-08 08:38:04 +00007748 CXTUResourceUsage usage = { (void*) nullptr, 0, nullptr };
Guy Benyei11169dd2012-12-18 14:30:41 +00007749 return usage;
7750 }
7751
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00007752 ASTUnit *astUnit = cxtu::getASTUnit(TU);
Ahmed Charlesb8984322014-03-07 20:03:18 +00007753 std::unique_ptr<MemUsageEntries> entries(new MemUsageEntries());
Guy Benyei11169dd2012-12-18 14:30:41 +00007754 ASTContext &astContext = astUnit->getASTContext();
7755
7756 // How much memory is used by AST nodes and types?
7757 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST,
7758 (unsigned long) astContext.getASTAllocatedMemory());
7759
7760 // How much memory is used by identifiers?
7761 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Identifiers,
7762 (unsigned long) astContext.Idents.getAllocator().getTotalMemory());
7763
7764 // How much memory is used for selectors?
7765 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Selectors,
7766 (unsigned long) astContext.Selectors.getTotalMemory());
7767
7768 // How much memory is used by ASTContext's side tables?
7769 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST_SideTables,
7770 (unsigned long) astContext.getSideTableAllocatedMemory());
7771
7772 // How much memory is used for caching global code completion results?
7773 unsigned long completionBytes = 0;
7774 if (GlobalCodeCompletionAllocator *completionAllocator =
Alp Tokerf994cef2014-07-05 03:08:06 +00007775 astUnit->getCachedCompletionAllocator().get()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007776 completionBytes = completionAllocator->getTotalMemory();
7777 }
7778 createCXTUResourceUsageEntry(*entries,
7779 CXTUResourceUsage_GlobalCompletionResults,
7780 completionBytes);
7781
7782 // How much memory is being used by SourceManager's content cache?
7783 createCXTUResourceUsageEntry(*entries,
7784 CXTUResourceUsage_SourceManagerContentCache,
7785 (unsigned long) astContext.getSourceManager().getContentCacheSize());
7786
7787 // How much memory is being used by the MemoryBuffer's in SourceManager?
7788 const SourceManager::MemoryBufferSizes &srcBufs =
7789 astUnit->getSourceManager().getMemoryBufferSizes();
7790
7791 createCXTUResourceUsageEntry(*entries,
7792 CXTUResourceUsage_SourceManager_Membuffer_Malloc,
7793 (unsigned long) srcBufs.malloc_bytes);
7794 createCXTUResourceUsageEntry(*entries,
7795 CXTUResourceUsage_SourceManager_Membuffer_MMap,
7796 (unsigned long) srcBufs.mmap_bytes);
7797 createCXTUResourceUsageEntry(*entries,
7798 CXTUResourceUsage_SourceManager_DataStructures,
7799 (unsigned long) astContext.getSourceManager()
7800 .getDataStructureSizes());
7801
7802 // How much memory is being used by the ExternalASTSource?
7803 if (ExternalASTSource *esrc = astContext.getExternalSource()) {
7804 const ExternalASTSource::MemoryBufferSizes &sizes =
7805 esrc->getMemoryBufferSizes();
7806
7807 createCXTUResourceUsageEntry(*entries,
7808 CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc,
7809 (unsigned long) sizes.malloc_bytes);
7810 createCXTUResourceUsageEntry(*entries,
7811 CXTUResourceUsage_ExternalASTSource_Membuffer_MMap,
7812 (unsigned long) sizes.mmap_bytes);
7813 }
7814
7815 // How much memory is being used by the Preprocessor?
7816 Preprocessor &pp = astUnit->getPreprocessor();
7817 createCXTUResourceUsageEntry(*entries,
7818 CXTUResourceUsage_Preprocessor,
7819 pp.getTotalMemory());
7820
7821 if (PreprocessingRecord *pRec = pp.getPreprocessingRecord()) {
7822 createCXTUResourceUsageEntry(*entries,
7823 CXTUResourceUsage_PreprocessingRecord,
7824 pRec->getTotalMemory());
7825 }
7826
7827 createCXTUResourceUsageEntry(*entries,
7828 CXTUResourceUsage_Preprocessor_HeaderSearch,
7829 pp.getHeaderSearchInfo().getTotalMemory());
Craig Topper69186e72014-06-08 08:38:04 +00007830
Guy Benyei11169dd2012-12-18 14:30:41 +00007831 CXTUResourceUsage usage = { (void*) entries.get(),
7832 (unsigned) entries->size(),
Alexander Kornienko6ee521c2015-01-23 15:36:10 +00007833 !entries->empty() ? &(*entries)[0] : nullptr };
Eric Fiseliere95fc442016-11-14 07:03:50 +00007834 (void)entries.release();
Guy Benyei11169dd2012-12-18 14:30:41 +00007835 return usage;
7836}
7837
7838void clang_disposeCXTUResourceUsage(CXTUResourceUsage usage) {
7839 if (usage.data)
7840 delete (MemUsageEntries*) usage.data;
7841}
7842
Argyrios Kyrtzidis0e282ef2013-12-06 18:55:45 +00007843CXSourceRangeList *clang_getSkippedRanges(CXTranslationUnit TU, CXFile file) {
7844 CXSourceRangeList *skipped = new CXSourceRangeList;
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00007845 skipped->count = 0;
Craig Topper69186e72014-06-08 08:38:04 +00007846 skipped->ranges = nullptr;
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00007847
Dmitri Gribenko852d6222014-02-11 15:02:48 +00007848 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00007849 LOG_BAD_TU(TU);
7850 return skipped;
7851 }
7852
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00007853 if (!file)
7854 return skipped;
7855
7856 ASTUnit *astUnit = cxtu::getASTUnit(TU);
7857 PreprocessingRecord *ppRec = astUnit->getPreprocessor().getPreprocessingRecord();
7858 if (!ppRec)
7859 return skipped;
7860
7861 ASTContext &Ctx = astUnit->getASTContext();
7862 SourceManager &sm = Ctx.getSourceManager();
7863 FileEntry *fileEntry = static_cast<FileEntry *>(file);
7864 FileID wantedFileID = sm.translateFile(fileEntry);
7865
7866 const std::vector<SourceRange> &SkippedRanges = ppRec->getSkippedRanges();
7867 std::vector<SourceRange> wantedRanges;
7868 for (std::vector<SourceRange>::const_iterator i = SkippedRanges.begin(), ei = SkippedRanges.end();
7869 i != ei; ++i) {
7870 if (sm.getFileID(i->getBegin()) == wantedFileID || sm.getFileID(i->getEnd()) == wantedFileID)
7871 wantedRanges.push_back(*i);
7872 }
7873
7874 skipped->count = wantedRanges.size();
7875 skipped->ranges = new CXSourceRange[skipped->count];
7876 for (unsigned i = 0, ei = skipped->count; i != ei; ++i)
7877 skipped->ranges[i] = cxloc::translateSourceRange(Ctx, wantedRanges[i]);
7878
7879 return skipped;
7880}
7881
Cameron Desrochersd8091282016-08-18 15:43:55 +00007882CXSourceRangeList *clang_getAllSkippedRanges(CXTranslationUnit TU) {
7883 CXSourceRangeList *skipped = new CXSourceRangeList;
7884 skipped->count = 0;
7885 skipped->ranges = nullptr;
7886
7887 if (isNotUsableTU(TU)) {
7888 LOG_BAD_TU(TU);
7889 return skipped;
7890 }
7891
7892 ASTUnit *astUnit = cxtu::getASTUnit(TU);
7893 PreprocessingRecord *ppRec = astUnit->getPreprocessor().getPreprocessingRecord();
7894 if (!ppRec)
7895 return skipped;
7896
7897 ASTContext &Ctx = astUnit->getASTContext();
7898
7899 const std::vector<SourceRange> &SkippedRanges = ppRec->getSkippedRanges();
7900
7901 skipped->count = SkippedRanges.size();
7902 skipped->ranges = new CXSourceRange[skipped->count];
7903 for (unsigned i = 0, ei = skipped->count; i != ei; ++i)
7904 skipped->ranges[i] = cxloc::translateSourceRange(Ctx, SkippedRanges[i]);
7905
7906 return skipped;
7907}
7908
Argyrios Kyrtzidis0e282ef2013-12-06 18:55:45 +00007909void clang_disposeSourceRangeList(CXSourceRangeList *ranges) {
7910 if (ranges) {
7911 delete[] ranges->ranges;
7912 delete ranges;
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00007913 }
7914}
7915
Guy Benyei11169dd2012-12-18 14:30:41 +00007916void clang::PrintLibclangResourceUsage(CXTranslationUnit TU) {
7917 CXTUResourceUsage Usage = clang_getCXTUResourceUsage(TU);
7918 for (unsigned I = 0; I != Usage.numEntries; ++I)
7919 fprintf(stderr, " %s: %lu\n",
7920 clang_getTUResourceUsageName(Usage.entries[I].kind),
7921 Usage.entries[I].amount);
7922
7923 clang_disposeCXTUResourceUsage(Usage);
7924}
7925
7926//===----------------------------------------------------------------------===//
7927// Misc. utility functions.
7928//===----------------------------------------------------------------------===//
7929
7930/// Default to using an 8 MB stack size on "safety" threads.
7931static unsigned SafetyStackThreadSize = 8 << 20;
7932
7933namespace clang {
7934
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00007935bool RunSafely(llvm::CrashRecoveryContext &CRC, llvm::function_ref<void()> Fn,
Guy Benyei11169dd2012-12-18 14:30:41 +00007936 unsigned Size) {
7937 if (!Size)
7938 Size = GetSafetyThreadStackSize();
7939 if (Size)
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00007940 return CRC.RunSafelyOnThread(Fn, Size);
7941 return CRC.RunSafely(Fn);
Guy Benyei11169dd2012-12-18 14:30:41 +00007942}
7943
7944unsigned GetSafetyThreadStackSize() {
7945 return SafetyStackThreadSize;
7946}
7947
7948void SetSafetyThreadStackSize(unsigned Value) {
7949 SafetyStackThreadSize = Value;
7950}
7951
Alexander Kornienkoab9db512015-06-22 23:07:51 +00007952}
Guy Benyei11169dd2012-12-18 14:30:41 +00007953
7954void clang::setThreadBackgroundPriority() {
7955 if (getenv("LIBCLANG_BGPRIO_DISABLE"))
7956 return;
7957
Alp Toker1a86ad22014-07-06 06:24:00 +00007958#ifdef USE_DARWIN_THREADS
Guy Benyei11169dd2012-12-18 14:30:41 +00007959 setpriority(PRIO_DARWIN_THREAD, 0, PRIO_DARWIN_BG);
7960#endif
7961}
7962
7963void cxindex::printDiagsToStderr(ASTUnit *Unit) {
7964 if (!Unit)
7965 return;
7966
7967 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
7968 DEnd = Unit->stored_diag_end();
7969 D != DEnd; ++D) {
Ben Langmuir749323f2014-04-22 17:40:12 +00007970 CXStoredDiagnostic Diag(*D, Unit->getLangOpts());
Guy Benyei11169dd2012-12-18 14:30:41 +00007971 CXString Msg = clang_formatDiagnostic(&Diag,
7972 clang_defaultDiagnosticDisplayOptions());
7973 fprintf(stderr, "%s\n", clang_getCString(Msg));
7974 clang_disposeString(Msg);
7975 }
7976#ifdef LLVM_ON_WIN32
7977 // On Windows, force a flush, since there may be multiple copies of
7978 // stderr and stdout in the file system, all with different buffers
7979 // but writing to the same device.
7980 fflush(stderr);
7981#endif
7982}
7983
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007984MacroInfo *cxindex::getMacroInfo(const IdentifierInfo &II,
7985 SourceLocation MacroDefLoc,
7986 CXTranslationUnit TU){
7987 if (MacroDefLoc.isInvalid() || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00007988 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007989 if (!II.hadMacroDefinition())
Craig Topper69186e72014-06-08 08:38:04 +00007990 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007991
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00007992 ASTUnit *Unit = cxtu::getASTUnit(TU);
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007993 Preprocessor &PP = Unit->getPreprocessor();
Richard Smith20e883e2015-04-29 23:20:19 +00007994 MacroDirective *MD = PP.getLocalMacroDirectiveHistory(&II);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00007995 if (MD) {
7996 for (MacroDirective::DefInfo
7997 Def = MD->getDefinition(); Def; Def = Def.getPreviousDefinition()) {
7998 if (MacroDefLoc == Def.getMacroInfo()->getDefinitionLoc())
7999 return Def.getMacroInfo();
8000 }
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008001 }
8002
Craig Topper69186e72014-06-08 08:38:04 +00008003 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008004}
8005
Richard Smith66a81862015-05-04 02:25:31 +00008006const MacroInfo *cxindex::getMacroInfo(const MacroDefinitionRecord *MacroDef,
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00008007 CXTranslationUnit TU) {
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008008 if (!MacroDef || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00008009 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008010 const IdentifierInfo *II = MacroDef->getName();
8011 if (!II)
Craig Topper69186e72014-06-08 08:38:04 +00008012 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008013
8014 return getMacroInfo(*II, MacroDef->getLocation(), TU);
8015}
8016
Richard Smith66a81862015-05-04 02:25:31 +00008017MacroDefinitionRecord *
8018cxindex::checkForMacroInMacroDefinition(const MacroInfo *MI, const Token &Tok,
8019 CXTranslationUnit TU) {
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008020 if (!MI || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00008021 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008022 if (Tok.isNot(tok::raw_identifier))
Craig Topper69186e72014-06-08 08:38:04 +00008023 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008024
8025 if (MI->getNumTokens() == 0)
Craig Topper69186e72014-06-08 08:38:04 +00008026 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008027 SourceRange DefRange(MI->getReplacementToken(0).getLocation(),
8028 MI->getDefinitionEndLoc());
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008029 ASTUnit *Unit = cxtu::getASTUnit(TU);
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008030
8031 // Check that the token is inside the definition and not its argument list.
8032 SourceManager &SM = Unit->getSourceManager();
8033 if (SM.isBeforeInTranslationUnit(Tok.getLocation(), DefRange.getBegin()))
Craig Topper69186e72014-06-08 08:38:04 +00008034 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008035 if (SM.isBeforeInTranslationUnit(DefRange.getEnd(), Tok.getLocation()))
Craig Topper69186e72014-06-08 08:38:04 +00008036 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008037
8038 Preprocessor &PP = Unit->getPreprocessor();
8039 PreprocessingRecord *PPRec = PP.getPreprocessingRecord();
8040 if (!PPRec)
Craig Topper69186e72014-06-08 08:38:04 +00008041 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008042
Alp Toker2d57cea2014-05-17 04:53:25 +00008043 IdentifierInfo &II = PP.getIdentifierTable().get(Tok.getRawIdentifier());
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008044 if (!II.hadMacroDefinition())
Craig Topper69186e72014-06-08 08:38:04 +00008045 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008046
8047 // Check that the identifier is not one of the macro arguments.
8048 if (std::find(MI->arg_begin(), MI->arg_end(), &II) != MI->arg_end())
Craig Topper69186e72014-06-08 08:38:04 +00008049 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008050
Richard Smith20e883e2015-04-29 23:20:19 +00008051 MacroDirective *InnerMD = PP.getLocalMacroDirectiveHistory(&II);
Argyrios Kyrtzidis09c9e812013-02-20 00:54:57 +00008052 if (!InnerMD)
Craig Topper69186e72014-06-08 08:38:04 +00008053 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008054
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00008055 return PPRec->findMacroDefinition(InnerMD->getMacroInfo());
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008056}
8057
Richard Smith66a81862015-05-04 02:25:31 +00008058MacroDefinitionRecord *
8059cxindex::checkForMacroInMacroDefinition(const MacroInfo *MI, SourceLocation Loc,
8060 CXTranslationUnit TU) {
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008061 if (Loc.isInvalid() || !MI || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00008062 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008063
8064 if (MI->getNumTokens() == 0)
Craig Topper69186e72014-06-08 08:38:04 +00008065 return nullptr;
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008066 ASTUnit *Unit = cxtu::getASTUnit(TU);
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008067 Preprocessor &PP = Unit->getPreprocessor();
8068 if (!PP.getPreprocessingRecord())
Craig Topper69186e72014-06-08 08:38:04 +00008069 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008070 Loc = Unit->getSourceManager().getSpellingLoc(Loc);
8071 Token Tok;
8072 if (PP.getRawToken(Loc, Tok))
Craig Topper69186e72014-06-08 08:38:04 +00008073 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008074
8075 return checkForMacroInMacroDefinition(MI, Tok, TU);
8076}
8077
Guy Benyei11169dd2012-12-18 14:30:41 +00008078CXString clang_getClangVersion() {
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00008079 return cxstring::createDup(getClangFullVersion());
Guy Benyei11169dd2012-12-18 14:30:41 +00008080}
8081
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008082Logger &cxindex::Logger::operator<<(CXTranslationUnit TU) {
8083 if (TU) {
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008084 if (ASTUnit *Unit = cxtu::getASTUnit(TU)) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008085 LogOS << '<' << Unit->getMainFileName() << '>';
Argyrios Kyrtzidis37f2ab42013-03-05 20:21:14 +00008086 if (Unit->isMainFileAST())
8087 LogOS << " (" << Unit->getASTFileName() << ')';
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008088 return *this;
8089 }
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00008090 } else {
8091 LogOS << "<NULL TU>";
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008092 }
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008093 return *this;
8094}
8095
Argyrios Kyrtzidisba4b5f82013-03-08 02:32:26 +00008096Logger &cxindex::Logger::operator<<(const FileEntry *FE) {
8097 *this << FE->getName();
8098 return *this;
8099}
8100
8101Logger &cxindex::Logger::operator<<(CXCursor cursor) {
8102 CXString cursorName = clang_getCursorDisplayName(cursor);
8103 *this << cursorName << "@" << clang_getCursorLocation(cursor);
8104 clang_disposeString(cursorName);
8105 return *this;
8106}
8107
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008108Logger &cxindex::Logger::operator<<(CXSourceLocation Loc) {
8109 CXFile File;
8110 unsigned Line, Column;
Craig Topper69186e72014-06-08 08:38:04 +00008111 clang_getFileLocation(Loc, &File, &Line, &Column, nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008112 CXString FileName = clang_getFileName(File);
8113 *this << llvm::format("(%s:%d:%d)", clang_getCString(FileName), Line, Column);
8114 clang_disposeString(FileName);
8115 return *this;
8116}
8117
8118Logger &cxindex::Logger::operator<<(CXSourceRange range) {
8119 CXSourceLocation BLoc = clang_getRangeStart(range);
8120 CXSourceLocation ELoc = clang_getRangeEnd(range);
8121
8122 CXFile BFile;
8123 unsigned BLine, BColumn;
Craig Topper69186e72014-06-08 08:38:04 +00008124 clang_getFileLocation(BLoc, &BFile, &BLine, &BColumn, nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008125
8126 CXFile EFile;
8127 unsigned ELine, EColumn;
Craig Topper69186e72014-06-08 08:38:04 +00008128 clang_getFileLocation(ELoc, &EFile, &ELine, &EColumn, nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008129
8130 CXString BFileName = clang_getFileName(BFile);
8131 if (BFile == EFile) {
8132 *this << llvm::format("[%s %d:%d-%d:%d]", clang_getCString(BFileName),
8133 BLine, BColumn, ELine, EColumn);
8134 } else {
8135 CXString EFileName = clang_getFileName(EFile);
8136 *this << llvm::format("[%s:%d:%d - ", clang_getCString(BFileName),
8137 BLine, BColumn)
8138 << llvm::format("%s:%d:%d]", clang_getCString(EFileName),
8139 ELine, EColumn);
8140 clang_disposeString(EFileName);
8141 }
8142 clang_disposeString(BFileName);
8143 return *this;
8144}
8145
8146Logger &cxindex::Logger::operator<<(CXString Str) {
8147 *this << clang_getCString(Str);
8148 return *this;
8149}
8150
8151Logger &cxindex::Logger::operator<<(const llvm::format_object_base &Fmt) {
8152 LogOS << Fmt;
8153 return *this;
8154}
8155
Chandler Carruth37ad2582014-06-27 15:14:39 +00008156static llvm::ManagedStatic<llvm::sys::Mutex> LoggingMutex;
8157
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008158cxindex::Logger::~Logger() {
Chandler Carruth37ad2582014-06-27 15:14:39 +00008159 llvm::sys::ScopedLock L(*LoggingMutex);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008160
8161 static llvm::TimeRecord sBeginTR = llvm::TimeRecord::getCurrentTime();
8162
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008163 raw_ostream &OS = llvm::errs();
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008164 OS << "[libclang:" << Name << ':';
8165
Alp Toker1a86ad22014-07-06 06:24:00 +00008166#ifdef USE_DARWIN_THREADS
8167 // TODO: Portability.
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008168 mach_port_t tid = pthread_mach_thread_np(pthread_self());
8169 OS << tid << ':';
8170#endif
8171
8172 llvm::TimeRecord TR = llvm::TimeRecord::getCurrentTime();
8173 OS << llvm::format("%7.4f] ", TR.getWallTime() - sBeginTR.getWallTime());
Yaron Keren09fb7c62015-03-10 07:33:23 +00008174 OS << Msg << '\n';
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008175
8176 if (Trace) {
Zachary Turner1fe2a8d2015-03-05 19:15:09 +00008177 llvm::sys::PrintStackTrace(OS);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008178 OS << "--------------------------------------------------\n";
8179 }
8180}
Benjamin Kramerc1ffdab2016-03-03 08:58:18 +00008181
8182#ifdef CLANG_TOOL_EXTRA_BUILD
8183// This anchor is used to force the linker to link the clang-tidy plugin.
8184extern volatile int ClangTidyPluginAnchorSource;
8185static int LLVM_ATTRIBUTE_UNUSED ClangTidyPluginAnchorDestination =
8186 ClangTidyPluginAnchorSource;
Benjamin Kramer9eba7352016-11-17 15:22:36 +00008187
8188// This anchor is used to force the linker to link the clang-include-fixer
8189// plugin.
8190extern volatile int ClangIncludeFixerPluginAnchorSource;
8191static int LLVM_ATTRIBUTE_UNUSED ClangIncludeFixerPluginAnchorDestination =
8192 ClangIncludeFixerPluginAnchorSource;
Benjamin Kramerc1ffdab2016-03-03 08:58:18 +00008193#endif