blob: 8cbedd0ad80fab18f259d350fd38a4e5970949c1 [file] [log] [blame]
Guy Benyei11169dd2012-12-18 14:30:41 +00001//===- CIndex.cpp - Clang-C Source Indexing Library -----------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the main API hooks in the Clang-C Source Indexing
11// library.
12//
13//===----------------------------------------------------------------------===//
14
Guy Benyei11169dd2012-12-18 14:30:41 +000015#include "CIndexDiagnostic.h"
Mehdi Amini9670f842016-07-18 19:02:11 +000016#include "CIndexer.h"
Chandler Carruth4b417452013-01-19 08:09:44 +000017#include "CLog.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000018#include "CXCursor.h"
19#include "CXSourceLocation.h"
20#include "CXString.h"
21#include "CXTranslationUnit.h"
22#include "CXType.h"
23#include "CursorVisitor.h"
David Blaikie0a4e61f2013-09-13 18:32:52 +000024#include "clang/AST/Attr.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000025#include "clang/AST/StmtVisitor.h"
26#include "clang/Basic/Diagnostic.h"
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +000027#include "clang/Basic/DiagnosticCategories.h"
28#include "clang/Basic/DiagnosticIDs.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000029#include "clang/Basic/Version.h"
30#include "clang/Frontend/ASTUnit.h"
31#include "clang/Frontend/CompilerInstance.h"
32#include "clang/Frontend/FrontendDiagnostic.h"
Argyrios Kyrtzidisca741ce2016-02-14 22:30:14 +000033#include "clang/Index/CodegenNameGenerator.h"
Dmitri Gribenko9e605112013-11-13 22:16:51 +000034#include "clang/Index/CommentToXML.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000035#include "clang/Lex/HeaderSearch.h"
36#include "clang/Lex/Lexer.h"
37#include "clang/Lex/PreprocessingRecord.h"
38#include "clang/Lex/Preprocessor.h"
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +000039#include "clang/Serialization/SerializationDiagnostic.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000040#include "llvm/ADT/Optional.h"
41#include "llvm/ADT/STLExtras.h"
42#include "llvm/ADT/StringSwitch.h"
Alp Toker1d257e12014-06-04 03:28:55 +000043#include "llvm/Config/llvm-config.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000044#include "llvm/Support/Compiler.h"
45#include "llvm/Support/CrashRecoveryContext.h"
Chandler Carruth4b417452013-01-19 08:09:44 +000046#include "llvm/Support/Format.h"
Chandler Carruth37ad2582014-06-27 15:14:39 +000047#include "llvm/Support/ManagedStatic.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000048#include "llvm/Support/MemoryBuffer.h"
49#include "llvm/Support/Mutex.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000050#include "llvm/Support/Program.h"
51#include "llvm/Support/SaveAndRestore.h"
52#include "llvm/Support/Signals.h"
Adrian Prantlbc068582015-07-08 01:00:30 +000053#include "llvm/Support/TargetSelect.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000054#include "llvm/Support/Threading.h"
55#include "llvm/Support/Timer.h"
56#include "llvm/Support/raw_ostream.h"
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +000057
Alp Toker1a86ad22014-07-06 06:24:00 +000058#if LLVM_ENABLE_THREADS != 0 && defined(__APPLE__)
59#define USE_DARWIN_THREADS
60#endif
61
62#ifdef USE_DARWIN_THREADS
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +000063#include <pthread.h>
64#endif
Guy Benyei11169dd2012-12-18 14:30:41 +000065
66using namespace clang;
67using namespace clang::cxcursor;
Guy Benyei11169dd2012-12-18 14:30:41 +000068using namespace clang::cxtu;
69using namespace clang::cxindex;
70
Dmitri Gribenkod36209e2013-01-26 21:32:42 +000071CXTranslationUnit cxtu::MakeCXTranslationUnit(CIndexer *CIdx, ASTUnit *AU) {
72 if (!AU)
Craig Topper69186e72014-06-08 08:38:04 +000073 return nullptr;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +000074 assert(CIdx);
Guy Benyei11169dd2012-12-18 14:30:41 +000075 CXTranslationUnit D = new CXTranslationUnitImpl();
76 D->CIdx = CIdx;
Dmitri Gribenkod36209e2013-01-26 21:32:42 +000077 D->TheASTUnit = AU;
Dmitri Gribenko74895212013-02-03 13:52:47 +000078 D->StringPool = new cxstring::CXStringPool();
Craig Topper69186e72014-06-08 08:38:04 +000079 D->Diagnostics = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +000080 D->OverridenCursorsPool = createOverridenCXCursorsPool();
Craig Topper69186e72014-06-08 08:38:04 +000081 D->CommentToXML = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +000082 return D;
83}
84
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +000085bool cxtu::isASTReadError(ASTUnit *AU) {
86 for (ASTUnit::stored_diag_iterator D = AU->stored_diag_begin(),
87 DEnd = AU->stored_diag_end();
88 D != DEnd; ++D) {
89 if (D->getLevel() >= DiagnosticsEngine::Error &&
90 DiagnosticIDs::getCategoryNumberForDiag(D->getID()) ==
91 diag::DiagCat_AST_Deserialization_Issue)
92 return true;
93 }
94 return false;
95}
96
Guy Benyei11169dd2012-12-18 14:30:41 +000097cxtu::CXTUOwner::~CXTUOwner() {
98 if (TU)
99 clang_disposeTranslationUnit(TU);
100}
101
102/// \brief Compare two source ranges to determine their relative position in
103/// the translation unit.
104static RangeComparisonResult RangeCompare(SourceManager &SM,
105 SourceRange R1,
106 SourceRange R2) {
107 assert(R1.isValid() && "First range is invalid?");
108 assert(R2.isValid() && "Second range is invalid?");
109 if (R1.getEnd() != R2.getBegin() &&
110 SM.isBeforeInTranslationUnit(R1.getEnd(), R2.getBegin()))
111 return RangeBefore;
112 if (R2.getEnd() != R1.getBegin() &&
113 SM.isBeforeInTranslationUnit(R2.getEnd(), R1.getBegin()))
114 return RangeAfter;
115 return RangeOverlap;
116}
117
118/// \brief Determine if a source location falls within, before, or after a
119/// a given source range.
120static RangeComparisonResult LocationCompare(SourceManager &SM,
121 SourceLocation L, SourceRange R) {
122 assert(R.isValid() && "First range is invalid?");
123 assert(L.isValid() && "Second range is invalid?");
124 if (L == R.getBegin() || L == R.getEnd())
125 return RangeOverlap;
126 if (SM.isBeforeInTranslationUnit(L, R.getBegin()))
127 return RangeBefore;
128 if (SM.isBeforeInTranslationUnit(R.getEnd(), L))
129 return RangeAfter;
130 return RangeOverlap;
131}
132
133/// \brief Translate a Clang source range into a CIndex source range.
134///
135/// Clang internally represents ranges where the end location points to the
136/// start of the token at the end. However, for external clients it is more
137/// useful to have a CXSourceRange be a proper half-open interval. This routine
138/// does the appropriate translation.
139CXSourceRange cxloc::translateSourceRange(const SourceManager &SM,
140 const LangOptions &LangOpts,
141 const CharSourceRange &R) {
142 // We want the last character in this location, so we will adjust the
143 // location accordingly.
144 SourceLocation EndLoc = R.getEnd();
145 if (EndLoc.isValid() && EndLoc.isMacroID() && !SM.isMacroArgExpansion(EndLoc))
146 EndLoc = SM.getExpansionRange(EndLoc).second;
Yaron Keren8b563662015-10-03 10:46:20 +0000147 if (R.isTokenRange() && EndLoc.isValid()) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000148 unsigned Length = Lexer::MeasureTokenLength(SM.getSpellingLoc(EndLoc),
149 SM, LangOpts);
150 EndLoc = EndLoc.getLocWithOffset(Length);
151 }
152
Bill Wendlingeade3622013-01-23 08:25:41 +0000153 CXSourceRange Result = {
Dmitri Gribenkof9304482013-01-23 15:56:07 +0000154 { &SM, &LangOpts },
Bill Wendlingeade3622013-01-23 08:25:41 +0000155 R.getBegin().getRawEncoding(),
156 EndLoc.getRawEncoding()
157 };
Guy Benyei11169dd2012-12-18 14:30:41 +0000158 return Result;
159}
160
161//===----------------------------------------------------------------------===//
162// Cursor visitor.
163//===----------------------------------------------------------------------===//
164
165static SourceRange getRawCursorExtent(CXCursor C);
166static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr);
167
168
169RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
170 return RangeCompare(AU->getSourceManager(), R, RegionOfInterest);
171}
172
173/// \brief Visit the given cursor and, if requested by the visitor,
174/// its children.
175///
176/// \param Cursor the cursor to visit.
177///
178/// \param CheckedRegionOfInterest if true, then the caller already checked
179/// that this cursor is within the region of interest.
180///
181/// \returns true if the visitation should be aborted, false if it
182/// should continue.
183bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
184 if (clang_isInvalid(Cursor.kind))
185 return false;
186
187 if (clang_isDeclaration(Cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +0000188 const Decl *D = getCursorDecl(Cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +0000189 if (!D) {
190 assert(0 && "Invalid declaration cursor");
191 return true; // abort.
192 }
193
194 // Ignore implicit declarations, unless it's an objc method because
195 // currently we should report implicit methods for properties when indexing.
196 if (D->isImplicit() && !isa<ObjCMethodDecl>(D))
197 return false;
198 }
199
200 // If we have a range of interest, and this cursor doesn't intersect with it,
201 // we're done.
202 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
203 SourceRange Range = getRawCursorExtent(Cursor);
204 if (Range.isInvalid() || CompareRegionOfInterest(Range))
205 return false;
206 }
207
208 switch (Visitor(Cursor, Parent, ClientData)) {
209 case CXChildVisit_Break:
210 return true;
211
212 case CXChildVisit_Continue:
213 return false;
214
215 case CXChildVisit_Recurse: {
216 bool ret = VisitChildren(Cursor);
217 if (PostChildrenVisitor)
218 if (PostChildrenVisitor(Cursor, ClientData))
219 return true;
220 return ret;
221 }
222 }
223
224 llvm_unreachable("Invalid CXChildVisitResult!");
225}
226
227static bool visitPreprocessedEntitiesInRange(SourceRange R,
228 PreprocessingRecord &PPRec,
229 CursorVisitor &Visitor) {
230 SourceManager &SM = Visitor.getASTUnit()->getSourceManager();
231 FileID FID;
232
233 if (!Visitor.shouldVisitIncludedEntities()) {
234 // If the begin/end of the range lie in the same FileID, do the optimization
235 // where we skip preprocessed entities that do not come from the same FileID.
236 FID = SM.getFileID(SM.getFileLoc(R.getBegin()));
237 if (FID != SM.getFileID(SM.getFileLoc(R.getEnd())))
238 FID = FileID();
239 }
240
Benjamin Kramerb4ef6682015-02-06 17:25:10 +0000241 const auto &Entities = PPRec.getPreprocessedEntitiesInRange(R);
242 return Visitor.visitPreprocessedEntities(Entities.begin(), Entities.end(),
Guy Benyei11169dd2012-12-18 14:30:41 +0000243 PPRec, FID);
244}
245
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000246bool CursorVisitor::visitFileRegion() {
Guy Benyei11169dd2012-12-18 14:30:41 +0000247 if (RegionOfInterest.isInvalid())
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000248 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000249
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +0000250 ASTUnit *Unit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +0000251 SourceManager &SM = Unit->getSourceManager();
252
253 std::pair<FileID, unsigned>
254 Begin = SM.getDecomposedLoc(SM.getFileLoc(RegionOfInterest.getBegin())),
255 End = SM.getDecomposedLoc(SM.getFileLoc(RegionOfInterest.getEnd()));
256
257 if (End.first != Begin.first) {
258 // If the end does not reside in the same file, try to recover by
259 // picking the end of the file of begin location.
260 End.first = Begin.first;
261 End.second = SM.getFileIDSize(Begin.first);
262 }
263
264 assert(Begin.first == End.first);
265 if (Begin.second > End.second)
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000266 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000267
268 FileID File = Begin.first;
269 unsigned Offset = Begin.second;
270 unsigned Length = End.second - Begin.second;
271
272 if (!VisitDeclsOnly && !VisitPreprocessorLast)
273 if (visitPreprocessedEntitiesInRegion())
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000274 return true; // visitation break.
Guy Benyei11169dd2012-12-18 14:30:41 +0000275
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000276 if (visitDeclsFromFileRegion(File, Offset, Length))
277 return true; // visitation break.
Guy Benyei11169dd2012-12-18 14:30:41 +0000278
279 if (!VisitDeclsOnly && VisitPreprocessorLast)
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000280 return visitPreprocessedEntitiesInRegion();
281
282 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000283}
284
285static bool isInLexicalContext(Decl *D, DeclContext *DC) {
286 if (!DC)
287 return false;
288
289 for (DeclContext *DeclDC = D->getLexicalDeclContext();
290 DeclDC; DeclDC = DeclDC->getLexicalParent()) {
291 if (DeclDC == DC)
292 return true;
293 }
294 return false;
295}
296
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000297bool CursorVisitor::visitDeclsFromFileRegion(FileID File,
Guy Benyei11169dd2012-12-18 14:30:41 +0000298 unsigned Offset, unsigned Length) {
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +0000299 ASTUnit *Unit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +0000300 SourceManager &SM = Unit->getSourceManager();
301 SourceRange Range = RegionOfInterest;
302
303 SmallVector<Decl *, 16> Decls;
304 Unit->findFileRegionDecls(File, Offset, Length, Decls);
305
306 // If we didn't find any file level decls for the file, try looking at the
307 // file that it was included from.
308 while (Decls.empty() || Decls.front()->isTopLevelDeclInObjCContainer()) {
309 bool Invalid = false;
310 const SrcMgr::SLocEntry &SLEntry = SM.getSLocEntry(File, &Invalid);
311 if (Invalid)
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000312 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000313
314 SourceLocation Outer;
315 if (SLEntry.isFile())
316 Outer = SLEntry.getFile().getIncludeLoc();
317 else
318 Outer = SLEntry.getExpansion().getExpansionLocStart();
319 if (Outer.isInvalid())
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000320 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000321
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000322 std::tie(File, Offset) = SM.getDecomposedExpansionLoc(Outer);
Guy Benyei11169dd2012-12-18 14:30:41 +0000323 Length = 0;
324 Unit->findFileRegionDecls(File, Offset, Length, Decls);
325 }
326
327 assert(!Decls.empty());
328
329 bool VisitedAtLeastOnce = false;
Craig Topper69186e72014-06-08 08:38:04 +0000330 DeclContext *CurDC = nullptr;
Craig Topper2341c0d2013-07-04 03:08:24 +0000331 SmallVectorImpl<Decl *>::iterator DIt = Decls.begin();
332 for (SmallVectorImpl<Decl *>::iterator DE = Decls.end(); DIt != DE; ++DIt) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000333 Decl *D = *DIt;
334 if (D->getSourceRange().isInvalid())
335 continue;
336
337 if (isInLexicalContext(D, CurDC))
338 continue;
339
340 CurDC = dyn_cast<DeclContext>(D);
341
342 if (TagDecl *TD = dyn_cast<TagDecl>(D))
343 if (!TD->isFreeStanding())
344 continue;
345
346 RangeComparisonResult CompRes = RangeCompare(SM, D->getSourceRange(),Range);
347 if (CompRes == RangeBefore)
348 continue;
349 if (CompRes == RangeAfter)
350 break;
351
352 assert(CompRes == RangeOverlap);
353 VisitedAtLeastOnce = true;
354
355 if (isa<ObjCContainerDecl>(D)) {
356 FileDI_current = &DIt;
357 FileDE_current = DE;
358 } else {
Craig Topper69186e72014-06-08 08:38:04 +0000359 FileDI_current = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +0000360 }
361
362 if (Visit(MakeCXCursor(D, TU, Range), /*CheckedRegionOfInterest=*/true))
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000363 return true; // visitation break.
Guy Benyei11169dd2012-12-18 14:30:41 +0000364 }
365
366 if (VisitedAtLeastOnce)
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000367 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000368
369 // No Decls overlapped with the range. Move up the lexical context until there
370 // is a context that contains the range or we reach the translation unit
371 // level.
372 DeclContext *DC = DIt == Decls.begin() ? (*DIt)->getLexicalDeclContext()
373 : (*(DIt-1))->getLexicalDeclContext();
374
375 while (DC && !DC->isTranslationUnit()) {
376 Decl *D = cast<Decl>(DC);
377 SourceRange CurDeclRange = D->getSourceRange();
378 if (CurDeclRange.isInvalid())
379 break;
380
381 if (RangeCompare(SM, CurDeclRange, Range) == RangeOverlap) {
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000382 if (Visit(MakeCXCursor(D, TU, Range), /*CheckedRegionOfInterest=*/true))
383 return true; // visitation break.
Guy Benyei11169dd2012-12-18 14:30:41 +0000384 }
385
386 DC = D->getLexicalDeclContext();
387 }
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000388
389 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000390}
391
392bool CursorVisitor::visitPreprocessedEntitiesInRegion() {
393 if (!AU->getPreprocessor().getPreprocessingRecord())
394 return false;
395
396 PreprocessingRecord &PPRec
397 = *AU->getPreprocessor().getPreprocessingRecord();
398 SourceManager &SM = AU->getSourceManager();
399
400 if (RegionOfInterest.isValid()) {
401 SourceRange MappedRange = AU->mapRangeToPreamble(RegionOfInterest);
402 SourceLocation B = MappedRange.getBegin();
403 SourceLocation E = MappedRange.getEnd();
404
405 if (AU->isInPreambleFileID(B)) {
406 if (SM.isLoadedSourceLocation(E))
407 return visitPreprocessedEntitiesInRange(SourceRange(B, E),
408 PPRec, *this);
409
410 // Beginning of range lies in the preamble but it also extends beyond
411 // it into the main file. Split the range into 2 parts, one covering
412 // the preamble and another covering the main file. This allows subsequent
413 // calls to visitPreprocessedEntitiesInRange to accept a source range that
414 // lies in the same FileID, allowing it to skip preprocessed entities that
415 // do not come from the same FileID.
416 bool breaked =
417 visitPreprocessedEntitiesInRange(
418 SourceRange(B, AU->getEndOfPreambleFileID()),
419 PPRec, *this);
420 if (breaked) return true;
421 return visitPreprocessedEntitiesInRange(
422 SourceRange(AU->getStartOfMainFileID(), E),
423 PPRec, *this);
424 }
425
426 return visitPreprocessedEntitiesInRange(SourceRange(B, E), PPRec, *this);
427 }
428
429 bool OnlyLocalDecls
430 = !AU->isMainFileAST() && AU->getOnlyLocalDecls();
431
432 if (OnlyLocalDecls)
433 return visitPreprocessedEntities(PPRec.local_begin(), PPRec.local_end(),
434 PPRec);
435
436 return visitPreprocessedEntities(PPRec.begin(), PPRec.end(), PPRec);
437}
438
439template<typename InputIterator>
440bool CursorVisitor::visitPreprocessedEntities(InputIterator First,
441 InputIterator Last,
442 PreprocessingRecord &PPRec,
443 FileID FID) {
444 for (; First != Last; ++First) {
445 if (!FID.isInvalid() && !PPRec.isEntityInFileID(First, FID))
446 continue;
447
448 PreprocessedEntity *PPE = *First;
Argyrios Kyrtzidis1030f262013-05-07 20:37:17 +0000449 if (!PPE)
450 continue;
451
Guy Benyei11169dd2012-12-18 14:30:41 +0000452 if (MacroExpansion *ME = dyn_cast<MacroExpansion>(PPE)) {
453 if (Visit(MakeMacroExpansionCursor(ME, TU)))
454 return true;
Richard Smith66a81862015-05-04 02:25:31 +0000455
Guy Benyei11169dd2012-12-18 14:30:41 +0000456 continue;
457 }
Richard Smith66a81862015-05-04 02:25:31 +0000458
459 if (MacroDefinitionRecord *MD = dyn_cast<MacroDefinitionRecord>(PPE)) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000460 if (Visit(MakeMacroDefinitionCursor(MD, TU)))
461 return true;
Richard Smith66a81862015-05-04 02:25:31 +0000462
Guy Benyei11169dd2012-12-18 14:30:41 +0000463 continue;
464 }
465
466 if (InclusionDirective *ID = dyn_cast<InclusionDirective>(PPE)) {
467 if (Visit(MakeInclusionDirectiveCursor(ID, TU)))
468 return true;
469
470 continue;
471 }
472 }
473
474 return false;
475}
476
477/// \brief Visit the children of the given cursor.
478///
479/// \returns true if the visitation should be aborted, false if it
480/// should continue.
481bool CursorVisitor::VisitChildren(CXCursor Cursor) {
482 if (clang_isReference(Cursor.kind) &&
483 Cursor.kind != CXCursor_CXXBaseSpecifier) {
484 // By definition, references have no children.
485 return false;
486 }
487
488 // Set the Parent field to Cursor, then back to its old value once we're
489 // done.
490 SetParentRAII SetParent(Parent, StmtParent, Cursor);
491
492 if (clang_isDeclaration(Cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +0000493 Decl *D = const_cast<Decl *>(getCursorDecl(Cursor));
Guy Benyei11169dd2012-12-18 14:30:41 +0000494 if (!D)
495 return false;
496
497 return VisitAttributes(D) || Visit(D);
498 }
499
500 if (clang_isStatement(Cursor.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +0000501 if (const Stmt *S = getCursorStmt(Cursor))
Guy Benyei11169dd2012-12-18 14:30:41 +0000502 return Visit(S);
503
504 return false;
505 }
506
507 if (clang_isExpression(Cursor.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +0000508 if (const Expr *E = getCursorExpr(Cursor))
Guy Benyei11169dd2012-12-18 14:30:41 +0000509 return Visit(E);
510
511 return false;
512 }
513
514 if (clang_isTranslationUnit(Cursor.kind)) {
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +0000515 CXTranslationUnit TU = getCursorTU(Cursor);
516 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +0000517
518 int VisitOrder[2] = { VisitPreprocessorLast, !VisitPreprocessorLast };
519 for (unsigned I = 0; I != 2; ++I) {
520 if (VisitOrder[I]) {
521 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
522 RegionOfInterest.isInvalid()) {
523 for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
524 TLEnd = CXXUnit->top_level_end();
525 TL != TLEnd; ++TL) {
Argyrios Kyrtzidise7c91042016-07-01 19:10:54 +0000526 const Optional<bool> V = handleDeclForVisitation(*TL);
527 if (!V.hasValue())
528 continue;
529 return V.getValue();
Guy Benyei11169dd2012-12-18 14:30:41 +0000530 }
531 } else if (VisitDeclContext(
532 CXXUnit->getASTContext().getTranslationUnitDecl()))
533 return true;
534 continue;
535 }
536
537 // Walk the preprocessing record.
538 if (CXXUnit->getPreprocessor().getPreprocessingRecord())
539 visitPreprocessedEntitiesInRegion();
540 }
541
542 return false;
543 }
544
545 if (Cursor.kind == CXCursor_CXXBaseSpecifier) {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +0000546 if (const CXXBaseSpecifier *Base = getCursorCXXBaseSpecifier(Cursor)) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000547 if (TypeSourceInfo *BaseTSInfo = Base->getTypeSourceInfo()) {
548 return Visit(BaseTSInfo->getTypeLoc());
549 }
550 }
551 }
552
553 if (Cursor.kind == CXCursor_IBOutletCollectionAttr) {
Dmitri Gribenkoe4baea62013-01-26 18:08:08 +0000554 const IBOutletCollectionAttr *A =
Guy Benyei11169dd2012-12-18 14:30:41 +0000555 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(Cursor));
Richard Smithb1f9a282013-10-31 01:56:18 +0000556 if (const ObjCObjectType *ObjT = A->getInterface()->getAs<ObjCObjectType>())
Richard Smithb87c4652013-10-31 21:23:20 +0000557 return Visit(cxcursor::MakeCursorObjCClassRef(
558 ObjT->getInterface(),
559 A->getInterfaceLoc()->getTypeLoc().getLocStart(), TU));
Guy Benyei11169dd2012-12-18 14:30:41 +0000560 }
561
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +0000562 // If pointing inside a macro definition, check if the token is an identifier
563 // that was ever defined as a macro. In such a case, create a "pseudo" macro
564 // expansion cursor for that token.
565 SourceLocation BeginLoc = RegionOfInterest.getBegin();
566 if (Cursor.kind == CXCursor_MacroDefinition &&
567 BeginLoc == RegionOfInterest.getEnd()) {
568 SourceLocation Loc = AU->mapLocationToPreamble(BeginLoc);
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +0000569 const MacroInfo *MI =
570 getMacroInfo(cxcursor::getCursorMacroDefinition(Cursor), TU);
Richard Smith66a81862015-05-04 02:25:31 +0000571 if (MacroDefinitionRecord *MacroDef =
572 checkForMacroInMacroDefinition(MI, Loc, TU))
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +0000573 return Visit(cxcursor::MakeMacroExpansionCursor(MacroDef, BeginLoc, TU));
574 }
575
Guy Benyei11169dd2012-12-18 14:30:41 +0000576 // Nothing to visit at the moment.
577 return false;
578}
579
580bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
581 if (TypeSourceInfo *TSInfo = B->getSignatureAsWritten())
582 if (Visit(TSInfo->getTypeLoc()))
583 return true;
584
585 if (Stmt *Body = B->getBody())
586 return Visit(MakeCXCursor(Body, StmtParent, TU, RegionOfInterest));
587
588 return false;
589}
590
Ted Kremenek03325582013-02-21 01:29:01 +0000591Optional<bool> CursorVisitor::shouldVisitCursor(CXCursor Cursor) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000592 if (RegionOfInterest.isValid()) {
593 SourceRange Range = getFullCursorExtent(Cursor, AU->getSourceManager());
594 if (Range.isInvalid())
David Blaikie7a30dc52013-02-21 01:47:18 +0000595 return None;
Guy Benyei11169dd2012-12-18 14:30:41 +0000596
597 switch (CompareRegionOfInterest(Range)) {
598 case RangeBefore:
599 // This declaration comes before the region of interest; skip it.
David Blaikie7a30dc52013-02-21 01:47:18 +0000600 return None;
Guy Benyei11169dd2012-12-18 14:30:41 +0000601
602 case RangeAfter:
603 // This declaration comes after the region of interest; we're done.
604 return false;
605
606 case RangeOverlap:
607 // This declaration overlaps the region of interest; visit it.
608 break;
609 }
610 }
611 return true;
612}
613
614bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
615 DeclContext::decl_iterator I = DC->decls_begin(), E = DC->decls_end();
616
617 // FIXME: Eventually remove. This part of a hack to support proper
618 // iteration over all Decls contained lexically within an ObjC container.
619 SaveAndRestore<DeclContext::decl_iterator*> DI_saved(DI_current, &I);
620 SaveAndRestore<DeclContext::decl_iterator> DE_saved(DE_current, E);
621
622 for ( ; I != E; ++I) {
623 Decl *D = *I;
624 if (D->getLexicalDeclContext() != DC)
625 continue;
Argyrios Kyrtzidise7c91042016-07-01 19:10:54 +0000626 const Optional<bool> V = handleDeclForVisitation(D);
Guy Benyei11169dd2012-12-18 14:30:41 +0000627 if (!V.hasValue())
628 continue;
Argyrios Kyrtzidise7c91042016-07-01 19:10:54 +0000629 return V.getValue();
Guy Benyei11169dd2012-12-18 14:30:41 +0000630 }
631 return false;
632}
633
Argyrios Kyrtzidise7c91042016-07-01 19:10:54 +0000634Optional<bool> CursorVisitor::handleDeclForVisitation(const Decl *D) {
635 CXCursor Cursor = MakeCXCursor(D, TU, RegionOfInterest);
636
637 // Ignore synthesized ivars here, otherwise if we have something like:
638 // @synthesize prop = _prop;
639 // and '_prop' is not declared, we will encounter a '_prop' ivar before
640 // encountering the 'prop' synthesize declaration and we will think that
641 // we passed the region-of-interest.
642 if (auto *ivarD = dyn_cast<ObjCIvarDecl>(D)) {
643 if (ivarD->getSynthesize())
644 return None;
645 }
646
647 // FIXME: ObjCClassRef/ObjCProtocolRef for forward class/protocol
648 // declarations is a mismatch with the compiler semantics.
649 if (Cursor.kind == CXCursor_ObjCInterfaceDecl) {
650 auto *ID = cast<ObjCInterfaceDecl>(D);
651 if (!ID->isThisDeclarationADefinition())
652 Cursor = MakeCursorObjCClassRef(ID, ID->getLocation(), TU);
653
654 } else if (Cursor.kind == CXCursor_ObjCProtocolDecl) {
655 auto *PD = cast<ObjCProtocolDecl>(D);
656 if (!PD->isThisDeclarationADefinition())
657 Cursor = MakeCursorObjCProtocolRef(PD, PD->getLocation(), TU);
658 }
659
660 const Optional<bool> V = shouldVisitCursor(Cursor);
661 if (!V.hasValue())
662 return None;
663 if (!V.getValue())
664 return false;
665 if (Visit(Cursor, true))
666 return true;
667 return None;
668}
669
Guy Benyei11169dd2012-12-18 14:30:41 +0000670bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
671 llvm_unreachable("Translation units are visited directly by Visit()");
672}
673
Sergey Kalinichev8f3b1872015-11-15 13:48:32 +0000674bool CursorVisitor::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
675 if (VisitTemplateParameters(D->getTemplateParameters()))
676 return true;
677
678 return Visit(MakeCXCursor(D->getTemplatedDecl(), TU, RegionOfInterest));
679}
680
Guy Benyei11169dd2012-12-18 14:30:41 +0000681bool CursorVisitor::VisitTypeAliasDecl(TypeAliasDecl *D) {
682 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
683 return Visit(TSInfo->getTypeLoc());
684
685 return false;
686}
687
688bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
689 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
690 return Visit(TSInfo->getTypeLoc());
691
692 return false;
693}
694
695bool CursorVisitor::VisitTagDecl(TagDecl *D) {
696 return VisitDeclContext(D);
697}
698
699bool CursorVisitor::VisitClassTemplateSpecializationDecl(
700 ClassTemplateSpecializationDecl *D) {
701 bool ShouldVisitBody = false;
702 switch (D->getSpecializationKind()) {
703 case TSK_Undeclared:
704 case TSK_ImplicitInstantiation:
705 // Nothing to visit
706 return false;
707
708 case TSK_ExplicitInstantiationDeclaration:
709 case TSK_ExplicitInstantiationDefinition:
710 break;
711
712 case TSK_ExplicitSpecialization:
713 ShouldVisitBody = true;
714 break;
715 }
716
717 // Visit the template arguments used in the specialization.
718 if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) {
719 TypeLoc TL = SpecType->getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +0000720 if (TemplateSpecializationTypeLoc TSTLoc =
721 TL.getAs<TemplateSpecializationTypeLoc>()) {
722 for (unsigned I = 0, N = TSTLoc.getNumArgs(); I != N; ++I)
723 if (VisitTemplateArgumentLoc(TSTLoc.getArgLoc(I)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000724 return true;
725 }
726 }
Alexander Kornienko1a9f1842015-12-28 15:24:08 +0000727
728 return ShouldVisitBody && VisitCXXRecordDecl(D);
Guy Benyei11169dd2012-12-18 14:30:41 +0000729}
730
731bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl(
732 ClassTemplatePartialSpecializationDecl *D) {
733 // FIXME: Visit the "outer" template parameter lists on the TagDecl
734 // before visiting these template parameters.
735 if (VisitTemplateParameters(D->getTemplateParameters()))
736 return true;
737
738 // Visit the partial specialization arguments.
Enea Zaffanella6dbe1872013-08-10 07:24:53 +0000739 const ASTTemplateArgumentListInfo *Info = D->getTemplateArgsAsWritten();
740 const TemplateArgumentLoc *TemplateArgs = Info->getTemplateArgs();
741 for (unsigned I = 0, N = Info->NumTemplateArgs; I != N; ++I)
Guy Benyei11169dd2012-12-18 14:30:41 +0000742 if (VisitTemplateArgumentLoc(TemplateArgs[I]))
743 return true;
744
745 return VisitCXXRecordDecl(D);
746}
747
748bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
749 // Visit the default argument.
750 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
751 if (TypeSourceInfo *DefArg = D->getDefaultArgumentInfo())
752 if (Visit(DefArg->getTypeLoc()))
753 return true;
754
755 return false;
756}
757
758bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
759 if (Expr *Init = D->getInitExpr())
760 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
761 return false;
762}
763
764bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
Argyrios Kyrtzidis2ec76742013-04-05 21:04:10 +0000765 unsigned NumParamList = DD->getNumTemplateParameterLists();
766 for (unsigned i = 0; i < NumParamList; i++) {
767 TemplateParameterList* Params = DD->getTemplateParameterList(i);
768 if (VisitTemplateParameters(Params))
769 return true;
770 }
771
Guy Benyei11169dd2012-12-18 14:30:41 +0000772 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
773 if (Visit(TSInfo->getTypeLoc()))
774 return true;
775
776 // Visit the nested-name-specifier, if present.
777 if (NestedNameSpecifierLoc QualifierLoc = DD->getQualifierLoc())
778 if (VisitNestedNameSpecifierLoc(QualifierLoc))
779 return true;
780
781 return false;
782}
783
Benjamin Kramer4cadf292014-03-07 21:51:58 +0000784/// \brief Compare two base or member initializers based on their source order.
785static int CompareCXXCtorInitializers(CXXCtorInitializer *const *X,
786 CXXCtorInitializer *const *Y) {
787 return (*X)->getSourceOrder() - (*Y)->getSourceOrder();
788}
789
Guy Benyei11169dd2012-12-18 14:30:41 +0000790bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Argyrios Kyrtzidis2ec76742013-04-05 21:04:10 +0000791 unsigned NumParamList = ND->getNumTemplateParameterLists();
792 for (unsigned i = 0; i < NumParamList; i++) {
793 TemplateParameterList* Params = ND->getTemplateParameterList(i);
794 if (VisitTemplateParameters(Params))
795 return true;
796 }
797
Guy Benyei11169dd2012-12-18 14:30:41 +0000798 if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
799 // Visit the function declaration's syntactic components in the order
800 // written. This requires a bit of work.
801 TypeLoc TL = TSInfo->getTypeLoc().IgnoreParens();
David Blaikie6adc78e2013-02-18 22:06:02 +0000802 FunctionTypeLoc FTL = TL.getAs<FunctionTypeLoc>();
Guy Benyei11169dd2012-12-18 14:30:41 +0000803
804 // If we have a function declared directly (without the use of a typedef),
805 // visit just the return type. Otherwise, just visit the function's type
806 // now.
Alp Toker42a16a62014-01-25 23:51:36 +0000807 if ((FTL && !isa<CXXConversionDecl>(ND) && Visit(FTL.getReturnLoc())) ||
Guy Benyei11169dd2012-12-18 14:30:41 +0000808 (!FTL && Visit(TL)))
809 return true;
810
811 // Visit the nested-name-specifier, if present.
812 if (NestedNameSpecifierLoc QualifierLoc = ND->getQualifierLoc())
813 if (VisitNestedNameSpecifierLoc(QualifierLoc))
814 return true;
815
816 // Visit the declaration name.
Argyrios Kyrtzidis4a4d2b42014-02-09 08:13:47 +0000817 if (!isa<CXXDestructorDecl>(ND))
818 if (VisitDeclarationNameInfo(ND->getNameInfo()))
819 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +0000820
821 // FIXME: Visit explicitly-specified template arguments!
822
823 // Visit the function parameters, if we have a function type.
David Blaikie6adc78e2013-02-18 22:06:02 +0000824 if (FTL && VisitFunctionTypeLoc(FTL, true))
Guy Benyei11169dd2012-12-18 14:30:41 +0000825 return true;
826
Bill Wendling44426052012-12-20 19:22:21 +0000827 // FIXME: Attributes?
Guy Benyei11169dd2012-12-18 14:30:41 +0000828 }
829
830 if (ND->doesThisDeclarationHaveABody() && !ND->isLateTemplateParsed()) {
831 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ND)) {
832 // Find the initializers that were written in the source.
833 SmallVector<CXXCtorInitializer *, 4> WrittenInits;
Aaron Ballman0ad78302014-03-13 17:34:31 +0000834 for (auto *I : Constructor->inits()) {
835 if (!I->isWritten())
Guy Benyei11169dd2012-12-18 14:30:41 +0000836 continue;
837
Aaron Ballman0ad78302014-03-13 17:34:31 +0000838 WrittenInits.push_back(I);
Guy Benyei11169dd2012-12-18 14:30:41 +0000839 }
840
841 // Sort the initializers in source order
Benjamin Kramer4cadf292014-03-07 21:51:58 +0000842 llvm::array_pod_sort(WrittenInits.begin(), WrittenInits.end(),
843 &CompareCXXCtorInitializers);
844
Guy Benyei11169dd2012-12-18 14:30:41 +0000845 // Visit the initializers in source order
846 for (unsigned I = 0, N = WrittenInits.size(); I != N; ++I) {
847 CXXCtorInitializer *Init = WrittenInits[I];
848 if (Init->isAnyMemberInitializer()) {
849 if (Visit(MakeCursorMemberRef(Init->getAnyMember(),
850 Init->getMemberLocation(), TU)))
851 return true;
852 } else if (TypeSourceInfo *TInfo = Init->getTypeSourceInfo()) {
853 if (Visit(TInfo->getTypeLoc()))
854 return true;
855 }
856
857 // Visit the initializer value.
858 if (Expr *Initializer = Init->getInit())
859 if (Visit(MakeCXCursor(Initializer, ND, TU, RegionOfInterest)))
860 return true;
861 }
862 }
863
864 if (Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest)))
865 return true;
866 }
867
868 return false;
869}
870
871bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
872 if (VisitDeclaratorDecl(D))
873 return true;
874
875 if (Expr *BitWidth = D->getBitWidth())
876 return Visit(MakeCXCursor(BitWidth, StmtParent, TU, RegionOfInterest));
877
878 return false;
879}
880
881bool CursorVisitor::VisitVarDecl(VarDecl *D) {
882 if (VisitDeclaratorDecl(D))
883 return true;
884
885 if (Expr *Init = D->getInit())
886 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
887
888 return false;
889}
890
891bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
892 if (VisitDeclaratorDecl(D))
893 return true;
894
895 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
896 if (Expr *DefArg = D->getDefaultArgument())
897 return Visit(MakeCXCursor(DefArg, StmtParent, TU, RegionOfInterest));
898
899 return false;
900}
901
902bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
903 // FIXME: Visit the "outer" template parameter lists on the FunctionDecl
904 // before visiting these template parameters.
905 if (VisitTemplateParameters(D->getTemplateParameters()))
906 return true;
907
908 return VisitFunctionDecl(D->getTemplatedDecl());
909}
910
911bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) {
912 // FIXME: Visit the "outer" template parameter lists on the TagDecl
913 // before visiting these template parameters.
914 if (VisitTemplateParameters(D->getTemplateParameters()))
915 return true;
916
917 return VisitCXXRecordDecl(D->getTemplatedDecl());
918}
919
920bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
921 if (VisitTemplateParameters(D->getTemplateParameters()))
922 return true;
923
924 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() &&
925 VisitTemplateArgumentLoc(D->getDefaultArgument()))
926 return true;
927
928 return false;
929}
930
Douglas Gregor9bda6cf2015-07-07 03:58:14 +0000931bool CursorVisitor::VisitObjCTypeParamDecl(ObjCTypeParamDecl *D) {
932 // Visit the bound, if it's explicit.
933 if (D->hasExplicitBound()) {
934 if (auto TInfo = D->getTypeSourceInfo()) {
935 if (Visit(TInfo->getTypeLoc()))
936 return true;
937 }
938 }
939
940 return false;
941}
942
Guy Benyei11169dd2012-12-18 14:30:41 +0000943bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Alp Toker314cc812014-01-25 16:55:45 +0000944 if (TypeSourceInfo *TSInfo = ND->getReturnTypeSourceInfo())
Guy Benyei11169dd2012-12-18 14:30:41 +0000945 if (Visit(TSInfo->getTypeLoc()))
946 return true;
947
David Majnemer59f77922016-06-24 04:05:48 +0000948 for (const auto *P : ND->parameters()) {
Aaron Ballman43b68be2014-03-07 17:50:17 +0000949 if (Visit(MakeCXCursor(P, TU, RegionOfInterest)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000950 return true;
951 }
952
Alexander Kornienko1a9f1842015-12-28 15:24:08 +0000953 return ND->isThisDeclarationADefinition() &&
954 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest));
Guy Benyei11169dd2012-12-18 14:30:41 +0000955}
956
957template <typename DeclIt>
958static void addRangedDeclsInContainer(DeclIt *DI_current, DeclIt DE_current,
959 SourceManager &SM, SourceLocation EndLoc,
960 SmallVectorImpl<Decl *> &Decls) {
961 DeclIt next = *DI_current;
962 while (++next != DE_current) {
963 Decl *D_next = *next;
964 if (!D_next)
965 break;
966 SourceLocation L = D_next->getLocStart();
967 if (!L.isValid())
968 break;
969 if (SM.isBeforeInTranslationUnit(L, EndLoc)) {
970 *DI_current = next;
971 Decls.push_back(D_next);
972 continue;
973 }
974 break;
975 }
976}
977
Guy Benyei11169dd2012-12-18 14:30:41 +0000978bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
979 // FIXME: Eventually convert back to just 'VisitDeclContext()'. Essentially
980 // an @implementation can lexically contain Decls that are not properly
981 // nested in the AST. When we identify such cases, we need to retrofit
982 // this nesting here.
983 if (!DI_current && !FileDI_current)
984 return VisitDeclContext(D);
985
986 // Scan the Decls that immediately come after the container
987 // in the current DeclContext. If any fall within the
988 // container's lexical region, stash them into a vector
989 // for later processing.
990 SmallVector<Decl *, 24> DeclsInContainer;
991 SourceLocation EndLoc = D->getSourceRange().getEnd();
992 SourceManager &SM = AU->getSourceManager();
993 if (EndLoc.isValid()) {
994 if (DI_current) {
995 addRangedDeclsInContainer(DI_current, DE_current, SM, EndLoc,
996 DeclsInContainer);
997 } else {
998 addRangedDeclsInContainer(FileDI_current, FileDE_current, SM, EndLoc,
999 DeclsInContainer);
1000 }
1001 }
1002
1003 // The common case.
1004 if (DeclsInContainer.empty())
1005 return VisitDeclContext(D);
1006
1007 // Get all the Decls in the DeclContext, and sort them with the
1008 // additional ones we've collected. Then visit them.
Aaron Ballman629afae2014-03-07 19:56:05 +00001009 for (auto *SubDecl : D->decls()) {
1010 if (!SubDecl || SubDecl->getLexicalDeclContext() != D ||
1011 SubDecl->getLocStart().isInvalid())
Guy Benyei11169dd2012-12-18 14:30:41 +00001012 continue;
Aaron Ballman629afae2014-03-07 19:56:05 +00001013 DeclsInContainer.push_back(SubDecl);
Guy Benyei11169dd2012-12-18 14:30:41 +00001014 }
1015
1016 // Now sort the Decls so that they appear in lexical order.
1017 std::sort(DeclsInContainer.begin(), DeclsInContainer.end(),
Benjamin Kramerbbdd7642014-03-01 14:48:57 +00001018 [&SM](Decl *A, Decl *B) {
1019 SourceLocation L_A = A->getLocStart();
1020 SourceLocation L_B = B->getLocStart();
1021 assert(L_A.isValid() && L_B.isValid());
1022 return SM.isBeforeInTranslationUnit(L_A, L_B);
1023 });
Guy Benyei11169dd2012-12-18 14:30:41 +00001024
1025 // Now visit the decls.
1026 for (SmallVectorImpl<Decl*>::iterator I = DeclsInContainer.begin(),
1027 E = DeclsInContainer.end(); I != E; ++I) {
1028 CXCursor Cursor = MakeCXCursor(*I, TU, RegionOfInterest);
Ted Kremenek03325582013-02-21 01:29:01 +00001029 const Optional<bool> &V = shouldVisitCursor(Cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00001030 if (!V.hasValue())
1031 continue;
1032 if (!V.getValue())
1033 return false;
1034 if (Visit(Cursor, true))
1035 return true;
1036 }
1037 return false;
1038}
1039
1040bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
1041 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
1042 TU)))
1043 return true;
1044
Douglas Gregore9d95f12015-07-07 03:57:35 +00001045 if (VisitObjCTypeParamList(ND->getTypeParamList()))
1046 return true;
1047
Guy Benyei11169dd2012-12-18 14:30:41 +00001048 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
1049 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
1050 E = ND->protocol_end(); I != E; ++I, ++PL)
1051 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
1052 return true;
1053
1054 return VisitObjCContainerDecl(ND);
1055}
1056
1057bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
1058 if (!PID->isThisDeclarationADefinition())
1059 return Visit(MakeCursorObjCProtocolRef(PID, PID->getLocation(), TU));
1060
1061 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
1062 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
1063 E = PID->protocol_end(); I != E; ++I, ++PL)
1064 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
1065 return true;
1066
1067 return VisitObjCContainerDecl(PID);
1068}
1069
1070bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
1071 if (PD->getTypeSourceInfo() && Visit(PD->getTypeSourceInfo()->getTypeLoc()))
1072 return true;
1073
1074 // FIXME: This implements a workaround with @property declarations also being
1075 // installed in the DeclContext for the @interface. Eventually this code
1076 // should be removed.
1077 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
1078 if (!CDecl || !CDecl->IsClassExtension())
1079 return false;
1080
1081 ObjCInterfaceDecl *ID = CDecl->getClassInterface();
1082 if (!ID)
1083 return false;
1084
1085 IdentifierInfo *PropertyId = PD->getIdentifier();
1086 ObjCPropertyDecl *prevDecl =
Manman Ren5b786402016-01-28 18:49:28 +00001087 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId,
1088 PD->getQueryKind());
Guy Benyei11169dd2012-12-18 14:30:41 +00001089
1090 if (!prevDecl)
1091 return false;
1092
1093 // Visit synthesized methods since they will be skipped when visiting
1094 // the @interface.
1095 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
1096 if (MD->isPropertyAccessor() && MD->getLexicalDeclContext() == CDecl)
1097 if (Visit(MakeCXCursor(MD, TU, RegionOfInterest)))
1098 return true;
1099
1100 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
1101 if (MD->isPropertyAccessor() && MD->getLexicalDeclContext() == CDecl)
1102 if (Visit(MakeCXCursor(MD, TU, RegionOfInterest)))
1103 return true;
1104
1105 return false;
1106}
1107
Douglas Gregore9d95f12015-07-07 03:57:35 +00001108bool CursorVisitor::VisitObjCTypeParamList(ObjCTypeParamList *typeParamList) {
1109 if (!typeParamList)
1110 return false;
1111
1112 for (auto *typeParam : *typeParamList) {
1113 // Visit the type parameter.
1114 if (Visit(MakeCXCursor(typeParam, TU, RegionOfInterest)))
1115 return true;
Douglas Gregore9d95f12015-07-07 03:57:35 +00001116 }
1117
1118 return false;
1119}
1120
Guy Benyei11169dd2012-12-18 14:30:41 +00001121bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
1122 if (!D->isThisDeclarationADefinition()) {
1123 // Forward declaration is treated like a reference.
1124 return Visit(MakeCursorObjCClassRef(D, D->getLocation(), TU));
1125 }
1126
Douglas Gregore9d95f12015-07-07 03:57:35 +00001127 // Objective-C type parameters.
1128 if (VisitObjCTypeParamList(D->getTypeParamListAsWritten()))
1129 return true;
1130
Guy Benyei11169dd2012-12-18 14:30:41 +00001131 // Issue callbacks for super class.
1132 if (D->getSuperClass() &&
1133 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
1134 D->getSuperClassLoc(),
1135 TU)))
1136 return true;
1137
Douglas Gregore9d95f12015-07-07 03:57:35 +00001138 if (TypeSourceInfo *SuperClassTInfo = D->getSuperClassTInfo())
1139 if (Visit(SuperClassTInfo->getTypeLoc()))
1140 return true;
1141
Guy Benyei11169dd2012-12-18 14:30:41 +00001142 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1143 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
1144 E = D->protocol_end(); I != E; ++I, ++PL)
1145 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
1146 return true;
1147
1148 return VisitObjCContainerDecl(D);
1149}
1150
1151bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
1152 return VisitObjCContainerDecl(D);
1153}
1154
1155bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
1156 // 'ID' could be null when dealing with invalid code.
1157 if (ObjCInterfaceDecl *ID = D->getClassInterface())
1158 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
1159 return true;
1160
1161 return VisitObjCImplDecl(D);
1162}
1163
1164bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
1165#if 0
1166 // Issue callbacks for super class.
1167 // FIXME: No source location information!
1168 if (D->getSuperClass() &&
1169 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
1170 D->getSuperClassLoc(),
1171 TU)))
1172 return true;
1173#endif
1174
1175 return VisitObjCImplDecl(D);
1176}
1177
1178bool CursorVisitor::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *PD) {
1179 if (ObjCIvarDecl *Ivar = PD->getPropertyIvarDecl())
1180 if (PD->isIvarNameSpecified())
1181 return Visit(MakeCursorMemberRef(Ivar, PD->getPropertyIvarDeclLoc(), TU));
1182
1183 return false;
1184}
1185
1186bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
1187 return VisitDeclContext(D);
1188}
1189
1190bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
1191 // Visit nested-name-specifier.
1192 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1193 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1194 return true;
1195
1196 return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(),
1197 D->getTargetNameLoc(), TU));
1198}
1199
1200bool CursorVisitor::VisitUsingDecl(UsingDecl *D) {
1201 // Visit nested-name-specifier.
1202 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1203 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1204 return true;
1205 }
1206
1207 if (Visit(MakeCursorOverloadedDeclRef(D, D->getLocation(), TU)))
1208 return true;
1209
1210 return VisitDeclarationNameInfo(D->getNameInfo());
1211}
1212
1213bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
1214 // Visit nested-name-specifier.
1215 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1216 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1217 return true;
1218
1219 return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(),
1220 D->getIdentLocation(), TU));
1221}
1222
1223bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
1224 // Visit nested-name-specifier.
1225 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1226 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1227 return true;
1228 }
1229
1230 return VisitDeclarationNameInfo(D->getNameInfo());
1231}
1232
1233bool CursorVisitor::VisitUnresolvedUsingTypenameDecl(
1234 UnresolvedUsingTypenameDecl *D) {
1235 // Visit nested-name-specifier.
1236 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1237 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1238 return true;
1239
1240 return false;
1241}
1242
Olivier Goffart81978012016-06-09 16:15:55 +00001243bool CursorVisitor::VisitStaticAssertDecl(StaticAssertDecl *D) {
1244 if (Visit(MakeCXCursor(D->getAssertExpr(), StmtParent, TU, RegionOfInterest)))
1245 return true;
Richard Trieuf3b77662016-09-13 01:37:01 +00001246 if (StringLiteral *Message = D->getMessage())
1247 if (Visit(MakeCXCursor(Message, StmtParent, TU, RegionOfInterest)))
1248 return true;
Olivier Goffart81978012016-06-09 16:15:55 +00001249 return false;
1250}
1251
Guy Benyei11169dd2012-12-18 14:30:41 +00001252bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
1253 switch (Name.getName().getNameKind()) {
1254 case clang::DeclarationName::Identifier:
1255 case clang::DeclarationName::CXXLiteralOperatorName:
1256 case clang::DeclarationName::CXXOperatorName:
1257 case clang::DeclarationName::CXXUsingDirective:
1258 return false;
1259
1260 case clang::DeclarationName::CXXConstructorName:
1261 case clang::DeclarationName::CXXDestructorName:
1262 case clang::DeclarationName::CXXConversionFunctionName:
1263 if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
1264 return Visit(TSInfo->getTypeLoc());
1265 return false;
1266
1267 case clang::DeclarationName::ObjCZeroArgSelector:
1268 case clang::DeclarationName::ObjCOneArgSelector:
1269 case clang::DeclarationName::ObjCMultiArgSelector:
1270 // FIXME: Per-identifier location info?
1271 return false;
1272 }
1273
1274 llvm_unreachable("Invalid DeclarationName::Kind!");
1275}
1276
1277bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS,
1278 SourceRange Range) {
1279 // FIXME: This whole routine is a hack to work around the lack of proper
1280 // source information in nested-name-specifiers (PR5791). Since we do have
1281 // a beginning source location, we can visit the first component of the
1282 // nested-name-specifier, if it's a single-token component.
1283 if (!NNS)
1284 return false;
1285
1286 // Get the first component in the nested-name-specifier.
1287 while (NestedNameSpecifier *Prefix = NNS->getPrefix())
1288 NNS = Prefix;
1289
1290 switch (NNS->getKind()) {
1291 case NestedNameSpecifier::Namespace:
1292 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(),
1293 TU));
1294
1295 case NestedNameSpecifier::NamespaceAlias:
1296 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
1297 Range.getBegin(), TU));
1298
1299 case NestedNameSpecifier::TypeSpec: {
1300 // If the type has a form where we know that the beginning of the source
1301 // range matches up with a reference cursor. Visit the appropriate reference
1302 // cursor.
1303 const Type *T = NNS->getAsType();
1304 if (const TypedefType *Typedef = dyn_cast<TypedefType>(T))
1305 return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU));
1306 if (const TagType *Tag = dyn_cast<TagType>(T))
1307 return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU));
1308 if (const TemplateSpecializationType *TST
1309 = dyn_cast<TemplateSpecializationType>(T))
1310 return VisitTemplateName(TST->getTemplateName(), Range.getBegin());
1311 break;
1312 }
1313
1314 case NestedNameSpecifier::TypeSpecWithTemplate:
1315 case NestedNameSpecifier::Global:
1316 case NestedNameSpecifier::Identifier:
Nikola Smiljanic67860242014-09-26 00:28:20 +00001317 case NestedNameSpecifier::Super:
Guy Benyei11169dd2012-12-18 14:30:41 +00001318 break;
1319 }
1320
1321 return false;
1322}
1323
1324bool
1325CursorVisitor::VisitNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
1326 SmallVector<NestedNameSpecifierLoc, 4> Qualifiers;
1327 for (; Qualifier; Qualifier = Qualifier.getPrefix())
1328 Qualifiers.push_back(Qualifier);
1329
1330 while (!Qualifiers.empty()) {
1331 NestedNameSpecifierLoc Q = Qualifiers.pop_back_val();
1332 NestedNameSpecifier *NNS = Q.getNestedNameSpecifier();
1333 switch (NNS->getKind()) {
1334 case NestedNameSpecifier::Namespace:
1335 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(),
1336 Q.getLocalBeginLoc(),
1337 TU)))
1338 return true;
1339
1340 break;
1341
1342 case NestedNameSpecifier::NamespaceAlias:
1343 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
1344 Q.getLocalBeginLoc(),
1345 TU)))
1346 return true;
1347
1348 break;
1349
1350 case NestedNameSpecifier::TypeSpec:
1351 case NestedNameSpecifier::TypeSpecWithTemplate:
1352 if (Visit(Q.getTypeLoc()))
1353 return true;
1354
1355 break;
1356
1357 case NestedNameSpecifier::Global:
1358 case NestedNameSpecifier::Identifier:
Nikola Smiljanic67860242014-09-26 00:28:20 +00001359 case NestedNameSpecifier::Super:
Guy Benyei11169dd2012-12-18 14:30:41 +00001360 break;
1361 }
1362 }
1363
1364 return false;
1365}
1366
1367bool CursorVisitor::VisitTemplateParameters(
1368 const TemplateParameterList *Params) {
1369 if (!Params)
1370 return false;
1371
1372 for (TemplateParameterList::const_iterator P = Params->begin(),
1373 PEnd = Params->end();
1374 P != PEnd; ++P) {
1375 if (Visit(MakeCXCursor(*P, TU, RegionOfInterest)))
1376 return true;
1377 }
1378
1379 return false;
1380}
1381
1382bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) {
1383 switch (Name.getKind()) {
1384 case TemplateName::Template:
1385 return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
1386
1387 case TemplateName::OverloadedTemplate:
1388 // Visit the overloaded template set.
1389 if (Visit(MakeCursorOverloadedDeclRef(Name, Loc, TU)))
1390 return true;
1391
1392 return false;
1393
1394 case TemplateName::DependentTemplate:
1395 // FIXME: Visit nested-name-specifier.
1396 return false;
1397
1398 case TemplateName::QualifiedTemplate:
1399 // FIXME: Visit nested-name-specifier.
1400 return Visit(MakeCursorTemplateRef(
1401 Name.getAsQualifiedTemplateName()->getDecl(),
1402 Loc, TU));
1403
1404 case TemplateName::SubstTemplateTemplateParm:
1405 return Visit(MakeCursorTemplateRef(
1406 Name.getAsSubstTemplateTemplateParm()->getParameter(),
1407 Loc, TU));
1408
1409 case TemplateName::SubstTemplateTemplateParmPack:
1410 return Visit(MakeCursorTemplateRef(
1411 Name.getAsSubstTemplateTemplateParmPack()->getParameterPack(),
1412 Loc, TU));
1413 }
1414
1415 llvm_unreachable("Invalid TemplateName::Kind!");
1416}
1417
1418bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
1419 switch (TAL.getArgument().getKind()) {
1420 case TemplateArgument::Null:
1421 case TemplateArgument::Integral:
1422 case TemplateArgument::Pack:
1423 return false;
1424
1425 case TemplateArgument::Type:
1426 if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
1427 return Visit(TSInfo->getTypeLoc());
1428 return false;
1429
1430 case TemplateArgument::Declaration:
1431 if (Expr *E = TAL.getSourceDeclExpression())
1432 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
1433 return false;
1434
1435 case TemplateArgument::NullPtr:
1436 if (Expr *E = TAL.getSourceNullPtrExpression())
1437 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
1438 return false;
1439
1440 case TemplateArgument::Expression:
1441 if (Expr *E = TAL.getSourceExpression())
1442 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
1443 return false;
1444
1445 case TemplateArgument::Template:
1446 case TemplateArgument::TemplateExpansion:
1447 if (VisitNestedNameSpecifierLoc(TAL.getTemplateQualifierLoc()))
1448 return true;
1449
1450 return VisitTemplateName(TAL.getArgument().getAsTemplateOrTemplatePattern(),
1451 TAL.getTemplateNameLoc());
1452 }
1453
1454 llvm_unreachable("Invalid TemplateArgument::Kind!");
1455}
1456
1457bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1458 return VisitDeclContext(D);
1459}
1460
1461bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1462 return Visit(TL.getUnqualifiedLoc());
1463}
1464
1465bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
1466 ASTContext &Context = AU->getASTContext();
1467
1468 // Some builtin types (such as Objective-C's "id", "sel", and
1469 // "Class") have associated declarations. Create cursors for those.
1470 QualType VisitType;
1471 switch (TL.getTypePtr()->getKind()) {
1472
1473 case BuiltinType::Void:
1474 case BuiltinType::NullPtr:
1475 case BuiltinType::Dependent:
Alexey Bader954ba212016-04-08 13:40:33 +00001476#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1477 case BuiltinType::Id:
Alexey Baderb62f1442016-04-13 08:33:41 +00001478#include "clang/Basic/OpenCLImageTypes.def"
NAKAMURA Takumi288c42e2013-02-07 12:47:42 +00001479 case BuiltinType::OCLSampler:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001480 case BuiltinType::OCLEvent:
Alexey Bader9c8453f2015-09-15 11:18:52 +00001481 case BuiltinType::OCLClkEvent:
1482 case BuiltinType::OCLQueue:
1483 case BuiltinType::OCLNDRange:
1484 case BuiltinType::OCLReserveID:
Guy Benyei11169dd2012-12-18 14:30:41 +00001485#define BUILTIN_TYPE(Id, SingletonId)
1486#define SIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
1487#define UNSIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
1488#define FLOATING_TYPE(Id, SingletonId) case BuiltinType::Id:
1489#define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id:
1490#include "clang/AST/BuiltinTypes.def"
1491 break;
1492
1493 case BuiltinType::ObjCId:
1494 VisitType = Context.getObjCIdType();
1495 break;
1496
1497 case BuiltinType::ObjCClass:
1498 VisitType = Context.getObjCClassType();
1499 break;
1500
1501 case BuiltinType::ObjCSel:
1502 VisitType = Context.getObjCSelType();
1503 break;
1504 }
1505
1506 if (!VisitType.isNull()) {
1507 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
1508 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
1509 TU));
1510 }
1511
1512 return false;
1513}
1514
1515bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
1516 return Visit(MakeCursorTypeRef(TL.getTypedefNameDecl(), TL.getNameLoc(), TU));
1517}
1518
1519bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
1520 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1521}
1522
1523bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
1524 if (TL.isDefinition())
1525 return Visit(MakeCXCursor(TL.getDecl(), TU, RegionOfInterest));
1526
1527 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1528}
1529
1530bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
1531 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1532}
1533
1534bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
Hans Wennborg59dbe862015-09-29 20:56:43 +00001535 return Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU));
Guy Benyei11169dd2012-12-18 14:30:41 +00001536}
1537
1538bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1539 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
1540 return true;
1541
Douglas Gregore9d95f12015-07-07 03:57:35 +00001542 for (unsigned I = 0, N = TL.getNumTypeArgs(); I != N; ++I) {
1543 if (Visit(TL.getTypeArgTInfo(I)->getTypeLoc()))
1544 return true;
1545 }
1546
Guy Benyei11169dd2012-12-18 14:30:41 +00001547 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1548 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1549 TU)))
1550 return true;
1551 }
1552
1553 return false;
1554}
1555
1556bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
1557 return Visit(TL.getPointeeLoc());
1558}
1559
1560bool CursorVisitor::VisitParenTypeLoc(ParenTypeLoc TL) {
1561 return Visit(TL.getInnerLoc());
1562}
1563
1564bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
1565 return Visit(TL.getPointeeLoc());
1566}
1567
1568bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1569 return Visit(TL.getPointeeLoc());
1570}
1571
1572bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1573 return Visit(TL.getPointeeLoc());
1574}
1575
1576bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
1577 return Visit(TL.getPointeeLoc());
1578}
1579
1580bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
1581 return Visit(TL.getPointeeLoc());
1582}
1583
1584bool CursorVisitor::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
1585 return Visit(TL.getModifiedLoc());
1586}
1587
1588bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
1589 bool SkipResultType) {
Alp Toker42a16a62014-01-25 23:51:36 +00001590 if (!SkipResultType && Visit(TL.getReturnLoc()))
Guy Benyei11169dd2012-12-18 14:30:41 +00001591 return true;
1592
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00001593 for (unsigned I = 0, N = TL.getNumParams(); I != N; ++I)
1594 if (Decl *D = TL.getParam(I))
Guy Benyei11169dd2012-12-18 14:30:41 +00001595 if (Visit(MakeCXCursor(D, TU, RegionOfInterest)))
1596 return true;
1597
1598 return false;
1599}
1600
1601bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
1602 if (Visit(TL.getElementLoc()))
1603 return true;
1604
1605 if (Expr *Size = TL.getSizeExpr())
1606 return Visit(MakeCXCursor(Size, StmtParent, TU, RegionOfInterest));
1607
1608 return false;
1609}
1610
Reid Kleckner8a365022013-06-24 17:51:48 +00001611bool CursorVisitor::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
1612 return Visit(TL.getOriginalLoc());
1613}
1614
Reid Kleckner0503a872013-12-05 01:23:43 +00001615bool CursorVisitor::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
1616 return Visit(TL.getOriginalLoc());
1617}
1618
Guy Benyei11169dd2012-12-18 14:30:41 +00001619bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
1620 TemplateSpecializationTypeLoc TL) {
1621 // Visit the template name.
1622 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1623 TL.getTemplateNameLoc()))
1624 return true;
1625
1626 // Visit the template arguments.
1627 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1628 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1629 return true;
1630
1631 return false;
1632}
1633
1634bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1635 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
1636}
1637
1638bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1639 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1640 return Visit(TSInfo->getTypeLoc());
1641
1642 return false;
1643}
1644
1645bool CursorVisitor::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
1646 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1647 return Visit(TSInfo->getTypeLoc());
1648
1649 return false;
1650}
1651
1652bool CursorVisitor::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
Hans Wennborg59dbe862015-09-29 20:56:43 +00001653 return VisitNestedNameSpecifierLoc(TL.getQualifierLoc());
Guy Benyei11169dd2012-12-18 14:30:41 +00001654}
1655
1656bool CursorVisitor::VisitDependentTemplateSpecializationTypeLoc(
1657 DependentTemplateSpecializationTypeLoc TL) {
1658 // Visit the nested-name-specifier, if there is one.
1659 if (TL.getQualifierLoc() &&
1660 VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1661 return true;
1662
1663 // Visit the template arguments.
1664 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1665 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1666 return true;
1667
1668 return false;
1669}
1670
1671bool CursorVisitor::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
1672 if (VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1673 return true;
1674
1675 return Visit(TL.getNamedTypeLoc());
1676}
1677
1678bool CursorVisitor::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
1679 return Visit(TL.getPatternLoc());
1680}
1681
1682bool CursorVisitor::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
1683 if (Expr *E = TL.getUnderlyingExpr())
1684 return Visit(MakeCXCursor(E, StmtParent, TU));
1685
1686 return false;
1687}
1688
1689bool CursorVisitor::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
1690 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1691}
1692
1693bool CursorVisitor::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
1694 return Visit(TL.getValueLoc());
1695}
1696
Xiuli Pan9c14e282016-01-09 12:53:17 +00001697bool CursorVisitor::VisitPipeTypeLoc(PipeTypeLoc TL) {
1698 return Visit(TL.getValueLoc());
1699}
1700
Guy Benyei11169dd2012-12-18 14:30:41 +00001701#define DEFAULT_TYPELOC_IMPL(CLASS, PARENT) \
1702bool CursorVisitor::Visit##CLASS##TypeLoc(CLASS##TypeLoc TL) { \
1703 return Visit##PARENT##Loc(TL); \
1704}
1705
1706DEFAULT_TYPELOC_IMPL(Complex, Type)
1707DEFAULT_TYPELOC_IMPL(ConstantArray, ArrayType)
1708DEFAULT_TYPELOC_IMPL(IncompleteArray, ArrayType)
1709DEFAULT_TYPELOC_IMPL(VariableArray, ArrayType)
1710DEFAULT_TYPELOC_IMPL(DependentSizedArray, ArrayType)
1711DEFAULT_TYPELOC_IMPL(DependentSizedExtVector, Type)
1712DEFAULT_TYPELOC_IMPL(Vector, Type)
1713DEFAULT_TYPELOC_IMPL(ExtVector, VectorType)
1714DEFAULT_TYPELOC_IMPL(FunctionProto, FunctionType)
1715DEFAULT_TYPELOC_IMPL(FunctionNoProto, FunctionType)
1716DEFAULT_TYPELOC_IMPL(Record, TagType)
1717DEFAULT_TYPELOC_IMPL(Enum, TagType)
1718DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParm, Type)
1719DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParmPack, Type)
1720DEFAULT_TYPELOC_IMPL(Auto, Type)
1721
1722bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
1723 // Visit the nested-name-specifier, if present.
1724 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1725 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1726 return true;
1727
1728 if (D->isCompleteDefinition()) {
Aaron Ballman574705e2014-03-13 15:41:46 +00001729 for (const auto &I : D->bases()) {
1730 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(&I, TU)))
Guy Benyei11169dd2012-12-18 14:30:41 +00001731 return true;
1732 }
1733 }
1734
1735 return VisitTagDecl(D);
1736}
1737
1738bool CursorVisitor::VisitAttributes(Decl *D) {
Aaron Ballmanb97112e2014-03-08 22:19:01 +00001739 for (const auto *I : D->attrs())
1740 if (Visit(MakeCXCursor(I, D, TU)))
Guy Benyei11169dd2012-12-18 14:30:41 +00001741 return true;
1742
1743 return false;
1744}
1745
1746//===----------------------------------------------------------------------===//
1747// Data-recursive visitor methods.
1748//===----------------------------------------------------------------------===//
1749
1750namespace {
1751#define DEF_JOB(NAME, DATA, KIND)\
1752class NAME : public VisitorJob {\
1753public:\
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001754 NAME(const DATA *d, CXCursor parent) : \
1755 VisitorJob(parent, VisitorJob::KIND, d) {} \
Guy Benyei11169dd2012-12-18 14:30:41 +00001756 static bool classof(const VisitorJob *VJ) { return VJ->getKind() == KIND; }\
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001757 const DATA *get() const { return static_cast<const DATA*>(data[0]); }\
Guy Benyei11169dd2012-12-18 14:30:41 +00001758};
1759
1760DEF_JOB(StmtVisit, Stmt, StmtVisitKind)
1761DEF_JOB(MemberExprParts, MemberExpr, MemberExprPartsKind)
1762DEF_JOB(DeclRefExprParts, DeclRefExpr, DeclRefExprPartsKind)
1763DEF_JOB(OverloadExprParts, OverloadExpr, OverloadExprPartsKind)
Guy Benyei11169dd2012-12-18 14:30:41 +00001764DEF_JOB(SizeOfPackExprParts, SizeOfPackExpr, SizeOfPackExprPartsKind)
1765DEF_JOB(LambdaExprParts, LambdaExpr, LambdaExprPartsKind)
1766DEF_JOB(PostChildrenVisit, void, PostChildrenVisitKind)
1767#undef DEF_JOB
1768
James Y Knight04ec5bf2015-12-24 02:59:37 +00001769class ExplicitTemplateArgsVisit : public VisitorJob {
1770public:
1771 ExplicitTemplateArgsVisit(const TemplateArgumentLoc *Begin,
1772 const TemplateArgumentLoc *End, CXCursor parent)
1773 : VisitorJob(parent, VisitorJob::ExplicitTemplateArgsVisitKind, Begin,
1774 End) {}
1775 static bool classof(const VisitorJob *VJ) {
1776 return VJ->getKind() == ExplicitTemplateArgsVisitKind;
1777 }
1778 const TemplateArgumentLoc *begin() const {
1779 return static_cast<const TemplateArgumentLoc *>(data[0]);
1780 }
1781 const TemplateArgumentLoc *end() {
1782 return static_cast<const TemplateArgumentLoc *>(data[1]);
1783 }
1784};
Guy Benyei11169dd2012-12-18 14:30:41 +00001785class DeclVisit : public VisitorJob {
1786public:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001787 DeclVisit(const Decl *D, CXCursor parent, bool isFirst) :
Guy Benyei11169dd2012-12-18 14:30:41 +00001788 VisitorJob(parent, VisitorJob::DeclVisitKind,
Craig Topper69186e72014-06-08 08:38:04 +00001789 D, isFirst ? (void*) 1 : (void*) nullptr) {}
Guy Benyei11169dd2012-12-18 14:30:41 +00001790 static bool classof(const VisitorJob *VJ) {
1791 return VJ->getKind() == DeclVisitKind;
1792 }
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001793 const Decl *get() const { return static_cast<const Decl *>(data[0]); }
Dmitri Gribenkoe5423a72015-03-23 19:23:50 +00001794 bool isFirst() const { return data[1] != nullptr; }
Guy Benyei11169dd2012-12-18 14:30:41 +00001795};
1796class TypeLocVisit : public VisitorJob {
1797public:
1798 TypeLocVisit(TypeLoc tl, CXCursor parent) :
1799 VisitorJob(parent, VisitorJob::TypeLocVisitKind,
1800 tl.getType().getAsOpaquePtr(), tl.getOpaqueData()) {}
1801
1802 static bool classof(const VisitorJob *VJ) {
1803 return VJ->getKind() == TypeLocVisitKind;
1804 }
1805
1806 TypeLoc get() const {
1807 QualType T = QualType::getFromOpaquePtr(data[0]);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001808 return TypeLoc(T, const_cast<void *>(data[1]));
Guy Benyei11169dd2012-12-18 14:30:41 +00001809 }
1810};
1811
1812class LabelRefVisit : public VisitorJob {
1813public:
1814 LabelRefVisit(LabelDecl *LD, SourceLocation labelLoc, CXCursor parent)
1815 : VisitorJob(parent, VisitorJob::LabelRefVisitKind, LD,
1816 labelLoc.getPtrEncoding()) {}
1817
1818 static bool classof(const VisitorJob *VJ) {
1819 return VJ->getKind() == VisitorJob::LabelRefVisitKind;
1820 }
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001821 const LabelDecl *get() const {
1822 return static_cast<const LabelDecl *>(data[0]);
1823 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001824 SourceLocation getLoc() const {
1825 return SourceLocation::getFromPtrEncoding(data[1]); }
1826};
1827
1828class NestedNameSpecifierLocVisit : public VisitorJob {
1829public:
1830 NestedNameSpecifierLocVisit(NestedNameSpecifierLoc Qualifier, CXCursor parent)
1831 : VisitorJob(parent, VisitorJob::NestedNameSpecifierLocVisitKind,
1832 Qualifier.getNestedNameSpecifier(),
1833 Qualifier.getOpaqueData()) { }
1834
1835 static bool classof(const VisitorJob *VJ) {
1836 return VJ->getKind() == VisitorJob::NestedNameSpecifierLocVisitKind;
1837 }
1838
1839 NestedNameSpecifierLoc get() const {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001840 return NestedNameSpecifierLoc(
1841 const_cast<NestedNameSpecifier *>(
1842 static_cast<const NestedNameSpecifier *>(data[0])),
1843 const_cast<void *>(data[1]));
Guy Benyei11169dd2012-12-18 14:30:41 +00001844 }
1845};
1846
1847class DeclarationNameInfoVisit : public VisitorJob {
1848public:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001849 DeclarationNameInfoVisit(const Stmt *S, CXCursor parent)
Dmitri Gribenkodd7dacf2013-02-03 13:19:54 +00001850 : VisitorJob(parent, VisitorJob::DeclarationNameInfoVisitKind, S) {}
Guy Benyei11169dd2012-12-18 14:30:41 +00001851 static bool classof(const VisitorJob *VJ) {
1852 return VJ->getKind() == VisitorJob::DeclarationNameInfoVisitKind;
1853 }
1854 DeclarationNameInfo get() const {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001855 const Stmt *S = static_cast<const Stmt *>(data[0]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001856 switch (S->getStmtClass()) {
1857 default:
1858 llvm_unreachable("Unhandled Stmt");
1859 case clang::Stmt::MSDependentExistsStmtClass:
1860 return cast<MSDependentExistsStmt>(S)->getNameInfo();
1861 case Stmt::CXXDependentScopeMemberExprClass:
1862 return cast<CXXDependentScopeMemberExpr>(S)->getMemberNameInfo();
1863 case Stmt::DependentScopeDeclRefExprClass:
1864 return cast<DependentScopeDeclRefExpr>(S)->getNameInfo();
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001865 case Stmt::OMPCriticalDirectiveClass:
1866 return cast<OMPCriticalDirective>(S)->getDirectiveName();
Guy Benyei11169dd2012-12-18 14:30:41 +00001867 }
1868 }
1869};
1870class MemberRefVisit : public VisitorJob {
1871public:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001872 MemberRefVisit(const FieldDecl *D, SourceLocation L, CXCursor parent)
Guy Benyei11169dd2012-12-18 14:30:41 +00001873 : VisitorJob(parent, VisitorJob::MemberRefVisitKind, D,
1874 L.getPtrEncoding()) {}
1875 static bool classof(const VisitorJob *VJ) {
1876 return VJ->getKind() == VisitorJob::MemberRefVisitKind;
1877 }
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001878 const FieldDecl *get() const {
1879 return static_cast<const FieldDecl *>(data[0]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001880 }
1881 SourceLocation getLoc() const {
1882 return SourceLocation::getFromRawEncoding((unsigned)(uintptr_t) data[1]);
1883 }
1884};
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001885class EnqueueVisitor : public ConstStmtVisitor<EnqueueVisitor, void> {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001886 friend class OMPClauseEnqueue;
Guy Benyei11169dd2012-12-18 14:30:41 +00001887 VisitorWorkList &WL;
1888 CXCursor Parent;
1889public:
1890 EnqueueVisitor(VisitorWorkList &wl, CXCursor parent)
1891 : WL(wl), Parent(parent) {}
1892
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001893 void VisitAddrLabelExpr(const AddrLabelExpr *E);
1894 void VisitBlockExpr(const BlockExpr *B);
1895 void VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
1896 void VisitCompoundStmt(const CompoundStmt *S);
1897 void VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) { /* Do nothing. */ }
1898 void VisitMSDependentExistsStmt(const MSDependentExistsStmt *S);
1899 void VisitCXXDependentScopeMemberExpr(const CXXDependentScopeMemberExpr *E);
1900 void VisitCXXNewExpr(const CXXNewExpr *E);
1901 void VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E);
1902 void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *E);
1903 void VisitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *E);
1904 void VisitCXXTemporaryObjectExpr(const CXXTemporaryObjectExpr *E);
1905 void VisitCXXTypeidExpr(const CXXTypeidExpr *E);
1906 void VisitCXXUnresolvedConstructExpr(const CXXUnresolvedConstructExpr *E);
1907 void VisitCXXUuidofExpr(const CXXUuidofExpr *E);
1908 void VisitCXXCatchStmt(const CXXCatchStmt *S);
Argyrios Kyrtzidis99891242014-11-13 09:03:21 +00001909 void VisitCXXForRangeStmt(const CXXForRangeStmt *S);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001910 void VisitDeclRefExpr(const DeclRefExpr *D);
1911 void VisitDeclStmt(const DeclStmt *S);
1912 void VisitDependentScopeDeclRefExpr(const DependentScopeDeclRefExpr *E);
1913 void VisitDesignatedInitExpr(const DesignatedInitExpr *E);
1914 void VisitExplicitCastExpr(const ExplicitCastExpr *E);
1915 void VisitForStmt(const ForStmt *FS);
1916 void VisitGotoStmt(const GotoStmt *GS);
1917 void VisitIfStmt(const IfStmt *If);
1918 void VisitInitListExpr(const InitListExpr *IE);
1919 void VisitMemberExpr(const MemberExpr *M);
1920 void VisitOffsetOfExpr(const OffsetOfExpr *E);
1921 void VisitObjCEncodeExpr(const ObjCEncodeExpr *E);
1922 void VisitObjCMessageExpr(const ObjCMessageExpr *M);
1923 void VisitOverloadExpr(const OverloadExpr *E);
1924 void VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
1925 void VisitStmt(const Stmt *S);
1926 void VisitSwitchStmt(const SwitchStmt *S);
1927 void VisitWhileStmt(const WhileStmt *W);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001928 void VisitTypeTraitExpr(const TypeTraitExpr *E);
1929 void VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E);
1930 void VisitExpressionTraitExpr(const ExpressionTraitExpr *E);
1931 void VisitUnresolvedMemberExpr(const UnresolvedMemberExpr *U);
1932 void VisitVAArgExpr(const VAArgExpr *E);
1933 void VisitSizeOfPackExpr(const SizeOfPackExpr *E);
1934 void VisitPseudoObjectExpr(const PseudoObjectExpr *E);
1935 void VisitOpaqueValueExpr(const OpaqueValueExpr *E);
1936 void VisitLambdaExpr(const LambdaExpr *E);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001937 void VisitOMPExecutableDirective(const OMPExecutableDirective *D);
Alexander Musman3aaab662014-08-19 11:27:13 +00001938 void VisitOMPLoopDirective(const OMPLoopDirective *D);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001939 void VisitOMPParallelDirective(const OMPParallelDirective *D);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00001940 void VisitOMPSimdDirective(const OMPSimdDirective *D);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001941 void VisitOMPForDirective(const OMPForDirective *D);
Alexander Musmanf82886e2014-09-18 05:12:34 +00001942 void VisitOMPForSimdDirective(const OMPForSimdDirective *D);
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00001943 void VisitOMPSectionsDirective(const OMPSectionsDirective *D);
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001944 void VisitOMPSectionDirective(const OMPSectionDirective *D);
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00001945 void VisitOMPSingleDirective(const OMPSingleDirective *D);
Alexander Musman80c22892014-07-17 08:54:58 +00001946 void VisitOMPMasterDirective(const OMPMasterDirective *D);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001947 void VisitOMPCriticalDirective(const OMPCriticalDirective *D);
Alexey Bataev4acb8592014-07-07 13:01:15 +00001948 void VisitOMPParallelForDirective(const OMPParallelForDirective *D);
Alexander Musmane4e893b2014-09-23 09:33:00 +00001949 void VisitOMPParallelForSimdDirective(const OMPParallelForSimdDirective *D);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001950 void VisitOMPParallelSectionsDirective(const OMPParallelSectionsDirective *D);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001951 void VisitOMPTaskDirective(const OMPTaskDirective *D);
Alexey Bataev68446b72014-07-18 07:47:19 +00001952 void VisitOMPTaskyieldDirective(const OMPTaskyieldDirective *D);
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001953 void VisitOMPBarrierDirective(const OMPBarrierDirective *D);
Alexey Bataev2df347a2014-07-18 10:17:07 +00001954 void VisitOMPTaskwaitDirective(const OMPTaskwaitDirective *D);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001955 void VisitOMPTaskgroupDirective(const OMPTaskgroupDirective *D);
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001956 void
1957 VisitOMPCancellationPointDirective(const OMPCancellationPointDirective *D);
Alexey Bataev80909872015-07-02 11:25:17 +00001958 void VisitOMPCancelDirective(const OMPCancelDirective *D);
Alexey Bataev6125da92014-07-21 11:26:11 +00001959 void VisitOMPFlushDirective(const OMPFlushDirective *D);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001960 void VisitOMPOrderedDirective(const OMPOrderedDirective *D);
Alexey Bataev0162e452014-07-22 10:10:35 +00001961 void VisitOMPAtomicDirective(const OMPAtomicDirective *D);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001962 void VisitOMPTargetDirective(const OMPTargetDirective *D);
Michael Wong65f367f2015-07-21 13:44:28 +00001963 void VisitOMPTargetDataDirective(const OMPTargetDataDirective *D);
Samuel Antaodf67fc42016-01-19 19:15:56 +00001964 void VisitOMPTargetEnterDataDirective(const OMPTargetEnterDataDirective *D);
Samuel Antao72590762016-01-19 20:04:50 +00001965 void VisitOMPTargetExitDataDirective(const OMPTargetExitDataDirective *D);
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00001966 void VisitOMPTargetParallelDirective(const OMPTargetParallelDirective *D);
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00001967 void
1968 VisitOMPTargetParallelForDirective(const OMPTargetParallelForDirective *D);
Alexey Bataev13314bf2014-10-09 04:18:56 +00001969 void VisitOMPTeamsDirective(const OMPTeamsDirective *D);
Alexey Bataev49f6e782015-12-01 04:18:41 +00001970 void VisitOMPTaskLoopDirective(const OMPTaskLoopDirective *D);
Alexey Bataev0a6ed842015-12-03 09:40:15 +00001971 void VisitOMPTaskLoopSimdDirective(const OMPTaskLoopSimdDirective *D);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00001972 void VisitOMPDistributeDirective(const OMPDistributeDirective *D);
Carlo Bertolli9925f152016-06-27 14:55:37 +00001973 void VisitOMPDistributeParallelForDirective(
1974 const OMPDistributeParallelForDirective *D);
Kelvin Li4a39add2016-07-05 05:00:15 +00001975 void VisitOMPDistributeParallelForSimdDirective(
1976 const OMPDistributeParallelForSimdDirective *D);
Kelvin Li787f3fc2016-07-06 04:45:38 +00001977 void VisitOMPDistributeSimdDirective(const OMPDistributeSimdDirective *D);
Kelvin Lia579b912016-07-14 02:54:56 +00001978 void VisitOMPTargetParallelForSimdDirective(
1979 const OMPTargetParallelForSimdDirective *D);
Kelvin Li986330c2016-07-20 22:57:10 +00001980 void VisitOMPTargetSimdDirective(const OMPTargetSimdDirective *D);
Kelvin Li02532872016-08-05 14:37:37 +00001981 void VisitOMPTeamsDistributeDirective(const OMPTeamsDistributeDirective *D);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001982
Guy Benyei11169dd2012-12-18 14:30:41 +00001983private:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001984 void AddDeclarationNameInfo(const Stmt *S);
Guy Benyei11169dd2012-12-18 14:30:41 +00001985 void AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier);
James Y Knight04ec5bf2015-12-24 02:59:37 +00001986 void AddExplicitTemplateArgs(const TemplateArgumentLoc *A,
1987 unsigned NumTemplateArgs);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001988 void AddMemberRef(const FieldDecl *D, SourceLocation L);
1989 void AddStmt(const Stmt *S);
1990 void AddDecl(const Decl *D, bool isFirst = true);
Guy Benyei11169dd2012-12-18 14:30:41 +00001991 void AddTypeLoc(TypeSourceInfo *TI);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001992 void EnqueueChildren(const Stmt *S);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001993 void EnqueueChildren(const OMPClause *S);
Guy Benyei11169dd2012-12-18 14:30:41 +00001994};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001995} // end anonyous namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00001996
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001997void EnqueueVisitor::AddDeclarationNameInfo(const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001998 // 'S' should always be non-null, since it comes from the
1999 // statement we are visiting.
2000 WL.push_back(DeclarationNameInfoVisit(S, Parent));
2001}
2002
2003void
2004EnqueueVisitor::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
2005 if (Qualifier)
2006 WL.push_back(NestedNameSpecifierLocVisit(Qualifier, Parent));
2007}
2008
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002009void EnqueueVisitor::AddStmt(const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002010 if (S)
2011 WL.push_back(StmtVisit(S, Parent));
2012}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002013void EnqueueVisitor::AddDecl(const Decl *D, bool isFirst) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002014 if (D)
2015 WL.push_back(DeclVisit(D, Parent, isFirst));
2016}
James Y Knight04ec5bf2015-12-24 02:59:37 +00002017void EnqueueVisitor::AddExplicitTemplateArgs(const TemplateArgumentLoc *A,
2018 unsigned NumTemplateArgs) {
2019 WL.push_back(ExplicitTemplateArgsVisit(A, A + NumTemplateArgs, Parent));
Guy Benyei11169dd2012-12-18 14:30:41 +00002020}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002021void EnqueueVisitor::AddMemberRef(const FieldDecl *D, SourceLocation L) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002022 if (D)
2023 WL.push_back(MemberRefVisit(D, L, Parent));
2024}
2025void EnqueueVisitor::AddTypeLoc(TypeSourceInfo *TI) {
2026 if (TI)
2027 WL.push_back(TypeLocVisit(TI->getTypeLoc(), Parent));
2028 }
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002029void EnqueueVisitor::EnqueueChildren(const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002030 unsigned size = WL.size();
Benjamin Kramer642f1732015-07-02 21:03:14 +00002031 for (const Stmt *SubStmt : S->children()) {
2032 AddStmt(SubStmt);
Guy Benyei11169dd2012-12-18 14:30:41 +00002033 }
2034 if (size == WL.size())
2035 return;
2036 // Now reverse the entries we just added. This will match the DFS
2037 // ordering performed by the worklist.
2038 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2039 std::reverse(I, E);
2040}
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002041namespace {
2042class OMPClauseEnqueue : public ConstOMPClauseVisitor<OMPClauseEnqueue> {
2043 EnqueueVisitor *Visitor;
Alexey Bataev756c1962013-09-24 03:17:45 +00002044 /// \brief Process clauses with list of variables.
2045 template <typename T>
2046 void VisitOMPClauseList(T *Node);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002047public:
2048 OMPClauseEnqueue(EnqueueVisitor *Visitor) : Visitor(Visitor) { }
2049#define OPENMP_CLAUSE(Name, Class) \
2050 void Visit##Class(const Class *C);
2051#include "clang/Basic/OpenMPKinds.def"
Alexey Bataev3392d762016-02-16 11:18:12 +00002052 void VisitOMPClauseWithPreInit(const OMPClauseWithPreInit *C);
Alexey Bataev005248a2016-02-25 05:25:57 +00002053 void VisitOMPClauseWithPostUpdate(const OMPClauseWithPostUpdate *C);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002054};
2055
Alexey Bataev3392d762016-02-16 11:18:12 +00002056void OMPClauseEnqueue::VisitOMPClauseWithPreInit(
2057 const OMPClauseWithPreInit *C) {
2058 Visitor->AddStmt(C->getPreInitStmt());
2059}
2060
Alexey Bataev005248a2016-02-25 05:25:57 +00002061void OMPClauseEnqueue::VisitOMPClauseWithPostUpdate(
2062 const OMPClauseWithPostUpdate *C) {
Alexey Bataev37e594c2016-03-04 07:21:16 +00002063 VisitOMPClauseWithPreInit(C);
Alexey Bataev005248a2016-02-25 05:25:57 +00002064 Visitor->AddStmt(C->getPostUpdateExpr());
2065}
2066
Alexey Bataevaadd52e2014-02-13 05:29:23 +00002067void OMPClauseEnqueue::VisitOMPIfClause(const OMPIfClause *C) {
2068 Visitor->AddStmt(C->getCondition());
2069}
2070
Alexey Bataev3778b602014-07-17 07:32:53 +00002071void OMPClauseEnqueue::VisitOMPFinalClause(const OMPFinalClause *C) {
2072 Visitor->AddStmt(C->getCondition());
2073}
2074
Alexey Bataev568a8332014-03-06 06:15:19 +00002075void OMPClauseEnqueue::VisitOMPNumThreadsClause(const OMPNumThreadsClause *C) {
2076 Visitor->AddStmt(C->getNumThreads());
2077}
2078
Alexey Bataev62c87d22014-03-21 04:51:18 +00002079void OMPClauseEnqueue::VisitOMPSafelenClause(const OMPSafelenClause *C) {
2080 Visitor->AddStmt(C->getSafelen());
2081}
2082
Alexey Bataev66b15b52015-08-21 11:14:16 +00002083void OMPClauseEnqueue::VisitOMPSimdlenClause(const OMPSimdlenClause *C) {
2084 Visitor->AddStmt(C->getSimdlen());
2085}
2086
Alexander Musman8bd31e62014-05-27 15:12:19 +00002087void OMPClauseEnqueue::VisitOMPCollapseClause(const OMPCollapseClause *C) {
2088 Visitor->AddStmt(C->getNumForLoops());
2089}
2090
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002091void OMPClauseEnqueue::VisitOMPDefaultClause(const OMPDefaultClause *C) { }
Alexey Bataev756c1962013-09-24 03:17:45 +00002092
Alexey Bataevbcbadb62014-05-06 06:04:14 +00002093void OMPClauseEnqueue::VisitOMPProcBindClause(const OMPProcBindClause *C) { }
2094
Alexey Bataev56dafe82014-06-20 07:16:17 +00002095void OMPClauseEnqueue::VisitOMPScheduleClause(const OMPScheduleClause *C) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002096 VisitOMPClauseWithPreInit(C);
Alexey Bataev56dafe82014-06-20 07:16:17 +00002097 Visitor->AddStmt(C->getChunkSize());
2098}
2099
Alexey Bataev10e775f2015-07-30 11:36:16 +00002100void OMPClauseEnqueue::VisitOMPOrderedClause(const OMPOrderedClause *C) {
2101 Visitor->AddStmt(C->getNumForLoops());
2102}
Alexey Bataev142e1fc2014-06-20 09:44:06 +00002103
Alexey Bataev236070f2014-06-20 11:19:47 +00002104void OMPClauseEnqueue::VisitOMPNowaitClause(const OMPNowaitClause *) {}
2105
Alexey Bataev7aea99a2014-07-17 12:19:31 +00002106void OMPClauseEnqueue::VisitOMPUntiedClause(const OMPUntiedClause *) {}
2107
Alexey Bataev74ba3a52014-07-17 12:47:03 +00002108void OMPClauseEnqueue::VisitOMPMergeableClause(const OMPMergeableClause *) {}
2109
Alexey Bataevf98b00c2014-07-23 02:27:21 +00002110void OMPClauseEnqueue::VisitOMPReadClause(const OMPReadClause *) {}
2111
Alexey Bataevdea47612014-07-23 07:46:59 +00002112void OMPClauseEnqueue::VisitOMPWriteClause(const OMPWriteClause *) {}
2113
Alexey Bataev67a4f222014-07-23 10:25:33 +00002114void OMPClauseEnqueue::VisitOMPUpdateClause(const OMPUpdateClause *) {}
2115
Alexey Bataev459dec02014-07-24 06:46:57 +00002116void OMPClauseEnqueue::VisitOMPCaptureClause(const OMPCaptureClause *) {}
2117
Alexey Bataev82bad8b2014-07-24 08:55:34 +00002118void OMPClauseEnqueue::VisitOMPSeqCstClause(const OMPSeqCstClause *) {}
2119
Alexey Bataev346265e2015-09-25 10:37:12 +00002120void OMPClauseEnqueue::VisitOMPThreadsClause(const OMPThreadsClause *) {}
2121
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002122void OMPClauseEnqueue::VisitOMPSIMDClause(const OMPSIMDClause *) {}
2123
Alexey Bataevb825de12015-12-07 10:51:44 +00002124void OMPClauseEnqueue::VisitOMPNogroupClause(const OMPNogroupClause *) {}
2125
Michael Wonge710d542015-08-07 16:16:36 +00002126void OMPClauseEnqueue::VisitOMPDeviceClause(const OMPDeviceClause *C) {
2127 Visitor->AddStmt(C->getDevice());
2128}
2129
Kelvin Li099bb8c2015-11-24 20:50:12 +00002130void OMPClauseEnqueue::VisitOMPNumTeamsClause(const OMPNumTeamsClause *C) {
2131 Visitor->AddStmt(C->getNumTeams());
2132}
2133
Kelvin Lia15fb1a2015-11-27 18:47:36 +00002134void OMPClauseEnqueue::VisitOMPThreadLimitClause(const OMPThreadLimitClause *C) {
2135 Visitor->AddStmt(C->getThreadLimit());
2136}
2137
Alexey Bataeva0569352015-12-01 10:17:31 +00002138void OMPClauseEnqueue::VisitOMPPriorityClause(const OMPPriorityClause *C) {
2139 Visitor->AddStmt(C->getPriority());
2140}
2141
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00002142void OMPClauseEnqueue::VisitOMPGrainsizeClause(const OMPGrainsizeClause *C) {
2143 Visitor->AddStmt(C->getGrainsize());
2144}
2145
Alexey Bataev382967a2015-12-08 12:06:20 +00002146void OMPClauseEnqueue::VisitOMPNumTasksClause(const OMPNumTasksClause *C) {
2147 Visitor->AddStmt(C->getNumTasks());
2148}
2149
Alexey Bataev28c75412015-12-15 08:19:24 +00002150void OMPClauseEnqueue::VisitOMPHintClause(const OMPHintClause *C) {
2151 Visitor->AddStmt(C->getHint());
2152}
2153
Alexey Bataev756c1962013-09-24 03:17:45 +00002154template<typename T>
2155void OMPClauseEnqueue::VisitOMPClauseList(T *Node) {
Alexey Bataev03b340a2014-10-21 03:16:40 +00002156 for (const auto *I : Node->varlists()) {
Aaron Ballman2205d2a2014-03-14 15:55:35 +00002157 Visitor->AddStmt(I);
Alexey Bataev03b340a2014-10-21 03:16:40 +00002158 }
Alexey Bataev756c1962013-09-24 03:17:45 +00002159}
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002160
2161void OMPClauseEnqueue::VisitOMPPrivateClause(const OMPPrivateClause *C) {
Alexey Bataev756c1962013-09-24 03:17:45 +00002162 VisitOMPClauseList(C);
Alexey Bataev03b340a2014-10-21 03:16:40 +00002163 for (const auto *E : C->private_copies()) {
2164 Visitor->AddStmt(E);
2165 }
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002166}
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002167void OMPClauseEnqueue::VisitOMPFirstprivateClause(
2168 const OMPFirstprivateClause *C) {
2169 VisitOMPClauseList(C);
Alexey Bataev417089f2016-02-17 13:19:37 +00002170 VisitOMPClauseWithPreInit(C);
2171 for (const auto *E : C->private_copies()) {
2172 Visitor->AddStmt(E);
2173 }
2174 for (const auto *E : C->inits()) {
2175 Visitor->AddStmt(E);
2176 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002177}
Alexander Musman1bb328c2014-06-04 13:06:39 +00002178void OMPClauseEnqueue::VisitOMPLastprivateClause(
2179 const OMPLastprivateClause *C) {
2180 VisitOMPClauseList(C);
Alexey Bataev005248a2016-02-25 05:25:57 +00002181 VisitOMPClauseWithPostUpdate(C);
Alexey Bataev38e89532015-04-16 04:54:05 +00002182 for (auto *E : C->private_copies()) {
2183 Visitor->AddStmt(E);
2184 }
2185 for (auto *E : C->source_exprs()) {
2186 Visitor->AddStmt(E);
2187 }
2188 for (auto *E : C->destination_exprs()) {
2189 Visitor->AddStmt(E);
2190 }
2191 for (auto *E : C->assignment_ops()) {
2192 Visitor->AddStmt(E);
2193 }
Alexander Musman1bb328c2014-06-04 13:06:39 +00002194}
Alexey Bataev758e55e2013-09-06 18:03:48 +00002195void OMPClauseEnqueue::VisitOMPSharedClause(const OMPSharedClause *C) {
Alexey Bataev756c1962013-09-24 03:17:45 +00002196 VisitOMPClauseList(C);
Alexey Bataev758e55e2013-09-06 18:03:48 +00002197}
Alexey Bataevc5e02582014-06-16 07:08:35 +00002198void OMPClauseEnqueue::VisitOMPReductionClause(const OMPReductionClause *C) {
2199 VisitOMPClauseList(C);
Alexey Bataev61205072016-03-02 04:57:40 +00002200 VisitOMPClauseWithPostUpdate(C);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00002201 for (auto *E : C->privates()) {
2202 Visitor->AddStmt(E);
2203 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002204 for (auto *E : C->lhs_exprs()) {
2205 Visitor->AddStmt(E);
2206 }
2207 for (auto *E : C->rhs_exprs()) {
2208 Visitor->AddStmt(E);
2209 }
2210 for (auto *E : C->reduction_ops()) {
2211 Visitor->AddStmt(E);
2212 }
Alexey Bataevc5e02582014-06-16 07:08:35 +00002213}
Alexander Musman8dba6642014-04-22 13:09:42 +00002214void OMPClauseEnqueue::VisitOMPLinearClause(const OMPLinearClause *C) {
2215 VisitOMPClauseList(C);
Alexey Bataev78849fb2016-03-09 09:49:00 +00002216 VisitOMPClauseWithPostUpdate(C);
Alexey Bataevbd9fec12015-08-18 06:47:21 +00002217 for (const auto *E : C->privates()) {
2218 Visitor->AddStmt(E);
2219 }
Alexander Musman3276a272015-03-21 10:12:56 +00002220 for (const auto *E : C->inits()) {
2221 Visitor->AddStmt(E);
2222 }
2223 for (const auto *E : C->updates()) {
2224 Visitor->AddStmt(E);
2225 }
2226 for (const auto *E : C->finals()) {
2227 Visitor->AddStmt(E);
2228 }
Alexander Musman8dba6642014-04-22 13:09:42 +00002229 Visitor->AddStmt(C->getStep());
Alexander Musman3276a272015-03-21 10:12:56 +00002230 Visitor->AddStmt(C->getCalcStep());
Alexander Musman8dba6642014-04-22 13:09:42 +00002231}
Alexander Musmanf0d76e72014-05-29 14:36:25 +00002232void OMPClauseEnqueue::VisitOMPAlignedClause(const OMPAlignedClause *C) {
2233 VisitOMPClauseList(C);
2234 Visitor->AddStmt(C->getAlignment());
2235}
Alexey Bataevd48bcd82014-03-31 03:36:38 +00002236void OMPClauseEnqueue::VisitOMPCopyinClause(const OMPCopyinClause *C) {
2237 VisitOMPClauseList(C);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00002238 for (auto *E : C->source_exprs()) {
2239 Visitor->AddStmt(E);
2240 }
2241 for (auto *E : C->destination_exprs()) {
2242 Visitor->AddStmt(E);
2243 }
2244 for (auto *E : C->assignment_ops()) {
2245 Visitor->AddStmt(E);
2246 }
Alexey Bataevd48bcd82014-03-31 03:36:38 +00002247}
Alexey Bataevbae9a792014-06-27 10:37:06 +00002248void
2249OMPClauseEnqueue::VisitOMPCopyprivateClause(const OMPCopyprivateClause *C) {
2250 VisitOMPClauseList(C);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002251 for (auto *E : C->source_exprs()) {
2252 Visitor->AddStmt(E);
2253 }
2254 for (auto *E : C->destination_exprs()) {
2255 Visitor->AddStmt(E);
2256 }
2257 for (auto *E : C->assignment_ops()) {
2258 Visitor->AddStmt(E);
2259 }
Alexey Bataevbae9a792014-06-27 10:37:06 +00002260}
Alexey Bataev6125da92014-07-21 11:26:11 +00002261void OMPClauseEnqueue::VisitOMPFlushClause(const OMPFlushClause *C) {
2262 VisitOMPClauseList(C);
2263}
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00002264void OMPClauseEnqueue::VisitOMPDependClause(const OMPDependClause *C) {
2265 VisitOMPClauseList(C);
2266}
Kelvin Li0bff7af2015-11-23 05:32:03 +00002267void OMPClauseEnqueue::VisitOMPMapClause(const OMPMapClause *C) {
2268 VisitOMPClauseList(C);
2269}
Carlo Bertollib4adf552016-01-15 18:50:31 +00002270void OMPClauseEnqueue::VisitOMPDistScheduleClause(
2271 const OMPDistScheduleClause *C) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002272 VisitOMPClauseWithPreInit(C);
Carlo Bertollib4adf552016-01-15 18:50:31 +00002273 Visitor->AddStmt(C->getChunkSize());
Carlo Bertollib4adf552016-01-15 18:50:31 +00002274}
Alexey Bataev3392d762016-02-16 11:18:12 +00002275void OMPClauseEnqueue::VisitOMPDefaultmapClause(
2276 const OMPDefaultmapClause * /*C*/) {}
Samuel Antao661c0902016-05-26 17:39:58 +00002277void OMPClauseEnqueue::VisitOMPToClause(const OMPToClause *C) {
2278 VisitOMPClauseList(C);
2279}
Samuel Antaoec172c62016-05-26 17:49:04 +00002280void OMPClauseEnqueue::VisitOMPFromClause(const OMPFromClause *C) {
2281 VisitOMPClauseList(C);
2282}
Carlo Bertolli2404b172016-07-13 15:37:16 +00002283void OMPClauseEnqueue::VisitOMPUseDevicePtrClause(const OMPUseDevicePtrClause *C) {
2284 VisitOMPClauseList(C);
2285}
Carlo Bertolli70594e92016-07-13 17:16:49 +00002286void OMPClauseEnqueue::VisitOMPIsDevicePtrClause(const OMPIsDevicePtrClause *C) {
2287 VisitOMPClauseList(C);
2288}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002289}
Alexey Bataev756c1962013-09-24 03:17:45 +00002290
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002291void EnqueueVisitor::EnqueueChildren(const OMPClause *S) {
2292 unsigned size = WL.size();
2293 OMPClauseEnqueue Visitor(this);
2294 Visitor.Visit(S);
2295 if (size == WL.size())
2296 return;
2297 // Now reverse the entries we just added. This will match the DFS
2298 // ordering performed by the worklist.
2299 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2300 std::reverse(I, E);
2301}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002302void EnqueueVisitor::VisitAddrLabelExpr(const AddrLabelExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002303 WL.push_back(LabelRefVisit(E->getLabel(), E->getLabelLoc(), Parent));
2304}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002305void EnqueueVisitor::VisitBlockExpr(const BlockExpr *B) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002306 AddDecl(B->getBlockDecl());
2307}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002308void EnqueueVisitor::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002309 EnqueueChildren(E);
2310 AddTypeLoc(E->getTypeSourceInfo());
2311}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002312void EnqueueVisitor::VisitCompoundStmt(const CompoundStmt *S) {
Pete Cooper57d3f142015-07-30 17:22:52 +00002313 for (auto &I : llvm::reverse(S->body()))
2314 AddStmt(I);
Guy Benyei11169dd2012-12-18 14:30:41 +00002315}
2316void EnqueueVisitor::
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002317VisitMSDependentExistsStmt(const MSDependentExistsStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002318 AddStmt(S->getSubStmt());
2319 AddDeclarationNameInfo(S);
2320 if (NestedNameSpecifierLoc QualifierLoc = S->getQualifierLoc())
2321 AddNestedNameSpecifierLoc(QualifierLoc);
2322}
2323
2324void EnqueueVisitor::
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002325VisitCXXDependentScopeMemberExpr(const CXXDependentScopeMemberExpr *E) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002326 if (E->hasExplicitTemplateArgs())
2327 AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002328 AddDeclarationNameInfo(E);
2329 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
2330 AddNestedNameSpecifierLoc(QualifierLoc);
2331 if (!E->isImplicitAccess())
2332 AddStmt(E->getBase());
2333}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002334void EnqueueVisitor::VisitCXXNewExpr(const CXXNewExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002335 // Enqueue the initializer , if any.
2336 AddStmt(E->getInitializer());
2337 // Enqueue the array size, if any.
2338 AddStmt(E->getArraySize());
2339 // Enqueue the allocated type.
2340 AddTypeLoc(E->getAllocatedTypeSourceInfo());
2341 // Enqueue the placement arguments.
2342 for (unsigned I = E->getNumPlacementArgs(); I > 0; --I)
2343 AddStmt(E->getPlacementArg(I-1));
2344}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002345void EnqueueVisitor::VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CE) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002346 for (unsigned I = CE->getNumArgs(); I > 1 /* Yes, this is 1 */; --I)
2347 AddStmt(CE->getArg(I-1));
2348 AddStmt(CE->getCallee());
2349 AddStmt(CE->getArg(0));
2350}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002351void EnqueueVisitor::VisitCXXPseudoDestructorExpr(
2352 const CXXPseudoDestructorExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002353 // Visit the name of the type being destroyed.
2354 AddTypeLoc(E->getDestroyedTypeInfo());
2355 // Visit the scope type that looks disturbingly like the nested-name-specifier
2356 // but isn't.
2357 AddTypeLoc(E->getScopeTypeInfo());
2358 // Visit the nested-name-specifier.
2359 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
2360 AddNestedNameSpecifierLoc(QualifierLoc);
2361 // Visit base expression.
2362 AddStmt(E->getBase());
2363}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002364void EnqueueVisitor::VisitCXXScalarValueInitExpr(
2365 const CXXScalarValueInitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002366 AddTypeLoc(E->getTypeSourceInfo());
2367}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002368void EnqueueVisitor::VisitCXXTemporaryObjectExpr(
2369 const CXXTemporaryObjectExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002370 EnqueueChildren(E);
2371 AddTypeLoc(E->getTypeSourceInfo());
2372}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002373void EnqueueVisitor::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002374 EnqueueChildren(E);
2375 if (E->isTypeOperand())
2376 AddTypeLoc(E->getTypeOperandSourceInfo());
2377}
2378
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002379void EnqueueVisitor::VisitCXXUnresolvedConstructExpr(
2380 const CXXUnresolvedConstructExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002381 EnqueueChildren(E);
2382 AddTypeLoc(E->getTypeSourceInfo());
2383}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002384void EnqueueVisitor::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002385 EnqueueChildren(E);
2386 if (E->isTypeOperand())
2387 AddTypeLoc(E->getTypeOperandSourceInfo());
2388}
2389
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002390void EnqueueVisitor::VisitCXXCatchStmt(const CXXCatchStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002391 EnqueueChildren(S);
2392 AddDecl(S->getExceptionDecl());
2393}
2394
Argyrios Kyrtzidis99891242014-11-13 09:03:21 +00002395void EnqueueVisitor::VisitCXXForRangeStmt(const CXXForRangeStmt *S) {
Argyrios Kyrtzidiscde70692014-11-13 09:50:19 +00002396 AddStmt(S->getBody());
Argyrios Kyrtzidis99891242014-11-13 09:03:21 +00002397 AddStmt(S->getRangeInit());
Argyrios Kyrtzidiscde70692014-11-13 09:50:19 +00002398 AddDecl(S->getLoopVariable());
Argyrios Kyrtzidis99891242014-11-13 09:03:21 +00002399}
2400
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002401void EnqueueVisitor::VisitDeclRefExpr(const DeclRefExpr *DR) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002402 if (DR->hasExplicitTemplateArgs())
2403 AddExplicitTemplateArgs(DR->getTemplateArgs(), DR->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002404 WL.push_back(DeclRefExprParts(DR, Parent));
2405}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002406void EnqueueVisitor::VisitDependentScopeDeclRefExpr(
2407 const DependentScopeDeclRefExpr *E) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002408 if (E->hasExplicitTemplateArgs())
2409 AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002410 AddDeclarationNameInfo(E);
2411 AddNestedNameSpecifierLoc(E->getQualifierLoc());
2412}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002413void EnqueueVisitor::VisitDeclStmt(const DeclStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002414 unsigned size = WL.size();
2415 bool isFirst = true;
Aaron Ballman535bbcc2014-03-14 17:01:24 +00002416 for (const auto *D : S->decls()) {
2417 AddDecl(D, isFirst);
Guy Benyei11169dd2012-12-18 14:30:41 +00002418 isFirst = false;
2419 }
2420 if (size == WL.size())
2421 return;
2422 // Now reverse the entries we just added. This will match the DFS
2423 // ordering performed by the worklist.
2424 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2425 std::reverse(I, E);
2426}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002427void EnqueueVisitor::VisitDesignatedInitExpr(const DesignatedInitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002428 AddStmt(E->getInit());
David Majnemerf7e36092016-06-23 00:15:04 +00002429 for (const DesignatedInitExpr::Designator &D :
2430 llvm::reverse(E->designators())) {
2431 if (D.isFieldDesignator()) {
2432 if (FieldDecl *Field = D.getField())
2433 AddMemberRef(Field, D.getFieldLoc());
Guy Benyei11169dd2012-12-18 14:30:41 +00002434 continue;
2435 }
David Majnemerf7e36092016-06-23 00:15:04 +00002436 if (D.isArrayDesignator()) {
2437 AddStmt(E->getArrayIndex(D));
Guy Benyei11169dd2012-12-18 14:30:41 +00002438 continue;
2439 }
David Majnemerf7e36092016-06-23 00:15:04 +00002440 assert(D.isArrayRangeDesignator() && "Unknown designator kind");
2441 AddStmt(E->getArrayRangeEnd(D));
2442 AddStmt(E->getArrayRangeStart(D));
Guy Benyei11169dd2012-12-18 14:30:41 +00002443 }
2444}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002445void EnqueueVisitor::VisitExplicitCastExpr(const ExplicitCastExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002446 EnqueueChildren(E);
2447 AddTypeLoc(E->getTypeInfoAsWritten());
2448}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002449void EnqueueVisitor::VisitForStmt(const ForStmt *FS) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002450 AddStmt(FS->getBody());
2451 AddStmt(FS->getInc());
2452 AddStmt(FS->getCond());
2453 AddDecl(FS->getConditionVariable());
2454 AddStmt(FS->getInit());
2455}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002456void EnqueueVisitor::VisitGotoStmt(const GotoStmt *GS) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002457 WL.push_back(LabelRefVisit(GS->getLabel(), GS->getLabelLoc(), Parent));
2458}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002459void EnqueueVisitor::VisitIfStmt(const IfStmt *If) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002460 AddStmt(If->getElse());
2461 AddStmt(If->getThen());
2462 AddStmt(If->getCond());
2463 AddDecl(If->getConditionVariable());
2464}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002465void EnqueueVisitor::VisitInitListExpr(const InitListExpr *IE) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002466 // We care about the syntactic form of the initializer list, only.
2467 if (InitListExpr *Syntactic = IE->getSyntacticForm())
2468 IE = Syntactic;
2469 EnqueueChildren(IE);
2470}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002471void EnqueueVisitor::VisitMemberExpr(const MemberExpr *M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002472 WL.push_back(MemberExprParts(M, Parent));
2473
2474 // If the base of the member access expression is an implicit 'this', don't
2475 // visit it.
2476 // FIXME: If we ever want to show these implicit accesses, this will be
2477 // unfortunate. However, clang_getCursor() relies on this behavior.
Argyrios Kyrtzidis58d0e7a2015-03-13 04:40:07 +00002478 if (M->isImplicitAccess())
2479 return;
2480
2481 // Ignore base anonymous struct/union fields, otherwise they will shadow the
2482 // real field that that we are interested in.
2483 if (auto *SubME = dyn_cast<MemberExpr>(M->getBase())) {
2484 if (auto *FD = dyn_cast_or_null<FieldDecl>(SubME->getMemberDecl())) {
2485 if (FD->isAnonymousStructOrUnion()) {
2486 AddStmt(SubME->getBase());
2487 return;
2488 }
2489 }
2490 }
2491
2492 AddStmt(M->getBase());
Guy Benyei11169dd2012-12-18 14:30:41 +00002493}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002494void EnqueueVisitor::VisitObjCEncodeExpr(const ObjCEncodeExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002495 AddTypeLoc(E->getEncodedTypeSourceInfo());
2496}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002497void EnqueueVisitor::VisitObjCMessageExpr(const ObjCMessageExpr *M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002498 EnqueueChildren(M);
2499 AddTypeLoc(M->getClassReceiverTypeInfo());
2500}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002501void EnqueueVisitor::VisitOffsetOfExpr(const OffsetOfExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002502 // Visit the components of the offsetof expression.
2503 for (unsigned N = E->getNumComponents(), I = N; I > 0; --I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002504 const OffsetOfNode &Node = E->getComponent(I-1);
2505 switch (Node.getKind()) {
2506 case OffsetOfNode::Array:
2507 AddStmt(E->getIndexExpr(Node.getArrayExprIndex()));
2508 break;
2509 case OffsetOfNode::Field:
2510 AddMemberRef(Node.getField(), Node.getSourceRange().getEnd());
2511 break;
2512 case OffsetOfNode::Identifier:
2513 case OffsetOfNode::Base:
2514 continue;
2515 }
2516 }
2517 // Visit the type into which we're computing the offset.
2518 AddTypeLoc(E->getTypeSourceInfo());
2519}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002520void EnqueueVisitor::VisitOverloadExpr(const OverloadExpr *E) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002521 if (E->hasExplicitTemplateArgs())
2522 AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002523 WL.push_back(OverloadExprParts(E, Parent));
2524}
2525void EnqueueVisitor::VisitUnaryExprOrTypeTraitExpr(
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002526 const UnaryExprOrTypeTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002527 EnqueueChildren(E);
2528 if (E->isArgumentType())
2529 AddTypeLoc(E->getArgumentTypeInfo());
2530}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002531void EnqueueVisitor::VisitStmt(const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002532 EnqueueChildren(S);
2533}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002534void EnqueueVisitor::VisitSwitchStmt(const SwitchStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002535 AddStmt(S->getBody());
2536 AddStmt(S->getCond());
2537 AddDecl(S->getConditionVariable());
2538}
2539
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002540void EnqueueVisitor::VisitWhileStmt(const WhileStmt *W) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002541 AddStmt(W->getBody());
2542 AddStmt(W->getCond());
2543 AddDecl(W->getConditionVariable());
2544}
2545
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002546void EnqueueVisitor::VisitTypeTraitExpr(const TypeTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002547 for (unsigned I = E->getNumArgs(); I > 0; --I)
2548 AddTypeLoc(E->getArg(I-1));
2549}
2550
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002551void EnqueueVisitor::VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002552 AddTypeLoc(E->getQueriedTypeSourceInfo());
2553}
2554
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002555void EnqueueVisitor::VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002556 EnqueueChildren(E);
2557}
2558
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002559void EnqueueVisitor::VisitUnresolvedMemberExpr(const UnresolvedMemberExpr *U) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002560 VisitOverloadExpr(U);
2561 if (!U->isImplicitAccess())
2562 AddStmt(U->getBase());
2563}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002564void EnqueueVisitor::VisitVAArgExpr(const VAArgExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002565 AddStmt(E->getSubExpr());
2566 AddTypeLoc(E->getWrittenTypeInfo());
2567}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002568void EnqueueVisitor::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002569 WL.push_back(SizeOfPackExprParts(E, Parent));
2570}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002571void EnqueueVisitor::VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002572 // If the opaque value has a source expression, just transparently
2573 // visit that. This is useful for (e.g.) pseudo-object expressions.
2574 if (Expr *SourceExpr = E->getSourceExpr())
2575 return Visit(SourceExpr);
2576}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002577void EnqueueVisitor::VisitLambdaExpr(const LambdaExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002578 AddStmt(E->getBody());
2579 WL.push_back(LambdaExprParts(E, Parent));
2580}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002581void EnqueueVisitor::VisitPseudoObjectExpr(const PseudoObjectExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002582 // Treat the expression like its syntactic form.
2583 Visit(E->getSyntacticForm());
2584}
2585
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002586void EnqueueVisitor::VisitOMPExecutableDirective(
2587 const OMPExecutableDirective *D) {
2588 EnqueueChildren(D);
2589 for (ArrayRef<OMPClause *>::iterator I = D->clauses().begin(),
2590 E = D->clauses().end();
2591 I != E; ++I)
2592 EnqueueChildren(*I);
2593}
2594
Alexander Musman3aaab662014-08-19 11:27:13 +00002595void EnqueueVisitor::VisitOMPLoopDirective(const OMPLoopDirective *D) {
2596 VisitOMPExecutableDirective(D);
2597}
2598
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002599void EnqueueVisitor::VisitOMPParallelDirective(const OMPParallelDirective *D) {
2600 VisitOMPExecutableDirective(D);
2601}
2602
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002603void EnqueueVisitor::VisitOMPSimdDirective(const OMPSimdDirective *D) {
Alexander Musman3aaab662014-08-19 11:27:13 +00002604 VisitOMPLoopDirective(D);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002605}
2606
Alexey Bataevf29276e2014-06-18 04:14:57 +00002607void EnqueueVisitor::VisitOMPForDirective(const OMPForDirective *D) {
Alexander Musman3aaab662014-08-19 11:27:13 +00002608 VisitOMPLoopDirective(D);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002609}
2610
Alexander Musmanf82886e2014-09-18 05:12:34 +00002611void EnqueueVisitor::VisitOMPForSimdDirective(const OMPForSimdDirective *D) {
2612 VisitOMPLoopDirective(D);
2613}
2614
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002615void EnqueueVisitor::VisitOMPSectionsDirective(const OMPSectionsDirective *D) {
2616 VisitOMPExecutableDirective(D);
2617}
2618
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002619void EnqueueVisitor::VisitOMPSectionDirective(const OMPSectionDirective *D) {
2620 VisitOMPExecutableDirective(D);
2621}
2622
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00002623void EnqueueVisitor::VisitOMPSingleDirective(const OMPSingleDirective *D) {
2624 VisitOMPExecutableDirective(D);
2625}
2626
Alexander Musman80c22892014-07-17 08:54:58 +00002627void EnqueueVisitor::VisitOMPMasterDirective(const OMPMasterDirective *D) {
2628 VisitOMPExecutableDirective(D);
2629}
2630
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002631void EnqueueVisitor::VisitOMPCriticalDirective(const OMPCriticalDirective *D) {
2632 VisitOMPExecutableDirective(D);
2633 AddDeclarationNameInfo(D);
2634}
2635
Alexey Bataev4acb8592014-07-07 13:01:15 +00002636void
2637EnqueueVisitor::VisitOMPParallelForDirective(const OMPParallelForDirective *D) {
Alexander Musman3aaab662014-08-19 11:27:13 +00002638 VisitOMPLoopDirective(D);
Alexey Bataev4acb8592014-07-07 13:01:15 +00002639}
2640
Alexander Musmane4e893b2014-09-23 09:33:00 +00002641void EnqueueVisitor::VisitOMPParallelForSimdDirective(
2642 const OMPParallelForSimdDirective *D) {
2643 VisitOMPLoopDirective(D);
2644}
2645
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002646void EnqueueVisitor::VisitOMPParallelSectionsDirective(
2647 const OMPParallelSectionsDirective *D) {
2648 VisitOMPExecutableDirective(D);
2649}
2650
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002651void EnqueueVisitor::VisitOMPTaskDirective(const OMPTaskDirective *D) {
2652 VisitOMPExecutableDirective(D);
2653}
2654
Alexey Bataev68446b72014-07-18 07:47:19 +00002655void
2656EnqueueVisitor::VisitOMPTaskyieldDirective(const OMPTaskyieldDirective *D) {
2657 VisitOMPExecutableDirective(D);
2658}
2659
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002660void EnqueueVisitor::VisitOMPBarrierDirective(const OMPBarrierDirective *D) {
2661 VisitOMPExecutableDirective(D);
2662}
2663
Alexey Bataev2df347a2014-07-18 10:17:07 +00002664void EnqueueVisitor::VisitOMPTaskwaitDirective(const OMPTaskwaitDirective *D) {
2665 VisitOMPExecutableDirective(D);
2666}
2667
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002668void EnqueueVisitor::VisitOMPTaskgroupDirective(
2669 const OMPTaskgroupDirective *D) {
2670 VisitOMPExecutableDirective(D);
2671}
2672
Alexey Bataev6125da92014-07-21 11:26:11 +00002673void EnqueueVisitor::VisitOMPFlushDirective(const OMPFlushDirective *D) {
2674 VisitOMPExecutableDirective(D);
2675}
2676
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002677void EnqueueVisitor::VisitOMPOrderedDirective(const OMPOrderedDirective *D) {
2678 VisitOMPExecutableDirective(D);
2679}
2680
Alexey Bataev0162e452014-07-22 10:10:35 +00002681void EnqueueVisitor::VisitOMPAtomicDirective(const OMPAtomicDirective *D) {
2682 VisitOMPExecutableDirective(D);
2683}
2684
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002685void EnqueueVisitor::VisitOMPTargetDirective(const OMPTargetDirective *D) {
2686 VisitOMPExecutableDirective(D);
2687}
2688
Michael Wong65f367f2015-07-21 13:44:28 +00002689void EnqueueVisitor::VisitOMPTargetDataDirective(const
2690 OMPTargetDataDirective *D) {
2691 VisitOMPExecutableDirective(D);
2692}
2693
Samuel Antaodf67fc42016-01-19 19:15:56 +00002694void EnqueueVisitor::VisitOMPTargetEnterDataDirective(
2695 const OMPTargetEnterDataDirective *D) {
2696 VisitOMPExecutableDirective(D);
2697}
2698
Samuel Antao72590762016-01-19 20:04:50 +00002699void EnqueueVisitor::VisitOMPTargetExitDataDirective(
2700 const OMPTargetExitDataDirective *D) {
2701 VisitOMPExecutableDirective(D);
2702}
2703
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00002704void EnqueueVisitor::VisitOMPTargetParallelDirective(
2705 const OMPTargetParallelDirective *D) {
2706 VisitOMPExecutableDirective(D);
2707}
2708
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00002709void EnqueueVisitor::VisitOMPTargetParallelForDirective(
2710 const OMPTargetParallelForDirective *D) {
2711 VisitOMPLoopDirective(D);
2712}
2713
Alexey Bataev13314bf2014-10-09 04:18:56 +00002714void EnqueueVisitor::VisitOMPTeamsDirective(const OMPTeamsDirective *D) {
2715 VisitOMPExecutableDirective(D);
2716}
2717
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002718void EnqueueVisitor::VisitOMPCancellationPointDirective(
2719 const OMPCancellationPointDirective *D) {
2720 VisitOMPExecutableDirective(D);
2721}
2722
Alexey Bataev80909872015-07-02 11:25:17 +00002723void EnqueueVisitor::VisitOMPCancelDirective(const OMPCancelDirective *D) {
2724 VisitOMPExecutableDirective(D);
2725}
2726
Alexey Bataev49f6e782015-12-01 04:18:41 +00002727void EnqueueVisitor::VisitOMPTaskLoopDirective(const OMPTaskLoopDirective *D) {
2728 VisitOMPLoopDirective(D);
2729}
2730
Alexey Bataev0a6ed842015-12-03 09:40:15 +00002731void EnqueueVisitor::VisitOMPTaskLoopSimdDirective(
2732 const OMPTaskLoopSimdDirective *D) {
2733 VisitOMPLoopDirective(D);
2734}
2735
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002736void EnqueueVisitor::VisitOMPDistributeDirective(
2737 const OMPDistributeDirective *D) {
2738 VisitOMPLoopDirective(D);
2739}
2740
Carlo Bertolli9925f152016-06-27 14:55:37 +00002741void EnqueueVisitor::VisitOMPDistributeParallelForDirective(
2742 const OMPDistributeParallelForDirective *D) {
2743 VisitOMPLoopDirective(D);
2744}
2745
Kelvin Li4a39add2016-07-05 05:00:15 +00002746void EnqueueVisitor::VisitOMPDistributeParallelForSimdDirective(
2747 const OMPDistributeParallelForSimdDirective *D) {
2748 VisitOMPLoopDirective(D);
2749}
2750
Kelvin Li787f3fc2016-07-06 04:45:38 +00002751void EnqueueVisitor::VisitOMPDistributeSimdDirective(
2752 const OMPDistributeSimdDirective *D) {
2753 VisitOMPLoopDirective(D);
2754}
2755
Kelvin Lia579b912016-07-14 02:54:56 +00002756void EnqueueVisitor::VisitOMPTargetParallelForSimdDirective(
2757 const OMPTargetParallelForSimdDirective *D) {
2758 VisitOMPLoopDirective(D);
2759}
2760
Kelvin Li986330c2016-07-20 22:57:10 +00002761void EnqueueVisitor::VisitOMPTargetSimdDirective(
2762 const OMPTargetSimdDirective *D) {
2763 VisitOMPLoopDirective(D);
2764}
2765
Kelvin Li02532872016-08-05 14:37:37 +00002766void EnqueueVisitor::VisitOMPTeamsDistributeDirective(
2767 const OMPTeamsDistributeDirective *D) {
2768 VisitOMPLoopDirective(D);
2769}
2770
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002771void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002772 EnqueueVisitor(WL, MakeCXCursor(S, StmtParent, TU,RegionOfInterest)).Visit(S);
2773}
2774
2775bool CursorVisitor::IsInRegionOfInterest(CXCursor C) {
2776 if (RegionOfInterest.isValid()) {
2777 SourceRange Range = getRawCursorExtent(C);
2778 if (Range.isInvalid() || CompareRegionOfInterest(Range))
2779 return false;
2780 }
2781 return true;
2782}
2783
2784bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) {
2785 while (!WL.empty()) {
2786 // Dequeue the worklist item.
Robert Wilhelm25284cc2013-08-23 16:11:15 +00002787 VisitorJob LI = WL.pop_back_val();
Guy Benyei11169dd2012-12-18 14:30:41 +00002788
2789 // Set the Parent field, then back to its old value once we're done.
2790 SetParentRAII SetParent(Parent, StmtParent, LI.getParent());
2791
2792 switch (LI.getKind()) {
2793 case VisitorJob::DeclVisitKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002794 const Decl *D = cast<DeclVisit>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00002795 if (!D)
2796 continue;
2797
2798 // For now, perform default visitation for Decls.
2799 if (Visit(MakeCXCursor(D, TU, RegionOfInterest,
2800 cast<DeclVisit>(&LI)->isFirst())))
2801 return true;
2802
2803 continue;
2804 }
2805 case VisitorJob::ExplicitTemplateArgsVisitKind: {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002806 for (const TemplateArgumentLoc &Arg :
2807 *cast<ExplicitTemplateArgsVisit>(&LI)) {
2808 if (VisitTemplateArgumentLoc(Arg))
Guy Benyei11169dd2012-12-18 14:30:41 +00002809 return true;
2810 }
2811 continue;
2812 }
2813 case VisitorJob::TypeLocVisitKind: {
2814 // Perform default visitation for TypeLocs.
2815 if (Visit(cast<TypeLocVisit>(&LI)->get()))
2816 return true;
2817 continue;
2818 }
2819 case VisitorJob::LabelRefVisitKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002820 const LabelDecl *LS = cast<LabelRefVisit>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00002821 if (LabelStmt *stmt = LS->getStmt()) {
2822 if (Visit(MakeCursorLabelRef(stmt, cast<LabelRefVisit>(&LI)->getLoc(),
2823 TU))) {
2824 return true;
2825 }
2826 }
2827 continue;
2828 }
2829
2830 case VisitorJob::NestedNameSpecifierLocVisitKind: {
2831 NestedNameSpecifierLocVisit *V = cast<NestedNameSpecifierLocVisit>(&LI);
2832 if (VisitNestedNameSpecifierLoc(V->get()))
2833 return true;
2834 continue;
2835 }
2836
2837 case VisitorJob::DeclarationNameInfoVisitKind: {
2838 if (VisitDeclarationNameInfo(cast<DeclarationNameInfoVisit>(&LI)
2839 ->get()))
2840 return true;
2841 continue;
2842 }
2843 case VisitorJob::MemberRefVisitKind: {
2844 MemberRefVisit *V = cast<MemberRefVisit>(&LI);
2845 if (Visit(MakeCursorMemberRef(V->get(), V->getLoc(), TU)))
2846 return true;
2847 continue;
2848 }
2849 case VisitorJob::StmtVisitKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002850 const Stmt *S = cast<StmtVisit>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00002851 if (!S)
2852 continue;
2853
2854 // Update the current cursor.
2855 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU, RegionOfInterest);
2856 if (!IsInRegionOfInterest(Cursor))
2857 continue;
2858 switch (Visitor(Cursor, Parent, ClientData)) {
2859 case CXChildVisit_Break: return true;
2860 case CXChildVisit_Continue: break;
2861 case CXChildVisit_Recurse:
2862 if (PostChildrenVisitor)
Craig Topper69186e72014-06-08 08:38:04 +00002863 WL.push_back(PostChildrenVisit(nullptr, Cursor));
Guy Benyei11169dd2012-12-18 14:30:41 +00002864 EnqueueWorkList(WL, S);
2865 break;
2866 }
2867 continue;
2868 }
2869 case VisitorJob::MemberExprPartsKind: {
2870 // Handle the other pieces in the MemberExpr besides the base.
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002871 const MemberExpr *M = cast<MemberExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00002872
2873 // Visit the nested-name-specifier
2874 if (NestedNameSpecifierLoc QualifierLoc = M->getQualifierLoc())
2875 if (VisitNestedNameSpecifierLoc(QualifierLoc))
2876 return true;
2877
2878 // Visit the declaration name.
2879 if (VisitDeclarationNameInfo(M->getMemberNameInfo()))
2880 return true;
2881
2882 // Visit the explicitly-specified template arguments, if any.
2883 if (M->hasExplicitTemplateArgs()) {
2884 for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(),
2885 *ArgEnd = Arg + M->getNumTemplateArgs();
2886 Arg != ArgEnd; ++Arg) {
2887 if (VisitTemplateArgumentLoc(*Arg))
2888 return true;
2889 }
2890 }
2891 continue;
2892 }
2893 case VisitorJob::DeclRefExprPartsKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002894 const DeclRefExpr *DR = cast<DeclRefExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00002895 // Visit nested-name-specifier, if present.
2896 if (NestedNameSpecifierLoc QualifierLoc = DR->getQualifierLoc())
2897 if (VisitNestedNameSpecifierLoc(QualifierLoc))
2898 return true;
2899 // Visit declaration name.
2900 if (VisitDeclarationNameInfo(DR->getNameInfo()))
2901 return true;
2902 continue;
2903 }
2904 case VisitorJob::OverloadExprPartsKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002905 const OverloadExpr *O = cast<OverloadExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00002906 // Visit the nested-name-specifier.
2907 if (NestedNameSpecifierLoc QualifierLoc = O->getQualifierLoc())
2908 if (VisitNestedNameSpecifierLoc(QualifierLoc))
2909 return true;
2910 // Visit the declaration name.
2911 if (VisitDeclarationNameInfo(O->getNameInfo()))
2912 return true;
2913 // Visit the overloaded declaration reference.
2914 if (Visit(MakeCursorOverloadedDeclRef(O, TU)))
2915 return true;
2916 continue;
2917 }
2918 case VisitorJob::SizeOfPackExprPartsKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002919 const SizeOfPackExpr *E = cast<SizeOfPackExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00002920 NamedDecl *Pack = E->getPack();
2921 if (isa<TemplateTypeParmDecl>(Pack)) {
2922 if (Visit(MakeCursorTypeRef(cast<TemplateTypeParmDecl>(Pack),
2923 E->getPackLoc(), TU)))
2924 return true;
2925
2926 continue;
2927 }
2928
2929 if (isa<TemplateTemplateParmDecl>(Pack)) {
2930 if (Visit(MakeCursorTemplateRef(cast<TemplateTemplateParmDecl>(Pack),
2931 E->getPackLoc(), TU)))
2932 return true;
2933
2934 continue;
2935 }
2936
2937 // Non-type template parameter packs and function parameter packs are
2938 // treated like DeclRefExpr cursors.
2939 continue;
2940 }
2941
2942 case VisitorJob::LambdaExprPartsKind: {
2943 // Visit captures.
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002944 const LambdaExpr *E = cast<LambdaExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00002945 for (LambdaExpr::capture_iterator C = E->explicit_capture_begin(),
2946 CEnd = E->explicit_capture_end();
2947 C != CEnd; ++C) {
Richard Smithba71c082013-05-16 06:20:58 +00002948 // FIXME: Lambda init-captures.
2949 if (!C->capturesVariable())
Guy Benyei11169dd2012-12-18 14:30:41 +00002950 continue;
Richard Smithba71c082013-05-16 06:20:58 +00002951
Guy Benyei11169dd2012-12-18 14:30:41 +00002952 if (Visit(MakeCursorVariableRef(C->getCapturedVar(),
2953 C->getLocation(),
2954 TU)))
2955 return true;
2956 }
2957
2958 // Visit parameters and return type, if present.
2959 if (E->hasExplicitParameters() || E->hasExplicitResultType()) {
2960 TypeLoc TL = E->getCallOperator()->getTypeSourceInfo()->getTypeLoc();
2961 if (E->hasExplicitParameters() && E->hasExplicitResultType()) {
2962 // Visit the whole type.
2963 if (Visit(TL))
2964 return true;
David Blaikie6adc78e2013-02-18 22:06:02 +00002965 } else if (FunctionProtoTypeLoc Proto =
2966 TL.getAs<FunctionProtoTypeLoc>()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002967 if (E->hasExplicitParameters()) {
2968 // Visit parameters.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00002969 for (unsigned I = 0, N = Proto.getNumParams(); I != N; ++I)
2970 if (Visit(MakeCXCursor(Proto.getParam(I), TU)))
Guy Benyei11169dd2012-12-18 14:30:41 +00002971 return true;
2972 } else {
2973 // Visit result type.
Alp Toker42a16a62014-01-25 23:51:36 +00002974 if (Visit(Proto.getReturnLoc()))
Guy Benyei11169dd2012-12-18 14:30:41 +00002975 return true;
2976 }
2977 }
2978 }
2979 break;
2980 }
2981
2982 case VisitorJob::PostChildrenVisitKind:
2983 if (PostChildrenVisitor(Parent, ClientData))
2984 return true;
2985 break;
2986 }
2987 }
2988 return false;
2989}
2990
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002991bool CursorVisitor::Visit(const Stmt *S) {
Craig Topper69186e72014-06-08 08:38:04 +00002992 VisitorWorkList *WL = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00002993 if (!WorkListFreeList.empty()) {
2994 WL = WorkListFreeList.back();
2995 WL->clear();
2996 WorkListFreeList.pop_back();
2997 }
2998 else {
2999 WL = new VisitorWorkList();
3000 WorkListCache.push_back(WL);
3001 }
3002 EnqueueWorkList(*WL, S);
3003 bool result = RunVisitorWorkList(*WL);
3004 WorkListFreeList.push_back(WL);
3005 return result;
3006}
3007
3008namespace {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003009typedef SmallVector<SourceRange, 4> RefNamePieces;
James Y Knight04ec5bf2015-12-24 02:59:37 +00003010RefNamePieces buildPieces(unsigned NameFlags, bool IsMemberRefExpr,
3011 const DeclarationNameInfo &NI, SourceRange QLoc,
3012 const SourceRange *TemplateArgsLoc = nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003013 const bool WantQualifier = NameFlags & CXNameRange_WantQualifier;
3014 const bool WantTemplateArgs = NameFlags & CXNameRange_WantTemplateArgs;
3015 const bool WantSinglePiece = NameFlags & CXNameRange_WantSinglePiece;
3016
3017 const DeclarationName::NameKind Kind = NI.getName().getNameKind();
3018
3019 RefNamePieces Pieces;
3020
3021 if (WantQualifier && QLoc.isValid())
3022 Pieces.push_back(QLoc);
3023
3024 if (Kind != DeclarationName::CXXOperatorName || IsMemberRefExpr)
3025 Pieces.push_back(NI.getLoc());
James Y Knight04ec5bf2015-12-24 02:59:37 +00003026
3027 if (WantTemplateArgs && TemplateArgsLoc && TemplateArgsLoc->isValid())
3028 Pieces.push_back(*TemplateArgsLoc);
3029
Guy Benyei11169dd2012-12-18 14:30:41 +00003030 if (Kind == DeclarationName::CXXOperatorName) {
3031 Pieces.push_back(SourceLocation::getFromRawEncoding(
3032 NI.getInfo().CXXOperatorName.BeginOpNameLoc));
3033 Pieces.push_back(SourceLocation::getFromRawEncoding(
3034 NI.getInfo().CXXOperatorName.EndOpNameLoc));
3035 }
3036
3037 if (WantSinglePiece) {
3038 SourceRange R(Pieces.front().getBegin(), Pieces.back().getEnd());
3039 Pieces.clear();
3040 Pieces.push_back(R);
3041 }
3042
3043 return Pieces;
3044}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003045}
Guy Benyei11169dd2012-12-18 14:30:41 +00003046
3047//===----------------------------------------------------------------------===//
3048// Misc. API hooks.
3049//===----------------------------------------------------------------------===//
3050
Chad Rosier05c71aa2013-03-27 18:28:23 +00003051static void fatal_error_handler(void *user_data, const std::string& reason,
3052 bool gen_crash_diag) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003053 // Write the result out to stderr avoiding errs() because raw_ostreams can
3054 // call report_fatal_error.
3055 fprintf(stderr, "LIBCLANG FATAL ERROR: %s\n", reason.c_str());
3056 ::abort();
3057}
3058
Chandler Carruth66660742014-06-27 16:37:27 +00003059namespace {
3060struct RegisterFatalErrorHandler {
3061 RegisterFatalErrorHandler() {
3062 llvm::install_fatal_error_handler(fatal_error_handler, nullptr);
3063 }
3064};
3065}
3066
3067static llvm::ManagedStatic<RegisterFatalErrorHandler> RegisterFatalErrorHandlerOnce;
3068
Guy Benyei11169dd2012-12-18 14:30:41 +00003069extern "C" {
3070CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
3071 int displayDiagnostics) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003072 // We use crash recovery to make some of our APIs more reliable, implicitly
3073 // enable it.
Argyrios Kyrtzidis3701f542013-11-27 08:58:09 +00003074 if (!getenv("LIBCLANG_DISABLE_CRASH_RECOVERY"))
3075 llvm::CrashRecoveryContext::Enable();
Guy Benyei11169dd2012-12-18 14:30:41 +00003076
Chandler Carruth66660742014-06-27 16:37:27 +00003077 // Look through the managed static to trigger construction of the managed
3078 // static which registers our fatal error handler. This ensures it is only
3079 // registered once.
3080 (void)*RegisterFatalErrorHandlerOnce;
Guy Benyei11169dd2012-12-18 14:30:41 +00003081
Adrian Prantlbc068582015-07-08 01:00:30 +00003082 // Initialize targets for clang module support.
3083 llvm::InitializeAllTargets();
3084 llvm::InitializeAllTargetMCs();
3085 llvm::InitializeAllAsmPrinters();
3086 llvm::InitializeAllAsmParsers();
3087
Adrian Prantlfb2398d2015-07-17 01:19:54 +00003088 CIndexer *CIdxr = new CIndexer();
3089
Guy Benyei11169dd2012-12-18 14:30:41 +00003090 if (excludeDeclarationsFromPCH)
3091 CIdxr->setOnlyLocalDecls();
3092 if (displayDiagnostics)
3093 CIdxr->setDisplayDiagnostics();
3094
3095 if (getenv("LIBCLANG_BGPRIO_INDEX"))
3096 CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() |
3097 CXGlobalOpt_ThreadBackgroundPriorityForIndexing);
3098 if (getenv("LIBCLANG_BGPRIO_EDIT"))
3099 CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() |
3100 CXGlobalOpt_ThreadBackgroundPriorityForEditing);
3101
3102 return CIdxr;
3103}
3104
3105void clang_disposeIndex(CXIndex CIdx) {
3106 if (CIdx)
3107 delete static_cast<CIndexer *>(CIdx);
3108}
3109
3110void clang_CXIndex_setGlobalOptions(CXIndex CIdx, unsigned options) {
3111 if (CIdx)
3112 static_cast<CIndexer *>(CIdx)->setCXGlobalOptFlags(options);
3113}
3114
3115unsigned clang_CXIndex_getGlobalOptions(CXIndex CIdx) {
3116 if (CIdx)
3117 return static_cast<CIndexer *>(CIdx)->getCXGlobalOptFlags();
3118 return 0;
3119}
3120
3121void clang_toggleCrashRecovery(unsigned isEnabled) {
3122 if (isEnabled)
3123 llvm::CrashRecoveryContext::Enable();
3124 else
3125 llvm::CrashRecoveryContext::Disable();
3126}
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003127
Guy Benyei11169dd2012-12-18 14:30:41 +00003128CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
3129 const char *ast_filename) {
Dmitri Gribenko8850cda2014-02-19 10:24:00 +00003130 CXTranslationUnit TU;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003131 enum CXErrorCode Result =
3132 clang_createTranslationUnit2(CIdx, ast_filename, &TU);
Reid Klecknerfd48fc62014-02-12 23:56:20 +00003133 (void)Result;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003134 assert((TU && Result == CXError_Success) ||
3135 (!TU && Result != CXError_Success));
3136 return TU;
3137}
3138
3139enum CXErrorCode clang_createTranslationUnit2(CXIndex CIdx,
3140 const char *ast_filename,
3141 CXTranslationUnit *out_TU) {
Dmitri Gribenko8850cda2014-02-19 10:24:00 +00003142 if (out_TU)
Craig Topper69186e72014-06-08 08:38:04 +00003143 *out_TU = nullptr;
Dmitri Gribenko8850cda2014-02-19 10:24:00 +00003144
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003145 if (!CIdx || !ast_filename || !out_TU)
3146 return CXError_InvalidArguments;
Guy Benyei11169dd2012-12-18 14:30:41 +00003147
Argyrios Kyrtzidis27021012013-05-24 22:24:07 +00003148 LOG_FUNC_SECTION {
3149 *Log << ast_filename;
3150 }
3151
Guy Benyei11169dd2012-12-18 14:30:41 +00003152 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
3153 FileSystemOptions FileSystemOpts;
3154
Justin Bognerd512c1e2014-10-15 00:33:06 +00003155 IntrusiveRefCntPtr<DiagnosticsEngine> Diags =
3156 CompilerInstance::createDiagnostics(new DiagnosticOptions());
David Blaikie6f7382d2014-08-10 19:08:04 +00003157 std::unique_ptr<ASTUnit> AU = ASTUnit::LoadFromASTFile(
Adrian Prantlfb2398d2015-07-17 01:19:54 +00003158 ast_filename, CXXIdx->getPCHContainerOperations()->getRawReader(), Diags,
Adrian Prantl6b21ab22015-08-27 19:46:20 +00003159 FileSystemOpts, /*UseDebugInfo=*/false,
3160 CXXIdx->getOnlyLocalDecls(), None,
David Blaikie6f7382d2014-08-10 19:08:04 +00003161 /*CaptureDiagnostics=*/true,
3162 /*AllowPCHWithCompilerErrors=*/true,
3163 /*UserFilesAreVolatile=*/true);
3164 *out_TU = MakeCXTranslationUnit(CXXIdx, AU.release());
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003165 return *out_TU ? CXError_Success : CXError_Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003166}
3167
3168unsigned clang_defaultEditingTranslationUnitOptions() {
3169 return CXTranslationUnit_PrecompiledPreamble |
3170 CXTranslationUnit_CacheCompletionResults;
3171}
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003172
Guy Benyei11169dd2012-12-18 14:30:41 +00003173CXTranslationUnit
3174clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
3175 const char *source_filename,
3176 int num_command_line_args,
3177 const char * const *command_line_args,
3178 unsigned num_unsaved_files,
3179 struct CXUnsavedFile *unsaved_files) {
3180 unsigned Options = CXTranslationUnit_DetailedPreprocessingRecord;
3181 return clang_parseTranslationUnit(CIdx, source_filename,
3182 command_line_args, num_command_line_args,
3183 unsaved_files, num_unsaved_files,
3184 Options);
3185}
3186
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003187static CXErrorCode
3188clang_parseTranslationUnit_Impl(CXIndex CIdx, const char *source_filename,
3189 const char *const *command_line_args,
3190 int num_command_line_args,
3191 ArrayRef<CXUnsavedFile> unsaved_files,
3192 unsigned options, CXTranslationUnit *out_TU) {
Dmitri Gribenko1bf8d912014-02-18 15:20:02 +00003193 // Set up the initial return values.
3194 if (out_TU)
Craig Topper69186e72014-06-08 08:38:04 +00003195 *out_TU = nullptr;
Dmitri Gribenko1bf8d912014-02-18 15:20:02 +00003196
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003197 // Check arguments.
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003198 if (!CIdx || !out_TU)
3199 return CXError_InvalidArguments;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003200
Guy Benyei11169dd2012-12-18 14:30:41 +00003201 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
3202
3203 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
3204 setThreadBackgroundPriority();
3205
3206 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Benjamin Kramer5c248d82015-12-15 09:30:31 +00003207 bool CreatePreambleOnFirstParse =
3208 options & CXTranslationUnit_CreatePreambleOnFirstParse;
Guy Benyei11169dd2012-12-18 14:30:41 +00003209 // FIXME: Add a flag for modules.
3210 TranslationUnitKind TUKind
3211 = (options & CXTranslationUnit_Incomplete)? TU_Prefix : TU_Complete;
Alp Toker8c8a8752013-12-03 06:53:35 +00003212 bool CacheCodeCompletionResults
Guy Benyei11169dd2012-12-18 14:30:41 +00003213 = options & CXTranslationUnit_CacheCompletionResults;
3214 bool IncludeBriefCommentsInCodeCompletion
3215 = options & CXTranslationUnit_IncludeBriefCommentsInCodeCompletion;
3216 bool SkipFunctionBodies = options & CXTranslationUnit_SkipFunctionBodies;
3217 bool ForSerialization = options & CXTranslationUnit_ForSerialization;
3218
3219 // Configure the diagnostics.
3220 IntrusiveRefCntPtr<DiagnosticsEngine>
Sean Silvaf1b49e22013-01-20 01:58:28 +00003221 Diags(CompilerInstance::createDiagnostics(new DiagnosticOptions));
Guy Benyei11169dd2012-12-18 14:30:41 +00003222
Manuel Klimek016c0242016-03-01 10:56:19 +00003223 if (options & CXTranslationUnit_KeepGoing)
3224 Diags->setFatalsAsError(true);
3225
Guy Benyei11169dd2012-12-18 14:30:41 +00003226 // Recover resources if we crash before exiting this function.
3227 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
3228 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Alp Tokerf994cef2014-07-05 03:08:06 +00003229 DiagCleanup(Diags.get());
Guy Benyei11169dd2012-12-18 14:30:41 +00003230
Ahmed Charlesb8984322014-03-07 20:03:18 +00003231 std::unique_ptr<std::vector<ASTUnit::RemappedFile>> RemappedFiles(
3232 new std::vector<ASTUnit::RemappedFile>());
Guy Benyei11169dd2012-12-18 14:30:41 +00003233
3234 // Recover resources if we crash before exiting this function.
3235 llvm::CrashRecoveryContextCleanupRegistrar<
3236 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
3237
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003238 for (auto &UF : unsaved_files) {
Rafael Espindolad87f8d72014-08-27 20:03:29 +00003239 std::unique_ptr<llvm::MemoryBuffer> MB =
Alp Toker9d85b182014-07-07 01:23:14 +00003240 llvm::MemoryBuffer::getMemBufferCopy(getContents(UF), UF.Filename);
Rafael Espindolad87f8d72014-08-27 20:03:29 +00003241 RemappedFiles->push_back(std::make_pair(UF.Filename, MB.release()));
Guy Benyei11169dd2012-12-18 14:30:41 +00003242 }
3243
Ahmed Charlesb8984322014-03-07 20:03:18 +00003244 std::unique_ptr<std::vector<const char *>> Args(
3245 new std::vector<const char *>());
Guy Benyei11169dd2012-12-18 14:30:41 +00003246
3247 // Recover resources if we crash before exiting this method.
3248 llvm::CrashRecoveryContextCleanupRegistrar<std::vector<const char*> >
3249 ArgsCleanup(Args.get());
3250
3251 // Since the Clang C library is primarily used by batch tools dealing with
3252 // (often very broken) source code, where spell-checking can have a
3253 // significant negative impact on performance (particularly when
3254 // precompiled headers are involved), we disable it by default.
3255 // Only do this if we haven't found a spell-checking-related argument.
3256 bool FoundSpellCheckingArgument = false;
3257 for (int I = 0; I != num_command_line_args; ++I) {
3258 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
3259 strcmp(command_line_args[I], "-fspell-checking") == 0) {
3260 FoundSpellCheckingArgument = true;
3261 break;
3262 }
3263 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003264 Args->insert(Args->end(), command_line_args,
3265 command_line_args + num_command_line_args);
3266
Benjamin Kramerc02670e2015-11-18 16:14:27 +00003267 if (!FoundSpellCheckingArgument)
3268 Args->insert(Args->begin() + 1, "-fno-spell-checking");
3269
Guy Benyei11169dd2012-12-18 14:30:41 +00003270 // The 'source_filename' argument is optional. If the caller does not
3271 // specify it then it is assumed that the source file is specified
3272 // in the actual argument list.
3273 // Put the source file after command_line_args otherwise if '-x' flag is
3274 // present it will be unused.
3275 if (source_filename)
3276 Args->push_back(source_filename);
3277
3278 // Do we need the detailed preprocessing record?
3279 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
3280 Args->push_back("-Xclang");
3281 Args->push_back("-detailed-preprocessing-record");
3282 }
3283
3284 unsigned NumErrors = Diags->getClient()->getNumErrors();
Ahmed Charlesb8984322014-03-07 20:03:18 +00003285 std::unique_ptr<ASTUnit> ErrUnit;
Benjamin Kramer5c248d82015-12-15 09:30:31 +00003286 // Unless the user specified that they want the preamble on the first parse
3287 // set it up to be created on the first reparse. This makes the first parse
3288 // faster, trading for a slower (first) reparse.
3289 unsigned PrecompilePreambleAfterNParses =
3290 !PrecompilePreamble ? 0 : 2 - CreatePreambleOnFirstParse;
Ahmed Charlesb8984322014-03-07 20:03:18 +00003291 std::unique_ptr<ASTUnit> Unit(ASTUnit::LoadFromCommandLine(
Adrian Prantlbb165fb2015-06-20 18:53:08 +00003292 Args->data(), Args->data() + Args->size(),
3293 CXXIdx->getPCHContainerOperations(), Diags,
Ahmed Charlesb8984322014-03-07 20:03:18 +00003294 CXXIdx->getClangResourcesPath(), CXXIdx->getOnlyLocalDecls(),
3295 /*CaptureDiagnostics=*/true, *RemappedFiles.get(),
Benjamin Kramer5c248d82015-12-15 09:30:31 +00003296 /*RemappedFilesKeepOriginalName=*/true, PrecompilePreambleAfterNParses,
3297 TUKind, CacheCodeCompletionResults, IncludeBriefCommentsInCodeCompletion,
Ahmed Charlesb8984322014-03-07 20:03:18 +00003298 /*AllowPCHWithCompilerErrors=*/true, SkipFunctionBodies,
Argyrios Kyrtzidisa3e2ff12015-11-20 03:36:21 +00003299 /*UserFilesAreVolatile=*/true, ForSerialization,
3300 CXXIdx->getPCHContainerOperations()->getRawReader().getFormat(),
3301 &ErrUnit));
Guy Benyei11169dd2012-12-18 14:30:41 +00003302
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003303 // Early failures in LoadFromCommandLine may return with ErrUnit unset.
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003304 if (!Unit && !ErrUnit)
3305 return CXError_ASTReadError;
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003306
Guy Benyei11169dd2012-12-18 14:30:41 +00003307 if (NumErrors != Diags->getClient()->getNumErrors()) {
3308 // Make sure to check that 'Unit' is non-NULL.
3309 if (CXXIdx->getDisplayDiagnostics())
3310 printDiagsToStderr(Unit ? Unit.get() : ErrUnit.get());
3311 }
3312
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003313 if (isASTReadError(Unit ? Unit.get() : ErrUnit.get()))
3314 return CXError_ASTReadError;
3315
3316 *out_TU = MakeCXTranslationUnit(CXXIdx, Unit.release());
3317 return *out_TU ? CXError_Success : CXError_Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003318}
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003319
3320CXTranslationUnit
3321clang_parseTranslationUnit(CXIndex CIdx,
3322 const char *source_filename,
3323 const char *const *command_line_args,
3324 int num_command_line_args,
3325 struct CXUnsavedFile *unsaved_files,
3326 unsigned num_unsaved_files,
3327 unsigned options) {
3328 CXTranslationUnit TU;
3329 enum CXErrorCode Result = clang_parseTranslationUnit2(
3330 CIdx, source_filename, command_line_args, num_command_line_args,
3331 unsaved_files, num_unsaved_files, options, &TU);
Reid Kleckner6eaf05a2014-02-13 01:19:59 +00003332 (void)Result;
Dmitri Gribenko1bf8d912014-02-18 15:20:02 +00003333 assert((TU && Result == CXError_Success) ||
3334 (!TU && Result != CXError_Success));
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003335 return TU;
3336}
3337
3338enum CXErrorCode clang_parseTranslationUnit2(
Benjamin Kramerc02670e2015-11-18 16:14:27 +00003339 CXIndex CIdx, const char *source_filename,
3340 const char *const *command_line_args, int num_command_line_args,
3341 struct CXUnsavedFile *unsaved_files, unsigned num_unsaved_files,
3342 unsigned options, CXTranslationUnit *out_TU) {
3343 SmallVector<const char *, 4> Args;
3344 Args.push_back("clang");
3345 Args.append(command_line_args, command_line_args + num_command_line_args);
3346 return clang_parseTranslationUnit2FullArgv(
3347 CIdx, source_filename, Args.data(), Args.size(), unsaved_files,
3348 num_unsaved_files, options, out_TU);
3349}
3350
3351enum CXErrorCode clang_parseTranslationUnit2FullArgv(
3352 CXIndex CIdx, const char *source_filename,
3353 const char *const *command_line_args, int num_command_line_args,
3354 struct CXUnsavedFile *unsaved_files, unsigned num_unsaved_files,
3355 unsigned options, CXTranslationUnit *out_TU) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00003356 LOG_FUNC_SECTION {
3357 *Log << source_filename << ": ";
3358 for (int i = 0; i != num_command_line_args; ++i)
3359 *Log << command_line_args[i] << " ";
3360 }
3361
Alp Toker9d85b182014-07-07 01:23:14 +00003362 if (num_unsaved_files && !unsaved_files)
3363 return CXError_InvalidArguments;
3364
Alp Toker5c532982014-07-07 22:42:03 +00003365 CXErrorCode result = CXError_Failure;
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003366 auto ParseTranslationUnitImpl = [=, &result] {
3367 result = clang_parseTranslationUnit_Impl(
3368 CIdx, source_filename, command_line_args, num_command_line_args,
3369 llvm::makeArrayRef(unsaved_files, num_unsaved_files), options, out_TU);
3370 };
Guy Benyei11169dd2012-12-18 14:30:41 +00003371 llvm::CrashRecoveryContext CRC;
3372
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003373 if (!RunSafely(CRC, ParseTranslationUnitImpl)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003374 fprintf(stderr, "libclang: crash detected during parsing: {\n");
3375 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
3376 fprintf(stderr, " 'command_line_args' : [");
3377 for (int i = 0; i != num_command_line_args; ++i) {
3378 if (i)
3379 fprintf(stderr, ", ");
3380 fprintf(stderr, "'%s'", command_line_args[i]);
3381 }
3382 fprintf(stderr, "],\n");
3383 fprintf(stderr, " 'unsaved_files' : [");
3384 for (unsigned i = 0; i != num_unsaved_files; ++i) {
3385 if (i)
3386 fprintf(stderr, ", ");
3387 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
3388 unsaved_files[i].Length);
3389 }
3390 fprintf(stderr, "],\n");
3391 fprintf(stderr, " 'options' : %d,\n", options);
3392 fprintf(stderr, "}\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003393
3394 return CXError_Crashed;
Guy Benyei11169dd2012-12-18 14:30:41 +00003395 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003396 if (CXTranslationUnit *TU = out_TU)
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003397 PrintLibclangResourceUsage(*TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00003398 }
Alp Toker5c532982014-07-07 22:42:03 +00003399
3400 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003401}
3402
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003403CXString clang_Type_getObjCEncoding(CXType CT) {
3404 CXTranslationUnit tu = static_cast<CXTranslationUnit>(CT.data[1]);
3405 ASTContext &Ctx = getASTUnit(tu)->getASTContext();
3406 std::string encoding;
3407 Ctx.getObjCEncodingForType(QualType::getFromOpaquePtr(CT.data[0]),
3408 encoding);
3409
3410 return cxstring::createDup(encoding);
3411}
3412
3413static const IdentifierInfo *getMacroIdentifier(CXCursor C) {
3414 if (C.kind == CXCursor_MacroDefinition) {
3415 if (const MacroDefinitionRecord *MDR = getCursorMacroDefinition(C))
3416 return MDR->getName();
3417 } else if (C.kind == CXCursor_MacroExpansion) {
3418 MacroExpansionCursor ME = getCursorMacroExpansion(C);
3419 return ME.getName();
3420 }
3421 return nullptr;
3422}
3423
3424unsigned clang_Cursor_isMacroFunctionLike(CXCursor C) {
3425 const IdentifierInfo *II = getMacroIdentifier(C);
3426 if (!II) {
3427 return false;
3428 }
3429 ASTUnit *ASTU = getCursorASTUnit(C);
3430 Preprocessor &PP = ASTU->getPreprocessor();
3431 if (const MacroInfo *MI = PP.getMacroInfo(II))
3432 return MI->isFunctionLike();
3433 return false;
3434}
3435
3436unsigned clang_Cursor_isMacroBuiltin(CXCursor C) {
3437 const IdentifierInfo *II = getMacroIdentifier(C);
3438 if (!II) {
3439 return false;
3440 }
3441 ASTUnit *ASTU = getCursorASTUnit(C);
3442 Preprocessor &PP = ASTU->getPreprocessor();
3443 if (const MacroInfo *MI = PP.getMacroInfo(II))
3444 return MI->isBuiltinMacro();
3445 return false;
3446}
3447
3448unsigned clang_Cursor_isFunctionInlined(CXCursor C) {
3449 const Decl *D = getCursorDecl(C);
3450 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
3451 if (!FD) {
3452 return false;
3453 }
3454 return FD->isInlined();
3455}
3456
3457static StringLiteral* getCFSTR_value(CallExpr *callExpr) {
3458 if (callExpr->getNumArgs() != 1) {
3459 return nullptr;
3460 }
3461
3462 StringLiteral *S = nullptr;
3463 auto *arg = callExpr->getArg(0);
3464 if (arg->getStmtClass() == Stmt::ImplicitCastExprClass) {
3465 ImplicitCastExpr *I = static_cast<ImplicitCastExpr *>(arg);
3466 auto *subExpr = I->getSubExprAsWritten();
3467
3468 if(subExpr->getStmtClass() != Stmt::StringLiteralClass){
3469 return nullptr;
3470 }
3471
3472 S = static_cast<StringLiteral *>(I->getSubExprAsWritten());
3473 } else if (arg->getStmtClass() == Stmt::StringLiteralClass) {
3474 S = static_cast<StringLiteral *>(callExpr->getArg(0));
3475 } else {
3476 return nullptr;
3477 }
3478 return S;
3479}
3480
David Blaikie59272572016-04-13 18:23:33 +00003481struct ExprEvalResult {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003482 CXEvalResultKind EvalType;
3483 union {
3484 int intVal;
3485 double floatVal;
3486 char *stringVal;
3487 } EvalData;
David Blaikie59272572016-04-13 18:23:33 +00003488 ~ExprEvalResult() {
3489 if (EvalType != CXEval_UnExposed && EvalType != CXEval_Float &&
3490 EvalType != CXEval_Int) {
3491 delete EvalData.stringVal;
3492 }
3493 }
3494};
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003495
3496void clang_EvalResult_dispose(CXEvalResult E) {
David Blaikie59272572016-04-13 18:23:33 +00003497 delete static_cast<ExprEvalResult *>(E);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003498}
3499
3500CXEvalResultKind clang_EvalResult_getKind(CXEvalResult E) {
3501 if (!E) {
3502 return CXEval_UnExposed;
3503 }
3504 return ((ExprEvalResult *)E)->EvalType;
3505}
3506
3507int clang_EvalResult_getAsInt(CXEvalResult E) {
3508 if (!E) {
3509 return 0;
3510 }
3511 return ((ExprEvalResult *)E)->EvalData.intVal;
3512}
3513
3514double clang_EvalResult_getAsDouble(CXEvalResult E) {
3515 if (!E) {
3516 return 0;
3517 }
3518 return ((ExprEvalResult *)E)->EvalData.floatVal;
3519}
3520
3521const char* clang_EvalResult_getAsStr(CXEvalResult E) {
3522 if (!E) {
3523 return nullptr;
3524 }
3525 return ((ExprEvalResult *)E)->EvalData.stringVal;
3526}
3527
3528static const ExprEvalResult* evaluateExpr(Expr *expr, CXCursor C) {
3529 Expr::EvalResult ER;
3530 ASTContext &ctx = getCursorContext(C);
David Blaikiebbc00882016-04-13 18:36:19 +00003531 if (!expr)
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003532 return nullptr;
David Blaikiebbc00882016-04-13 18:36:19 +00003533
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003534 expr = expr->IgnoreParens();
David Blaikiebbc00882016-04-13 18:36:19 +00003535 if (!expr->EvaluateAsRValue(ER, ctx))
3536 return nullptr;
3537
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003538 QualType rettype;
3539 CallExpr *callExpr;
David Blaikie59272572016-04-13 18:23:33 +00003540 auto result = llvm::make_unique<ExprEvalResult>();
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003541 result->EvalType = CXEval_UnExposed;
3542
David Blaikiebbc00882016-04-13 18:36:19 +00003543 if (ER.Val.isInt()) {
3544 result->EvalType = CXEval_Int;
3545 result->EvalData.intVal = ER.Val.getInt().getExtValue();
3546 return result.release();
3547 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003548
David Blaikiebbc00882016-04-13 18:36:19 +00003549 if (ER.Val.isFloat()) {
3550 llvm::SmallVector<char, 100> Buffer;
3551 ER.Val.getFloat().toString(Buffer);
3552 std::string floatStr(Buffer.data(), Buffer.size());
3553 result->EvalType = CXEval_Float;
3554 bool ignored;
3555 llvm::APFloat apFloat = ER.Val.getFloat();
3556 apFloat.convert(llvm::APFloat::IEEEdouble,
3557 llvm::APFloat::rmNearestTiesToEven, &ignored);
3558 result->EvalData.floatVal = apFloat.convertToDouble();
3559 return result.release();
3560 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003561
David Blaikiebbc00882016-04-13 18:36:19 +00003562 if (expr->getStmtClass() == Stmt::ImplicitCastExprClass) {
3563 const ImplicitCastExpr *I = dyn_cast<ImplicitCastExpr>(expr);
3564 auto *subExpr = I->getSubExprAsWritten();
3565 if (subExpr->getStmtClass() == Stmt::StringLiteralClass ||
3566 subExpr->getStmtClass() == Stmt::ObjCStringLiteralClass) {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003567 const StringLiteral *StrE = nullptr;
3568 const ObjCStringLiteral *ObjCExpr;
David Blaikiebbc00882016-04-13 18:36:19 +00003569 ObjCExpr = dyn_cast<ObjCStringLiteral>(subExpr);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003570
3571 if (ObjCExpr) {
3572 StrE = ObjCExpr->getString();
3573 result->EvalType = CXEval_ObjCStrLiteral;
3574 } else {
David Blaikiebbc00882016-04-13 18:36:19 +00003575 StrE = cast<StringLiteral>(I->getSubExprAsWritten());
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003576 result->EvalType = CXEval_StrLiteral;
3577 }
3578
3579 std::string strRef(StrE->getString().str());
David Blaikie59272572016-04-13 18:23:33 +00003580 result->EvalData.stringVal = new char[strRef.size() + 1];
David Blaikiebbc00882016-04-13 18:36:19 +00003581 strncpy((char *)result->EvalData.stringVal, strRef.c_str(),
3582 strRef.size());
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003583 result->EvalData.stringVal[strRef.size()] = '\0';
David Blaikie59272572016-04-13 18:23:33 +00003584 return result.release();
David Blaikiebbc00882016-04-13 18:36:19 +00003585 }
3586 } else if (expr->getStmtClass() == Stmt::ObjCStringLiteralClass ||
3587 expr->getStmtClass() == Stmt::StringLiteralClass) {
3588 const StringLiteral *StrE = nullptr;
3589 const ObjCStringLiteral *ObjCExpr;
3590 ObjCExpr = dyn_cast<ObjCStringLiteral>(expr);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003591
David Blaikiebbc00882016-04-13 18:36:19 +00003592 if (ObjCExpr) {
3593 StrE = ObjCExpr->getString();
3594 result->EvalType = CXEval_ObjCStrLiteral;
3595 } else {
3596 StrE = cast<StringLiteral>(expr);
3597 result->EvalType = CXEval_StrLiteral;
3598 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003599
David Blaikiebbc00882016-04-13 18:36:19 +00003600 std::string strRef(StrE->getString().str());
3601 result->EvalData.stringVal = new char[strRef.size() + 1];
3602 strncpy((char *)result->EvalData.stringVal, strRef.c_str(), strRef.size());
3603 result->EvalData.stringVal[strRef.size()] = '\0';
3604 return result.release();
3605 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003606
David Blaikiebbc00882016-04-13 18:36:19 +00003607 if (expr->getStmtClass() == Stmt::CStyleCastExprClass) {
3608 CStyleCastExpr *CC = static_cast<CStyleCastExpr *>(expr);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003609
David Blaikiebbc00882016-04-13 18:36:19 +00003610 rettype = CC->getType();
3611 if (rettype.getAsString() == "CFStringRef" &&
3612 CC->getSubExpr()->getStmtClass() == Stmt::CallExprClass) {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003613
David Blaikiebbc00882016-04-13 18:36:19 +00003614 callExpr = static_cast<CallExpr *>(CC->getSubExpr());
3615 StringLiteral *S = getCFSTR_value(callExpr);
3616 if (S) {
3617 std::string strLiteral(S->getString().str());
3618 result->EvalType = CXEval_CFStr;
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003619
David Blaikiebbc00882016-04-13 18:36:19 +00003620 result->EvalData.stringVal = new char[strLiteral.size() + 1];
3621 strncpy((char *)result->EvalData.stringVal, strLiteral.c_str(),
3622 strLiteral.size());
3623 result->EvalData.stringVal[strLiteral.size()] = '\0';
David Blaikie59272572016-04-13 18:23:33 +00003624 return result.release();
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003625 }
3626 }
3627
David Blaikiebbc00882016-04-13 18:36:19 +00003628 } else if (expr->getStmtClass() == Stmt::CallExprClass) {
3629 callExpr = static_cast<CallExpr *>(expr);
3630 rettype = callExpr->getCallReturnType(ctx);
3631
3632 if (rettype->isVectorType() || callExpr->getNumArgs() > 1)
3633 return nullptr;
3634
3635 if (rettype->isIntegralType(ctx) || rettype->isRealFloatingType()) {
3636 if (callExpr->getNumArgs() == 1 &&
3637 !callExpr->getArg(0)->getType()->isIntegralType(ctx))
3638 return nullptr;
3639 } else if (rettype.getAsString() == "CFStringRef") {
3640
3641 StringLiteral *S = getCFSTR_value(callExpr);
3642 if (S) {
3643 std::string strLiteral(S->getString().str());
3644 result->EvalType = CXEval_CFStr;
3645 result->EvalData.stringVal = new char[strLiteral.size() + 1];
3646 strncpy((char *)result->EvalData.stringVal, strLiteral.c_str(),
3647 strLiteral.size());
3648 result->EvalData.stringVal[strLiteral.size()] = '\0';
3649 return result.release();
3650 }
3651 }
3652 } else if (expr->getStmtClass() == Stmt::DeclRefExprClass) {
3653 DeclRefExpr *D = static_cast<DeclRefExpr *>(expr);
3654 ValueDecl *V = D->getDecl();
3655 if (V->getKind() == Decl::Function) {
3656 std::string strName = V->getNameAsString();
3657 result->EvalType = CXEval_Other;
3658 result->EvalData.stringVal = new char[strName.size() + 1];
3659 strncpy(result->EvalData.stringVal, strName.c_str(), strName.size());
3660 result->EvalData.stringVal[strName.size()] = '\0';
3661 return result.release();
3662 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003663 }
3664
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003665 return nullptr;
3666}
3667
3668CXEvalResult clang_Cursor_Evaluate(CXCursor C) {
3669 const Decl *D = getCursorDecl(C);
3670 if (D) {
3671 const Expr *expr = nullptr;
3672 if (auto *Var = dyn_cast<VarDecl>(D)) {
3673 expr = Var->getInit();
3674 } else if (auto *Field = dyn_cast<FieldDecl>(D)) {
3675 expr = Field->getInClassInitializer();
3676 }
3677 if (expr)
Aaron Ballman01dc1572016-01-20 15:25:30 +00003678 return const_cast<CXEvalResult>(reinterpret_cast<const void *>(
3679 evaluateExpr(const_cast<Expr *>(expr), C)));
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003680 return nullptr;
3681 }
3682
3683 const CompoundStmt *compoundStmt = dyn_cast_or_null<CompoundStmt>(getCursorStmt(C));
3684 if (compoundStmt) {
3685 Expr *expr = nullptr;
3686 for (auto *bodyIterator : compoundStmt->body()) {
3687 if ((expr = dyn_cast<Expr>(bodyIterator))) {
3688 break;
3689 }
3690 }
3691 if (expr)
Aaron Ballman01dc1572016-01-20 15:25:30 +00003692 return const_cast<CXEvalResult>(
3693 reinterpret_cast<const void *>(evaluateExpr(expr, C)));
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003694 }
3695 return nullptr;
3696}
3697
3698unsigned clang_Cursor_hasAttrs(CXCursor C) {
3699 const Decl *D = getCursorDecl(C);
3700 if (!D) {
3701 return 0;
3702 }
3703
3704 if (D->hasAttrs()) {
3705 return 1;
3706 }
3707
3708 return 0;
3709}
Guy Benyei11169dd2012-12-18 14:30:41 +00003710unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
3711 return CXSaveTranslationUnit_None;
3712}
3713
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003714static CXSaveError clang_saveTranslationUnit_Impl(CXTranslationUnit TU,
3715 const char *FileName,
3716 unsigned options) {
3717 CIndexer *CXXIdx = TU->CIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00003718 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
3719 setThreadBackgroundPriority();
3720
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003721 bool hadError = cxtu::getASTUnit(TU)->Save(FileName);
3722 return hadError ? CXSaveError_Unknown : CXSaveError_None;
Guy Benyei11169dd2012-12-18 14:30:41 +00003723}
3724
3725int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
3726 unsigned options) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00003727 LOG_FUNC_SECTION {
3728 *Log << TU << ' ' << FileName;
3729 }
3730
Dmitri Gribenko852d6222014-02-11 15:02:48 +00003731 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00003732 LOG_BAD_TU(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00003733 return CXSaveError_InvalidTU;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00003734 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003735
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00003736 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00003737 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3738 if (!CXXUnit->hasSema())
3739 return CXSaveError_InvalidTU;
3740
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003741 CXSaveError result;
3742 auto SaveTranslationUnitImpl = [=, &result]() {
3743 result = clang_saveTranslationUnit_Impl(TU, FileName, options);
3744 };
Guy Benyei11169dd2012-12-18 14:30:41 +00003745
3746 if (!CXXUnit->getDiagnostics().hasUnrecoverableErrorOccurred() ||
3747 getenv("LIBCLANG_NOTHREADS")) {
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003748 SaveTranslationUnitImpl();
Guy Benyei11169dd2012-12-18 14:30:41 +00003749
3750 if (getenv("LIBCLANG_RESOURCE_USAGE"))
3751 PrintLibclangResourceUsage(TU);
3752
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003753 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003754 }
3755
3756 // We have an AST that has invalid nodes due to compiler errors.
3757 // Use a crash recovery thread for protection.
3758
3759 llvm::CrashRecoveryContext CRC;
3760
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003761 if (!RunSafely(CRC, SaveTranslationUnitImpl)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003762 fprintf(stderr, "libclang: crash detected during AST saving: {\n");
3763 fprintf(stderr, " 'filename' : '%s'\n", FileName);
3764 fprintf(stderr, " 'options' : %d,\n", options);
3765 fprintf(stderr, "}\n");
3766
3767 return CXSaveError_Unknown;
3768
3769 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
3770 PrintLibclangResourceUsage(TU);
3771 }
3772
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003773 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003774}
3775
3776void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
3777 if (CTUnit) {
3778 // If the translation unit has been marked as unsafe to free, just discard
3779 // it.
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003780 ASTUnit *Unit = cxtu::getASTUnit(CTUnit);
3781 if (Unit && Unit->isUnsafeToFree())
Guy Benyei11169dd2012-12-18 14:30:41 +00003782 return;
3783
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00003784 delete cxtu::getASTUnit(CTUnit);
Dmitri Gribenkob95b3f12013-01-26 22:44:19 +00003785 delete CTUnit->StringPool;
Guy Benyei11169dd2012-12-18 14:30:41 +00003786 delete static_cast<CXDiagnosticSetImpl *>(CTUnit->Diagnostics);
3787 disposeOverridenCXCursorsPool(CTUnit->OverridenCursorsPool);
Dmitri Gribenko9e605112013-11-13 22:16:51 +00003788 delete CTUnit->CommentToXML;
Guy Benyei11169dd2012-12-18 14:30:41 +00003789 delete CTUnit;
3790 }
3791}
3792
3793unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
3794 return CXReparse_None;
3795}
3796
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003797static CXErrorCode
3798clang_reparseTranslationUnit_Impl(CXTranslationUnit TU,
3799 ArrayRef<CXUnsavedFile> unsaved_files,
3800 unsigned options) {
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003801 // Check arguments.
Dmitri Gribenko852d6222014-02-11 15:02:48 +00003802 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00003803 LOG_BAD_TU(TU);
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003804 return CXError_InvalidArguments;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003805 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003806
3807 // Reset the associated diagnostics.
3808 delete static_cast<CXDiagnosticSetImpl*>(TU->Diagnostics);
Craig Topper69186e72014-06-08 08:38:04 +00003809 TU->Diagnostics = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00003810
Dmitri Gribenko183436e2013-01-26 21:49:50 +00003811 CIndexer *CXXIdx = TU->CIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00003812 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing))
3813 setThreadBackgroundPriority();
3814
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00003815 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00003816 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ahmed Charlesb8984322014-03-07 20:03:18 +00003817
3818 std::unique_ptr<std::vector<ASTUnit::RemappedFile>> RemappedFiles(
3819 new std::vector<ASTUnit::RemappedFile>());
3820
Guy Benyei11169dd2012-12-18 14:30:41 +00003821 // Recover resources if we crash before exiting this function.
3822 llvm::CrashRecoveryContextCleanupRegistrar<
3823 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
Alp Toker9d85b182014-07-07 01:23:14 +00003824
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003825 for (auto &UF : unsaved_files) {
Rafael Espindolad87f8d72014-08-27 20:03:29 +00003826 std::unique_ptr<llvm::MemoryBuffer> MB =
Alp Toker9d85b182014-07-07 01:23:14 +00003827 llvm::MemoryBuffer::getMemBufferCopy(getContents(UF), UF.Filename);
Rafael Espindolad87f8d72014-08-27 20:03:29 +00003828 RemappedFiles->push_back(std::make_pair(UF.Filename, MB.release()));
Guy Benyei11169dd2012-12-18 14:30:41 +00003829 }
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003830
Adrian Prantlbb165fb2015-06-20 18:53:08 +00003831 if (!CXXUnit->Reparse(CXXIdx->getPCHContainerOperations(),
3832 *RemappedFiles.get()))
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003833 return CXError_Success;
3834 if (isASTReadError(CXXUnit))
3835 return CXError_ASTReadError;
3836 return CXError_Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003837}
3838
3839int clang_reparseTranslationUnit(CXTranslationUnit TU,
3840 unsigned num_unsaved_files,
3841 struct CXUnsavedFile *unsaved_files,
3842 unsigned options) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00003843 LOG_FUNC_SECTION {
3844 *Log << TU;
3845 }
3846
Alp Toker9d85b182014-07-07 01:23:14 +00003847 if (num_unsaved_files && !unsaved_files)
3848 return CXError_InvalidArguments;
3849
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003850 CXErrorCode result;
3851 auto ReparseTranslationUnitImpl = [=, &result]() {
3852 result = clang_reparseTranslationUnit_Impl(
3853 TU, llvm::makeArrayRef(unsaved_files, num_unsaved_files), options);
3854 };
Guy Benyei11169dd2012-12-18 14:30:41 +00003855
3856 if (getenv("LIBCLANG_NOTHREADS")) {
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003857 ReparseTranslationUnitImpl();
Alp Toker5c532982014-07-07 22:42:03 +00003858 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003859 }
3860
3861 llvm::CrashRecoveryContext CRC;
3862
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003863 if (!RunSafely(CRC, ReparseTranslationUnitImpl)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003864 fprintf(stderr, "libclang: crash detected during reparsing\n");
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00003865 cxtu::getASTUnit(TU)->setUnsafeToFree(true);
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003866 return CXError_Crashed;
Guy Benyei11169dd2012-12-18 14:30:41 +00003867 } else if (getenv("LIBCLANG_RESOURCE_USAGE"))
3868 PrintLibclangResourceUsage(TU);
3869
Alp Toker5c532982014-07-07 22:42:03 +00003870 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003871}
3872
3873
3874CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00003875 if (isNotUsableTU(CTUnit)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00003876 LOG_BAD_TU(CTUnit);
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00003877 return cxstring::createEmpty();
Dmitri Gribenko256454f2014-02-11 14:34:14 +00003878 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003879
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00003880 ASTUnit *CXXUnit = cxtu::getASTUnit(CTUnit);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00003881 return cxstring::createDup(CXXUnit->getOriginalSourceFileName());
Guy Benyei11169dd2012-12-18 14:30:41 +00003882}
3883
3884CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00003885 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00003886 LOG_BAD_TU(TU);
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00003887 return clang_getNullCursor();
Dmitri Gribenko256454f2014-02-11 14:34:14 +00003888 }
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00003889
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00003890 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00003891 return MakeCXCursor(CXXUnit->getASTContext().getTranslationUnitDecl(), TU);
3892}
3893
3894} // end: extern "C"
3895
3896//===----------------------------------------------------------------------===//
3897// CXFile Operations.
3898//===----------------------------------------------------------------------===//
3899
3900extern "C" {
3901CXString clang_getFileName(CXFile SFile) {
3902 if (!SFile)
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00003903 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00003904
3905 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00003906 return cxstring::createRef(FEnt->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00003907}
3908
3909time_t clang_getFileTime(CXFile SFile) {
3910 if (!SFile)
3911 return 0;
3912
3913 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
3914 return FEnt->getModificationTime();
3915}
3916
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00003917CXFile clang_getFile(CXTranslationUnit TU, const char *file_name) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00003918 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00003919 LOG_BAD_TU(TU);
Craig Topper69186e72014-06-08 08:38:04 +00003920 return nullptr;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00003921 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003922
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00003923 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00003924
3925 FileManager &FMgr = CXXUnit->getFileManager();
3926 return const_cast<FileEntry *>(FMgr.getFile(file_name));
3927}
3928
Dmitri Gribenko256454f2014-02-11 14:34:14 +00003929unsigned clang_isFileMultipleIncludeGuarded(CXTranslationUnit TU,
3930 CXFile file) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00003931 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00003932 LOG_BAD_TU(TU);
3933 return 0;
3934 }
3935
3936 if (!file)
Guy Benyei11169dd2012-12-18 14:30:41 +00003937 return 0;
3938
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00003939 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00003940 FileEntry *FEnt = static_cast<FileEntry *>(file);
3941 return CXXUnit->getPreprocessor().getHeaderSearchInfo()
3942 .isFileMultipleIncludeGuarded(FEnt);
3943}
3944
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00003945int clang_getFileUniqueID(CXFile file, CXFileUniqueID *outID) {
3946 if (!file || !outID)
3947 return 1;
3948
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00003949 FileEntry *FEnt = static_cast<FileEntry *>(file);
Rafael Espindolaf8f91b82013-08-01 21:42:11 +00003950 const llvm::sys::fs::UniqueID &ID = FEnt->getUniqueID();
3951 outID->data[0] = ID.getDevice();
3952 outID->data[1] = ID.getFile();
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00003953 outID->data[2] = FEnt->getModificationTime();
3954 return 0;
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00003955}
3956
Argyrios Kyrtzidisac3997e2014-08-16 00:26:19 +00003957int clang_File_isEqual(CXFile file1, CXFile file2) {
3958 if (file1 == file2)
3959 return true;
3960
3961 if (!file1 || !file2)
3962 return false;
3963
3964 FileEntry *FEnt1 = static_cast<FileEntry *>(file1);
3965 FileEntry *FEnt2 = static_cast<FileEntry *>(file2);
3966 return FEnt1->getUniqueID() == FEnt2->getUniqueID();
3967}
3968
Guy Benyei11169dd2012-12-18 14:30:41 +00003969} // end: extern "C"
3970
3971//===----------------------------------------------------------------------===//
3972// CXCursor Operations.
3973//===----------------------------------------------------------------------===//
3974
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00003975static const Decl *getDeclFromExpr(const Stmt *E) {
3976 if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00003977 return getDeclFromExpr(CE->getSubExpr());
3978
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00003979 if (const DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00003980 return RefExpr->getDecl();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00003981 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00003982 return ME->getMemberDecl();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00003983 if (const ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00003984 return RE->getDecl();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00003985 if (const ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003986 if (PRE->isExplicitProperty())
3987 return PRE->getExplicitProperty();
3988 // It could be messaging both getter and setter as in:
3989 // ++myobj.myprop;
3990 // in which case prefer to associate the setter since it is less obvious
3991 // from inspecting the source that the setter is going to get called.
3992 if (PRE->isMessagingSetter())
3993 return PRE->getImplicitPropertySetter();
3994 return PRE->getImplicitPropertyGetter();
3995 }
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00003996 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00003997 return getDeclFromExpr(POE->getSyntacticForm());
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00003998 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00003999 if (Expr *Src = OVE->getSourceExpr())
4000 return getDeclFromExpr(Src);
4001
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004002 if (const CallExpr *CE = dyn_cast<CallExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004003 return getDeclFromExpr(CE->getCallee());
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004004 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004005 if (!CE->isElidable())
4006 return CE->getConstructor();
Richard Smith5179eb72016-06-28 19:03:57 +00004007 if (const CXXInheritedCtorInitExpr *CE =
4008 dyn_cast<CXXInheritedCtorInitExpr>(E))
4009 return CE->getConstructor();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004010 if (const ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004011 return OME->getMethodDecl();
4012
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004013 if (const ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004014 return PE->getProtocol();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004015 if (const SubstNonTypeTemplateParmPackExpr *NTTP
Guy Benyei11169dd2012-12-18 14:30:41 +00004016 = dyn_cast<SubstNonTypeTemplateParmPackExpr>(E))
4017 return NTTP->getParameterPack();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004018 if (const SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004019 if (isa<NonTypeTemplateParmDecl>(SizeOfPack->getPack()) ||
4020 isa<ParmVarDecl>(SizeOfPack->getPack()))
4021 return SizeOfPack->getPack();
Craig Topper69186e72014-06-08 08:38:04 +00004022
4023 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004024}
4025
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004026static SourceLocation getLocationFromExpr(const Expr *E) {
4027 if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004028 return getLocationFromExpr(CE->getSubExpr());
4029
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004030 if (const ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004031 return /*FIXME:*/Msg->getLeftLoc();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004032 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004033 return DRE->getLocation();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004034 if (const MemberExpr *Member = dyn_cast<MemberExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004035 return Member->getMemberLoc();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004036 if (const ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004037 return Ivar->getLocation();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004038 if (const SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004039 return SizeOfPack->getPackLoc();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004040 if (const ObjCPropertyRefExpr *PropRef = dyn_cast<ObjCPropertyRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004041 return PropRef->getLocation();
4042
4043 return E->getLocStart();
4044}
4045
4046extern "C" {
4047
4048unsigned clang_visitChildren(CXCursor parent,
4049 CXCursorVisitor visitor,
4050 CXClientData client_data) {
4051 CursorVisitor CursorVis(getCursorTU(parent), visitor, client_data,
4052 /*VisitPreprocessorLast=*/false);
4053 return CursorVis.VisitChildren(parent);
4054}
4055
4056#ifndef __has_feature
4057#define __has_feature(x) 0
4058#endif
4059#if __has_feature(blocks)
4060typedef enum CXChildVisitResult
4061 (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
4062
4063static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
4064 CXClientData client_data) {
4065 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
4066 return block(cursor, parent);
4067}
4068#else
4069// If we are compiled with a compiler that doesn't have native blocks support,
4070// define and call the block manually, so the
4071typedef struct _CXChildVisitResult
4072{
4073 void *isa;
4074 int flags;
4075 int reserved;
4076 enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor,
4077 CXCursor);
4078} *CXCursorVisitorBlock;
4079
4080static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
4081 CXClientData client_data) {
4082 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
4083 return block->invoke(block, cursor, parent);
4084}
4085#endif
4086
4087
4088unsigned clang_visitChildrenWithBlock(CXCursor parent,
4089 CXCursorVisitorBlock block) {
4090 return clang_visitChildren(parent, visitWithBlock, block);
4091}
4092
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004093static CXString getDeclSpelling(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004094 if (!D)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004095 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004096
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004097 const NamedDecl *ND = dyn_cast<NamedDecl>(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00004098 if (!ND) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004099 if (const ObjCPropertyImplDecl *PropImpl =
4100 dyn_cast<ObjCPropertyImplDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00004101 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004102 return cxstring::createDup(Property->getIdentifier()->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004103
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004104 if (const ImportDecl *ImportD = dyn_cast<ImportDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00004105 if (Module *Mod = ImportD->getImportedModule())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004106 return cxstring::createDup(Mod->getFullModuleName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004107
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004108 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004109 }
4110
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004111 if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004112 return cxstring::createDup(OMD->getSelector().getAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004113
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004114 if (const ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
Guy Benyei11169dd2012-12-18 14:30:41 +00004115 // No, this isn't the same as the code below. getIdentifier() is non-virtual
4116 // and returns different names. NamedDecl returns the class name and
4117 // ObjCCategoryImplDecl returns the category name.
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004118 return cxstring::createRef(CIMP->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004119
4120 if (isa<UsingDirectiveDecl>(D))
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004121 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004122
4123 SmallString<1024> S;
4124 llvm::raw_svector_ostream os(S);
4125 ND->printName(os);
4126
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004127 return cxstring::createDup(os.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00004128}
4129
4130CXString clang_getCursorSpelling(CXCursor C) {
4131 if (clang_isTranslationUnit(C.kind))
Dmitri Gribenko2c173b42013-01-11 19:28:44 +00004132 return clang_getTranslationUnitSpelling(getCursorTU(C));
Guy Benyei11169dd2012-12-18 14:30:41 +00004133
4134 if (clang_isReference(C.kind)) {
4135 switch (C.kind) {
4136 case CXCursor_ObjCSuperClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004137 const ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004138 return cxstring::createRef(Super->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004139 }
4140 case CXCursor_ObjCClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004141 const ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004142 return cxstring::createRef(Class->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004143 }
4144 case CXCursor_ObjCProtocolRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004145 const ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004146 assert(OID && "getCursorSpelling(): Missing protocol decl");
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004147 return cxstring::createRef(OID->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004148 }
4149 case CXCursor_CXXBaseSpecifier: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004150 const CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004151 return cxstring::createDup(B->getType().getAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004152 }
4153 case CXCursor_TypeRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004154 const TypeDecl *Type = getCursorTypeRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004155 assert(Type && "Missing type decl");
4156
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004157 return cxstring::createDup(getCursorContext(C).getTypeDeclType(Type).
Guy Benyei11169dd2012-12-18 14:30:41 +00004158 getAsString());
4159 }
4160 case CXCursor_TemplateRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004161 const TemplateDecl *Template = getCursorTemplateRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004162 assert(Template && "Missing template decl");
4163
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004164 return cxstring::createDup(Template->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004165 }
4166
4167 case CXCursor_NamespaceRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004168 const NamedDecl *NS = getCursorNamespaceRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004169 assert(NS && "Missing namespace decl");
4170
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004171 return cxstring::createDup(NS->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004172 }
4173
4174 case CXCursor_MemberRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004175 const FieldDecl *Field = getCursorMemberRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004176 assert(Field && "Missing member decl");
4177
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004178 return cxstring::createDup(Field->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004179 }
4180
4181 case CXCursor_LabelRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004182 const LabelStmt *Label = getCursorLabelRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004183 assert(Label && "Missing label");
4184
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004185 return cxstring::createRef(Label->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004186 }
4187
4188 case CXCursor_OverloadedDeclRef: {
4189 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004190 if (const Decl *D = Storage.dyn_cast<const Decl *>()) {
4191 if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004192 return cxstring::createDup(ND->getNameAsString());
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004193 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004194 }
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004195 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004196 return cxstring::createDup(E->getName().getAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004197 OverloadedTemplateStorage *Ovl
4198 = Storage.get<OverloadedTemplateStorage*>();
4199 if (Ovl->size() == 0)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004200 return cxstring::createEmpty();
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004201 return cxstring::createDup((*Ovl->begin())->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004202 }
4203
4204 case CXCursor_VariableRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004205 const VarDecl *Var = getCursorVariableRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004206 assert(Var && "Missing variable decl");
4207
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004208 return cxstring::createDup(Var->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004209 }
4210
4211 default:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004212 return cxstring::createRef("<not implemented>");
Guy Benyei11169dd2012-12-18 14:30:41 +00004213 }
4214 }
4215
4216 if (clang_isExpression(C.kind)) {
Argyrios Kyrtzidis3227d862014-03-03 19:40:52 +00004217 const Expr *E = getCursorExpr(C);
4218
4219 if (C.kind == CXCursor_ObjCStringLiteral ||
4220 C.kind == CXCursor_StringLiteral) {
4221 const StringLiteral *SLit;
4222 if (const ObjCStringLiteral *OSL = dyn_cast<ObjCStringLiteral>(E)) {
4223 SLit = OSL->getString();
4224 } else {
4225 SLit = cast<StringLiteral>(E);
4226 }
4227 SmallString<256> Buf;
4228 llvm::raw_svector_ostream OS(Buf);
4229 SLit->outputString(OS);
4230 return cxstring::createDup(OS.str());
4231 }
4232
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004233 const Decl *D = getDeclFromExpr(getCursorExpr(C));
Guy Benyei11169dd2012-12-18 14:30:41 +00004234 if (D)
4235 return getDeclSpelling(D);
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004236 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004237 }
4238
4239 if (clang_isStatement(C.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004240 const Stmt *S = getCursorStmt(C);
4241 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004242 return cxstring::createRef(Label->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004243
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004244 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004245 }
4246
4247 if (C.kind == CXCursor_MacroExpansion)
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004248 return cxstring::createRef(getCursorMacroExpansion(C).getName()
Guy Benyei11169dd2012-12-18 14:30:41 +00004249 ->getNameStart());
4250
4251 if (C.kind == CXCursor_MacroDefinition)
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004252 return cxstring::createRef(getCursorMacroDefinition(C)->getName()
Guy Benyei11169dd2012-12-18 14:30:41 +00004253 ->getNameStart());
4254
4255 if (C.kind == CXCursor_InclusionDirective)
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004256 return cxstring::createDup(getCursorInclusionDirective(C)->getFileName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004257
4258 if (clang_isDeclaration(C.kind))
4259 return getDeclSpelling(getCursorDecl(C));
4260
4261 if (C.kind == CXCursor_AnnotateAttr) {
Dmitri Gribenkoe4baea62013-01-26 18:08:08 +00004262 const AnnotateAttr *AA = cast<AnnotateAttr>(cxcursor::getCursorAttr(C));
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004263 return cxstring::createDup(AA->getAnnotation());
Guy Benyei11169dd2012-12-18 14:30:41 +00004264 }
4265
4266 if (C.kind == CXCursor_AsmLabelAttr) {
Dmitri Gribenkoe4baea62013-01-26 18:08:08 +00004267 const AsmLabelAttr *AA = cast<AsmLabelAttr>(cxcursor::getCursorAttr(C));
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004268 return cxstring::createDup(AA->getLabel());
Guy Benyei11169dd2012-12-18 14:30:41 +00004269 }
4270
Argyrios Kyrtzidis16834f12013-09-25 00:14:38 +00004271 if (C.kind == CXCursor_PackedAttr) {
4272 return cxstring::createRef("packed");
4273 }
4274
Saleem Abdulrasool79c69712015-09-05 18:53:43 +00004275 if (C.kind == CXCursor_VisibilityAttr) {
4276 const VisibilityAttr *AA = cast<VisibilityAttr>(cxcursor::getCursorAttr(C));
4277 switch (AA->getVisibility()) {
4278 case VisibilityAttr::VisibilityType::Default:
4279 return cxstring::createRef("default");
4280 case VisibilityAttr::VisibilityType::Hidden:
4281 return cxstring::createRef("hidden");
4282 case VisibilityAttr::VisibilityType::Protected:
4283 return cxstring::createRef("protected");
4284 }
4285 llvm_unreachable("unknown visibility type");
4286 }
4287
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004288 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004289}
4290
4291CXSourceRange clang_Cursor_getSpellingNameRange(CXCursor C,
4292 unsigned pieceIndex,
4293 unsigned options) {
4294 if (clang_Cursor_isNull(C))
4295 return clang_getNullRange();
4296
4297 ASTContext &Ctx = getCursorContext(C);
4298
4299 if (clang_isStatement(C.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004300 const Stmt *S = getCursorStmt(C);
4301 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004302 if (pieceIndex > 0)
4303 return clang_getNullRange();
4304 return cxloc::translateSourceRange(Ctx, Label->getIdentLoc());
4305 }
4306
4307 return clang_getNullRange();
4308 }
4309
4310 if (C.kind == CXCursor_ObjCMessageExpr) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004311 if (const ObjCMessageExpr *
Guy Benyei11169dd2012-12-18 14:30:41 +00004312 ME = dyn_cast_or_null<ObjCMessageExpr>(getCursorExpr(C))) {
4313 if (pieceIndex >= ME->getNumSelectorLocs())
4314 return clang_getNullRange();
4315 return cxloc::translateSourceRange(Ctx, ME->getSelectorLoc(pieceIndex));
4316 }
4317 }
4318
4319 if (C.kind == CXCursor_ObjCInstanceMethodDecl ||
4320 C.kind == CXCursor_ObjCClassMethodDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004321 if (const ObjCMethodDecl *
Guy Benyei11169dd2012-12-18 14:30:41 +00004322 MD = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(C))) {
4323 if (pieceIndex >= MD->getNumSelectorLocs())
4324 return clang_getNullRange();
4325 return cxloc::translateSourceRange(Ctx, MD->getSelectorLoc(pieceIndex));
4326 }
4327 }
4328
4329 if (C.kind == CXCursor_ObjCCategoryDecl ||
4330 C.kind == CXCursor_ObjCCategoryImplDecl) {
4331 if (pieceIndex > 0)
4332 return clang_getNullRange();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004333 if (const ObjCCategoryDecl *
Guy Benyei11169dd2012-12-18 14:30:41 +00004334 CD = dyn_cast_or_null<ObjCCategoryDecl>(getCursorDecl(C)))
4335 return cxloc::translateSourceRange(Ctx, CD->getCategoryNameLoc());
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004336 if (const ObjCCategoryImplDecl *
Guy Benyei11169dd2012-12-18 14:30:41 +00004337 CID = dyn_cast_or_null<ObjCCategoryImplDecl>(getCursorDecl(C)))
4338 return cxloc::translateSourceRange(Ctx, CID->getCategoryNameLoc());
4339 }
4340
4341 if (C.kind == CXCursor_ModuleImportDecl) {
4342 if (pieceIndex > 0)
4343 return clang_getNullRange();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004344 if (const ImportDecl *ImportD =
4345 dyn_cast_or_null<ImportDecl>(getCursorDecl(C))) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004346 ArrayRef<SourceLocation> Locs = ImportD->getIdentifierLocs();
4347 if (!Locs.empty())
4348 return cxloc::translateSourceRange(Ctx,
4349 SourceRange(Locs.front(), Locs.back()));
4350 }
4351 return clang_getNullRange();
4352 }
4353
Argyrios Kyrtzidisa2a1e532014-08-26 20:23:26 +00004354 if (C.kind == CXCursor_CXXMethod || C.kind == CXCursor_Destructor ||
4355 C.kind == CXCursor_ConversionFunction) {
4356 if (pieceIndex > 0)
4357 return clang_getNullRange();
4358 if (const FunctionDecl *FD =
4359 dyn_cast_or_null<FunctionDecl>(getCursorDecl(C))) {
4360 DeclarationNameInfo FunctionName = FD->getNameInfo();
4361 return cxloc::translateSourceRange(Ctx, FunctionName.getSourceRange());
4362 }
4363 return clang_getNullRange();
4364 }
4365
Guy Benyei11169dd2012-12-18 14:30:41 +00004366 // FIXME: A CXCursor_InclusionDirective should give the location of the
4367 // filename, but we don't keep track of this.
4368
4369 // FIXME: A CXCursor_AnnotateAttr should give the location of the annotation
4370 // but we don't keep track of this.
4371
4372 // FIXME: A CXCursor_AsmLabelAttr should give the location of the label
4373 // but we don't keep track of this.
4374
4375 // Default handling, give the location of the cursor.
4376
4377 if (pieceIndex > 0)
4378 return clang_getNullRange();
4379
4380 CXSourceLocation CXLoc = clang_getCursorLocation(C);
4381 SourceLocation Loc = cxloc::translateSourceLocation(CXLoc);
4382 return cxloc::translateSourceRange(Ctx, Loc);
4383}
4384
Eli Bendersky44a206f2014-07-31 18:04:56 +00004385CXString clang_Cursor_getMangling(CXCursor C) {
4386 if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
4387 return cxstring::createEmpty();
4388
Eli Bendersky44a206f2014-07-31 18:04:56 +00004389 // Mangling only works for functions and variables.
Eli Bendersky79759592014-08-01 15:01:10 +00004390 const Decl *D = getCursorDecl(C);
Eli Bendersky44a206f2014-07-31 18:04:56 +00004391 if (!D || !(isa<FunctionDecl>(D) || isa<VarDecl>(D)))
4392 return cxstring::createEmpty();
4393
Argyrios Kyrtzidisca741ce2016-02-14 22:30:14 +00004394 ASTContext &Ctx = D->getASTContext();
4395 index::CodegenNameGenerator CGNameGen(Ctx);
4396 return cxstring::createDup(CGNameGen.getName(D));
Eli Bendersky44a206f2014-07-31 18:04:56 +00004397}
4398
Saleem Abdulrasool60034432015-11-12 03:57:22 +00004399CXStringSet *clang_Cursor_getCXXManglings(CXCursor C) {
4400 if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
4401 return nullptr;
4402
4403 const Decl *D = getCursorDecl(C);
4404 if (!(isa<CXXRecordDecl>(D) || isa<CXXMethodDecl>(D)))
4405 return nullptr;
4406
Argyrios Kyrtzidisca741ce2016-02-14 22:30:14 +00004407 ASTContext &Ctx = D->getASTContext();
4408 index::CodegenNameGenerator CGNameGen(Ctx);
4409 std::vector<std::string> Manglings = CGNameGen.getAllManglings(D);
Saleem Abdulrasool60034432015-11-12 03:57:22 +00004410 return cxstring::createSet(Manglings);
4411}
4412
Guy Benyei11169dd2012-12-18 14:30:41 +00004413CXString clang_getCursorDisplayName(CXCursor C) {
4414 if (!clang_isDeclaration(C.kind))
4415 return clang_getCursorSpelling(C);
4416
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004417 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00004418 if (!D)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004419 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004420
4421 PrintingPolicy Policy = getCursorContext(C).getPrintingPolicy();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004422 if (const FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00004423 D = FunTmpl->getTemplatedDecl();
4424
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004425 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004426 SmallString<64> Str;
4427 llvm::raw_svector_ostream OS(Str);
4428 OS << *Function;
4429 if (Function->getPrimaryTemplate())
4430 OS << "<>";
4431 OS << "(";
4432 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
4433 if (I)
4434 OS << ", ";
4435 OS << Function->getParamDecl(I)->getType().getAsString(Policy);
4436 }
4437
4438 if (Function->isVariadic()) {
4439 if (Function->getNumParams())
4440 OS << ", ";
4441 OS << "...";
4442 }
4443 OS << ")";
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004444 return cxstring::createDup(OS.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00004445 }
4446
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004447 if (const ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004448 SmallString<64> Str;
4449 llvm::raw_svector_ostream OS(Str);
4450 OS << *ClassTemplate;
4451 OS << "<";
4452 TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
4453 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
4454 if (I)
4455 OS << ", ";
4456
4457 NamedDecl *Param = Params->getParam(I);
4458 if (Param->getIdentifier()) {
4459 OS << Param->getIdentifier()->getName();
4460 continue;
4461 }
4462
4463 // There is no parameter name, which makes this tricky. Try to come up
4464 // with something useful that isn't too long.
4465 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
4466 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
4467 else if (NonTypeTemplateParmDecl *NTTP
4468 = dyn_cast<NonTypeTemplateParmDecl>(Param))
4469 OS << NTTP->getType().getAsString(Policy);
4470 else
4471 OS << "template<...> class";
4472 }
4473
4474 OS << ">";
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004475 return cxstring::createDup(OS.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00004476 }
4477
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004478 if (const ClassTemplateSpecializationDecl *ClassSpec
Guy Benyei11169dd2012-12-18 14:30:41 +00004479 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
4480 // If the type was explicitly written, use that.
4481 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004482 return cxstring::createDup(TSInfo->getType().getAsString(Policy));
Guy Benyei11169dd2012-12-18 14:30:41 +00004483
Benjamin Kramer9170e912013-02-22 15:46:01 +00004484 SmallString<128> Str;
Guy Benyei11169dd2012-12-18 14:30:41 +00004485 llvm::raw_svector_ostream OS(Str);
4486 OS << *ClassSpec;
David Majnemer6fbeee32016-07-07 04:43:07 +00004487 TemplateSpecializationType::PrintTemplateArgumentList(
4488 OS, ClassSpec->getTemplateArgs().asArray(), Policy);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004489 return cxstring::createDup(OS.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00004490 }
4491
4492 return clang_getCursorSpelling(C);
4493}
4494
4495CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
4496 switch (Kind) {
4497 case CXCursor_FunctionDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004498 return cxstring::createRef("FunctionDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004499 case CXCursor_TypedefDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004500 return cxstring::createRef("TypedefDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004501 case CXCursor_EnumDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004502 return cxstring::createRef("EnumDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004503 case CXCursor_EnumConstantDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004504 return cxstring::createRef("EnumConstantDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004505 case CXCursor_StructDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004506 return cxstring::createRef("StructDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004507 case CXCursor_UnionDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004508 return cxstring::createRef("UnionDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004509 case CXCursor_ClassDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004510 return cxstring::createRef("ClassDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004511 case CXCursor_FieldDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004512 return cxstring::createRef("FieldDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004513 case CXCursor_VarDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004514 return cxstring::createRef("VarDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004515 case CXCursor_ParmDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004516 return cxstring::createRef("ParmDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004517 case CXCursor_ObjCInterfaceDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004518 return cxstring::createRef("ObjCInterfaceDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004519 case CXCursor_ObjCCategoryDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004520 return cxstring::createRef("ObjCCategoryDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004521 case CXCursor_ObjCProtocolDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004522 return cxstring::createRef("ObjCProtocolDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004523 case CXCursor_ObjCPropertyDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004524 return cxstring::createRef("ObjCPropertyDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004525 case CXCursor_ObjCIvarDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004526 return cxstring::createRef("ObjCIvarDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004527 case CXCursor_ObjCInstanceMethodDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004528 return cxstring::createRef("ObjCInstanceMethodDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004529 case CXCursor_ObjCClassMethodDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004530 return cxstring::createRef("ObjCClassMethodDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004531 case CXCursor_ObjCImplementationDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004532 return cxstring::createRef("ObjCImplementationDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004533 case CXCursor_ObjCCategoryImplDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004534 return cxstring::createRef("ObjCCategoryImplDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004535 case CXCursor_CXXMethod:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004536 return cxstring::createRef("CXXMethod");
Guy Benyei11169dd2012-12-18 14:30:41 +00004537 case CXCursor_UnexposedDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004538 return cxstring::createRef("UnexposedDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004539 case CXCursor_ObjCSuperClassRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004540 return cxstring::createRef("ObjCSuperClassRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00004541 case CXCursor_ObjCProtocolRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004542 return cxstring::createRef("ObjCProtocolRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00004543 case CXCursor_ObjCClassRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004544 return cxstring::createRef("ObjCClassRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00004545 case CXCursor_TypeRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004546 return cxstring::createRef("TypeRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00004547 case CXCursor_TemplateRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004548 return cxstring::createRef("TemplateRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00004549 case CXCursor_NamespaceRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004550 return cxstring::createRef("NamespaceRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00004551 case CXCursor_MemberRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004552 return cxstring::createRef("MemberRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00004553 case CXCursor_LabelRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004554 return cxstring::createRef("LabelRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00004555 case CXCursor_OverloadedDeclRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004556 return cxstring::createRef("OverloadedDeclRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00004557 case CXCursor_VariableRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004558 return cxstring::createRef("VariableRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00004559 case CXCursor_IntegerLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004560 return cxstring::createRef("IntegerLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00004561 case CXCursor_FloatingLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004562 return cxstring::createRef("FloatingLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00004563 case CXCursor_ImaginaryLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004564 return cxstring::createRef("ImaginaryLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00004565 case CXCursor_StringLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004566 return cxstring::createRef("StringLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00004567 case CXCursor_CharacterLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004568 return cxstring::createRef("CharacterLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00004569 case CXCursor_ParenExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004570 return cxstring::createRef("ParenExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004571 case CXCursor_UnaryOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004572 return cxstring::createRef("UnaryOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00004573 case CXCursor_ArraySubscriptExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004574 return cxstring::createRef("ArraySubscriptExpr");
Alexey Bataev1a3320e2015-08-25 14:24:04 +00004575 case CXCursor_OMPArraySectionExpr:
4576 return cxstring::createRef("OMPArraySectionExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004577 case CXCursor_BinaryOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004578 return cxstring::createRef("BinaryOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00004579 case CXCursor_CompoundAssignOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004580 return cxstring::createRef("CompoundAssignOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00004581 case CXCursor_ConditionalOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004582 return cxstring::createRef("ConditionalOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00004583 case CXCursor_CStyleCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004584 return cxstring::createRef("CStyleCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004585 case CXCursor_CompoundLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004586 return cxstring::createRef("CompoundLiteralExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004587 case CXCursor_InitListExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004588 return cxstring::createRef("InitListExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004589 case CXCursor_AddrLabelExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004590 return cxstring::createRef("AddrLabelExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004591 case CXCursor_StmtExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004592 return cxstring::createRef("StmtExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004593 case CXCursor_GenericSelectionExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004594 return cxstring::createRef("GenericSelectionExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004595 case CXCursor_GNUNullExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004596 return cxstring::createRef("GNUNullExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004597 case CXCursor_CXXStaticCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004598 return cxstring::createRef("CXXStaticCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004599 case CXCursor_CXXDynamicCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004600 return cxstring::createRef("CXXDynamicCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004601 case CXCursor_CXXReinterpretCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004602 return cxstring::createRef("CXXReinterpretCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004603 case CXCursor_CXXConstCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004604 return cxstring::createRef("CXXConstCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004605 case CXCursor_CXXFunctionalCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004606 return cxstring::createRef("CXXFunctionalCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004607 case CXCursor_CXXTypeidExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004608 return cxstring::createRef("CXXTypeidExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004609 case CXCursor_CXXBoolLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004610 return cxstring::createRef("CXXBoolLiteralExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004611 case CXCursor_CXXNullPtrLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004612 return cxstring::createRef("CXXNullPtrLiteralExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004613 case CXCursor_CXXThisExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004614 return cxstring::createRef("CXXThisExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004615 case CXCursor_CXXThrowExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004616 return cxstring::createRef("CXXThrowExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004617 case CXCursor_CXXNewExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004618 return cxstring::createRef("CXXNewExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004619 case CXCursor_CXXDeleteExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004620 return cxstring::createRef("CXXDeleteExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004621 case CXCursor_UnaryExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004622 return cxstring::createRef("UnaryExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004623 case CXCursor_ObjCStringLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004624 return cxstring::createRef("ObjCStringLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00004625 case CXCursor_ObjCBoolLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004626 return cxstring::createRef("ObjCBoolLiteralExpr");
Erik Pilkington29099de2016-07-16 00:35:23 +00004627 case CXCursor_ObjCAvailabilityCheckExpr:
4628 return cxstring::createRef("ObjCAvailabilityCheckExpr");
Argyrios Kyrtzidisc2233be2013-04-23 17:57:17 +00004629 case CXCursor_ObjCSelfExpr:
4630 return cxstring::createRef("ObjCSelfExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004631 case CXCursor_ObjCEncodeExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004632 return cxstring::createRef("ObjCEncodeExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004633 case CXCursor_ObjCSelectorExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004634 return cxstring::createRef("ObjCSelectorExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004635 case CXCursor_ObjCProtocolExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004636 return cxstring::createRef("ObjCProtocolExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004637 case CXCursor_ObjCBridgedCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004638 return cxstring::createRef("ObjCBridgedCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004639 case CXCursor_BlockExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004640 return cxstring::createRef("BlockExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004641 case CXCursor_PackExpansionExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004642 return cxstring::createRef("PackExpansionExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004643 case CXCursor_SizeOfPackExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004644 return cxstring::createRef("SizeOfPackExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004645 case CXCursor_LambdaExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004646 return cxstring::createRef("LambdaExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004647 case CXCursor_UnexposedExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004648 return cxstring::createRef("UnexposedExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004649 case CXCursor_DeclRefExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004650 return cxstring::createRef("DeclRefExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004651 case CXCursor_MemberRefExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004652 return cxstring::createRef("MemberRefExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004653 case CXCursor_CallExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004654 return cxstring::createRef("CallExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004655 case CXCursor_ObjCMessageExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004656 return cxstring::createRef("ObjCMessageExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004657 case CXCursor_UnexposedStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004658 return cxstring::createRef("UnexposedStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004659 case CXCursor_DeclStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004660 return cxstring::createRef("DeclStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004661 case CXCursor_LabelStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004662 return cxstring::createRef("LabelStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004663 case CXCursor_CompoundStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004664 return cxstring::createRef("CompoundStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004665 case CXCursor_CaseStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004666 return cxstring::createRef("CaseStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004667 case CXCursor_DefaultStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004668 return cxstring::createRef("DefaultStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004669 case CXCursor_IfStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004670 return cxstring::createRef("IfStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004671 case CXCursor_SwitchStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004672 return cxstring::createRef("SwitchStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004673 case CXCursor_WhileStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004674 return cxstring::createRef("WhileStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004675 case CXCursor_DoStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004676 return cxstring::createRef("DoStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004677 case CXCursor_ForStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004678 return cxstring::createRef("ForStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004679 case CXCursor_GotoStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004680 return cxstring::createRef("GotoStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004681 case CXCursor_IndirectGotoStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004682 return cxstring::createRef("IndirectGotoStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004683 case CXCursor_ContinueStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004684 return cxstring::createRef("ContinueStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004685 case CXCursor_BreakStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004686 return cxstring::createRef("BreakStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004687 case CXCursor_ReturnStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004688 return cxstring::createRef("ReturnStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004689 case CXCursor_GCCAsmStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004690 return cxstring::createRef("GCCAsmStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004691 case CXCursor_MSAsmStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004692 return cxstring::createRef("MSAsmStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004693 case CXCursor_ObjCAtTryStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004694 return cxstring::createRef("ObjCAtTryStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004695 case CXCursor_ObjCAtCatchStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004696 return cxstring::createRef("ObjCAtCatchStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004697 case CXCursor_ObjCAtFinallyStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004698 return cxstring::createRef("ObjCAtFinallyStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004699 case CXCursor_ObjCAtThrowStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004700 return cxstring::createRef("ObjCAtThrowStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004701 case CXCursor_ObjCAtSynchronizedStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004702 return cxstring::createRef("ObjCAtSynchronizedStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004703 case CXCursor_ObjCAutoreleasePoolStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004704 return cxstring::createRef("ObjCAutoreleasePoolStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004705 case CXCursor_ObjCForCollectionStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004706 return cxstring::createRef("ObjCForCollectionStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004707 case CXCursor_CXXCatchStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004708 return cxstring::createRef("CXXCatchStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004709 case CXCursor_CXXTryStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004710 return cxstring::createRef("CXXTryStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004711 case CXCursor_CXXForRangeStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004712 return cxstring::createRef("CXXForRangeStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004713 case CXCursor_SEHTryStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004714 return cxstring::createRef("SEHTryStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004715 case CXCursor_SEHExceptStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004716 return cxstring::createRef("SEHExceptStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004717 case CXCursor_SEHFinallyStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004718 return cxstring::createRef("SEHFinallyStmt");
Nico Weber9b982072014-07-07 00:12:30 +00004719 case CXCursor_SEHLeaveStmt:
4720 return cxstring::createRef("SEHLeaveStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004721 case CXCursor_NullStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004722 return cxstring::createRef("NullStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004723 case CXCursor_InvalidFile:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004724 return cxstring::createRef("InvalidFile");
Guy Benyei11169dd2012-12-18 14:30:41 +00004725 case CXCursor_InvalidCode:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004726 return cxstring::createRef("InvalidCode");
Guy Benyei11169dd2012-12-18 14:30:41 +00004727 case CXCursor_NoDeclFound:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004728 return cxstring::createRef("NoDeclFound");
Guy Benyei11169dd2012-12-18 14:30:41 +00004729 case CXCursor_NotImplemented:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004730 return cxstring::createRef("NotImplemented");
Guy Benyei11169dd2012-12-18 14:30:41 +00004731 case CXCursor_TranslationUnit:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004732 return cxstring::createRef("TranslationUnit");
Guy Benyei11169dd2012-12-18 14:30:41 +00004733 case CXCursor_UnexposedAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004734 return cxstring::createRef("UnexposedAttr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004735 case CXCursor_IBActionAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004736 return cxstring::createRef("attribute(ibaction)");
Guy Benyei11169dd2012-12-18 14:30:41 +00004737 case CXCursor_IBOutletAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004738 return cxstring::createRef("attribute(iboutlet)");
Guy Benyei11169dd2012-12-18 14:30:41 +00004739 case CXCursor_IBOutletCollectionAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004740 return cxstring::createRef("attribute(iboutletcollection)");
Guy Benyei11169dd2012-12-18 14:30:41 +00004741 case CXCursor_CXXFinalAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004742 return cxstring::createRef("attribute(final)");
Guy Benyei11169dd2012-12-18 14:30:41 +00004743 case CXCursor_CXXOverrideAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004744 return cxstring::createRef("attribute(override)");
Guy Benyei11169dd2012-12-18 14:30:41 +00004745 case CXCursor_AnnotateAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004746 return cxstring::createRef("attribute(annotate)");
Guy Benyei11169dd2012-12-18 14:30:41 +00004747 case CXCursor_AsmLabelAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004748 return cxstring::createRef("asm label");
Argyrios Kyrtzidis16834f12013-09-25 00:14:38 +00004749 case CXCursor_PackedAttr:
4750 return cxstring::createRef("attribute(packed)");
Joey Gouly81228382014-05-01 15:41:58 +00004751 case CXCursor_PureAttr:
4752 return cxstring::createRef("attribute(pure)");
4753 case CXCursor_ConstAttr:
4754 return cxstring::createRef("attribute(const)");
4755 case CXCursor_NoDuplicateAttr:
4756 return cxstring::createRef("attribute(noduplicate)");
Eli Bendersky2581e662014-05-28 19:29:58 +00004757 case CXCursor_CUDAConstantAttr:
4758 return cxstring::createRef("attribute(constant)");
4759 case CXCursor_CUDADeviceAttr:
4760 return cxstring::createRef("attribute(device)");
4761 case CXCursor_CUDAGlobalAttr:
4762 return cxstring::createRef("attribute(global)");
4763 case CXCursor_CUDAHostAttr:
4764 return cxstring::createRef("attribute(host)");
Eli Bendersky9b071472014-08-08 14:59:00 +00004765 case CXCursor_CUDASharedAttr:
4766 return cxstring::createRef("attribute(shared)");
Saleem Abdulrasool79c69712015-09-05 18:53:43 +00004767 case CXCursor_VisibilityAttr:
4768 return cxstring::createRef("attribute(visibility)");
Saleem Abdulrasool8aa0b802015-12-10 18:45:18 +00004769 case CXCursor_DLLExport:
4770 return cxstring::createRef("attribute(dllexport)");
4771 case CXCursor_DLLImport:
4772 return cxstring::createRef("attribute(dllimport)");
Guy Benyei11169dd2012-12-18 14:30:41 +00004773 case CXCursor_PreprocessingDirective:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004774 return cxstring::createRef("preprocessing directive");
Guy Benyei11169dd2012-12-18 14:30:41 +00004775 case CXCursor_MacroDefinition:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004776 return cxstring::createRef("macro definition");
Guy Benyei11169dd2012-12-18 14:30:41 +00004777 case CXCursor_MacroExpansion:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004778 return cxstring::createRef("macro expansion");
Guy Benyei11169dd2012-12-18 14:30:41 +00004779 case CXCursor_InclusionDirective:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004780 return cxstring::createRef("inclusion directive");
Guy Benyei11169dd2012-12-18 14:30:41 +00004781 case CXCursor_Namespace:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004782 return cxstring::createRef("Namespace");
Guy Benyei11169dd2012-12-18 14:30:41 +00004783 case CXCursor_LinkageSpec:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004784 return cxstring::createRef("LinkageSpec");
Guy Benyei11169dd2012-12-18 14:30:41 +00004785 case CXCursor_CXXBaseSpecifier:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004786 return cxstring::createRef("C++ base class specifier");
Guy Benyei11169dd2012-12-18 14:30:41 +00004787 case CXCursor_Constructor:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004788 return cxstring::createRef("CXXConstructor");
Guy Benyei11169dd2012-12-18 14:30:41 +00004789 case CXCursor_Destructor:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004790 return cxstring::createRef("CXXDestructor");
Guy Benyei11169dd2012-12-18 14:30:41 +00004791 case CXCursor_ConversionFunction:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004792 return cxstring::createRef("CXXConversion");
Guy Benyei11169dd2012-12-18 14:30:41 +00004793 case CXCursor_TemplateTypeParameter:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004794 return cxstring::createRef("TemplateTypeParameter");
Guy Benyei11169dd2012-12-18 14:30:41 +00004795 case CXCursor_NonTypeTemplateParameter:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004796 return cxstring::createRef("NonTypeTemplateParameter");
Guy Benyei11169dd2012-12-18 14:30:41 +00004797 case CXCursor_TemplateTemplateParameter:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004798 return cxstring::createRef("TemplateTemplateParameter");
Guy Benyei11169dd2012-12-18 14:30:41 +00004799 case CXCursor_FunctionTemplate:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004800 return cxstring::createRef("FunctionTemplate");
Guy Benyei11169dd2012-12-18 14:30:41 +00004801 case CXCursor_ClassTemplate:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004802 return cxstring::createRef("ClassTemplate");
Guy Benyei11169dd2012-12-18 14:30:41 +00004803 case CXCursor_ClassTemplatePartialSpecialization:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004804 return cxstring::createRef("ClassTemplatePartialSpecialization");
Guy Benyei11169dd2012-12-18 14:30:41 +00004805 case CXCursor_NamespaceAlias:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004806 return cxstring::createRef("NamespaceAlias");
Guy Benyei11169dd2012-12-18 14:30:41 +00004807 case CXCursor_UsingDirective:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004808 return cxstring::createRef("UsingDirective");
Guy Benyei11169dd2012-12-18 14:30:41 +00004809 case CXCursor_UsingDeclaration:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004810 return cxstring::createRef("UsingDeclaration");
Guy Benyei11169dd2012-12-18 14:30:41 +00004811 case CXCursor_TypeAliasDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004812 return cxstring::createRef("TypeAliasDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004813 case CXCursor_ObjCSynthesizeDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004814 return cxstring::createRef("ObjCSynthesizeDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004815 case CXCursor_ObjCDynamicDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004816 return cxstring::createRef("ObjCDynamicDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004817 case CXCursor_CXXAccessSpecifier:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004818 return cxstring::createRef("CXXAccessSpecifier");
Guy Benyei11169dd2012-12-18 14:30:41 +00004819 case CXCursor_ModuleImportDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004820 return cxstring::createRef("ModuleImport");
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004821 case CXCursor_OMPParallelDirective:
Alexey Bataev1b59ab52014-02-27 08:29:12 +00004822 return cxstring::createRef("OMPParallelDirective");
4823 case CXCursor_OMPSimdDirective:
4824 return cxstring::createRef("OMPSimdDirective");
Alexey Bataevf29276e2014-06-18 04:14:57 +00004825 case CXCursor_OMPForDirective:
4826 return cxstring::createRef("OMPForDirective");
Alexander Musmanf82886e2014-09-18 05:12:34 +00004827 case CXCursor_OMPForSimdDirective:
4828 return cxstring::createRef("OMPForSimdDirective");
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004829 case CXCursor_OMPSectionsDirective:
4830 return cxstring::createRef("OMPSectionsDirective");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004831 case CXCursor_OMPSectionDirective:
4832 return cxstring::createRef("OMPSectionDirective");
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00004833 case CXCursor_OMPSingleDirective:
4834 return cxstring::createRef("OMPSingleDirective");
Alexander Musman80c22892014-07-17 08:54:58 +00004835 case CXCursor_OMPMasterDirective:
4836 return cxstring::createRef("OMPMasterDirective");
Alexander Musmand9ed09f2014-07-21 09:42:05 +00004837 case CXCursor_OMPCriticalDirective:
4838 return cxstring::createRef("OMPCriticalDirective");
Alexey Bataev4acb8592014-07-07 13:01:15 +00004839 case CXCursor_OMPParallelForDirective:
4840 return cxstring::createRef("OMPParallelForDirective");
Alexander Musmane4e893b2014-09-23 09:33:00 +00004841 case CXCursor_OMPParallelForSimdDirective:
4842 return cxstring::createRef("OMPParallelForSimdDirective");
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004843 case CXCursor_OMPParallelSectionsDirective:
4844 return cxstring::createRef("OMPParallelSectionsDirective");
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004845 case CXCursor_OMPTaskDirective:
4846 return cxstring::createRef("OMPTaskDirective");
Alexey Bataev68446b72014-07-18 07:47:19 +00004847 case CXCursor_OMPTaskyieldDirective:
4848 return cxstring::createRef("OMPTaskyieldDirective");
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00004849 case CXCursor_OMPBarrierDirective:
4850 return cxstring::createRef("OMPBarrierDirective");
Alexey Bataev2df347a2014-07-18 10:17:07 +00004851 case CXCursor_OMPTaskwaitDirective:
4852 return cxstring::createRef("OMPTaskwaitDirective");
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00004853 case CXCursor_OMPTaskgroupDirective:
4854 return cxstring::createRef("OMPTaskgroupDirective");
Alexey Bataev6125da92014-07-21 11:26:11 +00004855 case CXCursor_OMPFlushDirective:
4856 return cxstring::createRef("OMPFlushDirective");
Alexey Bataev9fb6e642014-07-22 06:45:04 +00004857 case CXCursor_OMPOrderedDirective:
4858 return cxstring::createRef("OMPOrderedDirective");
Alexey Bataev0162e452014-07-22 10:10:35 +00004859 case CXCursor_OMPAtomicDirective:
4860 return cxstring::createRef("OMPAtomicDirective");
Alexey Bataev0bd520b2014-09-19 08:19:49 +00004861 case CXCursor_OMPTargetDirective:
4862 return cxstring::createRef("OMPTargetDirective");
Michael Wong65f367f2015-07-21 13:44:28 +00004863 case CXCursor_OMPTargetDataDirective:
4864 return cxstring::createRef("OMPTargetDataDirective");
Samuel Antaodf67fc42016-01-19 19:15:56 +00004865 case CXCursor_OMPTargetEnterDataDirective:
4866 return cxstring::createRef("OMPTargetEnterDataDirective");
Samuel Antao72590762016-01-19 20:04:50 +00004867 case CXCursor_OMPTargetExitDataDirective:
4868 return cxstring::createRef("OMPTargetExitDataDirective");
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00004869 case CXCursor_OMPTargetParallelDirective:
4870 return cxstring::createRef("OMPTargetParallelDirective");
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00004871 case CXCursor_OMPTargetParallelForDirective:
4872 return cxstring::createRef("OMPTargetParallelForDirective");
Samuel Antao686c70c2016-05-26 17:30:50 +00004873 case CXCursor_OMPTargetUpdateDirective:
4874 return cxstring::createRef("OMPTargetUpdateDirective");
Alexey Bataev13314bf2014-10-09 04:18:56 +00004875 case CXCursor_OMPTeamsDirective:
4876 return cxstring::createRef("OMPTeamsDirective");
Alexey Bataev6d4ed052015-07-01 06:57:41 +00004877 case CXCursor_OMPCancellationPointDirective:
4878 return cxstring::createRef("OMPCancellationPointDirective");
Alexey Bataev80909872015-07-02 11:25:17 +00004879 case CXCursor_OMPCancelDirective:
4880 return cxstring::createRef("OMPCancelDirective");
Alexey Bataev49f6e782015-12-01 04:18:41 +00004881 case CXCursor_OMPTaskLoopDirective:
4882 return cxstring::createRef("OMPTaskLoopDirective");
Alexey Bataev0a6ed842015-12-03 09:40:15 +00004883 case CXCursor_OMPTaskLoopSimdDirective:
4884 return cxstring::createRef("OMPTaskLoopSimdDirective");
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004885 case CXCursor_OMPDistributeDirective:
4886 return cxstring::createRef("OMPDistributeDirective");
Carlo Bertolli9925f152016-06-27 14:55:37 +00004887 case CXCursor_OMPDistributeParallelForDirective:
4888 return cxstring::createRef("OMPDistributeParallelForDirective");
Kelvin Li4a39add2016-07-05 05:00:15 +00004889 case CXCursor_OMPDistributeParallelForSimdDirective:
4890 return cxstring::createRef("OMPDistributeParallelForSimdDirective");
Kelvin Li787f3fc2016-07-06 04:45:38 +00004891 case CXCursor_OMPDistributeSimdDirective:
4892 return cxstring::createRef("OMPDistributeSimdDirective");
Kelvin Lia579b912016-07-14 02:54:56 +00004893 case CXCursor_OMPTargetParallelForSimdDirective:
4894 return cxstring::createRef("OMPTargetParallelForSimdDirective");
Kelvin Li986330c2016-07-20 22:57:10 +00004895 case CXCursor_OMPTargetSimdDirective:
4896 return cxstring::createRef("OMPTargetSimdDirective");
Kelvin Li02532872016-08-05 14:37:37 +00004897 case CXCursor_OMPTeamsDistributeDirective:
4898 return cxstring::createRef("OMPTeamsDistributeDirective");
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00004899 case CXCursor_OverloadCandidate:
4900 return cxstring::createRef("OverloadCandidate");
Sergey Kalinichev8f3b1872015-11-15 13:48:32 +00004901 case CXCursor_TypeAliasTemplateDecl:
4902 return cxstring::createRef("TypeAliasTemplateDecl");
Olivier Goffart81978012016-06-09 16:15:55 +00004903 case CXCursor_StaticAssert:
4904 return cxstring::createRef("StaticAssert");
Guy Benyei11169dd2012-12-18 14:30:41 +00004905 }
4906
4907 llvm_unreachable("Unhandled CXCursorKind");
4908}
4909
4910struct GetCursorData {
4911 SourceLocation TokenBeginLoc;
4912 bool PointsAtMacroArgExpansion;
4913 bool VisitedObjCPropertyImplDecl;
4914 SourceLocation VisitedDeclaratorDeclStartLoc;
4915 CXCursor &BestCursor;
4916
4917 GetCursorData(SourceManager &SM,
4918 SourceLocation tokenBegin, CXCursor &outputCursor)
4919 : TokenBeginLoc(tokenBegin), BestCursor(outputCursor) {
4920 PointsAtMacroArgExpansion = SM.isMacroArgExpansion(tokenBegin);
4921 VisitedObjCPropertyImplDecl = false;
4922 }
4923};
4924
4925static enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
4926 CXCursor parent,
4927 CXClientData client_data) {
4928 GetCursorData *Data = static_cast<GetCursorData *>(client_data);
4929 CXCursor *BestCursor = &Data->BestCursor;
4930
4931 // If we point inside a macro argument we should provide info of what the
4932 // token is so use the actual cursor, don't replace it with a macro expansion
4933 // cursor.
4934 if (cursor.kind == CXCursor_MacroExpansion && Data->PointsAtMacroArgExpansion)
4935 return CXChildVisit_Recurse;
4936
4937 if (clang_isDeclaration(cursor.kind)) {
4938 // Avoid having the implicit methods override the property decls.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004939 if (const ObjCMethodDecl *MD
Guy Benyei11169dd2012-12-18 14:30:41 +00004940 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
4941 if (MD->isImplicit())
4942 return CXChildVisit_Break;
4943
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004944 } else if (const ObjCInterfaceDecl *ID
Guy Benyei11169dd2012-12-18 14:30:41 +00004945 = dyn_cast_or_null<ObjCInterfaceDecl>(getCursorDecl(cursor))) {
4946 // Check that when we have multiple @class references in the same line,
4947 // that later ones do not override the previous ones.
4948 // If we have:
4949 // @class Foo, Bar;
4950 // source ranges for both start at '@', so 'Bar' will end up overriding
4951 // 'Foo' even though the cursor location was at 'Foo'.
4952 if (BestCursor->kind == CXCursor_ObjCInterfaceDecl ||
4953 BestCursor->kind == CXCursor_ObjCClassRef)
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004954 if (const ObjCInterfaceDecl *PrevID
Guy Benyei11169dd2012-12-18 14:30:41 +00004955 = dyn_cast_or_null<ObjCInterfaceDecl>(getCursorDecl(*BestCursor))){
4956 if (PrevID != ID &&
4957 !PrevID->isThisDeclarationADefinition() &&
4958 !ID->isThisDeclarationADefinition())
4959 return CXChildVisit_Break;
4960 }
4961
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004962 } else if (const DeclaratorDecl *DD
Guy Benyei11169dd2012-12-18 14:30:41 +00004963 = dyn_cast_or_null<DeclaratorDecl>(getCursorDecl(cursor))) {
4964 SourceLocation StartLoc = DD->getSourceRange().getBegin();
4965 // Check that when we have multiple declarators in the same line,
4966 // that later ones do not override the previous ones.
4967 // If we have:
4968 // int Foo, Bar;
4969 // source ranges for both start at 'int', so 'Bar' will end up overriding
4970 // 'Foo' even though the cursor location was at 'Foo'.
4971 if (Data->VisitedDeclaratorDeclStartLoc == StartLoc)
4972 return CXChildVisit_Break;
4973 Data->VisitedDeclaratorDeclStartLoc = StartLoc;
4974
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004975 } else if (const ObjCPropertyImplDecl *PropImp
Guy Benyei11169dd2012-12-18 14:30:41 +00004976 = dyn_cast_or_null<ObjCPropertyImplDecl>(getCursorDecl(cursor))) {
4977 (void)PropImp;
4978 // Check that when we have multiple @synthesize in the same line,
4979 // that later ones do not override the previous ones.
4980 // If we have:
4981 // @synthesize Foo, Bar;
4982 // source ranges for both start at '@', so 'Bar' will end up overriding
4983 // 'Foo' even though the cursor location was at 'Foo'.
4984 if (Data->VisitedObjCPropertyImplDecl)
4985 return CXChildVisit_Break;
4986 Data->VisitedObjCPropertyImplDecl = true;
4987 }
4988 }
4989
4990 if (clang_isExpression(cursor.kind) &&
4991 clang_isDeclaration(BestCursor->kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004992 if (const Decl *D = getCursorDecl(*BestCursor)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004993 // Avoid having the cursor of an expression replace the declaration cursor
4994 // when the expression source range overlaps the declaration range.
4995 // This can happen for C++ constructor expressions whose range generally
4996 // include the variable declaration, e.g.:
4997 // MyCXXClass foo; // Make sure pointing at 'foo' returns a VarDecl cursor.
4998 if (D->getLocation().isValid() && Data->TokenBeginLoc.isValid() &&
4999 D->getLocation() == Data->TokenBeginLoc)
5000 return CXChildVisit_Break;
5001 }
5002 }
5003
5004 // If our current best cursor is the construction of a temporary object,
5005 // don't replace that cursor with a type reference, because we want
5006 // clang_getCursor() to point at the constructor.
5007 if (clang_isExpression(BestCursor->kind) &&
5008 isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
5009 cursor.kind == CXCursor_TypeRef) {
5010 // Keep the cursor pointing at CXXTemporaryObjectExpr but also mark it
5011 // as having the actual point on the type reference.
5012 *BestCursor = getTypeRefedCallExprCursor(*BestCursor);
5013 return CXChildVisit_Recurse;
5014 }
Douglas Gregore9d95f12015-07-07 03:57:35 +00005015
5016 // If we already have an Objective-C superclass reference, don't
5017 // update it further.
5018 if (BestCursor->kind == CXCursor_ObjCSuperClassRef)
5019 return CXChildVisit_Break;
5020
Guy Benyei11169dd2012-12-18 14:30:41 +00005021 *BestCursor = cursor;
5022 return CXChildVisit_Recurse;
5023}
5024
5025CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00005026 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00005027 LOG_BAD_TU(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00005028 return clang_getNullCursor();
Dmitri Gribenko256454f2014-02-11 14:34:14 +00005029 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005030
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00005031 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00005032 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
5033
5034 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
5035 CXCursor Result = cxcursor::getCursor(TU, SLoc);
5036
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005037 LOG_FUNC_SECTION {
Guy Benyei11169dd2012-12-18 14:30:41 +00005038 CXFile SearchFile;
5039 unsigned SearchLine, SearchColumn;
5040 CXFile ResultFile;
5041 unsigned ResultLine, ResultColumn;
5042 CXString SearchFileName, ResultFileName, KindSpelling, USR;
5043 const char *IsDef = clang_isCursorDefinition(Result)? " (Definition)" : "";
5044 CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
Craig Topper69186e72014-06-08 08:38:04 +00005045
5046 clang_getFileLocation(Loc, &SearchFile, &SearchLine, &SearchColumn,
5047 nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005048 clang_getFileLocation(ResultLoc, &ResultFile, &ResultLine,
Craig Topper69186e72014-06-08 08:38:04 +00005049 &ResultColumn, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005050 SearchFileName = clang_getFileName(SearchFile);
5051 ResultFileName = clang_getFileName(ResultFile);
5052 KindSpelling = clang_getCursorKindSpelling(Result.kind);
5053 USR = clang_getCursorUSR(Result);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005054 *Log << llvm::format("(%s:%d:%d) = %s",
5055 clang_getCString(SearchFileName), SearchLine, SearchColumn,
5056 clang_getCString(KindSpelling))
5057 << llvm::format("(%s:%d:%d):%s%s",
5058 clang_getCString(ResultFileName), ResultLine, ResultColumn,
5059 clang_getCString(USR), IsDef);
Guy Benyei11169dd2012-12-18 14:30:41 +00005060 clang_disposeString(SearchFileName);
5061 clang_disposeString(ResultFileName);
5062 clang_disposeString(KindSpelling);
5063 clang_disposeString(USR);
5064
5065 CXCursor Definition = clang_getCursorDefinition(Result);
5066 if (!clang_equalCursors(Definition, clang_getNullCursor())) {
5067 CXSourceLocation DefinitionLoc = clang_getCursorLocation(Definition);
5068 CXString DefinitionKindSpelling
5069 = clang_getCursorKindSpelling(Definition.kind);
5070 CXFile DefinitionFile;
5071 unsigned DefinitionLine, DefinitionColumn;
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005072 clang_getFileLocation(DefinitionLoc, &DefinitionFile,
Craig Topper69186e72014-06-08 08:38:04 +00005073 &DefinitionLine, &DefinitionColumn, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005074 CXString DefinitionFileName = clang_getFileName(DefinitionFile);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005075 *Log << llvm::format(" -> %s(%s:%d:%d)",
5076 clang_getCString(DefinitionKindSpelling),
5077 clang_getCString(DefinitionFileName),
5078 DefinitionLine, DefinitionColumn);
Guy Benyei11169dd2012-12-18 14:30:41 +00005079 clang_disposeString(DefinitionFileName);
5080 clang_disposeString(DefinitionKindSpelling);
5081 }
5082 }
5083
5084 return Result;
5085}
5086
5087CXCursor clang_getNullCursor(void) {
5088 return MakeCXCursorInvalid(CXCursor_InvalidFile);
5089}
5090
5091unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Argyrios Kyrtzidisbf1be592013-01-08 18:23:28 +00005092 // Clear out the "FirstInDeclGroup" part in a declaration cursor, since we
5093 // can't set consistently. For example, when visiting a DeclStmt we will set
5094 // it but we don't set it on the result of clang_getCursorDefinition for
5095 // a reference of the same declaration.
5096 // FIXME: Setting "FirstInDeclGroup" in CXCursors is a hack that only works
5097 // when visiting a DeclStmt currently, the AST should be enhanced to be able
5098 // to provide that kind of info.
5099 if (clang_isDeclaration(X.kind))
Craig Topper69186e72014-06-08 08:38:04 +00005100 X.data[1] = nullptr;
Argyrios Kyrtzidisbf1be592013-01-08 18:23:28 +00005101 if (clang_isDeclaration(Y.kind))
Craig Topper69186e72014-06-08 08:38:04 +00005102 Y.data[1] = nullptr;
Argyrios Kyrtzidisbf1be592013-01-08 18:23:28 +00005103
Guy Benyei11169dd2012-12-18 14:30:41 +00005104 return X == Y;
5105}
5106
5107unsigned clang_hashCursor(CXCursor C) {
5108 unsigned Index = 0;
5109 if (clang_isExpression(C.kind) || clang_isStatement(C.kind))
5110 Index = 1;
5111
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005112 return llvm::DenseMapInfo<std::pair<unsigned, const void*> >::getHashValue(
Guy Benyei11169dd2012-12-18 14:30:41 +00005113 std::make_pair(C.kind, C.data[Index]));
5114}
5115
5116unsigned clang_isInvalid(enum CXCursorKind K) {
5117 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
5118}
5119
5120unsigned clang_isDeclaration(enum CXCursorKind K) {
5121 return (K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl) ||
5122 (K >= CXCursor_FirstExtraDecl && K <= CXCursor_LastExtraDecl);
5123}
5124
5125unsigned clang_isReference(enum CXCursorKind K) {
5126 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
5127}
5128
5129unsigned clang_isExpression(enum CXCursorKind K) {
5130 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
5131}
5132
5133unsigned clang_isStatement(enum CXCursorKind K) {
5134 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
5135}
5136
5137unsigned clang_isAttribute(enum CXCursorKind K) {
5138 return K >= CXCursor_FirstAttr && K <= CXCursor_LastAttr;
5139}
5140
5141unsigned clang_isTranslationUnit(enum CXCursorKind K) {
5142 return K == CXCursor_TranslationUnit;
5143}
5144
5145unsigned clang_isPreprocessing(enum CXCursorKind K) {
5146 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
5147}
5148
5149unsigned clang_isUnexposed(enum CXCursorKind K) {
5150 switch (K) {
5151 case CXCursor_UnexposedDecl:
5152 case CXCursor_UnexposedExpr:
5153 case CXCursor_UnexposedStmt:
5154 case CXCursor_UnexposedAttr:
5155 return true;
5156 default:
5157 return false;
5158 }
5159}
5160
5161CXCursorKind clang_getCursorKind(CXCursor C) {
5162 return C.kind;
5163}
5164
5165CXSourceLocation clang_getCursorLocation(CXCursor C) {
5166 if (clang_isReference(C.kind)) {
5167 switch (C.kind) {
5168 case CXCursor_ObjCSuperClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005169 std::pair<const ObjCInterfaceDecl *, SourceLocation> P
Guy Benyei11169dd2012-12-18 14:30:41 +00005170 = getCursorObjCSuperClassRef(C);
5171 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5172 }
5173
5174 case CXCursor_ObjCProtocolRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005175 std::pair<const ObjCProtocolDecl *, SourceLocation> P
Guy Benyei11169dd2012-12-18 14:30:41 +00005176 = getCursorObjCProtocolRef(C);
5177 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5178 }
5179
5180 case CXCursor_ObjCClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005181 std::pair<const ObjCInterfaceDecl *, SourceLocation> P
Guy Benyei11169dd2012-12-18 14:30:41 +00005182 = getCursorObjCClassRef(C);
5183 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5184 }
5185
5186 case CXCursor_TypeRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005187 std::pair<const TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005188 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5189 }
5190
5191 case CXCursor_TemplateRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005192 std::pair<const TemplateDecl *, SourceLocation> P =
5193 getCursorTemplateRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005194 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5195 }
5196
5197 case CXCursor_NamespaceRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005198 std::pair<const NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005199 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5200 }
5201
5202 case CXCursor_MemberRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005203 std::pair<const FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005204 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5205 }
5206
5207 case CXCursor_VariableRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005208 std::pair<const VarDecl *, SourceLocation> P = getCursorVariableRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005209 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5210 }
5211
5212 case CXCursor_CXXBaseSpecifier: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005213 const CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005214 if (!BaseSpec)
5215 return clang_getNullLocation();
5216
5217 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
5218 return cxloc::translateSourceLocation(getCursorContext(C),
5219 TSInfo->getTypeLoc().getBeginLoc());
5220
5221 return cxloc::translateSourceLocation(getCursorContext(C),
5222 BaseSpec->getLocStart());
5223 }
5224
5225 case CXCursor_LabelRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005226 std::pair<const LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005227 return cxloc::translateSourceLocation(getCursorContext(C), P.second);
5228 }
5229
5230 case CXCursor_OverloadedDeclRef:
5231 return cxloc::translateSourceLocation(getCursorContext(C),
5232 getCursorOverloadedDeclRef(C).second);
5233
5234 default:
5235 // FIXME: Need a way to enumerate all non-reference cases.
5236 llvm_unreachable("Missed a reference kind");
5237 }
5238 }
5239
5240 if (clang_isExpression(C.kind))
5241 return cxloc::translateSourceLocation(getCursorContext(C),
5242 getLocationFromExpr(getCursorExpr(C)));
5243
5244 if (clang_isStatement(C.kind))
5245 return cxloc::translateSourceLocation(getCursorContext(C),
5246 getCursorStmt(C)->getLocStart());
5247
5248 if (C.kind == CXCursor_PreprocessingDirective) {
5249 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
5250 return cxloc::translateSourceLocation(getCursorContext(C), L);
5251 }
5252
5253 if (C.kind == CXCursor_MacroExpansion) {
5254 SourceLocation L
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00005255 = cxcursor::getCursorMacroExpansion(C).getSourceRange().getBegin();
Guy Benyei11169dd2012-12-18 14:30:41 +00005256 return cxloc::translateSourceLocation(getCursorContext(C), L);
5257 }
5258
5259 if (C.kind == CXCursor_MacroDefinition) {
5260 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
5261 return cxloc::translateSourceLocation(getCursorContext(C), L);
5262 }
5263
5264 if (C.kind == CXCursor_InclusionDirective) {
5265 SourceLocation L
5266 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
5267 return cxloc::translateSourceLocation(getCursorContext(C), L);
5268 }
5269
Argyrios Kyrtzidis16834f12013-09-25 00:14:38 +00005270 if (clang_isAttribute(C.kind)) {
5271 SourceLocation L
5272 = cxcursor::getCursorAttr(C)->getLocation();
5273 return cxloc::translateSourceLocation(getCursorContext(C), L);
5274 }
5275
Guy Benyei11169dd2012-12-18 14:30:41 +00005276 if (!clang_isDeclaration(C.kind))
5277 return clang_getNullLocation();
5278
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005279 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005280 if (!D)
5281 return clang_getNullLocation();
5282
5283 SourceLocation Loc = D->getLocation();
5284 // FIXME: Multiple variables declared in a single declaration
5285 // currently lack the information needed to correctly determine their
5286 // ranges when accounting for the type-specifier. We use context
5287 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
5288 // and if so, whether it is the first decl.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005289 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005290 if (!cxcursor::isFirstInDeclGroup(C))
5291 Loc = VD->getLocation();
5292 }
5293
5294 // For ObjC methods, give the start location of the method name.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005295 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00005296 Loc = MD->getSelectorStartLoc();
5297
5298 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
5299}
5300
5301} // end extern "C"
5302
5303CXCursor cxcursor::getCursor(CXTranslationUnit TU, SourceLocation SLoc) {
5304 assert(TU);
5305
5306 // Guard against an invalid SourceLocation, or we may assert in one
5307 // of the following calls.
5308 if (SLoc.isInvalid())
5309 return clang_getNullCursor();
5310
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00005311 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00005312
5313 // Translate the given source location to make it point at the beginning of
5314 // the token under the cursor.
5315 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
5316 CXXUnit->getASTContext().getLangOpts());
5317
5318 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
5319 if (SLoc.isValid()) {
5320 GetCursorData ResultData(CXXUnit->getSourceManager(), SLoc, Result);
5321 CursorVisitor CursorVis(TU, GetCursorVisitor, &ResultData,
5322 /*VisitPreprocessorLast=*/true,
5323 /*VisitIncludedEntities=*/false,
5324 SourceLocation(SLoc));
5325 CursorVis.visitFileRegion();
5326 }
5327
5328 return Result;
5329}
5330
5331static SourceRange getRawCursorExtent(CXCursor C) {
5332 if (clang_isReference(C.kind)) {
5333 switch (C.kind) {
5334 case CXCursor_ObjCSuperClassRef:
5335 return getCursorObjCSuperClassRef(C).second;
5336
5337 case CXCursor_ObjCProtocolRef:
5338 return getCursorObjCProtocolRef(C).second;
5339
5340 case CXCursor_ObjCClassRef:
5341 return getCursorObjCClassRef(C).second;
5342
5343 case CXCursor_TypeRef:
5344 return getCursorTypeRef(C).second;
5345
5346 case CXCursor_TemplateRef:
5347 return getCursorTemplateRef(C).second;
5348
5349 case CXCursor_NamespaceRef:
5350 return getCursorNamespaceRef(C).second;
5351
5352 case CXCursor_MemberRef:
5353 return getCursorMemberRef(C).second;
5354
5355 case CXCursor_CXXBaseSpecifier:
5356 return getCursorCXXBaseSpecifier(C)->getSourceRange();
5357
5358 case CXCursor_LabelRef:
5359 return getCursorLabelRef(C).second;
5360
5361 case CXCursor_OverloadedDeclRef:
5362 return getCursorOverloadedDeclRef(C).second;
5363
5364 case CXCursor_VariableRef:
5365 return getCursorVariableRef(C).second;
5366
5367 default:
5368 // FIXME: Need a way to enumerate all non-reference cases.
5369 llvm_unreachable("Missed a reference kind");
5370 }
5371 }
5372
5373 if (clang_isExpression(C.kind))
5374 return getCursorExpr(C)->getSourceRange();
5375
5376 if (clang_isStatement(C.kind))
5377 return getCursorStmt(C)->getSourceRange();
5378
5379 if (clang_isAttribute(C.kind))
5380 return getCursorAttr(C)->getRange();
5381
5382 if (C.kind == CXCursor_PreprocessingDirective)
5383 return cxcursor::getCursorPreprocessingDirective(C);
5384
5385 if (C.kind == CXCursor_MacroExpansion) {
5386 ASTUnit *TU = getCursorASTUnit(C);
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00005387 SourceRange Range = cxcursor::getCursorMacroExpansion(C).getSourceRange();
Guy Benyei11169dd2012-12-18 14:30:41 +00005388 return TU->mapRangeFromPreamble(Range);
5389 }
5390
5391 if (C.kind == CXCursor_MacroDefinition) {
5392 ASTUnit *TU = getCursorASTUnit(C);
5393 SourceRange Range = cxcursor::getCursorMacroDefinition(C)->getSourceRange();
5394 return TU->mapRangeFromPreamble(Range);
5395 }
5396
5397 if (C.kind == CXCursor_InclusionDirective) {
5398 ASTUnit *TU = getCursorASTUnit(C);
5399 SourceRange Range = cxcursor::getCursorInclusionDirective(C)->getSourceRange();
5400 return TU->mapRangeFromPreamble(Range);
5401 }
5402
5403 if (C.kind == CXCursor_TranslationUnit) {
5404 ASTUnit *TU = getCursorASTUnit(C);
5405 FileID MainID = TU->getSourceManager().getMainFileID();
5406 SourceLocation Start = TU->getSourceManager().getLocForStartOfFile(MainID);
5407 SourceLocation End = TU->getSourceManager().getLocForEndOfFile(MainID);
5408 return SourceRange(Start, End);
5409 }
5410
5411 if (clang_isDeclaration(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005412 const Decl *D = cxcursor::getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005413 if (!D)
5414 return SourceRange();
5415
5416 SourceRange R = D->getSourceRange();
5417 // FIXME: Multiple variables declared in a single declaration
5418 // currently lack the information needed to correctly determine their
5419 // ranges when accounting for the type-specifier. We use context
5420 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
5421 // and if so, whether it is the first decl.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005422 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005423 if (!cxcursor::isFirstInDeclGroup(C))
5424 R.setBegin(VD->getLocation());
5425 }
5426 return R;
5427 }
5428 return SourceRange();
5429}
5430
5431/// \brief Retrieves the "raw" cursor extent, which is then extended to include
5432/// the decl-specifier-seq for declarations.
5433static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr) {
5434 if (clang_isDeclaration(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005435 const Decl *D = cxcursor::getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005436 if (!D)
5437 return SourceRange();
5438
5439 SourceRange R = D->getSourceRange();
5440
5441 // Adjust the start of the location for declarations preceded by
5442 // declaration specifiers.
5443 SourceLocation StartLoc;
5444 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
5445 if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
5446 StartLoc = TI->getTypeLoc().getLocStart();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005447 } else if (const TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005448 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
5449 StartLoc = TI->getTypeLoc().getLocStart();
5450 }
5451
5452 if (StartLoc.isValid() && R.getBegin().isValid() &&
5453 SrcMgr.isBeforeInTranslationUnit(StartLoc, R.getBegin()))
5454 R.setBegin(StartLoc);
5455
5456 // FIXME: Multiple variables declared in a single declaration
5457 // currently lack the information needed to correctly determine their
5458 // ranges when accounting for the type-specifier. We use context
5459 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
5460 // and if so, whether it is the first decl.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005461 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005462 if (!cxcursor::isFirstInDeclGroup(C))
5463 R.setBegin(VD->getLocation());
5464 }
5465
5466 return R;
5467 }
5468
5469 return getRawCursorExtent(C);
5470}
5471
5472extern "C" {
5473
5474CXSourceRange clang_getCursorExtent(CXCursor C) {
5475 SourceRange R = getRawCursorExtent(C);
5476 if (R.isInvalid())
5477 return clang_getNullRange();
5478
5479 return cxloc::translateSourceRange(getCursorContext(C), R);
5480}
5481
5482CXCursor clang_getCursorReferenced(CXCursor C) {
5483 if (clang_isInvalid(C.kind))
5484 return clang_getNullCursor();
5485
5486 CXTranslationUnit tu = getCursorTU(C);
5487 if (clang_isDeclaration(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005488 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005489 if (!D)
5490 return clang_getNullCursor();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005491 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00005492 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), tu);
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005493 if (const ObjCPropertyImplDecl *PropImpl =
5494 dyn_cast<ObjCPropertyImplDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00005495 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
5496 return MakeCXCursor(Property, tu);
5497
5498 return C;
5499 }
5500
5501 if (clang_isExpression(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005502 const Expr *E = getCursorExpr(C);
5503 const Decl *D = getDeclFromExpr(E);
Guy Benyei11169dd2012-12-18 14:30:41 +00005504 if (D) {
5505 CXCursor declCursor = MakeCXCursor(D, tu);
5506 declCursor = getSelectorIdentifierCursor(getSelectorIdentifierIndex(C),
5507 declCursor);
5508 return declCursor;
5509 }
5510
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005511 if (const OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00005512 return MakeCursorOverloadedDeclRef(Ovl, tu);
5513
5514 return clang_getNullCursor();
5515 }
5516
5517 if (clang_isStatement(C.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00005518 const Stmt *S = getCursorStmt(C);
5519 if (const GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
Guy Benyei11169dd2012-12-18 14:30:41 +00005520 if (LabelDecl *label = Goto->getLabel())
5521 if (LabelStmt *labelS = label->getStmt())
5522 return MakeCXCursor(labelS, getCursorDecl(C), tu);
5523
5524 return clang_getNullCursor();
5525 }
Richard Smith66a81862015-05-04 02:25:31 +00005526
Guy Benyei11169dd2012-12-18 14:30:41 +00005527 if (C.kind == CXCursor_MacroExpansion) {
Richard Smith66a81862015-05-04 02:25:31 +00005528 if (const MacroDefinitionRecord *Def =
5529 getCursorMacroExpansion(C).getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00005530 return MakeMacroDefinitionCursor(Def, tu);
5531 }
5532
5533 if (!clang_isReference(C.kind))
5534 return clang_getNullCursor();
5535
5536 switch (C.kind) {
5537 case CXCursor_ObjCSuperClassRef:
5538 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, tu);
5539
5540 case CXCursor_ObjCProtocolRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005541 const ObjCProtocolDecl *Prot = getCursorObjCProtocolRef(C).first;
5542 if (const ObjCProtocolDecl *Def = Prot->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00005543 return MakeCXCursor(Def, tu);
5544
5545 return MakeCXCursor(Prot, tu);
5546 }
5547
5548 case CXCursor_ObjCClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005549 const ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
5550 if (const ObjCInterfaceDecl *Def = Class->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00005551 return MakeCXCursor(Def, tu);
5552
5553 return MakeCXCursor(Class, tu);
5554 }
5555
5556 case CXCursor_TypeRef:
5557 return MakeCXCursor(getCursorTypeRef(C).first, tu );
5558
5559 case CXCursor_TemplateRef:
5560 return MakeCXCursor(getCursorTemplateRef(C).first, tu );
5561
5562 case CXCursor_NamespaceRef:
5563 return MakeCXCursor(getCursorNamespaceRef(C).first, tu );
5564
5565 case CXCursor_MemberRef:
5566 return MakeCXCursor(getCursorMemberRef(C).first, tu );
5567
5568 case CXCursor_CXXBaseSpecifier: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005569 const CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005570 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
5571 tu ));
5572 }
5573
5574 case CXCursor_LabelRef:
5575 // FIXME: We end up faking the "parent" declaration here because we
5576 // don't want to make CXCursor larger.
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00005577 return MakeCXCursor(getCursorLabelRef(C).first,
5578 cxtu::getASTUnit(tu)->getASTContext()
5579 .getTranslationUnitDecl(),
Guy Benyei11169dd2012-12-18 14:30:41 +00005580 tu);
5581
5582 case CXCursor_OverloadedDeclRef:
5583 return C;
5584
5585 case CXCursor_VariableRef:
5586 return MakeCXCursor(getCursorVariableRef(C).first, tu);
5587
5588 default:
5589 // We would prefer to enumerate all non-reference cursor kinds here.
5590 llvm_unreachable("Unhandled reference cursor kind");
5591 }
5592}
5593
5594CXCursor clang_getCursorDefinition(CXCursor C) {
5595 if (clang_isInvalid(C.kind))
5596 return clang_getNullCursor();
5597
5598 CXTranslationUnit TU = getCursorTU(C);
5599
5600 bool WasReference = false;
5601 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
5602 C = clang_getCursorReferenced(C);
5603 WasReference = true;
5604 }
5605
5606 if (C.kind == CXCursor_MacroExpansion)
5607 return clang_getCursorReferenced(C);
5608
5609 if (!clang_isDeclaration(C.kind))
5610 return clang_getNullCursor();
5611
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005612 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005613 if (!D)
5614 return clang_getNullCursor();
5615
5616 switch (D->getKind()) {
5617 // Declaration kinds that don't really separate the notions of
5618 // declaration and definition.
5619 case Decl::Namespace:
5620 case Decl::Typedef:
5621 case Decl::TypeAlias:
5622 case Decl::TypeAliasTemplate:
5623 case Decl::TemplateTypeParm:
5624 case Decl::EnumConstant:
5625 case Decl::Field:
Richard Smithbdb84f32016-07-22 23:36:59 +00005626 case Decl::Binding:
John McCall5e77d762013-04-16 07:28:30 +00005627 case Decl::MSProperty:
Guy Benyei11169dd2012-12-18 14:30:41 +00005628 case Decl::IndirectField:
5629 case Decl::ObjCIvar:
5630 case Decl::ObjCAtDefsField:
5631 case Decl::ImplicitParam:
5632 case Decl::ParmVar:
5633 case Decl::NonTypeTemplateParm:
5634 case Decl::TemplateTemplateParm:
5635 case Decl::ObjCCategoryImpl:
5636 case Decl::ObjCImplementation:
5637 case Decl::AccessSpec:
5638 case Decl::LinkageSpec:
Richard Smith8df390f2016-09-08 23:14:54 +00005639 case Decl::Export:
Guy Benyei11169dd2012-12-18 14:30:41 +00005640 case Decl::ObjCPropertyImpl:
5641 case Decl::FileScopeAsm:
5642 case Decl::StaticAssert:
5643 case Decl::Block:
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00005644 case Decl::Captured:
Alexey Bataev4244be22016-02-11 05:35:55 +00005645 case Decl::OMPCapturedExpr:
Guy Benyei11169dd2012-12-18 14:30:41 +00005646 case Decl::Label: // FIXME: Is this right??
5647 case Decl::ClassScopeFunctionSpecialization:
5648 case Decl::Import:
Alexey Bataeva769e072013-03-22 06:34:35 +00005649 case Decl::OMPThreadPrivate:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00005650 case Decl::OMPDeclareReduction:
Douglas Gregor85f3f952015-07-07 03:57:15 +00005651 case Decl::ObjCTypeParam:
David Majnemerd9b1a4f2015-11-04 03:40:30 +00005652 case Decl::BuiltinTemplate:
Nico Weber66220292016-03-02 17:28:48 +00005653 case Decl::PragmaComment:
Nico Webercbbaeb12016-03-02 19:28:54 +00005654 case Decl::PragmaDetectMismatch:
Guy Benyei11169dd2012-12-18 14:30:41 +00005655 return C;
5656
5657 // Declaration kinds that don't make any sense here, but are
5658 // nonetheless harmless.
David Blaikief005d3c2013-02-22 17:44:58 +00005659 case Decl::Empty:
Guy Benyei11169dd2012-12-18 14:30:41 +00005660 case Decl::TranslationUnit:
Richard Smithf19e1272015-03-07 00:04:49 +00005661 case Decl::ExternCContext:
Guy Benyei11169dd2012-12-18 14:30:41 +00005662 break;
5663
5664 // Declaration kinds for which the definition is not resolvable.
5665 case Decl::UnresolvedUsingTypename:
5666 case Decl::UnresolvedUsingValue:
5667 break;
5668
5669 case Decl::UsingDirective:
5670 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
5671 TU);
5672
5673 case Decl::NamespaceAlias:
5674 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), TU);
5675
5676 case Decl::Enum:
5677 case Decl::Record:
5678 case Decl::CXXRecord:
5679 case Decl::ClassTemplateSpecialization:
5680 case Decl::ClassTemplatePartialSpecialization:
5681 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
5682 return MakeCXCursor(Def, TU);
5683 return clang_getNullCursor();
5684
5685 case Decl::Function:
5686 case Decl::CXXMethod:
5687 case Decl::CXXConstructor:
5688 case Decl::CXXDestructor:
5689 case Decl::CXXConversion: {
Craig Topper69186e72014-06-08 08:38:04 +00005690 const FunctionDecl *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005691 if (cast<FunctionDecl>(D)->getBody(Def))
Dmitri Gribenko9c256e32013-01-14 00:46:27 +00005692 return MakeCXCursor(Def, TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00005693 return clang_getNullCursor();
5694 }
5695
Larisse Voufo39a1e502013-08-06 01:03:05 +00005696 case Decl::Var:
5697 case Decl::VarTemplateSpecialization:
Richard Smithbdb84f32016-07-22 23:36:59 +00005698 case Decl::VarTemplatePartialSpecialization:
5699 case Decl::Decomposition: {
Guy Benyei11169dd2012-12-18 14:30:41 +00005700 // Ask the variable if it has a definition.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005701 if (const VarDecl *Def = cast<VarDecl>(D)->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00005702 return MakeCXCursor(Def, TU);
5703 return clang_getNullCursor();
5704 }
5705
5706 case Decl::FunctionTemplate: {
Craig Topper69186e72014-06-08 08:38:04 +00005707 const FunctionDecl *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005708 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
5709 return MakeCXCursor(Def->getDescribedFunctionTemplate(), TU);
5710 return clang_getNullCursor();
5711 }
5712
5713 case Decl::ClassTemplate: {
5714 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
5715 ->getDefinition())
5716 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
5717 TU);
5718 return clang_getNullCursor();
5719 }
5720
Larisse Voufo39a1e502013-08-06 01:03:05 +00005721 case Decl::VarTemplate: {
5722 if (VarDecl *Def =
5723 cast<VarTemplateDecl>(D)->getTemplatedDecl()->getDefinition())
5724 return MakeCXCursor(cast<VarDecl>(Def)->getDescribedVarTemplate(), TU);
5725 return clang_getNullCursor();
5726 }
5727
Guy Benyei11169dd2012-12-18 14:30:41 +00005728 case Decl::Using:
5729 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
5730 D->getLocation(), TU);
5731
5732 case Decl::UsingShadow:
Richard Smith5179eb72016-06-28 19:03:57 +00005733 case Decl::ConstructorUsingShadow:
Guy Benyei11169dd2012-12-18 14:30:41 +00005734 return clang_getCursorDefinition(
5735 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
5736 TU));
5737
5738 case Decl::ObjCMethod: {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005739 const ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00005740 if (Method->isThisDeclarationADefinition())
5741 return C;
5742
5743 // Dig out the method definition in the associated
5744 // @implementation, if we have it.
5745 // FIXME: The ASTs should make finding the definition easier.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005746 if (const ObjCInterfaceDecl *Class
Guy Benyei11169dd2012-12-18 14:30:41 +00005747 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
5748 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
5749 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
5750 Method->isInstanceMethod()))
5751 if (Def->isThisDeclarationADefinition())
5752 return MakeCXCursor(Def, TU);
5753
5754 return clang_getNullCursor();
5755 }
5756
5757 case Decl::ObjCCategory:
5758 if (ObjCCategoryImplDecl *Impl
5759 = cast<ObjCCategoryDecl>(D)->getImplementation())
5760 return MakeCXCursor(Impl, TU);
5761 return clang_getNullCursor();
5762
5763 case Decl::ObjCProtocol:
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005764 if (const ObjCProtocolDecl *Def = cast<ObjCProtocolDecl>(D)->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00005765 return MakeCXCursor(Def, TU);
5766 return clang_getNullCursor();
5767
5768 case Decl::ObjCInterface: {
5769 // There are two notions of a "definition" for an Objective-C
5770 // class: the interface and its implementation. When we resolved a
5771 // reference to an Objective-C class, produce the @interface as
5772 // the definition; when we were provided with the interface,
5773 // produce the @implementation as the definition.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005774 const ObjCInterfaceDecl *IFace = cast<ObjCInterfaceDecl>(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00005775 if (WasReference) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005776 if (const ObjCInterfaceDecl *Def = IFace->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00005777 return MakeCXCursor(Def, TU);
5778 } else if (ObjCImplementationDecl *Impl = IFace->getImplementation())
5779 return MakeCXCursor(Impl, TU);
5780 return clang_getNullCursor();
5781 }
5782
5783 case Decl::ObjCProperty:
5784 // FIXME: We don't really know where to find the
5785 // ObjCPropertyImplDecls that implement this property.
5786 return clang_getNullCursor();
5787
5788 case Decl::ObjCCompatibleAlias:
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005789 if (const ObjCInterfaceDecl *Class
Guy Benyei11169dd2012-12-18 14:30:41 +00005790 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005791 if (const ObjCInterfaceDecl *Def = Class->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00005792 return MakeCXCursor(Def, TU);
5793
5794 return clang_getNullCursor();
5795
5796 case Decl::Friend:
5797 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
5798 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
5799 return clang_getNullCursor();
5800
5801 case Decl::FriendTemplate:
5802 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
5803 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
5804 return clang_getNullCursor();
5805 }
5806
5807 return clang_getNullCursor();
5808}
5809
5810unsigned clang_isCursorDefinition(CXCursor C) {
5811 if (!clang_isDeclaration(C.kind))
5812 return 0;
5813
5814 return clang_getCursorDefinition(C) == C;
5815}
5816
5817CXCursor clang_getCanonicalCursor(CXCursor C) {
5818 if (!clang_isDeclaration(C.kind))
5819 return C;
5820
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005821 if (const Decl *D = getCursorDecl(C)) {
5822 if (const ObjCCategoryImplDecl *CatImplD = dyn_cast<ObjCCategoryImplDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00005823 if (ObjCCategoryDecl *CatD = CatImplD->getCategoryDecl())
5824 return MakeCXCursor(CatD, getCursorTU(C));
5825
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005826 if (const ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
5827 if (const ObjCInterfaceDecl *IFD = ImplD->getClassInterface())
Guy Benyei11169dd2012-12-18 14:30:41 +00005828 return MakeCXCursor(IFD, getCursorTU(C));
5829
5830 return MakeCXCursor(D->getCanonicalDecl(), getCursorTU(C));
5831 }
5832
5833 return C;
5834}
5835
5836int clang_Cursor_getObjCSelectorIndex(CXCursor cursor) {
5837 return cxcursor::getSelectorIdentifierIndexAndLoc(cursor).first;
5838}
5839
5840unsigned clang_getNumOverloadedDecls(CXCursor C) {
5841 if (C.kind != CXCursor_OverloadedDeclRef)
5842 return 0;
5843
5844 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005845 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
Guy Benyei11169dd2012-12-18 14:30:41 +00005846 return E->getNumDecls();
5847
5848 if (OverloadedTemplateStorage *S
5849 = Storage.dyn_cast<OverloadedTemplateStorage*>())
5850 return S->size();
5851
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005852 const Decl *D = Storage.get<const Decl *>();
5853 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00005854 return Using->shadow_size();
5855
5856 return 0;
5857}
5858
5859CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
5860 if (cursor.kind != CXCursor_OverloadedDeclRef)
5861 return clang_getNullCursor();
5862
5863 if (index >= clang_getNumOverloadedDecls(cursor))
5864 return clang_getNullCursor();
5865
5866 CXTranslationUnit TU = getCursorTU(cursor);
5867 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005868 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
Guy Benyei11169dd2012-12-18 14:30:41 +00005869 return MakeCXCursor(E->decls_begin()[index], TU);
5870
5871 if (OverloadedTemplateStorage *S
5872 = Storage.dyn_cast<OverloadedTemplateStorage*>())
5873 return MakeCXCursor(S->begin()[index], TU);
5874
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005875 const Decl *D = Storage.get<const Decl *>();
5876 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005877 // FIXME: This is, unfortunately, linear time.
5878 UsingDecl::shadow_iterator Pos = Using->shadow_begin();
5879 std::advance(Pos, index);
5880 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), TU);
5881 }
5882
5883 return clang_getNullCursor();
5884}
5885
5886void clang_getDefinitionSpellingAndExtent(CXCursor C,
5887 const char **startBuf,
5888 const char **endBuf,
5889 unsigned *startLine,
5890 unsigned *startColumn,
5891 unsigned *endLine,
5892 unsigned *endColumn) {
5893 assert(getCursorDecl(C) && "CXCursor has null decl");
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005894 const FunctionDecl *FD = dyn_cast<FunctionDecl>(getCursorDecl(C));
Guy Benyei11169dd2012-12-18 14:30:41 +00005895 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
5896
5897 SourceManager &SM = FD->getASTContext().getSourceManager();
5898 *startBuf = SM.getCharacterData(Body->getLBracLoc());
5899 *endBuf = SM.getCharacterData(Body->getRBracLoc());
5900 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
5901 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
5902 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
5903 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
5904}
5905
5906
5907CXSourceRange clang_getCursorReferenceNameRange(CXCursor C, unsigned NameFlags,
5908 unsigned PieceIndex) {
5909 RefNamePieces Pieces;
5910
5911 switch (C.kind) {
5912 case CXCursor_MemberRefExpr:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00005913 if (const MemberExpr *E = dyn_cast<MemberExpr>(getCursorExpr(C)))
Guy Benyei11169dd2012-12-18 14:30:41 +00005914 Pieces = buildPieces(NameFlags, true, E->getMemberNameInfo(),
5915 E->getQualifierLoc().getSourceRange());
5916 break;
5917
5918 case CXCursor_DeclRefExpr:
James Y Knight04ec5bf2015-12-24 02:59:37 +00005919 if (const DeclRefExpr *E = dyn_cast<DeclRefExpr>(getCursorExpr(C))) {
5920 SourceRange TemplateArgLoc(E->getLAngleLoc(), E->getRAngleLoc());
5921 Pieces =
5922 buildPieces(NameFlags, false, E->getNameInfo(),
5923 E->getQualifierLoc().getSourceRange(), &TemplateArgLoc);
5924 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005925 break;
5926
5927 case CXCursor_CallExpr:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00005928 if (const CXXOperatorCallExpr *OCE =
Guy Benyei11169dd2012-12-18 14:30:41 +00005929 dyn_cast<CXXOperatorCallExpr>(getCursorExpr(C))) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00005930 const Expr *Callee = OCE->getCallee();
5931 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Callee))
Guy Benyei11169dd2012-12-18 14:30:41 +00005932 Callee = ICE->getSubExpr();
5933
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00005934 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Callee))
Guy Benyei11169dd2012-12-18 14:30:41 +00005935 Pieces = buildPieces(NameFlags, false, DRE->getNameInfo(),
5936 DRE->getQualifierLoc().getSourceRange());
5937 }
5938 break;
5939
5940 default:
5941 break;
5942 }
5943
5944 if (Pieces.empty()) {
5945 if (PieceIndex == 0)
5946 return clang_getCursorExtent(C);
5947 } else if (PieceIndex < Pieces.size()) {
5948 SourceRange R = Pieces[PieceIndex];
5949 if (R.isValid())
5950 return cxloc::translateSourceRange(getCursorContext(C), R);
5951 }
5952
5953 return clang_getNullRange();
5954}
5955
5956void clang_enableStackTraces(void) {
Richard Smithdfed58a2016-06-09 00:53:41 +00005957 // FIXME: Provide an argv0 here so we can find llvm-symbolizer.
5958 llvm::sys::PrintStackTraceOnErrorSignal(StringRef());
Guy Benyei11169dd2012-12-18 14:30:41 +00005959}
5960
5961void clang_executeOnThread(void (*fn)(void*), void *user_data,
5962 unsigned stack_size) {
5963 llvm::llvm_execute_on_thread(fn, user_data, stack_size);
5964}
5965
5966} // end: extern "C"
5967
5968//===----------------------------------------------------------------------===//
5969// Token-based Operations.
5970//===----------------------------------------------------------------------===//
5971
5972/* CXToken layout:
5973 * int_data[0]: a CXTokenKind
5974 * int_data[1]: starting token location
5975 * int_data[2]: token length
5976 * int_data[3]: reserved
5977 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
5978 * otherwise unused.
5979 */
5980extern "C" {
5981
5982CXTokenKind clang_getTokenKind(CXToken CXTok) {
5983 return static_cast<CXTokenKind>(CXTok.int_data[0]);
5984}
5985
5986CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
5987 switch (clang_getTokenKind(CXTok)) {
5988 case CXToken_Identifier:
5989 case CXToken_Keyword:
5990 // We know we have an IdentifierInfo*, so use that.
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005991 return cxstring::createRef(static_cast<IdentifierInfo *>(CXTok.ptr_data)
Guy Benyei11169dd2012-12-18 14:30:41 +00005992 ->getNameStart());
5993
5994 case CXToken_Literal: {
5995 // We have stashed the starting pointer in the ptr_data field. Use it.
5996 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00005997 return cxstring::createDup(StringRef(Text, CXTok.int_data[2]));
Guy Benyei11169dd2012-12-18 14:30:41 +00005998 }
5999
6000 case CXToken_Punctuation:
6001 case CXToken_Comment:
6002 break;
6003 }
6004
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006005 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006006 LOG_BAD_TU(TU);
6007 return cxstring::createEmpty();
6008 }
6009
Guy Benyei11169dd2012-12-18 14:30:41 +00006010 // We have to find the starting buffer pointer the hard way, by
6011 // deconstructing the source location.
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006012 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006013 if (!CXXUnit)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00006014 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00006015
6016 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
6017 std::pair<FileID, unsigned> LocInfo
6018 = CXXUnit->getSourceManager().getDecomposedSpellingLoc(Loc);
6019 bool Invalid = false;
6020 StringRef Buffer
6021 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
6022 if (Invalid)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00006023 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00006024
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00006025 return cxstring::createDup(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Guy Benyei11169dd2012-12-18 14:30:41 +00006026}
6027
6028CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006029 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006030 LOG_BAD_TU(TU);
6031 return clang_getNullLocation();
6032 }
6033
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006034 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006035 if (!CXXUnit)
6036 return clang_getNullLocation();
6037
6038 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
6039 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
6040}
6041
6042CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006043 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006044 LOG_BAD_TU(TU);
6045 return clang_getNullRange();
6046 }
6047
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006048 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006049 if (!CXXUnit)
6050 return clang_getNullRange();
6051
6052 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
6053 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
6054}
6055
6056static void getTokens(ASTUnit *CXXUnit, SourceRange Range,
6057 SmallVectorImpl<CXToken> &CXTokens) {
6058 SourceManager &SourceMgr = CXXUnit->getSourceManager();
6059 std::pair<FileID, unsigned> BeginLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00006060 = SourceMgr.getDecomposedSpellingLoc(Range.getBegin());
Guy Benyei11169dd2012-12-18 14:30:41 +00006061 std::pair<FileID, unsigned> EndLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00006062 = SourceMgr.getDecomposedSpellingLoc(Range.getEnd());
Guy Benyei11169dd2012-12-18 14:30:41 +00006063
6064 // Cannot tokenize across files.
6065 if (BeginLocInfo.first != EndLocInfo.first)
6066 return;
6067
6068 // Create a lexer
6069 bool Invalid = false;
6070 StringRef Buffer
6071 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
6072 if (Invalid)
6073 return;
6074
6075 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
6076 CXXUnit->getASTContext().getLangOpts(),
6077 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
6078 Lex.SetCommentRetentionState(true);
6079
6080 // Lex tokens until we hit the end of the range.
6081 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
6082 Token Tok;
6083 bool previousWasAt = false;
6084 do {
6085 // Lex the next token
6086 Lex.LexFromRawLexer(Tok);
6087 if (Tok.is(tok::eof))
6088 break;
6089
6090 // Initialize the CXToken.
6091 CXToken CXTok;
6092
6093 // - Common fields
6094 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
6095 CXTok.int_data[2] = Tok.getLength();
6096 CXTok.int_data[3] = 0;
6097
6098 // - Kind-specific fields
6099 if (Tok.isLiteral()) {
6100 CXTok.int_data[0] = CXToken_Literal;
Dmitri Gribenkof9304482013-01-23 15:56:07 +00006101 CXTok.ptr_data = const_cast<char *>(Tok.getLiteralData());
Guy Benyei11169dd2012-12-18 14:30:41 +00006102 } else if (Tok.is(tok::raw_identifier)) {
6103 // Lookup the identifier to determine whether we have a keyword.
6104 IdentifierInfo *II
6105 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok);
6106
6107 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
6108 CXTok.int_data[0] = CXToken_Keyword;
6109 }
6110 else {
6111 CXTok.int_data[0] = Tok.is(tok::identifier)
6112 ? CXToken_Identifier
6113 : CXToken_Keyword;
6114 }
6115 CXTok.ptr_data = II;
6116 } else if (Tok.is(tok::comment)) {
6117 CXTok.int_data[0] = CXToken_Comment;
Craig Topper69186e72014-06-08 08:38:04 +00006118 CXTok.ptr_data = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006119 } else {
6120 CXTok.int_data[0] = CXToken_Punctuation;
Craig Topper69186e72014-06-08 08:38:04 +00006121 CXTok.ptr_data = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006122 }
6123 CXTokens.push_back(CXTok);
6124 previousWasAt = Tok.is(tok::at);
6125 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
6126}
6127
6128void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
6129 CXToken **Tokens, unsigned *NumTokens) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00006130 LOG_FUNC_SECTION {
6131 *Log << TU << ' ' << Range;
6132 }
6133
Guy Benyei11169dd2012-12-18 14:30:41 +00006134 if (Tokens)
Craig Topper69186e72014-06-08 08:38:04 +00006135 *Tokens = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006136 if (NumTokens)
6137 *NumTokens = 0;
6138
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006139 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006140 LOG_BAD_TU(TU);
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00006141 return;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006142 }
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00006143
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006144 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006145 if (!CXXUnit || !Tokens || !NumTokens)
6146 return;
6147
6148 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
6149
6150 SourceRange R = cxloc::translateCXSourceRange(Range);
6151 if (R.isInvalid())
6152 return;
6153
6154 SmallVector<CXToken, 32> CXTokens;
6155 getTokens(CXXUnit, R, CXTokens);
6156
6157 if (CXTokens.empty())
6158 return;
6159
6160 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
6161 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
6162 *NumTokens = CXTokens.size();
6163}
6164
6165void clang_disposeTokens(CXTranslationUnit TU,
6166 CXToken *Tokens, unsigned NumTokens) {
6167 free(Tokens);
6168}
6169
6170} // end: extern "C"
6171
6172//===----------------------------------------------------------------------===//
6173// Token annotation APIs.
6174//===----------------------------------------------------------------------===//
6175
Guy Benyei11169dd2012-12-18 14:30:41 +00006176static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
6177 CXCursor parent,
6178 CXClientData client_data);
6179static bool AnnotateTokensPostChildrenVisitor(CXCursor cursor,
6180 CXClientData client_data);
6181
6182namespace {
6183class AnnotateTokensWorker {
Guy Benyei11169dd2012-12-18 14:30:41 +00006184 CXToken *Tokens;
6185 CXCursor *Cursors;
6186 unsigned NumTokens;
6187 unsigned TokIdx;
6188 unsigned PreprocessingTokIdx;
6189 CursorVisitor AnnotateVis;
6190 SourceManager &SrcMgr;
6191 bool HasContextSensitiveKeywords;
6192
6193 struct PostChildrenInfo {
6194 CXCursor Cursor;
6195 SourceRange CursorRange;
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006196 unsigned BeforeReachingCursorIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00006197 unsigned BeforeChildrenTokenIdx;
6198 };
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006199 SmallVector<PostChildrenInfo, 8> PostChildrenInfos;
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006200
6201 CXToken &getTok(unsigned Idx) {
6202 assert(Idx < NumTokens);
6203 return Tokens[Idx];
6204 }
6205 const CXToken &getTok(unsigned Idx) const {
6206 assert(Idx < NumTokens);
6207 return Tokens[Idx];
6208 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006209 bool MoreTokens() const { return TokIdx < NumTokens; }
6210 unsigned NextToken() const { return TokIdx; }
6211 void AdvanceToken() { ++TokIdx; }
6212 SourceLocation GetTokenLoc(unsigned tokI) {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006213 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[1]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006214 }
6215 bool isFunctionMacroToken(unsigned tokI) const {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006216 return getTok(tokI).int_data[3] != 0;
Guy Benyei11169dd2012-12-18 14:30:41 +00006217 }
6218 SourceLocation getFunctionMacroTokenLoc(unsigned tokI) const {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006219 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[3]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006220 }
6221
6222 void annotateAndAdvanceTokens(CXCursor, RangeComparisonResult, SourceRange);
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006223 bool annotateAndAdvanceFunctionMacroTokens(CXCursor, RangeComparisonResult,
Guy Benyei11169dd2012-12-18 14:30:41 +00006224 SourceRange);
6225
6226public:
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006227 AnnotateTokensWorker(CXToken *tokens, CXCursor *cursors, unsigned numTokens,
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006228 CXTranslationUnit TU, SourceRange RegionOfInterest)
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006229 : Tokens(tokens), Cursors(cursors),
Guy Benyei11169dd2012-12-18 14:30:41 +00006230 NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006231 AnnotateVis(TU,
Guy Benyei11169dd2012-12-18 14:30:41 +00006232 AnnotateTokensVisitor, this,
6233 /*VisitPreprocessorLast=*/true,
6234 /*VisitIncludedEntities=*/false,
6235 RegionOfInterest,
6236 /*VisitDeclsOnly=*/false,
6237 AnnotateTokensPostChildrenVisitor),
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006238 SrcMgr(cxtu::getASTUnit(TU)->getSourceManager()),
Guy Benyei11169dd2012-12-18 14:30:41 +00006239 HasContextSensitiveKeywords(false) { }
6240
6241 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
6242 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
6243 bool postVisitChildren(CXCursor cursor);
6244 void AnnotateTokens();
6245
6246 /// \brief Determine whether the annotator saw any cursors that have
6247 /// context-sensitive keywords.
6248 bool hasContextSensitiveKeywords() const {
6249 return HasContextSensitiveKeywords;
6250 }
6251
6252 ~AnnotateTokensWorker() {
6253 assert(PostChildrenInfos.empty());
6254 }
6255};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006256}
Guy Benyei11169dd2012-12-18 14:30:41 +00006257
6258void AnnotateTokensWorker::AnnotateTokens() {
6259 // Walk the AST within the region of interest, annotating tokens
6260 // along the way.
6261 AnnotateVis.visitFileRegion();
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006262}
Guy Benyei11169dd2012-12-18 14:30:41 +00006263
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006264static inline void updateCursorAnnotation(CXCursor &Cursor,
6265 const CXCursor &updateC) {
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006266 if (clang_isInvalid(updateC.kind) || !clang_isInvalid(Cursor.kind))
Guy Benyei11169dd2012-12-18 14:30:41 +00006267 return;
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006268 Cursor = updateC;
Guy Benyei11169dd2012-12-18 14:30:41 +00006269}
6270
6271/// \brief It annotates and advances tokens with a cursor until the comparison
6272//// between the cursor location and the source range is the same as
6273/// \arg compResult.
6274///
6275/// Pass RangeBefore to annotate tokens with a cursor until a range is reached.
6276/// Pass RangeOverlap to annotate tokens inside a range.
6277void AnnotateTokensWorker::annotateAndAdvanceTokens(CXCursor updateC,
6278 RangeComparisonResult compResult,
6279 SourceRange range) {
6280 while (MoreTokens()) {
6281 const unsigned I = NextToken();
6282 if (isFunctionMacroToken(I))
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006283 if (!annotateAndAdvanceFunctionMacroTokens(updateC, compResult, range))
6284 return;
Guy Benyei11169dd2012-12-18 14:30:41 +00006285
6286 SourceLocation TokLoc = GetTokenLoc(I);
6287 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006288 updateCursorAnnotation(Cursors[I], updateC);
Guy Benyei11169dd2012-12-18 14:30:41 +00006289 AdvanceToken();
6290 continue;
6291 }
6292 break;
6293 }
6294}
6295
6296/// \brief Special annotation handling for macro argument tokens.
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006297/// \returns true if it advanced beyond all macro tokens, false otherwise.
6298bool AnnotateTokensWorker::annotateAndAdvanceFunctionMacroTokens(
Guy Benyei11169dd2012-12-18 14:30:41 +00006299 CXCursor updateC,
6300 RangeComparisonResult compResult,
6301 SourceRange range) {
6302 assert(MoreTokens());
6303 assert(isFunctionMacroToken(NextToken()) &&
6304 "Should be called only for macro arg tokens");
6305
6306 // This works differently than annotateAndAdvanceTokens; because expanded
6307 // macro arguments can have arbitrary translation-unit source order, we do not
6308 // advance the token index one by one until a token fails the range test.
6309 // We only advance once past all of the macro arg tokens if all of them
6310 // pass the range test. If one of them fails we keep the token index pointing
6311 // at the start of the macro arg tokens so that the failing token will be
6312 // annotated by a subsequent annotation try.
6313
6314 bool atLeastOneCompFail = false;
6315
6316 unsigned I = NextToken();
6317 for (; I < NumTokens && isFunctionMacroToken(I); ++I) {
6318 SourceLocation TokLoc = getFunctionMacroTokenLoc(I);
6319 if (TokLoc.isFileID())
6320 continue; // not macro arg token, it's parens or comma.
6321 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
6322 if (clang_isInvalid(clang_getCursorKind(Cursors[I])))
6323 Cursors[I] = updateC;
6324 } else
6325 atLeastOneCompFail = true;
6326 }
6327
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006328 if (atLeastOneCompFail)
6329 return false;
6330
6331 TokIdx = I; // All of the tokens were handled, advance beyond all of them.
6332 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00006333}
6334
6335enum CXChildVisitResult
6336AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006337 SourceRange cursorRange = getRawCursorExtent(cursor);
6338 if (cursorRange.isInvalid())
6339 return CXChildVisit_Recurse;
6340
6341 if (!HasContextSensitiveKeywords) {
6342 // Objective-C properties can have context-sensitive keywords.
6343 if (cursor.kind == CXCursor_ObjCPropertyDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006344 if (const ObjCPropertyDecl *Property
Guy Benyei11169dd2012-12-18 14:30:41 +00006345 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(cursor)))
6346 HasContextSensitiveKeywords = Property->getPropertyAttributesAsWritten() != 0;
6347 }
6348 // Objective-C methods can have context-sensitive keywords.
6349 else if (cursor.kind == CXCursor_ObjCInstanceMethodDecl ||
6350 cursor.kind == CXCursor_ObjCClassMethodDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006351 if (const ObjCMethodDecl *Method
Guy Benyei11169dd2012-12-18 14:30:41 +00006352 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
6353 if (Method->getObjCDeclQualifier())
6354 HasContextSensitiveKeywords = true;
6355 else {
David Majnemer59f77922016-06-24 04:05:48 +00006356 for (const auto *P : Method->parameters()) {
Aaron Ballman43b68be2014-03-07 17:50:17 +00006357 if (P->getObjCDeclQualifier()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006358 HasContextSensitiveKeywords = true;
6359 break;
6360 }
6361 }
6362 }
6363 }
6364 }
6365 // C++ methods can have context-sensitive keywords.
6366 else if (cursor.kind == CXCursor_CXXMethod) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006367 if (const CXXMethodDecl *Method
Guy Benyei11169dd2012-12-18 14:30:41 +00006368 = dyn_cast_or_null<CXXMethodDecl>(getCursorDecl(cursor))) {
6369 if (Method->hasAttr<FinalAttr>() || Method->hasAttr<OverrideAttr>())
6370 HasContextSensitiveKeywords = true;
6371 }
6372 }
6373 // C++ classes can have context-sensitive keywords.
6374 else if (cursor.kind == CXCursor_StructDecl ||
6375 cursor.kind == CXCursor_ClassDecl ||
6376 cursor.kind == CXCursor_ClassTemplate ||
6377 cursor.kind == CXCursor_ClassTemplatePartialSpecialization) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006378 if (const Decl *D = getCursorDecl(cursor))
Guy Benyei11169dd2012-12-18 14:30:41 +00006379 if (D->hasAttr<FinalAttr>())
6380 HasContextSensitiveKeywords = true;
6381 }
6382 }
Argyrios Kyrtzidis990b3862013-06-04 18:24:30 +00006383
6384 // Don't override a property annotation with its getter/setter method.
6385 if (cursor.kind == CXCursor_ObjCInstanceMethodDecl &&
6386 parent.kind == CXCursor_ObjCPropertyDecl)
6387 return CXChildVisit_Continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00006388
6389 if (clang_isPreprocessing(cursor.kind)) {
6390 // Items in the preprocessing record are kept separate from items in
6391 // declarations, so we keep a separate token index.
6392 unsigned SavedTokIdx = TokIdx;
6393 TokIdx = PreprocessingTokIdx;
6394
6395 // Skip tokens up until we catch up to the beginning of the preprocessing
6396 // entry.
6397 while (MoreTokens()) {
6398 const unsigned I = NextToken();
6399 SourceLocation TokLoc = GetTokenLoc(I);
6400 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
6401 case RangeBefore:
6402 AdvanceToken();
6403 continue;
6404 case RangeAfter:
6405 case RangeOverlap:
6406 break;
6407 }
6408 break;
6409 }
6410
6411 // Look at all of the tokens within this range.
6412 while (MoreTokens()) {
6413 const unsigned I = NextToken();
6414 SourceLocation TokLoc = GetTokenLoc(I);
6415 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
6416 case RangeBefore:
6417 llvm_unreachable("Infeasible");
6418 case RangeAfter:
6419 break;
6420 case RangeOverlap:
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00006421 // For macro expansions, just note where the beginning of the macro
6422 // expansion occurs.
6423 if (cursor.kind == CXCursor_MacroExpansion) {
6424 if (TokLoc == cursorRange.getBegin())
6425 Cursors[I] = cursor;
6426 AdvanceToken();
6427 break;
6428 }
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006429 // We may have already annotated macro names inside macro definitions.
6430 if (Cursors[I].kind != CXCursor_MacroExpansion)
6431 Cursors[I] = cursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00006432 AdvanceToken();
Guy Benyei11169dd2012-12-18 14:30:41 +00006433 continue;
6434 }
6435 break;
6436 }
6437
6438 // Save the preprocessing token index; restore the non-preprocessing
6439 // token index.
6440 PreprocessingTokIdx = TokIdx;
6441 TokIdx = SavedTokIdx;
6442 return CXChildVisit_Recurse;
6443 }
6444
6445 if (cursorRange.isInvalid())
6446 return CXChildVisit_Continue;
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006447
6448 unsigned BeforeReachingCursorIdx = NextToken();
Guy Benyei11169dd2012-12-18 14:30:41 +00006449 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00006450 const enum CXCursorKind K = clang_getCursorKind(parent);
6451 const CXCursor updateC =
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006452 (clang_isInvalid(K) || K == CXCursor_TranslationUnit ||
6453 // Attributes are annotated out-of-order, skip tokens until we reach it.
6454 clang_isAttribute(cursor.kind))
Guy Benyei11169dd2012-12-18 14:30:41 +00006455 ? clang_getNullCursor() : parent;
6456
6457 annotateAndAdvanceTokens(updateC, RangeBefore, cursorRange);
6458
6459 // Avoid having the cursor of an expression "overwrite" the annotation of the
6460 // variable declaration that it belongs to.
6461 // This can happen for C++ constructor expressions whose range generally
6462 // include the variable declaration, e.g.:
6463 // MyCXXClass foo; // Make sure we don't annotate 'foo' as a CallExpr cursor.
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006464 if (clang_isExpression(cursorK) && MoreTokens()) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006465 const Expr *E = getCursorExpr(cursor);
Dmitri Gribenkoa1691182013-01-26 18:12:08 +00006466 if (const Decl *D = getCursorParentDecl(cursor)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006467 const unsigned I = NextToken();
6468 if (E->getLocStart().isValid() && D->getLocation().isValid() &&
6469 E->getLocStart() == D->getLocation() &&
6470 E->getLocStart() == GetTokenLoc(I)) {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006471 updateCursorAnnotation(Cursors[I], updateC);
Guy Benyei11169dd2012-12-18 14:30:41 +00006472 AdvanceToken();
6473 }
6474 }
6475 }
6476
6477 // Before recursing into the children keep some state that we are going
6478 // to use in the AnnotateTokensWorker::postVisitChildren callback to do some
6479 // extra work after the child nodes are visited.
6480 // Note that we don't call VisitChildren here to avoid traversing statements
6481 // code-recursively which can blow the stack.
6482
6483 PostChildrenInfo Info;
6484 Info.Cursor = cursor;
6485 Info.CursorRange = cursorRange;
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006486 Info.BeforeReachingCursorIdx = BeforeReachingCursorIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00006487 Info.BeforeChildrenTokenIdx = NextToken();
6488 PostChildrenInfos.push_back(Info);
6489
6490 return CXChildVisit_Recurse;
6491}
6492
6493bool AnnotateTokensWorker::postVisitChildren(CXCursor cursor) {
6494 if (PostChildrenInfos.empty())
6495 return false;
6496 const PostChildrenInfo &Info = PostChildrenInfos.back();
6497 if (!clang_equalCursors(Info.Cursor, cursor))
6498 return false;
6499
6500 const unsigned BeforeChildren = Info.BeforeChildrenTokenIdx;
6501 const unsigned AfterChildren = NextToken();
6502 SourceRange cursorRange = Info.CursorRange;
6503
6504 // Scan the tokens that are at the end of the cursor, but are not captured
6505 // but the child cursors.
6506 annotateAndAdvanceTokens(cursor, RangeOverlap, cursorRange);
6507
6508 // Scan the tokens that are at the beginning of the cursor, but are not
6509 // capture by the child cursors.
6510 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
6511 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
6512 break;
6513
6514 Cursors[I] = cursor;
6515 }
6516
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006517 // Attributes are annotated out-of-order, rewind TokIdx to when we first
6518 // encountered the attribute cursor.
6519 if (clang_isAttribute(cursor.kind))
6520 TokIdx = Info.BeforeReachingCursorIdx;
6521
Guy Benyei11169dd2012-12-18 14:30:41 +00006522 PostChildrenInfos.pop_back();
6523 return false;
6524}
6525
6526static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
6527 CXCursor parent,
6528 CXClientData client_data) {
6529 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
6530}
6531
6532static bool AnnotateTokensPostChildrenVisitor(CXCursor cursor,
6533 CXClientData client_data) {
6534 return static_cast<AnnotateTokensWorker*>(client_data)->
6535 postVisitChildren(cursor);
6536}
6537
6538namespace {
6539
6540/// \brief Uses the macro expansions in the preprocessing record to find
6541/// and mark tokens that are macro arguments. This info is used by the
6542/// AnnotateTokensWorker.
6543class MarkMacroArgTokensVisitor {
6544 SourceManager &SM;
6545 CXToken *Tokens;
6546 unsigned NumTokens;
6547 unsigned CurIdx;
6548
6549public:
6550 MarkMacroArgTokensVisitor(SourceManager &SM,
6551 CXToken *tokens, unsigned numTokens)
6552 : SM(SM), Tokens(tokens), NumTokens(numTokens), CurIdx(0) { }
6553
6554 CXChildVisitResult visit(CXCursor cursor, CXCursor parent) {
6555 if (cursor.kind != CXCursor_MacroExpansion)
6556 return CXChildVisit_Continue;
6557
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00006558 SourceRange macroRange = getCursorMacroExpansion(cursor).getSourceRange();
Guy Benyei11169dd2012-12-18 14:30:41 +00006559 if (macroRange.getBegin() == macroRange.getEnd())
6560 return CXChildVisit_Continue; // it's not a function macro.
6561
6562 for (; CurIdx < NumTokens; ++CurIdx) {
6563 if (!SM.isBeforeInTranslationUnit(getTokenLoc(CurIdx),
6564 macroRange.getBegin()))
6565 break;
6566 }
6567
6568 if (CurIdx == NumTokens)
6569 return CXChildVisit_Break;
6570
6571 for (; CurIdx < NumTokens; ++CurIdx) {
6572 SourceLocation tokLoc = getTokenLoc(CurIdx);
6573 if (!SM.isBeforeInTranslationUnit(tokLoc, macroRange.getEnd()))
6574 break;
6575
6576 setFunctionMacroTokenLoc(CurIdx, SM.getMacroArgExpandedLocation(tokLoc));
6577 }
6578
6579 if (CurIdx == NumTokens)
6580 return CXChildVisit_Break;
6581
6582 return CXChildVisit_Continue;
6583 }
6584
6585private:
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006586 CXToken &getTok(unsigned Idx) {
6587 assert(Idx < NumTokens);
6588 return Tokens[Idx];
6589 }
6590 const CXToken &getTok(unsigned Idx) const {
6591 assert(Idx < NumTokens);
6592 return Tokens[Idx];
6593 }
6594
Guy Benyei11169dd2012-12-18 14:30:41 +00006595 SourceLocation getTokenLoc(unsigned tokI) {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006596 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[1]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006597 }
6598
6599 void setFunctionMacroTokenLoc(unsigned tokI, SourceLocation loc) {
6600 // The third field is reserved and currently not used. Use it here
6601 // to mark macro arg expanded tokens with their expanded locations.
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006602 getTok(tokI).int_data[3] = loc.getRawEncoding();
Guy Benyei11169dd2012-12-18 14:30:41 +00006603 }
6604};
6605
6606} // end anonymous namespace
6607
6608static CXChildVisitResult
6609MarkMacroArgTokensVisitorDelegate(CXCursor cursor, CXCursor parent,
6610 CXClientData client_data) {
6611 return static_cast<MarkMacroArgTokensVisitor*>(client_data)->visit(cursor,
6612 parent);
6613}
6614
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006615/// \brief Used by \c annotatePreprocessorTokens.
6616/// \returns true if lexing was finished, false otherwise.
6617static bool lexNext(Lexer &Lex, Token &Tok,
6618 unsigned &NextIdx, unsigned NumTokens) {
6619 if (NextIdx >= NumTokens)
6620 return true;
6621
6622 ++NextIdx;
6623 Lex.LexFromRawLexer(Tok);
Alexander Kornienko1a9f1842015-12-28 15:24:08 +00006624 return Tok.is(tok::eof);
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006625}
6626
Guy Benyei11169dd2012-12-18 14:30:41 +00006627static void annotatePreprocessorTokens(CXTranslationUnit TU,
6628 SourceRange RegionOfInterest,
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006629 CXCursor *Cursors,
6630 CXToken *Tokens,
6631 unsigned NumTokens) {
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006632 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006633
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00006634 Preprocessor &PP = CXXUnit->getPreprocessor();
Guy Benyei11169dd2012-12-18 14:30:41 +00006635 SourceManager &SourceMgr = CXXUnit->getSourceManager();
6636 std::pair<FileID, unsigned> BeginLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00006637 = SourceMgr.getDecomposedSpellingLoc(RegionOfInterest.getBegin());
Guy Benyei11169dd2012-12-18 14:30:41 +00006638 std::pair<FileID, unsigned> EndLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00006639 = SourceMgr.getDecomposedSpellingLoc(RegionOfInterest.getEnd());
Guy Benyei11169dd2012-12-18 14:30:41 +00006640
6641 if (BeginLocInfo.first != EndLocInfo.first)
6642 return;
6643
6644 StringRef Buffer;
6645 bool Invalid = false;
6646 Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
6647 if (Buffer.empty() || Invalid)
6648 return;
6649
6650 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
6651 CXXUnit->getASTContext().getLangOpts(),
6652 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
6653 Buffer.end());
6654 Lex.SetCommentRetentionState(true);
6655
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006656 unsigned NextIdx = 0;
Guy Benyei11169dd2012-12-18 14:30:41 +00006657 // Lex tokens in raw mode until we hit the end of the range, to avoid
6658 // entering #includes or expanding macros.
6659 while (true) {
6660 Token Tok;
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006661 if (lexNext(Lex, Tok, NextIdx, NumTokens))
6662 break;
6663 unsigned TokIdx = NextIdx-1;
6664 assert(Tok.getLocation() ==
6665 SourceLocation::getFromRawEncoding(Tokens[TokIdx].int_data[1]));
Guy Benyei11169dd2012-12-18 14:30:41 +00006666
6667 reprocess:
6668 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006669 // We have found a preprocessing directive. Annotate the tokens
6670 // appropriately.
Guy Benyei11169dd2012-12-18 14:30:41 +00006671 //
6672 // FIXME: Some simple tests here could identify macro definitions and
6673 // #undefs, to provide specific cursor kinds for those.
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006674
6675 SourceLocation BeginLoc = Tok.getLocation();
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00006676 if (lexNext(Lex, Tok, NextIdx, NumTokens))
6677 break;
6678
Craig Topper69186e72014-06-08 08:38:04 +00006679 MacroInfo *MI = nullptr;
Alp Toker2d57cea2014-05-17 04:53:25 +00006680 if (Tok.is(tok::raw_identifier) && Tok.getRawIdentifier() == "define") {
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00006681 if (lexNext(Lex, Tok, NextIdx, NumTokens))
6682 break;
6683
6684 if (Tok.is(tok::raw_identifier)) {
Alp Toker2d57cea2014-05-17 04:53:25 +00006685 IdentifierInfo &II =
6686 PP.getIdentifierTable().get(Tok.getRawIdentifier());
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00006687 SourceLocation MappedTokLoc =
6688 CXXUnit->mapLocationToPreamble(Tok.getLocation());
6689 MI = getMacroInfo(II, MappedTokLoc, TU);
6690 }
6691 }
6692
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006693 bool finished = false;
Guy Benyei11169dd2012-12-18 14:30:41 +00006694 do {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006695 if (lexNext(Lex, Tok, NextIdx, NumTokens)) {
6696 finished = true;
6697 break;
6698 }
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00006699 // If we are in a macro definition, check if the token was ever a
6700 // macro name and annotate it if that's the case.
6701 if (MI) {
6702 SourceLocation SaveLoc = Tok.getLocation();
6703 Tok.setLocation(CXXUnit->mapLocationToPreamble(SaveLoc));
Richard Smith66a81862015-05-04 02:25:31 +00006704 MacroDefinitionRecord *MacroDef =
6705 checkForMacroInMacroDefinition(MI, Tok, TU);
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00006706 Tok.setLocation(SaveLoc);
6707 if (MacroDef)
Richard Smith66a81862015-05-04 02:25:31 +00006708 Cursors[NextIdx - 1] =
6709 MakeMacroExpansionCursor(MacroDef, Tok.getLocation(), TU);
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00006710 }
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006711 } while (!Tok.isAtStartOfLine());
6712
6713 unsigned LastIdx = finished ? NextIdx-1 : NextIdx-2;
6714 assert(TokIdx <= LastIdx);
6715 SourceLocation EndLoc =
6716 SourceLocation::getFromRawEncoding(Tokens[LastIdx].int_data[1]);
6717 CXCursor Cursor =
6718 MakePreprocessingDirectiveCursor(SourceRange(BeginLoc, EndLoc), TU);
6719
6720 for (; TokIdx <= LastIdx; ++TokIdx)
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00006721 updateCursorAnnotation(Cursors[TokIdx], Cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00006722
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006723 if (finished)
6724 break;
6725 goto reprocess;
Guy Benyei11169dd2012-12-18 14:30:41 +00006726 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006727 }
6728}
6729
6730// This gets run a separate thread to avoid stack blowout.
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00006731static void clang_annotateTokensImpl(CXTranslationUnit TU, ASTUnit *CXXUnit,
6732 CXToken *Tokens, unsigned NumTokens,
6733 CXCursor *Cursors) {
Dmitri Gribenko183436e2013-01-26 21:49:50 +00006734 CIndexer *CXXIdx = TU->CIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00006735 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing))
6736 setThreadBackgroundPriority();
6737
6738 // Determine the region of interest, which contains all of the tokens.
6739 SourceRange RegionOfInterest;
6740 RegionOfInterest.setBegin(
6741 cxloc::translateSourceLocation(clang_getTokenLocation(TU, Tokens[0])));
6742 RegionOfInterest.setEnd(
6743 cxloc::translateSourceLocation(clang_getTokenLocation(TU,
6744 Tokens[NumTokens-1])));
6745
Guy Benyei11169dd2012-12-18 14:30:41 +00006746 // Relex the tokens within the source range to look for preprocessing
6747 // directives.
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006748 annotatePreprocessorTokens(TU, RegionOfInterest, Cursors, Tokens, NumTokens);
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00006749
6750 // If begin location points inside a macro argument, set it to the expansion
6751 // location so we can have the full context when annotating semantically.
6752 {
6753 SourceManager &SM = CXXUnit->getSourceManager();
6754 SourceLocation Loc =
6755 SM.getMacroArgExpandedLocation(RegionOfInterest.getBegin());
6756 if (Loc.isMacroID())
6757 RegionOfInterest.setBegin(SM.getExpansionLoc(Loc));
6758 }
6759
Guy Benyei11169dd2012-12-18 14:30:41 +00006760 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
6761 // Search and mark tokens that are macro argument expansions.
6762 MarkMacroArgTokensVisitor Visitor(CXXUnit->getSourceManager(),
6763 Tokens, NumTokens);
6764 CursorVisitor MacroArgMarker(TU,
6765 MarkMacroArgTokensVisitorDelegate, &Visitor,
6766 /*VisitPreprocessorLast=*/true,
6767 /*VisitIncludedEntities=*/false,
6768 RegionOfInterest);
6769 MacroArgMarker.visitPreprocessedEntitiesInRegion();
6770 }
6771
6772 // Annotate all of the source locations in the region of interest that map to
6773 // a specific cursor.
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006774 AnnotateTokensWorker W(Tokens, Cursors, NumTokens, TU, RegionOfInterest);
Guy Benyei11169dd2012-12-18 14:30:41 +00006775
6776 // FIXME: We use a ridiculous stack size here because the data-recursion
6777 // algorithm uses a large stack frame than the non-data recursive version,
6778 // and AnnotationTokensWorker currently transforms the data-recursion
6779 // algorithm back into a traditional recursion by explicitly calling
6780 // VisitChildren(). We will need to remove this explicit recursive call.
6781 W.AnnotateTokens();
6782
6783 // If we ran into any entities that involve context-sensitive keywords,
6784 // take another pass through the tokens to mark them as such.
6785 if (W.hasContextSensitiveKeywords()) {
6786 for (unsigned I = 0; I != NumTokens; ++I) {
6787 if (clang_getTokenKind(Tokens[I]) != CXToken_Identifier)
6788 continue;
6789
6790 if (Cursors[I].kind == CXCursor_ObjCPropertyDecl) {
6791 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006792 if (const ObjCPropertyDecl *Property
Guy Benyei11169dd2012-12-18 14:30:41 +00006793 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(Cursors[I]))) {
6794 if (Property->getPropertyAttributesAsWritten() != 0 &&
6795 llvm::StringSwitch<bool>(II->getName())
6796 .Case("readonly", true)
6797 .Case("assign", true)
6798 .Case("unsafe_unretained", true)
6799 .Case("readwrite", true)
6800 .Case("retain", true)
6801 .Case("copy", true)
6802 .Case("nonatomic", true)
6803 .Case("atomic", true)
6804 .Case("getter", true)
6805 .Case("setter", true)
6806 .Case("strong", true)
6807 .Case("weak", true)
Manman Ren04fd4d82016-05-31 23:22:04 +00006808 .Case("class", true)
Guy Benyei11169dd2012-12-18 14:30:41 +00006809 .Default(false))
6810 Tokens[I].int_data[0] = CXToken_Keyword;
6811 }
6812 continue;
6813 }
6814
6815 if (Cursors[I].kind == CXCursor_ObjCInstanceMethodDecl ||
6816 Cursors[I].kind == CXCursor_ObjCClassMethodDecl) {
6817 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
6818 if (llvm::StringSwitch<bool>(II->getName())
6819 .Case("in", true)
6820 .Case("out", true)
6821 .Case("inout", true)
6822 .Case("oneway", true)
6823 .Case("bycopy", true)
6824 .Case("byref", true)
6825 .Default(false))
6826 Tokens[I].int_data[0] = CXToken_Keyword;
6827 continue;
6828 }
6829
6830 if (Cursors[I].kind == CXCursor_CXXFinalAttr ||
6831 Cursors[I].kind == CXCursor_CXXOverrideAttr) {
6832 Tokens[I].int_data[0] = CXToken_Keyword;
6833 continue;
6834 }
6835 }
6836 }
6837}
6838
6839extern "C" {
6840
6841void clang_annotateTokens(CXTranslationUnit TU,
6842 CXToken *Tokens, unsigned NumTokens,
6843 CXCursor *Cursors) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006844 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006845 LOG_BAD_TU(TU);
6846 return;
6847 }
6848 if (NumTokens == 0 || !Tokens || !Cursors) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00006849 LOG_FUNC_SECTION { *Log << "<null input>"; }
Guy Benyei11169dd2012-12-18 14:30:41 +00006850 return;
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00006851 }
6852
6853 LOG_FUNC_SECTION {
6854 *Log << TU << ' ';
6855 CXSourceLocation bloc = clang_getTokenLocation(TU, Tokens[0]);
6856 CXSourceLocation eloc = clang_getTokenLocation(TU, Tokens[NumTokens-1]);
6857 *Log << clang_getRange(bloc, eloc);
6858 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006859
6860 // Any token we don't specifically annotate will have a NULL cursor.
6861 CXCursor C = clang_getNullCursor();
6862 for (unsigned I = 0; I != NumTokens; ++I)
6863 Cursors[I] = C;
6864
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006865 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006866 if (!CXXUnit)
6867 return;
6868
6869 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00006870
6871 auto AnnotateTokensImpl = [=]() {
6872 clang_annotateTokensImpl(TU, CXXUnit, Tokens, NumTokens, Cursors);
6873 };
Guy Benyei11169dd2012-12-18 14:30:41 +00006874 llvm::CrashRecoveryContext CRC;
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00006875 if (!RunSafely(CRC, AnnotateTokensImpl, GetSafetyThreadStackSize() * 2)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006876 fprintf(stderr, "libclang: crash detected while annotating tokens\n");
6877 }
6878}
6879
6880} // end: extern "C"
6881
6882//===----------------------------------------------------------------------===//
6883// Operations for querying linkage of a cursor.
6884//===----------------------------------------------------------------------===//
6885
6886extern "C" {
6887CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
6888 if (!clang_isDeclaration(cursor.kind))
6889 return CXLinkage_Invalid;
6890
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006891 const Decl *D = cxcursor::getCursorDecl(cursor);
6892 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
Rafael Espindola3ae00052013-05-13 00:12:11 +00006893 switch (ND->getLinkageInternal()) {
Rafael Espindola50df3a02013-05-25 17:16:20 +00006894 case NoLinkage:
6895 case VisibleNoLinkage: return CXLinkage_NoLinkage;
Guy Benyei11169dd2012-12-18 14:30:41 +00006896 case InternalLinkage: return CXLinkage_Internal;
6897 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
6898 case ExternalLinkage: return CXLinkage_External;
6899 };
6900
6901 return CXLinkage_Invalid;
6902}
6903} // end: extern "C"
6904
6905//===----------------------------------------------------------------------===//
Ehsan Akhgarib743de72016-05-31 15:55:51 +00006906// Operations for querying visibility of a cursor.
6907//===----------------------------------------------------------------------===//
6908
6909extern "C" {
6910CXVisibilityKind clang_getCursorVisibility(CXCursor cursor) {
6911 if (!clang_isDeclaration(cursor.kind))
6912 return CXVisibility_Invalid;
6913
6914 const Decl *D = cxcursor::getCursorDecl(cursor);
6915 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
6916 switch (ND->getVisibility()) {
6917 case HiddenVisibility: return CXVisibility_Hidden;
6918 case ProtectedVisibility: return CXVisibility_Protected;
6919 case DefaultVisibility: return CXVisibility_Default;
6920 };
6921
6922 return CXVisibility_Invalid;
6923}
6924} // end: extern "C"
6925
6926//===----------------------------------------------------------------------===//
Guy Benyei11169dd2012-12-18 14:30:41 +00006927// Operations for querying language of a cursor.
6928//===----------------------------------------------------------------------===//
6929
6930static CXLanguageKind getDeclLanguage(const Decl *D) {
6931 if (!D)
6932 return CXLanguage_C;
6933
6934 switch (D->getKind()) {
6935 default:
6936 break;
6937 case Decl::ImplicitParam:
6938 case Decl::ObjCAtDefsField:
6939 case Decl::ObjCCategory:
6940 case Decl::ObjCCategoryImpl:
6941 case Decl::ObjCCompatibleAlias:
6942 case Decl::ObjCImplementation:
6943 case Decl::ObjCInterface:
6944 case Decl::ObjCIvar:
6945 case Decl::ObjCMethod:
6946 case Decl::ObjCProperty:
6947 case Decl::ObjCPropertyImpl:
6948 case Decl::ObjCProtocol:
Douglas Gregor85f3f952015-07-07 03:57:15 +00006949 case Decl::ObjCTypeParam:
Guy Benyei11169dd2012-12-18 14:30:41 +00006950 return CXLanguage_ObjC;
6951 case Decl::CXXConstructor:
6952 case Decl::CXXConversion:
6953 case Decl::CXXDestructor:
6954 case Decl::CXXMethod:
6955 case Decl::CXXRecord:
6956 case Decl::ClassTemplate:
6957 case Decl::ClassTemplatePartialSpecialization:
6958 case Decl::ClassTemplateSpecialization:
6959 case Decl::Friend:
6960 case Decl::FriendTemplate:
6961 case Decl::FunctionTemplate:
6962 case Decl::LinkageSpec:
6963 case Decl::Namespace:
6964 case Decl::NamespaceAlias:
6965 case Decl::NonTypeTemplateParm:
6966 case Decl::StaticAssert:
6967 case Decl::TemplateTemplateParm:
6968 case Decl::TemplateTypeParm:
6969 case Decl::UnresolvedUsingTypename:
6970 case Decl::UnresolvedUsingValue:
6971 case Decl::Using:
6972 case Decl::UsingDirective:
6973 case Decl::UsingShadow:
6974 return CXLanguage_CPlusPlus;
6975 }
6976
6977 return CXLanguage_C;
6978}
6979
6980extern "C" {
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00006981
6982static CXAvailabilityKind getCursorAvailabilityForDecl(const Decl *D) {
6983 if (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted())
Manuel Klimek8e3a7ed2015-09-25 17:53:16 +00006984 return CXAvailability_NotAvailable;
Guy Benyei11169dd2012-12-18 14:30:41 +00006985
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00006986 switch (D->getAvailability()) {
6987 case AR_Available:
6988 case AR_NotYetIntroduced:
6989 if (const EnumConstantDecl *EnumConst = dyn_cast<EnumConstantDecl>(D))
Benjamin Kramer656363d2013-10-15 18:53:18 +00006990 return getCursorAvailabilityForDecl(
6991 cast<Decl>(EnumConst->getDeclContext()));
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00006992 return CXAvailability_Available;
6993
6994 case AR_Deprecated:
6995 return CXAvailability_Deprecated;
6996
6997 case AR_Unavailable:
6998 return CXAvailability_NotAvailable;
6999 }
Benjamin Kramer656363d2013-10-15 18:53:18 +00007000
7001 llvm_unreachable("Unknown availability kind!");
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007002}
7003
Guy Benyei11169dd2012-12-18 14:30:41 +00007004enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
7005 if (clang_isDeclaration(cursor.kind))
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007006 if (const Decl *D = cxcursor::getCursorDecl(cursor))
7007 return getCursorAvailabilityForDecl(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00007008
7009 return CXAvailability_Available;
7010}
7011
7012static CXVersion convertVersion(VersionTuple In) {
7013 CXVersion Out = { -1, -1, -1 };
7014 if (In.empty())
7015 return Out;
7016
7017 Out.Major = In.getMajor();
7018
NAKAMURA Takumic2b5d1f2013-02-21 02:32:34 +00007019 Optional<unsigned> Minor = In.getMinor();
7020 if (Minor.hasValue())
Guy Benyei11169dd2012-12-18 14:30:41 +00007021 Out.Minor = *Minor;
7022 else
7023 return Out;
7024
NAKAMURA Takumic2b5d1f2013-02-21 02:32:34 +00007025 Optional<unsigned> Subminor = In.getSubminor();
7026 if (Subminor.hasValue())
Guy Benyei11169dd2012-12-18 14:30:41 +00007027 Out.Subminor = *Subminor;
7028
7029 return Out;
7030}
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007031
7032static int getCursorPlatformAvailabilityForDecl(const Decl *D,
7033 int *always_deprecated,
7034 CXString *deprecated_message,
7035 int *always_unavailable,
7036 CXString *unavailable_message,
7037 CXPlatformAvailability *availability,
7038 int availability_size) {
7039 bool HadAvailAttr = false;
7040 int N = 0;
Aaron Ballmanb97112e2014-03-08 22:19:01 +00007041 for (auto A : D->attrs()) {
7042 if (DeprecatedAttr *Deprecated = dyn_cast<DeprecatedAttr>(A)) {
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007043 HadAvailAttr = true;
7044 if (always_deprecated)
7045 *always_deprecated = 1;
Nico Weberaacf0312014-04-24 05:16:45 +00007046 if (deprecated_message) {
Argyrios Kyrtzidisedfe07f2014-04-24 06:05:40 +00007047 clang_disposeString(*deprecated_message);
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007048 *deprecated_message = cxstring::createDup(Deprecated->getMessage());
Nico Weberaacf0312014-04-24 05:16:45 +00007049 }
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007050 continue;
7051 }
7052
Aaron Ballmanb97112e2014-03-08 22:19:01 +00007053 if (UnavailableAttr *Unavailable = dyn_cast<UnavailableAttr>(A)) {
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007054 HadAvailAttr = true;
7055 if (always_unavailable)
7056 *always_unavailable = 1;
7057 if (unavailable_message) {
Argyrios Kyrtzidisedfe07f2014-04-24 06:05:40 +00007058 clang_disposeString(*unavailable_message);
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007059 *unavailable_message = cxstring::createDup(Unavailable->getMessage());
7060 }
7061 continue;
7062 }
7063
Aaron Ballmanb97112e2014-03-08 22:19:01 +00007064 if (AvailabilityAttr *Avail = dyn_cast<AvailabilityAttr>(A)) {
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007065 HadAvailAttr = true;
7066 if (N < availability_size) {
7067 availability[N].Platform
7068 = cxstring::createDup(Avail->getPlatform()->getName());
7069 availability[N].Introduced = convertVersion(Avail->getIntroduced());
7070 availability[N].Deprecated = convertVersion(Avail->getDeprecated());
7071 availability[N].Obsoleted = convertVersion(Avail->getObsoleted());
7072 availability[N].Unavailable = Avail->getUnavailable();
7073 availability[N].Message = cxstring::createDup(Avail->getMessage());
7074 }
7075 ++N;
7076 }
7077 }
7078
7079 if (!HadAvailAttr)
7080 if (const EnumConstantDecl *EnumConst = dyn_cast<EnumConstantDecl>(D))
7081 return getCursorPlatformAvailabilityForDecl(
7082 cast<Decl>(EnumConst->getDeclContext()),
7083 always_deprecated,
7084 deprecated_message,
7085 always_unavailable,
7086 unavailable_message,
7087 availability,
7088 availability_size);
Guy Benyei11169dd2012-12-18 14:30:41 +00007089
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007090 return N;
7091}
7092
Guy Benyei11169dd2012-12-18 14:30:41 +00007093int clang_getCursorPlatformAvailability(CXCursor cursor,
7094 int *always_deprecated,
7095 CXString *deprecated_message,
7096 int *always_unavailable,
7097 CXString *unavailable_message,
7098 CXPlatformAvailability *availability,
7099 int availability_size) {
7100 if (always_deprecated)
7101 *always_deprecated = 0;
7102 if (deprecated_message)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00007103 *deprecated_message = cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00007104 if (always_unavailable)
7105 *always_unavailable = 0;
7106 if (unavailable_message)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00007107 *unavailable_message = cxstring::createEmpty();
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007108
Guy Benyei11169dd2012-12-18 14:30:41 +00007109 if (!clang_isDeclaration(cursor.kind))
7110 return 0;
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007111
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007112 const Decl *D = cxcursor::getCursorDecl(cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00007113 if (!D)
7114 return 0;
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007115
7116 return getCursorPlatformAvailabilityForDecl(D, always_deprecated,
7117 deprecated_message,
7118 always_unavailable,
7119 unavailable_message,
7120 availability,
7121 availability_size);
Guy Benyei11169dd2012-12-18 14:30:41 +00007122}
7123
7124void clang_disposeCXPlatformAvailability(CXPlatformAvailability *availability) {
7125 clang_disposeString(availability->Platform);
7126 clang_disposeString(availability->Message);
7127}
7128
7129CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
7130 if (clang_isDeclaration(cursor.kind))
7131 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
7132
7133 return CXLanguage_Invalid;
7134}
7135
7136 /// \brief If the given cursor is the "templated" declaration
7137 /// descibing a class or function template, return the class or
7138 /// function template.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007139static const Decl *maybeGetTemplateCursor(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007140 if (!D)
Craig Topper69186e72014-06-08 08:38:04 +00007141 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007142
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007143 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00007144 if (FunctionTemplateDecl *FunTmpl = FD->getDescribedFunctionTemplate())
7145 return FunTmpl;
7146
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007147 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00007148 if (ClassTemplateDecl *ClassTmpl = RD->getDescribedClassTemplate())
7149 return ClassTmpl;
7150
7151 return D;
7152}
7153
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00007154
7155enum CX_StorageClass clang_Cursor_getStorageClass(CXCursor C) {
7156 StorageClass sc = SC_None;
7157 const Decl *D = getCursorDecl(C);
7158 if (D) {
7159 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7160 sc = FD->getStorageClass();
7161 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7162 sc = VD->getStorageClass();
7163 } else {
7164 return CX_SC_Invalid;
7165 }
7166 } else {
7167 return CX_SC_Invalid;
7168 }
7169 switch (sc) {
7170 case SC_None:
7171 return CX_SC_None;
7172 case SC_Extern:
7173 return CX_SC_Extern;
7174 case SC_Static:
7175 return CX_SC_Static;
7176 case SC_PrivateExtern:
7177 return CX_SC_PrivateExtern;
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00007178 case SC_Auto:
7179 return CX_SC_Auto;
7180 case SC_Register:
7181 return CX_SC_Register;
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00007182 }
Kaelyn Takataab61e702014-10-15 18:03:26 +00007183 llvm_unreachable("Unhandled storage class!");
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00007184}
7185
Guy Benyei11169dd2012-12-18 14:30:41 +00007186CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
7187 if (clang_isDeclaration(cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007188 if (const Decl *D = getCursorDecl(cursor)) {
7189 const DeclContext *DC = D->getDeclContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00007190 if (!DC)
7191 return clang_getNullCursor();
7192
7193 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
7194 getCursorTU(cursor));
7195 }
7196 }
7197
7198 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007199 if (const Decl *D = getCursorDecl(cursor))
Guy Benyei11169dd2012-12-18 14:30:41 +00007200 return MakeCXCursor(D, getCursorTU(cursor));
7201 }
7202
7203 return clang_getNullCursor();
7204}
7205
7206CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
7207 if (clang_isDeclaration(cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007208 if (const Decl *D = getCursorDecl(cursor)) {
7209 const DeclContext *DC = D->getLexicalDeclContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00007210 if (!DC)
7211 return clang_getNullCursor();
7212
7213 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
7214 getCursorTU(cursor));
7215 }
7216 }
7217
7218 // FIXME: Note that we can't easily compute the lexical context of a
7219 // statement or expression, so we return nothing.
7220 return clang_getNullCursor();
7221}
7222
7223CXFile clang_getIncludedFile(CXCursor cursor) {
7224 if (cursor.kind != CXCursor_InclusionDirective)
Craig Topper69186e72014-06-08 08:38:04 +00007225 return nullptr;
7226
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00007227 const InclusionDirective *ID = getCursorInclusionDirective(cursor);
Dmitri Gribenkof9304482013-01-23 15:56:07 +00007228 return const_cast<FileEntry *>(ID->getFile());
Guy Benyei11169dd2012-12-18 14:30:41 +00007229}
7230
Argyrios Kyrtzidis9adfd8a2013-04-18 22:15:49 +00007231unsigned clang_Cursor_getObjCPropertyAttributes(CXCursor C, unsigned reserved) {
7232 if (C.kind != CXCursor_ObjCPropertyDecl)
7233 return CXObjCPropertyAttr_noattr;
7234
7235 unsigned Result = CXObjCPropertyAttr_noattr;
7236 const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(getCursorDecl(C));
7237 ObjCPropertyDecl::PropertyAttributeKind Attr =
7238 PD->getPropertyAttributesAsWritten();
7239
7240#define SET_CXOBJCPROP_ATTR(A) \
7241 if (Attr & ObjCPropertyDecl::OBJC_PR_##A) \
7242 Result |= CXObjCPropertyAttr_##A
7243 SET_CXOBJCPROP_ATTR(readonly);
7244 SET_CXOBJCPROP_ATTR(getter);
7245 SET_CXOBJCPROP_ATTR(assign);
7246 SET_CXOBJCPROP_ATTR(readwrite);
7247 SET_CXOBJCPROP_ATTR(retain);
7248 SET_CXOBJCPROP_ATTR(copy);
7249 SET_CXOBJCPROP_ATTR(nonatomic);
7250 SET_CXOBJCPROP_ATTR(setter);
7251 SET_CXOBJCPROP_ATTR(atomic);
7252 SET_CXOBJCPROP_ATTR(weak);
7253 SET_CXOBJCPROP_ATTR(strong);
7254 SET_CXOBJCPROP_ATTR(unsafe_unretained);
Manman Ren04fd4d82016-05-31 23:22:04 +00007255 SET_CXOBJCPROP_ATTR(class);
Argyrios Kyrtzidis9adfd8a2013-04-18 22:15:49 +00007256#undef SET_CXOBJCPROP_ATTR
7257
7258 return Result;
7259}
7260
Argyrios Kyrtzidis9d9bc012013-04-18 23:29:12 +00007261unsigned clang_Cursor_getObjCDeclQualifiers(CXCursor C) {
7262 if (!clang_isDeclaration(C.kind))
7263 return CXObjCDeclQualifier_None;
7264
7265 Decl::ObjCDeclQualifier QT = Decl::OBJC_TQ_None;
7266 const Decl *D = getCursorDecl(C);
7267 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
7268 QT = MD->getObjCDeclQualifier();
7269 else if (const ParmVarDecl *PD = dyn_cast<ParmVarDecl>(D))
7270 QT = PD->getObjCDeclQualifier();
7271 if (QT == Decl::OBJC_TQ_None)
7272 return CXObjCDeclQualifier_None;
7273
7274 unsigned Result = CXObjCDeclQualifier_None;
7275 if (QT & Decl::OBJC_TQ_In) Result |= CXObjCDeclQualifier_In;
7276 if (QT & Decl::OBJC_TQ_Inout) Result |= CXObjCDeclQualifier_Inout;
7277 if (QT & Decl::OBJC_TQ_Out) Result |= CXObjCDeclQualifier_Out;
7278 if (QT & Decl::OBJC_TQ_Bycopy) Result |= CXObjCDeclQualifier_Bycopy;
7279 if (QT & Decl::OBJC_TQ_Byref) Result |= CXObjCDeclQualifier_Byref;
7280 if (QT & Decl::OBJC_TQ_Oneway) Result |= CXObjCDeclQualifier_Oneway;
7281
7282 return Result;
7283}
7284
Argyrios Kyrtzidis7b50fc52013-07-05 20:44:37 +00007285unsigned clang_Cursor_isObjCOptional(CXCursor C) {
7286 if (!clang_isDeclaration(C.kind))
7287 return 0;
7288
7289 const Decl *D = getCursorDecl(C);
7290 if (const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D))
7291 return PD->getPropertyImplementation() == ObjCPropertyDecl::Optional;
7292 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
7293 return MD->getImplementationControl() == ObjCMethodDecl::Optional;
7294
7295 return 0;
7296}
7297
Argyrios Kyrtzidis23814e42013-04-18 23:53:05 +00007298unsigned clang_Cursor_isVariadic(CXCursor C) {
7299 if (!clang_isDeclaration(C.kind))
7300 return 0;
7301
7302 const Decl *D = getCursorDecl(C);
7303 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
7304 return FD->isVariadic();
7305 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
7306 return MD->isVariadic();
7307
7308 return 0;
7309}
7310
Guy Benyei11169dd2012-12-18 14:30:41 +00007311CXSourceRange clang_Cursor_getCommentRange(CXCursor C) {
7312 if (!clang_isDeclaration(C.kind))
7313 return clang_getNullRange();
7314
7315 const Decl *D = getCursorDecl(C);
7316 ASTContext &Context = getCursorContext(C);
7317 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
7318 if (!RC)
7319 return clang_getNullRange();
7320
7321 return cxloc::translateSourceRange(Context, RC->getSourceRange());
7322}
7323
7324CXString clang_Cursor_getRawCommentText(CXCursor C) {
7325 if (!clang_isDeclaration(C.kind))
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00007326 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00007327
7328 const Decl *D = getCursorDecl(C);
7329 ASTContext &Context = getCursorContext(C);
7330 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
7331 StringRef RawText = RC ? RC->getRawText(Context.getSourceManager()) :
7332 StringRef();
7333
7334 // Don't duplicate the string because RawText points directly into source
7335 // code.
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00007336 return cxstring::createRef(RawText);
Guy Benyei11169dd2012-12-18 14:30:41 +00007337}
7338
7339CXString clang_Cursor_getBriefCommentText(CXCursor C) {
7340 if (!clang_isDeclaration(C.kind))
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00007341 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00007342
7343 const Decl *D = getCursorDecl(C);
7344 const ASTContext &Context = getCursorContext(C);
7345 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
7346
7347 if (RC) {
7348 StringRef BriefText = RC->getBriefText(Context);
7349
7350 // Don't duplicate the string because RawComment ensures that this memory
7351 // will not go away.
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00007352 return cxstring::createRef(BriefText);
Guy Benyei11169dd2012-12-18 14:30:41 +00007353 }
7354
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00007355 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00007356}
7357
Guy Benyei11169dd2012-12-18 14:30:41 +00007358CXModule clang_Cursor_getModule(CXCursor C) {
7359 if (C.kind == CXCursor_ModuleImportDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007360 if (const ImportDecl *ImportD =
7361 dyn_cast_or_null<ImportDecl>(getCursorDecl(C)))
Guy Benyei11169dd2012-12-18 14:30:41 +00007362 return ImportD->getImportedModule();
7363 }
7364
Craig Topper69186e72014-06-08 08:38:04 +00007365 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007366}
7367
Argyrios Kyrtzidisf6d49c32014-05-14 23:14:37 +00007368CXModule clang_getModuleForFile(CXTranslationUnit TU, CXFile File) {
7369 if (isNotUsableTU(TU)) {
7370 LOG_BAD_TU(TU);
7371 return nullptr;
7372 }
7373 if (!File)
7374 return nullptr;
7375 FileEntry *FE = static_cast<FileEntry *>(File);
7376
7377 ASTUnit &Unit = *cxtu::getASTUnit(TU);
7378 HeaderSearch &HS = Unit.getPreprocessor().getHeaderSearchInfo();
7379 ModuleMap::KnownHeader Header = HS.findModuleForHeader(FE);
7380
Richard Smithfeb54b62014-10-23 02:01:19 +00007381 return Header.getModule();
Argyrios Kyrtzidisf6d49c32014-05-14 23:14:37 +00007382}
7383
Argyrios Kyrtzidis12fdb9e2013-04-26 22:47:49 +00007384CXFile clang_Module_getASTFile(CXModule CXMod) {
7385 if (!CXMod)
Craig Topper69186e72014-06-08 08:38:04 +00007386 return nullptr;
Argyrios Kyrtzidis12fdb9e2013-04-26 22:47:49 +00007387 Module *Mod = static_cast<Module*>(CXMod);
7388 return const_cast<FileEntry *>(Mod->getASTFile());
7389}
7390
Guy Benyei11169dd2012-12-18 14:30:41 +00007391CXModule clang_Module_getParent(CXModule CXMod) {
7392 if (!CXMod)
Craig Topper69186e72014-06-08 08:38:04 +00007393 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007394 Module *Mod = static_cast<Module*>(CXMod);
7395 return Mod->Parent;
7396}
7397
7398CXString clang_Module_getName(CXModule CXMod) {
7399 if (!CXMod)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00007400 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00007401 Module *Mod = static_cast<Module*>(CXMod);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00007402 return cxstring::createDup(Mod->Name);
Guy Benyei11169dd2012-12-18 14:30:41 +00007403}
7404
7405CXString clang_Module_getFullName(CXModule CXMod) {
7406 if (!CXMod)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00007407 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00007408 Module *Mod = static_cast<Module*>(CXMod);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00007409 return cxstring::createDup(Mod->getFullModuleName());
Guy Benyei11169dd2012-12-18 14:30:41 +00007410}
7411
Argyrios Kyrtzidis884337f2014-05-15 04:44:25 +00007412int clang_Module_isSystem(CXModule CXMod) {
7413 if (!CXMod)
7414 return 0;
7415 Module *Mod = static_cast<Module*>(CXMod);
7416 return Mod->IsSystem;
7417}
7418
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00007419unsigned clang_Module_getNumTopLevelHeaders(CXTranslationUnit TU,
7420 CXModule CXMod) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00007421 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00007422 LOG_BAD_TU(TU);
7423 return 0;
7424 }
7425 if (!CXMod)
Guy Benyei11169dd2012-12-18 14:30:41 +00007426 return 0;
7427 Module *Mod = static_cast<Module*>(CXMod);
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00007428 FileManager &FileMgr = cxtu::getASTUnit(TU)->getFileManager();
7429 ArrayRef<const FileEntry *> TopHeaders = Mod->getTopHeaders(FileMgr);
7430 return TopHeaders.size();
Guy Benyei11169dd2012-12-18 14:30:41 +00007431}
7432
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00007433CXFile clang_Module_getTopLevelHeader(CXTranslationUnit TU,
7434 CXModule CXMod, unsigned Index) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00007435 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00007436 LOG_BAD_TU(TU);
Craig Topper69186e72014-06-08 08:38:04 +00007437 return nullptr;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00007438 }
7439 if (!CXMod)
Craig Topper69186e72014-06-08 08:38:04 +00007440 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007441 Module *Mod = static_cast<Module*>(CXMod);
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00007442 FileManager &FileMgr = cxtu::getASTUnit(TU)->getFileManager();
Guy Benyei11169dd2012-12-18 14:30:41 +00007443
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00007444 ArrayRef<const FileEntry *> TopHeaders = Mod->getTopHeaders(FileMgr);
7445 if (Index < TopHeaders.size())
7446 return const_cast<FileEntry *>(TopHeaders[Index]);
Guy Benyei11169dd2012-12-18 14:30:41 +00007447
Craig Topper69186e72014-06-08 08:38:04 +00007448 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007449}
7450
7451} // end: extern "C"
7452
7453//===----------------------------------------------------------------------===//
7454// C++ AST instrospection.
7455//===----------------------------------------------------------------------===//
7456
7457extern "C" {
Jonathan Coe29565352016-04-27 12:48:25 +00007458
7459unsigned clang_CXXConstructor_isDefaultConstructor(CXCursor C) {
7460 if (!clang_isDeclaration(C.kind))
7461 return 0;
7462
7463 const Decl *D = cxcursor::getCursorDecl(C);
7464 const CXXConstructorDecl *Constructor =
7465 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
7466 return (Constructor && Constructor->isDefaultConstructor()) ? 1 : 0;
7467}
7468
7469unsigned clang_CXXConstructor_isCopyConstructor(CXCursor C) {
7470 if (!clang_isDeclaration(C.kind))
7471 return 0;
7472
7473 const Decl *D = cxcursor::getCursorDecl(C);
7474 const CXXConstructorDecl *Constructor =
7475 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
7476 return (Constructor && Constructor->isCopyConstructor()) ? 1 : 0;
7477}
7478
7479unsigned clang_CXXConstructor_isMoveConstructor(CXCursor C) {
7480 if (!clang_isDeclaration(C.kind))
7481 return 0;
7482
7483 const Decl *D = cxcursor::getCursorDecl(C);
7484 const CXXConstructorDecl *Constructor =
7485 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
7486 return (Constructor && Constructor->isMoveConstructor()) ? 1 : 0;
7487}
7488
7489unsigned clang_CXXConstructor_isConvertingConstructor(CXCursor C) {
7490 if (!clang_isDeclaration(C.kind))
7491 return 0;
7492
7493 const Decl *D = cxcursor::getCursorDecl(C);
7494 const CXXConstructorDecl *Constructor =
7495 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
7496 // Passing 'false' excludes constructors marked 'explicit'.
7497 return (Constructor && Constructor->isConvertingConstructor(false)) ? 1 : 0;
7498}
7499
Saleem Abdulrasool6ea75db2015-10-27 15:50:22 +00007500unsigned clang_CXXField_isMutable(CXCursor C) {
7501 if (!clang_isDeclaration(C.kind))
7502 return 0;
7503
7504 if (const auto D = cxcursor::getCursorDecl(C))
7505 if (const auto FD = dyn_cast_or_null<FieldDecl>(D))
7506 return FD->isMutable() ? 1 : 0;
7507 return 0;
7508}
7509
Dmitri Gribenko62770be2013-05-17 18:38:35 +00007510unsigned clang_CXXMethod_isPureVirtual(CXCursor C) {
7511 if (!clang_isDeclaration(C.kind))
7512 return 0;
7513
Dmitri Gribenko62770be2013-05-17 18:38:35 +00007514 const Decl *D = cxcursor::getCursorDecl(C);
Alp Tokera2794f92014-01-22 07:29:52 +00007515 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00007516 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Dmitri Gribenko62770be2013-05-17 18:38:35 +00007517 return (Method && Method->isVirtual() && Method->isPure()) ? 1 : 0;
7518}
7519
Dmitri Gribenkoe570ede2014-04-07 14:59:13 +00007520unsigned clang_CXXMethod_isConst(CXCursor C) {
7521 if (!clang_isDeclaration(C.kind))
7522 return 0;
7523
7524 const Decl *D = cxcursor::getCursorDecl(C);
7525 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00007526 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Dmitri Gribenkoe570ede2014-04-07 14:59:13 +00007527 return (Method && (Method->getTypeQualifiers() & Qualifiers::Const)) ? 1 : 0;
7528}
7529
Jonathan Coe29565352016-04-27 12:48:25 +00007530unsigned clang_CXXMethod_isDefaulted(CXCursor C) {
7531 if (!clang_isDeclaration(C.kind))
7532 return 0;
7533
7534 const Decl *D = cxcursor::getCursorDecl(C);
7535 const CXXMethodDecl *Method =
7536 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
7537 return (Method && Method->isDefaulted()) ? 1 : 0;
7538}
7539
Guy Benyei11169dd2012-12-18 14:30:41 +00007540unsigned clang_CXXMethod_isStatic(CXCursor C) {
7541 if (!clang_isDeclaration(C.kind))
7542 return 0;
7543
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007544 const Decl *D = cxcursor::getCursorDecl(C);
Alp Tokera2794f92014-01-22 07:29:52 +00007545 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00007546 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007547 return (Method && Method->isStatic()) ? 1 : 0;
7548}
7549
7550unsigned clang_CXXMethod_isVirtual(CXCursor C) {
7551 if (!clang_isDeclaration(C.kind))
7552 return 0;
7553
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007554 const Decl *D = cxcursor::getCursorDecl(C);
Alp Tokera2794f92014-01-22 07:29:52 +00007555 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00007556 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007557 return (Method && Method->isVirtual()) ? 1 : 0;
7558}
7559} // end: extern "C"
7560
7561//===----------------------------------------------------------------------===//
7562// Attribute introspection.
7563//===----------------------------------------------------------------------===//
7564
7565extern "C" {
7566CXType clang_getIBOutletCollectionType(CXCursor C) {
7567 if (C.kind != CXCursor_IBOutletCollectionAttr)
7568 return cxtype::MakeCXType(QualType(), cxcursor::getCursorTU(C));
7569
Dmitri Gribenkoe4baea62013-01-26 18:08:08 +00007570 const IBOutletCollectionAttr *A =
Guy Benyei11169dd2012-12-18 14:30:41 +00007571 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
7572
7573 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorTU(C));
7574}
7575} // end: extern "C"
7576
7577//===----------------------------------------------------------------------===//
7578// Inspecting memory usage.
7579//===----------------------------------------------------------------------===//
7580
7581typedef std::vector<CXTUResourceUsageEntry> MemUsageEntries;
7582
7583static inline void createCXTUResourceUsageEntry(MemUsageEntries &entries,
7584 enum CXTUResourceUsageKind k,
7585 unsigned long amount) {
7586 CXTUResourceUsageEntry entry = { k, amount };
7587 entries.push_back(entry);
7588}
7589
7590extern "C" {
7591
7592const char *clang_getTUResourceUsageName(CXTUResourceUsageKind kind) {
7593 const char *str = "";
7594 switch (kind) {
7595 case CXTUResourceUsage_AST:
7596 str = "ASTContext: expressions, declarations, and types";
7597 break;
7598 case CXTUResourceUsage_Identifiers:
7599 str = "ASTContext: identifiers";
7600 break;
7601 case CXTUResourceUsage_Selectors:
7602 str = "ASTContext: selectors";
7603 break;
7604 case CXTUResourceUsage_GlobalCompletionResults:
7605 str = "Code completion: cached global results";
7606 break;
7607 case CXTUResourceUsage_SourceManagerContentCache:
7608 str = "SourceManager: content cache allocator";
7609 break;
7610 case CXTUResourceUsage_AST_SideTables:
7611 str = "ASTContext: side tables";
7612 break;
7613 case CXTUResourceUsage_SourceManager_Membuffer_Malloc:
7614 str = "SourceManager: malloc'ed memory buffers";
7615 break;
7616 case CXTUResourceUsage_SourceManager_Membuffer_MMap:
7617 str = "SourceManager: mmap'ed memory buffers";
7618 break;
7619 case CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc:
7620 str = "ExternalASTSource: malloc'ed memory buffers";
7621 break;
7622 case CXTUResourceUsage_ExternalASTSource_Membuffer_MMap:
7623 str = "ExternalASTSource: mmap'ed memory buffers";
7624 break;
7625 case CXTUResourceUsage_Preprocessor:
7626 str = "Preprocessor: malloc'ed memory";
7627 break;
7628 case CXTUResourceUsage_PreprocessingRecord:
7629 str = "Preprocessor: PreprocessingRecord";
7630 break;
7631 case CXTUResourceUsage_SourceManager_DataStructures:
7632 str = "SourceManager: data structures and tables";
7633 break;
7634 case CXTUResourceUsage_Preprocessor_HeaderSearch:
7635 str = "Preprocessor: header search tables";
7636 break;
7637 }
7638 return str;
7639}
7640
7641CXTUResourceUsage clang_getCXTUResourceUsage(CXTranslationUnit TU) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00007642 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00007643 LOG_BAD_TU(TU);
Craig Topper69186e72014-06-08 08:38:04 +00007644 CXTUResourceUsage usage = { (void*) nullptr, 0, nullptr };
Guy Benyei11169dd2012-12-18 14:30:41 +00007645 return usage;
7646 }
7647
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00007648 ASTUnit *astUnit = cxtu::getASTUnit(TU);
Ahmed Charlesb8984322014-03-07 20:03:18 +00007649 std::unique_ptr<MemUsageEntries> entries(new MemUsageEntries());
Guy Benyei11169dd2012-12-18 14:30:41 +00007650 ASTContext &astContext = astUnit->getASTContext();
7651
7652 // How much memory is used by AST nodes and types?
7653 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST,
7654 (unsigned long) astContext.getASTAllocatedMemory());
7655
7656 // How much memory is used by identifiers?
7657 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Identifiers,
7658 (unsigned long) astContext.Idents.getAllocator().getTotalMemory());
7659
7660 // How much memory is used for selectors?
7661 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Selectors,
7662 (unsigned long) astContext.Selectors.getTotalMemory());
7663
7664 // How much memory is used by ASTContext's side tables?
7665 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST_SideTables,
7666 (unsigned long) astContext.getSideTableAllocatedMemory());
7667
7668 // How much memory is used for caching global code completion results?
7669 unsigned long completionBytes = 0;
7670 if (GlobalCodeCompletionAllocator *completionAllocator =
Alp Tokerf994cef2014-07-05 03:08:06 +00007671 astUnit->getCachedCompletionAllocator().get()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007672 completionBytes = completionAllocator->getTotalMemory();
7673 }
7674 createCXTUResourceUsageEntry(*entries,
7675 CXTUResourceUsage_GlobalCompletionResults,
7676 completionBytes);
7677
7678 // How much memory is being used by SourceManager's content cache?
7679 createCXTUResourceUsageEntry(*entries,
7680 CXTUResourceUsage_SourceManagerContentCache,
7681 (unsigned long) astContext.getSourceManager().getContentCacheSize());
7682
7683 // How much memory is being used by the MemoryBuffer's in SourceManager?
7684 const SourceManager::MemoryBufferSizes &srcBufs =
7685 astUnit->getSourceManager().getMemoryBufferSizes();
7686
7687 createCXTUResourceUsageEntry(*entries,
7688 CXTUResourceUsage_SourceManager_Membuffer_Malloc,
7689 (unsigned long) srcBufs.malloc_bytes);
7690 createCXTUResourceUsageEntry(*entries,
7691 CXTUResourceUsage_SourceManager_Membuffer_MMap,
7692 (unsigned long) srcBufs.mmap_bytes);
7693 createCXTUResourceUsageEntry(*entries,
7694 CXTUResourceUsage_SourceManager_DataStructures,
7695 (unsigned long) astContext.getSourceManager()
7696 .getDataStructureSizes());
7697
7698 // How much memory is being used by the ExternalASTSource?
7699 if (ExternalASTSource *esrc = astContext.getExternalSource()) {
7700 const ExternalASTSource::MemoryBufferSizes &sizes =
7701 esrc->getMemoryBufferSizes();
7702
7703 createCXTUResourceUsageEntry(*entries,
7704 CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc,
7705 (unsigned long) sizes.malloc_bytes);
7706 createCXTUResourceUsageEntry(*entries,
7707 CXTUResourceUsage_ExternalASTSource_Membuffer_MMap,
7708 (unsigned long) sizes.mmap_bytes);
7709 }
7710
7711 // How much memory is being used by the Preprocessor?
7712 Preprocessor &pp = astUnit->getPreprocessor();
7713 createCXTUResourceUsageEntry(*entries,
7714 CXTUResourceUsage_Preprocessor,
7715 pp.getTotalMemory());
7716
7717 if (PreprocessingRecord *pRec = pp.getPreprocessingRecord()) {
7718 createCXTUResourceUsageEntry(*entries,
7719 CXTUResourceUsage_PreprocessingRecord,
7720 pRec->getTotalMemory());
7721 }
7722
7723 createCXTUResourceUsageEntry(*entries,
7724 CXTUResourceUsage_Preprocessor_HeaderSearch,
7725 pp.getHeaderSearchInfo().getTotalMemory());
Craig Topper69186e72014-06-08 08:38:04 +00007726
Guy Benyei11169dd2012-12-18 14:30:41 +00007727 CXTUResourceUsage usage = { (void*) entries.get(),
7728 (unsigned) entries->size(),
Alexander Kornienko6ee521c2015-01-23 15:36:10 +00007729 !entries->empty() ? &(*entries)[0] : nullptr };
Ahmed Charles9a16beb2014-03-07 19:33:25 +00007730 entries.release();
Guy Benyei11169dd2012-12-18 14:30:41 +00007731 return usage;
7732}
7733
7734void clang_disposeCXTUResourceUsage(CXTUResourceUsage usage) {
7735 if (usage.data)
7736 delete (MemUsageEntries*) usage.data;
7737}
7738
Argyrios Kyrtzidis0e282ef2013-12-06 18:55:45 +00007739CXSourceRangeList *clang_getSkippedRanges(CXTranslationUnit TU, CXFile file) {
7740 CXSourceRangeList *skipped = new CXSourceRangeList;
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00007741 skipped->count = 0;
Craig Topper69186e72014-06-08 08:38:04 +00007742 skipped->ranges = nullptr;
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00007743
Dmitri Gribenko852d6222014-02-11 15:02:48 +00007744 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00007745 LOG_BAD_TU(TU);
7746 return skipped;
7747 }
7748
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00007749 if (!file)
7750 return skipped;
7751
7752 ASTUnit *astUnit = cxtu::getASTUnit(TU);
7753 PreprocessingRecord *ppRec = astUnit->getPreprocessor().getPreprocessingRecord();
7754 if (!ppRec)
7755 return skipped;
7756
7757 ASTContext &Ctx = astUnit->getASTContext();
7758 SourceManager &sm = Ctx.getSourceManager();
7759 FileEntry *fileEntry = static_cast<FileEntry *>(file);
7760 FileID wantedFileID = sm.translateFile(fileEntry);
7761
7762 const std::vector<SourceRange> &SkippedRanges = ppRec->getSkippedRanges();
7763 std::vector<SourceRange> wantedRanges;
7764 for (std::vector<SourceRange>::const_iterator i = SkippedRanges.begin(), ei = SkippedRanges.end();
7765 i != ei; ++i) {
7766 if (sm.getFileID(i->getBegin()) == wantedFileID || sm.getFileID(i->getEnd()) == wantedFileID)
7767 wantedRanges.push_back(*i);
7768 }
7769
7770 skipped->count = wantedRanges.size();
7771 skipped->ranges = new CXSourceRange[skipped->count];
7772 for (unsigned i = 0, ei = skipped->count; i != ei; ++i)
7773 skipped->ranges[i] = cxloc::translateSourceRange(Ctx, wantedRanges[i]);
7774
7775 return skipped;
7776}
7777
Cameron Desrochersd8091282016-08-18 15:43:55 +00007778CXSourceRangeList *clang_getAllSkippedRanges(CXTranslationUnit TU) {
7779 CXSourceRangeList *skipped = new CXSourceRangeList;
7780 skipped->count = 0;
7781 skipped->ranges = nullptr;
7782
7783 if (isNotUsableTU(TU)) {
7784 LOG_BAD_TU(TU);
7785 return skipped;
7786 }
7787
7788 ASTUnit *astUnit = cxtu::getASTUnit(TU);
7789 PreprocessingRecord *ppRec = astUnit->getPreprocessor().getPreprocessingRecord();
7790 if (!ppRec)
7791 return skipped;
7792
7793 ASTContext &Ctx = astUnit->getASTContext();
7794
7795 const std::vector<SourceRange> &SkippedRanges = ppRec->getSkippedRanges();
7796
7797 skipped->count = SkippedRanges.size();
7798 skipped->ranges = new CXSourceRange[skipped->count];
7799 for (unsigned i = 0, ei = skipped->count; i != ei; ++i)
7800 skipped->ranges[i] = cxloc::translateSourceRange(Ctx, SkippedRanges[i]);
7801
7802 return skipped;
7803}
7804
Argyrios Kyrtzidis0e282ef2013-12-06 18:55:45 +00007805void clang_disposeSourceRangeList(CXSourceRangeList *ranges) {
7806 if (ranges) {
7807 delete[] ranges->ranges;
7808 delete ranges;
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00007809 }
7810}
7811
Guy Benyei11169dd2012-12-18 14:30:41 +00007812} // end extern "C"
7813
7814void clang::PrintLibclangResourceUsage(CXTranslationUnit TU) {
7815 CXTUResourceUsage Usage = clang_getCXTUResourceUsage(TU);
7816 for (unsigned I = 0; I != Usage.numEntries; ++I)
7817 fprintf(stderr, " %s: %lu\n",
7818 clang_getTUResourceUsageName(Usage.entries[I].kind),
7819 Usage.entries[I].amount);
7820
7821 clang_disposeCXTUResourceUsage(Usage);
7822}
7823
7824//===----------------------------------------------------------------------===//
7825// Misc. utility functions.
7826//===----------------------------------------------------------------------===//
7827
7828/// Default to using an 8 MB stack size on "safety" threads.
7829static unsigned SafetyStackThreadSize = 8 << 20;
7830
7831namespace clang {
7832
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00007833bool RunSafely(llvm::CrashRecoveryContext &CRC, llvm::function_ref<void()> Fn,
Guy Benyei11169dd2012-12-18 14:30:41 +00007834 unsigned Size) {
7835 if (!Size)
7836 Size = GetSafetyThreadStackSize();
7837 if (Size)
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00007838 return CRC.RunSafelyOnThread(Fn, Size);
7839 return CRC.RunSafely(Fn);
Guy Benyei11169dd2012-12-18 14:30:41 +00007840}
7841
7842unsigned GetSafetyThreadStackSize() {
7843 return SafetyStackThreadSize;
7844}
7845
7846void SetSafetyThreadStackSize(unsigned Value) {
7847 SafetyStackThreadSize = Value;
7848}
7849
Alexander Kornienkoab9db512015-06-22 23:07:51 +00007850}
Guy Benyei11169dd2012-12-18 14:30:41 +00007851
7852void clang::setThreadBackgroundPriority() {
7853 if (getenv("LIBCLANG_BGPRIO_DISABLE"))
7854 return;
7855
Alp Toker1a86ad22014-07-06 06:24:00 +00007856#ifdef USE_DARWIN_THREADS
Guy Benyei11169dd2012-12-18 14:30:41 +00007857 setpriority(PRIO_DARWIN_THREAD, 0, PRIO_DARWIN_BG);
7858#endif
7859}
7860
7861void cxindex::printDiagsToStderr(ASTUnit *Unit) {
7862 if (!Unit)
7863 return;
7864
7865 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
7866 DEnd = Unit->stored_diag_end();
7867 D != DEnd; ++D) {
Ben Langmuir749323f2014-04-22 17:40:12 +00007868 CXStoredDiagnostic Diag(*D, Unit->getLangOpts());
Guy Benyei11169dd2012-12-18 14:30:41 +00007869 CXString Msg = clang_formatDiagnostic(&Diag,
7870 clang_defaultDiagnosticDisplayOptions());
7871 fprintf(stderr, "%s\n", clang_getCString(Msg));
7872 clang_disposeString(Msg);
7873 }
7874#ifdef LLVM_ON_WIN32
7875 // On Windows, force a flush, since there may be multiple copies of
7876 // stderr and stdout in the file system, all with different buffers
7877 // but writing to the same device.
7878 fflush(stderr);
7879#endif
7880}
7881
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007882MacroInfo *cxindex::getMacroInfo(const IdentifierInfo &II,
7883 SourceLocation MacroDefLoc,
7884 CXTranslationUnit TU){
7885 if (MacroDefLoc.isInvalid() || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00007886 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007887 if (!II.hadMacroDefinition())
Craig Topper69186e72014-06-08 08:38:04 +00007888 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007889
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00007890 ASTUnit *Unit = cxtu::getASTUnit(TU);
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007891 Preprocessor &PP = Unit->getPreprocessor();
Richard Smith20e883e2015-04-29 23:20:19 +00007892 MacroDirective *MD = PP.getLocalMacroDirectiveHistory(&II);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00007893 if (MD) {
7894 for (MacroDirective::DefInfo
7895 Def = MD->getDefinition(); Def; Def = Def.getPreviousDefinition()) {
7896 if (MacroDefLoc == Def.getMacroInfo()->getDefinitionLoc())
7897 return Def.getMacroInfo();
7898 }
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007899 }
7900
Craig Topper69186e72014-06-08 08:38:04 +00007901 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007902}
7903
Richard Smith66a81862015-05-04 02:25:31 +00007904const MacroInfo *cxindex::getMacroInfo(const MacroDefinitionRecord *MacroDef,
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00007905 CXTranslationUnit TU) {
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007906 if (!MacroDef || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00007907 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007908 const IdentifierInfo *II = MacroDef->getName();
7909 if (!II)
Craig Topper69186e72014-06-08 08:38:04 +00007910 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007911
7912 return getMacroInfo(*II, MacroDef->getLocation(), TU);
7913}
7914
Richard Smith66a81862015-05-04 02:25:31 +00007915MacroDefinitionRecord *
7916cxindex::checkForMacroInMacroDefinition(const MacroInfo *MI, const Token &Tok,
7917 CXTranslationUnit TU) {
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007918 if (!MI || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00007919 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007920 if (Tok.isNot(tok::raw_identifier))
Craig Topper69186e72014-06-08 08:38:04 +00007921 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007922
7923 if (MI->getNumTokens() == 0)
Craig Topper69186e72014-06-08 08:38:04 +00007924 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007925 SourceRange DefRange(MI->getReplacementToken(0).getLocation(),
7926 MI->getDefinitionEndLoc());
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00007927 ASTUnit *Unit = cxtu::getASTUnit(TU);
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007928
7929 // Check that the token is inside the definition and not its argument list.
7930 SourceManager &SM = Unit->getSourceManager();
7931 if (SM.isBeforeInTranslationUnit(Tok.getLocation(), DefRange.getBegin()))
Craig Topper69186e72014-06-08 08:38:04 +00007932 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007933 if (SM.isBeforeInTranslationUnit(DefRange.getEnd(), Tok.getLocation()))
Craig Topper69186e72014-06-08 08:38:04 +00007934 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007935
7936 Preprocessor &PP = Unit->getPreprocessor();
7937 PreprocessingRecord *PPRec = PP.getPreprocessingRecord();
7938 if (!PPRec)
Craig Topper69186e72014-06-08 08:38:04 +00007939 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007940
Alp Toker2d57cea2014-05-17 04:53:25 +00007941 IdentifierInfo &II = PP.getIdentifierTable().get(Tok.getRawIdentifier());
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007942 if (!II.hadMacroDefinition())
Craig Topper69186e72014-06-08 08:38:04 +00007943 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007944
7945 // Check that the identifier is not one of the macro arguments.
7946 if (std::find(MI->arg_begin(), MI->arg_end(), &II) != MI->arg_end())
Craig Topper69186e72014-06-08 08:38:04 +00007947 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007948
Richard Smith20e883e2015-04-29 23:20:19 +00007949 MacroDirective *InnerMD = PP.getLocalMacroDirectiveHistory(&II);
Argyrios Kyrtzidis09c9e812013-02-20 00:54:57 +00007950 if (!InnerMD)
Craig Topper69186e72014-06-08 08:38:04 +00007951 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007952
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00007953 return PPRec->findMacroDefinition(InnerMD->getMacroInfo());
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007954}
7955
Richard Smith66a81862015-05-04 02:25:31 +00007956MacroDefinitionRecord *
7957cxindex::checkForMacroInMacroDefinition(const MacroInfo *MI, SourceLocation Loc,
7958 CXTranslationUnit TU) {
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007959 if (Loc.isInvalid() || !MI || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00007960 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007961
7962 if (MI->getNumTokens() == 0)
Craig Topper69186e72014-06-08 08:38:04 +00007963 return nullptr;
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00007964 ASTUnit *Unit = cxtu::getASTUnit(TU);
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007965 Preprocessor &PP = Unit->getPreprocessor();
7966 if (!PP.getPreprocessingRecord())
Craig Topper69186e72014-06-08 08:38:04 +00007967 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007968 Loc = Unit->getSourceManager().getSpellingLoc(Loc);
7969 Token Tok;
7970 if (PP.getRawToken(Loc, Tok))
Craig Topper69186e72014-06-08 08:38:04 +00007971 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007972
7973 return checkForMacroInMacroDefinition(MI, Tok, TU);
7974}
7975
Guy Benyei11169dd2012-12-18 14:30:41 +00007976extern "C" {
7977
7978CXString clang_getClangVersion() {
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00007979 return cxstring::createDup(getClangFullVersion());
Guy Benyei11169dd2012-12-18 14:30:41 +00007980}
7981
7982} // end: extern "C"
7983
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00007984Logger &cxindex::Logger::operator<<(CXTranslationUnit TU) {
7985 if (TU) {
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00007986 if (ASTUnit *Unit = cxtu::getASTUnit(TU)) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00007987 LogOS << '<' << Unit->getMainFileName() << '>';
Argyrios Kyrtzidis37f2ab42013-03-05 20:21:14 +00007988 if (Unit->isMainFileAST())
7989 LogOS << " (" << Unit->getASTFileName() << ')';
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00007990 return *this;
7991 }
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00007992 } else {
7993 LogOS << "<NULL TU>";
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00007994 }
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00007995 return *this;
7996}
7997
Argyrios Kyrtzidisba4b5f82013-03-08 02:32:26 +00007998Logger &cxindex::Logger::operator<<(const FileEntry *FE) {
7999 *this << FE->getName();
8000 return *this;
8001}
8002
8003Logger &cxindex::Logger::operator<<(CXCursor cursor) {
8004 CXString cursorName = clang_getCursorDisplayName(cursor);
8005 *this << cursorName << "@" << clang_getCursorLocation(cursor);
8006 clang_disposeString(cursorName);
8007 return *this;
8008}
8009
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008010Logger &cxindex::Logger::operator<<(CXSourceLocation Loc) {
8011 CXFile File;
8012 unsigned Line, Column;
Craig Topper69186e72014-06-08 08:38:04 +00008013 clang_getFileLocation(Loc, &File, &Line, &Column, nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008014 CXString FileName = clang_getFileName(File);
8015 *this << llvm::format("(%s:%d:%d)", clang_getCString(FileName), Line, Column);
8016 clang_disposeString(FileName);
8017 return *this;
8018}
8019
8020Logger &cxindex::Logger::operator<<(CXSourceRange range) {
8021 CXSourceLocation BLoc = clang_getRangeStart(range);
8022 CXSourceLocation ELoc = clang_getRangeEnd(range);
8023
8024 CXFile BFile;
8025 unsigned BLine, BColumn;
Craig Topper69186e72014-06-08 08:38:04 +00008026 clang_getFileLocation(BLoc, &BFile, &BLine, &BColumn, nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008027
8028 CXFile EFile;
8029 unsigned ELine, EColumn;
Craig Topper69186e72014-06-08 08:38:04 +00008030 clang_getFileLocation(ELoc, &EFile, &ELine, &EColumn, nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008031
8032 CXString BFileName = clang_getFileName(BFile);
8033 if (BFile == EFile) {
8034 *this << llvm::format("[%s %d:%d-%d:%d]", clang_getCString(BFileName),
8035 BLine, BColumn, ELine, EColumn);
8036 } else {
8037 CXString EFileName = clang_getFileName(EFile);
8038 *this << llvm::format("[%s:%d:%d - ", clang_getCString(BFileName),
8039 BLine, BColumn)
8040 << llvm::format("%s:%d:%d]", clang_getCString(EFileName),
8041 ELine, EColumn);
8042 clang_disposeString(EFileName);
8043 }
8044 clang_disposeString(BFileName);
8045 return *this;
8046}
8047
8048Logger &cxindex::Logger::operator<<(CXString Str) {
8049 *this << clang_getCString(Str);
8050 return *this;
8051}
8052
8053Logger &cxindex::Logger::operator<<(const llvm::format_object_base &Fmt) {
8054 LogOS << Fmt;
8055 return *this;
8056}
8057
Chandler Carruth37ad2582014-06-27 15:14:39 +00008058static llvm::ManagedStatic<llvm::sys::Mutex> LoggingMutex;
8059
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008060cxindex::Logger::~Logger() {
Chandler Carruth37ad2582014-06-27 15:14:39 +00008061 llvm::sys::ScopedLock L(*LoggingMutex);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008062
8063 static llvm::TimeRecord sBeginTR = llvm::TimeRecord::getCurrentTime();
8064
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008065 raw_ostream &OS = llvm::errs();
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008066 OS << "[libclang:" << Name << ':';
8067
Alp Toker1a86ad22014-07-06 06:24:00 +00008068#ifdef USE_DARWIN_THREADS
8069 // TODO: Portability.
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008070 mach_port_t tid = pthread_mach_thread_np(pthread_self());
8071 OS << tid << ':';
8072#endif
8073
8074 llvm::TimeRecord TR = llvm::TimeRecord::getCurrentTime();
8075 OS << llvm::format("%7.4f] ", TR.getWallTime() - sBeginTR.getWallTime());
Yaron Keren09fb7c62015-03-10 07:33:23 +00008076 OS << Msg << '\n';
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008077
8078 if (Trace) {
Zachary Turner1fe2a8d2015-03-05 19:15:09 +00008079 llvm::sys::PrintStackTrace(OS);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008080 OS << "--------------------------------------------------\n";
8081 }
8082}
Benjamin Kramerc1ffdab2016-03-03 08:58:18 +00008083
8084#ifdef CLANG_TOOL_EXTRA_BUILD
8085// This anchor is used to force the linker to link the clang-tidy plugin.
8086extern volatile int ClangTidyPluginAnchorSource;
8087static int LLVM_ATTRIBUTE_UNUSED ClangTidyPluginAnchorDestination =
8088 ClangTidyPluginAnchorSource;
8089#endif