blob: 6e47697c6718aa5045151a9ecbd4724df48a652c [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
15#include "CIndexer.h"
16#include "CIndexDiagnostic.h"
Chandler Carruth4b417452013-01-19 08:09:44 +000017#include "CLog.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000018#include "CXCursor.h"
19#include "CXSourceLocation.h"
20#include "CXString.h"
21#include "CXTranslationUnit.h"
22#include "CXType.h"
23#include "CursorVisitor.h"
David Blaikie0a4e61f2013-09-13 18:32:52 +000024#include "clang/AST/Attr.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000025#include "clang/AST/StmtVisitor.h"
26#include "clang/Basic/Diagnostic.h"
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +000027#include "clang/Basic/DiagnosticCategories.h"
28#include "clang/Basic/DiagnosticIDs.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000029#include "clang/Basic/Version.h"
30#include "clang/Frontend/ASTUnit.h"
31#include "clang/Frontend/CompilerInstance.h"
32#include "clang/Frontend/FrontendDiagnostic.h"
Argyrios Kyrtzidisca741ce2016-02-14 22:30:14 +000033#include "clang/Index/CodegenNameGenerator.h"
Dmitri Gribenko9e605112013-11-13 22:16:51 +000034#include "clang/Index/CommentToXML.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000035#include "clang/Lex/HeaderSearch.h"
36#include "clang/Lex/Lexer.h"
37#include "clang/Lex/PreprocessingRecord.h"
38#include "clang/Lex/Preprocessor.h"
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +000039#include "clang/Serialization/SerializationDiagnostic.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000040#include "llvm/ADT/Optional.h"
41#include "llvm/ADT/STLExtras.h"
42#include "llvm/ADT/StringSwitch.h"
Alp Toker1d257e12014-06-04 03:28:55 +000043#include "llvm/Config/llvm-config.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000044#include "llvm/Support/Compiler.h"
45#include "llvm/Support/CrashRecoveryContext.h"
Chandler Carruth4b417452013-01-19 08:09:44 +000046#include "llvm/Support/Format.h"
Chandler Carruth37ad2582014-06-27 15:14:39 +000047#include "llvm/Support/ManagedStatic.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000048#include "llvm/Support/MemoryBuffer.h"
49#include "llvm/Support/Mutex.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000050#include "llvm/Support/Program.h"
51#include "llvm/Support/SaveAndRestore.h"
52#include "llvm/Support/Signals.h"
Adrian Prantlbc068582015-07-08 01:00:30 +000053#include "llvm/Support/TargetSelect.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000054#include "llvm/Support/Threading.h"
55#include "llvm/Support/Timer.h"
56#include "llvm/Support/raw_ostream.h"
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +000057
Alp Toker1a86ad22014-07-06 06:24:00 +000058#if LLVM_ENABLE_THREADS != 0 && defined(__APPLE__)
59#define USE_DARWIN_THREADS
60#endif
61
62#ifdef USE_DARWIN_THREADS
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +000063#include <pthread.h>
64#endif
Guy Benyei11169dd2012-12-18 14:30:41 +000065
66using namespace clang;
67using namespace clang::cxcursor;
Guy Benyei11169dd2012-12-18 14:30:41 +000068using namespace clang::cxtu;
69using namespace clang::cxindex;
70
Dmitri Gribenkod36209e2013-01-26 21:32:42 +000071CXTranslationUnit cxtu::MakeCXTranslationUnit(CIndexer *CIdx, ASTUnit *AU) {
72 if (!AU)
Craig Topper69186e72014-06-08 08:38:04 +000073 return nullptr;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +000074 assert(CIdx);
Guy Benyei11169dd2012-12-18 14:30:41 +000075 CXTranslationUnit D = new CXTranslationUnitImpl();
76 D->CIdx = CIdx;
Dmitri Gribenkod36209e2013-01-26 21:32:42 +000077 D->TheASTUnit = AU;
Dmitri Gribenko74895212013-02-03 13:52:47 +000078 D->StringPool = new cxstring::CXStringPool();
Craig Topper69186e72014-06-08 08:38:04 +000079 D->Diagnostics = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +000080 D->OverridenCursorsPool = createOverridenCXCursorsPool();
Craig Topper69186e72014-06-08 08:38:04 +000081 D->CommentToXML = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +000082 return D;
83}
84
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +000085bool cxtu::isASTReadError(ASTUnit *AU) {
86 for (ASTUnit::stored_diag_iterator D = AU->stored_diag_begin(),
87 DEnd = AU->stored_diag_end();
88 D != DEnd; ++D) {
89 if (D->getLevel() >= DiagnosticsEngine::Error &&
90 DiagnosticIDs::getCategoryNumberForDiag(D->getID()) ==
91 diag::DiagCat_AST_Deserialization_Issue)
92 return true;
93 }
94 return false;
95}
96
Guy Benyei11169dd2012-12-18 14:30:41 +000097cxtu::CXTUOwner::~CXTUOwner() {
98 if (TU)
99 clang_disposeTranslationUnit(TU);
100}
101
102/// \brief Compare two source ranges to determine their relative position in
103/// the translation unit.
104static RangeComparisonResult RangeCompare(SourceManager &SM,
105 SourceRange R1,
106 SourceRange R2) {
107 assert(R1.isValid() && "First range is invalid?");
108 assert(R2.isValid() && "Second range is invalid?");
109 if (R1.getEnd() != R2.getBegin() &&
110 SM.isBeforeInTranslationUnit(R1.getEnd(), R2.getBegin()))
111 return RangeBefore;
112 if (R2.getEnd() != R1.getBegin() &&
113 SM.isBeforeInTranslationUnit(R2.getEnd(), R1.getBegin()))
114 return RangeAfter;
115 return RangeOverlap;
116}
117
118/// \brief Determine if a source location falls within, before, or after a
119/// a given source range.
120static RangeComparisonResult LocationCompare(SourceManager &SM,
121 SourceLocation L, SourceRange R) {
122 assert(R.isValid() && "First range is invalid?");
123 assert(L.isValid() && "Second range is invalid?");
124 if (L == R.getBegin() || L == R.getEnd())
125 return RangeOverlap;
126 if (SM.isBeforeInTranslationUnit(L, R.getBegin()))
127 return RangeBefore;
128 if (SM.isBeforeInTranslationUnit(R.getEnd(), L))
129 return RangeAfter;
130 return RangeOverlap;
131}
132
133/// \brief Translate a Clang source range into a CIndex source range.
134///
135/// Clang internally represents ranges where the end location points to the
136/// start of the token at the end. However, for external clients it is more
137/// useful to have a CXSourceRange be a proper half-open interval. This routine
138/// does the appropriate translation.
139CXSourceRange cxloc::translateSourceRange(const SourceManager &SM,
140 const LangOptions &LangOpts,
141 const CharSourceRange &R) {
142 // We want the last character in this location, so we will adjust the
143 // location accordingly.
144 SourceLocation EndLoc = R.getEnd();
145 if (EndLoc.isValid() && EndLoc.isMacroID() && !SM.isMacroArgExpansion(EndLoc))
146 EndLoc = SM.getExpansionRange(EndLoc).second;
Yaron Keren8b563662015-10-03 10:46:20 +0000147 if (R.isTokenRange() && EndLoc.isValid()) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000148 unsigned Length = Lexer::MeasureTokenLength(SM.getSpellingLoc(EndLoc),
149 SM, LangOpts);
150 EndLoc = EndLoc.getLocWithOffset(Length);
151 }
152
Bill Wendlingeade3622013-01-23 08:25:41 +0000153 CXSourceRange Result = {
Dmitri Gribenkof9304482013-01-23 15:56:07 +0000154 { &SM, &LangOpts },
Bill Wendlingeade3622013-01-23 08:25:41 +0000155 R.getBegin().getRawEncoding(),
156 EndLoc.getRawEncoding()
157 };
Guy Benyei11169dd2012-12-18 14:30:41 +0000158 return Result;
159}
160
161//===----------------------------------------------------------------------===//
162// Cursor visitor.
163//===----------------------------------------------------------------------===//
164
165static SourceRange getRawCursorExtent(CXCursor C);
166static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr);
167
168
169RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
170 return RangeCompare(AU->getSourceManager(), R, RegionOfInterest);
171}
172
173/// \brief Visit the given cursor and, if requested by the visitor,
174/// its children.
175///
176/// \param Cursor the cursor to visit.
177///
178/// \param CheckedRegionOfInterest if true, then the caller already checked
179/// that this cursor is within the region of interest.
180///
181/// \returns true if the visitation should be aborted, false if it
182/// should continue.
183bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
184 if (clang_isInvalid(Cursor.kind))
185 return false;
186
187 if (clang_isDeclaration(Cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +0000188 const Decl *D = getCursorDecl(Cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +0000189 if (!D) {
190 assert(0 && "Invalid declaration cursor");
191 return true; // abort.
192 }
193
194 // Ignore implicit declarations, unless it's an objc method because
195 // currently we should report implicit methods for properties when indexing.
196 if (D->isImplicit() && !isa<ObjCMethodDecl>(D))
197 return false;
198 }
199
200 // If we have a range of interest, and this cursor doesn't intersect with it,
201 // we're done.
202 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
203 SourceRange Range = getRawCursorExtent(Cursor);
204 if (Range.isInvalid() || CompareRegionOfInterest(Range))
205 return false;
206 }
207
208 switch (Visitor(Cursor, Parent, ClientData)) {
209 case CXChildVisit_Break:
210 return true;
211
212 case CXChildVisit_Continue:
213 return false;
214
215 case CXChildVisit_Recurse: {
216 bool ret = VisitChildren(Cursor);
217 if (PostChildrenVisitor)
218 if (PostChildrenVisitor(Cursor, ClientData))
219 return true;
220 return ret;
221 }
222 }
223
224 llvm_unreachable("Invalid CXChildVisitResult!");
225}
226
227static bool visitPreprocessedEntitiesInRange(SourceRange R,
228 PreprocessingRecord &PPRec,
229 CursorVisitor &Visitor) {
230 SourceManager &SM = Visitor.getASTUnit()->getSourceManager();
231 FileID FID;
232
233 if (!Visitor.shouldVisitIncludedEntities()) {
234 // If the begin/end of the range lie in the same FileID, do the optimization
235 // where we skip preprocessed entities that do not come from the same FileID.
236 FID = SM.getFileID(SM.getFileLoc(R.getBegin()));
237 if (FID != SM.getFileID(SM.getFileLoc(R.getEnd())))
238 FID = FileID();
239 }
240
Benjamin Kramerb4ef6682015-02-06 17:25:10 +0000241 const auto &Entities = PPRec.getPreprocessedEntitiesInRange(R);
242 return Visitor.visitPreprocessedEntities(Entities.begin(), Entities.end(),
Guy Benyei11169dd2012-12-18 14:30:41 +0000243 PPRec, FID);
244}
245
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000246bool CursorVisitor::visitFileRegion() {
Guy Benyei11169dd2012-12-18 14:30:41 +0000247 if (RegionOfInterest.isInvalid())
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000248 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000249
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +0000250 ASTUnit *Unit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +0000251 SourceManager &SM = Unit->getSourceManager();
252
253 std::pair<FileID, unsigned>
254 Begin = SM.getDecomposedLoc(SM.getFileLoc(RegionOfInterest.getBegin())),
255 End = SM.getDecomposedLoc(SM.getFileLoc(RegionOfInterest.getEnd()));
256
257 if (End.first != Begin.first) {
258 // If the end does not reside in the same file, try to recover by
259 // picking the end of the file of begin location.
260 End.first = Begin.first;
261 End.second = SM.getFileIDSize(Begin.first);
262 }
263
264 assert(Begin.first == End.first);
265 if (Begin.second > End.second)
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000266 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000267
268 FileID File = Begin.first;
269 unsigned Offset = Begin.second;
270 unsigned Length = End.second - Begin.second;
271
272 if (!VisitDeclsOnly && !VisitPreprocessorLast)
273 if (visitPreprocessedEntitiesInRegion())
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000274 return true; // visitation break.
Guy Benyei11169dd2012-12-18 14:30:41 +0000275
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000276 if (visitDeclsFromFileRegion(File, Offset, Length))
277 return true; // visitation break.
Guy Benyei11169dd2012-12-18 14:30:41 +0000278
279 if (!VisitDeclsOnly && VisitPreprocessorLast)
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000280 return visitPreprocessedEntitiesInRegion();
281
282 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000283}
284
285static bool isInLexicalContext(Decl *D, DeclContext *DC) {
286 if (!DC)
287 return false;
288
289 for (DeclContext *DeclDC = D->getLexicalDeclContext();
290 DeclDC; DeclDC = DeclDC->getLexicalParent()) {
291 if (DeclDC == DC)
292 return true;
293 }
294 return false;
295}
296
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000297bool CursorVisitor::visitDeclsFromFileRegion(FileID File,
Guy Benyei11169dd2012-12-18 14:30:41 +0000298 unsigned Offset, unsigned Length) {
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +0000299 ASTUnit *Unit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +0000300 SourceManager &SM = Unit->getSourceManager();
301 SourceRange Range = RegionOfInterest;
302
303 SmallVector<Decl *, 16> Decls;
304 Unit->findFileRegionDecls(File, Offset, Length, Decls);
305
306 // If we didn't find any file level decls for the file, try looking at the
307 // file that it was included from.
308 while (Decls.empty() || Decls.front()->isTopLevelDeclInObjCContainer()) {
309 bool Invalid = false;
310 const SrcMgr::SLocEntry &SLEntry = SM.getSLocEntry(File, &Invalid);
311 if (Invalid)
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000312 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000313
314 SourceLocation Outer;
315 if (SLEntry.isFile())
316 Outer = SLEntry.getFile().getIncludeLoc();
317 else
318 Outer = SLEntry.getExpansion().getExpansionLocStart();
319 if (Outer.isInvalid())
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000320 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000321
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000322 std::tie(File, Offset) = SM.getDecomposedExpansionLoc(Outer);
Guy Benyei11169dd2012-12-18 14:30:41 +0000323 Length = 0;
324 Unit->findFileRegionDecls(File, Offset, Length, Decls);
325 }
326
327 assert(!Decls.empty());
328
329 bool VisitedAtLeastOnce = false;
Craig Topper69186e72014-06-08 08:38:04 +0000330 DeclContext *CurDC = nullptr;
Craig Topper2341c0d2013-07-04 03:08:24 +0000331 SmallVectorImpl<Decl *>::iterator DIt = Decls.begin();
332 for (SmallVectorImpl<Decl *>::iterator DE = Decls.end(); DIt != DE; ++DIt) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000333 Decl *D = *DIt;
334 if (D->getSourceRange().isInvalid())
335 continue;
336
337 if (isInLexicalContext(D, CurDC))
338 continue;
339
340 CurDC = dyn_cast<DeclContext>(D);
341
342 if (TagDecl *TD = dyn_cast<TagDecl>(D))
343 if (!TD->isFreeStanding())
344 continue;
345
346 RangeComparisonResult CompRes = RangeCompare(SM, D->getSourceRange(),Range);
347 if (CompRes == RangeBefore)
348 continue;
349 if (CompRes == RangeAfter)
350 break;
351
352 assert(CompRes == RangeOverlap);
353 VisitedAtLeastOnce = true;
354
355 if (isa<ObjCContainerDecl>(D)) {
356 FileDI_current = &DIt;
357 FileDE_current = DE;
358 } else {
Craig Topper69186e72014-06-08 08:38:04 +0000359 FileDI_current = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +0000360 }
361
362 if (Visit(MakeCXCursor(D, TU, Range), /*CheckedRegionOfInterest=*/true))
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000363 return true; // visitation break.
Guy Benyei11169dd2012-12-18 14:30:41 +0000364 }
365
366 if (VisitedAtLeastOnce)
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000367 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000368
369 // No Decls overlapped with the range. Move up the lexical context until there
370 // is a context that contains the range or we reach the translation unit
371 // level.
372 DeclContext *DC = DIt == Decls.begin() ? (*DIt)->getLexicalDeclContext()
373 : (*(DIt-1))->getLexicalDeclContext();
374
375 while (DC && !DC->isTranslationUnit()) {
376 Decl *D = cast<Decl>(DC);
377 SourceRange CurDeclRange = D->getSourceRange();
378 if (CurDeclRange.isInvalid())
379 break;
380
381 if (RangeCompare(SM, CurDeclRange, Range) == RangeOverlap) {
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000382 if (Visit(MakeCXCursor(D, TU, Range), /*CheckedRegionOfInterest=*/true))
383 return true; // visitation break.
Guy Benyei11169dd2012-12-18 14:30:41 +0000384 }
385
386 DC = D->getLexicalDeclContext();
387 }
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000388
389 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000390}
391
392bool CursorVisitor::visitPreprocessedEntitiesInRegion() {
393 if (!AU->getPreprocessor().getPreprocessingRecord())
394 return false;
395
396 PreprocessingRecord &PPRec
397 = *AU->getPreprocessor().getPreprocessingRecord();
398 SourceManager &SM = AU->getSourceManager();
399
400 if (RegionOfInterest.isValid()) {
401 SourceRange MappedRange = AU->mapRangeToPreamble(RegionOfInterest);
402 SourceLocation B = MappedRange.getBegin();
403 SourceLocation E = MappedRange.getEnd();
404
405 if (AU->isInPreambleFileID(B)) {
406 if (SM.isLoadedSourceLocation(E))
407 return visitPreprocessedEntitiesInRange(SourceRange(B, E),
408 PPRec, *this);
409
410 // Beginning of range lies in the preamble but it also extends beyond
411 // it into the main file. Split the range into 2 parts, one covering
412 // the preamble and another covering the main file. This allows subsequent
413 // calls to visitPreprocessedEntitiesInRange to accept a source range that
414 // lies in the same FileID, allowing it to skip preprocessed entities that
415 // do not come from the same FileID.
416 bool breaked =
417 visitPreprocessedEntitiesInRange(
418 SourceRange(B, AU->getEndOfPreambleFileID()),
419 PPRec, *this);
420 if (breaked) return true;
421 return visitPreprocessedEntitiesInRange(
422 SourceRange(AU->getStartOfMainFileID(), E),
423 PPRec, *this);
424 }
425
426 return visitPreprocessedEntitiesInRange(SourceRange(B, E), PPRec, *this);
427 }
428
429 bool OnlyLocalDecls
430 = !AU->isMainFileAST() && AU->getOnlyLocalDecls();
431
432 if (OnlyLocalDecls)
433 return visitPreprocessedEntities(PPRec.local_begin(), PPRec.local_end(),
434 PPRec);
435
436 return visitPreprocessedEntities(PPRec.begin(), PPRec.end(), PPRec);
437}
438
439template<typename InputIterator>
440bool CursorVisitor::visitPreprocessedEntities(InputIterator First,
441 InputIterator Last,
442 PreprocessingRecord &PPRec,
443 FileID FID) {
444 for (; First != Last; ++First) {
445 if (!FID.isInvalid() && !PPRec.isEntityInFileID(First, FID))
446 continue;
447
448 PreprocessedEntity *PPE = *First;
Argyrios Kyrtzidis1030f262013-05-07 20:37:17 +0000449 if (!PPE)
450 continue;
451
Guy Benyei11169dd2012-12-18 14:30:41 +0000452 if (MacroExpansion *ME = dyn_cast<MacroExpansion>(PPE)) {
453 if (Visit(MakeMacroExpansionCursor(ME, TU)))
454 return true;
Richard Smith66a81862015-05-04 02:25:31 +0000455
Guy Benyei11169dd2012-12-18 14:30:41 +0000456 continue;
457 }
Richard Smith66a81862015-05-04 02:25:31 +0000458
459 if (MacroDefinitionRecord *MD = dyn_cast<MacroDefinitionRecord>(PPE)) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000460 if (Visit(MakeMacroDefinitionCursor(MD, TU)))
461 return true;
Richard Smith66a81862015-05-04 02:25:31 +0000462
Guy Benyei11169dd2012-12-18 14:30:41 +0000463 continue;
464 }
465
466 if (InclusionDirective *ID = dyn_cast<InclusionDirective>(PPE)) {
467 if (Visit(MakeInclusionDirectiveCursor(ID, TU)))
468 return true;
469
470 continue;
471 }
472 }
473
474 return false;
475}
476
477/// \brief Visit the children of the given cursor.
478///
479/// \returns true if the visitation should be aborted, false if it
480/// should continue.
481bool CursorVisitor::VisitChildren(CXCursor Cursor) {
482 if (clang_isReference(Cursor.kind) &&
483 Cursor.kind != CXCursor_CXXBaseSpecifier) {
484 // By definition, references have no children.
485 return false;
486 }
487
488 // Set the Parent field to Cursor, then back to its old value once we're
489 // done.
490 SetParentRAII SetParent(Parent, StmtParent, Cursor);
491
492 if (clang_isDeclaration(Cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +0000493 Decl *D = const_cast<Decl *>(getCursorDecl(Cursor));
Guy Benyei11169dd2012-12-18 14:30:41 +0000494 if (!D)
495 return false;
496
497 return VisitAttributes(D) || Visit(D);
498 }
499
500 if (clang_isStatement(Cursor.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +0000501 if (const Stmt *S = getCursorStmt(Cursor))
Guy Benyei11169dd2012-12-18 14:30:41 +0000502 return Visit(S);
503
504 return false;
505 }
506
507 if (clang_isExpression(Cursor.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +0000508 if (const Expr *E = getCursorExpr(Cursor))
Guy Benyei11169dd2012-12-18 14:30:41 +0000509 return Visit(E);
510
511 return false;
512 }
513
514 if (clang_isTranslationUnit(Cursor.kind)) {
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +0000515 CXTranslationUnit TU = getCursorTU(Cursor);
516 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +0000517
518 int VisitOrder[2] = { VisitPreprocessorLast, !VisitPreprocessorLast };
519 for (unsigned I = 0; I != 2; ++I) {
520 if (VisitOrder[I]) {
521 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
522 RegionOfInterest.isInvalid()) {
523 for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
524 TLEnd = CXXUnit->top_level_end();
525 TL != TLEnd; ++TL) {
Argyrios Kyrtzidise7c91042016-07-01 19:10:54 +0000526 const Optional<bool> V = handleDeclForVisitation(*TL);
527 if (!V.hasValue())
528 continue;
529 return V.getValue();
Guy Benyei11169dd2012-12-18 14:30:41 +0000530 }
531 } else if (VisitDeclContext(
532 CXXUnit->getASTContext().getTranslationUnitDecl()))
533 return true;
534 continue;
535 }
536
537 // Walk the preprocessing record.
538 if (CXXUnit->getPreprocessor().getPreprocessingRecord())
539 visitPreprocessedEntitiesInRegion();
540 }
541
542 return false;
543 }
544
545 if (Cursor.kind == CXCursor_CXXBaseSpecifier) {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +0000546 if (const CXXBaseSpecifier *Base = getCursorCXXBaseSpecifier(Cursor)) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000547 if (TypeSourceInfo *BaseTSInfo = Base->getTypeSourceInfo()) {
548 return Visit(BaseTSInfo->getTypeLoc());
549 }
550 }
551 }
552
553 if (Cursor.kind == CXCursor_IBOutletCollectionAttr) {
Dmitri Gribenkoe4baea62013-01-26 18:08:08 +0000554 const IBOutletCollectionAttr *A =
Guy Benyei11169dd2012-12-18 14:30:41 +0000555 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(Cursor));
Richard Smithb1f9a282013-10-31 01:56:18 +0000556 if (const ObjCObjectType *ObjT = A->getInterface()->getAs<ObjCObjectType>())
Richard Smithb87c4652013-10-31 21:23:20 +0000557 return Visit(cxcursor::MakeCursorObjCClassRef(
558 ObjT->getInterface(),
559 A->getInterfaceLoc()->getTypeLoc().getLocStart(), TU));
Guy Benyei11169dd2012-12-18 14:30:41 +0000560 }
561
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +0000562 // If pointing inside a macro definition, check if the token is an identifier
563 // that was ever defined as a macro. In such a case, create a "pseudo" macro
564 // expansion cursor for that token.
565 SourceLocation BeginLoc = RegionOfInterest.getBegin();
566 if (Cursor.kind == CXCursor_MacroDefinition &&
567 BeginLoc == RegionOfInterest.getEnd()) {
568 SourceLocation Loc = AU->mapLocationToPreamble(BeginLoc);
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +0000569 const MacroInfo *MI =
570 getMacroInfo(cxcursor::getCursorMacroDefinition(Cursor), TU);
Richard Smith66a81862015-05-04 02:25:31 +0000571 if (MacroDefinitionRecord *MacroDef =
572 checkForMacroInMacroDefinition(MI, Loc, TU))
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +0000573 return Visit(cxcursor::MakeMacroExpansionCursor(MacroDef, BeginLoc, TU));
574 }
575
Guy Benyei11169dd2012-12-18 14:30:41 +0000576 // Nothing to visit at the moment.
577 return false;
578}
579
580bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
581 if (TypeSourceInfo *TSInfo = B->getSignatureAsWritten())
582 if (Visit(TSInfo->getTypeLoc()))
583 return true;
584
585 if (Stmt *Body = B->getBody())
586 return Visit(MakeCXCursor(Body, StmtParent, TU, RegionOfInterest));
587
588 return false;
589}
590
Ted Kremenek03325582013-02-21 01:29:01 +0000591Optional<bool> CursorVisitor::shouldVisitCursor(CXCursor Cursor) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000592 if (RegionOfInterest.isValid()) {
593 SourceRange Range = getFullCursorExtent(Cursor, AU->getSourceManager());
594 if (Range.isInvalid())
David Blaikie7a30dc52013-02-21 01:47:18 +0000595 return None;
Guy Benyei11169dd2012-12-18 14:30:41 +0000596
597 switch (CompareRegionOfInterest(Range)) {
598 case RangeBefore:
599 // This declaration comes before the region of interest; skip it.
David Blaikie7a30dc52013-02-21 01:47:18 +0000600 return None;
Guy Benyei11169dd2012-12-18 14:30:41 +0000601
602 case RangeAfter:
603 // This declaration comes after the region of interest; we're done.
604 return false;
605
606 case RangeOverlap:
607 // This declaration overlaps the region of interest; visit it.
608 break;
609 }
610 }
611 return true;
612}
613
614bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
615 DeclContext::decl_iterator I = DC->decls_begin(), E = DC->decls_end();
616
617 // FIXME: Eventually remove. This part of a hack to support proper
618 // iteration over all Decls contained lexically within an ObjC container.
619 SaveAndRestore<DeclContext::decl_iterator*> DI_saved(DI_current, &I);
620 SaveAndRestore<DeclContext::decl_iterator> DE_saved(DE_current, E);
621
622 for ( ; I != E; ++I) {
623 Decl *D = *I;
624 if (D->getLexicalDeclContext() != DC)
625 continue;
Argyrios Kyrtzidise7c91042016-07-01 19:10:54 +0000626 const Optional<bool> V = handleDeclForVisitation(D);
Guy Benyei11169dd2012-12-18 14:30:41 +0000627 if (!V.hasValue())
628 continue;
Argyrios Kyrtzidise7c91042016-07-01 19:10:54 +0000629 return V.getValue();
Guy Benyei11169dd2012-12-18 14:30:41 +0000630 }
631 return false;
632}
633
Argyrios Kyrtzidise7c91042016-07-01 19:10:54 +0000634Optional<bool> CursorVisitor::handleDeclForVisitation(const Decl *D) {
635 CXCursor Cursor = MakeCXCursor(D, TU, RegionOfInterest);
636
637 // Ignore synthesized ivars here, otherwise if we have something like:
638 // @synthesize prop = _prop;
639 // and '_prop' is not declared, we will encounter a '_prop' ivar before
640 // encountering the 'prop' synthesize declaration and we will think that
641 // we passed the region-of-interest.
642 if (auto *ivarD = dyn_cast<ObjCIvarDecl>(D)) {
643 if (ivarD->getSynthesize())
644 return None;
645 }
646
647 // FIXME: ObjCClassRef/ObjCProtocolRef for forward class/protocol
648 // declarations is a mismatch with the compiler semantics.
649 if (Cursor.kind == CXCursor_ObjCInterfaceDecl) {
650 auto *ID = cast<ObjCInterfaceDecl>(D);
651 if (!ID->isThisDeclarationADefinition())
652 Cursor = MakeCursorObjCClassRef(ID, ID->getLocation(), TU);
653
654 } else if (Cursor.kind == CXCursor_ObjCProtocolDecl) {
655 auto *PD = cast<ObjCProtocolDecl>(D);
656 if (!PD->isThisDeclarationADefinition())
657 Cursor = MakeCursorObjCProtocolRef(PD, PD->getLocation(), TU);
658 }
659
660 const Optional<bool> V = shouldVisitCursor(Cursor);
661 if (!V.hasValue())
662 return None;
663 if (!V.getValue())
664 return false;
665 if (Visit(Cursor, true))
666 return true;
667 return None;
668}
669
Guy Benyei11169dd2012-12-18 14:30:41 +0000670bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
671 llvm_unreachable("Translation units are visited directly by Visit()");
672}
673
Sergey Kalinichev8f3b1872015-11-15 13:48:32 +0000674bool CursorVisitor::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
675 if (VisitTemplateParameters(D->getTemplateParameters()))
676 return true;
677
678 return Visit(MakeCXCursor(D->getTemplatedDecl(), TU, RegionOfInterest));
679}
680
Guy Benyei11169dd2012-12-18 14:30:41 +0000681bool CursorVisitor::VisitTypeAliasDecl(TypeAliasDecl *D) {
682 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
683 return Visit(TSInfo->getTypeLoc());
684
685 return false;
686}
687
688bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
689 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
690 return Visit(TSInfo->getTypeLoc());
691
692 return false;
693}
694
695bool CursorVisitor::VisitTagDecl(TagDecl *D) {
696 return VisitDeclContext(D);
697}
698
699bool CursorVisitor::VisitClassTemplateSpecializationDecl(
700 ClassTemplateSpecializationDecl *D) {
701 bool ShouldVisitBody = false;
702 switch (D->getSpecializationKind()) {
703 case TSK_Undeclared:
704 case TSK_ImplicitInstantiation:
705 // Nothing to visit
706 return false;
707
708 case TSK_ExplicitInstantiationDeclaration:
709 case TSK_ExplicitInstantiationDefinition:
710 break;
711
712 case TSK_ExplicitSpecialization:
713 ShouldVisitBody = true;
714 break;
715 }
716
717 // Visit the template arguments used in the specialization.
718 if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) {
719 TypeLoc TL = SpecType->getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +0000720 if (TemplateSpecializationTypeLoc TSTLoc =
721 TL.getAs<TemplateSpecializationTypeLoc>()) {
722 for (unsigned I = 0, N = TSTLoc.getNumArgs(); I != N; ++I)
723 if (VisitTemplateArgumentLoc(TSTLoc.getArgLoc(I)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000724 return true;
725 }
726 }
Alexander Kornienko1a9f1842015-12-28 15:24:08 +0000727
728 return ShouldVisitBody && VisitCXXRecordDecl(D);
Guy Benyei11169dd2012-12-18 14:30:41 +0000729}
730
731bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl(
732 ClassTemplatePartialSpecializationDecl *D) {
733 // FIXME: Visit the "outer" template parameter lists on the TagDecl
734 // before visiting these template parameters.
735 if (VisitTemplateParameters(D->getTemplateParameters()))
736 return true;
737
738 // Visit the partial specialization arguments.
Enea Zaffanella6dbe1872013-08-10 07:24:53 +0000739 const ASTTemplateArgumentListInfo *Info = D->getTemplateArgsAsWritten();
740 const TemplateArgumentLoc *TemplateArgs = Info->getTemplateArgs();
741 for (unsigned I = 0, N = Info->NumTemplateArgs; I != N; ++I)
Guy Benyei11169dd2012-12-18 14:30:41 +0000742 if (VisitTemplateArgumentLoc(TemplateArgs[I]))
743 return true;
744
745 return VisitCXXRecordDecl(D);
746}
747
748bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
749 // Visit the default argument.
750 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
751 if (TypeSourceInfo *DefArg = D->getDefaultArgumentInfo())
752 if (Visit(DefArg->getTypeLoc()))
753 return true;
754
755 return false;
756}
757
758bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
759 if (Expr *Init = D->getInitExpr())
760 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
761 return false;
762}
763
764bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
Argyrios Kyrtzidis2ec76742013-04-05 21:04:10 +0000765 unsigned NumParamList = DD->getNumTemplateParameterLists();
766 for (unsigned i = 0; i < NumParamList; i++) {
767 TemplateParameterList* Params = DD->getTemplateParameterList(i);
768 if (VisitTemplateParameters(Params))
769 return true;
770 }
771
Guy Benyei11169dd2012-12-18 14:30:41 +0000772 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
773 if (Visit(TSInfo->getTypeLoc()))
774 return true;
775
776 // Visit the nested-name-specifier, if present.
777 if (NestedNameSpecifierLoc QualifierLoc = DD->getQualifierLoc())
778 if (VisitNestedNameSpecifierLoc(QualifierLoc))
779 return true;
780
781 return false;
782}
783
Benjamin Kramer4cadf292014-03-07 21:51:58 +0000784/// \brief Compare two base or member initializers based on their source order.
785static int CompareCXXCtorInitializers(CXXCtorInitializer *const *X,
786 CXXCtorInitializer *const *Y) {
787 return (*X)->getSourceOrder() - (*Y)->getSourceOrder();
788}
789
Guy Benyei11169dd2012-12-18 14:30:41 +0000790bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Argyrios Kyrtzidis2ec76742013-04-05 21:04:10 +0000791 unsigned NumParamList = ND->getNumTemplateParameterLists();
792 for (unsigned i = 0; i < NumParamList; i++) {
793 TemplateParameterList* Params = ND->getTemplateParameterList(i);
794 if (VisitTemplateParameters(Params))
795 return true;
796 }
797
Guy Benyei11169dd2012-12-18 14:30:41 +0000798 if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
799 // Visit the function declaration's syntactic components in the order
800 // written. This requires a bit of work.
801 TypeLoc TL = TSInfo->getTypeLoc().IgnoreParens();
David Blaikie6adc78e2013-02-18 22:06:02 +0000802 FunctionTypeLoc FTL = TL.getAs<FunctionTypeLoc>();
Guy Benyei11169dd2012-12-18 14:30:41 +0000803
804 // If we have a function declared directly (without the use of a typedef),
805 // visit just the return type. Otherwise, just visit the function's type
806 // now.
Alp Toker42a16a62014-01-25 23:51:36 +0000807 if ((FTL && !isa<CXXConversionDecl>(ND) && Visit(FTL.getReturnLoc())) ||
Guy Benyei11169dd2012-12-18 14:30:41 +0000808 (!FTL && Visit(TL)))
809 return true;
810
811 // Visit the nested-name-specifier, if present.
812 if (NestedNameSpecifierLoc QualifierLoc = ND->getQualifierLoc())
813 if (VisitNestedNameSpecifierLoc(QualifierLoc))
814 return true;
815
816 // Visit the declaration name.
Argyrios Kyrtzidis4a4d2b42014-02-09 08:13:47 +0000817 if (!isa<CXXDestructorDecl>(ND))
818 if (VisitDeclarationNameInfo(ND->getNameInfo()))
819 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +0000820
821 // FIXME: Visit explicitly-specified template arguments!
822
823 // Visit the function parameters, if we have a function type.
David Blaikie6adc78e2013-02-18 22:06:02 +0000824 if (FTL && VisitFunctionTypeLoc(FTL, true))
Guy Benyei11169dd2012-12-18 14:30:41 +0000825 return true;
826
Bill Wendling44426052012-12-20 19:22:21 +0000827 // FIXME: Attributes?
Guy Benyei11169dd2012-12-18 14:30:41 +0000828 }
829
830 if (ND->doesThisDeclarationHaveABody() && !ND->isLateTemplateParsed()) {
831 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ND)) {
832 // Find the initializers that were written in the source.
833 SmallVector<CXXCtorInitializer *, 4> WrittenInits;
Aaron Ballman0ad78302014-03-13 17:34:31 +0000834 for (auto *I : Constructor->inits()) {
835 if (!I->isWritten())
Guy Benyei11169dd2012-12-18 14:30:41 +0000836 continue;
837
Aaron Ballman0ad78302014-03-13 17:34:31 +0000838 WrittenInits.push_back(I);
Guy Benyei11169dd2012-12-18 14:30:41 +0000839 }
840
841 // Sort the initializers in source order
Benjamin Kramer4cadf292014-03-07 21:51:58 +0000842 llvm::array_pod_sort(WrittenInits.begin(), WrittenInits.end(),
843 &CompareCXXCtorInitializers);
844
Guy Benyei11169dd2012-12-18 14:30:41 +0000845 // Visit the initializers in source order
846 for (unsigned I = 0, N = WrittenInits.size(); I != N; ++I) {
847 CXXCtorInitializer *Init = WrittenInits[I];
848 if (Init->isAnyMemberInitializer()) {
849 if (Visit(MakeCursorMemberRef(Init->getAnyMember(),
850 Init->getMemberLocation(), TU)))
851 return true;
852 } else if (TypeSourceInfo *TInfo = Init->getTypeSourceInfo()) {
853 if (Visit(TInfo->getTypeLoc()))
854 return true;
855 }
856
857 // Visit the initializer value.
858 if (Expr *Initializer = Init->getInit())
859 if (Visit(MakeCXCursor(Initializer, ND, TU, RegionOfInterest)))
860 return true;
861 }
862 }
863
864 if (Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest)))
865 return true;
866 }
867
868 return false;
869}
870
871bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
872 if (VisitDeclaratorDecl(D))
873 return true;
874
875 if (Expr *BitWidth = D->getBitWidth())
876 return Visit(MakeCXCursor(BitWidth, StmtParent, TU, RegionOfInterest));
877
878 return false;
879}
880
881bool CursorVisitor::VisitVarDecl(VarDecl *D) {
882 if (VisitDeclaratorDecl(D))
883 return true;
884
885 if (Expr *Init = D->getInit())
886 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
887
888 return false;
889}
890
891bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
892 if (VisitDeclaratorDecl(D))
893 return true;
894
895 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
896 if (Expr *DefArg = D->getDefaultArgument())
897 return Visit(MakeCXCursor(DefArg, StmtParent, TU, RegionOfInterest));
898
899 return false;
900}
901
902bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
903 // FIXME: Visit the "outer" template parameter lists on the FunctionDecl
904 // before visiting these template parameters.
905 if (VisitTemplateParameters(D->getTemplateParameters()))
906 return true;
907
908 return VisitFunctionDecl(D->getTemplatedDecl());
909}
910
911bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) {
912 // FIXME: Visit the "outer" template parameter lists on the TagDecl
913 // before visiting these template parameters.
914 if (VisitTemplateParameters(D->getTemplateParameters()))
915 return true;
916
917 return VisitCXXRecordDecl(D->getTemplatedDecl());
918}
919
920bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
921 if (VisitTemplateParameters(D->getTemplateParameters()))
922 return true;
923
924 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() &&
925 VisitTemplateArgumentLoc(D->getDefaultArgument()))
926 return true;
927
928 return false;
929}
930
Douglas Gregor9bda6cf2015-07-07 03:58:14 +0000931bool CursorVisitor::VisitObjCTypeParamDecl(ObjCTypeParamDecl *D) {
932 // Visit the bound, if it's explicit.
933 if (D->hasExplicitBound()) {
934 if (auto TInfo = D->getTypeSourceInfo()) {
935 if (Visit(TInfo->getTypeLoc()))
936 return true;
937 }
938 }
939
940 return false;
941}
942
Guy Benyei11169dd2012-12-18 14:30:41 +0000943bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Alp Toker314cc812014-01-25 16:55:45 +0000944 if (TypeSourceInfo *TSInfo = ND->getReturnTypeSourceInfo())
Guy Benyei11169dd2012-12-18 14:30:41 +0000945 if (Visit(TSInfo->getTypeLoc()))
946 return true;
947
David Majnemer59f77922016-06-24 04:05:48 +0000948 for (const auto *P : ND->parameters()) {
Aaron Ballman43b68be2014-03-07 17:50:17 +0000949 if (Visit(MakeCXCursor(P, TU, RegionOfInterest)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000950 return true;
951 }
952
Alexander Kornienko1a9f1842015-12-28 15:24:08 +0000953 return ND->isThisDeclarationADefinition() &&
954 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest));
Guy Benyei11169dd2012-12-18 14:30:41 +0000955}
956
957template <typename DeclIt>
958static void addRangedDeclsInContainer(DeclIt *DI_current, DeclIt DE_current,
959 SourceManager &SM, SourceLocation EndLoc,
960 SmallVectorImpl<Decl *> &Decls) {
961 DeclIt next = *DI_current;
962 while (++next != DE_current) {
963 Decl *D_next = *next;
964 if (!D_next)
965 break;
966 SourceLocation L = D_next->getLocStart();
967 if (!L.isValid())
968 break;
969 if (SM.isBeforeInTranslationUnit(L, EndLoc)) {
970 *DI_current = next;
971 Decls.push_back(D_next);
972 continue;
973 }
974 break;
975 }
976}
977
Guy Benyei11169dd2012-12-18 14:30:41 +0000978bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
979 // FIXME: Eventually convert back to just 'VisitDeclContext()'. Essentially
980 // an @implementation can lexically contain Decls that are not properly
981 // nested in the AST. When we identify such cases, we need to retrofit
982 // this nesting here.
983 if (!DI_current && !FileDI_current)
984 return VisitDeclContext(D);
985
986 // Scan the Decls that immediately come after the container
987 // in the current DeclContext. If any fall within the
988 // container's lexical region, stash them into a vector
989 // for later processing.
990 SmallVector<Decl *, 24> DeclsInContainer;
991 SourceLocation EndLoc = D->getSourceRange().getEnd();
992 SourceManager &SM = AU->getSourceManager();
993 if (EndLoc.isValid()) {
994 if (DI_current) {
995 addRangedDeclsInContainer(DI_current, DE_current, SM, EndLoc,
996 DeclsInContainer);
997 } else {
998 addRangedDeclsInContainer(FileDI_current, FileDE_current, SM, EndLoc,
999 DeclsInContainer);
1000 }
1001 }
1002
1003 // The common case.
1004 if (DeclsInContainer.empty())
1005 return VisitDeclContext(D);
1006
1007 // Get all the Decls in the DeclContext, and sort them with the
1008 // additional ones we've collected. Then visit them.
Aaron Ballman629afae2014-03-07 19:56:05 +00001009 for (auto *SubDecl : D->decls()) {
1010 if (!SubDecl || SubDecl->getLexicalDeclContext() != D ||
1011 SubDecl->getLocStart().isInvalid())
Guy Benyei11169dd2012-12-18 14:30:41 +00001012 continue;
Aaron Ballman629afae2014-03-07 19:56:05 +00001013 DeclsInContainer.push_back(SubDecl);
Guy Benyei11169dd2012-12-18 14:30:41 +00001014 }
1015
1016 // Now sort the Decls so that they appear in lexical order.
1017 std::sort(DeclsInContainer.begin(), DeclsInContainer.end(),
Benjamin Kramerbbdd7642014-03-01 14:48:57 +00001018 [&SM](Decl *A, Decl *B) {
1019 SourceLocation L_A = A->getLocStart();
1020 SourceLocation L_B = B->getLocStart();
1021 assert(L_A.isValid() && L_B.isValid());
1022 return SM.isBeforeInTranslationUnit(L_A, L_B);
1023 });
Guy Benyei11169dd2012-12-18 14:30:41 +00001024
1025 // Now visit the decls.
1026 for (SmallVectorImpl<Decl*>::iterator I = DeclsInContainer.begin(),
1027 E = DeclsInContainer.end(); I != E; ++I) {
1028 CXCursor Cursor = MakeCXCursor(*I, TU, RegionOfInterest);
Ted Kremenek03325582013-02-21 01:29:01 +00001029 const Optional<bool> &V = shouldVisitCursor(Cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00001030 if (!V.hasValue())
1031 continue;
1032 if (!V.getValue())
1033 return false;
1034 if (Visit(Cursor, true))
1035 return true;
1036 }
1037 return false;
1038}
1039
1040bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
1041 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
1042 TU)))
1043 return true;
1044
Douglas Gregore9d95f12015-07-07 03:57:35 +00001045 if (VisitObjCTypeParamList(ND->getTypeParamList()))
1046 return true;
1047
Guy Benyei11169dd2012-12-18 14:30:41 +00001048 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
1049 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
1050 E = ND->protocol_end(); I != E; ++I, ++PL)
1051 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
1052 return true;
1053
1054 return VisitObjCContainerDecl(ND);
1055}
1056
1057bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
1058 if (!PID->isThisDeclarationADefinition())
1059 return Visit(MakeCursorObjCProtocolRef(PID, PID->getLocation(), TU));
1060
1061 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
1062 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
1063 E = PID->protocol_end(); I != E; ++I, ++PL)
1064 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
1065 return true;
1066
1067 return VisitObjCContainerDecl(PID);
1068}
1069
1070bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
1071 if (PD->getTypeSourceInfo() && Visit(PD->getTypeSourceInfo()->getTypeLoc()))
1072 return true;
1073
1074 // FIXME: This implements a workaround with @property declarations also being
1075 // installed in the DeclContext for the @interface. Eventually this code
1076 // should be removed.
1077 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
1078 if (!CDecl || !CDecl->IsClassExtension())
1079 return false;
1080
1081 ObjCInterfaceDecl *ID = CDecl->getClassInterface();
1082 if (!ID)
1083 return false;
1084
1085 IdentifierInfo *PropertyId = PD->getIdentifier();
1086 ObjCPropertyDecl *prevDecl =
Manman Ren5b786402016-01-28 18:49:28 +00001087 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId,
1088 PD->getQueryKind());
Guy Benyei11169dd2012-12-18 14:30:41 +00001089
1090 if (!prevDecl)
1091 return false;
1092
1093 // Visit synthesized methods since they will be skipped when visiting
1094 // the @interface.
1095 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
1096 if (MD->isPropertyAccessor() && MD->getLexicalDeclContext() == CDecl)
1097 if (Visit(MakeCXCursor(MD, TU, RegionOfInterest)))
1098 return true;
1099
1100 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
1101 if (MD->isPropertyAccessor() && MD->getLexicalDeclContext() == CDecl)
1102 if (Visit(MakeCXCursor(MD, TU, RegionOfInterest)))
1103 return true;
1104
1105 return false;
1106}
1107
Douglas Gregore9d95f12015-07-07 03:57:35 +00001108bool CursorVisitor::VisitObjCTypeParamList(ObjCTypeParamList *typeParamList) {
1109 if (!typeParamList)
1110 return false;
1111
1112 for (auto *typeParam : *typeParamList) {
1113 // Visit the type parameter.
1114 if (Visit(MakeCXCursor(typeParam, TU, RegionOfInterest)))
1115 return true;
Douglas Gregore9d95f12015-07-07 03:57:35 +00001116 }
1117
1118 return false;
1119}
1120
Guy Benyei11169dd2012-12-18 14:30:41 +00001121bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
1122 if (!D->isThisDeclarationADefinition()) {
1123 // Forward declaration is treated like a reference.
1124 return Visit(MakeCursorObjCClassRef(D, D->getLocation(), TU));
1125 }
1126
Douglas Gregore9d95f12015-07-07 03:57:35 +00001127 // Objective-C type parameters.
1128 if (VisitObjCTypeParamList(D->getTypeParamListAsWritten()))
1129 return true;
1130
Guy Benyei11169dd2012-12-18 14:30:41 +00001131 // Issue callbacks for super class.
1132 if (D->getSuperClass() &&
1133 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
1134 D->getSuperClassLoc(),
1135 TU)))
1136 return true;
1137
Douglas Gregore9d95f12015-07-07 03:57:35 +00001138 if (TypeSourceInfo *SuperClassTInfo = D->getSuperClassTInfo())
1139 if (Visit(SuperClassTInfo->getTypeLoc()))
1140 return true;
1141
Guy Benyei11169dd2012-12-18 14:30:41 +00001142 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1143 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
1144 E = D->protocol_end(); I != E; ++I, ++PL)
1145 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
1146 return true;
1147
1148 return VisitObjCContainerDecl(D);
1149}
1150
1151bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
1152 return VisitObjCContainerDecl(D);
1153}
1154
1155bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
1156 // 'ID' could be null when dealing with invalid code.
1157 if (ObjCInterfaceDecl *ID = D->getClassInterface())
1158 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
1159 return true;
1160
1161 return VisitObjCImplDecl(D);
1162}
1163
1164bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
1165#if 0
1166 // Issue callbacks for super class.
1167 // FIXME: No source location information!
1168 if (D->getSuperClass() &&
1169 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
1170 D->getSuperClassLoc(),
1171 TU)))
1172 return true;
1173#endif
1174
1175 return VisitObjCImplDecl(D);
1176}
1177
1178bool CursorVisitor::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *PD) {
1179 if (ObjCIvarDecl *Ivar = PD->getPropertyIvarDecl())
1180 if (PD->isIvarNameSpecified())
1181 return Visit(MakeCursorMemberRef(Ivar, PD->getPropertyIvarDeclLoc(), TU));
1182
1183 return false;
1184}
1185
1186bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
1187 return VisitDeclContext(D);
1188}
1189
1190bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
1191 // Visit nested-name-specifier.
1192 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1193 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1194 return true;
1195
1196 return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(),
1197 D->getTargetNameLoc(), TU));
1198}
1199
1200bool CursorVisitor::VisitUsingDecl(UsingDecl *D) {
1201 // Visit nested-name-specifier.
1202 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1203 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1204 return true;
1205 }
1206
1207 if (Visit(MakeCursorOverloadedDeclRef(D, D->getLocation(), TU)))
1208 return true;
1209
1210 return VisitDeclarationNameInfo(D->getNameInfo());
1211}
1212
1213bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
1214 // Visit nested-name-specifier.
1215 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1216 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1217 return true;
1218
1219 return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(),
1220 D->getIdentLocation(), TU));
1221}
1222
1223bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
1224 // Visit nested-name-specifier.
1225 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1226 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1227 return true;
1228 }
1229
1230 return VisitDeclarationNameInfo(D->getNameInfo());
1231}
1232
1233bool CursorVisitor::VisitUnresolvedUsingTypenameDecl(
1234 UnresolvedUsingTypenameDecl *D) {
1235 // Visit nested-name-specifier.
1236 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1237 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1238 return true;
1239
1240 return false;
1241}
1242
Olivier Goffart81978012016-06-09 16:15:55 +00001243bool CursorVisitor::VisitStaticAssertDecl(StaticAssertDecl *D) {
1244 if (Visit(MakeCXCursor(D->getAssertExpr(), StmtParent, TU, RegionOfInterest)))
1245 return true;
1246 if (Visit(MakeCXCursor(D->getMessage(), StmtParent, TU, RegionOfInterest)))
1247 return true;
1248 return false;
1249}
1250
Guy Benyei11169dd2012-12-18 14:30:41 +00001251bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
1252 switch (Name.getName().getNameKind()) {
1253 case clang::DeclarationName::Identifier:
1254 case clang::DeclarationName::CXXLiteralOperatorName:
1255 case clang::DeclarationName::CXXOperatorName:
1256 case clang::DeclarationName::CXXUsingDirective:
1257 return false;
1258
1259 case clang::DeclarationName::CXXConstructorName:
1260 case clang::DeclarationName::CXXDestructorName:
1261 case clang::DeclarationName::CXXConversionFunctionName:
1262 if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
1263 return Visit(TSInfo->getTypeLoc());
1264 return false;
1265
1266 case clang::DeclarationName::ObjCZeroArgSelector:
1267 case clang::DeclarationName::ObjCOneArgSelector:
1268 case clang::DeclarationName::ObjCMultiArgSelector:
1269 // FIXME: Per-identifier location info?
1270 return false;
1271 }
1272
1273 llvm_unreachable("Invalid DeclarationName::Kind!");
1274}
1275
1276bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS,
1277 SourceRange Range) {
1278 // FIXME: This whole routine is a hack to work around the lack of proper
1279 // source information in nested-name-specifiers (PR5791). Since we do have
1280 // a beginning source location, we can visit the first component of the
1281 // nested-name-specifier, if it's a single-token component.
1282 if (!NNS)
1283 return false;
1284
1285 // Get the first component in the nested-name-specifier.
1286 while (NestedNameSpecifier *Prefix = NNS->getPrefix())
1287 NNS = Prefix;
1288
1289 switch (NNS->getKind()) {
1290 case NestedNameSpecifier::Namespace:
1291 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(),
1292 TU));
1293
1294 case NestedNameSpecifier::NamespaceAlias:
1295 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
1296 Range.getBegin(), TU));
1297
1298 case NestedNameSpecifier::TypeSpec: {
1299 // If the type has a form where we know that the beginning of the source
1300 // range matches up with a reference cursor. Visit the appropriate reference
1301 // cursor.
1302 const Type *T = NNS->getAsType();
1303 if (const TypedefType *Typedef = dyn_cast<TypedefType>(T))
1304 return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU));
1305 if (const TagType *Tag = dyn_cast<TagType>(T))
1306 return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU));
1307 if (const TemplateSpecializationType *TST
1308 = dyn_cast<TemplateSpecializationType>(T))
1309 return VisitTemplateName(TST->getTemplateName(), Range.getBegin());
1310 break;
1311 }
1312
1313 case NestedNameSpecifier::TypeSpecWithTemplate:
1314 case NestedNameSpecifier::Global:
1315 case NestedNameSpecifier::Identifier:
Nikola Smiljanic67860242014-09-26 00:28:20 +00001316 case NestedNameSpecifier::Super:
Guy Benyei11169dd2012-12-18 14:30:41 +00001317 break;
1318 }
1319
1320 return false;
1321}
1322
1323bool
1324CursorVisitor::VisitNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
1325 SmallVector<NestedNameSpecifierLoc, 4> Qualifiers;
1326 for (; Qualifier; Qualifier = Qualifier.getPrefix())
1327 Qualifiers.push_back(Qualifier);
1328
1329 while (!Qualifiers.empty()) {
1330 NestedNameSpecifierLoc Q = Qualifiers.pop_back_val();
1331 NestedNameSpecifier *NNS = Q.getNestedNameSpecifier();
1332 switch (NNS->getKind()) {
1333 case NestedNameSpecifier::Namespace:
1334 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(),
1335 Q.getLocalBeginLoc(),
1336 TU)))
1337 return true;
1338
1339 break;
1340
1341 case NestedNameSpecifier::NamespaceAlias:
1342 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
1343 Q.getLocalBeginLoc(),
1344 TU)))
1345 return true;
1346
1347 break;
1348
1349 case NestedNameSpecifier::TypeSpec:
1350 case NestedNameSpecifier::TypeSpecWithTemplate:
1351 if (Visit(Q.getTypeLoc()))
1352 return true;
1353
1354 break;
1355
1356 case NestedNameSpecifier::Global:
1357 case NestedNameSpecifier::Identifier:
Nikola Smiljanic67860242014-09-26 00:28:20 +00001358 case NestedNameSpecifier::Super:
Guy Benyei11169dd2012-12-18 14:30:41 +00001359 break;
1360 }
1361 }
1362
1363 return false;
1364}
1365
1366bool CursorVisitor::VisitTemplateParameters(
1367 const TemplateParameterList *Params) {
1368 if (!Params)
1369 return false;
1370
1371 for (TemplateParameterList::const_iterator P = Params->begin(),
1372 PEnd = Params->end();
1373 P != PEnd; ++P) {
1374 if (Visit(MakeCXCursor(*P, TU, RegionOfInterest)))
1375 return true;
1376 }
1377
1378 return false;
1379}
1380
1381bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) {
1382 switch (Name.getKind()) {
1383 case TemplateName::Template:
1384 return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
1385
1386 case TemplateName::OverloadedTemplate:
1387 // Visit the overloaded template set.
1388 if (Visit(MakeCursorOverloadedDeclRef(Name, Loc, TU)))
1389 return true;
1390
1391 return false;
1392
1393 case TemplateName::DependentTemplate:
1394 // FIXME: Visit nested-name-specifier.
1395 return false;
1396
1397 case TemplateName::QualifiedTemplate:
1398 // FIXME: Visit nested-name-specifier.
1399 return Visit(MakeCursorTemplateRef(
1400 Name.getAsQualifiedTemplateName()->getDecl(),
1401 Loc, TU));
1402
1403 case TemplateName::SubstTemplateTemplateParm:
1404 return Visit(MakeCursorTemplateRef(
1405 Name.getAsSubstTemplateTemplateParm()->getParameter(),
1406 Loc, TU));
1407
1408 case TemplateName::SubstTemplateTemplateParmPack:
1409 return Visit(MakeCursorTemplateRef(
1410 Name.getAsSubstTemplateTemplateParmPack()->getParameterPack(),
1411 Loc, TU));
1412 }
1413
1414 llvm_unreachable("Invalid TemplateName::Kind!");
1415}
1416
1417bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
1418 switch (TAL.getArgument().getKind()) {
1419 case TemplateArgument::Null:
1420 case TemplateArgument::Integral:
1421 case TemplateArgument::Pack:
1422 return false;
1423
1424 case TemplateArgument::Type:
1425 if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
1426 return Visit(TSInfo->getTypeLoc());
1427 return false;
1428
1429 case TemplateArgument::Declaration:
1430 if (Expr *E = TAL.getSourceDeclExpression())
1431 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
1432 return false;
1433
1434 case TemplateArgument::NullPtr:
1435 if (Expr *E = TAL.getSourceNullPtrExpression())
1436 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
1437 return false;
1438
1439 case TemplateArgument::Expression:
1440 if (Expr *E = TAL.getSourceExpression())
1441 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
1442 return false;
1443
1444 case TemplateArgument::Template:
1445 case TemplateArgument::TemplateExpansion:
1446 if (VisitNestedNameSpecifierLoc(TAL.getTemplateQualifierLoc()))
1447 return true;
1448
1449 return VisitTemplateName(TAL.getArgument().getAsTemplateOrTemplatePattern(),
1450 TAL.getTemplateNameLoc());
1451 }
1452
1453 llvm_unreachable("Invalid TemplateArgument::Kind!");
1454}
1455
1456bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1457 return VisitDeclContext(D);
1458}
1459
1460bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1461 return Visit(TL.getUnqualifiedLoc());
1462}
1463
1464bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
1465 ASTContext &Context = AU->getASTContext();
1466
1467 // Some builtin types (such as Objective-C's "id", "sel", and
1468 // "Class") have associated declarations. Create cursors for those.
1469 QualType VisitType;
1470 switch (TL.getTypePtr()->getKind()) {
1471
1472 case BuiltinType::Void:
1473 case BuiltinType::NullPtr:
1474 case BuiltinType::Dependent:
Alexey Bader954ba212016-04-08 13:40:33 +00001475#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1476 case BuiltinType::Id:
Alexey Baderb62f1442016-04-13 08:33:41 +00001477#include "clang/Basic/OpenCLImageTypes.def"
NAKAMURA Takumi288c42e2013-02-07 12:47:42 +00001478 case BuiltinType::OCLSampler:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001479 case BuiltinType::OCLEvent:
Alexey Bader9c8453f2015-09-15 11:18:52 +00001480 case BuiltinType::OCLClkEvent:
1481 case BuiltinType::OCLQueue:
1482 case BuiltinType::OCLNDRange:
1483 case BuiltinType::OCLReserveID:
Guy Benyei11169dd2012-12-18 14:30:41 +00001484#define BUILTIN_TYPE(Id, SingletonId)
1485#define SIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
1486#define UNSIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
1487#define FLOATING_TYPE(Id, SingletonId) case BuiltinType::Id:
1488#define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id:
1489#include "clang/AST/BuiltinTypes.def"
1490 break;
1491
1492 case BuiltinType::ObjCId:
1493 VisitType = Context.getObjCIdType();
1494 break;
1495
1496 case BuiltinType::ObjCClass:
1497 VisitType = Context.getObjCClassType();
1498 break;
1499
1500 case BuiltinType::ObjCSel:
1501 VisitType = Context.getObjCSelType();
1502 break;
1503 }
1504
1505 if (!VisitType.isNull()) {
1506 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
1507 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
1508 TU));
1509 }
1510
1511 return false;
1512}
1513
1514bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
1515 return Visit(MakeCursorTypeRef(TL.getTypedefNameDecl(), TL.getNameLoc(), TU));
1516}
1517
1518bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
1519 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1520}
1521
1522bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
1523 if (TL.isDefinition())
1524 return Visit(MakeCXCursor(TL.getDecl(), TU, RegionOfInterest));
1525
1526 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1527}
1528
1529bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
1530 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1531}
1532
1533bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
Hans Wennborg59dbe862015-09-29 20:56:43 +00001534 return Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU));
Guy Benyei11169dd2012-12-18 14:30:41 +00001535}
1536
1537bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1538 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
1539 return true;
1540
Douglas Gregore9d95f12015-07-07 03:57:35 +00001541 for (unsigned I = 0, N = TL.getNumTypeArgs(); I != N; ++I) {
1542 if (Visit(TL.getTypeArgTInfo(I)->getTypeLoc()))
1543 return true;
1544 }
1545
Guy Benyei11169dd2012-12-18 14:30:41 +00001546 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1547 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1548 TU)))
1549 return true;
1550 }
1551
1552 return false;
1553}
1554
1555bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
1556 return Visit(TL.getPointeeLoc());
1557}
1558
1559bool CursorVisitor::VisitParenTypeLoc(ParenTypeLoc TL) {
1560 return Visit(TL.getInnerLoc());
1561}
1562
1563bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
1564 return Visit(TL.getPointeeLoc());
1565}
1566
1567bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1568 return Visit(TL.getPointeeLoc());
1569}
1570
1571bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1572 return Visit(TL.getPointeeLoc());
1573}
1574
1575bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
1576 return Visit(TL.getPointeeLoc());
1577}
1578
1579bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
1580 return Visit(TL.getPointeeLoc());
1581}
1582
1583bool CursorVisitor::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
1584 return Visit(TL.getModifiedLoc());
1585}
1586
1587bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
1588 bool SkipResultType) {
Alp Toker42a16a62014-01-25 23:51:36 +00001589 if (!SkipResultType && Visit(TL.getReturnLoc()))
Guy Benyei11169dd2012-12-18 14:30:41 +00001590 return true;
1591
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00001592 for (unsigned I = 0, N = TL.getNumParams(); I != N; ++I)
1593 if (Decl *D = TL.getParam(I))
Guy Benyei11169dd2012-12-18 14:30:41 +00001594 if (Visit(MakeCXCursor(D, TU, RegionOfInterest)))
1595 return true;
1596
1597 return false;
1598}
1599
1600bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
1601 if (Visit(TL.getElementLoc()))
1602 return true;
1603
1604 if (Expr *Size = TL.getSizeExpr())
1605 return Visit(MakeCXCursor(Size, StmtParent, TU, RegionOfInterest));
1606
1607 return false;
1608}
1609
Reid Kleckner8a365022013-06-24 17:51:48 +00001610bool CursorVisitor::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
1611 return Visit(TL.getOriginalLoc());
1612}
1613
Reid Kleckner0503a872013-12-05 01:23:43 +00001614bool CursorVisitor::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
1615 return Visit(TL.getOriginalLoc());
1616}
1617
Guy Benyei11169dd2012-12-18 14:30:41 +00001618bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
1619 TemplateSpecializationTypeLoc TL) {
1620 // Visit the template name.
1621 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1622 TL.getTemplateNameLoc()))
1623 return true;
1624
1625 // Visit the template arguments.
1626 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1627 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1628 return true;
1629
1630 return false;
1631}
1632
1633bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1634 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
1635}
1636
1637bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1638 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1639 return Visit(TSInfo->getTypeLoc());
1640
1641 return false;
1642}
1643
1644bool CursorVisitor::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
1645 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1646 return Visit(TSInfo->getTypeLoc());
1647
1648 return false;
1649}
1650
1651bool CursorVisitor::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
Hans Wennborg59dbe862015-09-29 20:56:43 +00001652 return VisitNestedNameSpecifierLoc(TL.getQualifierLoc());
Guy Benyei11169dd2012-12-18 14:30:41 +00001653}
1654
1655bool CursorVisitor::VisitDependentTemplateSpecializationTypeLoc(
1656 DependentTemplateSpecializationTypeLoc TL) {
1657 // Visit the nested-name-specifier, if there is one.
1658 if (TL.getQualifierLoc() &&
1659 VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1660 return true;
1661
1662 // Visit the template arguments.
1663 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1664 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1665 return true;
1666
1667 return false;
1668}
1669
1670bool CursorVisitor::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
1671 if (VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1672 return true;
1673
1674 return Visit(TL.getNamedTypeLoc());
1675}
1676
1677bool CursorVisitor::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
1678 return Visit(TL.getPatternLoc());
1679}
1680
1681bool CursorVisitor::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
1682 if (Expr *E = TL.getUnderlyingExpr())
1683 return Visit(MakeCXCursor(E, StmtParent, TU));
1684
1685 return false;
1686}
1687
1688bool CursorVisitor::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
1689 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1690}
1691
1692bool CursorVisitor::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
1693 return Visit(TL.getValueLoc());
1694}
1695
Xiuli Pan9c14e282016-01-09 12:53:17 +00001696bool CursorVisitor::VisitPipeTypeLoc(PipeTypeLoc TL) {
1697 return Visit(TL.getValueLoc());
1698}
1699
Guy Benyei11169dd2012-12-18 14:30:41 +00001700#define DEFAULT_TYPELOC_IMPL(CLASS, PARENT) \
1701bool CursorVisitor::Visit##CLASS##TypeLoc(CLASS##TypeLoc TL) { \
1702 return Visit##PARENT##Loc(TL); \
1703}
1704
1705DEFAULT_TYPELOC_IMPL(Complex, Type)
1706DEFAULT_TYPELOC_IMPL(ConstantArray, ArrayType)
1707DEFAULT_TYPELOC_IMPL(IncompleteArray, ArrayType)
1708DEFAULT_TYPELOC_IMPL(VariableArray, ArrayType)
1709DEFAULT_TYPELOC_IMPL(DependentSizedArray, ArrayType)
1710DEFAULT_TYPELOC_IMPL(DependentSizedExtVector, Type)
1711DEFAULT_TYPELOC_IMPL(Vector, Type)
1712DEFAULT_TYPELOC_IMPL(ExtVector, VectorType)
1713DEFAULT_TYPELOC_IMPL(FunctionProto, FunctionType)
1714DEFAULT_TYPELOC_IMPL(FunctionNoProto, FunctionType)
1715DEFAULT_TYPELOC_IMPL(Record, TagType)
1716DEFAULT_TYPELOC_IMPL(Enum, TagType)
1717DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParm, Type)
1718DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParmPack, Type)
1719DEFAULT_TYPELOC_IMPL(Auto, Type)
1720
1721bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
1722 // Visit the nested-name-specifier, if present.
1723 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1724 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1725 return true;
1726
1727 if (D->isCompleteDefinition()) {
Aaron Ballman574705e2014-03-13 15:41:46 +00001728 for (const auto &I : D->bases()) {
1729 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(&I, TU)))
Guy Benyei11169dd2012-12-18 14:30:41 +00001730 return true;
1731 }
1732 }
1733
1734 return VisitTagDecl(D);
1735}
1736
1737bool CursorVisitor::VisitAttributes(Decl *D) {
Aaron Ballmanb97112e2014-03-08 22:19:01 +00001738 for (const auto *I : D->attrs())
1739 if (Visit(MakeCXCursor(I, D, TU)))
Guy Benyei11169dd2012-12-18 14:30:41 +00001740 return true;
1741
1742 return false;
1743}
1744
1745//===----------------------------------------------------------------------===//
1746// Data-recursive visitor methods.
1747//===----------------------------------------------------------------------===//
1748
1749namespace {
1750#define DEF_JOB(NAME, DATA, KIND)\
1751class NAME : public VisitorJob {\
1752public:\
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001753 NAME(const DATA *d, CXCursor parent) : \
1754 VisitorJob(parent, VisitorJob::KIND, d) {} \
Guy Benyei11169dd2012-12-18 14:30:41 +00001755 static bool classof(const VisitorJob *VJ) { return VJ->getKind() == KIND; }\
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001756 const DATA *get() const { return static_cast<const DATA*>(data[0]); }\
Guy Benyei11169dd2012-12-18 14:30:41 +00001757};
1758
1759DEF_JOB(StmtVisit, Stmt, StmtVisitKind)
1760DEF_JOB(MemberExprParts, MemberExpr, MemberExprPartsKind)
1761DEF_JOB(DeclRefExprParts, DeclRefExpr, DeclRefExprPartsKind)
1762DEF_JOB(OverloadExprParts, OverloadExpr, OverloadExprPartsKind)
Guy Benyei11169dd2012-12-18 14:30:41 +00001763DEF_JOB(SizeOfPackExprParts, SizeOfPackExpr, SizeOfPackExprPartsKind)
1764DEF_JOB(LambdaExprParts, LambdaExpr, LambdaExprPartsKind)
1765DEF_JOB(PostChildrenVisit, void, PostChildrenVisitKind)
1766#undef DEF_JOB
1767
James Y Knight04ec5bf2015-12-24 02:59:37 +00001768class ExplicitTemplateArgsVisit : public VisitorJob {
1769public:
1770 ExplicitTemplateArgsVisit(const TemplateArgumentLoc *Begin,
1771 const TemplateArgumentLoc *End, CXCursor parent)
1772 : VisitorJob(parent, VisitorJob::ExplicitTemplateArgsVisitKind, Begin,
1773 End) {}
1774 static bool classof(const VisitorJob *VJ) {
1775 return VJ->getKind() == ExplicitTemplateArgsVisitKind;
1776 }
1777 const TemplateArgumentLoc *begin() const {
1778 return static_cast<const TemplateArgumentLoc *>(data[0]);
1779 }
1780 const TemplateArgumentLoc *end() {
1781 return static_cast<const TemplateArgumentLoc *>(data[1]);
1782 }
1783};
Guy Benyei11169dd2012-12-18 14:30:41 +00001784class DeclVisit : public VisitorJob {
1785public:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001786 DeclVisit(const Decl *D, CXCursor parent, bool isFirst) :
Guy Benyei11169dd2012-12-18 14:30:41 +00001787 VisitorJob(parent, VisitorJob::DeclVisitKind,
Craig Topper69186e72014-06-08 08:38:04 +00001788 D, isFirst ? (void*) 1 : (void*) nullptr) {}
Guy Benyei11169dd2012-12-18 14:30:41 +00001789 static bool classof(const VisitorJob *VJ) {
1790 return VJ->getKind() == DeclVisitKind;
1791 }
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001792 const Decl *get() const { return static_cast<const Decl *>(data[0]); }
Dmitri Gribenkoe5423a72015-03-23 19:23:50 +00001793 bool isFirst() const { return data[1] != nullptr; }
Guy Benyei11169dd2012-12-18 14:30:41 +00001794};
1795class TypeLocVisit : public VisitorJob {
1796public:
1797 TypeLocVisit(TypeLoc tl, CXCursor parent) :
1798 VisitorJob(parent, VisitorJob::TypeLocVisitKind,
1799 tl.getType().getAsOpaquePtr(), tl.getOpaqueData()) {}
1800
1801 static bool classof(const VisitorJob *VJ) {
1802 return VJ->getKind() == TypeLocVisitKind;
1803 }
1804
1805 TypeLoc get() const {
1806 QualType T = QualType::getFromOpaquePtr(data[0]);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001807 return TypeLoc(T, const_cast<void *>(data[1]));
Guy Benyei11169dd2012-12-18 14:30:41 +00001808 }
1809};
1810
1811class LabelRefVisit : public VisitorJob {
1812public:
1813 LabelRefVisit(LabelDecl *LD, SourceLocation labelLoc, CXCursor parent)
1814 : VisitorJob(parent, VisitorJob::LabelRefVisitKind, LD,
1815 labelLoc.getPtrEncoding()) {}
1816
1817 static bool classof(const VisitorJob *VJ) {
1818 return VJ->getKind() == VisitorJob::LabelRefVisitKind;
1819 }
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001820 const LabelDecl *get() const {
1821 return static_cast<const LabelDecl *>(data[0]);
1822 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001823 SourceLocation getLoc() const {
1824 return SourceLocation::getFromPtrEncoding(data[1]); }
1825};
1826
1827class NestedNameSpecifierLocVisit : public VisitorJob {
1828public:
1829 NestedNameSpecifierLocVisit(NestedNameSpecifierLoc Qualifier, CXCursor parent)
1830 : VisitorJob(parent, VisitorJob::NestedNameSpecifierLocVisitKind,
1831 Qualifier.getNestedNameSpecifier(),
1832 Qualifier.getOpaqueData()) { }
1833
1834 static bool classof(const VisitorJob *VJ) {
1835 return VJ->getKind() == VisitorJob::NestedNameSpecifierLocVisitKind;
1836 }
1837
1838 NestedNameSpecifierLoc get() const {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001839 return NestedNameSpecifierLoc(
1840 const_cast<NestedNameSpecifier *>(
1841 static_cast<const NestedNameSpecifier *>(data[0])),
1842 const_cast<void *>(data[1]));
Guy Benyei11169dd2012-12-18 14:30:41 +00001843 }
1844};
1845
1846class DeclarationNameInfoVisit : public VisitorJob {
1847public:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001848 DeclarationNameInfoVisit(const Stmt *S, CXCursor parent)
Dmitri Gribenkodd7dacf2013-02-03 13:19:54 +00001849 : VisitorJob(parent, VisitorJob::DeclarationNameInfoVisitKind, S) {}
Guy Benyei11169dd2012-12-18 14:30:41 +00001850 static bool classof(const VisitorJob *VJ) {
1851 return VJ->getKind() == VisitorJob::DeclarationNameInfoVisitKind;
1852 }
1853 DeclarationNameInfo get() const {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001854 const Stmt *S = static_cast<const Stmt *>(data[0]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001855 switch (S->getStmtClass()) {
1856 default:
1857 llvm_unreachable("Unhandled Stmt");
1858 case clang::Stmt::MSDependentExistsStmtClass:
1859 return cast<MSDependentExistsStmt>(S)->getNameInfo();
1860 case Stmt::CXXDependentScopeMemberExprClass:
1861 return cast<CXXDependentScopeMemberExpr>(S)->getMemberNameInfo();
1862 case Stmt::DependentScopeDeclRefExprClass:
1863 return cast<DependentScopeDeclRefExpr>(S)->getNameInfo();
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001864 case Stmt::OMPCriticalDirectiveClass:
1865 return cast<OMPCriticalDirective>(S)->getDirectiveName();
Guy Benyei11169dd2012-12-18 14:30:41 +00001866 }
1867 }
1868};
1869class MemberRefVisit : public VisitorJob {
1870public:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001871 MemberRefVisit(const FieldDecl *D, SourceLocation L, CXCursor parent)
Guy Benyei11169dd2012-12-18 14:30:41 +00001872 : VisitorJob(parent, VisitorJob::MemberRefVisitKind, D,
1873 L.getPtrEncoding()) {}
1874 static bool classof(const VisitorJob *VJ) {
1875 return VJ->getKind() == VisitorJob::MemberRefVisitKind;
1876 }
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001877 const FieldDecl *get() const {
1878 return static_cast<const FieldDecl *>(data[0]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001879 }
1880 SourceLocation getLoc() const {
1881 return SourceLocation::getFromRawEncoding((unsigned)(uintptr_t) data[1]);
1882 }
1883};
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001884class EnqueueVisitor : public ConstStmtVisitor<EnqueueVisitor, void> {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001885 friend class OMPClauseEnqueue;
Guy Benyei11169dd2012-12-18 14:30:41 +00001886 VisitorWorkList &WL;
1887 CXCursor Parent;
1888public:
1889 EnqueueVisitor(VisitorWorkList &wl, CXCursor parent)
1890 : WL(wl), Parent(parent) {}
1891
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001892 void VisitAddrLabelExpr(const AddrLabelExpr *E);
1893 void VisitBlockExpr(const BlockExpr *B);
1894 void VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
1895 void VisitCompoundStmt(const CompoundStmt *S);
1896 void VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) { /* Do nothing. */ }
1897 void VisitMSDependentExistsStmt(const MSDependentExistsStmt *S);
1898 void VisitCXXDependentScopeMemberExpr(const CXXDependentScopeMemberExpr *E);
1899 void VisitCXXNewExpr(const CXXNewExpr *E);
1900 void VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E);
1901 void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *E);
1902 void VisitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *E);
1903 void VisitCXXTemporaryObjectExpr(const CXXTemporaryObjectExpr *E);
1904 void VisitCXXTypeidExpr(const CXXTypeidExpr *E);
1905 void VisitCXXUnresolvedConstructExpr(const CXXUnresolvedConstructExpr *E);
1906 void VisitCXXUuidofExpr(const CXXUuidofExpr *E);
1907 void VisitCXXCatchStmt(const CXXCatchStmt *S);
Argyrios Kyrtzidis99891242014-11-13 09:03:21 +00001908 void VisitCXXForRangeStmt(const CXXForRangeStmt *S);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001909 void VisitDeclRefExpr(const DeclRefExpr *D);
1910 void VisitDeclStmt(const DeclStmt *S);
1911 void VisitDependentScopeDeclRefExpr(const DependentScopeDeclRefExpr *E);
1912 void VisitDesignatedInitExpr(const DesignatedInitExpr *E);
1913 void VisitExplicitCastExpr(const ExplicitCastExpr *E);
1914 void VisitForStmt(const ForStmt *FS);
1915 void VisitGotoStmt(const GotoStmt *GS);
1916 void VisitIfStmt(const IfStmt *If);
1917 void VisitInitListExpr(const InitListExpr *IE);
1918 void VisitMemberExpr(const MemberExpr *M);
1919 void VisitOffsetOfExpr(const OffsetOfExpr *E);
1920 void VisitObjCEncodeExpr(const ObjCEncodeExpr *E);
1921 void VisitObjCMessageExpr(const ObjCMessageExpr *M);
1922 void VisitOverloadExpr(const OverloadExpr *E);
1923 void VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
1924 void VisitStmt(const Stmt *S);
1925 void VisitSwitchStmt(const SwitchStmt *S);
1926 void VisitWhileStmt(const WhileStmt *W);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001927 void VisitTypeTraitExpr(const TypeTraitExpr *E);
1928 void VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E);
1929 void VisitExpressionTraitExpr(const ExpressionTraitExpr *E);
1930 void VisitUnresolvedMemberExpr(const UnresolvedMemberExpr *U);
1931 void VisitVAArgExpr(const VAArgExpr *E);
1932 void VisitSizeOfPackExpr(const SizeOfPackExpr *E);
1933 void VisitPseudoObjectExpr(const PseudoObjectExpr *E);
1934 void VisitOpaqueValueExpr(const OpaqueValueExpr *E);
1935 void VisitLambdaExpr(const LambdaExpr *E);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001936 void VisitOMPExecutableDirective(const OMPExecutableDirective *D);
Alexander Musman3aaab662014-08-19 11:27:13 +00001937 void VisitOMPLoopDirective(const OMPLoopDirective *D);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001938 void VisitOMPParallelDirective(const OMPParallelDirective *D);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00001939 void VisitOMPSimdDirective(const OMPSimdDirective *D);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001940 void VisitOMPForDirective(const OMPForDirective *D);
Alexander Musmanf82886e2014-09-18 05:12:34 +00001941 void VisitOMPForSimdDirective(const OMPForSimdDirective *D);
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00001942 void VisitOMPSectionsDirective(const OMPSectionsDirective *D);
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001943 void VisitOMPSectionDirective(const OMPSectionDirective *D);
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00001944 void VisitOMPSingleDirective(const OMPSingleDirective *D);
Alexander Musman80c22892014-07-17 08:54:58 +00001945 void VisitOMPMasterDirective(const OMPMasterDirective *D);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001946 void VisitOMPCriticalDirective(const OMPCriticalDirective *D);
Alexey Bataev4acb8592014-07-07 13:01:15 +00001947 void VisitOMPParallelForDirective(const OMPParallelForDirective *D);
Alexander Musmane4e893b2014-09-23 09:33:00 +00001948 void VisitOMPParallelForSimdDirective(const OMPParallelForSimdDirective *D);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001949 void VisitOMPParallelSectionsDirective(const OMPParallelSectionsDirective *D);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001950 void VisitOMPTaskDirective(const OMPTaskDirective *D);
Alexey Bataev68446b72014-07-18 07:47:19 +00001951 void VisitOMPTaskyieldDirective(const OMPTaskyieldDirective *D);
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001952 void VisitOMPBarrierDirective(const OMPBarrierDirective *D);
Alexey Bataev2df347a2014-07-18 10:17:07 +00001953 void VisitOMPTaskwaitDirective(const OMPTaskwaitDirective *D);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001954 void VisitOMPTaskgroupDirective(const OMPTaskgroupDirective *D);
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001955 void
1956 VisitOMPCancellationPointDirective(const OMPCancellationPointDirective *D);
Alexey Bataev80909872015-07-02 11:25:17 +00001957 void VisitOMPCancelDirective(const OMPCancelDirective *D);
Alexey Bataev6125da92014-07-21 11:26:11 +00001958 void VisitOMPFlushDirective(const OMPFlushDirective *D);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001959 void VisitOMPOrderedDirective(const OMPOrderedDirective *D);
Alexey Bataev0162e452014-07-22 10:10:35 +00001960 void VisitOMPAtomicDirective(const OMPAtomicDirective *D);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001961 void VisitOMPTargetDirective(const OMPTargetDirective *D);
Michael Wong65f367f2015-07-21 13:44:28 +00001962 void VisitOMPTargetDataDirective(const OMPTargetDataDirective *D);
Samuel Antaodf67fc42016-01-19 19:15:56 +00001963 void VisitOMPTargetEnterDataDirective(const OMPTargetEnterDataDirective *D);
Samuel Antao72590762016-01-19 20:04:50 +00001964 void VisitOMPTargetExitDataDirective(const OMPTargetExitDataDirective *D);
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00001965 void VisitOMPTargetParallelDirective(const OMPTargetParallelDirective *D);
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00001966 void
1967 VisitOMPTargetParallelForDirective(const OMPTargetParallelForDirective *D);
Alexey Bataev13314bf2014-10-09 04:18:56 +00001968 void VisitOMPTeamsDirective(const OMPTeamsDirective *D);
Alexey Bataev49f6e782015-12-01 04:18:41 +00001969 void VisitOMPTaskLoopDirective(const OMPTaskLoopDirective *D);
Alexey Bataev0a6ed842015-12-03 09:40:15 +00001970 void VisitOMPTaskLoopSimdDirective(const OMPTaskLoopSimdDirective *D);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00001971 void VisitOMPDistributeDirective(const OMPDistributeDirective *D);
Carlo Bertolli9925f152016-06-27 14:55:37 +00001972 void VisitOMPDistributeParallelForDirective(
1973 const OMPDistributeParallelForDirective *D);
Kelvin Li4a39add2016-07-05 05:00:15 +00001974 void VisitOMPDistributeParallelForSimdDirective(
1975 const OMPDistributeParallelForSimdDirective *D);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001976
Guy Benyei11169dd2012-12-18 14:30:41 +00001977private:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001978 void AddDeclarationNameInfo(const Stmt *S);
Guy Benyei11169dd2012-12-18 14:30:41 +00001979 void AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier);
James Y Knight04ec5bf2015-12-24 02:59:37 +00001980 void AddExplicitTemplateArgs(const TemplateArgumentLoc *A,
1981 unsigned NumTemplateArgs);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001982 void AddMemberRef(const FieldDecl *D, SourceLocation L);
1983 void AddStmt(const Stmt *S);
1984 void AddDecl(const Decl *D, bool isFirst = true);
Guy Benyei11169dd2012-12-18 14:30:41 +00001985 void AddTypeLoc(TypeSourceInfo *TI);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001986 void EnqueueChildren(const Stmt *S);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001987 void EnqueueChildren(const OMPClause *S);
Guy Benyei11169dd2012-12-18 14:30:41 +00001988};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001989} // end anonyous namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00001990
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001991void EnqueueVisitor::AddDeclarationNameInfo(const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001992 // 'S' should always be non-null, since it comes from the
1993 // statement we are visiting.
1994 WL.push_back(DeclarationNameInfoVisit(S, Parent));
1995}
1996
1997void
1998EnqueueVisitor::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
1999 if (Qualifier)
2000 WL.push_back(NestedNameSpecifierLocVisit(Qualifier, Parent));
2001}
2002
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002003void EnqueueVisitor::AddStmt(const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002004 if (S)
2005 WL.push_back(StmtVisit(S, Parent));
2006}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002007void EnqueueVisitor::AddDecl(const Decl *D, bool isFirst) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002008 if (D)
2009 WL.push_back(DeclVisit(D, Parent, isFirst));
2010}
James Y Knight04ec5bf2015-12-24 02:59:37 +00002011void EnqueueVisitor::AddExplicitTemplateArgs(const TemplateArgumentLoc *A,
2012 unsigned NumTemplateArgs) {
2013 WL.push_back(ExplicitTemplateArgsVisit(A, A + NumTemplateArgs, Parent));
Guy Benyei11169dd2012-12-18 14:30:41 +00002014}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002015void EnqueueVisitor::AddMemberRef(const FieldDecl *D, SourceLocation L) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002016 if (D)
2017 WL.push_back(MemberRefVisit(D, L, Parent));
2018}
2019void EnqueueVisitor::AddTypeLoc(TypeSourceInfo *TI) {
2020 if (TI)
2021 WL.push_back(TypeLocVisit(TI->getTypeLoc(), Parent));
2022 }
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002023void EnqueueVisitor::EnqueueChildren(const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002024 unsigned size = WL.size();
Benjamin Kramer642f1732015-07-02 21:03:14 +00002025 for (const Stmt *SubStmt : S->children()) {
2026 AddStmt(SubStmt);
Guy Benyei11169dd2012-12-18 14:30:41 +00002027 }
2028 if (size == WL.size())
2029 return;
2030 // Now reverse the entries we just added. This will match the DFS
2031 // ordering performed by the worklist.
2032 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2033 std::reverse(I, E);
2034}
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002035namespace {
2036class OMPClauseEnqueue : public ConstOMPClauseVisitor<OMPClauseEnqueue> {
2037 EnqueueVisitor *Visitor;
Alexey Bataev756c1962013-09-24 03:17:45 +00002038 /// \brief Process clauses with list of variables.
2039 template <typename T>
2040 void VisitOMPClauseList(T *Node);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002041public:
2042 OMPClauseEnqueue(EnqueueVisitor *Visitor) : Visitor(Visitor) { }
2043#define OPENMP_CLAUSE(Name, Class) \
2044 void Visit##Class(const Class *C);
2045#include "clang/Basic/OpenMPKinds.def"
Alexey Bataev3392d762016-02-16 11:18:12 +00002046 void VisitOMPClauseWithPreInit(const OMPClauseWithPreInit *C);
Alexey Bataev005248a2016-02-25 05:25:57 +00002047 void VisitOMPClauseWithPostUpdate(const OMPClauseWithPostUpdate *C);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002048};
2049
Alexey Bataev3392d762016-02-16 11:18:12 +00002050void OMPClauseEnqueue::VisitOMPClauseWithPreInit(
2051 const OMPClauseWithPreInit *C) {
2052 Visitor->AddStmt(C->getPreInitStmt());
2053}
2054
Alexey Bataev005248a2016-02-25 05:25:57 +00002055void OMPClauseEnqueue::VisitOMPClauseWithPostUpdate(
2056 const OMPClauseWithPostUpdate *C) {
Alexey Bataev37e594c2016-03-04 07:21:16 +00002057 VisitOMPClauseWithPreInit(C);
Alexey Bataev005248a2016-02-25 05:25:57 +00002058 Visitor->AddStmt(C->getPostUpdateExpr());
2059}
2060
Alexey Bataevaadd52e2014-02-13 05:29:23 +00002061void OMPClauseEnqueue::VisitOMPIfClause(const OMPIfClause *C) {
2062 Visitor->AddStmt(C->getCondition());
2063}
2064
Alexey Bataev3778b602014-07-17 07:32:53 +00002065void OMPClauseEnqueue::VisitOMPFinalClause(const OMPFinalClause *C) {
2066 Visitor->AddStmt(C->getCondition());
2067}
2068
Alexey Bataev568a8332014-03-06 06:15:19 +00002069void OMPClauseEnqueue::VisitOMPNumThreadsClause(const OMPNumThreadsClause *C) {
2070 Visitor->AddStmt(C->getNumThreads());
2071}
2072
Alexey Bataev62c87d22014-03-21 04:51:18 +00002073void OMPClauseEnqueue::VisitOMPSafelenClause(const OMPSafelenClause *C) {
2074 Visitor->AddStmt(C->getSafelen());
2075}
2076
Alexey Bataev66b15b52015-08-21 11:14:16 +00002077void OMPClauseEnqueue::VisitOMPSimdlenClause(const OMPSimdlenClause *C) {
2078 Visitor->AddStmt(C->getSimdlen());
2079}
2080
Alexander Musman8bd31e62014-05-27 15:12:19 +00002081void OMPClauseEnqueue::VisitOMPCollapseClause(const OMPCollapseClause *C) {
2082 Visitor->AddStmt(C->getNumForLoops());
2083}
2084
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002085void OMPClauseEnqueue::VisitOMPDefaultClause(const OMPDefaultClause *C) { }
Alexey Bataev756c1962013-09-24 03:17:45 +00002086
Alexey Bataevbcbadb62014-05-06 06:04:14 +00002087void OMPClauseEnqueue::VisitOMPProcBindClause(const OMPProcBindClause *C) { }
2088
Alexey Bataev56dafe82014-06-20 07:16:17 +00002089void OMPClauseEnqueue::VisitOMPScheduleClause(const OMPScheduleClause *C) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002090 VisitOMPClauseWithPreInit(C);
Alexey Bataev56dafe82014-06-20 07:16:17 +00002091 Visitor->AddStmt(C->getChunkSize());
2092}
2093
Alexey Bataev10e775f2015-07-30 11:36:16 +00002094void OMPClauseEnqueue::VisitOMPOrderedClause(const OMPOrderedClause *C) {
2095 Visitor->AddStmt(C->getNumForLoops());
2096}
Alexey Bataev142e1fc2014-06-20 09:44:06 +00002097
Alexey Bataev236070f2014-06-20 11:19:47 +00002098void OMPClauseEnqueue::VisitOMPNowaitClause(const OMPNowaitClause *) {}
2099
Alexey Bataev7aea99a2014-07-17 12:19:31 +00002100void OMPClauseEnqueue::VisitOMPUntiedClause(const OMPUntiedClause *) {}
2101
Alexey Bataev74ba3a52014-07-17 12:47:03 +00002102void OMPClauseEnqueue::VisitOMPMergeableClause(const OMPMergeableClause *) {}
2103
Alexey Bataevf98b00c2014-07-23 02:27:21 +00002104void OMPClauseEnqueue::VisitOMPReadClause(const OMPReadClause *) {}
2105
Alexey Bataevdea47612014-07-23 07:46:59 +00002106void OMPClauseEnqueue::VisitOMPWriteClause(const OMPWriteClause *) {}
2107
Alexey Bataev67a4f222014-07-23 10:25:33 +00002108void OMPClauseEnqueue::VisitOMPUpdateClause(const OMPUpdateClause *) {}
2109
Alexey Bataev459dec02014-07-24 06:46:57 +00002110void OMPClauseEnqueue::VisitOMPCaptureClause(const OMPCaptureClause *) {}
2111
Alexey Bataev82bad8b2014-07-24 08:55:34 +00002112void OMPClauseEnqueue::VisitOMPSeqCstClause(const OMPSeqCstClause *) {}
2113
Alexey Bataev346265e2015-09-25 10:37:12 +00002114void OMPClauseEnqueue::VisitOMPThreadsClause(const OMPThreadsClause *) {}
2115
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002116void OMPClauseEnqueue::VisitOMPSIMDClause(const OMPSIMDClause *) {}
2117
Alexey Bataevb825de12015-12-07 10:51:44 +00002118void OMPClauseEnqueue::VisitOMPNogroupClause(const OMPNogroupClause *) {}
2119
Michael Wonge710d542015-08-07 16:16:36 +00002120void OMPClauseEnqueue::VisitOMPDeviceClause(const OMPDeviceClause *C) {
2121 Visitor->AddStmt(C->getDevice());
2122}
2123
Kelvin Li099bb8c2015-11-24 20:50:12 +00002124void OMPClauseEnqueue::VisitOMPNumTeamsClause(const OMPNumTeamsClause *C) {
2125 Visitor->AddStmt(C->getNumTeams());
2126}
2127
Kelvin Lia15fb1a2015-11-27 18:47:36 +00002128void OMPClauseEnqueue::VisitOMPThreadLimitClause(const OMPThreadLimitClause *C) {
2129 Visitor->AddStmt(C->getThreadLimit());
2130}
2131
Alexey Bataeva0569352015-12-01 10:17:31 +00002132void OMPClauseEnqueue::VisitOMPPriorityClause(const OMPPriorityClause *C) {
2133 Visitor->AddStmt(C->getPriority());
2134}
2135
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00002136void OMPClauseEnqueue::VisitOMPGrainsizeClause(const OMPGrainsizeClause *C) {
2137 Visitor->AddStmt(C->getGrainsize());
2138}
2139
Alexey Bataev382967a2015-12-08 12:06:20 +00002140void OMPClauseEnqueue::VisitOMPNumTasksClause(const OMPNumTasksClause *C) {
2141 Visitor->AddStmt(C->getNumTasks());
2142}
2143
Alexey Bataev28c75412015-12-15 08:19:24 +00002144void OMPClauseEnqueue::VisitOMPHintClause(const OMPHintClause *C) {
2145 Visitor->AddStmt(C->getHint());
2146}
2147
Alexey Bataev756c1962013-09-24 03:17:45 +00002148template<typename T>
2149void OMPClauseEnqueue::VisitOMPClauseList(T *Node) {
Alexey Bataev03b340a2014-10-21 03:16:40 +00002150 for (const auto *I : Node->varlists()) {
Aaron Ballman2205d2a2014-03-14 15:55:35 +00002151 Visitor->AddStmt(I);
Alexey Bataev03b340a2014-10-21 03:16:40 +00002152 }
Alexey Bataev756c1962013-09-24 03:17:45 +00002153}
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002154
2155void OMPClauseEnqueue::VisitOMPPrivateClause(const OMPPrivateClause *C) {
Alexey Bataev756c1962013-09-24 03:17:45 +00002156 VisitOMPClauseList(C);
Alexey Bataev03b340a2014-10-21 03:16:40 +00002157 for (const auto *E : C->private_copies()) {
2158 Visitor->AddStmt(E);
2159 }
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002160}
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002161void OMPClauseEnqueue::VisitOMPFirstprivateClause(
2162 const OMPFirstprivateClause *C) {
2163 VisitOMPClauseList(C);
Alexey Bataev417089f2016-02-17 13:19:37 +00002164 VisitOMPClauseWithPreInit(C);
2165 for (const auto *E : C->private_copies()) {
2166 Visitor->AddStmt(E);
2167 }
2168 for (const auto *E : C->inits()) {
2169 Visitor->AddStmt(E);
2170 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002171}
Alexander Musman1bb328c2014-06-04 13:06:39 +00002172void OMPClauseEnqueue::VisitOMPLastprivateClause(
2173 const OMPLastprivateClause *C) {
2174 VisitOMPClauseList(C);
Alexey Bataev005248a2016-02-25 05:25:57 +00002175 VisitOMPClauseWithPostUpdate(C);
Alexey Bataev38e89532015-04-16 04:54:05 +00002176 for (auto *E : C->private_copies()) {
2177 Visitor->AddStmt(E);
2178 }
2179 for (auto *E : C->source_exprs()) {
2180 Visitor->AddStmt(E);
2181 }
2182 for (auto *E : C->destination_exprs()) {
2183 Visitor->AddStmt(E);
2184 }
2185 for (auto *E : C->assignment_ops()) {
2186 Visitor->AddStmt(E);
2187 }
Alexander Musman1bb328c2014-06-04 13:06:39 +00002188}
Alexey Bataev758e55e2013-09-06 18:03:48 +00002189void OMPClauseEnqueue::VisitOMPSharedClause(const OMPSharedClause *C) {
Alexey Bataev756c1962013-09-24 03:17:45 +00002190 VisitOMPClauseList(C);
Alexey Bataev758e55e2013-09-06 18:03:48 +00002191}
Alexey Bataevc5e02582014-06-16 07:08:35 +00002192void OMPClauseEnqueue::VisitOMPReductionClause(const OMPReductionClause *C) {
2193 VisitOMPClauseList(C);
Alexey Bataev61205072016-03-02 04:57:40 +00002194 VisitOMPClauseWithPostUpdate(C);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00002195 for (auto *E : C->privates()) {
2196 Visitor->AddStmt(E);
2197 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002198 for (auto *E : C->lhs_exprs()) {
2199 Visitor->AddStmt(E);
2200 }
2201 for (auto *E : C->rhs_exprs()) {
2202 Visitor->AddStmt(E);
2203 }
2204 for (auto *E : C->reduction_ops()) {
2205 Visitor->AddStmt(E);
2206 }
Alexey Bataevc5e02582014-06-16 07:08:35 +00002207}
Alexander Musman8dba6642014-04-22 13:09:42 +00002208void OMPClauseEnqueue::VisitOMPLinearClause(const OMPLinearClause *C) {
2209 VisitOMPClauseList(C);
Alexey Bataev78849fb2016-03-09 09:49:00 +00002210 VisitOMPClauseWithPostUpdate(C);
Alexey Bataevbd9fec12015-08-18 06:47:21 +00002211 for (const auto *E : C->privates()) {
2212 Visitor->AddStmt(E);
2213 }
Alexander Musman3276a272015-03-21 10:12:56 +00002214 for (const auto *E : C->inits()) {
2215 Visitor->AddStmt(E);
2216 }
2217 for (const auto *E : C->updates()) {
2218 Visitor->AddStmt(E);
2219 }
2220 for (const auto *E : C->finals()) {
2221 Visitor->AddStmt(E);
2222 }
Alexander Musman8dba6642014-04-22 13:09:42 +00002223 Visitor->AddStmt(C->getStep());
Alexander Musman3276a272015-03-21 10:12:56 +00002224 Visitor->AddStmt(C->getCalcStep());
Alexander Musman8dba6642014-04-22 13:09:42 +00002225}
Alexander Musmanf0d76e72014-05-29 14:36:25 +00002226void OMPClauseEnqueue::VisitOMPAlignedClause(const OMPAlignedClause *C) {
2227 VisitOMPClauseList(C);
2228 Visitor->AddStmt(C->getAlignment());
2229}
Alexey Bataevd48bcd82014-03-31 03:36:38 +00002230void OMPClauseEnqueue::VisitOMPCopyinClause(const OMPCopyinClause *C) {
2231 VisitOMPClauseList(C);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00002232 for (auto *E : C->source_exprs()) {
2233 Visitor->AddStmt(E);
2234 }
2235 for (auto *E : C->destination_exprs()) {
2236 Visitor->AddStmt(E);
2237 }
2238 for (auto *E : C->assignment_ops()) {
2239 Visitor->AddStmt(E);
2240 }
Alexey Bataevd48bcd82014-03-31 03:36:38 +00002241}
Alexey Bataevbae9a792014-06-27 10:37:06 +00002242void
2243OMPClauseEnqueue::VisitOMPCopyprivateClause(const OMPCopyprivateClause *C) {
2244 VisitOMPClauseList(C);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002245 for (auto *E : C->source_exprs()) {
2246 Visitor->AddStmt(E);
2247 }
2248 for (auto *E : C->destination_exprs()) {
2249 Visitor->AddStmt(E);
2250 }
2251 for (auto *E : C->assignment_ops()) {
2252 Visitor->AddStmt(E);
2253 }
Alexey Bataevbae9a792014-06-27 10:37:06 +00002254}
Alexey Bataev6125da92014-07-21 11:26:11 +00002255void OMPClauseEnqueue::VisitOMPFlushClause(const OMPFlushClause *C) {
2256 VisitOMPClauseList(C);
2257}
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00002258void OMPClauseEnqueue::VisitOMPDependClause(const OMPDependClause *C) {
2259 VisitOMPClauseList(C);
2260}
Kelvin Li0bff7af2015-11-23 05:32:03 +00002261void OMPClauseEnqueue::VisitOMPMapClause(const OMPMapClause *C) {
2262 VisitOMPClauseList(C);
2263}
Carlo Bertollib4adf552016-01-15 18:50:31 +00002264void OMPClauseEnqueue::VisitOMPDistScheduleClause(
2265 const OMPDistScheduleClause *C) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002266 VisitOMPClauseWithPreInit(C);
Carlo Bertollib4adf552016-01-15 18:50:31 +00002267 Visitor->AddStmt(C->getChunkSize());
Carlo Bertollib4adf552016-01-15 18:50:31 +00002268}
Alexey Bataev3392d762016-02-16 11:18:12 +00002269void OMPClauseEnqueue::VisitOMPDefaultmapClause(
2270 const OMPDefaultmapClause * /*C*/) {}
Samuel Antao661c0902016-05-26 17:39:58 +00002271void OMPClauseEnqueue::VisitOMPToClause(const OMPToClause *C) {
2272 VisitOMPClauseList(C);
2273}
Samuel Antaoec172c62016-05-26 17:49:04 +00002274void OMPClauseEnqueue::VisitOMPFromClause(const OMPFromClause *C) {
2275 VisitOMPClauseList(C);
2276}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002277}
Alexey Bataev756c1962013-09-24 03:17:45 +00002278
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002279void EnqueueVisitor::EnqueueChildren(const OMPClause *S) {
2280 unsigned size = WL.size();
2281 OMPClauseEnqueue Visitor(this);
2282 Visitor.Visit(S);
2283 if (size == WL.size())
2284 return;
2285 // Now reverse the entries we just added. This will match the DFS
2286 // ordering performed by the worklist.
2287 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2288 std::reverse(I, E);
2289}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002290void EnqueueVisitor::VisitAddrLabelExpr(const AddrLabelExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002291 WL.push_back(LabelRefVisit(E->getLabel(), E->getLabelLoc(), Parent));
2292}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002293void EnqueueVisitor::VisitBlockExpr(const BlockExpr *B) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002294 AddDecl(B->getBlockDecl());
2295}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002296void EnqueueVisitor::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002297 EnqueueChildren(E);
2298 AddTypeLoc(E->getTypeSourceInfo());
2299}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002300void EnqueueVisitor::VisitCompoundStmt(const CompoundStmt *S) {
Pete Cooper57d3f142015-07-30 17:22:52 +00002301 for (auto &I : llvm::reverse(S->body()))
2302 AddStmt(I);
Guy Benyei11169dd2012-12-18 14:30:41 +00002303}
2304void EnqueueVisitor::
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002305VisitMSDependentExistsStmt(const MSDependentExistsStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002306 AddStmt(S->getSubStmt());
2307 AddDeclarationNameInfo(S);
2308 if (NestedNameSpecifierLoc QualifierLoc = S->getQualifierLoc())
2309 AddNestedNameSpecifierLoc(QualifierLoc);
2310}
2311
2312void EnqueueVisitor::
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002313VisitCXXDependentScopeMemberExpr(const CXXDependentScopeMemberExpr *E) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002314 if (E->hasExplicitTemplateArgs())
2315 AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002316 AddDeclarationNameInfo(E);
2317 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
2318 AddNestedNameSpecifierLoc(QualifierLoc);
2319 if (!E->isImplicitAccess())
2320 AddStmt(E->getBase());
2321}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002322void EnqueueVisitor::VisitCXXNewExpr(const CXXNewExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002323 // Enqueue the initializer , if any.
2324 AddStmt(E->getInitializer());
2325 // Enqueue the array size, if any.
2326 AddStmt(E->getArraySize());
2327 // Enqueue the allocated type.
2328 AddTypeLoc(E->getAllocatedTypeSourceInfo());
2329 // Enqueue the placement arguments.
2330 for (unsigned I = E->getNumPlacementArgs(); I > 0; --I)
2331 AddStmt(E->getPlacementArg(I-1));
2332}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002333void EnqueueVisitor::VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CE) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002334 for (unsigned I = CE->getNumArgs(); I > 1 /* Yes, this is 1 */; --I)
2335 AddStmt(CE->getArg(I-1));
2336 AddStmt(CE->getCallee());
2337 AddStmt(CE->getArg(0));
2338}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002339void EnqueueVisitor::VisitCXXPseudoDestructorExpr(
2340 const CXXPseudoDestructorExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002341 // Visit the name of the type being destroyed.
2342 AddTypeLoc(E->getDestroyedTypeInfo());
2343 // Visit the scope type that looks disturbingly like the nested-name-specifier
2344 // but isn't.
2345 AddTypeLoc(E->getScopeTypeInfo());
2346 // Visit the nested-name-specifier.
2347 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
2348 AddNestedNameSpecifierLoc(QualifierLoc);
2349 // Visit base expression.
2350 AddStmt(E->getBase());
2351}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002352void EnqueueVisitor::VisitCXXScalarValueInitExpr(
2353 const CXXScalarValueInitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002354 AddTypeLoc(E->getTypeSourceInfo());
2355}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002356void EnqueueVisitor::VisitCXXTemporaryObjectExpr(
2357 const CXXTemporaryObjectExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002358 EnqueueChildren(E);
2359 AddTypeLoc(E->getTypeSourceInfo());
2360}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002361void EnqueueVisitor::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002362 EnqueueChildren(E);
2363 if (E->isTypeOperand())
2364 AddTypeLoc(E->getTypeOperandSourceInfo());
2365}
2366
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002367void EnqueueVisitor::VisitCXXUnresolvedConstructExpr(
2368 const CXXUnresolvedConstructExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002369 EnqueueChildren(E);
2370 AddTypeLoc(E->getTypeSourceInfo());
2371}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002372void EnqueueVisitor::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002373 EnqueueChildren(E);
2374 if (E->isTypeOperand())
2375 AddTypeLoc(E->getTypeOperandSourceInfo());
2376}
2377
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002378void EnqueueVisitor::VisitCXXCatchStmt(const CXXCatchStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002379 EnqueueChildren(S);
2380 AddDecl(S->getExceptionDecl());
2381}
2382
Argyrios Kyrtzidis99891242014-11-13 09:03:21 +00002383void EnqueueVisitor::VisitCXXForRangeStmt(const CXXForRangeStmt *S) {
Argyrios Kyrtzidiscde70692014-11-13 09:50:19 +00002384 AddStmt(S->getBody());
Argyrios Kyrtzidis99891242014-11-13 09:03:21 +00002385 AddStmt(S->getRangeInit());
Argyrios Kyrtzidiscde70692014-11-13 09:50:19 +00002386 AddDecl(S->getLoopVariable());
Argyrios Kyrtzidis99891242014-11-13 09:03:21 +00002387}
2388
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002389void EnqueueVisitor::VisitDeclRefExpr(const DeclRefExpr *DR) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002390 if (DR->hasExplicitTemplateArgs())
2391 AddExplicitTemplateArgs(DR->getTemplateArgs(), DR->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002392 WL.push_back(DeclRefExprParts(DR, Parent));
2393}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002394void EnqueueVisitor::VisitDependentScopeDeclRefExpr(
2395 const DependentScopeDeclRefExpr *E) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002396 if (E->hasExplicitTemplateArgs())
2397 AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002398 AddDeclarationNameInfo(E);
2399 AddNestedNameSpecifierLoc(E->getQualifierLoc());
2400}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002401void EnqueueVisitor::VisitDeclStmt(const DeclStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002402 unsigned size = WL.size();
2403 bool isFirst = true;
Aaron Ballman535bbcc2014-03-14 17:01:24 +00002404 for (const auto *D : S->decls()) {
2405 AddDecl(D, isFirst);
Guy Benyei11169dd2012-12-18 14:30:41 +00002406 isFirst = false;
2407 }
2408 if (size == WL.size())
2409 return;
2410 // Now reverse the entries we just added. This will match the DFS
2411 // ordering performed by the worklist.
2412 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2413 std::reverse(I, E);
2414}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002415void EnqueueVisitor::VisitDesignatedInitExpr(const DesignatedInitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002416 AddStmt(E->getInit());
David Majnemerf7e36092016-06-23 00:15:04 +00002417 for (const DesignatedInitExpr::Designator &D :
2418 llvm::reverse(E->designators())) {
2419 if (D.isFieldDesignator()) {
2420 if (FieldDecl *Field = D.getField())
2421 AddMemberRef(Field, D.getFieldLoc());
Guy Benyei11169dd2012-12-18 14:30:41 +00002422 continue;
2423 }
David Majnemerf7e36092016-06-23 00:15:04 +00002424 if (D.isArrayDesignator()) {
2425 AddStmt(E->getArrayIndex(D));
Guy Benyei11169dd2012-12-18 14:30:41 +00002426 continue;
2427 }
David Majnemerf7e36092016-06-23 00:15:04 +00002428 assert(D.isArrayRangeDesignator() && "Unknown designator kind");
2429 AddStmt(E->getArrayRangeEnd(D));
2430 AddStmt(E->getArrayRangeStart(D));
Guy Benyei11169dd2012-12-18 14:30:41 +00002431 }
2432}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002433void EnqueueVisitor::VisitExplicitCastExpr(const ExplicitCastExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002434 EnqueueChildren(E);
2435 AddTypeLoc(E->getTypeInfoAsWritten());
2436}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002437void EnqueueVisitor::VisitForStmt(const ForStmt *FS) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002438 AddStmt(FS->getBody());
2439 AddStmt(FS->getInc());
2440 AddStmt(FS->getCond());
2441 AddDecl(FS->getConditionVariable());
2442 AddStmt(FS->getInit());
2443}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002444void EnqueueVisitor::VisitGotoStmt(const GotoStmt *GS) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002445 WL.push_back(LabelRefVisit(GS->getLabel(), GS->getLabelLoc(), Parent));
2446}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002447void EnqueueVisitor::VisitIfStmt(const IfStmt *If) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002448 AddStmt(If->getElse());
2449 AddStmt(If->getThen());
2450 AddStmt(If->getCond());
2451 AddDecl(If->getConditionVariable());
2452}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002453void EnqueueVisitor::VisitInitListExpr(const InitListExpr *IE) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002454 // We care about the syntactic form of the initializer list, only.
2455 if (InitListExpr *Syntactic = IE->getSyntacticForm())
2456 IE = Syntactic;
2457 EnqueueChildren(IE);
2458}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002459void EnqueueVisitor::VisitMemberExpr(const MemberExpr *M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002460 WL.push_back(MemberExprParts(M, Parent));
2461
2462 // If the base of the member access expression is an implicit 'this', don't
2463 // visit it.
2464 // FIXME: If we ever want to show these implicit accesses, this will be
2465 // unfortunate. However, clang_getCursor() relies on this behavior.
Argyrios Kyrtzidis58d0e7a2015-03-13 04:40:07 +00002466 if (M->isImplicitAccess())
2467 return;
2468
2469 // Ignore base anonymous struct/union fields, otherwise they will shadow the
2470 // real field that that we are interested in.
2471 if (auto *SubME = dyn_cast<MemberExpr>(M->getBase())) {
2472 if (auto *FD = dyn_cast_or_null<FieldDecl>(SubME->getMemberDecl())) {
2473 if (FD->isAnonymousStructOrUnion()) {
2474 AddStmt(SubME->getBase());
2475 return;
2476 }
2477 }
2478 }
2479
2480 AddStmt(M->getBase());
Guy Benyei11169dd2012-12-18 14:30:41 +00002481}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002482void EnqueueVisitor::VisitObjCEncodeExpr(const ObjCEncodeExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002483 AddTypeLoc(E->getEncodedTypeSourceInfo());
2484}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002485void EnqueueVisitor::VisitObjCMessageExpr(const ObjCMessageExpr *M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002486 EnqueueChildren(M);
2487 AddTypeLoc(M->getClassReceiverTypeInfo());
2488}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002489void EnqueueVisitor::VisitOffsetOfExpr(const OffsetOfExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002490 // Visit the components of the offsetof expression.
2491 for (unsigned N = E->getNumComponents(), I = N; I > 0; --I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002492 const OffsetOfNode &Node = E->getComponent(I-1);
2493 switch (Node.getKind()) {
2494 case OffsetOfNode::Array:
2495 AddStmt(E->getIndexExpr(Node.getArrayExprIndex()));
2496 break;
2497 case OffsetOfNode::Field:
2498 AddMemberRef(Node.getField(), Node.getSourceRange().getEnd());
2499 break;
2500 case OffsetOfNode::Identifier:
2501 case OffsetOfNode::Base:
2502 continue;
2503 }
2504 }
2505 // Visit the type into which we're computing the offset.
2506 AddTypeLoc(E->getTypeSourceInfo());
2507}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002508void EnqueueVisitor::VisitOverloadExpr(const OverloadExpr *E) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002509 if (E->hasExplicitTemplateArgs())
2510 AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002511 WL.push_back(OverloadExprParts(E, Parent));
2512}
2513void EnqueueVisitor::VisitUnaryExprOrTypeTraitExpr(
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002514 const UnaryExprOrTypeTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002515 EnqueueChildren(E);
2516 if (E->isArgumentType())
2517 AddTypeLoc(E->getArgumentTypeInfo());
2518}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002519void EnqueueVisitor::VisitStmt(const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002520 EnqueueChildren(S);
2521}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002522void EnqueueVisitor::VisitSwitchStmt(const SwitchStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002523 AddStmt(S->getBody());
2524 AddStmt(S->getCond());
2525 AddDecl(S->getConditionVariable());
2526}
2527
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002528void EnqueueVisitor::VisitWhileStmt(const WhileStmt *W) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002529 AddStmt(W->getBody());
2530 AddStmt(W->getCond());
2531 AddDecl(W->getConditionVariable());
2532}
2533
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002534void EnqueueVisitor::VisitTypeTraitExpr(const TypeTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002535 for (unsigned I = E->getNumArgs(); I > 0; --I)
2536 AddTypeLoc(E->getArg(I-1));
2537}
2538
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002539void EnqueueVisitor::VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002540 AddTypeLoc(E->getQueriedTypeSourceInfo());
2541}
2542
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002543void EnqueueVisitor::VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002544 EnqueueChildren(E);
2545}
2546
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002547void EnqueueVisitor::VisitUnresolvedMemberExpr(const UnresolvedMemberExpr *U) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002548 VisitOverloadExpr(U);
2549 if (!U->isImplicitAccess())
2550 AddStmt(U->getBase());
2551}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002552void EnqueueVisitor::VisitVAArgExpr(const VAArgExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002553 AddStmt(E->getSubExpr());
2554 AddTypeLoc(E->getWrittenTypeInfo());
2555}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002556void EnqueueVisitor::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002557 WL.push_back(SizeOfPackExprParts(E, Parent));
2558}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002559void EnqueueVisitor::VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002560 // If the opaque value has a source expression, just transparently
2561 // visit that. This is useful for (e.g.) pseudo-object expressions.
2562 if (Expr *SourceExpr = E->getSourceExpr())
2563 return Visit(SourceExpr);
2564}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002565void EnqueueVisitor::VisitLambdaExpr(const LambdaExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002566 AddStmt(E->getBody());
2567 WL.push_back(LambdaExprParts(E, Parent));
2568}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002569void EnqueueVisitor::VisitPseudoObjectExpr(const PseudoObjectExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002570 // Treat the expression like its syntactic form.
2571 Visit(E->getSyntacticForm());
2572}
2573
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002574void EnqueueVisitor::VisitOMPExecutableDirective(
2575 const OMPExecutableDirective *D) {
2576 EnqueueChildren(D);
2577 for (ArrayRef<OMPClause *>::iterator I = D->clauses().begin(),
2578 E = D->clauses().end();
2579 I != E; ++I)
2580 EnqueueChildren(*I);
2581}
2582
Alexander Musman3aaab662014-08-19 11:27:13 +00002583void EnqueueVisitor::VisitOMPLoopDirective(const OMPLoopDirective *D) {
2584 VisitOMPExecutableDirective(D);
2585}
2586
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002587void EnqueueVisitor::VisitOMPParallelDirective(const OMPParallelDirective *D) {
2588 VisitOMPExecutableDirective(D);
2589}
2590
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002591void EnqueueVisitor::VisitOMPSimdDirective(const OMPSimdDirective *D) {
Alexander Musman3aaab662014-08-19 11:27:13 +00002592 VisitOMPLoopDirective(D);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002593}
2594
Alexey Bataevf29276e2014-06-18 04:14:57 +00002595void EnqueueVisitor::VisitOMPForDirective(const OMPForDirective *D) {
Alexander Musman3aaab662014-08-19 11:27:13 +00002596 VisitOMPLoopDirective(D);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002597}
2598
Alexander Musmanf82886e2014-09-18 05:12:34 +00002599void EnqueueVisitor::VisitOMPForSimdDirective(const OMPForSimdDirective *D) {
2600 VisitOMPLoopDirective(D);
2601}
2602
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002603void EnqueueVisitor::VisitOMPSectionsDirective(const OMPSectionsDirective *D) {
2604 VisitOMPExecutableDirective(D);
2605}
2606
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002607void EnqueueVisitor::VisitOMPSectionDirective(const OMPSectionDirective *D) {
2608 VisitOMPExecutableDirective(D);
2609}
2610
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00002611void EnqueueVisitor::VisitOMPSingleDirective(const OMPSingleDirective *D) {
2612 VisitOMPExecutableDirective(D);
2613}
2614
Alexander Musman80c22892014-07-17 08:54:58 +00002615void EnqueueVisitor::VisitOMPMasterDirective(const OMPMasterDirective *D) {
2616 VisitOMPExecutableDirective(D);
2617}
2618
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002619void EnqueueVisitor::VisitOMPCriticalDirective(const OMPCriticalDirective *D) {
2620 VisitOMPExecutableDirective(D);
2621 AddDeclarationNameInfo(D);
2622}
2623
Alexey Bataev4acb8592014-07-07 13:01:15 +00002624void
2625EnqueueVisitor::VisitOMPParallelForDirective(const OMPParallelForDirective *D) {
Alexander Musman3aaab662014-08-19 11:27:13 +00002626 VisitOMPLoopDirective(D);
Alexey Bataev4acb8592014-07-07 13:01:15 +00002627}
2628
Alexander Musmane4e893b2014-09-23 09:33:00 +00002629void EnqueueVisitor::VisitOMPParallelForSimdDirective(
2630 const OMPParallelForSimdDirective *D) {
2631 VisitOMPLoopDirective(D);
2632}
2633
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002634void EnqueueVisitor::VisitOMPParallelSectionsDirective(
2635 const OMPParallelSectionsDirective *D) {
2636 VisitOMPExecutableDirective(D);
2637}
2638
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002639void EnqueueVisitor::VisitOMPTaskDirective(const OMPTaskDirective *D) {
2640 VisitOMPExecutableDirective(D);
2641}
2642
Alexey Bataev68446b72014-07-18 07:47:19 +00002643void
2644EnqueueVisitor::VisitOMPTaskyieldDirective(const OMPTaskyieldDirective *D) {
2645 VisitOMPExecutableDirective(D);
2646}
2647
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002648void EnqueueVisitor::VisitOMPBarrierDirective(const OMPBarrierDirective *D) {
2649 VisitOMPExecutableDirective(D);
2650}
2651
Alexey Bataev2df347a2014-07-18 10:17:07 +00002652void EnqueueVisitor::VisitOMPTaskwaitDirective(const OMPTaskwaitDirective *D) {
2653 VisitOMPExecutableDirective(D);
2654}
2655
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002656void EnqueueVisitor::VisitOMPTaskgroupDirective(
2657 const OMPTaskgroupDirective *D) {
2658 VisitOMPExecutableDirective(D);
2659}
2660
Alexey Bataev6125da92014-07-21 11:26:11 +00002661void EnqueueVisitor::VisitOMPFlushDirective(const OMPFlushDirective *D) {
2662 VisitOMPExecutableDirective(D);
2663}
2664
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002665void EnqueueVisitor::VisitOMPOrderedDirective(const OMPOrderedDirective *D) {
2666 VisitOMPExecutableDirective(D);
2667}
2668
Alexey Bataev0162e452014-07-22 10:10:35 +00002669void EnqueueVisitor::VisitOMPAtomicDirective(const OMPAtomicDirective *D) {
2670 VisitOMPExecutableDirective(D);
2671}
2672
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002673void EnqueueVisitor::VisitOMPTargetDirective(const OMPTargetDirective *D) {
2674 VisitOMPExecutableDirective(D);
2675}
2676
Michael Wong65f367f2015-07-21 13:44:28 +00002677void EnqueueVisitor::VisitOMPTargetDataDirective(const
2678 OMPTargetDataDirective *D) {
2679 VisitOMPExecutableDirective(D);
2680}
2681
Samuel Antaodf67fc42016-01-19 19:15:56 +00002682void EnqueueVisitor::VisitOMPTargetEnterDataDirective(
2683 const OMPTargetEnterDataDirective *D) {
2684 VisitOMPExecutableDirective(D);
2685}
2686
Samuel Antao72590762016-01-19 20:04:50 +00002687void EnqueueVisitor::VisitOMPTargetExitDataDirective(
2688 const OMPTargetExitDataDirective *D) {
2689 VisitOMPExecutableDirective(D);
2690}
2691
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00002692void EnqueueVisitor::VisitOMPTargetParallelDirective(
2693 const OMPTargetParallelDirective *D) {
2694 VisitOMPExecutableDirective(D);
2695}
2696
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00002697void EnqueueVisitor::VisitOMPTargetParallelForDirective(
2698 const OMPTargetParallelForDirective *D) {
2699 VisitOMPLoopDirective(D);
2700}
2701
Alexey Bataev13314bf2014-10-09 04:18:56 +00002702void EnqueueVisitor::VisitOMPTeamsDirective(const OMPTeamsDirective *D) {
2703 VisitOMPExecutableDirective(D);
2704}
2705
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002706void EnqueueVisitor::VisitOMPCancellationPointDirective(
2707 const OMPCancellationPointDirective *D) {
2708 VisitOMPExecutableDirective(D);
2709}
2710
Alexey Bataev80909872015-07-02 11:25:17 +00002711void EnqueueVisitor::VisitOMPCancelDirective(const OMPCancelDirective *D) {
2712 VisitOMPExecutableDirective(D);
2713}
2714
Alexey Bataev49f6e782015-12-01 04:18:41 +00002715void EnqueueVisitor::VisitOMPTaskLoopDirective(const OMPTaskLoopDirective *D) {
2716 VisitOMPLoopDirective(D);
2717}
2718
Alexey Bataev0a6ed842015-12-03 09:40:15 +00002719void EnqueueVisitor::VisitOMPTaskLoopSimdDirective(
2720 const OMPTaskLoopSimdDirective *D) {
2721 VisitOMPLoopDirective(D);
2722}
2723
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002724void EnqueueVisitor::VisitOMPDistributeDirective(
2725 const OMPDistributeDirective *D) {
2726 VisitOMPLoopDirective(D);
2727}
2728
Carlo Bertolli9925f152016-06-27 14:55:37 +00002729void EnqueueVisitor::VisitOMPDistributeParallelForDirective(
2730 const OMPDistributeParallelForDirective *D) {
2731 VisitOMPLoopDirective(D);
2732}
2733
Kelvin Li4a39add2016-07-05 05:00:15 +00002734void EnqueueVisitor::VisitOMPDistributeParallelForSimdDirective(
2735 const OMPDistributeParallelForSimdDirective *D) {
2736 VisitOMPLoopDirective(D);
2737}
2738
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002739void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002740 EnqueueVisitor(WL, MakeCXCursor(S, StmtParent, TU,RegionOfInterest)).Visit(S);
2741}
2742
2743bool CursorVisitor::IsInRegionOfInterest(CXCursor C) {
2744 if (RegionOfInterest.isValid()) {
2745 SourceRange Range = getRawCursorExtent(C);
2746 if (Range.isInvalid() || CompareRegionOfInterest(Range))
2747 return false;
2748 }
2749 return true;
2750}
2751
2752bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) {
2753 while (!WL.empty()) {
2754 // Dequeue the worklist item.
Robert Wilhelm25284cc2013-08-23 16:11:15 +00002755 VisitorJob LI = WL.pop_back_val();
Guy Benyei11169dd2012-12-18 14:30:41 +00002756
2757 // Set the Parent field, then back to its old value once we're done.
2758 SetParentRAII SetParent(Parent, StmtParent, LI.getParent());
2759
2760 switch (LI.getKind()) {
2761 case VisitorJob::DeclVisitKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002762 const Decl *D = cast<DeclVisit>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00002763 if (!D)
2764 continue;
2765
2766 // For now, perform default visitation for Decls.
2767 if (Visit(MakeCXCursor(D, TU, RegionOfInterest,
2768 cast<DeclVisit>(&LI)->isFirst())))
2769 return true;
2770
2771 continue;
2772 }
2773 case VisitorJob::ExplicitTemplateArgsVisitKind: {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002774 for (const TemplateArgumentLoc &Arg :
2775 *cast<ExplicitTemplateArgsVisit>(&LI)) {
2776 if (VisitTemplateArgumentLoc(Arg))
Guy Benyei11169dd2012-12-18 14:30:41 +00002777 return true;
2778 }
2779 continue;
2780 }
2781 case VisitorJob::TypeLocVisitKind: {
2782 // Perform default visitation for TypeLocs.
2783 if (Visit(cast<TypeLocVisit>(&LI)->get()))
2784 return true;
2785 continue;
2786 }
2787 case VisitorJob::LabelRefVisitKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002788 const LabelDecl *LS = cast<LabelRefVisit>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00002789 if (LabelStmt *stmt = LS->getStmt()) {
2790 if (Visit(MakeCursorLabelRef(stmt, cast<LabelRefVisit>(&LI)->getLoc(),
2791 TU))) {
2792 return true;
2793 }
2794 }
2795 continue;
2796 }
2797
2798 case VisitorJob::NestedNameSpecifierLocVisitKind: {
2799 NestedNameSpecifierLocVisit *V = cast<NestedNameSpecifierLocVisit>(&LI);
2800 if (VisitNestedNameSpecifierLoc(V->get()))
2801 return true;
2802 continue;
2803 }
2804
2805 case VisitorJob::DeclarationNameInfoVisitKind: {
2806 if (VisitDeclarationNameInfo(cast<DeclarationNameInfoVisit>(&LI)
2807 ->get()))
2808 return true;
2809 continue;
2810 }
2811 case VisitorJob::MemberRefVisitKind: {
2812 MemberRefVisit *V = cast<MemberRefVisit>(&LI);
2813 if (Visit(MakeCursorMemberRef(V->get(), V->getLoc(), TU)))
2814 return true;
2815 continue;
2816 }
2817 case VisitorJob::StmtVisitKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002818 const Stmt *S = cast<StmtVisit>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00002819 if (!S)
2820 continue;
2821
2822 // Update the current cursor.
2823 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU, RegionOfInterest);
2824 if (!IsInRegionOfInterest(Cursor))
2825 continue;
2826 switch (Visitor(Cursor, Parent, ClientData)) {
2827 case CXChildVisit_Break: return true;
2828 case CXChildVisit_Continue: break;
2829 case CXChildVisit_Recurse:
2830 if (PostChildrenVisitor)
Craig Topper69186e72014-06-08 08:38:04 +00002831 WL.push_back(PostChildrenVisit(nullptr, Cursor));
Guy Benyei11169dd2012-12-18 14:30:41 +00002832 EnqueueWorkList(WL, S);
2833 break;
2834 }
2835 continue;
2836 }
2837 case VisitorJob::MemberExprPartsKind: {
2838 // Handle the other pieces in the MemberExpr besides the base.
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002839 const MemberExpr *M = cast<MemberExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00002840
2841 // Visit the nested-name-specifier
2842 if (NestedNameSpecifierLoc QualifierLoc = M->getQualifierLoc())
2843 if (VisitNestedNameSpecifierLoc(QualifierLoc))
2844 return true;
2845
2846 // Visit the declaration name.
2847 if (VisitDeclarationNameInfo(M->getMemberNameInfo()))
2848 return true;
2849
2850 // Visit the explicitly-specified template arguments, if any.
2851 if (M->hasExplicitTemplateArgs()) {
2852 for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(),
2853 *ArgEnd = Arg + M->getNumTemplateArgs();
2854 Arg != ArgEnd; ++Arg) {
2855 if (VisitTemplateArgumentLoc(*Arg))
2856 return true;
2857 }
2858 }
2859 continue;
2860 }
2861 case VisitorJob::DeclRefExprPartsKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002862 const DeclRefExpr *DR = cast<DeclRefExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00002863 // Visit nested-name-specifier, if present.
2864 if (NestedNameSpecifierLoc QualifierLoc = DR->getQualifierLoc())
2865 if (VisitNestedNameSpecifierLoc(QualifierLoc))
2866 return true;
2867 // Visit declaration name.
2868 if (VisitDeclarationNameInfo(DR->getNameInfo()))
2869 return true;
2870 continue;
2871 }
2872 case VisitorJob::OverloadExprPartsKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002873 const OverloadExpr *O = cast<OverloadExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00002874 // Visit the nested-name-specifier.
2875 if (NestedNameSpecifierLoc QualifierLoc = O->getQualifierLoc())
2876 if (VisitNestedNameSpecifierLoc(QualifierLoc))
2877 return true;
2878 // Visit the declaration name.
2879 if (VisitDeclarationNameInfo(O->getNameInfo()))
2880 return true;
2881 // Visit the overloaded declaration reference.
2882 if (Visit(MakeCursorOverloadedDeclRef(O, TU)))
2883 return true;
2884 continue;
2885 }
2886 case VisitorJob::SizeOfPackExprPartsKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002887 const SizeOfPackExpr *E = cast<SizeOfPackExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00002888 NamedDecl *Pack = E->getPack();
2889 if (isa<TemplateTypeParmDecl>(Pack)) {
2890 if (Visit(MakeCursorTypeRef(cast<TemplateTypeParmDecl>(Pack),
2891 E->getPackLoc(), TU)))
2892 return true;
2893
2894 continue;
2895 }
2896
2897 if (isa<TemplateTemplateParmDecl>(Pack)) {
2898 if (Visit(MakeCursorTemplateRef(cast<TemplateTemplateParmDecl>(Pack),
2899 E->getPackLoc(), TU)))
2900 return true;
2901
2902 continue;
2903 }
2904
2905 // Non-type template parameter packs and function parameter packs are
2906 // treated like DeclRefExpr cursors.
2907 continue;
2908 }
2909
2910 case VisitorJob::LambdaExprPartsKind: {
2911 // Visit captures.
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002912 const LambdaExpr *E = cast<LambdaExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00002913 for (LambdaExpr::capture_iterator C = E->explicit_capture_begin(),
2914 CEnd = E->explicit_capture_end();
2915 C != CEnd; ++C) {
Richard Smithba71c082013-05-16 06:20:58 +00002916 // FIXME: Lambda init-captures.
2917 if (!C->capturesVariable())
Guy Benyei11169dd2012-12-18 14:30:41 +00002918 continue;
Richard Smithba71c082013-05-16 06:20:58 +00002919
Guy Benyei11169dd2012-12-18 14:30:41 +00002920 if (Visit(MakeCursorVariableRef(C->getCapturedVar(),
2921 C->getLocation(),
2922 TU)))
2923 return true;
2924 }
2925
2926 // Visit parameters and return type, if present.
2927 if (E->hasExplicitParameters() || E->hasExplicitResultType()) {
2928 TypeLoc TL = E->getCallOperator()->getTypeSourceInfo()->getTypeLoc();
2929 if (E->hasExplicitParameters() && E->hasExplicitResultType()) {
2930 // Visit the whole type.
2931 if (Visit(TL))
2932 return true;
David Blaikie6adc78e2013-02-18 22:06:02 +00002933 } else if (FunctionProtoTypeLoc Proto =
2934 TL.getAs<FunctionProtoTypeLoc>()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002935 if (E->hasExplicitParameters()) {
2936 // Visit parameters.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00002937 for (unsigned I = 0, N = Proto.getNumParams(); I != N; ++I)
2938 if (Visit(MakeCXCursor(Proto.getParam(I), TU)))
Guy Benyei11169dd2012-12-18 14:30:41 +00002939 return true;
2940 } else {
2941 // Visit result type.
Alp Toker42a16a62014-01-25 23:51:36 +00002942 if (Visit(Proto.getReturnLoc()))
Guy Benyei11169dd2012-12-18 14:30:41 +00002943 return true;
2944 }
2945 }
2946 }
2947 break;
2948 }
2949
2950 case VisitorJob::PostChildrenVisitKind:
2951 if (PostChildrenVisitor(Parent, ClientData))
2952 return true;
2953 break;
2954 }
2955 }
2956 return false;
2957}
2958
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002959bool CursorVisitor::Visit(const Stmt *S) {
Craig Topper69186e72014-06-08 08:38:04 +00002960 VisitorWorkList *WL = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00002961 if (!WorkListFreeList.empty()) {
2962 WL = WorkListFreeList.back();
2963 WL->clear();
2964 WorkListFreeList.pop_back();
2965 }
2966 else {
2967 WL = new VisitorWorkList();
2968 WorkListCache.push_back(WL);
2969 }
2970 EnqueueWorkList(*WL, S);
2971 bool result = RunVisitorWorkList(*WL);
2972 WorkListFreeList.push_back(WL);
2973 return result;
2974}
2975
2976namespace {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002977typedef SmallVector<SourceRange, 4> RefNamePieces;
James Y Knight04ec5bf2015-12-24 02:59:37 +00002978RefNamePieces buildPieces(unsigned NameFlags, bool IsMemberRefExpr,
2979 const DeclarationNameInfo &NI, SourceRange QLoc,
2980 const SourceRange *TemplateArgsLoc = nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002981 const bool WantQualifier = NameFlags & CXNameRange_WantQualifier;
2982 const bool WantTemplateArgs = NameFlags & CXNameRange_WantTemplateArgs;
2983 const bool WantSinglePiece = NameFlags & CXNameRange_WantSinglePiece;
2984
2985 const DeclarationName::NameKind Kind = NI.getName().getNameKind();
2986
2987 RefNamePieces Pieces;
2988
2989 if (WantQualifier && QLoc.isValid())
2990 Pieces.push_back(QLoc);
2991
2992 if (Kind != DeclarationName::CXXOperatorName || IsMemberRefExpr)
2993 Pieces.push_back(NI.getLoc());
James Y Knight04ec5bf2015-12-24 02:59:37 +00002994
2995 if (WantTemplateArgs && TemplateArgsLoc && TemplateArgsLoc->isValid())
2996 Pieces.push_back(*TemplateArgsLoc);
2997
Guy Benyei11169dd2012-12-18 14:30:41 +00002998 if (Kind == DeclarationName::CXXOperatorName) {
2999 Pieces.push_back(SourceLocation::getFromRawEncoding(
3000 NI.getInfo().CXXOperatorName.BeginOpNameLoc));
3001 Pieces.push_back(SourceLocation::getFromRawEncoding(
3002 NI.getInfo().CXXOperatorName.EndOpNameLoc));
3003 }
3004
3005 if (WantSinglePiece) {
3006 SourceRange R(Pieces.front().getBegin(), Pieces.back().getEnd());
3007 Pieces.clear();
3008 Pieces.push_back(R);
3009 }
3010
3011 return Pieces;
3012}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003013}
Guy Benyei11169dd2012-12-18 14:30:41 +00003014
3015//===----------------------------------------------------------------------===//
3016// Misc. API hooks.
3017//===----------------------------------------------------------------------===//
3018
Chad Rosier05c71aa2013-03-27 18:28:23 +00003019static void fatal_error_handler(void *user_data, const std::string& reason,
3020 bool gen_crash_diag) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003021 // Write the result out to stderr avoiding errs() because raw_ostreams can
3022 // call report_fatal_error.
3023 fprintf(stderr, "LIBCLANG FATAL ERROR: %s\n", reason.c_str());
3024 ::abort();
3025}
3026
Chandler Carruth66660742014-06-27 16:37:27 +00003027namespace {
3028struct RegisterFatalErrorHandler {
3029 RegisterFatalErrorHandler() {
3030 llvm::install_fatal_error_handler(fatal_error_handler, nullptr);
3031 }
3032};
3033}
3034
3035static llvm::ManagedStatic<RegisterFatalErrorHandler> RegisterFatalErrorHandlerOnce;
3036
Guy Benyei11169dd2012-12-18 14:30:41 +00003037extern "C" {
3038CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
3039 int displayDiagnostics) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003040 // We use crash recovery to make some of our APIs more reliable, implicitly
3041 // enable it.
Argyrios Kyrtzidis3701f542013-11-27 08:58:09 +00003042 if (!getenv("LIBCLANG_DISABLE_CRASH_RECOVERY"))
3043 llvm::CrashRecoveryContext::Enable();
Guy Benyei11169dd2012-12-18 14:30:41 +00003044
Chandler Carruth66660742014-06-27 16:37:27 +00003045 // Look through the managed static to trigger construction of the managed
3046 // static which registers our fatal error handler. This ensures it is only
3047 // registered once.
3048 (void)*RegisterFatalErrorHandlerOnce;
Guy Benyei11169dd2012-12-18 14:30:41 +00003049
Adrian Prantlbc068582015-07-08 01:00:30 +00003050 // Initialize targets for clang module support.
3051 llvm::InitializeAllTargets();
3052 llvm::InitializeAllTargetMCs();
3053 llvm::InitializeAllAsmPrinters();
3054 llvm::InitializeAllAsmParsers();
3055
Adrian Prantlfb2398d2015-07-17 01:19:54 +00003056 CIndexer *CIdxr = new CIndexer();
3057
Guy Benyei11169dd2012-12-18 14:30:41 +00003058 if (excludeDeclarationsFromPCH)
3059 CIdxr->setOnlyLocalDecls();
3060 if (displayDiagnostics)
3061 CIdxr->setDisplayDiagnostics();
3062
3063 if (getenv("LIBCLANG_BGPRIO_INDEX"))
3064 CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() |
3065 CXGlobalOpt_ThreadBackgroundPriorityForIndexing);
3066 if (getenv("LIBCLANG_BGPRIO_EDIT"))
3067 CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() |
3068 CXGlobalOpt_ThreadBackgroundPriorityForEditing);
3069
3070 return CIdxr;
3071}
3072
3073void clang_disposeIndex(CXIndex CIdx) {
3074 if (CIdx)
3075 delete static_cast<CIndexer *>(CIdx);
3076}
3077
3078void clang_CXIndex_setGlobalOptions(CXIndex CIdx, unsigned options) {
3079 if (CIdx)
3080 static_cast<CIndexer *>(CIdx)->setCXGlobalOptFlags(options);
3081}
3082
3083unsigned clang_CXIndex_getGlobalOptions(CXIndex CIdx) {
3084 if (CIdx)
3085 return static_cast<CIndexer *>(CIdx)->getCXGlobalOptFlags();
3086 return 0;
3087}
3088
3089void clang_toggleCrashRecovery(unsigned isEnabled) {
3090 if (isEnabled)
3091 llvm::CrashRecoveryContext::Enable();
3092 else
3093 llvm::CrashRecoveryContext::Disable();
3094}
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003095
Guy Benyei11169dd2012-12-18 14:30:41 +00003096CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
3097 const char *ast_filename) {
Dmitri Gribenko8850cda2014-02-19 10:24:00 +00003098 CXTranslationUnit TU;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003099 enum CXErrorCode Result =
3100 clang_createTranslationUnit2(CIdx, ast_filename, &TU);
Reid Klecknerfd48fc62014-02-12 23:56:20 +00003101 (void)Result;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003102 assert((TU && Result == CXError_Success) ||
3103 (!TU && Result != CXError_Success));
3104 return TU;
3105}
3106
3107enum CXErrorCode clang_createTranslationUnit2(CXIndex CIdx,
3108 const char *ast_filename,
3109 CXTranslationUnit *out_TU) {
Dmitri Gribenko8850cda2014-02-19 10:24:00 +00003110 if (out_TU)
Craig Topper69186e72014-06-08 08:38:04 +00003111 *out_TU = nullptr;
Dmitri Gribenko8850cda2014-02-19 10:24:00 +00003112
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003113 if (!CIdx || !ast_filename || !out_TU)
3114 return CXError_InvalidArguments;
Guy Benyei11169dd2012-12-18 14:30:41 +00003115
Argyrios Kyrtzidis27021012013-05-24 22:24:07 +00003116 LOG_FUNC_SECTION {
3117 *Log << ast_filename;
3118 }
3119
Guy Benyei11169dd2012-12-18 14:30:41 +00003120 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
3121 FileSystemOptions FileSystemOpts;
3122
Justin Bognerd512c1e2014-10-15 00:33:06 +00003123 IntrusiveRefCntPtr<DiagnosticsEngine> Diags =
3124 CompilerInstance::createDiagnostics(new DiagnosticOptions());
David Blaikie6f7382d2014-08-10 19:08:04 +00003125 std::unique_ptr<ASTUnit> AU = ASTUnit::LoadFromASTFile(
Adrian Prantlfb2398d2015-07-17 01:19:54 +00003126 ast_filename, CXXIdx->getPCHContainerOperations()->getRawReader(), Diags,
Adrian Prantl6b21ab22015-08-27 19:46:20 +00003127 FileSystemOpts, /*UseDebugInfo=*/false,
3128 CXXIdx->getOnlyLocalDecls(), None,
David Blaikie6f7382d2014-08-10 19:08:04 +00003129 /*CaptureDiagnostics=*/true,
3130 /*AllowPCHWithCompilerErrors=*/true,
3131 /*UserFilesAreVolatile=*/true);
3132 *out_TU = MakeCXTranslationUnit(CXXIdx, AU.release());
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003133 return *out_TU ? CXError_Success : CXError_Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003134}
3135
3136unsigned clang_defaultEditingTranslationUnitOptions() {
3137 return CXTranslationUnit_PrecompiledPreamble |
3138 CXTranslationUnit_CacheCompletionResults;
3139}
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003140
Guy Benyei11169dd2012-12-18 14:30:41 +00003141CXTranslationUnit
3142clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
3143 const char *source_filename,
3144 int num_command_line_args,
3145 const char * const *command_line_args,
3146 unsigned num_unsaved_files,
3147 struct CXUnsavedFile *unsaved_files) {
3148 unsigned Options = CXTranslationUnit_DetailedPreprocessingRecord;
3149 return clang_parseTranslationUnit(CIdx, source_filename,
3150 command_line_args, num_command_line_args,
3151 unsaved_files, num_unsaved_files,
3152 Options);
3153}
3154
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003155static CXErrorCode
3156clang_parseTranslationUnit_Impl(CXIndex CIdx, const char *source_filename,
3157 const char *const *command_line_args,
3158 int num_command_line_args,
3159 ArrayRef<CXUnsavedFile> unsaved_files,
3160 unsigned options, CXTranslationUnit *out_TU) {
Dmitri Gribenko1bf8d912014-02-18 15:20:02 +00003161 // Set up the initial return values.
3162 if (out_TU)
Craig Topper69186e72014-06-08 08:38:04 +00003163 *out_TU = nullptr;
Dmitri Gribenko1bf8d912014-02-18 15:20:02 +00003164
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003165 // Check arguments.
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003166 if (!CIdx || !out_TU)
3167 return CXError_InvalidArguments;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003168
Guy Benyei11169dd2012-12-18 14:30:41 +00003169 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
3170
3171 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
3172 setThreadBackgroundPriority();
3173
3174 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Benjamin Kramer5c248d82015-12-15 09:30:31 +00003175 bool CreatePreambleOnFirstParse =
3176 options & CXTranslationUnit_CreatePreambleOnFirstParse;
Guy Benyei11169dd2012-12-18 14:30:41 +00003177 // FIXME: Add a flag for modules.
3178 TranslationUnitKind TUKind
3179 = (options & CXTranslationUnit_Incomplete)? TU_Prefix : TU_Complete;
Alp Toker8c8a8752013-12-03 06:53:35 +00003180 bool CacheCodeCompletionResults
Guy Benyei11169dd2012-12-18 14:30:41 +00003181 = options & CXTranslationUnit_CacheCompletionResults;
3182 bool IncludeBriefCommentsInCodeCompletion
3183 = options & CXTranslationUnit_IncludeBriefCommentsInCodeCompletion;
3184 bool SkipFunctionBodies = options & CXTranslationUnit_SkipFunctionBodies;
3185 bool ForSerialization = options & CXTranslationUnit_ForSerialization;
3186
3187 // Configure the diagnostics.
3188 IntrusiveRefCntPtr<DiagnosticsEngine>
Sean Silvaf1b49e22013-01-20 01:58:28 +00003189 Diags(CompilerInstance::createDiagnostics(new DiagnosticOptions));
Guy Benyei11169dd2012-12-18 14:30:41 +00003190
Manuel Klimek016c0242016-03-01 10:56:19 +00003191 if (options & CXTranslationUnit_KeepGoing)
3192 Diags->setFatalsAsError(true);
3193
Guy Benyei11169dd2012-12-18 14:30:41 +00003194 // Recover resources if we crash before exiting this function.
3195 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
3196 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Alp Tokerf994cef2014-07-05 03:08:06 +00003197 DiagCleanup(Diags.get());
Guy Benyei11169dd2012-12-18 14:30:41 +00003198
Ahmed Charlesb8984322014-03-07 20:03:18 +00003199 std::unique_ptr<std::vector<ASTUnit::RemappedFile>> RemappedFiles(
3200 new std::vector<ASTUnit::RemappedFile>());
Guy Benyei11169dd2012-12-18 14:30:41 +00003201
3202 // Recover resources if we crash before exiting this function.
3203 llvm::CrashRecoveryContextCleanupRegistrar<
3204 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
3205
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003206 for (auto &UF : unsaved_files) {
Rafael Espindolad87f8d72014-08-27 20:03:29 +00003207 std::unique_ptr<llvm::MemoryBuffer> MB =
Alp Toker9d85b182014-07-07 01:23:14 +00003208 llvm::MemoryBuffer::getMemBufferCopy(getContents(UF), UF.Filename);
Rafael Espindolad87f8d72014-08-27 20:03:29 +00003209 RemappedFiles->push_back(std::make_pair(UF.Filename, MB.release()));
Guy Benyei11169dd2012-12-18 14:30:41 +00003210 }
3211
Ahmed Charlesb8984322014-03-07 20:03:18 +00003212 std::unique_ptr<std::vector<const char *>> Args(
3213 new std::vector<const char *>());
Guy Benyei11169dd2012-12-18 14:30:41 +00003214
3215 // Recover resources if we crash before exiting this method.
3216 llvm::CrashRecoveryContextCleanupRegistrar<std::vector<const char*> >
3217 ArgsCleanup(Args.get());
3218
3219 // Since the Clang C library is primarily used by batch tools dealing with
3220 // (often very broken) source code, where spell-checking can have a
3221 // significant negative impact on performance (particularly when
3222 // precompiled headers are involved), we disable it by default.
3223 // Only do this if we haven't found a spell-checking-related argument.
3224 bool FoundSpellCheckingArgument = false;
3225 for (int I = 0; I != num_command_line_args; ++I) {
3226 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
3227 strcmp(command_line_args[I], "-fspell-checking") == 0) {
3228 FoundSpellCheckingArgument = true;
3229 break;
3230 }
3231 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003232 Args->insert(Args->end(), command_line_args,
3233 command_line_args + num_command_line_args);
3234
Benjamin Kramerc02670e2015-11-18 16:14:27 +00003235 if (!FoundSpellCheckingArgument)
3236 Args->insert(Args->begin() + 1, "-fno-spell-checking");
3237
Guy Benyei11169dd2012-12-18 14:30:41 +00003238 // The 'source_filename' argument is optional. If the caller does not
3239 // specify it then it is assumed that the source file is specified
3240 // in the actual argument list.
3241 // Put the source file after command_line_args otherwise if '-x' flag is
3242 // present it will be unused.
3243 if (source_filename)
3244 Args->push_back(source_filename);
3245
3246 // Do we need the detailed preprocessing record?
3247 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
3248 Args->push_back("-Xclang");
3249 Args->push_back("-detailed-preprocessing-record");
3250 }
3251
3252 unsigned NumErrors = Diags->getClient()->getNumErrors();
Ahmed Charlesb8984322014-03-07 20:03:18 +00003253 std::unique_ptr<ASTUnit> ErrUnit;
Benjamin Kramer5c248d82015-12-15 09:30:31 +00003254 // Unless the user specified that they want the preamble on the first parse
3255 // set it up to be created on the first reparse. This makes the first parse
3256 // faster, trading for a slower (first) reparse.
3257 unsigned PrecompilePreambleAfterNParses =
3258 !PrecompilePreamble ? 0 : 2 - CreatePreambleOnFirstParse;
Ahmed Charlesb8984322014-03-07 20:03:18 +00003259 std::unique_ptr<ASTUnit> Unit(ASTUnit::LoadFromCommandLine(
Adrian Prantlbb165fb2015-06-20 18:53:08 +00003260 Args->data(), Args->data() + Args->size(),
3261 CXXIdx->getPCHContainerOperations(), Diags,
Ahmed Charlesb8984322014-03-07 20:03:18 +00003262 CXXIdx->getClangResourcesPath(), CXXIdx->getOnlyLocalDecls(),
3263 /*CaptureDiagnostics=*/true, *RemappedFiles.get(),
Benjamin Kramer5c248d82015-12-15 09:30:31 +00003264 /*RemappedFilesKeepOriginalName=*/true, PrecompilePreambleAfterNParses,
3265 TUKind, CacheCodeCompletionResults, IncludeBriefCommentsInCodeCompletion,
Ahmed Charlesb8984322014-03-07 20:03:18 +00003266 /*AllowPCHWithCompilerErrors=*/true, SkipFunctionBodies,
Argyrios Kyrtzidisa3e2ff12015-11-20 03:36:21 +00003267 /*UserFilesAreVolatile=*/true, ForSerialization,
3268 CXXIdx->getPCHContainerOperations()->getRawReader().getFormat(),
3269 &ErrUnit));
Guy Benyei11169dd2012-12-18 14:30:41 +00003270
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003271 // Early failures in LoadFromCommandLine may return with ErrUnit unset.
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003272 if (!Unit && !ErrUnit)
3273 return CXError_ASTReadError;
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003274
Guy Benyei11169dd2012-12-18 14:30:41 +00003275 if (NumErrors != Diags->getClient()->getNumErrors()) {
3276 // Make sure to check that 'Unit' is non-NULL.
3277 if (CXXIdx->getDisplayDiagnostics())
3278 printDiagsToStderr(Unit ? Unit.get() : ErrUnit.get());
3279 }
3280
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003281 if (isASTReadError(Unit ? Unit.get() : ErrUnit.get()))
3282 return CXError_ASTReadError;
3283
3284 *out_TU = MakeCXTranslationUnit(CXXIdx, Unit.release());
3285 return *out_TU ? CXError_Success : CXError_Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003286}
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003287
3288CXTranslationUnit
3289clang_parseTranslationUnit(CXIndex CIdx,
3290 const char *source_filename,
3291 const char *const *command_line_args,
3292 int num_command_line_args,
3293 struct CXUnsavedFile *unsaved_files,
3294 unsigned num_unsaved_files,
3295 unsigned options) {
3296 CXTranslationUnit TU;
3297 enum CXErrorCode Result = clang_parseTranslationUnit2(
3298 CIdx, source_filename, command_line_args, num_command_line_args,
3299 unsaved_files, num_unsaved_files, options, &TU);
Reid Kleckner6eaf05a2014-02-13 01:19:59 +00003300 (void)Result;
Dmitri Gribenko1bf8d912014-02-18 15:20:02 +00003301 assert((TU && Result == CXError_Success) ||
3302 (!TU && Result != CXError_Success));
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003303 return TU;
3304}
3305
3306enum CXErrorCode clang_parseTranslationUnit2(
Benjamin Kramerc02670e2015-11-18 16:14:27 +00003307 CXIndex CIdx, const char *source_filename,
3308 const char *const *command_line_args, int num_command_line_args,
3309 struct CXUnsavedFile *unsaved_files, unsigned num_unsaved_files,
3310 unsigned options, CXTranslationUnit *out_TU) {
3311 SmallVector<const char *, 4> Args;
3312 Args.push_back("clang");
3313 Args.append(command_line_args, command_line_args + num_command_line_args);
3314 return clang_parseTranslationUnit2FullArgv(
3315 CIdx, source_filename, Args.data(), Args.size(), unsaved_files,
3316 num_unsaved_files, options, out_TU);
3317}
3318
3319enum CXErrorCode clang_parseTranslationUnit2FullArgv(
3320 CXIndex CIdx, const char *source_filename,
3321 const char *const *command_line_args, int num_command_line_args,
3322 struct CXUnsavedFile *unsaved_files, unsigned num_unsaved_files,
3323 unsigned options, CXTranslationUnit *out_TU) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00003324 LOG_FUNC_SECTION {
3325 *Log << source_filename << ": ";
3326 for (int i = 0; i != num_command_line_args; ++i)
3327 *Log << command_line_args[i] << " ";
3328 }
3329
Alp Toker9d85b182014-07-07 01:23:14 +00003330 if (num_unsaved_files && !unsaved_files)
3331 return CXError_InvalidArguments;
3332
Alp Toker5c532982014-07-07 22:42:03 +00003333 CXErrorCode result = CXError_Failure;
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003334 auto ParseTranslationUnitImpl = [=, &result] {
3335 result = clang_parseTranslationUnit_Impl(
3336 CIdx, source_filename, command_line_args, num_command_line_args,
3337 llvm::makeArrayRef(unsaved_files, num_unsaved_files), options, out_TU);
3338 };
Guy Benyei11169dd2012-12-18 14:30:41 +00003339 llvm::CrashRecoveryContext CRC;
3340
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003341 if (!RunSafely(CRC, ParseTranslationUnitImpl)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003342 fprintf(stderr, "libclang: crash detected during parsing: {\n");
3343 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
3344 fprintf(stderr, " 'command_line_args' : [");
3345 for (int i = 0; i != num_command_line_args; ++i) {
3346 if (i)
3347 fprintf(stderr, ", ");
3348 fprintf(stderr, "'%s'", command_line_args[i]);
3349 }
3350 fprintf(stderr, "],\n");
3351 fprintf(stderr, " 'unsaved_files' : [");
3352 for (unsigned i = 0; i != num_unsaved_files; ++i) {
3353 if (i)
3354 fprintf(stderr, ", ");
3355 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
3356 unsaved_files[i].Length);
3357 }
3358 fprintf(stderr, "],\n");
3359 fprintf(stderr, " 'options' : %d,\n", options);
3360 fprintf(stderr, "}\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003361
3362 return CXError_Crashed;
Guy Benyei11169dd2012-12-18 14:30:41 +00003363 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003364 if (CXTranslationUnit *TU = out_TU)
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003365 PrintLibclangResourceUsage(*TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00003366 }
Alp Toker5c532982014-07-07 22:42:03 +00003367
3368 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003369}
3370
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003371CXString clang_Type_getObjCEncoding(CXType CT) {
3372 CXTranslationUnit tu = static_cast<CXTranslationUnit>(CT.data[1]);
3373 ASTContext &Ctx = getASTUnit(tu)->getASTContext();
3374 std::string encoding;
3375 Ctx.getObjCEncodingForType(QualType::getFromOpaquePtr(CT.data[0]),
3376 encoding);
3377
3378 return cxstring::createDup(encoding);
3379}
3380
3381static const IdentifierInfo *getMacroIdentifier(CXCursor C) {
3382 if (C.kind == CXCursor_MacroDefinition) {
3383 if (const MacroDefinitionRecord *MDR = getCursorMacroDefinition(C))
3384 return MDR->getName();
3385 } else if (C.kind == CXCursor_MacroExpansion) {
3386 MacroExpansionCursor ME = getCursorMacroExpansion(C);
3387 return ME.getName();
3388 }
3389 return nullptr;
3390}
3391
3392unsigned clang_Cursor_isMacroFunctionLike(CXCursor C) {
3393 const IdentifierInfo *II = getMacroIdentifier(C);
3394 if (!II) {
3395 return false;
3396 }
3397 ASTUnit *ASTU = getCursorASTUnit(C);
3398 Preprocessor &PP = ASTU->getPreprocessor();
3399 if (const MacroInfo *MI = PP.getMacroInfo(II))
3400 return MI->isFunctionLike();
3401 return false;
3402}
3403
3404unsigned clang_Cursor_isMacroBuiltin(CXCursor C) {
3405 const IdentifierInfo *II = getMacroIdentifier(C);
3406 if (!II) {
3407 return false;
3408 }
3409 ASTUnit *ASTU = getCursorASTUnit(C);
3410 Preprocessor &PP = ASTU->getPreprocessor();
3411 if (const MacroInfo *MI = PP.getMacroInfo(II))
3412 return MI->isBuiltinMacro();
3413 return false;
3414}
3415
3416unsigned clang_Cursor_isFunctionInlined(CXCursor C) {
3417 const Decl *D = getCursorDecl(C);
3418 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
3419 if (!FD) {
3420 return false;
3421 }
3422 return FD->isInlined();
3423}
3424
3425static StringLiteral* getCFSTR_value(CallExpr *callExpr) {
3426 if (callExpr->getNumArgs() != 1) {
3427 return nullptr;
3428 }
3429
3430 StringLiteral *S = nullptr;
3431 auto *arg = callExpr->getArg(0);
3432 if (arg->getStmtClass() == Stmt::ImplicitCastExprClass) {
3433 ImplicitCastExpr *I = static_cast<ImplicitCastExpr *>(arg);
3434 auto *subExpr = I->getSubExprAsWritten();
3435
3436 if(subExpr->getStmtClass() != Stmt::StringLiteralClass){
3437 return nullptr;
3438 }
3439
3440 S = static_cast<StringLiteral *>(I->getSubExprAsWritten());
3441 } else if (arg->getStmtClass() == Stmt::StringLiteralClass) {
3442 S = static_cast<StringLiteral *>(callExpr->getArg(0));
3443 } else {
3444 return nullptr;
3445 }
3446 return S;
3447}
3448
David Blaikie59272572016-04-13 18:23:33 +00003449struct ExprEvalResult {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003450 CXEvalResultKind EvalType;
3451 union {
3452 int intVal;
3453 double floatVal;
3454 char *stringVal;
3455 } EvalData;
David Blaikie59272572016-04-13 18:23:33 +00003456 ~ExprEvalResult() {
3457 if (EvalType != CXEval_UnExposed && EvalType != CXEval_Float &&
3458 EvalType != CXEval_Int) {
3459 delete EvalData.stringVal;
3460 }
3461 }
3462};
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003463
3464void clang_EvalResult_dispose(CXEvalResult E) {
David Blaikie59272572016-04-13 18:23:33 +00003465 delete static_cast<ExprEvalResult *>(E);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003466}
3467
3468CXEvalResultKind clang_EvalResult_getKind(CXEvalResult E) {
3469 if (!E) {
3470 return CXEval_UnExposed;
3471 }
3472 return ((ExprEvalResult *)E)->EvalType;
3473}
3474
3475int clang_EvalResult_getAsInt(CXEvalResult E) {
3476 if (!E) {
3477 return 0;
3478 }
3479 return ((ExprEvalResult *)E)->EvalData.intVal;
3480}
3481
3482double clang_EvalResult_getAsDouble(CXEvalResult E) {
3483 if (!E) {
3484 return 0;
3485 }
3486 return ((ExprEvalResult *)E)->EvalData.floatVal;
3487}
3488
3489const char* clang_EvalResult_getAsStr(CXEvalResult E) {
3490 if (!E) {
3491 return nullptr;
3492 }
3493 return ((ExprEvalResult *)E)->EvalData.stringVal;
3494}
3495
3496static const ExprEvalResult* evaluateExpr(Expr *expr, CXCursor C) {
3497 Expr::EvalResult ER;
3498 ASTContext &ctx = getCursorContext(C);
David Blaikiebbc00882016-04-13 18:36:19 +00003499 if (!expr)
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003500 return nullptr;
David Blaikiebbc00882016-04-13 18:36:19 +00003501
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003502 expr = expr->IgnoreParens();
David Blaikiebbc00882016-04-13 18:36:19 +00003503 if (!expr->EvaluateAsRValue(ER, ctx))
3504 return nullptr;
3505
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003506 QualType rettype;
3507 CallExpr *callExpr;
David Blaikie59272572016-04-13 18:23:33 +00003508 auto result = llvm::make_unique<ExprEvalResult>();
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003509 result->EvalType = CXEval_UnExposed;
3510
David Blaikiebbc00882016-04-13 18:36:19 +00003511 if (ER.Val.isInt()) {
3512 result->EvalType = CXEval_Int;
3513 result->EvalData.intVal = ER.Val.getInt().getExtValue();
3514 return result.release();
3515 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003516
David Blaikiebbc00882016-04-13 18:36:19 +00003517 if (ER.Val.isFloat()) {
3518 llvm::SmallVector<char, 100> Buffer;
3519 ER.Val.getFloat().toString(Buffer);
3520 std::string floatStr(Buffer.data(), Buffer.size());
3521 result->EvalType = CXEval_Float;
3522 bool ignored;
3523 llvm::APFloat apFloat = ER.Val.getFloat();
3524 apFloat.convert(llvm::APFloat::IEEEdouble,
3525 llvm::APFloat::rmNearestTiesToEven, &ignored);
3526 result->EvalData.floatVal = apFloat.convertToDouble();
3527 return result.release();
3528 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003529
David Blaikiebbc00882016-04-13 18:36:19 +00003530 if (expr->getStmtClass() == Stmt::ImplicitCastExprClass) {
3531 const ImplicitCastExpr *I = dyn_cast<ImplicitCastExpr>(expr);
3532 auto *subExpr = I->getSubExprAsWritten();
3533 if (subExpr->getStmtClass() == Stmt::StringLiteralClass ||
3534 subExpr->getStmtClass() == Stmt::ObjCStringLiteralClass) {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003535 const StringLiteral *StrE = nullptr;
3536 const ObjCStringLiteral *ObjCExpr;
David Blaikiebbc00882016-04-13 18:36:19 +00003537 ObjCExpr = dyn_cast<ObjCStringLiteral>(subExpr);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003538
3539 if (ObjCExpr) {
3540 StrE = ObjCExpr->getString();
3541 result->EvalType = CXEval_ObjCStrLiteral;
3542 } else {
David Blaikiebbc00882016-04-13 18:36:19 +00003543 StrE = cast<StringLiteral>(I->getSubExprAsWritten());
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003544 result->EvalType = CXEval_StrLiteral;
3545 }
3546
3547 std::string strRef(StrE->getString().str());
David Blaikie59272572016-04-13 18:23:33 +00003548 result->EvalData.stringVal = new char[strRef.size() + 1];
David Blaikiebbc00882016-04-13 18:36:19 +00003549 strncpy((char *)result->EvalData.stringVal, strRef.c_str(),
3550 strRef.size());
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003551 result->EvalData.stringVal[strRef.size()] = '\0';
David Blaikie59272572016-04-13 18:23:33 +00003552 return result.release();
David Blaikiebbc00882016-04-13 18:36:19 +00003553 }
3554 } else if (expr->getStmtClass() == Stmt::ObjCStringLiteralClass ||
3555 expr->getStmtClass() == Stmt::StringLiteralClass) {
3556 const StringLiteral *StrE = nullptr;
3557 const ObjCStringLiteral *ObjCExpr;
3558 ObjCExpr = dyn_cast<ObjCStringLiteral>(expr);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003559
David Blaikiebbc00882016-04-13 18:36:19 +00003560 if (ObjCExpr) {
3561 StrE = ObjCExpr->getString();
3562 result->EvalType = CXEval_ObjCStrLiteral;
3563 } else {
3564 StrE = cast<StringLiteral>(expr);
3565 result->EvalType = CXEval_StrLiteral;
3566 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003567
David Blaikiebbc00882016-04-13 18:36:19 +00003568 std::string strRef(StrE->getString().str());
3569 result->EvalData.stringVal = new char[strRef.size() + 1];
3570 strncpy((char *)result->EvalData.stringVal, strRef.c_str(), strRef.size());
3571 result->EvalData.stringVal[strRef.size()] = '\0';
3572 return result.release();
3573 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003574
David Blaikiebbc00882016-04-13 18:36:19 +00003575 if (expr->getStmtClass() == Stmt::CStyleCastExprClass) {
3576 CStyleCastExpr *CC = static_cast<CStyleCastExpr *>(expr);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003577
David Blaikiebbc00882016-04-13 18:36:19 +00003578 rettype = CC->getType();
3579 if (rettype.getAsString() == "CFStringRef" &&
3580 CC->getSubExpr()->getStmtClass() == Stmt::CallExprClass) {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003581
David Blaikiebbc00882016-04-13 18:36:19 +00003582 callExpr = static_cast<CallExpr *>(CC->getSubExpr());
3583 StringLiteral *S = getCFSTR_value(callExpr);
3584 if (S) {
3585 std::string strLiteral(S->getString().str());
3586 result->EvalType = CXEval_CFStr;
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003587
David Blaikiebbc00882016-04-13 18:36:19 +00003588 result->EvalData.stringVal = new char[strLiteral.size() + 1];
3589 strncpy((char *)result->EvalData.stringVal, strLiteral.c_str(),
3590 strLiteral.size());
3591 result->EvalData.stringVal[strLiteral.size()] = '\0';
David Blaikie59272572016-04-13 18:23:33 +00003592 return result.release();
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003593 }
3594 }
3595
David Blaikiebbc00882016-04-13 18:36:19 +00003596 } else if (expr->getStmtClass() == Stmt::CallExprClass) {
3597 callExpr = static_cast<CallExpr *>(expr);
3598 rettype = callExpr->getCallReturnType(ctx);
3599
3600 if (rettype->isVectorType() || callExpr->getNumArgs() > 1)
3601 return nullptr;
3602
3603 if (rettype->isIntegralType(ctx) || rettype->isRealFloatingType()) {
3604 if (callExpr->getNumArgs() == 1 &&
3605 !callExpr->getArg(0)->getType()->isIntegralType(ctx))
3606 return nullptr;
3607 } else if (rettype.getAsString() == "CFStringRef") {
3608
3609 StringLiteral *S = getCFSTR_value(callExpr);
3610 if (S) {
3611 std::string strLiteral(S->getString().str());
3612 result->EvalType = CXEval_CFStr;
3613 result->EvalData.stringVal = new char[strLiteral.size() + 1];
3614 strncpy((char *)result->EvalData.stringVal, strLiteral.c_str(),
3615 strLiteral.size());
3616 result->EvalData.stringVal[strLiteral.size()] = '\0';
3617 return result.release();
3618 }
3619 }
3620 } else if (expr->getStmtClass() == Stmt::DeclRefExprClass) {
3621 DeclRefExpr *D = static_cast<DeclRefExpr *>(expr);
3622 ValueDecl *V = D->getDecl();
3623 if (V->getKind() == Decl::Function) {
3624 std::string strName = V->getNameAsString();
3625 result->EvalType = CXEval_Other;
3626 result->EvalData.stringVal = new char[strName.size() + 1];
3627 strncpy(result->EvalData.stringVal, strName.c_str(), strName.size());
3628 result->EvalData.stringVal[strName.size()] = '\0';
3629 return result.release();
3630 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003631 }
3632
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003633 return nullptr;
3634}
3635
3636CXEvalResult clang_Cursor_Evaluate(CXCursor C) {
3637 const Decl *D = getCursorDecl(C);
3638 if (D) {
3639 const Expr *expr = nullptr;
3640 if (auto *Var = dyn_cast<VarDecl>(D)) {
3641 expr = Var->getInit();
3642 } else if (auto *Field = dyn_cast<FieldDecl>(D)) {
3643 expr = Field->getInClassInitializer();
3644 }
3645 if (expr)
Aaron Ballman01dc1572016-01-20 15:25:30 +00003646 return const_cast<CXEvalResult>(reinterpret_cast<const void *>(
3647 evaluateExpr(const_cast<Expr *>(expr), C)));
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003648 return nullptr;
3649 }
3650
3651 const CompoundStmt *compoundStmt = dyn_cast_or_null<CompoundStmt>(getCursorStmt(C));
3652 if (compoundStmt) {
3653 Expr *expr = nullptr;
3654 for (auto *bodyIterator : compoundStmt->body()) {
3655 if ((expr = dyn_cast<Expr>(bodyIterator))) {
3656 break;
3657 }
3658 }
3659 if (expr)
Aaron Ballman01dc1572016-01-20 15:25:30 +00003660 return const_cast<CXEvalResult>(
3661 reinterpret_cast<const void *>(evaluateExpr(expr, C)));
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003662 }
3663 return nullptr;
3664}
3665
3666unsigned clang_Cursor_hasAttrs(CXCursor C) {
3667 const Decl *D = getCursorDecl(C);
3668 if (!D) {
3669 return 0;
3670 }
3671
3672 if (D->hasAttrs()) {
3673 return 1;
3674 }
3675
3676 return 0;
3677}
Guy Benyei11169dd2012-12-18 14:30:41 +00003678unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
3679 return CXSaveTranslationUnit_None;
3680}
3681
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003682static CXSaveError clang_saveTranslationUnit_Impl(CXTranslationUnit TU,
3683 const char *FileName,
3684 unsigned options) {
3685 CIndexer *CXXIdx = TU->CIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00003686 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
3687 setThreadBackgroundPriority();
3688
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003689 bool hadError = cxtu::getASTUnit(TU)->Save(FileName);
3690 return hadError ? CXSaveError_Unknown : CXSaveError_None;
Guy Benyei11169dd2012-12-18 14:30:41 +00003691}
3692
3693int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
3694 unsigned options) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00003695 LOG_FUNC_SECTION {
3696 *Log << TU << ' ' << FileName;
3697 }
3698
Dmitri Gribenko852d6222014-02-11 15:02:48 +00003699 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00003700 LOG_BAD_TU(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00003701 return CXSaveError_InvalidTU;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00003702 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003703
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00003704 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00003705 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3706 if (!CXXUnit->hasSema())
3707 return CXSaveError_InvalidTU;
3708
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003709 CXSaveError result;
3710 auto SaveTranslationUnitImpl = [=, &result]() {
3711 result = clang_saveTranslationUnit_Impl(TU, FileName, options);
3712 };
Guy Benyei11169dd2012-12-18 14:30:41 +00003713
3714 if (!CXXUnit->getDiagnostics().hasUnrecoverableErrorOccurred() ||
3715 getenv("LIBCLANG_NOTHREADS")) {
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003716 SaveTranslationUnitImpl();
Guy Benyei11169dd2012-12-18 14:30:41 +00003717
3718 if (getenv("LIBCLANG_RESOURCE_USAGE"))
3719 PrintLibclangResourceUsage(TU);
3720
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003721 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003722 }
3723
3724 // We have an AST that has invalid nodes due to compiler errors.
3725 // Use a crash recovery thread for protection.
3726
3727 llvm::CrashRecoveryContext CRC;
3728
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003729 if (!RunSafely(CRC, SaveTranslationUnitImpl)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003730 fprintf(stderr, "libclang: crash detected during AST saving: {\n");
3731 fprintf(stderr, " 'filename' : '%s'\n", FileName);
3732 fprintf(stderr, " 'options' : %d,\n", options);
3733 fprintf(stderr, "}\n");
3734
3735 return CXSaveError_Unknown;
3736
3737 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
3738 PrintLibclangResourceUsage(TU);
3739 }
3740
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003741 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003742}
3743
3744void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
3745 if (CTUnit) {
3746 // If the translation unit has been marked as unsafe to free, just discard
3747 // it.
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003748 ASTUnit *Unit = cxtu::getASTUnit(CTUnit);
3749 if (Unit && Unit->isUnsafeToFree())
Guy Benyei11169dd2012-12-18 14:30:41 +00003750 return;
3751
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00003752 delete cxtu::getASTUnit(CTUnit);
Dmitri Gribenkob95b3f12013-01-26 22:44:19 +00003753 delete CTUnit->StringPool;
Guy Benyei11169dd2012-12-18 14:30:41 +00003754 delete static_cast<CXDiagnosticSetImpl *>(CTUnit->Diagnostics);
3755 disposeOverridenCXCursorsPool(CTUnit->OverridenCursorsPool);
Dmitri Gribenko9e605112013-11-13 22:16:51 +00003756 delete CTUnit->CommentToXML;
Guy Benyei11169dd2012-12-18 14:30:41 +00003757 delete CTUnit;
3758 }
3759}
3760
3761unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
3762 return CXReparse_None;
3763}
3764
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003765static CXErrorCode
3766clang_reparseTranslationUnit_Impl(CXTranslationUnit TU,
3767 ArrayRef<CXUnsavedFile> unsaved_files,
3768 unsigned options) {
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003769 // Check arguments.
Dmitri Gribenko852d6222014-02-11 15:02:48 +00003770 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00003771 LOG_BAD_TU(TU);
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003772 return CXError_InvalidArguments;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003773 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003774
3775 // Reset the associated diagnostics.
3776 delete static_cast<CXDiagnosticSetImpl*>(TU->Diagnostics);
Craig Topper69186e72014-06-08 08:38:04 +00003777 TU->Diagnostics = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00003778
Dmitri Gribenko183436e2013-01-26 21:49:50 +00003779 CIndexer *CXXIdx = TU->CIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00003780 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing))
3781 setThreadBackgroundPriority();
3782
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00003783 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00003784 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ahmed Charlesb8984322014-03-07 20:03:18 +00003785
3786 std::unique_ptr<std::vector<ASTUnit::RemappedFile>> RemappedFiles(
3787 new std::vector<ASTUnit::RemappedFile>());
3788
Guy Benyei11169dd2012-12-18 14:30:41 +00003789 // Recover resources if we crash before exiting this function.
3790 llvm::CrashRecoveryContextCleanupRegistrar<
3791 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
Alp Toker9d85b182014-07-07 01:23:14 +00003792
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003793 for (auto &UF : unsaved_files) {
Rafael Espindolad87f8d72014-08-27 20:03:29 +00003794 std::unique_ptr<llvm::MemoryBuffer> MB =
Alp Toker9d85b182014-07-07 01:23:14 +00003795 llvm::MemoryBuffer::getMemBufferCopy(getContents(UF), UF.Filename);
Rafael Espindolad87f8d72014-08-27 20:03:29 +00003796 RemappedFiles->push_back(std::make_pair(UF.Filename, MB.release()));
Guy Benyei11169dd2012-12-18 14:30:41 +00003797 }
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003798
Adrian Prantlbb165fb2015-06-20 18:53:08 +00003799 if (!CXXUnit->Reparse(CXXIdx->getPCHContainerOperations(),
3800 *RemappedFiles.get()))
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003801 return CXError_Success;
3802 if (isASTReadError(CXXUnit))
3803 return CXError_ASTReadError;
3804 return CXError_Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003805}
3806
3807int clang_reparseTranslationUnit(CXTranslationUnit TU,
3808 unsigned num_unsaved_files,
3809 struct CXUnsavedFile *unsaved_files,
3810 unsigned options) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00003811 LOG_FUNC_SECTION {
3812 *Log << TU;
3813 }
3814
Alp Toker9d85b182014-07-07 01:23:14 +00003815 if (num_unsaved_files && !unsaved_files)
3816 return CXError_InvalidArguments;
3817
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003818 CXErrorCode result;
3819 auto ReparseTranslationUnitImpl = [=, &result]() {
3820 result = clang_reparseTranslationUnit_Impl(
3821 TU, llvm::makeArrayRef(unsaved_files, num_unsaved_files), options);
3822 };
Guy Benyei11169dd2012-12-18 14:30:41 +00003823
3824 if (getenv("LIBCLANG_NOTHREADS")) {
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003825 ReparseTranslationUnitImpl();
Alp Toker5c532982014-07-07 22:42:03 +00003826 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003827 }
3828
3829 llvm::CrashRecoveryContext CRC;
3830
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003831 if (!RunSafely(CRC, ReparseTranslationUnitImpl)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003832 fprintf(stderr, "libclang: crash detected during reparsing\n");
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00003833 cxtu::getASTUnit(TU)->setUnsafeToFree(true);
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003834 return CXError_Crashed;
Guy Benyei11169dd2012-12-18 14:30:41 +00003835 } else if (getenv("LIBCLANG_RESOURCE_USAGE"))
3836 PrintLibclangResourceUsage(TU);
3837
Alp Toker5c532982014-07-07 22:42:03 +00003838 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003839}
3840
3841
3842CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00003843 if (isNotUsableTU(CTUnit)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00003844 LOG_BAD_TU(CTUnit);
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00003845 return cxstring::createEmpty();
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(CTUnit);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00003849 return cxstring::createDup(CXXUnit->getOriginalSourceFileName());
Guy Benyei11169dd2012-12-18 14:30:41 +00003850}
3851
3852CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00003853 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00003854 LOG_BAD_TU(TU);
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00003855 return clang_getNullCursor();
Dmitri Gribenko256454f2014-02-11 14:34:14 +00003856 }
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00003857
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00003858 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00003859 return MakeCXCursor(CXXUnit->getASTContext().getTranslationUnitDecl(), TU);
3860}
3861
3862} // end: extern "C"
3863
3864//===----------------------------------------------------------------------===//
3865// CXFile Operations.
3866//===----------------------------------------------------------------------===//
3867
3868extern "C" {
3869CXString clang_getFileName(CXFile SFile) {
3870 if (!SFile)
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00003871 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00003872
3873 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00003874 return cxstring::createRef(FEnt->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00003875}
3876
3877time_t clang_getFileTime(CXFile SFile) {
3878 if (!SFile)
3879 return 0;
3880
3881 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
3882 return FEnt->getModificationTime();
3883}
3884
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00003885CXFile clang_getFile(CXTranslationUnit TU, const char *file_name) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00003886 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00003887 LOG_BAD_TU(TU);
Craig Topper69186e72014-06-08 08:38:04 +00003888 return nullptr;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00003889 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003890
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00003891 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00003892
3893 FileManager &FMgr = CXXUnit->getFileManager();
3894 return const_cast<FileEntry *>(FMgr.getFile(file_name));
3895}
3896
Dmitri Gribenko256454f2014-02-11 14:34:14 +00003897unsigned clang_isFileMultipleIncludeGuarded(CXTranslationUnit TU,
3898 CXFile file) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00003899 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00003900 LOG_BAD_TU(TU);
3901 return 0;
3902 }
3903
3904 if (!file)
Guy Benyei11169dd2012-12-18 14:30:41 +00003905 return 0;
3906
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00003907 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00003908 FileEntry *FEnt = static_cast<FileEntry *>(file);
3909 return CXXUnit->getPreprocessor().getHeaderSearchInfo()
3910 .isFileMultipleIncludeGuarded(FEnt);
3911}
3912
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00003913int clang_getFileUniqueID(CXFile file, CXFileUniqueID *outID) {
3914 if (!file || !outID)
3915 return 1;
3916
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00003917 FileEntry *FEnt = static_cast<FileEntry *>(file);
Rafael Espindolaf8f91b82013-08-01 21:42:11 +00003918 const llvm::sys::fs::UniqueID &ID = FEnt->getUniqueID();
3919 outID->data[0] = ID.getDevice();
3920 outID->data[1] = ID.getFile();
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00003921 outID->data[2] = FEnt->getModificationTime();
3922 return 0;
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00003923}
3924
Argyrios Kyrtzidisac3997e2014-08-16 00:26:19 +00003925int clang_File_isEqual(CXFile file1, CXFile file2) {
3926 if (file1 == file2)
3927 return true;
3928
3929 if (!file1 || !file2)
3930 return false;
3931
3932 FileEntry *FEnt1 = static_cast<FileEntry *>(file1);
3933 FileEntry *FEnt2 = static_cast<FileEntry *>(file2);
3934 return FEnt1->getUniqueID() == FEnt2->getUniqueID();
3935}
3936
Guy Benyei11169dd2012-12-18 14:30:41 +00003937} // end: extern "C"
3938
3939//===----------------------------------------------------------------------===//
3940// CXCursor Operations.
3941//===----------------------------------------------------------------------===//
3942
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00003943static const Decl *getDeclFromExpr(const Stmt *E) {
3944 if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00003945 return getDeclFromExpr(CE->getSubExpr());
3946
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00003947 if (const DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00003948 return RefExpr->getDecl();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00003949 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00003950 return ME->getMemberDecl();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00003951 if (const ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00003952 return RE->getDecl();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00003953 if (const ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003954 if (PRE->isExplicitProperty())
3955 return PRE->getExplicitProperty();
3956 // It could be messaging both getter and setter as in:
3957 // ++myobj.myprop;
3958 // in which case prefer to associate the setter since it is less obvious
3959 // from inspecting the source that the setter is going to get called.
3960 if (PRE->isMessagingSetter())
3961 return PRE->getImplicitPropertySetter();
3962 return PRE->getImplicitPropertyGetter();
3963 }
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00003964 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00003965 return getDeclFromExpr(POE->getSyntacticForm());
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00003966 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00003967 if (Expr *Src = OVE->getSourceExpr())
3968 return getDeclFromExpr(Src);
3969
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00003970 if (const CallExpr *CE = dyn_cast<CallExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00003971 return getDeclFromExpr(CE->getCallee());
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00003972 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00003973 if (!CE->isElidable())
3974 return CE->getConstructor();
Richard Smith5179eb72016-06-28 19:03:57 +00003975 if (const CXXInheritedCtorInitExpr *CE =
3976 dyn_cast<CXXInheritedCtorInitExpr>(E))
3977 return CE->getConstructor();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00003978 if (const ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00003979 return OME->getMethodDecl();
3980
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00003981 if (const ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00003982 return PE->getProtocol();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00003983 if (const SubstNonTypeTemplateParmPackExpr *NTTP
Guy Benyei11169dd2012-12-18 14:30:41 +00003984 = dyn_cast<SubstNonTypeTemplateParmPackExpr>(E))
3985 return NTTP->getParameterPack();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00003986 if (const SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00003987 if (isa<NonTypeTemplateParmDecl>(SizeOfPack->getPack()) ||
3988 isa<ParmVarDecl>(SizeOfPack->getPack()))
3989 return SizeOfPack->getPack();
Craig Topper69186e72014-06-08 08:38:04 +00003990
3991 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00003992}
3993
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003994static SourceLocation getLocationFromExpr(const Expr *E) {
3995 if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00003996 return getLocationFromExpr(CE->getSubExpr());
3997
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003998 if (const ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00003999 return /*FIXME:*/Msg->getLeftLoc();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004000 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004001 return DRE->getLocation();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004002 if (const MemberExpr *Member = dyn_cast<MemberExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004003 return Member->getMemberLoc();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004004 if (const ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004005 return Ivar->getLocation();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004006 if (const SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004007 return SizeOfPack->getPackLoc();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004008 if (const ObjCPropertyRefExpr *PropRef = dyn_cast<ObjCPropertyRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004009 return PropRef->getLocation();
4010
4011 return E->getLocStart();
4012}
4013
4014extern "C" {
4015
4016unsigned clang_visitChildren(CXCursor parent,
4017 CXCursorVisitor visitor,
4018 CXClientData client_data) {
4019 CursorVisitor CursorVis(getCursorTU(parent), visitor, client_data,
4020 /*VisitPreprocessorLast=*/false);
4021 return CursorVis.VisitChildren(parent);
4022}
4023
4024#ifndef __has_feature
4025#define __has_feature(x) 0
4026#endif
4027#if __has_feature(blocks)
4028typedef enum CXChildVisitResult
4029 (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
4030
4031static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
4032 CXClientData client_data) {
4033 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
4034 return block(cursor, parent);
4035}
4036#else
4037// If we are compiled with a compiler that doesn't have native blocks support,
4038// define and call the block manually, so the
4039typedef struct _CXChildVisitResult
4040{
4041 void *isa;
4042 int flags;
4043 int reserved;
4044 enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor,
4045 CXCursor);
4046} *CXCursorVisitorBlock;
4047
4048static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
4049 CXClientData client_data) {
4050 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
4051 return block->invoke(block, cursor, parent);
4052}
4053#endif
4054
4055
4056unsigned clang_visitChildrenWithBlock(CXCursor parent,
4057 CXCursorVisitorBlock block) {
4058 return clang_visitChildren(parent, visitWithBlock, block);
4059}
4060
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004061static CXString getDeclSpelling(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004062 if (!D)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004063 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004064
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004065 const NamedDecl *ND = dyn_cast<NamedDecl>(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00004066 if (!ND) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004067 if (const ObjCPropertyImplDecl *PropImpl =
4068 dyn_cast<ObjCPropertyImplDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00004069 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004070 return cxstring::createDup(Property->getIdentifier()->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004071
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004072 if (const ImportDecl *ImportD = dyn_cast<ImportDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00004073 if (Module *Mod = ImportD->getImportedModule())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004074 return cxstring::createDup(Mod->getFullModuleName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004075
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004076 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004077 }
4078
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004079 if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004080 return cxstring::createDup(OMD->getSelector().getAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004081
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004082 if (const ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
Guy Benyei11169dd2012-12-18 14:30:41 +00004083 // No, this isn't the same as the code below. getIdentifier() is non-virtual
4084 // and returns different names. NamedDecl returns the class name and
4085 // ObjCCategoryImplDecl returns the category name.
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004086 return cxstring::createRef(CIMP->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004087
4088 if (isa<UsingDirectiveDecl>(D))
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004089 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004090
4091 SmallString<1024> S;
4092 llvm::raw_svector_ostream os(S);
4093 ND->printName(os);
4094
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004095 return cxstring::createDup(os.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00004096}
4097
4098CXString clang_getCursorSpelling(CXCursor C) {
4099 if (clang_isTranslationUnit(C.kind))
Dmitri Gribenko2c173b42013-01-11 19:28:44 +00004100 return clang_getTranslationUnitSpelling(getCursorTU(C));
Guy Benyei11169dd2012-12-18 14:30:41 +00004101
4102 if (clang_isReference(C.kind)) {
4103 switch (C.kind) {
4104 case CXCursor_ObjCSuperClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004105 const ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004106 return cxstring::createRef(Super->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004107 }
4108 case CXCursor_ObjCClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004109 const ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004110 return cxstring::createRef(Class->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004111 }
4112 case CXCursor_ObjCProtocolRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004113 const ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004114 assert(OID && "getCursorSpelling(): Missing protocol decl");
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004115 return cxstring::createRef(OID->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004116 }
4117 case CXCursor_CXXBaseSpecifier: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004118 const CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004119 return cxstring::createDup(B->getType().getAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004120 }
4121 case CXCursor_TypeRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004122 const TypeDecl *Type = getCursorTypeRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004123 assert(Type && "Missing type decl");
4124
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004125 return cxstring::createDup(getCursorContext(C).getTypeDeclType(Type).
Guy Benyei11169dd2012-12-18 14:30:41 +00004126 getAsString());
4127 }
4128 case CXCursor_TemplateRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004129 const TemplateDecl *Template = getCursorTemplateRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004130 assert(Template && "Missing template decl");
4131
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004132 return cxstring::createDup(Template->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004133 }
4134
4135 case CXCursor_NamespaceRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004136 const NamedDecl *NS = getCursorNamespaceRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004137 assert(NS && "Missing namespace decl");
4138
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004139 return cxstring::createDup(NS->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004140 }
4141
4142 case CXCursor_MemberRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004143 const FieldDecl *Field = getCursorMemberRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004144 assert(Field && "Missing member decl");
4145
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004146 return cxstring::createDup(Field->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004147 }
4148
4149 case CXCursor_LabelRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004150 const LabelStmt *Label = getCursorLabelRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004151 assert(Label && "Missing label");
4152
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004153 return cxstring::createRef(Label->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004154 }
4155
4156 case CXCursor_OverloadedDeclRef: {
4157 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004158 if (const Decl *D = Storage.dyn_cast<const Decl *>()) {
4159 if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004160 return cxstring::createDup(ND->getNameAsString());
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004161 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004162 }
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004163 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004164 return cxstring::createDup(E->getName().getAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004165 OverloadedTemplateStorage *Ovl
4166 = Storage.get<OverloadedTemplateStorage*>();
4167 if (Ovl->size() == 0)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004168 return cxstring::createEmpty();
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004169 return cxstring::createDup((*Ovl->begin())->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004170 }
4171
4172 case CXCursor_VariableRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004173 const VarDecl *Var = getCursorVariableRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004174 assert(Var && "Missing variable decl");
4175
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004176 return cxstring::createDup(Var->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004177 }
4178
4179 default:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004180 return cxstring::createRef("<not implemented>");
Guy Benyei11169dd2012-12-18 14:30:41 +00004181 }
4182 }
4183
4184 if (clang_isExpression(C.kind)) {
Argyrios Kyrtzidis3227d862014-03-03 19:40:52 +00004185 const Expr *E = getCursorExpr(C);
4186
4187 if (C.kind == CXCursor_ObjCStringLiteral ||
4188 C.kind == CXCursor_StringLiteral) {
4189 const StringLiteral *SLit;
4190 if (const ObjCStringLiteral *OSL = dyn_cast<ObjCStringLiteral>(E)) {
4191 SLit = OSL->getString();
4192 } else {
4193 SLit = cast<StringLiteral>(E);
4194 }
4195 SmallString<256> Buf;
4196 llvm::raw_svector_ostream OS(Buf);
4197 SLit->outputString(OS);
4198 return cxstring::createDup(OS.str());
4199 }
4200
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004201 const Decl *D = getDeclFromExpr(getCursorExpr(C));
Guy Benyei11169dd2012-12-18 14:30:41 +00004202 if (D)
4203 return getDeclSpelling(D);
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004204 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004205 }
4206
4207 if (clang_isStatement(C.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004208 const Stmt *S = getCursorStmt(C);
4209 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004210 return cxstring::createRef(Label->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004211
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004212 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004213 }
4214
4215 if (C.kind == CXCursor_MacroExpansion)
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004216 return cxstring::createRef(getCursorMacroExpansion(C).getName()
Guy Benyei11169dd2012-12-18 14:30:41 +00004217 ->getNameStart());
4218
4219 if (C.kind == CXCursor_MacroDefinition)
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004220 return cxstring::createRef(getCursorMacroDefinition(C)->getName()
Guy Benyei11169dd2012-12-18 14:30:41 +00004221 ->getNameStart());
4222
4223 if (C.kind == CXCursor_InclusionDirective)
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004224 return cxstring::createDup(getCursorInclusionDirective(C)->getFileName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004225
4226 if (clang_isDeclaration(C.kind))
4227 return getDeclSpelling(getCursorDecl(C));
4228
4229 if (C.kind == CXCursor_AnnotateAttr) {
Dmitri Gribenkoe4baea62013-01-26 18:08:08 +00004230 const AnnotateAttr *AA = cast<AnnotateAttr>(cxcursor::getCursorAttr(C));
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004231 return cxstring::createDup(AA->getAnnotation());
Guy Benyei11169dd2012-12-18 14:30:41 +00004232 }
4233
4234 if (C.kind == CXCursor_AsmLabelAttr) {
Dmitri Gribenkoe4baea62013-01-26 18:08:08 +00004235 const AsmLabelAttr *AA = cast<AsmLabelAttr>(cxcursor::getCursorAttr(C));
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004236 return cxstring::createDup(AA->getLabel());
Guy Benyei11169dd2012-12-18 14:30:41 +00004237 }
4238
Argyrios Kyrtzidis16834f12013-09-25 00:14:38 +00004239 if (C.kind == CXCursor_PackedAttr) {
4240 return cxstring::createRef("packed");
4241 }
4242
Saleem Abdulrasool79c69712015-09-05 18:53:43 +00004243 if (C.kind == CXCursor_VisibilityAttr) {
4244 const VisibilityAttr *AA = cast<VisibilityAttr>(cxcursor::getCursorAttr(C));
4245 switch (AA->getVisibility()) {
4246 case VisibilityAttr::VisibilityType::Default:
4247 return cxstring::createRef("default");
4248 case VisibilityAttr::VisibilityType::Hidden:
4249 return cxstring::createRef("hidden");
4250 case VisibilityAttr::VisibilityType::Protected:
4251 return cxstring::createRef("protected");
4252 }
4253 llvm_unreachable("unknown visibility type");
4254 }
4255
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004256 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004257}
4258
4259CXSourceRange clang_Cursor_getSpellingNameRange(CXCursor C,
4260 unsigned pieceIndex,
4261 unsigned options) {
4262 if (clang_Cursor_isNull(C))
4263 return clang_getNullRange();
4264
4265 ASTContext &Ctx = getCursorContext(C);
4266
4267 if (clang_isStatement(C.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004268 const Stmt *S = getCursorStmt(C);
4269 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004270 if (pieceIndex > 0)
4271 return clang_getNullRange();
4272 return cxloc::translateSourceRange(Ctx, Label->getIdentLoc());
4273 }
4274
4275 return clang_getNullRange();
4276 }
4277
4278 if (C.kind == CXCursor_ObjCMessageExpr) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004279 if (const ObjCMessageExpr *
Guy Benyei11169dd2012-12-18 14:30:41 +00004280 ME = dyn_cast_or_null<ObjCMessageExpr>(getCursorExpr(C))) {
4281 if (pieceIndex >= ME->getNumSelectorLocs())
4282 return clang_getNullRange();
4283 return cxloc::translateSourceRange(Ctx, ME->getSelectorLoc(pieceIndex));
4284 }
4285 }
4286
4287 if (C.kind == CXCursor_ObjCInstanceMethodDecl ||
4288 C.kind == CXCursor_ObjCClassMethodDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004289 if (const ObjCMethodDecl *
Guy Benyei11169dd2012-12-18 14:30:41 +00004290 MD = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(C))) {
4291 if (pieceIndex >= MD->getNumSelectorLocs())
4292 return clang_getNullRange();
4293 return cxloc::translateSourceRange(Ctx, MD->getSelectorLoc(pieceIndex));
4294 }
4295 }
4296
4297 if (C.kind == CXCursor_ObjCCategoryDecl ||
4298 C.kind == CXCursor_ObjCCategoryImplDecl) {
4299 if (pieceIndex > 0)
4300 return clang_getNullRange();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004301 if (const ObjCCategoryDecl *
Guy Benyei11169dd2012-12-18 14:30:41 +00004302 CD = dyn_cast_or_null<ObjCCategoryDecl>(getCursorDecl(C)))
4303 return cxloc::translateSourceRange(Ctx, CD->getCategoryNameLoc());
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004304 if (const ObjCCategoryImplDecl *
Guy Benyei11169dd2012-12-18 14:30:41 +00004305 CID = dyn_cast_or_null<ObjCCategoryImplDecl>(getCursorDecl(C)))
4306 return cxloc::translateSourceRange(Ctx, CID->getCategoryNameLoc());
4307 }
4308
4309 if (C.kind == CXCursor_ModuleImportDecl) {
4310 if (pieceIndex > 0)
4311 return clang_getNullRange();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004312 if (const ImportDecl *ImportD =
4313 dyn_cast_or_null<ImportDecl>(getCursorDecl(C))) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004314 ArrayRef<SourceLocation> Locs = ImportD->getIdentifierLocs();
4315 if (!Locs.empty())
4316 return cxloc::translateSourceRange(Ctx,
4317 SourceRange(Locs.front(), Locs.back()));
4318 }
4319 return clang_getNullRange();
4320 }
4321
Argyrios Kyrtzidisa2a1e532014-08-26 20:23:26 +00004322 if (C.kind == CXCursor_CXXMethod || C.kind == CXCursor_Destructor ||
4323 C.kind == CXCursor_ConversionFunction) {
4324 if (pieceIndex > 0)
4325 return clang_getNullRange();
4326 if (const FunctionDecl *FD =
4327 dyn_cast_or_null<FunctionDecl>(getCursorDecl(C))) {
4328 DeclarationNameInfo FunctionName = FD->getNameInfo();
4329 return cxloc::translateSourceRange(Ctx, FunctionName.getSourceRange());
4330 }
4331 return clang_getNullRange();
4332 }
4333
Guy Benyei11169dd2012-12-18 14:30:41 +00004334 // FIXME: A CXCursor_InclusionDirective should give the location of the
4335 // filename, but we don't keep track of this.
4336
4337 // FIXME: A CXCursor_AnnotateAttr should give the location of the annotation
4338 // but we don't keep track of this.
4339
4340 // FIXME: A CXCursor_AsmLabelAttr should give the location of the label
4341 // but we don't keep track of this.
4342
4343 // Default handling, give the location of the cursor.
4344
4345 if (pieceIndex > 0)
4346 return clang_getNullRange();
4347
4348 CXSourceLocation CXLoc = clang_getCursorLocation(C);
4349 SourceLocation Loc = cxloc::translateSourceLocation(CXLoc);
4350 return cxloc::translateSourceRange(Ctx, Loc);
4351}
4352
Eli Bendersky44a206f2014-07-31 18:04:56 +00004353CXString clang_Cursor_getMangling(CXCursor C) {
4354 if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
4355 return cxstring::createEmpty();
4356
Eli Bendersky44a206f2014-07-31 18:04:56 +00004357 // Mangling only works for functions and variables.
Eli Bendersky79759592014-08-01 15:01:10 +00004358 const Decl *D = getCursorDecl(C);
Eli Bendersky44a206f2014-07-31 18:04:56 +00004359 if (!D || !(isa<FunctionDecl>(D) || isa<VarDecl>(D)))
4360 return cxstring::createEmpty();
4361
Argyrios Kyrtzidisca741ce2016-02-14 22:30:14 +00004362 ASTContext &Ctx = D->getASTContext();
4363 index::CodegenNameGenerator CGNameGen(Ctx);
4364 return cxstring::createDup(CGNameGen.getName(D));
Eli Bendersky44a206f2014-07-31 18:04:56 +00004365}
4366
Saleem Abdulrasool60034432015-11-12 03:57:22 +00004367CXStringSet *clang_Cursor_getCXXManglings(CXCursor C) {
4368 if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
4369 return nullptr;
4370
4371 const Decl *D = getCursorDecl(C);
4372 if (!(isa<CXXRecordDecl>(D) || isa<CXXMethodDecl>(D)))
4373 return nullptr;
4374
Argyrios Kyrtzidisca741ce2016-02-14 22:30:14 +00004375 ASTContext &Ctx = D->getASTContext();
4376 index::CodegenNameGenerator CGNameGen(Ctx);
4377 std::vector<std::string> Manglings = CGNameGen.getAllManglings(D);
Saleem Abdulrasool60034432015-11-12 03:57:22 +00004378 return cxstring::createSet(Manglings);
4379}
4380
Guy Benyei11169dd2012-12-18 14:30:41 +00004381CXString clang_getCursorDisplayName(CXCursor C) {
4382 if (!clang_isDeclaration(C.kind))
4383 return clang_getCursorSpelling(C);
4384
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004385 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00004386 if (!D)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004387 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004388
4389 PrintingPolicy Policy = getCursorContext(C).getPrintingPolicy();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004390 if (const FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00004391 D = FunTmpl->getTemplatedDecl();
4392
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004393 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004394 SmallString<64> Str;
4395 llvm::raw_svector_ostream OS(Str);
4396 OS << *Function;
4397 if (Function->getPrimaryTemplate())
4398 OS << "<>";
4399 OS << "(";
4400 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
4401 if (I)
4402 OS << ", ";
4403 OS << Function->getParamDecl(I)->getType().getAsString(Policy);
4404 }
4405
4406 if (Function->isVariadic()) {
4407 if (Function->getNumParams())
4408 OS << ", ";
4409 OS << "...";
4410 }
4411 OS << ")";
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004412 return cxstring::createDup(OS.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00004413 }
4414
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004415 if (const ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004416 SmallString<64> Str;
4417 llvm::raw_svector_ostream OS(Str);
4418 OS << *ClassTemplate;
4419 OS << "<";
4420 TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
4421 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
4422 if (I)
4423 OS << ", ";
4424
4425 NamedDecl *Param = Params->getParam(I);
4426 if (Param->getIdentifier()) {
4427 OS << Param->getIdentifier()->getName();
4428 continue;
4429 }
4430
4431 // There is no parameter name, which makes this tricky. Try to come up
4432 // with something useful that isn't too long.
4433 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
4434 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
4435 else if (NonTypeTemplateParmDecl *NTTP
4436 = dyn_cast<NonTypeTemplateParmDecl>(Param))
4437 OS << NTTP->getType().getAsString(Policy);
4438 else
4439 OS << "template<...> class";
4440 }
4441
4442 OS << ">";
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004443 return cxstring::createDup(OS.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00004444 }
4445
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004446 if (const ClassTemplateSpecializationDecl *ClassSpec
Guy Benyei11169dd2012-12-18 14:30:41 +00004447 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
4448 // If the type was explicitly written, use that.
4449 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004450 return cxstring::createDup(TSInfo->getType().getAsString(Policy));
Guy Benyei11169dd2012-12-18 14:30:41 +00004451
Benjamin Kramer9170e912013-02-22 15:46:01 +00004452 SmallString<128> Str;
Guy Benyei11169dd2012-12-18 14:30:41 +00004453 llvm::raw_svector_ostream OS(Str);
4454 OS << *ClassSpec;
Benjamin Kramer9170e912013-02-22 15:46:01 +00004455 TemplateSpecializationType::PrintTemplateArgumentList(OS,
Guy Benyei11169dd2012-12-18 14:30:41 +00004456 ClassSpec->getTemplateArgs().data(),
4457 ClassSpec->getTemplateArgs().size(),
4458 Policy);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004459 return cxstring::createDup(OS.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00004460 }
4461
4462 return clang_getCursorSpelling(C);
4463}
4464
4465CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
4466 switch (Kind) {
4467 case CXCursor_FunctionDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004468 return cxstring::createRef("FunctionDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004469 case CXCursor_TypedefDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004470 return cxstring::createRef("TypedefDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004471 case CXCursor_EnumDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004472 return cxstring::createRef("EnumDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004473 case CXCursor_EnumConstantDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004474 return cxstring::createRef("EnumConstantDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004475 case CXCursor_StructDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004476 return cxstring::createRef("StructDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004477 case CXCursor_UnionDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004478 return cxstring::createRef("UnionDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004479 case CXCursor_ClassDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004480 return cxstring::createRef("ClassDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004481 case CXCursor_FieldDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004482 return cxstring::createRef("FieldDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004483 case CXCursor_VarDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004484 return cxstring::createRef("VarDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004485 case CXCursor_ParmDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004486 return cxstring::createRef("ParmDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004487 case CXCursor_ObjCInterfaceDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004488 return cxstring::createRef("ObjCInterfaceDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004489 case CXCursor_ObjCCategoryDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004490 return cxstring::createRef("ObjCCategoryDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004491 case CXCursor_ObjCProtocolDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004492 return cxstring::createRef("ObjCProtocolDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004493 case CXCursor_ObjCPropertyDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004494 return cxstring::createRef("ObjCPropertyDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004495 case CXCursor_ObjCIvarDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004496 return cxstring::createRef("ObjCIvarDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004497 case CXCursor_ObjCInstanceMethodDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004498 return cxstring::createRef("ObjCInstanceMethodDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004499 case CXCursor_ObjCClassMethodDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004500 return cxstring::createRef("ObjCClassMethodDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004501 case CXCursor_ObjCImplementationDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004502 return cxstring::createRef("ObjCImplementationDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004503 case CXCursor_ObjCCategoryImplDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004504 return cxstring::createRef("ObjCCategoryImplDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004505 case CXCursor_CXXMethod:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004506 return cxstring::createRef("CXXMethod");
Guy Benyei11169dd2012-12-18 14:30:41 +00004507 case CXCursor_UnexposedDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004508 return cxstring::createRef("UnexposedDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004509 case CXCursor_ObjCSuperClassRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004510 return cxstring::createRef("ObjCSuperClassRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00004511 case CXCursor_ObjCProtocolRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004512 return cxstring::createRef("ObjCProtocolRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00004513 case CXCursor_ObjCClassRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004514 return cxstring::createRef("ObjCClassRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00004515 case CXCursor_TypeRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004516 return cxstring::createRef("TypeRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00004517 case CXCursor_TemplateRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004518 return cxstring::createRef("TemplateRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00004519 case CXCursor_NamespaceRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004520 return cxstring::createRef("NamespaceRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00004521 case CXCursor_MemberRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004522 return cxstring::createRef("MemberRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00004523 case CXCursor_LabelRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004524 return cxstring::createRef("LabelRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00004525 case CXCursor_OverloadedDeclRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004526 return cxstring::createRef("OverloadedDeclRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00004527 case CXCursor_VariableRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004528 return cxstring::createRef("VariableRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00004529 case CXCursor_IntegerLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004530 return cxstring::createRef("IntegerLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00004531 case CXCursor_FloatingLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004532 return cxstring::createRef("FloatingLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00004533 case CXCursor_ImaginaryLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004534 return cxstring::createRef("ImaginaryLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00004535 case CXCursor_StringLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004536 return cxstring::createRef("StringLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00004537 case CXCursor_CharacterLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004538 return cxstring::createRef("CharacterLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00004539 case CXCursor_ParenExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004540 return cxstring::createRef("ParenExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004541 case CXCursor_UnaryOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004542 return cxstring::createRef("UnaryOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00004543 case CXCursor_ArraySubscriptExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004544 return cxstring::createRef("ArraySubscriptExpr");
Alexey Bataev1a3320e2015-08-25 14:24:04 +00004545 case CXCursor_OMPArraySectionExpr:
4546 return cxstring::createRef("OMPArraySectionExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004547 case CXCursor_BinaryOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004548 return cxstring::createRef("BinaryOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00004549 case CXCursor_CompoundAssignOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004550 return cxstring::createRef("CompoundAssignOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00004551 case CXCursor_ConditionalOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004552 return cxstring::createRef("ConditionalOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00004553 case CXCursor_CStyleCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004554 return cxstring::createRef("CStyleCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004555 case CXCursor_CompoundLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004556 return cxstring::createRef("CompoundLiteralExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004557 case CXCursor_InitListExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004558 return cxstring::createRef("InitListExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004559 case CXCursor_AddrLabelExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004560 return cxstring::createRef("AddrLabelExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004561 case CXCursor_StmtExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004562 return cxstring::createRef("StmtExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004563 case CXCursor_GenericSelectionExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004564 return cxstring::createRef("GenericSelectionExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004565 case CXCursor_GNUNullExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004566 return cxstring::createRef("GNUNullExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004567 case CXCursor_CXXStaticCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004568 return cxstring::createRef("CXXStaticCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004569 case CXCursor_CXXDynamicCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004570 return cxstring::createRef("CXXDynamicCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004571 case CXCursor_CXXReinterpretCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004572 return cxstring::createRef("CXXReinterpretCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004573 case CXCursor_CXXConstCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004574 return cxstring::createRef("CXXConstCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004575 case CXCursor_CXXFunctionalCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004576 return cxstring::createRef("CXXFunctionalCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004577 case CXCursor_CXXTypeidExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004578 return cxstring::createRef("CXXTypeidExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004579 case CXCursor_CXXBoolLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004580 return cxstring::createRef("CXXBoolLiteralExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004581 case CXCursor_CXXNullPtrLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004582 return cxstring::createRef("CXXNullPtrLiteralExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004583 case CXCursor_CXXThisExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004584 return cxstring::createRef("CXXThisExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004585 case CXCursor_CXXThrowExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004586 return cxstring::createRef("CXXThrowExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004587 case CXCursor_CXXNewExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004588 return cxstring::createRef("CXXNewExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004589 case CXCursor_CXXDeleteExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004590 return cxstring::createRef("CXXDeleteExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004591 case CXCursor_UnaryExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004592 return cxstring::createRef("UnaryExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004593 case CXCursor_ObjCStringLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004594 return cxstring::createRef("ObjCStringLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00004595 case CXCursor_ObjCBoolLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004596 return cxstring::createRef("ObjCBoolLiteralExpr");
Argyrios Kyrtzidisc2233be2013-04-23 17:57:17 +00004597 case CXCursor_ObjCSelfExpr:
4598 return cxstring::createRef("ObjCSelfExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004599 case CXCursor_ObjCEncodeExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004600 return cxstring::createRef("ObjCEncodeExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004601 case CXCursor_ObjCSelectorExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004602 return cxstring::createRef("ObjCSelectorExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004603 case CXCursor_ObjCProtocolExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004604 return cxstring::createRef("ObjCProtocolExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004605 case CXCursor_ObjCBridgedCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004606 return cxstring::createRef("ObjCBridgedCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004607 case CXCursor_BlockExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004608 return cxstring::createRef("BlockExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004609 case CXCursor_PackExpansionExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004610 return cxstring::createRef("PackExpansionExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004611 case CXCursor_SizeOfPackExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004612 return cxstring::createRef("SizeOfPackExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004613 case CXCursor_LambdaExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004614 return cxstring::createRef("LambdaExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004615 case CXCursor_UnexposedExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004616 return cxstring::createRef("UnexposedExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004617 case CXCursor_DeclRefExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004618 return cxstring::createRef("DeclRefExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004619 case CXCursor_MemberRefExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004620 return cxstring::createRef("MemberRefExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004621 case CXCursor_CallExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004622 return cxstring::createRef("CallExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004623 case CXCursor_ObjCMessageExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004624 return cxstring::createRef("ObjCMessageExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004625 case CXCursor_UnexposedStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004626 return cxstring::createRef("UnexposedStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004627 case CXCursor_DeclStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004628 return cxstring::createRef("DeclStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004629 case CXCursor_LabelStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004630 return cxstring::createRef("LabelStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004631 case CXCursor_CompoundStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004632 return cxstring::createRef("CompoundStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004633 case CXCursor_CaseStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004634 return cxstring::createRef("CaseStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004635 case CXCursor_DefaultStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004636 return cxstring::createRef("DefaultStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004637 case CXCursor_IfStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004638 return cxstring::createRef("IfStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004639 case CXCursor_SwitchStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004640 return cxstring::createRef("SwitchStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004641 case CXCursor_WhileStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004642 return cxstring::createRef("WhileStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004643 case CXCursor_DoStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004644 return cxstring::createRef("DoStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004645 case CXCursor_ForStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004646 return cxstring::createRef("ForStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004647 case CXCursor_GotoStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004648 return cxstring::createRef("GotoStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004649 case CXCursor_IndirectGotoStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004650 return cxstring::createRef("IndirectGotoStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004651 case CXCursor_ContinueStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004652 return cxstring::createRef("ContinueStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004653 case CXCursor_BreakStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004654 return cxstring::createRef("BreakStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004655 case CXCursor_ReturnStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004656 return cxstring::createRef("ReturnStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004657 case CXCursor_GCCAsmStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004658 return cxstring::createRef("GCCAsmStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004659 case CXCursor_MSAsmStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004660 return cxstring::createRef("MSAsmStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004661 case CXCursor_ObjCAtTryStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004662 return cxstring::createRef("ObjCAtTryStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004663 case CXCursor_ObjCAtCatchStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004664 return cxstring::createRef("ObjCAtCatchStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004665 case CXCursor_ObjCAtFinallyStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004666 return cxstring::createRef("ObjCAtFinallyStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004667 case CXCursor_ObjCAtThrowStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004668 return cxstring::createRef("ObjCAtThrowStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004669 case CXCursor_ObjCAtSynchronizedStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004670 return cxstring::createRef("ObjCAtSynchronizedStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004671 case CXCursor_ObjCAutoreleasePoolStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004672 return cxstring::createRef("ObjCAutoreleasePoolStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004673 case CXCursor_ObjCForCollectionStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004674 return cxstring::createRef("ObjCForCollectionStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004675 case CXCursor_CXXCatchStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004676 return cxstring::createRef("CXXCatchStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004677 case CXCursor_CXXTryStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004678 return cxstring::createRef("CXXTryStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004679 case CXCursor_CXXForRangeStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004680 return cxstring::createRef("CXXForRangeStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004681 case CXCursor_SEHTryStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004682 return cxstring::createRef("SEHTryStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004683 case CXCursor_SEHExceptStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004684 return cxstring::createRef("SEHExceptStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004685 case CXCursor_SEHFinallyStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004686 return cxstring::createRef("SEHFinallyStmt");
Nico Weber9b982072014-07-07 00:12:30 +00004687 case CXCursor_SEHLeaveStmt:
4688 return cxstring::createRef("SEHLeaveStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004689 case CXCursor_NullStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004690 return cxstring::createRef("NullStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004691 case CXCursor_InvalidFile:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004692 return cxstring::createRef("InvalidFile");
Guy Benyei11169dd2012-12-18 14:30:41 +00004693 case CXCursor_InvalidCode:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004694 return cxstring::createRef("InvalidCode");
Guy Benyei11169dd2012-12-18 14:30:41 +00004695 case CXCursor_NoDeclFound:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004696 return cxstring::createRef("NoDeclFound");
Guy Benyei11169dd2012-12-18 14:30:41 +00004697 case CXCursor_NotImplemented:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004698 return cxstring::createRef("NotImplemented");
Guy Benyei11169dd2012-12-18 14:30:41 +00004699 case CXCursor_TranslationUnit:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004700 return cxstring::createRef("TranslationUnit");
Guy Benyei11169dd2012-12-18 14:30:41 +00004701 case CXCursor_UnexposedAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004702 return cxstring::createRef("UnexposedAttr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004703 case CXCursor_IBActionAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004704 return cxstring::createRef("attribute(ibaction)");
Guy Benyei11169dd2012-12-18 14:30:41 +00004705 case CXCursor_IBOutletAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004706 return cxstring::createRef("attribute(iboutlet)");
Guy Benyei11169dd2012-12-18 14:30:41 +00004707 case CXCursor_IBOutletCollectionAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004708 return cxstring::createRef("attribute(iboutletcollection)");
Guy Benyei11169dd2012-12-18 14:30:41 +00004709 case CXCursor_CXXFinalAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004710 return cxstring::createRef("attribute(final)");
Guy Benyei11169dd2012-12-18 14:30:41 +00004711 case CXCursor_CXXOverrideAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004712 return cxstring::createRef("attribute(override)");
Guy Benyei11169dd2012-12-18 14:30:41 +00004713 case CXCursor_AnnotateAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004714 return cxstring::createRef("attribute(annotate)");
Guy Benyei11169dd2012-12-18 14:30:41 +00004715 case CXCursor_AsmLabelAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004716 return cxstring::createRef("asm label");
Argyrios Kyrtzidis16834f12013-09-25 00:14:38 +00004717 case CXCursor_PackedAttr:
4718 return cxstring::createRef("attribute(packed)");
Joey Gouly81228382014-05-01 15:41:58 +00004719 case CXCursor_PureAttr:
4720 return cxstring::createRef("attribute(pure)");
4721 case CXCursor_ConstAttr:
4722 return cxstring::createRef("attribute(const)");
4723 case CXCursor_NoDuplicateAttr:
4724 return cxstring::createRef("attribute(noduplicate)");
Eli Bendersky2581e662014-05-28 19:29:58 +00004725 case CXCursor_CUDAConstantAttr:
4726 return cxstring::createRef("attribute(constant)");
4727 case CXCursor_CUDADeviceAttr:
4728 return cxstring::createRef("attribute(device)");
4729 case CXCursor_CUDAGlobalAttr:
4730 return cxstring::createRef("attribute(global)");
4731 case CXCursor_CUDAHostAttr:
4732 return cxstring::createRef("attribute(host)");
Eli Bendersky9b071472014-08-08 14:59:00 +00004733 case CXCursor_CUDASharedAttr:
4734 return cxstring::createRef("attribute(shared)");
Saleem Abdulrasool79c69712015-09-05 18:53:43 +00004735 case CXCursor_VisibilityAttr:
4736 return cxstring::createRef("attribute(visibility)");
Saleem Abdulrasool8aa0b802015-12-10 18:45:18 +00004737 case CXCursor_DLLExport:
4738 return cxstring::createRef("attribute(dllexport)");
4739 case CXCursor_DLLImport:
4740 return cxstring::createRef("attribute(dllimport)");
Guy Benyei11169dd2012-12-18 14:30:41 +00004741 case CXCursor_PreprocessingDirective:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004742 return cxstring::createRef("preprocessing directive");
Guy Benyei11169dd2012-12-18 14:30:41 +00004743 case CXCursor_MacroDefinition:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004744 return cxstring::createRef("macro definition");
Guy Benyei11169dd2012-12-18 14:30:41 +00004745 case CXCursor_MacroExpansion:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004746 return cxstring::createRef("macro expansion");
Guy Benyei11169dd2012-12-18 14:30:41 +00004747 case CXCursor_InclusionDirective:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004748 return cxstring::createRef("inclusion directive");
Guy Benyei11169dd2012-12-18 14:30:41 +00004749 case CXCursor_Namespace:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004750 return cxstring::createRef("Namespace");
Guy Benyei11169dd2012-12-18 14:30:41 +00004751 case CXCursor_LinkageSpec:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004752 return cxstring::createRef("LinkageSpec");
Guy Benyei11169dd2012-12-18 14:30:41 +00004753 case CXCursor_CXXBaseSpecifier:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004754 return cxstring::createRef("C++ base class specifier");
Guy Benyei11169dd2012-12-18 14:30:41 +00004755 case CXCursor_Constructor:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004756 return cxstring::createRef("CXXConstructor");
Guy Benyei11169dd2012-12-18 14:30:41 +00004757 case CXCursor_Destructor:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004758 return cxstring::createRef("CXXDestructor");
Guy Benyei11169dd2012-12-18 14:30:41 +00004759 case CXCursor_ConversionFunction:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004760 return cxstring::createRef("CXXConversion");
Guy Benyei11169dd2012-12-18 14:30:41 +00004761 case CXCursor_TemplateTypeParameter:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004762 return cxstring::createRef("TemplateTypeParameter");
Guy Benyei11169dd2012-12-18 14:30:41 +00004763 case CXCursor_NonTypeTemplateParameter:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004764 return cxstring::createRef("NonTypeTemplateParameter");
Guy Benyei11169dd2012-12-18 14:30:41 +00004765 case CXCursor_TemplateTemplateParameter:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004766 return cxstring::createRef("TemplateTemplateParameter");
Guy Benyei11169dd2012-12-18 14:30:41 +00004767 case CXCursor_FunctionTemplate:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004768 return cxstring::createRef("FunctionTemplate");
Guy Benyei11169dd2012-12-18 14:30:41 +00004769 case CXCursor_ClassTemplate:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004770 return cxstring::createRef("ClassTemplate");
Guy Benyei11169dd2012-12-18 14:30:41 +00004771 case CXCursor_ClassTemplatePartialSpecialization:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004772 return cxstring::createRef("ClassTemplatePartialSpecialization");
Guy Benyei11169dd2012-12-18 14:30:41 +00004773 case CXCursor_NamespaceAlias:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004774 return cxstring::createRef("NamespaceAlias");
Guy Benyei11169dd2012-12-18 14:30:41 +00004775 case CXCursor_UsingDirective:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004776 return cxstring::createRef("UsingDirective");
Guy Benyei11169dd2012-12-18 14:30:41 +00004777 case CXCursor_UsingDeclaration:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004778 return cxstring::createRef("UsingDeclaration");
Guy Benyei11169dd2012-12-18 14:30:41 +00004779 case CXCursor_TypeAliasDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004780 return cxstring::createRef("TypeAliasDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004781 case CXCursor_ObjCSynthesizeDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004782 return cxstring::createRef("ObjCSynthesizeDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004783 case CXCursor_ObjCDynamicDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004784 return cxstring::createRef("ObjCDynamicDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004785 case CXCursor_CXXAccessSpecifier:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004786 return cxstring::createRef("CXXAccessSpecifier");
Guy Benyei11169dd2012-12-18 14:30:41 +00004787 case CXCursor_ModuleImportDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004788 return cxstring::createRef("ModuleImport");
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004789 case CXCursor_OMPParallelDirective:
Alexey Bataev1b59ab52014-02-27 08:29:12 +00004790 return cxstring::createRef("OMPParallelDirective");
4791 case CXCursor_OMPSimdDirective:
4792 return cxstring::createRef("OMPSimdDirective");
Alexey Bataevf29276e2014-06-18 04:14:57 +00004793 case CXCursor_OMPForDirective:
4794 return cxstring::createRef("OMPForDirective");
Alexander Musmanf82886e2014-09-18 05:12:34 +00004795 case CXCursor_OMPForSimdDirective:
4796 return cxstring::createRef("OMPForSimdDirective");
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004797 case CXCursor_OMPSectionsDirective:
4798 return cxstring::createRef("OMPSectionsDirective");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004799 case CXCursor_OMPSectionDirective:
4800 return cxstring::createRef("OMPSectionDirective");
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00004801 case CXCursor_OMPSingleDirective:
4802 return cxstring::createRef("OMPSingleDirective");
Alexander Musman80c22892014-07-17 08:54:58 +00004803 case CXCursor_OMPMasterDirective:
4804 return cxstring::createRef("OMPMasterDirective");
Alexander Musmand9ed09f2014-07-21 09:42:05 +00004805 case CXCursor_OMPCriticalDirective:
4806 return cxstring::createRef("OMPCriticalDirective");
Alexey Bataev4acb8592014-07-07 13:01:15 +00004807 case CXCursor_OMPParallelForDirective:
4808 return cxstring::createRef("OMPParallelForDirective");
Alexander Musmane4e893b2014-09-23 09:33:00 +00004809 case CXCursor_OMPParallelForSimdDirective:
4810 return cxstring::createRef("OMPParallelForSimdDirective");
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004811 case CXCursor_OMPParallelSectionsDirective:
4812 return cxstring::createRef("OMPParallelSectionsDirective");
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004813 case CXCursor_OMPTaskDirective:
4814 return cxstring::createRef("OMPTaskDirective");
Alexey Bataev68446b72014-07-18 07:47:19 +00004815 case CXCursor_OMPTaskyieldDirective:
4816 return cxstring::createRef("OMPTaskyieldDirective");
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00004817 case CXCursor_OMPBarrierDirective:
4818 return cxstring::createRef("OMPBarrierDirective");
Alexey Bataev2df347a2014-07-18 10:17:07 +00004819 case CXCursor_OMPTaskwaitDirective:
4820 return cxstring::createRef("OMPTaskwaitDirective");
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00004821 case CXCursor_OMPTaskgroupDirective:
4822 return cxstring::createRef("OMPTaskgroupDirective");
Alexey Bataev6125da92014-07-21 11:26:11 +00004823 case CXCursor_OMPFlushDirective:
4824 return cxstring::createRef("OMPFlushDirective");
Alexey Bataev9fb6e642014-07-22 06:45:04 +00004825 case CXCursor_OMPOrderedDirective:
4826 return cxstring::createRef("OMPOrderedDirective");
Alexey Bataev0162e452014-07-22 10:10:35 +00004827 case CXCursor_OMPAtomicDirective:
4828 return cxstring::createRef("OMPAtomicDirective");
Alexey Bataev0bd520b2014-09-19 08:19:49 +00004829 case CXCursor_OMPTargetDirective:
4830 return cxstring::createRef("OMPTargetDirective");
Michael Wong65f367f2015-07-21 13:44:28 +00004831 case CXCursor_OMPTargetDataDirective:
4832 return cxstring::createRef("OMPTargetDataDirective");
Samuel Antaodf67fc42016-01-19 19:15:56 +00004833 case CXCursor_OMPTargetEnterDataDirective:
4834 return cxstring::createRef("OMPTargetEnterDataDirective");
Samuel Antao72590762016-01-19 20:04:50 +00004835 case CXCursor_OMPTargetExitDataDirective:
4836 return cxstring::createRef("OMPTargetExitDataDirective");
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00004837 case CXCursor_OMPTargetParallelDirective:
4838 return cxstring::createRef("OMPTargetParallelDirective");
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00004839 case CXCursor_OMPTargetParallelForDirective:
4840 return cxstring::createRef("OMPTargetParallelForDirective");
Samuel Antao686c70c2016-05-26 17:30:50 +00004841 case CXCursor_OMPTargetUpdateDirective:
4842 return cxstring::createRef("OMPTargetUpdateDirective");
Alexey Bataev13314bf2014-10-09 04:18:56 +00004843 case CXCursor_OMPTeamsDirective:
4844 return cxstring::createRef("OMPTeamsDirective");
Alexey Bataev6d4ed052015-07-01 06:57:41 +00004845 case CXCursor_OMPCancellationPointDirective:
4846 return cxstring::createRef("OMPCancellationPointDirective");
Alexey Bataev80909872015-07-02 11:25:17 +00004847 case CXCursor_OMPCancelDirective:
4848 return cxstring::createRef("OMPCancelDirective");
Alexey Bataev49f6e782015-12-01 04:18:41 +00004849 case CXCursor_OMPTaskLoopDirective:
4850 return cxstring::createRef("OMPTaskLoopDirective");
Alexey Bataev0a6ed842015-12-03 09:40:15 +00004851 case CXCursor_OMPTaskLoopSimdDirective:
4852 return cxstring::createRef("OMPTaskLoopSimdDirective");
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004853 case CXCursor_OMPDistributeDirective:
4854 return cxstring::createRef("OMPDistributeDirective");
Carlo Bertolli9925f152016-06-27 14:55:37 +00004855 case CXCursor_OMPDistributeParallelForDirective:
4856 return cxstring::createRef("OMPDistributeParallelForDirective");
Kelvin Li4a39add2016-07-05 05:00:15 +00004857 case CXCursor_OMPDistributeParallelForSimdDirective:
4858 return cxstring::createRef("OMPDistributeParallelForSimdDirective");
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00004859 case CXCursor_OverloadCandidate:
4860 return cxstring::createRef("OverloadCandidate");
Sergey Kalinichev8f3b1872015-11-15 13:48:32 +00004861 case CXCursor_TypeAliasTemplateDecl:
4862 return cxstring::createRef("TypeAliasTemplateDecl");
Olivier Goffart81978012016-06-09 16:15:55 +00004863 case CXCursor_StaticAssert:
4864 return cxstring::createRef("StaticAssert");
Guy Benyei11169dd2012-12-18 14:30:41 +00004865 }
4866
4867 llvm_unreachable("Unhandled CXCursorKind");
4868}
4869
4870struct GetCursorData {
4871 SourceLocation TokenBeginLoc;
4872 bool PointsAtMacroArgExpansion;
4873 bool VisitedObjCPropertyImplDecl;
4874 SourceLocation VisitedDeclaratorDeclStartLoc;
4875 CXCursor &BestCursor;
4876
4877 GetCursorData(SourceManager &SM,
4878 SourceLocation tokenBegin, CXCursor &outputCursor)
4879 : TokenBeginLoc(tokenBegin), BestCursor(outputCursor) {
4880 PointsAtMacroArgExpansion = SM.isMacroArgExpansion(tokenBegin);
4881 VisitedObjCPropertyImplDecl = false;
4882 }
4883};
4884
4885static enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
4886 CXCursor parent,
4887 CXClientData client_data) {
4888 GetCursorData *Data = static_cast<GetCursorData *>(client_data);
4889 CXCursor *BestCursor = &Data->BestCursor;
4890
4891 // If we point inside a macro argument we should provide info of what the
4892 // token is so use the actual cursor, don't replace it with a macro expansion
4893 // cursor.
4894 if (cursor.kind == CXCursor_MacroExpansion && Data->PointsAtMacroArgExpansion)
4895 return CXChildVisit_Recurse;
4896
4897 if (clang_isDeclaration(cursor.kind)) {
4898 // Avoid having the implicit methods override the property decls.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004899 if (const ObjCMethodDecl *MD
Guy Benyei11169dd2012-12-18 14:30:41 +00004900 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
4901 if (MD->isImplicit())
4902 return CXChildVisit_Break;
4903
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004904 } else if (const ObjCInterfaceDecl *ID
Guy Benyei11169dd2012-12-18 14:30:41 +00004905 = dyn_cast_or_null<ObjCInterfaceDecl>(getCursorDecl(cursor))) {
4906 // Check that when we have multiple @class references in the same line,
4907 // that later ones do not override the previous ones.
4908 // If we have:
4909 // @class Foo, Bar;
4910 // source ranges for both start at '@', so 'Bar' will end up overriding
4911 // 'Foo' even though the cursor location was at 'Foo'.
4912 if (BestCursor->kind == CXCursor_ObjCInterfaceDecl ||
4913 BestCursor->kind == CXCursor_ObjCClassRef)
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004914 if (const ObjCInterfaceDecl *PrevID
Guy Benyei11169dd2012-12-18 14:30:41 +00004915 = dyn_cast_or_null<ObjCInterfaceDecl>(getCursorDecl(*BestCursor))){
4916 if (PrevID != ID &&
4917 !PrevID->isThisDeclarationADefinition() &&
4918 !ID->isThisDeclarationADefinition())
4919 return CXChildVisit_Break;
4920 }
4921
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004922 } else if (const DeclaratorDecl *DD
Guy Benyei11169dd2012-12-18 14:30:41 +00004923 = dyn_cast_or_null<DeclaratorDecl>(getCursorDecl(cursor))) {
4924 SourceLocation StartLoc = DD->getSourceRange().getBegin();
4925 // Check that when we have multiple declarators in the same line,
4926 // that later ones do not override the previous ones.
4927 // If we have:
4928 // int Foo, Bar;
4929 // source ranges for both start at 'int', so 'Bar' will end up overriding
4930 // 'Foo' even though the cursor location was at 'Foo'.
4931 if (Data->VisitedDeclaratorDeclStartLoc == StartLoc)
4932 return CXChildVisit_Break;
4933 Data->VisitedDeclaratorDeclStartLoc = StartLoc;
4934
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004935 } else if (const ObjCPropertyImplDecl *PropImp
Guy Benyei11169dd2012-12-18 14:30:41 +00004936 = dyn_cast_or_null<ObjCPropertyImplDecl>(getCursorDecl(cursor))) {
4937 (void)PropImp;
4938 // Check that when we have multiple @synthesize in the same line,
4939 // that later ones do not override the previous ones.
4940 // If we have:
4941 // @synthesize Foo, Bar;
4942 // source ranges for both start at '@', so 'Bar' will end up overriding
4943 // 'Foo' even though the cursor location was at 'Foo'.
4944 if (Data->VisitedObjCPropertyImplDecl)
4945 return CXChildVisit_Break;
4946 Data->VisitedObjCPropertyImplDecl = true;
4947 }
4948 }
4949
4950 if (clang_isExpression(cursor.kind) &&
4951 clang_isDeclaration(BestCursor->kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004952 if (const Decl *D = getCursorDecl(*BestCursor)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004953 // Avoid having the cursor of an expression replace the declaration cursor
4954 // when the expression source range overlaps the declaration range.
4955 // This can happen for C++ constructor expressions whose range generally
4956 // include the variable declaration, e.g.:
4957 // MyCXXClass foo; // Make sure pointing at 'foo' returns a VarDecl cursor.
4958 if (D->getLocation().isValid() && Data->TokenBeginLoc.isValid() &&
4959 D->getLocation() == Data->TokenBeginLoc)
4960 return CXChildVisit_Break;
4961 }
4962 }
4963
4964 // If our current best cursor is the construction of a temporary object,
4965 // don't replace that cursor with a type reference, because we want
4966 // clang_getCursor() to point at the constructor.
4967 if (clang_isExpression(BestCursor->kind) &&
4968 isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
4969 cursor.kind == CXCursor_TypeRef) {
4970 // Keep the cursor pointing at CXXTemporaryObjectExpr but also mark it
4971 // as having the actual point on the type reference.
4972 *BestCursor = getTypeRefedCallExprCursor(*BestCursor);
4973 return CXChildVisit_Recurse;
4974 }
Douglas Gregore9d95f12015-07-07 03:57:35 +00004975
4976 // If we already have an Objective-C superclass reference, don't
4977 // update it further.
4978 if (BestCursor->kind == CXCursor_ObjCSuperClassRef)
4979 return CXChildVisit_Break;
4980
Guy Benyei11169dd2012-12-18 14:30:41 +00004981 *BestCursor = cursor;
4982 return CXChildVisit_Recurse;
4983}
4984
4985CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004986 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004987 LOG_BAD_TU(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004988 return clang_getNullCursor();
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004989 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004990
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004991 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004992 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
4993
4994 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
4995 CXCursor Result = cxcursor::getCursor(TU, SLoc);
4996
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00004997 LOG_FUNC_SECTION {
Guy Benyei11169dd2012-12-18 14:30:41 +00004998 CXFile SearchFile;
4999 unsigned SearchLine, SearchColumn;
5000 CXFile ResultFile;
5001 unsigned ResultLine, ResultColumn;
5002 CXString SearchFileName, ResultFileName, KindSpelling, USR;
5003 const char *IsDef = clang_isCursorDefinition(Result)? " (Definition)" : "";
5004 CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
Craig Topper69186e72014-06-08 08:38:04 +00005005
5006 clang_getFileLocation(Loc, &SearchFile, &SearchLine, &SearchColumn,
5007 nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005008 clang_getFileLocation(ResultLoc, &ResultFile, &ResultLine,
Craig Topper69186e72014-06-08 08:38:04 +00005009 &ResultColumn, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005010 SearchFileName = clang_getFileName(SearchFile);
5011 ResultFileName = clang_getFileName(ResultFile);
5012 KindSpelling = clang_getCursorKindSpelling(Result.kind);
5013 USR = clang_getCursorUSR(Result);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005014 *Log << llvm::format("(%s:%d:%d) = %s",
5015 clang_getCString(SearchFileName), SearchLine, SearchColumn,
5016 clang_getCString(KindSpelling))
5017 << llvm::format("(%s:%d:%d):%s%s",
5018 clang_getCString(ResultFileName), ResultLine, ResultColumn,
5019 clang_getCString(USR), IsDef);
Guy Benyei11169dd2012-12-18 14:30:41 +00005020 clang_disposeString(SearchFileName);
5021 clang_disposeString(ResultFileName);
5022 clang_disposeString(KindSpelling);
5023 clang_disposeString(USR);
5024
5025 CXCursor Definition = clang_getCursorDefinition(Result);
5026 if (!clang_equalCursors(Definition, clang_getNullCursor())) {
5027 CXSourceLocation DefinitionLoc = clang_getCursorLocation(Definition);
5028 CXString DefinitionKindSpelling
5029 = clang_getCursorKindSpelling(Definition.kind);
5030 CXFile DefinitionFile;
5031 unsigned DefinitionLine, DefinitionColumn;
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005032 clang_getFileLocation(DefinitionLoc, &DefinitionFile,
Craig Topper69186e72014-06-08 08:38:04 +00005033 &DefinitionLine, &DefinitionColumn, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005034 CXString DefinitionFileName = clang_getFileName(DefinitionFile);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005035 *Log << llvm::format(" -> %s(%s:%d:%d)",
5036 clang_getCString(DefinitionKindSpelling),
5037 clang_getCString(DefinitionFileName),
5038 DefinitionLine, DefinitionColumn);
Guy Benyei11169dd2012-12-18 14:30:41 +00005039 clang_disposeString(DefinitionFileName);
5040 clang_disposeString(DefinitionKindSpelling);
5041 }
5042 }
5043
5044 return Result;
5045}
5046
5047CXCursor clang_getNullCursor(void) {
5048 return MakeCXCursorInvalid(CXCursor_InvalidFile);
5049}
5050
5051unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Argyrios Kyrtzidisbf1be592013-01-08 18:23:28 +00005052 // Clear out the "FirstInDeclGroup" part in a declaration cursor, since we
5053 // can't set consistently. For example, when visiting a DeclStmt we will set
5054 // it but we don't set it on the result of clang_getCursorDefinition for
5055 // a reference of the same declaration.
5056 // FIXME: Setting "FirstInDeclGroup" in CXCursors is a hack that only works
5057 // when visiting a DeclStmt currently, the AST should be enhanced to be able
5058 // to provide that kind of info.
5059 if (clang_isDeclaration(X.kind))
Craig Topper69186e72014-06-08 08:38:04 +00005060 X.data[1] = nullptr;
Argyrios Kyrtzidisbf1be592013-01-08 18:23:28 +00005061 if (clang_isDeclaration(Y.kind))
Craig Topper69186e72014-06-08 08:38:04 +00005062 Y.data[1] = nullptr;
Argyrios Kyrtzidisbf1be592013-01-08 18:23:28 +00005063
Guy Benyei11169dd2012-12-18 14:30:41 +00005064 return X == Y;
5065}
5066
5067unsigned clang_hashCursor(CXCursor C) {
5068 unsigned Index = 0;
5069 if (clang_isExpression(C.kind) || clang_isStatement(C.kind))
5070 Index = 1;
5071
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005072 return llvm::DenseMapInfo<std::pair<unsigned, const void*> >::getHashValue(
Guy Benyei11169dd2012-12-18 14:30:41 +00005073 std::make_pair(C.kind, C.data[Index]));
5074}
5075
5076unsigned clang_isInvalid(enum CXCursorKind K) {
5077 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
5078}
5079
5080unsigned clang_isDeclaration(enum CXCursorKind K) {
5081 return (K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl) ||
5082 (K >= CXCursor_FirstExtraDecl && K <= CXCursor_LastExtraDecl);
5083}
5084
5085unsigned clang_isReference(enum CXCursorKind K) {
5086 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
5087}
5088
5089unsigned clang_isExpression(enum CXCursorKind K) {
5090 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
5091}
5092
5093unsigned clang_isStatement(enum CXCursorKind K) {
5094 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
5095}
5096
5097unsigned clang_isAttribute(enum CXCursorKind K) {
5098 return K >= CXCursor_FirstAttr && K <= CXCursor_LastAttr;
5099}
5100
5101unsigned clang_isTranslationUnit(enum CXCursorKind K) {
5102 return K == CXCursor_TranslationUnit;
5103}
5104
5105unsigned clang_isPreprocessing(enum CXCursorKind K) {
5106 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
5107}
5108
5109unsigned clang_isUnexposed(enum CXCursorKind K) {
5110 switch (K) {
5111 case CXCursor_UnexposedDecl:
5112 case CXCursor_UnexposedExpr:
5113 case CXCursor_UnexposedStmt:
5114 case CXCursor_UnexposedAttr:
5115 return true;
5116 default:
5117 return false;
5118 }
5119}
5120
5121CXCursorKind clang_getCursorKind(CXCursor C) {
5122 return C.kind;
5123}
5124
5125CXSourceLocation clang_getCursorLocation(CXCursor C) {
5126 if (clang_isReference(C.kind)) {
5127 switch (C.kind) {
5128 case CXCursor_ObjCSuperClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005129 std::pair<const ObjCInterfaceDecl *, SourceLocation> P
Guy Benyei11169dd2012-12-18 14:30:41 +00005130 = getCursorObjCSuperClassRef(C);
5131 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5132 }
5133
5134 case CXCursor_ObjCProtocolRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005135 std::pair<const ObjCProtocolDecl *, SourceLocation> P
Guy Benyei11169dd2012-12-18 14:30:41 +00005136 = getCursorObjCProtocolRef(C);
5137 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5138 }
5139
5140 case CXCursor_ObjCClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005141 std::pair<const ObjCInterfaceDecl *, SourceLocation> P
Guy Benyei11169dd2012-12-18 14:30:41 +00005142 = getCursorObjCClassRef(C);
5143 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5144 }
5145
5146 case CXCursor_TypeRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005147 std::pair<const TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005148 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5149 }
5150
5151 case CXCursor_TemplateRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005152 std::pair<const TemplateDecl *, SourceLocation> P =
5153 getCursorTemplateRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005154 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5155 }
5156
5157 case CXCursor_NamespaceRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005158 std::pair<const NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005159 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5160 }
5161
5162 case CXCursor_MemberRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005163 std::pair<const FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005164 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5165 }
5166
5167 case CXCursor_VariableRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005168 std::pair<const VarDecl *, SourceLocation> P = getCursorVariableRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005169 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5170 }
5171
5172 case CXCursor_CXXBaseSpecifier: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005173 const CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005174 if (!BaseSpec)
5175 return clang_getNullLocation();
5176
5177 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
5178 return cxloc::translateSourceLocation(getCursorContext(C),
5179 TSInfo->getTypeLoc().getBeginLoc());
5180
5181 return cxloc::translateSourceLocation(getCursorContext(C),
5182 BaseSpec->getLocStart());
5183 }
5184
5185 case CXCursor_LabelRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005186 std::pair<const LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005187 return cxloc::translateSourceLocation(getCursorContext(C), P.second);
5188 }
5189
5190 case CXCursor_OverloadedDeclRef:
5191 return cxloc::translateSourceLocation(getCursorContext(C),
5192 getCursorOverloadedDeclRef(C).second);
5193
5194 default:
5195 // FIXME: Need a way to enumerate all non-reference cases.
5196 llvm_unreachable("Missed a reference kind");
5197 }
5198 }
5199
5200 if (clang_isExpression(C.kind))
5201 return cxloc::translateSourceLocation(getCursorContext(C),
5202 getLocationFromExpr(getCursorExpr(C)));
5203
5204 if (clang_isStatement(C.kind))
5205 return cxloc::translateSourceLocation(getCursorContext(C),
5206 getCursorStmt(C)->getLocStart());
5207
5208 if (C.kind == CXCursor_PreprocessingDirective) {
5209 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
5210 return cxloc::translateSourceLocation(getCursorContext(C), L);
5211 }
5212
5213 if (C.kind == CXCursor_MacroExpansion) {
5214 SourceLocation L
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00005215 = cxcursor::getCursorMacroExpansion(C).getSourceRange().getBegin();
Guy Benyei11169dd2012-12-18 14:30:41 +00005216 return cxloc::translateSourceLocation(getCursorContext(C), L);
5217 }
5218
5219 if (C.kind == CXCursor_MacroDefinition) {
5220 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
5221 return cxloc::translateSourceLocation(getCursorContext(C), L);
5222 }
5223
5224 if (C.kind == CXCursor_InclusionDirective) {
5225 SourceLocation L
5226 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
5227 return cxloc::translateSourceLocation(getCursorContext(C), L);
5228 }
5229
Argyrios Kyrtzidis16834f12013-09-25 00:14:38 +00005230 if (clang_isAttribute(C.kind)) {
5231 SourceLocation L
5232 = cxcursor::getCursorAttr(C)->getLocation();
5233 return cxloc::translateSourceLocation(getCursorContext(C), L);
5234 }
5235
Guy Benyei11169dd2012-12-18 14:30:41 +00005236 if (!clang_isDeclaration(C.kind))
5237 return clang_getNullLocation();
5238
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005239 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005240 if (!D)
5241 return clang_getNullLocation();
5242
5243 SourceLocation Loc = D->getLocation();
5244 // FIXME: Multiple variables declared in a single declaration
5245 // currently lack the information needed to correctly determine their
5246 // ranges when accounting for the type-specifier. We use context
5247 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
5248 // and if so, whether it is the first decl.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005249 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005250 if (!cxcursor::isFirstInDeclGroup(C))
5251 Loc = VD->getLocation();
5252 }
5253
5254 // For ObjC methods, give the start location of the method name.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005255 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00005256 Loc = MD->getSelectorStartLoc();
5257
5258 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
5259}
5260
5261} // end extern "C"
5262
5263CXCursor cxcursor::getCursor(CXTranslationUnit TU, SourceLocation SLoc) {
5264 assert(TU);
5265
5266 // Guard against an invalid SourceLocation, or we may assert in one
5267 // of the following calls.
5268 if (SLoc.isInvalid())
5269 return clang_getNullCursor();
5270
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00005271 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00005272
5273 // Translate the given source location to make it point at the beginning of
5274 // the token under the cursor.
5275 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
5276 CXXUnit->getASTContext().getLangOpts());
5277
5278 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
5279 if (SLoc.isValid()) {
5280 GetCursorData ResultData(CXXUnit->getSourceManager(), SLoc, Result);
5281 CursorVisitor CursorVis(TU, GetCursorVisitor, &ResultData,
5282 /*VisitPreprocessorLast=*/true,
5283 /*VisitIncludedEntities=*/false,
5284 SourceLocation(SLoc));
5285 CursorVis.visitFileRegion();
5286 }
5287
5288 return Result;
5289}
5290
5291static SourceRange getRawCursorExtent(CXCursor C) {
5292 if (clang_isReference(C.kind)) {
5293 switch (C.kind) {
5294 case CXCursor_ObjCSuperClassRef:
5295 return getCursorObjCSuperClassRef(C).second;
5296
5297 case CXCursor_ObjCProtocolRef:
5298 return getCursorObjCProtocolRef(C).second;
5299
5300 case CXCursor_ObjCClassRef:
5301 return getCursorObjCClassRef(C).second;
5302
5303 case CXCursor_TypeRef:
5304 return getCursorTypeRef(C).second;
5305
5306 case CXCursor_TemplateRef:
5307 return getCursorTemplateRef(C).second;
5308
5309 case CXCursor_NamespaceRef:
5310 return getCursorNamespaceRef(C).second;
5311
5312 case CXCursor_MemberRef:
5313 return getCursorMemberRef(C).second;
5314
5315 case CXCursor_CXXBaseSpecifier:
5316 return getCursorCXXBaseSpecifier(C)->getSourceRange();
5317
5318 case CXCursor_LabelRef:
5319 return getCursorLabelRef(C).second;
5320
5321 case CXCursor_OverloadedDeclRef:
5322 return getCursorOverloadedDeclRef(C).second;
5323
5324 case CXCursor_VariableRef:
5325 return getCursorVariableRef(C).second;
5326
5327 default:
5328 // FIXME: Need a way to enumerate all non-reference cases.
5329 llvm_unreachable("Missed a reference kind");
5330 }
5331 }
5332
5333 if (clang_isExpression(C.kind))
5334 return getCursorExpr(C)->getSourceRange();
5335
5336 if (clang_isStatement(C.kind))
5337 return getCursorStmt(C)->getSourceRange();
5338
5339 if (clang_isAttribute(C.kind))
5340 return getCursorAttr(C)->getRange();
5341
5342 if (C.kind == CXCursor_PreprocessingDirective)
5343 return cxcursor::getCursorPreprocessingDirective(C);
5344
5345 if (C.kind == CXCursor_MacroExpansion) {
5346 ASTUnit *TU = getCursorASTUnit(C);
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00005347 SourceRange Range = cxcursor::getCursorMacroExpansion(C).getSourceRange();
Guy Benyei11169dd2012-12-18 14:30:41 +00005348 return TU->mapRangeFromPreamble(Range);
5349 }
5350
5351 if (C.kind == CXCursor_MacroDefinition) {
5352 ASTUnit *TU = getCursorASTUnit(C);
5353 SourceRange Range = cxcursor::getCursorMacroDefinition(C)->getSourceRange();
5354 return TU->mapRangeFromPreamble(Range);
5355 }
5356
5357 if (C.kind == CXCursor_InclusionDirective) {
5358 ASTUnit *TU = getCursorASTUnit(C);
5359 SourceRange Range = cxcursor::getCursorInclusionDirective(C)->getSourceRange();
5360 return TU->mapRangeFromPreamble(Range);
5361 }
5362
5363 if (C.kind == CXCursor_TranslationUnit) {
5364 ASTUnit *TU = getCursorASTUnit(C);
5365 FileID MainID = TU->getSourceManager().getMainFileID();
5366 SourceLocation Start = TU->getSourceManager().getLocForStartOfFile(MainID);
5367 SourceLocation End = TU->getSourceManager().getLocForEndOfFile(MainID);
5368 return SourceRange(Start, End);
5369 }
5370
5371 if (clang_isDeclaration(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005372 const Decl *D = cxcursor::getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005373 if (!D)
5374 return SourceRange();
5375
5376 SourceRange R = D->getSourceRange();
5377 // FIXME: Multiple variables declared in a single declaration
5378 // currently lack the information needed to correctly determine their
5379 // ranges when accounting for the type-specifier. We use context
5380 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
5381 // and if so, whether it is the first decl.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005382 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005383 if (!cxcursor::isFirstInDeclGroup(C))
5384 R.setBegin(VD->getLocation());
5385 }
5386 return R;
5387 }
5388 return SourceRange();
5389}
5390
5391/// \brief Retrieves the "raw" cursor extent, which is then extended to include
5392/// the decl-specifier-seq for declarations.
5393static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr) {
5394 if (clang_isDeclaration(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005395 const Decl *D = cxcursor::getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005396 if (!D)
5397 return SourceRange();
5398
5399 SourceRange R = D->getSourceRange();
5400
5401 // Adjust the start of the location for declarations preceded by
5402 // declaration specifiers.
5403 SourceLocation StartLoc;
5404 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
5405 if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
5406 StartLoc = TI->getTypeLoc().getLocStart();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005407 } else if (const TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005408 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
5409 StartLoc = TI->getTypeLoc().getLocStart();
5410 }
5411
5412 if (StartLoc.isValid() && R.getBegin().isValid() &&
5413 SrcMgr.isBeforeInTranslationUnit(StartLoc, R.getBegin()))
5414 R.setBegin(StartLoc);
5415
5416 // FIXME: Multiple variables declared in a single declaration
5417 // currently lack the information needed to correctly determine their
5418 // ranges when accounting for the type-specifier. We use context
5419 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
5420 // and if so, whether it is the first decl.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005421 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005422 if (!cxcursor::isFirstInDeclGroup(C))
5423 R.setBegin(VD->getLocation());
5424 }
5425
5426 return R;
5427 }
5428
5429 return getRawCursorExtent(C);
5430}
5431
5432extern "C" {
5433
5434CXSourceRange clang_getCursorExtent(CXCursor C) {
5435 SourceRange R = getRawCursorExtent(C);
5436 if (R.isInvalid())
5437 return clang_getNullRange();
5438
5439 return cxloc::translateSourceRange(getCursorContext(C), R);
5440}
5441
5442CXCursor clang_getCursorReferenced(CXCursor C) {
5443 if (clang_isInvalid(C.kind))
5444 return clang_getNullCursor();
5445
5446 CXTranslationUnit tu = getCursorTU(C);
5447 if (clang_isDeclaration(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005448 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005449 if (!D)
5450 return clang_getNullCursor();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005451 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00005452 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), tu);
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005453 if (const ObjCPropertyImplDecl *PropImpl =
5454 dyn_cast<ObjCPropertyImplDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00005455 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
5456 return MakeCXCursor(Property, tu);
5457
5458 return C;
5459 }
5460
5461 if (clang_isExpression(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005462 const Expr *E = getCursorExpr(C);
5463 const Decl *D = getDeclFromExpr(E);
Guy Benyei11169dd2012-12-18 14:30:41 +00005464 if (D) {
5465 CXCursor declCursor = MakeCXCursor(D, tu);
5466 declCursor = getSelectorIdentifierCursor(getSelectorIdentifierIndex(C),
5467 declCursor);
5468 return declCursor;
5469 }
5470
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005471 if (const OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00005472 return MakeCursorOverloadedDeclRef(Ovl, tu);
5473
5474 return clang_getNullCursor();
5475 }
5476
5477 if (clang_isStatement(C.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00005478 const Stmt *S = getCursorStmt(C);
5479 if (const GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
Guy Benyei11169dd2012-12-18 14:30:41 +00005480 if (LabelDecl *label = Goto->getLabel())
5481 if (LabelStmt *labelS = label->getStmt())
5482 return MakeCXCursor(labelS, getCursorDecl(C), tu);
5483
5484 return clang_getNullCursor();
5485 }
Richard Smith66a81862015-05-04 02:25:31 +00005486
Guy Benyei11169dd2012-12-18 14:30:41 +00005487 if (C.kind == CXCursor_MacroExpansion) {
Richard Smith66a81862015-05-04 02:25:31 +00005488 if (const MacroDefinitionRecord *Def =
5489 getCursorMacroExpansion(C).getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00005490 return MakeMacroDefinitionCursor(Def, tu);
5491 }
5492
5493 if (!clang_isReference(C.kind))
5494 return clang_getNullCursor();
5495
5496 switch (C.kind) {
5497 case CXCursor_ObjCSuperClassRef:
5498 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, tu);
5499
5500 case CXCursor_ObjCProtocolRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005501 const ObjCProtocolDecl *Prot = getCursorObjCProtocolRef(C).first;
5502 if (const ObjCProtocolDecl *Def = Prot->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00005503 return MakeCXCursor(Def, tu);
5504
5505 return MakeCXCursor(Prot, tu);
5506 }
5507
5508 case CXCursor_ObjCClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005509 const ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
5510 if (const ObjCInterfaceDecl *Def = Class->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00005511 return MakeCXCursor(Def, tu);
5512
5513 return MakeCXCursor(Class, tu);
5514 }
5515
5516 case CXCursor_TypeRef:
5517 return MakeCXCursor(getCursorTypeRef(C).first, tu );
5518
5519 case CXCursor_TemplateRef:
5520 return MakeCXCursor(getCursorTemplateRef(C).first, tu );
5521
5522 case CXCursor_NamespaceRef:
5523 return MakeCXCursor(getCursorNamespaceRef(C).first, tu );
5524
5525 case CXCursor_MemberRef:
5526 return MakeCXCursor(getCursorMemberRef(C).first, tu );
5527
5528 case CXCursor_CXXBaseSpecifier: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005529 const CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005530 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
5531 tu ));
5532 }
5533
5534 case CXCursor_LabelRef:
5535 // FIXME: We end up faking the "parent" declaration here because we
5536 // don't want to make CXCursor larger.
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00005537 return MakeCXCursor(getCursorLabelRef(C).first,
5538 cxtu::getASTUnit(tu)->getASTContext()
5539 .getTranslationUnitDecl(),
Guy Benyei11169dd2012-12-18 14:30:41 +00005540 tu);
5541
5542 case CXCursor_OverloadedDeclRef:
5543 return C;
5544
5545 case CXCursor_VariableRef:
5546 return MakeCXCursor(getCursorVariableRef(C).first, tu);
5547
5548 default:
5549 // We would prefer to enumerate all non-reference cursor kinds here.
5550 llvm_unreachable("Unhandled reference cursor kind");
5551 }
5552}
5553
5554CXCursor clang_getCursorDefinition(CXCursor C) {
5555 if (clang_isInvalid(C.kind))
5556 return clang_getNullCursor();
5557
5558 CXTranslationUnit TU = getCursorTU(C);
5559
5560 bool WasReference = false;
5561 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
5562 C = clang_getCursorReferenced(C);
5563 WasReference = true;
5564 }
5565
5566 if (C.kind == CXCursor_MacroExpansion)
5567 return clang_getCursorReferenced(C);
5568
5569 if (!clang_isDeclaration(C.kind))
5570 return clang_getNullCursor();
5571
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005572 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005573 if (!D)
5574 return clang_getNullCursor();
5575
5576 switch (D->getKind()) {
5577 // Declaration kinds that don't really separate the notions of
5578 // declaration and definition.
5579 case Decl::Namespace:
5580 case Decl::Typedef:
5581 case Decl::TypeAlias:
5582 case Decl::TypeAliasTemplate:
5583 case Decl::TemplateTypeParm:
5584 case Decl::EnumConstant:
5585 case Decl::Field:
John McCall5e77d762013-04-16 07:28:30 +00005586 case Decl::MSProperty:
Guy Benyei11169dd2012-12-18 14:30:41 +00005587 case Decl::IndirectField:
5588 case Decl::ObjCIvar:
5589 case Decl::ObjCAtDefsField:
5590 case Decl::ImplicitParam:
5591 case Decl::ParmVar:
5592 case Decl::NonTypeTemplateParm:
5593 case Decl::TemplateTemplateParm:
5594 case Decl::ObjCCategoryImpl:
5595 case Decl::ObjCImplementation:
5596 case Decl::AccessSpec:
5597 case Decl::LinkageSpec:
5598 case Decl::ObjCPropertyImpl:
5599 case Decl::FileScopeAsm:
5600 case Decl::StaticAssert:
5601 case Decl::Block:
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00005602 case Decl::Captured:
Alexey Bataev4244be22016-02-11 05:35:55 +00005603 case Decl::OMPCapturedExpr:
Guy Benyei11169dd2012-12-18 14:30:41 +00005604 case Decl::Label: // FIXME: Is this right??
5605 case Decl::ClassScopeFunctionSpecialization:
5606 case Decl::Import:
Alexey Bataeva769e072013-03-22 06:34:35 +00005607 case Decl::OMPThreadPrivate:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00005608 case Decl::OMPDeclareReduction:
Douglas Gregor85f3f952015-07-07 03:57:15 +00005609 case Decl::ObjCTypeParam:
David Majnemerd9b1a4f2015-11-04 03:40:30 +00005610 case Decl::BuiltinTemplate:
Nico Weber66220292016-03-02 17:28:48 +00005611 case Decl::PragmaComment:
Nico Webercbbaeb12016-03-02 19:28:54 +00005612 case Decl::PragmaDetectMismatch:
Guy Benyei11169dd2012-12-18 14:30:41 +00005613 return C;
5614
5615 // Declaration kinds that don't make any sense here, but are
5616 // nonetheless harmless.
David Blaikief005d3c2013-02-22 17:44:58 +00005617 case Decl::Empty:
Guy Benyei11169dd2012-12-18 14:30:41 +00005618 case Decl::TranslationUnit:
Richard Smithf19e1272015-03-07 00:04:49 +00005619 case Decl::ExternCContext:
Guy Benyei11169dd2012-12-18 14:30:41 +00005620 break;
5621
5622 // Declaration kinds for which the definition is not resolvable.
5623 case Decl::UnresolvedUsingTypename:
5624 case Decl::UnresolvedUsingValue:
5625 break;
5626
5627 case Decl::UsingDirective:
5628 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
5629 TU);
5630
5631 case Decl::NamespaceAlias:
5632 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), TU);
5633
5634 case Decl::Enum:
5635 case Decl::Record:
5636 case Decl::CXXRecord:
5637 case Decl::ClassTemplateSpecialization:
5638 case Decl::ClassTemplatePartialSpecialization:
5639 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
5640 return MakeCXCursor(Def, TU);
5641 return clang_getNullCursor();
5642
5643 case Decl::Function:
5644 case Decl::CXXMethod:
5645 case Decl::CXXConstructor:
5646 case Decl::CXXDestructor:
5647 case Decl::CXXConversion: {
Craig Topper69186e72014-06-08 08:38:04 +00005648 const FunctionDecl *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005649 if (cast<FunctionDecl>(D)->getBody(Def))
Dmitri Gribenko9c256e32013-01-14 00:46:27 +00005650 return MakeCXCursor(Def, TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00005651 return clang_getNullCursor();
5652 }
5653
Larisse Voufo39a1e502013-08-06 01:03:05 +00005654 case Decl::Var:
5655 case Decl::VarTemplateSpecialization:
5656 case Decl::VarTemplatePartialSpecialization: {
Guy Benyei11169dd2012-12-18 14:30:41 +00005657 // Ask the variable if it has a definition.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005658 if (const VarDecl *Def = cast<VarDecl>(D)->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00005659 return MakeCXCursor(Def, TU);
5660 return clang_getNullCursor();
5661 }
5662
5663 case Decl::FunctionTemplate: {
Craig Topper69186e72014-06-08 08:38:04 +00005664 const FunctionDecl *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005665 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
5666 return MakeCXCursor(Def->getDescribedFunctionTemplate(), TU);
5667 return clang_getNullCursor();
5668 }
5669
5670 case Decl::ClassTemplate: {
5671 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
5672 ->getDefinition())
5673 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
5674 TU);
5675 return clang_getNullCursor();
5676 }
5677
Larisse Voufo39a1e502013-08-06 01:03:05 +00005678 case Decl::VarTemplate: {
5679 if (VarDecl *Def =
5680 cast<VarTemplateDecl>(D)->getTemplatedDecl()->getDefinition())
5681 return MakeCXCursor(cast<VarDecl>(Def)->getDescribedVarTemplate(), TU);
5682 return clang_getNullCursor();
5683 }
5684
Guy Benyei11169dd2012-12-18 14:30:41 +00005685 case Decl::Using:
5686 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
5687 D->getLocation(), TU);
5688
5689 case Decl::UsingShadow:
Richard Smith5179eb72016-06-28 19:03:57 +00005690 case Decl::ConstructorUsingShadow:
Guy Benyei11169dd2012-12-18 14:30:41 +00005691 return clang_getCursorDefinition(
5692 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
5693 TU));
5694
5695 case Decl::ObjCMethod: {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005696 const ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00005697 if (Method->isThisDeclarationADefinition())
5698 return C;
5699
5700 // Dig out the method definition in the associated
5701 // @implementation, if we have it.
5702 // FIXME: The ASTs should make finding the definition easier.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005703 if (const ObjCInterfaceDecl *Class
Guy Benyei11169dd2012-12-18 14:30:41 +00005704 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
5705 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
5706 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
5707 Method->isInstanceMethod()))
5708 if (Def->isThisDeclarationADefinition())
5709 return MakeCXCursor(Def, TU);
5710
5711 return clang_getNullCursor();
5712 }
5713
5714 case Decl::ObjCCategory:
5715 if (ObjCCategoryImplDecl *Impl
5716 = cast<ObjCCategoryDecl>(D)->getImplementation())
5717 return MakeCXCursor(Impl, TU);
5718 return clang_getNullCursor();
5719
5720 case Decl::ObjCProtocol:
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005721 if (const ObjCProtocolDecl *Def = cast<ObjCProtocolDecl>(D)->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00005722 return MakeCXCursor(Def, TU);
5723 return clang_getNullCursor();
5724
5725 case Decl::ObjCInterface: {
5726 // There are two notions of a "definition" for an Objective-C
5727 // class: the interface and its implementation. When we resolved a
5728 // reference to an Objective-C class, produce the @interface as
5729 // the definition; when we were provided with the interface,
5730 // produce the @implementation as the definition.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005731 const ObjCInterfaceDecl *IFace = cast<ObjCInterfaceDecl>(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00005732 if (WasReference) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005733 if (const ObjCInterfaceDecl *Def = IFace->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00005734 return MakeCXCursor(Def, TU);
5735 } else if (ObjCImplementationDecl *Impl = IFace->getImplementation())
5736 return MakeCXCursor(Impl, TU);
5737 return clang_getNullCursor();
5738 }
5739
5740 case Decl::ObjCProperty:
5741 // FIXME: We don't really know where to find the
5742 // ObjCPropertyImplDecls that implement this property.
5743 return clang_getNullCursor();
5744
5745 case Decl::ObjCCompatibleAlias:
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005746 if (const ObjCInterfaceDecl *Class
Guy Benyei11169dd2012-12-18 14:30:41 +00005747 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005748 if (const ObjCInterfaceDecl *Def = Class->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00005749 return MakeCXCursor(Def, TU);
5750
5751 return clang_getNullCursor();
5752
5753 case Decl::Friend:
5754 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
5755 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
5756 return clang_getNullCursor();
5757
5758 case Decl::FriendTemplate:
5759 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
5760 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
5761 return clang_getNullCursor();
5762 }
5763
5764 return clang_getNullCursor();
5765}
5766
5767unsigned clang_isCursorDefinition(CXCursor C) {
5768 if (!clang_isDeclaration(C.kind))
5769 return 0;
5770
5771 return clang_getCursorDefinition(C) == C;
5772}
5773
5774CXCursor clang_getCanonicalCursor(CXCursor C) {
5775 if (!clang_isDeclaration(C.kind))
5776 return C;
5777
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005778 if (const Decl *D = getCursorDecl(C)) {
5779 if (const ObjCCategoryImplDecl *CatImplD = dyn_cast<ObjCCategoryImplDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00005780 if (ObjCCategoryDecl *CatD = CatImplD->getCategoryDecl())
5781 return MakeCXCursor(CatD, getCursorTU(C));
5782
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005783 if (const ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
5784 if (const ObjCInterfaceDecl *IFD = ImplD->getClassInterface())
Guy Benyei11169dd2012-12-18 14:30:41 +00005785 return MakeCXCursor(IFD, getCursorTU(C));
5786
5787 return MakeCXCursor(D->getCanonicalDecl(), getCursorTU(C));
5788 }
5789
5790 return C;
5791}
5792
5793int clang_Cursor_getObjCSelectorIndex(CXCursor cursor) {
5794 return cxcursor::getSelectorIdentifierIndexAndLoc(cursor).first;
5795}
5796
5797unsigned clang_getNumOverloadedDecls(CXCursor C) {
5798 if (C.kind != CXCursor_OverloadedDeclRef)
5799 return 0;
5800
5801 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005802 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
Guy Benyei11169dd2012-12-18 14:30:41 +00005803 return E->getNumDecls();
5804
5805 if (OverloadedTemplateStorage *S
5806 = Storage.dyn_cast<OverloadedTemplateStorage*>())
5807 return S->size();
5808
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005809 const Decl *D = Storage.get<const Decl *>();
5810 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00005811 return Using->shadow_size();
5812
5813 return 0;
5814}
5815
5816CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
5817 if (cursor.kind != CXCursor_OverloadedDeclRef)
5818 return clang_getNullCursor();
5819
5820 if (index >= clang_getNumOverloadedDecls(cursor))
5821 return clang_getNullCursor();
5822
5823 CXTranslationUnit TU = getCursorTU(cursor);
5824 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005825 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
Guy Benyei11169dd2012-12-18 14:30:41 +00005826 return MakeCXCursor(E->decls_begin()[index], TU);
5827
5828 if (OverloadedTemplateStorage *S
5829 = Storage.dyn_cast<OverloadedTemplateStorage*>())
5830 return MakeCXCursor(S->begin()[index], TU);
5831
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005832 const Decl *D = Storage.get<const Decl *>();
5833 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005834 // FIXME: This is, unfortunately, linear time.
5835 UsingDecl::shadow_iterator Pos = Using->shadow_begin();
5836 std::advance(Pos, index);
5837 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), TU);
5838 }
5839
5840 return clang_getNullCursor();
5841}
5842
5843void clang_getDefinitionSpellingAndExtent(CXCursor C,
5844 const char **startBuf,
5845 const char **endBuf,
5846 unsigned *startLine,
5847 unsigned *startColumn,
5848 unsigned *endLine,
5849 unsigned *endColumn) {
5850 assert(getCursorDecl(C) && "CXCursor has null decl");
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005851 const FunctionDecl *FD = dyn_cast<FunctionDecl>(getCursorDecl(C));
Guy Benyei11169dd2012-12-18 14:30:41 +00005852 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
5853
5854 SourceManager &SM = FD->getASTContext().getSourceManager();
5855 *startBuf = SM.getCharacterData(Body->getLBracLoc());
5856 *endBuf = SM.getCharacterData(Body->getRBracLoc());
5857 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
5858 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
5859 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
5860 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
5861}
5862
5863
5864CXSourceRange clang_getCursorReferenceNameRange(CXCursor C, unsigned NameFlags,
5865 unsigned PieceIndex) {
5866 RefNamePieces Pieces;
5867
5868 switch (C.kind) {
5869 case CXCursor_MemberRefExpr:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00005870 if (const MemberExpr *E = dyn_cast<MemberExpr>(getCursorExpr(C)))
Guy Benyei11169dd2012-12-18 14:30:41 +00005871 Pieces = buildPieces(NameFlags, true, E->getMemberNameInfo(),
5872 E->getQualifierLoc().getSourceRange());
5873 break;
5874
5875 case CXCursor_DeclRefExpr:
James Y Knight04ec5bf2015-12-24 02:59:37 +00005876 if (const DeclRefExpr *E = dyn_cast<DeclRefExpr>(getCursorExpr(C))) {
5877 SourceRange TemplateArgLoc(E->getLAngleLoc(), E->getRAngleLoc());
5878 Pieces =
5879 buildPieces(NameFlags, false, E->getNameInfo(),
5880 E->getQualifierLoc().getSourceRange(), &TemplateArgLoc);
5881 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005882 break;
5883
5884 case CXCursor_CallExpr:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00005885 if (const CXXOperatorCallExpr *OCE =
Guy Benyei11169dd2012-12-18 14:30:41 +00005886 dyn_cast<CXXOperatorCallExpr>(getCursorExpr(C))) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00005887 const Expr *Callee = OCE->getCallee();
5888 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Callee))
Guy Benyei11169dd2012-12-18 14:30:41 +00005889 Callee = ICE->getSubExpr();
5890
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00005891 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Callee))
Guy Benyei11169dd2012-12-18 14:30:41 +00005892 Pieces = buildPieces(NameFlags, false, DRE->getNameInfo(),
5893 DRE->getQualifierLoc().getSourceRange());
5894 }
5895 break;
5896
5897 default:
5898 break;
5899 }
5900
5901 if (Pieces.empty()) {
5902 if (PieceIndex == 0)
5903 return clang_getCursorExtent(C);
5904 } else if (PieceIndex < Pieces.size()) {
5905 SourceRange R = Pieces[PieceIndex];
5906 if (R.isValid())
5907 return cxloc::translateSourceRange(getCursorContext(C), R);
5908 }
5909
5910 return clang_getNullRange();
5911}
5912
5913void clang_enableStackTraces(void) {
Richard Smithdfed58a2016-06-09 00:53:41 +00005914 // FIXME: Provide an argv0 here so we can find llvm-symbolizer.
5915 llvm::sys::PrintStackTraceOnErrorSignal(StringRef());
Guy Benyei11169dd2012-12-18 14:30:41 +00005916}
5917
5918void clang_executeOnThread(void (*fn)(void*), void *user_data,
5919 unsigned stack_size) {
5920 llvm::llvm_execute_on_thread(fn, user_data, stack_size);
5921}
5922
5923} // end: extern "C"
5924
5925//===----------------------------------------------------------------------===//
5926// Token-based Operations.
5927//===----------------------------------------------------------------------===//
5928
5929/* CXToken layout:
5930 * int_data[0]: a CXTokenKind
5931 * int_data[1]: starting token location
5932 * int_data[2]: token length
5933 * int_data[3]: reserved
5934 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
5935 * otherwise unused.
5936 */
5937extern "C" {
5938
5939CXTokenKind clang_getTokenKind(CXToken CXTok) {
5940 return static_cast<CXTokenKind>(CXTok.int_data[0]);
5941}
5942
5943CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
5944 switch (clang_getTokenKind(CXTok)) {
5945 case CXToken_Identifier:
5946 case CXToken_Keyword:
5947 // We know we have an IdentifierInfo*, so use that.
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005948 return cxstring::createRef(static_cast<IdentifierInfo *>(CXTok.ptr_data)
Guy Benyei11169dd2012-12-18 14:30:41 +00005949 ->getNameStart());
5950
5951 case CXToken_Literal: {
5952 // We have stashed the starting pointer in the ptr_data field. Use it.
5953 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00005954 return cxstring::createDup(StringRef(Text, CXTok.int_data[2]));
Guy Benyei11169dd2012-12-18 14:30:41 +00005955 }
5956
5957 case CXToken_Punctuation:
5958 case CXToken_Comment:
5959 break;
5960 }
5961
Dmitri Gribenko852d6222014-02-11 15:02:48 +00005962 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00005963 LOG_BAD_TU(TU);
5964 return cxstring::createEmpty();
5965 }
5966
Guy Benyei11169dd2012-12-18 14:30:41 +00005967 // We have to find the starting buffer pointer the hard way, by
5968 // deconstructing the source location.
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00005969 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00005970 if (!CXXUnit)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00005971 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00005972
5973 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
5974 std::pair<FileID, unsigned> LocInfo
5975 = CXXUnit->getSourceManager().getDecomposedSpellingLoc(Loc);
5976 bool Invalid = false;
5977 StringRef Buffer
5978 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
5979 if (Invalid)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00005980 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00005981
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00005982 return cxstring::createDup(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Guy Benyei11169dd2012-12-18 14:30:41 +00005983}
5984
5985CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00005986 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00005987 LOG_BAD_TU(TU);
5988 return clang_getNullLocation();
5989 }
5990
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00005991 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00005992 if (!CXXUnit)
5993 return clang_getNullLocation();
5994
5995 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
5996 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
5997}
5998
5999CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006000 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006001 LOG_BAD_TU(TU);
6002 return clang_getNullRange();
6003 }
6004
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006005 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006006 if (!CXXUnit)
6007 return clang_getNullRange();
6008
6009 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
6010 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
6011}
6012
6013static void getTokens(ASTUnit *CXXUnit, SourceRange Range,
6014 SmallVectorImpl<CXToken> &CXTokens) {
6015 SourceManager &SourceMgr = CXXUnit->getSourceManager();
6016 std::pair<FileID, unsigned> BeginLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00006017 = SourceMgr.getDecomposedSpellingLoc(Range.getBegin());
Guy Benyei11169dd2012-12-18 14:30:41 +00006018 std::pair<FileID, unsigned> EndLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00006019 = SourceMgr.getDecomposedSpellingLoc(Range.getEnd());
Guy Benyei11169dd2012-12-18 14:30:41 +00006020
6021 // Cannot tokenize across files.
6022 if (BeginLocInfo.first != EndLocInfo.first)
6023 return;
6024
6025 // Create a lexer
6026 bool Invalid = false;
6027 StringRef Buffer
6028 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
6029 if (Invalid)
6030 return;
6031
6032 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
6033 CXXUnit->getASTContext().getLangOpts(),
6034 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
6035 Lex.SetCommentRetentionState(true);
6036
6037 // Lex tokens until we hit the end of the range.
6038 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
6039 Token Tok;
6040 bool previousWasAt = false;
6041 do {
6042 // Lex the next token
6043 Lex.LexFromRawLexer(Tok);
6044 if (Tok.is(tok::eof))
6045 break;
6046
6047 // Initialize the CXToken.
6048 CXToken CXTok;
6049
6050 // - Common fields
6051 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
6052 CXTok.int_data[2] = Tok.getLength();
6053 CXTok.int_data[3] = 0;
6054
6055 // - Kind-specific fields
6056 if (Tok.isLiteral()) {
6057 CXTok.int_data[0] = CXToken_Literal;
Dmitri Gribenkof9304482013-01-23 15:56:07 +00006058 CXTok.ptr_data = const_cast<char *>(Tok.getLiteralData());
Guy Benyei11169dd2012-12-18 14:30:41 +00006059 } else if (Tok.is(tok::raw_identifier)) {
6060 // Lookup the identifier to determine whether we have a keyword.
6061 IdentifierInfo *II
6062 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok);
6063
6064 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
6065 CXTok.int_data[0] = CXToken_Keyword;
6066 }
6067 else {
6068 CXTok.int_data[0] = Tok.is(tok::identifier)
6069 ? CXToken_Identifier
6070 : CXToken_Keyword;
6071 }
6072 CXTok.ptr_data = II;
6073 } else if (Tok.is(tok::comment)) {
6074 CXTok.int_data[0] = CXToken_Comment;
Craig Topper69186e72014-06-08 08:38:04 +00006075 CXTok.ptr_data = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006076 } else {
6077 CXTok.int_data[0] = CXToken_Punctuation;
Craig Topper69186e72014-06-08 08:38:04 +00006078 CXTok.ptr_data = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006079 }
6080 CXTokens.push_back(CXTok);
6081 previousWasAt = Tok.is(tok::at);
6082 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
6083}
6084
6085void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
6086 CXToken **Tokens, unsigned *NumTokens) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00006087 LOG_FUNC_SECTION {
6088 *Log << TU << ' ' << Range;
6089 }
6090
Guy Benyei11169dd2012-12-18 14:30:41 +00006091 if (Tokens)
Craig Topper69186e72014-06-08 08:38:04 +00006092 *Tokens = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006093 if (NumTokens)
6094 *NumTokens = 0;
6095
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006096 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006097 LOG_BAD_TU(TU);
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00006098 return;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006099 }
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00006100
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006101 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006102 if (!CXXUnit || !Tokens || !NumTokens)
6103 return;
6104
6105 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
6106
6107 SourceRange R = cxloc::translateCXSourceRange(Range);
6108 if (R.isInvalid())
6109 return;
6110
6111 SmallVector<CXToken, 32> CXTokens;
6112 getTokens(CXXUnit, R, CXTokens);
6113
6114 if (CXTokens.empty())
6115 return;
6116
6117 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
6118 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
6119 *NumTokens = CXTokens.size();
6120}
6121
6122void clang_disposeTokens(CXTranslationUnit TU,
6123 CXToken *Tokens, unsigned NumTokens) {
6124 free(Tokens);
6125}
6126
6127} // end: extern "C"
6128
6129//===----------------------------------------------------------------------===//
6130// Token annotation APIs.
6131//===----------------------------------------------------------------------===//
6132
Guy Benyei11169dd2012-12-18 14:30:41 +00006133static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
6134 CXCursor parent,
6135 CXClientData client_data);
6136static bool AnnotateTokensPostChildrenVisitor(CXCursor cursor,
6137 CXClientData client_data);
6138
6139namespace {
6140class AnnotateTokensWorker {
Guy Benyei11169dd2012-12-18 14:30:41 +00006141 CXToken *Tokens;
6142 CXCursor *Cursors;
6143 unsigned NumTokens;
6144 unsigned TokIdx;
6145 unsigned PreprocessingTokIdx;
6146 CursorVisitor AnnotateVis;
6147 SourceManager &SrcMgr;
6148 bool HasContextSensitiveKeywords;
6149
6150 struct PostChildrenInfo {
6151 CXCursor Cursor;
6152 SourceRange CursorRange;
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006153 unsigned BeforeReachingCursorIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00006154 unsigned BeforeChildrenTokenIdx;
6155 };
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006156 SmallVector<PostChildrenInfo, 8> PostChildrenInfos;
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006157
6158 CXToken &getTok(unsigned Idx) {
6159 assert(Idx < NumTokens);
6160 return Tokens[Idx];
6161 }
6162 const CXToken &getTok(unsigned Idx) const {
6163 assert(Idx < NumTokens);
6164 return Tokens[Idx];
6165 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006166 bool MoreTokens() const { return TokIdx < NumTokens; }
6167 unsigned NextToken() const { return TokIdx; }
6168 void AdvanceToken() { ++TokIdx; }
6169 SourceLocation GetTokenLoc(unsigned tokI) {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006170 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[1]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006171 }
6172 bool isFunctionMacroToken(unsigned tokI) const {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006173 return getTok(tokI).int_data[3] != 0;
Guy Benyei11169dd2012-12-18 14:30:41 +00006174 }
6175 SourceLocation getFunctionMacroTokenLoc(unsigned tokI) const {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006176 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[3]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006177 }
6178
6179 void annotateAndAdvanceTokens(CXCursor, RangeComparisonResult, SourceRange);
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006180 bool annotateAndAdvanceFunctionMacroTokens(CXCursor, RangeComparisonResult,
Guy Benyei11169dd2012-12-18 14:30:41 +00006181 SourceRange);
6182
6183public:
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006184 AnnotateTokensWorker(CXToken *tokens, CXCursor *cursors, unsigned numTokens,
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006185 CXTranslationUnit TU, SourceRange RegionOfInterest)
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006186 : Tokens(tokens), Cursors(cursors),
Guy Benyei11169dd2012-12-18 14:30:41 +00006187 NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006188 AnnotateVis(TU,
Guy Benyei11169dd2012-12-18 14:30:41 +00006189 AnnotateTokensVisitor, this,
6190 /*VisitPreprocessorLast=*/true,
6191 /*VisitIncludedEntities=*/false,
6192 RegionOfInterest,
6193 /*VisitDeclsOnly=*/false,
6194 AnnotateTokensPostChildrenVisitor),
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006195 SrcMgr(cxtu::getASTUnit(TU)->getSourceManager()),
Guy Benyei11169dd2012-12-18 14:30:41 +00006196 HasContextSensitiveKeywords(false) { }
6197
6198 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
6199 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
6200 bool postVisitChildren(CXCursor cursor);
6201 void AnnotateTokens();
6202
6203 /// \brief Determine whether the annotator saw any cursors that have
6204 /// context-sensitive keywords.
6205 bool hasContextSensitiveKeywords() const {
6206 return HasContextSensitiveKeywords;
6207 }
6208
6209 ~AnnotateTokensWorker() {
6210 assert(PostChildrenInfos.empty());
6211 }
6212};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006213}
Guy Benyei11169dd2012-12-18 14:30:41 +00006214
6215void AnnotateTokensWorker::AnnotateTokens() {
6216 // Walk the AST within the region of interest, annotating tokens
6217 // along the way.
6218 AnnotateVis.visitFileRegion();
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006219}
Guy Benyei11169dd2012-12-18 14:30:41 +00006220
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006221static inline void updateCursorAnnotation(CXCursor &Cursor,
6222 const CXCursor &updateC) {
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006223 if (clang_isInvalid(updateC.kind) || !clang_isInvalid(Cursor.kind))
Guy Benyei11169dd2012-12-18 14:30:41 +00006224 return;
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006225 Cursor = updateC;
Guy Benyei11169dd2012-12-18 14:30:41 +00006226}
6227
6228/// \brief It annotates and advances tokens with a cursor until the comparison
6229//// between the cursor location and the source range is the same as
6230/// \arg compResult.
6231///
6232/// Pass RangeBefore to annotate tokens with a cursor until a range is reached.
6233/// Pass RangeOverlap to annotate tokens inside a range.
6234void AnnotateTokensWorker::annotateAndAdvanceTokens(CXCursor updateC,
6235 RangeComparisonResult compResult,
6236 SourceRange range) {
6237 while (MoreTokens()) {
6238 const unsigned I = NextToken();
6239 if (isFunctionMacroToken(I))
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006240 if (!annotateAndAdvanceFunctionMacroTokens(updateC, compResult, range))
6241 return;
Guy Benyei11169dd2012-12-18 14:30:41 +00006242
6243 SourceLocation TokLoc = GetTokenLoc(I);
6244 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006245 updateCursorAnnotation(Cursors[I], updateC);
Guy Benyei11169dd2012-12-18 14:30:41 +00006246 AdvanceToken();
6247 continue;
6248 }
6249 break;
6250 }
6251}
6252
6253/// \brief Special annotation handling for macro argument tokens.
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006254/// \returns true if it advanced beyond all macro tokens, false otherwise.
6255bool AnnotateTokensWorker::annotateAndAdvanceFunctionMacroTokens(
Guy Benyei11169dd2012-12-18 14:30:41 +00006256 CXCursor updateC,
6257 RangeComparisonResult compResult,
6258 SourceRange range) {
6259 assert(MoreTokens());
6260 assert(isFunctionMacroToken(NextToken()) &&
6261 "Should be called only for macro arg tokens");
6262
6263 // This works differently than annotateAndAdvanceTokens; because expanded
6264 // macro arguments can have arbitrary translation-unit source order, we do not
6265 // advance the token index one by one until a token fails the range test.
6266 // We only advance once past all of the macro arg tokens if all of them
6267 // pass the range test. If one of them fails we keep the token index pointing
6268 // at the start of the macro arg tokens so that the failing token will be
6269 // annotated by a subsequent annotation try.
6270
6271 bool atLeastOneCompFail = false;
6272
6273 unsigned I = NextToken();
6274 for (; I < NumTokens && isFunctionMacroToken(I); ++I) {
6275 SourceLocation TokLoc = getFunctionMacroTokenLoc(I);
6276 if (TokLoc.isFileID())
6277 continue; // not macro arg token, it's parens or comma.
6278 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
6279 if (clang_isInvalid(clang_getCursorKind(Cursors[I])))
6280 Cursors[I] = updateC;
6281 } else
6282 atLeastOneCompFail = true;
6283 }
6284
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006285 if (atLeastOneCompFail)
6286 return false;
6287
6288 TokIdx = I; // All of the tokens were handled, advance beyond all of them.
6289 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00006290}
6291
6292enum CXChildVisitResult
6293AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006294 SourceRange cursorRange = getRawCursorExtent(cursor);
6295 if (cursorRange.isInvalid())
6296 return CXChildVisit_Recurse;
6297
6298 if (!HasContextSensitiveKeywords) {
6299 // Objective-C properties can have context-sensitive keywords.
6300 if (cursor.kind == CXCursor_ObjCPropertyDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006301 if (const ObjCPropertyDecl *Property
Guy Benyei11169dd2012-12-18 14:30:41 +00006302 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(cursor)))
6303 HasContextSensitiveKeywords = Property->getPropertyAttributesAsWritten() != 0;
6304 }
6305 // Objective-C methods can have context-sensitive keywords.
6306 else if (cursor.kind == CXCursor_ObjCInstanceMethodDecl ||
6307 cursor.kind == CXCursor_ObjCClassMethodDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006308 if (const ObjCMethodDecl *Method
Guy Benyei11169dd2012-12-18 14:30:41 +00006309 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
6310 if (Method->getObjCDeclQualifier())
6311 HasContextSensitiveKeywords = true;
6312 else {
David Majnemer59f77922016-06-24 04:05:48 +00006313 for (const auto *P : Method->parameters()) {
Aaron Ballman43b68be2014-03-07 17:50:17 +00006314 if (P->getObjCDeclQualifier()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006315 HasContextSensitiveKeywords = true;
6316 break;
6317 }
6318 }
6319 }
6320 }
6321 }
6322 // C++ methods can have context-sensitive keywords.
6323 else if (cursor.kind == CXCursor_CXXMethod) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006324 if (const CXXMethodDecl *Method
Guy Benyei11169dd2012-12-18 14:30:41 +00006325 = dyn_cast_or_null<CXXMethodDecl>(getCursorDecl(cursor))) {
6326 if (Method->hasAttr<FinalAttr>() || Method->hasAttr<OverrideAttr>())
6327 HasContextSensitiveKeywords = true;
6328 }
6329 }
6330 // C++ classes can have context-sensitive keywords.
6331 else if (cursor.kind == CXCursor_StructDecl ||
6332 cursor.kind == CXCursor_ClassDecl ||
6333 cursor.kind == CXCursor_ClassTemplate ||
6334 cursor.kind == CXCursor_ClassTemplatePartialSpecialization) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006335 if (const Decl *D = getCursorDecl(cursor))
Guy Benyei11169dd2012-12-18 14:30:41 +00006336 if (D->hasAttr<FinalAttr>())
6337 HasContextSensitiveKeywords = true;
6338 }
6339 }
Argyrios Kyrtzidis990b3862013-06-04 18:24:30 +00006340
6341 // Don't override a property annotation with its getter/setter method.
6342 if (cursor.kind == CXCursor_ObjCInstanceMethodDecl &&
6343 parent.kind == CXCursor_ObjCPropertyDecl)
6344 return CXChildVisit_Continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00006345
6346 if (clang_isPreprocessing(cursor.kind)) {
6347 // Items in the preprocessing record are kept separate from items in
6348 // declarations, so we keep a separate token index.
6349 unsigned SavedTokIdx = TokIdx;
6350 TokIdx = PreprocessingTokIdx;
6351
6352 // Skip tokens up until we catch up to the beginning of the preprocessing
6353 // entry.
6354 while (MoreTokens()) {
6355 const unsigned I = NextToken();
6356 SourceLocation TokLoc = GetTokenLoc(I);
6357 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
6358 case RangeBefore:
6359 AdvanceToken();
6360 continue;
6361 case RangeAfter:
6362 case RangeOverlap:
6363 break;
6364 }
6365 break;
6366 }
6367
6368 // Look at all of the tokens within this range.
6369 while (MoreTokens()) {
6370 const unsigned I = NextToken();
6371 SourceLocation TokLoc = GetTokenLoc(I);
6372 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
6373 case RangeBefore:
6374 llvm_unreachable("Infeasible");
6375 case RangeAfter:
6376 break;
6377 case RangeOverlap:
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00006378 // For macro expansions, just note where the beginning of the macro
6379 // expansion occurs.
6380 if (cursor.kind == CXCursor_MacroExpansion) {
6381 if (TokLoc == cursorRange.getBegin())
6382 Cursors[I] = cursor;
6383 AdvanceToken();
6384 break;
6385 }
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006386 // We may have already annotated macro names inside macro definitions.
6387 if (Cursors[I].kind != CXCursor_MacroExpansion)
6388 Cursors[I] = cursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00006389 AdvanceToken();
Guy Benyei11169dd2012-12-18 14:30:41 +00006390 continue;
6391 }
6392 break;
6393 }
6394
6395 // Save the preprocessing token index; restore the non-preprocessing
6396 // token index.
6397 PreprocessingTokIdx = TokIdx;
6398 TokIdx = SavedTokIdx;
6399 return CXChildVisit_Recurse;
6400 }
6401
6402 if (cursorRange.isInvalid())
6403 return CXChildVisit_Continue;
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006404
6405 unsigned BeforeReachingCursorIdx = NextToken();
Guy Benyei11169dd2012-12-18 14:30:41 +00006406 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00006407 const enum CXCursorKind K = clang_getCursorKind(parent);
6408 const CXCursor updateC =
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006409 (clang_isInvalid(K) || K == CXCursor_TranslationUnit ||
6410 // Attributes are annotated out-of-order, skip tokens until we reach it.
6411 clang_isAttribute(cursor.kind))
Guy Benyei11169dd2012-12-18 14:30:41 +00006412 ? clang_getNullCursor() : parent;
6413
6414 annotateAndAdvanceTokens(updateC, RangeBefore, cursorRange);
6415
6416 // Avoid having the cursor of an expression "overwrite" the annotation of the
6417 // variable declaration that it belongs to.
6418 // This can happen for C++ constructor expressions whose range generally
6419 // include the variable declaration, e.g.:
6420 // MyCXXClass foo; // Make sure we don't annotate 'foo' as a CallExpr cursor.
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006421 if (clang_isExpression(cursorK) && MoreTokens()) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006422 const Expr *E = getCursorExpr(cursor);
Dmitri Gribenkoa1691182013-01-26 18:12:08 +00006423 if (const Decl *D = getCursorParentDecl(cursor)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006424 const unsigned I = NextToken();
6425 if (E->getLocStart().isValid() && D->getLocation().isValid() &&
6426 E->getLocStart() == D->getLocation() &&
6427 E->getLocStart() == GetTokenLoc(I)) {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006428 updateCursorAnnotation(Cursors[I], updateC);
Guy Benyei11169dd2012-12-18 14:30:41 +00006429 AdvanceToken();
6430 }
6431 }
6432 }
6433
6434 // Before recursing into the children keep some state that we are going
6435 // to use in the AnnotateTokensWorker::postVisitChildren callback to do some
6436 // extra work after the child nodes are visited.
6437 // Note that we don't call VisitChildren here to avoid traversing statements
6438 // code-recursively which can blow the stack.
6439
6440 PostChildrenInfo Info;
6441 Info.Cursor = cursor;
6442 Info.CursorRange = cursorRange;
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006443 Info.BeforeReachingCursorIdx = BeforeReachingCursorIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00006444 Info.BeforeChildrenTokenIdx = NextToken();
6445 PostChildrenInfos.push_back(Info);
6446
6447 return CXChildVisit_Recurse;
6448}
6449
6450bool AnnotateTokensWorker::postVisitChildren(CXCursor cursor) {
6451 if (PostChildrenInfos.empty())
6452 return false;
6453 const PostChildrenInfo &Info = PostChildrenInfos.back();
6454 if (!clang_equalCursors(Info.Cursor, cursor))
6455 return false;
6456
6457 const unsigned BeforeChildren = Info.BeforeChildrenTokenIdx;
6458 const unsigned AfterChildren = NextToken();
6459 SourceRange cursorRange = Info.CursorRange;
6460
6461 // Scan the tokens that are at the end of the cursor, but are not captured
6462 // but the child cursors.
6463 annotateAndAdvanceTokens(cursor, RangeOverlap, cursorRange);
6464
6465 // Scan the tokens that are at the beginning of the cursor, but are not
6466 // capture by the child cursors.
6467 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
6468 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
6469 break;
6470
6471 Cursors[I] = cursor;
6472 }
6473
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006474 // Attributes are annotated out-of-order, rewind TokIdx to when we first
6475 // encountered the attribute cursor.
6476 if (clang_isAttribute(cursor.kind))
6477 TokIdx = Info.BeforeReachingCursorIdx;
6478
Guy Benyei11169dd2012-12-18 14:30:41 +00006479 PostChildrenInfos.pop_back();
6480 return false;
6481}
6482
6483static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
6484 CXCursor parent,
6485 CXClientData client_data) {
6486 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
6487}
6488
6489static bool AnnotateTokensPostChildrenVisitor(CXCursor cursor,
6490 CXClientData client_data) {
6491 return static_cast<AnnotateTokensWorker*>(client_data)->
6492 postVisitChildren(cursor);
6493}
6494
6495namespace {
6496
6497/// \brief Uses the macro expansions in the preprocessing record to find
6498/// and mark tokens that are macro arguments. This info is used by the
6499/// AnnotateTokensWorker.
6500class MarkMacroArgTokensVisitor {
6501 SourceManager &SM;
6502 CXToken *Tokens;
6503 unsigned NumTokens;
6504 unsigned CurIdx;
6505
6506public:
6507 MarkMacroArgTokensVisitor(SourceManager &SM,
6508 CXToken *tokens, unsigned numTokens)
6509 : SM(SM), Tokens(tokens), NumTokens(numTokens), CurIdx(0) { }
6510
6511 CXChildVisitResult visit(CXCursor cursor, CXCursor parent) {
6512 if (cursor.kind != CXCursor_MacroExpansion)
6513 return CXChildVisit_Continue;
6514
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00006515 SourceRange macroRange = getCursorMacroExpansion(cursor).getSourceRange();
Guy Benyei11169dd2012-12-18 14:30:41 +00006516 if (macroRange.getBegin() == macroRange.getEnd())
6517 return CXChildVisit_Continue; // it's not a function macro.
6518
6519 for (; CurIdx < NumTokens; ++CurIdx) {
6520 if (!SM.isBeforeInTranslationUnit(getTokenLoc(CurIdx),
6521 macroRange.getBegin()))
6522 break;
6523 }
6524
6525 if (CurIdx == NumTokens)
6526 return CXChildVisit_Break;
6527
6528 for (; CurIdx < NumTokens; ++CurIdx) {
6529 SourceLocation tokLoc = getTokenLoc(CurIdx);
6530 if (!SM.isBeforeInTranslationUnit(tokLoc, macroRange.getEnd()))
6531 break;
6532
6533 setFunctionMacroTokenLoc(CurIdx, SM.getMacroArgExpandedLocation(tokLoc));
6534 }
6535
6536 if (CurIdx == NumTokens)
6537 return CXChildVisit_Break;
6538
6539 return CXChildVisit_Continue;
6540 }
6541
6542private:
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006543 CXToken &getTok(unsigned Idx) {
6544 assert(Idx < NumTokens);
6545 return Tokens[Idx];
6546 }
6547 const CXToken &getTok(unsigned Idx) const {
6548 assert(Idx < NumTokens);
6549 return Tokens[Idx];
6550 }
6551
Guy Benyei11169dd2012-12-18 14:30:41 +00006552 SourceLocation getTokenLoc(unsigned tokI) {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006553 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[1]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006554 }
6555
6556 void setFunctionMacroTokenLoc(unsigned tokI, SourceLocation loc) {
6557 // The third field is reserved and currently not used. Use it here
6558 // to mark macro arg expanded tokens with their expanded locations.
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006559 getTok(tokI).int_data[3] = loc.getRawEncoding();
Guy Benyei11169dd2012-12-18 14:30:41 +00006560 }
6561};
6562
6563} // end anonymous namespace
6564
6565static CXChildVisitResult
6566MarkMacroArgTokensVisitorDelegate(CXCursor cursor, CXCursor parent,
6567 CXClientData client_data) {
6568 return static_cast<MarkMacroArgTokensVisitor*>(client_data)->visit(cursor,
6569 parent);
6570}
6571
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006572/// \brief Used by \c annotatePreprocessorTokens.
6573/// \returns true if lexing was finished, false otherwise.
6574static bool lexNext(Lexer &Lex, Token &Tok,
6575 unsigned &NextIdx, unsigned NumTokens) {
6576 if (NextIdx >= NumTokens)
6577 return true;
6578
6579 ++NextIdx;
6580 Lex.LexFromRawLexer(Tok);
Alexander Kornienko1a9f1842015-12-28 15:24:08 +00006581 return Tok.is(tok::eof);
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006582}
6583
Guy Benyei11169dd2012-12-18 14:30:41 +00006584static void annotatePreprocessorTokens(CXTranslationUnit TU,
6585 SourceRange RegionOfInterest,
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006586 CXCursor *Cursors,
6587 CXToken *Tokens,
6588 unsigned NumTokens) {
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006589 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006590
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00006591 Preprocessor &PP = CXXUnit->getPreprocessor();
Guy Benyei11169dd2012-12-18 14:30:41 +00006592 SourceManager &SourceMgr = CXXUnit->getSourceManager();
6593 std::pair<FileID, unsigned> BeginLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00006594 = SourceMgr.getDecomposedSpellingLoc(RegionOfInterest.getBegin());
Guy Benyei11169dd2012-12-18 14:30:41 +00006595 std::pair<FileID, unsigned> EndLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00006596 = SourceMgr.getDecomposedSpellingLoc(RegionOfInterest.getEnd());
Guy Benyei11169dd2012-12-18 14:30:41 +00006597
6598 if (BeginLocInfo.first != EndLocInfo.first)
6599 return;
6600
6601 StringRef Buffer;
6602 bool Invalid = false;
6603 Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
6604 if (Buffer.empty() || Invalid)
6605 return;
6606
6607 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
6608 CXXUnit->getASTContext().getLangOpts(),
6609 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
6610 Buffer.end());
6611 Lex.SetCommentRetentionState(true);
6612
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006613 unsigned NextIdx = 0;
Guy Benyei11169dd2012-12-18 14:30:41 +00006614 // Lex tokens in raw mode until we hit the end of the range, to avoid
6615 // entering #includes or expanding macros.
6616 while (true) {
6617 Token Tok;
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006618 if (lexNext(Lex, Tok, NextIdx, NumTokens))
6619 break;
6620 unsigned TokIdx = NextIdx-1;
6621 assert(Tok.getLocation() ==
6622 SourceLocation::getFromRawEncoding(Tokens[TokIdx].int_data[1]));
Guy Benyei11169dd2012-12-18 14:30:41 +00006623
6624 reprocess:
6625 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006626 // We have found a preprocessing directive. Annotate the tokens
6627 // appropriately.
Guy Benyei11169dd2012-12-18 14:30:41 +00006628 //
6629 // FIXME: Some simple tests here could identify macro definitions and
6630 // #undefs, to provide specific cursor kinds for those.
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006631
6632 SourceLocation BeginLoc = Tok.getLocation();
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00006633 if (lexNext(Lex, Tok, NextIdx, NumTokens))
6634 break;
6635
Craig Topper69186e72014-06-08 08:38:04 +00006636 MacroInfo *MI = nullptr;
Alp Toker2d57cea2014-05-17 04:53:25 +00006637 if (Tok.is(tok::raw_identifier) && Tok.getRawIdentifier() == "define") {
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00006638 if (lexNext(Lex, Tok, NextIdx, NumTokens))
6639 break;
6640
6641 if (Tok.is(tok::raw_identifier)) {
Alp Toker2d57cea2014-05-17 04:53:25 +00006642 IdentifierInfo &II =
6643 PP.getIdentifierTable().get(Tok.getRawIdentifier());
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00006644 SourceLocation MappedTokLoc =
6645 CXXUnit->mapLocationToPreamble(Tok.getLocation());
6646 MI = getMacroInfo(II, MappedTokLoc, TU);
6647 }
6648 }
6649
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006650 bool finished = false;
Guy Benyei11169dd2012-12-18 14:30:41 +00006651 do {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006652 if (lexNext(Lex, Tok, NextIdx, NumTokens)) {
6653 finished = true;
6654 break;
6655 }
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00006656 // If we are in a macro definition, check if the token was ever a
6657 // macro name and annotate it if that's the case.
6658 if (MI) {
6659 SourceLocation SaveLoc = Tok.getLocation();
6660 Tok.setLocation(CXXUnit->mapLocationToPreamble(SaveLoc));
Richard Smith66a81862015-05-04 02:25:31 +00006661 MacroDefinitionRecord *MacroDef =
6662 checkForMacroInMacroDefinition(MI, Tok, TU);
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00006663 Tok.setLocation(SaveLoc);
6664 if (MacroDef)
Richard Smith66a81862015-05-04 02:25:31 +00006665 Cursors[NextIdx - 1] =
6666 MakeMacroExpansionCursor(MacroDef, Tok.getLocation(), TU);
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00006667 }
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006668 } while (!Tok.isAtStartOfLine());
6669
6670 unsigned LastIdx = finished ? NextIdx-1 : NextIdx-2;
6671 assert(TokIdx <= LastIdx);
6672 SourceLocation EndLoc =
6673 SourceLocation::getFromRawEncoding(Tokens[LastIdx].int_data[1]);
6674 CXCursor Cursor =
6675 MakePreprocessingDirectiveCursor(SourceRange(BeginLoc, EndLoc), TU);
6676
6677 for (; TokIdx <= LastIdx; ++TokIdx)
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00006678 updateCursorAnnotation(Cursors[TokIdx], Cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00006679
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006680 if (finished)
6681 break;
6682 goto reprocess;
Guy Benyei11169dd2012-12-18 14:30:41 +00006683 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006684 }
6685}
6686
6687// This gets run a separate thread to avoid stack blowout.
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00006688static void clang_annotateTokensImpl(CXTranslationUnit TU, ASTUnit *CXXUnit,
6689 CXToken *Tokens, unsigned NumTokens,
6690 CXCursor *Cursors) {
Dmitri Gribenko183436e2013-01-26 21:49:50 +00006691 CIndexer *CXXIdx = TU->CIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00006692 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing))
6693 setThreadBackgroundPriority();
6694
6695 // Determine the region of interest, which contains all of the tokens.
6696 SourceRange RegionOfInterest;
6697 RegionOfInterest.setBegin(
6698 cxloc::translateSourceLocation(clang_getTokenLocation(TU, Tokens[0])));
6699 RegionOfInterest.setEnd(
6700 cxloc::translateSourceLocation(clang_getTokenLocation(TU,
6701 Tokens[NumTokens-1])));
6702
Guy Benyei11169dd2012-12-18 14:30:41 +00006703 // Relex the tokens within the source range to look for preprocessing
6704 // directives.
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006705 annotatePreprocessorTokens(TU, RegionOfInterest, Cursors, Tokens, NumTokens);
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00006706
6707 // If begin location points inside a macro argument, set it to the expansion
6708 // location so we can have the full context when annotating semantically.
6709 {
6710 SourceManager &SM = CXXUnit->getSourceManager();
6711 SourceLocation Loc =
6712 SM.getMacroArgExpandedLocation(RegionOfInterest.getBegin());
6713 if (Loc.isMacroID())
6714 RegionOfInterest.setBegin(SM.getExpansionLoc(Loc));
6715 }
6716
Guy Benyei11169dd2012-12-18 14:30:41 +00006717 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
6718 // Search and mark tokens that are macro argument expansions.
6719 MarkMacroArgTokensVisitor Visitor(CXXUnit->getSourceManager(),
6720 Tokens, NumTokens);
6721 CursorVisitor MacroArgMarker(TU,
6722 MarkMacroArgTokensVisitorDelegate, &Visitor,
6723 /*VisitPreprocessorLast=*/true,
6724 /*VisitIncludedEntities=*/false,
6725 RegionOfInterest);
6726 MacroArgMarker.visitPreprocessedEntitiesInRegion();
6727 }
6728
6729 // Annotate all of the source locations in the region of interest that map to
6730 // a specific cursor.
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006731 AnnotateTokensWorker W(Tokens, Cursors, NumTokens, TU, RegionOfInterest);
Guy Benyei11169dd2012-12-18 14:30:41 +00006732
6733 // FIXME: We use a ridiculous stack size here because the data-recursion
6734 // algorithm uses a large stack frame than the non-data recursive version,
6735 // and AnnotationTokensWorker currently transforms the data-recursion
6736 // algorithm back into a traditional recursion by explicitly calling
6737 // VisitChildren(). We will need to remove this explicit recursive call.
6738 W.AnnotateTokens();
6739
6740 // If we ran into any entities that involve context-sensitive keywords,
6741 // take another pass through the tokens to mark them as such.
6742 if (W.hasContextSensitiveKeywords()) {
6743 for (unsigned I = 0; I != NumTokens; ++I) {
6744 if (clang_getTokenKind(Tokens[I]) != CXToken_Identifier)
6745 continue;
6746
6747 if (Cursors[I].kind == CXCursor_ObjCPropertyDecl) {
6748 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006749 if (const ObjCPropertyDecl *Property
Guy Benyei11169dd2012-12-18 14:30:41 +00006750 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(Cursors[I]))) {
6751 if (Property->getPropertyAttributesAsWritten() != 0 &&
6752 llvm::StringSwitch<bool>(II->getName())
6753 .Case("readonly", true)
6754 .Case("assign", true)
6755 .Case("unsafe_unretained", true)
6756 .Case("readwrite", true)
6757 .Case("retain", true)
6758 .Case("copy", true)
6759 .Case("nonatomic", true)
6760 .Case("atomic", true)
6761 .Case("getter", true)
6762 .Case("setter", true)
6763 .Case("strong", true)
6764 .Case("weak", true)
Manman Ren04fd4d82016-05-31 23:22:04 +00006765 .Case("class", true)
Guy Benyei11169dd2012-12-18 14:30:41 +00006766 .Default(false))
6767 Tokens[I].int_data[0] = CXToken_Keyword;
6768 }
6769 continue;
6770 }
6771
6772 if (Cursors[I].kind == CXCursor_ObjCInstanceMethodDecl ||
6773 Cursors[I].kind == CXCursor_ObjCClassMethodDecl) {
6774 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
6775 if (llvm::StringSwitch<bool>(II->getName())
6776 .Case("in", true)
6777 .Case("out", true)
6778 .Case("inout", true)
6779 .Case("oneway", true)
6780 .Case("bycopy", true)
6781 .Case("byref", true)
6782 .Default(false))
6783 Tokens[I].int_data[0] = CXToken_Keyword;
6784 continue;
6785 }
6786
6787 if (Cursors[I].kind == CXCursor_CXXFinalAttr ||
6788 Cursors[I].kind == CXCursor_CXXOverrideAttr) {
6789 Tokens[I].int_data[0] = CXToken_Keyword;
6790 continue;
6791 }
6792 }
6793 }
6794}
6795
6796extern "C" {
6797
6798void clang_annotateTokens(CXTranslationUnit TU,
6799 CXToken *Tokens, unsigned NumTokens,
6800 CXCursor *Cursors) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006801 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006802 LOG_BAD_TU(TU);
6803 return;
6804 }
6805 if (NumTokens == 0 || !Tokens || !Cursors) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00006806 LOG_FUNC_SECTION { *Log << "<null input>"; }
Guy Benyei11169dd2012-12-18 14:30:41 +00006807 return;
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00006808 }
6809
6810 LOG_FUNC_SECTION {
6811 *Log << TU << ' ';
6812 CXSourceLocation bloc = clang_getTokenLocation(TU, Tokens[0]);
6813 CXSourceLocation eloc = clang_getTokenLocation(TU, Tokens[NumTokens-1]);
6814 *Log << clang_getRange(bloc, eloc);
6815 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006816
6817 // Any token we don't specifically annotate will have a NULL cursor.
6818 CXCursor C = clang_getNullCursor();
6819 for (unsigned I = 0; I != NumTokens; ++I)
6820 Cursors[I] = C;
6821
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006822 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006823 if (!CXXUnit)
6824 return;
6825
6826 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00006827
6828 auto AnnotateTokensImpl = [=]() {
6829 clang_annotateTokensImpl(TU, CXXUnit, Tokens, NumTokens, Cursors);
6830 };
Guy Benyei11169dd2012-12-18 14:30:41 +00006831 llvm::CrashRecoveryContext CRC;
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00006832 if (!RunSafely(CRC, AnnotateTokensImpl, GetSafetyThreadStackSize() * 2)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006833 fprintf(stderr, "libclang: crash detected while annotating tokens\n");
6834 }
6835}
6836
6837} // end: extern "C"
6838
6839//===----------------------------------------------------------------------===//
6840// Operations for querying linkage of a cursor.
6841//===----------------------------------------------------------------------===//
6842
6843extern "C" {
6844CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
6845 if (!clang_isDeclaration(cursor.kind))
6846 return CXLinkage_Invalid;
6847
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006848 const Decl *D = cxcursor::getCursorDecl(cursor);
6849 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
Rafael Espindola3ae00052013-05-13 00:12:11 +00006850 switch (ND->getLinkageInternal()) {
Rafael Espindola50df3a02013-05-25 17:16:20 +00006851 case NoLinkage:
6852 case VisibleNoLinkage: return CXLinkage_NoLinkage;
Guy Benyei11169dd2012-12-18 14:30:41 +00006853 case InternalLinkage: return CXLinkage_Internal;
6854 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
6855 case ExternalLinkage: return CXLinkage_External;
6856 };
6857
6858 return CXLinkage_Invalid;
6859}
6860} // end: extern "C"
6861
6862//===----------------------------------------------------------------------===//
Ehsan Akhgarib743de72016-05-31 15:55:51 +00006863// Operations for querying visibility of a cursor.
6864//===----------------------------------------------------------------------===//
6865
6866extern "C" {
6867CXVisibilityKind clang_getCursorVisibility(CXCursor cursor) {
6868 if (!clang_isDeclaration(cursor.kind))
6869 return CXVisibility_Invalid;
6870
6871 const Decl *D = cxcursor::getCursorDecl(cursor);
6872 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
6873 switch (ND->getVisibility()) {
6874 case HiddenVisibility: return CXVisibility_Hidden;
6875 case ProtectedVisibility: return CXVisibility_Protected;
6876 case DefaultVisibility: return CXVisibility_Default;
6877 };
6878
6879 return CXVisibility_Invalid;
6880}
6881} // end: extern "C"
6882
6883//===----------------------------------------------------------------------===//
Guy Benyei11169dd2012-12-18 14:30:41 +00006884// Operations for querying language of a cursor.
6885//===----------------------------------------------------------------------===//
6886
6887static CXLanguageKind getDeclLanguage(const Decl *D) {
6888 if (!D)
6889 return CXLanguage_C;
6890
6891 switch (D->getKind()) {
6892 default:
6893 break;
6894 case Decl::ImplicitParam:
6895 case Decl::ObjCAtDefsField:
6896 case Decl::ObjCCategory:
6897 case Decl::ObjCCategoryImpl:
6898 case Decl::ObjCCompatibleAlias:
6899 case Decl::ObjCImplementation:
6900 case Decl::ObjCInterface:
6901 case Decl::ObjCIvar:
6902 case Decl::ObjCMethod:
6903 case Decl::ObjCProperty:
6904 case Decl::ObjCPropertyImpl:
6905 case Decl::ObjCProtocol:
Douglas Gregor85f3f952015-07-07 03:57:15 +00006906 case Decl::ObjCTypeParam:
Guy Benyei11169dd2012-12-18 14:30:41 +00006907 return CXLanguage_ObjC;
6908 case Decl::CXXConstructor:
6909 case Decl::CXXConversion:
6910 case Decl::CXXDestructor:
6911 case Decl::CXXMethod:
6912 case Decl::CXXRecord:
6913 case Decl::ClassTemplate:
6914 case Decl::ClassTemplatePartialSpecialization:
6915 case Decl::ClassTemplateSpecialization:
6916 case Decl::Friend:
6917 case Decl::FriendTemplate:
6918 case Decl::FunctionTemplate:
6919 case Decl::LinkageSpec:
6920 case Decl::Namespace:
6921 case Decl::NamespaceAlias:
6922 case Decl::NonTypeTemplateParm:
6923 case Decl::StaticAssert:
6924 case Decl::TemplateTemplateParm:
6925 case Decl::TemplateTypeParm:
6926 case Decl::UnresolvedUsingTypename:
6927 case Decl::UnresolvedUsingValue:
6928 case Decl::Using:
6929 case Decl::UsingDirective:
6930 case Decl::UsingShadow:
6931 return CXLanguage_CPlusPlus;
6932 }
6933
6934 return CXLanguage_C;
6935}
6936
6937extern "C" {
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00006938
6939static CXAvailabilityKind getCursorAvailabilityForDecl(const Decl *D) {
6940 if (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted())
Manuel Klimek8e3a7ed2015-09-25 17:53:16 +00006941 return CXAvailability_NotAvailable;
Guy Benyei11169dd2012-12-18 14:30:41 +00006942
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00006943 switch (D->getAvailability()) {
6944 case AR_Available:
6945 case AR_NotYetIntroduced:
6946 if (const EnumConstantDecl *EnumConst = dyn_cast<EnumConstantDecl>(D))
Benjamin Kramer656363d2013-10-15 18:53:18 +00006947 return getCursorAvailabilityForDecl(
6948 cast<Decl>(EnumConst->getDeclContext()));
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00006949 return CXAvailability_Available;
6950
6951 case AR_Deprecated:
6952 return CXAvailability_Deprecated;
6953
6954 case AR_Unavailable:
6955 return CXAvailability_NotAvailable;
6956 }
Benjamin Kramer656363d2013-10-15 18:53:18 +00006957
6958 llvm_unreachable("Unknown availability kind!");
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00006959}
6960
Guy Benyei11169dd2012-12-18 14:30:41 +00006961enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
6962 if (clang_isDeclaration(cursor.kind))
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00006963 if (const Decl *D = cxcursor::getCursorDecl(cursor))
6964 return getCursorAvailabilityForDecl(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00006965
6966 return CXAvailability_Available;
6967}
6968
6969static CXVersion convertVersion(VersionTuple In) {
6970 CXVersion Out = { -1, -1, -1 };
6971 if (In.empty())
6972 return Out;
6973
6974 Out.Major = In.getMajor();
6975
NAKAMURA Takumic2b5d1f2013-02-21 02:32:34 +00006976 Optional<unsigned> Minor = In.getMinor();
6977 if (Minor.hasValue())
Guy Benyei11169dd2012-12-18 14:30:41 +00006978 Out.Minor = *Minor;
6979 else
6980 return Out;
6981
NAKAMURA Takumic2b5d1f2013-02-21 02:32:34 +00006982 Optional<unsigned> Subminor = In.getSubminor();
6983 if (Subminor.hasValue())
Guy Benyei11169dd2012-12-18 14:30:41 +00006984 Out.Subminor = *Subminor;
6985
6986 return Out;
6987}
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00006988
6989static int getCursorPlatformAvailabilityForDecl(const Decl *D,
6990 int *always_deprecated,
6991 CXString *deprecated_message,
6992 int *always_unavailable,
6993 CXString *unavailable_message,
6994 CXPlatformAvailability *availability,
6995 int availability_size) {
6996 bool HadAvailAttr = false;
6997 int N = 0;
Aaron Ballmanb97112e2014-03-08 22:19:01 +00006998 for (auto A : D->attrs()) {
6999 if (DeprecatedAttr *Deprecated = dyn_cast<DeprecatedAttr>(A)) {
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007000 HadAvailAttr = true;
7001 if (always_deprecated)
7002 *always_deprecated = 1;
Nico Weberaacf0312014-04-24 05:16:45 +00007003 if (deprecated_message) {
Argyrios Kyrtzidisedfe07f2014-04-24 06:05:40 +00007004 clang_disposeString(*deprecated_message);
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007005 *deprecated_message = cxstring::createDup(Deprecated->getMessage());
Nico Weberaacf0312014-04-24 05:16:45 +00007006 }
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007007 continue;
7008 }
7009
Aaron Ballmanb97112e2014-03-08 22:19:01 +00007010 if (UnavailableAttr *Unavailable = dyn_cast<UnavailableAttr>(A)) {
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007011 HadAvailAttr = true;
7012 if (always_unavailable)
7013 *always_unavailable = 1;
7014 if (unavailable_message) {
Argyrios Kyrtzidisedfe07f2014-04-24 06:05:40 +00007015 clang_disposeString(*unavailable_message);
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007016 *unavailable_message = cxstring::createDup(Unavailable->getMessage());
7017 }
7018 continue;
7019 }
7020
Aaron Ballmanb97112e2014-03-08 22:19:01 +00007021 if (AvailabilityAttr *Avail = dyn_cast<AvailabilityAttr>(A)) {
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007022 HadAvailAttr = true;
7023 if (N < availability_size) {
7024 availability[N].Platform
7025 = cxstring::createDup(Avail->getPlatform()->getName());
7026 availability[N].Introduced = convertVersion(Avail->getIntroduced());
7027 availability[N].Deprecated = convertVersion(Avail->getDeprecated());
7028 availability[N].Obsoleted = convertVersion(Avail->getObsoleted());
7029 availability[N].Unavailable = Avail->getUnavailable();
7030 availability[N].Message = cxstring::createDup(Avail->getMessage());
7031 }
7032 ++N;
7033 }
7034 }
7035
7036 if (!HadAvailAttr)
7037 if (const EnumConstantDecl *EnumConst = dyn_cast<EnumConstantDecl>(D))
7038 return getCursorPlatformAvailabilityForDecl(
7039 cast<Decl>(EnumConst->getDeclContext()),
7040 always_deprecated,
7041 deprecated_message,
7042 always_unavailable,
7043 unavailable_message,
7044 availability,
7045 availability_size);
Guy Benyei11169dd2012-12-18 14:30:41 +00007046
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007047 return N;
7048}
7049
Guy Benyei11169dd2012-12-18 14:30:41 +00007050int clang_getCursorPlatformAvailability(CXCursor cursor,
7051 int *always_deprecated,
7052 CXString *deprecated_message,
7053 int *always_unavailable,
7054 CXString *unavailable_message,
7055 CXPlatformAvailability *availability,
7056 int availability_size) {
7057 if (always_deprecated)
7058 *always_deprecated = 0;
7059 if (deprecated_message)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00007060 *deprecated_message = cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00007061 if (always_unavailable)
7062 *always_unavailable = 0;
7063 if (unavailable_message)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00007064 *unavailable_message = cxstring::createEmpty();
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007065
Guy Benyei11169dd2012-12-18 14:30:41 +00007066 if (!clang_isDeclaration(cursor.kind))
7067 return 0;
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007068
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007069 const Decl *D = cxcursor::getCursorDecl(cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00007070 if (!D)
7071 return 0;
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007072
7073 return getCursorPlatformAvailabilityForDecl(D, always_deprecated,
7074 deprecated_message,
7075 always_unavailable,
7076 unavailable_message,
7077 availability,
7078 availability_size);
Guy Benyei11169dd2012-12-18 14:30:41 +00007079}
7080
7081void clang_disposeCXPlatformAvailability(CXPlatformAvailability *availability) {
7082 clang_disposeString(availability->Platform);
7083 clang_disposeString(availability->Message);
7084}
7085
7086CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
7087 if (clang_isDeclaration(cursor.kind))
7088 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
7089
7090 return CXLanguage_Invalid;
7091}
7092
7093 /// \brief If the given cursor is the "templated" declaration
7094 /// descibing a class or function template, return the class or
7095 /// function template.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007096static const Decl *maybeGetTemplateCursor(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007097 if (!D)
Craig Topper69186e72014-06-08 08:38:04 +00007098 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007099
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007100 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00007101 if (FunctionTemplateDecl *FunTmpl = FD->getDescribedFunctionTemplate())
7102 return FunTmpl;
7103
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007104 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00007105 if (ClassTemplateDecl *ClassTmpl = RD->getDescribedClassTemplate())
7106 return ClassTmpl;
7107
7108 return D;
7109}
7110
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00007111
7112enum CX_StorageClass clang_Cursor_getStorageClass(CXCursor C) {
7113 StorageClass sc = SC_None;
7114 const Decl *D = getCursorDecl(C);
7115 if (D) {
7116 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7117 sc = FD->getStorageClass();
7118 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7119 sc = VD->getStorageClass();
7120 } else {
7121 return CX_SC_Invalid;
7122 }
7123 } else {
7124 return CX_SC_Invalid;
7125 }
7126 switch (sc) {
7127 case SC_None:
7128 return CX_SC_None;
7129 case SC_Extern:
7130 return CX_SC_Extern;
7131 case SC_Static:
7132 return CX_SC_Static;
7133 case SC_PrivateExtern:
7134 return CX_SC_PrivateExtern;
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00007135 case SC_Auto:
7136 return CX_SC_Auto;
7137 case SC_Register:
7138 return CX_SC_Register;
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00007139 }
Kaelyn Takataab61e702014-10-15 18:03:26 +00007140 llvm_unreachable("Unhandled storage class!");
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00007141}
7142
Guy Benyei11169dd2012-12-18 14:30:41 +00007143CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
7144 if (clang_isDeclaration(cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007145 if (const Decl *D = getCursorDecl(cursor)) {
7146 const DeclContext *DC = D->getDeclContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00007147 if (!DC)
7148 return clang_getNullCursor();
7149
7150 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
7151 getCursorTU(cursor));
7152 }
7153 }
7154
7155 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007156 if (const Decl *D = getCursorDecl(cursor))
Guy Benyei11169dd2012-12-18 14:30:41 +00007157 return MakeCXCursor(D, getCursorTU(cursor));
7158 }
7159
7160 return clang_getNullCursor();
7161}
7162
7163CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
7164 if (clang_isDeclaration(cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007165 if (const Decl *D = getCursorDecl(cursor)) {
7166 const DeclContext *DC = D->getLexicalDeclContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00007167 if (!DC)
7168 return clang_getNullCursor();
7169
7170 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
7171 getCursorTU(cursor));
7172 }
7173 }
7174
7175 // FIXME: Note that we can't easily compute the lexical context of a
7176 // statement or expression, so we return nothing.
7177 return clang_getNullCursor();
7178}
7179
7180CXFile clang_getIncludedFile(CXCursor cursor) {
7181 if (cursor.kind != CXCursor_InclusionDirective)
Craig Topper69186e72014-06-08 08:38:04 +00007182 return nullptr;
7183
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00007184 const InclusionDirective *ID = getCursorInclusionDirective(cursor);
Dmitri Gribenkof9304482013-01-23 15:56:07 +00007185 return const_cast<FileEntry *>(ID->getFile());
Guy Benyei11169dd2012-12-18 14:30:41 +00007186}
7187
Argyrios Kyrtzidis9adfd8a2013-04-18 22:15:49 +00007188unsigned clang_Cursor_getObjCPropertyAttributes(CXCursor C, unsigned reserved) {
7189 if (C.kind != CXCursor_ObjCPropertyDecl)
7190 return CXObjCPropertyAttr_noattr;
7191
7192 unsigned Result = CXObjCPropertyAttr_noattr;
7193 const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(getCursorDecl(C));
7194 ObjCPropertyDecl::PropertyAttributeKind Attr =
7195 PD->getPropertyAttributesAsWritten();
7196
7197#define SET_CXOBJCPROP_ATTR(A) \
7198 if (Attr & ObjCPropertyDecl::OBJC_PR_##A) \
7199 Result |= CXObjCPropertyAttr_##A
7200 SET_CXOBJCPROP_ATTR(readonly);
7201 SET_CXOBJCPROP_ATTR(getter);
7202 SET_CXOBJCPROP_ATTR(assign);
7203 SET_CXOBJCPROP_ATTR(readwrite);
7204 SET_CXOBJCPROP_ATTR(retain);
7205 SET_CXOBJCPROP_ATTR(copy);
7206 SET_CXOBJCPROP_ATTR(nonatomic);
7207 SET_CXOBJCPROP_ATTR(setter);
7208 SET_CXOBJCPROP_ATTR(atomic);
7209 SET_CXOBJCPROP_ATTR(weak);
7210 SET_CXOBJCPROP_ATTR(strong);
7211 SET_CXOBJCPROP_ATTR(unsafe_unretained);
Manman Ren04fd4d82016-05-31 23:22:04 +00007212 SET_CXOBJCPROP_ATTR(class);
Argyrios Kyrtzidis9adfd8a2013-04-18 22:15:49 +00007213#undef SET_CXOBJCPROP_ATTR
7214
7215 return Result;
7216}
7217
Argyrios Kyrtzidis9d9bc012013-04-18 23:29:12 +00007218unsigned clang_Cursor_getObjCDeclQualifiers(CXCursor C) {
7219 if (!clang_isDeclaration(C.kind))
7220 return CXObjCDeclQualifier_None;
7221
7222 Decl::ObjCDeclQualifier QT = Decl::OBJC_TQ_None;
7223 const Decl *D = getCursorDecl(C);
7224 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
7225 QT = MD->getObjCDeclQualifier();
7226 else if (const ParmVarDecl *PD = dyn_cast<ParmVarDecl>(D))
7227 QT = PD->getObjCDeclQualifier();
7228 if (QT == Decl::OBJC_TQ_None)
7229 return CXObjCDeclQualifier_None;
7230
7231 unsigned Result = CXObjCDeclQualifier_None;
7232 if (QT & Decl::OBJC_TQ_In) Result |= CXObjCDeclQualifier_In;
7233 if (QT & Decl::OBJC_TQ_Inout) Result |= CXObjCDeclQualifier_Inout;
7234 if (QT & Decl::OBJC_TQ_Out) Result |= CXObjCDeclQualifier_Out;
7235 if (QT & Decl::OBJC_TQ_Bycopy) Result |= CXObjCDeclQualifier_Bycopy;
7236 if (QT & Decl::OBJC_TQ_Byref) Result |= CXObjCDeclQualifier_Byref;
7237 if (QT & Decl::OBJC_TQ_Oneway) Result |= CXObjCDeclQualifier_Oneway;
7238
7239 return Result;
7240}
7241
Argyrios Kyrtzidis7b50fc52013-07-05 20:44:37 +00007242unsigned clang_Cursor_isObjCOptional(CXCursor C) {
7243 if (!clang_isDeclaration(C.kind))
7244 return 0;
7245
7246 const Decl *D = getCursorDecl(C);
7247 if (const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D))
7248 return PD->getPropertyImplementation() == ObjCPropertyDecl::Optional;
7249 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
7250 return MD->getImplementationControl() == ObjCMethodDecl::Optional;
7251
7252 return 0;
7253}
7254
Argyrios Kyrtzidis23814e42013-04-18 23:53:05 +00007255unsigned clang_Cursor_isVariadic(CXCursor C) {
7256 if (!clang_isDeclaration(C.kind))
7257 return 0;
7258
7259 const Decl *D = getCursorDecl(C);
7260 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
7261 return FD->isVariadic();
7262 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
7263 return MD->isVariadic();
7264
7265 return 0;
7266}
7267
Guy Benyei11169dd2012-12-18 14:30:41 +00007268CXSourceRange clang_Cursor_getCommentRange(CXCursor C) {
7269 if (!clang_isDeclaration(C.kind))
7270 return clang_getNullRange();
7271
7272 const Decl *D = getCursorDecl(C);
7273 ASTContext &Context = getCursorContext(C);
7274 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
7275 if (!RC)
7276 return clang_getNullRange();
7277
7278 return cxloc::translateSourceRange(Context, RC->getSourceRange());
7279}
7280
7281CXString clang_Cursor_getRawCommentText(CXCursor C) {
7282 if (!clang_isDeclaration(C.kind))
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00007283 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00007284
7285 const Decl *D = getCursorDecl(C);
7286 ASTContext &Context = getCursorContext(C);
7287 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
7288 StringRef RawText = RC ? RC->getRawText(Context.getSourceManager()) :
7289 StringRef();
7290
7291 // Don't duplicate the string because RawText points directly into source
7292 // code.
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00007293 return cxstring::createRef(RawText);
Guy Benyei11169dd2012-12-18 14:30:41 +00007294}
7295
7296CXString clang_Cursor_getBriefCommentText(CXCursor C) {
7297 if (!clang_isDeclaration(C.kind))
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00007298 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00007299
7300 const Decl *D = getCursorDecl(C);
7301 const ASTContext &Context = getCursorContext(C);
7302 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
7303
7304 if (RC) {
7305 StringRef BriefText = RC->getBriefText(Context);
7306
7307 // Don't duplicate the string because RawComment ensures that this memory
7308 // will not go away.
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00007309 return cxstring::createRef(BriefText);
Guy Benyei11169dd2012-12-18 14:30:41 +00007310 }
7311
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00007312 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00007313}
7314
Guy Benyei11169dd2012-12-18 14:30:41 +00007315CXModule clang_Cursor_getModule(CXCursor C) {
7316 if (C.kind == CXCursor_ModuleImportDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007317 if (const ImportDecl *ImportD =
7318 dyn_cast_or_null<ImportDecl>(getCursorDecl(C)))
Guy Benyei11169dd2012-12-18 14:30:41 +00007319 return ImportD->getImportedModule();
7320 }
7321
Craig Topper69186e72014-06-08 08:38:04 +00007322 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007323}
7324
Argyrios Kyrtzidisf6d49c32014-05-14 23:14:37 +00007325CXModule clang_getModuleForFile(CXTranslationUnit TU, CXFile File) {
7326 if (isNotUsableTU(TU)) {
7327 LOG_BAD_TU(TU);
7328 return nullptr;
7329 }
7330 if (!File)
7331 return nullptr;
7332 FileEntry *FE = static_cast<FileEntry *>(File);
7333
7334 ASTUnit &Unit = *cxtu::getASTUnit(TU);
7335 HeaderSearch &HS = Unit.getPreprocessor().getHeaderSearchInfo();
7336 ModuleMap::KnownHeader Header = HS.findModuleForHeader(FE);
7337
Richard Smithfeb54b62014-10-23 02:01:19 +00007338 return Header.getModule();
Argyrios Kyrtzidisf6d49c32014-05-14 23:14:37 +00007339}
7340
Argyrios Kyrtzidis12fdb9e2013-04-26 22:47:49 +00007341CXFile clang_Module_getASTFile(CXModule CXMod) {
7342 if (!CXMod)
Craig Topper69186e72014-06-08 08:38:04 +00007343 return nullptr;
Argyrios Kyrtzidis12fdb9e2013-04-26 22:47:49 +00007344 Module *Mod = static_cast<Module*>(CXMod);
7345 return const_cast<FileEntry *>(Mod->getASTFile());
7346}
7347
Guy Benyei11169dd2012-12-18 14:30:41 +00007348CXModule clang_Module_getParent(CXModule CXMod) {
7349 if (!CXMod)
Craig Topper69186e72014-06-08 08:38:04 +00007350 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007351 Module *Mod = static_cast<Module*>(CXMod);
7352 return Mod->Parent;
7353}
7354
7355CXString clang_Module_getName(CXModule CXMod) {
7356 if (!CXMod)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00007357 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00007358 Module *Mod = static_cast<Module*>(CXMod);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00007359 return cxstring::createDup(Mod->Name);
Guy Benyei11169dd2012-12-18 14:30:41 +00007360}
7361
7362CXString clang_Module_getFullName(CXModule CXMod) {
7363 if (!CXMod)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00007364 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00007365 Module *Mod = static_cast<Module*>(CXMod);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00007366 return cxstring::createDup(Mod->getFullModuleName());
Guy Benyei11169dd2012-12-18 14:30:41 +00007367}
7368
Argyrios Kyrtzidis884337f2014-05-15 04:44:25 +00007369int clang_Module_isSystem(CXModule CXMod) {
7370 if (!CXMod)
7371 return 0;
7372 Module *Mod = static_cast<Module*>(CXMod);
7373 return Mod->IsSystem;
7374}
7375
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00007376unsigned clang_Module_getNumTopLevelHeaders(CXTranslationUnit TU,
7377 CXModule CXMod) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00007378 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00007379 LOG_BAD_TU(TU);
7380 return 0;
7381 }
7382 if (!CXMod)
Guy Benyei11169dd2012-12-18 14:30:41 +00007383 return 0;
7384 Module *Mod = static_cast<Module*>(CXMod);
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00007385 FileManager &FileMgr = cxtu::getASTUnit(TU)->getFileManager();
7386 ArrayRef<const FileEntry *> TopHeaders = Mod->getTopHeaders(FileMgr);
7387 return TopHeaders.size();
Guy Benyei11169dd2012-12-18 14:30:41 +00007388}
7389
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00007390CXFile clang_Module_getTopLevelHeader(CXTranslationUnit TU,
7391 CXModule CXMod, unsigned Index) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00007392 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00007393 LOG_BAD_TU(TU);
Craig Topper69186e72014-06-08 08:38:04 +00007394 return nullptr;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00007395 }
7396 if (!CXMod)
Craig Topper69186e72014-06-08 08:38:04 +00007397 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007398 Module *Mod = static_cast<Module*>(CXMod);
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00007399 FileManager &FileMgr = cxtu::getASTUnit(TU)->getFileManager();
Guy Benyei11169dd2012-12-18 14:30:41 +00007400
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00007401 ArrayRef<const FileEntry *> TopHeaders = Mod->getTopHeaders(FileMgr);
7402 if (Index < TopHeaders.size())
7403 return const_cast<FileEntry *>(TopHeaders[Index]);
Guy Benyei11169dd2012-12-18 14:30:41 +00007404
Craig Topper69186e72014-06-08 08:38:04 +00007405 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007406}
7407
7408} // end: extern "C"
7409
7410//===----------------------------------------------------------------------===//
7411// C++ AST instrospection.
7412//===----------------------------------------------------------------------===//
7413
7414extern "C" {
Jonathan Coe29565352016-04-27 12:48:25 +00007415
7416unsigned clang_CXXConstructor_isDefaultConstructor(CXCursor C) {
7417 if (!clang_isDeclaration(C.kind))
7418 return 0;
7419
7420 const Decl *D = cxcursor::getCursorDecl(C);
7421 const CXXConstructorDecl *Constructor =
7422 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
7423 return (Constructor && Constructor->isDefaultConstructor()) ? 1 : 0;
7424}
7425
7426unsigned clang_CXXConstructor_isCopyConstructor(CXCursor C) {
7427 if (!clang_isDeclaration(C.kind))
7428 return 0;
7429
7430 const Decl *D = cxcursor::getCursorDecl(C);
7431 const CXXConstructorDecl *Constructor =
7432 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
7433 return (Constructor && Constructor->isCopyConstructor()) ? 1 : 0;
7434}
7435
7436unsigned clang_CXXConstructor_isMoveConstructor(CXCursor C) {
7437 if (!clang_isDeclaration(C.kind))
7438 return 0;
7439
7440 const Decl *D = cxcursor::getCursorDecl(C);
7441 const CXXConstructorDecl *Constructor =
7442 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
7443 return (Constructor && Constructor->isMoveConstructor()) ? 1 : 0;
7444}
7445
7446unsigned clang_CXXConstructor_isConvertingConstructor(CXCursor C) {
7447 if (!clang_isDeclaration(C.kind))
7448 return 0;
7449
7450 const Decl *D = cxcursor::getCursorDecl(C);
7451 const CXXConstructorDecl *Constructor =
7452 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
7453 // Passing 'false' excludes constructors marked 'explicit'.
7454 return (Constructor && Constructor->isConvertingConstructor(false)) ? 1 : 0;
7455}
7456
Saleem Abdulrasool6ea75db2015-10-27 15:50:22 +00007457unsigned clang_CXXField_isMutable(CXCursor C) {
7458 if (!clang_isDeclaration(C.kind))
7459 return 0;
7460
7461 if (const auto D = cxcursor::getCursorDecl(C))
7462 if (const auto FD = dyn_cast_or_null<FieldDecl>(D))
7463 return FD->isMutable() ? 1 : 0;
7464 return 0;
7465}
7466
Dmitri Gribenko62770be2013-05-17 18:38:35 +00007467unsigned clang_CXXMethod_isPureVirtual(CXCursor C) {
7468 if (!clang_isDeclaration(C.kind))
7469 return 0;
7470
Dmitri Gribenko62770be2013-05-17 18:38:35 +00007471 const Decl *D = cxcursor::getCursorDecl(C);
Alp Tokera2794f92014-01-22 07:29:52 +00007472 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00007473 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Dmitri Gribenko62770be2013-05-17 18:38:35 +00007474 return (Method && Method->isVirtual() && Method->isPure()) ? 1 : 0;
7475}
7476
Dmitri Gribenkoe570ede2014-04-07 14:59:13 +00007477unsigned clang_CXXMethod_isConst(CXCursor C) {
7478 if (!clang_isDeclaration(C.kind))
7479 return 0;
7480
7481 const Decl *D = cxcursor::getCursorDecl(C);
7482 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00007483 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Dmitri Gribenkoe570ede2014-04-07 14:59:13 +00007484 return (Method && (Method->getTypeQualifiers() & Qualifiers::Const)) ? 1 : 0;
7485}
7486
Jonathan Coe29565352016-04-27 12:48:25 +00007487unsigned clang_CXXMethod_isDefaulted(CXCursor C) {
7488 if (!clang_isDeclaration(C.kind))
7489 return 0;
7490
7491 const Decl *D = cxcursor::getCursorDecl(C);
7492 const CXXMethodDecl *Method =
7493 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
7494 return (Method && Method->isDefaulted()) ? 1 : 0;
7495}
7496
Guy Benyei11169dd2012-12-18 14:30:41 +00007497unsigned clang_CXXMethod_isStatic(CXCursor C) {
7498 if (!clang_isDeclaration(C.kind))
7499 return 0;
7500
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007501 const Decl *D = cxcursor::getCursorDecl(C);
Alp Tokera2794f92014-01-22 07:29:52 +00007502 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00007503 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007504 return (Method && Method->isStatic()) ? 1 : 0;
7505}
7506
7507unsigned clang_CXXMethod_isVirtual(CXCursor C) {
7508 if (!clang_isDeclaration(C.kind))
7509 return 0;
7510
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007511 const Decl *D = cxcursor::getCursorDecl(C);
Alp Tokera2794f92014-01-22 07:29:52 +00007512 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00007513 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007514 return (Method && Method->isVirtual()) ? 1 : 0;
7515}
7516} // end: extern "C"
7517
7518//===----------------------------------------------------------------------===//
7519// Attribute introspection.
7520//===----------------------------------------------------------------------===//
7521
7522extern "C" {
7523CXType clang_getIBOutletCollectionType(CXCursor C) {
7524 if (C.kind != CXCursor_IBOutletCollectionAttr)
7525 return cxtype::MakeCXType(QualType(), cxcursor::getCursorTU(C));
7526
Dmitri Gribenkoe4baea62013-01-26 18:08:08 +00007527 const IBOutletCollectionAttr *A =
Guy Benyei11169dd2012-12-18 14:30:41 +00007528 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
7529
7530 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorTU(C));
7531}
7532} // end: extern "C"
7533
7534//===----------------------------------------------------------------------===//
7535// Inspecting memory usage.
7536//===----------------------------------------------------------------------===//
7537
7538typedef std::vector<CXTUResourceUsageEntry> MemUsageEntries;
7539
7540static inline void createCXTUResourceUsageEntry(MemUsageEntries &entries,
7541 enum CXTUResourceUsageKind k,
7542 unsigned long amount) {
7543 CXTUResourceUsageEntry entry = { k, amount };
7544 entries.push_back(entry);
7545}
7546
7547extern "C" {
7548
7549const char *clang_getTUResourceUsageName(CXTUResourceUsageKind kind) {
7550 const char *str = "";
7551 switch (kind) {
7552 case CXTUResourceUsage_AST:
7553 str = "ASTContext: expressions, declarations, and types";
7554 break;
7555 case CXTUResourceUsage_Identifiers:
7556 str = "ASTContext: identifiers";
7557 break;
7558 case CXTUResourceUsage_Selectors:
7559 str = "ASTContext: selectors";
7560 break;
7561 case CXTUResourceUsage_GlobalCompletionResults:
7562 str = "Code completion: cached global results";
7563 break;
7564 case CXTUResourceUsage_SourceManagerContentCache:
7565 str = "SourceManager: content cache allocator";
7566 break;
7567 case CXTUResourceUsage_AST_SideTables:
7568 str = "ASTContext: side tables";
7569 break;
7570 case CXTUResourceUsage_SourceManager_Membuffer_Malloc:
7571 str = "SourceManager: malloc'ed memory buffers";
7572 break;
7573 case CXTUResourceUsage_SourceManager_Membuffer_MMap:
7574 str = "SourceManager: mmap'ed memory buffers";
7575 break;
7576 case CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc:
7577 str = "ExternalASTSource: malloc'ed memory buffers";
7578 break;
7579 case CXTUResourceUsage_ExternalASTSource_Membuffer_MMap:
7580 str = "ExternalASTSource: mmap'ed memory buffers";
7581 break;
7582 case CXTUResourceUsage_Preprocessor:
7583 str = "Preprocessor: malloc'ed memory";
7584 break;
7585 case CXTUResourceUsage_PreprocessingRecord:
7586 str = "Preprocessor: PreprocessingRecord";
7587 break;
7588 case CXTUResourceUsage_SourceManager_DataStructures:
7589 str = "SourceManager: data structures and tables";
7590 break;
7591 case CXTUResourceUsage_Preprocessor_HeaderSearch:
7592 str = "Preprocessor: header search tables";
7593 break;
7594 }
7595 return str;
7596}
7597
7598CXTUResourceUsage clang_getCXTUResourceUsage(CXTranslationUnit TU) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00007599 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00007600 LOG_BAD_TU(TU);
Craig Topper69186e72014-06-08 08:38:04 +00007601 CXTUResourceUsage usage = { (void*) nullptr, 0, nullptr };
Guy Benyei11169dd2012-12-18 14:30:41 +00007602 return usage;
7603 }
7604
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00007605 ASTUnit *astUnit = cxtu::getASTUnit(TU);
Ahmed Charlesb8984322014-03-07 20:03:18 +00007606 std::unique_ptr<MemUsageEntries> entries(new MemUsageEntries());
Guy Benyei11169dd2012-12-18 14:30:41 +00007607 ASTContext &astContext = astUnit->getASTContext();
7608
7609 // How much memory is used by AST nodes and types?
7610 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST,
7611 (unsigned long) astContext.getASTAllocatedMemory());
7612
7613 // How much memory is used by identifiers?
7614 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Identifiers,
7615 (unsigned long) astContext.Idents.getAllocator().getTotalMemory());
7616
7617 // How much memory is used for selectors?
7618 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Selectors,
7619 (unsigned long) astContext.Selectors.getTotalMemory());
7620
7621 // How much memory is used by ASTContext's side tables?
7622 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST_SideTables,
7623 (unsigned long) astContext.getSideTableAllocatedMemory());
7624
7625 // How much memory is used for caching global code completion results?
7626 unsigned long completionBytes = 0;
7627 if (GlobalCodeCompletionAllocator *completionAllocator =
Alp Tokerf994cef2014-07-05 03:08:06 +00007628 astUnit->getCachedCompletionAllocator().get()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007629 completionBytes = completionAllocator->getTotalMemory();
7630 }
7631 createCXTUResourceUsageEntry(*entries,
7632 CXTUResourceUsage_GlobalCompletionResults,
7633 completionBytes);
7634
7635 // How much memory is being used by SourceManager's content cache?
7636 createCXTUResourceUsageEntry(*entries,
7637 CXTUResourceUsage_SourceManagerContentCache,
7638 (unsigned long) astContext.getSourceManager().getContentCacheSize());
7639
7640 // How much memory is being used by the MemoryBuffer's in SourceManager?
7641 const SourceManager::MemoryBufferSizes &srcBufs =
7642 astUnit->getSourceManager().getMemoryBufferSizes();
7643
7644 createCXTUResourceUsageEntry(*entries,
7645 CXTUResourceUsage_SourceManager_Membuffer_Malloc,
7646 (unsigned long) srcBufs.malloc_bytes);
7647 createCXTUResourceUsageEntry(*entries,
7648 CXTUResourceUsage_SourceManager_Membuffer_MMap,
7649 (unsigned long) srcBufs.mmap_bytes);
7650 createCXTUResourceUsageEntry(*entries,
7651 CXTUResourceUsage_SourceManager_DataStructures,
7652 (unsigned long) astContext.getSourceManager()
7653 .getDataStructureSizes());
7654
7655 // How much memory is being used by the ExternalASTSource?
7656 if (ExternalASTSource *esrc = astContext.getExternalSource()) {
7657 const ExternalASTSource::MemoryBufferSizes &sizes =
7658 esrc->getMemoryBufferSizes();
7659
7660 createCXTUResourceUsageEntry(*entries,
7661 CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc,
7662 (unsigned long) sizes.malloc_bytes);
7663 createCXTUResourceUsageEntry(*entries,
7664 CXTUResourceUsage_ExternalASTSource_Membuffer_MMap,
7665 (unsigned long) sizes.mmap_bytes);
7666 }
7667
7668 // How much memory is being used by the Preprocessor?
7669 Preprocessor &pp = astUnit->getPreprocessor();
7670 createCXTUResourceUsageEntry(*entries,
7671 CXTUResourceUsage_Preprocessor,
7672 pp.getTotalMemory());
7673
7674 if (PreprocessingRecord *pRec = pp.getPreprocessingRecord()) {
7675 createCXTUResourceUsageEntry(*entries,
7676 CXTUResourceUsage_PreprocessingRecord,
7677 pRec->getTotalMemory());
7678 }
7679
7680 createCXTUResourceUsageEntry(*entries,
7681 CXTUResourceUsage_Preprocessor_HeaderSearch,
7682 pp.getHeaderSearchInfo().getTotalMemory());
Craig Topper69186e72014-06-08 08:38:04 +00007683
Guy Benyei11169dd2012-12-18 14:30:41 +00007684 CXTUResourceUsage usage = { (void*) entries.get(),
7685 (unsigned) entries->size(),
Alexander Kornienko6ee521c2015-01-23 15:36:10 +00007686 !entries->empty() ? &(*entries)[0] : nullptr };
Ahmed Charles9a16beb2014-03-07 19:33:25 +00007687 entries.release();
Guy Benyei11169dd2012-12-18 14:30:41 +00007688 return usage;
7689}
7690
7691void clang_disposeCXTUResourceUsage(CXTUResourceUsage usage) {
7692 if (usage.data)
7693 delete (MemUsageEntries*) usage.data;
7694}
7695
Argyrios Kyrtzidis0e282ef2013-12-06 18:55:45 +00007696CXSourceRangeList *clang_getSkippedRanges(CXTranslationUnit TU, CXFile file) {
7697 CXSourceRangeList *skipped = new CXSourceRangeList;
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00007698 skipped->count = 0;
Craig Topper69186e72014-06-08 08:38:04 +00007699 skipped->ranges = nullptr;
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00007700
Dmitri Gribenko852d6222014-02-11 15:02:48 +00007701 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00007702 LOG_BAD_TU(TU);
7703 return skipped;
7704 }
7705
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00007706 if (!file)
7707 return skipped;
7708
7709 ASTUnit *astUnit = cxtu::getASTUnit(TU);
7710 PreprocessingRecord *ppRec = astUnit->getPreprocessor().getPreprocessingRecord();
7711 if (!ppRec)
7712 return skipped;
7713
7714 ASTContext &Ctx = astUnit->getASTContext();
7715 SourceManager &sm = Ctx.getSourceManager();
7716 FileEntry *fileEntry = static_cast<FileEntry *>(file);
7717 FileID wantedFileID = sm.translateFile(fileEntry);
7718
7719 const std::vector<SourceRange> &SkippedRanges = ppRec->getSkippedRanges();
7720 std::vector<SourceRange> wantedRanges;
7721 for (std::vector<SourceRange>::const_iterator i = SkippedRanges.begin(), ei = SkippedRanges.end();
7722 i != ei; ++i) {
7723 if (sm.getFileID(i->getBegin()) == wantedFileID || sm.getFileID(i->getEnd()) == wantedFileID)
7724 wantedRanges.push_back(*i);
7725 }
7726
7727 skipped->count = wantedRanges.size();
7728 skipped->ranges = new CXSourceRange[skipped->count];
7729 for (unsigned i = 0, ei = skipped->count; i != ei; ++i)
7730 skipped->ranges[i] = cxloc::translateSourceRange(Ctx, wantedRanges[i]);
7731
7732 return skipped;
7733}
7734
Argyrios Kyrtzidis0e282ef2013-12-06 18:55:45 +00007735void clang_disposeSourceRangeList(CXSourceRangeList *ranges) {
7736 if (ranges) {
7737 delete[] ranges->ranges;
7738 delete ranges;
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00007739 }
7740}
7741
Guy Benyei11169dd2012-12-18 14:30:41 +00007742} // end extern "C"
7743
7744void clang::PrintLibclangResourceUsage(CXTranslationUnit TU) {
7745 CXTUResourceUsage Usage = clang_getCXTUResourceUsage(TU);
7746 for (unsigned I = 0; I != Usage.numEntries; ++I)
7747 fprintf(stderr, " %s: %lu\n",
7748 clang_getTUResourceUsageName(Usage.entries[I].kind),
7749 Usage.entries[I].amount);
7750
7751 clang_disposeCXTUResourceUsage(Usage);
7752}
7753
7754//===----------------------------------------------------------------------===//
7755// Misc. utility functions.
7756//===----------------------------------------------------------------------===//
7757
7758/// Default to using an 8 MB stack size on "safety" threads.
7759static unsigned SafetyStackThreadSize = 8 << 20;
7760
7761namespace clang {
7762
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00007763bool RunSafely(llvm::CrashRecoveryContext &CRC, llvm::function_ref<void()> Fn,
Guy Benyei11169dd2012-12-18 14:30:41 +00007764 unsigned Size) {
7765 if (!Size)
7766 Size = GetSafetyThreadStackSize();
7767 if (Size)
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00007768 return CRC.RunSafelyOnThread(Fn, Size);
7769 return CRC.RunSafely(Fn);
Guy Benyei11169dd2012-12-18 14:30:41 +00007770}
7771
7772unsigned GetSafetyThreadStackSize() {
7773 return SafetyStackThreadSize;
7774}
7775
7776void SetSafetyThreadStackSize(unsigned Value) {
7777 SafetyStackThreadSize = Value;
7778}
7779
Alexander Kornienkoab9db512015-06-22 23:07:51 +00007780}
Guy Benyei11169dd2012-12-18 14:30:41 +00007781
7782void clang::setThreadBackgroundPriority() {
7783 if (getenv("LIBCLANG_BGPRIO_DISABLE"))
7784 return;
7785
Alp Toker1a86ad22014-07-06 06:24:00 +00007786#ifdef USE_DARWIN_THREADS
Guy Benyei11169dd2012-12-18 14:30:41 +00007787 setpriority(PRIO_DARWIN_THREAD, 0, PRIO_DARWIN_BG);
7788#endif
7789}
7790
7791void cxindex::printDiagsToStderr(ASTUnit *Unit) {
7792 if (!Unit)
7793 return;
7794
7795 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
7796 DEnd = Unit->stored_diag_end();
7797 D != DEnd; ++D) {
Ben Langmuir749323f2014-04-22 17:40:12 +00007798 CXStoredDiagnostic Diag(*D, Unit->getLangOpts());
Guy Benyei11169dd2012-12-18 14:30:41 +00007799 CXString Msg = clang_formatDiagnostic(&Diag,
7800 clang_defaultDiagnosticDisplayOptions());
7801 fprintf(stderr, "%s\n", clang_getCString(Msg));
7802 clang_disposeString(Msg);
7803 }
7804#ifdef LLVM_ON_WIN32
7805 // On Windows, force a flush, since there may be multiple copies of
7806 // stderr and stdout in the file system, all with different buffers
7807 // but writing to the same device.
7808 fflush(stderr);
7809#endif
7810}
7811
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007812MacroInfo *cxindex::getMacroInfo(const IdentifierInfo &II,
7813 SourceLocation MacroDefLoc,
7814 CXTranslationUnit TU){
7815 if (MacroDefLoc.isInvalid() || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00007816 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007817 if (!II.hadMacroDefinition())
Craig Topper69186e72014-06-08 08:38:04 +00007818 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007819
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00007820 ASTUnit *Unit = cxtu::getASTUnit(TU);
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007821 Preprocessor &PP = Unit->getPreprocessor();
Richard Smith20e883e2015-04-29 23:20:19 +00007822 MacroDirective *MD = PP.getLocalMacroDirectiveHistory(&II);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00007823 if (MD) {
7824 for (MacroDirective::DefInfo
7825 Def = MD->getDefinition(); Def; Def = Def.getPreviousDefinition()) {
7826 if (MacroDefLoc == Def.getMacroInfo()->getDefinitionLoc())
7827 return Def.getMacroInfo();
7828 }
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007829 }
7830
Craig Topper69186e72014-06-08 08:38:04 +00007831 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007832}
7833
Richard Smith66a81862015-05-04 02:25:31 +00007834const MacroInfo *cxindex::getMacroInfo(const MacroDefinitionRecord *MacroDef,
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00007835 CXTranslationUnit TU) {
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007836 if (!MacroDef || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00007837 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007838 const IdentifierInfo *II = MacroDef->getName();
7839 if (!II)
Craig Topper69186e72014-06-08 08:38:04 +00007840 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007841
7842 return getMacroInfo(*II, MacroDef->getLocation(), TU);
7843}
7844
Richard Smith66a81862015-05-04 02:25:31 +00007845MacroDefinitionRecord *
7846cxindex::checkForMacroInMacroDefinition(const MacroInfo *MI, const Token &Tok,
7847 CXTranslationUnit TU) {
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007848 if (!MI || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00007849 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007850 if (Tok.isNot(tok::raw_identifier))
Craig Topper69186e72014-06-08 08:38:04 +00007851 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007852
7853 if (MI->getNumTokens() == 0)
Craig Topper69186e72014-06-08 08:38:04 +00007854 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007855 SourceRange DefRange(MI->getReplacementToken(0).getLocation(),
7856 MI->getDefinitionEndLoc());
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00007857 ASTUnit *Unit = cxtu::getASTUnit(TU);
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007858
7859 // Check that the token is inside the definition and not its argument list.
7860 SourceManager &SM = Unit->getSourceManager();
7861 if (SM.isBeforeInTranslationUnit(Tok.getLocation(), DefRange.getBegin()))
Craig Topper69186e72014-06-08 08:38:04 +00007862 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007863 if (SM.isBeforeInTranslationUnit(DefRange.getEnd(), Tok.getLocation()))
Craig Topper69186e72014-06-08 08:38:04 +00007864 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007865
7866 Preprocessor &PP = Unit->getPreprocessor();
7867 PreprocessingRecord *PPRec = PP.getPreprocessingRecord();
7868 if (!PPRec)
Craig Topper69186e72014-06-08 08:38:04 +00007869 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007870
Alp Toker2d57cea2014-05-17 04:53:25 +00007871 IdentifierInfo &II = PP.getIdentifierTable().get(Tok.getRawIdentifier());
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007872 if (!II.hadMacroDefinition())
Craig Topper69186e72014-06-08 08:38:04 +00007873 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007874
7875 // Check that the identifier is not one of the macro arguments.
7876 if (std::find(MI->arg_begin(), MI->arg_end(), &II) != MI->arg_end())
Craig Topper69186e72014-06-08 08:38:04 +00007877 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007878
Richard Smith20e883e2015-04-29 23:20:19 +00007879 MacroDirective *InnerMD = PP.getLocalMacroDirectiveHistory(&II);
Argyrios Kyrtzidis09c9e812013-02-20 00:54:57 +00007880 if (!InnerMD)
Craig Topper69186e72014-06-08 08:38:04 +00007881 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007882
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00007883 return PPRec->findMacroDefinition(InnerMD->getMacroInfo());
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007884}
7885
Richard Smith66a81862015-05-04 02:25:31 +00007886MacroDefinitionRecord *
7887cxindex::checkForMacroInMacroDefinition(const MacroInfo *MI, SourceLocation Loc,
7888 CXTranslationUnit TU) {
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007889 if (Loc.isInvalid() || !MI || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00007890 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007891
7892 if (MI->getNumTokens() == 0)
Craig Topper69186e72014-06-08 08:38:04 +00007893 return nullptr;
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00007894 ASTUnit *Unit = cxtu::getASTUnit(TU);
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007895 Preprocessor &PP = Unit->getPreprocessor();
7896 if (!PP.getPreprocessingRecord())
Craig Topper69186e72014-06-08 08:38:04 +00007897 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007898 Loc = Unit->getSourceManager().getSpellingLoc(Loc);
7899 Token Tok;
7900 if (PP.getRawToken(Loc, Tok))
Craig Topper69186e72014-06-08 08:38:04 +00007901 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007902
7903 return checkForMacroInMacroDefinition(MI, Tok, TU);
7904}
7905
Guy Benyei11169dd2012-12-18 14:30:41 +00007906extern "C" {
7907
7908CXString clang_getClangVersion() {
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00007909 return cxstring::createDup(getClangFullVersion());
Guy Benyei11169dd2012-12-18 14:30:41 +00007910}
7911
7912} // end: extern "C"
7913
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00007914Logger &cxindex::Logger::operator<<(CXTranslationUnit TU) {
7915 if (TU) {
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00007916 if (ASTUnit *Unit = cxtu::getASTUnit(TU)) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00007917 LogOS << '<' << Unit->getMainFileName() << '>';
Argyrios Kyrtzidis37f2ab42013-03-05 20:21:14 +00007918 if (Unit->isMainFileAST())
7919 LogOS << " (" << Unit->getASTFileName() << ')';
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00007920 return *this;
7921 }
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00007922 } else {
7923 LogOS << "<NULL TU>";
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00007924 }
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00007925 return *this;
7926}
7927
Argyrios Kyrtzidisba4b5f82013-03-08 02:32:26 +00007928Logger &cxindex::Logger::operator<<(const FileEntry *FE) {
7929 *this << FE->getName();
7930 return *this;
7931}
7932
7933Logger &cxindex::Logger::operator<<(CXCursor cursor) {
7934 CXString cursorName = clang_getCursorDisplayName(cursor);
7935 *this << cursorName << "@" << clang_getCursorLocation(cursor);
7936 clang_disposeString(cursorName);
7937 return *this;
7938}
7939
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00007940Logger &cxindex::Logger::operator<<(CXSourceLocation Loc) {
7941 CXFile File;
7942 unsigned Line, Column;
Craig Topper69186e72014-06-08 08:38:04 +00007943 clang_getFileLocation(Loc, &File, &Line, &Column, nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00007944 CXString FileName = clang_getFileName(File);
7945 *this << llvm::format("(%s:%d:%d)", clang_getCString(FileName), Line, Column);
7946 clang_disposeString(FileName);
7947 return *this;
7948}
7949
7950Logger &cxindex::Logger::operator<<(CXSourceRange range) {
7951 CXSourceLocation BLoc = clang_getRangeStart(range);
7952 CXSourceLocation ELoc = clang_getRangeEnd(range);
7953
7954 CXFile BFile;
7955 unsigned BLine, BColumn;
Craig Topper69186e72014-06-08 08:38:04 +00007956 clang_getFileLocation(BLoc, &BFile, &BLine, &BColumn, nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00007957
7958 CXFile EFile;
7959 unsigned ELine, EColumn;
Craig Topper69186e72014-06-08 08:38:04 +00007960 clang_getFileLocation(ELoc, &EFile, &ELine, &EColumn, nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00007961
7962 CXString BFileName = clang_getFileName(BFile);
7963 if (BFile == EFile) {
7964 *this << llvm::format("[%s %d:%d-%d:%d]", clang_getCString(BFileName),
7965 BLine, BColumn, ELine, EColumn);
7966 } else {
7967 CXString EFileName = clang_getFileName(EFile);
7968 *this << llvm::format("[%s:%d:%d - ", clang_getCString(BFileName),
7969 BLine, BColumn)
7970 << llvm::format("%s:%d:%d]", clang_getCString(EFileName),
7971 ELine, EColumn);
7972 clang_disposeString(EFileName);
7973 }
7974 clang_disposeString(BFileName);
7975 return *this;
7976}
7977
7978Logger &cxindex::Logger::operator<<(CXString Str) {
7979 *this << clang_getCString(Str);
7980 return *this;
7981}
7982
7983Logger &cxindex::Logger::operator<<(const llvm::format_object_base &Fmt) {
7984 LogOS << Fmt;
7985 return *this;
7986}
7987
Chandler Carruth37ad2582014-06-27 15:14:39 +00007988static llvm::ManagedStatic<llvm::sys::Mutex> LoggingMutex;
7989
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00007990cxindex::Logger::~Logger() {
Chandler Carruth37ad2582014-06-27 15:14:39 +00007991 llvm::sys::ScopedLock L(*LoggingMutex);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00007992
7993 static llvm::TimeRecord sBeginTR = llvm::TimeRecord::getCurrentTime();
7994
Dmitri Gribenkof8579502013-01-12 19:30:44 +00007995 raw_ostream &OS = llvm::errs();
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00007996 OS << "[libclang:" << Name << ':';
7997
Alp Toker1a86ad22014-07-06 06:24:00 +00007998#ifdef USE_DARWIN_THREADS
7999 // TODO: Portability.
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008000 mach_port_t tid = pthread_mach_thread_np(pthread_self());
8001 OS << tid << ':';
8002#endif
8003
8004 llvm::TimeRecord TR = llvm::TimeRecord::getCurrentTime();
8005 OS << llvm::format("%7.4f] ", TR.getWallTime() - sBeginTR.getWallTime());
Yaron Keren09fb7c62015-03-10 07:33:23 +00008006 OS << Msg << '\n';
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008007
8008 if (Trace) {
Zachary Turner1fe2a8d2015-03-05 19:15:09 +00008009 llvm::sys::PrintStackTrace(OS);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008010 OS << "--------------------------------------------------\n";
8011 }
8012}
Benjamin Kramerc1ffdab2016-03-03 08:58:18 +00008013
8014#ifdef CLANG_TOOL_EXTRA_BUILD
8015// This anchor is used to force the linker to link the clang-tidy plugin.
8016extern volatile int ClangTidyPluginAnchorSource;
8017static int LLVM_ATTRIBUTE_UNUSED ClangTidyPluginAnchorDestination =
8018 ClangTidyPluginAnchorSource;
8019#endif