blob: 4a1badb68d52403fdfae304e9f093bd1f1291677 [file] [log] [blame]
Guy Benyei11169dd2012-12-18 14:30:41 +00001//===- CIndex.cpp - Clang-C Source Indexing Library -----------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the main API hooks in the Clang-C Source Indexing
11// library.
12//
13//===----------------------------------------------------------------------===//
14
15#include "CIndexer.h"
16#include "CIndexDiagnostic.h"
Chandler Carruth4b417452013-01-19 08:09:44 +000017#include "CLog.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000018#include "CXCursor.h"
19#include "CXSourceLocation.h"
20#include "CXString.h"
21#include "CXTranslationUnit.h"
22#include "CXType.h"
23#include "CursorVisitor.h"
David Blaikie0a4e61f2013-09-13 18:32:52 +000024#include "clang/AST/Attr.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000025#include "clang/AST/StmtVisitor.h"
26#include "clang/Basic/Diagnostic.h"
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +000027#include "clang/Basic/DiagnosticCategories.h"
28#include "clang/Basic/DiagnosticIDs.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000029#include "clang/Basic/Version.h"
30#include "clang/Frontend/ASTUnit.h"
31#include "clang/Frontend/CompilerInstance.h"
32#include "clang/Frontend/FrontendDiagnostic.h"
Argyrios Kyrtzidisca741ce2016-02-14 22:30:14 +000033#include "clang/Index/CodegenNameGenerator.h"
Dmitri Gribenko9e605112013-11-13 22:16:51 +000034#include "clang/Index/CommentToXML.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000035#include "clang/Lex/HeaderSearch.h"
36#include "clang/Lex/Lexer.h"
37#include "clang/Lex/PreprocessingRecord.h"
38#include "clang/Lex/Preprocessor.h"
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +000039#include "clang/Serialization/SerializationDiagnostic.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000040#include "llvm/ADT/Optional.h"
41#include "llvm/ADT/STLExtras.h"
42#include "llvm/ADT/StringSwitch.h"
Alp Toker1d257e12014-06-04 03:28:55 +000043#include "llvm/Config/llvm-config.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000044#include "llvm/Support/Compiler.h"
45#include "llvm/Support/CrashRecoveryContext.h"
Chandler Carruth4b417452013-01-19 08:09:44 +000046#include "llvm/Support/Format.h"
Chandler Carruth37ad2582014-06-27 15:14:39 +000047#include "llvm/Support/ManagedStatic.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000048#include "llvm/Support/MemoryBuffer.h"
49#include "llvm/Support/Mutex.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000050#include "llvm/Support/Program.h"
51#include "llvm/Support/SaveAndRestore.h"
52#include "llvm/Support/Signals.h"
Adrian Prantlbc068582015-07-08 01:00:30 +000053#include "llvm/Support/TargetSelect.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000054#include "llvm/Support/Threading.h"
55#include "llvm/Support/Timer.h"
56#include "llvm/Support/raw_ostream.h"
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +000057
Alp Toker1a86ad22014-07-06 06:24:00 +000058#if LLVM_ENABLE_THREADS != 0 && defined(__APPLE__)
59#define USE_DARWIN_THREADS
60#endif
61
62#ifdef USE_DARWIN_THREADS
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +000063#include <pthread.h>
64#endif
Guy Benyei11169dd2012-12-18 14:30:41 +000065
66using namespace clang;
67using namespace clang::cxcursor;
Guy Benyei11169dd2012-12-18 14:30:41 +000068using namespace clang::cxtu;
69using namespace clang::cxindex;
70
Dmitri Gribenkod36209e2013-01-26 21:32:42 +000071CXTranslationUnit cxtu::MakeCXTranslationUnit(CIndexer *CIdx, ASTUnit *AU) {
72 if (!AU)
Craig Topper69186e72014-06-08 08:38:04 +000073 return nullptr;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +000074 assert(CIdx);
Guy Benyei11169dd2012-12-18 14:30:41 +000075 CXTranslationUnit D = new CXTranslationUnitImpl();
76 D->CIdx = CIdx;
Dmitri Gribenkod36209e2013-01-26 21:32:42 +000077 D->TheASTUnit = AU;
Dmitri Gribenko74895212013-02-03 13:52:47 +000078 D->StringPool = new cxstring::CXStringPool();
Craig Topper69186e72014-06-08 08:38:04 +000079 D->Diagnostics = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +000080 D->OverridenCursorsPool = createOverridenCXCursorsPool();
Craig Topper69186e72014-06-08 08:38:04 +000081 D->CommentToXML = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +000082 return D;
83}
84
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +000085bool cxtu::isASTReadError(ASTUnit *AU) {
86 for (ASTUnit::stored_diag_iterator D = AU->stored_diag_begin(),
87 DEnd = AU->stored_diag_end();
88 D != DEnd; ++D) {
89 if (D->getLevel() >= DiagnosticsEngine::Error &&
90 DiagnosticIDs::getCategoryNumberForDiag(D->getID()) ==
91 diag::DiagCat_AST_Deserialization_Issue)
92 return true;
93 }
94 return false;
95}
96
Guy Benyei11169dd2012-12-18 14:30:41 +000097cxtu::CXTUOwner::~CXTUOwner() {
98 if (TU)
99 clang_disposeTranslationUnit(TU);
100}
101
102/// \brief Compare two source ranges to determine their relative position in
103/// the translation unit.
104static RangeComparisonResult RangeCompare(SourceManager &SM,
105 SourceRange R1,
106 SourceRange R2) {
107 assert(R1.isValid() && "First range is invalid?");
108 assert(R2.isValid() && "Second range is invalid?");
109 if (R1.getEnd() != R2.getBegin() &&
110 SM.isBeforeInTranslationUnit(R1.getEnd(), R2.getBegin()))
111 return RangeBefore;
112 if (R2.getEnd() != R1.getBegin() &&
113 SM.isBeforeInTranslationUnit(R2.getEnd(), R1.getBegin()))
114 return RangeAfter;
115 return RangeOverlap;
116}
117
118/// \brief Determine if a source location falls within, before, or after a
119/// a given source range.
120static RangeComparisonResult LocationCompare(SourceManager &SM,
121 SourceLocation L, SourceRange R) {
122 assert(R.isValid() && "First range is invalid?");
123 assert(L.isValid() && "Second range is invalid?");
124 if (L == R.getBegin() || L == R.getEnd())
125 return RangeOverlap;
126 if (SM.isBeforeInTranslationUnit(L, R.getBegin()))
127 return RangeBefore;
128 if (SM.isBeforeInTranslationUnit(R.getEnd(), L))
129 return RangeAfter;
130 return RangeOverlap;
131}
132
133/// \brief Translate a Clang source range into a CIndex source range.
134///
135/// Clang internally represents ranges where the end location points to the
136/// start of the token at the end. However, for external clients it is more
137/// useful to have a CXSourceRange be a proper half-open interval. This routine
138/// does the appropriate translation.
139CXSourceRange cxloc::translateSourceRange(const SourceManager &SM,
140 const LangOptions &LangOpts,
141 const CharSourceRange &R) {
142 // We want the last character in this location, so we will adjust the
143 // location accordingly.
144 SourceLocation EndLoc = R.getEnd();
145 if (EndLoc.isValid() && EndLoc.isMacroID() && !SM.isMacroArgExpansion(EndLoc))
146 EndLoc = SM.getExpansionRange(EndLoc).second;
Yaron Keren8b563662015-10-03 10:46:20 +0000147 if (R.isTokenRange() && EndLoc.isValid()) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000148 unsigned Length = Lexer::MeasureTokenLength(SM.getSpellingLoc(EndLoc),
149 SM, LangOpts);
150 EndLoc = EndLoc.getLocWithOffset(Length);
151 }
152
Bill Wendlingeade3622013-01-23 08:25:41 +0000153 CXSourceRange Result = {
Dmitri Gribenkof9304482013-01-23 15:56:07 +0000154 { &SM, &LangOpts },
Bill Wendlingeade3622013-01-23 08:25:41 +0000155 R.getBegin().getRawEncoding(),
156 EndLoc.getRawEncoding()
157 };
Guy Benyei11169dd2012-12-18 14:30:41 +0000158 return Result;
159}
160
161//===----------------------------------------------------------------------===//
162// Cursor visitor.
163//===----------------------------------------------------------------------===//
164
165static SourceRange getRawCursorExtent(CXCursor C);
166static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr);
167
168
169RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
170 return RangeCompare(AU->getSourceManager(), R, RegionOfInterest);
171}
172
173/// \brief Visit the given cursor and, if requested by the visitor,
174/// its children.
175///
176/// \param Cursor the cursor to visit.
177///
178/// \param CheckedRegionOfInterest if true, then the caller already checked
179/// that this cursor is within the region of interest.
180///
181/// \returns true if the visitation should be aborted, false if it
182/// should continue.
183bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
184 if (clang_isInvalid(Cursor.kind))
185 return false;
186
187 if (clang_isDeclaration(Cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +0000188 const Decl *D = getCursorDecl(Cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +0000189 if (!D) {
190 assert(0 && "Invalid declaration cursor");
191 return true; // abort.
192 }
193
194 // Ignore implicit declarations, unless it's an objc method because
195 // currently we should report implicit methods for properties when indexing.
196 if (D->isImplicit() && !isa<ObjCMethodDecl>(D))
197 return false;
198 }
199
200 // If we have a range of interest, and this cursor doesn't intersect with it,
201 // we're done.
202 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
203 SourceRange Range = getRawCursorExtent(Cursor);
204 if (Range.isInvalid() || CompareRegionOfInterest(Range))
205 return false;
206 }
207
208 switch (Visitor(Cursor, Parent, ClientData)) {
209 case CXChildVisit_Break:
210 return true;
211
212 case CXChildVisit_Continue:
213 return false;
214
215 case CXChildVisit_Recurse: {
216 bool ret = VisitChildren(Cursor);
217 if (PostChildrenVisitor)
218 if (PostChildrenVisitor(Cursor, ClientData))
219 return true;
220 return ret;
221 }
222 }
223
224 llvm_unreachable("Invalid CXChildVisitResult!");
225}
226
227static bool visitPreprocessedEntitiesInRange(SourceRange R,
228 PreprocessingRecord &PPRec,
229 CursorVisitor &Visitor) {
230 SourceManager &SM = Visitor.getASTUnit()->getSourceManager();
231 FileID FID;
232
233 if (!Visitor.shouldVisitIncludedEntities()) {
234 // If the begin/end of the range lie in the same FileID, do the optimization
235 // where we skip preprocessed entities that do not come from the same FileID.
236 FID = SM.getFileID(SM.getFileLoc(R.getBegin()));
237 if (FID != SM.getFileID(SM.getFileLoc(R.getEnd())))
238 FID = FileID();
239 }
240
Benjamin Kramerb4ef6682015-02-06 17:25:10 +0000241 const auto &Entities = PPRec.getPreprocessedEntitiesInRange(R);
242 return Visitor.visitPreprocessedEntities(Entities.begin(), Entities.end(),
Guy Benyei11169dd2012-12-18 14:30:41 +0000243 PPRec, FID);
244}
245
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000246bool CursorVisitor::visitFileRegion() {
Guy Benyei11169dd2012-12-18 14:30:41 +0000247 if (RegionOfInterest.isInvalid())
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000248 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000249
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +0000250 ASTUnit *Unit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +0000251 SourceManager &SM = Unit->getSourceManager();
252
253 std::pair<FileID, unsigned>
254 Begin = SM.getDecomposedLoc(SM.getFileLoc(RegionOfInterest.getBegin())),
255 End = SM.getDecomposedLoc(SM.getFileLoc(RegionOfInterest.getEnd()));
256
257 if (End.first != Begin.first) {
258 // If the end does not reside in the same file, try to recover by
259 // picking the end of the file of begin location.
260 End.first = Begin.first;
261 End.second = SM.getFileIDSize(Begin.first);
262 }
263
264 assert(Begin.first == End.first);
265 if (Begin.second > End.second)
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000266 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000267
268 FileID File = Begin.first;
269 unsigned Offset = Begin.second;
270 unsigned Length = End.second - Begin.second;
271
272 if (!VisitDeclsOnly && !VisitPreprocessorLast)
273 if (visitPreprocessedEntitiesInRegion())
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000274 return true; // visitation break.
Guy Benyei11169dd2012-12-18 14:30:41 +0000275
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000276 if (visitDeclsFromFileRegion(File, Offset, Length))
277 return true; // visitation break.
Guy Benyei11169dd2012-12-18 14:30:41 +0000278
279 if (!VisitDeclsOnly && VisitPreprocessorLast)
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000280 return visitPreprocessedEntitiesInRegion();
281
282 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000283}
284
285static bool isInLexicalContext(Decl *D, DeclContext *DC) {
286 if (!DC)
287 return false;
288
289 for (DeclContext *DeclDC = D->getLexicalDeclContext();
290 DeclDC; DeclDC = DeclDC->getLexicalParent()) {
291 if (DeclDC == DC)
292 return true;
293 }
294 return false;
295}
296
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000297bool CursorVisitor::visitDeclsFromFileRegion(FileID File,
Guy Benyei11169dd2012-12-18 14:30:41 +0000298 unsigned Offset, unsigned Length) {
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +0000299 ASTUnit *Unit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +0000300 SourceManager &SM = Unit->getSourceManager();
301 SourceRange Range = RegionOfInterest;
302
303 SmallVector<Decl *, 16> Decls;
304 Unit->findFileRegionDecls(File, Offset, Length, Decls);
305
306 // If we didn't find any file level decls for the file, try looking at the
307 // file that it was included from.
308 while (Decls.empty() || Decls.front()->isTopLevelDeclInObjCContainer()) {
309 bool Invalid = false;
310 const SrcMgr::SLocEntry &SLEntry = SM.getSLocEntry(File, &Invalid);
311 if (Invalid)
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000312 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000313
314 SourceLocation Outer;
315 if (SLEntry.isFile())
316 Outer = SLEntry.getFile().getIncludeLoc();
317 else
318 Outer = SLEntry.getExpansion().getExpansionLocStart();
319 if (Outer.isInvalid())
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000320 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000321
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000322 std::tie(File, Offset) = SM.getDecomposedExpansionLoc(Outer);
Guy Benyei11169dd2012-12-18 14:30:41 +0000323 Length = 0;
324 Unit->findFileRegionDecls(File, Offset, Length, Decls);
325 }
326
327 assert(!Decls.empty());
328
329 bool VisitedAtLeastOnce = false;
Craig Topper69186e72014-06-08 08:38:04 +0000330 DeclContext *CurDC = nullptr;
Craig Topper2341c0d2013-07-04 03:08:24 +0000331 SmallVectorImpl<Decl *>::iterator DIt = Decls.begin();
332 for (SmallVectorImpl<Decl *>::iterator DE = Decls.end(); DIt != DE; ++DIt) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000333 Decl *D = *DIt;
334 if (D->getSourceRange().isInvalid())
335 continue;
336
337 if (isInLexicalContext(D, CurDC))
338 continue;
339
340 CurDC = dyn_cast<DeclContext>(D);
341
342 if (TagDecl *TD = dyn_cast<TagDecl>(D))
343 if (!TD->isFreeStanding())
344 continue;
345
346 RangeComparisonResult CompRes = RangeCompare(SM, D->getSourceRange(),Range);
347 if (CompRes == RangeBefore)
348 continue;
349 if (CompRes == RangeAfter)
350 break;
351
352 assert(CompRes == RangeOverlap);
353 VisitedAtLeastOnce = true;
354
355 if (isa<ObjCContainerDecl>(D)) {
356 FileDI_current = &DIt;
357 FileDE_current = DE;
358 } else {
Craig Topper69186e72014-06-08 08:38:04 +0000359 FileDI_current = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +0000360 }
361
362 if (Visit(MakeCXCursor(D, TU, Range), /*CheckedRegionOfInterest=*/true))
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000363 return true; // visitation break.
Guy Benyei11169dd2012-12-18 14:30:41 +0000364 }
365
366 if (VisitedAtLeastOnce)
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000367 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000368
369 // No Decls overlapped with the range. Move up the lexical context until there
370 // is a context that contains the range or we reach the translation unit
371 // level.
372 DeclContext *DC = DIt == Decls.begin() ? (*DIt)->getLexicalDeclContext()
373 : (*(DIt-1))->getLexicalDeclContext();
374
375 while (DC && !DC->isTranslationUnit()) {
376 Decl *D = cast<Decl>(DC);
377 SourceRange CurDeclRange = D->getSourceRange();
378 if (CurDeclRange.isInvalid())
379 break;
380
381 if (RangeCompare(SM, CurDeclRange, Range) == RangeOverlap) {
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000382 if (Visit(MakeCXCursor(D, TU, Range), /*CheckedRegionOfInterest=*/true))
383 return true; // visitation break.
Guy Benyei11169dd2012-12-18 14:30:41 +0000384 }
385
386 DC = D->getLexicalDeclContext();
387 }
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000388
389 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000390}
391
392bool CursorVisitor::visitPreprocessedEntitiesInRegion() {
393 if (!AU->getPreprocessor().getPreprocessingRecord())
394 return false;
395
396 PreprocessingRecord &PPRec
397 = *AU->getPreprocessor().getPreprocessingRecord();
398 SourceManager &SM = AU->getSourceManager();
399
400 if (RegionOfInterest.isValid()) {
401 SourceRange MappedRange = AU->mapRangeToPreamble(RegionOfInterest);
402 SourceLocation B = MappedRange.getBegin();
403 SourceLocation E = MappedRange.getEnd();
404
405 if (AU->isInPreambleFileID(B)) {
406 if (SM.isLoadedSourceLocation(E))
407 return visitPreprocessedEntitiesInRange(SourceRange(B, E),
408 PPRec, *this);
409
410 // Beginning of range lies in the preamble but it also extends beyond
411 // it into the main file. Split the range into 2 parts, one covering
412 // the preamble and another covering the main file. This allows subsequent
413 // calls to visitPreprocessedEntitiesInRange to accept a source range that
414 // lies in the same FileID, allowing it to skip preprocessed entities that
415 // do not come from the same FileID.
416 bool breaked =
417 visitPreprocessedEntitiesInRange(
418 SourceRange(B, AU->getEndOfPreambleFileID()),
419 PPRec, *this);
420 if (breaked) return true;
421 return visitPreprocessedEntitiesInRange(
422 SourceRange(AU->getStartOfMainFileID(), E),
423 PPRec, *this);
424 }
425
426 return visitPreprocessedEntitiesInRange(SourceRange(B, E), PPRec, *this);
427 }
428
429 bool OnlyLocalDecls
430 = !AU->isMainFileAST() && AU->getOnlyLocalDecls();
431
432 if (OnlyLocalDecls)
433 return visitPreprocessedEntities(PPRec.local_begin(), PPRec.local_end(),
434 PPRec);
435
436 return visitPreprocessedEntities(PPRec.begin(), PPRec.end(), PPRec);
437}
438
439template<typename InputIterator>
440bool CursorVisitor::visitPreprocessedEntities(InputIterator First,
441 InputIterator Last,
442 PreprocessingRecord &PPRec,
443 FileID FID) {
444 for (; First != Last; ++First) {
445 if (!FID.isInvalid() && !PPRec.isEntityInFileID(First, FID))
446 continue;
447
448 PreprocessedEntity *PPE = *First;
Argyrios Kyrtzidis1030f262013-05-07 20:37:17 +0000449 if (!PPE)
450 continue;
451
Guy Benyei11169dd2012-12-18 14:30:41 +0000452 if (MacroExpansion *ME = dyn_cast<MacroExpansion>(PPE)) {
453 if (Visit(MakeMacroExpansionCursor(ME, TU)))
454 return true;
Richard Smith66a81862015-05-04 02:25:31 +0000455
Guy Benyei11169dd2012-12-18 14:30:41 +0000456 continue;
457 }
Richard Smith66a81862015-05-04 02:25:31 +0000458
459 if (MacroDefinitionRecord *MD = dyn_cast<MacroDefinitionRecord>(PPE)) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000460 if (Visit(MakeMacroDefinitionCursor(MD, TU)))
461 return true;
Richard Smith66a81862015-05-04 02:25:31 +0000462
Guy Benyei11169dd2012-12-18 14:30:41 +0000463 continue;
464 }
465
466 if (InclusionDirective *ID = dyn_cast<InclusionDirective>(PPE)) {
467 if (Visit(MakeInclusionDirectiveCursor(ID, TU)))
468 return true;
469
470 continue;
471 }
472 }
473
474 return false;
475}
476
477/// \brief Visit the children of the given cursor.
478///
479/// \returns true if the visitation should be aborted, false if it
480/// should continue.
481bool CursorVisitor::VisitChildren(CXCursor Cursor) {
482 if (clang_isReference(Cursor.kind) &&
483 Cursor.kind != CXCursor_CXXBaseSpecifier) {
484 // By definition, references have no children.
485 return false;
486 }
487
488 // Set the Parent field to Cursor, then back to its old value once we're
489 // done.
490 SetParentRAII SetParent(Parent, StmtParent, Cursor);
491
492 if (clang_isDeclaration(Cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +0000493 Decl *D = const_cast<Decl *>(getCursorDecl(Cursor));
Guy Benyei11169dd2012-12-18 14:30:41 +0000494 if (!D)
495 return false;
496
497 return VisitAttributes(D) || Visit(D);
498 }
499
500 if (clang_isStatement(Cursor.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +0000501 if (const Stmt *S = getCursorStmt(Cursor))
Guy Benyei11169dd2012-12-18 14:30:41 +0000502 return Visit(S);
503
504 return false;
505 }
506
507 if (clang_isExpression(Cursor.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +0000508 if (const Expr *E = getCursorExpr(Cursor))
Guy Benyei11169dd2012-12-18 14:30:41 +0000509 return Visit(E);
510
511 return false;
512 }
513
514 if (clang_isTranslationUnit(Cursor.kind)) {
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +0000515 CXTranslationUnit TU = getCursorTU(Cursor);
516 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +0000517
518 int VisitOrder[2] = { VisitPreprocessorLast, !VisitPreprocessorLast };
519 for (unsigned I = 0; I != 2; ++I) {
520 if (VisitOrder[I]) {
521 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
522 RegionOfInterest.isInvalid()) {
523 for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
524 TLEnd = CXXUnit->top_level_end();
525 TL != TLEnd; ++TL) {
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +0000526 if (Visit(MakeCXCursor(*TL, TU, RegionOfInterest), true))
Guy Benyei11169dd2012-12-18 14:30:41 +0000527 return true;
528 }
529 } else if (VisitDeclContext(
530 CXXUnit->getASTContext().getTranslationUnitDecl()))
531 return true;
532 continue;
533 }
534
535 // Walk the preprocessing record.
536 if (CXXUnit->getPreprocessor().getPreprocessingRecord())
537 visitPreprocessedEntitiesInRegion();
538 }
539
540 return false;
541 }
542
543 if (Cursor.kind == CXCursor_CXXBaseSpecifier) {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +0000544 if (const CXXBaseSpecifier *Base = getCursorCXXBaseSpecifier(Cursor)) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000545 if (TypeSourceInfo *BaseTSInfo = Base->getTypeSourceInfo()) {
546 return Visit(BaseTSInfo->getTypeLoc());
547 }
548 }
549 }
550
551 if (Cursor.kind == CXCursor_IBOutletCollectionAttr) {
Dmitri Gribenkoe4baea62013-01-26 18:08:08 +0000552 const IBOutletCollectionAttr *A =
Guy Benyei11169dd2012-12-18 14:30:41 +0000553 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(Cursor));
Richard Smithb1f9a282013-10-31 01:56:18 +0000554 if (const ObjCObjectType *ObjT = A->getInterface()->getAs<ObjCObjectType>())
Richard Smithb87c4652013-10-31 21:23:20 +0000555 return Visit(cxcursor::MakeCursorObjCClassRef(
556 ObjT->getInterface(),
557 A->getInterfaceLoc()->getTypeLoc().getLocStart(), TU));
Guy Benyei11169dd2012-12-18 14:30:41 +0000558 }
559
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +0000560 // If pointing inside a macro definition, check if the token is an identifier
561 // that was ever defined as a macro. In such a case, create a "pseudo" macro
562 // expansion cursor for that token.
563 SourceLocation BeginLoc = RegionOfInterest.getBegin();
564 if (Cursor.kind == CXCursor_MacroDefinition &&
565 BeginLoc == RegionOfInterest.getEnd()) {
566 SourceLocation Loc = AU->mapLocationToPreamble(BeginLoc);
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +0000567 const MacroInfo *MI =
568 getMacroInfo(cxcursor::getCursorMacroDefinition(Cursor), TU);
Richard Smith66a81862015-05-04 02:25:31 +0000569 if (MacroDefinitionRecord *MacroDef =
570 checkForMacroInMacroDefinition(MI, Loc, TU))
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +0000571 return Visit(cxcursor::MakeMacroExpansionCursor(MacroDef, BeginLoc, TU));
572 }
573
Guy Benyei11169dd2012-12-18 14:30:41 +0000574 // Nothing to visit at the moment.
575 return false;
576}
577
578bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
579 if (TypeSourceInfo *TSInfo = B->getSignatureAsWritten())
580 if (Visit(TSInfo->getTypeLoc()))
581 return true;
582
583 if (Stmt *Body = B->getBody())
584 return Visit(MakeCXCursor(Body, StmtParent, TU, RegionOfInterest));
585
586 return false;
587}
588
Ted Kremenek03325582013-02-21 01:29:01 +0000589Optional<bool> CursorVisitor::shouldVisitCursor(CXCursor Cursor) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000590 if (RegionOfInterest.isValid()) {
591 SourceRange Range = getFullCursorExtent(Cursor, AU->getSourceManager());
592 if (Range.isInvalid())
David Blaikie7a30dc52013-02-21 01:47:18 +0000593 return None;
Guy Benyei11169dd2012-12-18 14:30:41 +0000594
595 switch (CompareRegionOfInterest(Range)) {
596 case RangeBefore:
597 // This declaration comes before the region of interest; skip it.
David Blaikie7a30dc52013-02-21 01:47:18 +0000598 return None;
Guy Benyei11169dd2012-12-18 14:30:41 +0000599
600 case RangeAfter:
601 // This declaration comes after the region of interest; we're done.
602 return false;
603
604 case RangeOverlap:
605 // This declaration overlaps the region of interest; visit it.
606 break;
607 }
608 }
609 return true;
610}
611
612bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
613 DeclContext::decl_iterator I = DC->decls_begin(), E = DC->decls_end();
614
615 // FIXME: Eventually remove. This part of a hack to support proper
616 // iteration over all Decls contained lexically within an ObjC container.
617 SaveAndRestore<DeclContext::decl_iterator*> DI_saved(DI_current, &I);
618 SaveAndRestore<DeclContext::decl_iterator> DE_saved(DE_current, E);
619
620 for ( ; I != E; ++I) {
621 Decl *D = *I;
622 if (D->getLexicalDeclContext() != DC)
623 continue;
624 CXCursor Cursor = MakeCXCursor(D, TU, RegionOfInterest);
625
626 // Ignore synthesized ivars here, otherwise if we have something like:
627 // @synthesize prop = _prop;
628 // and '_prop' is not declared, we will encounter a '_prop' ivar before
629 // encountering the 'prop' synthesize declaration and we will think that
630 // we passed the region-of-interest.
631 if (ObjCIvarDecl *ivarD = dyn_cast<ObjCIvarDecl>(D)) {
632 if (ivarD->getSynthesize())
633 continue;
634 }
635
636 // FIXME: ObjCClassRef/ObjCProtocolRef for forward class/protocol
637 // declarations is a mismatch with the compiler semantics.
638 if (Cursor.kind == CXCursor_ObjCInterfaceDecl) {
639 ObjCInterfaceDecl *ID = cast<ObjCInterfaceDecl>(D);
640 if (!ID->isThisDeclarationADefinition())
641 Cursor = MakeCursorObjCClassRef(ID, ID->getLocation(), TU);
642
643 } else if (Cursor.kind == CXCursor_ObjCProtocolDecl) {
644 ObjCProtocolDecl *PD = cast<ObjCProtocolDecl>(D);
645 if (!PD->isThisDeclarationADefinition())
646 Cursor = MakeCursorObjCProtocolRef(PD, PD->getLocation(), TU);
647 }
648
Ted Kremenek03325582013-02-21 01:29:01 +0000649 const Optional<bool> &V = shouldVisitCursor(Cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +0000650 if (!V.hasValue())
651 continue;
652 if (!V.getValue())
653 return false;
654 if (Visit(Cursor, true))
655 return true;
656 }
657 return false;
658}
659
660bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
661 llvm_unreachable("Translation units are visited directly by Visit()");
662}
663
Sergey Kalinichev8f3b1872015-11-15 13:48:32 +0000664bool CursorVisitor::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
665 if (VisitTemplateParameters(D->getTemplateParameters()))
666 return true;
667
668 return Visit(MakeCXCursor(D->getTemplatedDecl(), TU, RegionOfInterest));
669}
670
Guy Benyei11169dd2012-12-18 14:30:41 +0000671bool CursorVisitor::VisitTypeAliasDecl(TypeAliasDecl *D) {
672 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
673 return Visit(TSInfo->getTypeLoc());
674
675 return false;
676}
677
678bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
679 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
680 return Visit(TSInfo->getTypeLoc());
681
682 return false;
683}
684
685bool CursorVisitor::VisitTagDecl(TagDecl *D) {
686 return VisitDeclContext(D);
687}
688
689bool CursorVisitor::VisitClassTemplateSpecializationDecl(
690 ClassTemplateSpecializationDecl *D) {
691 bool ShouldVisitBody = false;
692 switch (D->getSpecializationKind()) {
693 case TSK_Undeclared:
694 case TSK_ImplicitInstantiation:
695 // Nothing to visit
696 return false;
697
698 case TSK_ExplicitInstantiationDeclaration:
699 case TSK_ExplicitInstantiationDefinition:
700 break;
701
702 case TSK_ExplicitSpecialization:
703 ShouldVisitBody = true;
704 break;
705 }
706
707 // Visit the template arguments used in the specialization.
708 if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) {
709 TypeLoc TL = SpecType->getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +0000710 if (TemplateSpecializationTypeLoc TSTLoc =
711 TL.getAs<TemplateSpecializationTypeLoc>()) {
712 for (unsigned I = 0, N = TSTLoc.getNumArgs(); I != N; ++I)
713 if (VisitTemplateArgumentLoc(TSTLoc.getArgLoc(I)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000714 return true;
715 }
716 }
Alexander Kornienko1a9f1842015-12-28 15:24:08 +0000717
718 return ShouldVisitBody && VisitCXXRecordDecl(D);
Guy Benyei11169dd2012-12-18 14:30:41 +0000719}
720
721bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl(
722 ClassTemplatePartialSpecializationDecl *D) {
723 // FIXME: Visit the "outer" template parameter lists on the TagDecl
724 // before visiting these template parameters.
725 if (VisitTemplateParameters(D->getTemplateParameters()))
726 return true;
727
728 // Visit the partial specialization arguments.
Enea Zaffanella6dbe1872013-08-10 07:24:53 +0000729 const ASTTemplateArgumentListInfo *Info = D->getTemplateArgsAsWritten();
730 const TemplateArgumentLoc *TemplateArgs = Info->getTemplateArgs();
731 for (unsigned I = 0, N = Info->NumTemplateArgs; I != N; ++I)
Guy Benyei11169dd2012-12-18 14:30:41 +0000732 if (VisitTemplateArgumentLoc(TemplateArgs[I]))
733 return true;
734
735 return VisitCXXRecordDecl(D);
736}
737
738bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
739 // Visit the default argument.
740 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
741 if (TypeSourceInfo *DefArg = D->getDefaultArgumentInfo())
742 if (Visit(DefArg->getTypeLoc()))
743 return true;
744
745 return false;
746}
747
748bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
749 if (Expr *Init = D->getInitExpr())
750 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
751 return false;
752}
753
754bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
Argyrios Kyrtzidis2ec76742013-04-05 21:04:10 +0000755 unsigned NumParamList = DD->getNumTemplateParameterLists();
756 for (unsigned i = 0; i < NumParamList; i++) {
757 TemplateParameterList* Params = DD->getTemplateParameterList(i);
758 if (VisitTemplateParameters(Params))
759 return true;
760 }
761
Guy Benyei11169dd2012-12-18 14:30:41 +0000762 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
763 if (Visit(TSInfo->getTypeLoc()))
764 return true;
765
766 // Visit the nested-name-specifier, if present.
767 if (NestedNameSpecifierLoc QualifierLoc = DD->getQualifierLoc())
768 if (VisitNestedNameSpecifierLoc(QualifierLoc))
769 return true;
770
771 return false;
772}
773
Benjamin Kramer4cadf292014-03-07 21:51:58 +0000774/// \brief Compare two base or member initializers based on their source order.
775static int CompareCXXCtorInitializers(CXXCtorInitializer *const *X,
776 CXXCtorInitializer *const *Y) {
777 return (*X)->getSourceOrder() - (*Y)->getSourceOrder();
778}
779
Guy Benyei11169dd2012-12-18 14:30:41 +0000780bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Argyrios Kyrtzidis2ec76742013-04-05 21:04:10 +0000781 unsigned NumParamList = ND->getNumTemplateParameterLists();
782 for (unsigned i = 0; i < NumParamList; i++) {
783 TemplateParameterList* Params = ND->getTemplateParameterList(i);
784 if (VisitTemplateParameters(Params))
785 return true;
786 }
787
Guy Benyei11169dd2012-12-18 14:30:41 +0000788 if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
789 // Visit the function declaration's syntactic components in the order
790 // written. This requires a bit of work.
791 TypeLoc TL = TSInfo->getTypeLoc().IgnoreParens();
David Blaikie6adc78e2013-02-18 22:06:02 +0000792 FunctionTypeLoc FTL = TL.getAs<FunctionTypeLoc>();
Guy Benyei11169dd2012-12-18 14:30:41 +0000793
794 // If we have a function declared directly (without the use of a typedef),
795 // visit just the return type. Otherwise, just visit the function's type
796 // now.
Alp Toker42a16a62014-01-25 23:51:36 +0000797 if ((FTL && !isa<CXXConversionDecl>(ND) && Visit(FTL.getReturnLoc())) ||
Guy Benyei11169dd2012-12-18 14:30:41 +0000798 (!FTL && Visit(TL)))
799 return true;
800
801 // Visit the nested-name-specifier, if present.
802 if (NestedNameSpecifierLoc QualifierLoc = ND->getQualifierLoc())
803 if (VisitNestedNameSpecifierLoc(QualifierLoc))
804 return true;
805
806 // Visit the declaration name.
Argyrios Kyrtzidis4a4d2b42014-02-09 08:13:47 +0000807 if (!isa<CXXDestructorDecl>(ND))
808 if (VisitDeclarationNameInfo(ND->getNameInfo()))
809 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +0000810
811 // FIXME: Visit explicitly-specified template arguments!
812
813 // Visit the function parameters, if we have a function type.
David Blaikie6adc78e2013-02-18 22:06:02 +0000814 if (FTL && VisitFunctionTypeLoc(FTL, true))
Guy Benyei11169dd2012-12-18 14:30:41 +0000815 return true;
816
Bill Wendling44426052012-12-20 19:22:21 +0000817 // FIXME: Attributes?
Guy Benyei11169dd2012-12-18 14:30:41 +0000818 }
819
820 if (ND->doesThisDeclarationHaveABody() && !ND->isLateTemplateParsed()) {
821 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ND)) {
822 // Find the initializers that were written in the source.
823 SmallVector<CXXCtorInitializer *, 4> WrittenInits;
Aaron Ballman0ad78302014-03-13 17:34:31 +0000824 for (auto *I : Constructor->inits()) {
825 if (!I->isWritten())
Guy Benyei11169dd2012-12-18 14:30:41 +0000826 continue;
827
Aaron Ballman0ad78302014-03-13 17:34:31 +0000828 WrittenInits.push_back(I);
Guy Benyei11169dd2012-12-18 14:30:41 +0000829 }
830
831 // Sort the initializers in source order
Benjamin Kramer4cadf292014-03-07 21:51:58 +0000832 llvm::array_pod_sort(WrittenInits.begin(), WrittenInits.end(),
833 &CompareCXXCtorInitializers);
834
Guy Benyei11169dd2012-12-18 14:30:41 +0000835 // Visit the initializers in source order
836 for (unsigned I = 0, N = WrittenInits.size(); I != N; ++I) {
837 CXXCtorInitializer *Init = WrittenInits[I];
838 if (Init->isAnyMemberInitializer()) {
839 if (Visit(MakeCursorMemberRef(Init->getAnyMember(),
840 Init->getMemberLocation(), TU)))
841 return true;
842 } else if (TypeSourceInfo *TInfo = Init->getTypeSourceInfo()) {
843 if (Visit(TInfo->getTypeLoc()))
844 return true;
845 }
846
847 // Visit the initializer value.
848 if (Expr *Initializer = Init->getInit())
849 if (Visit(MakeCXCursor(Initializer, ND, TU, RegionOfInterest)))
850 return true;
851 }
852 }
853
854 if (Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest)))
855 return true;
856 }
857
858 return false;
859}
860
861bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
862 if (VisitDeclaratorDecl(D))
863 return true;
864
865 if (Expr *BitWidth = D->getBitWidth())
866 return Visit(MakeCXCursor(BitWidth, StmtParent, TU, RegionOfInterest));
867
868 return false;
869}
870
871bool CursorVisitor::VisitVarDecl(VarDecl *D) {
872 if (VisitDeclaratorDecl(D))
873 return true;
874
875 if (Expr *Init = D->getInit())
876 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
877
878 return false;
879}
880
881bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
882 if (VisitDeclaratorDecl(D))
883 return true;
884
885 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
886 if (Expr *DefArg = D->getDefaultArgument())
887 return Visit(MakeCXCursor(DefArg, StmtParent, TU, RegionOfInterest));
888
889 return false;
890}
891
892bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
893 // FIXME: Visit the "outer" template parameter lists on the FunctionDecl
894 // before visiting these template parameters.
895 if (VisitTemplateParameters(D->getTemplateParameters()))
896 return true;
897
898 return VisitFunctionDecl(D->getTemplatedDecl());
899}
900
901bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) {
902 // FIXME: Visit the "outer" template parameter lists on the TagDecl
903 // before visiting these template parameters.
904 if (VisitTemplateParameters(D->getTemplateParameters()))
905 return true;
906
907 return VisitCXXRecordDecl(D->getTemplatedDecl());
908}
909
910bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
911 if (VisitTemplateParameters(D->getTemplateParameters()))
912 return true;
913
914 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() &&
915 VisitTemplateArgumentLoc(D->getDefaultArgument()))
916 return true;
917
918 return false;
919}
920
Douglas Gregor9bda6cf2015-07-07 03:58:14 +0000921bool CursorVisitor::VisitObjCTypeParamDecl(ObjCTypeParamDecl *D) {
922 // Visit the bound, if it's explicit.
923 if (D->hasExplicitBound()) {
924 if (auto TInfo = D->getTypeSourceInfo()) {
925 if (Visit(TInfo->getTypeLoc()))
926 return true;
927 }
928 }
929
930 return false;
931}
932
Guy Benyei11169dd2012-12-18 14:30:41 +0000933bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Alp Toker314cc812014-01-25 16:55:45 +0000934 if (TypeSourceInfo *TSInfo = ND->getReturnTypeSourceInfo())
Guy Benyei11169dd2012-12-18 14:30:41 +0000935 if (Visit(TSInfo->getTypeLoc()))
936 return true;
937
Aaron Ballman43b68be2014-03-07 17:50:17 +0000938 for (const auto *P : ND->params()) {
939 if (Visit(MakeCXCursor(P, TU, RegionOfInterest)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000940 return true;
941 }
942
Alexander Kornienko1a9f1842015-12-28 15:24:08 +0000943 return ND->isThisDeclarationADefinition() &&
944 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest));
Guy Benyei11169dd2012-12-18 14:30:41 +0000945}
946
947template <typename DeclIt>
948static void addRangedDeclsInContainer(DeclIt *DI_current, DeclIt DE_current,
949 SourceManager &SM, SourceLocation EndLoc,
950 SmallVectorImpl<Decl *> &Decls) {
951 DeclIt next = *DI_current;
952 while (++next != DE_current) {
953 Decl *D_next = *next;
954 if (!D_next)
955 break;
956 SourceLocation L = D_next->getLocStart();
957 if (!L.isValid())
958 break;
959 if (SM.isBeforeInTranslationUnit(L, EndLoc)) {
960 *DI_current = next;
961 Decls.push_back(D_next);
962 continue;
963 }
964 break;
965 }
966}
967
Guy Benyei11169dd2012-12-18 14:30:41 +0000968bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
969 // FIXME: Eventually convert back to just 'VisitDeclContext()'. Essentially
970 // an @implementation can lexically contain Decls that are not properly
971 // nested in the AST. When we identify such cases, we need to retrofit
972 // this nesting here.
973 if (!DI_current && !FileDI_current)
974 return VisitDeclContext(D);
975
976 // Scan the Decls that immediately come after the container
977 // in the current DeclContext. If any fall within the
978 // container's lexical region, stash them into a vector
979 // for later processing.
980 SmallVector<Decl *, 24> DeclsInContainer;
981 SourceLocation EndLoc = D->getSourceRange().getEnd();
982 SourceManager &SM = AU->getSourceManager();
983 if (EndLoc.isValid()) {
984 if (DI_current) {
985 addRangedDeclsInContainer(DI_current, DE_current, SM, EndLoc,
986 DeclsInContainer);
987 } else {
988 addRangedDeclsInContainer(FileDI_current, FileDE_current, SM, EndLoc,
989 DeclsInContainer);
990 }
991 }
992
993 // The common case.
994 if (DeclsInContainer.empty())
995 return VisitDeclContext(D);
996
997 // Get all the Decls in the DeclContext, and sort them with the
998 // additional ones we've collected. Then visit them.
Aaron Ballman629afae2014-03-07 19:56:05 +0000999 for (auto *SubDecl : D->decls()) {
1000 if (!SubDecl || SubDecl->getLexicalDeclContext() != D ||
1001 SubDecl->getLocStart().isInvalid())
Guy Benyei11169dd2012-12-18 14:30:41 +00001002 continue;
Aaron Ballman629afae2014-03-07 19:56:05 +00001003 DeclsInContainer.push_back(SubDecl);
Guy Benyei11169dd2012-12-18 14:30:41 +00001004 }
1005
1006 // Now sort the Decls so that they appear in lexical order.
1007 std::sort(DeclsInContainer.begin(), DeclsInContainer.end(),
Benjamin Kramerbbdd7642014-03-01 14:48:57 +00001008 [&SM](Decl *A, Decl *B) {
1009 SourceLocation L_A = A->getLocStart();
1010 SourceLocation L_B = B->getLocStart();
1011 assert(L_A.isValid() && L_B.isValid());
1012 return SM.isBeforeInTranslationUnit(L_A, L_B);
1013 });
Guy Benyei11169dd2012-12-18 14:30:41 +00001014
1015 // Now visit the decls.
1016 for (SmallVectorImpl<Decl*>::iterator I = DeclsInContainer.begin(),
1017 E = DeclsInContainer.end(); I != E; ++I) {
1018 CXCursor Cursor = MakeCXCursor(*I, TU, RegionOfInterest);
Ted Kremenek03325582013-02-21 01:29:01 +00001019 const Optional<bool> &V = shouldVisitCursor(Cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00001020 if (!V.hasValue())
1021 continue;
1022 if (!V.getValue())
1023 return false;
1024 if (Visit(Cursor, true))
1025 return true;
1026 }
1027 return false;
1028}
1029
1030bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
1031 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
1032 TU)))
1033 return true;
1034
Douglas Gregore9d95f12015-07-07 03:57:35 +00001035 if (VisitObjCTypeParamList(ND->getTypeParamList()))
1036 return true;
1037
Guy Benyei11169dd2012-12-18 14:30:41 +00001038 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
1039 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
1040 E = ND->protocol_end(); I != E; ++I, ++PL)
1041 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
1042 return true;
1043
1044 return VisitObjCContainerDecl(ND);
1045}
1046
1047bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
1048 if (!PID->isThisDeclarationADefinition())
1049 return Visit(MakeCursorObjCProtocolRef(PID, PID->getLocation(), TU));
1050
1051 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
1052 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
1053 E = PID->protocol_end(); I != E; ++I, ++PL)
1054 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
1055 return true;
1056
1057 return VisitObjCContainerDecl(PID);
1058}
1059
1060bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
1061 if (PD->getTypeSourceInfo() && Visit(PD->getTypeSourceInfo()->getTypeLoc()))
1062 return true;
1063
1064 // FIXME: This implements a workaround with @property declarations also being
1065 // installed in the DeclContext for the @interface. Eventually this code
1066 // should be removed.
1067 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
1068 if (!CDecl || !CDecl->IsClassExtension())
1069 return false;
1070
1071 ObjCInterfaceDecl *ID = CDecl->getClassInterface();
1072 if (!ID)
1073 return false;
1074
1075 IdentifierInfo *PropertyId = PD->getIdentifier();
1076 ObjCPropertyDecl *prevDecl =
Manman Ren5b786402016-01-28 18:49:28 +00001077 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId,
1078 PD->getQueryKind());
Guy Benyei11169dd2012-12-18 14:30:41 +00001079
1080 if (!prevDecl)
1081 return false;
1082
1083 // Visit synthesized methods since they will be skipped when visiting
1084 // the @interface.
1085 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
1086 if (MD->isPropertyAccessor() && MD->getLexicalDeclContext() == CDecl)
1087 if (Visit(MakeCXCursor(MD, TU, RegionOfInterest)))
1088 return true;
1089
1090 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
1091 if (MD->isPropertyAccessor() && MD->getLexicalDeclContext() == CDecl)
1092 if (Visit(MakeCXCursor(MD, TU, RegionOfInterest)))
1093 return true;
1094
1095 return false;
1096}
1097
Douglas Gregore9d95f12015-07-07 03:57:35 +00001098bool CursorVisitor::VisitObjCTypeParamList(ObjCTypeParamList *typeParamList) {
1099 if (!typeParamList)
1100 return false;
1101
1102 for (auto *typeParam : *typeParamList) {
1103 // Visit the type parameter.
1104 if (Visit(MakeCXCursor(typeParam, TU, RegionOfInterest)))
1105 return true;
Douglas Gregore9d95f12015-07-07 03:57:35 +00001106 }
1107
1108 return false;
1109}
1110
Guy Benyei11169dd2012-12-18 14:30:41 +00001111bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
1112 if (!D->isThisDeclarationADefinition()) {
1113 // Forward declaration is treated like a reference.
1114 return Visit(MakeCursorObjCClassRef(D, D->getLocation(), TU));
1115 }
1116
Douglas Gregore9d95f12015-07-07 03:57:35 +00001117 // Objective-C type parameters.
1118 if (VisitObjCTypeParamList(D->getTypeParamListAsWritten()))
1119 return true;
1120
Guy Benyei11169dd2012-12-18 14:30:41 +00001121 // Issue callbacks for super class.
1122 if (D->getSuperClass() &&
1123 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
1124 D->getSuperClassLoc(),
1125 TU)))
1126 return true;
1127
Douglas Gregore9d95f12015-07-07 03:57:35 +00001128 if (TypeSourceInfo *SuperClassTInfo = D->getSuperClassTInfo())
1129 if (Visit(SuperClassTInfo->getTypeLoc()))
1130 return true;
1131
Guy Benyei11169dd2012-12-18 14:30:41 +00001132 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1133 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
1134 E = D->protocol_end(); I != E; ++I, ++PL)
1135 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
1136 return true;
1137
1138 return VisitObjCContainerDecl(D);
1139}
1140
1141bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
1142 return VisitObjCContainerDecl(D);
1143}
1144
1145bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
1146 // 'ID' could be null when dealing with invalid code.
1147 if (ObjCInterfaceDecl *ID = D->getClassInterface())
1148 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
1149 return true;
1150
1151 return VisitObjCImplDecl(D);
1152}
1153
1154bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
1155#if 0
1156 // Issue callbacks for super class.
1157 // FIXME: No source location information!
1158 if (D->getSuperClass() &&
1159 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
1160 D->getSuperClassLoc(),
1161 TU)))
1162 return true;
1163#endif
1164
1165 return VisitObjCImplDecl(D);
1166}
1167
1168bool CursorVisitor::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *PD) {
1169 if (ObjCIvarDecl *Ivar = PD->getPropertyIvarDecl())
1170 if (PD->isIvarNameSpecified())
1171 return Visit(MakeCursorMemberRef(Ivar, PD->getPropertyIvarDeclLoc(), TU));
1172
1173 return false;
1174}
1175
1176bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
1177 return VisitDeclContext(D);
1178}
1179
1180bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
1181 // Visit nested-name-specifier.
1182 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1183 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1184 return true;
1185
1186 return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(),
1187 D->getTargetNameLoc(), TU));
1188}
1189
1190bool CursorVisitor::VisitUsingDecl(UsingDecl *D) {
1191 // Visit nested-name-specifier.
1192 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1193 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1194 return true;
1195 }
1196
1197 if (Visit(MakeCursorOverloadedDeclRef(D, D->getLocation(), TU)))
1198 return true;
1199
1200 return VisitDeclarationNameInfo(D->getNameInfo());
1201}
1202
1203bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
1204 // Visit nested-name-specifier.
1205 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1206 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1207 return true;
1208
1209 return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(),
1210 D->getIdentLocation(), TU));
1211}
1212
1213bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
1214 // Visit nested-name-specifier.
1215 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1216 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1217 return true;
1218 }
1219
1220 return VisitDeclarationNameInfo(D->getNameInfo());
1221}
1222
1223bool CursorVisitor::VisitUnresolvedUsingTypenameDecl(
1224 UnresolvedUsingTypenameDecl *D) {
1225 // Visit nested-name-specifier.
1226 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1227 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1228 return true;
1229
1230 return false;
1231}
1232
Olivier Goffart81978012016-06-09 16:15:55 +00001233bool CursorVisitor::VisitStaticAssertDecl(StaticAssertDecl *D) {
1234 if (Visit(MakeCXCursor(D->getAssertExpr(), StmtParent, TU, RegionOfInterest)))
1235 return true;
1236 if (Visit(MakeCXCursor(D->getMessage(), StmtParent, TU, RegionOfInterest)))
1237 return true;
1238 return false;
1239}
1240
Guy Benyei11169dd2012-12-18 14:30:41 +00001241bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
1242 switch (Name.getName().getNameKind()) {
1243 case clang::DeclarationName::Identifier:
1244 case clang::DeclarationName::CXXLiteralOperatorName:
1245 case clang::DeclarationName::CXXOperatorName:
1246 case clang::DeclarationName::CXXUsingDirective:
1247 return false;
1248
1249 case clang::DeclarationName::CXXConstructorName:
1250 case clang::DeclarationName::CXXDestructorName:
1251 case clang::DeclarationName::CXXConversionFunctionName:
1252 if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
1253 return Visit(TSInfo->getTypeLoc());
1254 return false;
1255
1256 case clang::DeclarationName::ObjCZeroArgSelector:
1257 case clang::DeclarationName::ObjCOneArgSelector:
1258 case clang::DeclarationName::ObjCMultiArgSelector:
1259 // FIXME: Per-identifier location info?
1260 return false;
1261 }
1262
1263 llvm_unreachable("Invalid DeclarationName::Kind!");
1264}
1265
1266bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS,
1267 SourceRange Range) {
1268 // FIXME: This whole routine is a hack to work around the lack of proper
1269 // source information in nested-name-specifiers (PR5791). Since we do have
1270 // a beginning source location, we can visit the first component of the
1271 // nested-name-specifier, if it's a single-token component.
1272 if (!NNS)
1273 return false;
1274
1275 // Get the first component in the nested-name-specifier.
1276 while (NestedNameSpecifier *Prefix = NNS->getPrefix())
1277 NNS = Prefix;
1278
1279 switch (NNS->getKind()) {
1280 case NestedNameSpecifier::Namespace:
1281 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(),
1282 TU));
1283
1284 case NestedNameSpecifier::NamespaceAlias:
1285 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
1286 Range.getBegin(), TU));
1287
1288 case NestedNameSpecifier::TypeSpec: {
1289 // If the type has a form where we know that the beginning of the source
1290 // range matches up with a reference cursor. Visit the appropriate reference
1291 // cursor.
1292 const Type *T = NNS->getAsType();
1293 if (const TypedefType *Typedef = dyn_cast<TypedefType>(T))
1294 return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU));
1295 if (const TagType *Tag = dyn_cast<TagType>(T))
1296 return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU));
1297 if (const TemplateSpecializationType *TST
1298 = dyn_cast<TemplateSpecializationType>(T))
1299 return VisitTemplateName(TST->getTemplateName(), Range.getBegin());
1300 break;
1301 }
1302
1303 case NestedNameSpecifier::TypeSpecWithTemplate:
1304 case NestedNameSpecifier::Global:
1305 case NestedNameSpecifier::Identifier:
Nikola Smiljanic67860242014-09-26 00:28:20 +00001306 case NestedNameSpecifier::Super:
Guy Benyei11169dd2012-12-18 14:30:41 +00001307 break;
1308 }
1309
1310 return false;
1311}
1312
1313bool
1314CursorVisitor::VisitNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
1315 SmallVector<NestedNameSpecifierLoc, 4> Qualifiers;
1316 for (; Qualifier; Qualifier = Qualifier.getPrefix())
1317 Qualifiers.push_back(Qualifier);
1318
1319 while (!Qualifiers.empty()) {
1320 NestedNameSpecifierLoc Q = Qualifiers.pop_back_val();
1321 NestedNameSpecifier *NNS = Q.getNestedNameSpecifier();
1322 switch (NNS->getKind()) {
1323 case NestedNameSpecifier::Namespace:
1324 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(),
1325 Q.getLocalBeginLoc(),
1326 TU)))
1327 return true;
1328
1329 break;
1330
1331 case NestedNameSpecifier::NamespaceAlias:
1332 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
1333 Q.getLocalBeginLoc(),
1334 TU)))
1335 return true;
1336
1337 break;
1338
1339 case NestedNameSpecifier::TypeSpec:
1340 case NestedNameSpecifier::TypeSpecWithTemplate:
1341 if (Visit(Q.getTypeLoc()))
1342 return true;
1343
1344 break;
1345
1346 case NestedNameSpecifier::Global:
1347 case NestedNameSpecifier::Identifier:
Nikola Smiljanic67860242014-09-26 00:28:20 +00001348 case NestedNameSpecifier::Super:
Guy Benyei11169dd2012-12-18 14:30:41 +00001349 break;
1350 }
1351 }
1352
1353 return false;
1354}
1355
1356bool CursorVisitor::VisitTemplateParameters(
1357 const TemplateParameterList *Params) {
1358 if (!Params)
1359 return false;
1360
1361 for (TemplateParameterList::const_iterator P = Params->begin(),
1362 PEnd = Params->end();
1363 P != PEnd; ++P) {
1364 if (Visit(MakeCXCursor(*P, TU, RegionOfInterest)))
1365 return true;
1366 }
1367
1368 return false;
1369}
1370
1371bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) {
1372 switch (Name.getKind()) {
1373 case TemplateName::Template:
1374 return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
1375
1376 case TemplateName::OverloadedTemplate:
1377 // Visit the overloaded template set.
1378 if (Visit(MakeCursorOverloadedDeclRef(Name, Loc, TU)))
1379 return true;
1380
1381 return false;
1382
1383 case TemplateName::DependentTemplate:
1384 // FIXME: Visit nested-name-specifier.
1385 return false;
1386
1387 case TemplateName::QualifiedTemplate:
1388 // FIXME: Visit nested-name-specifier.
1389 return Visit(MakeCursorTemplateRef(
1390 Name.getAsQualifiedTemplateName()->getDecl(),
1391 Loc, TU));
1392
1393 case TemplateName::SubstTemplateTemplateParm:
1394 return Visit(MakeCursorTemplateRef(
1395 Name.getAsSubstTemplateTemplateParm()->getParameter(),
1396 Loc, TU));
1397
1398 case TemplateName::SubstTemplateTemplateParmPack:
1399 return Visit(MakeCursorTemplateRef(
1400 Name.getAsSubstTemplateTemplateParmPack()->getParameterPack(),
1401 Loc, TU));
1402 }
1403
1404 llvm_unreachable("Invalid TemplateName::Kind!");
1405}
1406
1407bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
1408 switch (TAL.getArgument().getKind()) {
1409 case TemplateArgument::Null:
1410 case TemplateArgument::Integral:
1411 case TemplateArgument::Pack:
1412 return false;
1413
1414 case TemplateArgument::Type:
1415 if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
1416 return Visit(TSInfo->getTypeLoc());
1417 return false;
1418
1419 case TemplateArgument::Declaration:
1420 if (Expr *E = TAL.getSourceDeclExpression())
1421 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
1422 return false;
1423
1424 case TemplateArgument::NullPtr:
1425 if (Expr *E = TAL.getSourceNullPtrExpression())
1426 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
1427 return false;
1428
1429 case TemplateArgument::Expression:
1430 if (Expr *E = TAL.getSourceExpression())
1431 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
1432 return false;
1433
1434 case TemplateArgument::Template:
1435 case TemplateArgument::TemplateExpansion:
1436 if (VisitNestedNameSpecifierLoc(TAL.getTemplateQualifierLoc()))
1437 return true;
1438
1439 return VisitTemplateName(TAL.getArgument().getAsTemplateOrTemplatePattern(),
1440 TAL.getTemplateNameLoc());
1441 }
1442
1443 llvm_unreachable("Invalid TemplateArgument::Kind!");
1444}
1445
1446bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1447 return VisitDeclContext(D);
1448}
1449
1450bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1451 return Visit(TL.getUnqualifiedLoc());
1452}
1453
1454bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
1455 ASTContext &Context = AU->getASTContext();
1456
1457 // Some builtin types (such as Objective-C's "id", "sel", and
1458 // "Class") have associated declarations. Create cursors for those.
1459 QualType VisitType;
1460 switch (TL.getTypePtr()->getKind()) {
1461
1462 case BuiltinType::Void:
1463 case BuiltinType::NullPtr:
1464 case BuiltinType::Dependent:
Alexey Bader954ba212016-04-08 13:40:33 +00001465#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1466 case BuiltinType::Id:
Alexey Baderb62f1442016-04-13 08:33:41 +00001467#include "clang/Basic/OpenCLImageTypes.def"
NAKAMURA Takumi288c42e2013-02-07 12:47:42 +00001468 case BuiltinType::OCLSampler:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001469 case BuiltinType::OCLEvent:
Alexey Bader9c8453f2015-09-15 11:18:52 +00001470 case BuiltinType::OCLClkEvent:
1471 case BuiltinType::OCLQueue:
1472 case BuiltinType::OCLNDRange:
1473 case BuiltinType::OCLReserveID:
Guy Benyei11169dd2012-12-18 14:30:41 +00001474#define BUILTIN_TYPE(Id, SingletonId)
1475#define SIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
1476#define UNSIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
1477#define FLOATING_TYPE(Id, SingletonId) case BuiltinType::Id:
1478#define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id:
1479#include "clang/AST/BuiltinTypes.def"
1480 break;
1481
1482 case BuiltinType::ObjCId:
1483 VisitType = Context.getObjCIdType();
1484 break;
1485
1486 case BuiltinType::ObjCClass:
1487 VisitType = Context.getObjCClassType();
1488 break;
1489
1490 case BuiltinType::ObjCSel:
1491 VisitType = Context.getObjCSelType();
1492 break;
1493 }
1494
1495 if (!VisitType.isNull()) {
1496 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
1497 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
1498 TU));
1499 }
1500
1501 return false;
1502}
1503
1504bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
1505 return Visit(MakeCursorTypeRef(TL.getTypedefNameDecl(), TL.getNameLoc(), TU));
1506}
1507
1508bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
1509 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1510}
1511
1512bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
1513 if (TL.isDefinition())
1514 return Visit(MakeCXCursor(TL.getDecl(), TU, RegionOfInterest));
1515
1516 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1517}
1518
1519bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
1520 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1521}
1522
1523bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
Hans Wennborg59dbe862015-09-29 20:56:43 +00001524 return Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU));
Guy Benyei11169dd2012-12-18 14:30:41 +00001525}
1526
1527bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1528 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
1529 return true;
1530
Douglas Gregore9d95f12015-07-07 03:57:35 +00001531 for (unsigned I = 0, N = TL.getNumTypeArgs(); I != N; ++I) {
1532 if (Visit(TL.getTypeArgTInfo(I)->getTypeLoc()))
1533 return true;
1534 }
1535
Guy Benyei11169dd2012-12-18 14:30:41 +00001536 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1537 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1538 TU)))
1539 return true;
1540 }
1541
1542 return false;
1543}
1544
1545bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
1546 return Visit(TL.getPointeeLoc());
1547}
1548
1549bool CursorVisitor::VisitParenTypeLoc(ParenTypeLoc TL) {
1550 return Visit(TL.getInnerLoc());
1551}
1552
1553bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
1554 return Visit(TL.getPointeeLoc());
1555}
1556
1557bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1558 return Visit(TL.getPointeeLoc());
1559}
1560
1561bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1562 return Visit(TL.getPointeeLoc());
1563}
1564
1565bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
1566 return Visit(TL.getPointeeLoc());
1567}
1568
1569bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
1570 return Visit(TL.getPointeeLoc());
1571}
1572
1573bool CursorVisitor::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
1574 return Visit(TL.getModifiedLoc());
1575}
1576
1577bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
1578 bool SkipResultType) {
Alp Toker42a16a62014-01-25 23:51:36 +00001579 if (!SkipResultType && Visit(TL.getReturnLoc()))
Guy Benyei11169dd2012-12-18 14:30:41 +00001580 return true;
1581
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00001582 for (unsigned I = 0, N = TL.getNumParams(); I != N; ++I)
1583 if (Decl *D = TL.getParam(I))
Guy Benyei11169dd2012-12-18 14:30:41 +00001584 if (Visit(MakeCXCursor(D, TU, RegionOfInterest)))
1585 return true;
1586
1587 return false;
1588}
1589
1590bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
1591 if (Visit(TL.getElementLoc()))
1592 return true;
1593
1594 if (Expr *Size = TL.getSizeExpr())
1595 return Visit(MakeCXCursor(Size, StmtParent, TU, RegionOfInterest));
1596
1597 return false;
1598}
1599
Reid Kleckner8a365022013-06-24 17:51:48 +00001600bool CursorVisitor::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
1601 return Visit(TL.getOriginalLoc());
1602}
1603
Reid Kleckner0503a872013-12-05 01:23:43 +00001604bool CursorVisitor::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
1605 return Visit(TL.getOriginalLoc());
1606}
1607
Guy Benyei11169dd2012-12-18 14:30:41 +00001608bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
1609 TemplateSpecializationTypeLoc TL) {
1610 // Visit the template name.
1611 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1612 TL.getTemplateNameLoc()))
1613 return true;
1614
1615 // Visit the template arguments.
1616 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1617 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1618 return true;
1619
1620 return false;
1621}
1622
1623bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1624 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
1625}
1626
1627bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1628 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1629 return Visit(TSInfo->getTypeLoc());
1630
1631 return false;
1632}
1633
1634bool CursorVisitor::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
1635 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1636 return Visit(TSInfo->getTypeLoc());
1637
1638 return false;
1639}
1640
1641bool CursorVisitor::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
Hans Wennborg59dbe862015-09-29 20:56:43 +00001642 return VisitNestedNameSpecifierLoc(TL.getQualifierLoc());
Guy Benyei11169dd2012-12-18 14:30:41 +00001643}
1644
1645bool CursorVisitor::VisitDependentTemplateSpecializationTypeLoc(
1646 DependentTemplateSpecializationTypeLoc TL) {
1647 // Visit the nested-name-specifier, if there is one.
1648 if (TL.getQualifierLoc() &&
1649 VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1650 return true;
1651
1652 // Visit the template arguments.
1653 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1654 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1655 return true;
1656
1657 return false;
1658}
1659
1660bool CursorVisitor::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
1661 if (VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1662 return true;
1663
1664 return Visit(TL.getNamedTypeLoc());
1665}
1666
1667bool CursorVisitor::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
1668 return Visit(TL.getPatternLoc());
1669}
1670
1671bool CursorVisitor::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
1672 if (Expr *E = TL.getUnderlyingExpr())
1673 return Visit(MakeCXCursor(E, StmtParent, TU));
1674
1675 return false;
1676}
1677
1678bool CursorVisitor::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
1679 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1680}
1681
1682bool CursorVisitor::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
1683 return Visit(TL.getValueLoc());
1684}
1685
Xiuli Pan9c14e282016-01-09 12:53:17 +00001686bool CursorVisitor::VisitPipeTypeLoc(PipeTypeLoc TL) {
1687 return Visit(TL.getValueLoc());
1688}
1689
Guy Benyei11169dd2012-12-18 14:30:41 +00001690#define DEFAULT_TYPELOC_IMPL(CLASS, PARENT) \
1691bool CursorVisitor::Visit##CLASS##TypeLoc(CLASS##TypeLoc TL) { \
1692 return Visit##PARENT##Loc(TL); \
1693}
1694
1695DEFAULT_TYPELOC_IMPL(Complex, Type)
1696DEFAULT_TYPELOC_IMPL(ConstantArray, ArrayType)
1697DEFAULT_TYPELOC_IMPL(IncompleteArray, ArrayType)
1698DEFAULT_TYPELOC_IMPL(VariableArray, ArrayType)
1699DEFAULT_TYPELOC_IMPL(DependentSizedArray, ArrayType)
1700DEFAULT_TYPELOC_IMPL(DependentSizedExtVector, Type)
1701DEFAULT_TYPELOC_IMPL(Vector, Type)
1702DEFAULT_TYPELOC_IMPL(ExtVector, VectorType)
1703DEFAULT_TYPELOC_IMPL(FunctionProto, FunctionType)
1704DEFAULT_TYPELOC_IMPL(FunctionNoProto, FunctionType)
1705DEFAULT_TYPELOC_IMPL(Record, TagType)
1706DEFAULT_TYPELOC_IMPL(Enum, TagType)
1707DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParm, Type)
1708DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParmPack, Type)
1709DEFAULT_TYPELOC_IMPL(Auto, Type)
1710
1711bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
1712 // Visit the nested-name-specifier, if present.
1713 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1714 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1715 return true;
1716
1717 if (D->isCompleteDefinition()) {
Aaron Ballman574705e2014-03-13 15:41:46 +00001718 for (const auto &I : D->bases()) {
1719 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(&I, TU)))
Guy Benyei11169dd2012-12-18 14:30:41 +00001720 return true;
1721 }
1722 }
1723
1724 return VisitTagDecl(D);
1725}
1726
1727bool CursorVisitor::VisitAttributes(Decl *D) {
Aaron Ballmanb97112e2014-03-08 22:19:01 +00001728 for (const auto *I : D->attrs())
1729 if (Visit(MakeCXCursor(I, D, TU)))
Guy Benyei11169dd2012-12-18 14:30:41 +00001730 return true;
1731
1732 return false;
1733}
1734
1735//===----------------------------------------------------------------------===//
1736// Data-recursive visitor methods.
1737//===----------------------------------------------------------------------===//
1738
1739namespace {
1740#define DEF_JOB(NAME, DATA, KIND)\
1741class NAME : public VisitorJob {\
1742public:\
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001743 NAME(const DATA *d, CXCursor parent) : \
1744 VisitorJob(parent, VisitorJob::KIND, d) {} \
Guy Benyei11169dd2012-12-18 14:30:41 +00001745 static bool classof(const VisitorJob *VJ) { return VJ->getKind() == KIND; }\
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001746 const DATA *get() const { return static_cast<const DATA*>(data[0]); }\
Guy Benyei11169dd2012-12-18 14:30:41 +00001747};
1748
1749DEF_JOB(StmtVisit, Stmt, StmtVisitKind)
1750DEF_JOB(MemberExprParts, MemberExpr, MemberExprPartsKind)
1751DEF_JOB(DeclRefExprParts, DeclRefExpr, DeclRefExprPartsKind)
1752DEF_JOB(OverloadExprParts, OverloadExpr, OverloadExprPartsKind)
Guy Benyei11169dd2012-12-18 14:30:41 +00001753DEF_JOB(SizeOfPackExprParts, SizeOfPackExpr, SizeOfPackExprPartsKind)
1754DEF_JOB(LambdaExprParts, LambdaExpr, LambdaExprPartsKind)
1755DEF_JOB(PostChildrenVisit, void, PostChildrenVisitKind)
1756#undef DEF_JOB
1757
James Y Knight04ec5bf2015-12-24 02:59:37 +00001758class ExplicitTemplateArgsVisit : public VisitorJob {
1759public:
1760 ExplicitTemplateArgsVisit(const TemplateArgumentLoc *Begin,
1761 const TemplateArgumentLoc *End, CXCursor parent)
1762 : VisitorJob(parent, VisitorJob::ExplicitTemplateArgsVisitKind, Begin,
1763 End) {}
1764 static bool classof(const VisitorJob *VJ) {
1765 return VJ->getKind() == ExplicitTemplateArgsVisitKind;
1766 }
1767 const TemplateArgumentLoc *begin() const {
1768 return static_cast<const TemplateArgumentLoc *>(data[0]);
1769 }
1770 const TemplateArgumentLoc *end() {
1771 return static_cast<const TemplateArgumentLoc *>(data[1]);
1772 }
1773};
Guy Benyei11169dd2012-12-18 14:30:41 +00001774class DeclVisit : public VisitorJob {
1775public:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001776 DeclVisit(const Decl *D, CXCursor parent, bool isFirst) :
Guy Benyei11169dd2012-12-18 14:30:41 +00001777 VisitorJob(parent, VisitorJob::DeclVisitKind,
Craig Topper69186e72014-06-08 08:38:04 +00001778 D, isFirst ? (void*) 1 : (void*) nullptr) {}
Guy Benyei11169dd2012-12-18 14:30:41 +00001779 static bool classof(const VisitorJob *VJ) {
1780 return VJ->getKind() == DeclVisitKind;
1781 }
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001782 const Decl *get() const { return static_cast<const Decl *>(data[0]); }
Dmitri Gribenkoe5423a72015-03-23 19:23:50 +00001783 bool isFirst() const { return data[1] != nullptr; }
Guy Benyei11169dd2012-12-18 14:30:41 +00001784};
1785class TypeLocVisit : public VisitorJob {
1786public:
1787 TypeLocVisit(TypeLoc tl, CXCursor parent) :
1788 VisitorJob(parent, VisitorJob::TypeLocVisitKind,
1789 tl.getType().getAsOpaquePtr(), tl.getOpaqueData()) {}
1790
1791 static bool classof(const VisitorJob *VJ) {
1792 return VJ->getKind() == TypeLocVisitKind;
1793 }
1794
1795 TypeLoc get() const {
1796 QualType T = QualType::getFromOpaquePtr(data[0]);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001797 return TypeLoc(T, const_cast<void *>(data[1]));
Guy Benyei11169dd2012-12-18 14:30:41 +00001798 }
1799};
1800
1801class LabelRefVisit : public VisitorJob {
1802public:
1803 LabelRefVisit(LabelDecl *LD, SourceLocation labelLoc, CXCursor parent)
1804 : VisitorJob(parent, VisitorJob::LabelRefVisitKind, LD,
1805 labelLoc.getPtrEncoding()) {}
1806
1807 static bool classof(const VisitorJob *VJ) {
1808 return VJ->getKind() == VisitorJob::LabelRefVisitKind;
1809 }
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001810 const LabelDecl *get() const {
1811 return static_cast<const LabelDecl *>(data[0]);
1812 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001813 SourceLocation getLoc() const {
1814 return SourceLocation::getFromPtrEncoding(data[1]); }
1815};
1816
1817class NestedNameSpecifierLocVisit : public VisitorJob {
1818public:
1819 NestedNameSpecifierLocVisit(NestedNameSpecifierLoc Qualifier, CXCursor parent)
1820 : VisitorJob(parent, VisitorJob::NestedNameSpecifierLocVisitKind,
1821 Qualifier.getNestedNameSpecifier(),
1822 Qualifier.getOpaqueData()) { }
1823
1824 static bool classof(const VisitorJob *VJ) {
1825 return VJ->getKind() == VisitorJob::NestedNameSpecifierLocVisitKind;
1826 }
1827
1828 NestedNameSpecifierLoc get() const {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001829 return NestedNameSpecifierLoc(
1830 const_cast<NestedNameSpecifier *>(
1831 static_cast<const NestedNameSpecifier *>(data[0])),
1832 const_cast<void *>(data[1]));
Guy Benyei11169dd2012-12-18 14:30:41 +00001833 }
1834};
1835
1836class DeclarationNameInfoVisit : public VisitorJob {
1837public:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001838 DeclarationNameInfoVisit(const Stmt *S, CXCursor parent)
Dmitri Gribenkodd7dacf2013-02-03 13:19:54 +00001839 : VisitorJob(parent, VisitorJob::DeclarationNameInfoVisitKind, S) {}
Guy Benyei11169dd2012-12-18 14:30:41 +00001840 static bool classof(const VisitorJob *VJ) {
1841 return VJ->getKind() == VisitorJob::DeclarationNameInfoVisitKind;
1842 }
1843 DeclarationNameInfo get() const {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001844 const Stmt *S = static_cast<const Stmt *>(data[0]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001845 switch (S->getStmtClass()) {
1846 default:
1847 llvm_unreachable("Unhandled Stmt");
1848 case clang::Stmt::MSDependentExistsStmtClass:
1849 return cast<MSDependentExistsStmt>(S)->getNameInfo();
1850 case Stmt::CXXDependentScopeMemberExprClass:
1851 return cast<CXXDependentScopeMemberExpr>(S)->getMemberNameInfo();
1852 case Stmt::DependentScopeDeclRefExprClass:
1853 return cast<DependentScopeDeclRefExpr>(S)->getNameInfo();
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001854 case Stmt::OMPCriticalDirectiveClass:
1855 return cast<OMPCriticalDirective>(S)->getDirectiveName();
Guy Benyei11169dd2012-12-18 14:30:41 +00001856 }
1857 }
1858};
1859class MemberRefVisit : public VisitorJob {
1860public:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001861 MemberRefVisit(const FieldDecl *D, SourceLocation L, CXCursor parent)
Guy Benyei11169dd2012-12-18 14:30:41 +00001862 : VisitorJob(parent, VisitorJob::MemberRefVisitKind, D,
1863 L.getPtrEncoding()) {}
1864 static bool classof(const VisitorJob *VJ) {
1865 return VJ->getKind() == VisitorJob::MemberRefVisitKind;
1866 }
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001867 const FieldDecl *get() const {
1868 return static_cast<const FieldDecl *>(data[0]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001869 }
1870 SourceLocation getLoc() const {
1871 return SourceLocation::getFromRawEncoding((unsigned)(uintptr_t) data[1]);
1872 }
1873};
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001874class EnqueueVisitor : public ConstStmtVisitor<EnqueueVisitor, void> {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001875 friend class OMPClauseEnqueue;
Guy Benyei11169dd2012-12-18 14:30:41 +00001876 VisitorWorkList &WL;
1877 CXCursor Parent;
1878public:
1879 EnqueueVisitor(VisitorWorkList &wl, CXCursor parent)
1880 : WL(wl), Parent(parent) {}
1881
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001882 void VisitAddrLabelExpr(const AddrLabelExpr *E);
1883 void VisitBlockExpr(const BlockExpr *B);
1884 void VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
1885 void VisitCompoundStmt(const CompoundStmt *S);
1886 void VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) { /* Do nothing. */ }
1887 void VisitMSDependentExistsStmt(const MSDependentExistsStmt *S);
1888 void VisitCXXDependentScopeMemberExpr(const CXXDependentScopeMemberExpr *E);
1889 void VisitCXXNewExpr(const CXXNewExpr *E);
1890 void VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E);
1891 void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *E);
1892 void VisitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *E);
1893 void VisitCXXTemporaryObjectExpr(const CXXTemporaryObjectExpr *E);
1894 void VisitCXXTypeidExpr(const CXXTypeidExpr *E);
1895 void VisitCXXUnresolvedConstructExpr(const CXXUnresolvedConstructExpr *E);
1896 void VisitCXXUuidofExpr(const CXXUuidofExpr *E);
1897 void VisitCXXCatchStmt(const CXXCatchStmt *S);
Argyrios Kyrtzidis99891242014-11-13 09:03:21 +00001898 void VisitCXXForRangeStmt(const CXXForRangeStmt *S);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001899 void VisitDeclRefExpr(const DeclRefExpr *D);
1900 void VisitDeclStmt(const DeclStmt *S);
1901 void VisitDependentScopeDeclRefExpr(const DependentScopeDeclRefExpr *E);
1902 void VisitDesignatedInitExpr(const DesignatedInitExpr *E);
1903 void VisitExplicitCastExpr(const ExplicitCastExpr *E);
1904 void VisitForStmt(const ForStmt *FS);
1905 void VisitGotoStmt(const GotoStmt *GS);
1906 void VisitIfStmt(const IfStmt *If);
1907 void VisitInitListExpr(const InitListExpr *IE);
1908 void VisitMemberExpr(const MemberExpr *M);
1909 void VisitOffsetOfExpr(const OffsetOfExpr *E);
1910 void VisitObjCEncodeExpr(const ObjCEncodeExpr *E);
1911 void VisitObjCMessageExpr(const ObjCMessageExpr *M);
1912 void VisitOverloadExpr(const OverloadExpr *E);
1913 void VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
1914 void VisitStmt(const Stmt *S);
1915 void VisitSwitchStmt(const SwitchStmt *S);
1916 void VisitWhileStmt(const WhileStmt *W);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001917 void VisitTypeTraitExpr(const TypeTraitExpr *E);
1918 void VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E);
1919 void VisitExpressionTraitExpr(const ExpressionTraitExpr *E);
1920 void VisitUnresolvedMemberExpr(const UnresolvedMemberExpr *U);
1921 void VisitVAArgExpr(const VAArgExpr *E);
1922 void VisitSizeOfPackExpr(const SizeOfPackExpr *E);
1923 void VisitPseudoObjectExpr(const PseudoObjectExpr *E);
1924 void VisitOpaqueValueExpr(const OpaqueValueExpr *E);
1925 void VisitLambdaExpr(const LambdaExpr *E);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001926 void VisitOMPExecutableDirective(const OMPExecutableDirective *D);
Alexander Musman3aaab662014-08-19 11:27:13 +00001927 void VisitOMPLoopDirective(const OMPLoopDirective *D);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001928 void VisitOMPParallelDirective(const OMPParallelDirective *D);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00001929 void VisitOMPSimdDirective(const OMPSimdDirective *D);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001930 void VisitOMPForDirective(const OMPForDirective *D);
Alexander Musmanf82886e2014-09-18 05:12:34 +00001931 void VisitOMPForSimdDirective(const OMPForSimdDirective *D);
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00001932 void VisitOMPSectionsDirective(const OMPSectionsDirective *D);
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001933 void VisitOMPSectionDirective(const OMPSectionDirective *D);
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00001934 void VisitOMPSingleDirective(const OMPSingleDirective *D);
Alexander Musman80c22892014-07-17 08:54:58 +00001935 void VisitOMPMasterDirective(const OMPMasterDirective *D);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001936 void VisitOMPCriticalDirective(const OMPCriticalDirective *D);
Alexey Bataev4acb8592014-07-07 13:01:15 +00001937 void VisitOMPParallelForDirective(const OMPParallelForDirective *D);
Alexander Musmane4e893b2014-09-23 09:33:00 +00001938 void VisitOMPParallelForSimdDirective(const OMPParallelForSimdDirective *D);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001939 void VisitOMPParallelSectionsDirective(const OMPParallelSectionsDirective *D);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001940 void VisitOMPTaskDirective(const OMPTaskDirective *D);
Alexey Bataev68446b72014-07-18 07:47:19 +00001941 void VisitOMPTaskyieldDirective(const OMPTaskyieldDirective *D);
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001942 void VisitOMPBarrierDirective(const OMPBarrierDirective *D);
Alexey Bataev2df347a2014-07-18 10:17:07 +00001943 void VisitOMPTaskwaitDirective(const OMPTaskwaitDirective *D);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001944 void VisitOMPTaskgroupDirective(const OMPTaskgroupDirective *D);
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001945 void
1946 VisitOMPCancellationPointDirective(const OMPCancellationPointDirective *D);
Alexey Bataev80909872015-07-02 11:25:17 +00001947 void VisitOMPCancelDirective(const OMPCancelDirective *D);
Alexey Bataev6125da92014-07-21 11:26:11 +00001948 void VisitOMPFlushDirective(const OMPFlushDirective *D);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001949 void VisitOMPOrderedDirective(const OMPOrderedDirective *D);
Alexey Bataev0162e452014-07-22 10:10:35 +00001950 void VisitOMPAtomicDirective(const OMPAtomicDirective *D);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001951 void VisitOMPTargetDirective(const OMPTargetDirective *D);
Michael Wong65f367f2015-07-21 13:44:28 +00001952 void VisitOMPTargetDataDirective(const OMPTargetDataDirective *D);
Samuel Antaodf67fc42016-01-19 19:15:56 +00001953 void VisitOMPTargetEnterDataDirective(const OMPTargetEnterDataDirective *D);
Samuel Antao72590762016-01-19 20:04:50 +00001954 void VisitOMPTargetExitDataDirective(const OMPTargetExitDataDirective *D);
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00001955 void VisitOMPTargetParallelDirective(const OMPTargetParallelDirective *D);
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00001956 void
1957 VisitOMPTargetParallelForDirective(const OMPTargetParallelForDirective *D);
Alexey Bataev13314bf2014-10-09 04:18:56 +00001958 void VisitOMPTeamsDirective(const OMPTeamsDirective *D);
Alexey Bataev49f6e782015-12-01 04:18:41 +00001959 void VisitOMPTaskLoopDirective(const OMPTaskLoopDirective *D);
Alexey Bataev0a6ed842015-12-03 09:40:15 +00001960 void VisitOMPTaskLoopSimdDirective(const OMPTaskLoopSimdDirective *D);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00001961 void VisitOMPDistributeDirective(const OMPDistributeDirective *D);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001962
Guy Benyei11169dd2012-12-18 14:30:41 +00001963private:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001964 void AddDeclarationNameInfo(const Stmt *S);
Guy Benyei11169dd2012-12-18 14:30:41 +00001965 void AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier);
James Y Knight04ec5bf2015-12-24 02:59:37 +00001966 void AddExplicitTemplateArgs(const TemplateArgumentLoc *A,
1967 unsigned NumTemplateArgs);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001968 void AddMemberRef(const FieldDecl *D, SourceLocation L);
1969 void AddStmt(const Stmt *S);
1970 void AddDecl(const Decl *D, bool isFirst = true);
Guy Benyei11169dd2012-12-18 14:30:41 +00001971 void AddTypeLoc(TypeSourceInfo *TI);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001972 void EnqueueChildren(const Stmt *S);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001973 void EnqueueChildren(const OMPClause *S);
Guy Benyei11169dd2012-12-18 14:30:41 +00001974};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001975} // end anonyous namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00001976
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001977void EnqueueVisitor::AddDeclarationNameInfo(const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001978 // 'S' should always be non-null, since it comes from the
1979 // statement we are visiting.
1980 WL.push_back(DeclarationNameInfoVisit(S, Parent));
1981}
1982
1983void
1984EnqueueVisitor::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
1985 if (Qualifier)
1986 WL.push_back(NestedNameSpecifierLocVisit(Qualifier, Parent));
1987}
1988
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001989void EnqueueVisitor::AddStmt(const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001990 if (S)
1991 WL.push_back(StmtVisit(S, Parent));
1992}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001993void EnqueueVisitor::AddDecl(const Decl *D, bool isFirst) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001994 if (D)
1995 WL.push_back(DeclVisit(D, Parent, isFirst));
1996}
James Y Knight04ec5bf2015-12-24 02:59:37 +00001997void EnqueueVisitor::AddExplicitTemplateArgs(const TemplateArgumentLoc *A,
1998 unsigned NumTemplateArgs) {
1999 WL.push_back(ExplicitTemplateArgsVisit(A, A + NumTemplateArgs, Parent));
Guy Benyei11169dd2012-12-18 14:30:41 +00002000}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002001void EnqueueVisitor::AddMemberRef(const FieldDecl *D, SourceLocation L) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002002 if (D)
2003 WL.push_back(MemberRefVisit(D, L, Parent));
2004}
2005void EnqueueVisitor::AddTypeLoc(TypeSourceInfo *TI) {
2006 if (TI)
2007 WL.push_back(TypeLocVisit(TI->getTypeLoc(), Parent));
2008 }
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002009void EnqueueVisitor::EnqueueChildren(const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002010 unsigned size = WL.size();
Benjamin Kramer642f1732015-07-02 21:03:14 +00002011 for (const Stmt *SubStmt : S->children()) {
2012 AddStmt(SubStmt);
Guy Benyei11169dd2012-12-18 14:30:41 +00002013 }
2014 if (size == WL.size())
2015 return;
2016 // Now reverse the entries we just added. This will match the DFS
2017 // ordering performed by the worklist.
2018 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2019 std::reverse(I, E);
2020}
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002021namespace {
2022class OMPClauseEnqueue : public ConstOMPClauseVisitor<OMPClauseEnqueue> {
2023 EnqueueVisitor *Visitor;
Alexey Bataev756c1962013-09-24 03:17:45 +00002024 /// \brief Process clauses with list of variables.
2025 template <typename T>
2026 void VisitOMPClauseList(T *Node);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002027public:
2028 OMPClauseEnqueue(EnqueueVisitor *Visitor) : Visitor(Visitor) { }
2029#define OPENMP_CLAUSE(Name, Class) \
2030 void Visit##Class(const Class *C);
2031#include "clang/Basic/OpenMPKinds.def"
Alexey Bataev3392d762016-02-16 11:18:12 +00002032 void VisitOMPClauseWithPreInit(const OMPClauseWithPreInit *C);
Alexey Bataev005248a2016-02-25 05:25:57 +00002033 void VisitOMPClauseWithPostUpdate(const OMPClauseWithPostUpdate *C);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002034};
2035
Alexey Bataev3392d762016-02-16 11:18:12 +00002036void OMPClauseEnqueue::VisitOMPClauseWithPreInit(
2037 const OMPClauseWithPreInit *C) {
2038 Visitor->AddStmt(C->getPreInitStmt());
2039}
2040
Alexey Bataev005248a2016-02-25 05:25:57 +00002041void OMPClauseEnqueue::VisitOMPClauseWithPostUpdate(
2042 const OMPClauseWithPostUpdate *C) {
Alexey Bataev37e594c2016-03-04 07:21:16 +00002043 VisitOMPClauseWithPreInit(C);
Alexey Bataev005248a2016-02-25 05:25:57 +00002044 Visitor->AddStmt(C->getPostUpdateExpr());
2045}
2046
Alexey Bataevaadd52e2014-02-13 05:29:23 +00002047void OMPClauseEnqueue::VisitOMPIfClause(const OMPIfClause *C) {
2048 Visitor->AddStmt(C->getCondition());
2049}
2050
Alexey Bataev3778b602014-07-17 07:32:53 +00002051void OMPClauseEnqueue::VisitOMPFinalClause(const OMPFinalClause *C) {
2052 Visitor->AddStmt(C->getCondition());
2053}
2054
Alexey Bataev568a8332014-03-06 06:15:19 +00002055void OMPClauseEnqueue::VisitOMPNumThreadsClause(const OMPNumThreadsClause *C) {
2056 Visitor->AddStmt(C->getNumThreads());
2057}
2058
Alexey Bataev62c87d22014-03-21 04:51:18 +00002059void OMPClauseEnqueue::VisitOMPSafelenClause(const OMPSafelenClause *C) {
2060 Visitor->AddStmt(C->getSafelen());
2061}
2062
Alexey Bataev66b15b52015-08-21 11:14:16 +00002063void OMPClauseEnqueue::VisitOMPSimdlenClause(const OMPSimdlenClause *C) {
2064 Visitor->AddStmt(C->getSimdlen());
2065}
2066
Alexander Musman8bd31e62014-05-27 15:12:19 +00002067void OMPClauseEnqueue::VisitOMPCollapseClause(const OMPCollapseClause *C) {
2068 Visitor->AddStmt(C->getNumForLoops());
2069}
2070
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002071void OMPClauseEnqueue::VisitOMPDefaultClause(const OMPDefaultClause *C) { }
Alexey Bataev756c1962013-09-24 03:17:45 +00002072
Alexey Bataevbcbadb62014-05-06 06:04:14 +00002073void OMPClauseEnqueue::VisitOMPProcBindClause(const OMPProcBindClause *C) { }
2074
Alexey Bataev56dafe82014-06-20 07:16:17 +00002075void OMPClauseEnqueue::VisitOMPScheduleClause(const OMPScheduleClause *C) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002076 VisitOMPClauseWithPreInit(C);
Alexey Bataev56dafe82014-06-20 07:16:17 +00002077 Visitor->AddStmt(C->getChunkSize());
2078}
2079
Alexey Bataev10e775f2015-07-30 11:36:16 +00002080void OMPClauseEnqueue::VisitOMPOrderedClause(const OMPOrderedClause *C) {
2081 Visitor->AddStmt(C->getNumForLoops());
2082}
Alexey Bataev142e1fc2014-06-20 09:44:06 +00002083
Alexey Bataev236070f2014-06-20 11:19:47 +00002084void OMPClauseEnqueue::VisitOMPNowaitClause(const OMPNowaitClause *) {}
2085
Alexey Bataev7aea99a2014-07-17 12:19:31 +00002086void OMPClauseEnqueue::VisitOMPUntiedClause(const OMPUntiedClause *) {}
2087
Alexey Bataev74ba3a52014-07-17 12:47:03 +00002088void OMPClauseEnqueue::VisitOMPMergeableClause(const OMPMergeableClause *) {}
2089
Alexey Bataevf98b00c2014-07-23 02:27:21 +00002090void OMPClauseEnqueue::VisitOMPReadClause(const OMPReadClause *) {}
2091
Alexey Bataevdea47612014-07-23 07:46:59 +00002092void OMPClauseEnqueue::VisitOMPWriteClause(const OMPWriteClause *) {}
2093
Alexey Bataev67a4f222014-07-23 10:25:33 +00002094void OMPClauseEnqueue::VisitOMPUpdateClause(const OMPUpdateClause *) {}
2095
Alexey Bataev459dec02014-07-24 06:46:57 +00002096void OMPClauseEnqueue::VisitOMPCaptureClause(const OMPCaptureClause *) {}
2097
Alexey Bataev82bad8b2014-07-24 08:55:34 +00002098void OMPClauseEnqueue::VisitOMPSeqCstClause(const OMPSeqCstClause *) {}
2099
Alexey Bataev346265e2015-09-25 10:37:12 +00002100void OMPClauseEnqueue::VisitOMPThreadsClause(const OMPThreadsClause *) {}
2101
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002102void OMPClauseEnqueue::VisitOMPSIMDClause(const OMPSIMDClause *) {}
2103
Alexey Bataevb825de12015-12-07 10:51:44 +00002104void OMPClauseEnqueue::VisitOMPNogroupClause(const OMPNogroupClause *) {}
2105
Michael Wonge710d542015-08-07 16:16:36 +00002106void OMPClauseEnqueue::VisitOMPDeviceClause(const OMPDeviceClause *C) {
2107 Visitor->AddStmt(C->getDevice());
2108}
2109
Kelvin Li099bb8c2015-11-24 20:50:12 +00002110void OMPClauseEnqueue::VisitOMPNumTeamsClause(const OMPNumTeamsClause *C) {
2111 Visitor->AddStmt(C->getNumTeams());
2112}
2113
Kelvin Lia15fb1a2015-11-27 18:47:36 +00002114void OMPClauseEnqueue::VisitOMPThreadLimitClause(const OMPThreadLimitClause *C) {
2115 Visitor->AddStmt(C->getThreadLimit());
2116}
2117
Alexey Bataeva0569352015-12-01 10:17:31 +00002118void OMPClauseEnqueue::VisitOMPPriorityClause(const OMPPriorityClause *C) {
2119 Visitor->AddStmt(C->getPriority());
2120}
2121
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00002122void OMPClauseEnqueue::VisitOMPGrainsizeClause(const OMPGrainsizeClause *C) {
2123 Visitor->AddStmt(C->getGrainsize());
2124}
2125
Alexey Bataev382967a2015-12-08 12:06:20 +00002126void OMPClauseEnqueue::VisitOMPNumTasksClause(const OMPNumTasksClause *C) {
2127 Visitor->AddStmt(C->getNumTasks());
2128}
2129
Alexey Bataev28c75412015-12-15 08:19:24 +00002130void OMPClauseEnqueue::VisitOMPHintClause(const OMPHintClause *C) {
2131 Visitor->AddStmt(C->getHint());
2132}
2133
Alexey Bataev756c1962013-09-24 03:17:45 +00002134template<typename T>
2135void OMPClauseEnqueue::VisitOMPClauseList(T *Node) {
Alexey Bataev03b340a2014-10-21 03:16:40 +00002136 for (const auto *I : Node->varlists()) {
Aaron Ballman2205d2a2014-03-14 15:55:35 +00002137 Visitor->AddStmt(I);
Alexey Bataev03b340a2014-10-21 03:16:40 +00002138 }
Alexey Bataev756c1962013-09-24 03:17:45 +00002139}
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002140
2141void OMPClauseEnqueue::VisitOMPPrivateClause(const OMPPrivateClause *C) {
Alexey Bataev756c1962013-09-24 03:17:45 +00002142 VisitOMPClauseList(C);
Alexey Bataev03b340a2014-10-21 03:16:40 +00002143 for (const auto *E : C->private_copies()) {
2144 Visitor->AddStmt(E);
2145 }
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002146}
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002147void OMPClauseEnqueue::VisitOMPFirstprivateClause(
2148 const OMPFirstprivateClause *C) {
2149 VisitOMPClauseList(C);
Alexey Bataev417089f2016-02-17 13:19:37 +00002150 VisitOMPClauseWithPreInit(C);
2151 for (const auto *E : C->private_copies()) {
2152 Visitor->AddStmt(E);
2153 }
2154 for (const auto *E : C->inits()) {
2155 Visitor->AddStmt(E);
2156 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002157}
Alexander Musman1bb328c2014-06-04 13:06:39 +00002158void OMPClauseEnqueue::VisitOMPLastprivateClause(
2159 const OMPLastprivateClause *C) {
2160 VisitOMPClauseList(C);
Alexey Bataev005248a2016-02-25 05:25:57 +00002161 VisitOMPClauseWithPostUpdate(C);
Alexey Bataev38e89532015-04-16 04:54:05 +00002162 for (auto *E : C->private_copies()) {
2163 Visitor->AddStmt(E);
2164 }
2165 for (auto *E : C->source_exprs()) {
2166 Visitor->AddStmt(E);
2167 }
2168 for (auto *E : C->destination_exprs()) {
2169 Visitor->AddStmt(E);
2170 }
2171 for (auto *E : C->assignment_ops()) {
2172 Visitor->AddStmt(E);
2173 }
Alexander Musman1bb328c2014-06-04 13:06:39 +00002174}
Alexey Bataev758e55e2013-09-06 18:03:48 +00002175void OMPClauseEnqueue::VisitOMPSharedClause(const OMPSharedClause *C) {
Alexey Bataev756c1962013-09-24 03:17:45 +00002176 VisitOMPClauseList(C);
Alexey Bataev758e55e2013-09-06 18:03:48 +00002177}
Alexey Bataevc5e02582014-06-16 07:08:35 +00002178void OMPClauseEnqueue::VisitOMPReductionClause(const OMPReductionClause *C) {
2179 VisitOMPClauseList(C);
Alexey Bataev61205072016-03-02 04:57:40 +00002180 VisitOMPClauseWithPostUpdate(C);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00002181 for (auto *E : C->privates()) {
2182 Visitor->AddStmt(E);
2183 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002184 for (auto *E : C->lhs_exprs()) {
2185 Visitor->AddStmt(E);
2186 }
2187 for (auto *E : C->rhs_exprs()) {
2188 Visitor->AddStmt(E);
2189 }
2190 for (auto *E : C->reduction_ops()) {
2191 Visitor->AddStmt(E);
2192 }
Alexey Bataevc5e02582014-06-16 07:08:35 +00002193}
Alexander Musman8dba6642014-04-22 13:09:42 +00002194void OMPClauseEnqueue::VisitOMPLinearClause(const OMPLinearClause *C) {
2195 VisitOMPClauseList(C);
Alexey Bataev78849fb2016-03-09 09:49:00 +00002196 VisitOMPClauseWithPostUpdate(C);
Alexey Bataevbd9fec12015-08-18 06:47:21 +00002197 for (const auto *E : C->privates()) {
2198 Visitor->AddStmt(E);
2199 }
Alexander Musman3276a272015-03-21 10:12:56 +00002200 for (const auto *E : C->inits()) {
2201 Visitor->AddStmt(E);
2202 }
2203 for (const auto *E : C->updates()) {
2204 Visitor->AddStmt(E);
2205 }
2206 for (const auto *E : C->finals()) {
2207 Visitor->AddStmt(E);
2208 }
Alexander Musman8dba6642014-04-22 13:09:42 +00002209 Visitor->AddStmt(C->getStep());
Alexander Musman3276a272015-03-21 10:12:56 +00002210 Visitor->AddStmt(C->getCalcStep());
Alexander Musman8dba6642014-04-22 13:09:42 +00002211}
Alexander Musmanf0d76e72014-05-29 14:36:25 +00002212void OMPClauseEnqueue::VisitOMPAlignedClause(const OMPAlignedClause *C) {
2213 VisitOMPClauseList(C);
2214 Visitor->AddStmt(C->getAlignment());
2215}
Alexey Bataevd48bcd82014-03-31 03:36:38 +00002216void OMPClauseEnqueue::VisitOMPCopyinClause(const OMPCopyinClause *C) {
2217 VisitOMPClauseList(C);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00002218 for (auto *E : C->source_exprs()) {
2219 Visitor->AddStmt(E);
2220 }
2221 for (auto *E : C->destination_exprs()) {
2222 Visitor->AddStmt(E);
2223 }
2224 for (auto *E : C->assignment_ops()) {
2225 Visitor->AddStmt(E);
2226 }
Alexey Bataevd48bcd82014-03-31 03:36:38 +00002227}
Alexey Bataevbae9a792014-06-27 10:37:06 +00002228void
2229OMPClauseEnqueue::VisitOMPCopyprivateClause(const OMPCopyprivateClause *C) {
2230 VisitOMPClauseList(C);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002231 for (auto *E : C->source_exprs()) {
2232 Visitor->AddStmt(E);
2233 }
2234 for (auto *E : C->destination_exprs()) {
2235 Visitor->AddStmt(E);
2236 }
2237 for (auto *E : C->assignment_ops()) {
2238 Visitor->AddStmt(E);
2239 }
Alexey Bataevbae9a792014-06-27 10:37:06 +00002240}
Alexey Bataev6125da92014-07-21 11:26:11 +00002241void OMPClauseEnqueue::VisitOMPFlushClause(const OMPFlushClause *C) {
2242 VisitOMPClauseList(C);
2243}
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00002244void OMPClauseEnqueue::VisitOMPDependClause(const OMPDependClause *C) {
2245 VisitOMPClauseList(C);
2246}
Kelvin Li0bff7af2015-11-23 05:32:03 +00002247void OMPClauseEnqueue::VisitOMPMapClause(const OMPMapClause *C) {
2248 VisitOMPClauseList(C);
2249}
Carlo Bertollib4adf552016-01-15 18:50:31 +00002250void OMPClauseEnqueue::VisitOMPDistScheduleClause(
2251 const OMPDistScheduleClause *C) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002252 VisitOMPClauseWithPreInit(C);
Carlo Bertollib4adf552016-01-15 18:50:31 +00002253 Visitor->AddStmt(C->getChunkSize());
Carlo Bertollib4adf552016-01-15 18:50:31 +00002254}
Alexey Bataev3392d762016-02-16 11:18:12 +00002255void OMPClauseEnqueue::VisitOMPDefaultmapClause(
2256 const OMPDefaultmapClause * /*C*/) {}
Samuel Antao661c0902016-05-26 17:39:58 +00002257void OMPClauseEnqueue::VisitOMPToClause(const OMPToClause *C) {
2258 VisitOMPClauseList(C);
2259}
Samuel Antaoec172c62016-05-26 17:49:04 +00002260void OMPClauseEnqueue::VisitOMPFromClause(const OMPFromClause *C) {
2261 VisitOMPClauseList(C);
2262}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002263}
Alexey Bataev756c1962013-09-24 03:17:45 +00002264
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002265void EnqueueVisitor::EnqueueChildren(const OMPClause *S) {
2266 unsigned size = WL.size();
2267 OMPClauseEnqueue Visitor(this);
2268 Visitor.Visit(S);
2269 if (size == WL.size())
2270 return;
2271 // Now reverse the entries we just added. This will match the DFS
2272 // ordering performed by the worklist.
2273 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2274 std::reverse(I, E);
2275}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002276void EnqueueVisitor::VisitAddrLabelExpr(const AddrLabelExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002277 WL.push_back(LabelRefVisit(E->getLabel(), E->getLabelLoc(), Parent));
2278}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002279void EnqueueVisitor::VisitBlockExpr(const BlockExpr *B) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002280 AddDecl(B->getBlockDecl());
2281}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002282void EnqueueVisitor::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002283 EnqueueChildren(E);
2284 AddTypeLoc(E->getTypeSourceInfo());
2285}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002286void EnqueueVisitor::VisitCompoundStmt(const CompoundStmt *S) {
Pete Cooper57d3f142015-07-30 17:22:52 +00002287 for (auto &I : llvm::reverse(S->body()))
2288 AddStmt(I);
Guy Benyei11169dd2012-12-18 14:30:41 +00002289}
2290void EnqueueVisitor::
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002291VisitMSDependentExistsStmt(const MSDependentExistsStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002292 AddStmt(S->getSubStmt());
2293 AddDeclarationNameInfo(S);
2294 if (NestedNameSpecifierLoc QualifierLoc = S->getQualifierLoc())
2295 AddNestedNameSpecifierLoc(QualifierLoc);
2296}
2297
2298void EnqueueVisitor::
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002299VisitCXXDependentScopeMemberExpr(const CXXDependentScopeMemberExpr *E) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002300 if (E->hasExplicitTemplateArgs())
2301 AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002302 AddDeclarationNameInfo(E);
2303 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
2304 AddNestedNameSpecifierLoc(QualifierLoc);
2305 if (!E->isImplicitAccess())
2306 AddStmt(E->getBase());
2307}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002308void EnqueueVisitor::VisitCXXNewExpr(const CXXNewExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002309 // Enqueue the initializer , if any.
2310 AddStmt(E->getInitializer());
2311 // Enqueue the array size, if any.
2312 AddStmt(E->getArraySize());
2313 // Enqueue the allocated type.
2314 AddTypeLoc(E->getAllocatedTypeSourceInfo());
2315 // Enqueue the placement arguments.
2316 for (unsigned I = E->getNumPlacementArgs(); I > 0; --I)
2317 AddStmt(E->getPlacementArg(I-1));
2318}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002319void EnqueueVisitor::VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CE) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002320 for (unsigned I = CE->getNumArgs(); I > 1 /* Yes, this is 1 */; --I)
2321 AddStmt(CE->getArg(I-1));
2322 AddStmt(CE->getCallee());
2323 AddStmt(CE->getArg(0));
2324}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002325void EnqueueVisitor::VisitCXXPseudoDestructorExpr(
2326 const CXXPseudoDestructorExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002327 // Visit the name of the type being destroyed.
2328 AddTypeLoc(E->getDestroyedTypeInfo());
2329 // Visit the scope type that looks disturbingly like the nested-name-specifier
2330 // but isn't.
2331 AddTypeLoc(E->getScopeTypeInfo());
2332 // Visit the nested-name-specifier.
2333 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
2334 AddNestedNameSpecifierLoc(QualifierLoc);
2335 // Visit base expression.
2336 AddStmt(E->getBase());
2337}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002338void EnqueueVisitor::VisitCXXScalarValueInitExpr(
2339 const CXXScalarValueInitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002340 AddTypeLoc(E->getTypeSourceInfo());
2341}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002342void EnqueueVisitor::VisitCXXTemporaryObjectExpr(
2343 const CXXTemporaryObjectExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002344 EnqueueChildren(E);
2345 AddTypeLoc(E->getTypeSourceInfo());
2346}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002347void EnqueueVisitor::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002348 EnqueueChildren(E);
2349 if (E->isTypeOperand())
2350 AddTypeLoc(E->getTypeOperandSourceInfo());
2351}
2352
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002353void EnqueueVisitor::VisitCXXUnresolvedConstructExpr(
2354 const CXXUnresolvedConstructExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002355 EnqueueChildren(E);
2356 AddTypeLoc(E->getTypeSourceInfo());
2357}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002358void EnqueueVisitor::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002359 EnqueueChildren(E);
2360 if (E->isTypeOperand())
2361 AddTypeLoc(E->getTypeOperandSourceInfo());
2362}
2363
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002364void EnqueueVisitor::VisitCXXCatchStmt(const CXXCatchStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002365 EnqueueChildren(S);
2366 AddDecl(S->getExceptionDecl());
2367}
2368
Argyrios Kyrtzidis99891242014-11-13 09:03:21 +00002369void EnqueueVisitor::VisitCXXForRangeStmt(const CXXForRangeStmt *S) {
Argyrios Kyrtzidiscde70692014-11-13 09:50:19 +00002370 AddStmt(S->getBody());
Argyrios Kyrtzidis99891242014-11-13 09:03:21 +00002371 AddStmt(S->getRangeInit());
Argyrios Kyrtzidiscde70692014-11-13 09:50:19 +00002372 AddDecl(S->getLoopVariable());
Argyrios Kyrtzidis99891242014-11-13 09:03:21 +00002373}
2374
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002375void EnqueueVisitor::VisitDeclRefExpr(const DeclRefExpr *DR) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002376 if (DR->hasExplicitTemplateArgs())
2377 AddExplicitTemplateArgs(DR->getTemplateArgs(), DR->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002378 WL.push_back(DeclRefExprParts(DR, Parent));
2379}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002380void EnqueueVisitor::VisitDependentScopeDeclRefExpr(
2381 const DependentScopeDeclRefExpr *E) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002382 if (E->hasExplicitTemplateArgs())
2383 AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002384 AddDeclarationNameInfo(E);
2385 AddNestedNameSpecifierLoc(E->getQualifierLoc());
2386}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002387void EnqueueVisitor::VisitDeclStmt(const DeclStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002388 unsigned size = WL.size();
2389 bool isFirst = true;
Aaron Ballman535bbcc2014-03-14 17:01:24 +00002390 for (const auto *D : S->decls()) {
2391 AddDecl(D, isFirst);
Guy Benyei11169dd2012-12-18 14:30:41 +00002392 isFirst = false;
2393 }
2394 if (size == WL.size())
2395 return;
2396 // Now reverse the entries we just added. This will match the DFS
2397 // ordering performed by the worklist.
2398 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2399 std::reverse(I, E);
2400}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002401void EnqueueVisitor::VisitDesignatedInitExpr(const DesignatedInitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002402 AddStmt(E->getInit());
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002403 for (DesignatedInitExpr::const_reverse_designators_iterator
Guy Benyei11169dd2012-12-18 14:30:41 +00002404 D = E->designators_rbegin(), DEnd = E->designators_rend();
2405 D != DEnd; ++D) {
2406 if (D->isFieldDesignator()) {
2407 if (FieldDecl *Field = D->getField())
2408 AddMemberRef(Field, D->getFieldLoc());
2409 continue;
2410 }
2411 if (D->isArrayDesignator()) {
2412 AddStmt(E->getArrayIndex(*D));
2413 continue;
2414 }
2415 assert(D->isArrayRangeDesignator() && "Unknown designator kind");
2416 AddStmt(E->getArrayRangeEnd(*D));
2417 AddStmt(E->getArrayRangeStart(*D));
2418 }
2419}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002420void EnqueueVisitor::VisitExplicitCastExpr(const ExplicitCastExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002421 EnqueueChildren(E);
2422 AddTypeLoc(E->getTypeInfoAsWritten());
2423}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002424void EnqueueVisitor::VisitForStmt(const ForStmt *FS) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002425 AddStmt(FS->getBody());
2426 AddStmt(FS->getInc());
2427 AddStmt(FS->getCond());
2428 AddDecl(FS->getConditionVariable());
2429 AddStmt(FS->getInit());
2430}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002431void EnqueueVisitor::VisitGotoStmt(const GotoStmt *GS) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002432 WL.push_back(LabelRefVisit(GS->getLabel(), GS->getLabelLoc(), Parent));
2433}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002434void EnqueueVisitor::VisitIfStmt(const IfStmt *If) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002435 AddStmt(If->getElse());
2436 AddStmt(If->getThen());
2437 AddStmt(If->getCond());
2438 AddDecl(If->getConditionVariable());
2439}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002440void EnqueueVisitor::VisitInitListExpr(const InitListExpr *IE) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002441 // We care about the syntactic form of the initializer list, only.
2442 if (InitListExpr *Syntactic = IE->getSyntacticForm())
2443 IE = Syntactic;
2444 EnqueueChildren(IE);
2445}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002446void EnqueueVisitor::VisitMemberExpr(const MemberExpr *M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002447 WL.push_back(MemberExprParts(M, Parent));
2448
2449 // If the base of the member access expression is an implicit 'this', don't
2450 // visit it.
2451 // FIXME: If we ever want to show these implicit accesses, this will be
2452 // unfortunate. However, clang_getCursor() relies on this behavior.
Argyrios Kyrtzidis58d0e7a2015-03-13 04:40:07 +00002453 if (M->isImplicitAccess())
2454 return;
2455
2456 // Ignore base anonymous struct/union fields, otherwise they will shadow the
2457 // real field that that we are interested in.
2458 if (auto *SubME = dyn_cast<MemberExpr>(M->getBase())) {
2459 if (auto *FD = dyn_cast_or_null<FieldDecl>(SubME->getMemberDecl())) {
2460 if (FD->isAnonymousStructOrUnion()) {
2461 AddStmt(SubME->getBase());
2462 return;
2463 }
2464 }
2465 }
2466
2467 AddStmt(M->getBase());
Guy Benyei11169dd2012-12-18 14:30:41 +00002468}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002469void EnqueueVisitor::VisitObjCEncodeExpr(const ObjCEncodeExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002470 AddTypeLoc(E->getEncodedTypeSourceInfo());
2471}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002472void EnqueueVisitor::VisitObjCMessageExpr(const ObjCMessageExpr *M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002473 EnqueueChildren(M);
2474 AddTypeLoc(M->getClassReceiverTypeInfo());
2475}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002476void EnqueueVisitor::VisitOffsetOfExpr(const OffsetOfExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002477 // Visit the components of the offsetof expression.
2478 for (unsigned N = E->getNumComponents(), I = N; I > 0; --I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002479 const OffsetOfNode &Node = E->getComponent(I-1);
2480 switch (Node.getKind()) {
2481 case OffsetOfNode::Array:
2482 AddStmt(E->getIndexExpr(Node.getArrayExprIndex()));
2483 break;
2484 case OffsetOfNode::Field:
2485 AddMemberRef(Node.getField(), Node.getSourceRange().getEnd());
2486 break;
2487 case OffsetOfNode::Identifier:
2488 case OffsetOfNode::Base:
2489 continue;
2490 }
2491 }
2492 // Visit the type into which we're computing the offset.
2493 AddTypeLoc(E->getTypeSourceInfo());
2494}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002495void EnqueueVisitor::VisitOverloadExpr(const OverloadExpr *E) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002496 if (E->hasExplicitTemplateArgs())
2497 AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002498 WL.push_back(OverloadExprParts(E, Parent));
2499}
2500void EnqueueVisitor::VisitUnaryExprOrTypeTraitExpr(
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002501 const UnaryExprOrTypeTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002502 EnqueueChildren(E);
2503 if (E->isArgumentType())
2504 AddTypeLoc(E->getArgumentTypeInfo());
2505}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002506void EnqueueVisitor::VisitStmt(const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002507 EnqueueChildren(S);
2508}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002509void EnqueueVisitor::VisitSwitchStmt(const SwitchStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002510 AddStmt(S->getBody());
2511 AddStmt(S->getCond());
2512 AddDecl(S->getConditionVariable());
2513}
2514
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002515void EnqueueVisitor::VisitWhileStmt(const WhileStmt *W) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002516 AddStmt(W->getBody());
2517 AddStmt(W->getCond());
2518 AddDecl(W->getConditionVariable());
2519}
2520
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002521void EnqueueVisitor::VisitTypeTraitExpr(const TypeTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002522 for (unsigned I = E->getNumArgs(); I > 0; --I)
2523 AddTypeLoc(E->getArg(I-1));
2524}
2525
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002526void EnqueueVisitor::VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002527 AddTypeLoc(E->getQueriedTypeSourceInfo());
2528}
2529
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002530void EnqueueVisitor::VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002531 EnqueueChildren(E);
2532}
2533
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002534void EnqueueVisitor::VisitUnresolvedMemberExpr(const UnresolvedMemberExpr *U) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002535 VisitOverloadExpr(U);
2536 if (!U->isImplicitAccess())
2537 AddStmt(U->getBase());
2538}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002539void EnqueueVisitor::VisitVAArgExpr(const VAArgExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002540 AddStmt(E->getSubExpr());
2541 AddTypeLoc(E->getWrittenTypeInfo());
2542}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002543void EnqueueVisitor::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002544 WL.push_back(SizeOfPackExprParts(E, Parent));
2545}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002546void EnqueueVisitor::VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002547 // If the opaque value has a source expression, just transparently
2548 // visit that. This is useful for (e.g.) pseudo-object expressions.
2549 if (Expr *SourceExpr = E->getSourceExpr())
2550 return Visit(SourceExpr);
2551}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002552void EnqueueVisitor::VisitLambdaExpr(const LambdaExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002553 AddStmt(E->getBody());
2554 WL.push_back(LambdaExprParts(E, Parent));
2555}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002556void EnqueueVisitor::VisitPseudoObjectExpr(const PseudoObjectExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002557 // Treat the expression like its syntactic form.
2558 Visit(E->getSyntacticForm());
2559}
2560
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002561void EnqueueVisitor::VisitOMPExecutableDirective(
2562 const OMPExecutableDirective *D) {
2563 EnqueueChildren(D);
2564 for (ArrayRef<OMPClause *>::iterator I = D->clauses().begin(),
2565 E = D->clauses().end();
2566 I != E; ++I)
2567 EnqueueChildren(*I);
2568}
2569
Alexander Musman3aaab662014-08-19 11:27:13 +00002570void EnqueueVisitor::VisitOMPLoopDirective(const OMPLoopDirective *D) {
2571 VisitOMPExecutableDirective(D);
2572}
2573
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002574void EnqueueVisitor::VisitOMPParallelDirective(const OMPParallelDirective *D) {
2575 VisitOMPExecutableDirective(D);
2576}
2577
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002578void EnqueueVisitor::VisitOMPSimdDirective(const OMPSimdDirective *D) {
Alexander Musman3aaab662014-08-19 11:27:13 +00002579 VisitOMPLoopDirective(D);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002580}
2581
Alexey Bataevf29276e2014-06-18 04:14:57 +00002582void EnqueueVisitor::VisitOMPForDirective(const OMPForDirective *D) {
Alexander Musman3aaab662014-08-19 11:27:13 +00002583 VisitOMPLoopDirective(D);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002584}
2585
Alexander Musmanf82886e2014-09-18 05:12:34 +00002586void EnqueueVisitor::VisitOMPForSimdDirective(const OMPForSimdDirective *D) {
2587 VisitOMPLoopDirective(D);
2588}
2589
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002590void EnqueueVisitor::VisitOMPSectionsDirective(const OMPSectionsDirective *D) {
2591 VisitOMPExecutableDirective(D);
2592}
2593
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002594void EnqueueVisitor::VisitOMPSectionDirective(const OMPSectionDirective *D) {
2595 VisitOMPExecutableDirective(D);
2596}
2597
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00002598void EnqueueVisitor::VisitOMPSingleDirective(const OMPSingleDirective *D) {
2599 VisitOMPExecutableDirective(D);
2600}
2601
Alexander Musman80c22892014-07-17 08:54:58 +00002602void EnqueueVisitor::VisitOMPMasterDirective(const OMPMasterDirective *D) {
2603 VisitOMPExecutableDirective(D);
2604}
2605
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002606void EnqueueVisitor::VisitOMPCriticalDirective(const OMPCriticalDirective *D) {
2607 VisitOMPExecutableDirective(D);
2608 AddDeclarationNameInfo(D);
2609}
2610
Alexey Bataev4acb8592014-07-07 13:01:15 +00002611void
2612EnqueueVisitor::VisitOMPParallelForDirective(const OMPParallelForDirective *D) {
Alexander Musman3aaab662014-08-19 11:27:13 +00002613 VisitOMPLoopDirective(D);
Alexey Bataev4acb8592014-07-07 13:01:15 +00002614}
2615
Alexander Musmane4e893b2014-09-23 09:33:00 +00002616void EnqueueVisitor::VisitOMPParallelForSimdDirective(
2617 const OMPParallelForSimdDirective *D) {
2618 VisitOMPLoopDirective(D);
2619}
2620
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002621void EnqueueVisitor::VisitOMPParallelSectionsDirective(
2622 const OMPParallelSectionsDirective *D) {
2623 VisitOMPExecutableDirective(D);
2624}
2625
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002626void EnqueueVisitor::VisitOMPTaskDirective(const OMPTaskDirective *D) {
2627 VisitOMPExecutableDirective(D);
2628}
2629
Alexey Bataev68446b72014-07-18 07:47:19 +00002630void
2631EnqueueVisitor::VisitOMPTaskyieldDirective(const OMPTaskyieldDirective *D) {
2632 VisitOMPExecutableDirective(D);
2633}
2634
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002635void EnqueueVisitor::VisitOMPBarrierDirective(const OMPBarrierDirective *D) {
2636 VisitOMPExecutableDirective(D);
2637}
2638
Alexey Bataev2df347a2014-07-18 10:17:07 +00002639void EnqueueVisitor::VisitOMPTaskwaitDirective(const OMPTaskwaitDirective *D) {
2640 VisitOMPExecutableDirective(D);
2641}
2642
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002643void EnqueueVisitor::VisitOMPTaskgroupDirective(
2644 const OMPTaskgroupDirective *D) {
2645 VisitOMPExecutableDirective(D);
2646}
2647
Alexey Bataev6125da92014-07-21 11:26:11 +00002648void EnqueueVisitor::VisitOMPFlushDirective(const OMPFlushDirective *D) {
2649 VisitOMPExecutableDirective(D);
2650}
2651
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002652void EnqueueVisitor::VisitOMPOrderedDirective(const OMPOrderedDirective *D) {
2653 VisitOMPExecutableDirective(D);
2654}
2655
Alexey Bataev0162e452014-07-22 10:10:35 +00002656void EnqueueVisitor::VisitOMPAtomicDirective(const OMPAtomicDirective *D) {
2657 VisitOMPExecutableDirective(D);
2658}
2659
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002660void EnqueueVisitor::VisitOMPTargetDirective(const OMPTargetDirective *D) {
2661 VisitOMPExecutableDirective(D);
2662}
2663
Michael Wong65f367f2015-07-21 13:44:28 +00002664void EnqueueVisitor::VisitOMPTargetDataDirective(const
2665 OMPTargetDataDirective *D) {
2666 VisitOMPExecutableDirective(D);
2667}
2668
Samuel Antaodf67fc42016-01-19 19:15:56 +00002669void EnqueueVisitor::VisitOMPTargetEnterDataDirective(
2670 const OMPTargetEnterDataDirective *D) {
2671 VisitOMPExecutableDirective(D);
2672}
2673
Samuel Antao72590762016-01-19 20:04:50 +00002674void EnqueueVisitor::VisitOMPTargetExitDataDirective(
2675 const OMPTargetExitDataDirective *D) {
2676 VisitOMPExecutableDirective(D);
2677}
2678
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00002679void EnqueueVisitor::VisitOMPTargetParallelDirective(
2680 const OMPTargetParallelDirective *D) {
2681 VisitOMPExecutableDirective(D);
2682}
2683
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00002684void EnqueueVisitor::VisitOMPTargetParallelForDirective(
2685 const OMPTargetParallelForDirective *D) {
2686 VisitOMPLoopDirective(D);
2687}
2688
Alexey Bataev13314bf2014-10-09 04:18:56 +00002689void EnqueueVisitor::VisitOMPTeamsDirective(const OMPTeamsDirective *D) {
2690 VisitOMPExecutableDirective(D);
2691}
2692
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002693void EnqueueVisitor::VisitOMPCancellationPointDirective(
2694 const OMPCancellationPointDirective *D) {
2695 VisitOMPExecutableDirective(D);
2696}
2697
Alexey Bataev80909872015-07-02 11:25:17 +00002698void EnqueueVisitor::VisitOMPCancelDirective(const OMPCancelDirective *D) {
2699 VisitOMPExecutableDirective(D);
2700}
2701
Alexey Bataev49f6e782015-12-01 04:18:41 +00002702void EnqueueVisitor::VisitOMPTaskLoopDirective(const OMPTaskLoopDirective *D) {
2703 VisitOMPLoopDirective(D);
2704}
2705
Alexey Bataev0a6ed842015-12-03 09:40:15 +00002706void EnqueueVisitor::VisitOMPTaskLoopSimdDirective(
2707 const OMPTaskLoopSimdDirective *D) {
2708 VisitOMPLoopDirective(D);
2709}
2710
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002711void EnqueueVisitor::VisitOMPDistributeDirective(
2712 const OMPDistributeDirective *D) {
2713 VisitOMPLoopDirective(D);
2714}
2715
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002716void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002717 EnqueueVisitor(WL, MakeCXCursor(S, StmtParent, TU,RegionOfInterest)).Visit(S);
2718}
2719
2720bool CursorVisitor::IsInRegionOfInterest(CXCursor C) {
2721 if (RegionOfInterest.isValid()) {
2722 SourceRange Range = getRawCursorExtent(C);
2723 if (Range.isInvalid() || CompareRegionOfInterest(Range))
2724 return false;
2725 }
2726 return true;
2727}
2728
2729bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) {
2730 while (!WL.empty()) {
2731 // Dequeue the worklist item.
Robert Wilhelm25284cc2013-08-23 16:11:15 +00002732 VisitorJob LI = WL.pop_back_val();
Guy Benyei11169dd2012-12-18 14:30:41 +00002733
2734 // Set the Parent field, then back to its old value once we're done.
2735 SetParentRAII SetParent(Parent, StmtParent, LI.getParent());
2736
2737 switch (LI.getKind()) {
2738 case VisitorJob::DeclVisitKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002739 const Decl *D = cast<DeclVisit>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00002740 if (!D)
2741 continue;
2742
2743 // For now, perform default visitation for Decls.
2744 if (Visit(MakeCXCursor(D, TU, RegionOfInterest,
2745 cast<DeclVisit>(&LI)->isFirst())))
2746 return true;
2747
2748 continue;
2749 }
2750 case VisitorJob::ExplicitTemplateArgsVisitKind: {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002751 for (const TemplateArgumentLoc &Arg :
2752 *cast<ExplicitTemplateArgsVisit>(&LI)) {
2753 if (VisitTemplateArgumentLoc(Arg))
Guy Benyei11169dd2012-12-18 14:30:41 +00002754 return true;
2755 }
2756 continue;
2757 }
2758 case VisitorJob::TypeLocVisitKind: {
2759 // Perform default visitation for TypeLocs.
2760 if (Visit(cast<TypeLocVisit>(&LI)->get()))
2761 return true;
2762 continue;
2763 }
2764 case VisitorJob::LabelRefVisitKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002765 const LabelDecl *LS = cast<LabelRefVisit>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00002766 if (LabelStmt *stmt = LS->getStmt()) {
2767 if (Visit(MakeCursorLabelRef(stmt, cast<LabelRefVisit>(&LI)->getLoc(),
2768 TU))) {
2769 return true;
2770 }
2771 }
2772 continue;
2773 }
2774
2775 case VisitorJob::NestedNameSpecifierLocVisitKind: {
2776 NestedNameSpecifierLocVisit *V = cast<NestedNameSpecifierLocVisit>(&LI);
2777 if (VisitNestedNameSpecifierLoc(V->get()))
2778 return true;
2779 continue;
2780 }
2781
2782 case VisitorJob::DeclarationNameInfoVisitKind: {
2783 if (VisitDeclarationNameInfo(cast<DeclarationNameInfoVisit>(&LI)
2784 ->get()))
2785 return true;
2786 continue;
2787 }
2788 case VisitorJob::MemberRefVisitKind: {
2789 MemberRefVisit *V = cast<MemberRefVisit>(&LI);
2790 if (Visit(MakeCursorMemberRef(V->get(), V->getLoc(), TU)))
2791 return true;
2792 continue;
2793 }
2794 case VisitorJob::StmtVisitKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002795 const Stmt *S = cast<StmtVisit>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00002796 if (!S)
2797 continue;
2798
2799 // Update the current cursor.
2800 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU, RegionOfInterest);
2801 if (!IsInRegionOfInterest(Cursor))
2802 continue;
2803 switch (Visitor(Cursor, Parent, ClientData)) {
2804 case CXChildVisit_Break: return true;
2805 case CXChildVisit_Continue: break;
2806 case CXChildVisit_Recurse:
2807 if (PostChildrenVisitor)
Craig Topper69186e72014-06-08 08:38:04 +00002808 WL.push_back(PostChildrenVisit(nullptr, Cursor));
Guy Benyei11169dd2012-12-18 14:30:41 +00002809 EnqueueWorkList(WL, S);
2810 break;
2811 }
2812 continue;
2813 }
2814 case VisitorJob::MemberExprPartsKind: {
2815 // Handle the other pieces in the MemberExpr besides the base.
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002816 const MemberExpr *M = cast<MemberExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00002817
2818 // Visit the nested-name-specifier
2819 if (NestedNameSpecifierLoc QualifierLoc = M->getQualifierLoc())
2820 if (VisitNestedNameSpecifierLoc(QualifierLoc))
2821 return true;
2822
2823 // Visit the declaration name.
2824 if (VisitDeclarationNameInfo(M->getMemberNameInfo()))
2825 return true;
2826
2827 // Visit the explicitly-specified template arguments, if any.
2828 if (M->hasExplicitTemplateArgs()) {
2829 for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(),
2830 *ArgEnd = Arg + M->getNumTemplateArgs();
2831 Arg != ArgEnd; ++Arg) {
2832 if (VisitTemplateArgumentLoc(*Arg))
2833 return true;
2834 }
2835 }
2836 continue;
2837 }
2838 case VisitorJob::DeclRefExprPartsKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002839 const DeclRefExpr *DR = cast<DeclRefExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00002840 // Visit nested-name-specifier, if present.
2841 if (NestedNameSpecifierLoc QualifierLoc = DR->getQualifierLoc())
2842 if (VisitNestedNameSpecifierLoc(QualifierLoc))
2843 return true;
2844 // Visit declaration name.
2845 if (VisitDeclarationNameInfo(DR->getNameInfo()))
2846 return true;
2847 continue;
2848 }
2849 case VisitorJob::OverloadExprPartsKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002850 const OverloadExpr *O = cast<OverloadExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00002851 // Visit the nested-name-specifier.
2852 if (NestedNameSpecifierLoc QualifierLoc = O->getQualifierLoc())
2853 if (VisitNestedNameSpecifierLoc(QualifierLoc))
2854 return true;
2855 // Visit the declaration name.
2856 if (VisitDeclarationNameInfo(O->getNameInfo()))
2857 return true;
2858 // Visit the overloaded declaration reference.
2859 if (Visit(MakeCursorOverloadedDeclRef(O, TU)))
2860 return true;
2861 continue;
2862 }
2863 case VisitorJob::SizeOfPackExprPartsKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002864 const SizeOfPackExpr *E = cast<SizeOfPackExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00002865 NamedDecl *Pack = E->getPack();
2866 if (isa<TemplateTypeParmDecl>(Pack)) {
2867 if (Visit(MakeCursorTypeRef(cast<TemplateTypeParmDecl>(Pack),
2868 E->getPackLoc(), TU)))
2869 return true;
2870
2871 continue;
2872 }
2873
2874 if (isa<TemplateTemplateParmDecl>(Pack)) {
2875 if (Visit(MakeCursorTemplateRef(cast<TemplateTemplateParmDecl>(Pack),
2876 E->getPackLoc(), TU)))
2877 return true;
2878
2879 continue;
2880 }
2881
2882 // Non-type template parameter packs and function parameter packs are
2883 // treated like DeclRefExpr cursors.
2884 continue;
2885 }
2886
2887 case VisitorJob::LambdaExprPartsKind: {
2888 // Visit captures.
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002889 const LambdaExpr *E = cast<LambdaExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00002890 for (LambdaExpr::capture_iterator C = E->explicit_capture_begin(),
2891 CEnd = E->explicit_capture_end();
2892 C != CEnd; ++C) {
Richard Smithba71c082013-05-16 06:20:58 +00002893 // FIXME: Lambda init-captures.
2894 if (!C->capturesVariable())
Guy Benyei11169dd2012-12-18 14:30:41 +00002895 continue;
Richard Smithba71c082013-05-16 06:20:58 +00002896
Guy Benyei11169dd2012-12-18 14:30:41 +00002897 if (Visit(MakeCursorVariableRef(C->getCapturedVar(),
2898 C->getLocation(),
2899 TU)))
2900 return true;
2901 }
2902
2903 // Visit parameters and return type, if present.
2904 if (E->hasExplicitParameters() || E->hasExplicitResultType()) {
2905 TypeLoc TL = E->getCallOperator()->getTypeSourceInfo()->getTypeLoc();
2906 if (E->hasExplicitParameters() && E->hasExplicitResultType()) {
2907 // Visit the whole type.
2908 if (Visit(TL))
2909 return true;
David Blaikie6adc78e2013-02-18 22:06:02 +00002910 } else if (FunctionProtoTypeLoc Proto =
2911 TL.getAs<FunctionProtoTypeLoc>()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002912 if (E->hasExplicitParameters()) {
2913 // Visit parameters.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00002914 for (unsigned I = 0, N = Proto.getNumParams(); I != N; ++I)
2915 if (Visit(MakeCXCursor(Proto.getParam(I), TU)))
Guy Benyei11169dd2012-12-18 14:30:41 +00002916 return true;
2917 } else {
2918 // Visit result type.
Alp Toker42a16a62014-01-25 23:51:36 +00002919 if (Visit(Proto.getReturnLoc()))
Guy Benyei11169dd2012-12-18 14:30:41 +00002920 return true;
2921 }
2922 }
2923 }
2924 break;
2925 }
2926
2927 case VisitorJob::PostChildrenVisitKind:
2928 if (PostChildrenVisitor(Parent, ClientData))
2929 return true;
2930 break;
2931 }
2932 }
2933 return false;
2934}
2935
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002936bool CursorVisitor::Visit(const Stmt *S) {
Craig Topper69186e72014-06-08 08:38:04 +00002937 VisitorWorkList *WL = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00002938 if (!WorkListFreeList.empty()) {
2939 WL = WorkListFreeList.back();
2940 WL->clear();
2941 WorkListFreeList.pop_back();
2942 }
2943 else {
2944 WL = new VisitorWorkList();
2945 WorkListCache.push_back(WL);
2946 }
2947 EnqueueWorkList(*WL, S);
2948 bool result = RunVisitorWorkList(*WL);
2949 WorkListFreeList.push_back(WL);
2950 return result;
2951}
2952
2953namespace {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002954typedef SmallVector<SourceRange, 4> RefNamePieces;
James Y Knight04ec5bf2015-12-24 02:59:37 +00002955RefNamePieces buildPieces(unsigned NameFlags, bool IsMemberRefExpr,
2956 const DeclarationNameInfo &NI, SourceRange QLoc,
2957 const SourceRange *TemplateArgsLoc = nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002958 const bool WantQualifier = NameFlags & CXNameRange_WantQualifier;
2959 const bool WantTemplateArgs = NameFlags & CXNameRange_WantTemplateArgs;
2960 const bool WantSinglePiece = NameFlags & CXNameRange_WantSinglePiece;
2961
2962 const DeclarationName::NameKind Kind = NI.getName().getNameKind();
2963
2964 RefNamePieces Pieces;
2965
2966 if (WantQualifier && QLoc.isValid())
2967 Pieces.push_back(QLoc);
2968
2969 if (Kind != DeclarationName::CXXOperatorName || IsMemberRefExpr)
2970 Pieces.push_back(NI.getLoc());
James Y Knight04ec5bf2015-12-24 02:59:37 +00002971
2972 if (WantTemplateArgs && TemplateArgsLoc && TemplateArgsLoc->isValid())
2973 Pieces.push_back(*TemplateArgsLoc);
2974
Guy Benyei11169dd2012-12-18 14:30:41 +00002975 if (Kind == DeclarationName::CXXOperatorName) {
2976 Pieces.push_back(SourceLocation::getFromRawEncoding(
2977 NI.getInfo().CXXOperatorName.BeginOpNameLoc));
2978 Pieces.push_back(SourceLocation::getFromRawEncoding(
2979 NI.getInfo().CXXOperatorName.EndOpNameLoc));
2980 }
2981
2982 if (WantSinglePiece) {
2983 SourceRange R(Pieces.front().getBegin(), Pieces.back().getEnd());
2984 Pieces.clear();
2985 Pieces.push_back(R);
2986 }
2987
2988 return Pieces;
2989}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002990}
Guy Benyei11169dd2012-12-18 14:30:41 +00002991
2992//===----------------------------------------------------------------------===//
2993// Misc. API hooks.
2994//===----------------------------------------------------------------------===//
2995
Chad Rosier05c71aa2013-03-27 18:28:23 +00002996static void fatal_error_handler(void *user_data, const std::string& reason,
2997 bool gen_crash_diag) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002998 // Write the result out to stderr avoiding errs() because raw_ostreams can
2999 // call report_fatal_error.
3000 fprintf(stderr, "LIBCLANG FATAL ERROR: %s\n", reason.c_str());
3001 ::abort();
3002}
3003
Chandler Carruth66660742014-06-27 16:37:27 +00003004namespace {
3005struct RegisterFatalErrorHandler {
3006 RegisterFatalErrorHandler() {
3007 llvm::install_fatal_error_handler(fatal_error_handler, nullptr);
3008 }
3009};
3010}
3011
3012static llvm::ManagedStatic<RegisterFatalErrorHandler> RegisterFatalErrorHandlerOnce;
3013
Guy Benyei11169dd2012-12-18 14:30:41 +00003014extern "C" {
3015CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
3016 int displayDiagnostics) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003017 // We use crash recovery to make some of our APIs more reliable, implicitly
3018 // enable it.
Argyrios Kyrtzidis3701f542013-11-27 08:58:09 +00003019 if (!getenv("LIBCLANG_DISABLE_CRASH_RECOVERY"))
3020 llvm::CrashRecoveryContext::Enable();
Guy Benyei11169dd2012-12-18 14:30:41 +00003021
Chandler Carruth66660742014-06-27 16:37:27 +00003022 // Look through the managed static to trigger construction of the managed
3023 // static which registers our fatal error handler. This ensures it is only
3024 // registered once.
3025 (void)*RegisterFatalErrorHandlerOnce;
Guy Benyei11169dd2012-12-18 14:30:41 +00003026
Adrian Prantlbc068582015-07-08 01:00:30 +00003027 // Initialize targets for clang module support.
3028 llvm::InitializeAllTargets();
3029 llvm::InitializeAllTargetMCs();
3030 llvm::InitializeAllAsmPrinters();
3031 llvm::InitializeAllAsmParsers();
3032
Adrian Prantlfb2398d2015-07-17 01:19:54 +00003033 CIndexer *CIdxr = new CIndexer();
3034
Guy Benyei11169dd2012-12-18 14:30:41 +00003035 if (excludeDeclarationsFromPCH)
3036 CIdxr->setOnlyLocalDecls();
3037 if (displayDiagnostics)
3038 CIdxr->setDisplayDiagnostics();
3039
3040 if (getenv("LIBCLANG_BGPRIO_INDEX"))
3041 CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() |
3042 CXGlobalOpt_ThreadBackgroundPriorityForIndexing);
3043 if (getenv("LIBCLANG_BGPRIO_EDIT"))
3044 CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() |
3045 CXGlobalOpt_ThreadBackgroundPriorityForEditing);
3046
3047 return CIdxr;
3048}
3049
3050void clang_disposeIndex(CXIndex CIdx) {
3051 if (CIdx)
3052 delete static_cast<CIndexer *>(CIdx);
3053}
3054
3055void clang_CXIndex_setGlobalOptions(CXIndex CIdx, unsigned options) {
3056 if (CIdx)
3057 static_cast<CIndexer *>(CIdx)->setCXGlobalOptFlags(options);
3058}
3059
3060unsigned clang_CXIndex_getGlobalOptions(CXIndex CIdx) {
3061 if (CIdx)
3062 return static_cast<CIndexer *>(CIdx)->getCXGlobalOptFlags();
3063 return 0;
3064}
3065
3066void clang_toggleCrashRecovery(unsigned isEnabled) {
3067 if (isEnabled)
3068 llvm::CrashRecoveryContext::Enable();
3069 else
3070 llvm::CrashRecoveryContext::Disable();
3071}
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003072
Guy Benyei11169dd2012-12-18 14:30:41 +00003073CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
3074 const char *ast_filename) {
Dmitri Gribenko8850cda2014-02-19 10:24:00 +00003075 CXTranslationUnit TU;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003076 enum CXErrorCode Result =
3077 clang_createTranslationUnit2(CIdx, ast_filename, &TU);
Reid Klecknerfd48fc62014-02-12 23:56:20 +00003078 (void)Result;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003079 assert((TU && Result == CXError_Success) ||
3080 (!TU && Result != CXError_Success));
3081 return TU;
3082}
3083
3084enum CXErrorCode clang_createTranslationUnit2(CXIndex CIdx,
3085 const char *ast_filename,
3086 CXTranslationUnit *out_TU) {
Dmitri Gribenko8850cda2014-02-19 10:24:00 +00003087 if (out_TU)
Craig Topper69186e72014-06-08 08:38:04 +00003088 *out_TU = nullptr;
Dmitri Gribenko8850cda2014-02-19 10:24:00 +00003089
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003090 if (!CIdx || !ast_filename || !out_TU)
3091 return CXError_InvalidArguments;
Guy Benyei11169dd2012-12-18 14:30:41 +00003092
Argyrios Kyrtzidis27021012013-05-24 22:24:07 +00003093 LOG_FUNC_SECTION {
3094 *Log << ast_filename;
3095 }
3096
Guy Benyei11169dd2012-12-18 14:30:41 +00003097 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
3098 FileSystemOptions FileSystemOpts;
3099
Justin Bognerd512c1e2014-10-15 00:33:06 +00003100 IntrusiveRefCntPtr<DiagnosticsEngine> Diags =
3101 CompilerInstance::createDiagnostics(new DiagnosticOptions());
David Blaikie6f7382d2014-08-10 19:08:04 +00003102 std::unique_ptr<ASTUnit> AU = ASTUnit::LoadFromASTFile(
Adrian Prantlfb2398d2015-07-17 01:19:54 +00003103 ast_filename, CXXIdx->getPCHContainerOperations()->getRawReader(), Diags,
Adrian Prantl6b21ab22015-08-27 19:46:20 +00003104 FileSystemOpts, /*UseDebugInfo=*/false,
3105 CXXIdx->getOnlyLocalDecls(), None,
David Blaikie6f7382d2014-08-10 19:08:04 +00003106 /*CaptureDiagnostics=*/true,
3107 /*AllowPCHWithCompilerErrors=*/true,
3108 /*UserFilesAreVolatile=*/true);
3109 *out_TU = MakeCXTranslationUnit(CXXIdx, AU.release());
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003110 return *out_TU ? CXError_Success : CXError_Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003111}
3112
3113unsigned clang_defaultEditingTranslationUnitOptions() {
3114 return CXTranslationUnit_PrecompiledPreamble |
3115 CXTranslationUnit_CacheCompletionResults;
3116}
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003117
Guy Benyei11169dd2012-12-18 14:30:41 +00003118CXTranslationUnit
3119clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
3120 const char *source_filename,
3121 int num_command_line_args,
3122 const char * const *command_line_args,
3123 unsigned num_unsaved_files,
3124 struct CXUnsavedFile *unsaved_files) {
3125 unsigned Options = CXTranslationUnit_DetailedPreprocessingRecord;
3126 return clang_parseTranslationUnit(CIdx, source_filename,
3127 command_line_args, num_command_line_args,
3128 unsaved_files, num_unsaved_files,
3129 Options);
3130}
3131
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003132static CXErrorCode
3133clang_parseTranslationUnit_Impl(CXIndex CIdx, const char *source_filename,
3134 const char *const *command_line_args,
3135 int num_command_line_args,
3136 ArrayRef<CXUnsavedFile> unsaved_files,
3137 unsigned options, CXTranslationUnit *out_TU) {
Dmitri Gribenko1bf8d912014-02-18 15:20:02 +00003138 // Set up the initial return values.
3139 if (out_TU)
Craig Topper69186e72014-06-08 08:38:04 +00003140 *out_TU = nullptr;
Dmitri Gribenko1bf8d912014-02-18 15:20:02 +00003141
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003142 // Check arguments.
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003143 if (!CIdx || !out_TU)
3144 return CXError_InvalidArguments;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003145
Guy Benyei11169dd2012-12-18 14:30:41 +00003146 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
3147
3148 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
3149 setThreadBackgroundPriority();
3150
3151 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Benjamin Kramer5c248d82015-12-15 09:30:31 +00003152 bool CreatePreambleOnFirstParse =
3153 options & CXTranslationUnit_CreatePreambleOnFirstParse;
Guy Benyei11169dd2012-12-18 14:30:41 +00003154 // FIXME: Add a flag for modules.
3155 TranslationUnitKind TUKind
3156 = (options & CXTranslationUnit_Incomplete)? TU_Prefix : TU_Complete;
Alp Toker8c8a8752013-12-03 06:53:35 +00003157 bool CacheCodeCompletionResults
Guy Benyei11169dd2012-12-18 14:30:41 +00003158 = options & CXTranslationUnit_CacheCompletionResults;
3159 bool IncludeBriefCommentsInCodeCompletion
3160 = options & CXTranslationUnit_IncludeBriefCommentsInCodeCompletion;
3161 bool SkipFunctionBodies = options & CXTranslationUnit_SkipFunctionBodies;
3162 bool ForSerialization = options & CXTranslationUnit_ForSerialization;
3163
3164 // Configure the diagnostics.
3165 IntrusiveRefCntPtr<DiagnosticsEngine>
Sean Silvaf1b49e22013-01-20 01:58:28 +00003166 Diags(CompilerInstance::createDiagnostics(new DiagnosticOptions));
Guy Benyei11169dd2012-12-18 14:30:41 +00003167
Manuel Klimek016c0242016-03-01 10:56:19 +00003168 if (options & CXTranslationUnit_KeepGoing)
3169 Diags->setFatalsAsError(true);
3170
Guy Benyei11169dd2012-12-18 14:30:41 +00003171 // Recover resources if we crash before exiting this function.
3172 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
3173 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Alp Tokerf994cef2014-07-05 03:08:06 +00003174 DiagCleanup(Diags.get());
Guy Benyei11169dd2012-12-18 14:30:41 +00003175
Ahmed Charlesb8984322014-03-07 20:03:18 +00003176 std::unique_ptr<std::vector<ASTUnit::RemappedFile>> RemappedFiles(
3177 new std::vector<ASTUnit::RemappedFile>());
Guy Benyei11169dd2012-12-18 14:30:41 +00003178
3179 // Recover resources if we crash before exiting this function.
3180 llvm::CrashRecoveryContextCleanupRegistrar<
3181 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
3182
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003183 for (auto &UF : unsaved_files) {
Rafael Espindolad87f8d72014-08-27 20:03:29 +00003184 std::unique_ptr<llvm::MemoryBuffer> MB =
Alp Toker9d85b182014-07-07 01:23:14 +00003185 llvm::MemoryBuffer::getMemBufferCopy(getContents(UF), UF.Filename);
Rafael Espindolad87f8d72014-08-27 20:03:29 +00003186 RemappedFiles->push_back(std::make_pair(UF.Filename, MB.release()));
Guy Benyei11169dd2012-12-18 14:30:41 +00003187 }
3188
Ahmed Charlesb8984322014-03-07 20:03:18 +00003189 std::unique_ptr<std::vector<const char *>> Args(
3190 new std::vector<const char *>());
Guy Benyei11169dd2012-12-18 14:30:41 +00003191
3192 // Recover resources if we crash before exiting this method.
3193 llvm::CrashRecoveryContextCleanupRegistrar<std::vector<const char*> >
3194 ArgsCleanup(Args.get());
3195
3196 // Since the Clang C library is primarily used by batch tools dealing with
3197 // (often very broken) source code, where spell-checking can have a
3198 // significant negative impact on performance (particularly when
3199 // precompiled headers are involved), we disable it by default.
3200 // Only do this if we haven't found a spell-checking-related argument.
3201 bool FoundSpellCheckingArgument = false;
3202 for (int I = 0; I != num_command_line_args; ++I) {
3203 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
3204 strcmp(command_line_args[I], "-fspell-checking") == 0) {
3205 FoundSpellCheckingArgument = true;
3206 break;
3207 }
3208 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003209 Args->insert(Args->end(), command_line_args,
3210 command_line_args + num_command_line_args);
3211
Benjamin Kramerc02670e2015-11-18 16:14:27 +00003212 if (!FoundSpellCheckingArgument)
3213 Args->insert(Args->begin() + 1, "-fno-spell-checking");
3214
Guy Benyei11169dd2012-12-18 14:30:41 +00003215 // The 'source_filename' argument is optional. If the caller does not
3216 // specify it then it is assumed that the source file is specified
3217 // in the actual argument list.
3218 // Put the source file after command_line_args otherwise if '-x' flag is
3219 // present it will be unused.
3220 if (source_filename)
3221 Args->push_back(source_filename);
3222
3223 // Do we need the detailed preprocessing record?
3224 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
3225 Args->push_back("-Xclang");
3226 Args->push_back("-detailed-preprocessing-record");
3227 }
3228
3229 unsigned NumErrors = Diags->getClient()->getNumErrors();
Ahmed Charlesb8984322014-03-07 20:03:18 +00003230 std::unique_ptr<ASTUnit> ErrUnit;
Benjamin Kramer5c248d82015-12-15 09:30:31 +00003231 // Unless the user specified that they want the preamble on the first parse
3232 // set it up to be created on the first reparse. This makes the first parse
3233 // faster, trading for a slower (first) reparse.
3234 unsigned PrecompilePreambleAfterNParses =
3235 !PrecompilePreamble ? 0 : 2 - CreatePreambleOnFirstParse;
Ahmed Charlesb8984322014-03-07 20:03:18 +00003236 std::unique_ptr<ASTUnit> Unit(ASTUnit::LoadFromCommandLine(
Adrian Prantlbb165fb2015-06-20 18:53:08 +00003237 Args->data(), Args->data() + Args->size(),
3238 CXXIdx->getPCHContainerOperations(), Diags,
Ahmed Charlesb8984322014-03-07 20:03:18 +00003239 CXXIdx->getClangResourcesPath(), CXXIdx->getOnlyLocalDecls(),
3240 /*CaptureDiagnostics=*/true, *RemappedFiles.get(),
Benjamin Kramer5c248d82015-12-15 09:30:31 +00003241 /*RemappedFilesKeepOriginalName=*/true, PrecompilePreambleAfterNParses,
3242 TUKind, CacheCodeCompletionResults, IncludeBriefCommentsInCodeCompletion,
Ahmed Charlesb8984322014-03-07 20:03:18 +00003243 /*AllowPCHWithCompilerErrors=*/true, SkipFunctionBodies,
Argyrios Kyrtzidisa3e2ff12015-11-20 03:36:21 +00003244 /*UserFilesAreVolatile=*/true, ForSerialization,
3245 CXXIdx->getPCHContainerOperations()->getRawReader().getFormat(),
3246 &ErrUnit));
Guy Benyei11169dd2012-12-18 14:30:41 +00003247
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003248 // Early failures in LoadFromCommandLine may return with ErrUnit unset.
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003249 if (!Unit && !ErrUnit)
3250 return CXError_ASTReadError;
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003251
Guy Benyei11169dd2012-12-18 14:30:41 +00003252 if (NumErrors != Diags->getClient()->getNumErrors()) {
3253 // Make sure to check that 'Unit' is non-NULL.
3254 if (CXXIdx->getDisplayDiagnostics())
3255 printDiagsToStderr(Unit ? Unit.get() : ErrUnit.get());
3256 }
3257
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003258 if (isASTReadError(Unit ? Unit.get() : ErrUnit.get()))
3259 return CXError_ASTReadError;
3260
3261 *out_TU = MakeCXTranslationUnit(CXXIdx, Unit.release());
3262 return *out_TU ? CXError_Success : CXError_Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003263}
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003264
3265CXTranslationUnit
3266clang_parseTranslationUnit(CXIndex CIdx,
3267 const char *source_filename,
3268 const char *const *command_line_args,
3269 int num_command_line_args,
3270 struct CXUnsavedFile *unsaved_files,
3271 unsigned num_unsaved_files,
3272 unsigned options) {
3273 CXTranslationUnit TU;
3274 enum CXErrorCode Result = clang_parseTranslationUnit2(
3275 CIdx, source_filename, command_line_args, num_command_line_args,
3276 unsaved_files, num_unsaved_files, options, &TU);
Reid Kleckner6eaf05a2014-02-13 01:19:59 +00003277 (void)Result;
Dmitri Gribenko1bf8d912014-02-18 15:20:02 +00003278 assert((TU && Result == CXError_Success) ||
3279 (!TU && Result != CXError_Success));
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003280 return TU;
3281}
3282
3283enum CXErrorCode clang_parseTranslationUnit2(
Benjamin Kramerc02670e2015-11-18 16:14:27 +00003284 CXIndex CIdx, const char *source_filename,
3285 const char *const *command_line_args, int num_command_line_args,
3286 struct CXUnsavedFile *unsaved_files, unsigned num_unsaved_files,
3287 unsigned options, CXTranslationUnit *out_TU) {
3288 SmallVector<const char *, 4> Args;
3289 Args.push_back("clang");
3290 Args.append(command_line_args, command_line_args + num_command_line_args);
3291 return clang_parseTranslationUnit2FullArgv(
3292 CIdx, source_filename, Args.data(), Args.size(), unsaved_files,
3293 num_unsaved_files, options, out_TU);
3294}
3295
3296enum CXErrorCode clang_parseTranslationUnit2FullArgv(
3297 CXIndex CIdx, const char *source_filename,
3298 const char *const *command_line_args, int num_command_line_args,
3299 struct CXUnsavedFile *unsaved_files, unsigned num_unsaved_files,
3300 unsigned options, CXTranslationUnit *out_TU) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00003301 LOG_FUNC_SECTION {
3302 *Log << source_filename << ": ";
3303 for (int i = 0; i != num_command_line_args; ++i)
3304 *Log << command_line_args[i] << " ";
3305 }
3306
Alp Toker9d85b182014-07-07 01:23:14 +00003307 if (num_unsaved_files && !unsaved_files)
3308 return CXError_InvalidArguments;
3309
Alp Toker5c532982014-07-07 22:42:03 +00003310 CXErrorCode result = CXError_Failure;
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003311 auto ParseTranslationUnitImpl = [=, &result] {
3312 result = clang_parseTranslationUnit_Impl(
3313 CIdx, source_filename, command_line_args, num_command_line_args,
3314 llvm::makeArrayRef(unsaved_files, num_unsaved_files), options, out_TU);
3315 };
Guy Benyei11169dd2012-12-18 14:30:41 +00003316 llvm::CrashRecoveryContext CRC;
3317
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003318 if (!RunSafely(CRC, ParseTranslationUnitImpl)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003319 fprintf(stderr, "libclang: crash detected during parsing: {\n");
3320 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
3321 fprintf(stderr, " 'command_line_args' : [");
3322 for (int i = 0; i != num_command_line_args; ++i) {
3323 if (i)
3324 fprintf(stderr, ", ");
3325 fprintf(stderr, "'%s'", command_line_args[i]);
3326 }
3327 fprintf(stderr, "],\n");
3328 fprintf(stderr, " 'unsaved_files' : [");
3329 for (unsigned i = 0; i != num_unsaved_files; ++i) {
3330 if (i)
3331 fprintf(stderr, ", ");
3332 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
3333 unsaved_files[i].Length);
3334 }
3335 fprintf(stderr, "],\n");
3336 fprintf(stderr, " 'options' : %d,\n", options);
3337 fprintf(stderr, "}\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003338
3339 return CXError_Crashed;
Guy Benyei11169dd2012-12-18 14:30:41 +00003340 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003341 if (CXTranslationUnit *TU = out_TU)
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003342 PrintLibclangResourceUsage(*TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00003343 }
Alp Toker5c532982014-07-07 22:42:03 +00003344
3345 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003346}
3347
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003348CXString clang_Type_getObjCEncoding(CXType CT) {
3349 CXTranslationUnit tu = static_cast<CXTranslationUnit>(CT.data[1]);
3350 ASTContext &Ctx = getASTUnit(tu)->getASTContext();
3351 std::string encoding;
3352 Ctx.getObjCEncodingForType(QualType::getFromOpaquePtr(CT.data[0]),
3353 encoding);
3354
3355 return cxstring::createDup(encoding);
3356}
3357
3358static const IdentifierInfo *getMacroIdentifier(CXCursor C) {
3359 if (C.kind == CXCursor_MacroDefinition) {
3360 if (const MacroDefinitionRecord *MDR = getCursorMacroDefinition(C))
3361 return MDR->getName();
3362 } else if (C.kind == CXCursor_MacroExpansion) {
3363 MacroExpansionCursor ME = getCursorMacroExpansion(C);
3364 return ME.getName();
3365 }
3366 return nullptr;
3367}
3368
3369unsigned clang_Cursor_isMacroFunctionLike(CXCursor C) {
3370 const IdentifierInfo *II = getMacroIdentifier(C);
3371 if (!II) {
3372 return false;
3373 }
3374 ASTUnit *ASTU = getCursorASTUnit(C);
3375 Preprocessor &PP = ASTU->getPreprocessor();
3376 if (const MacroInfo *MI = PP.getMacroInfo(II))
3377 return MI->isFunctionLike();
3378 return false;
3379}
3380
3381unsigned clang_Cursor_isMacroBuiltin(CXCursor C) {
3382 const IdentifierInfo *II = getMacroIdentifier(C);
3383 if (!II) {
3384 return false;
3385 }
3386 ASTUnit *ASTU = getCursorASTUnit(C);
3387 Preprocessor &PP = ASTU->getPreprocessor();
3388 if (const MacroInfo *MI = PP.getMacroInfo(II))
3389 return MI->isBuiltinMacro();
3390 return false;
3391}
3392
3393unsigned clang_Cursor_isFunctionInlined(CXCursor C) {
3394 const Decl *D = getCursorDecl(C);
3395 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
3396 if (!FD) {
3397 return false;
3398 }
3399 return FD->isInlined();
3400}
3401
3402static StringLiteral* getCFSTR_value(CallExpr *callExpr) {
3403 if (callExpr->getNumArgs() != 1) {
3404 return nullptr;
3405 }
3406
3407 StringLiteral *S = nullptr;
3408 auto *arg = callExpr->getArg(0);
3409 if (arg->getStmtClass() == Stmt::ImplicitCastExprClass) {
3410 ImplicitCastExpr *I = static_cast<ImplicitCastExpr *>(arg);
3411 auto *subExpr = I->getSubExprAsWritten();
3412
3413 if(subExpr->getStmtClass() != Stmt::StringLiteralClass){
3414 return nullptr;
3415 }
3416
3417 S = static_cast<StringLiteral *>(I->getSubExprAsWritten());
3418 } else if (arg->getStmtClass() == Stmt::StringLiteralClass) {
3419 S = static_cast<StringLiteral *>(callExpr->getArg(0));
3420 } else {
3421 return nullptr;
3422 }
3423 return S;
3424}
3425
David Blaikie59272572016-04-13 18:23:33 +00003426struct ExprEvalResult {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003427 CXEvalResultKind EvalType;
3428 union {
3429 int intVal;
3430 double floatVal;
3431 char *stringVal;
3432 } EvalData;
David Blaikie59272572016-04-13 18:23:33 +00003433 ~ExprEvalResult() {
3434 if (EvalType != CXEval_UnExposed && EvalType != CXEval_Float &&
3435 EvalType != CXEval_Int) {
3436 delete EvalData.stringVal;
3437 }
3438 }
3439};
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003440
3441void clang_EvalResult_dispose(CXEvalResult E) {
David Blaikie59272572016-04-13 18:23:33 +00003442 delete static_cast<ExprEvalResult *>(E);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003443}
3444
3445CXEvalResultKind clang_EvalResult_getKind(CXEvalResult E) {
3446 if (!E) {
3447 return CXEval_UnExposed;
3448 }
3449 return ((ExprEvalResult *)E)->EvalType;
3450}
3451
3452int clang_EvalResult_getAsInt(CXEvalResult E) {
3453 if (!E) {
3454 return 0;
3455 }
3456 return ((ExprEvalResult *)E)->EvalData.intVal;
3457}
3458
3459double clang_EvalResult_getAsDouble(CXEvalResult E) {
3460 if (!E) {
3461 return 0;
3462 }
3463 return ((ExprEvalResult *)E)->EvalData.floatVal;
3464}
3465
3466const char* clang_EvalResult_getAsStr(CXEvalResult E) {
3467 if (!E) {
3468 return nullptr;
3469 }
3470 return ((ExprEvalResult *)E)->EvalData.stringVal;
3471}
3472
3473static const ExprEvalResult* evaluateExpr(Expr *expr, CXCursor C) {
3474 Expr::EvalResult ER;
3475 ASTContext &ctx = getCursorContext(C);
David Blaikiebbc00882016-04-13 18:36:19 +00003476 if (!expr)
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003477 return nullptr;
David Blaikiebbc00882016-04-13 18:36:19 +00003478
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003479 expr = expr->IgnoreParens();
David Blaikiebbc00882016-04-13 18:36:19 +00003480 if (!expr->EvaluateAsRValue(ER, ctx))
3481 return nullptr;
3482
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003483 QualType rettype;
3484 CallExpr *callExpr;
David Blaikie59272572016-04-13 18:23:33 +00003485 auto result = llvm::make_unique<ExprEvalResult>();
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003486 result->EvalType = CXEval_UnExposed;
3487
David Blaikiebbc00882016-04-13 18:36:19 +00003488 if (ER.Val.isInt()) {
3489 result->EvalType = CXEval_Int;
3490 result->EvalData.intVal = ER.Val.getInt().getExtValue();
3491 return result.release();
3492 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003493
David Blaikiebbc00882016-04-13 18:36:19 +00003494 if (ER.Val.isFloat()) {
3495 llvm::SmallVector<char, 100> Buffer;
3496 ER.Val.getFloat().toString(Buffer);
3497 std::string floatStr(Buffer.data(), Buffer.size());
3498 result->EvalType = CXEval_Float;
3499 bool ignored;
3500 llvm::APFloat apFloat = ER.Val.getFloat();
3501 apFloat.convert(llvm::APFloat::IEEEdouble,
3502 llvm::APFloat::rmNearestTiesToEven, &ignored);
3503 result->EvalData.floatVal = apFloat.convertToDouble();
3504 return result.release();
3505 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003506
David Blaikiebbc00882016-04-13 18:36:19 +00003507 if (expr->getStmtClass() == Stmt::ImplicitCastExprClass) {
3508 const ImplicitCastExpr *I = dyn_cast<ImplicitCastExpr>(expr);
3509 auto *subExpr = I->getSubExprAsWritten();
3510 if (subExpr->getStmtClass() == Stmt::StringLiteralClass ||
3511 subExpr->getStmtClass() == Stmt::ObjCStringLiteralClass) {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003512 const StringLiteral *StrE = nullptr;
3513 const ObjCStringLiteral *ObjCExpr;
David Blaikiebbc00882016-04-13 18:36:19 +00003514 ObjCExpr = dyn_cast<ObjCStringLiteral>(subExpr);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003515
3516 if (ObjCExpr) {
3517 StrE = ObjCExpr->getString();
3518 result->EvalType = CXEval_ObjCStrLiteral;
3519 } else {
David Blaikiebbc00882016-04-13 18:36:19 +00003520 StrE = cast<StringLiteral>(I->getSubExprAsWritten());
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003521 result->EvalType = CXEval_StrLiteral;
3522 }
3523
3524 std::string strRef(StrE->getString().str());
David Blaikie59272572016-04-13 18:23:33 +00003525 result->EvalData.stringVal = new char[strRef.size() + 1];
David Blaikiebbc00882016-04-13 18:36:19 +00003526 strncpy((char *)result->EvalData.stringVal, strRef.c_str(),
3527 strRef.size());
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003528 result->EvalData.stringVal[strRef.size()] = '\0';
David Blaikie59272572016-04-13 18:23:33 +00003529 return result.release();
David Blaikiebbc00882016-04-13 18:36:19 +00003530 }
3531 } else if (expr->getStmtClass() == Stmt::ObjCStringLiteralClass ||
3532 expr->getStmtClass() == Stmt::StringLiteralClass) {
3533 const StringLiteral *StrE = nullptr;
3534 const ObjCStringLiteral *ObjCExpr;
3535 ObjCExpr = dyn_cast<ObjCStringLiteral>(expr);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003536
David Blaikiebbc00882016-04-13 18:36:19 +00003537 if (ObjCExpr) {
3538 StrE = ObjCExpr->getString();
3539 result->EvalType = CXEval_ObjCStrLiteral;
3540 } else {
3541 StrE = cast<StringLiteral>(expr);
3542 result->EvalType = CXEval_StrLiteral;
3543 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003544
David Blaikiebbc00882016-04-13 18:36:19 +00003545 std::string strRef(StrE->getString().str());
3546 result->EvalData.stringVal = new char[strRef.size() + 1];
3547 strncpy((char *)result->EvalData.stringVal, strRef.c_str(), strRef.size());
3548 result->EvalData.stringVal[strRef.size()] = '\0';
3549 return result.release();
3550 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003551
David Blaikiebbc00882016-04-13 18:36:19 +00003552 if (expr->getStmtClass() == Stmt::CStyleCastExprClass) {
3553 CStyleCastExpr *CC = static_cast<CStyleCastExpr *>(expr);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003554
David Blaikiebbc00882016-04-13 18:36:19 +00003555 rettype = CC->getType();
3556 if (rettype.getAsString() == "CFStringRef" &&
3557 CC->getSubExpr()->getStmtClass() == Stmt::CallExprClass) {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003558
David Blaikiebbc00882016-04-13 18:36:19 +00003559 callExpr = static_cast<CallExpr *>(CC->getSubExpr());
3560 StringLiteral *S = getCFSTR_value(callExpr);
3561 if (S) {
3562 std::string strLiteral(S->getString().str());
3563 result->EvalType = CXEval_CFStr;
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003564
David Blaikiebbc00882016-04-13 18:36:19 +00003565 result->EvalData.stringVal = new char[strLiteral.size() + 1];
3566 strncpy((char *)result->EvalData.stringVal, strLiteral.c_str(),
3567 strLiteral.size());
3568 result->EvalData.stringVal[strLiteral.size()] = '\0';
David Blaikie59272572016-04-13 18:23:33 +00003569 return result.release();
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003570 }
3571 }
3572
David Blaikiebbc00882016-04-13 18:36:19 +00003573 } else if (expr->getStmtClass() == Stmt::CallExprClass) {
3574 callExpr = static_cast<CallExpr *>(expr);
3575 rettype = callExpr->getCallReturnType(ctx);
3576
3577 if (rettype->isVectorType() || callExpr->getNumArgs() > 1)
3578 return nullptr;
3579
3580 if (rettype->isIntegralType(ctx) || rettype->isRealFloatingType()) {
3581 if (callExpr->getNumArgs() == 1 &&
3582 !callExpr->getArg(0)->getType()->isIntegralType(ctx))
3583 return nullptr;
3584 } else if (rettype.getAsString() == "CFStringRef") {
3585
3586 StringLiteral *S = getCFSTR_value(callExpr);
3587 if (S) {
3588 std::string strLiteral(S->getString().str());
3589 result->EvalType = CXEval_CFStr;
3590 result->EvalData.stringVal = new char[strLiteral.size() + 1];
3591 strncpy((char *)result->EvalData.stringVal, strLiteral.c_str(),
3592 strLiteral.size());
3593 result->EvalData.stringVal[strLiteral.size()] = '\0';
3594 return result.release();
3595 }
3596 }
3597 } else if (expr->getStmtClass() == Stmt::DeclRefExprClass) {
3598 DeclRefExpr *D = static_cast<DeclRefExpr *>(expr);
3599 ValueDecl *V = D->getDecl();
3600 if (V->getKind() == Decl::Function) {
3601 std::string strName = V->getNameAsString();
3602 result->EvalType = CXEval_Other;
3603 result->EvalData.stringVal = new char[strName.size() + 1];
3604 strncpy(result->EvalData.stringVal, strName.c_str(), strName.size());
3605 result->EvalData.stringVal[strName.size()] = '\0';
3606 return result.release();
3607 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003608 }
3609
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003610 return nullptr;
3611}
3612
3613CXEvalResult clang_Cursor_Evaluate(CXCursor C) {
3614 const Decl *D = getCursorDecl(C);
3615 if (D) {
3616 const Expr *expr = nullptr;
3617 if (auto *Var = dyn_cast<VarDecl>(D)) {
3618 expr = Var->getInit();
3619 } else if (auto *Field = dyn_cast<FieldDecl>(D)) {
3620 expr = Field->getInClassInitializer();
3621 }
3622 if (expr)
Aaron Ballman01dc1572016-01-20 15:25:30 +00003623 return const_cast<CXEvalResult>(reinterpret_cast<const void *>(
3624 evaluateExpr(const_cast<Expr *>(expr), C)));
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003625 return nullptr;
3626 }
3627
3628 const CompoundStmt *compoundStmt = dyn_cast_or_null<CompoundStmt>(getCursorStmt(C));
3629 if (compoundStmt) {
3630 Expr *expr = nullptr;
3631 for (auto *bodyIterator : compoundStmt->body()) {
3632 if ((expr = dyn_cast<Expr>(bodyIterator))) {
3633 break;
3634 }
3635 }
3636 if (expr)
Aaron Ballman01dc1572016-01-20 15:25:30 +00003637 return const_cast<CXEvalResult>(
3638 reinterpret_cast<const void *>(evaluateExpr(expr, C)));
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003639 }
3640 return nullptr;
3641}
3642
3643unsigned clang_Cursor_hasAttrs(CXCursor C) {
3644 const Decl *D = getCursorDecl(C);
3645 if (!D) {
3646 return 0;
3647 }
3648
3649 if (D->hasAttrs()) {
3650 return 1;
3651 }
3652
3653 return 0;
3654}
Guy Benyei11169dd2012-12-18 14:30:41 +00003655unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
3656 return CXSaveTranslationUnit_None;
3657}
3658
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003659static CXSaveError clang_saveTranslationUnit_Impl(CXTranslationUnit TU,
3660 const char *FileName,
3661 unsigned options) {
3662 CIndexer *CXXIdx = TU->CIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00003663 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
3664 setThreadBackgroundPriority();
3665
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003666 bool hadError = cxtu::getASTUnit(TU)->Save(FileName);
3667 return hadError ? CXSaveError_Unknown : CXSaveError_None;
Guy Benyei11169dd2012-12-18 14:30:41 +00003668}
3669
3670int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
3671 unsigned options) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00003672 LOG_FUNC_SECTION {
3673 *Log << TU << ' ' << FileName;
3674 }
3675
Dmitri Gribenko852d6222014-02-11 15:02:48 +00003676 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00003677 LOG_BAD_TU(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00003678 return CXSaveError_InvalidTU;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00003679 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003680
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00003681 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00003682 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3683 if (!CXXUnit->hasSema())
3684 return CXSaveError_InvalidTU;
3685
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003686 CXSaveError result;
3687 auto SaveTranslationUnitImpl = [=, &result]() {
3688 result = clang_saveTranslationUnit_Impl(TU, FileName, options);
3689 };
Guy Benyei11169dd2012-12-18 14:30:41 +00003690
3691 if (!CXXUnit->getDiagnostics().hasUnrecoverableErrorOccurred() ||
3692 getenv("LIBCLANG_NOTHREADS")) {
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003693 SaveTranslationUnitImpl();
Guy Benyei11169dd2012-12-18 14:30:41 +00003694
3695 if (getenv("LIBCLANG_RESOURCE_USAGE"))
3696 PrintLibclangResourceUsage(TU);
3697
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003698 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003699 }
3700
3701 // We have an AST that has invalid nodes due to compiler errors.
3702 // Use a crash recovery thread for protection.
3703
3704 llvm::CrashRecoveryContext CRC;
3705
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003706 if (!RunSafely(CRC, SaveTranslationUnitImpl)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003707 fprintf(stderr, "libclang: crash detected during AST saving: {\n");
3708 fprintf(stderr, " 'filename' : '%s'\n", FileName);
3709 fprintf(stderr, " 'options' : %d,\n", options);
3710 fprintf(stderr, "}\n");
3711
3712 return CXSaveError_Unknown;
3713
3714 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
3715 PrintLibclangResourceUsage(TU);
3716 }
3717
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003718 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003719}
3720
3721void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
3722 if (CTUnit) {
3723 // If the translation unit has been marked as unsafe to free, just discard
3724 // it.
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003725 ASTUnit *Unit = cxtu::getASTUnit(CTUnit);
3726 if (Unit && Unit->isUnsafeToFree())
Guy Benyei11169dd2012-12-18 14:30:41 +00003727 return;
3728
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00003729 delete cxtu::getASTUnit(CTUnit);
Dmitri Gribenkob95b3f12013-01-26 22:44:19 +00003730 delete CTUnit->StringPool;
Guy Benyei11169dd2012-12-18 14:30:41 +00003731 delete static_cast<CXDiagnosticSetImpl *>(CTUnit->Diagnostics);
3732 disposeOverridenCXCursorsPool(CTUnit->OverridenCursorsPool);
Dmitri Gribenko9e605112013-11-13 22:16:51 +00003733 delete CTUnit->CommentToXML;
Guy Benyei11169dd2012-12-18 14:30:41 +00003734 delete CTUnit;
3735 }
3736}
3737
3738unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
3739 return CXReparse_None;
3740}
3741
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003742static CXErrorCode
3743clang_reparseTranslationUnit_Impl(CXTranslationUnit TU,
3744 ArrayRef<CXUnsavedFile> unsaved_files,
3745 unsigned options) {
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003746 // Check arguments.
Dmitri Gribenko852d6222014-02-11 15:02:48 +00003747 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00003748 LOG_BAD_TU(TU);
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003749 return CXError_InvalidArguments;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003750 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003751
3752 // Reset the associated diagnostics.
3753 delete static_cast<CXDiagnosticSetImpl*>(TU->Diagnostics);
Craig Topper69186e72014-06-08 08:38:04 +00003754 TU->Diagnostics = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00003755
Dmitri Gribenko183436e2013-01-26 21:49:50 +00003756 CIndexer *CXXIdx = TU->CIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00003757 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing))
3758 setThreadBackgroundPriority();
3759
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00003760 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00003761 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ahmed Charlesb8984322014-03-07 20:03:18 +00003762
3763 std::unique_ptr<std::vector<ASTUnit::RemappedFile>> RemappedFiles(
3764 new std::vector<ASTUnit::RemappedFile>());
3765
Guy Benyei11169dd2012-12-18 14:30:41 +00003766 // Recover resources if we crash before exiting this function.
3767 llvm::CrashRecoveryContextCleanupRegistrar<
3768 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
Alp Toker9d85b182014-07-07 01:23:14 +00003769
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003770 for (auto &UF : unsaved_files) {
Rafael Espindolad87f8d72014-08-27 20:03:29 +00003771 std::unique_ptr<llvm::MemoryBuffer> MB =
Alp Toker9d85b182014-07-07 01:23:14 +00003772 llvm::MemoryBuffer::getMemBufferCopy(getContents(UF), UF.Filename);
Rafael Espindolad87f8d72014-08-27 20:03:29 +00003773 RemappedFiles->push_back(std::make_pair(UF.Filename, MB.release()));
Guy Benyei11169dd2012-12-18 14:30:41 +00003774 }
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003775
Adrian Prantlbb165fb2015-06-20 18:53:08 +00003776 if (!CXXUnit->Reparse(CXXIdx->getPCHContainerOperations(),
3777 *RemappedFiles.get()))
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003778 return CXError_Success;
3779 if (isASTReadError(CXXUnit))
3780 return CXError_ASTReadError;
3781 return CXError_Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003782}
3783
3784int clang_reparseTranslationUnit(CXTranslationUnit TU,
3785 unsigned num_unsaved_files,
3786 struct CXUnsavedFile *unsaved_files,
3787 unsigned options) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00003788 LOG_FUNC_SECTION {
3789 *Log << TU;
3790 }
3791
Alp Toker9d85b182014-07-07 01:23:14 +00003792 if (num_unsaved_files && !unsaved_files)
3793 return CXError_InvalidArguments;
3794
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003795 CXErrorCode result;
3796 auto ReparseTranslationUnitImpl = [=, &result]() {
3797 result = clang_reparseTranslationUnit_Impl(
3798 TU, llvm::makeArrayRef(unsaved_files, num_unsaved_files), options);
3799 };
Guy Benyei11169dd2012-12-18 14:30:41 +00003800
3801 if (getenv("LIBCLANG_NOTHREADS")) {
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003802 ReparseTranslationUnitImpl();
Alp Toker5c532982014-07-07 22:42:03 +00003803 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003804 }
3805
3806 llvm::CrashRecoveryContext CRC;
3807
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003808 if (!RunSafely(CRC, ReparseTranslationUnitImpl)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003809 fprintf(stderr, "libclang: crash detected during reparsing\n");
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00003810 cxtu::getASTUnit(TU)->setUnsafeToFree(true);
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003811 return CXError_Crashed;
Guy Benyei11169dd2012-12-18 14:30:41 +00003812 } else if (getenv("LIBCLANG_RESOURCE_USAGE"))
3813 PrintLibclangResourceUsage(TU);
3814
Alp Toker5c532982014-07-07 22:42:03 +00003815 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003816}
3817
3818
3819CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00003820 if (isNotUsableTU(CTUnit)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00003821 LOG_BAD_TU(CTUnit);
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00003822 return cxstring::createEmpty();
Dmitri Gribenko256454f2014-02-11 14:34:14 +00003823 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003824
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00003825 ASTUnit *CXXUnit = cxtu::getASTUnit(CTUnit);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00003826 return cxstring::createDup(CXXUnit->getOriginalSourceFileName());
Guy Benyei11169dd2012-12-18 14:30:41 +00003827}
3828
3829CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00003830 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00003831 LOG_BAD_TU(TU);
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00003832 return clang_getNullCursor();
Dmitri Gribenko256454f2014-02-11 14:34:14 +00003833 }
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00003834
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00003835 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00003836 return MakeCXCursor(CXXUnit->getASTContext().getTranslationUnitDecl(), TU);
3837}
3838
3839} // end: extern "C"
3840
3841//===----------------------------------------------------------------------===//
3842// CXFile Operations.
3843//===----------------------------------------------------------------------===//
3844
3845extern "C" {
3846CXString clang_getFileName(CXFile SFile) {
3847 if (!SFile)
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00003848 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00003849
3850 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00003851 return cxstring::createRef(FEnt->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00003852}
3853
3854time_t clang_getFileTime(CXFile SFile) {
3855 if (!SFile)
3856 return 0;
3857
3858 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
3859 return FEnt->getModificationTime();
3860}
3861
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00003862CXFile clang_getFile(CXTranslationUnit TU, const char *file_name) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00003863 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00003864 LOG_BAD_TU(TU);
Craig Topper69186e72014-06-08 08:38:04 +00003865 return nullptr;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00003866 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003867
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00003868 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00003869
3870 FileManager &FMgr = CXXUnit->getFileManager();
3871 return const_cast<FileEntry *>(FMgr.getFile(file_name));
3872}
3873
Dmitri Gribenko256454f2014-02-11 14:34:14 +00003874unsigned clang_isFileMultipleIncludeGuarded(CXTranslationUnit TU,
3875 CXFile file) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00003876 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00003877 LOG_BAD_TU(TU);
3878 return 0;
3879 }
3880
3881 if (!file)
Guy Benyei11169dd2012-12-18 14:30:41 +00003882 return 0;
3883
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00003884 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00003885 FileEntry *FEnt = static_cast<FileEntry *>(file);
3886 return CXXUnit->getPreprocessor().getHeaderSearchInfo()
3887 .isFileMultipleIncludeGuarded(FEnt);
3888}
3889
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00003890int clang_getFileUniqueID(CXFile file, CXFileUniqueID *outID) {
3891 if (!file || !outID)
3892 return 1;
3893
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00003894 FileEntry *FEnt = static_cast<FileEntry *>(file);
Rafael Espindolaf8f91b82013-08-01 21:42:11 +00003895 const llvm::sys::fs::UniqueID &ID = FEnt->getUniqueID();
3896 outID->data[0] = ID.getDevice();
3897 outID->data[1] = ID.getFile();
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00003898 outID->data[2] = FEnt->getModificationTime();
3899 return 0;
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00003900}
3901
Argyrios Kyrtzidisac3997e2014-08-16 00:26:19 +00003902int clang_File_isEqual(CXFile file1, CXFile file2) {
3903 if (file1 == file2)
3904 return true;
3905
3906 if (!file1 || !file2)
3907 return false;
3908
3909 FileEntry *FEnt1 = static_cast<FileEntry *>(file1);
3910 FileEntry *FEnt2 = static_cast<FileEntry *>(file2);
3911 return FEnt1->getUniqueID() == FEnt2->getUniqueID();
3912}
3913
Guy Benyei11169dd2012-12-18 14:30:41 +00003914} // end: extern "C"
3915
3916//===----------------------------------------------------------------------===//
3917// CXCursor Operations.
3918//===----------------------------------------------------------------------===//
3919
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00003920static const Decl *getDeclFromExpr(const Stmt *E) {
3921 if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00003922 return getDeclFromExpr(CE->getSubExpr());
3923
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00003924 if (const DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00003925 return RefExpr->getDecl();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00003926 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00003927 return ME->getMemberDecl();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00003928 if (const ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00003929 return RE->getDecl();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00003930 if (const ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003931 if (PRE->isExplicitProperty())
3932 return PRE->getExplicitProperty();
3933 // It could be messaging both getter and setter as in:
3934 // ++myobj.myprop;
3935 // in which case prefer to associate the setter since it is less obvious
3936 // from inspecting the source that the setter is going to get called.
3937 if (PRE->isMessagingSetter())
3938 return PRE->getImplicitPropertySetter();
3939 return PRE->getImplicitPropertyGetter();
3940 }
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00003941 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00003942 return getDeclFromExpr(POE->getSyntacticForm());
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00003943 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00003944 if (Expr *Src = OVE->getSourceExpr())
3945 return getDeclFromExpr(Src);
3946
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00003947 if (const CallExpr *CE = dyn_cast<CallExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00003948 return getDeclFromExpr(CE->getCallee());
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00003949 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00003950 if (!CE->isElidable())
3951 return CE->getConstructor();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00003952 if (const ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00003953 return OME->getMethodDecl();
3954
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00003955 if (const ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00003956 return PE->getProtocol();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00003957 if (const SubstNonTypeTemplateParmPackExpr *NTTP
Guy Benyei11169dd2012-12-18 14:30:41 +00003958 = dyn_cast<SubstNonTypeTemplateParmPackExpr>(E))
3959 return NTTP->getParameterPack();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00003960 if (const SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00003961 if (isa<NonTypeTemplateParmDecl>(SizeOfPack->getPack()) ||
3962 isa<ParmVarDecl>(SizeOfPack->getPack()))
3963 return SizeOfPack->getPack();
Craig Topper69186e72014-06-08 08:38:04 +00003964
3965 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00003966}
3967
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003968static SourceLocation getLocationFromExpr(const Expr *E) {
3969 if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00003970 return getLocationFromExpr(CE->getSubExpr());
3971
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003972 if (const ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00003973 return /*FIXME:*/Msg->getLeftLoc();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003974 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00003975 return DRE->getLocation();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003976 if (const MemberExpr *Member = dyn_cast<MemberExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00003977 return Member->getMemberLoc();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003978 if (const ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00003979 return Ivar->getLocation();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003980 if (const SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00003981 return SizeOfPack->getPackLoc();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003982 if (const ObjCPropertyRefExpr *PropRef = dyn_cast<ObjCPropertyRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00003983 return PropRef->getLocation();
3984
3985 return E->getLocStart();
3986}
3987
3988extern "C" {
3989
3990unsigned clang_visitChildren(CXCursor parent,
3991 CXCursorVisitor visitor,
3992 CXClientData client_data) {
3993 CursorVisitor CursorVis(getCursorTU(parent), visitor, client_data,
3994 /*VisitPreprocessorLast=*/false);
3995 return CursorVis.VisitChildren(parent);
3996}
3997
3998#ifndef __has_feature
3999#define __has_feature(x) 0
4000#endif
4001#if __has_feature(blocks)
4002typedef enum CXChildVisitResult
4003 (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
4004
4005static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
4006 CXClientData client_data) {
4007 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
4008 return block(cursor, parent);
4009}
4010#else
4011// If we are compiled with a compiler that doesn't have native blocks support,
4012// define and call the block manually, so the
4013typedef struct _CXChildVisitResult
4014{
4015 void *isa;
4016 int flags;
4017 int reserved;
4018 enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor,
4019 CXCursor);
4020} *CXCursorVisitorBlock;
4021
4022static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
4023 CXClientData client_data) {
4024 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
4025 return block->invoke(block, cursor, parent);
4026}
4027#endif
4028
4029
4030unsigned clang_visitChildrenWithBlock(CXCursor parent,
4031 CXCursorVisitorBlock block) {
4032 return clang_visitChildren(parent, visitWithBlock, block);
4033}
4034
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004035static CXString getDeclSpelling(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004036 if (!D)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004037 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004038
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004039 const NamedDecl *ND = dyn_cast<NamedDecl>(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00004040 if (!ND) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004041 if (const ObjCPropertyImplDecl *PropImpl =
4042 dyn_cast<ObjCPropertyImplDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00004043 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004044 return cxstring::createDup(Property->getIdentifier()->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004045
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004046 if (const ImportDecl *ImportD = dyn_cast<ImportDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00004047 if (Module *Mod = ImportD->getImportedModule())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004048 return cxstring::createDup(Mod->getFullModuleName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004049
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004050 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004051 }
4052
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004053 if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004054 return cxstring::createDup(OMD->getSelector().getAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004055
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004056 if (const ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
Guy Benyei11169dd2012-12-18 14:30:41 +00004057 // No, this isn't the same as the code below. getIdentifier() is non-virtual
4058 // and returns different names. NamedDecl returns the class name and
4059 // ObjCCategoryImplDecl returns the category name.
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004060 return cxstring::createRef(CIMP->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004061
4062 if (isa<UsingDirectiveDecl>(D))
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004063 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004064
4065 SmallString<1024> S;
4066 llvm::raw_svector_ostream os(S);
4067 ND->printName(os);
4068
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004069 return cxstring::createDup(os.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00004070}
4071
4072CXString clang_getCursorSpelling(CXCursor C) {
4073 if (clang_isTranslationUnit(C.kind))
Dmitri Gribenko2c173b42013-01-11 19:28:44 +00004074 return clang_getTranslationUnitSpelling(getCursorTU(C));
Guy Benyei11169dd2012-12-18 14:30:41 +00004075
4076 if (clang_isReference(C.kind)) {
4077 switch (C.kind) {
4078 case CXCursor_ObjCSuperClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004079 const ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004080 return cxstring::createRef(Super->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004081 }
4082 case CXCursor_ObjCClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004083 const ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004084 return cxstring::createRef(Class->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004085 }
4086 case CXCursor_ObjCProtocolRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004087 const ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004088 assert(OID && "getCursorSpelling(): Missing protocol decl");
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004089 return cxstring::createRef(OID->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004090 }
4091 case CXCursor_CXXBaseSpecifier: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004092 const CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004093 return cxstring::createDup(B->getType().getAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004094 }
4095 case CXCursor_TypeRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004096 const TypeDecl *Type = getCursorTypeRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004097 assert(Type && "Missing type decl");
4098
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004099 return cxstring::createDup(getCursorContext(C).getTypeDeclType(Type).
Guy Benyei11169dd2012-12-18 14:30:41 +00004100 getAsString());
4101 }
4102 case CXCursor_TemplateRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004103 const TemplateDecl *Template = getCursorTemplateRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004104 assert(Template && "Missing template decl");
4105
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004106 return cxstring::createDup(Template->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004107 }
4108
4109 case CXCursor_NamespaceRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004110 const NamedDecl *NS = getCursorNamespaceRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004111 assert(NS && "Missing namespace decl");
4112
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004113 return cxstring::createDup(NS->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004114 }
4115
4116 case CXCursor_MemberRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004117 const FieldDecl *Field = getCursorMemberRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004118 assert(Field && "Missing member decl");
4119
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004120 return cxstring::createDup(Field->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004121 }
4122
4123 case CXCursor_LabelRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004124 const LabelStmt *Label = getCursorLabelRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004125 assert(Label && "Missing label");
4126
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004127 return cxstring::createRef(Label->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004128 }
4129
4130 case CXCursor_OverloadedDeclRef: {
4131 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004132 if (const Decl *D = Storage.dyn_cast<const Decl *>()) {
4133 if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004134 return cxstring::createDup(ND->getNameAsString());
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004135 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004136 }
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004137 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004138 return cxstring::createDup(E->getName().getAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004139 OverloadedTemplateStorage *Ovl
4140 = Storage.get<OverloadedTemplateStorage*>();
4141 if (Ovl->size() == 0)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004142 return cxstring::createEmpty();
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004143 return cxstring::createDup((*Ovl->begin())->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004144 }
4145
4146 case CXCursor_VariableRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004147 const VarDecl *Var = getCursorVariableRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004148 assert(Var && "Missing variable decl");
4149
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004150 return cxstring::createDup(Var->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004151 }
4152
4153 default:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004154 return cxstring::createRef("<not implemented>");
Guy Benyei11169dd2012-12-18 14:30:41 +00004155 }
4156 }
4157
4158 if (clang_isExpression(C.kind)) {
Argyrios Kyrtzidis3227d862014-03-03 19:40:52 +00004159 const Expr *E = getCursorExpr(C);
4160
4161 if (C.kind == CXCursor_ObjCStringLiteral ||
4162 C.kind == CXCursor_StringLiteral) {
4163 const StringLiteral *SLit;
4164 if (const ObjCStringLiteral *OSL = dyn_cast<ObjCStringLiteral>(E)) {
4165 SLit = OSL->getString();
4166 } else {
4167 SLit = cast<StringLiteral>(E);
4168 }
4169 SmallString<256> Buf;
4170 llvm::raw_svector_ostream OS(Buf);
4171 SLit->outputString(OS);
4172 return cxstring::createDup(OS.str());
4173 }
4174
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004175 const Decl *D = getDeclFromExpr(getCursorExpr(C));
Guy Benyei11169dd2012-12-18 14:30:41 +00004176 if (D)
4177 return getDeclSpelling(D);
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004178 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004179 }
4180
4181 if (clang_isStatement(C.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004182 const Stmt *S = getCursorStmt(C);
4183 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004184 return cxstring::createRef(Label->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004185
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004186 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004187 }
4188
4189 if (C.kind == CXCursor_MacroExpansion)
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004190 return cxstring::createRef(getCursorMacroExpansion(C).getName()
Guy Benyei11169dd2012-12-18 14:30:41 +00004191 ->getNameStart());
4192
4193 if (C.kind == CXCursor_MacroDefinition)
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004194 return cxstring::createRef(getCursorMacroDefinition(C)->getName()
Guy Benyei11169dd2012-12-18 14:30:41 +00004195 ->getNameStart());
4196
4197 if (C.kind == CXCursor_InclusionDirective)
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004198 return cxstring::createDup(getCursorInclusionDirective(C)->getFileName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004199
4200 if (clang_isDeclaration(C.kind))
4201 return getDeclSpelling(getCursorDecl(C));
4202
4203 if (C.kind == CXCursor_AnnotateAttr) {
Dmitri Gribenkoe4baea62013-01-26 18:08:08 +00004204 const AnnotateAttr *AA = cast<AnnotateAttr>(cxcursor::getCursorAttr(C));
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004205 return cxstring::createDup(AA->getAnnotation());
Guy Benyei11169dd2012-12-18 14:30:41 +00004206 }
4207
4208 if (C.kind == CXCursor_AsmLabelAttr) {
Dmitri Gribenkoe4baea62013-01-26 18:08:08 +00004209 const AsmLabelAttr *AA = cast<AsmLabelAttr>(cxcursor::getCursorAttr(C));
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004210 return cxstring::createDup(AA->getLabel());
Guy Benyei11169dd2012-12-18 14:30:41 +00004211 }
4212
Argyrios Kyrtzidis16834f12013-09-25 00:14:38 +00004213 if (C.kind == CXCursor_PackedAttr) {
4214 return cxstring::createRef("packed");
4215 }
4216
Saleem Abdulrasool79c69712015-09-05 18:53:43 +00004217 if (C.kind == CXCursor_VisibilityAttr) {
4218 const VisibilityAttr *AA = cast<VisibilityAttr>(cxcursor::getCursorAttr(C));
4219 switch (AA->getVisibility()) {
4220 case VisibilityAttr::VisibilityType::Default:
4221 return cxstring::createRef("default");
4222 case VisibilityAttr::VisibilityType::Hidden:
4223 return cxstring::createRef("hidden");
4224 case VisibilityAttr::VisibilityType::Protected:
4225 return cxstring::createRef("protected");
4226 }
4227 llvm_unreachable("unknown visibility type");
4228 }
4229
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004230 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004231}
4232
4233CXSourceRange clang_Cursor_getSpellingNameRange(CXCursor C,
4234 unsigned pieceIndex,
4235 unsigned options) {
4236 if (clang_Cursor_isNull(C))
4237 return clang_getNullRange();
4238
4239 ASTContext &Ctx = getCursorContext(C);
4240
4241 if (clang_isStatement(C.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004242 const Stmt *S = getCursorStmt(C);
4243 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004244 if (pieceIndex > 0)
4245 return clang_getNullRange();
4246 return cxloc::translateSourceRange(Ctx, Label->getIdentLoc());
4247 }
4248
4249 return clang_getNullRange();
4250 }
4251
4252 if (C.kind == CXCursor_ObjCMessageExpr) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004253 if (const ObjCMessageExpr *
Guy Benyei11169dd2012-12-18 14:30:41 +00004254 ME = dyn_cast_or_null<ObjCMessageExpr>(getCursorExpr(C))) {
4255 if (pieceIndex >= ME->getNumSelectorLocs())
4256 return clang_getNullRange();
4257 return cxloc::translateSourceRange(Ctx, ME->getSelectorLoc(pieceIndex));
4258 }
4259 }
4260
4261 if (C.kind == CXCursor_ObjCInstanceMethodDecl ||
4262 C.kind == CXCursor_ObjCClassMethodDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004263 if (const ObjCMethodDecl *
Guy Benyei11169dd2012-12-18 14:30:41 +00004264 MD = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(C))) {
4265 if (pieceIndex >= MD->getNumSelectorLocs())
4266 return clang_getNullRange();
4267 return cxloc::translateSourceRange(Ctx, MD->getSelectorLoc(pieceIndex));
4268 }
4269 }
4270
4271 if (C.kind == CXCursor_ObjCCategoryDecl ||
4272 C.kind == CXCursor_ObjCCategoryImplDecl) {
4273 if (pieceIndex > 0)
4274 return clang_getNullRange();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004275 if (const ObjCCategoryDecl *
Guy Benyei11169dd2012-12-18 14:30:41 +00004276 CD = dyn_cast_or_null<ObjCCategoryDecl>(getCursorDecl(C)))
4277 return cxloc::translateSourceRange(Ctx, CD->getCategoryNameLoc());
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004278 if (const ObjCCategoryImplDecl *
Guy Benyei11169dd2012-12-18 14:30:41 +00004279 CID = dyn_cast_or_null<ObjCCategoryImplDecl>(getCursorDecl(C)))
4280 return cxloc::translateSourceRange(Ctx, CID->getCategoryNameLoc());
4281 }
4282
4283 if (C.kind == CXCursor_ModuleImportDecl) {
4284 if (pieceIndex > 0)
4285 return clang_getNullRange();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004286 if (const ImportDecl *ImportD =
4287 dyn_cast_or_null<ImportDecl>(getCursorDecl(C))) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004288 ArrayRef<SourceLocation> Locs = ImportD->getIdentifierLocs();
4289 if (!Locs.empty())
4290 return cxloc::translateSourceRange(Ctx,
4291 SourceRange(Locs.front(), Locs.back()));
4292 }
4293 return clang_getNullRange();
4294 }
4295
Argyrios Kyrtzidisa2a1e532014-08-26 20:23:26 +00004296 if (C.kind == CXCursor_CXXMethod || C.kind == CXCursor_Destructor ||
4297 C.kind == CXCursor_ConversionFunction) {
4298 if (pieceIndex > 0)
4299 return clang_getNullRange();
4300 if (const FunctionDecl *FD =
4301 dyn_cast_or_null<FunctionDecl>(getCursorDecl(C))) {
4302 DeclarationNameInfo FunctionName = FD->getNameInfo();
4303 return cxloc::translateSourceRange(Ctx, FunctionName.getSourceRange());
4304 }
4305 return clang_getNullRange();
4306 }
4307
Guy Benyei11169dd2012-12-18 14:30:41 +00004308 // FIXME: A CXCursor_InclusionDirective should give the location of the
4309 // filename, but we don't keep track of this.
4310
4311 // FIXME: A CXCursor_AnnotateAttr should give the location of the annotation
4312 // but we don't keep track of this.
4313
4314 // FIXME: A CXCursor_AsmLabelAttr should give the location of the label
4315 // but we don't keep track of this.
4316
4317 // Default handling, give the location of the cursor.
4318
4319 if (pieceIndex > 0)
4320 return clang_getNullRange();
4321
4322 CXSourceLocation CXLoc = clang_getCursorLocation(C);
4323 SourceLocation Loc = cxloc::translateSourceLocation(CXLoc);
4324 return cxloc::translateSourceRange(Ctx, Loc);
4325}
4326
Eli Bendersky44a206f2014-07-31 18:04:56 +00004327CXString clang_Cursor_getMangling(CXCursor C) {
4328 if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
4329 return cxstring::createEmpty();
4330
Eli Bendersky44a206f2014-07-31 18:04:56 +00004331 // Mangling only works for functions and variables.
Eli Bendersky79759592014-08-01 15:01:10 +00004332 const Decl *D = getCursorDecl(C);
Eli Bendersky44a206f2014-07-31 18:04:56 +00004333 if (!D || !(isa<FunctionDecl>(D) || isa<VarDecl>(D)))
4334 return cxstring::createEmpty();
4335
Argyrios Kyrtzidisca741ce2016-02-14 22:30:14 +00004336 ASTContext &Ctx = D->getASTContext();
4337 index::CodegenNameGenerator CGNameGen(Ctx);
4338 return cxstring::createDup(CGNameGen.getName(D));
Eli Bendersky44a206f2014-07-31 18:04:56 +00004339}
4340
Saleem Abdulrasool60034432015-11-12 03:57:22 +00004341CXStringSet *clang_Cursor_getCXXManglings(CXCursor C) {
4342 if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
4343 return nullptr;
4344
4345 const Decl *D = getCursorDecl(C);
4346 if (!(isa<CXXRecordDecl>(D) || isa<CXXMethodDecl>(D)))
4347 return nullptr;
4348
Argyrios Kyrtzidisca741ce2016-02-14 22:30:14 +00004349 ASTContext &Ctx = D->getASTContext();
4350 index::CodegenNameGenerator CGNameGen(Ctx);
4351 std::vector<std::string> Manglings = CGNameGen.getAllManglings(D);
Saleem Abdulrasool60034432015-11-12 03:57:22 +00004352 return cxstring::createSet(Manglings);
4353}
4354
Guy Benyei11169dd2012-12-18 14:30:41 +00004355CXString clang_getCursorDisplayName(CXCursor C) {
4356 if (!clang_isDeclaration(C.kind))
4357 return clang_getCursorSpelling(C);
4358
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004359 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00004360 if (!D)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004361 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004362
4363 PrintingPolicy Policy = getCursorContext(C).getPrintingPolicy();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004364 if (const FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00004365 D = FunTmpl->getTemplatedDecl();
4366
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004367 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004368 SmallString<64> Str;
4369 llvm::raw_svector_ostream OS(Str);
4370 OS << *Function;
4371 if (Function->getPrimaryTemplate())
4372 OS << "<>";
4373 OS << "(";
4374 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
4375 if (I)
4376 OS << ", ";
4377 OS << Function->getParamDecl(I)->getType().getAsString(Policy);
4378 }
4379
4380 if (Function->isVariadic()) {
4381 if (Function->getNumParams())
4382 OS << ", ";
4383 OS << "...";
4384 }
4385 OS << ")";
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004386 return cxstring::createDup(OS.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00004387 }
4388
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004389 if (const ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004390 SmallString<64> Str;
4391 llvm::raw_svector_ostream OS(Str);
4392 OS << *ClassTemplate;
4393 OS << "<";
4394 TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
4395 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
4396 if (I)
4397 OS << ", ";
4398
4399 NamedDecl *Param = Params->getParam(I);
4400 if (Param->getIdentifier()) {
4401 OS << Param->getIdentifier()->getName();
4402 continue;
4403 }
4404
4405 // There is no parameter name, which makes this tricky. Try to come up
4406 // with something useful that isn't too long.
4407 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
4408 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
4409 else if (NonTypeTemplateParmDecl *NTTP
4410 = dyn_cast<NonTypeTemplateParmDecl>(Param))
4411 OS << NTTP->getType().getAsString(Policy);
4412 else
4413 OS << "template<...> class";
4414 }
4415
4416 OS << ">";
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004417 return cxstring::createDup(OS.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00004418 }
4419
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004420 if (const ClassTemplateSpecializationDecl *ClassSpec
Guy Benyei11169dd2012-12-18 14:30:41 +00004421 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
4422 // If the type was explicitly written, use that.
4423 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004424 return cxstring::createDup(TSInfo->getType().getAsString(Policy));
Guy Benyei11169dd2012-12-18 14:30:41 +00004425
Benjamin Kramer9170e912013-02-22 15:46:01 +00004426 SmallString<128> Str;
Guy Benyei11169dd2012-12-18 14:30:41 +00004427 llvm::raw_svector_ostream OS(Str);
4428 OS << *ClassSpec;
Benjamin Kramer9170e912013-02-22 15:46:01 +00004429 TemplateSpecializationType::PrintTemplateArgumentList(OS,
Guy Benyei11169dd2012-12-18 14:30:41 +00004430 ClassSpec->getTemplateArgs().data(),
4431 ClassSpec->getTemplateArgs().size(),
4432 Policy);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004433 return cxstring::createDup(OS.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00004434 }
4435
4436 return clang_getCursorSpelling(C);
4437}
4438
4439CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
4440 switch (Kind) {
4441 case CXCursor_FunctionDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004442 return cxstring::createRef("FunctionDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004443 case CXCursor_TypedefDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004444 return cxstring::createRef("TypedefDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004445 case CXCursor_EnumDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004446 return cxstring::createRef("EnumDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004447 case CXCursor_EnumConstantDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004448 return cxstring::createRef("EnumConstantDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004449 case CXCursor_StructDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004450 return cxstring::createRef("StructDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004451 case CXCursor_UnionDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004452 return cxstring::createRef("UnionDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004453 case CXCursor_ClassDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004454 return cxstring::createRef("ClassDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004455 case CXCursor_FieldDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004456 return cxstring::createRef("FieldDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004457 case CXCursor_VarDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004458 return cxstring::createRef("VarDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004459 case CXCursor_ParmDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004460 return cxstring::createRef("ParmDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004461 case CXCursor_ObjCInterfaceDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004462 return cxstring::createRef("ObjCInterfaceDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004463 case CXCursor_ObjCCategoryDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004464 return cxstring::createRef("ObjCCategoryDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004465 case CXCursor_ObjCProtocolDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004466 return cxstring::createRef("ObjCProtocolDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004467 case CXCursor_ObjCPropertyDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004468 return cxstring::createRef("ObjCPropertyDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004469 case CXCursor_ObjCIvarDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004470 return cxstring::createRef("ObjCIvarDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004471 case CXCursor_ObjCInstanceMethodDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004472 return cxstring::createRef("ObjCInstanceMethodDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004473 case CXCursor_ObjCClassMethodDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004474 return cxstring::createRef("ObjCClassMethodDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004475 case CXCursor_ObjCImplementationDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004476 return cxstring::createRef("ObjCImplementationDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004477 case CXCursor_ObjCCategoryImplDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004478 return cxstring::createRef("ObjCCategoryImplDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004479 case CXCursor_CXXMethod:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004480 return cxstring::createRef("CXXMethod");
Guy Benyei11169dd2012-12-18 14:30:41 +00004481 case CXCursor_UnexposedDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004482 return cxstring::createRef("UnexposedDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004483 case CXCursor_ObjCSuperClassRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004484 return cxstring::createRef("ObjCSuperClassRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00004485 case CXCursor_ObjCProtocolRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004486 return cxstring::createRef("ObjCProtocolRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00004487 case CXCursor_ObjCClassRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004488 return cxstring::createRef("ObjCClassRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00004489 case CXCursor_TypeRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004490 return cxstring::createRef("TypeRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00004491 case CXCursor_TemplateRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004492 return cxstring::createRef("TemplateRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00004493 case CXCursor_NamespaceRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004494 return cxstring::createRef("NamespaceRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00004495 case CXCursor_MemberRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004496 return cxstring::createRef("MemberRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00004497 case CXCursor_LabelRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004498 return cxstring::createRef("LabelRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00004499 case CXCursor_OverloadedDeclRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004500 return cxstring::createRef("OverloadedDeclRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00004501 case CXCursor_VariableRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004502 return cxstring::createRef("VariableRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00004503 case CXCursor_IntegerLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004504 return cxstring::createRef("IntegerLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00004505 case CXCursor_FloatingLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004506 return cxstring::createRef("FloatingLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00004507 case CXCursor_ImaginaryLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004508 return cxstring::createRef("ImaginaryLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00004509 case CXCursor_StringLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004510 return cxstring::createRef("StringLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00004511 case CXCursor_CharacterLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004512 return cxstring::createRef("CharacterLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00004513 case CXCursor_ParenExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004514 return cxstring::createRef("ParenExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004515 case CXCursor_UnaryOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004516 return cxstring::createRef("UnaryOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00004517 case CXCursor_ArraySubscriptExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004518 return cxstring::createRef("ArraySubscriptExpr");
Alexey Bataev1a3320e2015-08-25 14:24:04 +00004519 case CXCursor_OMPArraySectionExpr:
4520 return cxstring::createRef("OMPArraySectionExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004521 case CXCursor_BinaryOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004522 return cxstring::createRef("BinaryOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00004523 case CXCursor_CompoundAssignOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004524 return cxstring::createRef("CompoundAssignOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00004525 case CXCursor_ConditionalOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004526 return cxstring::createRef("ConditionalOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00004527 case CXCursor_CStyleCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004528 return cxstring::createRef("CStyleCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004529 case CXCursor_CompoundLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004530 return cxstring::createRef("CompoundLiteralExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004531 case CXCursor_InitListExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004532 return cxstring::createRef("InitListExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004533 case CXCursor_AddrLabelExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004534 return cxstring::createRef("AddrLabelExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004535 case CXCursor_StmtExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004536 return cxstring::createRef("StmtExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004537 case CXCursor_GenericSelectionExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004538 return cxstring::createRef("GenericSelectionExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004539 case CXCursor_GNUNullExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004540 return cxstring::createRef("GNUNullExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004541 case CXCursor_CXXStaticCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004542 return cxstring::createRef("CXXStaticCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004543 case CXCursor_CXXDynamicCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004544 return cxstring::createRef("CXXDynamicCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004545 case CXCursor_CXXReinterpretCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004546 return cxstring::createRef("CXXReinterpretCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004547 case CXCursor_CXXConstCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004548 return cxstring::createRef("CXXConstCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004549 case CXCursor_CXXFunctionalCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004550 return cxstring::createRef("CXXFunctionalCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004551 case CXCursor_CXXTypeidExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004552 return cxstring::createRef("CXXTypeidExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004553 case CXCursor_CXXBoolLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004554 return cxstring::createRef("CXXBoolLiteralExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004555 case CXCursor_CXXNullPtrLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004556 return cxstring::createRef("CXXNullPtrLiteralExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004557 case CXCursor_CXXThisExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004558 return cxstring::createRef("CXXThisExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004559 case CXCursor_CXXThrowExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004560 return cxstring::createRef("CXXThrowExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004561 case CXCursor_CXXNewExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004562 return cxstring::createRef("CXXNewExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004563 case CXCursor_CXXDeleteExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004564 return cxstring::createRef("CXXDeleteExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004565 case CXCursor_UnaryExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004566 return cxstring::createRef("UnaryExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004567 case CXCursor_ObjCStringLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004568 return cxstring::createRef("ObjCStringLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00004569 case CXCursor_ObjCBoolLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004570 return cxstring::createRef("ObjCBoolLiteralExpr");
Argyrios Kyrtzidisc2233be2013-04-23 17:57:17 +00004571 case CXCursor_ObjCSelfExpr:
4572 return cxstring::createRef("ObjCSelfExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004573 case CXCursor_ObjCEncodeExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004574 return cxstring::createRef("ObjCEncodeExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004575 case CXCursor_ObjCSelectorExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004576 return cxstring::createRef("ObjCSelectorExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004577 case CXCursor_ObjCProtocolExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004578 return cxstring::createRef("ObjCProtocolExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004579 case CXCursor_ObjCBridgedCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004580 return cxstring::createRef("ObjCBridgedCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004581 case CXCursor_BlockExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004582 return cxstring::createRef("BlockExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004583 case CXCursor_PackExpansionExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004584 return cxstring::createRef("PackExpansionExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004585 case CXCursor_SizeOfPackExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004586 return cxstring::createRef("SizeOfPackExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004587 case CXCursor_LambdaExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004588 return cxstring::createRef("LambdaExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004589 case CXCursor_UnexposedExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004590 return cxstring::createRef("UnexposedExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004591 case CXCursor_DeclRefExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004592 return cxstring::createRef("DeclRefExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004593 case CXCursor_MemberRefExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004594 return cxstring::createRef("MemberRefExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004595 case CXCursor_CallExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004596 return cxstring::createRef("CallExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004597 case CXCursor_ObjCMessageExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004598 return cxstring::createRef("ObjCMessageExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004599 case CXCursor_UnexposedStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004600 return cxstring::createRef("UnexposedStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004601 case CXCursor_DeclStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004602 return cxstring::createRef("DeclStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004603 case CXCursor_LabelStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004604 return cxstring::createRef("LabelStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004605 case CXCursor_CompoundStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004606 return cxstring::createRef("CompoundStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004607 case CXCursor_CaseStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004608 return cxstring::createRef("CaseStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004609 case CXCursor_DefaultStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004610 return cxstring::createRef("DefaultStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004611 case CXCursor_IfStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004612 return cxstring::createRef("IfStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004613 case CXCursor_SwitchStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004614 return cxstring::createRef("SwitchStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004615 case CXCursor_WhileStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004616 return cxstring::createRef("WhileStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004617 case CXCursor_DoStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004618 return cxstring::createRef("DoStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004619 case CXCursor_ForStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004620 return cxstring::createRef("ForStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004621 case CXCursor_GotoStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004622 return cxstring::createRef("GotoStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004623 case CXCursor_IndirectGotoStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004624 return cxstring::createRef("IndirectGotoStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004625 case CXCursor_ContinueStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004626 return cxstring::createRef("ContinueStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004627 case CXCursor_BreakStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004628 return cxstring::createRef("BreakStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004629 case CXCursor_ReturnStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004630 return cxstring::createRef("ReturnStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004631 case CXCursor_GCCAsmStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004632 return cxstring::createRef("GCCAsmStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004633 case CXCursor_MSAsmStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004634 return cxstring::createRef("MSAsmStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004635 case CXCursor_ObjCAtTryStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004636 return cxstring::createRef("ObjCAtTryStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004637 case CXCursor_ObjCAtCatchStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004638 return cxstring::createRef("ObjCAtCatchStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004639 case CXCursor_ObjCAtFinallyStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004640 return cxstring::createRef("ObjCAtFinallyStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004641 case CXCursor_ObjCAtThrowStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004642 return cxstring::createRef("ObjCAtThrowStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004643 case CXCursor_ObjCAtSynchronizedStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004644 return cxstring::createRef("ObjCAtSynchronizedStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004645 case CXCursor_ObjCAutoreleasePoolStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004646 return cxstring::createRef("ObjCAutoreleasePoolStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004647 case CXCursor_ObjCForCollectionStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004648 return cxstring::createRef("ObjCForCollectionStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004649 case CXCursor_CXXCatchStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004650 return cxstring::createRef("CXXCatchStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004651 case CXCursor_CXXTryStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004652 return cxstring::createRef("CXXTryStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004653 case CXCursor_CXXForRangeStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004654 return cxstring::createRef("CXXForRangeStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004655 case CXCursor_SEHTryStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004656 return cxstring::createRef("SEHTryStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004657 case CXCursor_SEHExceptStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004658 return cxstring::createRef("SEHExceptStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004659 case CXCursor_SEHFinallyStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004660 return cxstring::createRef("SEHFinallyStmt");
Nico Weber9b982072014-07-07 00:12:30 +00004661 case CXCursor_SEHLeaveStmt:
4662 return cxstring::createRef("SEHLeaveStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004663 case CXCursor_NullStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004664 return cxstring::createRef("NullStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004665 case CXCursor_InvalidFile:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004666 return cxstring::createRef("InvalidFile");
Guy Benyei11169dd2012-12-18 14:30:41 +00004667 case CXCursor_InvalidCode:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004668 return cxstring::createRef("InvalidCode");
Guy Benyei11169dd2012-12-18 14:30:41 +00004669 case CXCursor_NoDeclFound:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004670 return cxstring::createRef("NoDeclFound");
Guy Benyei11169dd2012-12-18 14:30:41 +00004671 case CXCursor_NotImplemented:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004672 return cxstring::createRef("NotImplemented");
Guy Benyei11169dd2012-12-18 14:30:41 +00004673 case CXCursor_TranslationUnit:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004674 return cxstring::createRef("TranslationUnit");
Guy Benyei11169dd2012-12-18 14:30:41 +00004675 case CXCursor_UnexposedAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004676 return cxstring::createRef("UnexposedAttr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004677 case CXCursor_IBActionAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004678 return cxstring::createRef("attribute(ibaction)");
Guy Benyei11169dd2012-12-18 14:30:41 +00004679 case CXCursor_IBOutletAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004680 return cxstring::createRef("attribute(iboutlet)");
Guy Benyei11169dd2012-12-18 14:30:41 +00004681 case CXCursor_IBOutletCollectionAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004682 return cxstring::createRef("attribute(iboutletcollection)");
Guy Benyei11169dd2012-12-18 14:30:41 +00004683 case CXCursor_CXXFinalAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004684 return cxstring::createRef("attribute(final)");
Guy Benyei11169dd2012-12-18 14:30:41 +00004685 case CXCursor_CXXOverrideAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004686 return cxstring::createRef("attribute(override)");
Guy Benyei11169dd2012-12-18 14:30:41 +00004687 case CXCursor_AnnotateAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004688 return cxstring::createRef("attribute(annotate)");
Guy Benyei11169dd2012-12-18 14:30:41 +00004689 case CXCursor_AsmLabelAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004690 return cxstring::createRef("asm label");
Argyrios Kyrtzidis16834f12013-09-25 00:14:38 +00004691 case CXCursor_PackedAttr:
4692 return cxstring::createRef("attribute(packed)");
Joey Gouly81228382014-05-01 15:41:58 +00004693 case CXCursor_PureAttr:
4694 return cxstring::createRef("attribute(pure)");
4695 case CXCursor_ConstAttr:
4696 return cxstring::createRef("attribute(const)");
4697 case CXCursor_NoDuplicateAttr:
4698 return cxstring::createRef("attribute(noduplicate)");
Eli Bendersky2581e662014-05-28 19:29:58 +00004699 case CXCursor_CUDAConstantAttr:
4700 return cxstring::createRef("attribute(constant)");
4701 case CXCursor_CUDADeviceAttr:
4702 return cxstring::createRef("attribute(device)");
4703 case CXCursor_CUDAGlobalAttr:
4704 return cxstring::createRef("attribute(global)");
4705 case CXCursor_CUDAHostAttr:
4706 return cxstring::createRef("attribute(host)");
Eli Bendersky9b071472014-08-08 14:59:00 +00004707 case CXCursor_CUDASharedAttr:
4708 return cxstring::createRef("attribute(shared)");
Saleem Abdulrasool79c69712015-09-05 18:53:43 +00004709 case CXCursor_VisibilityAttr:
4710 return cxstring::createRef("attribute(visibility)");
Saleem Abdulrasool8aa0b802015-12-10 18:45:18 +00004711 case CXCursor_DLLExport:
4712 return cxstring::createRef("attribute(dllexport)");
4713 case CXCursor_DLLImport:
4714 return cxstring::createRef("attribute(dllimport)");
Guy Benyei11169dd2012-12-18 14:30:41 +00004715 case CXCursor_PreprocessingDirective:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004716 return cxstring::createRef("preprocessing directive");
Guy Benyei11169dd2012-12-18 14:30:41 +00004717 case CXCursor_MacroDefinition:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004718 return cxstring::createRef("macro definition");
Guy Benyei11169dd2012-12-18 14:30:41 +00004719 case CXCursor_MacroExpansion:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004720 return cxstring::createRef("macro expansion");
Guy Benyei11169dd2012-12-18 14:30:41 +00004721 case CXCursor_InclusionDirective:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004722 return cxstring::createRef("inclusion directive");
Guy Benyei11169dd2012-12-18 14:30:41 +00004723 case CXCursor_Namespace:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004724 return cxstring::createRef("Namespace");
Guy Benyei11169dd2012-12-18 14:30:41 +00004725 case CXCursor_LinkageSpec:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004726 return cxstring::createRef("LinkageSpec");
Guy Benyei11169dd2012-12-18 14:30:41 +00004727 case CXCursor_CXXBaseSpecifier:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004728 return cxstring::createRef("C++ base class specifier");
Guy Benyei11169dd2012-12-18 14:30:41 +00004729 case CXCursor_Constructor:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004730 return cxstring::createRef("CXXConstructor");
Guy Benyei11169dd2012-12-18 14:30:41 +00004731 case CXCursor_Destructor:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004732 return cxstring::createRef("CXXDestructor");
Guy Benyei11169dd2012-12-18 14:30:41 +00004733 case CXCursor_ConversionFunction:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004734 return cxstring::createRef("CXXConversion");
Guy Benyei11169dd2012-12-18 14:30:41 +00004735 case CXCursor_TemplateTypeParameter:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004736 return cxstring::createRef("TemplateTypeParameter");
Guy Benyei11169dd2012-12-18 14:30:41 +00004737 case CXCursor_NonTypeTemplateParameter:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004738 return cxstring::createRef("NonTypeTemplateParameter");
Guy Benyei11169dd2012-12-18 14:30:41 +00004739 case CXCursor_TemplateTemplateParameter:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004740 return cxstring::createRef("TemplateTemplateParameter");
Guy Benyei11169dd2012-12-18 14:30:41 +00004741 case CXCursor_FunctionTemplate:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004742 return cxstring::createRef("FunctionTemplate");
Guy Benyei11169dd2012-12-18 14:30:41 +00004743 case CXCursor_ClassTemplate:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004744 return cxstring::createRef("ClassTemplate");
Guy Benyei11169dd2012-12-18 14:30:41 +00004745 case CXCursor_ClassTemplatePartialSpecialization:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004746 return cxstring::createRef("ClassTemplatePartialSpecialization");
Guy Benyei11169dd2012-12-18 14:30:41 +00004747 case CXCursor_NamespaceAlias:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004748 return cxstring::createRef("NamespaceAlias");
Guy Benyei11169dd2012-12-18 14:30:41 +00004749 case CXCursor_UsingDirective:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004750 return cxstring::createRef("UsingDirective");
Guy Benyei11169dd2012-12-18 14:30:41 +00004751 case CXCursor_UsingDeclaration:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004752 return cxstring::createRef("UsingDeclaration");
Guy Benyei11169dd2012-12-18 14:30:41 +00004753 case CXCursor_TypeAliasDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004754 return cxstring::createRef("TypeAliasDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004755 case CXCursor_ObjCSynthesizeDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004756 return cxstring::createRef("ObjCSynthesizeDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004757 case CXCursor_ObjCDynamicDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004758 return cxstring::createRef("ObjCDynamicDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004759 case CXCursor_CXXAccessSpecifier:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004760 return cxstring::createRef("CXXAccessSpecifier");
Guy Benyei11169dd2012-12-18 14:30:41 +00004761 case CXCursor_ModuleImportDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004762 return cxstring::createRef("ModuleImport");
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004763 case CXCursor_OMPParallelDirective:
Alexey Bataev1b59ab52014-02-27 08:29:12 +00004764 return cxstring::createRef("OMPParallelDirective");
4765 case CXCursor_OMPSimdDirective:
4766 return cxstring::createRef("OMPSimdDirective");
Alexey Bataevf29276e2014-06-18 04:14:57 +00004767 case CXCursor_OMPForDirective:
4768 return cxstring::createRef("OMPForDirective");
Alexander Musmanf82886e2014-09-18 05:12:34 +00004769 case CXCursor_OMPForSimdDirective:
4770 return cxstring::createRef("OMPForSimdDirective");
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004771 case CXCursor_OMPSectionsDirective:
4772 return cxstring::createRef("OMPSectionsDirective");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004773 case CXCursor_OMPSectionDirective:
4774 return cxstring::createRef("OMPSectionDirective");
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00004775 case CXCursor_OMPSingleDirective:
4776 return cxstring::createRef("OMPSingleDirective");
Alexander Musman80c22892014-07-17 08:54:58 +00004777 case CXCursor_OMPMasterDirective:
4778 return cxstring::createRef("OMPMasterDirective");
Alexander Musmand9ed09f2014-07-21 09:42:05 +00004779 case CXCursor_OMPCriticalDirective:
4780 return cxstring::createRef("OMPCriticalDirective");
Alexey Bataev4acb8592014-07-07 13:01:15 +00004781 case CXCursor_OMPParallelForDirective:
4782 return cxstring::createRef("OMPParallelForDirective");
Alexander Musmane4e893b2014-09-23 09:33:00 +00004783 case CXCursor_OMPParallelForSimdDirective:
4784 return cxstring::createRef("OMPParallelForSimdDirective");
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004785 case CXCursor_OMPParallelSectionsDirective:
4786 return cxstring::createRef("OMPParallelSectionsDirective");
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004787 case CXCursor_OMPTaskDirective:
4788 return cxstring::createRef("OMPTaskDirective");
Alexey Bataev68446b72014-07-18 07:47:19 +00004789 case CXCursor_OMPTaskyieldDirective:
4790 return cxstring::createRef("OMPTaskyieldDirective");
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00004791 case CXCursor_OMPBarrierDirective:
4792 return cxstring::createRef("OMPBarrierDirective");
Alexey Bataev2df347a2014-07-18 10:17:07 +00004793 case CXCursor_OMPTaskwaitDirective:
4794 return cxstring::createRef("OMPTaskwaitDirective");
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00004795 case CXCursor_OMPTaskgroupDirective:
4796 return cxstring::createRef("OMPTaskgroupDirective");
Alexey Bataev6125da92014-07-21 11:26:11 +00004797 case CXCursor_OMPFlushDirective:
4798 return cxstring::createRef("OMPFlushDirective");
Alexey Bataev9fb6e642014-07-22 06:45:04 +00004799 case CXCursor_OMPOrderedDirective:
4800 return cxstring::createRef("OMPOrderedDirective");
Alexey Bataev0162e452014-07-22 10:10:35 +00004801 case CXCursor_OMPAtomicDirective:
4802 return cxstring::createRef("OMPAtomicDirective");
Alexey Bataev0bd520b2014-09-19 08:19:49 +00004803 case CXCursor_OMPTargetDirective:
4804 return cxstring::createRef("OMPTargetDirective");
Michael Wong65f367f2015-07-21 13:44:28 +00004805 case CXCursor_OMPTargetDataDirective:
4806 return cxstring::createRef("OMPTargetDataDirective");
Samuel Antaodf67fc42016-01-19 19:15:56 +00004807 case CXCursor_OMPTargetEnterDataDirective:
4808 return cxstring::createRef("OMPTargetEnterDataDirective");
Samuel Antao72590762016-01-19 20:04:50 +00004809 case CXCursor_OMPTargetExitDataDirective:
4810 return cxstring::createRef("OMPTargetExitDataDirective");
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00004811 case CXCursor_OMPTargetParallelDirective:
4812 return cxstring::createRef("OMPTargetParallelDirective");
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00004813 case CXCursor_OMPTargetParallelForDirective:
4814 return cxstring::createRef("OMPTargetParallelForDirective");
Samuel Antao686c70c2016-05-26 17:30:50 +00004815 case CXCursor_OMPTargetUpdateDirective:
4816 return cxstring::createRef("OMPTargetUpdateDirective");
Alexey Bataev13314bf2014-10-09 04:18:56 +00004817 case CXCursor_OMPTeamsDirective:
4818 return cxstring::createRef("OMPTeamsDirective");
Alexey Bataev6d4ed052015-07-01 06:57:41 +00004819 case CXCursor_OMPCancellationPointDirective:
4820 return cxstring::createRef("OMPCancellationPointDirective");
Alexey Bataev80909872015-07-02 11:25:17 +00004821 case CXCursor_OMPCancelDirective:
4822 return cxstring::createRef("OMPCancelDirective");
Alexey Bataev49f6e782015-12-01 04:18:41 +00004823 case CXCursor_OMPTaskLoopDirective:
4824 return cxstring::createRef("OMPTaskLoopDirective");
Alexey Bataev0a6ed842015-12-03 09:40:15 +00004825 case CXCursor_OMPTaskLoopSimdDirective:
4826 return cxstring::createRef("OMPTaskLoopSimdDirective");
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004827 case CXCursor_OMPDistributeDirective:
4828 return cxstring::createRef("OMPDistributeDirective");
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00004829 case CXCursor_OverloadCandidate:
4830 return cxstring::createRef("OverloadCandidate");
Sergey Kalinichev8f3b1872015-11-15 13:48:32 +00004831 case CXCursor_TypeAliasTemplateDecl:
4832 return cxstring::createRef("TypeAliasTemplateDecl");
Olivier Goffart81978012016-06-09 16:15:55 +00004833 case CXCursor_StaticAssert:
4834 return cxstring::createRef("StaticAssert");
Guy Benyei11169dd2012-12-18 14:30:41 +00004835 }
4836
4837 llvm_unreachable("Unhandled CXCursorKind");
4838}
4839
4840struct GetCursorData {
4841 SourceLocation TokenBeginLoc;
4842 bool PointsAtMacroArgExpansion;
4843 bool VisitedObjCPropertyImplDecl;
4844 SourceLocation VisitedDeclaratorDeclStartLoc;
4845 CXCursor &BestCursor;
4846
4847 GetCursorData(SourceManager &SM,
4848 SourceLocation tokenBegin, CXCursor &outputCursor)
4849 : TokenBeginLoc(tokenBegin), BestCursor(outputCursor) {
4850 PointsAtMacroArgExpansion = SM.isMacroArgExpansion(tokenBegin);
4851 VisitedObjCPropertyImplDecl = false;
4852 }
4853};
4854
4855static enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
4856 CXCursor parent,
4857 CXClientData client_data) {
4858 GetCursorData *Data = static_cast<GetCursorData *>(client_data);
4859 CXCursor *BestCursor = &Data->BestCursor;
4860
4861 // If we point inside a macro argument we should provide info of what the
4862 // token is so use the actual cursor, don't replace it with a macro expansion
4863 // cursor.
4864 if (cursor.kind == CXCursor_MacroExpansion && Data->PointsAtMacroArgExpansion)
4865 return CXChildVisit_Recurse;
4866
4867 if (clang_isDeclaration(cursor.kind)) {
4868 // Avoid having the implicit methods override the property decls.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004869 if (const ObjCMethodDecl *MD
Guy Benyei11169dd2012-12-18 14:30:41 +00004870 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
4871 if (MD->isImplicit())
4872 return CXChildVisit_Break;
4873
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004874 } else if (const ObjCInterfaceDecl *ID
Guy Benyei11169dd2012-12-18 14:30:41 +00004875 = dyn_cast_or_null<ObjCInterfaceDecl>(getCursorDecl(cursor))) {
4876 // Check that when we have multiple @class references in the same line,
4877 // that later ones do not override the previous ones.
4878 // If we have:
4879 // @class Foo, Bar;
4880 // source ranges for both start at '@', so 'Bar' will end up overriding
4881 // 'Foo' even though the cursor location was at 'Foo'.
4882 if (BestCursor->kind == CXCursor_ObjCInterfaceDecl ||
4883 BestCursor->kind == CXCursor_ObjCClassRef)
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004884 if (const ObjCInterfaceDecl *PrevID
Guy Benyei11169dd2012-12-18 14:30:41 +00004885 = dyn_cast_or_null<ObjCInterfaceDecl>(getCursorDecl(*BestCursor))){
4886 if (PrevID != ID &&
4887 !PrevID->isThisDeclarationADefinition() &&
4888 !ID->isThisDeclarationADefinition())
4889 return CXChildVisit_Break;
4890 }
4891
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004892 } else if (const DeclaratorDecl *DD
Guy Benyei11169dd2012-12-18 14:30:41 +00004893 = dyn_cast_or_null<DeclaratorDecl>(getCursorDecl(cursor))) {
4894 SourceLocation StartLoc = DD->getSourceRange().getBegin();
4895 // Check that when we have multiple declarators in the same line,
4896 // that later ones do not override the previous ones.
4897 // If we have:
4898 // int Foo, Bar;
4899 // source ranges for both start at 'int', so 'Bar' will end up overriding
4900 // 'Foo' even though the cursor location was at 'Foo'.
4901 if (Data->VisitedDeclaratorDeclStartLoc == StartLoc)
4902 return CXChildVisit_Break;
4903 Data->VisitedDeclaratorDeclStartLoc = StartLoc;
4904
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004905 } else if (const ObjCPropertyImplDecl *PropImp
Guy Benyei11169dd2012-12-18 14:30:41 +00004906 = dyn_cast_or_null<ObjCPropertyImplDecl>(getCursorDecl(cursor))) {
4907 (void)PropImp;
4908 // Check that when we have multiple @synthesize in the same line,
4909 // that later ones do not override the previous ones.
4910 // If we have:
4911 // @synthesize Foo, Bar;
4912 // source ranges for both start at '@', so 'Bar' will end up overriding
4913 // 'Foo' even though the cursor location was at 'Foo'.
4914 if (Data->VisitedObjCPropertyImplDecl)
4915 return CXChildVisit_Break;
4916 Data->VisitedObjCPropertyImplDecl = true;
4917 }
4918 }
4919
4920 if (clang_isExpression(cursor.kind) &&
4921 clang_isDeclaration(BestCursor->kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004922 if (const Decl *D = getCursorDecl(*BestCursor)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004923 // Avoid having the cursor of an expression replace the declaration cursor
4924 // when the expression source range overlaps the declaration range.
4925 // This can happen for C++ constructor expressions whose range generally
4926 // include the variable declaration, e.g.:
4927 // MyCXXClass foo; // Make sure pointing at 'foo' returns a VarDecl cursor.
4928 if (D->getLocation().isValid() && Data->TokenBeginLoc.isValid() &&
4929 D->getLocation() == Data->TokenBeginLoc)
4930 return CXChildVisit_Break;
4931 }
4932 }
4933
4934 // If our current best cursor is the construction of a temporary object,
4935 // don't replace that cursor with a type reference, because we want
4936 // clang_getCursor() to point at the constructor.
4937 if (clang_isExpression(BestCursor->kind) &&
4938 isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
4939 cursor.kind == CXCursor_TypeRef) {
4940 // Keep the cursor pointing at CXXTemporaryObjectExpr but also mark it
4941 // as having the actual point on the type reference.
4942 *BestCursor = getTypeRefedCallExprCursor(*BestCursor);
4943 return CXChildVisit_Recurse;
4944 }
Douglas Gregore9d95f12015-07-07 03:57:35 +00004945
4946 // If we already have an Objective-C superclass reference, don't
4947 // update it further.
4948 if (BestCursor->kind == CXCursor_ObjCSuperClassRef)
4949 return CXChildVisit_Break;
4950
Guy Benyei11169dd2012-12-18 14:30:41 +00004951 *BestCursor = cursor;
4952 return CXChildVisit_Recurse;
4953}
4954
4955CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004956 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004957 LOG_BAD_TU(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004958 return clang_getNullCursor();
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004959 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004960
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004961 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004962 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
4963
4964 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
4965 CXCursor Result = cxcursor::getCursor(TU, SLoc);
4966
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00004967 LOG_FUNC_SECTION {
Guy Benyei11169dd2012-12-18 14:30:41 +00004968 CXFile SearchFile;
4969 unsigned SearchLine, SearchColumn;
4970 CXFile ResultFile;
4971 unsigned ResultLine, ResultColumn;
4972 CXString SearchFileName, ResultFileName, KindSpelling, USR;
4973 const char *IsDef = clang_isCursorDefinition(Result)? " (Definition)" : "";
4974 CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
Craig Topper69186e72014-06-08 08:38:04 +00004975
4976 clang_getFileLocation(Loc, &SearchFile, &SearchLine, &SearchColumn,
4977 nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00004978 clang_getFileLocation(ResultLoc, &ResultFile, &ResultLine,
Craig Topper69186e72014-06-08 08:38:04 +00004979 &ResultColumn, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00004980 SearchFileName = clang_getFileName(SearchFile);
4981 ResultFileName = clang_getFileName(ResultFile);
4982 KindSpelling = clang_getCursorKindSpelling(Result.kind);
4983 USR = clang_getCursorUSR(Result);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00004984 *Log << llvm::format("(%s:%d:%d) = %s",
4985 clang_getCString(SearchFileName), SearchLine, SearchColumn,
4986 clang_getCString(KindSpelling))
4987 << llvm::format("(%s:%d:%d):%s%s",
4988 clang_getCString(ResultFileName), ResultLine, ResultColumn,
4989 clang_getCString(USR), IsDef);
Guy Benyei11169dd2012-12-18 14:30:41 +00004990 clang_disposeString(SearchFileName);
4991 clang_disposeString(ResultFileName);
4992 clang_disposeString(KindSpelling);
4993 clang_disposeString(USR);
4994
4995 CXCursor Definition = clang_getCursorDefinition(Result);
4996 if (!clang_equalCursors(Definition, clang_getNullCursor())) {
4997 CXSourceLocation DefinitionLoc = clang_getCursorLocation(Definition);
4998 CXString DefinitionKindSpelling
4999 = clang_getCursorKindSpelling(Definition.kind);
5000 CXFile DefinitionFile;
5001 unsigned DefinitionLine, DefinitionColumn;
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005002 clang_getFileLocation(DefinitionLoc, &DefinitionFile,
Craig Topper69186e72014-06-08 08:38:04 +00005003 &DefinitionLine, &DefinitionColumn, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005004 CXString DefinitionFileName = clang_getFileName(DefinitionFile);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005005 *Log << llvm::format(" -> %s(%s:%d:%d)",
5006 clang_getCString(DefinitionKindSpelling),
5007 clang_getCString(DefinitionFileName),
5008 DefinitionLine, DefinitionColumn);
Guy Benyei11169dd2012-12-18 14:30:41 +00005009 clang_disposeString(DefinitionFileName);
5010 clang_disposeString(DefinitionKindSpelling);
5011 }
5012 }
5013
5014 return Result;
5015}
5016
5017CXCursor clang_getNullCursor(void) {
5018 return MakeCXCursorInvalid(CXCursor_InvalidFile);
5019}
5020
5021unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Argyrios Kyrtzidisbf1be592013-01-08 18:23:28 +00005022 // Clear out the "FirstInDeclGroup" part in a declaration cursor, since we
5023 // can't set consistently. For example, when visiting a DeclStmt we will set
5024 // it but we don't set it on the result of clang_getCursorDefinition for
5025 // a reference of the same declaration.
5026 // FIXME: Setting "FirstInDeclGroup" in CXCursors is a hack that only works
5027 // when visiting a DeclStmt currently, the AST should be enhanced to be able
5028 // to provide that kind of info.
5029 if (clang_isDeclaration(X.kind))
Craig Topper69186e72014-06-08 08:38:04 +00005030 X.data[1] = nullptr;
Argyrios Kyrtzidisbf1be592013-01-08 18:23:28 +00005031 if (clang_isDeclaration(Y.kind))
Craig Topper69186e72014-06-08 08:38:04 +00005032 Y.data[1] = nullptr;
Argyrios Kyrtzidisbf1be592013-01-08 18:23:28 +00005033
Guy Benyei11169dd2012-12-18 14:30:41 +00005034 return X == Y;
5035}
5036
5037unsigned clang_hashCursor(CXCursor C) {
5038 unsigned Index = 0;
5039 if (clang_isExpression(C.kind) || clang_isStatement(C.kind))
5040 Index = 1;
5041
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005042 return llvm::DenseMapInfo<std::pair<unsigned, const void*> >::getHashValue(
Guy Benyei11169dd2012-12-18 14:30:41 +00005043 std::make_pair(C.kind, C.data[Index]));
5044}
5045
5046unsigned clang_isInvalid(enum CXCursorKind K) {
5047 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
5048}
5049
5050unsigned clang_isDeclaration(enum CXCursorKind K) {
5051 return (K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl) ||
5052 (K >= CXCursor_FirstExtraDecl && K <= CXCursor_LastExtraDecl);
5053}
5054
5055unsigned clang_isReference(enum CXCursorKind K) {
5056 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
5057}
5058
5059unsigned clang_isExpression(enum CXCursorKind K) {
5060 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
5061}
5062
5063unsigned clang_isStatement(enum CXCursorKind K) {
5064 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
5065}
5066
5067unsigned clang_isAttribute(enum CXCursorKind K) {
5068 return K >= CXCursor_FirstAttr && K <= CXCursor_LastAttr;
5069}
5070
5071unsigned clang_isTranslationUnit(enum CXCursorKind K) {
5072 return K == CXCursor_TranslationUnit;
5073}
5074
5075unsigned clang_isPreprocessing(enum CXCursorKind K) {
5076 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
5077}
5078
5079unsigned clang_isUnexposed(enum CXCursorKind K) {
5080 switch (K) {
5081 case CXCursor_UnexposedDecl:
5082 case CXCursor_UnexposedExpr:
5083 case CXCursor_UnexposedStmt:
5084 case CXCursor_UnexposedAttr:
5085 return true;
5086 default:
5087 return false;
5088 }
5089}
5090
5091CXCursorKind clang_getCursorKind(CXCursor C) {
5092 return C.kind;
5093}
5094
5095CXSourceLocation clang_getCursorLocation(CXCursor C) {
5096 if (clang_isReference(C.kind)) {
5097 switch (C.kind) {
5098 case CXCursor_ObjCSuperClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005099 std::pair<const ObjCInterfaceDecl *, SourceLocation> P
Guy Benyei11169dd2012-12-18 14:30:41 +00005100 = getCursorObjCSuperClassRef(C);
5101 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5102 }
5103
5104 case CXCursor_ObjCProtocolRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005105 std::pair<const ObjCProtocolDecl *, SourceLocation> P
Guy Benyei11169dd2012-12-18 14:30:41 +00005106 = getCursorObjCProtocolRef(C);
5107 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5108 }
5109
5110 case CXCursor_ObjCClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005111 std::pair<const ObjCInterfaceDecl *, SourceLocation> P
Guy Benyei11169dd2012-12-18 14:30:41 +00005112 = getCursorObjCClassRef(C);
5113 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5114 }
5115
5116 case CXCursor_TypeRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005117 std::pair<const TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005118 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5119 }
5120
5121 case CXCursor_TemplateRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005122 std::pair<const TemplateDecl *, SourceLocation> P =
5123 getCursorTemplateRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005124 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5125 }
5126
5127 case CXCursor_NamespaceRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005128 std::pair<const NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005129 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5130 }
5131
5132 case CXCursor_MemberRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005133 std::pair<const FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005134 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5135 }
5136
5137 case CXCursor_VariableRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005138 std::pair<const VarDecl *, SourceLocation> P = getCursorVariableRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005139 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5140 }
5141
5142 case CXCursor_CXXBaseSpecifier: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005143 const CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005144 if (!BaseSpec)
5145 return clang_getNullLocation();
5146
5147 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
5148 return cxloc::translateSourceLocation(getCursorContext(C),
5149 TSInfo->getTypeLoc().getBeginLoc());
5150
5151 return cxloc::translateSourceLocation(getCursorContext(C),
5152 BaseSpec->getLocStart());
5153 }
5154
5155 case CXCursor_LabelRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005156 std::pair<const LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005157 return cxloc::translateSourceLocation(getCursorContext(C), P.second);
5158 }
5159
5160 case CXCursor_OverloadedDeclRef:
5161 return cxloc::translateSourceLocation(getCursorContext(C),
5162 getCursorOverloadedDeclRef(C).second);
5163
5164 default:
5165 // FIXME: Need a way to enumerate all non-reference cases.
5166 llvm_unreachable("Missed a reference kind");
5167 }
5168 }
5169
5170 if (clang_isExpression(C.kind))
5171 return cxloc::translateSourceLocation(getCursorContext(C),
5172 getLocationFromExpr(getCursorExpr(C)));
5173
5174 if (clang_isStatement(C.kind))
5175 return cxloc::translateSourceLocation(getCursorContext(C),
5176 getCursorStmt(C)->getLocStart());
5177
5178 if (C.kind == CXCursor_PreprocessingDirective) {
5179 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
5180 return cxloc::translateSourceLocation(getCursorContext(C), L);
5181 }
5182
5183 if (C.kind == CXCursor_MacroExpansion) {
5184 SourceLocation L
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00005185 = cxcursor::getCursorMacroExpansion(C).getSourceRange().getBegin();
Guy Benyei11169dd2012-12-18 14:30:41 +00005186 return cxloc::translateSourceLocation(getCursorContext(C), L);
5187 }
5188
5189 if (C.kind == CXCursor_MacroDefinition) {
5190 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
5191 return cxloc::translateSourceLocation(getCursorContext(C), L);
5192 }
5193
5194 if (C.kind == CXCursor_InclusionDirective) {
5195 SourceLocation L
5196 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
5197 return cxloc::translateSourceLocation(getCursorContext(C), L);
5198 }
5199
Argyrios Kyrtzidis16834f12013-09-25 00:14:38 +00005200 if (clang_isAttribute(C.kind)) {
5201 SourceLocation L
5202 = cxcursor::getCursorAttr(C)->getLocation();
5203 return cxloc::translateSourceLocation(getCursorContext(C), L);
5204 }
5205
Guy Benyei11169dd2012-12-18 14:30:41 +00005206 if (!clang_isDeclaration(C.kind))
5207 return clang_getNullLocation();
5208
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005209 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005210 if (!D)
5211 return clang_getNullLocation();
5212
5213 SourceLocation Loc = D->getLocation();
5214 // FIXME: Multiple variables declared in a single declaration
5215 // currently lack the information needed to correctly determine their
5216 // ranges when accounting for the type-specifier. We use context
5217 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
5218 // and if so, whether it is the first decl.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005219 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005220 if (!cxcursor::isFirstInDeclGroup(C))
5221 Loc = VD->getLocation();
5222 }
5223
5224 // For ObjC methods, give the start location of the method name.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005225 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00005226 Loc = MD->getSelectorStartLoc();
5227
5228 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
5229}
5230
5231} // end extern "C"
5232
5233CXCursor cxcursor::getCursor(CXTranslationUnit TU, SourceLocation SLoc) {
5234 assert(TU);
5235
5236 // Guard against an invalid SourceLocation, or we may assert in one
5237 // of the following calls.
5238 if (SLoc.isInvalid())
5239 return clang_getNullCursor();
5240
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00005241 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00005242
5243 // Translate the given source location to make it point at the beginning of
5244 // the token under the cursor.
5245 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
5246 CXXUnit->getASTContext().getLangOpts());
5247
5248 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
5249 if (SLoc.isValid()) {
5250 GetCursorData ResultData(CXXUnit->getSourceManager(), SLoc, Result);
5251 CursorVisitor CursorVis(TU, GetCursorVisitor, &ResultData,
5252 /*VisitPreprocessorLast=*/true,
5253 /*VisitIncludedEntities=*/false,
5254 SourceLocation(SLoc));
5255 CursorVis.visitFileRegion();
5256 }
5257
5258 return Result;
5259}
5260
5261static SourceRange getRawCursorExtent(CXCursor C) {
5262 if (clang_isReference(C.kind)) {
5263 switch (C.kind) {
5264 case CXCursor_ObjCSuperClassRef:
5265 return getCursorObjCSuperClassRef(C).second;
5266
5267 case CXCursor_ObjCProtocolRef:
5268 return getCursorObjCProtocolRef(C).second;
5269
5270 case CXCursor_ObjCClassRef:
5271 return getCursorObjCClassRef(C).second;
5272
5273 case CXCursor_TypeRef:
5274 return getCursorTypeRef(C).second;
5275
5276 case CXCursor_TemplateRef:
5277 return getCursorTemplateRef(C).second;
5278
5279 case CXCursor_NamespaceRef:
5280 return getCursorNamespaceRef(C).second;
5281
5282 case CXCursor_MemberRef:
5283 return getCursorMemberRef(C).second;
5284
5285 case CXCursor_CXXBaseSpecifier:
5286 return getCursorCXXBaseSpecifier(C)->getSourceRange();
5287
5288 case CXCursor_LabelRef:
5289 return getCursorLabelRef(C).second;
5290
5291 case CXCursor_OverloadedDeclRef:
5292 return getCursorOverloadedDeclRef(C).second;
5293
5294 case CXCursor_VariableRef:
5295 return getCursorVariableRef(C).second;
5296
5297 default:
5298 // FIXME: Need a way to enumerate all non-reference cases.
5299 llvm_unreachable("Missed a reference kind");
5300 }
5301 }
5302
5303 if (clang_isExpression(C.kind))
5304 return getCursorExpr(C)->getSourceRange();
5305
5306 if (clang_isStatement(C.kind))
5307 return getCursorStmt(C)->getSourceRange();
5308
5309 if (clang_isAttribute(C.kind))
5310 return getCursorAttr(C)->getRange();
5311
5312 if (C.kind == CXCursor_PreprocessingDirective)
5313 return cxcursor::getCursorPreprocessingDirective(C);
5314
5315 if (C.kind == CXCursor_MacroExpansion) {
5316 ASTUnit *TU = getCursorASTUnit(C);
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00005317 SourceRange Range = cxcursor::getCursorMacroExpansion(C).getSourceRange();
Guy Benyei11169dd2012-12-18 14:30:41 +00005318 return TU->mapRangeFromPreamble(Range);
5319 }
5320
5321 if (C.kind == CXCursor_MacroDefinition) {
5322 ASTUnit *TU = getCursorASTUnit(C);
5323 SourceRange Range = cxcursor::getCursorMacroDefinition(C)->getSourceRange();
5324 return TU->mapRangeFromPreamble(Range);
5325 }
5326
5327 if (C.kind == CXCursor_InclusionDirective) {
5328 ASTUnit *TU = getCursorASTUnit(C);
5329 SourceRange Range = cxcursor::getCursorInclusionDirective(C)->getSourceRange();
5330 return TU->mapRangeFromPreamble(Range);
5331 }
5332
5333 if (C.kind == CXCursor_TranslationUnit) {
5334 ASTUnit *TU = getCursorASTUnit(C);
5335 FileID MainID = TU->getSourceManager().getMainFileID();
5336 SourceLocation Start = TU->getSourceManager().getLocForStartOfFile(MainID);
5337 SourceLocation End = TU->getSourceManager().getLocForEndOfFile(MainID);
5338 return SourceRange(Start, End);
5339 }
5340
5341 if (clang_isDeclaration(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005342 const Decl *D = cxcursor::getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005343 if (!D)
5344 return SourceRange();
5345
5346 SourceRange R = D->getSourceRange();
5347 // FIXME: Multiple variables declared in a single declaration
5348 // currently lack the information needed to correctly determine their
5349 // ranges when accounting for the type-specifier. We use context
5350 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
5351 // and if so, whether it is the first decl.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005352 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005353 if (!cxcursor::isFirstInDeclGroup(C))
5354 R.setBegin(VD->getLocation());
5355 }
5356 return R;
5357 }
5358 return SourceRange();
5359}
5360
5361/// \brief Retrieves the "raw" cursor extent, which is then extended to include
5362/// the decl-specifier-seq for declarations.
5363static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr) {
5364 if (clang_isDeclaration(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005365 const Decl *D = cxcursor::getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005366 if (!D)
5367 return SourceRange();
5368
5369 SourceRange R = D->getSourceRange();
5370
5371 // Adjust the start of the location for declarations preceded by
5372 // declaration specifiers.
5373 SourceLocation StartLoc;
5374 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
5375 if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
5376 StartLoc = TI->getTypeLoc().getLocStart();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005377 } else if (const TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005378 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
5379 StartLoc = TI->getTypeLoc().getLocStart();
5380 }
5381
5382 if (StartLoc.isValid() && R.getBegin().isValid() &&
5383 SrcMgr.isBeforeInTranslationUnit(StartLoc, R.getBegin()))
5384 R.setBegin(StartLoc);
5385
5386 // FIXME: Multiple variables declared in a single declaration
5387 // currently lack the information needed to correctly determine their
5388 // ranges when accounting for the type-specifier. We use context
5389 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
5390 // and if so, whether it is the first decl.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005391 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005392 if (!cxcursor::isFirstInDeclGroup(C))
5393 R.setBegin(VD->getLocation());
5394 }
5395
5396 return R;
5397 }
5398
5399 return getRawCursorExtent(C);
5400}
5401
5402extern "C" {
5403
5404CXSourceRange clang_getCursorExtent(CXCursor C) {
5405 SourceRange R = getRawCursorExtent(C);
5406 if (R.isInvalid())
5407 return clang_getNullRange();
5408
5409 return cxloc::translateSourceRange(getCursorContext(C), R);
5410}
5411
5412CXCursor clang_getCursorReferenced(CXCursor C) {
5413 if (clang_isInvalid(C.kind))
5414 return clang_getNullCursor();
5415
5416 CXTranslationUnit tu = getCursorTU(C);
5417 if (clang_isDeclaration(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005418 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005419 if (!D)
5420 return clang_getNullCursor();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005421 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00005422 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), tu);
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005423 if (const ObjCPropertyImplDecl *PropImpl =
5424 dyn_cast<ObjCPropertyImplDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00005425 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
5426 return MakeCXCursor(Property, tu);
5427
5428 return C;
5429 }
5430
5431 if (clang_isExpression(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005432 const Expr *E = getCursorExpr(C);
5433 const Decl *D = getDeclFromExpr(E);
Guy Benyei11169dd2012-12-18 14:30:41 +00005434 if (D) {
5435 CXCursor declCursor = MakeCXCursor(D, tu);
5436 declCursor = getSelectorIdentifierCursor(getSelectorIdentifierIndex(C),
5437 declCursor);
5438 return declCursor;
5439 }
5440
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005441 if (const OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00005442 return MakeCursorOverloadedDeclRef(Ovl, tu);
5443
5444 return clang_getNullCursor();
5445 }
5446
5447 if (clang_isStatement(C.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00005448 const Stmt *S = getCursorStmt(C);
5449 if (const GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
Guy Benyei11169dd2012-12-18 14:30:41 +00005450 if (LabelDecl *label = Goto->getLabel())
5451 if (LabelStmt *labelS = label->getStmt())
5452 return MakeCXCursor(labelS, getCursorDecl(C), tu);
5453
5454 return clang_getNullCursor();
5455 }
Richard Smith66a81862015-05-04 02:25:31 +00005456
Guy Benyei11169dd2012-12-18 14:30:41 +00005457 if (C.kind == CXCursor_MacroExpansion) {
Richard Smith66a81862015-05-04 02:25:31 +00005458 if (const MacroDefinitionRecord *Def =
5459 getCursorMacroExpansion(C).getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00005460 return MakeMacroDefinitionCursor(Def, tu);
5461 }
5462
5463 if (!clang_isReference(C.kind))
5464 return clang_getNullCursor();
5465
5466 switch (C.kind) {
5467 case CXCursor_ObjCSuperClassRef:
5468 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, tu);
5469
5470 case CXCursor_ObjCProtocolRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005471 const ObjCProtocolDecl *Prot = getCursorObjCProtocolRef(C).first;
5472 if (const ObjCProtocolDecl *Def = Prot->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00005473 return MakeCXCursor(Def, tu);
5474
5475 return MakeCXCursor(Prot, tu);
5476 }
5477
5478 case CXCursor_ObjCClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005479 const ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
5480 if (const ObjCInterfaceDecl *Def = Class->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00005481 return MakeCXCursor(Def, tu);
5482
5483 return MakeCXCursor(Class, tu);
5484 }
5485
5486 case CXCursor_TypeRef:
5487 return MakeCXCursor(getCursorTypeRef(C).first, tu );
5488
5489 case CXCursor_TemplateRef:
5490 return MakeCXCursor(getCursorTemplateRef(C).first, tu );
5491
5492 case CXCursor_NamespaceRef:
5493 return MakeCXCursor(getCursorNamespaceRef(C).first, tu );
5494
5495 case CXCursor_MemberRef:
5496 return MakeCXCursor(getCursorMemberRef(C).first, tu );
5497
5498 case CXCursor_CXXBaseSpecifier: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005499 const CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005500 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
5501 tu ));
5502 }
5503
5504 case CXCursor_LabelRef:
5505 // FIXME: We end up faking the "parent" declaration here because we
5506 // don't want to make CXCursor larger.
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00005507 return MakeCXCursor(getCursorLabelRef(C).first,
5508 cxtu::getASTUnit(tu)->getASTContext()
5509 .getTranslationUnitDecl(),
Guy Benyei11169dd2012-12-18 14:30:41 +00005510 tu);
5511
5512 case CXCursor_OverloadedDeclRef:
5513 return C;
5514
5515 case CXCursor_VariableRef:
5516 return MakeCXCursor(getCursorVariableRef(C).first, tu);
5517
5518 default:
5519 // We would prefer to enumerate all non-reference cursor kinds here.
5520 llvm_unreachable("Unhandled reference cursor kind");
5521 }
5522}
5523
5524CXCursor clang_getCursorDefinition(CXCursor C) {
5525 if (clang_isInvalid(C.kind))
5526 return clang_getNullCursor();
5527
5528 CXTranslationUnit TU = getCursorTU(C);
5529
5530 bool WasReference = false;
5531 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
5532 C = clang_getCursorReferenced(C);
5533 WasReference = true;
5534 }
5535
5536 if (C.kind == CXCursor_MacroExpansion)
5537 return clang_getCursorReferenced(C);
5538
5539 if (!clang_isDeclaration(C.kind))
5540 return clang_getNullCursor();
5541
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005542 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005543 if (!D)
5544 return clang_getNullCursor();
5545
5546 switch (D->getKind()) {
5547 // Declaration kinds that don't really separate the notions of
5548 // declaration and definition.
5549 case Decl::Namespace:
5550 case Decl::Typedef:
5551 case Decl::TypeAlias:
5552 case Decl::TypeAliasTemplate:
5553 case Decl::TemplateTypeParm:
5554 case Decl::EnumConstant:
5555 case Decl::Field:
John McCall5e77d762013-04-16 07:28:30 +00005556 case Decl::MSProperty:
Guy Benyei11169dd2012-12-18 14:30:41 +00005557 case Decl::IndirectField:
5558 case Decl::ObjCIvar:
5559 case Decl::ObjCAtDefsField:
5560 case Decl::ImplicitParam:
5561 case Decl::ParmVar:
5562 case Decl::NonTypeTemplateParm:
5563 case Decl::TemplateTemplateParm:
5564 case Decl::ObjCCategoryImpl:
5565 case Decl::ObjCImplementation:
5566 case Decl::AccessSpec:
5567 case Decl::LinkageSpec:
5568 case Decl::ObjCPropertyImpl:
5569 case Decl::FileScopeAsm:
5570 case Decl::StaticAssert:
5571 case Decl::Block:
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00005572 case Decl::Captured:
Alexey Bataev4244be22016-02-11 05:35:55 +00005573 case Decl::OMPCapturedExpr:
Guy Benyei11169dd2012-12-18 14:30:41 +00005574 case Decl::Label: // FIXME: Is this right??
5575 case Decl::ClassScopeFunctionSpecialization:
5576 case Decl::Import:
Alexey Bataeva769e072013-03-22 06:34:35 +00005577 case Decl::OMPThreadPrivate:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00005578 case Decl::OMPDeclareReduction:
Douglas Gregor85f3f952015-07-07 03:57:15 +00005579 case Decl::ObjCTypeParam:
David Majnemerd9b1a4f2015-11-04 03:40:30 +00005580 case Decl::BuiltinTemplate:
Nico Weber66220292016-03-02 17:28:48 +00005581 case Decl::PragmaComment:
Nico Webercbbaeb12016-03-02 19:28:54 +00005582 case Decl::PragmaDetectMismatch:
Guy Benyei11169dd2012-12-18 14:30:41 +00005583 return C;
5584
5585 // Declaration kinds that don't make any sense here, but are
5586 // nonetheless harmless.
David Blaikief005d3c2013-02-22 17:44:58 +00005587 case Decl::Empty:
Guy Benyei11169dd2012-12-18 14:30:41 +00005588 case Decl::TranslationUnit:
Richard Smithf19e1272015-03-07 00:04:49 +00005589 case Decl::ExternCContext:
Guy Benyei11169dd2012-12-18 14:30:41 +00005590 break;
5591
5592 // Declaration kinds for which the definition is not resolvable.
5593 case Decl::UnresolvedUsingTypename:
5594 case Decl::UnresolvedUsingValue:
5595 break;
5596
5597 case Decl::UsingDirective:
5598 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
5599 TU);
5600
5601 case Decl::NamespaceAlias:
5602 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), TU);
5603
5604 case Decl::Enum:
5605 case Decl::Record:
5606 case Decl::CXXRecord:
5607 case Decl::ClassTemplateSpecialization:
5608 case Decl::ClassTemplatePartialSpecialization:
5609 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
5610 return MakeCXCursor(Def, TU);
5611 return clang_getNullCursor();
5612
5613 case Decl::Function:
5614 case Decl::CXXMethod:
5615 case Decl::CXXConstructor:
5616 case Decl::CXXDestructor:
5617 case Decl::CXXConversion: {
Craig Topper69186e72014-06-08 08:38:04 +00005618 const FunctionDecl *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005619 if (cast<FunctionDecl>(D)->getBody(Def))
Dmitri Gribenko9c256e32013-01-14 00:46:27 +00005620 return MakeCXCursor(Def, TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00005621 return clang_getNullCursor();
5622 }
5623
Larisse Voufo39a1e502013-08-06 01:03:05 +00005624 case Decl::Var:
5625 case Decl::VarTemplateSpecialization:
5626 case Decl::VarTemplatePartialSpecialization: {
Guy Benyei11169dd2012-12-18 14:30:41 +00005627 // Ask the variable if it has a definition.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005628 if (const VarDecl *Def = cast<VarDecl>(D)->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00005629 return MakeCXCursor(Def, TU);
5630 return clang_getNullCursor();
5631 }
5632
5633 case Decl::FunctionTemplate: {
Craig Topper69186e72014-06-08 08:38:04 +00005634 const FunctionDecl *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005635 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
5636 return MakeCXCursor(Def->getDescribedFunctionTemplate(), TU);
5637 return clang_getNullCursor();
5638 }
5639
5640 case Decl::ClassTemplate: {
5641 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
5642 ->getDefinition())
5643 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
5644 TU);
5645 return clang_getNullCursor();
5646 }
5647
Larisse Voufo39a1e502013-08-06 01:03:05 +00005648 case Decl::VarTemplate: {
5649 if (VarDecl *Def =
5650 cast<VarTemplateDecl>(D)->getTemplatedDecl()->getDefinition())
5651 return MakeCXCursor(cast<VarDecl>(Def)->getDescribedVarTemplate(), TU);
5652 return clang_getNullCursor();
5653 }
5654
Guy Benyei11169dd2012-12-18 14:30:41 +00005655 case Decl::Using:
5656 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
5657 D->getLocation(), TU);
5658
5659 case Decl::UsingShadow:
5660 return clang_getCursorDefinition(
5661 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
5662 TU));
5663
5664 case Decl::ObjCMethod: {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005665 const ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00005666 if (Method->isThisDeclarationADefinition())
5667 return C;
5668
5669 // Dig out the method definition in the associated
5670 // @implementation, if we have it.
5671 // FIXME: The ASTs should make finding the definition easier.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005672 if (const ObjCInterfaceDecl *Class
Guy Benyei11169dd2012-12-18 14:30:41 +00005673 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
5674 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
5675 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
5676 Method->isInstanceMethod()))
5677 if (Def->isThisDeclarationADefinition())
5678 return MakeCXCursor(Def, TU);
5679
5680 return clang_getNullCursor();
5681 }
5682
5683 case Decl::ObjCCategory:
5684 if (ObjCCategoryImplDecl *Impl
5685 = cast<ObjCCategoryDecl>(D)->getImplementation())
5686 return MakeCXCursor(Impl, TU);
5687 return clang_getNullCursor();
5688
5689 case Decl::ObjCProtocol:
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005690 if (const ObjCProtocolDecl *Def = cast<ObjCProtocolDecl>(D)->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00005691 return MakeCXCursor(Def, TU);
5692 return clang_getNullCursor();
5693
5694 case Decl::ObjCInterface: {
5695 // There are two notions of a "definition" for an Objective-C
5696 // class: the interface and its implementation. When we resolved a
5697 // reference to an Objective-C class, produce the @interface as
5698 // the definition; when we were provided with the interface,
5699 // produce the @implementation as the definition.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005700 const ObjCInterfaceDecl *IFace = cast<ObjCInterfaceDecl>(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00005701 if (WasReference) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005702 if (const ObjCInterfaceDecl *Def = IFace->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00005703 return MakeCXCursor(Def, TU);
5704 } else if (ObjCImplementationDecl *Impl = IFace->getImplementation())
5705 return MakeCXCursor(Impl, TU);
5706 return clang_getNullCursor();
5707 }
5708
5709 case Decl::ObjCProperty:
5710 // FIXME: We don't really know where to find the
5711 // ObjCPropertyImplDecls that implement this property.
5712 return clang_getNullCursor();
5713
5714 case Decl::ObjCCompatibleAlias:
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005715 if (const ObjCInterfaceDecl *Class
Guy Benyei11169dd2012-12-18 14:30:41 +00005716 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005717 if (const ObjCInterfaceDecl *Def = Class->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00005718 return MakeCXCursor(Def, TU);
5719
5720 return clang_getNullCursor();
5721
5722 case Decl::Friend:
5723 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
5724 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
5725 return clang_getNullCursor();
5726
5727 case Decl::FriendTemplate:
5728 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
5729 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
5730 return clang_getNullCursor();
5731 }
5732
5733 return clang_getNullCursor();
5734}
5735
5736unsigned clang_isCursorDefinition(CXCursor C) {
5737 if (!clang_isDeclaration(C.kind))
5738 return 0;
5739
5740 return clang_getCursorDefinition(C) == C;
5741}
5742
5743CXCursor clang_getCanonicalCursor(CXCursor C) {
5744 if (!clang_isDeclaration(C.kind))
5745 return C;
5746
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005747 if (const Decl *D = getCursorDecl(C)) {
5748 if (const ObjCCategoryImplDecl *CatImplD = dyn_cast<ObjCCategoryImplDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00005749 if (ObjCCategoryDecl *CatD = CatImplD->getCategoryDecl())
5750 return MakeCXCursor(CatD, getCursorTU(C));
5751
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005752 if (const ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
5753 if (const ObjCInterfaceDecl *IFD = ImplD->getClassInterface())
Guy Benyei11169dd2012-12-18 14:30:41 +00005754 return MakeCXCursor(IFD, getCursorTU(C));
5755
5756 return MakeCXCursor(D->getCanonicalDecl(), getCursorTU(C));
5757 }
5758
5759 return C;
5760}
5761
5762int clang_Cursor_getObjCSelectorIndex(CXCursor cursor) {
5763 return cxcursor::getSelectorIdentifierIndexAndLoc(cursor).first;
5764}
5765
5766unsigned clang_getNumOverloadedDecls(CXCursor C) {
5767 if (C.kind != CXCursor_OverloadedDeclRef)
5768 return 0;
5769
5770 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005771 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
Guy Benyei11169dd2012-12-18 14:30:41 +00005772 return E->getNumDecls();
5773
5774 if (OverloadedTemplateStorage *S
5775 = Storage.dyn_cast<OverloadedTemplateStorage*>())
5776 return S->size();
5777
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005778 const Decl *D = Storage.get<const Decl *>();
5779 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00005780 return Using->shadow_size();
5781
5782 return 0;
5783}
5784
5785CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
5786 if (cursor.kind != CXCursor_OverloadedDeclRef)
5787 return clang_getNullCursor();
5788
5789 if (index >= clang_getNumOverloadedDecls(cursor))
5790 return clang_getNullCursor();
5791
5792 CXTranslationUnit TU = getCursorTU(cursor);
5793 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005794 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
Guy Benyei11169dd2012-12-18 14:30:41 +00005795 return MakeCXCursor(E->decls_begin()[index], TU);
5796
5797 if (OverloadedTemplateStorage *S
5798 = Storage.dyn_cast<OverloadedTemplateStorage*>())
5799 return MakeCXCursor(S->begin()[index], TU);
5800
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005801 const Decl *D = Storage.get<const Decl *>();
5802 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005803 // FIXME: This is, unfortunately, linear time.
5804 UsingDecl::shadow_iterator Pos = Using->shadow_begin();
5805 std::advance(Pos, index);
5806 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), TU);
5807 }
5808
5809 return clang_getNullCursor();
5810}
5811
5812void clang_getDefinitionSpellingAndExtent(CXCursor C,
5813 const char **startBuf,
5814 const char **endBuf,
5815 unsigned *startLine,
5816 unsigned *startColumn,
5817 unsigned *endLine,
5818 unsigned *endColumn) {
5819 assert(getCursorDecl(C) && "CXCursor has null decl");
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005820 const FunctionDecl *FD = dyn_cast<FunctionDecl>(getCursorDecl(C));
Guy Benyei11169dd2012-12-18 14:30:41 +00005821 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
5822
5823 SourceManager &SM = FD->getASTContext().getSourceManager();
5824 *startBuf = SM.getCharacterData(Body->getLBracLoc());
5825 *endBuf = SM.getCharacterData(Body->getRBracLoc());
5826 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
5827 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
5828 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
5829 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
5830}
5831
5832
5833CXSourceRange clang_getCursorReferenceNameRange(CXCursor C, unsigned NameFlags,
5834 unsigned PieceIndex) {
5835 RefNamePieces Pieces;
5836
5837 switch (C.kind) {
5838 case CXCursor_MemberRefExpr:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00005839 if (const MemberExpr *E = dyn_cast<MemberExpr>(getCursorExpr(C)))
Guy Benyei11169dd2012-12-18 14:30:41 +00005840 Pieces = buildPieces(NameFlags, true, E->getMemberNameInfo(),
5841 E->getQualifierLoc().getSourceRange());
5842 break;
5843
5844 case CXCursor_DeclRefExpr:
James Y Knight04ec5bf2015-12-24 02:59:37 +00005845 if (const DeclRefExpr *E = dyn_cast<DeclRefExpr>(getCursorExpr(C))) {
5846 SourceRange TemplateArgLoc(E->getLAngleLoc(), E->getRAngleLoc());
5847 Pieces =
5848 buildPieces(NameFlags, false, E->getNameInfo(),
5849 E->getQualifierLoc().getSourceRange(), &TemplateArgLoc);
5850 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005851 break;
5852
5853 case CXCursor_CallExpr:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00005854 if (const CXXOperatorCallExpr *OCE =
Guy Benyei11169dd2012-12-18 14:30:41 +00005855 dyn_cast<CXXOperatorCallExpr>(getCursorExpr(C))) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00005856 const Expr *Callee = OCE->getCallee();
5857 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Callee))
Guy Benyei11169dd2012-12-18 14:30:41 +00005858 Callee = ICE->getSubExpr();
5859
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00005860 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Callee))
Guy Benyei11169dd2012-12-18 14:30:41 +00005861 Pieces = buildPieces(NameFlags, false, DRE->getNameInfo(),
5862 DRE->getQualifierLoc().getSourceRange());
5863 }
5864 break;
5865
5866 default:
5867 break;
5868 }
5869
5870 if (Pieces.empty()) {
5871 if (PieceIndex == 0)
5872 return clang_getCursorExtent(C);
5873 } else if (PieceIndex < Pieces.size()) {
5874 SourceRange R = Pieces[PieceIndex];
5875 if (R.isValid())
5876 return cxloc::translateSourceRange(getCursorContext(C), R);
5877 }
5878
5879 return clang_getNullRange();
5880}
5881
5882void clang_enableStackTraces(void) {
Richard Smithdfed58a2016-06-09 00:53:41 +00005883 // FIXME: Provide an argv0 here so we can find llvm-symbolizer.
5884 llvm::sys::PrintStackTraceOnErrorSignal(StringRef());
Guy Benyei11169dd2012-12-18 14:30:41 +00005885}
5886
5887void clang_executeOnThread(void (*fn)(void*), void *user_data,
5888 unsigned stack_size) {
5889 llvm::llvm_execute_on_thread(fn, user_data, stack_size);
5890}
5891
5892} // end: extern "C"
5893
5894//===----------------------------------------------------------------------===//
5895// Token-based Operations.
5896//===----------------------------------------------------------------------===//
5897
5898/* CXToken layout:
5899 * int_data[0]: a CXTokenKind
5900 * int_data[1]: starting token location
5901 * int_data[2]: token length
5902 * int_data[3]: reserved
5903 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
5904 * otherwise unused.
5905 */
5906extern "C" {
5907
5908CXTokenKind clang_getTokenKind(CXToken CXTok) {
5909 return static_cast<CXTokenKind>(CXTok.int_data[0]);
5910}
5911
5912CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
5913 switch (clang_getTokenKind(CXTok)) {
5914 case CXToken_Identifier:
5915 case CXToken_Keyword:
5916 // We know we have an IdentifierInfo*, so use that.
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005917 return cxstring::createRef(static_cast<IdentifierInfo *>(CXTok.ptr_data)
Guy Benyei11169dd2012-12-18 14:30:41 +00005918 ->getNameStart());
5919
5920 case CXToken_Literal: {
5921 // We have stashed the starting pointer in the ptr_data field. Use it.
5922 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00005923 return cxstring::createDup(StringRef(Text, CXTok.int_data[2]));
Guy Benyei11169dd2012-12-18 14:30:41 +00005924 }
5925
5926 case CXToken_Punctuation:
5927 case CXToken_Comment:
5928 break;
5929 }
5930
Dmitri Gribenko852d6222014-02-11 15:02:48 +00005931 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00005932 LOG_BAD_TU(TU);
5933 return cxstring::createEmpty();
5934 }
5935
Guy Benyei11169dd2012-12-18 14:30:41 +00005936 // We have to find the starting buffer pointer the hard way, by
5937 // deconstructing the source location.
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00005938 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00005939 if (!CXXUnit)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00005940 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00005941
5942 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
5943 std::pair<FileID, unsigned> LocInfo
5944 = CXXUnit->getSourceManager().getDecomposedSpellingLoc(Loc);
5945 bool Invalid = false;
5946 StringRef Buffer
5947 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
5948 if (Invalid)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00005949 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00005950
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00005951 return cxstring::createDup(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Guy Benyei11169dd2012-12-18 14:30:41 +00005952}
5953
5954CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00005955 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00005956 LOG_BAD_TU(TU);
5957 return clang_getNullLocation();
5958 }
5959
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00005960 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00005961 if (!CXXUnit)
5962 return clang_getNullLocation();
5963
5964 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
5965 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
5966}
5967
5968CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00005969 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00005970 LOG_BAD_TU(TU);
5971 return clang_getNullRange();
5972 }
5973
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00005974 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00005975 if (!CXXUnit)
5976 return clang_getNullRange();
5977
5978 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
5979 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
5980}
5981
5982static void getTokens(ASTUnit *CXXUnit, SourceRange Range,
5983 SmallVectorImpl<CXToken> &CXTokens) {
5984 SourceManager &SourceMgr = CXXUnit->getSourceManager();
5985 std::pair<FileID, unsigned> BeginLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00005986 = SourceMgr.getDecomposedSpellingLoc(Range.getBegin());
Guy Benyei11169dd2012-12-18 14:30:41 +00005987 std::pair<FileID, unsigned> EndLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00005988 = SourceMgr.getDecomposedSpellingLoc(Range.getEnd());
Guy Benyei11169dd2012-12-18 14:30:41 +00005989
5990 // Cannot tokenize across files.
5991 if (BeginLocInfo.first != EndLocInfo.first)
5992 return;
5993
5994 // Create a lexer
5995 bool Invalid = false;
5996 StringRef Buffer
5997 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
5998 if (Invalid)
5999 return;
6000
6001 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
6002 CXXUnit->getASTContext().getLangOpts(),
6003 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
6004 Lex.SetCommentRetentionState(true);
6005
6006 // Lex tokens until we hit the end of the range.
6007 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
6008 Token Tok;
6009 bool previousWasAt = false;
6010 do {
6011 // Lex the next token
6012 Lex.LexFromRawLexer(Tok);
6013 if (Tok.is(tok::eof))
6014 break;
6015
6016 // Initialize the CXToken.
6017 CXToken CXTok;
6018
6019 // - Common fields
6020 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
6021 CXTok.int_data[2] = Tok.getLength();
6022 CXTok.int_data[3] = 0;
6023
6024 // - Kind-specific fields
6025 if (Tok.isLiteral()) {
6026 CXTok.int_data[0] = CXToken_Literal;
Dmitri Gribenkof9304482013-01-23 15:56:07 +00006027 CXTok.ptr_data = const_cast<char *>(Tok.getLiteralData());
Guy Benyei11169dd2012-12-18 14:30:41 +00006028 } else if (Tok.is(tok::raw_identifier)) {
6029 // Lookup the identifier to determine whether we have a keyword.
6030 IdentifierInfo *II
6031 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok);
6032
6033 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
6034 CXTok.int_data[0] = CXToken_Keyword;
6035 }
6036 else {
6037 CXTok.int_data[0] = Tok.is(tok::identifier)
6038 ? CXToken_Identifier
6039 : CXToken_Keyword;
6040 }
6041 CXTok.ptr_data = II;
6042 } else if (Tok.is(tok::comment)) {
6043 CXTok.int_data[0] = CXToken_Comment;
Craig Topper69186e72014-06-08 08:38:04 +00006044 CXTok.ptr_data = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006045 } else {
6046 CXTok.int_data[0] = CXToken_Punctuation;
Craig Topper69186e72014-06-08 08:38:04 +00006047 CXTok.ptr_data = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006048 }
6049 CXTokens.push_back(CXTok);
6050 previousWasAt = Tok.is(tok::at);
6051 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
6052}
6053
6054void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
6055 CXToken **Tokens, unsigned *NumTokens) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00006056 LOG_FUNC_SECTION {
6057 *Log << TU << ' ' << Range;
6058 }
6059
Guy Benyei11169dd2012-12-18 14:30:41 +00006060 if (Tokens)
Craig Topper69186e72014-06-08 08:38:04 +00006061 *Tokens = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006062 if (NumTokens)
6063 *NumTokens = 0;
6064
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006065 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006066 LOG_BAD_TU(TU);
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00006067 return;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006068 }
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00006069
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006070 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006071 if (!CXXUnit || !Tokens || !NumTokens)
6072 return;
6073
6074 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
6075
6076 SourceRange R = cxloc::translateCXSourceRange(Range);
6077 if (R.isInvalid())
6078 return;
6079
6080 SmallVector<CXToken, 32> CXTokens;
6081 getTokens(CXXUnit, R, CXTokens);
6082
6083 if (CXTokens.empty())
6084 return;
6085
6086 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
6087 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
6088 *NumTokens = CXTokens.size();
6089}
6090
6091void clang_disposeTokens(CXTranslationUnit TU,
6092 CXToken *Tokens, unsigned NumTokens) {
6093 free(Tokens);
6094}
6095
6096} // end: extern "C"
6097
6098//===----------------------------------------------------------------------===//
6099// Token annotation APIs.
6100//===----------------------------------------------------------------------===//
6101
Guy Benyei11169dd2012-12-18 14:30:41 +00006102static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
6103 CXCursor parent,
6104 CXClientData client_data);
6105static bool AnnotateTokensPostChildrenVisitor(CXCursor cursor,
6106 CXClientData client_data);
6107
6108namespace {
6109class AnnotateTokensWorker {
Guy Benyei11169dd2012-12-18 14:30:41 +00006110 CXToken *Tokens;
6111 CXCursor *Cursors;
6112 unsigned NumTokens;
6113 unsigned TokIdx;
6114 unsigned PreprocessingTokIdx;
6115 CursorVisitor AnnotateVis;
6116 SourceManager &SrcMgr;
6117 bool HasContextSensitiveKeywords;
6118
6119 struct PostChildrenInfo {
6120 CXCursor Cursor;
6121 SourceRange CursorRange;
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006122 unsigned BeforeReachingCursorIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00006123 unsigned BeforeChildrenTokenIdx;
6124 };
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006125 SmallVector<PostChildrenInfo, 8> PostChildrenInfos;
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006126
6127 CXToken &getTok(unsigned Idx) {
6128 assert(Idx < NumTokens);
6129 return Tokens[Idx];
6130 }
6131 const CXToken &getTok(unsigned Idx) const {
6132 assert(Idx < NumTokens);
6133 return Tokens[Idx];
6134 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006135 bool MoreTokens() const { return TokIdx < NumTokens; }
6136 unsigned NextToken() const { return TokIdx; }
6137 void AdvanceToken() { ++TokIdx; }
6138 SourceLocation GetTokenLoc(unsigned tokI) {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006139 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[1]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006140 }
6141 bool isFunctionMacroToken(unsigned tokI) const {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006142 return getTok(tokI).int_data[3] != 0;
Guy Benyei11169dd2012-12-18 14:30:41 +00006143 }
6144 SourceLocation getFunctionMacroTokenLoc(unsigned tokI) const {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006145 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[3]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006146 }
6147
6148 void annotateAndAdvanceTokens(CXCursor, RangeComparisonResult, SourceRange);
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006149 bool annotateAndAdvanceFunctionMacroTokens(CXCursor, RangeComparisonResult,
Guy Benyei11169dd2012-12-18 14:30:41 +00006150 SourceRange);
6151
6152public:
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006153 AnnotateTokensWorker(CXToken *tokens, CXCursor *cursors, unsigned numTokens,
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006154 CXTranslationUnit TU, SourceRange RegionOfInterest)
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006155 : Tokens(tokens), Cursors(cursors),
Guy Benyei11169dd2012-12-18 14:30:41 +00006156 NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006157 AnnotateVis(TU,
Guy Benyei11169dd2012-12-18 14:30:41 +00006158 AnnotateTokensVisitor, this,
6159 /*VisitPreprocessorLast=*/true,
6160 /*VisitIncludedEntities=*/false,
6161 RegionOfInterest,
6162 /*VisitDeclsOnly=*/false,
6163 AnnotateTokensPostChildrenVisitor),
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006164 SrcMgr(cxtu::getASTUnit(TU)->getSourceManager()),
Guy Benyei11169dd2012-12-18 14:30:41 +00006165 HasContextSensitiveKeywords(false) { }
6166
6167 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
6168 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
6169 bool postVisitChildren(CXCursor cursor);
6170 void AnnotateTokens();
6171
6172 /// \brief Determine whether the annotator saw any cursors that have
6173 /// context-sensitive keywords.
6174 bool hasContextSensitiveKeywords() const {
6175 return HasContextSensitiveKeywords;
6176 }
6177
6178 ~AnnotateTokensWorker() {
6179 assert(PostChildrenInfos.empty());
6180 }
6181};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006182}
Guy Benyei11169dd2012-12-18 14:30:41 +00006183
6184void AnnotateTokensWorker::AnnotateTokens() {
6185 // Walk the AST within the region of interest, annotating tokens
6186 // along the way.
6187 AnnotateVis.visitFileRegion();
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006188}
Guy Benyei11169dd2012-12-18 14:30:41 +00006189
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006190static inline void updateCursorAnnotation(CXCursor &Cursor,
6191 const CXCursor &updateC) {
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006192 if (clang_isInvalid(updateC.kind) || !clang_isInvalid(Cursor.kind))
Guy Benyei11169dd2012-12-18 14:30:41 +00006193 return;
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006194 Cursor = updateC;
Guy Benyei11169dd2012-12-18 14:30:41 +00006195}
6196
6197/// \brief It annotates and advances tokens with a cursor until the comparison
6198//// between the cursor location and the source range is the same as
6199/// \arg compResult.
6200///
6201/// Pass RangeBefore to annotate tokens with a cursor until a range is reached.
6202/// Pass RangeOverlap to annotate tokens inside a range.
6203void AnnotateTokensWorker::annotateAndAdvanceTokens(CXCursor updateC,
6204 RangeComparisonResult compResult,
6205 SourceRange range) {
6206 while (MoreTokens()) {
6207 const unsigned I = NextToken();
6208 if (isFunctionMacroToken(I))
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006209 if (!annotateAndAdvanceFunctionMacroTokens(updateC, compResult, range))
6210 return;
Guy Benyei11169dd2012-12-18 14:30:41 +00006211
6212 SourceLocation TokLoc = GetTokenLoc(I);
6213 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006214 updateCursorAnnotation(Cursors[I], updateC);
Guy Benyei11169dd2012-12-18 14:30:41 +00006215 AdvanceToken();
6216 continue;
6217 }
6218 break;
6219 }
6220}
6221
6222/// \brief Special annotation handling for macro argument tokens.
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006223/// \returns true if it advanced beyond all macro tokens, false otherwise.
6224bool AnnotateTokensWorker::annotateAndAdvanceFunctionMacroTokens(
Guy Benyei11169dd2012-12-18 14:30:41 +00006225 CXCursor updateC,
6226 RangeComparisonResult compResult,
6227 SourceRange range) {
6228 assert(MoreTokens());
6229 assert(isFunctionMacroToken(NextToken()) &&
6230 "Should be called only for macro arg tokens");
6231
6232 // This works differently than annotateAndAdvanceTokens; because expanded
6233 // macro arguments can have arbitrary translation-unit source order, we do not
6234 // advance the token index one by one until a token fails the range test.
6235 // We only advance once past all of the macro arg tokens if all of them
6236 // pass the range test. If one of them fails we keep the token index pointing
6237 // at the start of the macro arg tokens so that the failing token will be
6238 // annotated by a subsequent annotation try.
6239
6240 bool atLeastOneCompFail = false;
6241
6242 unsigned I = NextToken();
6243 for (; I < NumTokens && isFunctionMacroToken(I); ++I) {
6244 SourceLocation TokLoc = getFunctionMacroTokenLoc(I);
6245 if (TokLoc.isFileID())
6246 continue; // not macro arg token, it's parens or comma.
6247 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
6248 if (clang_isInvalid(clang_getCursorKind(Cursors[I])))
6249 Cursors[I] = updateC;
6250 } else
6251 atLeastOneCompFail = true;
6252 }
6253
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006254 if (atLeastOneCompFail)
6255 return false;
6256
6257 TokIdx = I; // All of the tokens were handled, advance beyond all of them.
6258 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00006259}
6260
6261enum CXChildVisitResult
6262AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006263 SourceRange cursorRange = getRawCursorExtent(cursor);
6264 if (cursorRange.isInvalid())
6265 return CXChildVisit_Recurse;
6266
6267 if (!HasContextSensitiveKeywords) {
6268 // Objective-C properties can have context-sensitive keywords.
6269 if (cursor.kind == CXCursor_ObjCPropertyDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006270 if (const ObjCPropertyDecl *Property
Guy Benyei11169dd2012-12-18 14:30:41 +00006271 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(cursor)))
6272 HasContextSensitiveKeywords = Property->getPropertyAttributesAsWritten() != 0;
6273 }
6274 // Objective-C methods can have context-sensitive keywords.
6275 else if (cursor.kind == CXCursor_ObjCInstanceMethodDecl ||
6276 cursor.kind == CXCursor_ObjCClassMethodDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006277 if (const ObjCMethodDecl *Method
Guy Benyei11169dd2012-12-18 14:30:41 +00006278 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
6279 if (Method->getObjCDeclQualifier())
6280 HasContextSensitiveKeywords = true;
6281 else {
Aaron Ballman43b68be2014-03-07 17:50:17 +00006282 for (const auto *P : Method->params()) {
6283 if (P->getObjCDeclQualifier()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006284 HasContextSensitiveKeywords = true;
6285 break;
6286 }
6287 }
6288 }
6289 }
6290 }
6291 // C++ methods can have context-sensitive keywords.
6292 else if (cursor.kind == CXCursor_CXXMethod) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006293 if (const CXXMethodDecl *Method
Guy Benyei11169dd2012-12-18 14:30:41 +00006294 = dyn_cast_or_null<CXXMethodDecl>(getCursorDecl(cursor))) {
6295 if (Method->hasAttr<FinalAttr>() || Method->hasAttr<OverrideAttr>())
6296 HasContextSensitiveKeywords = true;
6297 }
6298 }
6299 // C++ classes can have context-sensitive keywords.
6300 else if (cursor.kind == CXCursor_StructDecl ||
6301 cursor.kind == CXCursor_ClassDecl ||
6302 cursor.kind == CXCursor_ClassTemplate ||
6303 cursor.kind == CXCursor_ClassTemplatePartialSpecialization) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006304 if (const Decl *D = getCursorDecl(cursor))
Guy Benyei11169dd2012-12-18 14:30:41 +00006305 if (D->hasAttr<FinalAttr>())
6306 HasContextSensitiveKeywords = true;
6307 }
6308 }
Argyrios Kyrtzidis990b3862013-06-04 18:24:30 +00006309
6310 // Don't override a property annotation with its getter/setter method.
6311 if (cursor.kind == CXCursor_ObjCInstanceMethodDecl &&
6312 parent.kind == CXCursor_ObjCPropertyDecl)
6313 return CXChildVisit_Continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00006314
6315 if (clang_isPreprocessing(cursor.kind)) {
6316 // Items in the preprocessing record are kept separate from items in
6317 // declarations, so we keep a separate token index.
6318 unsigned SavedTokIdx = TokIdx;
6319 TokIdx = PreprocessingTokIdx;
6320
6321 // Skip tokens up until we catch up to the beginning of the preprocessing
6322 // entry.
6323 while (MoreTokens()) {
6324 const unsigned I = NextToken();
6325 SourceLocation TokLoc = GetTokenLoc(I);
6326 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
6327 case RangeBefore:
6328 AdvanceToken();
6329 continue;
6330 case RangeAfter:
6331 case RangeOverlap:
6332 break;
6333 }
6334 break;
6335 }
6336
6337 // Look at all of the tokens within this range.
6338 while (MoreTokens()) {
6339 const unsigned I = NextToken();
6340 SourceLocation TokLoc = GetTokenLoc(I);
6341 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
6342 case RangeBefore:
6343 llvm_unreachable("Infeasible");
6344 case RangeAfter:
6345 break;
6346 case RangeOverlap:
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00006347 // For macro expansions, just note where the beginning of the macro
6348 // expansion occurs.
6349 if (cursor.kind == CXCursor_MacroExpansion) {
6350 if (TokLoc == cursorRange.getBegin())
6351 Cursors[I] = cursor;
6352 AdvanceToken();
6353 break;
6354 }
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006355 // We may have already annotated macro names inside macro definitions.
6356 if (Cursors[I].kind != CXCursor_MacroExpansion)
6357 Cursors[I] = cursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00006358 AdvanceToken();
Guy Benyei11169dd2012-12-18 14:30:41 +00006359 continue;
6360 }
6361 break;
6362 }
6363
6364 // Save the preprocessing token index; restore the non-preprocessing
6365 // token index.
6366 PreprocessingTokIdx = TokIdx;
6367 TokIdx = SavedTokIdx;
6368 return CXChildVisit_Recurse;
6369 }
6370
6371 if (cursorRange.isInvalid())
6372 return CXChildVisit_Continue;
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006373
6374 unsigned BeforeReachingCursorIdx = NextToken();
Guy Benyei11169dd2012-12-18 14:30:41 +00006375 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00006376 const enum CXCursorKind K = clang_getCursorKind(parent);
6377 const CXCursor updateC =
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006378 (clang_isInvalid(K) || K == CXCursor_TranslationUnit ||
6379 // Attributes are annotated out-of-order, skip tokens until we reach it.
6380 clang_isAttribute(cursor.kind))
Guy Benyei11169dd2012-12-18 14:30:41 +00006381 ? clang_getNullCursor() : parent;
6382
6383 annotateAndAdvanceTokens(updateC, RangeBefore, cursorRange);
6384
6385 // Avoid having the cursor of an expression "overwrite" the annotation of the
6386 // variable declaration that it belongs to.
6387 // This can happen for C++ constructor expressions whose range generally
6388 // include the variable declaration, e.g.:
6389 // MyCXXClass foo; // Make sure we don't annotate 'foo' as a CallExpr cursor.
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006390 if (clang_isExpression(cursorK) && MoreTokens()) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006391 const Expr *E = getCursorExpr(cursor);
Dmitri Gribenkoa1691182013-01-26 18:12:08 +00006392 if (const Decl *D = getCursorParentDecl(cursor)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006393 const unsigned I = NextToken();
6394 if (E->getLocStart().isValid() && D->getLocation().isValid() &&
6395 E->getLocStart() == D->getLocation() &&
6396 E->getLocStart() == GetTokenLoc(I)) {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006397 updateCursorAnnotation(Cursors[I], updateC);
Guy Benyei11169dd2012-12-18 14:30:41 +00006398 AdvanceToken();
6399 }
6400 }
6401 }
6402
6403 // Before recursing into the children keep some state that we are going
6404 // to use in the AnnotateTokensWorker::postVisitChildren callback to do some
6405 // extra work after the child nodes are visited.
6406 // Note that we don't call VisitChildren here to avoid traversing statements
6407 // code-recursively which can blow the stack.
6408
6409 PostChildrenInfo Info;
6410 Info.Cursor = cursor;
6411 Info.CursorRange = cursorRange;
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006412 Info.BeforeReachingCursorIdx = BeforeReachingCursorIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00006413 Info.BeforeChildrenTokenIdx = NextToken();
6414 PostChildrenInfos.push_back(Info);
6415
6416 return CXChildVisit_Recurse;
6417}
6418
6419bool AnnotateTokensWorker::postVisitChildren(CXCursor cursor) {
6420 if (PostChildrenInfos.empty())
6421 return false;
6422 const PostChildrenInfo &Info = PostChildrenInfos.back();
6423 if (!clang_equalCursors(Info.Cursor, cursor))
6424 return false;
6425
6426 const unsigned BeforeChildren = Info.BeforeChildrenTokenIdx;
6427 const unsigned AfterChildren = NextToken();
6428 SourceRange cursorRange = Info.CursorRange;
6429
6430 // Scan the tokens that are at the end of the cursor, but are not captured
6431 // but the child cursors.
6432 annotateAndAdvanceTokens(cursor, RangeOverlap, cursorRange);
6433
6434 // Scan the tokens that are at the beginning of the cursor, but are not
6435 // capture by the child cursors.
6436 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
6437 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
6438 break;
6439
6440 Cursors[I] = cursor;
6441 }
6442
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006443 // Attributes are annotated out-of-order, rewind TokIdx to when we first
6444 // encountered the attribute cursor.
6445 if (clang_isAttribute(cursor.kind))
6446 TokIdx = Info.BeforeReachingCursorIdx;
6447
Guy Benyei11169dd2012-12-18 14:30:41 +00006448 PostChildrenInfos.pop_back();
6449 return false;
6450}
6451
6452static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
6453 CXCursor parent,
6454 CXClientData client_data) {
6455 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
6456}
6457
6458static bool AnnotateTokensPostChildrenVisitor(CXCursor cursor,
6459 CXClientData client_data) {
6460 return static_cast<AnnotateTokensWorker*>(client_data)->
6461 postVisitChildren(cursor);
6462}
6463
6464namespace {
6465
6466/// \brief Uses the macro expansions in the preprocessing record to find
6467/// and mark tokens that are macro arguments. This info is used by the
6468/// AnnotateTokensWorker.
6469class MarkMacroArgTokensVisitor {
6470 SourceManager &SM;
6471 CXToken *Tokens;
6472 unsigned NumTokens;
6473 unsigned CurIdx;
6474
6475public:
6476 MarkMacroArgTokensVisitor(SourceManager &SM,
6477 CXToken *tokens, unsigned numTokens)
6478 : SM(SM), Tokens(tokens), NumTokens(numTokens), CurIdx(0) { }
6479
6480 CXChildVisitResult visit(CXCursor cursor, CXCursor parent) {
6481 if (cursor.kind != CXCursor_MacroExpansion)
6482 return CXChildVisit_Continue;
6483
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00006484 SourceRange macroRange = getCursorMacroExpansion(cursor).getSourceRange();
Guy Benyei11169dd2012-12-18 14:30:41 +00006485 if (macroRange.getBegin() == macroRange.getEnd())
6486 return CXChildVisit_Continue; // it's not a function macro.
6487
6488 for (; CurIdx < NumTokens; ++CurIdx) {
6489 if (!SM.isBeforeInTranslationUnit(getTokenLoc(CurIdx),
6490 macroRange.getBegin()))
6491 break;
6492 }
6493
6494 if (CurIdx == NumTokens)
6495 return CXChildVisit_Break;
6496
6497 for (; CurIdx < NumTokens; ++CurIdx) {
6498 SourceLocation tokLoc = getTokenLoc(CurIdx);
6499 if (!SM.isBeforeInTranslationUnit(tokLoc, macroRange.getEnd()))
6500 break;
6501
6502 setFunctionMacroTokenLoc(CurIdx, SM.getMacroArgExpandedLocation(tokLoc));
6503 }
6504
6505 if (CurIdx == NumTokens)
6506 return CXChildVisit_Break;
6507
6508 return CXChildVisit_Continue;
6509 }
6510
6511private:
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006512 CXToken &getTok(unsigned Idx) {
6513 assert(Idx < NumTokens);
6514 return Tokens[Idx];
6515 }
6516 const CXToken &getTok(unsigned Idx) const {
6517 assert(Idx < NumTokens);
6518 return Tokens[Idx];
6519 }
6520
Guy Benyei11169dd2012-12-18 14:30:41 +00006521 SourceLocation getTokenLoc(unsigned tokI) {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006522 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[1]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006523 }
6524
6525 void setFunctionMacroTokenLoc(unsigned tokI, SourceLocation loc) {
6526 // The third field is reserved and currently not used. Use it here
6527 // to mark macro arg expanded tokens with their expanded locations.
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006528 getTok(tokI).int_data[3] = loc.getRawEncoding();
Guy Benyei11169dd2012-12-18 14:30:41 +00006529 }
6530};
6531
6532} // end anonymous namespace
6533
6534static CXChildVisitResult
6535MarkMacroArgTokensVisitorDelegate(CXCursor cursor, CXCursor parent,
6536 CXClientData client_data) {
6537 return static_cast<MarkMacroArgTokensVisitor*>(client_data)->visit(cursor,
6538 parent);
6539}
6540
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006541/// \brief Used by \c annotatePreprocessorTokens.
6542/// \returns true if lexing was finished, false otherwise.
6543static bool lexNext(Lexer &Lex, Token &Tok,
6544 unsigned &NextIdx, unsigned NumTokens) {
6545 if (NextIdx >= NumTokens)
6546 return true;
6547
6548 ++NextIdx;
6549 Lex.LexFromRawLexer(Tok);
Alexander Kornienko1a9f1842015-12-28 15:24:08 +00006550 return Tok.is(tok::eof);
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006551}
6552
Guy Benyei11169dd2012-12-18 14:30:41 +00006553static void annotatePreprocessorTokens(CXTranslationUnit TU,
6554 SourceRange RegionOfInterest,
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006555 CXCursor *Cursors,
6556 CXToken *Tokens,
6557 unsigned NumTokens) {
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006558 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006559
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00006560 Preprocessor &PP = CXXUnit->getPreprocessor();
Guy Benyei11169dd2012-12-18 14:30:41 +00006561 SourceManager &SourceMgr = CXXUnit->getSourceManager();
6562 std::pair<FileID, unsigned> BeginLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00006563 = SourceMgr.getDecomposedSpellingLoc(RegionOfInterest.getBegin());
Guy Benyei11169dd2012-12-18 14:30:41 +00006564 std::pair<FileID, unsigned> EndLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00006565 = SourceMgr.getDecomposedSpellingLoc(RegionOfInterest.getEnd());
Guy Benyei11169dd2012-12-18 14:30:41 +00006566
6567 if (BeginLocInfo.first != EndLocInfo.first)
6568 return;
6569
6570 StringRef Buffer;
6571 bool Invalid = false;
6572 Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
6573 if (Buffer.empty() || Invalid)
6574 return;
6575
6576 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
6577 CXXUnit->getASTContext().getLangOpts(),
6578 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
6579 Buffer.end());
6580 Lex.SetCommentRetentionState(true);
6581
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006582 unsigned NextIdx = 0;
Guy Benyei11169dd2012-12-18 14:30:41 +00006583 // Lex tokens in raw mode until we hit the end of the range, to avoid
6584 // entering #includes or expanding macros.
6585 while (true) {
6586 Token Tok;
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006587 if (lexNext(Lex, Tok, NextIdx, NumTokens))
6588 break;
6589 unsigned TokIdx = NextIdx-1;
6590 assert(Tok.getLocation() ==
6591 SourceLocation::getFromRawEncoding(Tokens[TokIdx].int_data[1]));
Guy Benyei11169dd2012-12-18 14:30:41 +00006592
6593 reprocess:
6594 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006595 // We have found a preprocessing directive. Annotate the tokens
6596 // appropriately.
Guy Benyei11169dd2012-12-18 14:30:41 +00006597 //
6598 // FIXME: Some simple tests here could identify macro definitions and
6599 // #undefs, to provide specific cursor kinds for those.
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006600
6601 SourceLocation BeginLoc = Tok.getLocation();
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00006602 if (lexNext(Lex, Tok, NextIdx, NumTokens))
6603 break;
6604
Craig Topper69186e72014-06-08 08:38:04 +00006605 MacroInfo *MI = nullptr;
Alp Toker2d57cea2014-05-17 04:53:25 +00006606 if (Tok.is(tok::raw_identifier) && Tok.getRawIdentifier() == "define") {
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00006607 if (lexNext(Lex, Tok, NextIdx, NumTokens))
6608 break;
6609
6610 if (Tok.is(tok::raw_identifier)) {
Alp Toker2d57cea2014-05-17 04:53:25 +00006611 IdentifierInfo &II =
6612 PP.getIdentifierTable().get(Tok.getRawIdentifier());
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00006613 SourceLocation MappedTokLoc =
6614 CXXUnit->mapLocationToPreamble(Tok.getLocation());
6615 MI = getMacroInfo(II, MappedTokLoc, TU);
6616 }
6617 }
6618
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006619 bool finished = false;
Guy Benyei11169dd2012-12-18 14:30:41 +00006620 do {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006621 if (lexNext(Lex, Tok, NextIdx, NumTokens)) {
6622 finished = true;
6623 break;
6624 }
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00006625 // If we are in a macro definition, check if the token was ever a
6626 // macro name and annotate it if that's the case.
6627 if (MI) {
6628 SourceLocation SaveLoc = Tok.getLocation();
6629 Tok.setLocation(CXXUnit->mapLocationToPreamble(SaveLoc));
Richard Smith66a81862015-05-04 02:25:31 +00006630 MacroDefinitionRecord *MacroDef =
6631 checkForMacroInMacroDefinition(MI, Tok, TU);
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00006632 Tok.setLocation(SaveLoc);
6633 if (MacroDef)
Richard Smith66a81862015-05-04 02:25:31 +00006634 Cursors[NextIdx - 1] =
6635 MakeMacroExpansionCursor(MacroDef, Tok.getLocation(), TU);
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00006636 }
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006637 } while (!Tok.isAtStartOfLine());
6638
6639 unsigned LastIdx = finished ? NextIdx-1 : NextIdx-2;
6640 assert(TokIdx <= LastIdx);
6641 SourceLocation EndLoc =
6642 SourceLocation::getFromRawEncoding(Tokens[LastIdx].int_data[1]);
6643 CXCursor Cursor =
6644 MakePreprocessingDirectiveCursor(SourceRange(BeginLoc, EndLoc), TU);
6645
6646 for (; TokIdx <= LastIdx; ++TokIdx)
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00006647 updateCursorAnnotation(Cursors[TokIdx], Cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00006648
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006649 if (finished)
6650 break;
6651 goto reprocess;
Guy Benyei11169dd2012-12-18 14:30:41 +00006652 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006653 }
6654}
6655
6656// This gets run a separate thread to avoid stack blowout.
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00006657static void clang_annotateTokensImpl(CXTranslationUnit TU, ASTUnit *CXXUnit,
6658 CXToken *Tokens, unsigned NumTokens,
6659 CXCursor *Cursors) {
Dmitri Gribenko183436e2013-01-26 21:49:50 +00006660 CIndexer *CXXIdx = TU->CIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00006661 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing))
6662 setThreadBackgroundPriority();
6663
6664 // Determine the region of interest, which contains all of the tokens.
6665 SourceRange RegionOfInterest;
6666 RegionOfInterest.setBegin(
6667 cxloc::translateSourceLocation(clang_getTokenLocation(TU, Tokens[0])));
6668 RegionOfInterest.setEnd(
6669 cxloc::translateSourceLocation(clang_getTokenLocation(TU,
6670 Tokens[NumTokens-1])));
6671
Guy Benyei11169dd2012-12-18 14:30:41 +00006672 // Relex the tokens within the source range to look for preprocessing
6673 // directives.
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006674 annotatePreprocessorTokens(TU, RegionOfInterest, Cursors, Tokens, NumTokens);
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00006675
6676 // If begin location points inside a macro argument, set it to the expansion
6677 // location so we can have the full context when annotating semantically.
6678 {
6679 SourceManager &SM = CXXUnit->getSourceManager();
6680 SourceLocation Loc =
6681 SM.getMacroArgExpandedLocation(RegionOfInterest.getBegin());
6682 if (Loc.isMacroID())
6683 RegionOfInterest.setBegin(SM.getExpansionLoc(Loc));
6684 }
6685
Guy Benyei11169dd2012-12-18 14:30:41 +00006686 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
6687 // Search and mark tokens that are macro argument expansions.
6688 MarkMacroArgTokensVisitor Visitor(CXXUnit->getSourceManager(),
6689 Tokens, NumTokens);
6690 CursorVisitor MacroArgMarker(TU,
6691 MarkMacroArgTokensVisitorDelegate, &Visitor,
6692 /*VisitPreprocessorLast=*/true,
6693 /*VisitIncludedEntities=*/false,
6694 RegionOfInterest);
6695 MacroArgMarker.visitPreprocessedEntitiesInRegion();
6696 }
6697
6698 // Annotate all of the source locations in the region of interest that map to
6699 // a specific cursor.
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006700 AnnotateTokensWorker W(Tokens, Cursors, NumTokens, TU, RegionOfInterest);
Guy Benyei11169dd2012-12-18 14:30:41 +00006701
6702 // FIXME: We use a ridiculous stack size here because the data-recursion
6703 // algorithm uses a large stack frame than the non-data recursive version,
6704 // and AnnotationTokensWorker currently transforms the data-recursion
6705 // algorithm back into a traditional recursion by explicitly calling
6706 // VisitChildren(). We will need to remove this explicit recursive call.
6707 W.AnnotateTokens();
6708
6709 // If we ran into any entities that involve context-sensitive keywords,
6710 // take another pass through the tokens to mark them as such.
6711 if (W.hasContextSensitiveKeywords()) {
6712 for (unsigned I = 0; I != NumTokens; ++I) {
6713 if (clang_getTokenKind(Tokens[I]) != CXToken_Identifier)
6714 continue;
6715
6716 if (Cursors[I].kind == CXCursor_ObjCPropertyDecl) {
6717 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006718 if (const ObjCPropertyDecl *Property
Guy Benyei11169dd2012-12-18 14:30:41 +00006719 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(Cursors[I]))) {
6720 if (Property->getPropertyAttributesAsWritten() != 0 &&
6721 llvm::StringSwitch<bool>(II->getName())
6722 .Case("readonly", true)
6723 .Case("assign", true)
6724 .Case("unsafe_unretained", true)
6725 .Case("readwrite", true)
6726 .Case("retain", true)
6727 .Case("copy", true)
6728 .Case("nonatomic", true)
6729 .Case("atomic", true)
6730 .Case("getter", true)
6731 .Case("setter", true)
6732 .Case("strong", true)
6733 .Case("weak", true)
Manman Ren04fd4d82016-05-31 23:22:04 +00006734 .Case("class", true)
Guy Benyei11169dd2012-12-18 14:30:41 +00006735 .Default(false))
6736 Tokens[I].int_data[0] = CXToken_Keyword;
6737 }
6738 continue;
6739 }
6740
6741 if (Cursors[I].kind == CXCursor_ObjCInstanceMethodDecl ||
6742 Cursors[I].kind == CXCursor_ObjCClassMethodDecl) {
6743 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
6744 if (llvm::StringSwitch<bool>(II->getName())
6745 .Case("in", true)
6746 .Case("out", true)
6747 .Case("inout", true)
6748 .Case("oneway", true)
6749 .Case("bycopy", true)
6750 .Case("byref", true)
6751 .Default(false))
6752 Tokens[I].int_data[0] = CXToken_Keyword;
6753 continue;
6754 }
6755
6756 if (Cursors[I].kind == CXCursor_CXXFinalAttr ||
6757 Cursors[I].kind == CXCursor_CXXOverrideAttr) {
6758 Tokens[I].int_data[0] = CXToken_Keyword;
6759 continue;
6760 }
6761 }
6762 }
6763}
6764
6765extern "C" {
6766
6767void clang_annotateTokens(CXTranslationUnit TU,
6768 CXToken *Tokens, unsigned NumTokens,
6769 CXCursor *Cursors) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006770 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006771 LOG_BAD_TU(TU);
6772 return;
6773 }
6774 if (NumTokens == 0 || !Tokens || !Cursors) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00006775 LOG_FUNC_SECTION { *Log << "<null input>"; }
Guy Benyei11169dd2012-12-18 14:30:41 +00006776 return;
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00006777 }
6778
6779 LOG_FUNC_SECTION {
6780 *Log << TU << ' ';
6781 CXSourceLocation bloc = clang_getTokenLocation(TU, Tokens[0]);
6782 CXSourceLocation eloc = clang_getTokenLocation(TU, Tokens[NumTokens-1]);
6783 *Log << clang_getRange(bloc, eloc);
6784 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006785
6786 // Any token we don't specifically annotate will have a NULL cursor.
6787 CXCursor C = clang_getNullCursor();
6788 for (unsigned I = 0; I != NumTokens; ++I)
6789 Cursors[I] = C;
6790
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006791 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006792 if (!CXXUnit)
6793 return;
6794
6795 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00006796
6797 auto AnnotateTokensImpl = [=]() {
6798 clang_annotateTokensImpl(TU, CXXUnit, Tokens, NumTokens, Cursors);
6799 };
Guy Benyei11169dd2012-12-18 14:30:41 +00006800 llvm::CrashRecoveryContext CRC;
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00006801 if (!RunSafely(CRC, AnnotateTokensImpl, GetSafetyThreadStackSize() * 2)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006802 fprintf(stderr, "libclang: crash detected while annotating tokens\n");
6803 }
6804}
6805
6806} // end: extern "C"
6807
6808//===----------------------------------------------------------------------===//
6809// Operations for querying linkage of a cursor.
6810//===----------------------------------------------------------------------===//
6811
6812extern "C" {
6813CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
6814 if (!clang_isDeclaration(cursor.kind))
6815 return CXLinkage_Invalid;
6816
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006817 const Decl *D = cxcursor::getCursorDecl(cursor);
6818 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
Rafael Espindola3ae00052013-05-13 00:12:11 +00006819 switch (ND->getLinkageInternal()) {
Rafael Espindola50df3a02013-05-25 17:16:20 +00006820 case NoLinkage:
6821 case VisibleNoLinkage: return CXLinkage_NoLinkage;
Guy Benyei11169dd2012-12-18 14:30:41 +00006822 case InternalLinkage: return CXLinkage_Internal;
6823 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
6824 case ExternalLinkage: return CXLinkage_External;
6825 };
6826
6827 return CXLinkage_Invalid;
6828}
6829} // end: extern "C"
6830
6831//===----------------------------------------------------------------------===//
Ehsan Akhgarib743de72016-05-31 15:55:51 +00006832// Operations for querying visibility of a cursor.
6833//===----------------------------------------------------------------------===//
6834
6835extern "C" {
6836CXVisibilityKind clang_getCursorVisibility(CXCursor cursor) {
6837 if (!clang_isDeclaration(cursor.kind))
6838 return CXVisibility_Invalid;
6839
6840 const Decl *D = cxcursor::getCursorDecl(cursor);
6841 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
6842 switch (ND->getVisibility()) {
6843 case HiddenVisibility: return CXVisibility_Hidden;
6844 case ProtectedVisibility: return CXVisibility_Protected;
6845 case DefaultVisibility: return CXVisibility_Default;
6846 };
6847
6848 return CXVisibility_Invalid;
6849}
6850} // end: extern "C"
6851
6852//===----------------------------------------------------------------------===//
Guy Benyei11169dd2012-12-18 14:30:41 +00006853// Operations for querying language of a cursor.
6854//===----------------------------------------------------------------------===//
6855
6856static CXLanguageKind getDeclLanguage(const Decl *D) {
6857 if (!D)
6858 return CXLanguage_C;
6859
6860 switch (D->getKind()) {
6861 default:
6862 break;
6863 case Decl::ImplicitParam:
6864 case Decl::ObjCAtDefsField:
6865 case Decl::ObjCCategory:
6866 case Decl::ObjCCategoryImpl:
6867 case Decl::ObjCCompatibleAlias:
6868 case Decl::ObjCImplementation:
6869 case Decl::ObjCInterface:
6870 case Decl::ObjCIvar:
6871 case Decl::ObjCMethod:
6872 case Decl::ObjCProperty:
6873 case Decl::ObjCPropertyImpl:
6874 case Decl::ObjCProtocol:
Douglas Gregor85f3f952015-07-07 03:57:15 +00006875 case Decl::ObjCTypeParam:
Guy Benyei11169dd2012-12-18 14:30:41 +00006876 return CXLanguage_ObjC;
6877 case Decl::CXXConstructor:
6878 case Decl::CXXConversion:
6879 case Decl::CXXDestructor:
6880 case Decl::CXXMethod:
6881 case Decl::CXXRecord:
6882 case Decl::ClassTemplate:
6883 case Decl::ClassTemplatePartialSpecialization:
6884 case Decl::ClassTemplateSpecialization:
6885 case Decl::Friend:
6886 case Decl::FriendTemplate:
6887 case Decl::FunctionTemplate:
6888 case Decl::LinkageSpec:
6889 case Decl::Namespace:
6890 case Decl::NamespaceAlias:
6891 case Decl::NonTypeTemplateParm:
6892 case Decl::StaticAssert:
6893 case Decl::TemplateTemplateParm:
6894 case Decl::TemplateTypeParm:
6895 case Decl::UnresolvedUsingTypename:
6896 case Decl::UnresolvedUsingValue:
6897 case Decl::Using:
6898 case Decl::UsingDirective:
6899 case Decl::UsingShadow:
6900 return CXLanguage_CPlusPlus;
6901 }
6902
6903 return CXLanguage_C;
6904}
6905
6906extern "C" {
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00006907
6908static CXAvailabilityKind getCursorAvailabilityForDecl(const Decl *D) {
6909 if (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted())
Manuel Klimek8e3a7ed2015-09-25 17:53:16 +00006910 return CXAvailability_NotAvailable;
Guy Benyei11169dd2012-12-18 14:30:41 +00006911
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00006912 switch (D->getAvailability()) {
6913 case AR_Available:
6914 case AR_NotYetIntroduced:
6915 if (const EnumConstantDecl *EnumConst = dyn_cast<EnumConstantDecl>(D))
Benjamin Kramer656363d2013-10-15 18:53:18 +00006916 return getCursorAvailabilityForDecl(
6917 cast<Decl>(EnumConst->getDeclContext()));
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00006918 return CXAvailability_Available;
6919
6920 case AR_Deprecated:
6921 return CXAvailability_Deprecated;
6922
6923 case AR_Unavailable:
6924 return CXAvailability_NotAvailable;
6925 }
Benjamin Kramer656363d2013-10-15 18:53:18 +00006926
6927 llvm_unreachable("Unknown availability kind!");
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00006928}
6929
Guy Benyei11169dd2012-12-18 14:30:41 +00006930enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
6931 if (clang_isDeclaration(cursor.kind))
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00006932 if (const Decl *D = cxcursor::getCursorDecl(cursor))
6933 return getCursorAvailabilityForDecl(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00006934
6935 return CXAvailability_Available;
6936}
6937
6938static CXVersion convertVersion(VersionTuple In) {
6939 CXVersion Out = { -1, -1, -1 };
6940 if (In.empty())
6941 return Out;
6942
6943 Out.Major = In.getMajor();
6944
NAKAMURA Takumic2b5d1f2013-02-21 02:32:34 +00006945 Optional<unsigned> Minor = In.getMinor();
6946 if (Minor.hasValue())
Guy Benyei11169dd2012-12-18 14:30:41 +00006947 Out.Minor = *Minor;
6948 else
6949 return Out;
6950
NAKAMURA Takumic2b5d1f2013-02-21 02:32:34 +00006951 Optional<unsigned> Subminor = In.getSubminor();
6952 if (Subminor.hasValue())
Guy Benyei11169dd2012-12-18 14:30:41 +00006953 Out.Subminor = *Subminor;
6954
6955 return Out;
6956}
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00006957
6958static int getCursorPlatformAvailabilityForDecl(const Decl *D,
6959 int *always_deprecated,
6960 CXString *deprecated_message,
6961 int *always_unavailable,
6962 CXString *unavailable_message,
6963 CXPlatformAvailability *availability,
6964 int availability_size) {
6965 bool HadAvailAttr = false;
6966 int N = 0;
Aaron Ballmanb97112e2014-03-08 22:19:01 +00006967 for (auto A : D->attrs()) {
6968 if (DeprecatedAttr *Deprecated = dyn_cast<DeprecatedAttr>(A)) {
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00006969 HadAvailAttr = true;
6970 if (always_deprecated)
6971 *always_deprecated = 1;
Nico Weberaacf0312014-04-24 05:16:45 +00006972 if (deprecated_message) {
Argyrios Kyrtzidisedfe07f2014-04-24 06:05:40 +00006973 clang_disposeString(*deprecated_message);
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00006974 *deprecated_message = cxstring::createDup(Deprecated->getMessage());
Nico Weberaacf0312014-04-24 05:16:45 +00006975 }
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00006976 continue;
6977 }
6978
Aaron Ballmanb97112e2014-03-08 22:19:01 +00006979 if (UnavailableAttr *Unavailable = dyn_cast<UnavailableAttr>(A)) {
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00006980 HadAvailAttr = true;
6981 if (always_unavailable)
6982 *always_unavailable = 1;
6983 if (unavailable_message) {
Argyrios Kyrtzidisedfe07f2014-04-24 06:05:40 +00006984 clang_disposeString(*unavailable_message);
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00006985 *unavailable_message = cxstring::createDup(Unavailable->getMessage());
6986 }
6987 continue;
6988 }
6989
Aaron Ballmanb97112e2014-03-08 22:19:01 +00006990 if (AvailabilityAttr *Avail = dyn_cast<AvailabilityAttr>(A)) {
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00006991 HadAvailAttr = true;
6992 if (N < availability_size) {
6993 availability[N].Platform
6994 = cxstring::createDup(Avail->getPlatform()->getName());
6995 availability[N].Introduced = convertVersion(Avail->getIntroduced());
6996 availability[N].Deprecated = convertVersion(Avail->getDeprecated());
6997 availability[N].Obsoleted = convertVersion(Avail->getObsoleted());
6998 availability[N].Unavailable = Avail->getUnavailable();
6999 availability[N].Message = cxstring::createDup(Avail->getMessage());
7000 }
7001 ++N;
7002 }
7003 }
7004
7005 if (!HadAvailAttr)
7006 if (const EnumConstantDecl *EnumConst = dyn_cast<EnumConstantDecl>(D))
7007 return getCursorPlatformAvailabilityForDecl(
7008 cast<Decl>(EnumConst->getDeclContext()),
7009 always_deprecated,
7010 deprecated_message,
7011 always_unavailable,
7012 unavailable_message,
7013 availability,
7014 availability_size);
Guy Benyei11169dd2012-12-18 14:30:41 +00007015
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007016 return N;
7017}
7018
Guy Benyei11169dd2012-12-18 14:30:41 +00007019int clang_getCursorPlatformAvailability(CXCursor cursor,
7020 int *always_deprecated,
7021 CXString *deprecated_message,
7022 int *always_unavailable,
7023 CXString *unavailable_message,
7024 CXPlatformAvailability *availability,
7025 int availability_size) {
7026 if (always_deprecated)
7027 *always_deprecated = 0;
7028 if (deprecated_message)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00007029 *deprecated_message = cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00007030 if (always_unavailable)
7031 *always_unavailable = 0;
7032 if (unavailable_message)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00007033 *unavailable_message = cxstring::createEmpty();
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007034
Guy Benyei11169dd2012-12-18 14:30:41 +00007035 if (!clang_isDeclaration(cursor.kind))
7036 return 0;
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007037
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007038 const Decl *D = cxcursor::getCursorDecl(cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00007039 if (!D)
7040 return 0;
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007041
7042 return getCursorPlatformAvailabilityForDecl(D, always_deprecated,
7043 deprecated_message,
7044 always_unavailable,
7045 unavailable_message,
7046 availability,
7047 availability_size);
Guy Benyei11169dd2012-12-18 14:30:41 +00007048}
7049
7050void clang_disposeCXPlatformAvailability(CXPlatformAvailability *availability) {
7051 clang_disposeString(availability->Platform);
7052 clang_disposeString(availability->Message);
7053}
7054
7055CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
7056 if (clang_isDeclaration(cursor.kind))
7057 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
7058
7059 return CXLanguage_Invalid;
7060}
7061
7062 /// \brief If the given cursor is the "templated" declaration
7063 /// descibing a class or function template, return the class or
7064 /// function template.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007065static const Decl *maybeGetTemplateCursor(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007066 if (!D)
Craig Topper69186e72014-06-08 08:38:04 +00007067 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007068
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007069 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00007070 if (FunctionTemplateDecl *FunTmpl = FD->getDescribedFunctionTemplate())
7071 return FunTmpl;
7072
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007073 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00007074 if (ClassTemplateDecl *ClassTmpl = RD->getDescribedClassTemplate())
7075 return ClassTmpl;
7076
7077 return D;
7078}
7079
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00007080
7081enum CX_StorageClass clang_Cursor_getStorageClass(CXCursor C) {
7082 StorageClass sc = SC_None;
7083 const Decl *D = getCursorDecl(C);
7084 if (D) {
7085 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7086 sc = FD->getStorageClass();
7087 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7088 sc = VD->getStorageClass();
7089 } else {
7090 return CX_SC_Invalid;
7091 }
7092 } else {
7093 return CX_SC_Invalid;
7094 }
7095 switch (sc) {
7096 case SC_None:
7097 return CX_SC_None;
7098 case SC_Extern:
7099 return CX_SC_Extern;
7100 case SC_Static:
7101 return CX_SC_Static;
7102 case SC_PrivateExtern:
7103 return CX_SC_PrivateExtern;
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00007104 case SC_Auto:
7105 return CX_SC_Auto;
7106 case SC_Register:
7107 return CX_SC_Register;
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00007108 }
Kaelyn Takataab61e702014-10-15 18:03:26 +00007109 llvm_unreachable("Unhandled storage class!");
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00007110}
7111
Guy Benyei11169dd2012-12-18 14:30:41 +00007112CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
7113 if (clang_isDeclaration(cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007114 if (const Decl *D = getCursorDecl(cursor)) {
7115 const DeclContext *DC = D->getDeclContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00007116 if (!DC)
7117 return clang_getNullCursor();
7118
7119 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
7120 getCursorTU(cursor));
7121 }
7122 }
7123
7124 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007125 if (const Decl *D = getCursorDecl(cursor))
Guy Benyei11169dd2012-12-18 14:30:41 +00007126 return MakeCXCursor(D, getCursorTU(cursor));
7127 }
7128
7129 return clang_getNullCursor();
7130}
7131
7132CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
7133 if (clang_isDeclaration(cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007134 if (const Decl *D = getCursorDecl(cursor)) {
7135 const DeclContext *DC = D->getLexicalDeclContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00007136 if (!DC)
7137 return clang_getNullCursor();
7138
7139 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
7140 getCursorTU(cursor));
7141 }
7142 }
7143
7144 // FIXME: Note that we can't easily compute the lexical context of a
7145 // statement or expression, so we return nothing.
7146 return clang_getNullCursor();
7147}
7148
7149CXFile clang_getIncludedFile(CXCursor cursor) {
7150 if (cursor.kind != CXCursor_InclusionDirective)
Craig Topper69186e72014-06-08 08:38:04 +00007151 return nullptr;
7152
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00007153 const InclusionDirective *ID = getCursorInclusionDirective(cursor);
Dmitri Gribenkof9304482013-01-23 15:56:07 +00007154 return const_cast<FileEntry *>(ID->getFile());
Guy Benyei11169dd2012-12-18 14:30:41 +00007155}
7156
Argyrios Kyrtzidis9adfd8a2013-04-18 22:15:49 +00007157unsigned clang_Cursor_getObjCPropertyAttributes(CXCursor C, unsigned reserved) {
7158 if (C.kind != CXCursor_ObjCPropertyDecl)
7159 return CXObjCPropertyAttr_noattr;
7160
7161 unsigned Result = CXObjCPropertyAttr_noattr;
7162 const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(getCursorDecl(C));
7163 ObjCPropertyDecl::PropertyAttributeKind Attr =
7164 PD->getPropertyAttributesAsWritten();
7165
7166#define SET_CXOBJCPROP_ATTR(A) \
7167 if (Attr & ObjCPropertyDecl::OBJC_PR_##A) \
7168 Result |= CXObjCPropertyAttr_##A
7169 SET_CXOBJCPROP_ATTR(readonly);
7170 SET_CXOBJCPROP_ATTR(getter);
7171 SET_CXOBJCPROP_ATTR(assign);
7172 SET_CXOBJCPROP_ATTR(readwrite);
7173 SET_CXOBJCPROP_ATTR(retain);
7174 SET_CXOBJCPROP_ATTR(copy);
7175 SET_CXOBJCPROP_ATTR(nonatomic);
7176 SET_CXOBJCPROP_ATTR(setter);
7177 SET_CXOBJCPROP_ATTR(atomic);
7178 SET_CXOBJCPROP_ATTR(weak);
7179 SET_CXOBJCPROP_ATTR(strong);
7180 SET_CXOBJCPROP_ATTR(unsafe_unretained);
Manman Ren04fd4d82016-05-31 23:22:04 +00007181 SET_CXOBJCPROP_ATTR(class);
Argyrios Kyrtzidis9adfd8a2013-04-18 22:15:49 +00007182#undef SET_CXOBJCPROP_ATTR
7183
7184 return Result;
7185}
7186
Argyrios Kyrtzidis9d9bc012013-04-18 23:29:12 +00007187unsigned clang_Cursor_getObjCDeclQualifiers(CXCursor C) {
7188 if (!clang_isDeclaration(C.kind))
7189 return CXObjCDeclQualifier_None;
7190
7191 Decl::ObjCDeclQualifier QT = Decl::OBJC_TQ_None;
7192 const Decl *D = getCursorDecl(C);
7193 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
7194 QT = MD->getObjCDeclQualifier();
7195 else if (const ParmVarDecl *PD = dyn_cast<ParmVarDecl>(D))
7196 QT = PD->getObjCDeclQualifier();
7197 if (QT == Decl::OBJC_TQ_None)
7198 return CXObjCDeclQualifier_None;
7199
7200 unsigned Result = CXObjCDeclQualifier_None;
7201 if (QT & Decl::OBJC_TQ_In) Result |= CXObjCDeclQualifier_In;
7202 if (QT & Decl::OBJC_TQ_Inout) Result |= CXObjCDeclQualifier_Inout;
7203 if (QT & Decl::OBJC_TQ_Out) Result |= CXObjCDeclQualifier_Out;
7204 if (QT & Decl::OBJC_TQ_Bycopy) Result |= CXObjCDeclQualifier_Bycopy;
7205 if (QT & Decl::OBJC_TQ_Byref) Result |= CXObjCDeclQualifier_Byref;
7206 if (QT & Decl::OBJC_TQ_Oneway) Result |= CXObjCDeclQualifier_Oneway;
7207
7208 return Result;
7209}
7210
Argyrios Kyrtzidis7b50fc52013-07-05 20:44:37 +00007211unsigned clang_Cursor_isObjCOptional(CXCursor C) {
7212 if (!clang_isDeclaration(C.kind))
7213 return 0;
7214
7215 const Decl *D = getCursorDecl(C);
7216 if (const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D))
7217 return PD->getPropertyImplementation() == ObjCPropertyDecl::Optional;
7218 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
7219 return MD->getImplementationControl() == ObjCMethodDecl::Optional;
7220
7221 return 0;
7222}
7223
Argyrios Kyrtzidis23814e42013-04-18 23:53:05 +00007224unsigned clang_Cursor_isVariadic(CXCursor C) {
7225 if (!clang_isDeclaration(C.kind))
7226 return 0;
7227
7228 const Decl *D = getCursorDecl(C);
7229 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
7230 return FD->isVariadic();
7231 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
7232 return MD->isVariadic();
7233
7234 return 0;
7235}
7236
Guy Benyei11169dd2012-12-18 14:30:41 +00007237CXSourceRange clang_Cursor_getCommentRange(CXCursor C) {
7238 if (!clang_isDeclaration(C.kind))
7239 return clang_getNullRange();
7240
7241 const Decl *D = getCursorDecl(C);
7242 ASTContext &Context = getCursorContext(C);
7243 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
7244 if (!RC)
7245 return clang_getNullRange();
7246
7247 return cxloc::translateSourceRange(Context, RC->getSourceRange());
7248}
7249
7250CXString clang_Cursor_getRawCommentText(CXCursor C) {
7251 if (!clang_isDeclaration(C.kind))
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00007252 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00007253
7254 const Decl *D = getCursorDecl(C);
7255 ASTContext &Context = getCursorContext(C);
7256 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
7257 StringRef RawText = RC ? RC->getRawText(Context.getSourceManager()) :
7258 StringRef();
7259
7260 // Don't duplicate the string because RawText points directly into source
7261 // code.
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00007262 return cxstring::createRef(RawText);
Guy Benyei11169dd2012-12-18 14:30:41 +00007263}
7264
7265CXString clang_Cursor_getBriefCommentText(CXCursor C) {
7266 if (!clang_isDeclaration(C.kind))
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00007267 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00007268
7269 const Decl *D = getCursorDecl(C);
7270 const ASTContext &Context = getCursorContext(C);
7271 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
7272
7273 if (RC) {
7274 StringRef BriefText = RC->getBriefText(Context);
7275
7276 // Don't duplicate the string because RawComment ensures that this memory
7277 // will not go away.
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00007278 return cxstring::createRef(BriefText);
Guy Benyei11169dd2012-12-18 14:30:41 +00007279 }
7280
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00007281 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00007282}
7283
Guy Benyei11169dd2012-12-18 14:30:41 +00007284CXModule clang_Cursor_getModule(CXCursor C) {
7285 if (C.kind == CXCursor_ModuleImportDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007286 if (const ImportDecl *ImportD =
7287 dyn_cast_or_null<ImportDecl>(getCursorDecl(C)))
Guy Benyei11169dd2012-12-18 14:30:41 +00007288 return ImportD->getImportedModule();
7289 }
7290
Craig Topper69186e72014-06-08 08:38:04 +00007291 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007292}
7293
Argyrios Kyrtzidisf6d49c32014-05-14 23:14:37 +00007294CXModule clang_getModuleForFile(CXTranslationUnit TU, CXFile File) {
7295 if (isNotUsableTU(TU)) {
7296 LOG_BAD_TU(TU);
7297 return nullptr;
7298 }
7299 if (!File)
7300 return nullptr;
7301 FileEntry *FE = static_cast<FileEntry *>(File);
7302
7303 ASTUnit &Unit = *cxtu::getASTUnit(TU);
7304 HeaderSearch &HS = Unit.getPreprocessor().getHeaderSearchInfo();
7305 ModuleMap::KnownHeader Header = HS.findModuleForHeader(FE);
7306
Richard Smithfeb54b62014-10-23 02:01:19 +00007307 return Header.getModule();
Argyrios Kyrtzidisf6d49c32014-05-14 23:14:37 +00007308}
7309
Argyrios Kyrtzidis12fdb9e2013-04-26 22:47:49 +00007310CXFile clang_Module_getASTFile(CXModule CXMod) {
7311 if (!CXMod)
Craig Topper69186e72014-06-08 08:38:04 +00007312 return nullptr;
Argyrios Kyrtzidis12fdb9e2013-04-26 22:47:49 +00007313 Module *Mod = static_cast<Module*>(CXMod);
7314 return const_cast<FileEntry *>(Mod->getASTFile());
7315}
7316
Guy Benyei11169dd2012-12-18 14:30:41 +00007317CXModule clang_Module_getParent(CXModule CXMod) {
7318 if (!CXMod)
Craig Topper69186e72014-06-08 08:38:04 +00007319 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007320 Module *Mod = static_cast<Module*>(CXMod);
7321 return Mod->Parent;
7322}
7323
7324CXString clang_Module_getName(CXModule CXMod) {
7325 if (!CXMod)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00007326 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00007327 Module *Mod = static_cast<Module*>(CXMod);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00007328 return cxstring::createDup(Mod->Name);
Guy Benyei11169dd2012-12-18 14:30:41 +00007329}
7330
7331CXString clang_Module_getFullName(CXModule CXMod) {
7332 if (!CXMod)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00007333 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00007334 Module *Mod = static_cast<Module*>(CXMod);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00007335 return cxstring::createDup(Mod->getFullModuleName());
Guy Benyei11169dd2012-12-18 14:30:41 +00007336}
7337
Argyrios Kyrtzidis884337f2014-05-15 04:44:25 +00007338int clang_Module_isSystem(CXModule CXMod) {
7339 if (!CXMod)
7340 return 0;
7341 Module *Mod = static_cast<Module*>(CXMod);
7342 return Mod->IsSystem;
7343}
7344
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00007345unsigned clang_Module_getNumTopLevelHeaders(CXTranslationUnit TU,
7346 CXModule CXMod) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00007347 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00007348 LOG_BAD_TU(TU);
7349 return 0;
7350 }
7351 if (!CXMod)
Guy Benyei11169dd2012-12-18 14:30:41 +00007352 return 0;
7353 Module *Mod = static_cast<Module*>(CXMod);
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00007354 FileManager &FileMgr = cxtu::getASTUnit(TU)->getFileManager();
7355 ArrayRef<const FileEntry *> TopHeaders = Mod->getTopHeaders(FileMgr);
7356 return TopHeaders.size();
Guy Benyei11169dd2012-12-18 14:30:41 +00007357}
7358
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00007359CXFile clang_Module_getTopLevelHeader(CXTranslationUnit TU,
7360 CXModule CXMod, unsigned Index) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00007361 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00007362 LOG_BAD_TU(TU);
Craig Topper69186e72014-06-08 08:38:04 +00007363 return nullptr;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00007364 }
7365 if (!CXMod)
Craig Topper69186e72014-06-08 08:38:04 +00007366 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007367 Module *Mod = static_cast<Module*>(CXMod);
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00007368 FileManager &FileMgr = cxtu::getASTUnit(TU)->getFileManager();
Guy Benyei11169dd2012-12-18 14:30:41 +00007369
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00007370 ArrayRef<const FileEntry *> TopHeaders = Mod->getTopHeaders(FileMgr);
7371 if (Index < TopHeaders.size())
7372 return const_cast<FileEntry *>(TopHeaders[Index]);
Guy Benyei11169dd2012-12-18 14:30:41 +00007373
Craig Topper69186e72014-06-08 08:38:04 +00007374 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007375}
7376
7377} // end: extern "C"
7378
7379//===----------------------------------------------------------------------===//
7380// C++ AST instrospection.
7381//===----------------------------------------------------------------------===//
7382
7383extern "C" {
Jonathan Coe29565352016-04-27 12:48:25 +00007384
7385unsigned clang_CXXConstructor_isDefaultConstructor(CXCursor C) {
7386 if (!clang_isDeclaration(C.kind))
7387 return 0;
7388
7389 const Decl *D = cxcursor::getCursorDecl(C);
7390 const CXXConstructorDecl *Constructor =
7391 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
7392 return (Constructor && Constructor->isDefaultConstructor()) ? 1 : 0;
7393}
7394
7395unsigned clang_CXXConstructor_isCopyConstructor(CXCursor C) {
7396 if (!clang_isDeclaration(C.kind))
7397 return 0;
7398
7399 const Decl *D = cxcursor::getCursorDecl(C);
7400 const CXXConstructorDecl *Constructor =
7401 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
7402 return (Constructor && Constructor->isCopyConstructor()) ? 1 : 0;
7403}
7404
7405unsigned clang_CXXConstructor_isMoveConstructor(CXCursor C) {
7406 if (!clang_isDeclaration(C.kind))
7407 return 0;
7408
7409 const Decl *D = cxcursor::getCursorDecl(C);
7410 const CXXConstructorDecl *Constructor =
7411 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
7412 return (Constructor && Constructor->isMoveConstructor()) ? 1 : 0;
7413}
7414
7415unsigned clang_CXXConstructor_isConvertingConstructor(CXCursor C) {
7416 if (!clang_isDeclaration(C.kind))
7417 return 0;
7418
7419 const Decl *D = cxcursor::getCursorDecl(C);
7420 const CXXConstructorDecl *Constructor =
7421 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
7422 // Passing 'false' excludes constructors marked 'explicit'.
7423 return (Constructor && Constructor->isConvertingConstructor(false)) ? 1 : 0;
7424}
7425
Saleem Abdulrasool6ea75db2015-10-27 15:50:22 +00007426unsigned clang_CXXField_isMutable(CXCursor C) {
7427 if (!clang_isDeclaration(C.kind))
7428 return 0;
7429
7430 if (const auto D = cxcursor::getCursorDecl(C))
7431 if (const auto FD = dyn_cast_or_null<FieldDecl>(D))
7432 return FD->isMutable() ? 1 : 0;
7433 return 0;
7434}
7435
Dmitri Gribenko62770be2013-05-17 18:38:35 +00007436unsigned clang_CXXMethod_isPureVirtual(CXCursor C) {
7437 if (!clang_isDeclaration(C.kind))
7438 return 0;
7439
Dmitri Gribenko62770be2013-05-17 18:38:35 +00007440 const Decl *D = cxcursor::getCursorDecl(C);
Alp Tokera2794f92014-01-22 07:29:52 +00007441 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00007442 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Dmitri Gribenko62770be2013-05-17 18:38:35 +00007443 return (Method && Method->isVirtual() && Method->isPure()) ? 1 : 0;
7444}
7445
Dmitri Gribenkoe570ede2014-04-07 14:59:13 +00007446unsigned clang_CXXMethod_isConst(CXCursor C) {
7447 if (!clang_isDeclaration(C.kind))
7448 return 0;
7449
7450 const Decl *D = cxcursor::getCursorDecl(C);
7451 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00007452 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Dmitri Gribenkoe570ede2014-04-07 14:59:13 +00007453 return (Method && (Method->getTypeQualifiers() & Qualifiers::Const)) ? 1 : 0;
7454}
7455
Jonathan Coe29565352016-04-27 12:48:25 +00007456unsigned clang_CXXMethod_isDefaulted(CXCursor C) {
7457 if (!clang_isDeclaration(C.kind))
7458 return 0;
7459
7460 const Decl *D = cxcursor::getCursorDecl(C);
7461 const CXXMethodDecl *Method =
7462 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
7463 return (Method && Method->isDefaulted()) ? 1 : 0;
7464}
7465
Guy Benyei11169dd2012-12-18 14:30:41 +00007466unsigned clang_CXXMethod_isStatic(CXCursor C) {
7467 if (!clang_isDeclaration(C.kind))
7468 return 0;
7469
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007470 const Decl *D = cxcursor::getCursorDecl(C);
Alp Tokera2794f92014-01-22 07:29:52 +00007471 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00007472 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007473 return (Method && Method->isStatic()) ? 1 : 0;
7474}
7475
7476unsigned clang_CXXMethod_isVirtual(CXCursor C) {
7477 if (!clang_isDeclaration(C.kind))
7478 return 0;
7479
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007480 const Decl *D = cxcursor::getCursorDecl(C);
Alp Tokera2794f92014-01-22 07:29:52 +00007481 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00007482 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007483 return (Method && Method->isVirtual()) ? 1 : 0;
7484}
7485} // end: extern "C"
7486
7487//===----------------------------------------------------------------------===//
7488// Attribute introspection.
7489//===----------------------------------------------------------------------===//
7490
7491extern "C" {
7492CXType clang_getIBOutletCollectionType(CXCursor C) {
7493 if (C.kind != CXCursor_IBOutletCollectionAttr)
7494 return cxtype::MakeCXType(QualType(), cxcursor::getCursorTU(C));
7495
Dmitri Gribenkoe4baea62013-01-26 18:08:08 +00007496 const IBOutletCollectionAttr *A =
Guy Benyei11169dd2012-12-18 14:30:41 +00007497 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
7498
7499 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorTU(C));
7500}
7501} // end: extern "C"
7502
7503//===----------------------------------------------------------------------===//
7504// Inspecting memory usage.
7505//===----------------------------------------------------------------------===//
7506
7507typedef std::vector<CXTUResourceUsageEntry> MemUsageEntries;
7508
7509static inline void createCXTUResourceUsageEntry(MemUsageEntries &entries,
7510 enum CXTUResourceUsageKind k,
7511 unsigned long amount) {
7512 CXTUResourceUsageEntry entry = { k, amount };
7513 entries.push_back(entry);
7514}
7515
7516extern "C" {
7517
7518const char *clang_getTUResourceUsageName(CXTUResourceUsageKind kind) {
7519 const char *str = "";
7520 switch (kind) {
7521 case CXTUResourceUsage_AST:
7522 str = "ASTContext: expressions, declarations, and types";
7523 break;
7524 case CXTUResourceUsage_Identifiers:
7525 str = "ASTContext: identifiers";
7526 break;
7527 case CXTUResourceUsage_Selectors:
7528 str = "ASTContext: selectors";
7529 break;
7530 case CXTUResourceUsage_GlobalCompletionResults:
7531 str = "Code completion: cached global results";
7532 break;
7533 case CXTUResourceUsage_SourceManagerContentCache:
7534 str = "SourceManager: content cache allocator";
7535 break;
7536 case CXTUResourceUsage_AST_SideTables:
7537 str = "ASTContext: side tables";
7538 break;
7539 case CXTUResourceUsage_SourceManager_Membuffer_Malloc:
7540 str = "SourceManager: malloc'ed memory buffers";
7541 break;
7542 case CXTUResourceUsage_SourceManager_Membuffer_MMap:
7543 str = "SourceManager: mmap'ed memory buffers";
7544 break;
7545 case CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc:
7546 str = "ExternalASTSource: malloc'ed memory buffers";
7547 break;
7548 case CXTUResourceUsage_ExternalASTSource_Membuffer_MMap:
7549 str = "ExternalASTSource: mmap'ed memory buffers";
7550 break;
7551 case CXTUResourceUsage_Preprocessor:
7552 str = "Preprocessor: malloc'ed memory";
7553 break;
7554 case CXTUResourceUsage_PreprocessingRecord:
7555 str = "Preprocessor: PreprocessingRecord";
7556 break;
7557 case CXTUResourceUsage_SourceManager_DataStructures:
7558 str = "SourceManager: data structures and tables";
7559 break;
7560 case CXTUResourceUsage_Preprocessor_HeaderSearch:
7561 str = "Preprocessor: header search tables";
7562 break;
7563 }
7564 return str;
7565}
7566
7567CXTUResourceUsage clang_getCXTUResourceUsage(CXTranslationUnit TU) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00007568 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00007569 LOG_BAD_TU(TU);
Craig Topper69186e72014-06-08 08:38:04 +00007570 CXTUResourceUsage usage = { (void*) nullptr, 0, nullptr };
Guy Benyei11169dd2012-12-18 14:30:41 +00007571 return usage;
7572 }
7573
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00007574 ASTUnit *astUnit = cxtu::getASTUnit(TU);
Ahmed Charlesb8984322014-03-07 20:03:18 +00007575 std::unique_ptr<MemUsageEntries> entries(new MemUsageEntries());
Guy Benyei11169dd2012-12-18 14:30:41 +00007576 ASTContext &astContext = astUnit->getASTContext();
7577
7578 // How much memory is used by AST nodes and types?
7579 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST,
7580 (unsigned long) astContext.getASTAllocatedMemory());
7581
7582 // How much memory is used by identifiers?
7583 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Identifiers,
7584 (unsigned long) astContext.Idents.getAllocator().getTotalMemory());
7585
7586 // How much memory is used for selectors?
7587 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Selectors,
7588 (unsigned long) astContext.Selectors.getTotalMemory());
7589
7590 // How much memory is used by ASTContext's side tables?
7591 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST_SideTables,
7592 (unsigned long) astContext.getSideTableAllocatedMemory());
7593
7594 // How much memory is used for caching global code completion results?
7595 unsigned long completionBytes = 0;
7596 if (GlobalCodeCompletionAllocator *completionAllocator =
Alp Tokerf994cef2014-07-05 03:08:06 +00007597 astUnit->getCachedCompletionAllocator().get()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007598 completionBytes = completionAllocator->getTotalMemory();
7599 }
7600 createCXTUResourceUsageEntry(*entries,
7601 CXTUResourceUsage_GlobalCompletionResults,
7602 completionBytes);
7603
7604 // How much memory is being used by SourceManager's content cache?
7605 createCXTUResourceUsageEntry(*entries,
7606 CXTUResourceUsage_SourceManagerContentCache,
7607 (unsigned long) astContext.getSourceManager().getContentCacheSize());
7608
7609 // How much memory is being used by the MemoryBuffer's in SourceManager?
7610 const SourceManager::MemoryBufferSizes &srcBufs =
7611 astUnit->getSourceManager().getMemoryBufferSizes();
7612
7613 createCXTUResourceUsageEntry(*entries,
7614 CXTUResourceUsage_SourceManager_Membuffer_Malloc,
7615 (unsigned long) srcBufs.malloc_bytes);
7616 createCXTUResourceUsageEntry(*entries,
7617 CXTUResourceUsage_SourceManager_Membuffer_MMap,
7618 (unsigned long) srcBufs.mmap_bytes);
7619 createCXTUResourceUsageEntry(*entries,
7620 CXTUResourceUsage_SourceManager_DataStructures,
7621 (unsigned long) astContext.getSourceManager()
7622 .getDataStructureSizes());
7623
7624 // How much memory is being used by the ExternalASTSource?
7625 if (ExternalASTSource *esrc = astContext.getExternalSource()) {
7626 const ExternalASTSource::MemoryBufferSizes &sizes =
7627 esrc->getMemoryBufferSizes();
7628
7629 createCXTUResourceUsageEntry(*entries,
7630 CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc,
7631 (unsigned long) sizes.malloc_bytes);
7632 createCXTUResourceUsageEntry(*entries,
7633 CXTUResourceUsage_ExternalASTSource_Membuffer_MMap,
7634 (unsigned long) sizes.mmap_bytes);
7635 }
7636
7637 // How much memory is being used by the Preprocessor?
7638 Preprocessor &pp = astUnit->getPreprocessor();
7639 createCXTUResourceUsageEntry(*entries,
7640 CXTUResourceUsage_Preprocessor,
7641 pp.getTotalMemory());
7642
7643 if (PreprocessingRecord *pRec = pp.getPreprocessingRecord()) {
7644 createCXTUResourceUsageEntry(*entries,
7645 CXTUResourceUsage_PreprocessingRecord,
7646 pRec->getTotalMemory());
7647 }
7648
7649 createCXTUResourceUsageEntry(*entries,
7650 CXTUResourceUsage_Preprocessor_HeaderSearch,
7651 pp.getHeaderSearchInfo().getTotalMemory());
Craig Topper69186e72014-06-08 08:38:04 +00007652
Guy Benyei11169dd2012-12-18 14:30:41 +00007653 CXTUResourceUsage usage = { (void*) entries.get(),
7654 (unsigned) entries->size(),
Alexander Kornienko6ee521c2015-01-23 15:36:10 +00007655 !entries->empty() ? &(*entries)[0] : nullptr };
Ahmed Charles9a16beb2014-03-07 19:33:25 +00007656 entries.release();
Guy Benyei11169dd2012-12-18 14:30:41 +00007657 return usage;
7658}
7659
7660void clang_disposeCXTUResourceUsage(CXTUResourceUsage usage) {
7661 if (usage.data)
7662 delete (MemUsageEntries*) usage.data;
7663}
7664
Argyrios Kyrtzidis0e282ef2013-12-06 18:55:45 +00007665CXSourceRangeList *clang_getSkippedRanges(CXTranslationUnit TU, CXFile file) {
7666 CXSourceRangeList *skipped = new CXSourceRangeList;
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00007667 skipped->count = 0;
Craig Topper69186e72014-06-08 08:38:04 +00007668 skipped->ranges = nullptr;
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00007669
Dmitri Gribenko852d6222014-02-11 15:02:48 +00007670 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00007671 LOG_BAD_TU(TU);
7672 return skipped;
7673 }
7674
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00007675 if (!file)
7676 return skipped;
7677
7678 ASTUnit *astUnit = cxtu::getASTUnit(TU);
7679 PreprocessingRecord *ppRec = astUnit->getPreprocessor().getPreprocessingRecord();
7680 if (!ppRec)
7681 return skipped;
7682
7683 ASTContext &Ctx = astUnit->getASTContext();
7684 SourceManager &sm = Ctx.getSourceManager();
7685 FileEntry *fileEntry = static_cast<FileEntry *>(file);
7686 FileID wantedFileID = sm.translateFile(fileEntry);
7687
7688 const std::vector<SourceRange> &SkippedRanges = ppRec->getSkippedRanges();
7689 std::vector<SourceRange> wantedRanges;
7690 for (std::vector<SourceRange>::const_iterator i = SkippedRanges.begin(), ei = SkippedRanges.end();
7691 i != ei; ++i) {
7692 if (sm.getFileID(i->getBegin()) == wantedFileID || sm.getFileID(i->getEnd()) == wantedFileID)
7693 wantedRanges.push_back(*i);
7694 }
7695
7696 skipped->count = wantedRanges.size();
7697 skipped->ranges = new CXSourceRange[skipped->count];
7698 for (unsigned i = 0, ei = skipped->count; i != ei; ++i)
7699 skipped->ranges[i] = cxloc::translateSourceRange(Ctx, wantedRanges[i]);
7700
7701 return skipped;
7702}
7703
Argyrios Kyrtzidis0e282ef2013-12-06 18:55:45 +00007704void clang_disposeSourceRangeList(CXSourceRangeList *ranges) {
7705 if (ranges) {
7706 delete[] ranges->ranges;
7707 delete ranges;
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00007708 }
7709}
7710
Guy Benyei11169dd2012-12-18 14:30:41 +00007711} // end extern "C"
7712
7713void clang::PrintLibclangResourceUsage(CXTranslationUnit TU) {
7714 CXTUResourceUsage Usage = clang_getCXTUResourceUsage(TU);
7715 for (unsigned I = 0; I != Usage.numEntries; ++I)
7716 fprintf(stderr, " %s: %lu\n",
7717 clang_getTUResourceUsageName(Usage.entries[I].kind),
7718 Usage.entries[I].amount);
7719
7720 clang_disposeCXTUResourceUsage(Usage);
7721}
7722
7723//===----------------------------------------------------------------------===//
7724// Misc. utility functions.
7725//===----------------------------------------------------------------------===//
7726
7727/// Default to using an 8 MB stack size on "safety" threads.
7728static unsigned SafetyStackThreadSize = 8 << 20;
7729
7730namespace clang {
7731
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00007732bool RunSafely(llvm::CrashRecoveryContext &CRC, llvm::function_ref<void()> Fn,
Guy Benyei11169dd2012-12-18 14:30:41 +00007733 unsigned Size) {
7734 if (!Size)
7735 Size = GetSafetyThreadStackSize();
7736 if (Size)
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00007737 return CRC.RunSafelyOnThread(Fn, Size);
7738 return CRC.RunSafely(Fn);
Guy Benyei11169dd2012-12-18 14:30:41 +00007739}
7740
7741unsigned GetSafetyThreadStackSize() {
7742 return SafetyStackThreadSize;
7743}
7744
7745void SetSafetyThreadStackSize(unsigned Value) {
7746 SafetyStackThreadSize = Value;
7747}
7748
Alexander Kornienkoab9db512015-06-22 23:07:51 +00007749}
Guy Benyei11169dd2012-12-18 14:30:41 +00007750
7751void clang::setThreadBackgroundPriority() {
7752 if (getenv("LIBCLANG_BGPRIO_DISABLE"))
7753 return;
7754
Alp Toker1a86ad22014-07-06 06:24:00 +00007755#ifdef USE_DARWIN_THREADS
Guy Benyei11169dd2012-12-18 14:30:41 +00007756 setpriority(PRIO_DARWIN_THREAD, 0, PRIO_DARWIN_BG);
7757#endif
7758}
7759
7760void cxindex::printDiagsToStderr(ASTUnit *Unit) {
7761 if (!Unit)
7762 return;
7763
7764 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
7765 DEnd = Unit->stored_diag_end();
7766 D != DEnd; ++D) {
Ben Langmuir749323f2014-04-22 17:40:12 +00007767 CXStoredDiagnostic Diag(*D, Unit->getLangOpts());
Guy Benyei11169dd2012-12-18 14:30:41 +00007768 CXString Msg = clang_formatDiagnostic(&Diag,
7769 clang_defaultDiagnosticDisplayOptions());
7770 fprintf(stderr, "%s\n", clang_getCString(Msg));
7771 clang_disposeString(Msg);
7772 }
7773#ifdef LLVM_ON_WIN32
7774 // On Windows, force a flush, since there may be multiple copies of
7775 // stderr and stdout in the file system, all with different buffers
7776 // but writing to the same device.
7777 fflush(stderr);
7778#endif
7779}
7780
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007781MacroInfo *cxindex::getMacroInfo(const IdentifierInfo &II,
7782 SourceLocation MacroDefLoc,
7783 CXTranslationUnit TU){
7784 if (MacroDefLoc.isInvalid() || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00007785 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007786 if (!II.hadMacroDefinition())
Craig Topper69186e72014-06-08 08:38:04 +00007787 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007788
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00007789 ASTUnit *Unit = cxtu::getASTUnit(TU);
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007790 Preprocessor &PP = Unit->getPreprocessor();
Richard Smith20e883e2015-04-29 23:20:19 +00007791 MacroDirective *MD = PP.getLocalMacroDirectiveHistory(&II);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00007792 if (MD) {
7793 for (MacroDirective::DefInfo
7794 Def = MD->getDefinition(); Def; Def = Def.getPreviousDefinition()) {
7795 if (MacroDefLoc == Def.getMacroInfo()->getDefinitionLoc())
7796 return Def.getMacroInfo();
7797 }
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007798 }
7799
Craig Topper69186e72014-06-08 08:38:04 +00007800 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007801}
7802
Richard Smith66a81862015-05-04 02:25:31 +00007803const MacroInfo *cxindex::getMacroInfo(const MacroDefinitionRecord *MacroDef,
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00007804 CXTranslationUnit TU) {
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007805 if (!MacroDef || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00007806 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007807 const IdentifierInfo *II = MacroDef->getName();
7808 if (!II)
Craig Topper69186e72014-06-08 08:38:04 +00007809 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007810
7811 return getMacroInfo(*II, MacroDef->getLocation(), TU);
7812}
7813
Richard Smith66a81862015-05-04 02:25:31 +00007814MacroDefinitionRecord *
7815cxindex::checkForMacroInMacroDefinition(const MacroInfo *MI, const Token &Tok,
7816 CXTranslationUnit TU) {
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007817 if (!MI || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00007818 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007819 if (Tok.isNot(tok::raw_identifier))
Craig Topper69186e72014-06-08 08:38:04 +00007820 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007821
7822 if (MI->getNumTokens() == 0)
Craig Topper69186e72014-06-08 08:38:04 +00007823 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007824 SourceRange DefRange(MI->getReplacementToken(0).getLocation(),
7825 MI->getDefinitionEndLoc());
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00007826 ASTUnit *Unit = cxtu::getASTUnit(TU);
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007827
7828 // Check that the token is inside the definition and not its argument list.
7829 SourceManager &SM = Unit->getSourceManager();
7830 if (SM.isBeforeInTranslationUnit(Tok.getLocation(), DefRange.getBegin()))
Craig Topper69186e72014-06-08 08:38:04 +00007831 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007832 if (SM.isBeforeInTranslationUnit(DefRange.getEnd(), Tok.getLocation()))
Craig Topper69186e72014-06-08 08:38:04 +00007833 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007834
7835 Preprocessor &PP = Unit->getPreprocessor();
7836 PreprocessingRecord *PPRec = PP.getPreprocessingRecord();
7837 if (!PPRec)
Craig Topper69186e72014-06-08 08:38:04 +00007838 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007839
Alp Toker2d57cea2014-05-17 04:53:25 +00007840 IdentifierInfo &II = PP.getIdentifierTable().get(Tok.getRawIdentifier());
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007841 if (!II.hadMacroDefinition())
Craig Topper69186e72014-06-08 08:38:04 +00007842 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007843
7844 // Check that the identifier is not one of the macro arguments.
7845 if (std::find(MI->arg_begin(), MI->arg_end(), &II) != MI->arg_end())
Craig Topper69186e72014-06-08 08:38:04 +00007846 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007847
Richard Smith20e883e2015-04-29 23:20:19 +00007848 MacroDirective *InnerMD = PP.getLocalMacroDirectiveHistory(&II);
Argyrios Kyrtzidis09c9e812013-02-20 00:54:57 +00007849 if (!InnerMD)
Craig Topper69186e72014-06-08 08:38:04 +00007850 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007851
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00007852 return PPRec->findMacroDefinition(InnerMD->getMacroInfo());
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007853}
7854
Richard Smith66a81862015-05-04 02:25:31 +00007855MacroDefinitionRecord *
7856cxindex::checkForMacroInMacroDefinition(const MacroInfo *MI, SourceLocation Loc,
7857 CXTranslationUnit TU) {
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007858 if (Loc.isInvalid() || !MI || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00007859 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007860
7861 if (MI->getNumTokens() == 0)
Craig Topper69186e72014-06-08 08:38:04 +00007862 return nullptr;
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00007863 ASTUnit *Unit = cxtu::getASTUnit(TU);
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007864 Preprocessor &PP = Unit->getPreprocessor();
7865 if (!PP.getPreprocessingRecord())
Craig Topper69186e72014-06-08 08:38:04 +00007866 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007867 Loc = Unit->getSourceManager().getSpellingLoc(Loc);
7868 Token Tok;
7869 if (PP.getRawToken(Loc, Tok))
Craig Topper69186e72014-06-08 08:38:04 +00007870 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007871
7872 return checkForMacroInMacroDefinition(MI, Tok, TU);
7873}
7874
Guy Benyei11169dd2012-12-18 14:30:41 +00007875extern "C" {
7876
7877CXString clang_getClangVersion() {
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00007878 return cxstring::createDup(getClangFullVersion());
Guy Benyei11169dd2012-12-18 14:30:41 +00007879}
7880
7881} // end: extern "C"
7882
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00007883Logger &cxindex::Logger::operator<<(CXTranslationUnit TU) {
7884 if (TU) {
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00007885 if (ASTUnit *Unit = cxtu::getASTUnit(TU)) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00007886 LogOS << '<' << Unit->getMainFileName() << '>';
Argyrios Kyrtzidis37f2ab42013-03-05 20:21:14 +00007887 if (Unit->isMainFileAST())
7888 LogOS << " (" << Unit->getASTFileName() << ')';
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00007889 return *this;
7890 }
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00007891 } else {
7892 LogOS << "<NULL TU>";
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00007893 }
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00007894 return *this;
7895}
7896
Argyrios Kyrtzidisba4b5f82013-03-08 02:32:26 +00007897Logger &cxindex::Logger::operator<<(const FileEntry *FE) {
7898 *this << FE->getName();
7899 return *this;
7900}
7901
7902Logger &cxindex::Logger::operator<<(CXCursor cursor) {
7903 CXString cursorName = clang_getCursorDisplayName(cursor);
7904 *this << cursorName << "@" << clang_getCursorLocation(cursor);
7905 clang_disposeString(cursorName);
7906 return *this;
7907}
7908
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00007909Logger &cxindex::Logger::operator<<(CXSourceLocation Loc) {
7910 CXFile File;
7911 unsigned Line, Column;
Craig Topper69186e72014-06-08 08:38:04 +00007912 clang_getFileLocation(Loc, &File, &Line, &Column, nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00007913 CXString FileName = clang_getFileName(File);
7914 *this << llvm::format("(%s:%d:%d)", clang_getCString(FileName), Line, Column);
7915 clang_disposeString(FileName);
7916 return *this;
7917}
7918
7919Logger &cxindex::Logger::operator<<(CXSourceRange range) {
7920 CXSourceLocation BLoc = clang_getRangeStart(range);
7921 CXSourceLocation ELoc = clang_getRangeEnd(range);
7922
7923 CXFile BFile;
7924 unsigned BLine, BColumn;
Craig Topper69186e72014-06-08 08:38:04 +00007925 clang_getFileLocation(BLoc, &BFile, &BLine, &BColumn, nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00007926
7927 CXFile EFile;
7928 unsigned ELine, EColumn;
Craig Topper69186e72014-06-08 08:38:04 +00007929 clang_getFileLocation(ELoc, &EFile, &ELine, &EColumn, nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00007930
7931 CXString BFileName = clang_getFileName(BFile);
7932 if (BFile == EFile) {
7933 *this << llvm::format("[%s %d:%d-%d:%d]", clang_getCString(BFileName),
7934 BLine, BColumn, ELine, EColumn);
7935 } else {
7936 CXString EFileName = clang_getFileName(EFile);
7937 *this << llvm::format("[%s:%d:%d - ", clang_getCString(BFileName),
7938 BLine, BColumn)
7939 << llvm::format("%s:%d:%d]", clang_getCString(EFileName),
7940 ELine, EColumn);
7941 clang_disposeString(EFileName);
7942 }
7943 clang_disposeString(BFileName);
7944 return *this;
7945}
7946
7947Logger &cxindex::Logger::operator<<(CXString Str) {
7948 *this << clang_getCString(Str);
7949 return *this;
7950}
7951
7952Logger &cxindex::Logger::operator<<(const llvm::format_object_base &Fmt) {
7953 LogOS << Fmt;
7954 return *this;
7955}
7956
Chandler Carruth37ad2582014-06-27 15:14:39 +00007957static llvm::ManagedStatic<llvm::sys::Mutex> LoggingMutex;
7958
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00007959cxindex::Logger::~Logger() {
Chandler Carruth37ad2582014-06-27 15:14:39 +00007960 llvm::sys::ScopedLock L(*LoggingMutex);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00007961
7962 static llvm::TimeRecord sBeginTR = llvm::TimeRecord::getCurrentTime();
7963
Dmitri Gribenkof8579502013-01-12 19:30:44 +00007964 raw_ostream &OS = llvm::errs();
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00007965 OS << "[libclang:" << Name << ':';
7966
Alp Toker1a86ad22014-07-06 06:24:00 +00007967#ifdef USE_DARWIN_THREADS
7968 // TODO: Portability.
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00007969 mach_port_t tid = pthread_mach_thread_np(pthread_self());
7970 OS << tid << ':';
7971#endif
7972
7973 llvm::TimeRecord TR = llvm::TimeRecord::getCurrentTime();
7974 OS << llvm::format("%7.4f] ", TR.getWallTime() - sBeginTR.getWallTime());
Yaron Keren09fb7c62015-03-10 07:33:23 +00007975 OS << Msg << '\n';
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00007976
7977 if (Trace) {
Zachary Turner1fe2a8d2015-03-05 19:15:09 +00007978 llvm::sys::PrintStackTrace(OS);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00007979 OS << "--------------------------------------------------\n";
7980 }
7981}
Benjamin Kramerc1ffdab2016-03-03 08:58:18 +00007982
7983#ifdef CLANG_TOOL_EXTRA_BUILD
7984// This anchor is used to force the linker to link the clang-tidy plugin.
7985extern volatile int ClangTidyPluginAnchorSource;
7986static int LLVM_ATTRIBUTE_UNUSED ClangTidyPluginAnchorDestination =
7987 ClangTidyPluginAnchorSource;
7988#endif