blob: 48a0a332cf35e6be0a6e7778c6a4b08c75363419 [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) {
2116 Visitor->AddStmt(C->getNumThreads());
2117}
2118
Alexey Bataev62c87d22014-03-21 04:51:18 +00002119void OMPClauseEnqueue::VisitOMPSafelenClause(const OMPSafelenClause *C) {
2120 Visitor->AddStmt(C->getSafelen());
2121}
2122
Alexey Bataev66b15b52015-08-21 11:14:16 +00002123void OMPClauseEnqueue::VisitOMPSimdlenClause(const OMPSimdlenClause *C) {
2124 Visitor->AddStmt(C->getSimdlen());
2125}
2126
Alexander Musman8bd31e62014-05-27 15:12:19 +00002127void OMPClauseEnqueue::VisitOMPCollapseClause(const OMPCollapseClause *C) {
2128 Visitor->AddStmt(C->getNumForLoops());
2129}
2130
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002131void OMPClauseEnqueue::VisitOMPDefaultClause(const OMPDefaultClause *C) { }
Alexey Bataev756c1962013-09-24 03:17:45 +00002132
Alexey Bataevbcbadb62014-05-06 06:04:14 +00002133void OMPClauseEnqueue::VisitOMPProcBindClause(const OMPProcBindClause *C) { }
2134
Alexey Bataev56dafe82014-06-20 07:16:17 +00002135void OMPClauseEnqueue::VisitOMPScheduleClause(const OMPScheduleClause *C) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002136 VisitOMPClauseWithPreInit(C);
Alexey Bataev56dafe82014-06-20 07:16:17 +00002137 Visitor->AddStmt(C->getChunkSize());
2138}
2139
Alexey Bataev10e775f2015-07-30 11:36:16 +00002140void OMPClauseEnqueue::VisitOMPOrderedClause(const OMPOrderedClause *C) {
2141 Visitor->AddStmt(C->getNumForLoops());
2142}
Alexey Bataev142e1fc2014-06-20 09:44:06 +00002143
Alexey Bataev236070f2014-06-20 11:19:47 +00002144void OMPClauseEnqueue::VisitOMPNowaitClause(const OMPNowaitClause *) {}
2145
Alexey Bataev7aea99a2014-07-17 12:19:31 +00002146void OMPClauseEnqueue::VisitOMPUntiedClause(const OMPUntiedClause *) {}
2147
Alexey Bataev74ba3a52014-07-17 12:47:03 +00002148void OMPClauseEnqueue::VisitOMPMergeableClause(const OMPMergeableClause *) {}
2149
Alexey Bataevf98b00c2014-07-23 02:27:21 +00002150void OMPClauseEnqueue::VisitOMPReadClause(const OMPReadClause *) {}
2151
Alexey Bataevdea47612014-07-23 07:46:59 +00002152void OMPClauseEnqueue::VisitOMPWriteClause(const OMPWriteClause *) {}
2153
Alexey Bataev67a4f222014-07-23 10:25:33 +00002154void OMPClauseEnqueue::VisitOMPUpdateClause(const OMPUpdateClause *) {}
2155
Alexey Bataev459dec02014-07-24 06:46:57 +00002156void OMPClauseEnqueue::VisitOMPCaptureClause(const OMPCaptureClause *) {}
2157
Alexey Bataev82bad8b2014-07-24 08:55:34 +00002158void OMPClauseEnqueue::VisitOMPSeqCstClause(const OMPSeqCstClause *) {}
2159
Alexey Bataev346265e2015-09-25 10:37:12 +00002160void OMPClauseEnqueue::VisitOMPThreadsClause(const OMPThreadsClause *) {}
2161
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002162void OMPClauseEnqueue::VisitOMPSIMDClause(const OMPSIMDClause *) {}
2163
Alexey Bataevb825de12015-12-07 10:51:44 +00002164void OMPClauseEnqueue::VisitOMPNogroupClause(const OMPNogroupClause *) {}
2165
Michael Wonge710d542015-08-07 16:16:36 +00002166void OMPClauseEnqueue::VisitOMPDeviceClause(const OMPDeviceClause *C) {
2167 Visitor->AddStmt(C->getDevice());
2168}
2169
Kelvin Li099bb8c2015-11-24 20:50:12 +00002170void OMPClauseEnqueue::VisitOMPNumTeamsClause(const OMPNumTeamsClause *C) {
2171 Visitor->AddStmt(C->getNumTeams());
2172}
2173
Kelvin Lia15fb1a2015-11-27 18:47:36 +00002174void OMPClauseEnqueue::VisitOMPThreadLimitClause(const OMPThreadLimitClause *C) {
2175 Visitor->AddStmt(C->getThreadLimit());
2176}
2177
Alexey Bataeva0569352015-12-01 10:17:31 +00002178void OMPClauseEnqueue::VisitOMPPriorityClause(const OMPPriorityClause *C) {
2179 Visitor->AddStmt(C->getPriority());
2180}
2181
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00002182void OMPClauseEnqueue::VisitOMPGrainsizeClause(const OMPGrainsizeClause *C) {
2183 Visitor->AddStmt(C->getGrainsize());
2184}
2185
Alexey Bataev382967a2015-12-08 12:06:20 +00002186void OMPClauseEnqueue::VisitOMPNumTasksClause(const OMPNumTasksClause *C) {
2187 Visitor->AddStmt(C->getNumTasks());
2188}
2189
Alexey Bataev28c75412015-12-15 08:19:24 +00002190void OMPClauseEnqueue::VisitOMPHintClause(const OMPHintClause *C) {
2191 Visitor->AddStmt(C->getHint());
2192}
2193
Alexey Bataev756c1962013-09-24 03:17:45 +00002194template<typename T>
2195void OMPClauseEnqueue::VisitOMPClauseList(T *Node) {
Alexey Bataev03b340a2014-10-21 03:16:40 +00002196 for (const auto *I : Node->varlists()) {
Aaron Ballman2205d2a2014-03-14 15:55:35 +00002197 Visitor->AddStmt(I);
Alexey Bataev03b340a2014-10-21 03:16:40 +00002198 }
Alexey Bataev756c1962013-09-24 03:17:45 +00002199}
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002200
2201void OMPClauseEnqueue::VisitOMPPrivateClause(const OMPPrivateClause *C) {
Alexey Bataev756c1962013-09-24 03:17:45 +00002202 VisitOMPClauseList(C);
Alexey Bataev03b340a2014-10-21 03:16:40 +00002203 for (const auto *E : C->private_copies()) {
2204 Visitor->AddStmt(E);
2205 }
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002206}
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002207void OMPClauseEnqueue::VisitOMPFirstprivateClause(
2208 const OMPFirstprivateClause *C) {
2209 VisitOMPClauseList(C);
Alexey Bataev417089f2016-02-17 13:19:37 +00002210 VisitOMPClauseWithPreInit(C);
2211 for (const auto *E : C->private_copies()) {
2212 Visitor->AddStmt(E);
2213 }
2214 for (const auto *E : C->inits()) {
2215 Visitor->AddStmt(E);
2216 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002217}
Alexander Musman1bb328c2014-06-04 13:06:39 +00002218void OMPClauseEnqueue::VisitOMPLastprivateClause(
2219 const OMPLastprivateClause *C) {
2220 VisitOMPClauseList(C);
Alexey Bataev005248a2016-02-25 05:25:57 +00002221 VisitOMPClauseWithPostUpdate(C);
Alexey Bataev38e89532015-04-16 04:54:05 +00002222 for (auto *E : C->private_copies()) {
2223 Visitor->AddStmt(E);
2224 }
2225 for (auto *E : C->source_exprs()) {
2226 Visitor->AddStmt(E);
2227 }
2228 for (auto *E : C->destination_exprs()) {
2229 Visitor->AddStmt(E);
2230 }
2231 for (auto *E : C->assignment_ops()) {
2232 Visitor->AddStmt(E);
2233 }
Alexander Musman1bb328c2014-06-04 13:06:39 +00002234}
Alexey Bataev758e55e2013-09-06 18:03:48 +00002235void OMPClauseEnqueue::VisitOMPSharedClause(const OMPSharedClause *C) {
Alexey Bataev756c1962013-09-24 03:17:45 +00002236 VisitOMPClauseList(C);
Alexey Bataev758e55e2013-09-06 18:03:48 +00002237}
Alexey Bataevc5e02582014-06-16 07:08:35 +00002238void OMPClauseEnqueue::VisitOMPReductionClause(const OMPReductionClause *C) {
2239 VisitOMPClauseList(C);
Alexey Bataev61205072016-03-02 04:57:40 +00002240 VisitOMPClauseWithPostUpdate(C);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00002241 for (auto *E : C->privates()) {
2242 Visitor->AddStmt(E);
2243 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002244 for (auto *E : C->lhs_exprs()) {
2245 Visitor->AddStmt(E);
2246 }
2247 for (auto *E : C->rhs_exprs()) {
2248 Visitor->AddStmt(E);
2249 }
2250 for (auto *E : C->reduction_ops()) {
2251 Visitor->AddStmt(E);
2252 }
Alexey Bataevc5e02582014-06-16 07:08:35 +00002253}
Alexander Musman8dba6642014-04-22 13:09:42 +00002254void OMPClauseEnqueue::VisitOMPLinearClause(const OMPLinearClause *C) {
2255 VisitOMPClauseList(C);
Alexey Bataev78849fb2016-03-09 09:49:00 +00002256 VisitOMPClauseWithPostUpdate(C);
Alexey Bataevbd9fec12015-08-18 06:47:21 +00002257 for (const auto *E : C->privates()) {
2258 Visitor->AddStmt(E);
2259 }
Alexander Musman3276a272015-03-21 10:12:56 +00002260 for (const auto *E : C->inits()) {
2261 Visitor->AddStmt(E);
2262 }
2263 for (const auto *E : C->updates()) {
2264 Visitor->AddStmt(E);
2265 }
2266 for (const auto *E : C->finals()) {
2267 Visitor->AddStmt(E);
2268 }
Alexander Musman8dba6642014-04-22 13:09:42 +00002269 Visitor->AddStmt(C->getStep());
Alexander Musman3276a272015-03-21 10:12:56 +00002270 Visitor->AddStmt(C->getCalcStep());
Alexander Musman8dba6642014-04-22 13:09:42 +00002271}
Alexander Musmanf0d76e72014-05-29 14:36:25 +00002272void OMPClauseEnqueue::VisitOMPAlignedClause(const OMPAlignedClause *C) {
2273 VisitOMPClauseList(C);
2274 Visitor->AddStmt(C->getAlignment());
2275}
Alexey Bataevd48bcd82014-03-31 03:36:38 +00002276void OMPClauseEnqueue::VisitOMPCopyinClause(const OMPCopyinClause *C) {
2277 VisitOMPClauseList(C);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00002278 for (auto *E : C->source_exprs()) {
2279 Visitor->AddStmt(E);
2280 }
2281 for (auto *E : C->destination_exprs()) {
2282 Visitor->AddStmt(E);
2283 }
2284 for (auto *E : C->assignment_ops()) {
2285 Visitor->AddStmt(E);
2286 }
Alexey Bataevd48bcd82014-03-31 03:36:38 +00002287}
Alexey Bataevbae9a792014-06-27 10:37:06 +00002288void
2289OMPClauseEnqueue::VisitOMPCopyprivateClause(const OMPCopyprivateClause *C) {
2290 VisitOMPClauseList(C);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002291 for (auto *E : C->source_exprs()) {
2292 Visitor->AddStmt(E);
2293 }
2294 for (auto *E : C->destination_exprs()) {
2295 Visitor->AddStmt(E);
2296 }
2297 for (auto *E : C->assignment_ops()) {
2298 Visitor->AddStmt(E);
2299 }
Alexey Bataevbae9a792014-06-27 10:37:06 +00002300}
Alexey Bataev6125da92014-07-21 11:26:11 +00002301void OMPClauseEnqueue::VisitOMPFlushClause(const OMPFlushClause *C) {
2302 VisitOMPClauseList(C);
2303}
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00002304void OMPClauseEnqueue::VisitOMPDependClause(const OMPDependClause *C) {
2305 VisitOMPClauseList(C);
2306}
Kelvin Li0bff7af2015-11-23 05:32:03 +00002307void OMPClauseEnqueue::VisitOMPMapClause(const OMPMapClause *C) {
2308 VisitOMPClauseList(C);
2309}
Carlo Bertollib4adf552016-01-15 18:50:31 +00002310void OMPClauseEnqueue::VisitOMPDistScheduleClause(
2311 const OMPDistScheduleClause *C) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002312 VisitOMPClauseWithPreInit(C);
Carlo Bertollib4adf552016-01-15 18:50:31 +00002313 Visitor->AddStmt(C->getChunkSize());
Carlo Bertollib4adf552016-01-15 18:50:31 +00002314}
Alexey Bataev3392d762016-02-16 11:18:12 +00002315void OMPClauseEnqueue::VisitOMPDefaultmapClause(
2316 const OMPDefaultmapClause * /*C*/) {}
Samuel Antao661c0902016-05-26 17:39:58 +00002317void OMPClauseEnqueue::VisitOMPToClause(const OMPToClause *C) {
2318 VisitOMPClauseList(C);
2319}
Samuel Antaoec172c62016-05-26 17:49:04 +00002320void OMPClauseEnqueue::VisitOMPFromClause(const OMPFromClause *C) {
2321 VisitOMPClauseList(C);
2322}
Carlo Bertolli2404b172016-07-13 15:37:16 +00002323void OMPClauseEnqueue::VisitOMPUseDevicePtrClause(const OMPUseDevicePtrClause *C) {
2324 VisitOMPClauseList(C);
2325}
Carlo Bertolli70594e92016-07-13 17:16:49 +00002326void OMPClauseEnqueue::VisitOMPIsDevicePtrClause(const OMPIsDevicePtrClause *C) {
2327 VisitOMPClauseList(C);
2328}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002329}
Alexey Bataev756c1962013-09-24 03:17:45 +00002330
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002331void EnqueueVisitor::EnqueueChildren(const OMPClause *S) {
2332 unsigned size = WL.size();
2333 OMPClauseEnqueue Visitor(this);
2334 Visitor.Visit(S);
2335 if (size == WL.size())
2336 return;
2337 // Now reverse the entries we just added. This will match the DFS
2338 // ordering performed by the worklist.
2339 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2340 std::reverse(I, E);
2341}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002342void EnqueueVisitor::VisitAddrLabelExpr(const AddrLabelExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002343 WL.push_back(LabelRefVisit(E->getLabel(), E->getLabelLoc(), Parent));
2344}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002345void EnqueueVisitor::VisitBlockExpr(const BlockExpr *B) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002346 AddDecl(B->getBlockDecl());
2347}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002348void EnqueueVisitor::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002349 EnqueueChildren(E);
2350 AddTypeLoc(E->getTypeSourceInfo());
2351}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002352void EnqueueVisitor::VisitCompoundStmt(const CompoundStmt *S) {
Pete Cooper57d3f142015-07-30 17:22:52 +00002353 for (auto &I : llvm::reverse(S->body()))
2354 AddStmt(I);
Guy Benyei11169dd2012-12-18 14:30:41 +00002355}
2356void EnqueueVisitor::
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002357VisitMSDependentExistsStmt(const MSDependentExistsStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002358 AddStmt(S->getSubStmt());
2359 AddDeclarationNameInfo(S);
2360 if (NestedNameSpecifierLoc QualifierLoc = S->getQualifierLoc())
2361 AddNestedNameSpecifierLoc(QualifierLoc);
2362}
2363
2364void EnqueueVisitor::
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002365VisitCXXDependentScopeMemberExpr(const CXXDependentScopeMemberExpr *E) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002366 if (E->hasExplicitTemplateArgs())
2367 AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002368 AddDeclarationNameInfo(E);
2369 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
2370 AddNestedNameSpecifierLoc(QualifierLoc);
2371 if (!E->isImplicitAccess())
2372 AddStmt(E->getBase());
2373}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002374void EnqueueVisitor::VisitCXXNewExpr(const CXXNewExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002375 // Enqueue the initializer , if any.
2376 AddStmt(E->getInitializer());
2377 // Enqueue the array size, if any.
2378 AddStmt(E->getArraySize());
2379 // Enqueue the allocated type.
2380 AddTypeLoc(E->getAllocatedTypeSourceInfo());
2381 // Enqueue the placement arguments.
2382 for (unsigned I = E->getNumPlacementArgs(); I > 0; --I)
2383 AddStmt(E->getPlacementArg(I-1));
2384}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002385void EnqueueVisitor::VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CE) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002386 for (unsigned I = CE->getNumArgs(); I > 1 /* Yes, this is 1 */; --I)
2387 AddStmt(CE->getArg(I-1));
2388 AddStmt(CE->getCallee());
2389 AddStmt(CE->getArg(0));
2390}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002391void EnqueueVisitor::VisitCXXPseudoDestructorExpr(
2392 const CXXPseudoDestructorExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002393 // Visit the name of the type being destroyed.
2394 AddTypeLoc(E->getDestroyedTypeInfo());
2395 // Visit the scope type that looks disturbingly like the nested-name-specifier
2396 // but isn't.
2397 AddTypeLoc(E->getScopeTypeInfo());
2398 // Visit the nested-name-specifier.
2399 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
2400 AddNestedNameSpecifierLoc(QualifierLoc);
2401 // Visit base expression.
2402 AddStmt(E->getBase());
2403}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002404void EnqueueVisitor::VisitCXXScalarValueInitExpr(
2405 const CXXScalarValueInitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002406 AddTypeLoc(E->getTypeSourceInfo());
2407}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002408void EnqueueVisitor::VisitCXXTemporaryObjectExpr(
2409 const CXXTemporaryObjectExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002410 EnqueueChildren(E);
2411 AddTypeLoc(E->getTypeSourceInfo());
2412}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002413void EnqueueVisitor::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002414 EnqueueChildren(E);
2415 if (E->isTypeOperand())
2416 AddTypeLoc(E->getTypeOperandSourceInfo());
2417}
2418
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002419void EnqueueVisitor::VisitCXXUnresolvedConstructExpr(
2420 const CXXUnresolvedConstructExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002421 EnqueueChildren(E);
2422 AddTypeLoc(E->getTypeSourceInfo());
2423}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002424void EnqueueVisitor::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002425 EnqueueChildren(E);
2426 if (E->isTypeOperand())
2427 AddTypeLoc(E->getTypeOperandSourceInfo());
2428}
2429
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002430void EnqueueVisitor::VisitCXXCatchStmt(const CXXCatchStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002431 EnqueueChildren(S);
2432 AddDecl(S->getExceptionDecl());
2433}
2434
Argyrios Kyrtzidis99891242014-11-13 09:03:21 +00002435void EnqueueVisitor::VisitCXXForRangeStmt(const CXXForRangeStmt *S) {
Argyrios Kyrtzidiscde70692014-11-13 09:50:19 +00002436 AddStmt(S->getBody());
Argyrios Kyrtzidis99891242014-11-13 09:03:21 +00002437 AddStmt(S->getRangeInit());
Argyrios Kyrtzidiscde70692014-11-13 09:50:19 +00002438 AddDecl(S->getLoopVariable());
Argyrios Kyrtzidis99891242014-11-13 09:03:21 +00002439}
2440
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002441void EnqueueVisitor::VisitDeclRefExpr(const DeclRefExpr *DR) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002442 if (DR->hasExplicitTemplateArgs())
2443 AddExplicitTemplateArgs(DR->getTemplateArgs(), DR->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002444 WL.push_back(DeclRefExprParts(DR, Parent));
2445}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002446void EnqueueVisitor::VisitDependentScopeDeclRefExpr(
2447 const DependentScopeDeclRefExpr *E) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002448 if (E->hasExplicitTemplateArgs())
2449 AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002450 AddDeclarationNameInfo(E);
2451 AddNestedNameSpecifierLoc(E->getQualifierLoc());
2452}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002453void EnqueueVisitor::VisitDeclStmt(const DeclStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002454 unsigned size = WL.size();
2455 bool isFirst = true;
Aaron Ballman535bbcc2014-03-14 17:01:24 +00002456 for (const auto *D : S->decls()) {
2457 AddDecl(D, isFirst);
Guy Benyei11169dd2012-12-18 14:30:41 +00002458 isFirst = false;
2459 }
2460 if (size == WL.size())
2461 return;
2462 // Now reverse the entries we just added. This will match the DFS
2463 // ordering performed by the worklist.
2464 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2465 std::reverse(I, E);
2466}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002467void EnqueueVisitor::VisitDesignatedInitExpr(const DesignatedInitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002468 AddStmt(E->getInit());
David Majnemerf7e36092016-06-23 00:15:04 +00002469 for (const DesignatedInitExpr::Designator &D :
2470 llvm::reverse(E->designators())) {
2471 if (D.isFieldDesignator()) {
2472 if (FieldDecl *Field = D.getField())
2473 AddMemberRef(Field, D.getFieldLoc());
Guy Benyei11169dd2012-12-18 14:30:41 +00002474 continue;
2475 }
David Majnemerf7e36092016-06-23 00:15:04 +00002476 if (D.isArrayDesignator()) {
2477 AddStmt(E->getArrayIndex(D));
Guy Benyei11169dd2012-12-18 14:30:41 +00002478 continue;
2479 }
David Majnemerf7e36092016-06-23 00:15:04 +00002480 assert(D.isArrayRangeDesignator() && "Unknown designator kind");
2481 AddStmt(E->getArrayRangeEnd(D));
2482 AddStmt(E->getArrayRangeStart(D));
Guy Benyei11169dd2012-12-18 14:30:41 +00002483 }
2484}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002485void EnqueueVisitor::VisitExplicitCastExpr(const ExplicitCastExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002486 EnqueueChildren(E);
2487 AddTypeLoc(E->getTypeInfoAsWritten());
2488}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002489void EnqueueVisitor::VisitForStmt(const ForStmt *FS) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002490 AddStmt(FS->getBody());
2491 AddStmt(FS->getInc());
2492 AddStmt(FS->getCond());
2493 AddDecl(FS->getConditionVariable());
2494 AddStmt(FS->getInit());
2495}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002496void EnqueueVisitor::VisitGotoStmt(const GotoStmt *GS) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002497 WL.push_back(LabelRefVisit(GS->getLabel(), GS->getLabelLoc(), Parent));
2498}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002499void EnqueueVisitor::VisitIfStmt(const IfStmt *If) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002500 AddStmt(If->getElse());
2501 AddStmt(If->getThen());
2502 AddStmt(If->getCond());
2503 AddDecl(If->getConditionVariable());
2504}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002505void EnqueueVisitor::VisitInitListExpr(const InitListExpr *IE) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002506 // We care about the syntactic form of the initializer list, only.
2507 if (InitListExpr *Syntactic = IE->getSyntacticForm())
2508 IE = Syntactic;
2509 EnqueueChildren(IE);
2510}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002511void EnqueueVisitor::VisitMemberExpr(const MemberExpr *M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002512 WL.push_back(MemberExprParts(M, Parent));
2513
2514 // If the base of the member access expression is an implicit 'this', don't
2515 // visit it.
2516 // FIXME: If we ever want to show these implicit accesses, this will be
2517 // unfortunate. However, clang_getCursor() relies on this behavior.
Argyrios Kyrtzidis58d0e7a2015-03-13 04:40:07 +00002518 if (M->isImplicitAccess())
2519 return;
2520
2521 // Ignore base anonymous struct/union fields, otherwise they will shadow the
2522 // real field that that we are interested in.
2523 if (auto *SubME = dyn_cast<MemberExpr>(M->getBase())) {
2524 if (auto *FD = dyn_cast_or_null<FieldDecl>(SubME->getMemberDecl())) {
2525 if (FD->isAnonymousStructOrUnion()) {
2526 AddStmt(SubME->getBase());
2527 return;
2528 }
2529 }
2530 }
2531
2532 AddStmt(M->getBase());
Guy Benyei11169dd2012-12-18 14:30:41 +00002533}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002534void EnqueueVisitor::VisitObjCEncodeExpr(const ObjCEncodeExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002535 AddTypeLoc(E->getEncodedTypeSourceInfo());
2536}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002537void EnqueueVisitor::VisitObjCMessageExpr(const ObjCMessageExpr *M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002538 EnqueueChildren(M);
2539 AddTypeLoc(M->getClassReceiverTypeInfo());
2540}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002541void EnqueueVisitor::VisitOffsetOfExpr(const OffsetOfExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002542 // Visit the components of the offsetof expression.
2543 for (unsigned N = E->getNumComponents(), I = N; I > 0; --I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002544 const OffsetOfNode &Node = E->getComponent(I-1);
2545 switch (Node.getKind()) {
2546 case OffsetOfNode::Array:
2547 AddStmt(E->getIndexExpr(Node.getArrayExprIndex()));
2548 break;
2549 case OffsetOfNode::Field:
2550 AddMemberRef(Node.getField(), Node.getSourceRange().getEnd());
2551 break;
2552 case OffsetOfNode::Identifier:
2553 case OffsetOfNode::Base:
2554 continue;
2555 }
2556 }
2557 // Visit the type into which we're computing the offset.
2558 AddTypeLoc(E->getTypeSourceInfo());
2559}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002560void EnqueueVisitor::VisitOverloadExpr(const OverloadExpr *E) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002561 if (E->hasExplicitTemplateArgs())
2562 AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002563 WL.push_back(OverloadExprParts(E, Parent));
2564}
2565void EnqueueVisitor::VisitUnaryExprOrTypeTraitExpr(
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002566 const UnaryExprOrTypeTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002567 EnqueueChildren(E);
2568 if (E->isArgumentType())
2569 AddTypeLoc(E->getArgumentTypeInfo());
2570}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002571void EnqueueVisitor::VisitStmt(const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002572 EnqueueChildren(S);
2573}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002574void EnqueueVisitor::VisitSwitchStmt(const SwitchStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002575 AddStmt(S->getBody());
2576 AddStmt(S->getCond());
2577 AddDecl(S->getConditionVariable());
2578}
2579
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002580void EnqueueVisitor::VisitWhileStmt(const WhileStmt *W) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002581 AddStmt(W->getBody());
2582 AddStmt(W->getCond());
2583 AddDecl(W->getConditionVariable());
2584}
2585
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002586void EnqueueVisitor::VisitTypeTraitExpr(const TypeTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002587 for (unsigned I = E->getNumArgs(); I > 0; --I)
2588 AddTypeLoc(E->getArg(I-1));
2589}
2590
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002591void EnqueueVisitor::VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002592 AddTypeLoc(E->getQueriedTypeSourceInfo());
2593}
2594
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002595void EnqueueVisitor::VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002596 EnqueueChildren(E);
2597}
2598
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002599void EnqueueVisitor::VisitUnresolvedMemberExpr(const UnresolvedMemberExpr *U) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002600 VisitOverloadExpr(U);
2601 if (!U->isImplicitAccess())
2602 AddStmt(U->getBase());
2603}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002604void EnqueueVisitor::VisitVAArgExpr(const VAArgExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002605 AddStmt(E->getSubExpr());
2606 AddTypeLoc(E->getWrittenTypeInfo());
2607}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002608void EnqueueVisitor::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002609 WL.push_back(SizeOfPackExprParts(E, Parent));
2610}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002611void EnqueueVisitor::VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002612 // If the opaque value has a source expression, just transparently
2613 // visit that. This is useful for (e.g.) pseudo-object expressions.
2614 if (Expr *SourceExpr = E->getSourceExpr())
2615 return Visit(SourceExpr);
2616}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002617void EnqueueVisitor::VisitLambdaExpr(const LambdaExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002618 AddStmt(E->getBody());
2619 WL.push_back(LambdaExprParts(E, Parent));
2620}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002621void EnqueueVisitor::VisitPseudoObjectExpr(const PseudoObjectExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002622 // Treat the expression like its syntactic form.
2623 Visit(E->getSyntacticForm());
2624}
2625
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002626void EnqueueVisitor::VisitOMPExecutableDirective(
2627 const OMPExecutableDirective *D) {
2628 EnqueueChildren(D);
2629 for (ArrayRef<OMPClause *>::iterator I = D->clauses().begin(),
2630 E = D->clauses().end();
2631 I != E; ++I)
2632 EnqueueChildren(*I);
2633}
2634
Alexander Musman3aaab662014-08-19 11:27:13 +00002635void EnqueueVisitor::VisitOMPLoopDirective(const OMPLoopDirective *D) {
2636 VisitOMPExecutableDirective(D);
2637}
2638
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002639void EnqueueVisitor::VisitOMPParallelDirective(const OMPParallelDirective *D) {
2640 VisitOMPExecutableDirective(D);
2641}
2642
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002643void EnqueueVisitor::VisitOMPSimdDirective(const OMPSimdDirective *D) {
Alexander Musman3aaab662014-08-19 11:27:13 +00002644 VisitOMPLoopDirective(D);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002645}
2646
Alexey Bataevf29276e2014-06-18 04:14:57 +00002647void EnqueueVisitor::VisitOMPForDirective(const OMPForDirective *D) {
Alexander Musman3aaab662014-08-19 11:27:13 +00002648 VisitOMPLoopDirective(D);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002649}
2650
Alexander Musmanf82886e2014-09-18 05:12:34 +00002651void EnqueueVisitor::VisitOMPForSimdDirective(const OMPForSimdDirective *D) {
2652 VisitOMPLoopDirective(D);
2653}
2654
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002655void EnqueueVisitor::VisitOMPSectionsDirective(const OMPSectionsDirective *D) {
2656 VisitOMPExecutableDirective(D);
2657}
2658
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002659void EnqueueVisitor::VisitOMPSectionDirective(const OMPSectionDirective *D) {
2660 VisitOMPExecutableDirective(D);
2661}
2662
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00002663void EnqueueVisitor::VisitOMPSingleDirective(const OMPSingleDirective *D) {
2664 VisitOMPExecutableDirective(D);
2665}
2666
Alexander Musman80c22892014-07-17 08:54:58 +00002667void EnqueueVisitor::VisitOMPMasterDirective(const OMPMasterDirective *D) {
2668 VisitOMPExecutableDirective(D);
2669}
2670
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002671void EnqueueVisitor::VisitOMPCriticalDirective(const OMPCriticalDirective *D) {
2672 VisitOMPExecutableDirective(D);
2673 AddDeclarationNameInfo(D);
2674}
2675
Alexey Bataev4acb8592014-07-07 13:01:15 +00002676void
2677EnqueueVisitor::VisitOMPParallelForDirective(const OMPParallelForDirective *D) {
Alexander Musman3aaab662014-08-19 11:27:13 +00002678 VisitOMPLoopDirective(D);
Alexey Bataev4acb8592014-07-07 13:01:15 +00002679}
2680
Alexander Musmane4e893b2014-09-23 09:33:00 +00002681void EnqueueVisitor::VisitOMPParallelForSimdDirective(
2682 const OMPParallelForSimdDirective *D) {
2683 VisitOMPLoopDirective(D);
2684}
2685
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002686void EnqueueVisitor::VisitOMPParallelSectionsDirective(
2687 const OMPParallelSectionsDirective *D) {
2688 VisitOMPExecutableDirective(D);
2689}
2690
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002691void EnqueueVisitor::VisitOMPTaskDirective(const OMPTaskDirective *D) {
2692 VisitOMPExecutableDirective(D);
2693}
2694
Alexey Bataev68446b72014-07-18 07:47:19 +00002695void
2696EnqueueVisitor::VisitOMPTaskyieldDirective(const OMPTaskyieldDirective *D) {
2697 VisitOMPExecutableDirective(D);
2698}
2699
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002700void EnqueueVisitor::VisitOMPBarrierDirective(const OMPBarrierDirective *D) {
2701 VisitOMPExecutableDirective(D);
2702}
2703
Alexey Bataev2df347a2014-07-18 10:17:07 +00002704void EnqueueVisitor::VisitOMPTaskwaitDirective(const OMPTaskwaitDirective *D) {
2705 VisitOMPExecutableDirective(D);
2706}
2707
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002708void EnqueueVisitor::VisitOMPTaskgroupDirective(
2709 const OMPTaskgroupDirective *D) {
2710 VisitOMPExecutableDirective(D);
2711}
2712
Alexey Bataev6125da92014-07-21 11:26:11 +00002713void EnqueueVisitor::VisitOMPFlushDirective(const OMPFlushDirective *D) {
2714 VisitOMPExecutableDirective(D);
2715}
2716
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002717void EnqueueVisitor::VisitOMPOrderedDirective(const OMPOrderedDirective *D) {
2718 VisitOMPExecutableDirective(D);
2719}
2720
Alexey Bataev0162e452014-07-22 10:10:35 +00002721void EnqueueVisitor::VisitOMPAtomicDirective(const OMPAtomicDirective *D) {
2722 VisitOMPExecutableDirective(D);
2723}
2724
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002725void EnqueueVisitor::VisitOMPTargetDirective(const OMPTargetDirective *D) {
2726 VisitOMPExecutableDirective(D);
2727}
2728
Michael Wong65f367f2015-07-21 13:44:28 +00002729void EnqueueVisitor::VisitOMPTargetDataDirective(const
2730 OMPTargetDataDirective *D) {
2731 VisitOMPExecutableDirective(D);
2732}
2733
Samuel Antaodf67fc42016-01-19 19:15:56 +00002734void EnqueueVisitor::VisitOMPTargetEnterDataDirective(
2735 const OMPTargetEnterDataDirective *D) {
2736 VisitOMPExecutableDirective(D);
2737}
2738
Samuel Antao72590762016-01-19 20:04:50 +00002739void EnqueueVisitor::VisitOMPTargetExitDataDirective(
2740 const OMPTargetExitDataDirective *D) {
2741 VisitOMPExecutableDirective(D);
2742}
2743
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00002744void EnqueueVisitor::VisitOMPTargetParallelDirective(
2745 const OMPTargetParallelDirective *D) {
2746 VisitOMPExecutableDirective(D);
2747}
2748
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00002749void EnqueueVisitor::VisitOMPTargetParallelForDirective(
2750 const OMPTargetParallelForDirective *D) {
2751 VisitOMPLoopDirective(D);
2752}
2753
Alexey Bataev13314bf2014-10-09 04:18:56 +00002754void EnqueueVisitor::VisitOMPTeamsDirective(const OMPTeamsDirective *D) {
2755 VisitOMPExecutableDirective(D);
2756}
2757
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002758void EnqueueVisitor::VisitOMPCancellationPointDirective(
2759 const OMPCancellationPointDirective *D) {
2760 VisitOMPExecutableDirective(D);
2761}
2762
Alexey Bataev80909872015-07-02 11:25:17 +00002763void EnqueueVisitor::VisitOMPCancelDirective(const OMPCancelDirective *D) {
2764 VisitOMPExecutableDirective(D);
2765}
2766
Alexey Bataev49f6e782015-12-01 04:18:41 +00002767void EnqueueVisitor::VisitOMPTaskLoopDirective(const OMPTaskLoopDirective *D) {
2768 VisitOMPLoopDirective(D);
2769}
2770
Alexey Bataev0a6ed842015-12-03 09:40:15 +00002771void EnqueueVisitor::VisitOMPTaskLoopSimdDirective(
2772 const OMPTaskLoopSimdDirective *D) {
2773 VisitOMPLoopDirective(D);
2774}
2775
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002776void EnqueueVisitor::VisitOMPDistributeDirective(
2777 const OMPDistributeDirective *D) {
2778 VisitOMPLoopDirective(D);
2779}
2780
Carlo Bertolli9925f152016-06-27 14:55:37 +00002781void EnqueueVisitor::VisitOMPDistributeParallelForDirective(
2782 const OMPDistributeParallelForDirective *D) {
2783 VisitOMPLoopDirective(D);
2784}
2785
Kelvin Li4a39add2016-07-05 05:00:15 +00002786void EnqueueVisitor::VisitOMPDistributeParallelForSimdDirective(
2787 const OMPDistributeParallelForSimdDirective *D) {
2788 VisitOMPLoopDirective(D);
2789}
2790
Kelvin Li787f3fc2016-07-06 04:45:38 +00002791void EnqueueVisitor::VisitOMPDistributeSimdDirective(
2792 const OMPDistributeSimdDirective *D) {
2793 VisitOMPLoopDirective(D);
2794}
2795
Kelvin Lia579b912016-07-14 02:54:56 +00002796void EnqueueVisitor::VisitOMPTargetParallelForSimdDirective(
2797 const OMPTargetParallelForSimdDirective *D) {
2798 VisitOMPLoopDirective(D);
2799}
2800
Kelvin Li986330c2016-07-20 22:57:10 +00002801void EnqueueVisitor::VisitOMPTargetSimdDirective(
2802 const OMPTargetSimdDirective *D) {
2803 VisitOMPLoopDirective(D);
2804}
2805
Kelvin Li02532872016-08-05 14:37:37 +00002806void EnqueueVisitor::VisitOMPTeamsDistributeDirective(
2807 const OMPTeamsDistributeDirective *D) {
2808 VisitOMPLoopDirective(D);
2809}
2810
Kelvin Li4e325f72016-10-25 12:50:55 +00002811void EnqueueVisitor::VisitOMPTeamsDistributeSimdDirective(
2812 const OMPTeamsDistributeSimdDirective *D) {
2813 VisitOMPLoopDirective(D);
2814}
2815
Kelvin Li579e41c2016-11-30 23:51:03 +00002816void EnqueueVisitor::VisitOMPTeamsDistributeParallelForSimdDirective(
2817 const OMPTeamsDistributeParallelForSimdDirective *D) {
2818 VisitOMPLoopDirective(D);
2819}
2820
Kelvin Li7ade93f2016-12-09 03:24:30 +00002821void EnqueueVisitor::VisitOMPTeamsDistributeParallelForDirective(
2822 const OMPTeamsDistributeParallelForDirective *D) {
2823 VisitOMPLoopDirective(D);
2824}
2825
Kelvin Libf594a52016-12-17 05:48:59 +00002826void EnqueueVisitor::VisitOMPTargetTeamsDirective(
2827 const OMPTargetTeamsDirective *D) {
2828 VisitOMPExecutableDirective(D);
2829}
2830
Kelvin Li83c451e2016-12-25 04:52:54 +00002831void EnqueueVisitor::VisitOMPTargetTeamsDistributeDirective(
2832 const OMPTargetTeamsDistributeDirective *D) {
2833 VisitOMPLoopDirective(D);
2834}
2835
Kelvin Li80e8f562016-12-29 22:16:30 +00002836void EnqueueVisitor::VisitOMPTargetTeamsDistributeParallelForDirective(
2837 const OMPTargetTeamsDistributeParallelForDirective *D) {
2838 VisitOMPLoopDirective(D);
2839}
2840
Kelvin Li1851df52017-01-03 05:23:48 +00002841void EnqueueVisitor::VisitOMPTargetTeamsDistributeParallelForSimdDirective(
2842 const OMPTargetTeamsDistributeParallelForSimdDirective *D) {
2843 VisitOMPLoopDirective(D);
2844}
2845
Kelvin Lida681182017-01-10 18:08:18 +00002846void EnqueueVisitor::VisitOMPTargetTeamsDistributeSimdDirective(
2847 const OMPTargetTeamsDistributeSimdDirective *D) {
2848 VisitOMPLoopDirective(D);
2849}
2850
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002851void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002852 EnqueueVisitor(WL, MakeCXCursor(S, StmtParent, TU,RegionOfInterest)).Visit(S);
2853}
2854
2855bool CursorVisitor::IsInRegionOfInterest(CXCursor C) {
2856 if (RegionOfInterest.isValid()) {
2857 SourceRange Range = getRawCursorExtent(C);
2858 if (Range.isInvalid() || CompareRegionOfInterest(Range))
2859 return false;
2860 }
2861 return true;
2862}
2863
2864bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) {
2865 while (!WL.empty()) {
2866 // Dequeue the worklist item.
Robert Wilhelm25284cc2013-08-23 16:11:15 +00002867 VisitorJob LI = WL.pop_back_val();
Guy Benyei11169dd2012-12-18 14:30:41 +00002868
2869 // Set the Parent field, then back to its old value once we're done.
2870 SetParentRAII SetParent(Parent, StmtParent, LI.getParent());
2871
2872 switch (LI.getKind()) {
2873 case VisitorJob::DeclVisitKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002874 const Decl *D = cast<DeclVisit>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00002875 if (!D)
2876 continue;
2877
2878 // For now, perform default visitation for Decls.
2879 if (Visit(MakeCXCursor(D, TU, RegionOfInterest,
2880 cast<DeclVisit>(&LI)->isFirst())))
2881 return true;
2882
2883 continue;
2884 }
2885 case VisitorJob::ExplicitTemplateArgsVisitKind: {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002886 for (const TemplateArgumentLoc &Arg :
2887 *cast<ExplicitTemplateArgsVisit>(&LI)) {
2888 if (VisitTemplateArgumentLoc(Arg))
Guy Benyei11169dd2012-12-18 14:30:41 +00002889 return true;
2890 }
2891 continue;
2892 }
2893 case VisitorJob::TypeLocVisitKind: {
2894 // Perform default visitation for TypeLocs.
2895 if (Visit(cast<TypeLocVisit>(&LI)->get()))
2896 return true;
2897 continue;
2898 }
2899 case VisitorJob::LabelRefVisitKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002900 const LabelDecl *LS = cast<LabelRefVisit>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00002901 if (LabelStmt *stmt = LS->getStmt()) {
2902 if (Visit(MakeCursorLabelRef(stmt, cast<LabelRefVisit>(&LI)->getLoc(),
2903 TU))) {
2904 return true;
2905 }
2906 }
2907 continue;
2908 }
2909
2910 case VisitorJob::NestedNameSpecifierLocVisitKind: {
2911 NestedNameSpecifierLocVisit *V = cast<NestedNameSpecifierLocVisit>(&LI);
2912 if (VisitNestedNameSpecifierLoc(V->get()))
2913 return true;
2914 continue;
2915 }
2916
2917 case VisitorJob::DeclarationNameInfoVisitKind: {
2918 if (VisitDeclarationNameInfo(cast<DeclarationNameInfoVisit>(&LI)
2919 ->get()))
2920 return true;
2921 continue;
2922 }
2923 case VisitorJob::MemberRefVisitKind: {
2924 MemberRefVisit *V = cast<MemberRefVisit>(&LI);
2925 if (Visit(MakeCursorMemberRef(V->get(), V->getLoc(), TU)))
2926 return true;
2927 continue;
2928 }
2929 case VisitorJob::StmtVisitKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002930 const Stmt *S = cast<StmtVisit>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00002931 if (!S)
2932 continue;
2933
2934 // Update the current cursor.
2935 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU, RegionOfInterest);
2936 if (!IsInRegionOfInterest(Cursor))
2937 continue;
2938 switch (Visitor(Cursor, Parent, ClientData)) {
2939 case CXChildVisit_Break: return true;
2940 case CXChildVisit_Continue: break;
2941 case CXChildVisit_Recurse:
2942 if (PostChildrenVisitor)
Craig Topper69186e72014-06-08 08:38:04 +00002943 WL.push_back(PostChildrenVisit(nullptr, Cursor));
Guy Benyei11169dd2012-12-18 14:30:41 +00002944 EnqueueWorkList(WL, S);
2945 break;
2946 }
2947 continue;
2948 }
2949 case VisitorJob::MemberExprPartsKind: {
2950 // Handle the other pieces in the MemberExpr besides the base.
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002951 const MemberExpr *M = cast<MemberExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00002952
2953 // Visit the nested-name-specifier
2954 if (NestedNameSpecifierLoc QualifierLoc = M->getQualifierLoc())
2955 if (VisitNestedNameSpecifierLoc(QualifierLoc))
2956 return true;
2957
2958 // Visit the declaration name.
2959 if (VisitDeclarationNameInfo(M->getMemberNameInfo()))
2960 return true;
2961
2962 // Visit the explicitly-specified template arguments, if any.
2963 if (M->hasExplicitTemplateArgs()) {
2964 for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(),
2965 *ArgEnd = Arg + M->getNumTemplateArgs();
2966 Arg != ArgEnd; ++Arg) {
2967 if (VisitTemplateArgumentLoc(*Arg))
2968 return true;
2969 }
2970 }
2971 continue;
2972 }
2973 case VisitorJob::DeclRefExprPartsKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002974 const DeclRefExpr *DR = cast<DeclRefExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00002975 // Visit nested-name-specifier, if present.
2976 if (NestedNameSpecifierLoc QualifierLoc = DR->getQualifierLoc())
2977 if (VisitNestedNameSpecifierLoc(QualifierLoc))
2978 return true;
2979 // Visit declaration name.
2980 if (VisitDeclarationNameInfo(DR->getNameInfo()))
2981 return true;
2982 continue;
2983 }
2984 case VisitorJob::OverloadExprPartsKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002985 const OverloadExpr *O = cast<OverloadExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00002986 // Visit the nested-name-specifier.
2987 if (NestedNameSpecifierLoc QualifierLoc = O->getQualifierLoc())
2988 if (VisitNestedNameSpecifierLoc(QualifierLoc))
2989 return true;
2990 // Visit the declaration name.
2991 if (VisitDeclarationNameInfo(O->getNameInfo()))
2992 return true;
2993 // Visit the overloaded declaration reference.
2994 if (Visit(MakeCursorOverloadedDeclRef(O, TU)))
2995 return true;
2996 continue;
2997 }
2998 case VisitorJob::SizeOfPackExprPartsKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002999 const SizeOfPackExpr *E = cast<SizeOfPackExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003000 NamedDecl *Pack = E->getPack();
3001 if (isa<TemplateTypeParmDecl>(Pack)) {
3002 if (Visit(MakeCursorTypeRef(cast<TemplateTypeParmDecl>(Pack),
3003 E->getPackLoc(), TU)))
3004 return true;
3005
3006 continue;
3007 }
3008
3009 if (isa<TemplateTemplateParmDecl>(Pack)) {
3010 if (Visit(MakeCursorTemplateRef(cast<TemplateTemplateParmDecl>(Pack),
3011 E->getPackLoc(), TU)))
3012 return true;
3013
3014 continue;
3015 }
3016
3017 // Non-type template parameter packs and function parameter packs are
3018 // treated like DeclRefExpr cursors.
3019 continue;
3020 }
3021
3022 case VisitorJob::LambdaExprPartsKind: {
3023 // Visit captures.
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003024 const LambdaExpr *E = cast<LambdaExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003025 for (LambdaExpr::capture_iterator C = E->explicit_capture_begin(),
3026 CEnd = E->explicit_capture_end();
3027 C != CEnd; ++C) {
Richard Smithba71c082013-05-16 06:20:58 +00003028 // FIXME: Lambda init-captures.
3029 if (!C->capturesVariable())
Guy Benyei11169dd2012-12-18 14:30:41 +00003030 continue;
Richard Smithba71c082013-05-16 06:20:58 +00003031
Guy Benyei11169dd2012-12-18 14:30:41 +00003032 if (Visit(MakeCursorVariableRef(C->getCapturedVar(),
3033 C->getLocation(),
3034 TU)))
3035 return true;
3036 }
3037
3038 // Visit parameters and return type, if present.
3039 if (E->hasExplicitParameters() || E->hasExplicitResultType()) {
3040 TypeLoc TL = E->getCallOperator()->getTypeSourceInfo()->getTypeLoc();
3041 if (E->hasExplicitParameters() && E->hasExplicitResultType()) {
3042 // Visit the whole type.
3043 if (Visit(TL))
3044 return true;
David Blaikie6adc78e2013-02-18 22:06:02 +00003045 } else if (FunctionProtoTypeLoc Proto =
3046 TL.getAs<FunctionProtoTypeLoc>()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003047 if (E->hasExplicitParameters()) {
3048 // Visit parameters.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00003049 for (unsigned I = 0, N = Proto.getNumParams(); I != N; ++I)
3050 if (Visit(MakeCXCursor(Proto.getParam(I), TU)))
Guy Benyei11169dd2012-12-18 14:30:41 +00003051 return true;
3052 } else {
3053 // Visit result type.
Alp Toker42a16a62014-01-25 23:51:36 +00003054 if (Visit(Proto.getReturnLoc()))
Guy Benyei11169dd2012-12-18 14:30:41 +00003055 return true;
3056 }
3057 }
3058 }
3059 break;
3060 }
3061
3062 case VisitorJob::PostChildrenVisitKind:
3063 if (PostChildrenVisitor(Parent, ClientData))
3064 return true;
3065 break;
3066 }
3067 }
3068 return false;
3069}
3070
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003071bool CursorVisitor::Visit(const Stmt *S) {
Craig Topper69186e72014-06-08 08:38:04 +00003072 VisitorWorkList *WL = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00003073 if (!WorkListFreeList.empty()) {
3074 WL = WorkListFreeList.back();
3075 WL->clear();
3076 WorkListFreeList.pop_back();
3077 }
3078 else {
3079 WL = new VisitorWorkList();
3080 WorkListCache.push_back(WL);
3081 }
3082 EnqueueWorkList(*WL, S);
3083 bool result = RunVisitorWorkList(*WL);
3084 WorkListFreeList.push_back(WL);
3085 return result;
3086}
3087
3088namespace {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003089typedef SmallVector<SourceRange, 4> RefNamePieces;
James Y Knight04ec5bf2015-12-24 02:59:37 +00003090RefNamePieces buildPieces(unsigned NameFlags, bool IsMemberRefExpr,
3091 const DeclarationNameInfo &NI, SourceRange QLoc,
3092 const SourceRange *TemplateArgsLoc = nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003093 const bool WantQualifier = NameFlags & CXNameRange_WantQualifier;
3094 const bool WantTemplateArgs = NameFlags & CXNameRange_WantTemplateArgs;
3095 const bool WantSinglePiece = NameFlags & CXNameRange_WantSinglePiece;
3096
3097 const DeclarationName::NameKind Kind = NI.getName().getNameKind();
3098
3099 RefNamePieces Pieces;
3100
3101 if (WantQualifier && QLoc.isValid())
3102 Pieces.push_back(QLoc);
3103
3104 if (Kind != DeclarationName::CXXOperatorName || IsMemberRefExpr)
3105 Pieces.push_back(NI.getLoc());
James Y Knight04ec5bf2015-12-24 02:59:37 +00003106
3107 if (WantTemplateArgs && TemplateArgsLoc && TemplateArgsLoc->isValid())
3108 Pieces.push_back(*TemplateArgsLoc);
3109
Guy Benyei11169dd2012-12-18 14:30:41 +00003110 if (Kind == DeclarationName::CXXOperatorName) {
3111 Pieces.push_back(SourceLocation::getFromRawEncoding(
3112 NI.getInfo().CXXOperatorName.BeginOpNameLoc));
3113 Pieces.push_back(SourceLocation::getFromRawEncoding(
3114 NI.getInfo().CXXOperatorName.EndOpNameLoc));
3115 }
3116
3117 if (WantSinglePiece) {
3118 SourceRange R(Pieces.front().getBegin(), Pieces.back().getEnd());
3119 Pieces.clear();
3120 Pieces.push_back(R);
3121 }
3122
3123 return Pieces;
3124}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003125}
Guy Benyei11169dd2012-12-18 14:30:41 +00003126
3127//===----------------------------------------------------------------------===//
3128// Misc. API hooks.
3129//===----------------------------------------------------------------------===//
3130
Chad Rosier05c71aa2013-03-27 18:28:23 +00003131static void fatal_error_handler(void *user_data, const std::string& reason,
3132 bool gen_crash_diag) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003133 // Write the result out to stderr avoiding errs() because raw_ostreams can
3134 // call report_fatal_error.
3135 fprintf(stderr, "LIBCLANG FATAL ERROR: %s\n", reason.c_str());
3136 ::abort();
3137}
3138
Chandler Carruth66660742014-06-27 16:37:27 +00003139namespace {
3140struct RegisterFatalErrorHandler {
3141 RegisterFatalErrorHandler() {
3142 llvm::install_fatal_error_handler(fatal_error_handler, nullptr);
3143 }
3144};
3145}
3146
3147static llvm::ManagedStatic<RegisterFatalErrorHandler> RegisterFatalErrorHandlerOnce;
3148
Guy Benyei11169dd2012-12-18 14:30:41 +00003149CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
3150 int displayDiagnostics) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003151 // We use crash recovery to make some of our APIs more reliable, implicitly
3152 // enable it.
Argyrios Kyrtzidis3701f542013-11-27 08:58:09 +00003153 if (!getenv("LIBCLANG_DISABLE_CRASH_RECOVERY"))
3154 llvm::CrashRecoveryContext::Enable();
Guy Benyei11169dd2012-12-18 14:30:41 +00003155
Chandler Carruth66660742014-06-27 16:37:27 +00003156 // Look through the managed static to trigger construction of the managed
3157 // static which registers our fatal error handler. This ensures it is only
3158 // registered once.
3159 (void)*RegisterFatalErrorHandlerOnce;
Guy Benyei11169dd2012-12-18 14:30:41 +00003160
Adrian Prantlbc068582015-07-08 01:00:30 +00003161 // Initialize targets for clang module support.
3162 llvm::InitializeAllTargets();
3163 llvm::InitializeAllTargetMCs();
3164 llvm::InitializeAllAsmPrinters();
3165 llvm::InitializeAllAsmParsers();
3166
Adrian Prantlfb2398d2015-07-17 01:19:54 +00003167 CIndexer *CIdxr = new CIndexer();
3168
Guy Benyei11169dd2012-12-18 14:30:41 +00003169 if (excludeDeclarationsFromPCH)
3170 CIdxr->setOnlyLocalDecls();
3171 if (displayDiagnostics)
3172 CIdxr->setDisplayDiagnostics();
3173
3174 if (getenv("LIBCLANG_BGPRIO_INDEX"))
3175 CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() |
3176 CXGlobalOpt_ThreadBackgroundPriorityForIndexing);
3177 if (getenv("LIBCLANG_BGPRIO_EDIT"))
3178 CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() |
3179 CXGlobalOpt_ThreadBackgroundPriorityForEditing);
3180
3181 return CIdxr;
3182}
3183
3184void clang_disposeIndex(CXIndex CIdx) {
3185 if (CIdx)
3186 delete static_cast<CIndexer *>(CIdx);
3187}
3188
3189void clang_CXIndex_setGlobalOptions(CXIndex CIdx, unsigned options) {
3190 if (CIdx)
3191 static_cast<CIndexer *>(CIdx)->setCXGlobalOptFlags(options);
3192}
3193
3194unsigned clang_CXIndex_getGlobalOptions(CXIndex CIdx) {
3195 if (CIdx)
3196 return static_cast<CIndexer *>(CIdx)->getCXGlobalOptFlags();
3197 return 0;
3198}
3199
3200void clang_toggleCrashRecovery(unsigned isEnabled) {
3201 if (isEnabled)
3202 llvm::CrashRecoveryContext::Enable();
3203 else
3204 llvm::CrashRecoveryContext::Disable();
3205}
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003206
Guy Benyei11169dd2012-12-18 14:30:41 +00003207CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
3208 const char *ast_filename) {
Dmitri Gribenko8850cda2014-02-19 10:24:00 +00003209 CXTranslationUnit TU;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003210 enum CXErrorCode Result =
3211 clang_createTranslationUnit2(CIdx, ast_filename, &TU);
Reid Klecknerfd48fc62014-02-12 23:56:20 +00003212 (void)Result;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003213 assert((TU && Result == CXError_Success) ||
3214 (!TU && Result != CXError_Success));
3215 return TU;
3216}
3217
3218enum CXErrorCode clang_createTranslationUnit2(CXIndex CIdx,
3219 const char *ast_filename,
3220 CXTranslationUnit *out_TU) {
Dmitri Gribenko8850cda2014-02-19 10:24:00 +00003221 if (out_TU)
Craig Topper69186e72014-06-08 08:38:04 +00003222 *out_TU = nullptr;
Dmitri Gribenko8850cda2014-02-19 10:24:00 +00003223
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003224 if (!CIdx || !ast_filename || !out_TU)
3225 return CXError_InvalidArguments;
Guy Benyei11169dd2012-12-18 14:30:41 +00003226
Argyrios Kyrtzidis27021012013-05-24 22:24:07 +00003227 LOG_FUNC_SECTION {
3228 *Log << ast_filename;
3229 }
3230
Guy Benyei11169dd2012-12-18 14:30:41 +00003231 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
3232 FileSystemOptions FileSystemOpts;
3233
Justin Bognerd512c1e2014-10-15 00:33:06 +00003234 IntrusiveRefCntPtr<DiagnosticsEngine> Diags =
3235 CompilerInstance::createDiagnostics(new DiagnosticOptions());
David Blaikie6f7382d2014-08-10 19:08:04 +00003236 std::unique_ptr<ASTUnit> AU = ASTUnit::LoadFromASTFile(
Adrian Prantlfb2398d2015-07-17 01:19:54 +00003237 ast_filename, CXXIdx->getPCHContainerOperations()->getRawReader(), Diags,
Adrian Prantl6b21ab22015-08-27 19:46:20 +00003238 FileSystemOpts, /*UseDebugInfo=*/false,
3239 CXXIdx->getOnlyLocalDecls(), None,
David Blaikie6f7382d2014-08-10 19:08:04 +00003240 /*CaptureDiagnostics=*/true,
3241 /*AllowPCHWithCompilerErrors=*/true,
3242 /*UserFilesAreVolatile=*/true);
David Blaikieea4395e2017-01-06 19:49:01 +00003243 *out_TU = MakeCXTranslationUnit(CXXIdx, std::move(AU));
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003244 return *out_TU ? CXError_Success : CXError_Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003245}
3246
3247unsigned clang_defaultEditingTranslationUnitOptions() {
3248 return CXTranslationUnit_PrecompiledPreamble |
3249 CXTranslationUnit_CacheCompletionResults;
3250}
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003251
Guy Benyei11169dd2012-12-18 14:30:41 +00003252CXTranslationUnit
3253clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
3254 const char *source_filename,
3255 int num_command_line_args,
3256 const char * const *command_line_args,
3257 unsigned num_unsaved_files,
3258 struct CXUnsavedFile *unsaved_files) {
3259 unsigned Options = CXTranslationUnit_DetailedPreprocessingRecord;
3260 return clang_parseTranslationUnit(CIdx, source_filename,
3261 command_line_args, num_command_line_args,
3262 unsaved_files, num_unsaved_files,
3263 Options);
3264}
3265
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003266static CXErrorCode
3267clang_parseTranslationUnit_Impl(CXIndex CIdx, const char *source_filename,
3268 const char *const *command_line_args,
3269 int num_command_line_args,
3270 ArrayRef<CXUnsavedFile> unsaved_files,
3271 unsigned options, CXTranslationUnit *out_TU) {
Dmitri Gribenko1bf8d912014-02-18 15:20:02 +00003272 // Set up the initial return values.
3273 if (out_TU)
Craig Topper69186e72014-06-08 08:38:04 +00003274 *out_TU = nullptr;
Dmitri Gribenko1bf8d912014-02-18 15:20:02 +00003275
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003276 // Check arguments.
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003277 if (!CIdx || !out_TU)
3278 return CXError_InvalidArguments;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003279
Guy Benyei11169dd2012-12-18 14:30:41 +00003280 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
3281
3282 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
3283 setThreadBackgroundPriority();
3284
3285 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Benjamin Kramer5c248d82015-12-15 09:30:31 +00003286 bool CreatePreambleOnFirstParse =
3287 options & CXTranslationUnit_CreatePreambleOnFirstParse;
Guy Benyei11169dd2012-12-18 14:30:41 +00003288 // FIXME: Add a flag for modules.
3289 TranslationUnitKind TUKind
3290 = (options & CXTranslationUnit_Incomplete)? TU_Prefix : TU_Complete;
Alp Toker8c8a8752013-12-03 06:53:35 +00003291 bool CacheCodeCompletionResults
Guy Benyei11169dd2012-12-18 14:30:41 +00003292 = options & CXTranslationUnit_CacheCompletionResults;
3293 bool IncludeBriefCommentsInCodeCompletion
3294 = options & CXTranslationUnit_IncludeBriefCommentsInCodeCompletion;
3295 bool SkipFunctionBodies = options & CXTranslationUnit_SkipFunctionBodies;
3296 bool ForSerialization = options & CXTranslationUnit_ForSerialization;
3297
3298 // Configure the diagnostics.
3299 IntrusiveRefCntPtr<DiagnosticsEngine>
Sean Silvaf1b49e22013-01-20 01:58:28 +00003300 Diags(CompilerInstance::createDiagnostics(new DiagnosticOptions));
Guy Benyei11169dd2012-12-18 14:30:41 +00003301
Manuel Klimek016c0242016-03-01 10:56:19 +00003302 if (options & CXTranslationUnit_KeepGoing)
3303 Diags->setFatalsAsError(true);
3304
Guy Benyei11169dd2012-12-18 14:30:41 +00003305 // Recover resources if we crash before exiting this function.
3306 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
3307 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Alp Tokerf994cef2014-07-05 03:08:06 +00003308 DiagCleanup(Diags.get());
Guy Benyei11169dd2012-12-18 14:30:41 +00003309
Ahmed Charlesb8984322014-03-07 20:03:18 +00003310 std::unique_ptr<std::vector<ASTUnit::RemappedFile>> RemappedFiles(
3311 new std::vector<ASTUnit::RemappedFile>());
Guy Benyei11169dd2012-12-18 14:30:41 +00003312
3313 // Recover resources if we crash before exiting this function.
3314 llvm::CrashRecoveryContextCleanupRegistrar<
3315 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
3316
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003317 for (auto &UF : unsaved_files) {
Rafael Espindolad87f8d72014-08-27 20:03:29 +00003318 std::unique_ptr<llvm::MemoryBuffer> MB =
Alp Toker9d85b182014-07-07 01:23:14 +00003319 llvm::MemoryBuffer::getMemBufferCopy(getContents(UF), UF.Filename);
Rafael Espindolad87f8d72014-08-27 20:03:29 +00003320 RemappedFiles->push_back(std::make_pair(UF.Filename, MB.release()));
Guy Benyei11169dd2012-12-18 14:30:41 +00003321 }
3322
Ahmed Charlesb8984322014-03-07 20:03:18 +00003323 std::unique_ptr<std::vector<const char *>> Args(
3324 new std::vector<const char *>());
Guy Benyei11169dd2012-12-18 14:30:41 +00003325
3326 // Recover resources if we crash before exiting this method.
3327 llvm::CrashRecoveryContextCleanupRegistrar<std::vector<const char*> >
3328 ArgsCleanup(Args.get());
3329
3330 // Since the Clang C library is primarily used by batch tools dealing with
3331 // (often very broken) source code, where spell-checking can have a
3332 // significant negative impact on performance (particularly when
3333 // precompiled headers are involved), we disable it by default.
3334 // Only do this if we haven't found a spell-checking-related argument.
3335 bool FoundSpellCheckingArgument = false;
3336 for (int I = 0; I != num_command_line_args; ++I) {
3337 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
3338 strcmp(command_line_args[I], "-fspell-checking") == 0) {
3339 FoundSpellCheckingArgument = true;
3340 break;
3341 }
3342 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003343 Args->insert(Args->end(), command_line_args,
3344 command_line_args + num_command_line_args);
3345
Benjamin Kramerc02670e2015-11-18 16:14:27 +00003346 if (!FoundSpellCheckingArgument)
3347 Args->insert(Args->begin() + 1, "-fno-spell-checking");
3348
Guy Benyei11169dd2012-12-18 14:30:41 +00003349 // The 'source_filename' argument is optional. If the caller does not
3350 // specify it then it is assumed that the source file is specified
3351 // in the actual argument list.
3352 // Put the source file after command_line_args otherwise if '-x' flag is
3353 // present it will be unused.
3354 if (source_filename)
3355 Args->push_back(source_filename);
3356
3357 // Do we need the detailed preprocessing record?
3358 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
3359 Args->push_back("-Xclang");
3360 Args->push_back("-detailed-preprocessing-record");
3361 }
3362
3363 unsigned NumErrors = Diags->getClient()->getNumErrors();
Ahmed Charlesb8984322014-03-07 20:03:18 +00003364 std::unique_ptr<ASTUnit> ErrUnit;
Benjamin Kramer5c248d82015-12-15 09:30:31 +00003365 // Unless the user specified that they want the preamble on the first parse
3366 // set it up to be created on the first reparse. This makes the first parse
3367 // faster, trading for a slower (first) reparse.
3368 unsigned PrecompilePreambleAfterNParses =
3369 !PrecompilePreamble ? 0 : 2 - CreatePreambleOnFirstParse;
Ahmed Charlesb8984322014-03-07 20:03:18 +00003370 std::unique_ptr<ASTUnit> Unit(ASTUnit::LoadFromCommandLine(
Adrian Prantlbb165fb2015-06-20 18:53:08 +00003371 Args->data(), Args->data() + Args->size(),
3372 CXXIdx->getPCHContainerOperations(), Diags,
Ahmed Charlesb8984322014-03-07 20:03:18 +00003373 CXXIdx->getClangResourcesPath(), CXXIdx->getOnlyLocalDecls(),
3374 /*CaptureDiagnostics=*/true, *RemappedFiles.get(),
Benjamin Kramer5c248d82015-12-15 09:30:31 +00003375 /*RemappedFilesKeepOriginalName=*/true, PrecompilePreambleAfterNParses,
3376 TUKind, CacheCodeCompletionResults, IncludeBriefCommentsInCodeCompletion,
Ahmed Charlesb8984322014-03-07 20:03:18 +00003377 /*AllowPCHWithCompilerErrors=*/true, SkipFunctionBodies,
Argyrios Kyrtzidisa3e2ff12015-11-20 03:36:21 +00003378 /*UserFilesAreVolatile=*/true, ForSerialization,
3379 CXXIdx->getPCHContainerOperations()->getRawReader().getFormat(),
3380 &ErrUnit));
Guy Benyei11169dd2012-12-18 14:30:41 +00003381
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003382 // Early failures in LoadFromCommandLine may return with ErrUnit unset.
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003383 if (!Unit && !ErrUnit)
3384 return CXError_ASTReadError;
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003385
Guy Benyei11169dd2012-12-18 14:30:41 +00003386 if (NumErrors != Diags->getClient()->getNumErrors()) {
3387 // Make sure to check that 'Unit' is non-NULL.
3388 if (CXXIdx->getDisplayDiagnostics())
3389 printDiagsToStderr(Unit ? Unit.get() : ErrUnit.get());
3390 }
3391
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003392 if (isASTReadError(Unit ? Unit.get() : ErrUnit.get()))
3393 return CXError_ASTReadError;
3394
David Blaikieea4395e2017-01-06 19:49:01 +00003395 *out_TU = MakeCXTranslationUnit(CXXIdx, std::move(Unit));
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003396 return *out_TU ? CXError_Success : CXError_Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003397}
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003398
3399CXTranslationUnit
3400clang_parseTranslationUnit(CXIndex CIdx,
3401 const char *source_filename,
3402 const char *const *command_line_args,
3403 int num_command_line_args,
3404 struct CXUnsavedFile *unsaved_files,
3405 unsigned num_unsaved_files,
3406 unsigned options) {
3407 CXTranslationUnit TU;
3408 enum CXErrorCode Result = clang_parseTranslationUnit2(
3409 CIdx, source_filename, command_line_args, num_command_line_args,
3410 unsaved_files, num_unsaved_files, options, &TU);
Reid Kleckner6eaf05a2014-02-13 01:19:59 +00003411 (void)Result;
Dmitri Gribenko1bf8d912014-02-18 15:20:02 +00003412 assert((TU && Result == CXError_Success) ||
3413 (!TU && Result != CXError_Success));
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003414 return TU;
3415}
3416
3417enum CXErrorCode clang_parseTranslationUnit2(
Benjamin Kramerc02670e2015-11-18 16:14:27 +00003418 CXIndex CIdx, const char *source_filename,
3419 const char *const *command_line_args, int num_command_line_args,
3420 struct CXUnsavedFile *unsaved_files, unsigned num_unsaved_files,
3421 unsigned options, CXTranslationUnit *out_TU) {
3422 SmallVector<const char *, 4> Args;
3423 Args.push_back("clang");
3424 Args.append(command_line_args, command_line_args + num_command_line_args);
3425 return clang_parseTranslationUnit2FullArgv(
3426 CIdx, source_filename, Args.data(), Args.size(), unsaved_files,
3427 num_unsaved_files, options, out_TU);
3428}
3429
3430enum CXErrorCode clang_parseTranslationUnit2FullArgv(
3431 CXIndex CIdx, const char *source_filename,
3432 const char *const *command_line_args, int num_command_line_args,
3433 struct CXUnsavedFile *unsaved_files, unsigned num_unsaved_files,
3434 unsigned options, CXTranslationUnit *out_TU) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00003435 LOG_FUNC_SECTION {
3436 *Log << source_filename << ": ";
3437 for (int i = 0; i != num_command_line_args; ++i)
3438 *Log << command_line_args[i] << " ";
3439 }
3440
Alp Toker9d85b182014-07-07 01:23:14 +00003441 if (num_unsaved_files && !unsaved_files)
3442 return CXError_InvalidArguments;
3443
Alp Toker5c532982014-07-07 22:42:03 +00003444 CXErrorCode result = CXError_Failure;
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003445 auto ParseTranslationUnitImpl = [=, &result] {
3446 result = clang_parseTranslationUnit_Impl(
3447 CIdx, source_filename, command_line_args, num_command_line_args,
3448 llvm::makeArrayRef(unsaved_files, num_unsaved_files), options, out_TU);
3449 };
Guy Benyei11169dd2012-12-18 14:30:41 +00003450 llvm::CrashRecoveryContext CRC;
3451
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003452 if (!RunSafely(CRC, ParseTranslationUnitImpl)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003453 fprintf(stderr, "libclang: crash detected during parsing: {\n");
3454 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
3455 fprintf(stderr, " 'command_line_args' : [");
3456 for (int i = 0; i != num_command_line_args; ++i) {
3457 if (i)
3458 fprintf(stderr, ", ");
3459 fprintf(stderr, "'%s'", command_line_args[i]);
3460 }
3461 fprintf(stderr, "],\n");
3462 fprintf(stderr, " 'unsaved_files' : [");
3463 for (unsigned i = 0; i != num_unsaved_files; ++i) {
3464 if (i)
3465 fprintf(stderr, ", ");
3466 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
3467 unsaved_files[i].Length);
3468 }
3469 fprintf(stderr, "],\n");
3470 fprintf(stderr, " 'options' : %d,\n", options);
3471 fprintf(stderr, "}\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003472
3473 return CXError_Crashed;
Guy Benyei11169dd2012-12-18 14:30:41 +00003474 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003475 if (CXTranslationUnit *TU = out_TU)
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003476 PrintLibclangResourceUsage(*TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00003477 }
Alp Toker5c532982014-07-07 22:42:03 +00003478
3479 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003480}
3481
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003482CXString clang_Type_getObjCEncoding(CXType CT) {
3483 CXTranslationUnit tu = static_cast<CXTranslationUnit>(CT.data[1]);
3484 ASTContext &Ctx = getASTUnit(tu)->getASTContext();
3485 std::string encoding;
3486 Ctx.getObjCEncodingForType(QualType::getFromOpaquePtr(CT.data[0]),
3487 encoding);
3488
3489 return cxstring::createDup(encoding);
3490}
3491
3492static const IdentifierInfo *getMacroIdentifier(CXCursor C) {
3493 if (C.kind == CXCursor_MacroDefinition) {
3494 if (const MacroDefinitionRecord *MDR = getCursorMacroDefinition(C))
3495 return MDR->getName();
3496 } else if (C.kind == CXCursor_MacroExpansion) {
3497 MacroExpansionCursor ME = getCursorMacroExpansion(C);
3498 return ME.getName();
3499 }
3500 return nullptr;
3501}
3502
3503unsigned clang_Cursor_isMacroFunctionLike(CXCursor C) {
3504 const IdentifierInfo *II = getMacroIdentifier(C);
3505 if (!II) {
3506 return false;
3507 }
3508 ASTUnit *ASTU = getCursorASTUnit(C);
3509 Preprocessor &PP = ASTU->getPreprocessor();
3510 if (const MacroInfo *MI = PP.getMacroInfo(II))
3511 return MI->isFunctionLike();
3512 return false;
3513}
3514
3515unsigned clang_Cursor_isMacroBuiltin(CXCursor C) {
3516 const IdentifierInfo *II = getMacroIdentifier(C);
3517 if (!II) {
3518 return false;
3519 }
3520 ASTUnit *ASTU = getCursorASTUnit(C);
3521 Preprocessor &PP = ASTU->getPreprocessor();
3522 if (const MacroInfo *MI = PP.getMacroInfo(II))
3523 return MI->isBuiltinMacro();
3524 return false;
3525}
3526
3527unsigned clang_Cursor_isFunctionInlined(CXCursor C) {
3528 const Decl *D = getCursorDecl(C);
3529 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
3530 if (!FD) {
3531 return false;
3532 }
3533 return FD->isInlined();
3534}
3535
3536static StringLiteral* getCFSTR_value(CallExpr *callExpr) {
3537 if (callExpr->getNumArgs() != 1) {
3538 return nullptr;
3539 }
3540
3541 StringLiteral *S = nullptr;
3542 auto *arg = callExpr->getArg(0);
3543 if (arg->getStmtClass() == Stmt::ImplicitCastExprClass) {
3544 ImplicitCastExpr *I = static_cast<ImplicitCastExpr *>(arg);
3545 auto *subExpr = I->getSubExprAsWritten();
3546
3547 if(subExpr->getStmtClass() != Stmt::StringLiteralClass){
3548 return nullptr;
3549 }
3550
3551 S = static_cast<StringLiteral *>(I->getSubExprAsWritten());
3552 } else if (arg->getStmtClass() == Stmt::StringLiteralClass) {
3553 S = static_cast<StringLiteral *>(callExpr->getArg(0));
3554 } else {
3555 return nullptr;
3556 }
3557 return S;
3558}
3559
David Blaikie59272572016-04-13 18:23:33 +00003560struct ExprEvalResult {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003561 CXEvalResultKind EvalType;
3562 union {
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003563 unsigned long long unsignedVal;
3564 long long intVal;
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003565 double floatVal;
3566 char *stringVal;
3567 } EvalData;
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003568 bool IsUnsignedInt;
David Blaikie59272572016-04-13 18:23:33 +00003569 ~ExprEvalResult() {
3570 if (EvalType != CXEval_UnExposed && EvalType != CXEval_Float &&
3571 EvalType != CXEval_Int) {
3572 delete EvalData.stringVal;
3573 }
3574 }
3575};
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003576
3577void clang_EvalResult_dispose(CXEvalResult E) {
David Blaikie59272572016-04-13 18:23:33 +00003578 delete static_cast<ExprEvalResult *>(E);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003579}
3580
3581CXEvalResultKind clang_EvalResult_getKind(CXEvalResult E) {
3582 if (!E) {
3583 return CXEval_UnExposed;
3584 }
3585 return ((ExprEvalResult *)E)->EvalType;
3586}
3587
3588int clang_EvalResult_getAsInt(CXEvalResult E) {
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003589 return clang_EvalResult_getAsLongLong(E);
3590}
3591
3592long long clang_EvalResult_getAsLongLong(CXEvalResult E) {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003593 if (!E) {
3594 return 0;
3595 }
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003596 ExprEvalResult *Result = (ExprEvalResult*)E;
3597 if (Result->IsUnsignedInt)
3598 return Result->EvalData.unsignedVal;
3599 return Result->EvalData.intVal;
3600}
3601
3602unsigned clang_EvalResult_isUnsignedInt(CXEvalResult E) {
3603 return ((ExprEvalResult *)E)->IsUnsignedInt;
3604}
3605
3606unsigned long long clang_EvalResult_getAsUnsigned(CXEvalResult E) {
3607 if (!E) {
3608 return 0;
3609 }
3610
3611 ExprEvalResult *Result = (ExprEvalResult*)E;
3612 if (Result->IsUnsignedInt)
3613 return Result->EvalData.unsignedVal;
3614 return Result->EvalData.intVal;
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003615}
3616
3617double clang_EvalResult_getAsDouble(CXEvalResult E) {
3618 if (!E) {
3619 return 0;
3620 }
3621 return ((ExprEvalResult *)E)->EvalData.floatVal;
3622}
3623
3624const char* clang_EvalResult_getAsStr(CXEvalResult E) {
3625 if (!E) {
3626 return nullptr;
3627 }
3628 return ((ExprEvalResult *)E)->EvalData.stringVal;
3629}
3630
3631static const ExprEvalResult* evaluateExpr(Expr *expr, CXCursor C) {
3632 Expr::EvalResult ER;
3633 ASTContext &ctx = getCursorContext(C);
David Blaikiebbc00882016-04-13 18:36:19 +00003634 if (!expr)
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003635 return nullptr;
David Blaikiebbc00882016-04-13 18:36:19 +00003636
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003637 expr = expr->IgnoreParens();
David Blaikiebbc00882016-04-13 18:36:19 +00003638 if (!expr->EvaluateAsRValue(ER, ctx))
3639 return nullptr;
3640
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003641 QualType rettype;
3642 CallExpr *callExpr;
David Blaikie59272572016-04-13 18:23:33 +00003643 auto result = llvm::make_unique<ExprEvalResult>();
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003644 result->EvalType = CXEval_UnExposed;
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003645 result->IsUnsignedInt = false;
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003646
David Blaikiebbc00882016-04-13 18:36:19 +00003647 if (ER.Val.isInt()) {
3648 result->EvalType = CXEval_Int;
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003649
3650 auto& val = ER.Val.getInt();
3651 if (val.isUnsigned()) {
3652 result->IsUnsignedInt = true;
3653 result->EvalData.unsignedVal = val.getZExtValue();
3654 } else {
3655 result->EvalData.intVal = val.getExtValue();
3656 }
3657
David Blaikiebbc00882016-04-13 18:36:19 +00003658 return result.release();
3659 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003660
David Blaikiebbc00882016-04-13 18:36:19 +00003661 if (ER.Val.isFloat()) {
3662 llvm::SmallVector<char, 100> Buffer;
3663 ER.Val.getFloat().toString(Buffer);
3664 std::string floatStr(Buffer.data(), Buffer.size());
3665 result->EvalType = CXEval_Float;
3666 bool ignored;
3667 llvm::APFloat apFloat = ER.Val.getFloat();
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003668 apFloat.convert(llvm::APFloat::IEEEdouble(),
David Blaikiebbc00882016-04-13 18:36:19 +00003669 llvm::APFloat::rmNearestTiesToEven, &ignored);
3670 result->EvalData.floatVal = apFloat.convertToDouble();
3671 return result.release();
3672 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003673
David Blaikiebbc00882016-04-13 18:36:19 +00003674 if (expr->getStmtClass() == Stmt::ImplicitCastExprClass) {
3675 const ImplicitCastExpr *I = dyn_cast<ImplicitCastExpr>(expr);
3676 auto *subExpr = I->getSubExprAsWritten();
3677 if (subExpr->getStmtClass() == Stmt::StringLiteralClass ||
3678 subExpr->getStmtClass() == Stmt::ObjCStringLiteralClass) {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003679 const StringLiteral *StrE = nullptr;
3680 const ObjCStringLiteral *ObjCExpr;
David Blaikiebbc00882016-04-13 18:36:19 +00003681 ObjCExpr = dyn_cast<ObjCStringLiteral>(subExpr);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003682
3683 if (ObjCExpr) {
3684 StrE = ObjCExpr->getString();
3685 result->EvalType = CXEval_ObjCStrLiteral;
3686 } else {
David Blaikiebbc00882016-04-13 18:36:19 +00003687 StrE = cast<StringLiteral>(I->getSubExprAsWritten());
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003688 result->EvalType = CXEval_StrLiteral;
3689 }
3690
3691 std::string strRef(StrE->getString().str());
David Blaikie59272572016-04-13 18:23:33 +00003692 result->EvalData.stringVal = new char[strRef.size() + 1];
David Blaikiebbc00882016-04-13 18:36:19 +00003693 strncpy((char *)result->EvalData.stringVal, strRef.c_str(),
3694 strRef.size());
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003695 result->EvalData.stringVal[strRef.size()] = '\0';
David Blaikie59272572016-04-13 18:23:33 +00003696 return result.release();
David Blaikiebbc00882016-04-13 18:36:19 +00003697 }
3698 } else if (expr->getStmtClass() == Stmt::ObjCStringLiteralClass ||
3699 expr->getStmtClass() == Stmt::StringLiteralClass) {
3700 const StringLiteral *StrE = nullptr;
3701 const ObjCStringLiteral *ObjCExpr;
3702 ObjCExpr = dyn_cast<ObjCStringLiteral>(expr);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003703
David Blaikiebbc00882016-04-13 18:36:19 +00003704 if (ObjCExpr) {
3705 StrE = ObjCExpr->getString();
3706 result->EvalType = CXEval_ObjCStrLiteral;
3707 } else {
3708 StrE = cast<StringLiteral>(expr);
3709 result->EvalType = CXEval_StrLiteral;
3710 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003711
David Blaikiebbc00882016-04-13 18:36:19 +00003712 std::string strRef(StrE->getString().str());
3713 result->EvalData.stringVal = new char[strRef.size() + 1];
3714 strncpy((char *)result->EvalData.stringVal, strRef.c_str(), strRef.size());
3715 result->EvalData.stringVal[strRef.size()] = '\0';
3716 return result.release();
3717 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003718
David Blaikiebbc00882016-04-13 18:36:19 +00003719 if (expr->getStmtClass() == Stmt::CStyleCastExprClass) {
3720 CStyleCastExpr *CC = static_cast<CStyleCastExpr *>(expr);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003721
David Blaikiebbc00882016-04-13 18:36:19 +00003722 rettype = CC->getType();
3723 if (rettype.getAsString() == "CFStringRef" &&
3724 CC->getSubExpr()->getStmtClass() == Stmt::CallExprClass) {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003725
David Blaikiebbc00882016-04-13 18:36:19 +00003726 callExpr = static_cast<CallExpr *>(CC->getSubExpr());
3727 StringLiteral *S = getCFSTR_value(callExpr);
3728 if (S) {
3729 std::string strLiteral(S->getString().str());
3730 result->EvalType = CXEval_CFStr;
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003731
David Blaikiebbc00882016-04-13 18:36:19 +00003732 result->EvalData.stringVal = new char[strLiteral.size() + 1];
3733 strncpy((char *)result->EvalData.stringVal, strLiteral.c_str(),
3734 strLiteral.size());
3735 result->EvalData.stringVal[strLiteral.size()] = '\0';
David Blaikie59272572016-04-13 18:23:33 +00003736 return result.release();
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003737 }
3738 }
3739
David Blaikiebbc00882016-04-13 18:36:19 +00003740 } else if (expr->getStmtClass() == Stmt::CallExprClass) {
3741 callExpr = static_cast<CallExpr *>(expr);
3742 rettype = callExpr->getCallReturnType(ctx);
3743
3744 if (rettype->isVectorType() || callExpr->getNumArgs() > 1)
3745 return nullptr;
3746
3747 if (rettype->isIntegralType(ctx) || rettype->isRealFloatingType()) {
3748 if (callExpr->getNumArgs() == 1 &&
3749 !callExpr->getArg(0)->getType()->isIntegralType(ctx))
3750 return nullptr;
3751 } else if (rettype.getAsString() == "CFStringRef") {
3752
3753 StringLiteral *S = getCFSTR_value(callExpr);
3754 if (S) {
3755 std::string strLiteral(S->getString().str());
3756 result->EvalType = CXEval_CFStr;
3757 result->EvalData.stringVal = new char[strLiteral.size() + 1];
3758 strncpy((char *)result->EvalData.stringVal, strLiteral.c_str(),
3759 strLiteral.size());
3760 result->EvalData.stringVal[strLiteral.size()] = '\0';
3761 return result.release();
3762 }
3763 }
3764 } else if (expr->getStmtClass() == Stmt::DeclRefExprClass) {
3765 DeclRefExpr *D = static_cast<DeclRefExpr *>(expr);
3766 ValueDecl *V = D->getDecl();
3767 if (V->getKind() == Decl::Function) {
3768 std::string strName = V->getNameAsString();
3769 result->EvalType = CXEval_Other;
3770 result->EvalData.stringVal = new char[strName.size() + 1];
3771 strncpy(result->EvalData.stringVal, strName.c_str(), strName.size());
3772 result->EvalData.stringVal[strName.size()] = '\0';
3773 return result.release();
3774 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003775 }
3776
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003777 return nullptr;
3778}
3779
3780CXEvalResult clang_Cursor_Evaluate(CXCursor C) {
3781 const Decl *D = getCursorDecl(C);
3782 if (D) {
3783 const Expr *expr = nullptr;
3784 if (auto *Var = dyn_cast<VarDecl>(D)) {
3785 expr = Var->getInit();
3786 } else if (auto *Field = dyn_cast<FieldDecl>(D)) {
3787 expr = Field->getInClassInitializer();
3788 }
3789 if (expr)
Aaron Ballman01dc1572016-01-20 15:25:30 +00003790 return const_cast<CXEvalResult>(reinterpret_cast<const void *>(
3791 evaluateExpr(const_cast<Expr *>(expr), C)));
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003792 return nullptr;
3793 }
3794
3795 const CompoundStmt *compoundStmt = dyn_cast_or_null<CompoundStmt>(getCursorStmt(C));
3796 if (compoundStmt) {
3797 Expr *expr = nullptr;
3798 for (auto *bodyIterator : compoundStmt->body()) {
3799 if ((expr = dyn_cast<Expr>(bodyIterator))) {
3800 break;
3801 }
3802 }
3803 if (expr)
Aaron Ballman01dc1572016-01-20 15:25:30 +00003804 return const_cast<CXEvalResult>(
3805 reinterpret_cast<const void *>(evaluateExpr(expr, C)));
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003806 }
3807 return nullptr;
3808}
3809
3810unsigned clang_Cursor_hasAttrs(CXCursor C) {
3811 const Decl *D = getCursorDecl(C);
3812 if (!D) {
3813 return 0;
3814 }
3815
3816 if (D->hasAttrs()) {
3817 return 1;
3818 }
3819
3820 return 0;
3821}
Guy Benyei11169dd2012-12-18 14:30:41 +00003822unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
3823 return CXSaveTranslationUnit_None;
3824}
3825
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003826static CXSaveError clang_saveTranslationUnit_Impl(CXTranslationUnit TU,
3827 const char *FileName,
3828 unsigned options) {
3829 CIndexer *CXXIdx = TU->CIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00003830 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
3831 setThreadBackgroundPriority();
3832
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003833 bool hadError = cxtu::getASTUnit(TU)->Save(FileName);
3834 return hadError ? CXSaveError_Unknown : CXSaveError_None;
Guy Benyei11169dd2012-12-18 14:30:41 +00003835}
3836
3837int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
3838 unsigned options) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00003839 LOG_FUNC_SECTION {
3840 *Log << TU << ' ' << FileName;
3841 }
3842
Dmitri Gribenko852d6222014-02-11 15:02:48 +00003843 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00003844 LOG_BAD_TU(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00003845 return CXSaveError_InvalidTU;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00003846 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003847
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00003848 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00003849 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3850 if (!CXXUnit->hasSema())
3851 return CXSaveError_InvalidTU;
3852
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003853 CXSaveError result;
3854 auto SaveTranslationUnitImpl = [=, &result]() {
3855 result = clang_saveTranslationUnit_Impl(TU, FileName, options);
3856 };
Guy Benyei11169dd2012-12-18 14:30:41 +00003857
3858 if (!CXXUnit->getDiagnostics().hasUnrecoverableErrorOccurred() ||
3859 getenv("LIBCLANG_NOTHREADS")) {
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003860 SaveTranslationUnitImpl();
Guy Benyei11169dd2012-12-18 14:30:41 +00003861
3862 if (getenv("LIBCLANG_RESOURCE_USAGE"))
3863 PrintLibclangResourceUsage(TU);
3864
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003865 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003866 }
3867
3868 // We have an AST that has invalid nodes due to compiler errors.
3869 // Use a crash recovery thread for protection.
3870
3871 llvm::CrashRecoveryContext CRC;
3872
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003873 if (!RunSafely(CRC, SaveTranslationUnitImpl)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003874 fprintf(stderr, "libclang: crash detected during AST saving: {\n");
3875 fprintf(stderr, " 'filename' : '%s'\n", FileName);
3876 fprintf(stderr, " 'options' : %d,\n", options);
3877 fprintf(stderr, "}\n");
3878
3879 return CXSaveError_Unknown;
3880
3881 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
3882 PrintLibclangResourceUsage(TU);
3883 }
3884
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003885 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003886}
3887
3888void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
3889 if (CTUnit) {
3890 // If the translation unit has been marked as unsafe to free, just discard
3891 // it.
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003892 ASTUnit *Unit = cxtu::getASTUnit(CTUnit);
3893 if (Unit && Unit->isUnsafeToFree())
Guy Benyei11169dd2012-12-18 14:30:41 +00003894 return;
3895
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00003896 delete cxtu::getASTUnit(CTUnit);
Dmitri Gribenkob95b3f12013-01-26 22:44:19 +00003897 delete CTUnit->StringPool;
Guy Benyei11169dd2012-12-18 14:30:41 +00003898 delete static_cast<CXDiagnosticSetImpl *>(CTUnit->Diagnostics);
3899 disposeOverridenCXCursorsPool(CTUnit->OverridenCursorsPool);
Dmitri Gribenko9e605112013-11-13 22:16:51 +00003900 delete CTUnit->CommentToXML;
Guy Benyei11169dd2012-12-18 14:30:41 +00003901 delete CTUnit;
3902 }
3903}
3904
3905unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
3906 return CXReparse_None;
3907}
3908
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003909static CXErrorCode
3910clang_reparseTranslationUnit_Impl(CXTranslationUnit TU,
3911 ArrayRef<CXUnsavedFile> unsaved_files,
3912 unsigned options) {
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003913 // Check arguments.
Dmitri Gribenko852d6222014-02-11 15:02:48 +00003914 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00003915 LOG_BAD_TU(TU);
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003916 return CXError_InvalidArguments;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003917 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003918
3919 // Reset the associated diagnostics.
3920 delete static_cast<CXDiagnosticSetImpl*>(TU->Diagnostics);
Craig Topper69186e72014-06-08 08:38:04 +00003921 TU->Diagnostics = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00003922
Dmitri Gribenko183436e2013-01-26 21:49:50 +00003923 CIndexer *CXXIdx = TU->CIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00003924 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing))
3925 setThreadBackgroundPriority();
3926
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00003927 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00003928 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ahmed Charlesb8984322014-03-07 20:03:18 +00003929
3930 std::unique_ptr<std::vector<ASTUnit::RemappedFile>> RemappedFiles(
3931 new std::vector<ASTUnit::RemappedFile>());
3932
Guy Benyei11169dd2012-12-18 14:30:41 +00003933 // Recover resources if we crash before exiting this function.
3934 llvm::CrashRecoveryContextCleanupRegistrar<
3935 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
Alp Toker9d85b182014-07-07 01:23:14 +00003936
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003937 for (auto &UF : unsaved_files) {
Rafael Espindolad87f8d72014-08-27 20:03:29 +00003938 std::unique_ptr<llvm::MemoryBuffer> MB =
Alp Toker9d85b182014-07-07 01:23:14 +00003939 llvm::MemoryBuffer::getMemBufferCopy(getContents(UF), UF.Filename);
Rafael Espindolad87f8d72014-08-27 20:03:29 +00003940 RemappedFiles->push_back(std::make_pair(UF.Filename, MB.release()));
Guy Benyei11169dd2012-12-18 14:30:41 +00003941 }
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003942
Adrian Prantlbb165fb2015-06-20 18:53:08 +00003943 if (!CXXUnit->Reparse(CXXIdx->getPCHContainerOperations(),
3944 *RemappedFiles.get()))
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003945 return CXError_Success;
3946 if (isASTReadError(CXXUnit))
3947 return CXError_ASTReadError;
3948 return CXError_Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003949}
3950
3951int clang_reparseTranslationUnit(CXTranslationUnit TU,
3952 unsigned num_unsaved_files,
3953 struct CXUnsavedFile *unsaved_files,
3954 unsigned options) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00003955 LOG_FUNC_SECTION {
3956 *Log << TU;
3957 }
3958
Alp Toker9d85b182014-07-07 01:23:14 +00003959 if (num_unsaved_files && !unsaved_files)
3960 return CXError_InvalidArguments;
3961
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003962 CXErrorCode result;
3963 auto ReparseTranslationUnitImpl = [=, &result]() {
3964 result = clang_reparseTranslationUnit_Impl(
3965 TU, llvm::makeArrayRef(unsaved_files, num_unsaved_files), options);
3966 };
Guy Benyei11169dd2012-12-18 14:30:41 +00003967
3968 if (getenv("LIBCLANG_NOTHREADS")) {
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003969 ReparseTranslationUnitImpl();
Alp Toker5c532982014-07-07 22:42:03 +00003970 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003971 }
3972
3973 llvm::CrashRecoveryContext CRC;
3974
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003975 if (!RunSafely(CRC, ReparseTranslationUnitImpl)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003976 fprintf(stderr, "libclang: crash detected during reparsing\n");
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00003977 cxtu::getASTUnit(TU)->setUnsafeToFree(true);
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003978 return CXError_Crashed;
Guy Benyei11169dd2012-12-18 14:30:41 +00003979 } else if (getenv("LIBCLANG_RESOURCE_USAGE"))
3980 PrintLibclangResourceUsage(TU);
3981
Alp Toker5c532982014-07-07 22:42:03 +00003982 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003983}
3984
3985
3986CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00003987 if (isNotUsableTU(CTUnit)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00003988 LOG_BAD_TU(CTUnit);
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00003989 return cxstring::createEmpty();
Dmitri Gribenko256454f2014-02-11 14:34:14 +00003990 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003991
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00003992 ASTUnit *CXXUnit = cxtu::getASTUnit(CTUnit);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00003993 return cxstring::createDup(CXXUnit->getOriginalSourceFileName());
Guy Benyei11169dd2012-12-18 14:30:41 +00003994}
3995
3996CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00003997 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00003998 LOG_BAD_TU(TU);
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00003999 return clang_getNullCursor();
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004000 }
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00004001
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004002 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004003 return MakeCXCursor(CXXUnit->getASTContext().getTranslationUnitDecl(), TU);
4004}
4005
Guy Benyei11169dd2012-12-18 14:30:41 +00004006//===----------------------------------------------------------------------===//
4007// CXFile Operations.
4008//===----------------------------------------------------------------------===//
4009
Guy Benyei11169dd2012-12-18 14:30:41 +00004010CXString clang_getFileName(CXFile SFile) {
4011 if (!SFile)
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00004012 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00004013
4014 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004015 return cxstring::createRef(FEnt->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004016}
4017
4018time_t clang_getFileTime(CXFile SFile) {
4019 if (!SFile)
4020 return 0;
4021
4022 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
4023 return FEnt->getModificationTime();
4024}
4025
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004026CXFile clang_getFile(CXTranslationUnit TU, const char *file_name) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004027 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004028 LOG_BAD_TU(TU);
Craig Topper69186e72014-06-08 08:38:04 +00004029 return nullptr;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004030 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004031
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004032 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004033
4034 FileManager &FMgr = CXXUnit->getFileManager();
4035 return const_cast<FileEntry *>(FMgr.getFile(file_name));
4036}
4037
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004038unsigned clang_isFileMultipleIncludeGuarded(CXTranslationUnit TU,
4039 CXFile file) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004040 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004041 LOG_BAD_TU(TU);
4042 return 0;
4043 }
4044
4045 if (!file)
Guy Benyei11169dd2012-12-18 14:30:41 +00004046 return 0;
4047
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004048 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004049 FileEntry *FEnt = static_cast<FileEntry *>(file);
4050 return CXXUnit->getPreprocessor().getHeaderSearchInfo()
4051 .isFileMultipleIncludeGuarded(FEnt);
4052}
4053
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00004054int clang_getFileUniqueID(CXFile file, CXFileUniqueID *outID) {
4055 if (!file || !outID)
4056 return 1;
4057
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00004058 FileEntry *FEnt = static_cast<FileEntry *>(file);
Rafael Espindolaf8f91b82013-08-01 21:42:11 +00004059 const llvm::sys::fs::UniqueID &ID = FEnt->getUniqueID();
4060 outID->data[0] = ID.getDevice();
4061 outID->data[1] = ID.getFile();
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00004062 outID->data[2] = FEnt->getModificationTime();
4063 return 0;
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00004064}
4065
Argyrios Kyrtzidisac3997e2014-08-16 00:26:19 +00004066int clang_File_isEqual(CXFile file1, CXFile file2) {
4067 if (file1 == file2)
4068 return true;
4069
4070 if (!file1 || !file2)
4071 return false;
4072
4073 FileEntry *FEnt1 = static_cast<FileEntry *>(file1);
4074 FileEntry *FEnt2 = static_cast<FileEntry *>(file2);
4075 return FEnt1->getUniqueID() == FEnt2->getUniqueID();
4076}
4077
Guy Benyei11169dd2012-12-18 14:30:41 +00004078//===----------------------------------------------------------------------===//
4079// CXCursor Operations.
4080//===----------------------------------------------------------------------===//
4081
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004082static const Decl *getDeclFromExpr(const Stmt *E) {
4083 if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004084 return getDeclFromExpr(CE->getSubExpr());
4085
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004086 if (const DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004087 return RefExpr->getDecl();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004088 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004089 return ME->getMemberDecl();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004090 if (const ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004091 return RE->getDecl();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004092 if (const ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004093 if (PRE->isExplicitProperty())
4094 return PRE->getExplicitProperty();
4095 // It could be messaging both getter and setter as in:
4096 // ++myobj.myprop;
4097 // in which case prefer to associate the setter since it is less obvious
4098 // from inspecting the source that the setter is going to get called.
4099 if (PRE->isMessagingSetter())
4100 return PRE->getImplicitPropertySetter();
4101 return PRE->getImplicitPropertyGetter();
4102 }
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004103 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004104 return getDeclFromExpr(POE->getSyntacticForm());
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004105 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004106 if (Expr *Src = OVE->getSourceExpr())
4107 return getDeclFromExpr(Src);
4108
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004109 if (const CallExpr *CE = dyn_cast<CallExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004110 return getDeclFromExpr(CE->getCallee());
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004111 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004112 if (!CE->isElidable())
4113 return CE->getConstructor();
Richard Smith5179eb72016-06-28 19:03:57 +00004114 if (const CXXInheritedCtorInitExpr *CE =
4115 dyn_cast<CXXInheritedCtorInitExpr>(E))
4116 return CE->getConstructor();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004117 if (const ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004118 return OME->getMethodDecl();
4119
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004120 if (const ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004121 return PE->getProtocol();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004122 if (const SubstNonTypeTemplateParmPackExpr *NTTP
Guy Benyei11169dd2012-12-18 14:30:41 +00004123 = dyn_cast<SubstNonTypeTemplateParmPackExpr>(E))
4124 return NTTP->getParameterPack();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004125 if (const SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004126 if (isa<NonTypeTemplateParmDecl>(SizeOfPack->getPack()) ||
4127 isa<ParmVarDecl>(SizeOfPack->getPack()))
4128 return SizeOfPack->getPack();
Craig Topper69186e72014-06-08 08:38:04 +00004129
4130 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004131}
4132
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004133static SourceLocation getLocationFromExpr(const Expr *E) {
4134 if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004135 return getLocationFromExpr(CE->getSubExpr());
4136
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004137 if (const ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004138 return /*FIXME:*/Msg->getLeftLoc();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004139 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004140 return DRE->getLocation();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004141 if (const MemberExpr *Member = dyn_cast<MemberExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004142 return Member->getMemberLoc();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004143 if (const ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004144 return Ivar->getLocation();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004145 if (const SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004146 return SizeOfPack->getPackLoc();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004147 if (const ObjCPropertyRefExpr *PropRef = dyn_cast<ObjCPropertyRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004148 return PropRef->getLocation();
4149
4150 return E->getLocStart();
4151}
4152
NAKAMURA Takumia01f4c32016-12-19 16:50:43 +00004153extern "C" {
4154
Guy Benyei11169dd2012-12-18 14:30:41 +00004155unsigned clang_visitChildren(CXCursor parent,
4156 CXCursorVisitor visitor,
4157 CXClientData client_data) {
4158 CursorVisitor CursorVis(getCursorTU(parent), visitor, client_data,
4159 /*VisitPreprocessorLast=*/false);
4160 return CursorVis.VisitChildren(parent);
4161}
4162
4163#ifndef __has_feature
4164#define __has_feature(x) 0
4165#endif
4166#if __has_feature(blocks)
4167typedef enum CXChildVisitResult
4168 (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
4169
4170static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
4171 CXClientData client_data) {
4172 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
4173 return block(cursor, parent);
4174}
4175#else
4176// If we are compiled with a compiler that doesn't have native blocks support,
4177// define and call the block manually, so the
4178typedef struct _CXChildVisitResult
4179{
4180 void *isa;
4181 int flags;
4182 int reserved;
4183 enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor,
4184 CXCursor);
4185} *CXCursorVisitorBlock;
4186
4187static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
4188 CXClientData client_data) {
4189 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
4190 return block->invoke(block, cursor, parent);
4191}
4192#endif
4193
4194
4195unsigned clang_visitChildrenWithBlock(CXCursor parent,
4196 CXCursorVisitorBlock block) {
4197 return clang_visitChildren(parent, visitWithBlock, block);
4198}
4199
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004200static CXString getDeclSpelling(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004201 if (!D)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004202 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004203
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004204 const NamedDecl *ND = dyn_cast<NamedDecl>(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00004205 if (!ND) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004206 if (const ObjCPropertyImplDecl *PropImpl =
4207 dyn_cast<ObjCPropertyImplDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00004208 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004209 return cxstring::createDup(Property->getIdentifier()->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004210
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004211 if (const ImportDecl *ImportD = dyn_cast<ImportDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00004212 if (Module *Mod = ImportD->getImportedModule())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004213 return cxstring::createDup(Mod->getFullModuleName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004214
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004215 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004216 }
4217
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004218 if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004219 return cxstring::createDup(OMD->getSelector().getAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004220
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004221 if (const ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
Guy Benyei11169dd2012-12-18 14:30:41 +00004222 // No, this isn't the same as the code below. getIdentifier() is non-virtual
4223 // and returns different names. NamedDecl returns the class name and
4224 // ObjCCategoryImplDecl returns the category name.
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004225 return cxstring::createRef(CIMP->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004226
4227 if (isa<UsingDirectiveDecl>(D))
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004228 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004229
4230 SmallString<1024> S;
4231 llvm::raw_svector_ostream os(S);
4232 ND->printName(os);
4233
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004234 return cxstring::createDup(os.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00004235}
4236
4237CXString clang_getCursorSpelling(CXCursor C) {
4238 if (clang_isTranslationUnit(C.kind))
Dmitri Gribenko2c173b42013-01-11 19:28:44 +00004239 return clang_getTranslationUnitSpelling(getCursorTU(C));
Guy Benyei11169dd2012-12-18 14:30:41 +00004240
4241 if (clang_isReference(C.kind)) {
4242 switch (C.kind) {
4243 case CXCursor_ObjCSuperClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004244 const ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004245 return cxstring::createRef(Super->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004246 }
4247 case CXCursor_ObjCClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004248 const ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004249 return cxstring::createRef(Class->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004250 }
4251 case CXCursor_ObjCProtocolRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004252 const ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004253 assert(OID && "getCursorSpelling(): Missing protocol decl");
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004254 return cxstring::createRef(OID->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004255 }
4256 case CXCursor_CXXBaseSpecifier: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004257 const CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004258 return cxstring::createDup(B->getType().getAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004259 }
4260 case CXCursor_TypeRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004261 const TypeDecl *Type = getCursorTypeRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004262 assert(Type && "Missing type decl");
4263
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004264 return cxstring::createDup(getCursorContext(C).getTypeDeclType(Type).
Guy Benyei11169dd2012-12-18 14:30:41 +00004265 getAsString());
4266 }
4267 case CXCursor_TemplateRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004268 const TemplateDecl *Template = getCursorTemplateRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004269 assert(Template && "Missing template decl");
4270
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004271 return cxstring::createDup(Template->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004272 }
4273
4274 case CXCursor_NamespaceRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004275 const NamedDecl *NS = getCursorNamespaceRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004276 assert(NS && "Missing namespace decl");
4277
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004278 return cxstring::createDup(NS->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004279 }
4280
4281 case CXCursor_MemberRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004282 const FieldDecl *Field = getCursorMemberRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004283 assert(Field && "Missing member decl");
4284
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004285 return cxstring::createDup(Field->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004286 }
4287
4288 case CXCursor_LabelRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004289 const LabelStmt *Label = getCursorLabelRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004290 assert(Label && "Missing label");
4291
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004292 return cxstring::createRef(Label->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004293 }
4294
4295 case CXCursor_OverloadedDeclRef: {
4296 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004297 if (const Decl *D = Storage.dyn_cast<const Decl *>()) {
4298 if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004299 return cxstring::createDup(ND->getNameAsString());
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004300 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004301 }
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004302 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004303 return cxstring::createDup(E->getName().getAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004304 OverloadedTemplateStorage *Ovl
4305 = Storage.get<OverloadedTemplateStorage*>();
4306 if (Ovl->size() == 0)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004307 return cxstring::createEmpty();
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004308 return cxstring::createDup((*Ovl->begin())->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004309 }
4310
4311 case CXCursor_VariableRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004312 const VarDecl *Var = getCursorVariableRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004313 assert(Var && "Missing variable decl");
4314
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004315 return cxstring::createDup(Var->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004316 }
4317
4318 default:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004319 return cxstring::createRef("<not implemented>");
Guy Benyei11169dd2012-12-18 14:30:41 +00004320 }
4321 }
4322
4323 if (clang_isExpression(C.kind)) {
Argyrios Kyrtzidis3227d862014-03-03 19:40:52 +00004324 const Expr *E = getCursorExpr(C);
4325
4326 if (C.kind == CXCursor_ObjCStringLiteral ||
4327 C.kind == CXCursor_StringLiteral) {
4328 const StringLiteral *SLit;
4329 if (const ObjCStringLiteral *OSL = dyn_cast<ObjCStringLiteral>(E)) {
4330 SLit = OSL->getString();
4331 } else {
4332 SLit = cast<StringLiteral>(E);
4333 }
4334 SmallString<256> Buf;
4335 llvm::raw_svector_ostream OS(Buf);
4336 SLit->outputString(OS);
4337 return cxstring::createDup(OS.str());
4338 }
4339
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004340 const Decl *D = getDeclFromExpr(getCursorExpr(C));
Guy Benyei11169dd2012-12-18 14:30:41 +00004341 if (D)
4342 return getDeclSpelling(D);
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004343 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004344 }
4345
4346 if (clang_isStatement(C.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004347 const Stmt *S = getCursorStmt(C);
4348 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004349 return cxstring::createRef(Label->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004350
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004351 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004352 }
4353
4354 if (C.kind == CXCursor_MacroExpansion)
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004355 return cxstring::createRef(getCursorMacroExpansion(C).getName()
Guy Benyei11169dd2012-12-18 14:30:41 +00004356 ->getNameStart());
4357
4358 if (C.kind == CXCursor_MacroDefinition)
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004359 return cxstring::createRef(getCursorMacroDefinition(C)->getName()
Guy Benyei11169dd2012-12-18 14:30:41 +00004360 ->getNameStart());
4361
4362 if (C.kind == CXCursor_InclusionDirective)
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004363 return cxstring::createDup(getCursorInclusionDirective(C)->getFileName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004364
4365 if (clang_isDeclaration(C.kind))
4366 return getDeclSpelling(getCursorDecl(C));
4367
4368 if (C.kind == CXCursor_AnnotateAttr) {
Dmitri Gribenkoe4baea62013-01-26 18:08:08 +00004369 const AnnotateAttr *AA = cast<AnnotateAttr>(cxcursor::getCursorAttr(C));
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004370 return cxstring::createDup(AA->getAnnotation());
Guy Benyei11169dd2012-12-18 14:30:41 +00004371 }
4372
4373 if (C.kind == CXCursor_AsmLabelAttr) {
Dmitri Gribenkoe4baea62013-01-26 18:08:08 +00004374 const AsmLabelAttr *AA = cast<AsmLabelAttr>(cxcursor::getCursorAttr(C));
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004375 return cxstring::createDup(AA->getLabel());
Guy Benyei11169dd2012-12-18 14:30:41 +00004376 }
4377
Argyrios Kyrtzidis16834f12013-09-25 00:14:38 +00004378 if (C.kind == CXCursor_PackedAttr) {
4379 return cxstring::createRef("packed");
4380 }
4381
Saleem Abdulrasool79c69712015-09-05 18:53:43 +00004382 if (C.kind == CXCursor_VisibilityAttr) {
4383 const VisibilityAttr *AA = cast<VisibilityAttr>(cxcursor::getCursorAttr(C));
4384 switch (AA->getVisibility()) {
4385 case VisibilityAttr::VisibilityType::Default:
4386 return cxstring::createRef("default");
4387 case VisibilityAttr::VisibilityType::Hidden:
4388 return cxstring::createRef("hidden");
4389 case VisibilityAttr::VisibilityType::Protected:
4390 return cxstring::createRef("protected");
4391 }
4392 llvm_unreachable("unknown visibility type");
4393 }
4394
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004395 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004396}
4397
4398CXSourceRange clang_Cursor_getSpellingNameRange(CXCursor C,
4399 unsigned pieceIndex,
4400 unsigned options) {
4401 if (clang_Cursor_isNull(C))
4402 return clang_getNullRange();
4403
4404 ASTContext &Ctx = getCursorContext(C);
4405
4406 if (clang_isStatement(C.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004407 const Stmt *S = getCursorStmt(C);
4408 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004409 if (pieceIndex > 0)
4410 return clang_getNullRange();
4411 return cxloc::translateSourceRange(Ctx, Label->getIdentLoc());
4412 }
4413
4414 return clang_getNullRange();
4415 }
4416
4417 if (C.kind == CXCursor_ObjCMessageExpr) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004418 if (const ObjCMessageExpr *
Guy Benyei11169dd2012-12-18 14:30:41 +00004419 ME = dyn_cast_or_null<ObjCMessageExpr>(getCursorExpr(C))) {
4420 if (pieceIndex >= ME->getNumSelectorLocs())
4421 return clang_getNullRange();
4422 return cxloc::translateSourceRange(Ctx, ME->getSelectorLoc(pieceIndex));
4423 }
4424 }
4425
4426 if (C.kind == CXCursor_ObjCInstanceMethodDecl ||
4427 C.kind == CXCursor_ObjCClassMethodDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004428 if (const ObjCMethodDecl *
Guy Benyei11169dd2012-12-18 14:30:41 +00004429 MD = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(C))) {
4430 if (pieceIndex >= MD->getNumSelectorLocs())
4431 return clang_getNullRange();
4432 return cxloc::translateSourceRange(Ctx, MD->getSelectorLoc(pieceIndex));
4433 }
4434 }
4435
4436 if (C.kind == CXCursor_ObjCCategoryDecl ||
4437 C.kind == CXCursor_ObjCCategoryImplDecl) {
4438 if (pieceIndex > 0)
4439 return clang_getNullRange();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004440 if (const ObjCCategoryDecl *
Guy Benyei11169dd2012-12-18 14:30:41 +00004441 CD = dyn_cast_or_null<ObjCCategoryDecl>(getCursorDecl(C)))
4442 return cxloc::translateSourceRange(Ctx, CD->getCategoryNameLoc());
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004443 if (const ObjCCategoryImplDecl *
Guy Benyei11169dd2012-12-18 14:30:41 +00004444 CID = dyn_cast_or_null<ObjCCategoryImplDecl>(getCursorDecl(C)))
4445 return cxloc::translateSourceRange(Ctx, CID->getCategoryNameLoc());
4446 }
4447
4448 if (C.kind == CXCursor_ModuleImportDecl) {
4449 if (pieceIndex > 0)
4450 return clang_getNullRange();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004451 if (const ImportDecl *ImportD =
4452 dyn_cast_or_null<ImportDecl>(getCursorDecl(C))) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004453 ArrayRef<SourceLocation> Locs = ImportD->getIdentifierLocs();
4454 if (!Locs.empty())
4455 return cxloc::translateSourceRange(Ctx,
4456 SourceRange(Locs.front(), Locs.back()));
4457 }
4458 return clang_getNullRange();
4459 }
4460
Argyrios Kyrtzidisa2a1e532014-08-26 20:23:26 +00004461 if (C.kind == CXCursor_CXXMethod || C.kind == CXCursor_Destructor ||
Kevin Funk4be5d672016-12-20 09:56:56 +00004462 C.kind == CXCursor_ConversionFunction ||
4463 C.kind == CXCursor_FunctionDecl) {
Argyrios Kyrtzidisa2a1e532014-08-26 20:23:26 +00004464 if (pieceIndex > 0)
4465 return clang_getNullRange();
4466 if (const FunctionDecl *FD =
4467 dyn_cast_or_null<FunctionDecl>(getCursorDecl(C))) {
4468 DeclarationNameInfo FunctionName = FD->getNameInfo();
4469 return cxloc::translateSourceRange(Ctx, FunctionName.getSourceRange());
4470 }
4471 return clang_getNullRange();
4472 }
4473
Guy Benyei11169dd2012-12-18 14:30:41 +00004474 // FIXME: A CXCursor_InclusionDirective should give the location of the
4475 // filename, but we don't keep track of this.
4476
4477 // FIXME: A CXCursor_AnnotateAttr should give the location of the annotation
4478 // but we don't keep track of this.
4479
4480 // FIXME: A CXCursor_AsmLabelAttr should give the location of the label
4481 // but we don't keep track of this.
4482
4483 // Default handling, give the location of the cursor.
4484
4485 if (pieceIndex > 0)
4486 return clang_getNullRange();
4487
4488 CXSourceLocation CXLoc = clang_getCursorLocation(C);
4489 SourceLocation Loc = cxloc::translateSourceLocation(CXLoc);
4490 return cxloc::translateSourceRange(Ctx, Loc);
4491}
4492
Eli Bendersky44a206f2014-07-31 18:04:56 +00004493CXString clang_Cursor_getMangling(CXCursor C) {
4494 if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
4495 return cxstring::createEmpty();
4496
Eli Bendersky44a206f2014-07-31 18:04:56 +00004497 // Mangling only works for functions and variables.
Eli Bendersky79759592014-08-01 15:01:10 +00004498 const Decl *D = getCursorDecl(C);
Eli Bendersky44a206f2014-07-31 18:04:56 +00004499 if (!D || !(isa<FunctionDecl>(D) || isa<VarDecl>(D)))
4500 return cxstring::createEmpty();
4501
Argyrios Kyrtzidisca741ce2016-02-14 22:30:14 +00004502 ASTContext &Ctx = D->getASTContext();
4503 index::CodegenNameGenerator CGNameGen(Ctx);
4504 return cxstring::createDup(CGNameGen.getName(D));
Eli Bendersky44a206f2014-07-31 18:04:56 +00004505}
4506
Saleem Abdulrasool60034432015-11-12 03:57:22 +00004507CXStringSet *clang_Cursor_getCXXManglings(CXCursor C) {
4508 if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
4509 return nullptr;
4510
4511 const Decl *D = getCursorDecl(C);
4512 if (!(isa<CXXRecordDecl>(D) || isa<CXXMethodDecl>(D)))
4513 return nullptr;
4514
Argyrios Kyrtzidisca741ce2016-02-14 22:30:14 +00004515 ASTContext &Ctx = D->getASTContext();
4516 index::CodegenNameGenerator CGNameGen(Ctx);
4517 std::vector<std::string> Manglings = CGNameGen.getAllManglings(D);
Saleem Abdulrasool60034432015-11-12 03:57:22 +00004518 return cxstring::createSet(Manglings);
4519}
4520
Guy Benyei11169dd2012-12-18 14:30:41 +00004521CXString clang_getCursorDisplayName(CXCursor C) {
4522 if (!clang_isDeclaration(C.kind))
4523 return clang_getCursorSpelling(C);
4524
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004525 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00004526 if (!D)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004527 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004528
4529 PrintingPolicy Policy = getCursorContext(C).getPrintingPolicy();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004530 if (const FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00004531 D = FunTmpl->getTemplatedDecl();
4532
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004533 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004534 SmallString<64> Str;
4535 llvm::raw_svector_ostream OS(Str);
4536 OS << *Function;
4537 if (Function->getPrimaryTemplate())
4538 OS << "<>";
4539 OS << "(";
4540 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
4541 if (I)
4542 OS << ", ";
4543 OS << Function->getParamDecl(I)->getType().getAsString(Policy);
4544 }
4545
4546 if (Function->isVariadic()) {
4547 if (Function->getNumParams())
4548 OS << ", ";
4549 OS << "...";
4550 }
4551 OS << ")";
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004552 return cxstring::createDup(OS.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00004553 }
4554
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004555 if (const ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004556 SmallString<64> Str;
4557 llvm::raw_svector_ostream OS(Str);
4558 OS << *ClassTemplate;
4559 OS << "<";
4560 TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
4561 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
4562 if (I)
4563 OS << ", ";
4564
4565 NamedDecl *Param = Params->getParam(I);
4566 if (Param->getIdentifier()) {
4567 OS << Param->getIdentifier()->getName();
4568 continue;
4569 }
4570
4571 // There is no parameter name, which makes this tricky. Try to come up
4572 // with something useful that isn't too long.
4573 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
4574 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
4575 else if (NonTypeTemplateParmDecl *NTTP
4576 = dyn_cast<NonTypeTemplateParmDecl>(Param))
4577 OS << NTTP->getType().getAsString(Policy);
4578 else
4579 OS << "template<...> class";
4580 }
4581
4582 OS << ">";
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004583 return cxstring::createDup(OS.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00004584 }
4585
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004586 if (const ClassTemplateSpecializationDecl *ClassSpec
Guy Benyei11169dd2012-12-18 14:30:41 +00004587 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
4588 // If the type was explicitly written, use that.
4589 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004590 return cxstring::createDup(TSInfo->getType().getAsString(Policy));
Guy Benyei11169dd2012-12-18 14:30:41 +00004591
Benjamin Kramer9170e912013-02-22 15:46:01 +00004592 SmallString<128> Str;
Guy Benyei11169dd2012-12-18 14:30:41 +00004593 llvm::raw_svector_ostream OS(Str);
4594 OS << *ClassSpec;
David Majnemer6fbeee32016-07-07 04:43:07 +00004595 TemplateSpecializationType::PrintTemplateArgumentList(
4596 OS, ClassSpec->getTemplateArgs().asArray(), Policy);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004597 return cxstring::createDup(OS.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00004598 }
4599
4600 return clang_getCursorSpelling(C);
4601}
4602
4603CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
4604 switch (Kind) {
4605 case CXCursor_FunctionDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004606 return cxstring::createRef("FunctionDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004607 case CXCursor_TypedefDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004608 return cxstring::createRef("TypedefDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004609 case CXCursor_EnumDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004610 return cxstring::createRef("EnumDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004611 case CXCursor_EnumConstantDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004612 return cxstring::createRef("EnumConstantDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004613 case CXCursor_StructDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004614 return cxstring::createRef("StructDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004615 case CXCursor_UnionDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004616 return cxstring::createRef("UnionDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004617 case CXCursor_ClassDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004618 return cxstring::createRef("ClassDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004619 case CXCursor_FieldDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004620 return cxstring::createRef("FieldDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004621 case CXCursor_VarDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004622 return cxstring::createRef("VarDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004623 case CXCursor_ParmDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004624 return cxstring::createRef("ParmDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004625 case CXCursor_ObjCInterfaceDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004626 return cxstring::createRef("ObjCInterfaceDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004627 case CXCursor_ObjCCategoryDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004628 return cxstring::createRef("ObjCCategoryDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004629 case CXCursor_ObjCProtocolDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004630 return cxstring::createRef("ObjCProtocolDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004631 case CXCursor_ObjCPropertyDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004632 return cxstring::createRef("ObjCPropertyDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004633 case CXCursor_ObjCIvarDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004634 return cxstring::createRef("ObjCIvarDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004635 case CXCursor_ObjCInstanceMethodDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004636 return cxstring::createRef("ObjCInstanceMethodDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004637 case CXCursor_ObjCClassMethodDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004638 return cxstring::createRef("ObjCClassMethodDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004639 case CXCursor_ObjCImplementationDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004640 return cxstring::createRef("ObjCImplementationDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004641 case CXCursor_ObjCCategoryImplDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004642 return cxstring::createRef("ObjCCategoryImplDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004643 case CXCursor_CXXMethod:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004644 return cxstring::createRef("CXXMethod");
Guy Benyei11169dd2012-12-18 14:30:41 +00004645 case CXCursor_UnexposedDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004646 return cxstring::createRef("UnexposedDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004647 case CXCursor_ObjCSuperClassRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004648 return cxstring::createRef("ObjCSuperClassRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00004649 case CXCursor_ObjCProtocolRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004650 return cxstring::createRef("ObjCProtocolRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00004651 case CXCursor_ObjCClassRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004652 return cxstring::createRef("ObjCClassRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00004653 case CXCursor_TypeRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004654 return cxstring::createRef("TypeRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00004655 case CXCursor_TemplateRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004656 return cxstring::createRef("TemplateRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00004657 case CXCursor_NamespaceRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004658 return cxstring::createRef("NamespaceRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00004659 case CXCursor_MemberRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004660 return cxstring::createRef("MemberRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00004661 case CXCursor_LabelRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004662 return cxstring::createRef("LabelRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00004663 case CXCursor_OverloadedDeclRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004664 return cxstring::createRef("OverloadedDeclRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00004665 case CXCursor_VariableRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004666 return cxstring::createRef("VariableRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00004667 case CXCursor_IntegerLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004668 return cxstring::createRef("IntegerLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00004669 case CXCursor_FloatingLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004670 return cxstring::createRef("FloatingLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00004671 case CXCursor_ImaginaryLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004672 return cxstring::createRef("ImaginaryLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00004673 case CXCursor_StringLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004674 return cxstring::createRef("StringLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00004675 case CXCursor_CharacterLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004676 return cxstring::createRef("CharacterLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00004677 case CXCursor_ParenExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004678 return cxstring::createRef("ParenExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004679 case CXCursor_UnaryOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004680 return cxstring::createRef("UnaryOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00004681 case CXCursor_ArraySubscriptExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004682 return cxstring::createRef("ArraySubscriptExpr");
Alexey Bataev1a3320e2015-08-25 14:24:04 +00004683 case CXCursor_OMPArraySectionExpr:
4684 return cxstring::createRef("OMPArraySectionExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004685 case CXCursor_BinaryOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004686 return cxstring::createRef("BinaryOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00004687 case CXCursor_CompoundAssignOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004688 return cxstring::createRef("CompoundAssignOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00004689 case CXCursor_ConditionalOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004690 return cxstring::createRef("ConditionalOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00004691 case CXCursor_CStyleCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004692 return cxstring::createRef("CStyleCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004693 case CXCursor_CompoundLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004694 return cxstring::createRef("CompoundLiteralExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004695 case CXCursor_InitListExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004696 return cxstring::createRef("InitListExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004697 case CXCursor_AddrLabelExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004698 return cxstring::createRef("AddrLabelExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004699 case CXCursor_StmtExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004700 return cxstring::createRef("StmtExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004701 case CXCursor_GenericSelectionExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004702 return cxstring::createRef("GenericSelectionExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004703 case CXCursor_GNUNullExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004704 return cxstring::createRef("GNUNullExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004705 case CXCursor_CXXStaticCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004706 return cxstring::createRef("CXXStaticCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004707 case CXCursor_CXXDynamicCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004708 return cxstring::createRef("CXXDynamicCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004709 case CXCursor_CXXReinterpretCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004710 return cxstring::createRef("CXXReinterpretCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004711 case CXCursor_CXXConstCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004712 return cxstring::createRef("CXXConstCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004713 case CXCursor_CXXFunctionalCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004714 return cxstring::createRef("CXXFunctionalCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004715 case CXCursor_CXXTypeidExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004716 return cxstring::createRef("CXXTypeidExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004717 case CXCursor_CXXBoolLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004718 return cxstring::createRef("CXXBoolLiteralExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004719 case CXCursor_CXXNullPtrLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004720 return cxstring::createRef("CXXNullPtrLiteralExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004721 case CXCursor_CXXThisExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004722 return cxstring::createRef("CXXThisExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004723 case CXCursor_CXXThrowExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004724 return cxstring::createRef("CXXThrowExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004725 case CXCursor_CXXNewExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004726 return cxstring::createRef("CXXNewExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004727 case CXCursor_CXXDeleteExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004728 return cxstring::createRef("CXXDeleteExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004729 case CXCursor_UnaryExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004730 return cxstring::createRef("UnaryExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004731 case CXCursor_ObjCStringLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004732 return cxstring::createRef("ObjCStringLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00004733 case CXCursor_ObjCBoolLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004734 return cxstring::createRef("ObjCBoolLiteralExpr");
Erik Pilkington29099de2016-07-16 00:35:23 +00004735 case CXCursor_ObjCAvailabilityCheckExpr:
4736 return cxstring::createRef("ObjCAvailabilityCheckExpr");
Argyrios Kyrtzidisc2233be2013-04-23 17:57:17 +00004737 case CXCursor_ObjCSelfExpr:
4738 return cxstring::createRef("ObjCSelfExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004739 case CXCursor_ObjCEncodeExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004740 return cxstring::createRef("ObjCEncodeExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004741 case CXCursor_ObjCSelectorExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004742 return cxstring::createRef("ObjCSelectorExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004743 case CXCursor_ObjCProtocolExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004744 return cxstring::createRef("ObjCProtocolExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004745 case CXCursor_ObjCBridgedCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004746 return cxstring::createRef("ObjCBridgedCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004747 case CXCursor_BlockExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004748 return cxstring::createRef("BlockExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004749 case CXCursor_PackExpansionExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004750 return cxstring::createRef("PackExpansionExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004751 case CXCursor_SizeOfPackExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004752 return cxstring::createRef("SizeOfPackExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004753 case CXCursor_LambdaExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004754 return cxstring::createRef("LambdaExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004755 case CXCursor_UnexposedExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004756 return cxstring::createRef("UnexposedExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004757 case CXCursor_DeclRefExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004758 return cxstring::createRef("DeclRefExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004759 case CXCursor_MemberRefExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004760 return cxstring::createRef("MemberRefExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004761 case CXCursor_CallExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004762 return cxstring::createRef("CallExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004763 case CXCursor_ObjCMessageExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004764 return cxstring::createRef("ObjCMessageExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004765 case CXCursor_UnexposedStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004766 return cxstring::createRef("UnexposedStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004767 case CXCursor_DeclStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004768 return cxstring::createRef("DeclStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004769 case CXCursor_LabelStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004770 return cxstring::createRef("LabelStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004771 case CXCursor_CompoundStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004772 return cxstring::createRef("CompoundStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004773 case CXCursor_CaseStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004774 return cxstring::createRef("CaseStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004775 case CXCursor_DefaultStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004776 return cxstring::createRef("DefaultStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004777 case CXCursor_IfStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004778 return cxstring::createRef("IfStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004779 case CXCursor_SwitchStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004780 return cxstring::createRef("SwitchStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004781 case CXCursor_WhileStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004782 return cxstring::createRef("WhileStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004783 case CXCursor_DoStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004784 return cxstring::createRef("DoStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004785 case CXCursor_ForStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004786 return cxstring::createRef("ForStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004787 case CXCursor_GotoStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004788 return cxstring::createRef("GotoStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004789 case CXCursor_IndirectGotoStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004790 return cxstring::createRef("IndirectGotoStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004791 case CXCursor_ContinueStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004792 return cxstring::createRef("ContinueStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004793 case CXCursor_BreakStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004794 return cxstring::createRef("BreakStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004795 case CXCursor_ReturnStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004796 return cxstring::createRef("ReturnStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004797 case CXCursor_GCCAsmStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004798 return cxstring::createRef("GCCAsmStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004799 case CXCursor_MSAsmStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004800 return cxstring::createRef("MSAsmStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004801 case CXCursor_ObjCAtTryStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004802 return cxstring::createRef("ObjCAtTryStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004803 case CXCursor_ObjCAtCatchStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004804 return cxstring::createRef("ObjCAtCatchStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004805 case CXCursor_ObjCAtFinallyStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004806 return cxstring::createRef("ObjCAtFinallyStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004807 case CXCursor_ObjCAtThrowStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004808 return cxstring::createRef("ObjCAtThrowStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004809 case CXCursor_ObjCAtSynchronizedStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004810 return cxstring::createRef("ObjCAtSynchronizedStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004811 case CXCursor_ObjCAutoreleasePoolStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004812 return cxstring::createRef("ObjCAutoreleasePoolStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004813 case CXCursor_ObjCForCollectionStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004814 return cxstring::createRef("ObjCForCollectionStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004815 case CXCursor_CXXCatchStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004816 return cxstring::createRef("CXXCatchStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004817 case CXCursor_CXXTryStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004818 return cxstring::createRef("CXXTryStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004819 case CXCursor_CXXForRangeStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004820 return cxstring::createRef("CXXForRangeStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004821 case CXCursor_SEHTryStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004822 return cxstring::createRef("SEHTryStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004823 case CXCursor_SEHExceptStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004824 return cxstring::createRef("SEHExceptStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004825 case CXCursor_SEHFinallyStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004826 return cxstring::createRef("SEHFinallyStmt");
Nico Weber9b982072014-07-07 00:12:30 +00004827 case CXCursor_SEHLeaveStmt:
4828 return cxstring::createRef("SEHLeaveStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004829 case CXCursor_NullStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004830 return cxstring::createRef("NullStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004831 case CXCursor_InvalidFile:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004832 return cxstring::createRef("InvalidFile");
Guy Benyei11169dd2012-12-18 14:30:41 +00004833 case CXCursor_InvalidCode:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004834 return cxstring::createRef("InvalidCode");
Guy Benyei11169dd2012-12-18 14:30:41 +00004835 case CXCursor_NoDeclFound:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004836 return cxstring::createRef("NoDeclFound");
Guy Benyei11169dd2012-12-18 14:30:41 +00004837 case CXCursor_NotImplemented:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004838 return cxstring::createRef("NotImplemented");
Guy Benyei11169dd2012-12-18 14:30:41 +00004839 case CXCursor_TranslationUnit:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004840 return cxstring::createRef("TranslationUnit");
Guy Benyei11169dd2012-12-18 14:30:41 +00004841 case CXCursor_UnexposedAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004842 return cxstring::createRef("UnexposedAttr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004843 case CXCursor_IBActionAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004844 return cxstring::createRef("attribute(ibaction)");
Guy Benyei11169dd2012-12-18 14:30:41 +00004845 case CXCursor_IBOutletAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004846 return cxstring::createRef("attribute(iboutlet)");
Guy Benyei11169dd2012-12-18 14:30:41 +00004847 case CXCursor_IBOutletCollectionAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004848 return cxstring::createRef("attribute(iboutletcollection)");
Guy Benyei11169dd2012-12-18 14:30:41 +00004849 case CXCursor_CXXFinalAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004850 return cxstring::createRef("attribute(final)");
Guy Benyei11169dd2012-12-18 14:30:41 +00004851 case CXCursor_CXXOverrideAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004852 return cxstring::createRef("attribute(override)");
Guy Benyei11169dd2012-12-18 14:30:41 +00004853 case CXCursor_AnnotateAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004854 return cxstring::createRef("attribute(annotate)");
Guy Benyei11169dd2012-12-18 14:30:41 +00004855 case CXCursor_AsmLabelAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004856 return cxstring::createRef("asm label");
Argyrios Kyrtzidis16834f12013-09-25 00:14:38 +00004857 case CXCursor_PackedAttr:
4858 return cxstring::createRef("attribute(packed)");
Joey Gouly81228382014-05-01 15:41:58 +00004859 case CXCursor_PureAttr:
4860 return cxstring::createRef("attribute(pure)");
4861 case CXCursor_ConstAttr:
4862 return cxstring::createRef("attribute(const)");
4863 case CXCursor_NoDuplicateAttr:
4864 return cxstring::createRef("attribute(noduplicate)");
Eli Bendersky2581e662014-05-28 19:29:58 +00004865 case CXCursor_CUDAConstantAttr:
4866 return cxstring::createRef("attribute(constant)");
4867 case CXCursor_CUDADeviceAttr:
4868 return cxstring::createRef("attribute(device)");
4869 case CXCursor_CUDAGlobalAttr:
4870 return cxstring::createRef("attribute(global)");
4871 case CXCursor_CUDAHostAttr:
4872 return cxstring::createRef("attribute(host)");
Eli Bendersky9b071472014-08-08 14:59:00 +00004873 case CXCursor_CUDASharedAttr:
4874 return cxstring::createRef("attribute(shared)");
Saleem Abdulrasool79c69712015-09-05 18:53:43 +00004875 case CXCursor_VisibilityAttr:
4876 return cxstring::createRef("attribute(visibility)");
Saleem Abdulrasool8aa0b802015-12-10 18:45:18 +00004877 case CXCursor_DLLExport:
4878 return cxstring::createRef("attribute(dllexport)");
4879 case CXCursor_DLLImport:
4880 return cxstring::createRef("attribute(dllimport)");
Guy Benyei11169dd2012-12-18 14:30:41 +00004881 case CXCursor_PreprocessingDirective:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004882 return cxstring::createRef("preprocessing directive");
Guy Benyei11169dd2012-12-18 14:30:41 +00004883 case CXCursor_MacroDefinition:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004884 return cxstring::createRef("macro definition");
Guy Benyei11169dd2012-12-18 14:30:41 +00004885 case CXCursor_MacroExpansion:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004886 return cxstring::createRef("macro expansion");
Guy Benyei11169dd2012-12-18 14:30:41 +00004887 case CXCursor_InclusionDirective:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004888 return cxstring::createRef("inclusion directive");
Guy Benyei11169dd2012-12-18 14:30:41 +00004889 case CXCursor_Namespace:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004890 return cxstring::createRef("Namespace");
Guy Benyei11169dd2012-12-18 14:30:41 +00004891 case CXCursor_LinkageSpec:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004892 return cxstring::createRef("LinkageSpec");
Guy Benyei11169dd2012-12-18 14:30:41 +00004893 case CXCursor_CXXBaseSpecifier:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004894 return cxstring::createRef("C++ base class specifier");
Guy Benyei11169dd2012-12-18 14:30:41 +00004895 case CXCursor_Constructor:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004896 return cxstring::createRef("CXXConstructor");
Guy Benyei11169dd2012-12-18 14:30:41 +00004897 case CXCursor_Destructor:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004898 return cxstring::createRef("CXXDestructor");
Guy Benyei11169dd2012-12-18 14:30:41 +00004899 case CXCursor_ConversionFunction:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004900 return cxstring::createRef("CXXConversion");
Guy Benyei11169dd2012-12-18 14:30:41 +00004901 case CXCursor_TemplateTypeParameter:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004902 return cxstring::createRef("TemplateTypeParameter");
Guy Benyei11169dd2012-12-18 14:30:41 +00004903 case CXCursor_NonTypeTemplateParameter:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004904 return cxstring::createRef("NonTypeTemplateParameter");
Guy Benyei11169dd2012-12-18 14:30:41 +00004905 case CXCursor_TemplateTemplateParameter:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004906 return cxstring::createRef("TemplateTemplateParameter");
Guy Benyei11169dd2012-12-18 14:30:41 +00004907 case CXCursor_FunctionTemplate:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004908 return cxstring::createRef("FunctionTemplate");
Guy Benyei11169dd2012-12-18 14:30:41 +00004909 case CXCursor_ClassTemplate:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004910 return cxstring::createRef("ClassTemplate");
Guy Benyei11169dd2012-12-18 14:30:41 +00004911 case CXCursor_ClassTemplatePartialSpecialization:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004912 return cxstring::createRef("ClassTemplatePartialSpecialization");
Guy Benyei11169dd2012-12-18 14:30:41 +00004913 case CXCursor_NamespaceAlias:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004914 return cxstring::createRef("NamespaceAlias");
Guy Benyei11169dd2012-12-18 14:30:41 +00004915 case CXCursor_UsingDirective:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004916 return cxstring::createRef("UsingDirective");
Guy Benyei11169dd2012-12-18 14:30:41 +00004917 case CXCursor_UsingDeclaration:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004918 return cxstring::createRef("UsingDeclaration");
Guy Benyei11169dd2012-12-18 14:30:41 +00004919 case CXCursor_TypeAliasDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004920 return cxstring::createRef("TypeAliasDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004921 case CXCursor_ObjCSynthesizeDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004922 return cxstring::createRef("ObjCSynthesizeDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004923 case CXCursor_ObjCDynamicDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004924 return cxstring::createRef("ObjCDynamicDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004925 case CXCursor_CXXAccessSpecifier:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004926 return cxstring::createRef("CXXAccessSpecifier");
Guy Benyei11169dd2012-12-18 14:30:41 +00004927 case CXCursor_ModuleImportDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004928 return cxstring::createRef("ModuleImport");
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004929 case CXCursor_OMPParallelDirective:
Alexey Bataev1b59ab52014-02-27 08:29:12 +00004930 return cxstring::createRef("OMPParallelDirective");
4931 case CXCursor_OMPSimdDirective:
4932 return cxstring::createRef("OMPSimdDirective");
Alexey Bataevf29276e2014-06-18 04:14:57 +00004933 case CXCursor_OMPForDirective:
4934 return cxstring::createRef("OMPForDirective");
Alexander Musmanf82886e2014-09-18 05:12:34 +00004935 case CXCursor_OMPForSimdDirective:
4936 return cxstring::createRef("OMPForSimdDirective");
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004937 case CXCursor_OMPSectionsDirective:
4938 return cxstring::createRef("OMPSectionsDirective");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004939 case CXCursor_OMPSectionDirective:
4940 return cxstring::createRef("OMPSectionDirective");
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00004941 case CXCursor_OMPSingleDirective:
4942 return cxstring::createRef("OMPSingleDirective");
Alexander Musman80c22892014-07-17 08:54:58 +00004943 case CXCursor_OMPMasterDirective:
4944 return cxstring::createRef("OMPMasterDirective");
Alexander Musmand9ed09f2014-07-21 09:42:05 +00004945 case CXCursor_OMPCriticalDirective:
4946 return cxstring::createRef("OMPCriticalDirective");
Alexey Bataev4acb8592014-07-07 13:01:15 +00004947 case CXCursor_OMPParallelForDirective:
4948 return cxstring::createRef("OMPParallelForDirective");
Alexander Musmane4e893b2014-09-23 09:33:00 +00004949 case CXCursor_OMPParallelForSimdDirective:
4950 return cxstring::createRef("OMPParallelForSimdDirective");
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004951 case CXCursor_OMPParallelSectionsDirective:
4952 return cxstring::createRef("OMPParallelSectionsDirective");
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004953 case CXCursor_OMPTaskDirective:
4954 return cxstring::createRef("OMPTaskDirective");
Alexey Bataev68446b72014-07-18 07:47:19 +00004955 case CXCursor_OMPTaskyieldDirective:
4956 return cxstring::createRef("OMPTaskyieldDirective");
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00004957 case CXCursor_OMPBarrierDirective:
4958 return cxstring::createRef("OMPBarrierDirective");
Alexey Bataev2df347a2014-07-18 10:17:07 +00004959 case CXCursor_OMPTaskwaitDirective:
4960 return cxstring::createRef("OMPTaskwaitDirective");
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00004961 case CXCursor_OMPTaskgroupDirective:
4962 return cxstring::createRef("OMPTaskgroupDirective");
Alexey Bataev6125da92014-07-21 11:26:11 +00004963 case CXCursor_OMPFlushDirective:
4964 return cxstring::createRef("OMPFlushDirective");
Alexey Bataev9fb6e642014-07-22 06:45:04 +00004965 case CXCursor_OMPOrderedDirective:
4966 return cxstring::createRef("OMPOrderedDirective");
Alexey Bataev0162e452014-07-22 10:10:35 +00004967 case CXCursor_OMPAtomicDirective:
4968 return cxstring::createRef("OMPAtomicDirective");
Alexey Bataev0bd520b2014-09-19 08:19:49 +00004969 case CXCursor_OMPTargetDirective:
4970 return cxstring::createRef("OMPTargetDirective");
Michael Wong65f367f2015-07-21 13:44:28 +00004971 case CXCursor_OMPTargetDataDirective:
4972 return cxstring::createRef("OMPTargetDataDirective");
Samuel Antaodf67fc42016-01-19 19:15:56 +00004973 case CXCursor_OMPTargetEnterDataDirective:
4974 return cxstring::createRef("OMPTargetEnterDataDirective");
Samuel Antao72590762016-01-19 20:04:50 +00004975 case CXCursor_OMPTargetExitDataDirective:
4976 return cxstring::createRef("OMPTargetExitDataDirective");
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00004977 case CXCursor_OMPTargetParallelDirective:
4978 return cxstring::createRef("OMPTargetParallelDirective");
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00004979 case CXCursor_OMPTargetParallelForDirective:
4980 return cxstring::createRef("OMPTargetParallelForDirective");
Samuel Antao686c70c2016-05-26 17:30:50 +00004981 case CXCursor_OMPTargetUpdateDirective:
4982 return cxstring::createRef("OMPTargetUpdateDirective");
Alexey Bataev13314bf2014-10-09 04:18:56 +00004983 case CXCursor_OMPTeamsDirective:
4984 return cxstring::createRef("OMPTeamsDirective");
Alexey Bataev6d4ed052015-07-01 06:57:41 +00004985 case CXCursor_OMPCancellationPointDirective:
4986 return cxstring::createRef("OMPCancellationPointDirective");
Alexey Bataev80909872015-07-02 11:25:17 +00004987 case CXCursor_OMPCancelDirective:
4988 return cxstring::createRef("OMPCancelDirective");
Alexey Bataev49f6e782015-12-01 04:18:41 +00004989 case CXCursor_OMPTaskLoopDirective:
4990 return cxstring::createRef("OMPTaskLoopDirective");
Alexey Bataev0a6ed842015-12-03 09:40:15 +00004991 case CXCursor_OMPTaskLoopSimdDirective:
4992 return cxstring::createRef("OMPTaskLoopSimdDirective");
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004993 case CXCursor_OMPDistributeDirective:
4994 return cxstring::createRef("OMPDistributeDirective");
Carlo Bertolli9925f152016-06-27 14:55:37 +00004995 case CXCursor_OMPDistributeParallelForDirective:
4996 return cxstring::createRef("OMPDistributeParallelForDirective");
Kelvin Li4a39add2016-07-05 05:00:15 +00004997 case CXCursor_OMPDistributeParallelForSimdDirective:
4998 return cxstring::createRef("OMPDistributeParallelForSimdDirective");
Kelvin Li787f3fc2016-07-06 04:45:38 +00004999 case CXCursor_OMPDistributeSimdDirective:
5000 return cxstring::createRef("OMPDistributeSimdDirective");
Kelvin Lia579b912016-07-14 02:54:56 +00005001 case CXCursor_OMPTargetParallelForSimdDirective:
5002 return cxstring::createRef("OMPTargetParallelForSimdDirective");
Kelvin Li986330c2016-07-20 22:57:10 +00005003 case CXCursor_OMPTargetSimdDirective:
5004 return cxstring::createRef("OMPTargetSimdDirective");
Kelvin Li02532872016-08-05 14:37:37 +00005005 case CXCursor_OMPTeamsDistributeDirective:
5006 return cxstring::createRef("OMPTeamsDistributeDirective");
Kelvin Li4e325f72016-10-25 12:50:55 +00005007 case CXCursor_OMPTeamsDistributeSimdDirective:
5008 return cxstring::createRef("OMPTeamsDistributeSimdDirective");
Kelvin Li579e41c2016-11-30 23:51:03 +00005009 case CXCursor_OMPTeamsDistributeParallelForSimdDirective:
5010 return cxstring::createRef("OMPTeamsDistributeParallelForSimdDirective");
Kelvin Li7ade93f2016-12-09 03:24:30 +00005011 case CXCursor_OMPTeamsDistributeParallelForDirective:
5012 return cxstring::createRef("OMPTeamsDistributeParallelForDirective");
Kelvin Libf594a52016-12-17 05:48:59 +00005013 case CXCursor_OMPTargetTeamsDirective:
5014 return cxstring::createRef("OMPTargetTeamsDirective");
Kelvin Li83c451e2016-12-25 04:52:54 +00005015 case CXCursor_OMPTargetTeamsDistributeDirective:
5016 return cxstring::createRef("OMPTargetTeamsDistributeDirective");
Kelvin Li80e8f562016-12-29 22:16:30 +00005017 case CXCursor_OMPTargetTeamsDistributeParallelForDirective:
5018 return cxstring::createRef("OMPTargetTeamsDistributeParallelForDirective");
Kelvin Li1851df52017-01-03 05:23:48 +00005019 case CXCursor_OMPTargetTeamsDistributeParallelForSimdDirective:
5020 return cxstring::createRef(
5021 "OMPTargetTeamsDistributeParallelForSimdDirective");
Kelvin Lida681182017-01-10 18:08:18 +00005022 case CXCursor_OMPTargetTeamsDistributeSimdDirective:
5023 return cxstring::createRef("OMPTargetTeamsDistributeSimdDirective");
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005024 case CXCursor_OverloadCandidate:
5025 return cxstring::createRef("OverloadCandidate");
Sergey Kalinichev8f3b1872015-11-15 13:48:32 +00005026 case CXCursor_TypeAliasTemplateDecl:
5027 return cxstring::createRef("TypeAliasTemplateDecl");
Olivier Goffart81978012016-06-09 16:15:55 +00005028 case CXCursor_StaticAssert:
5029 return cxstring::createRef("StaticAssert");
Olivier Goffartd211c642016-11-04 06:29:27 +00005030 case CXCursor_FriendDecl:
5031 return cxstring::createRef("FriendDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005032 }
5033
5034 llvm_unreachable("Unhandled CXCursorKind");
5035}
5036
5037struct GetCursorData {
5038 SourceLocation TokenBeginLoc;
5039 bool PointsAtMacroArgExpansion;
5040 bool VisitedObjCPropertyImplDecl;
5041 SourceLocation VisitedDeclaratorDeclStartLoc;
5042 CXCursor &BestCursor;
5043
5044 GetCursorData(SourceManager &SM,
5045 SourceLocation tokenBegin, CXCursor &outputCursor)
5046 : TokenBeginLoc(tokenBegin), BestCursor(outputCursor) {
5047 PointsAtMacroArgExpansion = SM.isMacroArgExpansion(tokenBegin);
5048 VisitedObjCPropertyImplDecl = false;
5049 }
5050};
5051
5052static enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
5053 CXCursor parent,
5054 CXClientData client_data) {
5055 GetCursorData *Data = static_cast<GetCursorData *>(client_data);
5056 CXCursor *BestCursor = &Data->BestCursor;
5057
5058 // If we point inside a macro argument we should provide info of what the
5059 // token is so use the actual cursor, don't replace it with a macro expansion
5060 // cursor.
5061 if (cursor.kind == CXCursor_MacroExpansion && Data->PointsAtMacroArgExpansion)
5062 return CXChildVisit_Recurse;
5063
5064 if (clang_isDeclaration(cursor.kind)) {
5065 // Avoid having the implicit methods override the property decls.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005066 if (const ObjCMethodDecl *MD
Guy Benyei11169dd2012-12-18 14:30:41 +00005067 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
5068 if (MD->isImplicit())
5069 return CXChildVisit_Break;
5070
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005071 } else if (const ObjCInterfaceDecl *ID
Guy Benyei11169dd2012-12-18 14:30:41 +00005072 = dyn_cast_or_null<ObjCInterfaceDecl>(getCursorDecl(cursor))) {
5073 // Check that when we have multiple @class references in the same line,
5074 // that later ones do not override the previous ones.
5075 // If we have:
5076 // @class Foo, Bar;
5077 // source ranges for both start at '@', so 'Bar' will end up overriding
5078 // 'Foo' even though the cursor location was at 'Foo'.
5079 if (BestCursor->kind == CXCursor_ObjCInterfaceDecl ||
5080 BestCursor->kind == CXCursor_ObjCClassRef)
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005081 if (const ObjCInterfaceDecl *PrevID
Guy Benyei11169dd2012-12-18 14:30:41 +00005082 = dyn_cast_or_null<ObjCInterfaceDecl>(getCursorDecl(*BestCursor))){
5083 if (PrevID != ID &&
5084 !PrevID->isThisDeclarationADefinition() &&
5085 !ID->isThisDeclarationADefinition())
5086 return CXChildVisit_Break;
5087 }
5088
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005089 } else if (const DeclaratorDecl *DD
Guy Benyei11169dd2012-12-18 14:30:41 +00005090 = dyn_cast_or_null<DeclaratorDecl>(getCursorDecl(cursor))) {
5091 SourceLocation StartLoc = DD->getSourceRange().getBegin();
5092 // Check that when we have multiple declarators in the same line,
5093 // that later ones do not override the previous ones.
5094 // If we have:
5095 // int Foo, Bar;
5096 // source ranges for both start at 'int', so 'Bar' will end up overriding
5097 // 'Foo' even though the cursor location was at 'Foo'.
5098 if (Data->VisitedDeclaratorDeclStartLoc == StartLoc)
5099 return CXChildVisit_Break;
5100 Data->VisitedDeclaratorDeclStartLoc = StartLoc;
5101
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005102 } else if (const ObjCPropertyImplDecl *PropImp
Guy Benyei11169dd2012-12-18 14:30:41 +00005103 = dyn_cast_or_null<ObjCPropertyImplDecl>(getCursorDecl(cursor))) {
5104 (void)PropImp;
5105 // Check that when we have multiple @synthesize in the same line,
5106 // that later ones do not override the previous ones.
5107 // If we have:
5108 // @synthesize Foo, Bar;
5109 // source ranges for both start at '@', so 'Bar' will end up overriding
5110 // 'Foo' even though the cursor location was at 'Foo'.
5111 if (Data->VisitedObjCPropertyImplDecl)
5112 return CXChildVisit_Break;
5113 Data->VisitedObjCPropertyImplDecl = true;
5114 }
5115 }
5116
5117 if (clang_isExpression(cursor.kind) &&
5118 clang_isDeclaration(BestCursor->kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005119 if (const Decl *D = getCursorDecl(*BestCursor)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005120 // Avoid having the cursor of an expression replace the declaration cursor
5121 // when the expression source range overlaps the declaration range.
5122 // This can happen for C++ constructor expressions whose range generally
5123 // include the variable declaration, e.g.:
5124 // MyCXXClass foo; // Make sure pointing at 'foo' returns a VarDecl cursor.
5125 if (D->getLocation().isValid() && Data->TokenBeginLoc.isValid() &&
5126 D->getLocation() == Data->TokenBeginLoc)
5127 return CXChildVisit_Break;
5128 }
5129 }
5130
5131 // If our current best cursor is the construction of a temporary object,
5132 // don't replace that cursor with a type reference, because we want
5133 // clang_getCursor() to point at the constructor.
5134 if (clang_isExpression(BestCursor->kind) &&
5135 isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
5136 cursor.kind == CXCursor_TypeRef) {
5137 // Keep the cursor pointing at CXXTemporaryObjectExpr but also mark it
5138 // as having the actual point on the type reference.
5139 *BestCursor = getTypeRefedCallExprCursor(*BestCursor);
5140 return CXChildVisit_Recurse;
5141 }
Douglas Gregore9d95f12015-07-07 03:57:35 +00005142
5143 // If we already have an Objective-C superclass reference, don't
5144 // update it further.
5145 if (BestCursor->kind == CXCursor_ObjCSuperClassRef)
5146 return CXChildVisit_Break;
5147
Guy Benyei11169dd2012-12-18 14:30:41 +00005148 *BestCursor = cursor;
5149 return CXChildVisit_Recurse;
5150}
5151
5152CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00005153 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00005154 LOG_BAD_TU(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00005155 return clang_getNullCursor();
Dmitri Gribenko256454f2014-02-11 14:34:14 +00005156 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005157
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00005158 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00005159 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
5160
5161 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
5162 CXCursor Result = cxcursor::getCursor(TU, SLoc);
5163
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005164 LOG_FUNC_SECTION {
Guy Benyei11169dd2012-12-18 14:30:41 +00005165 CXFile SearchFile;
5166 unsigned SearchLine, SearchColumn;
5167 CXFile ResultFile;
5168 unsigned ResultLine, ResultColumn;
5169 CXString SearchFileName, ResultFileName, KindSpelling, USR;
5170 const char *IsDef = clang_isCursorDefinition(Result)? " (Definition)" : "";
5171 CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
Craig Topper69186e72014-06-08 08:38:04 +00005172
5173 clang_getFileLocation(Loc, &SearchFile, &SearchLine, &SearchColumn,
5174 nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005175 clang_getFileLocation(ResultLoc, &ResultFile, &ResultLine,
Craig Topper69186e72014-06-08 08:38:04 +00005176 &ResultColumn, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005177 SearchFileName = clang_getFileName(SearchFile);
5178 ResultFileName = clang_getFileName(ResultFile);
5179 KindSpelling = clang_getCursorKindSpelling(Result.kind);
5180 USR = clang_getCursorUSR(Result);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005181 *Log << llvm::format("(%s:%d:%d) = %s",
5182 clang_getCString(SearchFileName), SearchLine, SearchColumn,
5183 clang_getCString(KindSpelling))
5184 << llvm::format("(%s:%d:%d):%s%s",
5185 clang_getCString(ResultFileName), ResultLine, ResultColumn,
5186 clang_getCString(USR), IsDef);
Guy Benyei11169dd2012-12-18 14:30:41 +00005187 clang_disposeString(SearchFileName);
5188 clang_disposeString(ResultFileName);
5189 clang_disposeString(KindSpelling);
5190 clang_disposeString(USR);
5191
5192 CXCursor Definition = clang_getCursorDefinition(Result);
5193 if (!clang_equalCursors(Definition, clang_getNullCursor())) {
5194 CXSourceLocation DefinitionLoc = clang_getCursorLocation(Definition);
5195 CXString DefinitionKindSpelling
5196 = clang_getCursorKindSpelling(Definition.kind);
5197 CXFile DefinitionFile;
5198 unsigned DefinitionLine, DefinitionColumn;
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005199 clang_getFileLocation(DefinitionLoc, &DefinitionFile,
Craig Topper69186e72014-06-08 08:38:04 +00005200 &DefinitionLine, &DefinitionColumn, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005201 CXString DefinitionFileName = clang_getFileName(DefinitionFile);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005202 *Log << llvm::format(" -> %s(%s:%d:%d)",
5203 clang_getCString(DefinitionKindSpelling),
5204 clang_getCString(DefinitionFileName),
5205 DefinitionLine, DefinitionColumn);
Guy Benyei11169dd2012-12-18 14:30:41 +00005206 clang_disposeString(DefinitionFileName);
5207 clang_disposeString(DefinitionKindSpelling);
5208 }
5209 }
5210
5211 return Result;
5212}
5213
5214CXCursor clang_getNullCursor(void) {
5215 return MakeCXCursorInvalid(CXCursor_InvalidFile);
5216}
5217
5218unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Argyrios Kyrtzidisbf1be592013-01-08 18:23:28 +00005219 // Clear out the "FirstInDeclGroup" part in a declaration cursor, since we
5220 // can't set consistently. For example, when visiting a DeclStmt we will set
5221 // it but we don't set it on the result of clang_getCursorDefinition for
5222 // a reference of the same declaration.
5223 // FIXME: Setting "FirstInDeclGroup" in CXCursors is a hack that only works
5224 // when visiting a DeclStmt currently, the AST should be enhanced to be able
5225 // to provide that kind of info.
5226 if (clang_isDeclaration(X.kind))
Craig Topper69186e72014-06-08 08:38:04 +00005227 X.data[1] = nullptr;
Argyrios Kyrtzidisbf1be592013-01-08 18:23:28 +00005228 if (clang_isDeclaration(Y.kind))
Craig Topper69186e72014-06-08 08:38:04 +00005229 Y.data[1] = nullptr;
Argyrios Kyrtzidisbf1be592013-01-08 18:23:28 +00005230
Guy Benyei11169dd2012-12-18 14:30:41 +00005231 return X == Y;
5232}
5233
5234unsigned clang_hashCursor(CXCursor C) {
5235 unsigned Index = 0;
5236 if (clang_isExpression(C.kind) || clang_isStatement(C.kind))
5237 Index = 1;
5238
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005239 return llvm::DenseMapInfo<std::pair<unsigned, const void*> >::getHashValue(
Guy Benyei11169dd2012-12-18 14:30:41 +00005240 std::make_pair(C.kind, C.data[Index]));
5241}
5242
5243unsigned clang_isInvalid(enum CXCursorKind K) {
5244 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
5245}
5246
5247unsigned clang_isDeclaration(enum CXCursorKind K) {
5248 return (K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl) ||
5249 (K >= CXCursor_FirstExtraDecl && K <= CXCursor_LastExtraDecl);
5250}
5251
5252unsigned clang_isReference(enum CXCursorKind K) {
5253 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
5254}
5255
5256unsigned clang_isExpression(enum CXCursorKind K) {
5257 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
5258}
5259
5260unsigned clang_isStatement(enum CXCursorKind K) {
5261 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
5262}
5263
5264unsigned clang_isAttribute(enum CXCursorKind K) {
5265 return K >= CXCursor_FirstAttr && K <= CXCursor_LastAttr;
5266}
5267
5268unsigned clang_isTranslationUnit(enum CXCursorKind K) {
5269 return K == CXCursor_TranslationUnit;
5270}
5271
5272unsigned clang_isPreprocessing(enum CXCursorKind K) {
5273 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
5274}
5275
5276unsigned clang_isUnexposed(enum CXCursorKind K) {
5277 switch (K) {
5278 case CXCursor_UnexposedDecl:
5279 case CXCursor_UnexposedExpr:
5280 case CXCursor_UnexposedStmt:
5281 case CXCursor_UnexposedAttr:
5282 return true;
5283 default:
5284 return false;
5285 }
5286}
5287
5288CXCursorKind clang_getCursorKind(CXCursor C) {
5289 return C.kind;
5290}
5291
5292CXSourceLocation clang_getCursorLocation(CXCursor C) {
5293 if (clang_isReference(C.kind)) {
5294 switch (C.kind) {
5295 case CXCursor_ObjCSuperClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005296 std::pair<const ObjCInterfaceDecl *, SourceLocation> P
Guy Benyei11169dd2012-12-18 14:30:41 +00005297 = getCursorObjCSuperClassRef(C);
5298 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5299 }
5300
5301 case CXCursor_ObjCProtocolRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005302 std::pair<const ObjCProtocolDecl *, SourceLocation> P
Guy Benyei11169dd2012-12-18 14:30:41 +00005303 = getCursorObjCProtocolRef(C);
5304 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5305 }
5306
5307 case CXCursor_ObjCClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005308 std::pair<const ObjCInterfaceDecl *, SourceLocation> P
Guy Benyei11169dd2012-12-18 14:30:41 +00005309 = getCursorObjCClassRef(C);
5310 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5311 }
5312
5313 case CXCursor_TypeRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005314 std::pair<const TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005315 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5316 }
5317
5318 case CXCursor_TemplateRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005319 std::pair<const TemplateDecl *, SourceLocation> P =
5320 getCursorTemplateRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005321 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5322 }
5323
5324 case CXCursor_NamespaceRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005325 std::pair<const NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005326 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5327 }
5328
5329 case CXCursor_MemberRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005330 std::pair<const FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005331 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5332 }
5333
5334 case CXCursor_VariableRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005335 std::pair<const VarDecl *, SourceLocation> P = getCursorVariableRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005336 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5337 }
5338
5339 case CXCursor_CXXBaseSpecifier: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005340 const CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005341 if (!BaseSpec)
5342 return clang_getNullLocation();
5343
5344 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
5345 return cxloc::translateSourceLocation(getCursorContext(C),
5346 TSInfo->getTypeLoc().getBeginLoc());
5347
5348 return cxloc::translateSourceLocation(getCursorContext(C),
5349 BaseSpec->getLocStart());
5350 }
5351
5352 case CXCursor_LabelRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005353 std::pair<const LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005354 return cxloc::translateSourceLocation(getCursorContext(C), P.second);
5355 }
5356
5357 case CXCursor_OverloadedDeclRef:
5358 return cxloc::translateSourceLocation(getCursorContext(C),
5359 getCursorOverloadedDeclRef(C).second);
5360
5361 default:
5362 // FIXME: Need a way to enumerate all non-reference cases.
5363 llvm_unreachable("Missed a reference kind");
5364 }
5365 }
5366
5367 if (clang_isExpression(C.kind))
5368 return cxloc::translateSourceLocation(getCursorContext(C),
5369 getLocationFromExpr(getCursorExpr(C)));
5370
5371 if (clang_isStatement(C.kind))
5372 return cxloc::translateSourceLocation(getCursorContext(C),
5373 getCursorStmt(C)->getLocStart());
5374
5375 if (C.kind == CXCursor_PreprocessingDirective) {
5376 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
5377 return cxloc::translateSourceLocation(getCursorContext(C), L);
5378 }
5379
5380 if (C.kind == CXCursor_MacroExpansion) {
5381 SourceLocation L
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00005382 = cxcursor::getCursorMacroExpansion(C).getSourceRange().getBegin();
Guy Benyei11169dd2012-12-18 14:30:41 +00005383 return cxloc::translateSourceLocation(getCursorContext(C), L);
5384 }
5385
5386 if (C.kind == CXCursor_MacroDefinition) {
5387 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
5388 return cxloc::translateSourceLocation(getCursorContext(C), L);
5389 }
5390
5391 if (C.kind == CXCursor_InclusionDirective) {
5392 SourceLocation L
5393 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
5394 return cxloc::translateSourceLocation(getCursorContext(C), L);
5395 }
5396
Argyrios Kyrtzidis16834f12013-09-25 00:14:38 +00005397 if (clang_isAttribute(C.kind)) {
5398 SourceLocation L
5399 = cxcursor::getCursorAttr(C)->getLocation();
5400 return cxloc::translateSourceLocation(getCursorContext(C), L);
5401 }
5402
Guy Benyei11169dd2012-12-18 14:30:41 +00005403 if (!clang_isDeclaration(C.kind))
5404 return clang_getNullLocation();
5405
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005406 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005407 if (!D)
5408 return clang_getNullLocation();
5409
5410 SourceLocation Loc = D->getLocation();
5411 // FIXME: Multiple variables declared in a single declaration
5412 // currently lack the information needed to correctly determine their
5413 // ranges when accounting for the type-specifier. We use context
5414 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
5415 // and if so, whether it is the first decl.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005416 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005417 if (!cxcursor::isFirstInDeclGroup(C))
5418 Loc = VD->getLocation();
5419 }
5420
5421 // For ObjC methods, give the start location of the method name.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005422 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00005423 Loc = MD->getSelectorStartLoc();
5424
5425 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
5426}
5427
NAKAMURA Takumia01f4c32016-12-19 16:50:43 +00005428} // end extern "C"
5429
Guy Benyei11169dd2012-12-18 14:30:41 +00005430CXCursor cxcursor::getCursor(CXTranslationUnit TU, SourceLocation SLoc) {
5431 assert(TU);
5432
5433 // Guard against an invalid SourceLocation, or we may assert in one
5434 // of the following calls.
5435 if (SLoc.isInvalid())
5436 return clang_getNullCursor();
5437
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00005438 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00005439
5440 // Translate the given source location to make it point at the beginning of
5441 // the token under the cursor.
5442 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
5443 CXXUnit->getASTContext().getLangOpts());
5444
5445 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
5446 if (SLoc.isValid()) {
5447 GetCursorData ResultData(CXXUnit->getSourceManager(), SLoc, Result);
5448 CursorVisitor CursorVis(TU, GetCursorVisitor, &ResultData,
5449 /*VisitPreprocessorLast=*/true,
5450 /*VisitIncludedEntities=*/false,
5451 SourceLocation(SLoc));
5452 CursorVis.visitFileRegion();
5453 }
5454
5455 return Result;
5456}
5457
5458static SourceRange getRawCursorExtent(CXCursor C) {
5459 if (clang_isReference(C.kind)) {
5460 switch (C.kind) {
5461 case CXCursor_ObjCSuperClassRef:
5462 return getCursorObjCSuperClassRef(C).second;
5463
5464 case CXCursor_ObjCProtocolRef:
5465 return getCursorObjCProtocolRef(C).second;
5466
5467 case CXCursor_ObjCClassRef:
5468 return getCursorObjCClassRef(C).second;
5469
5470 case CXCursor_TypeRef:
5471 return getCursorTypeRef(C).second;
5472
5473 case CXCursor_TemplateRef:
5474 return getCursorTemplateRef(C).second;
5475
5476 case CXCursor_NamespaceRef:
5477 return getCursorNamespaceRef(C).second;
5478
5479 case CXCursor_MemberRef:
5480 return getCursorMemberRef(C).second;
5481
5482 case CXCursor_CXXBaseSpecifier:
5483 return getCursorCXXBaseSpecifier(C)->getSourceRange();
5484
5485 case CXCursor_LabelRef:
5486 return getCursorLabelRef(C).second;
5487
5488 case CXCursor_OverloadedDeclRef:
5489 return getCursorOverloadedDeclRef(C).second;
5490
5491 case CXCursor_VariableRef:
5492 return getCursorVariableRef(C).second;
5493
5494 default:
5495 // FIXME: Need a way to enumerate all non-reference cases.
5496 llvm_unreachable("Missed a reference kind");
5497 }
5498 }
5499
5500 if (clang_isExpression(C.kind))
5501 return getCursorExpr(C)->getSourceRange();
5502
5503 if (clang_isStatement(C.kind))
5504 return getCursorStmt(C)->getSourceRange();
5505
5506 if (clang_isAttribute(C.kind))
5507 return getCursorAttr(C)->getRange();
5508
5509 if (C.kind == CXCursor_PreprocessingDirective)
5510 return cxcursor::getCursorPreprocessingDirective(C);
5511
5512 if (C.kind == CXCursor_MacroExpansion) {
5513 ASTUnit *TU = getCursorASTUnit(C);
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00005514 SourceRange Range = cxcursor::getCursorMacroExpansion(C).getSourceRange();
Guy Benyei11169dd2012-12-18 14:30:41 +00005515 return TU->mapRangeFromPreamble(Range);
5516 }
5517
5518 if (C.kind == CXCursor_MacroDefinition) {
5519 ASTUnit *TU = getCursorASTUnit(C);
5520 SourceRange Range = cxcursor::getCursorMacroDefinition(C)->getSourceRange();
5521 return TU->mapRangeFromPreamble(Range);
5522 }
5523
5524 if (C.kind == CXCursor_InclusionDirective) {
5525 ASTUnit *TU = getCursorASTUnit(C);
5526 SourceRange Range = cxcursor::getCursorInclusionDirective(C)->getSourceRange();
5527 return TU->mapRangeFromPreamble(Range);
5528 }
5529
5530 if (C.kind == CXCursor_TranslationUnit) {
5531 ASTUnit *TU = getCursorASTUnit(C);
5532 FileID MainID = TU->getSourceManager().getMainFileID();
5533 SourceLocation Start = TU->getSourceManager().getLocForStartOfFile(MainID);
5534 SourceLocation End = TU->getSourceManager().getLocForEndOfFile(MainID);
5535 return SourceRange(Start, End);
5536 }
5537
5538 if (clang_isDeclaration(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005539 const Decl *D = cxcursor::getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005540 if (!D)
5541 return SourceRange();
5542
5543 SourceRange R = D->getSourceRange();
5544 // FIXME: Multiple variables declared in a single declaration
5545 // currently lack the information needed to correctly determine their
5546 // ranges when accounting for the type-specifier. We use context
5547 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
5548 // and if so, whether it is the first decl.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005549 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005550 if (!cxcursor::isFirstInDeclGroup(C))
5551 R.setBegin(VD->getLocation());
5552 }
5553 return R;
5554 }
5555 return SourceRange();
5556}
5557
5558/// \brief Retrieves the "raw" cursor extent, which is then extended to include
5559/// the decl-specifier-seq for declarations.
5560static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr) {
5561 if (clang_isDeclaration(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005562 const Decl *D = cxcursor::getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005563 if (!D)
5564 return SourceRange();
5565
5566 SourceRange R = D->getSourceRange();
5567
5568 // Adjust the start of the location for declarations preceded by
5569 // declaration specifiers.
5570 SourceLocation StartLoc;
5571 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
5572 if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
5573 StartLoc = TI->getTypeLoc().getLocStart();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005574 } else if (const TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005575 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
5576 StartLoc = TI->getTypeLoc().getLocStart();
5577 }
5578
5579 if (StartLoc.isValid() && R.getBegin().isValid() &&
5580 SrcMgr.isBeforeInTranslationUnit(StartLoc, R.getBegin()))
5581 R.setBegin(StartLoc);
5582
5583 // FIXME: Multiple variables declared in a single declaration
5584 // currently lack the information needed to correctly determine their
5585 // ranges when accounting for the type-specifier. We use context
5586 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
5587 // and if so, whether it is the first decl.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005588 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005589 if (!cxcursor::isFirstInDeclGroup(C))
5590 R.setBegin(VD->getLocation());
5591 }
5592
5593 return R;
5594 }
5595
5596 return getRawCursorExtent(C);
5597}
5598
Guy Benyei11169dd2012-12-18 14:30:41 +00005599CXSourceRange clang_getCursorExtent(CXCursor C) {
5600 SourceRange R = getRawCursorExtent(C);
5601 if (R.isInvalid())
5602 return clang_getNullRange();
5603
5604 return cxloc::translateSourceRange(getCursorContext(C), R);
5605}
5606
5607CXCursor clang_getCursorReferenced(CXCursor C) {
5608 if (clang_isInvalid(C.kind))
5609 return clang_getNullCursor();
5610
5611 CXTranslationUnit tu = getCursorTU(C);
5612 if (clang_isDeclaration(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005613 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005614 if (!D)
5615 return clang_getNullCursor();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005616 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00005617 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), tu);
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005618 if (const ObjCPropertyImplDecl *PropImpl =
5619 dyn_cast<ObjCPropertyImplDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00005620 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
5621 return MakeCXCursor(Property, tu);
5622
5623 return C;
5624 }
5625
5626 if (clang_isExpression(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005627 const Expr *E = getCursorExpr(C);
5628 const Decl *D = getDeclFromExpr(E);
Guy Benyei11169dd2012-12-18 14:30:41 +00005629 if (D) {
5630 CXCursor declCursor = MakeCXCursor(D, tu);
5631 declCursor = getSelectorIdentifierCursor(getSelectorIdentifierIndex(C),
5632 declCursor);
5633 return declCursor;
5634 }
5635
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005636 if (const OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00005637 return MakeCursorOverloadedDeclRef(Ovl, tu);
5638
5639 return clang_getNullCursor();
5640 }
5641
5642 if (clang_isStatement(C.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00005643 const Stmt *S = getCursorStmt(C);
5644 if (const GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
Guy Benyei11169dd2012-12-18 14:30:41 +00005645 if (LabelDecl *label = Goto->getLabel())
5646 if (LabelStmt *labelS = label->getStmt())
5647 return MakeCXCursor(labelS, getCursorDecl(C), tu);
5648
5649 return clang_getNullCursor();
5650 }
Richard Smith66a81862015-05-04 02:25:31 +00005651
Guy Benyei11169dd2012-12-18 14:30:41 +00005652 if (C.kind == CXCursor_MacroExpansion) {
Richard Smith66a81862015-05-04 02:25:31 +00005653 if (const MacroDefinitionRecord *Def =
5654 getCursorMacroExpansion(C).getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00005655 return MakeMacroDefinitionCursor(Def, tu);
5656 }
5657
5658 if (!clang_isReference(C.kind))
5659 return clang_getNullCursor();
5660
5661 switch (C.kind) {
5662 case CXCursor_ObjCSuperClassRef:
5663 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, tu);
5664
5665 case CXCursor_ObjCProtocolRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005666 const ObjCProtocolDecl *Prot = getCursorObjCProtocolRef(C).first;
5667 if (const ObjCProtocolDecl *Def = Prot->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00005668 return MakeCXCursor(Def, tu);
5669
5670 return MakeCXCursor(Prot, tu);
5671 }
5672
5673 case CXCursor_ObjCClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005674 const ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
5675 if (const ObjCInterfaceDecl *Def = Class->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00005676 return MakeCXCursor(Def, tu);
5677
5678 return MakeCXCursor(Class, tu);
5679 }
5680
5681 case CXCursor_TypeRef:
5682 return MakeCXCursor(getCursorTypeRef(C).first, tu );
5683
5684 case CXCursor_TemplateRef:
5685 return MakeCXCursor(getCursorTemplateRef(C).first, tu );
5686
5687 case CXCursor_NamespaceRef:
5688 return MakeCXCursor(getCursorNamespaceRef(C).first, tu );
5689
5690 case CXCursor_MemberRef:
5691 return MakeCXCursor(getCursorMemberRef(C).first, tu );
5692
5693 case CXCursor_CXXBaseSpecifier: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005694 const CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005695 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
5696 tu ));
5697 }
5698
5699 case CXCursor_LabelRef:
5700 // FIXME: We end up faking the "parent" declaration here because we
5701 // don't want to make CXCursor larger.
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00005702 return MakeCXCursor(getCursorLabelRef(C).first,
5703 cxtu::getASTUnit(tu)->getASTContext()
5704 .getTranslationUnitDecl(),
Guy Benyei11169dd2012-12-18 14:30:41 +00005705 tu);
5706
5707 case CXCursor_OverloadedDeclRef:
5708 return C;
5709
5710 case CXCursor_VariableRef:
5711 return MakeCXCursor(getCursorVariableRef(C).first, tu);
5712
5713 default:
5714 // We would prefer to enumerate all non-reference cursor kinds here.
5715 llvm_unreachable("Unhandled reference cursor kind");
5716 }
5717}
5718
5719CXCursor clang_getCursorDefinition(CXCursor C) {
5720 if (clang_isInvalid(C.kind))
5721 return clang_getNullCursor();
5722
5723 CXTranslationUnit TU = getCursorTU(C);
5724
5725 bool WasReference = false;
5726 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
5727 C = clang_getCursorReferenced(C);
5728 WasReference = true;
5729 }
5730
5731 if (C.kind == CXCursor_MacroExpansion)
5732 return clang_getCursorReferenced(C);
5733
5734 if (!clang_isDeclaration(C.kind))
5735 return clang_getNullCursor();
5736
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005737 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005738 if (!D)
5739 return clang_getNullCursor();
5740
5741 switch (D->getKind()) {
5742 // Declaration kinds that don't really separate the notions of
5743 // declaration and definition.
5744 case Decl::Namespace:
5745 case Decl::Typedef:
5746 case Decl::TypeAlias:
5747 case Decl::TypeAliasTemplate:
5748 case Decl::TemplateTypeParm:
5749 case Decl::EnumConstant:
5750 case Decl::Field:
Richard Smithbdb84f32016-07-22 23:36:59 +00005751 case Decl::Binding:
John McCall5e77d762013-04-16 07:28:30 +00005752 case Decl::MSProperty:
Guy Benyei11169dd2012-12-18 14:30:41 +00005753 case Decl::IndirectField:
5754 case Decl::ObjCIvar:
5755 case Decl::ObjCAtDefsField:
5756 case Decl::ImplicitParam:
5757 case Decl::ParmVar:
5758 case Decl::NonTypeTemplateParm:
5759 case Decl::TemplateTemplateParm:
5760 case Decl::ObjCCategoryImpl:
5761 case Decl::ObjCImplementation:
5762 case Decl::AccessSpec:
5763 case Decl::LinkageSpec:
Richard Smith8df390f2016-09-08 23:14:54 +00005764 case Decl::Export:
Guy Benyei11169dd2012-12-18 14:30:41 +00005765 case Decl::ObjCPropertyImpl:
5766 case Decl::FileScopeAsm:
5767 case Decl::StaticAssert:
5768 case Decl::Block:
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00005769 case Decl::Captured:
Alexey Bataev4244be22016-02-11 05:35:55 +00005770 case Decl::OMPCapturedExpr:
Guy Benyei11169dd2012-12-18 14:30:41 +00005771 case Decl::Label: // FIXME: Is this right??
5772 case Decl::ClassScopeFunctionSpecialization:
5773 case Decl::Import:
Alexey Bataeva769e072013-03-22 06:34:35 +00005774 case Decl::OMPThreadPrivate:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00005775 case Decl::OMPDeclareReduction:
Douglas Gregor85f3f952015-07-07 03:57:15 +00005776 case Decl::ObjCTypeParam:
David Majnemerd9b1a4f2015-11-04 03:40:30 +00005777 case Decl::BuiltinTemplate:
Nico Weber66220292016-03-02 17:28:48 +00005778 case Decl::PragmaComment:
Nico Webercbbaeb12016-03-02 19:28:54 +00005779 case Decl::PragmaDetectMismatch:
Richard Smith151c4562016-12-20 21:35:28 +00005780 case Decl::UsingPack:
Guy Benyei11169dd2012-12-18 14:30:41 +00005781 return C;
5782
5783 // Declaration kinds that don't make any sense here, but are
5784 // nonetheless harmless.
David Blaikief005d3c2013-02-22 17:44:58 +00005785 case Decl::Empty:
Guy Benyei11169dd2012-12-18 14:30:41 +00005786 case Decl::TranslationUnit:
Richard Smithf19e1272015-03-07 00:04:49 +00005787 case Decl::ExternCContext:
Guy Benyei11169dd2012-12-18 14:30:41 +00005788 break;
5789
5790 // Declaration kinds for which the definition is not resolvable.
5791 case Decl::UnresolvedUsingTypename:
5792 case Decl::UnresolvedUsingValue:
5793 break;
5794
5795 case Decl::UsingDirective:
5796 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
5797 TU);
5798
5799 case Decl::NamespaceAlias:
5800 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), TU);
5801
5802 case Decl::Enum:
5803 case Decl::Record:
5804 case Decl::CXXRecord:
5805 case Decl::ClassTemplateSpecialization:
5806 case Decl::ClassTemplatePartialSpecialization:
5807 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
5808 return MakeCXCursor(Def, TU);
5809 return clang_getNullCursor();
5810
5811 case Decl::Function:
5812 case Decl::CXXMethod:
5813 case Decl::CXXConstructor:
5814 case Decl::CXXDestructor:
5815 case Decl::CXXConversion: {
Craig Topper69186e72014-06-08 08:38:04 +00005816 const FunctionDecl *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005817 if (cast<FunctionDecl>(D)->getBody(Def))
Dmitri Gribenko9c256e32013-01-14 00:46:27 +00005818 return MakeCXCursor(Def, TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00005819 return clang_getNullCursor();
5820 }
5821
Larisse Voufo39a1e502013-08-06 01:03:05 +00005822 case Decl::Var:
5823 case Decl::VarTemplateSpecialization:
Richard Smithbdb84f32016-07-22 23:36:59 +00005824 case Decl::VarTemplatePartialSpecialization:
5825 case Decl::Decomposition: {
Guy Benyei11169dd2012-12-18 14:30:41 +00005826 // Ask the variable if it has a definition.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005827 if (const VarDecl *Def = cast<VarDecl>(D)->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00005828 return MakeCXCursor(Def, TU);
5829 return clang_getNullCursor();
5830 }
5831
5832 case Decl::FunctionTemplate: {
Craig Topper69186e72014-06-08 08:38:04 +00005833 const FunctionDecl *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005834 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
5835 return MakeCXCursor(Def->getDescribedFunctionTemplate(), TU);
5836 return clang_getNullCursor();
5837 }
5838
5839 case Decl::ClassTemplate: {
5840 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
5841 ->getDefinition())
5842 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
5843 TU);
5844 return clang_getNullCursor();
5845 }
5846
Larisse Voufo39a1e502013-08-06 01:03:05 +00005847 case Decl::VarTemplate: {
5848 if (VarDecl *Def =
5849 cast<VarTemplateDecl>(D)->getTemplatedDecl()->getDefinition())
5850 return MakeCXCursor(cast<VarDecl>(Def)->getDescribedVarTemplate(), TU);
5851 return clang_getNullCursor();
5852 }
5853
Guy Benyei11169dd2012-12-18 14:30:41 +00005854 case Decl::Using:
5855 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
5856 D->getLocation(), TU);
5857
5858 case Decl::UsingShadow:
Richard Smith5179eb72016-06-28 19:03:57 +00005859 case Decl::ConstructorUsingShadow:
Guy Benyei11169dd2012-12-18 14:30:41 +00005860 return clang_getCursorDefinition(
5861 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
5862 TU));
5863
5864 case Decl::ObjCMethod: {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005865 const ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00005866 if (Method->isThisDeclarationADefinition())
5867 return C;
5868
5869 // Dig out the method definition in the associated
5870 // @implementation, if we have it.
5871 // FIXME: The ASTs should make finding the definition easier.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005872 if (const ObjCInterfaceDecl *Class
Guy Benyei11169dd2012-12-18 14:30:41 +00005873 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
5874 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
5875 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
5876 Method->isInstanceMethod()))
5877 if (Def->isThisDeclarationADefinition())
5878 return MakeCXCursor(Def, TU);
5879
5880 return clang_getNullCursor();
5881 }
5882
5883 case Decl::ObjCCategory:
5884 if (ObjCCategoryImplDecl *Impl
5885 = cast<ObjCCategoryDecl>(D)->getImplementation())
5886 return MakeCXCursor(Impl, TU);
5887 return clang_getNullCursor();
5888
5889 case Decl::ObjCProtocol:
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005890 if (const ObjCProtocolDecl *Def = cast<ObjCProtocolDecl>(D)->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00005891 return MakeCXCursor(Def, TU);
5892 return clang_getNullCursor();
5893
5894 case Decl::ObjCInterface: {
5895 // There are two notions of a "definition" for an Objective-C
5896 // class: the interface and its implementation. When we resolved a
5897 // reference to an Objective-C class, produce the @interface as
5898 // the definition; when we were provided with the interface,
5899 // produce the @implementation as the definition.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005900 const ObjCInterfaceDecl *IFace = cast<ObjCInterfaceDecl>(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00005901 if (WasReference) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005902 if (const ObjCInterfaceDecl *Def = IFace->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00005903 return MakeCXCursor(Def, TU);
5904 } else if (ObjCImplementationDecl *Impl = IFace->getImplementation())
5905 return MakeCXCursor(Impl, TU);
5906 return clang_getNullCursor();
5907 }
5908
5909 case Decl::ObjCProperty:
5910 // FIXME: We don't really know where to find the
5911 // ObjCPropertyImplDecls that implement this property.
5912 return clang_getNullCursor();
5913
5914 case Decl::ObjCCompatibleAlias:
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005915 if (const ObjCInterfaceDecl *Class
Guy Benyei11169dd2012-12-18 14:30:41 +00005916 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005917 if (const ObjCInterfaceDecl *Def = Class->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00005918 return MakeCXCursor(Def, TU);
5919
5920 return clang_getNullCursor();
5921
5922 case Decl::Friend:
5923 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
5924 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
5925 return clang_getNullCursor();
5926
5927 case Decl::FriendTemplate:
5928 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
5929 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
5930 return clang_getNullCursor();
5931 }
5932
5933 return clang_getNullCursor();
5934}
5935
5936unsigned clang_isCursorDefinition(CXCursor C) {
5937 if (!clang_isDeclaration(C.kind))
5938 return 0;
5939
5940 return clang_getCursorDefinition(C) == C;
5941}
5942
5943CXCursor clang_getCanonicalCursor(CXCursor C) {
5944 if (!clang_isDeclaration(C.kind))
5945 return C;
5946
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005947 if (const Decl *D = getCursorDecl(C)) {
5948 if (const ObjCCategoryImplDecl *CatImplD = dyn_cast<ObjCCategoryImplDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00005949 if (ObjCCategoryDecl *CatD = CatImplD->getCategoryDecl())
5950 return MakeCXCursor(CatD, getCursorTU(C));
5951
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005952 if (const ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
5953 if (const ObjCInterfaceDecl *IFD = ImplD->getClassInterface())
Guy Benyei11169dd2012-12-18 14:30:41 +00005954 return MakeCXCursor(IFD, getCursorTU(C));
5955
5956 return MakeCXCursor(D->getCanonicalDecl(), getCursorTU(C));
5957 }
5958
5959 return C;
5960}
5961
5962int clang_Cursor_getObjCSelectorIndex(CXCursor cursor) {
5963 return cxcursor::getSelectorIdentifierIndexAndLoc(cursor).first;
5964}
5965
5966unsigned clang_getNumOverloadedDecls(CXCursor C) {
5967 if (C.kind != CXCursor_OverloadedDeclRef)
5968 return 0;
5969
5970 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005971 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
Guy Benyei11169dd2012-12-18 14:30:41 +00005972 return E->getNumDecls();
5973
5974 if (OverloadedTemplateStorage *S
5975 = Storage.dyn_cast<OverloadedTemplateStorage*>())
5976 return S->size();
5977
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005978 const Decl *D = Storage.get<const Decl *>();
5979 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00005980 return Using->shadow_size();
5981
5982 return 0;
5983}
5984
5985CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
5986 if (cursor.kind != CXCursor_OverloadedDeclRef)
5987 return clang_getNullCursor();
5988
5989 if (index >= clang_getNumOverloadedDecls(cursor))
5990 return clang_getNullCursor();
5991
5992 CXTranslationUnit TU = getCursorTU(cursor);
5993 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005994 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
Guy Benyei11169dd2012-12-18 14:30:41 +00005995 return MakeCXCursor(E->decls_begin()[index], TU);
5996
5997 if (OverloadedTemplateStorage *S
5998 = Storage.dyn_cast<OverloadedTemplateStorage*>())
5999 return MakeCXCursor(S->begin()[index], TU);
6000
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006001 const Decl *D = Storage.get<const Decl *>();
6002 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006003 // FIXME: This is, unfortunately, linear time.
6004 UsingDecl::shadow_iterator Pos = Using->shadow_begin();
6005 std::advance(Pos, index);
6006 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), TU);
6007 }
6008
6009 return clang_getNullCursor();
6010}
6011
6012void clang_getDefinitionSpellingAndExtent(CXCursor C,
6013 const char **startBuf,
6014 const char **endBuf,
6015 unsigned *startLine,
6016 unsigned *startColumn,
6017 unsigned *endLine,
6018 unsigned *endColumn) {
6019 assert(getCursorDecl(C) && "CXCursor has null decl");
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006020 const FunctionDecl *FD = dyn_cast<FunctionDecl>(getCursorDecl(C));
Guy Benyei11169dd2012-12-18 14:30:41 +00006021 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
6022
6023 SourceManager &SM = FD->getASTContext().getSourceManager();
6024 *startBuf = SM.getCharacterData(Body->getLBracLoc());
6025 *endBuf = SM.getCharacterData(Body->getRBracLoc());
6026 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
6027 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
6028 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
6029 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
6030}
6031
6032
6033CXSourceRange clang_getCursorReferenceNameRange(CXCursor C, unsigned NameFlags,
6034 unsigned PieceIndex) {
6035 RefNamePieces Pieces;
6036
6037 switch (C.kind) {
6038 case CXCursor_MemberRefExpr:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006039 if (const MemberExpr *E = dyn_cast<MemberExpr>(getCursorExpr(C)))
Guy Benyei11169dd2012-12-18 14:30:41 +00006040 Pieces = buildPieces(NameFlags, true, E->getMemberNameInfo(),
6041 E->getQualifierLoc().getSourceRange());
6042 break;
6043
6044 case CXCursor_DeclRefExpr:
James Y Knight04ec5bf2015-12-24 02:59:37 +00006045 if (const DeclRefExpr *E = dyn_cast<DeclRefExpr>(getCursorExpr(C))) {
6046 SourceRange TemplateArgLoc(E->getLAngleLoc(), E->getRAngleLoc());
6047 Pieces =
6048 buildPieces(NameFlags, false, E->getNameInfo(),
6049 E->getQualifierLoc().getSourceRange(), &TemplateArgLoc);
6050 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006051 break;
6052
6053 case CXCursor_CallExpr:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006054 if (const CXXOperatorCallExpr *OCE =
Guy Benyei11169dd2012-12-18 14:30:41 +00006055 dyn_cast<CXXOperatorCallExpr>(getCursorExpr(C))) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006056 const Expr *Callee = OCE->getCallee();
6057 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Callee))
Guy Benyei11169dd2012-12-18 14:30:41 +00006058 Callee = ICE->getSubExpr();
6059
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006060 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Callee))
Guy Benyei11169dd2012-12-18 14:30:41 +00006061 Pieces = buildPieces(NameFlags, false, DRE->getNameInfo(),
6062 DRE->getQualifierLoc().getSourceRange());
6063 }
6064 break;
6065
6066 default:
6067 break;
6068 }
6069
6070 if (Pieces.empty()) {
6071 if (PieceIndex == 0)
6072 return clang_getCursorExtent(C);
6073 } else if (PieceIndex < Pieces.size()) {
6074 SourceRange R = Pieces[PieceIndex];
6075 if (R.isValid())
6076 return cxloc::translateSourceRange(getCursorContext(C), R);
6077 }
6078
6079 return clang_getNullRange();
6080}
6081
6082void clang_enableStackTraces(void) {
Richard Smithdfed58a2016-06-09 00:53:41 +00006083 // FIXME: Provide an argv0 here so we can find llvm-symbolizer.
6084 llvm::sys::PrintStackTraceOnErrorSignal(StringRef());
Guy Benyei11169dd2012-12-18 14:30:41 +00006085}
6086
6087void clang_executeOnThread(void (*fn)(void*), void *user_data,
6088 unsigned stack_size) {
6089 llvm::llvm_execute_on_thread(fn, user_data, stack_size);
6090}
6091
Guy Benyei11169dd2012-12-18 14:30:41 +00006092//===----------------------------------------------------------------------===//
6093// Token-based Operations.
6094//===----------------------------------------------------------------------===//
6095
6096/* CXToken layout:
6097 * int_data[0]: a CXTokenKind
6098 * int_data[1]: starting token location
6099 * int_data[2]: token length
6100 * int_data[3]: reserved
6101 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
6102 * otherwise unused.
6103 */
Guy Benyei11169dd2012-12-18 14:30:41 +00006104CXTokenKind clang_getTokenKind(CXToken CXTok) {
6105 return static_cast<CXTokenKind>(CXTok.int_data[0]);
6106}
6107
6108CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
6109 switch (clang_getTokenKind(CXTok)) {
6110 case CXToken_Identifier:
6111 case CXToken_Keyword:
6112 // We know we have an IdentifierInfo*, so use that.
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00006113 return cxstring::createRef(static_cast<IdentifierInfo *>(CXTok.ptr_data)
Guy Benyei11169dd2012-12-18 14:30:41 +00006114 ->getNameStart());
6115
6116 case CXToken_Literal: {
6117 // We have stashed the starting pointer in the ptr_data field. Use it.
6118 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00006119 return cxstring::createDup(StringRef(Text, CXTok.int_data[2]));
Guy Benyei11169dd2012-12-18 14:30:41 +00006120 }
6121
6122 case CXToken_Punctuation:
6123 case CXToken_Comment:
6124 break;
6125 }
6126
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006127 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006128 LOG_BAD_TU(TU);
6129 return cxstring::createEmpty();
6130 }
6131
Guy Benyei11169dd2012-12-18 14:30:41 +00006132 // We have to find the starting buffer pointer the hard way, by
6133 // deconstructing the source location.
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006134 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006135 if (!CXXUnit)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00006136 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00006137
6138 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
6139 std::pair<FileID, unsigned> LocInfo
6140 = CXXUnit->getSourceManager().getDecomposedSpellingLoc(Loc);
6141 bool Invalid = false;
6142 StringRef Buffer
6143 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
6144 if (Invalid)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00006145 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00006146
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00006147 return cxstring::createDup(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Guy Benyei11169dd2012-12-18 14:30:41 +00006148}
6149
6150CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006151 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006152 LOG_BAD_TU(TU);
6153 return clang_getNullLocation();
6154 }
6155
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006156 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006157 if (!CXXUnit)
6158 return clang_getNullLocation();
6159
6160 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
6161 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
6162}
6163
6164CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006165 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006166 LOG_BAD_TU(TU);
6167 return clang_getNullRange();
6168 }
6169
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006170 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006171 if (!CXXUnit)
6172 return clang_getNullRange();
6173
6174 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
6175 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
6176}
6177
6178static void getTokens(ASTUnit *CXXUnit, SourceRange Range,
6179 SmallVectorImpl<CXToken> &CXTokens) {
6180 SourceManager &SourceMgr = CXXUnit->getSourceManager();
6181 std::pair<FileID, unsigned> BeginLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00006182 = SourceMgr.getDecomposedSpellingLoc(Range.getBegin());
Guy Benyei11169dd2012-12-18 14:30:41 +00006183 std::pair<FileID, unsigned> EndLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00006184 = SourceMgr.getDecomposedSpellingLoc(Range.getEnd());
Guy Benyei11169dd2012-12-18 14:30:41 +00006185
6186 // Cannot tokenize across files.
6187 if (BeginLocInfo.first != EndLocInfo.first)
6188 return;
6189
6190 // Create a lexer
6191 bool Invalid = false;
6192 StringRef Buffer
6193 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
6194 if (Invalid)
6195 return;
6196
6197 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
6198 CXXUnit->getASTContext().getLangOpts(),
6199 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
6200 Lex.SetCommentRetentionState(true);
6201
6202 // Lex tokens until we hit the end of the range.
6203 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
6204 Token Tok;
6205 bool previousWasAt = false;
6206 do {
6207 // Lex the next token
6208 Lex.LexFromRawLexer(Tok);
6209 if (Tok.is(tok::eof))
6210 break;
6211
6212 // Initialize the CXToken.
6213 CXToken CXTok;
6214
6215 // - Common fields
6216 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
6217 CXTok.int_data[2] = Tok.getLength();
6218 CXTok.int_data[3] = 0;
6219
6220 // - Kind-specific fields
6221 if (Tok.isLiteral()) {
6222 CXTok.int_data[0] = CXToken_Literal;
Dmitri Gribenkof9304482013-01-23 15:56:07 +00006223 CXTok.ptr_data = const_cast<char *>(Tok.getLiteralData());
Guy Benyei11169dd2012-12-18 14:30:41 +00006224 } else if (Tok.is(tok::raw_identifier)) {
6225 // Lookup the identifier to determine whether we have a keyword.
6226 IdentifierInfo *II
6227 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok);
6228
6229 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
6230 CXTok.int_data[0] = CXToken_Keyword;
6231 }
6232 else {
6233 CXTok.int_data[0] = Tok.is(tok::identifier)
6234 ? CXToken_Identifier
6235 : CXToken_Keyword;
6236 }
6237 CXTok.ptr_data = II;
6238 } else if (Tok.is(tok::comment)) {
6239 CXTok.int_data[0] = CXToken_Comment;
Craig Topper69186e72014-06-08 08:38:04 +00006240 CXTok.ptr_data = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006241 } else {
6242 CXTok.int_data[0] = CXToken_Punctuation;
Craig Topper69186e72014-06-08 08:38:04 +00006243 CXTok.ptr_data = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006244 }
6245 CXTokens.push_back(CXTok);
6246 previousWasAt = Tok.is(tok::at);
Argyrios Kyrtzidisc7c6a072016-11-09 23:58:39 +00006247 } while (Lex.getBufferLocation() < EffectiveBufferEnd);
Guy Benyei11169dd2012-12-18 14:30:41 +00006248}
6249
6250void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
6251 CXToken **Tokens, unsigned *NumTokens) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00006252 LOG_FUNC_SECTION {
6253 *Log << TU << ' ' << Range;
6254 }
6255
Guy Benyei11169dd2012-12-18 14:30:41 +00006256 if (Tokens)
Craig Topper69186e72014-06-08 08:38:04 +00006257 *Tokens = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006258 if (NumTokens)
6259 *NumTokens = 0;
6260
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006261 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006262 LOG_BAD_TU(TU);
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00006263 return;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006264 }
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00006265
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006266 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006267 if (!CXXUnit || !Tokens || !NumTokens)
6268 return;
6269
6270 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
6271
6272 SourceRange R = cxloc::translateCXSourceRange(Range);
6273 if (R.isInvalid())
6274 return;
6275
6276 SmallVector<CXToken, 32> CXTokens;
6277 getTokens(CXXUnit, R, CXTokens);
6278
6279 if (CXTokens.empty())
6280 return;
6281
6282 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
6283 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
6284 *NumTokens = CXTokens.size();
6285}
6286
6287void clang_disposeTokens(CXTranslationUnit TU,
6288 CXToken *Tokens, unsigned NumTokens) {
6289 free(Tokens);
6290}
6291
Guy Benyei11169dd2012-12-18 14:30:41 +00006292//===----------------------------------------------------------------------===//
6293// Token annotation APIs.
6294//===----------------------------------------------------------------------===//
6295
Guy Benyei11169dd2012-12-18 14:30:41 +00006296static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
6297 CXCursor parent,
6298 CXClientData client_data);
6299static bool AnnotateTokensPostChildrenVisitor(CXCursor cursor,
6300 CXClientData client_data);
6301
6302namespace {
6303class AnnotateTokensWorker {
Guy Benyei11169dd2012-12-18 14:30:41 +00006304 CXToken *Tokens;
6305 CXCursor *Cursors;
6306 unsigned NumTokens;
6307 unsigned TokIdx;
6308 unsigned PreprocessingTokIdx;
6309 CursorVisitor AnnotateVis;
6310 SourceManager &SrcMgr;
6311 bool HasContextSensitiveKeywords;
6312
6313 struct PostChildrenInfo {
6314 CXCursor Cursor;
6315 SourceRange CursorRange;
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006316 unsigned BeforeReachingCursorIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00006317 unsigned BeforeChildrenTokenIdx;
6318 };
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006319 SmallVector<PostChildrenInfo, 8> PostChildrenInfos;
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006320
6321 CXToken &getTok(unsigned Idx) {
6322 assert(Idx < NumTokens);
6323 return Tokens[Idx];
6324 }
6325 const CXToken &getTok(unsigned Idx) const {
6326 assert(Idx < NumTokens);
6327 return Tokens[Idx];
6328 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006329 bool MoreTokens() const { return TokIdx < NumTokens; }
6330 unsigned NextToken() const { return TokIdx; }
6331 void AdvanceToken() { ++TokIdx; }
6332 SourceLocation GetTokenLoc(unsigned tokI) {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006333 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[1]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006334 }
6335 bool isFunctionMacroToken(unsigned tokI) const {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006336 return getTok(tokI).int_data[3] != 0;
Guy Benyei11169dd2012-12-18 14:30:41 +00006337 }
6338 SourceLocation getFunctionMacroTokenLoc(unsigned tokI) const {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006339 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[3]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006340 }
6341
6342 void annotateAndAdvanceTokens(CXCursor, RangeComparisonResult, SourceRange);
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006343 bool annotateAndAdvanceFunctionMacroTokens(CXCursor, RangeComparisonResult,
Guy Benyei11169dd2012-12-18 14:30:41 +00006344 SourceRange);
6345
6346public:
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006347 AnnotateTokensWorker(CXToken *tokens, CXCursor *cursors, unsigned numTokens,
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006348 CXTranslationUnit TU, SourceRange RegionOfInterest)
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006349 : Tokens(tokens), Cursors(cursors),
Guy Benyei11169dd2012-12-18 14:30:41 +00006350 NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006351 AnnotateVis(TU,
Guy Benyei11169dd2012-12-18 14:30:41 +00006352 AnnotateTokensVisitor, this,
6353 /*VisitPreprocessorLast=*/true,
6354 /*VisitIncludedEntities=*/false,
6355 RegionOfInterest,
6356 /*VisitDeclsOnly=*/false,
6357 AnnotateTokensPostChildrenVisitor),
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006358 SrcMgr(cxtu::getASTUnit(TU)->getSourceManager()),
Guy Benyei11169dd2012-12-18 14:30:41 +00006359 HasContextSensitiveKeywords(false) { }
6360
6361 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
6362 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
6363 bool postVisitChildren(CXCursor cursor);
6364 void AnnotateTokens();
6365
6366 /// \brief Determine whether the annotator saw any cursors that have
6367 /// context-sensitive keywords.
6368 bool hasContextSensitiveKeywords() const {
6369 return HasContextSensitiveKeywords;
6370 }
6371
6372 ~AnnotateTokensWorker() {
6373 assert(PostChildrenInfos.empty());
6374 }
6375};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006376}
Guy Benyei11169dd2012-12-18 14:30:41 +00006377
6378void AnnotateTokensWorker::AnnotateTokens() {
6379 // Walk the AST within the region of interest, annotating tokens
6380 // along the way.
6381 AnnotateVis.visitFileRegion();
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006382}
Guy Benyei11169dd2012-12-18 14:30:41 +00006383
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006384static inline void updateCursorAnnotation(CXCursor &Cursor,
6385 const CXCursor &updateC) {
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006386 if (clang_isInvalid(updateC.kind) || !clang_isInvalid(Cursor.kind))
Guy Benyei11169dd2012-12-18 14:30:41 +00006387 return;
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006388 Cursor = updateC;
Guy Benyei11169dd2012-12-18 14:30:41 +00006389}
6390
6391/// \brief It annotates and advances tokens with a cursor until the comparison
6392//// between the cursor location and the source range is the same as
6393/// \arg compResult.
6394///
6395/// Pass RangeBefore to annotate tokens with a cursor until a range is reached.
6396/// Pass RangeOverlap to annotate tokens inside a range.
6397void AnnotateTokensWorker::annotateAndAdvanceTokens(CXCursor updateC,
6398 RangeComparisonResult compResult,
6399 SourceRange range) {
6400 while (MoreTokens()) {
6401 const unsigned I = NextToken();
6402 if (isFunctionMacroToken(I))
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006403 if (!annotateAndAdvanceFunctionMacroTokens(updateC, compResult, range))
6404 return;
Guy Benyei11169dd2012-12-18 14:30:41 +00006405
6406 SourceLocation TokLoc = GetTokenLoc(I);
6407 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006408 updateCursorAnnotation(Cursors[I], updateC);
Guy Benyei11169dd2012-12-18 14:30:41 +00006409 AdvanceToken();
6410 continue;
6411 }
6412 break;
6413 }
6414}
6415
6416/// \brief Special annotation handling for macro argument tokens.
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006417/// \returns true if it advanced beyond all macro tokens, false otherwise.
6418bool AnnotateTokensWorker::annotateAndAdvanceFunctionMacroTokens(
Guy Benyei11169dd2012-12-18 14:30:41 +00006419 CXCursor updateC,
6420 RangeComparisonResult compResult,
6421 SourceRange range) {
6422 assert(MoreTokens());
6423 assert(isFunctionMacroToken(NextToken()) &&
6424 "Should be called only for macro arg tokens");
6425
6426 // This works differently than annotateAndAdvanceTokens; because expanded
6427 // macro arguments can have arbitrary translation-unit source order, we do not
6428 // advance the token index one by one until a token fails the range test.
6429 // We only advance once past all of the macro arg tokens if all of them
6430 // pass the range test. If one of them fails we keep the token index pointing
6431 // at the start of the macro arg tokens so that the failing token will be
6432 // annotated by a subsequent annotation try.
6433
6434 bool atLeastOneCompFail = false;
6435
6436 unsigned I = NextToken();
6437 for (; I < NumTokens && isFunctionMacroToken(I); ++I) {
6438 SourceLocation TokLoc = getFunctionMacroTokenLoc(I);
6439 if (TokLoc.isFileID())
6440 continue; // not macro arg token, it's parens or comma.
6441 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
6442 if (clang_isInvalid(clang_getCursorKind(Cursors[I])))
6443 Cursors[I] = updateC;
6444 } else
6445 atLeastOneCompFail = true;
6446 }
6447
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006448 if (atLeastOneCompFail)
6449 return false;
6450
6451 TokIdx = I; // All of the tokens were handled, advance beyond all of them.
6452 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00006453}
6454
6455enum CXChildVisitResult
6456AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006457 SourceRange cursorRange = getRawCursorExtent(cursor);
6458 if (cursorRange.isInvalid())
6459 return CXChildVisit_Recurse;
6460
6461 if (!HasContextSensitiveKeywords) {
6462 // Objective-C properties can have context-sensitive keywords.
6463 if (cursor.kind == CXCursor_ObjCPropertyDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006464 if (const ObjCPropertyDecl *Property
Guy Benyei11169dd2012-12-18 14:30:41 +00006465 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(cursor)))
6466 HasContextSensitiveKeywords = Property->getPropertyAttributesAsWritten() != 0;
6467 }
6468 // Objective-C methods can have context-sensitive keywords.
6469 else if (cursor.kind == CXCursor_ObjCInstanceMethodDecl ||
6470 cursor.kind == CXCursor_ObjCClassMethodDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006471 if (const ObjCMethodDecl *Method
Guy Benyei11169dd2012-12-18 14:30:41 +00006472 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
6473 if (Method->getObjCDeclQualifier())
6474 HasContextSensitiveKeywords = true;
6475 else {
David Majnemer59f77922016-06-24 04:05:48 +00006476 for (const auto *P : Method->parameters()) {
Aaron Ballman43b68be2014-03-07 17:50:17 +00006477 if (P->getObjCDeclQualifier()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006478 HasContextSensitiveKeywords = true;
6479 break;
6480 }
6481 }
6482 }
6483 }
6484 }
6485 // C++ methods can have context-sensitive keywords.
6486 else if (cursor.kind == CXCursor_CXXMethod) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006487 if (const CXXMethodDecl *Method
Guy Benyei11169dd2012-12-18 14:30:41 +00006488 = dyn_cast_or_null<CXXMethodDecl>(getCursorDecl(cursor))) {
6489 if (Method->hasAttr<FinalAttr>() || Method->hasAttr<OverrideAttr>())
6490 HasContextSensitiveKeywords = true;
6491 }
6492 }
6493 // C++ classes can have context-sensitive keywords.
6494 else if (cursor.kind == CXCursor_StructDecl ||
6495 cursor.kind == CXCursor_ClassDecl ||
6496 cursor.kind == CXCursor_ClassTemplate ||
6497 cursor.kind == CXCursor_ClassTemplatePartialSpecialization) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006498 if (const Decl *D = getCursorDecl(cursor))
Guy Benyei11169dd2012-12-18 14:30:41 +00006499 if (D->hasAttr<FinalAttr>())
6500 HasContextSensitiveKeywords = true;
6501 }
6502 }
Argyrios Kyrtzidis990b3862013-06-04 18:24:30 +00006503
6504 // Don't override a property annotation with its getter/setter method.
6505 if (cursor.kind == CXCursor_ObjCInstanceMethodDecl &&
6506 parent.kind == CXCursor_ObjCPropertyDecl)
6507 return CXChildVisit_Continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00006508
6509 if (clang_isPreprocessing(cursor.kind)) {
6510 // Items in the preprocessing record are kept separate from items in
6511 // declarations, so we keep a separate token index.
6512 unsigned SavedTokIdx = TokIdx;
6513 TokIdx = PreprocessingTokIdx;
6514
6515 // Skip tokens up until we catch up to the beginning of the preprocessing
6516 // entry.
6517 while (MoreTokens()) {
6518 const unsigned I = NextToken();
6519 SourceLocation TokLoc = GetTokenLoc(I);
6520 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
6521 case RangeBefore:
6522 AdvanceToken();
6523 continue;
6524 case RangeAfter:
6525 case RangeOverlap:
6526 break;
6527 }
6528 break;
6529 }
6530
6531 // Look at all of the tokens within this range.
6532 while (MoreTokens()) {
6533 const unsigned I = NextToken();
6534 SourceLocation TokLoc = GetTokenLoc(I);
6535 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
6536 case RangeBefore:
6537 llvm_unreachable("Infeasible");
6538 case RangeAfter:
6539 break;
6540 case RangeOverlap:
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00006541 // For macro expansions, just note where the beginning of the macro
6542 // expansion occurs.
6543 if (cursor.kind == CXCursor_MacroExpansion) {
6544 if (TokLoc == cursorRange.getBegin())
6545 Cursors[I] = cursor;
6546 AdvanceToken();
6547 break;
6548 }
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006549 // We may have already annotated macro names inside macro definitions.
6550 if (Cursors[I].kind != CXCursor_MacroExpansion)
6551 Cursors[I] = cursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00006552 AdvanceToken();
Guy Benyei11169dd2012-12-18 14:30:41 +00006553 continue;
6554 }
6555 break;
6556 }
6557
6558 // Save the preprocessing token index; restore the non-preprocessing
6559 // token index.
6560 PreprocessingTokIdx = TokIdx;
6561 TokIdx = SavedTokIdx;
6562 return CXChildVisit_Recurse;
6563 }
6564
6565 if (cursorRange.isInvalid())
6566 return CXChildVisit_Continue;
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006567
6568 unsigned BeforeReachingCursorIdx = NextToken();
Guy Benyei11169dd2012-12-18 14:30:41 +00006569 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00006570 const enum CXCursorKind K = clang_getCursorKind(parent);
6571 const CXCursor updateC =
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006572 (clang_isInvalid(K) || K == CXCursor_TranslationUnit ||
6573 // Attributes are annotated out-of-order, skip tokens until we reach it.
6574 clang_isAttribute(cursor.kind))
Guy Benyei11169dd2012-12-18 14:30:41 +00006575 ? clang_getNullCursor() : parent;
6576
6577 annotateAndAdvanceTokens(updateC, RangeBefore, cursorRange);
6578
6579 // Avoid having the cursor of an expression "overwrite" the annotation of the
6580 // variable declaration that it belongs to.
6581 // This can happen for C++ constructor expressions whose range generally
6582 // include the variable declaration, e.g.:
6583 // MyCXXClass foo; // Make sure we don't annotate 'foo' as a CallExpr cursor.
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006584 if (clang_isExpression(cursorK) && MoreTokens()) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006585 const Expr *E = getCursorExpr(cursor);
Dmitri Gribenkoa1691182013-01-26 18:12:08 +00006586 if (const Decl *D = getCursorParentDecl(cursor)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006587 const unsigned I = NextToken();
6588 if (E->getLocStart().isValid() && D->getLocation().isValid() &&
6589 E->getLocStart() == D->getLocation() &&
6590 E->getLocStart() == GetTokenLoc(I)) {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006591 updateCursorAnnotation(Cursors[I], updateC);
Guy Benyei11169dd2012-12-18 14:30:41 +00006592 AdvanceToken();
6593 }
6594 }
6595 }
6596
6597 // Before recursing into the children keep some state that we are going
6598 // to use in the AnnotateTokensWorker::postVisitChildren callback to do some
6599 // extra work after the child nodes are visited.
6600 // Note that we don't call VisitChildren here to avoid traversing statements
6601 // code-recursively which can blow the stack.
6602
6603 PostChildrenInfo Info;
6604 Info.Cursor = cursor;
6605 Info.CursorRange = cursorRange;
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006606 Info.BeforeReachingCursorIdx = BeforeReachingCursorIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00006607 Info.BeforeChildrenTokenIdx = NextToken();
6608 PostChildrenInfos.push_back(Info);
6609
6610 return CXChildVisit_Recurse;
6611}
6612
6613bool AnnotateTokensWorker::postVisitChildren(CXCursor cursor) {
6614 if (PostChildrenInfos.empty())
6615 return false;
6616 const PostChildrenInfo &Info = PostChildrenInfos.back();
6617 if (!clang_equalCursors(Info.Cursor, cursor))
6618 return false;
6619
6620 const unsigned BeforeChildren = Info.BeforeChildrenTokenIdx;
6621 const unsigned AfterChildren = NextToken();
6622 SourceRange cursorRange = Info.CursorRange;
6623
6624 // Scan the tokens that are at the end of the cursor, but are not captured
6625 // but the child cursors.
6626 annotateAndAdvanceTokens(cursor, RangeOverlap, cursorRange);
6627
6628 // Scan the tokens that are at the beginning of the cursor, but are not
6629 // capture by the child cursors.
6630 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
6631 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
6632 break;
6633
6634 Cursors[I] = cursor;
6635 }
6636
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006637 // Attributes are annotated out-of-order, rewind TokIdx to when we first
6638 // encountered the attribute cursor.
6639 if (clang_isAttribute(cursor.kind))
6640 TokIdx = Info.BeforeReachingCursorIdx;
6641
Guy Benyei11169dd2012-12-18 14:30:41 +00006642 PostChildrenInfos.pop_back();
6643 return false;
6644}
6645
6646static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
6647 CXCursor parent,
6648 CXClientData client_data) {
6649 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
6650}
6651
6652static bool AnnotateTokensPostChildrenVisitor(CXCursor cursor,
6653 CXClientData client_data) {
6654 return static_cast<AnnotateTokensWorker*>(client_data)->
6655 postVisitChildren(cursor);
6656}
6657
6658namespace {
6659
6660/// \brief Uses the macro expansions in the preprocessing record to find
6661/// and mark tokens that are macro arguments. This info is used by the
6662/// AnnotateTokensWorker.
6663class MarkMacroArgTokensVisitor {
6664 SourceManager &SM;
6665 CXToken *Tokens;
6666 unsigned NumTokens;
6667 unsigned CurIdx;
6668
6669public:
6670 MarkMacroArgTokensVisitor(SourceManager &SM,
6671 CXToken *tokens, unsigned numTokens)
6672 : SM(SM), Tokens(tokens), NumTokens(numTokens), CurIdx(0) { }
6673
6674 CXChildVisitResult visit(CXCursor cursor, CXCursor parent) {
6675 if (cursor.kind != CXCursor_MacroExpansion)
6676 return CXChildVisit_Continue;
6677
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00006678 SourceRange macroRange = getCursorMacroExpansion(cursor).getSourceRange();
Guy Benyei11169dd2012-12-18 14:30:41 +00006679 if (macroRange.getBegin() == macroRange.getEnd())
6680 return CXChildVisit_Continue; // it's not a function macro.
6681
6682 for (; CurIdx < NumTokens; ++CurIdx) {
6683 if (!SM.isBeforeInTranslationUnit(getTokenLoc(CurIdx),
6684 macroRange.getBegin()))
6685 break;
6686 }
6687
6688 if (CurIdx == NumTokens)
6689 return CXChildVisit_Break;
6690
6691 for (; CurIdx < NumTokens; ++CurIdx) {
6692 SourceLocation tokLoc = getTokenLoc(CurIdx);
6693 if (!SM.isBeforeInTranslationUnit(tokLoc, macroRange.getEnd()))
6694 break;
6695
6696 setFunctionMacroTokenLoc(CurIdx, SM.getMacroArgExpandedLocation(tokLoc));
6697 }
6698
6699 if (CurIdx == NumTokens)
6700 return CXChildVisit_Break;
6701
6702 return CXChildVisit_Continue;
6703 }
6704
6705private:
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006706 CXToken &getTok(unsigned Idx) {
6707 assert(Idx < NumTokens);
6708 return Tokens[Idx];
6709 }
6710 const CXToken &getTok(unsigned Idx) const {
6711 assert(Idx < NumTokens);
6712 return Tokens[Idx];
6713 }
6714
Guy Benyei11169dd2012-12-18 14:30:41 +00006715 SourceLocation getTokenLoc(unsigned tokI) {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006716 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[1]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006717 }
6718
6719 void setFunctionMacroTokenLoc(unsigned tokI, SourceLocation loc) {
6720 // The third field is reserved and currently not used. Use it here
6721 // to mark macro arg expanded tokens with their expanded locations.
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006722 getTok(tokI).int_data[3] = loc.getRawEncoding();
Guy Benyei11169dd2012-12-18 14:30:41 +00006723 }
6724};
6725
6726} // end anonymous namespace
6727
6728static CXChildVisitResult
6729MarkMacroArgTokensVisitorDelegate(CXCursor cursor, CXCursor parent,
6730 CXClientData client_data) {
6731 return static_cast<MarkMacroArgTokensVisitor*>(client_data)->visit(cursor,
6732 parent);
6733}
6734
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006735/// \brief Used by \c annotatePreprocessorTokens.
6736/// \returns true if lexing was finished, false otherwise.
6737static bool lexNext(Lexer &Lex, Token &Tok,
6738 unsigned &NextIdx, unsigned NumTokens) {
6739 if (NextIdx >= NumTokens)
6740 return true;
6741
6742 ++NextIdx;
6743 Lex.LexFromRawLexer(Tok);
Alexander Kornienko1a9f1842015-12-28 15:24:08 +00006744 return Tok.is(tok::eof);
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006745}
6746
Guy Benyei11169dd2012-12-18 14:30:41 +00006747static void annotatePreprocessorTokens(CXTranslationUnit TU,
6748 SourceRange RegionOfInterest,
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006749 CXCursor *Cursors,
6750 CXToken *Tokens,
6751 unsigned NumTokens) {
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006752 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006753
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00006754 Preprocessor &PP = CXXUnit->getPreprocessor();
Guy Benyei11169dd2012-12-18 14:30:41 +00006755 SourceManager &SourceMgr = CXXUnit->getSourceManager();
6756 std::pair<FileID, unsigned> BeginLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00006757 = SourceMgr.getDecomposedSpellingLoc(RegionOfInterest.getBegin());
Guy Benyei11169dd2012-12-18 14:30:41 +00006758 std::pair<FileID, unsigned> EndLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00006759 = SourceMgr.getDecomposedSpellingLoc(RegionOfInterest.getEnd());
Guy Benyei11169dd2012-12-18 14:30:41 +00006760
6761 if (BeginLocInfo.first != EndLocInfo.first)
6762 return;
6763
6764 StringRef Buffer;
6765 bool Invalid = false;
6766 Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
6767 if (Buffer.empty() || Invalid)
6768 return;
6769
6770 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
6771 CXXUnit->getASTContext().getLangOpts(),
6772 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
6773 Buffer.end());
6774 Lex.SetCommentRetentionState(true);
6775
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006776 unsigned NextIdx = 0;
Guy Benyei11169dd2012-12-18 14:30:41 +00006777 // Lex tokens in raw mode until we hit the end of the range, to avoid
6778 // entering #includes or expanding macros.
6779 while (true) {
6780 Token Tok;
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006781 if (lexNext(Lex, Tok, NextIdx, NumTokens))
6782 break;
6783 unsigned TokIdx = NextIdx-1;
6784 assert(Tok.getLocation() ==
6785 SourceLocation::getFromRawEncoding(Tokens[TokIdx].int_data[1]));
Guy Benyei11169dd2012-12-18 14:30:41 +00006786
6787 reprocess:
6788 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006789 // We have found a preprocessing directive. Annotate the tokens
6790 // appropriately.
Guy Benyei11169dd2012-12-18 14:30:41 +00006791 //
6792 // FIXME: Some simple tests here could identify macro definitions and
6793 // #undefs, to provide specific cursor kinds for those.
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006794
6795 SourceLocation BeginLoc = Tok.getLocation();
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00006796 if (lexNext(Lex, Tok, NextIdx, NumTokens))
6797 break;
6798
Craig Topper69186e72014-06-08 08:38:04 +00006799 MacroInfo *MI = nullptr;
Alp Toker2d57cea2014-05-17 04:53:25 +00006800 if (Tok.is(tok::raw_identifier) && Tok.getRawIdentifier() == "define") {
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00006801 if (lexNext(Lex, Tok, NextIdx, NumTokens))
6802 break;
6803
6804 if (Tok.is(tok::raw_identifier)) {
Alp Toker2d57cea2014-05-17 04:53:25 +00006805 IdentifierInfo &II =
6806 PP.getIdentifierTable().get(Tok.getRawIdentifier());
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00006807 SourceLocation MappedTokLoc =
6808 CXXUnit->mapLocationToPreamble(Tok.getLocation());
6809 MI = getMacroInfo(II, MappedTokLoc, TU);
6810 }
6811 }
6812
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006813 bool finished = false;
Guy Benyei11169dd2012-12-18 14:30:41 +00006814 do {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006815 if (lexNext(Lex, Tok, NextIdx, NumTokens)) {
6816 finished = true;
6817 break;
6818 }
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00006819 // If we are in a macro definition, check if the token was ever a
6820 // macro name and annotate it if that's the case.
6821 if (MI) {
6822 SourceLocation SaveLoc = Tok.getLocation();
6823 Tok.setLocation(CXXUnit->mapLocationToPreamble(SaveLoc));
Richard Smith66a81862015-05-04 02:25:31 +00006824 MacroDefinitionRecord *MacroDef =
6825 checkForMacroInMacroDefinition(MI, Tok, TU);
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00006826 Tok.setLocation(SaveLoc);
6827 if (MacroDef)
Richard Smith66a81862015-05-04 02:25:31 +00006828 Cursors[NextIdx - 1] =
6829 MakeMacroExpansionCursor(MacroDef, Tok.getLocation(), TU);
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00006830 }
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006831 } while (!Tok.isAtStartOfLine());
6832
6833 unsigned LastIdx = finished ? NextIdx-1 : NextIdx-2;
6834 assert(TokIdx <= LastIdx);
6835 SourceLocation EndLoc =
6836 SourceLocation::getFromRawEncoding(Tokens[LastIdx].int_data[1]);
6837 CXCursor Cursor =
6838 MakePreprocessingDirectiveCursor(SourceRange(BeginLoc, EndLoc), TU);
6839
6840 for (; TokIdx <= LastIdx; ++TokIdx)
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00006841 updateCursorAnnotation(Cursors[TokIdx], Cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00006842
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006843 if (finished)
6844 break;
6845 goto reprocess;
Guy Benyei11169dd2012-12-18 14:30:41 +00006846 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006847 }
6848}
6849
6850// This gets run a separate thread to avoid stack blowout.
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00006851static void clang_annotateTokensImpl(CXTranslationUnit TU, ASTUnit *CXXUnit,
6852 CXToken *Tokens, unsigned NumTokens,
6853 CXCursor *Cursors) {
Dmitri Gribenko183436e2013-01-26 21:49:50 +00006854 CIndexer *CXXIdx = TU->CIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00006855 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing))
6856 setThreadBackgroundPriority();
6857
6858 // Determine the region of interest, which contains all of the tokens.
6859 SourceRange RegionOfInterest;
6860 RegionOfInterest.setBegin(
6861 cxloc::translateSourceLocation(clang_getTokenLocation(TU, Tokens[0])));
6862 RegionOfInterest.setEnd(
6863 cxloc::translateSourceLocation(clang_getTokenLocation(TU,
6864 Tokens[NumTokens-1])));
6865
Guy Benyei11169dd2012-12-18 14:30:41 +00006866 // Relex the tokens within the source range to look for preprocessing
6867 // directives.
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006868 annotatePreprocessorTokens(TU, RegionOfInterest, Cursors, Tokens, NumTokens);
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00006869
6870 // If begin location points inside a macro argument, set it to the expansion
6871 // location so we can have the full context when annotating semantically.
6872 {
6873 SourceManager &SM = CXXUnit->getSourceManager();
6874 SourceLocation Loc =
6875 SM.getMacroArgExpandedLocation(RegionOfInterest.getBegin());
6876 if (Loc.isMacroID())
6877 RegionOfInterest.setBegin(SM.getExpansionLoc(Loc));
6878 }
6879
Guy Benyei11169dd2012-12-18 14:30:41 +00006880 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
6881 // Search and mark tokens that are macro argument expansions.
6882 MarkMacroArgTokensVisitor Visitor(CXXUnit->getSourceManager(),
6883 Tokens, NumTokens);
6884 CursorVisitor MacroArgMarker(TU,
6885 MarkMacroArgTokensVisitorDelegate, &Visitor,
6886 /*VisitPreprocessorLast=*/true,
6887 /*VisitIncludedEntities=*/false,
6888 RegionOfInterest);
6889 MacroArgMarker.visitPreprocessedEntitiesInRegion();
6890 }
6891
6892 // Annotate all of the source locations in the region of interest that map to
6893 // a specific cursor.
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006894 AnnotateTokensWorker W(Tokens, Cursors, NumTokens, TU, RegionOfInterest);
Guy Benyei11169dd2012-12-18 14:30:41 +00006895
6896 // FIXME: We use a ridiculous stack size here because the data-recursion
6897 // algorithm uses a large stack frame than the non-data recursive version,
6898 // and AnnotationTokensWorker currently transforms the data-recursion
6899 // algorithm back into a traditional recursion by explicitly calling
6900 // VisitChildren(). We will need to remove this explicit recursive call.
6901 W.AnnotateTokens();
6902
6903 // If we ran into any entities that involve context-sensitive keywords,
6904 // take another pass through the tokens to mark them as such.
6905 if (W.hasContextSensitiveKeywords()) {
6906 for (unsigned I = 0; I != NumTokens; ++I) {
6907 if (clang_getTokenKind(Tokens[I]) != CXToken_Identifier)
6908 continue;
6909
6910 if (Cursors[I].kind == CXCursor_ObjCPropertyDecl) {
6911 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006912 if (const ObjCPropertyDecl *Property
Guy Benyei11169dd2012-12-18 14:30:41 +00006913 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(Cursors[I]))) {
6914 if (Property->getPropertyAttributesAsWritten() != 0 &&
6915 llvm::StringSwitch<bool>(II->getName())
6916 .Case("readonly", true)
6917 .Case("assign", true)
6918 .Case("unsafe_unretained", true)
6919 .Case("readwrite", true)
6920 .Case("retain", true)
6921 .Case("copy", true)
6922 .Case("nonatomic", true)
6923 .Case("atomic", true)
6924 .Case("getter", true)
6925 .Case("setter", true)
6926 .Case("strong", true)
6927 .Case("weak", true)
Manman Ren04fd4d82016-05-31 23:22:04 +00006928 .Case("class", true)
Guy Benyei11169dd2012-12-18 14:30:41 +00006929 .Default(false))
6930 Tokens[I].int_data[0] = CXToken_Keyword;
6931 }
6932 continue;
6933 }
6934
6935 if (Cursors[I].kind == CXCursor_ObjCInstanceMethodDecl ||
6936 Cursors[I].kind == CXCursor_ObjCClassMethodDecl) {
6937 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
6938 if (llvm::StringSwitch<bool>(II->getName())
6939 .Case("in", true)
6940 .Case("out", true)
6941 .Case("inout", true)
6942 .Case("oneway", true)
6943 .Case("bycopy", true)
6944 .Case("byref", true)
6945 .Default(false))
6946 Tokens[I].int_data[0] = CXToken_Keyword;
6947 continue;
6948 }
6949
6950 if (Cursors[I].kind == CXCursor_CXXFinalAttr ||
6951 Cursors[I].kind == CXCursor_CXXOverrideAttr) {
6952 Tokens[I].int_data[0] = CXToken_Keyword;
6953 continue;
6954 }
6955 }
6956 }
6957}
6958
Guy Benyei11169dd2012-12-18 14:30:41 +00006959void clang_annotateTokens(CXTranslationUnit TU,
6960 CXToken *Tokens, unsigned NumTokens,
6961 CXCursor *Cursors) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006962 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006963 LOG_BAD_TU(TU);
6964 return;
6965 }
6966 if (NumTokens == 0 || !Tokens || !Cursors) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00006967 LOG_FUNC_SECTION { *Log << "<null input>"; }
Guy Benyei11169dd2012-12-18 14:30:41 +00006968 return;
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00006969 }
6970
6971 LOG_FUNC_SECTION {
6972 *Log << TU << ' ';
6973 CXSourceLocation bloc = clang_getTokenLocation(TU, Tokens[0]);
6974 CXSourceLocation eloc = clang_getTokenLocation(TU, Tokens[NumTokens-1]);
6975 *Log << clang_getRange(bloc, eloc);
6976 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006977
6978 // Any token we don't specifically annotate will have a NULL cursor.
6979 CXCursor C = clang_getNullCursor();
6980 for (unsigned I = 0; I != NumTokens; ++I)
6981 Cursors[I] = C;
6982
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006983 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006984 if (!CXXUnit)
6985 return;
6986
6987 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00006988
6989 auto AnnotateTokensImpl = [=]() {
6990 clang_annotateTokensImpl(TU, CXXUnit, Tokens, NumTokens, Cursors);
6991 };
Guy Benyei11169dd2012-12-18 14:30:41 +00006992 llvm::CrashRecoveryContext CRC;
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00006993 if (!RunSafely(CRC, AnnotateTokensImpl, GetSafetyThreadStackSize() * 2)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006994 fprintf(stderr, "libclang: crash detected while annotating tokens\n");
6995 }
6996}
6997
Guy Benyei11169dd2012-12-18 14:30:41 +00006998//===----------------------------------------------------------------------===//
6999// Operations for querying linkage of a cursor.
7000//===----------------------------------------------------------------------===//
7001
Guy Benyei11169dd2012-12-18 14:30:41 +00007002CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
7003 if (!clang_isDeclaration(cursor.kind))
7004 return CXLinkage_Invalid;
7005
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007006 const Decl *D = cxcursor::getCursorDecl(cursor);
7007 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
Rafael Espindola3ae00052013-05-13 00:12:11 +00007008 switch (ND->getLinkageInternal()) {
Rafael Espindola50df3a02013-05-25 17:16:20 +00007009 case NoLinkage:
7010 case VisibleNoLinkage: return CXLinkage_NoLinkage;
Guy Benyei11169dd2012-12-18 14:30:41 +00007011 case InternalLinkage: return CXLinkage_Internal;
7012 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
7013 case ExternalLinkage: return CXLinkage_External;
7014 };
7015
7016 return CXLinkage_Invalid;
7017}
Guy Benyei11169dd2012-12-18 14:30:41 +00007018
7019//===----------------------------------------------------------------------===//
Ehsan Akhgarib743de72016-05-31 15:55:51 +00007020// Operations for querying visibility of a cursor.
7021//===----------------------------------------------------------------------===//
7022
Ehsan Akhgarib743de72016-05-31 15:55:51 +00007023CXVisibilityKind clang_getCursorVisibility(CXCursor cursor) {
7024 if (!clang_isDeclaration(cursor.kind))
7025 return CXVisibility_Invalid;
7026
7027 const Decl *D = cxcursor::getCursorDecl(cursor);
7028 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
7029 switch (ND->getVisibility()) {
7030 case HiddenVisibility: return CXVisibility_Hidden;
7031 case ProtectedVisibility: return CXVisibility_Protected;
7032 case DefaultVisibility: return CXVisibility_Default;
7033 };
7034
7035 return CXVisibility_Invalid;
7036}
Ehsan Akhgarib743de72016-05-31 15:55:51 +00007037
7038//===----------------------------------------------------------------------===//
Guy Benyei11169dd2012-12-18 14:30:41 +00007039// Operations for querying language of a cursor.
7040//===----------------------------------------------------------------------===//
7041
7042static CXLanguageKind getDeclLanguage(const Decl *D) {
7043 if (!D)
7044 return CXLanguage_C;
7045
7046 switch (D->getKind()) {
7047 default:
7048 break;
7049 case Decl::ImplicitParam:
7050 case Decl::ObjCAtDefsField:
7051 case Decl::ObjCCategory:
7052 case Decl::ObjCCategoryImpl:
7053 case Decl::ObjCCompatibleAlias:
7054 case Decl::ObjCImplementation:
7055 case Decl::ObjCInterface:
7056 case Decl::ObjCIvar:
7057 case Decl::ObjCMethod:
7058 case Decl::ObjCProperty:
7059 case Decl::ObjCPropertyImpl:
7060 case Decl::ObjCProtocol:
Douglas Gregor85f3f952015-07-07 03:57:15 +00007061 case Decl::ObjCTypeParam:
Guy Benyei11169dd2012-12-18 14:30:41 +00007062 return CXLanguage_ObjC;
7063 case Decl::CXXConstructor:
7064 case Decl::CXXConversion:
7065 case Decl::CXXDestructor:
7066 case Decl::CXXMethod:
7067 case Decl::CXXRecord:
7068 case Decl::ClassTemplate:
7069 case Decl::ClassTemplatePartialSpecialization:
7070 case Decl::ClassTemplateSpecialization:
7071 case Decl::Friend:
7072 case Decl::FriendTemplate:
7073 case Decl::FunctionTemplate:
7074 case Decl::LinkageSpec:
7075 case Decl::Namespace:
7076 case Decl::NamespaceAlias:
7077 case Decl::NonTypeTemplateParm:
7078 case Decl::StaticAssert:
7079 case Decl::TemplateTemplateParm:
7080 case Decl::TemplateTypeParm:
7081 case Decl::UnresolvedUsingTypename:
7082 case Decl::UnresolvedUsingValue:
7083 case Decl::Using:
7084 case Decl::UsingDirective:
7085 case Decl::UsingShadow:
7086 return CXLanguage_CPlusPlus;
7087 }
7088
7089 return CXLanguage_C;
7090}
7091
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007092static CXAvailabilityKind getCursorAvailabilityForDecl(const Decl *D) {
7093 if (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted())
Manuel Klimek8e3a7ed2015-09-25 17:53:16 +00007094 return CXAvailability_NotAvailable;
Guy Benyei11169dd2012-12-18 14:30:41 +00007095
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007096 switch (D->getAvailability()) {
7097 case AR_Available:
7098 case AR_NotYetIntroduced:
7099 if (const EnumConstantDecl *EnumConst = dyn_cast<EnumConstantDecl>(D))
Benjamin Kramer656363d2013-10-15 18:53:18 +00007100 return getCursorAvailabilityForDecl(
7101 cast<Decl>(EnumConst->getDeclContext()));
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007102 return CXAvailability_Available;
7103
7104 case AR_Deprecated:
7105 return CXAvailability_Deprecated;
7106
7107 case AR_Unavailable:
7108 return CXAvailability_NotAvailable;
7109 }
Benjamin Kramer656363d2013-10-15 18:53:18 +00007110
7111 llvm_unreachable("Unknown availability kind!");
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007112}
7113
Guy Benyei11169dd2012-12-18 14:30:41 +00007114enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
7115 if (clang_isDeclaration(cursor.kind))
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007116 if (const Decl *D = cxcursor::getCursorDecl(cursor))
7117 return getCursorAvailabilityForDecl(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00007118
7119 return CXAvailability_Available;
7120}
7121
7122static CXVersion convertVersion(VersionTuple In) {
7123 CXVersion Out = { -1, -1, -1 };
7124 if (In.empty())
7125 return Out;
7126
7127 Out.Major = In.getMajor();
7128
NAKAMURA Takumic2b5d1f2013-02-21 02:32:34 +00007129 Optional<unsigned> Minor = In.getMinor();
7130 if (Minor.hasValue())
Guy Benyei11169dd2012-12-18 14:30:41 +00007131 Out.Minor = *Minor;
7132 else
7133 return Out;
7134
NAKAMURA Takumic2b5d1f2013-02-21 02:32:34 +00007135 Optional<unsigned> Subminor = In.getSubminor();
7136 if (Subminor.hasValue())
Guy Benyei11169dd2012-12-18 14:30:41 +00007137 Out.Subminor = *Subminor;
7138
7139 return Out;
7140}
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007141
7142static int getCursorPlatformAvailabilityForDecl(const Decl *D,
7143 int *always_deprecated,
7144 CXString *deprecated_message,
7145 int *always_unavailable,
7146 CXString *unavailable_message,
7147 CXPlatformAvailability *availability,
7148 int availability_size) {
7149 bool HadAvailAttr = false;
7150 int N = 0;
Aaron Ballmanb97112e2014-03-08 22:19:01 +00007151 for (auto A : D->attrs()) {
7152 if (DeprecatedAttr *Deprecated = dyn_cast<DeprecatedAttr>(A)) {
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007153 HadAvailAttr = true;
7154 if (always_deprecated)
7155 *always_deprecated = 1;
Nico Weberaacf0312014-04-24 05:16:45 +00007156 if (deprecated_message) {
Argyrios Kyrtzidisedfe07f2014-04-24 06:05:40 +00007157 clang_disposeString(*deprecated_message);
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007158 *deprecated_message = cxstring::createDup(Deprecated->getMessage());
Nico Weberaacf0312014-04-24 05:16:45 +00007159 }
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007160 continue;
7161 }
7162
Aaron Ballmanb97112e2014-03-08 22:19:01 +00007163 if (UnavailableAttr *Unavailable = dyn_cast<UnavailableAttr>(A)) {
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007164 HadAvailAttr = true;
7165 if (always_unavailable)
7166 *always_unavailable = 1;
7167 if (unavailable_message) {
Argyrios Kyrtzidisedfe07f2014-04-24 06:05:40 +00007168 clang_disposeString(*unavailable_message);
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007169 *unavailable_message = cxstring::createDup(Unavailable->getMessage());
7170 }
7171 continue;
7172 }
7173
Aaron Ballmanb97112e2014-03-08 22:19:01 +00007174 if (AvailabilityAttr *Avail = dyn_cast<AvailabilityAttr>(A)) {
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007175 HadAvailAttr = true;
7176 if (N < availability_size) {
7177 availability[N].Platform
7178 = cxstring::createDup(Avail->getPlatform()->getName());
7179 availability[N].Introduced = convertVersion(Avail->getIntroduced());
7180 availability[N].Deprecated = convertVersion(Avail->getDeprecated());
7181 availability[N].Obsoleted = convertVersion(Avail->getObsoleted());
7182 availability[N].Unavailable = Avail->getUnavailable();
7183 availability[N].Message = cxstring::createDup(Avail->getMessage());
7184 }
7185 ++N;
7186 }
7187 }
7188
7189 if (!HadAvailAttr)
7190 if (const EnumConstantDecl *EnumConst = dyn_cast<EnumConstantDecl>(D))
7191 return getCursorPlatformAvailabilityForDecl(
7192 cast<Decl>(EnumConst->getDeclContext()),
7193 always_deprecated,
7194 deprecated_message,
7195 always_unavailable,
7196 unavailable_message,
7197 availability,
7198 availability_size);
Guy Benyei11169dd2012-12-18 14:30:41 +00007199
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007200 return N;
7201}
7202
Guy Benyei11169dd2012-12-18 14:30:41 +00007203int clang_getCursorPlatformAvailability(CXCursor cursor,
7204 int *always_deprecated,
7205 CXString *deprecated_message,
7206 int *always_unavailable,
7207 CXString *unavailable_message,
7208 CXPlatformAvailability *availability,
7209 int availability_size) {
7210 if (always_deprecated)
7211 *always_deprecated = 0;
7212 if (deprecated_message)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00007213 *deprecated_message = cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00007214 if (always_unavailable)
7215 *always_unavailable = 0;
7216 if (unavailable_message)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00007217 *unavailable_message = cxstring::createEmpty();
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007218
Guy Benyei11169dd2012-12-18 14:30:41 +00007219 if (!clang_isDeclaration(cursor.kind))
7220 return 0;
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007221
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007222 const Decl *D = cxcursor::getCursorDecl(cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00007223 if (!D)
7224 return 0;
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007225
7226 return getCursorPlatformAvailabilityForDecl(D, always_deprecated,
7227 deprecated_message,
7228 always_unavailable,
7229 unavailable_message,
7230 availability,
7231 availability_size);
Guy Benyei11169dd2012-12-18 14:30:41 +00007232}
7233
7234void clang_disposeCXPlatformAvailability(CXPlatformAvailability *availability) {
7235 clang_disposeString(availability->Platform);
7236 clang_disposeString(availability->Message);
7237}
7238
7239CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
7240 if (clang_isDeclaration(cursor.kind))
7241 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
7242
7243 return CXLanguage_Invalid;
7244}
7245
7246 /// \brief If the given cursor is the "templated" declaration
7247 /// descibing a class or function template, return the class or
7248 /// function template.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007249static const Decl *maybeGetTemplateCursor(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007250 if (!D)
Craig Topper69186e72014-06-08 08:38:04 +00007251 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007252
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007253 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00007254 if (FunctionTemplateDecl *FunTmpl = FD->getDescribedFunctionTemplate())
7255 return FunTmpl;
7256
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007257 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00007258 if (ClassTemplateDecl *ClassTmpl = RD->getDescribedClassTemplate())
7259 return ClassTmpl;
7260
7261 return D;
7262}
7263
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00007264
7265enum CX_StorageClass clang_Cursor_getStorageClass(CXCursor C) {
7266 StorageClass sc = SC_None;
7267 const Decl *D = getCursorDecl(C);
7268 if (D) {
7269 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7270 sc = FD->getStorageClass();
7271 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7272 sc = VD->getStorageClass();
7273 } else {
7274 return CX_SC_Invalid;
7275 }
7276 } else {
7277 return CX_SC_Invalid;
7278 }
7279 switch (sc) {
7280 case SC_None:
7281 return CX_SC_None;
7282 case SC_Extern:
7283 return CX_SC_Extern;
7284 case SC_Static:
7285 return CX_SC_Static;
7286 case SC_PrivateExtern:
7287 return CX_SC_PrivateExtern;
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00007288 case SC_Auto:
7289 return CX_SC_Auto;
7290 case SC_Register:
7291 return CX_SC_Register;
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00007292 }
Kaelyn Takataab61e702014-10-15 18:03:26 +00007293 llvm_unreachable("Unhandled storage class!");
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00007294}
7295
Guy Benyei11169dd2012-12-18 14:30:41 +00007296CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
7297 if (clang_isDeclaration(cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007298 if (const Decl *D = getCursorDecl(cursor)) {
7299 const DeclContext *DC = D->getDeclContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00007300 if (!DC)
7301 return clang_getNullCursor();
7302
7303 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
7304 getCursorTU(cursor));
7305 }
7306 }
7307
7308 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007309 if (const Decl *D = getCursorDecl(cursor))
Guy Benyei11169dd2012-12-18 14:30:41 +00007310 return MakeCXCursor(D, getCursorTU(cursor));
7311 }
7312
7313 return clang_getNullCursor();
7314}
7315
7316CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
7317 if (clang_isDeclaration(cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007318 if (const Decl *D = getCursorDecl(cursor)) {
7319 const DeclContext *DC = D->getLexicalDeclContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00007320 if (!DC)
7321 return clang_getNullCursor();
7322
7323 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
7324 getCursorTU(cursor));
7325 }
7326 }
7327
7328 // FIXME: Note that we can't easily compute the lexical context of a
7329 // statement or expression, so we return nothing.
7330 return clang_getNullCursor();
7331}
7332
7333CXFile clang_getIncludedFile(CXCursor cursor) {
7334 if (cursor.kind != CXCursor_InclusionDirective)
Craig Topper69186e72014-06-08 08:38:04 +00007335 return nullptr;
7336
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00007337 const InclusionDirective *ID = getCursorInclusionDirective(cursor);
Dmitri Gribenkof9304482013-01-23 15:56:07 +00007338 return const_cast<FileEntry *>(ID->getFile());
Guy Benyei11169dd2012-12-18 14:30:41 +00007339}
7340
Argyrios Kyrtzidis9adfd8a2013-04-18 22:15:49 +00007341unsigned clang_Cursor_getObjCPropertyAttributes(CXCursor C, unsigned reserved) {
7342 if (C.kind != CXCursor_ObjCPropertyDecl)
7343 return CXObjCPropertyAttr_noattr;
7344
7345 unsigned Result = CXObjCPropertyAttr_noattr;
7346 const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(getCursorDecl(C));
7347 ObjCPropertyDecl::PropertyAttributeKind Attr =
7348 PD->getPropertyAttributesAsWritten();
7349
7350#define SET_CXOBJCPROP_ATTR(A) \
7351 if (Attr & ObjCPropertyDecl::OBJC_PR_##A) \
7352 Result |= CXObjCPropertyAttr_##A
7353 SET_CXOBJCPROP_ATTR(readonly);
7354 SET_CXOBJCPROP_ATTR(getter);
7355 SET_CXOBJCPROP_ATTR(assign);
7356 SET_CXOBJCPROP_ATTR(readwrite);
7357 SET_CXOBJCPROP_ATTR(retain);
7358 SET_CXOBJCPROP_ATTR(copy);
7359 SET_CXOBJCPROP_ATTR(nonatomic);
7360 SET_CXOBJCPROP_ATTR(setter);
7361 SET_CXOBJCPROP_ATTR(atomic);
7362 SET_CXOBJCPROP_ATTR(weak);
7363 SET_CXOBJCPROP_ATTR(strong);
7364 SET_CXOBJCPROP_ATTR(unsafe_unretained);
Manman Ren04fd4d82016-05-31 23:22:04 +00007365 SET_CXOBJCPROP_ATTR(class);
Argyrios Kyrtzidis9adfd8a2013-04-18 22:15:49 +00007366#undef SET_CXOBJCPROP_ATTR
7367
7368 return Result;
7369}
7370
Argyrios Kyrtzidis9d9bc012013-04-18 23:29:12 +00007371unsigned clang_Cursor_getObjCDeclQualifiers(CXCursor C) {
7372 if (!clang_isDeclaration(C.kind))
7373 return CXObjCDeclQualifier_None;
7374
7375 Decl::ObjCDeclQualifier QT = Decl::OBJC_TQ_None;
7376 const Decl *D = getCursorDecl(C);
7377 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
7378 QT = MD->getObjCDeclQualifier();
7379 else if (const ParmVarDecl *PD = dyn_cast<ParmVarDecl>(D))
7380 QT = PD->getObjCDeclQualifier();
7381 if (QT == Decl::OBJC_TQ_None)
7382 return CXObjCDeclQualifier_None;
7383
7384 unsigned Result = CXObjCDeclQualifier_None;
7385 if (QT & Decl::OBJC_TQ_In) Result |= CXObjCDeclQualifier_In;
7386 if (QT & Decl::OBJC_TQ_Inout) Result |= CXObjCDeclQualifier_Inout;
7387 if (QT & Decl::OBJC_TQ_Out) Result |= CXObjCDeclQualifier_Out;
7388 if (QT & Decl::OBJC_TQ_Bycopy) Result |= CXObjCDeclQualifier_Bycopy;
7389 if (QT & Decl::OBJC_TQ_Byref) Result |= CXObjCDeclQualifier_Byref;
7390 if (QT & Decl::OBJC_TQ_Oneway) Result |= CXObjCDeclQualifier_Oneway;
7391
7392 return Result;
7393}
7394
Argyrios Kyrtzidis7b50fc52013-07-05 20:44:37 +00007395unsigned clang_Cursor_isObjCOptional(CXCursor C) {
7396 if (!clang_isDeclaration(C.kind))
7397 return 0;
7398
7399 const Decl *D = getCursorDecl(C);
7400 if (const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D))
7401 return PD->getPropertyImplementation() == ObjCPropertyDecl::Optional;
7402 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
7403 return MD->getImplementationControl() == ObjCMethodDecl::Optional;
7404
7405 return 0;
7406}
7407
Argyrios Kyrtzidis23814e42013-04-18 23:53:05 +00007408unsigned clang_Cursor_isVariadic(CXCursor C) {
7409 if (!clang_isDeclaration(C.kind))
7410 return 0;
7411
7412 const Decl *D = getCursorDecl(C);
7413 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
7414 return FD->isVariadic();
7415 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
7416 return MD->isVariadic();
7417
7418 return 0;
7419}
7420
Guy Benyei11169dd2012-12-18 14:30:41 +00007421CXSourceRange clang_Cursor_getCommentRange(CXCursor C) {
7422 if (!clang_isDeclaration(C.kind))
7423 return clang_getNullRange();
7424
7425 const Decl *D = getCursorDecl(C);
7426 ASTContext &Context = getCursorContext(C);
7427 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
7428 if (!RC)
7429 return clang_getNullRange();
7430
7431 return cxloc::translateSourceRange(Context, RC->getSourceRange());
7432}
7433
7434CXString clang_Cursor_getRawCommentText(CXCursor C) {
7435 if (!clang_isDeclaration(C.kind))
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00007436 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00007437
7438 const Decl *D = getCursorDecl(C);
7439 ASTContext &Context = getCursorContext(C);
7440 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
7441 StringRef RawText = RC ? RC->getRawText(Context.getSourceManager()) :
7442 StringRef();
7443
7444 // Don't duplicate the string because RawText points directly into source
7445 // code.
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00007446 return cxstring::createRef(RawText);
Guy Benyei11169dd2012-12-18 14:30:41 +00007447}
7448
7449CXString clang_Cursor_getBriefCommentText(CXCursor C) {
7450 if (!clang_isDeclaration(C.kind))
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00007451 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00007452
7453 const Decl *D = getCursorDecl(C);
7454 const ASTContext &Context = getCursorContext(C);
7455 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
7456
7457 if (RC) {
7458 StringRef BriefText = RC->getBriefText(Context);
7459
7460 // Don't duplicate the string because RawComment ensures that this memory
7461 // will not go away.
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00007462 return cxstring::createRef(BriefText);
Guy Benyei11169dd2012-12-18 14:30:41 +00007463 }
7464
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00007465 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00007466}
7467
Guy Benyei11169dd2012-12-18 14:30:41 +00007468CXModule clang_Cursor_getModule(CXCursor C) {
7469 if (C.kind == CXCursor_ModuleImportDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007470 if (const ImportDecl *ImportD =
7471 dyn_cast_or_null<ImportDecl>(getCursorDecl(C)))
Guy Benyei11169dd2012-12-18 14:30:41 +00007472 return ImportD->getImportedModule();
7473 }
7474
Craig Topper69186e72014-06-08 08:38:04 +00007475 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007476}
7477
Argyrios Kyrtzidisf6d49c32014-05-14 23:14:37 +00007478CXModule clang_getModuleForFile(CXTranslationUnit TU, CXFile File) {
7479 if (isNotUsableTU(TU)) {
7480 LOG_BAD_TU(TU);
7481 return nullptr;
7482 }
7483 if (!File)
7484 return nullptr;
7485 FileEntry *FE = static_cast<FileEntry *>(File);
7486
7487 ASTUnit &Unit = *cxtu::getASTUnit(TU);
7488 HeaderSearch &HS = Unit.getPreprocessor().getHeaderSearchInfo();
7489 ModuleMap::KnownHeader Header = HS.findModuleForHeader(FE);
7490
Richard Smithfeb54b62014-10-23 02:01:19 +00007491 return Header.getModule();
Argyrios Kyrtzidisf6d49c32014-05-14 23:14:37 +00007492}
7493
Argyrios Kyrtzidis12fdb9e2013-04-26 22:47:49 +00007494CXFile clang_Module_getASTFile(CXModule CXMod) {
7495 if (!CXMod)
Craig Topper69186e72014-06-08 08:38:04 +00007496 return nullptr;
Argyrios Kyrtzidis12fdb9e2013-04-26 22:47:49 +00007497 Module *Mod = static_cast<Module*>(CXMod);
7498 return const_cast<FileEntry *>(Mod->getASTFile());
7499}
7500
Guy Benyei11169dd2012-12-18 14:30:41 +00007501CXModule clang_Module_getParent(CXModule CXMod) {
7502 if (!CXMod)
Craig Topper69186e72014-06-08 08:38:04 +00007503 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007504 Module *Mod = static_cast<Module*>(CXMod);
7505 return Mod->Parent;
7506}
7507
7508CXString clang_Module_getName(CXModule CXMod) {
7509 if (!CXMod)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00007510 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00007511 Module *Mod = static_cast<Module*>(CXMod);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00007512 return cxstring::createDup(Mod->Name);
Guy Benyei11169dd2012-12-18 14:30:41 +00007513}
7514
7515CXString clang_Module_getFullName(CXModule CXMod) {
7516 if (!CXMod)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00007517 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00007518 Module *Mod = static_cast<Module*>(CXMod);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00007519 return cxstring::createDup(Mod->getFullModuleName());
Guy Benyei11169dd2012-12-18 14:30:41 +00007520}
7521
Argyrios Kyrtzidis884337f2014-05-15 04:44:25 +00007522int clang_Module_isSystem(CXModule CXMod) {
7523 if (!CXMod)
7524 return 0;
7525 Module *Mod = static_cast<Module*>(CXMod);
7526 return Mod->IsSystem;
7527}
7528
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00007529unsigned clang_Module_getNumTopLevelHeaders(CXTranslationUnit TU,
7530 CXModule CXMod) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00007531 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00007532 LOG_BAD_TU(TU);
7533 return 0;
7534 }
7535 if (!CXMod)
Guy Benyei11169dd2012-12-18 14:30:41 +00007536 return 0;
7537 Module *Mod = static_cast<Module*>(CXMod);
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00007538 FileManager &FileMgr = cxtu::getASTUnit(TU)->getFileManager();
7539 ArrayRef<const FileEntry *> TopHeaders = Mod->getTopHeaders(FileMgr);
7540 return TopHeaders.size();
Guy Benyei11169dd2012-12-18 14:30:41 +00007541}
7542
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00007543CXFile clang_Module_getTopLevelHeader(CXTranslationUnit TU,
7544 CXModule CXMod, unsigned Index) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00007545 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00007546 LOG_BAD_TU(TU);
Craig Topper69186e72014-06-08 08:38:04 +00007547 return nullptr;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00007548 }
7549 if (!CXMod)
Craig Topper69186e72014-06-08 08:38:04 +00007550 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007551 Module *Mod = static_cast<Module*>(CXMod);
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00007552 FileManager &FileMgr = cxtu::getASTUnit(TU)->getFileManager();
Guy Benyei11169dd2012-12-18 14:30:41 +00007553
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00007554 ArrayRef<const FileEntry *> TopHeaders = Mod->getTopHeaders(FileMgr);
7555 if (Index < TopHeaders.size())
7556 return const_cast<FileEntry *>(TopHeaders[Index]);
Guy Benyei11169dd2012-12-18 14:30:41 +00007557
Craig Topper69186e72014-06-08 08:38:04 +00007558 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007559}
7560
Guy Benyei11169dd2012-12-18 14:30:41 +00007561//===----------------------------------------------------------------------===//
7562// C++ AST instrospection.
7563//===----------------------------------------------------------------------===//
7564
Jonathan Coe29565352016-04-27 12:48:25 +00007565unsigned clang_CXXConstructor_isDefaultConstructor(CXCursor C) {
7566 if (!clang_isDeclaration(C.kind))
7567 return 0;
7568
7569 const Decl *D = cxcursor::getCursorDecl(C);
7570 const CXXConstructorDecl *Constructor =
7571 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
7572 return (Constructor && Constructor->isDefaultConstructor()) ? 1 : 0;
7573}
7574
7575unsigned clang_CXXConstructor_isCopyConstructor(CXCursor C) {
7576 if (!clang_isDeclaration(C.kind))
7577 return 0;
7578
7579 const Decl *D = cxcursor::getCursorDecl(C);
7580 const CXXConstructorDecl *Constructor =
7581 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
7582 return (Constructor && Constructor->isCopyConstructor()) ? 1 : 0;
7583}
7584
7585unsigned clang_CXXConstructor_isMoveConstructor(CXCursor C) {
7586 if (!clang_isDeclaration(C.kind))
7587 return 0;
7588
7589 const Decl *D = cxcursor::getCursorDecl(C);
7590 const CXXConstructorDecl *Constructor =
7591 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
7592 return (Constructor && Constructor->isMoveConstructor()) ? 1 : 0;
7593}
7594
7595unsigned clang_CXXConstructor_isConvertingConstructor(CXCursor C) {
7596 if (!clang_isDeclaration(C.kind))
7597 return 0;
7598
7599 const Decl *D = cxcursor::getCursorDecl(C);
7600 const CXXConstructorDecl *Constructor =
7601 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
7602 // Passing 'false' excludes constructors marked 'explicit'.
7603 return (Constructor && Constructor->isConvertingConstructor(false)) ? 1 : 0;
7604}
7605
Saleem Abdulrasool6ea75db2015-10-27 15:50:22 +00007606unsigned clang_CXXField_isMutable(CXCursor C) {
7607 if (!clang_isDeclaration(C.kind))
7608 return 0;
7609
7610 if (const auto D = cxcursor::getCursorDecl(C))
7611 if (const auto FD = dyn_cast_or_null<FieldDecl>(D))
7612 return FD->isMutable() ? 1 : 0;
7613 return 0;
7614}
7615
Dmitri Gribenko62770be2013-05-17 18:38:35 +00007616unsigned clang_CXXMethod_isPureVirtual(CXCursor C) {
7617 if (!clang_isDeclaration(C.kind))
7618 return 0;
7619
Dmitri Gribenko62770be2013-05-17 18:38:35 +00007620 const Decl *D = cxcursor::getCursorDecl(C);
Alp Tokera2794f92014-01-22 07:29:52 +00007621 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00007622 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Dmitri Gribenko62770be2013-05-17 18:38:35 +00007623 return (Method && Method->isVirtual() && Method->isPure()) ? 1 : 0;
7624}
7625
Dmitri Gribenkoe570ede2014-04-07 14:59:13 +00007626unsigned clang_CXXMethod_isConst(CXCursor C) {
7627 if (!clang_isDeclaration(C.kind))
7628 return 0;
7629
7630 const Decl *D = cxcursor::getCursorDecl(C);
7631 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00007632 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Dmitri Gribenkoe570ede2014-04-07 14:59:13 +00007633 return (Method && (Method->getTypeQualifiers() & Qualifiers::Const)) ? 1 : 0;
7634}
7635
Jonathan Coe29565352016-04-27 12:48:25 +00007636unsigned clang_CXXMethod_isDefaulted(CXCursor C) {
7637 if (!clang_isDeclaration(C.kind))
7638 return 0;
7639
7640 const Decl *D = cxcursor::getCursorDecl(C);
7641 const CXXMethodDecl *Method =
7642 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
7643 return (Method && Method->isDefaulted()) ? 1 : 0;
7644}
7645
Guy Benyei11169dd2012-12-18 14:30:41 +00007646unsigned clang_CXXMethod_isStatic(CXCursor C) {
7647 if (!clang_isDeclaration(C.kind))
7648 return 0;
7649
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007650 const Decl *D = cxcursor::getCursorDecl(C);
Alp Tokera2794f92014-01-22 07:29:52 +00007651 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00007652 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007653 return (Method && Method->isStatic()) ? 1 : 0;
7654}
7655
7656unsigned clang_CXXMethod_isVirtual(CXCursor C) {
7657 if (!clang_isDeclaration(C.kind))
7658 return 0;
7659
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007660 const Decl *D = cxcursor::getCursorDecl(C);
Alp Tokera2794f92014-01-22 07:29:52 +00007661 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00007662 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007663 return (Method && Method->isVirtual()) ? 1 : 0;
7664}
Guy Benyei11169dd2012-12-18 14:30:41 +00007665
7666//===----------------------------------------------------------------------===//
7667// Attribute introspection.
7668//===----------------------------------------------------------------------===//
7669
Guy Benyei11169dd2012-12-18 14:30:41 +00007670CXType clang_getIBOutletCollectionType(CXCursor C) {
7671 if (C.kind != CXCursor_IBOutletCollectionAttr)
7672 return cxtype::MakeCXType(QualType(), cxcursor::getCursorTU(C));
7673
Dmitri Gribenkoe4baea62013-01-26 18:08:08 +00007674 const IBOutletCollectionAttr *A =
Guy Benyei11169dd2012-12-18 14:30:41 +00007675 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
7676
7677 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorTU(C));
7678}
Guy Benyei11169dd2012-12-18 14:30:41 +00007679
7680//===----------------------------------------------------------------------===//
7681// Inspecting memory usage.
7682//===----------------------------------------------------------------------===//
7683
7684typedef std::vector<CXTUResourceUsageEntry> MemUsageEntries;
7685
7686static inline void createCXTUResourceUsageEntry(MemUsageEntries &entries,
7687 enum CXTUResourceUsageKind k,
7688 unsigned long amount) {
7689 CXTUResourceUsageEntry entry = { k, amount };
7690 entries.push_back(entry);
7691}
7692
Guy Benyei11169dd2012-12-18 14:30:41 +00007693const char *clang_getTUResourceUsageName(CXTUResourceUsageKind kind) {
7694 const char *str = "";
7695 switch (kind) {
7696 case CXTUResourceUsage_AST:
7697 str = "ASTContext: expressions, declarations, and types";
7698 break;
7699 case CXTUResourceUsage_Identifiers:
7700 str = "ASTContext: identifiers";
7701 break;
7702 case CXTUResourceUsage_Selectors:
7703 str = "ASTContext: selectors";
7704 break;
7705 case CXTUResourceUsage_GlobalCompletionResults:
7706 str = "Code completion: cached global results";
7707 break;
7708 case CXTUResourceUsage_SourceManagerContentCache:
7709 str = "SourceManager: content cache allocator";
7710 break;
7711 case CXTUResourceUsage_AST_SideTables:
7712 str = "ASTContext: side tables";
7713 break;
7714 case CXTUResourceUsage_SourceManager_Membuffer_Malloc:
7715 str = "SourceManager: malloc'ed memory buffers";
7716 break;
7717 case CXTUResourceUsage_SourceManager_Membuffer_MMap:
7718 str = "SourceManager: mmap'ed memory buffers";
7719 break;
7720 case CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc:
7721 str = "ExternalASTSource: malloc'ed memory buffers";
7722 break;
7723 case CXTUResourceUsage_ExternalASTSource_Membuffer_MMap:
7724 str = "ExternalASTSource: mmap'ed memory buffers";
7725 break;
7726 case CXTUResourceUsage_Preprocessor:
7727 str = "Preprocessor: malloc'ed memory";
7728 break;
7729 case CXTUResourceUsage_PreprocessingRecord:
7730 str = "Preprocessor: PreprocessingRecord";
7731 break;
7732 case CXTUResourceUsage_SourceManager_DataStructures:
7733 str = "SourceManager: data structures and tables";
7734 break;
7735 case CXTUResourceUsage_Preprocessor_HeaderSearch:
7736 str = "Preprocessor: header search tables";
7737 break;
7738 }
7739 return str;
7740}
7741
7742CXTUResourceUsage clang_getCXTUResourceUsage(CXTranslationUnit TU) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00007743 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00007744 LOG_BAD_TU(TU);
Craig Topper69186e72014-06-08 08:38:04 +00007745 CXTUResourceUsage usage = { (void*) nullptr, 0, nullptr };
Guy Benyei11169dd2012-12-18 14:30:41 +00007746 return usage;
7747 }
7748
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00007749 ASTUnit *astUnit = cxtu::getASTUnit(TU);
Ahmed Charlesb8984322014-03-07 20:03:18 +00007750 std::unique_ptr<MemUsageEntries> entries(new MemUsageEntries());
Guy Benyei11169dd2012-12-18 14:30:41 +00007751 ASTContext &astContext = astUnit->getASTContext();
7752
7753 // How much memory is used by AST nodes and types?
7754 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST,
7755 (unsigned long) astContext.getASTAllocatedMemory());
7756
7757 // How much memory is used by identifiers?
7758 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Identifiers,
7759 (unsigned long) astContext.Idents.getAllocator().getTotalMemory());
7760
7761 // How much memory is used for selectors?
7762 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Selectors,
7763 (unsigned long) astContext.Selectors.getTotalMemory());
7764
7765 // How much memory is used by ASTContext's side tables?
7766 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST_SideTables,
7767 (unsigned long) astContext.getSideTableAllocatedMemory());
7768
7769 // How much memory is used for caching global code completion results?
7770 unsigned long completionBytes = 0;
7771 if (GlobalCodeCompletionAllocator *completionAllocator =
Alp Tokerf994cef2014-07-05 03:08:06 +00007772 astUnit->getCachedCompletionAllocator().get()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007773 completionBytes = completionAllocator->getTotalMemory();
7774 }
7775 createCXTUResourceUsageEntry(*entries,
7776 CXTUResourceUsage_GlobalCompletionResults,
7777 completionBytes);
7778
7779 // How much memory is being used by SourceManager's content cache?
7780 createCXTUResourceUsageEntry(*entries,
7781 CXTUResourceUsage_SourceManagerContentCache,
7782 (unsigned long) astContext.getSourceManager().getContentCacheSize());
7783
7784 // How much memory is being used by the MemoryBuffer's in SourceManager?
7785 const SourceManager::MemoryBufferSizes &srcBufs =
7786 astUnit->getSourceManager().getMemoryBufferSizes();
7787
7788 createCXTUResourceUsageEntry(*entries,
7789 CXTUResourceUsage_SourceManager_Membuffer_Malloc,
7790 (unsigned long) srcBufs.malloc_bytes);
7791 createCXTUResourceUsageEntry(*entries,
7792 CXTUResourceUsage_SourceManager_Membuffer_MMap,
7793 (unsigned long) srcBufs.mmap_bytes);
7794 createCXTUResourceUsageEntry(*entries,
7795 CXTUResourceUsage_SourceManager_DataStructures,
7796 (unsigned long) astContext.getSourceManager()
7797 .getDataStructureSizes());
7798
7799 // How much memory is being used by the ExternalASTSource?
7800 if (ExternalASTSource *esrc = astContext.getExternalSource()) {
7801 const ExternalASTSource::MemoryBufferSizes &sizes =
7802 esrc->getMemoryBufferSizes();
7803
7804 createCXTUResourceUsageEntry(*entries,
7805 CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc,
7806 (unsigned long) sizes.malloc_bytes);
7807 createCXTUResourceUsageEntry(*entries,
7808 CXTUResourceUsage_ExternalASTSource_Membuffer_MMap,
7809 (unsigned long) sizes.mmap_bytes);
7810 }
7811
7812 // How much memory is being used by the Preprocessor?
7813 Preprocessor &pp = astUnit->getPreprocessor();
7814 createCXTUResourceUsageEntry(*entries,
7815 CXTUResourceUsage_Preprocessor,
7816 pp.getTotalMemory());
7817
7818 if (PreprocessingRecord *pRec = pp.getPreprocessingRecord()) {
7819 createCXTUResourceUsageEntry(*entries,
7820 CXTUResourceUsage_PreprocessingRecord,
7821 pRec->getTotalMemory());
7822 }
7823
7824 createCXTUResourceUsageEntry(*entries,
7825 CXTUResourceUsage_Preprocessor_HeaderSearch,
7826 pp.getHeaderSearchInfo().getTotalMemory());
Craig Topper69186e72014-06-08 08:38:04 +00007827
Guy Benyei11169dd2012-12-18 14:30:41 +00007828 CXTUResourceUsage usage = { (void*) entries.get(),
7829 (unsigned) entries->size(),
Alexander Kornienko6ee521c2015-01-23 15:36:10 +00007830 !entries->empty() ? &(*entries)[0] : nullptr };
Eric Fiseliere95fc442016-11-14 07:03:50 +00007831 (void)entries.release();
Guy Benyei11169dd2012-12-18 14:30:41 +00007832 return usage;
7833}
7834
7835void clang_disposeCXTUResourceUsage(CXTUResourceUsage usage) {
7836 if (usage.data)
7837 delete (MemUsageEntries*) usage.data;
7838}
7839
Argyrios Kyrtzidis0e282ef2013-12-06 18:55:45 +00007840CXSourceRangeList *clang_getSkippedRanges(CXTranslationUnit TU, CXFile file) {
7841 CXSourceRangeList *skipped = new CXSourceRangeList;
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00007842 skipped->count = 0;
Craig Topper69186e72014-06-08 08:38:04 +00007843 skipped->ranges = nullptr;
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00007844
Dmitri Gribenko852d6222014-02-11 15:02:48 +00007845 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00007846 LOG_BAD_TU(TU);
7847 return skipped;
7848 }
7849
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00007850 if (!file)
7851 return skipped;
7852
7853 ASTUnit *astUnit = cxtu::getASTUnit(TU);
7854 PreprocessingRecord *ppRec = astUnit->getPreprocessor().getPreprocessingRecord();
7855 if (!ppRec)
7856 return skipped;
7857
7858 ASTContext &Ctx = astUnit->getASTContext();
7859 SourceManager &sm = Ctx.getSourceManager();
7860 FileEntry *fileEntry = static_cast<FileEntry *>(file);
7861 FileID wantedFileID = sm.translateFile(fileEntry);
7862
7863 const std::vector<SourceRange> &SkippedRanges = ppRec->getSkippedRanges();
7864 std::vector<SourceRange> wantedRanges;
7865 for (std::vector<SourceRange>::const_iterator i = SkippedRanges.begin(), ei = SkippedRanges.end();
7866 i != ei; ++i) {
7867 if (sm.getFileID(i->getBegin()) == wantedFileID || sm.getFileID(i->getEnd()) == wantedFileID)
7868 wantedRanges.push_back(*i);
7869 }
7870
7871 skipped->count = wantedRanges.size();
7872 skipped->ranges = new CXSourceRange[skipped->count];
7873 for (unsigned i = 0, ei = skipped->count; i != ei; ++i)
7874 skipped->ranges[i] = cxloc::translateSourceRange(Ctx, wantedRanges[i]);
7875
7876 return skipped;
7877}
7878
Cameron Desrochersd8091282016-08-18 15:43:55 +00007879CXSourceRangeList *clang_getAllSkippedRanges(CXTranslationUnit TU) {
7880 CXSourceRangeList *skipped = new CXSourceRangeList;
7881 skipped->count = 0;
7882 skipped->ranges = nullptr;
7883
7884 if (isNotUsableTU(TU)) {
7885 LOG_BAD_TU(TU);
7886 return skipped;
7887 }
7888
7889 ASTUnit *astUnit = cxtu::getASTUnit(TU);
7890 PreprocessingRecord *ppRec = astUnit->getPreprocessor().getPreprocessingRecord();
7891 if (!ppRec)
7892 return skipped;
7893
7894 ASTContext &Ctx = astUnit->getASTContext();
7895
7896 const std::vector<SourceRange> &SkippedRanges = ppRec->getSkippedRanges();
7897
7898 skipped->count = SkippedRanges.size();
7899 skipped->ranges = new CXSourceRange[skipped->count];
7900 for (unsigned i = 0, ei = skipped->count; i != ei; ++i)
7901 skipped->ranges[i] = cxloc::translateSourceRange(Ctx, SkippedRanges[i]);
7902
7903 return skipped;
7904}
7905
Argyrios Kyrtzidis0e282ef2013-12-06 18:55:45 +00007906void clang_disposeSourceRangeList(CXSourceRangeList *ranges) {
7907 if (ranges) {
7908 delete[] ranges->ranges;
7909 delete ranges;
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00007910 }
7911}
7912
Guy Benyei11169dd2012-12-18 14:30:41 +00007913void clang::PrintLibclangResourceUsage(CXTranslationUnit TU) {
7914 CXTUResourceUsage Usage = clang_getCXTUResourceUsage(TU);
7915 for (unsigned I = 0; I != Usage.numEntries; ++I)
7916 fprintf(stderr, " %s: %lu\n",
7917 clang_getTUResourceUsageName(Usage.entries[I].kind),
7918 Usage.entries[I].amount);
7919
7920 clang_disposeCXTUResourceUsage(Usage);
7921}
7922
7923//===----------------------------------------------------------------------===//
7924// Misc. utility functions.
7925//===----------------------------------------------------------------------===//
7926
7927/// Default to using an 8 MB stack size on "safety" threads.
7928static unsigned SafetyStackThreadSize = 8 << 20;
7929
7930namespace clang {
7931
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00007932bool RunSafely(llvm::CrashRecoveryContext &CRC, llvm::function_ref<void()> Fn,
Guy Benyei11169dd2012-12-18 14:30:41 +00007933 unsigned Size) {
7934 if (!Size)
7935 Size = GetSafetyThreadStackSize();
7936 if (Size)
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00007937 return CRC.RunSafelyOnThread(Fn, Size);
7938 return CRC.RunSafely(Fn);
Guy Benyei11169dd2012-12-18 14:30:41 +00007939}
7940
7941unsigned GetSafetyThreadStackSize() {
7942 return SafetyStackThreadSize;
7943}
7944
7945void SetSafetyThreadStackSize(unsigned Value) {
7946 SafetyStackThreadSize = Value;
7947}
7948
Alexander Kornienkoab9db512015-06-22 23:07:51 +00007949}
Guy Benyei11169dd2012-12-18 14:30:41 +00007950
7951void clang::setThreadBackgroundPriority() {
7952 if (getenv("LIBCLANG_BGPRIO_DISABLE"))
7953 return;
7954
Alp Toker1a86ad22014-07-06 06:24:00 +00007955#ifdef USE_DARWIN_THREADS
Guy Benyei11169dd2012-12-18 14:30:41 +00007956 setpriority(PRIO_DARWIN_THREAD, 0, PRIO_DARWIN_BG);
7957#endif
7958}
7959
7960void cxindex::printDiagsToStderr(ASTUnit *Unit) {
7961 if (!Unit)
7962 return;
7963
7964 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
7965 DEnd = Unit->stored_diag_end();
7966 D != DEnd; ++D) {
Ben Langmuir749323f2014-04-22 17:40:12 +00007967 CXStoredDiagnostic Diag(*D, Unit->getLangOpts());
Guy Benyei11169dd2012-12-18 14:30:41 +00007968 CXString Msg = clang_formatDiagnostic(&Diag,
7969 clang_defaultDiagnosticDisplayOptions());
7970 fprintf(stderr, "%s\n", clang_getCString(Msg));
7971 clang_disposeString(Msg);
7972 }
7973#ifdef LLVM_ON_WIN32
7974 // On Windows, force a flush, since there may be multiple copies of
7975 // stderr and stdout in the file system, all with different buffers
7976 // but writing to the same device.
7977 fflush(stderr);
7978#endif
7979}
7980
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007981MacroInfo *cxindex::getMacroInfo(const IdentifierInfo &II,
7982 SourceLocation MacroDefLoc,
7983 CXTranslationUnit TU){
7984 if (MacroDefLoc.isInvalid() || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00007985 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007986 if (!II.hadMacroDefinition())
Craig Topper69186e72014-06-08 08:38:04 +00007987 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007988
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00007989 ASTUnit *Unit = cxtu::getASTUnit(TU);
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007990 Preprocessor &PP = Unit->getPreprocessor();
Richard Smith20e883e2015-04-29 23:20:19 +00007991 MacroDirective *MD = PP.getLocalMacroDirectiveHistory(&II);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00007992 if (MD) {
7993 for (MacroDirective::DefInfo
7994 Def = MD->getDefinition(); Def; Def = Def.getPreviousDefinition()) {
7995 if (MacroDefLoc == Def.getMacroInfo()->getDefinitionLoc())
7996 return Def.getMacroInfo();
7997 }
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007998 }
7999
Craig Topper69186e72014-06-08 08:38:04 +00008000 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008001}
8002
Richard Smith66a81862015-05-04 02:25:31 +00008003const MacroInfo *cxindex::getMacroInfo(const MacroDefinitionRecord *MacroDef,
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00008004 CXTranslationUnit TU) {
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008005 if (!MacroDef || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00008006 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008007 const IdentifierInfo *II = MacroDef->getName();
8008 if (!II)
Craig Topper69186e72014-06-08 08:38:04 +00008009 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008010
8011 return getMacroInfo(*II, MacroDef->getLocation(), TU);
8012}
8013
Richard Smith66a81862015-05-04 02:25:31 +00008014MacroDefinitionRecord *
8015cxindex::checkForMacroInMacroDefinition(const MacroInfo *MI, const Token &Tok,
8016 CXTranslationUnit TU) {
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008017 if (!MI || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00008018 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008019 if (Tok.isNot(tok::raw_identifier))
Craig Topper69186e72014-06-08 08:38:04 +00008020 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008021
8022 if (MI->getNumTokens() == 0)
Craig Topper69186e72014-06-08 08:38:04 +00008023 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008024 SourceRange DefRange(MI->getReplacementToken(0).getLocation(),
8025 MI->getDefinitionEndLoc());
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008026 ASTUnit *Unit = cxtu::getASTUnit(TU);
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008027
8028 // Check that the token is inside the definition and not its argument list.
8029 SourceManager &SM = Unit->getSourceManager();
8030 if (SM.isBeforeInTranslationUnit(Tok.getLocation(), DefRange.getBegin()))
Craig Topper69186e72014-06-08 08:38:04 +00008031 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008032 if (SM.isBeforeInTranslationUnit(DefRange.getEnd(), Tok.getLocation()))
Craig Topper69186e72014-06-08 08:38:04 +00008033 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008034
8035 Preprocessor &PP = Unit->getPreprocessor();
8036 PreprocessingRecord *PPRec = PP.getPreprocessingRecord();
8037 if (!PPRec)
Craig Topper69186e72014-06-08 08:38:04 +00008038 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008039
Alp Toker2d57cea2014-05-17 04:53:25 +00008040 IdentifierInfo &II = PP.getIdentifierTable().get(Tok.getRawIdentifier());
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008041 if (!II.hadMacroDefinition())
Craig Topper69186e72014-06-08 08:38:04 +00008042 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008043
8044 // Check that the identifier is not one of the macro arguments.
8045 if (std::find(MI->arg_begin(), MI->arg_end(), &II) != MI->arg_end())
Craig Topper69186e72014-06-08 08:38:04 +00008046 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008047
Richard Smith20e883e2015-04-29 23:20:19 +00008048 MacroDirective *InnerMD = PP.getLocalMacroDirectiveHistory(&II);
Argyrios Kyrtzidis09c9e812013-02-20 00:54:57 +00008049 if (!InnerMD)
Craig Topper69186e72014-06-08 08:38:04 +00008050 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008051
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00008052 return PPRec->findMacroDefinition(InnerMD->getMacroInfo());
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008053}
8054
Richard Smith66a81862015-05-04 02:25:31 +00008055MacroDefinitionRecord *
8056cxindex::checkForMacroInMacroDefinition(const MacroInfo *MI, SourceLocation Loc,
8057 CXTranslationUnit TU) {
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008058 if (Loc.isInvalid() || !MI || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00008059 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008060
8061 if (MI->getNumTokens() == 0)
Craig Topper69186e72014-06-08 08:38:04 +00008062 return nullptr;
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008063 ASTUnit *Unit = cxtu::getASTUnit(TU);
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008064 Preprocessor &PP = Unit->getPreprocessor();
8065 if (!PP.getPreprocessingRecord())
Craig Topper69186e72014-06-08 08:38:04 +00008066 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008067 Loc = Unit->getSourceManager().getSpellingLoc(Loc);
8068 Token Tok;
8069 if (PP.getRawToken(Loc, Tok))
Craig Topper69186e72014-06-08 08:38:04 +00008070 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008071
8072 return checkForMacroInMacroDefinition(MI, Tok, TU);
8073}
8074
Guy Benyei11169dd2012-12-18 14:30:41 +00008075CXString clang_getClangVersion() {
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00008076 return cxstring::createDup(getClangFullVersion());
Guy Benyei11169dd2012-12-18 14:30:41 +00008077}
8078
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008079Logger &cxindex::Logger::operator<<(CXTranslationUnit TU) {
8080 if (TU) {
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008081 if (ASTUnit *Unit = cxtu::getASTUnit(TU)) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008082 LogOS << '<' << Unit->getMainFileName() << '>';
Argyrios Kyrtzidis37f2ab42013-03-05 20:21:14 +00008083 if (Unit->isMainFileAST())
8084 LogOS << " (" << Unit->getASTFileName() << ')';
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008085 return *this;
8086 }
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00008087 } else {
8088 LogOS << "<NULL TU>";
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008089 }
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008090 return *this;
8091}
8092
Argyrios Kyrtzidisba4b5f82013-03-08 02:32:26 +00008093Logger &cxindex::Logger::operator<<(const FileEntry *FE) {
8094 *this << FE->getName();
8095 return *this;
8096}
8097
8098Logger &cxindex::Logger::operator<<(CXCursor cursor) {
8099 CXString cursorName = clang_getCursorDisplayName(cursor);
8100 *this << cursorName << "@" << clang_getCursorLocation(cursor);
8101 clang_disposeString(cursorName);
8102 return *this;
8103}
8104
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008105Logger &cxindex::Logger::operator<<(CXSourceLocation Loc) {
8106 CXFile File;
8107 unsigned Line, Column;
Craig Topper69186e72014-06-08 08:38:04 +00008108 clang_getFileLocation(Loc, &File, &Line, &Column, nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008109 CXString FileName = clang_getFileName(File);
8110 *this << llvm::format("(%s:%d:%d)", clang_getCString(FileName), Line, Column);
8111 clang_disposeString(FileName);
8112 return *this;
8113}
8114
8115Logger &cxindex::Logger::operator<<(CXSourceRange range) {
8116 CXSourceLocation BLoc = clang_getRangeStart(range);
8117 CXSourceLocation ELoc = clang_getRangeEnd(range);
8118
8119 CXFile BFile;
8120 unsigned BLine, BColumn;
Craig Topper69186e72014-06-08 08:38:04 +00008121 clang_getFileLocation(BLoc, &BFile, &BLine, &BColumn, nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008122
8123 CXFile EFile;
8124 unsigned ELine, EColumn;
Craig Topper69186e72014-06-08 08:38:04 +00008125 clang_getFileLocation(ELoc, &EFile, &ELine, &EColumn, nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008126
8127 CXString BFileName = clang_getFileName(BFile);
8128 if (BFile == EFile) {
8129 *this << llvm::format("[%s %d:%d-%d:%d]", clang_getCString(BFileName),
8130 BLine, BColumn, ELine, EColumn);
8131 } else {
8132 CXString EFileName = clang_getFileName(EFile);
8133 *this << llvm::format("[%s:%d:%d - ", clang_getCString(BFileName),
8134 BLine, BColumn)
8135 << llvm::format("%s:%d:%d]", clang_getCString(EFileName),
8136 ELine, EColumn);
8137 clang_disposeString(EFileName);
8138 }
8139 clang_disposeString(BFileName);
8140 return *this;
8141}
8142
8143Logger &cxindex::Logger::operator<<(CXString Str) {
8144 *this << clang_getCString(Str);
8145 return *this;
8146}
8147
8148Logger &cxindex::Logger::operator<<(const llvm::format_object_base &Fmt) {
8149 LogOS << Fmt;
8150 return *this;
8151}
8152
Chandler Carruth37ad2582014-06-27 15:14:39 +00008153static llvm::ManagedStatic<llvm::sys::Mutex> LoggingMutex;
8154
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008155cxindex::Logger::~Logger() {
Chandler Carruth37ad2582014-06-27 15:14:39 +00008156 llvm::sys::ScopedLock L(*LoggingMutex);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008157
8158 static llvm::TimeRecord sBeginTR = llvm::TimeRecord::getCurrentTime();
8159
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008160 raw_ostream &OS = llvm::errs();
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008161 OS << "[libclang:" << Name << ':';
8162
Alp Toker1a86ad22014-07-06 06:24:00 +00008163#ifdef USE_DARWIN_THREADS
8164 // TODO: Portability.
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008165 mach_port_t tid = pthread_mach_thread_np(pthread_self());
8166 OS << tid << ':';
8167#endif
8168
8169 llvm::TimeRecord TR = llvm::TimeRecord::getCurrentTime();
8170 OS << llvm::format("%7.4f] ", TR.getWallTime() - sBeginTR.getWallTime());
Yaron Keren09fb7c62015-03-10 07:33:23 +00008171 OS << Msg << '\n';
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008172
8173 if (Trace) {
Zachary Turner1fe2a8d2015-03-05 19:15:09 +00008174 llvm::sys::PrintStackTrace(OS);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008175 OS << "--------------------------------------------------\n";
8176 }
8177}
Benjamin Kramerc1ffdab2016-03-03 08:58:18 +00008178
8179#ifdef CLANG_TOOL_EXTRA_BUILD
8180// This anchor is used to force the linker to link the clang-tidy plugin.
8181extern volatile int ClangTidyPluginAnchorSource;
8182static int LLVM_ATTRIBUTE_UNUSED ClangTidyPluginAnchorDestination =
8183 ClangTidyPluginAnchorSource;
Benjamin Kramer9eba7352016-11-17 15:22:36 +00008184
8185// This anchor is used to force the linker to link the clang-include-fixer
8186// plugin.
8187extern volatile int ClangIncludeFixerPluginAnchorSource;
8188static int LLVM_ATTRIBUTE_UNUSED ClangIncludeFixerPluginAnchorDestination =
8189 ClangIncludeFixerPluginAnchorSource;
Benjamin Kramerc1ffdab2016-03-03 08:58:18 +00008190#endif