blob: 9cdb2ee8d697130bc5848772fecc9bb66fe4ec0b [file] [log] [blame]
Guy Benyei11169dd2012-12-18 14:30:41 +00001//===- CIndex.cpp - Clang-C Source Indexing Library -----------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the main API hooks in the Clang-C Source Indexing
11// library.
12//
13//===----------------------------------------------------------------------===//
14
Guy Benyei11169dd2012-12-18 14:30:41 +000015#include "CIndexDiagnostic.h"
Mehdi Amini9670f842016-07-18 19:02:11 +000016#include "CIndexer.h"
Chandler Carruth4b417452013-01-19 08:09:44 +000017#include "CLog.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000018#include "CXCursor.h"
19#include "CXSourceLocation.h"
20#include "CXString.h"
21#include "CXTranslationUnit.h"
22#include "CXType.h"
23#include "CursorVisitor.h"
David Blaikie0a4e61f2013-09-13 18:32:52 +000024#include "clang/AST/Attr.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000025#include "clang/AST/StmtVisitor.h"
26#include "clang/Basic/Diagnostic.h"
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +000027#include "clang/Basic/DiagnosticCategories.h"
28#include "clang/Basic/DiagnosticIDs.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000029#include "clang/Basic/Version.h"
30#include "clang/Frontend/ASTUnit.h"
31#include "clang/Frontend/CompilerInstance.h"
32#include "clang/Frontend/FrontendDiagnostic.h"
Argyrios Kyrtzidisca741ce2016-02-14 22:30:14 +000033#include "clang/Index/CodegenNameGenerator.h"
Dmitri Gribenko9e605112013-11-13 22:16:51 +000034#include "clang/Index/CommentToXML.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000035#include "clang/Lex/HeaderSearch.h"
36#include "clang/Lex/Lexer.h"
37#include "clang/Lex/PreprocessingRecord.h"
38#include "clang/Lex/Preprocessor.h"
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +000039#include "clang/Serialization/SerializationDiagnostic.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000040#include "llvm/ADT/Optional.h"
41#include "llvm/ADT/STLExtras.h"
42#include "llvm/ADT/StringSwitch.h"
Alp Toker1d257e12014-06-04 03:28:55 +000043#include "llvm/Config/llvm-config.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000044#include "llvm/Support/Compiler.h"
45#include "llvm/Support/CrashRecoveryContext.h"
Chandler Carruth4b417452013-01-19 08:09:44 +000046#include "llvm/Support/Format.h"
Chandler Carruth37ad2582014-06-27 15:14:39 +000047#include "llvm/Support/ManagedStatic.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000048#include "llvm/Support/MemoryBuffer.h"
49#include "llvm/Support/Mutex.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000050#include "llvm/Support/Program.h"
51#include "llvm/Support/SaveAndRestore.h"
52#include "llvm/Support/Signals.h"
Adrian Prantlbc068582015-07-08 01:00:30 +000053#include "llvm/Support/TargetSelect.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000054#include "llvm/Support/Threading.h"
55#include "llvm/Support/Timer.h"
56#include "llvm/Support/raw_ostream.h"
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +000057
Alp Toker1a86ad22014-07-06 06:24:00 +000058#if LLVM_ENABLE_THREADS != 0 && defined(__APPLE__)
59#define USE_DARWIN_THREADS
60#endif
61
62#ifdef USE_DARWIN_THREADS
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +000063#include <pthread.h>
64#endif
Guy Benyei11169dd2012-12-18 14:30:41 +000065
66using namespace clang;
67using namespace clang::cxcursor;
Guy Benyei11169dd2012-12-18 14:30:41 +000068using namespace clang::cxtu;
69using namespace clang::cxindex;
70
David Blaikieea4395e2017-01-06 19:49:01 +000071CXTranslationUnit cxtu::MakeCXTranslationUnit(CIndexer *CIdx,
72 std::unique_ptr<ASTUnit> AU) {
Dmitri Gribenkod36209e2013-01-26 21:32:42 +000073 if (!AU)
Craig Topper69186e72014-06-08 08:38:04 +000074 return nullptr;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +000075 assert(CIdx);
Guy Benyei11169dd2012-12-18 14:30:41 +000076 CXTranslationUnit D = new CXTranslationUnitImpl();
77 D->CIdx = CIdx;
David Blaikieea4395e2017-01-06 19:49:01 +000078 D->TheASTUnit = AU.release();
Dmitri Gribenko74895212013-02-03 13:52:47 +000079 D->StringPool = new cxstring::CXStringPool();
Craig Topper69186e72014-06-08 08:38:04 +000080 D->Diagnostics = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +000081 D->OverridenCursorsPool = createOverridenCXCursorsPool();
Craig Topper69186e72014-06-08 08:38:04 +000082 D->CommentToXML = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +000083 return D;
84}
85
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +000086bool cxtu::isASTReadError(ASTUnit *AU) {
87 for (ASTUnit::stored_diag_iterator D = AU->stored_diag_begin(),
88 DEnd = AU->stored_diag_end();
89 D != DEnd; ++D) {
90 if (D->getLevel() >= DiagnosticsEngine::Error &&
91 DiagnosticIDs::getCategoryNumberForDiag(D->getID()) ==
92 diag::DiagCat_AST_Deserialization_Issue)
93 return true;
94 }
95 return false;
96}
97
Guy Benyei11169dd2012-12-18 14:30:41 +000098cxtu::CXTUOwner::~CXTUOwner() {
99 if (TU)
100 clang_disposeTranslationUnit(TU);
101}
102
103/// \brief Compare two source ranges to determine their relative position in
104/// the translation unit.
105static RangeComparisonResult RangeCompare(SourceManager &SM,
106 SourceRange R1,
107 SourceRange R2) {
108 assert(R1.isValid() && "First range is invalid?");
109 assert(R2.isValid() && "Second range is invalid?");
110 if (R1.getEnd() != R2.getBegin() &&
111 SM.isBeforeInTranslationUnit(R1.getEnd(), R2.getBegin()))
112 return RangeBefore;
113 if (R2.getEnd() != R1.getBegin() &&
114 SM.isBeforeInTranslationUnit(R2.getEnd(), R1.getBegin()))
115 return RangeAfter;
116 return RangeOverlap;
117}
118
119/// \brief Determine if a source location falls within, before, or after a
120/// a given source range.
121static RangeComparisonResult LocationCompare(SourceManager &SM,
122 SourceLocation L, SourceRange R) {
123 assert(R.isValid() && "First range is invalid?");
124 assert(L.isValid() && "Second range is invalid?");
125 if (L == R.getBegin() || L == R.getEnd())
126 return RangeOverlap;
127 if (SM.isBeforeInTranslationUnit(L, R.getBegin()))
128 return RangeBefore;
129 if (SM.isBeforeInTranslationUnit(R.getEnd(), L))
130 return RangeAfter;
131 return RangeOverlap;
132}
133
134/// \brief Translate a Clang source range into a CIndex source range.
135///
136/// Clang internally represents ranges where the end location points to the
137/// start of the token at the end. However, for external clients it is more
138/// useful to have a CXSourceRange be a proper half-open interval. This routine
139/// does the appropriate translation.
140CXSourceRange cxloc::translateSourceRange(const SourceManager &SM,
141 const LangOptions &LangOpts,
142 const CharSourceRange &R) {
143 // We want the last character in this location, so we will adjust the
144 // location accordingly.
145 SourceLocation EndLoc = R.getEnd();
146 if (EndLoc.isValid() && EndLoc.isMacroID() && !SM.isMacroArgExpansion(EndLoc))
147 EndLoc = SM.getExpansionRange(EndLoc).second;
Yaron Keren8b563662015-10-03 10:46:20 +0000148 if (R.isTokenRange() && EndLoc.isValid()) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000149 unsigned Length = Lexer::MeasureTokenLength(SM.getSpellingLoc(EndLoc),
150 SM, LangOpts);
151 EndLoc = EndLoc.getLocWithOffset(Length);
152 }
153
Bill Wendlingeade3622013-01-23 08:25:41 +0000154 CXSourceRange Result = {
Dmitri Gribenkof9304482013-01-23 15:56:07 +0000155 { &SM, &LangOpts },
Bill Wendlingeade3622013-01-23 08:25:41 +0000156 R.getBegin().getRawEncoding(),
157 EndLoc.getRawEncoding()
158 };
Guy Benyei11169dd2012-12-18 14:30:41 +0000159 return Result;
160}
161
162//===----------------------------------------------------------------------===//
163// Cursor visitor.
164//===----------------------------------------------------------------------===//
165
166static SourceRange getRawCursorExtent(CXCursor C);
167static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr);
168
169
170RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
171 return RangeCompare(AU->getSourceManager(), R, RegionOfInterest);
172}
173
174/// \brief Visit the given cursor and, if requested by the visitor,
175/// its children.
176///
177/// \param Cursor the cursor to visit.
178///
179/// \param CheckedRegionOfInterest if true, then the caller already checked
180/// that this cursor is within the region of interest.
181///
182/// \returns true if the visitation should be aborted, false if it
183/// should continue.
184bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
185 if (clang_isInvalid(Cursor.kind))
186 return false;
187
188 if (clang_isDeclaration(Cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +0000189 const Decl *D = getCursorDecl(Cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +0000190 if (!D) {
191 assert(0 && "Invalid declaration cursor");
192 return true; // abort.
193 }
194
195 // Ignore implicit declarations, unless it's an objc method because
196 // currently we should report implicit methods for properties when indexing.
197 if (D->isImplicit() && !isa<ObjCMethodDecl>(D))
198 return false;
199 }
200
201 // If we have a range of interest, and this cursor doesn't intersect with it,
202 // we're done.
203 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
204 SourceRange Range = getRawCursorExtent(Cursor);
205 if (Range.isInvalid() || CompareRegionOfInterest(Range))
206 return false;
207 }
208
209 switch (Visitor(Cursor, Parent, ClientData)) {
210 case CXChildVisit_Break:
211 return true;
212
213 case CXChildVisit_Continue:
214 return false;
215
216 case CXChildVisit_Recurse: {
217 bool ret = VisitChildren(Cursor);
218 if (PostChildrenVisitor)
219 if (PostChildrenVisitor(Cursor, ClientData))
220 return true;
221 return ret;
222 }
223 }
224
225 llvm_unreachable("Invalid CXChildVisitResult!");
226}
227
228static bool visitPreprocessedEntitiesInRange(SourceRange R,
229 PreprocessingRecord &PPRec,
230 CursorVisitor &Visitor) {
231 SourceManager &SM = Visitor.getASTUnit()->getSourceManager();
232 FileID FID;
233
234 if (!Visitor.shouldVisitIncludedEntities()) {
235 // If the begin/end of the range lie in the same FileID, do the optimization
236 // where we skip preprocessed entities that do not come from the same FileID.
237 FID = SM.getFileID(SM.getFileLoc(R.getBegin()));
238 if (FID != SM.getFileID(SM.getFileLoc(R.getEnd())))
239 FID = FileID();
240 }
241
Benjamin Kramerb4ef6682015-02-06 17:25:10 +0000242 const auto &Entities = PPRec.getPreprocessedEntitiesInRange(R);
243 return Visitor.visitPreprocessedEntities(Entities.begin(), Entities.end(),
Guy Benyei11169dd2012-12-18 14:30:41 +0000244 PPRec, FID);
245}
246
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000247bool CursorVisitor::visitFileRegion() {
Guy Benyei11169dd2012-12-18 14:30:41 +0000248 if (RegionOfInterest.isInvalid())
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000249 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000250
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +0000251 ASTUnit *Unit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +0000252 SourceManager &SM = Unit->getSourceManager();
253
254 std::pair<FileID, unsigned>
255 Begin = SM.getDecomposedLoc(SM.getFileLoc(RegionOfInterest.getBegin())),
256 End = SM.getDecomposedLoc(SM.getFileLoc(RegionOfInterest.getEnd()));
257
258 if (End.first != Begin.first) {
259 // If the end does not reside in the same file, try to recover by
260 // picking the end of the file of begin location.
261 End.first = Begin.first;
262 End.second = SM.getFileIDSize(Begin.first);
263 }
264
265 assert(Begin.first == End.first);
266 if (Begin.second > End.second)
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000267 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000268
269 FileID File = Begin.first;
270 unsigned Offset = Begin.second;
271 unsigned Length = End.second - Begin.second;
272
273 if (!VisitDeclsOnly && !VisitPreprocessorLast)
274 if (visitPreprocessedEntitiesInRegion())
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000275 return true; // visitation break.
Guy Benyei11169dd2012-12-18 14:30:41 +0000276
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000277 if (visitDeclsFromFileRegion(File, Offset, Length))
278 return true; // visitation break.
Guy Benyei11169dd2012-12-18 14:30:41 +0000279
280 if (!VisitDeclsOnly && VisitPreprocessorLast)
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000281 return visitPreprocessedEntitiesInRegion();
282
283 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000284}
285
286static bool isInLexicalContext(Decl *D, DeclContext *DC) {
287 if (!DC)
288 return false;
289
290 for (DeclContext *DeclDC = D->getLexicalDeclContext();
291 DeclDC; DeclDC = DeclDC->getLexicalParent()) {
292 if (DeclDC == DC)
293 return true;
294 }
295 return false;
296}
297
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000298bool CursorVisitor::visitDeclsFromFileRegion(FileID File,
Guy Benyei11169dd2012-12-18 14:30:41 +0000299 unsigned Offset, unsigned Length) {
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +0000300 ASTUnit *Unit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +0000301 SourceManager &SM = Unit->getSourceManager();
302 SourceRange Range = RegionOfInterest;
303
304 SmallVector<Decl *, 16> Decls;
305 Unit->findFileRegionDecls(File, Offset, Length, Decls);
306
307 // If we didn't find any file level decls for the file, try looking at the
308 // file that it was included from.
309 while (Decls.empty() || Decls.front()->isTopLevelDeclInObjCContainer()) {
310 bool Invalid = false;
311 const SrcMgr::SLocEntry &SLEntry = SM.getSLocEntry(File, &Invalid);
312 if (Invalid)
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000313 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000314
315 SourceLocation Outer;
316 if (SLEntry.isFile())
317 Outer = SLEntry.getFile().getIncludeLoc();
318 else
319 Outer = SLEntry.getExpansion().getExpansionLocStart();
320 if (Outer.isInvalid())
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000321 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000322
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000323 std::tie(File, Offset) = SM.getDecomposedExpansionLoc(Outer);
Guy Benyei11169dd2012-12-18 14:30:41 +0000324 Length = 0;
325 Unit->findFileRegionDecls(File, Offset, Length, Decls);
326 }
327
328 assert(!Decls.empty());
329
330 bool VisitedAtLeastOnce = false;
Craig Topper69186e72014-06-08 08:38:04 +0000331 DeclContext *CurDC = nullptr;
Craig Topper2341c0d2013-07-04 03:08:24 +0000332 SmallVectorImpl<Decl *>::iterator DIt = Decls.begin();
333 for (SmallVectorImpl<Decl *>::iterator DE = Decls.end(); DIt != DE; ++DIt) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000334 Decl *D = *DIt;
335 if (D->getSourceRange().isInvalid())
336 continue;
337
338 if (isInLexicalContext(D, CurDC))
339 continue;
340
341 CurDC = dyn_cast<DeclContext>(D);
342
343 if (TagDecl *TD = dyn_cast<TagDecl>(D))
344 if (!TD->isFreeStanding())
345 continue;
346
347 RangeComparisonResult CompRes = RangeCompare(SM, D->getSourceRange(),Range);
348 if (CompRes == RangeBefore)
349 continue;
350 if (CompRes == RangeAfter)
351 break;
352
353 assert(CompRes == RangeOverlap);
354 VisitedAtLeastOnce = true;
355
356 if (isa<ObjCContainerDecl>(D)) {
357 FileDI_current = &DIt;
358 FileDE_current = DE;
359 } else {
Craig Topper69186e72014-06-08 08:38:04 +0000360 FileDI_current = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +0000361 }
362
363 if (Visit(MakeCXCursor(D, TU, Range), /*CheckedRegionOfInterest=*/true))
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000364 return true; // visitation break.
Guy Benyei11169dd2012-12-18 14:30:41 +0000365 }
366
367 if (VisitedAtLeastOnce)
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000368 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000369
370 // No Decls overlapped with the range. Move up the lexical context until there
371 // is a context that contains the range or we reach the translation unit
372 // level.
373 DeclContext *DC = DIt == Decls.begin() ? (*DIt)->getLexicalDeclContext()
374 : (*(DIt-1))->getLexicalDeclContext();
375
376 while (DC && !DC->isTranslationUnit()) {
377 Decl *D = cast<Decl>(DC);
378 SourceRange CurDeclRange = D->getSourceRange();
379 if (CurDeclRange.isInvalid())
380 break;
381
382 if (RangeCompare(SM, CurDeclRange, Range) == RangeOverlap) {
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000383 if (Visit(MakeCXCursor(D, TU, Range), /*CheckedRegionOfInterest=*/true))
384 return true; // visitation break.
Guy Benyei11169dd2012-12-18 14:30:41 +0000385 }
386
387 DC = D->getLexicalDeclContext();
388 }
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000389
390 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000391}
392
393bool CursorVisitor::visitPreprocessedEntitiesInRegion() {
394 if (!AU->getPreprocessor().getPreprocessingRecord())
395 return false;
396
397 PreprocessingRecord &PPRec
398 = *AU->getPreprocessor().getPreprocessingRecord();
399 SourceManager &SM = AU->getSourceManager();
400
401 if (RegionOfInterest.isValid()) {
402 SourceRange MappedRange = AU->mapRangeToPreamble(RegionOfInterest);
403 SourceLocation B = MappedRange.getBegin();
404 SourceLocation E = MappedRange.getEnd();
405
406 if (AU->isInPreambleFileID(B)) {
407 if (SM.isLoadedSourceLocation(E))
408 return visitPreprocessedEntitiesInRange(SourceRange(B, E),
409 PPRec, *this);
410
411 // Beginning of range lies in the preamble but it also extends beyond
412 // it into the main file. Split the range into 2 parts, one covering
413 // the preamble and another covering the main file. This allows subsequent
414 // calls to visitPreprocessedEntitiesInRange to accept a source range that
415 // lies in the same FileID, allowing it to skip preprocessed entities that
416 // do not come from the same FileID.
417 bool breaked =
418 visitPreprocessedEntitiesInRange(
419 SourceRange(B, AU->getEndOfPreambleFileID()),
420 PPRec, *this);
421 if (breaked) return true;
422 return visitPreprocessedEntitiesInRange(
423 SourceRange(AU->getStartOfMainFileID(), E),
424 PPRec, *this);
425 }
426
427 return visitPreprocessedEntitiesInRange(SourceRange(B, E), PPRec, *this);
428 }
429
430 bool OnlyLocalDecls
431 = !AU->isMainFileAST() && AU->getOnlyLocalDecls();
432
433 if (OnlyLocalDecls)
434 return visitPreprocessedEntities(PPRec.local_begin(), PPRec.local_end(),
435 PPRec);
436
437 return visitPreprocessedEntities(PPRec.begin(), PPRec.end(), PPRec);
438}
439
440template<typename InputIterator>
441bool CursorVisitor::visitPreprocessedEntities(InputIterator First,
442 InputIterator Last,
443 PreprocessingRecord &PPRec,
444 FileID FID) {
445 for (; First != Last; ++First) {
446 if (!FID.isInvalid() && !PPRec.isEntityInFileID(First, FID))
447 continue;
448
449 PreprocessedEntity *PPE = *First;
Argyrios Kyrtzidis1030f262013-05-07 20:37:17 +0000450 if (!PPE)
451 continue;
452
Guy Benyei11169dd2012-12-18 14:30:41 +0000453 if (MacroExpansion *ME = dyn_cast<MacroExpansion>(PPE)) {
454 if (Visit(MakeMacroExpansionCursor(ME, TU)))
455 return true;
Richard Smith66a81862015-05-04 02:25:31 +0000456
Guy Benyei11169dd2012-12-18 14:30:41 +0000457 continue;
458 }
Richard Smith66a81862015-05-04 02:25:31 +0000459
460 if (MacroDefinitionRecord *MD = dyn_cast<MacroDefinitionRecord>(PPE)) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000461 if (Visit(MakeMacroDefinitionCursor(MD, TU)))
462 return true;
Richard Smith66a81862015-05-04 02:25:31 +0000463
Guy Benyei11169dd2012-12-18 14:30:41 +0000464 continue;
465 }
466
467 if (InclusionDirective *ID = dyn_cast<InclusionDirective>(PPE)) {
468 if (Visit(MakeInclusionDirectiveCursor(ID, TU)))
469 return true;
470
471 continue;
472 }
473 }
474
475 return false;
476}
477
478/// \brief Visit the children of the given cursor.
479///
480/// \returns true if the visitation should be aborted, false if it
481/// should continue.
482bool CursorVisitor::VisitChildren(CXCursor Cursor) {
483 if (clang_isReference(Cursor.kind) &&
484 Cursor.kind != CXCursor_CXXBaseSpecifier) {
485 // By definition, references have no children.
486 return false;
487 }
488
489 // Set the Parent field to Cursor, then back to its old value once we're
490 // done.
491 SetParentRAII SetParent(Parent, StmtParent, Cursor);
492
493 if (clang_isDeclaration(Cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +0000494 Decl *D = const_cast<Decl *>(getCursorDecl(Cursor));
Guy Benyei11169dd2012-12-18 14:30:41 +0000495 if (!D)
496 return false;
497
498 return VisitAttributes(D) || Visit(D);
499 }
500
501 if (clang_isStatement(Cursor.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +0000502 if (const Stmt *S = getCursorStmt(Cursor))
Guy Benyei11169dd2012-12-18 14:30:41 +0000503 return Visit(S);
504
505 return false;
506 }
507
508 if (clang_isExpression(Cursor.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +0000509 if (const Expr *E = getCursorExpr(Cursor))
Guy Benyei11169dd2012-12-18 14:30:41 +0000510 return Visit(E);
511
512 return false;
513 }
514
515 if (clang_isTranslationUnit(Cursor.kind)) {
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +0000516 CXTranslationUnit TU = getCursorTU(Cursor);
517 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +0000518
519 int VisitOrder[2] = { VisitPreprocessorLast, !VisitPreprocessorLast };
520 for (unsigned I = 0; I != 2; ++I) {
521 if (VisitOrder[I]) {
522 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
523 RegionOfInterest.isInvalid()) {
524 for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
525 TLEnd = CXXUnit->top_level_end();
526 TL != TLEnd; ++TL) {
Argyrios Kyrtzidise7c91042016-07-01 19:10:54 +0000527 const Optional<bool> V = handleDeclForVisitation(*TL);
528 if (!V.hasValue())
529 continue;
530 return V.getValue();
Guy Benyei11169dd2012-12-18 14:30:41 +0000531 }
532 } else if (VisitDeclContext(
533 CXXUnit->getASTContext().getTranslationUnitDecl()))
534 return true;
535 continue;
536 }
537
538 // Walk the preprocessing record.
539 if (CXXUnit->getPreprocessor().getPreprocessingRecord())
540 visitPreprocessedEntitiesInRegion();
541 }
542
543 return false;
544 }
545
546 if (Cursor.kind == CXCursor_CXXBaseSpecifier) {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +0000547 if (const CXXBaseSpecifier *Base = getCursorCXXBaseSpecifier(Cursor)) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000548 if (TypeSourceInfo *BaseTSInfo = Base->getTypeSourceInfo()) {
549 return Visit(BaseTSInfo->getTypeLoc());
550 }
551 }
552 }
553
554 if (Cursor.kind == CXCursor_IBOutletCollectionAttr) {
Dmitri Gribenkoe4baea62013-01-26 18:08:08 +0000555 const IBOutletCollectionAttr *A =
Guy Benyei11169dd2012-12-18 14:30:41 +0000556 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(Cursor));
Richard Smithb1f9a282013-10-31 01:56:18 +0000557 if (const ObjCObjectType *ObjT = A->getInterface()->getAs<ObjCObjectType>())
Richard Smithb87c4652013-10-31 21:23:20 +0000558 return Visit(cxcursor::MakeCursorObjCClassRef(
559 ObjT->getInterface(),
560 A->getInterfaceLoc()->getTypeLoc().getLocStart(), TU));
Guy Benyei11169dd2012-12-18 14:30:41 +0000561 }
562
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +0000563 // If pointing inside a macro definition, check if the token is an identifier
564 // that was ever defined as a macro. In such a case, create a "pseudo" macro
565 // expansion cursor for that token.
566 SourceLocation BeginLoc = RegionOfInterest.getBegin();
567 if (Cursor.kind == CXCursor_MacroDefinition &&
568 BeginLoc == RegionOfInterest.getEnd()) {
569 SourceLocation Loc = AU->mapLocationToPreamble(BeginLoc);
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +0000570 const MacroInfo *MI =
571 getMacroInfo(cxcursor::getCursorMacroDefinition(Cursor), TU);
Richard Smith66a81862015-05-04 02:25:31 +0000572 if (MacroDefinitionRecord *MacroDef =
573 checkForMacroInMacroDefinition(MI, Loc, TU))
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +0000574 return Visit(cxcursor::MakeMacroExpansionCursor(MacroDef, BeginLoc, TU));
575 }
576
Guy Benyei11169dd2012-12-18 14:30:41 +0000577 // Nothing to visit at the moment.
578 return false;
579}
580
581bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
582 if (TypeSourceInfo *TSInfo = B->getSignatureAsWritten())
583 if (Visit(TSInfo->getTypeLoc()))
584 return true;
585
586 if (Stmt *Body = B->getBody())
587 return Visit(MakeCXCursor(Body, StmtParent, TU, RegionOfInterest));
588
589 return false;
590}
591
Ted Kremenek03325582013-02-21 01:29:01 +0000592Optional<bool> CursorVisitor::shouldVisitCursor(CXCursor Cursor) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000593 if (RegionOfInterest.isValid()) {
594 SourceRange Range = getFullCursorExtent(Cursor, AU->getSourceManager());
595 if (Range.isInvalid())
David Blaikie7a30dc52013-02-21 01:47:18 +0000596 return None;
Guy Benyei11169dd2012-12-18 14:30:41 +0000597
598 switch (CompareRegionOfInterest(Range)) {
599 case RangeBefore:
600 // This declaration comes before the region of interest; skip it.
David Blaikie7a30dc52013-02-21 01:47:18 +0000601 return None;
Guy Benyei11169dd2012-12-18 14:30:41 +0000602
603 case RangeAfter:
604 // This declaration comes after the region of interest; we're done.
605 return false;
606
607 case RangeOverlap:
608 // This declaration overlaps the region of interest; visit it.
609 break;
610 }
611 }
612 return true;
613}
614
615bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
616 DeclContext::decl_iterator I = DC->decls_begin(), E = DC->decls_end();
617
618 // FIXME: Eventually remove. This part of a hack to support proper
619 // iteration over all Decls contained lexically within an ObjC container.
620 SaveAndRestore<DeclContext::decl_iterator*> DI_saved(DI_current, &I);
621 SaveAndRestore<DeclContext::decl_iterator> DE_saved(DE_current, E);
622
623 for ( ; I != E; ++I) {
624 Decl *D = *I;
625 if (D->getLexicalDeclContext() != DC)
626 continue;
Argyrios Kyrtzidise7c91042016-07-01 19:10:54 +0000627 const Optional<bool> V = handleDeclForVisitation(D);
Guy Benyei11169dd2012-12-18 14:30:41 +0000628 if (!V.hasValue())
629 continue;
Argyrios Kyrtzidise7c91042016-07-01 19:10:54 +0000630 return V.getValue();
Guy Benyei11169dd2012-12-18 14:30:41 +0000631 }
632 return false;
633}
634
Argyrios Kyrtzidise7c91042016-07-01 19:10:54 +0000635Optional<bool> CursorVisitor::handleDeclForVisitation(const Decl *D) {
636 CXCursor Cursor = MakeCXCursor(D, TU, RegionOfInterest);
637
638 // Ignore synthesized ivars here, otherwise if we have something like:
639 // @synthesize prop = _prop;
640 // and '_prop' is not declared, we will encounter a '_prop' ivar before
641 // encountering the 'prop' synthesize declaration and we will think that
642 // we passed the region-of-interest.
643 if (auto *ivarD = dyn_cast<ObjCIvarDecl>(D)) {
644 if (ivarD->getSynthesize())
645 return None;
646 }
647
648 // FIXME: ObjCClassRef/ObjCProtocolRef for forward class/protocol
649 // declarations is a mismatch with the compiler semantics.
650 if (Cursor.kind == CXCursor_ObjCInterfaceDecl) {
651 auto *ID = cast<ObjCInterfaceDecl>(D);
652 if (!ID->isThisDeclarationADefinition())
653 Cursor = MakeCursorObjCClassRef(ID, ID->getLocation(), TU);
654
655 } else if (Cursor.kind == CXCursor_ObjCProtocolDecl) {
656 auto *PD = cast<ObjCProtocolDecl>(D);
657 if (!PD->isThisDeclarationADefinition())
658 Cursor = MakeCursorObjCProtocolRef(PD, PD->getLocation(), TU);
659 }
660
661 const Optional<bool> V = shouldVisitCursor(Cursor);
662 if (!V.hasValue())
663 return None;
664 if (!V.getValue())
665 return false;
666 if (Visit(Cursor, true))
667 return true;
668 return None;
669}
670
Guy Benyei11169dd2012-12-18 14:30:41 +0000671bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
672 llvm_unreachable("Translation units are visited directly by Visit()");
673}
674
Sergey Kalinichev8f3b1872015-11-15 13:48:32 +0000675bool CursorVisitor::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
676 if (VisitTemplateParameters(D->getTemplateParameters()))
677 return true;
678
679 return Visit(MakeCXCursor(D->getTemplatedDecl(), TU, RegionOfInterest));
680}
681
Guy Benyei11169dd2012-12-18 14:30:41 +0000682bool CursorVisitor::VisitTypeAliasDecl(TypeAliasDecl *D) {
683 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
684 return Visit(TSInfo->getTypeLoc());
685
686 return false;
687}
688
689bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
690 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
691 return Visit(TSInfo->getTypeLoc());
692
693 return false;
694}
695
696bool CursorVisitor::VisitTagDecl(TagDecl *D) {
697 return VisitDeclContext(D);
698}
699
700bool CursorVisitor::VisitClassTemplateSpecializationDecl(
701 ClassTemplateSpecializationDecl *D) {
702 bool ShouldVisitBody = false;
703 switch (D->getSpecializationKind()) {
704 case TSK_Undeclared:
705 case TSK_ImplicitInstantiation:
706 // Nothing to visit
707 return false;
708
709 case TSK_ExplicitInstantiationDeclaration:
710 case TSK_ExplicitInstantiationDefinition:
711 break;
712
713 case TSK_ExplicitSpecialization:
714 ShouldVisitBody = true;
715 break;
716 }
717
718 // Visit the template arguments used in the specialization.
719 if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) {
720 TypeLoc TL = SpecType->getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +0000721 if (TemplateSpecializationTypeLoc TSTLoc =
722 TL.getAs<TemplateSpecializationTypeLoc>()) {
723 for (unsigned I = 0, N = TSTLoc.getNumArgs(); I != N; ++I)
724 if (VisitTemplateArgumentLoc(TSTLoc.getArgLoc(I)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000725 return true;
726 }
727 }
Alexander Kornienko1a9f1842015-12-28 15:24:08 +0000728
729 return ShouldVisitBody && VisitCXXRecordDecl(D);
Guy Benyei11169dd2012-12-18 14:30:41 +0000730}
731
732bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl(
733 ClassTemplatePartialSpecializationDecl *D) {
734 // FIXME: Visit the "outer" template parameter lists on the TagDecl
735 // before visiting these template parameters.
736 if (VisitTemplateParameters(D->getTemplateParameters()))
737 return true;
738
739 // Visit the partial specialization arguments.
Enea Zaffanella6dbe1872013-08-10 07:24:53 +0000740 const ASTTemplateArgumentListInfo *Info = D->getTemplateArgsAsWritten();
741 const TemplateArgumentLoc *TemplateArgs = Info->getTemplateArgs();
742 for (unsigned I = 0, N = Info->NumTemplateArgs; I != N; ++I)
Guy Benyei11169dd2012-12-18 14:30:41 +0000743 if (VisitTemplateArgumentLoc(TemplateArgs[I]))
744 return true;
745
746 return VisitCXXRecordDecl(D);
747}
748
749bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
750 // Visit the default argument.
751 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
752 if (TypeSourceInfo *DefArg = D->getDefaultArgumentInfo())
753 if (Visit(DefArg->getTypeLoc()))
754 return true;
755
756 return false;
757}
758
759bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
760 if (Expr *Init = D->getInitExpr())
761 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
762 return false;
763}
764
765bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
Argyrios Kyrtzidis2ec76742013-04-05 21:04:10 +0000766 unsigned NumParamList = DD->getNumTemplateParameterLists();
767 for (unsigned i = 0; i < NumParamList; i++) {
768 TemplateParameterList* Params = DD->getTemplateParameterList(i);
769 if (VisitTemplateParameters(Params))
770 return true;
771 }
772
Guy Benyei11169dd2012-12-18 14:30:41 +0000773 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
774 if (Visit(TSInfo->getTypeLoc()))
775 return true;
776
777 // Visit the nested-name-specifier, if present.
778 if (NestedNameSpecifierLoc QualifierLoc = DD->getQualifierLoc())
779 if (VisitNestedNameSpecifierLoc(QualifierLoc))
780 return true;
781
782 return false;
783}
784
Benjamin Kramer4cadf292014-03-07 21:51:58 +0000785/// \brief Compare two base or member initializers based on their source order.
786static int CompareCXXCtorInitializers(CXXCtorInitializer *const *X,
787 CXXCtorInitializer *const *Y) {
788 return (*X)->getSourceOrder() - (*Y)->getSourceOrder();
789}
790
Guy Benyei11169dd2012-12-18 14:30:41 +0000791bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Argyrios Kyrtzidis2ec76742013-04-05 21:04:10 +0000792 unsigned NumParamList = ND->getNumTemplateParameterLists();
793 for (unsigned i = 0; i < NumParamList; i++) {
794 TemplateParameterList* Params = ND->getTemplateParameterList(i);
795 if (VisitTemplateParameters(Params))
796 return true;
797 }
798
Guy Benyei11169dd2012-12-18 14:30:41 +0000799 if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
800 // Visit the function declaration's syntactic components in the order
801 // written. This requires a bit of work.
802 TypeLoc TL = TSInfo->getTypeLoc().IgnoreParens();
David Blaikie6adc78e2013-02-18 22:06:02 +0000803 FunctionTypeLoc FTL = TL.getAs<FunctionTypeLoc>();
Guy Benyei11169dd2012-12-18 14:30:41 +0000804
805 // If we have a function declared directly (without the use of a typedef),
806 // visit just the return type. Otherwise, just visit the function's type
807 // now.
Alp Toker42a16a62014-01-25 23:51:36 +0000808 if ((FTL && !isa<CXXConversionDecl>(ND) && Visit(FTL.getReturnLoc())) ||
Guy Benyei11169dd2012-12-18 14:30:41 +0000809 (!FTL && Visit(TL)))
810 return true;
811
812 // Visit the nested-name-specifier, if present.
813 if (NestedNameSpecifierLoc QualifierLoc = ND->getQualifierLoc())
814 if (VisitNestedNameSpecifierLoc(QualifierLoc))
815 return true;
816
817 // Visit the declaration name.
Argyrios Kyrtzidis4a4d2b42014-02-09 08:13:47 +0000818 if (!isa<CXXDestructorDecl>(ND))
819 if (VisitDeclarationNameInfo(ND->getNameInfo()))
820 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +0000821
822 // FIXME: Visit explicitly-specified template arguments!
823
824 // Visit the function parameters, if we have a function type.
David Blaikie6adc78e2013-02-18 22:06:02 +0000825 if (FTL && VisitFunctionTypeLoc(FTL, true))
Guy Benyei11169dd2012-12-18 14:30:41 +0000826 return true;
827
Bill Wendling44426052012-12-20 19:22:21 +0000828 // FIXME: Attributes?
Guy Benyei11169dd2012-12-18 14:30:41 +0000829 }
830
831 if (ND->doesThisDeclarationHaveABody() && !ND->isLateTemplateParsed()) {
832 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ND)) {
833 // Find the initializers that were written in the source.
834 SmallVector<CXXCtorInitializer *, 4> WrittenInits;
Aaron Ballman0ad78302014-03-13 17:34:31 +0000835 for (auto *I : Constructor->inits()) {
836 if (!I->isWritten())
Guy Benyei11169dd2012-12-18 14:30:41 +0000837 continue;
838
Aaron Ballman0ad78302014-03-13 17:34:31 +0000839 WrittenInits.push_back(I);
Guy Benyei11169dd2012-12-18 14:30:41 +0000840 }
841
842 // Sort the initializers in source order
Benjamin Kramer4cadf292014-03-07 21:51:58 +0000843 llvm::array_pod_sort(WrittenInits.begin(), WrittenInits.end(),
844 &CompareCXXCtorInitializers);
845
Guy Benyei11169dd2012-12-18 14:30:41 +0000846 // Visit the initializers in source order
847 for (unsigned I = 0, N = WrittenInits.size(); I != N; ++I) {
848 CXXCtorInitializer *Init = WrittenInits[I];
849 if (Init->isAnyMemberInitializer()) {
850 if (Visit(MakeCursorMemberRef(Init->getAnyMember(),
851 Init->getMemberLocation(), TU)))
852 return true;
853 } else if (TypeSourceInfo *TInfo = Init->getTypeSourceInfo()) {
854 if (Visit(TInfo->getTypeLoc()))
855 return true;
856 }
857
858 // Visit the initializer value.
859 if (Expr *Initializer = Init->getInit())
860 if (Visit(MakeCXCursor(Initializer, ND, TU, RegionOfInterest)))
861 return true;
862 }
863 }
864
865 if (Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest)))
866 return true;
867 }
868
869 return false;
870}
871
872bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
873 if (VisitDeclaratorDecl(D))
874 return true;
875
876 if (Expr *BitWidth = D->getBitWidth())
877 return Visit(MakeCXCursor(BitWidth, StmtParent, TU, RegionOfInterest));
878
879 return false;
880}
881
882bool CursorVisitor::VisitVarDecl(VarDecl *D) {
883 if (VisitDeclaratorDecl(D))
884 return true;
885
886 if (Expr *Init = D->getInit())
887 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
888
889 return false;
890}
891
892bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
893 if (VisitDeclaratorDecl(D))
894 return true;
895
896 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
897 if (Expr *DefArg = D->getDefaultArgument())
898 return Visit(MakeCXCursor(DefArg, StmtParent, TU, RegionOfInterest));
899
900 return false;
901}
902
903bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
904 // FIXME: Visit the "outer" template parameter lists on the FunctionDecl
905 // before visiting these template parameters.
906 if (VisitTemplateParameters(D->getTemplateParameters()))
907 return true;
908
909 return VisitFunctionDecl(D->getTemplatedDecl());
910}
911
912bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) {
913 // FIXME: Visit the "outer" template parameter lists on the TagDecl
914 // before visiting these template parameters.
915 if (VisitTemplateParameters(D->getTemplateParameters()))
916 return true;
917
918 return VisitCXXRecordDecl(D->getTemplatedDecl());
919}
920
921bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
922 if (VisitTemplateParameters(D->getTemplateParameters()))
923 return true;
924
925 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() &&
926 VisitTemplateArgumentLoc(D->getDefaultArgument()))
927 return true;
928
929 return false;
930}
931
Douglas Gregor9bda6cf2015-07-07 03:58:14 +0000932bool CursorVisitor::VisitObjCTypeParamDecl(ObjCTypeParamDecl *D) {
933 // Visit the bound, if it's explicit.
934 if (D->hasExplicitBound()) {
935 if (auto TInfo = D->getTypeSourceInfo()) {
936 if (Visit(TInfo->getTypeLoc()))
937 return true;
938 }
939 }
940
941 return false;
942}
943
Guy Benyei11169dd2012-12-18 14:30:41 +0000944bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Alp Toker314cc812014-01-25 16:55:45 +0000945 if (TypeSourceInfo *TSInfo = ND->getReturnTypeSourceInfo())
Guy Benyei11169dd2012-12-18 14:30:41 +0000946 if (Visit(TSInfo->getTypeLoc()))
947 return true;
948
David Majnemer59f77922016-06-24 04:05:48 +0000949 for (const auto *P : ND->parameters()) {
Aaron Ballman43b68be2014-03-07 17:50:17 +0000950 if (Visit(MakeCXCursor(P, TU, RegionOfInterest)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000951 return true;
952 }
953
Alexander Kornienko1a9f1842015-12-28 15:24:08 +0000954 return ND->isThisDeclarationADefinition() &&
955 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest));
Guy Benyei11169dd2012-12-18 14:30:41 +0000956}
957
958template <typename DeclIt>
959static void addRangedDeclsInContainer(DeclIt *DI_current, DeclIt DE_current,
960 SourceManager &SM, SourceLocation EndLoc,
961 SmallVectorImpl<Decl *> &Decls) {
962 DeclIt next = *DI_current;
963 while (++next != DE_current) {
964 Decl *D_next = *next;
965 if (!D_next)
966 break;
967 SourceLocation L = D_next->getLocStart();
968 if (!L.isValid())
969 break;
970 if (SM.isBeforeInTranslationUnit(L, EndLoc)) {
971 *DI_current = next;
972 Decls.push_back(D_next);
973 continue;
974 }
975 break;
976 }
977}
978
Guy Benyei11169dd2012-12-18 14:30:41 +0000979bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
980 // FIXME: Eventually convert back to just 'VisitDeclContext()'. Essentially
981 // an @implementation can lexically contain Decls that are not properly
982 // nested in the AST. When we identify such cases, we need to retrofit
983 // this nesting here.
984 if (!DI_current && !FileDI_current)
985 return VisitDeclContext(D);
986
987 // Scan the Decls that immediately come after the container
988 // in the current DeclContext. If any fall within the
989 // container's lexical region, stash them into a vector
990 // for later processing.
991 SmallVector<Decl *, 24> DeclsInContainer;
992 SourceLocation EndLoc = D->getSourceRange().getEnd();
993 SourceManager &SM = AU->getSourceManager();
994 if (EndLoc.isValid()) {
995 if (DI_current) {
996 addRangedDeclsInContainer(DI_current, DE_current, SM, EndLoc,
997 DeclsInContainer);
998 } else {
999 addRangedDeclsInContainer(FileDI_current, FileDE_current, SM, EndLoc,
1000 DeclsInContainer);
1001 }
1002 }
1003
1004 // The common case.
1005 if (DeclsInContainer.empty())
1006 return VisitDeclContext(D);
1007
1008 // Get all the Decls in the DeclContext, and sort them with the
1009 // additional ones we've collected. Then visit them.
Aaron Ballman629afae2014-03-07 19:56:05 +00001010 for (auto *SubDecl : D->decls()) {
1011 if (!SubDecl || SubDecl->getLexicalDeclContext() != D ||
1012 SubDecl->getLocStart().isInvalid())
Guy Benyei11169dd2012-12-18 14:30:41 +00001013 continue;
Aaron Ballman629afae2014-03-07 19:56:05 +00001014 DeclsInContainer.push_back(SubDecl);
Guy Benyei11169dd2012-12-18 14:30:41 +00001015 }
1016
1017 // Now sort the Decls so that they appear in lexical order.
1018 std::sort(DeclsInContainer.begin(), DeclsInContainer.end(),
Benjamin Kramerbbdd7642014-03-01 14:48:57 +00001019 [&SM](Decl *A, Decl *B) {
1020 SourceLocation L_A = A->getLocStart();
1021 SourceLocation L_B = B->getLocStart();
1022 assert(L_A.isValid() && L_B.isValid());
1023 return SM.isBeforeInTranslationUnit(L_A, L_B);
1024 });
Guy Benyei11169dd2012-12-18 14:30:41 +00001025
1026 // Now visit the decls.
1027 for (SmallVectorImpl<Decl*>::iterator I = DeclsInContainer.begin(),
1028 E = DeclsInContainer.end(); I != E; ++I) {
1029 CXCursor Cursor = MakeCXCursor(*I, TU, RegionOfInterest);
Ted Kremenek03325582013-02-21 01:29:01 +00001030 const Optional<bool> &V = shouldVisitCursor(Cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00001031 if (!V.hasValue())
1032 continue;
1033 if (!V.getValue())
1034 return false;
1035 if (Visit(Cursor, true))
1036 return true;
1037 }
1038 return false;
1039}
1040
1041bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
1042 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
1043 TU)))
1044 return true;
1045
Douglas Gregore9d95f12015-07-07 03:57:35 +00001046 if (VisitObjCTypeParamList(ND->getTypeParamList()))
1047 return true;
1048
Guy Benyei11169dd2012-12-18 14:30:41 +00001049 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
1050 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
1051 E = ND->protocol_end(); I != E; ++I, ++PL)
1052 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
1053 return true;
1054
1055 return VisitObjCContainerDecl(ND);
1056}
1057
1058bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
1059 if (!PID->isThisDeclarationADefinition())
1060 return Visit(MakeCursorObjCProtocolRef(PID, PID->getLocation(), TU));
1061
1062 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
1063 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
1064 E = PID->protocol_end(); I != E; ++I, ++PL)
1065 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
1066 return true;
1067
1068 return VisitObjCContainerDecl(PID);
1069}
1070
1071bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
1072 if (PD->getTypeSourceInfo() && Visit(PD->getTypeSourceInfo()->getTypeLoc()))
1073 return true;
1074
1075 // FIXME: This implements a workaround with @property declarations also being
1076 // installed in the DeclContext for the @interface. Eventually this code
1077 // should be removed.
1078 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
1079 if (!CDecl || !CDecl->IsClassExtension())
1080 return false;
1081
1082 ObjCInterfaceDecl *ID = CDecl->getClassInterface();
1083 if (!ID)
1084 return false;
1085
1086 IdentifierInfo *PropertyId = PD->getIdentifier();
1087 ObjCPropertyDecl *prevDecl =
Manman Ren5b786402016-01-28 18:49:28 +00001088 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId,
1089 PD->getQueryKind());
Guy Benyei11169dd2012-12-18 14:30:41 +00001090
1091 if (!prevDecl)
1092 return false;
1093
1094 // Visit synthesized methods since they will be skipped when visiting
1095 // the @interface.
1096 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
1097 if (MD->isPropertyAccessor() && MD->getLexicalDeclContext() == CDecl)
1098 if (Visit(MakeCXCursor(MD, TU, RegionOfInterest)))
1099 return true;
1100
1101 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
1102 if (MD->isPropertyAccessor() && MD->getLexicalDeclContext() == CDecl)
1103 if (Visit(MakeCXCursor(MD, TU, RegionOfInterest)))
1104 return true;
1105
1106 return false;
1107}
1108
Douglas Gregore9d95f12015-07-07 03:57:35 +00001109bool CursorVisitor::VisitObjCTypeParamList(ObjCTypeParamList *typeParamList) {
1110 if (!typeParamList)
1111 return false;
1112
1113 for (auto *typeParam : *typeParamList) {
1114 // Visit the type parameter.
1115 if (Visit(MakeCXCursor(typeParam, TU, RegionOfInterest)))
1116 return true;
Douglas Gregore9d95f12015-07-07 03:57:35 +00001117 }
1118
1119 return false;
1120}
1121
Guy Benyei11169dd2012-12-18 14:30:41 +00001122bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
1123 if (!D->isThisDeclarationADefinition()) {
1124 // Forward declaration is treated like a reference.
1125 return Visit(MakeCursorObjCClassRef(D, D->getLocation(), TU));
1126 }
1127
Douglas Gregore9d95f12015-07-07 03:57:35 +00001128 // Objective-C type parameters.
1129 if (VisitObjCTypeParamList(D->getTypeParamListAsWritten()))
1130 return true;
1131
Guy Benyei11169dd2012-12-18 14:30:41 +00001132 // Issue callbacks for super class.
1133 if (D->getSuperClass() &&
1134 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
1135 D->getSuperClassLoc(),
1136 TU)))
1137 return true;
1138
Douglas Gregore9d95f12015-07-07 03:57:35 +00001139 if (TypeSourceInfo *SuperClassTInfo = D->getSuperClassTInfo())
1140 if (Visit(SuperClassTInfo->getTypeLoc()))
1141 return true;
1142
Guy Benyei11169dd2012-12-18 14:30:41 +00001143 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1144 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
1145 E = D->protocol_end(); I != E; ++I, ++PL)
1146 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
1147 return true;
1148
1149 return VisitObjCContainerDecl(D);
1150}
1151
1152bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
1153 return VisitObjCContainerDecl(D);
1154}
1155
1156bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
1157 // 'ID' could be null when dealing with invalid code.
1158 if (ObjCInterfaceDecl *ID = D->getClassInterface())
1159 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
1160 return true;
1161
1162 return VisitObjCImplDecl(D);
1163}
1164
1165bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
1166#if 0
1167 // Issue callbacks for super class.
1168 // FIXME: No source location information!
1169 if (D->getSuperClass() &&
1170 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
1171 D->getSuperClassLoc(),
1172 TU)))
1173 return true;
1174#endif
1175
1176 return VisitObjCImplDecl(D);
1177}
1178
1179bool CursorVisitor::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *PD) {
1180 if (ObjCIvarDecl *Ivar = PD->getPropertyIvarDecl())
1181 if (PD->isIvarNameSpecified())
1182 return Visit(MakeCursorMemberRef(Ivar, PD->getPropertyIvarDeclLoc(), TU));
1183
1184 return false;
1185}
1186
1187bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
1188 return VisitDeclContext(D);
1189}
1190
1191bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
1192 // Visit nested-name-specifier.
1193 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1194 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1195 return true;
1196
1197 return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(),
1198 D->getTargetNameLoc(), TU));
1199}
1200
1201bool CursorVisitor::VisitUsingDecl(UsingDecl *D) {
1202 // Visit nested-name-specifier.
1203 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1204 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1205 return true;
1206 }
1207
1208 if (Visit(MakeCursorOverloadedDeclRef(D, D->getLocation(), TU)))
1209 return true;
1210
1211 return VisitDeclarationNameInfo(D->getNameInfo());
1212}
1213
1214bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
1215 // Visit nested-name-specifier.
1216 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1217 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1218 return true;
1219
1220 return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(),
1221 D->getIdentLocation(), TU));
1222}
1223
1224bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
1225 // Visit nested-name-specifier.
1226 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1227 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1228 return true;
1229 }
1230
1231 return VisitDeclarationNameInfo(D->getNameInfo());
1232}
1233
1234bool CursorVisitor::VisitUnresolvedUsingTypenameDecl(
1235 UnresolvedUsingTypenameDecl *D) {
1236 // Visit nested-name-specifier.
1237 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1238 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1239 return true;
1240
1241 return false;
1242}
1243
Olivier Goffart81978012016-06-09 16:15:55 +00001244bool CursorVisitor::VisitStaticAssertDecl(StaticAssertDecl *D) {
1245 if (Visit(MakeCXCursor(D->getAssertExpr(), StmtParent, TU, RegionOfInterest)))
1246 return true;
Richard Trieuf3b77662016-09-13 01:37:01 +00001247 if (StringLiteral *Message = D->getMessage())
1248 if (Visit(MakeCXCursor(Message, StmtParent, TU, RegionOfInterest)))
1249 return true;
Olivier Goffart81978012016-06-09 16:15:55 +00001250 return false;
1251}
1252
Olivier Goffartd211c642016-11-04 06:29:27 +00001253bool CursorVisitor::VisitFriendDecl(FriendDecl *D) {
1254 if (NamedDecl *FriendD = D->getFriendDecl()) {
1255 if (Visit(MakeCXCursor(FriendD, TU, RegionOfInterest)))
1256 return true;
1257 } else if (TypeSourceInfo *TI = D->getFriendType()) {
1258 if (Visit(TI->getTypeLoc()))
1259 return true;
1260 }
1261 return false;
1262}
1263
Guy Benyei11169dd2012-12-18 14:30:41 +00001264bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
1265 switch (Name.getName().getNameKind()) {
1266 case clang::DeclarationName::Identifier:
1267 case clang::DeclarationName::CXXLiteralOperatorName:
1268 case clang::DeclarationName::CXXOperatorName:
1269 case clang::DeclarationName::CXXUsingDirective:
1270 return false;
1271
1272 case clang::DeclarationName::CXXConstructorName:
1273 case clang::DeclarationName::CXXDestructorName:
1274 case clang::DeclarationName::CXXConversionFunctionName:
1275 if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
1276 return Visit(TSInfo->getTypeLoc());
1277 return false;
1278
1279 case clang::DeclarationName::ObjCZeroArgSelector:
1280 case clang::DeclarationName::ObjCOneArgSelector:
1281 case clang::DeclarationName::ObjCMultiArgSelector:
1282 // FIXME: Per-identifier location info?
1283 return false;
1284 }
1285
1286 llvm_unreachable("Invalid DeclarationName::Kind!");
1287}
1288
1289bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS,
1290 SourceRange Range) {
1291 // FIXME: This whole routine is a hack to work around the lack of proper
1292 // source information in nested-name-specifiers (PR5791). Since we do have
1293 // a beginning source location, we can visit the first component of the
1294 // nested-name-specifier, if it's a single-token component.
1295 if (!NNS)
1296 return false;
1297
1298 // Get the first component in the nested-name-specifier.
1299 while (NestedNameSpecifier *Prefix = NNS->getPrefix())
1300 NNS = Prefix;
1301
1302 switch (NNS->getKind()) {
1303 case NestedNameSpecifier::Namespace:
1304 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(),
1305 TU));
1306
1307 case NestedNameSpecifier::NamespaceAlias:
1308 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
1309 Range.getBegin(), TU));
1310
1311 case NestedNameSpecifier::TypeSpec: {
1312 // If the type has a form where we know that the beginning of the source
1313 // range matches up with a reference cursor. Visit the appropriate reference
1314 // cursor.
1315 const Type *T = NNS->getAsType();
1316 if (const TypedefType *Typedef = dyn_cast<TypedefType>(T))
1317 return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU));
1318 if (const TagType *Tag = dyn_cast<TagType>(T))
1319 return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU));
1320 if (const TemplateSpecializationType *TST
1321 = dyn_cast<TemplateSpecializationType>(T))
1322 return VisitTemplateName(TST->getTemplateName(), Range.getBegin());
1323 break;
1324 }
1325
1326 case NestedNameSpecifier::TypeSpecWithTemplate:
1327 case NestedNameSpecifier::Global:
1328 case NestedNameSpecifier::Identifier:
Nikola Smiljanic67860242014-09-26 00:28:20 +00001329 case NestedNameSpecifier::Super:
Guy Benyei11169dd2012-12-18 14:30:41 +00001330 break;
1331 }
1332
1333 return false;
1334}
1335
1336bool
1337CursorVisitor::VisitNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
1338 SmallVector<NestedNameSpecifierLoc, 4> Qualifiers;
1339 for (; Qualifier; Qualifier = Qualifier.getPrefix())
1340 Qualifiers.push_back(Qualifier);
1341
1342 while (!Qualifiers.empty()) {
1343 NestedNameSpecifierLoc Q = Qualifiers.pop_back_val();
1344 NestedNameSpecifier *NNS = Q.getNestedNameSpecifier();
1345 switch (NNS->getKind()) {
1346 case NestedNameSpecifier::Namespace:
1347 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(),
1348 Q.getLocalBeginLoc(),
1349 TU)))
1350 return true;
1351
1352 break;
1353
1354 case NestedNameSpecifier::NamespaceAlias:
1355 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
1356 Q.getLocalBeginLoc(),
1357 TU)))
1358 return true;
1359
1360 break;
1361
1362 case NestedNameSpecifier::TypeSpec:
1363 case NestedNameSpecifier::TypeSpecWithTemplate:
1364 if (Visit(Q.getTypeLoc()))
1365 return true;
1366
1367 break;
1368
1369 case NestedNameSpecifier::Global:
1370 case NestedNameSpecifier::Identifier:
Nikola Smiljanic67860242014-09-26 00:28:20 +00001371 case NestedNameSpecifier::Super:
Guy Benyei11169dd2012-12-18 14:30:41 +00001372 break;
1373 }
1374 }
1375
1376 return false;
1377}
1378
1379bool CursorVisitor::VisitTemplateParameters(
1380 const TemplateParameterList *Params) {
1381 if (!Params)
1382 return false;
1383
1384 for (TemplateParameterList::const_iterator P = Params->begin(),
1385 PEnd = Params->end();
1386 P != PEnd; ++P) {
1387 if (Visit(MakeCXCursor(*P, TU, RegionOfInterest)))
1388 return true;
1389 }
1390
1391 return false;
1392}
1393
1394bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) {
1395 switch (Name.getKind()) {
1396 case TemplateName::Template:
1397 return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
1398
1399 case TemplateName::OverloadedTemplate:
1400 // Visit the overloaded template set.
1401 if (Visit(MakeCursorOverloadedDeclRef(Name, Loc, TU)))
1402 return true;
1403
1404 return false;
1405
1406 case TemplateName::DependentTemplate:
1407 // FIXME: Visit nested-name-specifier.
1408 return false;
1409
1410 case TemplateName::QualifiedTemplate:
1411 // FIXME: Visit nested-name-specifier.
1412 return Visit(MakeCursorTemplateRef(
1413 Name.getAsQualifiedTemplateName()->getDecl(),
1414 Loc, TU));
1415
1416 case TemplateName::SubstTemplateTemplateParm:
1417 return Visit(MakeCursorTemplateRef(
1418 Name.getAsSubstTemplateTemplateParm()->getParameter(),
1419 Loc, TU));
1420
1421 case TemplateName::SubstTemplateTemplateParmPack:
1422 return Visit(MakeCursorTemplateRef(
1423 Name.getAsSubstTemplateTemplateParmPack()->getParameterPack(),
1424 Loc, TU));
1425 }
1426
1427 llvm_unreachable("Invalid TemplateName::Kind!");
1428}
1429
1430bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
1431 switch (TAL.getArgument().getKind()) {
1432 case TemplateArgument::Null:
1433 case TemplateArgument::Integral:
1434 case TemplateArgument::Pack:
1435 return false;
1436
1437 case TemplateArgument::Type:
1438 if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
1439 return Visit(TSInfo->getTypeLoc());
1440 return false;
1441
1442 case TemplateArgument::Declaration:
1443 if (Expr *E = TAL.getSourceDeclExpression())
1444 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
1445 return false;
1446
1447 case TemplateArgument::NullPtr:
1448 if (Expr *E = TAL.getSourceNullPtrExpression())
1449 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
1450 return false;
1451
1452 case TemplateArgument::Expression:
1453 if (Expr *E = TAL.getSourceExpression())
1454 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
1455 return false;
1456
1457 case TemplateArgument::Template:
1458 case TemplateArgument::TemplateExpansion:
1459 if (VisitNestedNameSpecifierLoc(TAL.getTemplateQualifierLoc()))
1460 return true;
1461
1462 return VisitTemplateName(TAL.getArgument().getAsTemplateOrTemplatePattern(),
1463 TAL.getTemplateNameLoc());
1464 }
1465
1466 llvm_unreachable("Invalid TemplateArgument::Kind!");
1467}
1468
1469bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1470 return VisitDeclContext(D);
1471}
1472
1473bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1474 return Visit(TL.getUnqualifiedLoc());
1475}
1476
1477bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
1478 ASTContext &Context = AU->getASTContext();
1479
1480 // Some builtin types (such as Objective-C's "id", "sel", and
1481 // "Class") have associated declarations. Create cursors for those.
1482 QualType VisitType;
1483 switch (TL.getTypePtr()->getKind()) {
1484
1485 case BuiltinType::Void:
1486 case BuiltinType::NullPtr:
1487 case BuiltinType::Dependent:
Alexey Bader954ba212016-04-08 13:40:33 +00001488#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1489 case BuiltinType::Id:
Alexey Baderb62f1442016-04-13 08:33:41 +00001490#include "clang/Basic/OpenCLImageTypes.def"
NAKAMURA Takumi288c42e2013-02-07 12:47:42 +00001491 case BuiltinType::OCLSampler:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001492 case BuiltinType::OCLEvent:
Alexey Bader9c8453f2015-09-15 11:18:52 +00001493 case BuiltinType::OCLClkEvent:
1494 case BuiltinType::OCLQueue:
1495 case BuiltinType::OCLNDRange:
1496 case BuiltinType::OCLReserveID:
Guy Benyei11169dd2012-12-18 14:30:41 +00001497#define BUILTIN_TYPE(Id, SingletonId)
1498#define SIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
1499#define UNSIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
1500#define FLOATING_TYPE(Id, SingletonId) case BuiltinType::Id:
1501#define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id:
1502#include "clang/AST/BuiltinTypes.def"
1503 break;
1504
1505 case BuiltinType::ObjCId:
1506 VisitType = Context.getObjCIdType();
1507 break;
1508
1509 case BuiltinType::ObjCClass:
1510 VisitType = Context.getObjCClassType();
1511 break;
1512
1513 case BuiltinType::ObjCSel:
1514 VisitType = Context.getObjCSelType();
1515 break;
1516 }
1517
1518 if (!VisitType.isNull()) {
1519 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
1520 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
1521 TU));
1522 }
1523
1524 return false;
1525}
1526
1527bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
1528 return Visit(MakeCursorTypeRef(TL.getTypedefNameDecl(), TL.getNameLoc(), TU));
1529}
1530
1531bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
1532 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1533}
1534
1535bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
1536 if (TL.isDefinition())
1537 return Visit(MakeCXCursor(TL.getDecl(), TU, RegionOfInterest));
1538
1539 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1540}
1541
1542bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
1543 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1544}
1545
1546bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
Hans Wennborg59dbe862015-09-29 20:56:43 +00001547 return Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU));
Guy Benyei11169dd2012-12-18 14:30:41 +00001548}
1549
Manman Rene6be26c2016-09-13 17:25:08 +00001550bool CursorVisitor::VisitObjCTypeParamTypeLoc(ObjCTypeParamTypeLoc TL) {
1551 if (Visit(MakeCursorTypeRef(TL.getDecl(), TL.getLocStart(), TU)))
1552 return true;
1553 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1554 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1555 TU)))
1556 return true;
1557 }
1558
1559 return false;
1560}
1561
Guy Benyei11169dd2012-12-18 14:30:41 +00001562bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1563 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
1564 return true;
1565
Douglas Gregore9d95f12015-07-07 03:57:35 +00001566 for (unsigned I = 0, N = TL.getNumTypeArgs(); I != N; ++I) {
1567 if (Visit(TL.getTypeArgTInfo(I)->getTypeLoc()))
1568 return true;
1569 }
1570
Guy Benyei11169dd2012-12-18 14:30:41 +00001571 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1572 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1573 TU)))
1574 return true;
1575 }
1576
1577 return false;
1578}
1579
1580bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
1581 return Visit(TL.getPointeeLoc());
1582}
1583
1584bool CursorVisitor::VisitParenTypeLoc(ParenTypeLoc TL) {
1585 return Visit(TL.getInnerLoc());
1586}
1587
1588bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
1589 return Visit(TL.getPointeeLoc());
1590}
1591
1592bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1593 return Visit(TL.getPointeeLoc());
1594}
1595
1596bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1597 return Visit(TL.getPointeeLoc());
1598}
1599
1600bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
1601 return Visit(TL.getPointeeLoc());
1602}
1603
1604bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
1605 return Visit(TL.getPointeeLoc());
1606}
1607
1608bool CursorVisitor::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
1609 return Visit(TL.getModifiedLoc());
1610}
1611
1612bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
1613 bool SkipResultType) {
Alp Toker42a16a62014-01-25 23:51:36 +00001614 if (!SkipResultType && Visit(TL.getReturnLoc()))
Guy Benyei11169dd2012-12-18 14:30:41 +00001615 return true;
1616
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00001617 for (unsigned I = 0, N = TL.getNumParams(); I != N; ++I)
1618 if (Decl *D = TL.getParam(I))
Guy Benyei11169dd2012-12-18 14:30:41 +00001619 if (Visit(MakeCXCursor(D, TU, RegionOfInterest)))
1620 return true;
1621
1622 return false;
1623}
1624
1625bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
1626 if (Visit(TL.getElementLoc()))
1627 return true;
1628
1629 if (Expr *Size = TL.getSizeExpr())
1630 return Visit(MakeCXCursor(Size, StmtParent, TU, RegionOfInterest));
1631
1632 return false;
1633}
1634
Reid Kleckner8a365022013-06-24 17:51:48 +00001635bool CursorVisitor::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
1636 return Visit(TL.getOriginalLoc());
1637}
1638
Reid Kleckner0503a872013-12-05 01:23:43 +00001639bool CursorVisitor::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
1640 return Visit(TL.getOriginalLoc());
1641}
1642
Guy Benyei11169dd2012-12-18 14:30:41 +00001643bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
1644 TemplateSpecializationTypeLoc TL) {
1645 // Visit the template name.
1646 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1647 TL.getTemplateNameLoc()))
1648 return true;
1649
1650 // Visit the template arguments.
1651 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1652 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1653 return true;
1654
1655 return false;
1656}
1657
1658bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1659 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
1660}
1661
1662bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1663 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1664 return Visit(TSInfo->getTypeLoc());
1665
1666 return false;
1667}
1668
1669bool CursorVisitor::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
1670 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1671 return Visit(TSInfo->getTypeLoc());
1672
1673 return false;
1674}
1675
1676bool CursorVisitor::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
Hans Wennborg59dbe862015-09-29 20:56:43 +00001677 return VisitNestedNameSpecifierLoc(TL.getQualifierLoc());
Guy Benyei11169dd2012-12-18 14:30:41 +00001678}
1679
1680bool CursorVisitor::VisitDependentTemplateSpecializationTypeLoc(
1681 DependentTemplateSpecializationTypeLoc TL) {
1682 // Visit the nested-name-specifier, if there is one.
1683 if (TL.getQualifierLoc() &&
1684 VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1685 return true;
1686
1687 // Visit the template arguments.
1688 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1689 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1690 return true;
1691
1692 return false;
1693}
1694
1695bool CursorVisitor::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
1696 if (VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1697 return true;
1698
1699 return Visit(TL.getNamedTypeLoc());
1700}
1701
1702bool CursorVisitor::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
1703 return Visit(TL.getPatternLoc());
1704}
1705
1706bool CursorVisitor::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
1707 if (Expr *E = TL.getUnderlyingExpr())
1708 return Visit(MakeCXCursor(E, StmtParent, TU));
1709
1710 return false;
1711}
1712
1713bool CursorVisitor::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
1714 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1715}
1716
1717bool CursorVisitor::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
1718 return Visit(TL.getValueLoc());
1719}
1720
Xiuli Pan9c14e282016-01-09 12:53:17 +00001721bool CursorVisitor::VisitPipeTypeLoc(PipeTypeLoc TL) {
1722 return Visit(TL.getValueLoc());
1723}
1724
Guy Benyei11169dd2012-12-18 14:30:41 +00001725#define DEFAULT_TYPELOC_IMPL(CLASS, PARENT) \
1726bool CursorVisitor::Visit##CLASS##TypeLoc(CLASS##TypeLoc TL) { \
1727 return Visit##PARENT##Loc(TL); \
1728}
1729
1730DEFAULT_TYPELOC_IMPL(Complex, Type)
1731DEFAULT_TYPELOC_IMPL(ConstantArray, ArrayType)
1732DEFAULT_TYPELOC_IMPL(IncompleteArray, ArrayType)
1733DEFAULT_TYPELOC_IMPL(VariableArray, ArrayType)
1734DEFAULT_TYPELOC_IMPL(DependentSizedArray, ArrayType)
1735DEFAULT_TYPELOC_IMPL(DependentSizedExtVector, Type)
1736DEFAULT_TYPELOC_IMPL(Vector, Type)
1737DEFAULT_TYPELOC_IMPL(ExtVector, VectorType)
1738DEFAULT_TYPELOC_IMPL(FunctionProto, FunctionType)
1739DEFAULT_TYPELOC_IMPL(FunctionNoProto, FunctionType)
1740DEFAULT_TYPELOC_IMPL(Record, TagType)
1741DEFAULT_TYPELOC_IMPL(Enum, TagType)
1742DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParm, Type)
1743DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParmPack, Type)
1744DEFAULT_TYPELOC_IMPL(Auto, Type)
1745
1746bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
1747 // Visit the nested-name-specifier, if present.
1748 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1749 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1750 return true;
1751
1752 if (D->isCompleteDefinition()) {
Aaron Ballman574705e2014-03-13 15:41:46 +00001753 for (const auto &I : D->bases()) {
1754 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(&I, TU)))
Guy Benyei11169dd2012-12-18 14:30:41 +00001755 return true;
1756 }
1757 }
1758
1759 return VisitTagDecl(D);
1760}
1761
1762bool CursorVisitor::VisitAttributes(Decl *D) {
Aaron Ballmanb97112e2014-03-08 22:19:01 +00001763 for (const auto *I : D->attrs())
1764 if (Visit(MakeCXCursor(I, D, TU)))
Guy Benyei11169dd2012-12-18 14:30:41 +00001765 return true;
1766
1767 return false;
1768}
1769
1770//===----------------------------------------------------------------------===//
1771// Data-recursive visitor methods.
1772//===----------------------------------------------------------------------===//
1773
1774namespace {
1775#define DEF_JOB(NAME, DATA, KIND)\
1776class NAME : public VisitorJob {\
1777public:\
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001778 NAME(const DATA *d, CXCursor parent) : \
1779 VisitorJob(parent, VisitorJob::KIND, d) {} \
Guy Benyei11169dd2012-12-18 14:30:41 +00001780 static bool classof(const VisitorJob *VJ) { return VJ->getKind() == KIND; }\
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001781 const DATA *get() const { return static_cast<const DATA*>(data[0]); }\
Guy Benyei11169dd2012-12-18 14:30:41 +00001782};
1783
1784DEF_JOB(StmtVisit, Stmt, StmtVisitKind)
1785DEF_JOB(MemberExprParts, MemberExpr, MemberExprPartsKind)
1786DEF_JOB(DeclRefExprParts, DeclRefExpr, DeclRefExprPartsKind)
1787DEF_JOB(OverloadExprParts, OverloadExpr, OverloadExprPartsKind)
Guy Benyei11169dd2012-12-18 14:30:41 +00001788DEF_JOB(SizeOfPackExprParts, SizeOfPackExpr, SizeOfPackExprPartsKind)
1789DEF_JOB(LambdaExprParts, LambdaExpr, LambdaExprPartsKind)
1790DEF_JOB(PostChildrenVisit, void, PostChildrenVisitKind)
1791#undef DEF_JOB
1792
James Y Knight04ec5bf2015-12-24 02:59:37 +00001793class ExplicitTemplateArgsVisit : public VisitorJob {
1794public:
1795 ExplicitTemplateArgsVisit(const TemplateArgumentLoc *Begin,
1796 const TemplateArgumentLoc *End, CXCursor parent)
1797 : VisitorJob(parent, VisitorJob::ExplicitTemplateArgsVisitKind, Begin,
1798 End) {}
1799 static bool classof(const VisitorJob *VJ) {
1800 return VJ->getKind() == ExplicitTemplateArgsVisitKind;
1801 }
1802 const TemplateArgumentLoc *begin() const {
1803 return static_cast<const TemplateArgumentLoc *>(data[0]);
1804 }
1805 const TemplateArgumentLoc *end() {
1806 return static_cast<const TemplateArgumentLoc *>(data[1]);
1807 }
1808};
Guy Benyei11169dd2012-12-18 14:30:41 +00001809class DeclVisit : public VisitorJob {
1810public:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001811 DeclVisit(const Decl *D, CXCursor parent, bool isFirst) :
Guy Benyei11169dd2012-12-18 14:30:41 +00001812 VisitorJob(parent, VisitorJob::DeclVisitKind,
Craig Topper69186e72014-06-08 08:38:04 +00001813 D, isFirst ? (void*) 1 : (void*) nullptr) {}
Guy Benyei11169dd2012-12-18 14:30:41 +00001814 static bool classof(const VisitorJob *VJ) {
1815 return VJ->getKind() == DeclVisitKind;
1816 }
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001817 const Decl *get() const { return static_cast<const Decl *>(data[0]); }
Dmitri Gribenkoe5423a72015-03-23 19:23:50 +00001818 bool isFirst() const { return data[1] != nullptr; }
Guy Benyei11169dd2012-12-18 14:30:41 +00001819};
1820class TypeLocVisit : public VisitorJob {
1821public:
1822 TypeLocVisit(TypeLoc tl, CXCursor parent) :
1823 VisitorJob(parent, VisitorJob::TypeLocVisitKind,
1824 tl.getType().getAsOpaquePtr(), tl.getOpaqueData()) {}
1825
1826 static bool classof(const VisitorJob *VJ) {
1827 return VJ->getKind() == TypeLocVisitKind;
1828 }
1829
1830 TypeLoc get() const {
1831 QualType T = QualType::getFromOpaquePtr(data[0]);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001832 return TypeLoc(T, const_cast<void *>(data[1]));
Guy Benyei11169dd2012-12-18 14:30:41 +00001833 }
1834};
1835
1836class LabelRefVisit : public VisitorJob {
1837public:
1838 LabelRefVisit(LabelDecl *LD, SourceLocation labelLoc, CXCursor parent)
1839 : VisitorJob(parent, VisitorJob::LabelRefVisitKind, LD,
1840 labelLoc.getPtrEncoding()) {}
1841
1842 static bool classof(const VisitorJob *VJ) {
1843 return VJ->getKind() == VisitorJob::LabelRefVisitKind;
1844 }
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001845 const LabelDecl *get() const {
1846 return static_cast<const LabelDecl *>(data[0]);
1847 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001848 SourceLocation getLoc() const {
1849 return SourceLocation::getFromPtrEncoding(data[1]); }
1850};
1851
1852class NestedNameSpecifierLocVisit : public VisitorJob {
1853public:
1854 NestedNameSpecifierLocVisit(NestedNameSpecifierLoc Qualifier, CXCursor parent)
1855 : VisitorJob(parent, VisitorJob::NestedNameSpecifierLocVisitKind,
1856 Qualifier.getNestedNameSpecifier(),
1857 Qualifier.getOpaqueData()) { }
1858
1859 static bool classof(const VisitorJob *VJ) {
1860 return VJ->getKind() == VisitorJob::NestedNameSpecifierLocVisitKind;
1861 }
1862
1863 NestedNameSpecifierLoc get() const {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001864 return NestedNameSpecifierLoc(
1865 const_cast<NestedNameSpecifier *>(
1866 static_cast<const NestedNameSpecifier *>(data[0])),
1867 const_cast<void *>(data[1]));
Guy Benyei11169dd2012-12-18 14:30:41 +00001868 }
1869};
1870
1871class DeclarationNameInfoVisit : public VisitorJob {
1872public:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001873 DeclarationNameInfoVisit(const Stmt *S, CXCursor parent)
Dmitri Gribenkodd7dacf2013-02-03 13:19:54 +00001874 : VisitorJob(parent, VisitorJob::DeclarationNameInfoVisitKind, S) {}
Guy Benyei11169dd2012-12-18 14:30:41 +00001875 static bool classof(const VisitorJob *VJ) {
1876 return VJ->getKind() == VisitorJob::DeclarationNameInfoVisitKind;
1877 }
1878 DeclarationNameInfo get() const {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001879 const Stmt *S = static_cast<const Stmt *>(data[0]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001880 switch (S->getStmtClass()) {
1881 default:
1882 llvm_unreachable("Unhandled Stmt");
1883 case clang::Stmt::MSDependentExistsStmtClass:
1884 return cast<MSDependentExistsStmt>(S)->getNameInfo();
1885 case Stmt::CXXDependentScopeMemberExprClass:
1886 return cast<CXXDependentScopeMemberExpr>(S)->getMemberNameInfo();
1887 case Stmt::DependentScopeDeclRefExprClass:
1888 return cast<DependentScopeDeclRefExpr>(S)->getNameInfo();
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001889 case Stmt::OMPCriticalDirectiveClass:
1890 return cast<OMPCriticalDirective>(S)->getDirectiveName();
Guy Benyei11169dd2012-12-18 14:30:41 +00001891 }
1892 }
1893};
1894class MemberRefVisit : public VisitorJob {
1895public:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001896 MemberRefVisit(const FieldDecl *D, SourceLocation L, CXCursor parent)
Guy Benyei11169dd2012-12-18 14:30:41 +00001897 : VisitorJob(parent, VisitorJob::MemberRefVisitKind, D,
1898 L.getPtrEncoding()) {}
1899 static bool classof(const VisitorJob *VJ) {
1900 return VJ->getKind() == VisitorJob::MemberRefVisitKind;
1901 }
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001902 const FieldDecl *get() const {
1903 return static_cast<const FieldDecl *>(data[0]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001904 }
1905 SourceLocation getLoc() const {
1906 return SourceLocation::getFromRawEncoding((unsigned)(uintptr_t) data[1]);
1907 }
1908};
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001909class EnqueueVisitor : public ConstStmtVisitor<EnqueueVisitor, void> {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001910 friend class OMPClauseEnqueue;
Guy Benyei11169dd2012-12-18 14:30:41 +00001911 VisitorWorkList &WL;
1912 CXCursor Parent;
1913public:
1914 EnqueueVisitor(VisitorWorkList &wl, CXCursor parent)
1915 : WL(wl), Parent(parent) {}
1916
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001917 void VisitAddrLabelExpr(const AddrLabelExpr *E);
1918 void VisitBlockExpr(const BlockExpr *B);
1919 void VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
1920 void VisitCompoundStmt(const CompoundStmt *S);
1921 void VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) { /* Do nothing. */ }
1922 void VisitMSDependentExistsStmt(const MSDependentExistsStmt *S);
1923 void VisitCXXDependentScopeMemberExpr(const CXXDependentScopeMemberExpr *E);
1924 void VisitCXXNewExpr(const CXXNewExpr *E);
1925 void VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E);
1926 void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *E);
1927 void VisitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *E);
1928 void VisitCXXTemporaryObjectExpr(const CXXTemporaryObjectExpr *E);
1929 void VisitCXXTypeidExpr(const CXXTypeidExpr *E);
1930 void VisitCXXUnresolvedConstructExpr(const CXXUnresolvedConstructExpr *E);
1931 void VisitCXXUuidofExpr(const CXXUuidofExpr *E);
1932 void VisitCXXCatchStmt(const CXXCatchStmt *S);
Argyrios Kyrtzidis99891242014-11-13 09:03:21 +00001933 void VisitCXXForRangeStmt(const CXXForRangeStmt *S);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001934 void VisitDeclRefExpr(const DeclRefExpr *D);
1935 void VisitDeclStmt(const DeclStmt *S);
1936 void VisitDependentScopeDeclRefExpr(const DependentScopeDeclRefExpr *E);
1937 void VisitDesignatedInitExpr(const DesignatedInitExpr *E);
1938 void VisitExplicitCastExpr(const ExplicitCastExpr *E);
1939 void VisitForStmt(const ForStmt *FS);
1940 void VisitGotoStmt(const GotoStmt *GS);
1941 void VisitIfStmt(const IfStmt *If);
1942 void VisitInitListExpr(const InitListExpr *IE);
1943 void VisitMemberExpr(const MemberExpr *M);
1944 void VisitOffsetOfExpr(const OffsetOfExpr *E);
1945 void VisitObjCEncodeExpr(const ObjCEncodeExpr *E);
1946 void VisitObjCMessageExpr(const ObjCMessageExpr *M);
1947 void VisitOverloadExpr(const OverloadExpr *E);
1948 void VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
1949 void VisitStmt(const Stmt *S);
1950 void VisitSwitchStmt(const SwitchStmt *S);
1951 void VisitWhileStmt(const WhileStmt *W);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001952 void VisitTypeTraitExpr(const TypeTraitExpr *E);
1953 void VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E);
1954 void VisitExpressionTraitExpr(const ExpressionTraitExpr *E);
1955 void VisitUnresolvedMemberExpr(const UnresolvedMemberExpr *U);
1956 void VisitVAArgExpr(const VAArgExpr *E);
1957 void VisitSizeOfPackExpr(const SizeOfPackExpr *E);
1958 void VisitPseudoObjectExpr(const PseudoObjectExpr *E);
1959 void VisitOpaqueValueExpr(const OpaqueValueExpr *E);
1960 void VisitLambdaExpr(const LambdaExpr *E);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001961 void VisitOMPExecutableDirective(const OMPExecutableDirective *D);
Alexander Musman3aaab662014-08-19 11:27:13 +00001962 void VisitOMPLoopDirective(const OMPLoopDirective *D);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001963 void VisitOMPParallelDirective(const OMPParallelDirective *D);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00001964 void VisitOMPSimdDirective(const OMPSimdDirective *D);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001965 void VisitOMPForDirective(const OMPForDirective *D);
Alexander Musmanf82886e2014-09-18 05:12:34 +00001966 void VisitOMPForSimdDirective(const OMPForSimdDirective *D);
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00001967 void VisitOMPSectionsDirective(const OMPSectionsDirective *D);
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001968 void VisitOMPSectionDirective(const OMPSectionDirective *D);
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00001969 void VisitOMPSingleDirective(const OMPSingleDirective *D);
Alexander Musman80c22892014-07-17 08:54:58 +00001970 void VisitOMPMasterDirective(const OMPMasterDirective *D);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001971 void VisitOMPCriticalDirective(const OMPCriticalDirective *D);
Alexey Bataev4acb8592014-07-07 13:01:15 +00001972 void VisitOMPParallelForDirective(const OMPParallelForDirective *D);
Alexander Musmane4e893b2014-09-23 09:33:00 +00001973 void VisitOMPParallelForSimdDirective(const OMPParallelForSimdDirective *D);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001974 void VisitOMPParallelSectionsDirective(const OMPParallelSectionsDirective *D);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001975 void VisitOMPTaskDirective(const OMPTaskDirective *D);
Alexey Bataev68446b72014-07-18 07:47:19 +00001976 void VisitOMPTaskyieldDirective(const OMPTaskyieldDirective *D);
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001977 void VisitOMPBarrierDirective(const OMPBarrierDirective *D);
Alexey Bataev2df347a2014-07-18 10:17:07 +00001978 void VisitOMPTaskwaitDirective(const OMPTaskwaitDirective *D);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001979 void VisitOMPTaskgroupDirective(const OMPTaskgroupDirective *D);
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001980 void
1981 VisitOMPCancellationPointDirective(const OMPCancellationPointDirective *D);
Alexey Bataev80909872015-07-02 11:25:17 +00001982 void VisitOMPCancelDirective(const OMPCancelDirective *D);
Alexey Bataev6125da92014-07-21 11:26:11 +00001983 void VisitOMPFlushDirective(const OMPFlushDirective *D);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001984 void VisitOMPOrderedDirective(const OMPOrderedDirective *D);
Alexey Bataev0162e452014-07-22 10:10:35 +00001985 void VisitOMPAtomicDirective(const OMPAtomicDirective *D);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001986 void VisitOMPTargetDirective(const OMPTargetDirective *D);
Michael Wong65f367f2015-07-21 13:44:28 +00001987 void VisitOMPTargetDataDirective(const OMPTargetDataDirective *D);
Samuel Antaodf67fc42016-01-19 19:15:56 +00001988 void VisitOMPTargetEnterDataDirective(const OMPTargetEnterDataDirective *D);
Samuel Antao72590762016-01-19 20:04:50 +00001989 void VisitOMPTargetExitDataDirective(const OMPTargetExitDataDirective *D);
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00001990 void VisitOMPTargetParallelDirective(const OMPTargetParallelDirective *D);
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00001991 void
1992 VisitOMPTargetParallelForDirective(const OMPTargetParallelForDirective *D);
Alexey Bataev13314bf2014-10-09 04:18:56 +00001993 void VisitOMPTeamsDirective(const OMPTeamsDirective *D);
Alexey Bataev49f6e782015-12-01 04:18:41 +00001994 void VisitOMPTaskLoopDirective(const OMPTaskLoopDirective *D);
Alexey Bataev0a6ed842015-12-03 09:40:15 +00001995 void VisitOMPTaskLoopSimdDirective(const OMPTaskLoopSimdDirective *D);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00001996 void VisitOMPDistributeDirective(const OMPDistributeDirective *D);
Carlo Bertolli9925f152016-06-27 14:55:37 +00001997 void VisitOMPDistributeParallelForDirective(
1998 const OMPDistributeParallelForDirective *D);
Kelvin Li4a39add2016-07-05 05:00:15 +00001999 void VisitOMPDistributeParallelForSimdDirective(
2000 const OMPDistributeParallelForSimdDirective *D);
Kelvin Li787f3fc2016-07-06 04:45:38 +00002001 void VisitOMPDistributeSimdDirective(const OMPDistributeSimdDirective *D);
Kelvin Lia579b912016-07-14 02:54:56 +00002002 void VisitOMPTargetParallelForSimdDirective(
2003 const OMPTargetParallelForSimdDirective *D);
Kelvin Li986330c2016-07-20 22:57:10 +00002004 void VisitOMPTargetSimdDirective(const OMPTargetSimdDirective *D);
Kelvin Li02532872016-08-05 14:37:37 +00002005 void VisitOMPTeamsDistributeDirective(const OMPTeamsDistributeDirective *D);
Kelvin Li4e325f72016-10-25 12:50:55 +00002006 void VisitOMPTeamsDistributeSimdDirective(
2007 const OMPTeamsDistributeSimdDirective *D);
Kelvin Li579e41c2016-11-30 23:51:03 +00002008 void VisitOMPTeamsDistributeParallelForSimdDirective(
2009 const OMPTeamsDistributeParallelForSimdDirective *D);
Kelvin Li7ade93f2016-12-09 03:24:30 +00002010 void VisitOMPTeamsDistributeParallelForDirective(
2011 const OMPTeamsDistributeParallelForDirective *D);
Kelvin Libf594a52016-12-17 05:48:59 +00002012 void VisitOMPTargetTeamsDirective(const OMPTargetTeamsDirective *D);
Kelvin Li83c451e2016-12-25 04:52:54 +00002013 void VisitOMPTargetTeamsDistributeDirective(
2014 const OMPTargetTeamsDistributeDirective *D);
Kelvin Li80e8f562016-12-29 22:16:30 +00002015 void VisitOMPTargetTeamsDistributeParallelForDirective(
2016 const OMPTargetTeamsDistributeParallelForDirective *D);
Kelvin Li1851df52017-01-03 05:23:48 +00002017 void VisitOMPTargetTeamsDistributeParallelForSimdDirective(
2018 const OMPTargetTeamsDistributeParallelForSimdDirective *D);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002019
Guy Benyei11169dd2012-12-18 14:30:41 +00002020private:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002021 void AddDeclarationNameInfo(const Stmt *S);
Guy Benyei11169dd2012-12-18 14:30:41 +00002022 void AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier);
James Y Knight04ec5bf2015-12-24 02:59:37 +00002023 void AddExplicitTemplateArgs(const TemplateArgumentLoc *A,
2024 unsigned NumTemplateArgs);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002025 void AddMemberRef(const FieldDecl *D, SourceLocation L);
2026 void AddStmt(const Stmt *S);
2027 void AddDecl(const Decl *D, bool isFirst = true);
Guy Benyei11169dd2012-12-18 14:30:41 +00002028 void AddTypeLoc(TypeSourceInfo *TI);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002029 void EnqueueChildren(const Stmt *S);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002030 void EnqueueChildren(const OMPClause *S);
Guy Benyei11169dd2012-12-18 14:30:41 +00002031};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002032} // end anonyous namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00002033
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002034void EnqueueVisitor::AddDeclarationNameInfo(const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002035 // 'S' should always be non-null, since it comes from the
2036 // statement we are visiting.
2037 WL.push_back(DeclarationNameInfoVisit(S, Parent));
2038}
2039
2040void
2041EnqueueVisitor::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
2042 if (Qualifier)
2043 WL.push_back(NestedNameSpecifierLocVisit(Qualifier, Parent));
2044}
2045
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002046void EnqueueVisitor::AddStmt(const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002047 if (S)
2048 WL.push_back(StmtVisit(S, Parent));
2049}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002050void EnqueueVisitor::AddDecl(const Decl *D, bool isFirst) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002051 if (D)
2052 WL.push_back(DeclVisit(D, Parent, isFirst));
2053}
James Y Knight04ec5bf2015-12-24 02:59:37 +00002054void EnqueueVisitor::AddExplicitTemplateArgs(const TemplateArgumentLoc *A,
2055 unsigned NumTemplateArgs) {
2056 WL.push_back(ExplicitTemplateArgsVisit(A, A + NumTemplateArgs, Parent));
Guy Benyei11169dd2012-12-18 14:30:41 +00002057}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002058void EnqueueVisitor::AddMemberRef(const FieldDecl *D, SourceLocation L) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002059 if (D)
2060 WL.push_back(MemberRefVisit(D, L, Parent));
2061}
2062void EnqueueVisitor::AddTypeLoc(TypeSourceInfo *TI) {
2063 if (TI)
2064 WL.push_back(TypeLocVisit(TI->getTypeLoc(), Parent));
2065 }
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002066void EnqueueVisitor::EnqueueChildren(const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002067 unsigned size = WL.size();
Benjamin Kramer642f1732015-07-02 21:03:14 +00002068 for (const Stmt *SubStmt : S->children()) {
2069 AddStmt(SubStmt);
Guy Benyei11169dd2012-12-18 14:30:41 +00002070 }
2071 if (size == WL.size())
2072 return;
2073 // Now reverse the entries we just added. This will match the DFS
2074 // ordering performed by the worklist.
2075 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2076 std::reverse(I, E);
2077}
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002078namespace {
2079class OMPClauseEnqueue : public ConstOMPClauseVisitor<OMPClauseEnqueue> {
2080 EnqueueVisitor *Visitor;
Alexey Bataev756c1962013-09-24 03:17:45 +00002081 /// \brief Process clauses with list of variables.
2082 template <typename T>
2083 void VisitOMPClauseList(T *Node);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002084public:
2085 OMPClauseEnqueue(EnqueueVisitor *Visitor) : Visitor(Visitor) { }
2086#define OPENMP_CLAUSE(Name, Class) \
2087 void Visit##Class(const Class *C);
2088#include "clang/Basic/OpenMPKinds.def"
Alexey Bataev3392d762016-02-16 11:18:12 +00002089 void VisitOMPClauseWithPreInit(const OMPClauseWithPreInit *C);
Alexey Bataev005248a2016-02-25 05:25:57 +00002090 void VisitOMPClauseWithPostUpdate(const OMPClauseWithPostUpdate *C);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002091};
2092
Alexey Bataev3392d762016-02-16 11:18:12 +00002093void OMPClauseEnqueue::VisitOMPClauseWithPreInit(
2094 const OMPClauseWithPreInit *C) {
2095 Visitor->AddStmt(C->getPreInitStmt());
2096}
2097
Alexey Bataev005248a2016-02-25 05:25:57 +00002098void OMPClauseEnqueue::VisitOMPClauseWithPostUpdate(
2099 const OMPClauseWithPostUpdate *C) {
Alexey Bataev37e594c2016-03-04 07:21:16 +00002100 VisitOMPClauseWithPreInit(C);
Alexey Bataev005248a2016-02-25 05:25:57 +00002101 Visitor->AddStmt(C->getPostUpdateExpr());
2102}
2103
Alexey Bataevaadd52e2014-02-13 05:29:23 +00002104void OMPClauseEnqueue::VisitOMPIfClause(const OMPIfClause *C) {
2105 Visitor->AddStmt(C->getCondition());
2106}
2107
Alexey Bataev3778b602014-07-17 07:32:53 +00002108void OMPClauseEnqueue::VisitOMPFinalClause(const OMPFinalClause *C) {
2109 Visitor->AddStmt(C->getCondition());
2110}
2111
Alexey Bataev568a8332014-03-06 06:15:19 +00002112void OMPClauseEnqueue::VisitOMPNumThreadsClause(const OMPNumThreadsClause *C) {
2113 Visitor->AddStmt(C->getNumThreads());
2114}
2115
Alexey Bataev62c87d22014-03-21 04:51:18 +00002116void OMPClauseEnqueue::VisitOMPSafelenClause(const OMPSafelenClause *C) {
2117 Visitor->AddStmt(C->getSafelen());
2118}
2119
Alexey Bataev66b15b52015-08-21 11:14:16 +00002120void OMPClauseEnqueue::VisitOMPSimdlenClause(const OMPSimdlenClause *C) {
2121 Visitor->AddStmt(C->getSimdlen());
2122}
2123
Alexander Musman8bd31e62014-05-27 15:12:19 +00002124void OMPClauseEnqueue::VisitOMPCollapseClause(const OMPCollapseClause *C) {
2125 Visitor->AddStmt(C->getNumForLoops());
2126}
2127
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002128void OMPClauseEnqueue::VisitOMPDefaultClause(const OMPDefaultClause *C) { }
Alexey Bataev756c1962013-09-24 03:17:45 +00002129
Alexey Bataevbcbadb62014-05-06 06:04:14 +00002130void OMPClauseEnqueue::VisitOMPProcBindClause(const OMPProcBindClause *C) { }
2131
Alexey Bataev56dafe82014-06-20 07:16:17 +00002132void OMPClauseEnqueue::VisitOMPScheduleClause(const OMPScheduleClause *C) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002133 VisitOMPClauseWithPreInit(C);
Alexey Bataev56dafe82014-06-20 07:16:17 +00002134 Visitor->AddStmt(C->getChunkSize());
2135}
2136
Alexey Bataev10e775f2015-07-30 11:36:16 +00002137void OMPClauseEnqueue::VisitOMPOrderedClause(const OMPOrderedClause *C) {
2138 Visitor->AddStmt(C->getNumForLoops());
2139}
Alexey Bataev142e1fc2014-06-20 09:44:06 +00002140
Alexey Bataev236070f2014-06-20 11:19:47 +00002141void OMPClauseEnqueue::VisitOMPNowaitClause(const OMPNowaitClause *) {}
2142
Alexey Bataev7aea99a2014-07-17 12:19:31 +00002143void OMPClauseEnqueue::VisitOMPUntiedClause(const OMPUntiedClause *) {}
2144
Alexey Bataev74ba3a52014-07-17 12:47:03 +00002145void OMPClauseEnqueue::VisitOMPMergeableClause(const OMPMergeableClause *) {}
2146
Alexey Bataevf98b00c2014-07-23 02:27:21 +00002147void OMPClauseEnqueue::VisitOMPReadClause(const OMPReadClause *) {}
2148
Alexey Bataevdea47612014-07-23 07:46:59 +00002149void OMPClauseEnqueue::VisitOMPWriteClause(const OMPWriteClause *) {}
2150
Alexey Bataev67a4f222014-07-23 10:25:33 +00002151void OMPClauseEnqueue::VisitOMPUpdateClause(const OMPUpdateClause *) {}
2152
Alexey Bataev459dec02014-07-24 06:46:57 +00002153void OMPClauseEnqueue::VisitOMPCaptureClause(const OMPCaptureClause *) {}
2154
Alexey Bataev82bad8b2014-07-24 08:55:34 +00002155void OMPClauseEnqueue::VisitOMPSeqCstClause(const OMPSeqCstClause *) {}
2156
Alexey Bataev346265e2015-09-25 10:37:12 +00002157void OMPClauseEnqueue::VisitOMPThreadsClause(const OMPThreadsClause *) {}
2158
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002159void OMPClauseEnqueue::VisitOMPSIMDClause(const OMPSIMDClause *) {}
2160
Alexey Bataevb825de12015-12-07 10:51:44 +00002161void OMPClauseEnqueue::VisitOMPNogroupClause(const OMPNogroupClause *) {}
2162
Michael Wonge710d542015-08-07 16:16:36 +00002163void OMPClauseEnqueue::VisitOMPDeviceClause(const OMPDeviceClause *C) {
2164 Visitor->AddStmt(C->getDevice());
2165}
2166
Kelvin Li099bb8c2015-11-24 20:50:12 +00002167void OMPClauseEnqueue::VisitOMPNumTeamsClause(const OMPNumTeamsClause *C) {
2168 Visitor->AddStmt(C->getNumTeams());
2169}
2170
Kelvin Lia15fb1a2015-11-27 18:47:36 +00002171void OMPClauseEnqueue::VisitOMPThreadLimitClause(const OMPThreadLimitClause *C) {
2172 Visitor->AddStmt(C->getThreadLimit());
2173}
2174
Alexey Bataeva0569352015-12-01 10:17:31 +00002175void OMPClauseEnqueue::VisitOMPPriorityClause(const OMPPriorityClause *C) {
2176 Visitor->AddStmt(C->getPriority());
2177}
2178
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00002179void OMPClauseEnqueue::VisitOMPGrainsizeClause(const OMPGrainsizeClause *C) {
2180 Visitor->AddStmt(C->getGrainsize());
2181}
2182
Alexey Bataev382967a2015-12-08 12:06:20 +00002183void OMPClauseEnqueue::VisitOMPNumTasksClause(const OMPNumTasksClause *C) {
2184 Visitor->AddStmt(C->getNumTasks());
2185}
2186
Alexey Bataev28c75412015-12-15 08:19:24 +00002187void OMPClauseEnqueue::VisitOMPHintClause(const OMPHintClause *C) {
2188 Visitor->AddStmt(C->getHint());
2189}
2190
Alexey Bataev756c1962013-09-24 03:17:45 +00002191template<typename T>
2192void OMPClauseEnqueue::VisitOMPClauseList(T *Node) {
Alexey Bataev03b340a2014-10-21 03:16:40 +00002193 for (const auto *I : Node->varlists()) {
Aaron Ballman2205d2a2014-03-14 15:55:35 +00002194 Visitor->AddStmt(I);
Alexey Bataev03b340a2014-10-21 03:16:40 +00002195 }
Alexey Bataev756c1962013-09-24 03:17:45 +00002196}
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002197
2198void OMPClauseEnqueue::VisitOMPPrivateClause(const OMPPrivateClause *C) {
Alexey Bataev756c1962013-09-24 03:17:45 +00002199 VisitOMPClauseList(C);
Alexey Bataev03b340a2014-10-21 03:16:40 +00002200 for (const auto *E : C->private_copies()) {
2201 Visitor->AddStmt(E);
2202 }
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002203}
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002204void OMPClauseEnqueue::VisitOMPFirstprivateClause(
2205 const OMPFirstprivateClause *C) {
2206 VisitOMPClauseList(C);
Alexey Bataev417089f2016-02-17 13:19:37 +00002207 VisitOMPClauseWithPreInit(C);
2208 for (const auto *E : C->private_copies()) {
2209 Visitor->AddStmt(E);
2210 }
2211 for (const auto *E : C->inits()) {
2212 Visitor->AddStmt(E);
2213 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002214}
Alexander Musman1bb328c2014-06-04 13:06:39 +00002215void OMPClauseEnqueue::VisitOMPLastprivateClause(
2216 const OMPLastprivateClause *C) {
2217 VisitOMPClauseList(C);
Alexey Bataev005248a2016-02-25 05:25:57 +00002218 VisitOMPClauseWithPostUpdate(C);
Alexey Bataev38e89532015-04-16 04:54:05 +00002219 for (auto *E : C->private_copies()) {
2220 Visitor->AddStmt(E);
2221 }
2222 for (auto *E : C->source_exprs()) {
2223 Visitor->AddStmt(E);
2224 }
2225 for (auto *E : C->destination_exprs()) {
2226 Visitor->AddStmt(E);
2227 }
2228 for (auto *E : C->assignment_ops()) {
2229 Visitor->AddStmt(E);
2230 }
Alexander Musman1bb328c2014-06-04 13:06:39 +00002231}
Alexey Bataev758e55e2013-09-06 18:03:48 +00002232void OMPClauseEnqueue::VisitOMPSharedClause(const OMPSharedClause *C) {
Alexey Bataev756c1962013-09-24 03:17:45 +00002233 VisitOMPClauseList(C);
Alexey Bataev758e55e2013-09-06 18:03:48 +00002234}
Alexey Bataevc5e02582014-06-16 07:08:35 +00002235void OMPClauseEnqueue::VisitOMPReductionClause(const OMPReductionClause *C) {
2236 VisitOMPClauseList(C);
Alexey Bataev61205072016-03-02 04:57:40 +00002237 VisitOMPClauseWithPostUpdate(C);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00002238 for (auto *E : C->privates()) {
2239 Visitor->AddStmt(E);
2240 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002241 for (auto *E : C->lhs_exprs()) {
2242 Visitor->AddStmt(E);
2243 }
2244 for (auto *E : C->rhs_exprs()) {
2245 Visitor->AddStmt(E);
2246 }
2247 for (auto *E : C->reduction_ops()) {
2248 Visitor->AddStmt(E);
2249 }
Alexey Bataevc5e02582014-06-16 07:08:35 +00002250}
Alexander Musman8dba6642014-04-22 13:09:42 +00002251void OMPClauseEnqueue::VisitOMPLinearClause(const OMPLinearClause *C) {
2252 VisitOMPClauseList(C);
Alexey Bataev78849fb2016-03-09 09:49:00 +00002253 VisitOMPClauseWithPostUpdate(C);
Alexey Bataevbd9fec12015-08-18 06:47:21 +00002254 for (const auto *E : C->privates()) {
2255 Visitor->AddStmt(E);
2256 }
Alexander Musman3276a272015-03-21 10:12:56 +00002257 for (const auto *E : C->inits()) {
2258 Visitor->AddStmt(E);
2259 }
2260 for (const auto *E : C->updates()) {
2261 Visitor->AddStmt(E);
2262 }
2263 for (const auto *E : C->finals()) {
2264 Visitor->AddStmt(E);
2265 }
Alexander Musman8dba6642014-04-22 13:09:42 +00002266 Visitor->AddStmt(C->getStep());
Alexander Musman3276a272015-03-21 10:12:56 +00002267 Visitor->AddStmt(C->getCalcStep());
Alexander Musman8dba6642014-04-22 13:09:42 +00002268}
Alexander Musmanf0d76e72014-05-29 14:36:25 +00002269void OMPClauseEnqueue::VisitOMPAlignedClause(const OMPAlignedClause *C) {
2270 VisitOMPClauseList(C);
2271 Visitor->AddStmt(C->getAlignment());
2272}
Alexey Bataevd48bcd82014-03-31 03:36:38 +00002273void OMPClauseEnqueue::VisitOMPCopyinClause(const OMPCopyinClause *C) {
2274 VisitOMPClauseList(C);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00002275 for (auto *E : C->source_exprs()) {
2276 Visitor->AddStmt(E);
2277 }
2278 for (auto *E : C->destination_exprs()) {
2279 Visitor->AddStmt(E);
2280 }
2281 for (auto *E : C->assignment_ops()) {
2282 Visitor->AddStmt(E);
2283 }
Alexey Bataevd48bcd82014-03-31 03:36:38 +00002284}
Alexey Bataevbae9a792014-06-27 10:37:06 +00002285void
2286OMPClauseEnqueue::VisitOMPCopyprivateClause(const OMPCopyprivateClause *C) {
2287 VisitOMPClauseList(C);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002288 for (auto *E : C->source_exprs()) {
2289 Visitor->AddStmt(E);
2290 }
2291 for (auto *E : C->destination_exprs()) {
2292 Visitor->AddStmt(E);
2293 }
2294 for (auto *E : C->assignment_ops()) {
2295 Visitor->AddStmt(E);
2296 }
Alexey Bataevbae9a792014-06-27 10:37:06 +00002297}
Alexey Bataev6125da92014-07-21 11:26:11 +00002298void OMPClauseEnqueue::VisitOMPFlushClause(const OMPFlushClause *C) {
2299 VisitOMPClauseList(C);
2300}
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00002301void OMPClauseEnqueue::VisitOMPDependClause(const OMPDependClause *C) {
2302 VisitOMPClauseList(C);
2303}
Kelvin Li0bff7af2015-11-23 05:32:03 +00002304void OMPClauseEnqueue::VisitOMPMapClause(const OMPMapClause *C) {
2305 VisitOMPClauseList(C);
2306}
Carlo Bertollib4adf552016-01-15 18:50:31 +00002307void OMPClauseEnqueue::VisitOMPDistScheduleClause(
2308 const OMPDistScheduleClause *C) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002309 VisitOMPClauseWithPreInit(C);
Carlo Bertollib4adf552016-01-15 18:50:31 +00002310 Visitor->AddStmt(C->getChunkSize());
Carlo Bertollib4adf552016-01-15 18:50:31 +00002311}
Alexey Bataev3392d762016-02-16 11:18:12 +00002312void OMPClauseEnqueue::VisitOMPDefaultmapClause(
2313 const OMPDefaultmapClause * /*C*/) {}
Samuel Antao661c0902016-05-26 17:39:58 +00002314void OMPClauseEnqueue::VisitOMPToClause(const OMPToClause *C) {
2315 VisitOMPClauseList(C);
2316}
Samuel Antaoec172c62016-05-26 17:49:04 +00002317void OMPClauseEnqueue::VisitOMPFromClause(const OMPFromClause *C) {
2318 VisitOMPClauseList(C);
2319}
Carlo Bertolli2404b172016-07-13 15:37:16 +00002320void OMPClauseEnqueue::VisitOMPUseDevicePtrClause(const OMPUseDevicePtrClause *C) {
2321 VisitOMPClauseList(C);
2322}
Carlo Bertolli70594e92016-07-13 17:16:49 +00002323void OMPClauseEnqueue::VisitOMPIsDevicePtrClause(const OMPIsDevicePtrClause *C) {
2324 VisitOMPClauseList(C);
2325}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002326}
Alexey Bataev756c1962013-09-24 03:17:45 +00002327
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002328void EnqueueVisitor::EnqueueChildren(const OMPClause *S) {
2329 unsigned size = WL.size();
2330 OMPClauseEnqueue Visitor(this);
2331 Visitor.Visit(S);
2332 if (size == WL.size())
2333 return;
2334 // Now reverse the entries we just added. This will match the DFS
2335 // ordering performed by the worklist.
2336 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2337 std::reverse(I, E);
2338}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002339void EnqueueVisitor::VisitAddrLabelExpr(const AddrLabelExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002340 WL.push_back(LabelRefVisit(E->getLabel(), E->getLabelLoc(), Parent));
2341}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002342void EnqueueVisitor::VisitBlockExpr(const BlockExpr *B) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002343 AddDecl(B->getBlockDecl());
2344}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002345void EnqueueVisitor::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002346 EnqueueChildren(E);
2347 AddTypeLoc(E->getTypeSourceInfo());
2348}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002349void EnqueueVisitor::VisitCompoundStmt(const CompoundStmt *S) {
Pete Cooper57d3f142015-07-30 17:22:52 +00002350 for (auto &I : llvm::reverse(S->body()))
2351 AddStmt(I);
Guy Benyei11169dd2012-12-18 14:30:41 +00002352}
2353void EnqueueVisitor::
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002354VisitMSDependentExistsStmt(const MSDependentExistsStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002355 AddStmt(S->getSubStmt());
2356 AddDeclarationNameInfo(S);
2357 if (NestedNameSpecifierLoc QualifierLoc = S->getQualifierLoc())
2358 AddNestedNameSpecifierLoc(QualifierLoc);
2359}
2360
2361void EnqueueVisitor::
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002362VisitCXXDependentScopeMemberExpr(const CXXDependentScopeMemberExpr *E) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002363 if (E->hasExplicitTemplateArgs())
2364 AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002365 AddDeclarationNameInfo(E);
2366 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
2367 AddNestedNameSpecifierLoc(QualifierLoc);
2368 if (!E->isImplicitAccess())
2369 AddStmt(E->getBase());
2370}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002371void EnqueueVisitor::VisitCXXNewExpr(const CXXNewExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002372 // Enqueue the initializer , if any.
2373 AddStmt(E->getInitializer());
2374 // Enqueue the array size, if any.
2375 AddStmt(E->getArraySize());
2376 // Enqueue the allocated type.
2377 AddTypeLoc(E->getAllocatedTypeSourceInfo());
2378 // Enqueue the placement arguments.
2379 for (unsigned I = E->getNumPlacementArgs(); I > 0; --I)
2380 AddStmt(E->getPlacementArg(I-1));
2381}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002382void EnqueueVisitor::VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CE) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002383 for (unsigned I = CE->getNumArgs(); I > 1 /* Yes, this is 1 */; --I)
2384 AddStmt(CE->getArg(I-1));
2385 AddStmt(CE->getCallee());
2386 AddStmt(CE->getArg(0));
2387}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002388void EnqueueVisitor::VisitCXXPseudoDestructorExpr(
2389 const CXXPseudoDestructorExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002390 // Visit the name of the type being destroyed.
2391 AddTypeLoc(E->getDestroyedTypeInfo());
2392 // Visit the scope type that looks disturbingly like the nested-name-specifier
2393 // but isn't.
2394 AddTypeLoc(E->getScopeTypeInfo());
2395 // Visit the nested-name-specifier.
2396 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
2397 AddNestedNameSpecifierLoc(QualifierLoc);
2398 // Visit base expression.
2399 AddStmt(E->getBase());
2400}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002401void EnqueueVisitor::VisitCXXScalarValueInitExpr(
2402 const CXXScalarValueInitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002403 AddTypeLoc(E->getTypeSourceInfo());
2404}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002405void EnqueueVisitor::VisitCXXTemporaryObjectExpr(
2406 const CXXTemporaryObjectExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002407 EnqueueChildren(E);
2408 AddTypeLoc(E->getTypeSourceInfo());
2409}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002410void EnqueueVisitor::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002411 EnqueueChildren(E);
2412 if (E->isTypeOperand())
2413 AddTypeLoc(E->getTypeOperandSourceInfo());
2414}
2415
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002416void EnqueueVisitor::VisitCXXUnresolvedConstructExpr(
2417 const CXXUnresolvedConstructExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002418 EnqueueChildren(E);
2419 AddTypeLoc(E->getTypeSourceInfo());
2420}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002421void EnqueueVisitor::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002422 EnqueueChildren(E);
2423 if (E->isTypeOperand())
2424 AddTypeLoc(E->getTypeOperandSourceInfo());
2425}
2426
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002427void EnqueueVisitor::VisitCXXCatchStmt(const CXXCatchStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002428 EnqueueChildren(S);
2429 AddDecl(S->getExceptionDecl());
2430}
2431
Argyrios Kyrtzidis99891242014-11-13 09:03:21 +00002432void EnqueueVisitor::VisitCXXForRangeStmt(const CXXForRangeStmt *S) {
Argyrios Kyrtzidiscde70692014-11-13 09:50:19 +00002433 AddStmt(S->getBody());
Argyrios Kyrtzidis99891242014-11-13 09:03:21 +00002434 AddStmt(S->getRangeInit());
Argyrios Kyrtzidiscde70692014-11-13 09:50:19 +00002435 AddDecl(S->getLoopVariable());
Argyrios Kyrtzidis99891242014-11-13 09:03:21 +00002436}
2437
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002438void EnqueueVisitor::VisitDeclRefExpr(const DeclRefExpr *DR) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002439 if (DR->hasExplicitTemplateArgs())
2440 AddExplicitTemplateArgs(DR->getTemplateArgs(), DR->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002441 WL.push_back(DeclRefExprParts(DR, Parent));
2442}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002443void EnqueueVisitor::VisitDependentScopeDeclRefExpr(
2444 const DependentScopeDeclRefExpr *E) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002445 if (E->hasExplicitTemplateArgs())
2446 AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002447 AddDeclarationNameInfo(E);
2448 AddNestedNameSpecifierLoc(E->getQualifierLoc());
2449}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002450void EnqueueVisitor::VisitDeclStmt(const DeclStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002451 unsigned size = WL.size();
2452 bool isFirst = true;
Aaron Ballman535bbcc2014-03-14 17:01:24 +00002453 for (const auto *D : S->decls()) {
2454 AddDecl(D, isFirst);
Guy Benyei11169dd2012-12-18 14:30:41 +00002455 isFirst = false;
2456 }
2457 if (size == WL.size())
2458 return;
2459 // Now reverse the entries we just added. This will match the DFS
2460 // ordering performed by the worklist.
2461 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2462 std::reverse(I, E);
2463}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002464void EnqueueVisitor::VisitDesignatedInitExpr(const DesignatedInitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002465 AddStmt(E->getInit());
David Majnemerf7e36092016-06-23 00:15:04 +00002466 for (const DesignatedInitExpr::Designator &D :
2467 llvm::reverse(E->designators())) {
2468 if (D.isFieldDesignator()) {
2469 if (FieldDecl *Field = D.getField())
2470 AddMemberRef(Field, D.getFieldLoc());
Guy Benyei11169dd2012-12-18 14:30:41 +00002471 continue;
2472 }
David Majnemerf7e36092016-06-23 00:15:04 +00002473 if (D.isArrayDesignator()) {
2474 AddStmt(E->getArrayIndex(D));
Guy Benyei11169dd2012-12-18 14:30:41 +00002475 continue;
2476 }
David Majnemerf7e36092016-06-23 00:15:04 +00002477 assert(D.isArrayRangeDesignator() && "Unknown designator kind");
2478 AddStmt(E->getArrayRangeEnd(D));
2479 AddStmt(E->getArrayRangeStart(D));
Guy Benyei11169dd2012-12-18 14:30:41 +00002480 }
2481}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002482void EnqueueVisitor::VisitExplicitCastExpr(const ExplicitCastExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002483 EnqueueChildren(E);
2484 AddTypeLoc(E->getTypeInfoAsWritten());
2485}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002486void EnqueueVisitor::VisitForStmt(const ForStmt *FS) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002487 AddStmt(FS->getBody());
2488 AddStmt(FS->getInc());
2489 AddStmt(FS->getCond());
2490 AddDecl(FS->getConditionVariable());
2491 AddStmt(FS->getInit());
2492}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002493void EnqueueVisitor::VisitGotoStmt(const GotoStmt *GS) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002494 WL.push_back(LabelRefVisit(GS->getLabel(), GS->getLabelLoc(), Parent));
2495}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002496void EnqueueVisitor::VisitIfStmt(const IfStmt *If) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002497 AddStmt(If->getElse());
2498 AddStmt(If->getThen());
2499 AddStmt(If->getCond());
2500 AddDecl(If->getConditionVariable());
2501}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002502void EnqueueVisitor::VisitInitListExpr(const InitListExpr *IE) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002503 // We care about the syntactic form of the initializer list, only.
2504 if (InitListExpr *Syntactic = IE->getSyntacticForm())
2505 IE = Syntactic;
2506 EnqueueChildren(IE);
2507}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002508void EnqueueVisitor::VisitMemberExpr(const MemberExpr *M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002509 WL.push_back(MemberExprParts(M, Parent));
2510
2511 // If the base of the member access expression is an implicit 'this', don't
2512 // visit it.
2513 // FIXME: If we ever want to show these implicit accesses, this will be
2514 // unfortunate. However, clang_getCursor() relies on this behavior.
Argyrios Kyrtzidis58d0e7a2015-03-13 04:40:07 +00002515 if (M->isImplicitAccess())
2516 return;
2517
2518 // Ignore base anonymous struct/union fields, otherwise they will shadow the
2519 // real field that that we are interested in.
2520 if (auto *SubME = dyn_cast<MemberExpr>(M->getBase())) {
2521 if (auto *FD = dyn_cast_or_null<FieldDecl>(SubME->getMemberDecl())) {
2522 if (FD->isAnonymousStructOrUnion()) {
2523 AddStmt(SubME->getBase());
2524 return;
2525 }
2526 }
2527 }
2528
2529 AddStmt(M->getBase());
Guy Benyei11169dd2012-12-18 14:30:41 +00002530}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002531void EnqueueVisitor::VisitObjCEncodeExpr(const ObjCEncodeExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002532 AddTypeLoc(E->getEncodedTypeSourceInfo());
2533}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002534void EnqueueVisitor::VisitObjCMessageExpr(const ObjCMessageExpr *M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002535 EnqueueChildren(M);
2536 AddTypeLoc(M->getClassReceiverTypeInfo());
2537}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002538void EnqueueVisitor::VisitOffsetOfExpr(const OffsetOfExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002539 // Visit the components of the offsetof expression.
2540 for (unsigned N = E->getNumComponents(), I = N; I > 0; --I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002541 const OffsetOfNode &Node = E->getComponent(I-1);
2542 switch (Node.getKind()) {
2543 case OffsetOfNode::Array:
2544 AddStmt(E->getIndexExpr(Node.getArrayExprIndex()));
2545 break;
2546 case OffsetOfNode::Field:
2547 AddMemberRef(Node.getField(), Node.getSourceRange().getEnd());
2548 break;
2549 case OffsetOfNode::Identifier:
2550 case OffsetOfNode::Base:
2551 continue;
2552 }
2553 }
2554 // Visit the type into which we're computing the offset.
2555 AddTypeLoc(E->getTypeSourceInfo());
2556}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002557void EnqueueVisitor::VisitOverloadExpr(const OverloadExpr *E) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002558 if (E->hasExplicitTemplateArgs())
2559 AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002560 WL.push_back(OverloadExprParts(E, Parent));
2561}
2562void EnqueueVisitor::VisitUnaryExprOrTypeTraitExpr(
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002563 const UnaryExprOrTypeTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002564 EnqueueChildren(E);
2565 if (E->isArgumentType())
2566 AddTypeLoc(E->getArgumentTypeInfo());
2567}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002568void EnqueueVisitor::VisitStmt(const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002569 EnqueueChildren(S);
2570}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002571void EnqueueVisitor::VisitSwitchStmt(const SwitchStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002572 AddStmt(S->getBody());
2573 AddStmt(S->getCond());
2574 AddDecl(S->getConditionVariable());
2575}
2576
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002577void EnqueueVisitor::VisitWhileStmt(const WhileStmt *W) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002578 AddStmt(W->getBody());
2579 AddStmt(W->getCond());
2580 AddDecl(W->getConditionVariable());
2581}
2582
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002583void EnqueueVisitor::VisitTypeTraitExpr(const TypeTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002584 for (unsigned I = E->getNumArgs(); I > 0; --I)
2585 AddTypeLoc(E->getArg(I-1));
2586}
2587
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002588void EnqueueVisitor::VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002589 AddTypeLoc(E->getQueriedTypeSourceInfo());
2590}
2591
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002592void EnqueueVisitor::VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002593 EnqueueChildren(E);
2594}
2595
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002596void EnqueueVisitor::VisitUnresolvedMemberExpr(const UnresolvedMemberExpr *U) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002597 VisitOverloadExpr(U);
2598 if (!U->isImplicitAccess())
2599 AddStmt(U->getBase());
2600}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002601void EnqueueVisitor::VisitVAArgExpr(const VAArgExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002602 AddStmt(E->getSubExpr());
2603 AddTypeLoc(E->getWrittenTypeInfo());
2604}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002605void EnqueueVisitor::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002606 WL.push_back(SizeOfPackExprParts(E, Parent));
2607}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002608void EnqueueVisitor::VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002609 // If the opaque value has a source expression, just transparently
2610 // visit that. This is useful for (e.g.) pseudo-object expressions.
2611 if (Expr *SourceExpr = E->getSourceExpr())
2612 return Visit(SourceExpr);
2613}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002614void EnqueueVisitor::VisitLambdaExpr(const LambdaExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002615 AddStmt(E->getBody());
2616 WL.push_back(LambdaExprParts(E, Parent));
2617}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002618void EnqueueVisitor::VisitPseudoObjectExpr(const PseudoObjectExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002619 // Treat the expression like its syntactic form.
2620 Visit(E->getSyntacticForm());
2621}
2622
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002623void EnqueueVisitor::VisitOMPExecutableDirective(
2624 const OMPExecutableDirective *D) {
2625 EnqueueChildren(D);
2626 for (ArrayRef<OMPClause *>::iterator I = D->clauses().begin(),
2627 E = D->clauses().end();
2628 I != E; ++I)
2629 EnqueueChildren(*I);
2630}
2631
Alexander Musman3aaab662014-08-19 11:27:13 +00002632void EnqueueVisitor::VisitOMPLoopDirective(const OMPLoopDirective *D) {
2633 VisitOMPExecutableDirective(D);
2634}
2635
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002636void EnqueueVisitor::VisitOMPParallelDirective(const OMPParallelDirective *D) {
2637 VisitOMPExecutableDirective(D);
2638}
2639
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002640void EnqueueVisitor::VisitOMPSimdDirective(const OMPSimdDirective *D) {
Alexander Musman3aaab662014-08-19 11:27:13 +00002641 VisitOMPLoopDirective(D);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002642}
2643
Alexey Bataevf29276e2014-06-18 04:14:57 +00002644void EnqueueVisitor::VisitOMPForDirective(const OMPForDirective *D) {
Alexander Musman3aaab662014-08-19 11:27:13 +00002645 VisitOMPLoopDirective(D);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002646}
2647
Alexander Musmanf82886e2014-09-18 05:12:34 +00002648void EnqueueVisitor::VisitOMPForSimdDirective(const OMPForSimdDirective *D) {
2649 VisitOMPLoopDirective(D);
2650}
2651
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002652void EnqueueVisitor::VisitOMPSectionsDirective(const OMPSectionsDirective *D) {
2653 VisitOMPExecutableDirective(D);
2654}
2655
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002656void EnqueueVisitor::VisitOMPSectionDirective(const OMPSectionDirective *D) {
2657 VisitOMPExecutableDirective(D);
2658}
2659
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00002660void EnqueueVisitor::VisitOMPSingleDirective(const OMPSingleDirective *D) {
2661 VisitOMPExecutableDirective(D);
2662}
2663
Alexander Musman80c22892014-07-17 08:54:58 +00002664void EnqueueVisitor::VisitOMPMasterDirective(const OMPMasterDirective *D) {
2665 VisitOMPExecutableDirective(D);
2666}
2667
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002668void EnqueueVisitor::VisitOMPCriticalDirective(const OMPCriticalDirective *D) {
2669 VisitOMPExecutableDirective(D);
2670 AddDeclarationNameInfo(D);
2671}
2672
Alexey Bataev4acb8592014-07-07 13:01:15 +00002673void
2674EnqueueVisitor::VisitOMPParallelForDirective(const OMPParallelForDirective *D) {
Alexander Musman3aaab662014-08-19 11:27:13 +00002675 VisitOMPLoopDirective(D);
Alexey Bataev4acb8592014-07-07 13:01:15 +00002676}
2677
Alexander Musmane4e893b2014-09-23 09:33:00 +00002678void EnqueueVisitor::VisitOMPParallelForSimdDirective(
2679 const OMPParallelForSimdDirective *D) {
2680 VisitOMPLoopDirective(D);
2681}
2682
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002683void EnqueueVisitor::VisitOMPParallelSectionsDirective(
2684 const OMPParallelSectionsDirective *D) {
2685 VisitOMPExecutableDirective(D);
2686}
2687
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002688void EnqueueVisitor::VisitOMPTaskDirective(const OMPTaskDirective *D) {
2689 VisitOMPExecutableDirective(D);
2690}
2691
Alexey Bataev68446b72014-07-18 07:47:19 +00002692void
2693EnqueueVisitor::VisitOMPTaskyieldDirective(const OMPTaskyieldDirective *D) {
2694 VisitOMPExecutableDirective(D);
2695}
2696
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002697void EnqueueVisitor::VisitOMPBarrierDirective(const OMPBarrierDirective *D) {
2698 VisitOMPExecutableDirective(D);
2699}
2700
Alexey Bataev2df347a2014-07-18 10:17:07 +00002701void EnqueueVisitor::VisitOMPTaskwaitDirective(const OMPTaskwaitDirective *D) {
2702 VisitOMPExecutableDirective(D);
2703}
2704
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002705void EnqueueVisitor::VisitOMPTaskgroupDirective(
2706 const OMPTaskgroupDirective *D) {
2707 VisitOMPExecutableDirective(D);
2708}
2709
Alexey Bataev6125da92014-07-21 11:26:11 +00002710void EnqueueVisitor::VisitOMPFlushDirective(const OMPFlushDirective *D) {
2711 VisitOMPExecutableDirective(D);
2712}
2713
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002714void EnqueueVisitor::VisitOMPOrderedDirective(const OMPOrderedDirective *D) {
2715 VisitOMPExecutableDirective(D);
2716}
2717
Alexey Bataev0162e452014-07-22 10:10:35 +00002718void EnqueueVisitor::VisitOMPAtomicDirective(const OMPAtomicDirective *D) {
2719 VisitOMPExecutableDirective(D);
2720}
2721
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002722void EnqueueVisitor::VisitOMPTargetDirective(const OMPTargetDirective *D) {
2723 VisitOMPExecutableDirective(D);
2724}
2725
Michael Wong65f367f2015-07-21 13:44:28 +00002726void EnqueueVisitor::VisitOMPTargetDataDirective(const
2727 OMPTargetDataDirective *D) {
2728 VisitOMPExecutableDirective(D);
2729}
2730
Samuel Antaodf67fc42016-01-19 19:15:56 +00002731void EnqueueVisitor::VisitOMPTargetEnterDataDirective(
2732 const OMPTargetEnterDataDirective *D) {
2733 VisitOMPExecutableDirective(D);
2734}
2735
Samuel Antao72590762016-01-19 20:04:50 +00002736void EnqueueVisitor::VisitOMPTargetExitDataDirective(
2737 const OMPTargetExitDataDirective *D) {
2738 VisitOMPExecutableDirective(D);
2739}
2740
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00002741void EnqueueVisitor::VisitOMPTargetParallelDirective(
2742 const OMPTargetParallelDirective *D) {
2743 VisitOMPExecutableDirective(D);
2744}
2745
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00002746void EnqueueVisitor::VisitOMPTargetParallelForDirective(
2747 const OMPTargetParallelForDirective *D) {
2748 VisitOMPLoopDirective(D);
2749}
2750
Alexey Bataev13314bf2014-10-09 04:18:56 +00002751void EnqueueVisitor::VisitOMPTeamsDirective(const OMPTeamsDirective *D) {
2752 VisitOMPExecutableDirective(D);
2753}
2754
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002755void EnqueueVisitor::VisitOMPCancellationPointDirective(
2756 const OMPCancellationPointDirective *D) {
2757 VisitOMPExecutableDirective(D);
2758}
2759
Alexey Bataev80909872015-07-02 11:25:17 +00002760void EnqueueVisitor::VisitOMPCancelDirective(const OMPCancelDirective *D) {
2761 VisitOMPExecutableDirective(D);
2762}
2763
Alexey Bataev49f6e782015-12-01 04:18:41 +00002764void EnqueueVisitor::VisitOMPTaskLoopDirective(const OMPTaskLoopDirective *D) {
2765 VisitOMPLoopDirective(D);
2766}
2767
Alexey Bataev0a6ed842015-12-03 09:40:15 +00002768void EnqueueVisitor::VisitOMPTaskLoopSimdDirective(
2769 const OMPTaskLoopSimdDirective *D) {
2770 VisitOMPLoopDirective(D);
2771}
2772
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002773void EnqueueVisitor::VisitOMPDistributeDirective(
2774 const OMPDistributeDirective *D) {
2775 VisitOMPLoopDirective(D);
2776}
2777
Carlo Bertolli9925f152016-06-27 14:55:37 +00002778void EnqueueVisitor::VisitOMPDistributeParallelForDirective(
2779 const OMPDistributeParallelForDirective *D) {
2780 VisitOMPLoopDirective(D);
2781}
2782
Kelvin Li4a39add2016-07-05 05:00:15 +00002783void EnqueueVisitor::VisitOMPDistributeParallelForSimdDirective(
2784 const OMPDistributeParallelForSimdDirective *D) {
2785 VisitOMPLoopDirective(D);
2786}
2787
Kelvin Li787f3fc2016-07-06 04:45:38 +00002788void EnqueueVisitor::VisitOMPDistributeSimdDirective(
2789 const OMPDistributeSimdDirective *D) {
2790 VisitOMPLoopDirective(D);
2791}
2792
Kelvin Lia579b912016-07-14 02:54:56 +00002793void EnqueueVisitor::VisitOMPTargetParallelForSimdDirective(
2794 const OMPTargetParallelForSimdDirective *D) {
2795 VisitOMPLoopDirective(D);
2796}
2797
Kelvin Li986330c2016-07-20 22:57:10 +00002798void EnqueueVisitor::VisitOMPTargetSimdDirective(
2799 const OMPTargetSimdDirective *D) {
2800 VisitOMPLoopDirective(D);
2801}
2802
Kelvin Li02532872016-08-05 14:37:37 +00002803void EnqueueVisitor::VisitOMPTeamsDistributeDirective(
2804 const OMPTeamsDistributeDirective *D) {
2805 VisitOMPLoopDirective(D);
2806}
2807
Kelvin Li4e325f72016-10-25 12:50:55 +00002808void EnqueueVisitor::VisitOMPTeamsDistributeSimdDirective(
2809 const OMPTeamsDistributeSimdDirective *D) {
2810 VisitOMPLoopDirective(D);
2811}
2812
Kelvin Li579e41c2016-11-30 23:51:03 +00002813void EnqueueVisitor::VisitOMPTeamsDistributeParallelForSimdDirective(
2814 const OMPTeamsDistributeParallelForSimdDirective *D) {
2815 VisitOMPLoopDirective(D);
2816}
2817
Kelvin Li7ade93f2016-12-09 03:24:30 +00002818void EnqueueVisitor::VisitOMPTeamsDistributeParallelForDirective(
2819 const OMPTeamsDistributeParallelForDirective *D) {
2820 VisitOMPLoopDirective(D);
2821}
2822
Kelvin Libf594a52016-12-17 05:48:59 +00002823void EnqueueVisitor::VisitOMPTargetTeamsDirective(
2824 const OMPTargetTeamsDirective *D) {
2825 VisitOMPExecutableDirective(D);
2826}
2827
Kelvin Li83c451e2016-12-25 04:52:54 +00002828void EnqueueVisitor::VisitOMPTargetTeamsDistributeDirective(
2829 const OMPTargetTeamsDistributeDirective *D) {
2830 VisitOMPLoopDirective(D);
2831}
2832
Kelvin Li80e8f562016-12-29 22:16:30 +00002833void EnqueueVisitor::VisitOMPTargetTeamsDistributeParallelForDirective(
2834 const OMPTargetTeamsDistributeParallelForDirective *D) {
2835 VisitOMPLoopDirective(D);
2836}
2837
Kelvin Li1851df52017-01-03 05:23:48 +00002838void EnqueueVisitor::VisitOMPTargetTeamsDistributeParallelForSimdDirective(
2839 const OMPTargetTeamsDistributeParallelForSimdDirective *D) {
2840 VisitOMPLoopDirective(D);
2841}
2842
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002843void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002844 EnqueueVisitor(WL, MakeCXCursor(S, StmtParent, TU,RegionOfInterest)).Visit(S);
2845}
2846
2847bool CursorVisitor::IsInRegionOfInterest(CXCursor C) {
2848 if (RegionOfInterest.isValid()) {
2849 SourceRange Range = getRawCursorExtent(C);
2850 if (Range.isInvalid() || CompareRegionOfInterest(Range))
2851 return false;
2852 }
2853 return true;
2854}
2855
2856bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) {
2857 while (!WL.empty()) {
2858 // Dequeue the worklist item.
Robert Wilhelm25284cc2013-08-23 16:11:15 +00002859 VisitorJob LI = WL.pop_back_val();
Guy Benyei11169dd2012-12-18 14:30:41 +00002860
2861 // Set the Parent field, then back to its old value once we're done.
2862 SetParentRAII SetParent(Parent, StmtParent, LI.getParent());
2863
2864 switch (LI.getKind()) {
2865 case VisitorJob::DeclVisitKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002866 const Decl *D = cast<DeclVisit>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00002867 if (!D)
2868 continue;
2869
2870 // For now, perform default visitation for Decls.
2871 if (Visit(MakeCXCursor(D, TU, RegionOfInterest,
2872 cast<DeclVisit>(&LI)->isFirst())))
2873 return true;
2874
2875 continue;
2876 }
2877 case VisitorJob::ExplicitTemplateArgsVisitKind: {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002878 for (const TemplateArgumentLoc &Arg :
2879 *cast<ExplicitTemplateArgsVisit>(&LI)) {
2880 if (VisitTemplateArgumentLoc(Arg))
Guy Benyei11169dd2012-12-18 14:30:41 +00002881 return true;
2882 }
2883 continue;
2884 }
2885 case VisitorJob::TypeLocVisitKind: {
2886 // Perform default visitation for TypeLocs.
2887 if (Visit(cast<TypeLocVisit>(&LI)->get()))
2888 return true;
2889 continue;
2890 }
2891 case VisitorJob::LabelRefVisitKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002892 const LabelDecl *LS = cast<LabelRefVisit>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00002893 if (LabelStmt *stmt = LS->getStmt()) {
2894 if (Visit(MakeCursorLabelRef(stmt, cast<LabelRefVisit>(&LI)->getLoc(),
2895 TU))) {
2896 return true;
2897 }
2898 }
2899 continue;
2900 }
2901
2902 case VisitorJob::NestedNameSpecifierLocVisitKind: {
2903 NestedNameSpecifierLocVisit *V = cast<NestedNameSpecifierLocVisit>(&LI);
2904 if (VisitNestedNameSpecifierLoc(V->get()))
2905 return true;
2906 continue;
2907 }
2908
2909 case VisitorJob::DeclarationNameInfoVisitKind: {
2910 if (VisitDeclarationNameInfo(cast<DeclarationNameInfoVisit>(&LI)
2911 ->get()))
2912 return true;
2913 continue;
2914 }
2915 case VisitorJob::MemberRefVisitKind: {
2916 MemberRefVisit *V = cast<MemberRefVisit>(&LI);
2917 if (Visit(MakeCursorMemberRef(V->get(), V->getLoc(), TU)))
2918 return true;
2919 continue;
2920 }
2921 case VisitorJob::StmtVisitKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002922 const Stmt *S = cast<StmtVisit>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00002923 if (!S)
2924 continue;
2925
2926 // Update the current cursor.
2927 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU, RegionOfInterest);
2928 if (!IsInRegionOfInterest(Cursor))
2929 continue;
2930 switch (Visitor(Cursor, Parent, ClientData)) {
2931 case CXChildVisit_Break: return true;
2932 case CXChildVisit_Continue: break;
2933 case CXChildVisit_Recurse:
2934 if (PostChildrenVisitor)
Craig Topper69186e72014-06-08 08:38:04 +00002935 WL.push_back(PostChildrenVisit(nullptr, Cursor));
Guy Benyei11169dd2012-12-18 14:30:41 +00002936 EnqueueWorkList(WL, S);
2937 break;
2938 }
2939 continue;
2940 }
2941 case VisitorJob::MemberExprPartsKind: {
2942 // Handle the other pieces in the MemberExpr besides the base.
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002943 const MemberExpr *M = cast<MemberExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00002944
2945 // Visit the nested-name-specifier
2946 if (NestedNameSpecifierLoc QualifierLoc = M->getQualifierLoc())
2947 if (VisitNestedNameSpecifierLoc(QualifierLoc))
2948 return true;
2949
2950 // Visit the declaration name.
2951 if (VisitDeclarationNameInfo(M->getMemberNameInfo()))
2952 return true;
2953
2954 // Visit the explicitly-specified template arguments, if any.
2955 if (M->hasExplicitTemplateArgs()) {
2956 for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(),
2957 *ArgEnd = Arg + M->getNumTemplateArgs();
2958 Arg != ArgEnd; ++Arg) {
2959 if (VisitTemplateArgumentLoc(*Arg))
2960 return true;
2961 }
2962 }
2963 continue;
2964 }
2965 case VisitorJob::DeclRefExprPartsKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002966 const DeclRefExpr *DR = cast<DeclRefExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00002967 // Visit nested-name-specifier, if present.
2968 if (NestedNameSpecifierLoc QualifierLoc = DR->getQualifierLoc())
2969 if (VisitNestedNameSpecifierLoc(QualifierLoc))
2970 return true;
2971 // Visit declaration name.
2972 if (VisitDeclarationNameInfo(DR->getNameInfo()))
2973 return true;
2974 continue;
2975 }
2976 case VisitorJob::OverloadExprPartsKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002977 const OverloadExpr *O = cast<OverloadExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00002978 // Visit the nested-name-specifier.
2979 if (NestedNameSpecifierLoc QualifierLoc = O->getQualifierLoc())
2980 if (VisitNestedNameSpecifierLoc(QualifierLoc))
2981 return true;
2982 // Visit the declaration name.
2983 if (VisitDeclarationNameInfo(O->getNameInfo()))
2984 return true;
2985 // Visit the overloaded declaration reference.
2986 if (Visit(MakeCursorOverloadedDeclRef(O, TU)))
2987 return true;
2988 continue;
2989 }
2990 case VisitorJob::SizeOfPackExprPartsKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002991 const SizeOfPackExpr *E = cast<SizeOfPackExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00002992 NamedDecl *Pack = E->getPack();
2993 if (isa<TemplateTypeParmDecl>(Pack)) {
2994 if (Visit(MakeCursorTypeRef(cast<TemplateTypeParmDecl>(Pack),
2995 E->getPackLoc(), TU)))
2996 return true;
2997
2998 continue;
2999 }
3000
3001 if (isa<TemplateTemplateParmDecl>(Pack)) {
3002 if (Visit(MakeCursorTemplateRef(cast<TemplateTemplateParmDecl>(Pack),
3003 E->getPackLoc(), TU)))
3004 return true;
3005
3006 continue;
3007 }
3008
3009 // Non-type template parameter packs and function parameter packs are
3010 // treated like DeclRefExpr cursors.
3011 continue;
3012 }
3013
3014 case VisitorJob::LambdaExprPartsKind: {
3015 // Visit captures.
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003016 const LambdaExpr *E = cast<LambdaExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003017 for (LambdaExpr::capture_iterator C = E->explicit_capture_begin(),
3018 CEnd = E->explicit_capture_end();
3019 C != CEnd; ++C) {
Richard Smithba71c082013-05-16 06:20:58 +00003020 // FIXME: Lambda init-captures.
3021 if (!C->capturesVariable())
Guy Benyei11169dd2012-12-18 14:30:41 +00003022 continue;
Richard Smithba71c082013-05-16 06:20:58 +00003023
Guy Benyei11169dd2012-12-18 14:30:41 +00003024 if (Visit(MakeCursorVariableRef(C->getCapturedVar(),
3025 C->getLocation(),
3026 TU)))
3027 return true;
3028 }
3029
3030 // Visit parameters and return type, if present.
3031 if (E->hasExplicitParameters() || E->hasExplicitResultType()) {
3032 TypeLoc TL = E->getCallOperator()->getTypeSourceInfo()->getTypeLoc();
3033 if (E->hasExplicitParameters() && E->hasExplicitResultType()) {
3034 // Visit the whole type.
3035 if (Visit(TL))
3036 return true;
David Blaikie6adc78e2013-02-18 22:06:02 +00003037 } else if (FunctionProtoTypeLoc Proto =
3038 TL.getAs<FunctionProtoTypeLoc>()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003039 if (E->hasExplicitParameters()) {
3040 // Visit parameters.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00003041 for (unsigned I = 0, N = Proto.getNumParams(); I != N; ++I)
3042 if (Visit(MakeCXCursor(Proto.getParam(I), TU)))
Guy Benyei11169dd2012-12-18 14:30:41 +00003043 return true;
3044 } else {
3045 // Visit result type.
Alp Toker42a16a62014-01-25 23:51:36 +00003046 if (Visit(Proto.getReturnLoc()))
Guy Benyei11169dd2012-12-18 14:30:41 +00003047 return true;
3048 }
3049 }
3050 }
3051 break;
3052 }
3053
3054 case VisitorJob::PostChildrenVisitKind:
3055 if (PostChildrenVisitor(Parent, ClientData))
3056 return true;
3057 break;
3058 }
3059 }
3060 return false;
3061}
3062
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003063bool CursorVisitor::Visit(const Stmt *S) {
Craig Topper69186e72014-06-08 08:38:04 +00003064 VisitorWorkList *WL = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00003065 if (!WorkListFreeList.empty()) {
3066 WL = WorkListFreeList.back();
3067 WL->clear();
3068 WorkListFreeList.pop_back();
3069 }
3070 else {
3071 WL = new VisitorWorkList();
3072 WorkListCache.push_back(WL);
3073 }
3074 EnqueueWorkList(*WL, S);
3075 bool result = RunVisitorWorkList(*WL);
3076 WorkListFreeList.push_back(WL);
3077 return result;
3078}
3079
3080namespace {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003081typedef SmallVector<SourceRange, 4> RefNamePieces;
James Y Knight04ec5bf2015-12-24 02:59:37 +00003082RefNamePieces buildPieces(unsigned NameFlags, bool IsMemberRefExpr,
3083 const DeclarationNameInfo &NI, SourceRange QLoc,
3084 const SourceRange *TemplateArgsLoc = nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003085 const bool WantQualifier = NameFlags & CXNameRange_WantQualifier;
3086 const bool WantTemplateArgs = NameFlags & CXNameRange_WantTemplateArgs;
3087 const bool WantSinglePiece = NameFlags & CXNameRange_WantSinglePiece;
3088
3089 const DeclarationName::NameKind Kind = NI.getName().getNameKind();
3090
3091 RefNamePieces Pieces;
3092
3093 if (WantQualifier && QLoc.isValid())
3094 Pieces.push_back(QLoc);
3095
3096 if (Kind != DeclarationName::CXXOperatorName || IsMemberRefExpr)
3097 Pieces.push_back(NI.getLoc());
James Y Knight04ec5bf2015-12-24 02:59:37 +00003098
3099 if (WantTemplateArgs && TemplateArgsLoc && TemplateArgsLoc->isValid())
3100 Pieces.push_back(*TemplateArgsLoc);
3101
Guy Benyei11169dd2012-12-18 14:30:41 +00003102 if (Kind == DeclarationName::CXXOperatorName) {
3103 Pieces.push_back(SourceLocation::getFromRawEncoding(
3104 NI.getInfo().CXXOperatorName.BeginOpNameLoc));
3105 Pieces.push_back(SourceLocation::getFromRawEncoding(
3106 NI.getInfo().CXXOperatorName.EndOpNameLoc));
3107 }
3108
3109 if (WantSinglePiece) {
3110 SourceRange R(Pieces.front().getBegin(), Pieces.back().getEnd());
3111 Pieces.clear();
3112 Pieces.push_back(R);
3113 }
3114
3115 return Pieces;
3116}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003117}
Guy Benyei11169dd2012-12-18 14:30:41 +00003118
3119//===----------------------------------------------------------------------===//
3120// Misc. API hooks.
3121//===----------------------------------------------------------------------===//
3122
Chad Rosier05c71aa2013-03-27 18:28:23 +00003123static void fatal_error_handler(void *user_data, const std::string& reason,
3124 bool gen_crash_diag) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003125 // Write the result out to stderr avoiding errs() because raw_ostreams can
3126 // call report_fatal_error.
3127 fprintf(stderr, "LIBCLANG FATAL ERROR: %s\n", reason.c_str());
3128 ::abort();
3129}
3130
Chandler Carruth66660742014-06-27 16:37:27 +00003131namespace {
3132struct RegisterFatalErrorHandler {
3133 RegisterFatalErrorHandler() {
3134 llvm::install_fatal_error_handler(fatal_error_handler, nullptr);
3135 }
3136};
3137}
3138
3139static llvm::ManagedStatic<RegisterFatalErrorHandler> RegisterFatalErrorHandlerOnce;
3140
Guy Benyei11169dd2012-12-18 14:30:41 +00003141CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
3142 int displayDiagnostics) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003143 // We use crash recovery to make some of our APIs more reliable, implicitly
3144 // enable it.
Argyrios Kyrtzidis3701f542013-11-27 08:58:09 +00003145 if (!getenv("LIBCLANG_DISABLE_CRASH_RECOVERY"))
3146 llvm::CrashRecoveryContext::Enable();
Guy Benyei11169dd2012-12-18 14:30:41 +00003147
Chandler Carruth66660742014-06-27 16:37:27 +00003148 // Look through the managed static to trigger construction of the managed
3149 // static which registers our fatal error handler. This ensures it is only
3150 // registered once.
3151 (void)*RegisterFatalErrorHandlerOnce;
Guy Benyei11169dd2012-12-18 14:30:41 +00003152
Adrian Prantlbc068582015-07-08 01:00:30 +00003153 // Initialize targets for clang module support.
3154 llvm::InitializeAllTargets();
3155 llvm::InitializeAllTargetMCs();
3156 llvm::InitializeAllAsmPrinters();
3157 llvm::InitializeAllAsmParsers();
3158
Adrian Prantlfb2398d2015-07-17 01:19:54 +00003159 CIndexer *CIdxr = new CIndexer();
3160
Guy Benyei11169dd2012-12-18 14:30:41 +00003161 if (excludeDeclarationsFromPCH)
3162 CIdxr->setOnlyLocalDecls();
3163 if (displayDiagnostics)
3164 CIdxr->setDisplayDiagnostics();
3165
3166 if (getenv("LIBCLANG_BGPRIO_INDEX"))
3167 CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() |
3168 CXGlobalOpt_ThreadBackgroundPriorityForIndexing);
3169 if (getenv("LIBCLANG_BGPRIO_EDIT"))
3170 CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() |
3171 CXGlobalOpt_ThreadBackgroundPriorityForEditing);
3172
3173 return CIdxr;
3174}
3175
3176void clang_disposeIndex(CXIndex CIdx) {
3177 if (CIdx)
3178 delete static_cast<CIndexer *>(CIdx);
3179}
3180
3181void clang_CXIndex_setGlobalOptions(CXIndex CIdx, unsigned options) {
3182 if (CIdx)
3183 static_cast<CIndexer *>(CIdx)->setCXGlobalOptFlags(options);
3184}
3185
3186unsigned clang_CXIndex_getGlobalOptions(CXIndex CIdx) {
3187 if (CIdx)
3188 return static_cast<CIndexer *>(CIdx)->getCXGlobalOptFlags();
3189 return 0;
3190}
3191
3192void clang_toggleCrashRecovery(unsigned isEnabled) {
3193 if (isEnabled)
3194 llvm::CrashRecoveryContext::Enable();
3195 else
3196 llvm::CrashRecoveryContext::Disable();
3197}
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003198
Guy Benyei11169dd2012-12-18 14:30:41 +00003199CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
3200 const char *ast_filename) {
Dmitri Gribenko8850cda2014-02-19 10:24:00 +00003201 CXTranslationUnit TU;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003202 enum CXErrorCode Result =
3203 clang_createTranslationUnit2(CIdx, ast_filename, &TU);
Reid Klecknerfd48fc62014-02-12 23:56:20 +00003204 (void)Result;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003205 assert((TU && Result == CXError_Success) ||
3206 (!TU && Result != CXError_Success));
3207 return TU;
3208}
3209
3210enum CXErrorCode clang_createTranslationUnit2(CXIndex CIdx,
3211 const char *ast_filename,
3212 CXTranslationUnit *out_TU) {
Dmitri Gribenko8850cda2014-02-19 10:24:00 +00003213 if (out_TU)
Craig Topper69186e72014-06-08 08:38:04 +00003214 *out_TU = nullptr;
Dmitri Gribenko8850cda2014-02-19 10:24:00 +00003215
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003216 if (!CIdx || !ast_filename || !out_TU)
3217 return CXError_InvalidArguments;
Guy Benyei11169dd2012-12-18 14:30:41 +00003218
Argyrios Kyrtzidis27021012013-05-24 22:24:07 +00003219 LOG_FUNC_SECTION {
3220 *Log << ast_filename;
3221 }
3222
Guy Benyei11169dd2012-12-18 14:30:41 +00003223 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
3224 FileSystemOptions FileSystemOpts;
3225
Justin Bognerd512c1e2014-10-15 00:33:06 +00003226 IntrusiveRefCntPtr<DiagnosticsEngine> Diags =
3227 CompilerInstance::createDiagnostics(new DiagnosticOptions());
David Blaikie6f7382d2014-08-10 19:08:04 +00003228 std::unique_ptr<ASTUnit> AU = ASTUnit::LoadFromASTFile(
Adrian Prantlfb2398d2015-07-17 01:19:54 +00003229 ast_filename, CXXIdx->getPCHContainerOperations()->getRawReader(), Diags,
Adrian Prantl6b21ab22015-08-27 19:46:20 +00003230 FileSystemOpts, /*UseDebugInfo=*/false,
3231 CXXIdx->getOnlyLocalDecls(), None,
David Blaikie6f7382d2014-08-10 19:08:04 +00003232 /*CaptureDiagnostics=*/true,
3233 /*AllowPCHWithCompilerErrors=*/true,
3234 /*UserFilesAreVolatile=*/true);
David Blaikieea4395e2017-01-06 19:49:01 +00003235 *out_TU = MakeCXTranslationUnit(CXXIdx, std::move(AU));
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003236 return *out_TU ? CXError_Success : CXError_Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003237}
3238
3239unsigned clang_defaultEditingTranslationUnitOptions() {
3240 return CXTranslationUnit_PrecompiledPreamble |
3241 CXTranslationUnit_CacheCompletionResults;
3242}
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003243
Guy Benyei11169dd2012-12-18 14:30:41 +00003244CXTranslationUnit
3245clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
3246 const char *source_filename,
3247 int num_command_line_args,
3248 const char * const *command_line_args,
3249 unsigned num_unsaved_files,
3250 struct CXUnsavedFile *unsaved_files) {
3251 unsigned Options = CXTranslationUnit_DetailedPreprocessingRecord;
3252 return clang_parseTranslationUnit(CIdx, source_filename,
3253 command_line_args, num_command_line_args,
3254 unsaved_files, num_unsaved_files,
3255 Options);
3256}
3257
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003258static CXErrorCode
3259clang_parseTranslationUnit_Impl(CXIndex CIdx, const char *source_filename,
3260 const char *const *command_line_args,
3261 int num_command_line_args,
3262 ArrayRef<CXUnsavedFile> unsaved_files,
3263 unsigned options, CXTranslationUnit *out_TU) {
Dmitri Gribenko1bf8d912014-02-18 15:20:02 +00003264 // Set up the initial return values.
3265 if (out_TU)
Craig Topper69186e72014-06-08 08:38:04 +00003266 *out_TU = nullptr;
Dmitri Gribenko1bf8d912014-02-18 15:20:02 +00003267
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003268 // Check arguments.
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003269 if (!CIdx || !out_TU)
3270 return CXError_InvalidArguments;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003271
Guy Benyei11169dd2012-12-18 14:30:41 +00003272 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
3273
3274 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
3275 setThreadBackgroundPriority();
3276
3277 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Benjamin Kramer5c248d82015-12-15 09:30:31 +00003278 bool CreatePreambleOnFirstParse =
3279 options & CXTranslationUnit_CreatePreambleOnFirstParse;
Guy Benyei11169dd2012-12-18 14:30:41 +00003280 // FIXME: Add a flag for modules.
3281 TranslationUnitKind TUKind
3282 = (options & CXTranslationUnit_Incomplete)? TU_Prefix : TU_Complete;
Alp Toker8c8a8752013-12-03 06:53:35 +00003283 bool CacheCodeCompletionResults
Guy Benyei11169dd2012-12-18 14:30:41 +00003284 = options & CXTranslationUnit_CacheCompletionResults;
3285 bool IncludeBriefCommentsInCodeCompletion
3286 = options & CXTranslationUnit_IncludeBriefCommentsInCodeCompletion;
3287 bool SkipFunctionBodies = options & CXTranslationUnit_SkipFunctionBodies;
3288 bool ForSerialization = options & CXTranslationUnit_ForSerialization;
3289
3290 // Configure the diagnostics.
3291 IntrusiveRefCntPtr<DiagnosticsEngine>
Sean Silvaf1b49e22013-01-20 01:58:28 +00003292 Diags(CompilerInstance::createDiagnostics(new DiagnosticOptions));
Guy Benyei11169dd2012-12-18 14:30:41 +00003293
Manuel Klimek016c0242016-03-01 10:56:19 +00003294 if (options & CXTranslationUnit_KeepGoing)
3295 Diags->setFatalsAsError(true);
3296
Guy Benyei11169dd2012-12-18 14:30:41 +00003297 // Recover resources if we crash before exiting this function.
3298 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
3299 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Alp Tokerf994cef2014-07-05 03:08:06 +00003300 DiagCleanup(Diags.get());
Guy Benyei11169dd2012-12-18 14:30:41 +00003301
Ahmed Charlesb8984322014-03-07 20:03:18 +00003302 std::unique_ptr<std::vector<ASTUnit::RemappedFile>> RemappedFiles(
3303 new std::vector<ASTUnit::RemappedFile>());
Guy Benyei11169dd2012-12-18 14:30:41 +00003304
3305 // Recover resources if we crash before exiting this function.
3306 llvm::CrashRecoveryContextCleanupRegistrar<
3307 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
3308
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003309 for (auto &UF : unsaved_files) {
Rafael Espindolad87f8d72014-08-27 20:03:29 +00003310 std::unique_ptr<llvm::MemoryBuffer> MB =
Alp Toker9d85b182014-07-07 01:23:14 +00003311 llvm::MemoryBuffer::getMemBufferCopy(getContents(UF), UF.Filename);
Rafael Espindolad87f8d72014-08-27 20:03:29 +00003312 RemappedFiles->push_back(std::make_pair(UF.Filename, MB.release()));
Guy Benyei11169dd2012-12-18 14:30:41 +00003313 }
3314
Ahmed Charlesb8984322014-03-07 20:03:18 +00003315 std::unique_ptr<std::vector<const char *>> Args(
3316 new std::vector<const char *>());
Guy Benyei11169dd2012-12-18 14:30:41 +00003317
3318 // Recover resources if we crash before exiting this method.
3319 llvm::CrashRecoveryContextCleanupRegistrar<std::vector<const char*> >
3320 ArgsCleanup(Args.get());
3321
3322 // Since the Clang C library is primarily used by batch tools dealing with
3323 // (often very broken) source code, where spell-checking can have a
3324 // significant negative impact on performance (particularly when
3325 // precompiled headers are involved), we disable it by default.
3326 // Only do this if we haven't found a spell-checking-related argument.
3327 bool FoundSpellCheckingArgument = false;
3328 for (int I = 0; I != num_command_line_args; ++I) {
3329 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
3330 strcmp(command_line_args[I], "-fspell-checking") == 0) {
3331 FoundSpellCheckingArgument = true;
3332 break;
3333 }
3334 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003335 Args->insert(Args->end(), command_line_args,
3336 command_line_args + num_command_line_args);
3337
Benjamin Kramerc02670e2015-11-18 16:14:27 +00003338 if (!FoundSpellCheckingArgument)
3339 Args->insert(Args->begin() + 1, "-fno-spell-checking");
3340
Guy Benyei11169dd2012-12-18 14:30:41 +00003341 // The 'source_filename' argument is optional. If the caller does not
3342 // specify it then it is assumed that the source file is specified
3343 // in the actual argument list.
3344 // Put the source file after command_line_args otherwise if '-x' flag is
3345 // present it will be unused.
3346 if (source_filename)
3347 Args->push_back(source_filename);
3348
3349 // Do we need the detailed preprocessing record?
3350 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
3351 Args->push_back("-Xclang");
3352 Args->push_back("-detailed-preprocessing-record");
3353 }
3354
3355 unsigned NumErrors = Diags->getClient()->getNumErrors();
Ahmed Charlesb8984322014-03-07 20:03:18 +00003356 std::unique_ptr<ASTUnit> ErrUnit;
Benjamin Kramer5c248d82015-12-15 09:30:31 +00003357 // Unless the user specified that they want the preamble on the first parse
3358 // set it up to be created on the first reparse. This makes the first parse
3359 // faster, trading for a slower (first) reparse.
3360 unsigned PrecompilePreambleAfterNParses =
3361 !PrecompilePreamble ? 0 : 2 - CreatePreambleOnFirstParse;
Ahmed Charlesb8984322014-03-07 20:03:18 +00003362 std::unique_ptr<ASTUnit> Unit(ASTUnit::LoadFromCommandLine(
Adrian Prantlbb165fb2015-06-20 18:53:08 +00003363 Args->data(), Args->data() + Args->size(),
3364 CXXIdx->getPCHContainerOperations(), Diags,
Ahmed Charlesb8984322014-03-07 20:03:18 +00003365 CXXIdx->getClangResourcesPath(), CXXIdx->getOnlyLocalDecls(),
3366 /*CaptureDiagnostics=*/true, *RemappedFiles.get(),
Benjamin Kramer5c248d82015-12-15 09:30:31 +00003367 /*RemappedFilesKeepOriginalName=*/true, PrecompilePreambleAfterNParses,
3368 TUKind, CacheCodeCompletionResults, IncludeBriefCommentsInCodeCompletion,
Ahmed Charlesb8984322014-03-07 20:03:18 +00003369 /*AllowPCHWithCompilerErrors=*/true, SkipFunctionBodies,
Argyrios Kyrtzidisa3e2ff12015-11-20 03:36:21 +00003370 /*UserFilesAreVolatile=*/true, ForSerialization,
3371 CXXIdx->getPCHContainerOperations()->getRawReader().getFormat(),
3372 &ErrUnit));
Guy Benyei11169dd2012-12-18 14:30:41 +00003373
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003374 // Early failures in LoadFromCommandLine may return with ErrUnit unset.
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003375 if (!Unit && !ErrUnit)
3376 return CXError_ASTReadError;
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003377
Guy Benyei11169dd2012-12-18 14:30:41 +00003378 if (NumErrors != Diags->getClient()->getNumErrors()) {
3379 // Make sure to check that 'Unit' is non-NULL.
3380 if (CXXIdx->getDisplayDiagnostics())
3381 printDiagsToStderr(Unit ? Unit.get() : ErrUnit.get());
3382 }
3383
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003384 if (isASTReadError(Unit ? Unit.get() : ErrUnit.get()))
3385 return CXError_ASTReadError;
3386
David Blaikieea4395e2017-01-06 19:49:01 +00003387 *out_TU = MakeCXTranslationUnit(CXXIdx, std::move(Unit));
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003388 return *out_TU ? CXError_Success : CXError_Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003389}
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003390
3391CXTranslationUnit
3392clang_parseTranslationUnit(CXIndex CIdx,
3393 const char *source_filename,
3394 const char *const *command_line_args,
3395 int num_command_line_args,
3396 struct CXUnsavedFile *unsaved_files,
3397 unsigned num_unsaved_files,
3398 unsigned options) {
3399 CXTranslationUnit TU;
3400 enum CXErrorCode Result = clang_parseTranslationUnit2(
3401 CIdx, source_filename, command_line_args, num_command_line_args,
3402 unsaved_files, num_unsaved_files, options, &TU);
Reid Kleckner6eaf05a2014-02-13 01:19:59 +00003403 (void)Result;
Dmitri Gribenko1bf8d912014-02-18 15:20:02 +00003404 assert((TU && Result == CXError_Success) ||
3405 (!TU && Result != CXError_Success));
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003406 return TU;
3407}
3408
3409enum CXErrorCode clang_parseTranslationUnit2(
Benjamin Kramerc02670e2015-11-18 16:14:27 +00003410 CXIndex CIdx, const char *source_filename,
3411 const char *const *command_line_args, int num_command_line_args,
3412 struct CXUnsavedFile *unsaved_files, unsigned num_unsaved_files,
3413 unsigned options, CXTranslationUnit *out_TU) {
3414 SmallVector<const char *, 4> Args;
3415 Args.push_back("clang");
3416 Args.append(command_line_args, command_line_args + num_command_line_args);
3417 return clang_parseTranslationUnit2FullArgv(
3418 CIdx, source_filename, Args.data(), Args.size(), unsaved_files,
3419 num_unsaved_files, options, out_TU);
3420}
3421
3422enum CXErrorCode clang_parseTranslationUnit2FullArgv(
3423 CXIndex CIdx, const char *source_filename,
3424 const char *const *command_line_args, int num_command_line_args,
3425 struct CXUnsavedFile *unsaved_files, unsigned num_unsaved_files,
3426 unsigned options, CXTranslationUnit *out_TU) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00003427 LOG_FUNC_SECTION {
3428 *Log << source_filename << ": ";
3429 for (int i = 0; i != num_command_line_args; ++i)
3430 *Log << command_line_args[i] << " ";
3431 }
3432
Alp Toker9d85b182014-07-07 01:23:14 +00003433 if (num_unsaved_files && !unsaved_files)
3434 return CXError_InvalidArguments;
3435
Alp Toker5c532982014-07-07 22:42:03 +00003436 CXErrorCode result = CXError_Failure;
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003437 auto ParseTranslationUnitImpl = [=, &result] {
3438 result = clang_parseTranslationUnit_Impl(
3439 CIdx, source_filename, command_line_args, num_command_line_args,
3440 llvm::makeArrayRef(unsaved_files, num_unsaved_files), options, out_TU);
3441 };
Guy Benyei11169dd2012-12-18 14:30:41 +00003442 llvm::CrashRecoveryContext CRC;
3443
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003444 if (!RunSafely(CRC, ParseTranslationUnitImpl)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003445 fprintf(stderr, "libclang: crash detected during parsing: {\n");
3446 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
3447 fprintf(stderr, " 'command_line_args' : [");
3448 for (int i = 0; i != num_command_line_args; ++i) {
3449 if (i)
3450 fprintf(stderr, ", ");
3451 fprintf(stderr, "'%s'", command_line_args[i]);
3452 }
3453 fprintf(stderr, "],\n");
3454 fprintf(stderr, " 'unsaved_files' : [");
3455 for (unsigned i = 0; i != num_unsaved_files; ++i) {
3456 if (i)
3457 fprintf(stderr, ", ");
3458 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
3459 unsaved_files[i].Length);
3460 }
3461 fprintf(stderr, "],\n");
3462 fprintf(stderr, " 'options' : %d,\n", options);
3463 fprintf(stderr, "}\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003464
3465 return CXError_Crashed;
Guy Benyei11169dd2012-12-18 14:30:41 +00003466 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003467 if (CXTranslationUnit *TU = out_TU)
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003468 PrintLibclangResourceUsage(*TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00003469 }
Alp Toker5c532982014-07-07 22:42:03 +00003470
3471 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003472}
3473
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003474CXString clang_Type_getObjCEncoding(CXType CT) {
3475 CXTranslationUnit tu = static_cast<CXTranslationUnit>(CT.data[1]);
3476 ASTContext &Ctx = getASTUnit(tu)->getASTContext();
3477 std::string encoding;
3478 Ctx.getObjCEncodingForType(QualType::getFromOpaquePtr(CT.data[0]),
3479 encoding);
3480
3481 return cxstring::createDup(encoding);
3482}
3483
3484static const IdentifierInfo *getMacroIdentifier(CXCursor C) {
3485 if (C.kind == CXCursor_MacroDefinition) {
3486 if (const MacroDefinitionRecord *MDR = getCursorMacroDefinition(C))
3487 return MDR->getName();
3488 } else if (C.kind == CXCursor_MacroExpansion) {
3489 MacroExpansionCursor ME = getCursorMacroExpansion(C);
3490 return ME.getName();
3491 }
3492 return nullptr;
3493}
3494
3495unsigned clang_Cursor_isMacroFunctionLike(CXCursor C) {
3496 const IdentifierInfo *II = getMacroIdentifier(C);
3497 if (!II) {
3498 return false;
3499 }
3500 ASTUnit *ASTU = getCursorASTUnit(C);
3501 Preprocessor &PP = ASTU->getPreprocessor();
3502 if (const MacroInfo *MI = PP.getMacroInfo(II))
3503 return MI->isFunctionLike();
3504 return false;
3505}
3506
3507unsigned clang_Cursor_isMacroBuiltin(CXCursor C) {
3508 const IdentifierInfo *II = getMacroIdentifier(C);
3509 if (!II) {
3510 return false;
3511 }
3512 ASTUnit *ASTU = getCursorASTUnit(C);
3513 Preprocessor &PP = ASTU->getPreprocessor();
3514 if (const MacroInfo *MI = PP.getMacroInfo(II))
3515 return MI->isBuiltinMacro();
3516 return false;
3517}
3518
3519unsigned clang_Cursor_isFunctionInlined(CXCursor C) {
3520 const Decl *D = getCursorDecl(C);
3521 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
3522 if (!FD) {
3523 return false;
3524 }
3525 return FD->isInlined();
3526}
3527
3528static StringLiteral* getCFSTR_value(CallExpr *callExpr) {
3529 if (callExpr->getNumArgs() != 1) {
3530 return nullptr;
3531 }
3532
3533 StringLiteral *S = nullptr;
3534 auto *arg = callExpr->getArg(0);
3535 if (arg->getStmtClass() == Stmt::ImplicitCastExprClass) {
3536 ImplicitCastExpr *I = static_cast<ImplicitCastExpr *>(arg);
3537 auto *subExpr = I->getSubExprAsWritten();
3538
3539 if(subExpr->getStmtClass() != Stmt::StringLiteralClass){
3540 return nullptr;
3541 }
3542
3543 S = static_cast<StringLiteral *>(I->getSubExprAsWritten());
3544 } else if (arg->getStmtClass() == Stmt::StringLiteralClass) {
3545 S = static_cast<StringLiteral *>(callExpr->getArg(0));
3546 } else {
3547 return nullptr;
3548 }
3549 return S;
3550}
3551
David Blaikie59272572016-04-13 18:23:33 +00003552struct ExprEvalResult {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003553 CXEvalResultKind EvalType;
3554 union {
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003555 unsigned long long unsignedVal;
3556 long long intVal;
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003557 double floatVal;
3558 char *stringVal;
3559 } EvalData;
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003560 bool IsUnsignedInt;
David Blaikie59272572016-04-13 18:23:33 +00003561 ~ExprEvalResult() {
3562 if (EvalType != CXEval_UnExposed && EvalType != CXEval_Float &&
3563 EvalType != CXEval_Int) {
3564 delete EvalData.stringVal;
3565 }
3566 }
3567};
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003568
3569void clang_EvalResult_dispose(CXEvalResult E) {
David Blaikie59272572016-04-13 18:23:33 +00003570 delete static_cast<ExprEvalResult *>(E);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003571}
3572
3573CXEvalResultKind clang_EvalResult_getKind(CXEvalResult E) {
3574 if (!E) {
3575 return CXEval_UnExposed;
3576 }
3577 return ((ExprEvalResult *)E)->EvalType;
3578}
3579
3580int clang_EvalResult_getAsInt(CXEvalResult E) {
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003581 return clang_EvalResult_getAsLongLong(E);
3582}
3583
3584long long clang_EvalResult_getAsLongLong(CXEvalResult E) {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003585 if (!E) {
3586 return 0;
3587 }
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003588 ExprEvalResult *Result = (ExprEvalResult*)E;
3589 if (Result->IsUnsignedInt)
3590 return Result->EvalData.unsignedVal;
3591 return Result->EvalData.intVal;
3592}
3593
3594unsigned clang_EvalResult_isUnsignedInt(CXEvalResult E) {
3595 return ((ExprEvalResult *)E)->IsUnsignedInt;
3596}
3597
3598unsigned long long clang_EvalResult_getAsUnsigned(CXEvalResult E) {
3599 if (!E) {
3600 return 0;
3601 }
3602
3603 ExprEvalResult *Result = (ExprEvalResult*)E;
3604 if (Result->IsUnsignedInt)
3605 return Result->EvalData.unsignedVal;
3606 return Result->EvalData.intVal;
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003607}
3608
3609double clang_EvalResult_getAsDouble(CXEvalResult E) {
3610 if (!E) {
3611 return 0;
3612 }
3613 return ((ExprEvalResult *)E)->EvalData.floatVal;
3614}
3615
3616const char* clang_EvalResult_getAsStr(CXEvalResult E) {
3617 if (!E) {
3618 return nullptr;
3619 }
3620 return ((ExprEvalResult *)E)->EvalData.stringVal;
3621}
3622
3623static const ExprEvalResult* evaluateExpr(Expr *expr, CXCursor C) {
3624 Expr::EvalResult ER;
3625 ASTContext &ctx = getCursorContext(C);
David Blaikiebbc00882016-04-13 18:36:19 +00003626 if (!expr)
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003627 return nullptr;
David Blaikiebbc00882016-04-13 18:36:19 +00003628
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003629 expr = expr->IgnoreParens();
David Blaikiebbc00882016-04-13 18:36:19 +00003630 if (!expr->EvaluateAsRValue(ER, ctx))
3631 return nullptr;
3632
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003633 QualType rettype;
3634 CallExpr *callExpr;
David Blaikie59272572016-04-13 18:23:33 +00003635 auto result = llvm::make_unique<ExprEvalResult>();
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003636 result->EvalType = CXEval_UnExposed;
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003637 result->IsUnsignedInt = false;
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003638
David Blaikiebbc00882016-04-13 18:36:19 +00003639 if (ER.Val.isInt()) {
3640 result->EvalType = CXEval_Int;
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003641
3642 auto& val = ER.Val.getInt();
3643 if (val.isUnsigned()) {
3644 result->IsUnsignedInt = true;
3645 result->EvalData.unsignedVal = val.getZExtValue();
3646 } else {
3647 result->EvalData.intVal = val.getExtValue();
3648 }
3649
David Blaikiebbc00882016-04-13 18:36:19 +00003650 return result.release();
3651 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003652
David Blaikiebbc00882016-04-13 18:36:19 +00003653 if (ER.Val.isFloat()) {
3654 llvm::SmallVector<char, 100> Buffer;
3655 ER.Val.getFloat().toString(Buffer);
3656 std::string floatStr(Buffer.data(), Buffer.size());
3657 result->EvalType = CXEval_Float;
3658 bool ignored;
3659 llvm::APFloat apFloat = ER.Val.getFloat();
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003660 apFloat.convert(llvm::APFloat::IEEEdouble(),
David Blaikiebbc00882016-04-13 18:36:19 +00003661 llvm::APFloat::rmNearestTiesToEven, &ignored);
3662 result->EvalData.floatVal = apFloat.convertToDouble();
3663 return result.release();
3664 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003665
David Blaikiebbc00882016-04-13 18:36:19 +00003666 if (expr->getStmtClass() == Stmt::ImplicitCastExprClass) {
3667 const ImplicitCastExpr *I = dyn_cast<ImplicitCastExpr>(expr);
3668 auto *subExpr = I->getSubExprAsWritten();
3669 if (subExpr->getStmtClass() == Stmt::StringLiteralClass ||
3670 subExpr->getStmtClass() == Stmt::ObjCStringLiteralClass) {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003671 const StringLiteral *StrE = nullptr;
3672 const ObjCStringLiteral *ObjCExpr;
David Blaikiebbc00882016-04-13 18:36:19 +00003673 ObjCExpr = dyn_cast<ObjCStringLiteral>(subExpr);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003674
3675 if (ObjCExpr) {
3676 StrE = ObjCExpr->getString();
3677 result->EvalType = CXEval_ObjCStrLiteral;
3678 } else {
David Blaikiebbc00882016-04-13 18:36:19 +00003679 StrE = cast<StringLiteral>(I->getSubExprAsWritten());
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003680 result->EvalType = CXEval_StrLiteral;
3681 }
3682
3683 std::string strRef(StrE->getString().str());
David Blaikie59272572016-04-13 18:23:33 +00003684 result->EvalData.stringVal = new char[strRef.size() + 1];
David Blaikiebbc00882016-04-13 18:36:19 +00003685 strncpy((char *)result->EvalData.stringVal, strRef.c_str(),
3686 strRef.size());
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003687 result->EvalData.stringVal[strRef.size()] = '\0';
David Blaikie59272572016-04-13 18:23:33 +00003688 return result.release();
David Blaikiebbc00882016-04-13 18:36:19 +00003689 }
3690 } else if (expr->getStmtClass() == Stmt::ObjCStringLiteralClass ||
3691 expr->getStmtClass() == Stmt::StringLiteralClass) {
3692 const StringLiteral *StrE = nullptr;
3693 const ObjCStringLiteral *ObjCExpr;
3694 ObjCExpr = dyn_cast<ObjCStringLiteral>(expr);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003695
David Blaikiebbc00882016-04-13 18:36:19 +00003696 if (ObjCExpr) {
3697 StrE = ObjCExpr->getString();
3698 result->EvalType = CXEval_ObjCStrLiteral;
3699 } else {
3700 StrE = cast<StringLiteral>(expr);
3701 result->EvalType = CXEval_StrLiteral;
3702 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003703
David Blaikiebbc00882016-04-13 18:36:19 +00003704 std::string strRef(StrE->getString().str());
3705 result->EvalData.stringVal = new char[strRef.size() + 1];
3706 strncpy((char *)result->EvalData.stringVal, strRef.c_str(), strRef.size());
3707 result->EvalData.stringVal[strRef.size()] = '\0';
3708 return result.release();
3709 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003710
David Blaikiebbc00882016-04-13 18:36:19 +00003711 if (expr->getStmtClass() == Stmt::CStyleCastExprClass) {
3712 CStyleCastExpr *CC = static_cast<CStyleCastExpr *>(expr);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003713
David Blaikiebbc00882016-04-13 18:36:19 +00003714 rettype = CC->getType();
3715 if (rettype.getAsString() == "CFStringRef" &&
3716 CC->getSubExpr()->getStmtClass() == Stmt::CallExprClass) {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003717
David Blaikiebbc00882016-04-13 18:36:19 +00003718 callExpr = static_cast<CallExpr *>(CC->getSubExpr());
3719 StringLiteral *S = getCFSTR_value(callExpr);
3720 if (S) {
3721 std::string strLiteral(S->getString().str());
3722 result->EvalType = CXEval_CFStr;
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003723
David Blaikiebbc00882016-04-13 18:36:19 +00003724 result->EvalData.stringVal = new char[strLiteral.size() + 1];
3725 strncpy((char *)result->EvalData.stringVal, strLiteral.c_str(),
3726 strLiteral.size());
3727 result->EvalData.stringVal[strLiteral.size()] = '\0';
David Blaikie59272572016-04-13 18:23:33 +00003728 return result.release();
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003729 }
3730 }
3731
David Blaikiebbc00882016-04-13 18:36:19 +00003732 } else if (expr->getStmtClass() == Stmt::CallExprClass) {
3733 callExpr = static_cast<CallExpr *>(expr);
3734 rettype = callExpr->getCallReturnType(ctx);
3735
3736 if (rettype->isVectorType() || callExpr->getNumArgs() > 1)
3737 return nullptr;
3738
3739 if (rettype->isIntegralType(ctx) || rettype->isRealFloatingType()) {
3740 if (callExpr->getNumArgs() == 1 &&
3741 !callExpr->getArg(0)->getType()->isIntegralType(ctx))
3742 return nullptr;
3743 } else if (rettype.getAsString() == "CFStringRef") {
3744
3745 StringLiteral *S = getCFSTR_value(callExpr);
3746 if (S) {
3747 std::string strLiteral(S->getString().str());
3748 result->EvalType = CXEval_CFStr;
3749 result->EvalData.stringVal = new char[strLiteral.size() + 1];
3750 strncpy((char *)result->EvalData.stringVal, strLiteral.c_str(),
3751 strLiteral.size());
3752 result->EvalData.stringVal[strLiteral.size()] = '\0';
3753 return result.release();
3754 }
3755 }
3756 } else if (expr->getStmtClass() == Stmt::DeclRefExprClass) {
3757 DeclRefExpr *D = static_cast<DeclRefExpr *>(expr);
3758 ValueDecl *V = D->getDecl();
3759 if (V->getKind() == Decl::Function) {
3760 std::string strName = V->getNameAsString();
3761 result->EvalType = CXEval_Other;
3762 result->EvalData.stringVal = new char[strName.size() + 1];
3763 strncpy(result->EvalData.stringVal, strName.c_str(), strName.size());
3764 result->EvalData.stringVal[strName.size()] = '\0';
3765 return result.release();
3766 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003767 }
3768
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003769 return nullptr;
3770}
3771
3772CXEvalResult clang_Cursor_Evaluate(CXCursor C) {
3773 const Decl *D = getCursorDecl(C);
3774 if (D) {
3775 const Expr *expr = nullptr;
3776 if (auto *Var = dyn_cast<VarDecl>(D)) {
3777 expr = Var->getInit();
3778 } else if (auto *Field = dyn_cast<FieldDecl>(D)) {
3779 expr = Field->getInClassInitializer();
3780 }
3781 if (expr)
Aaron Ballman01dc1572016-01-20 15:25:30 +00003782 return const_cast<CXEvalResult>(reinterpret_cast<const void *>(
3783 evaluateExpr(const_cast<Expr *>(expr), C)));
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003784 return nullptr;
3785 }
3786
3787 const CompoundStmt *compoundStmt = dyn_cast_or_null<CompoundStmt>(getCursorStmt(C));
3788 if (compoundStmt) {
3789 Expr *expr = nullptr;
3790 for (auto *bodyIterator : compoundStmt->body()) {
3791 if ((expr = dyn_cast<Expr>(bodyIterator))) {
3792 break;
3793 }
3794 }
3795 if (expr)
Aaron Ballman01dc1572016-01-20 15:25:30 +00003796 return const_cast<CXEvalResult>(
3797 reinterpret_cast<const void *>(evaluateExpr(expr, C)));
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003798 }
3799 return nullptr;
3800}
3801
3802unsigned clang_Cursor_hasAttrs(CXCursor C) {
3803 const Decl *D = getCursorDecl(C);
3804 if (!D) {
3805 return 0;
3806 }
3807
3808 if (D->hasAttrs()) {
3809 return 1;
3810 }
3811
3812 return 0;
3813}
Guy Benyei11169dd2012-12-18 14:30:41 +00003814unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
3815 return CXSaveTranslationUnit_None;
3816}
3817
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003818static CXSaveError clang_saveTranslationUnit_Impl(CXTranslationUnit TU,
3819 const char *FileName,
3820 unsigned options) {
3821 CIndexer *CXXIdx = TU->CIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00003822 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
3823 setThreadBackgroundPriority();
3824
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003825 bool hadError = cxtu::getASTUnit(TU)->Save(FileName);
3826 return hadError ? CXSaveError_Unknown : CXSaveError_None;
Guy Benyei11169dd2012-12-18 14:30:41 +00003827}
3828
3829int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
3830 unsigned options) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00003831 LOG_FUNC_SECTION {
3832 *Log << TU << ' ' << FileName;
3833 }
3834
Dmitri Gribenko852d6222014-02-11 15:02:48 +00003835 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00003836 LOG_BAD_TU(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00003837 return CXSaveError_InvalidTU;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00003838 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003839
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00003840 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00003841 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3842 if (!CXXUnit->hasSema())
3843 return CXSaveError_InvalidTU;
3844
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003845 CXSaveError result;
3846 auto SaveTranslationUnitImpl = [=, &result]() {
3847 result = clang_saveTranslationUnit_Impl(TU, FileName, options);
3848 };
Guy Benyei11169dd2012-12-18 14:30:41 +00003849
3850 if (!CXXUnit->getDiagnostics().hasUnrecoverableErrorOccurred() ||
3851 getenv("LIBCLANG_NOTHREADS")) {
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003852 SaveTranslationUnitImpl();
Guy Benyei11169dd2012-12-18 14:30:41 +00003853
3854 if (getenv("LIBCLANG_RESOURCE_USAGE"))
3855 PrintLibclangResourceUsage(TU);
3856
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003857 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003858 }
3859
3860 // We have an AST that has invalid nodes due to compiler errors.
3861 // Use a crash recovery thread for protection.
3862
3863 llvm::CrashRecoveryContext CRC;
3864
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003865 if (!RunSafely(CRC, SaveTranslationUnitImpl)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003866 fprintf(stderr, "libclang: crash detected during AST saving: {\n");
3867 fprintf(stderr, " 'filename' : '%s'\n", FileName);
3868 fprintf(stderr, " 'options' : %d,\n", options);
3869 fprintf(stderr, "}\n");
3870
3871 return CXSaveError_Unknown;
3872
3873 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
3874 PrintLibclangResourceUsage(TU);
3875 }
3876
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003877 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003878}
3879
3880void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
3881 if (CTUnit) {
3882 // If the translation unit has been marked as unsafe to free, just discard
3883 // it.
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003884 ASTUnit *Unit = cxtu::getASTUnit(CTUnit);
3885 if (Unit && Unit->isUnsafeToFree())
Guy Benyei11169dd2012-12-18 14:30:41 +00003886 return;
3887
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00003888 delete cxtu::getASTUnit(CTUnit);
Dmitri Gribenkob95b3f12013-01-26 22:44:19 +00003889 delete CTUnit->StringPool;
Guy Benyei11169dd2012-12-18 14:30:41 +00003890 delete static_cast<CXDiagnosticSetImpl *>(CTUnit->Diagnostics);
3891 disposeOverridenCXCursorsPool(CTUnit->OverridenCursorsPool);
Dmitri Gribenko9e605112013-11-13 22:16:51 +00003892 delete CTUnit->CommentToXML;
Guy Benyei11169dd2012-12-18 14:30:41 +00003893 delete CTUnit;
3894 }
3895}
3896
3897unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
3898 return CXReparse_None;
3899}
3900
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003901static CXErrorCode
3902clang_reparseTranslationUnit_Impl(CXTranslationUnit TU,
3903 ArrayRef<CXUnsavedFile> unsaved_files,
3904 unsigned options) {
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003905 // Check arguments.
Dmitri Gribenko852d6222014-02-11 15:02:48 +00003906 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00003907 LOG_BAD_TU(TU);
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003908 return CXError_InvalidArguments;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003909 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003910
3911 // Reset the associated diagnostics.
3912 delete static_cast<CXDiagnosticSetImpl*>(TU->Diagnostics);
Craig Topper69186e72014-06-08 08:38:04 +00003913 TU->Diagnostics = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00003914
Dmitri Gribenko183436e2013-01-26 21:49:50 +00003915 CIndexer *CXXIdx = TU->CIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00003916 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing))
3917 setThreadBackgroundPriority();
3918
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00003919 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00003920 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ahmed Charlesb8984322014-03-07 20:03:18 +00003921
3922 std::unique_ptr<std::vector<ASTUnit::RemappedFile>> RemappedFiles(
3923 new std::vector<ASTUnit::RemappedFile>());
3924
Guy Benyei11169dd2012-12-18 14:30:41 +00003925 // Recover resources if we crash before exiting this function.
3926 llvm::CrashRecoveryContextCleanupRegistrar<
3927 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
Alp Toker9d85b182014-07-07 01:23:14 +00003928
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003929 for (auto &UF : unsaved_files) {
Rafael Espindolad87f8d72014-08-27 20:03:29 +00003930 std::unique_ptr<llvm::MemoryBuffer> MB =
Alp Toker9d85b182014-07-07 01:23:14 +00003931 llvm::MemoryBuffer::getMemBufferCopy(getContents(UF), UF.Filename);
Rafael Espindolad87f8d72014-08-27 20:03:29 +00003932 RemappedFiles->push_back(std::make_pair(UF.Filename, MB.release()));
Guy Benyei11169dd2012-12-18 14:30:41 +00003933 }
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003934
Adrian Prantlbb165fb2015-06-20 18:53:08 +00003935 if (!CXXUnit->Reparse(CXXIdx->getPCHContainerOperations(),
3936 *RemappedFiles.get()))
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003937 return CXError_Success;
3938 if (isASTReadError(CXXUnit))
3939 return CXError_ASTReadError;
3940 return CXError_Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003941}
3942
3943int clang_reparseTranslationUnit(CXTranslationUnit TU,
3944 unsigned num_unsaved_files,
3945 struct CXUnsavedFile *unsaved_files,
3946 unsigned options) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00003947 LOG_FUNC_SECTION {
3948 *Log << TU;
3949 }
3950
Alp Toker9d85b182014-07-07 01:23:14 +00003951 if (num_unsaved_files && !unsaved_files)
3952 return CXError_InvalidArguments;
3953
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003954 CXErrorCode result;
3955 auto ReparseTranslationUnitImpl = [=, &result]() {
3956 result = clang_reparseTranslationUnit_Impl(
3957 TU, llvm::makeArrayRef(unsaved_files, num_unsaved_files), options);
3958 };
Guy Benyei11169dd2012-12-18 14:30:41 +00003959
3960 if (getenv("LIBCLANG_NOTHREADS")) {
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003961 ReparseTranslationUnitImpl();
Alp Toker5c532982014-07-07 22:42:03 +00003962 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003963 }
3964
3965 llvm::CrashRecoveryContext CRC;
3966
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003967 if (!RunSafely(CRC, ReparseTranslationUnitImpl)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003968 fprintf(stderr, "libclang: crash detected during reparsing\n");
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00003969 cxtu::getASTUnit(TU)->setUnsafeToFree(true);
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003970 return CXError_Crashed;
Guy Benyei11169dd2012-12-18 14:30:41 +00003971 } else if (getenv("LIBCLANG_RESOURCE_USAGE"))
3972 PrintLibclangResourceUsage(TU);
3973
Alp Toker5c532982014-07-07 22:42:03 +00003974 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003975}
3976
3977
3978CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00003979 if (isNotUsableTU(CTUnit)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00003980 LOG_BAD_TU(CTUnit);
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00003981 return cxstring::createEmpty();
Dmitri Gribenko256454f2014-02-11 14:34:14 +00003982 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003983
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00003984 ASTUnit *CXXUnit = cxtu::getASTUnit(CTUnit);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00003985 return cxstring::createDup(CXXUnit->getOriginalSourceFileName());
Guy Benyei11169dd2012-12-18 14:30:41 +00003986}
3987
3988CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00003989 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00003990 LOG_BAD_TU(TU);
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00003991 return clang_getNullCursor();
Dmitri Gribenko256454f2014-02-11 14:34:14 +00003992 }
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00003993
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00003994 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00003995 return MakeCXCursor(CXXUnit->getASTContext().getTranslationUnitDecl(), TU);
3996}
3997
Guy Benyei11169dd2012-12-18 14:30:41 +00003998//===----------------------------------------------------------------------===//
3999// CXFile Operations.
4000//===----------------------------------------------------------------------===//
4001
Guy Benyei11169dd2012-12-18 14:30:41 +00004002CXString clang_getFileName(CXFile SFile) {
4003 if (!SFile)
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00004004 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00004005
4006 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004007 return cxstring::createRef(FEnt->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004008}
4009
4010time_t clang_getFileTime(CXFile SFile) {
4011 if (!SFile)
4012 return 0;
4013
4014 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
4015 return FEnt->getModificationTime();
4016}
4017
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004018CXFile clang_getFile(CXTranslationUnit TU, const char *file_name) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004019 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004020 LOG_BAD_TU(TU);
Craig Topper69186e72014-06-08 08:38:04 +00004021 return nullptr;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004022 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004023
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004024 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004025
4026 FileManager &FMgr = CXXUnit->getFileManager();
4027 return const_cast<FileEntry *>(FMgr.getFile(file_name));
4028}
4029
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004030unsigned clang_isFileMultipleIncludeGuarded(CXTranslationUnit TU,
4031 CXFile file) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004032 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004033 LOG_BAD_TU(TU);
4034 return 0;
4035 }
4036
4037 if (!file)
Guy Benyei11169dd2012-12-18 14:30:41 +00004038 return 0;
4039
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004040 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004041 FileEntry *FEnt = static_cast<FileEntry *>(file);
4042 return CXXUnit->getPreprocessor().getHeaderSearchInfo()
4043 .isFileMultipleIncludeGuarded(FEnt);
4044}
4045
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00004046int clang_getFileUniqueID(CXFile file, CXFileUniqueID *outID) {
4047 if (!file || !outID)
4048 return 1;
4049
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00004050 FileEntry *FEnt = static_cast<FileEntry *>(file);
Rafael Espindolaf8f91b82013-08-01 21:42:11 +00004051 const llvm::sys::fs::UniqueID &ID = FEnt->getUniqueID();
4052 outID->data[0] = ID.getDevice();
4053 outID->data[1] = ID.getFile();
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00004054 outID->data[2] = FEnt->getModificationTime();
4055 return 0;
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00004056}
4057
Argyrios Kyrtzidisac3997e2014-08-16 00:26:19 +00004058int clang_File_isEqual(CXFile file1, CXFile file2) {
4059 if (file1 == file2)
4060 return true;
4061
4062 if (!file1 || !file2)
4063 return false;
4064
4065 FileEntry *FEnt1 = static_cast<FileEntry *>(file1);
4066 FileEntry *FEnt2 = static_cast<FileEntry *>(file2);
4067 return FEnt1->getUniqueID() == FEnt2->getUniqueID();
4068}
4069
Guy Benyei11169dd2012-12-18 14:30:41 +00004070//===----------------------------------------------------------------------===//
4071// CXCursor Operations.
4072//===----------------------------------------------------------------------===//
4073
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004074static const Decl *getDeclFromExpr(const Stmt *E) {
4075 if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004076 return getDeclFromExpr(CE->getSubExpr());
4077
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004078 if (const DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004079 return RefExpr->getDecl();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004080 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004081 return ME->getMemberDecl();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004082 if (const ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004083 return RE->getDecl();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004084 if (const ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004085 if (PRE->isExplicitProperty())
4086 return PRE->getExplicitProperty();
4087 // It could be messaging both getter and setter as in:
4088 // ++myobj.myprop;
4089 // in which case prefer to associate the setter since it is less obvious
4090 // from inspecting the source that the setter is going to get called.
4091 if (PRE->isMessagingSetter())
4092 return PRE->getImplicitPropertySetter();
4093 return PRE->getImplicitPropertyGetter();
4094 }
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004095 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004096 return getDeclFromExpr(POE->getSyntacticForm());
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004097 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004098 if (Expr *Src = OVE->getSourceExpr())
4099 return getDeclFromExpr(Src);
4100
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004101 if (const CallExpr *CE = dyn_cast<CallExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004102 return getDeclFromExpr(CE->getCallee());
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004103 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004104 if (!CE->isElidable())
4105 return CE->getConstructor();
Richard Smith5179eb72016-06-28 19:03:57 +00004106 if (const CXXInheritedCtorInitExpr *CE =
4107 dyn_cast<CXXInheritedCtorInitExpr>(E))
4108 return CE->getConstructor();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004109 if (const ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004110 return OME->getMethodDecl();
4111
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004112 if (const ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004113 return PE->getProtocol();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004114 if (const SubstNonTypeTemplateParmPackExpr *NTTP
Guy Benyei11169dd2012-12-18 14:30:41 +00004115 = dyn_cast<SubstNonTypeTemplateParmPackExpr>(E))
4116 return NTTP->getParameterPack();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004117 if (const SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004118 if (isa<NonTypeTemplateParmDecl>(SizeOfPack->getPack()) ||
4119 isa<ParmVarDecl>(SizeOfPack->getPack()))
4120 return SizeOfPack->getPack();
Craig Topper69186e72014-06-08 08:38:04 +00004121
4122 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004123}
4124
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004125static SourceLocation getLocationFromExpr(const Expr *E) {
4126 if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004127 return getLocationFromExpr(CE->getSubExpr());
4128
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004129 if (const ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004130 return /*FIXME:*/Msg->getLeftLoc();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004131 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004132 return DRE->getLocation();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004133 if (const MemberExpr *Member = dyn_cast<MemberExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004134 return Member->getMemberLoc();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004135 if (const ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004136 return Ivar->getLocation();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004137 if (const SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004138 return SizeOfPack->getPackLoc();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004139 if (const ObjCPropertyRefExpr *PropRef = dyn_cast<ObjCPropertyRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004140 return PropRef->getLocation();
4141
4142 return E->getLocStart();
4143}
4144
NAKAMURA Takumia01f4c32016-12-19 16:50:43 +00004145extern "C" {
4146
Guy Benyei11169dd2012-12-18 14:30:41 +00004147unsigned clang_visitChildren(CXCursor parent,
4148 CXCursorVisitor visitor,
4149 CXClientData client_data) {
4150 CursorVisitor CursorVis(getCursorTU(parent), visitor, client_data,
4151 /*VisitPreprocessorLast=*/false);
4152 return CursorVis.VisitChildren(parent);
4153}
4154
4155#ifndef __has_feature
4156#define __has_feature(x) 0
4157#endif
4158#if __has_feature(blocks)
4159typedef enum CXChildVisitResult
4160 (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
4161
4162static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
4163 CXClientData client_data) {
4164 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
4165 return block(cursor, parent);
4166}
4167#else
4168// If we are compiled with a compiler that doesn't have native blocks support,
4169// define and call the block manually, so the
4170typedef struct _CXChildVisitResult
4171{
4172 void *isa;
4173 int flags;
4174 int reserved;
4175 enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor,
4176 CXCursor);
4177} *CXCursorVisitorBlock;
4178
4179static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
4180 CXClientData client_data) {
4181 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
4182 return block->invoke(block, cursor, parent);
4183}
4184#endif
4185
4186
4187unsigned clang_visitChildrenWithBlock(CXCursor parent,
4188 CXCursorVisitorBlock block) {
4189 return clang_visitChildren(parent, visitWithBlock, block);
4190}
4191
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004192static CXString getDeclSpelling(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004193 if (!D)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004194 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004195
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004196 const NamedDecl *ND = dyn_cast<NamedDecl>(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00004197 if (!ND) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004198 if (const ObjCPropertyImplDecl *PropImpl =
4199 dyn_cast<ObjCPropertyImplDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00004200 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004201 return cxstring::createDup(Property->getIdentifier()->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004202
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004203 if (const ImportDecl *ImportD = dyn_cast<ImportDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00004204 if (Module *Mod = ImportD->getImportedModule())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004205 return cxstring::createDup(Mod->getFullModuleName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004206
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004207 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004208 }
4209
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004210 if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004211 return cxstring::createDup(OMD->getSelector().getAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004212
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004213 if (const ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
Guy Benyei11169dd2012-12-18 14:30:41 +00004214 // No, this isn't the same as the code below. getIdentifier() is non-virtual
4215 // and returns different names. NamedDecl returns the class name and
4216 // ObjCCategoryImplDecl returns the category name.
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004217 return cxstring::createRef(CIMP->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004218
4219 if (isa<UsingDirectiveDecl>(D))
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004220 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004221
4222 SmallString<1024> S;
4223 llvm::raw_svector_ostream os(S);
4224 ND->printName(os);
4225
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004226 return cxstring::createDup(os.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00004227}
4228
4229CXString clang_getCursorSpelling(CXCursor C) {
4230 if (clang_isTranslationUnit(C.kind))
Dmitri Gribenko2c173b42013-01-11 19:28:44 +00004231 return clang_getTranslationUnitSpelling(getCursorTU(C));
Guy Benyei11169dd2012-12-18 14:30:41 +00004232
4233 if (clang_isReference(C.kind)) {
4234 switch (C.kind) {
4235 case CXCursor_ObjCSuperClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004236 const ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004237 return cxstring::createRef(Super->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004238 }
4239 case CXCursor_ObjCClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004240 const ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004241 return cxstring::createRef(Class->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004242 }
4243 case CXCursor_ObjCProtocolRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004244 const ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004245 assert(OID && "getCursorSpelling(): Missing protocol decl");
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004246 return cxstring::createRef(OID->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004247 }
4248 case CXCursor_CXXBaseSpecifier: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004249 const CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004250 return cxstring::createDup(B->getType().getAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004251 }
4252 case CXCursor_TypeRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004253 const TypeDecl *Type = getCursorTypeRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004254 assert(Type && "Missing type decl");
4255
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004256 return cxstring::createDup(getCursorContext(C).getTypeDeclType(Type).
Guy Benyei11169dd2012-12-18 14:30:41 +00004257 getAsString());
4258 }
4259 case CXCursor_TemplateRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004260 const TemplateDecl *Template = getCursorTemplateRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004261 assert(Template && "Missing template decl");
4262
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004263 return cxstring::createDup(Template->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004264 }
4265
4266 case CXCursor_NamespaceRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004267 const NamedDecl *NS = getCursorNamespaceRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004268 assert(NS && "Missing namespace decl");
4269
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004270 return cxstring::createDup(NS->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004271 }
4272
4273 case CXCursor_MemberRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004274 const FieldDecl *Field = getCursorMemberRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004275 assert(Field && "Missing member decl");
4276
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004277 return cxstring::createDup(Field->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004278 }
4279
4280 case CXCursor_LabelRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004281 const LabelStmt *Label = getCursorLabelRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004282 assert(Label && "Missing label");
4283
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004284 return cxstring::createRef(Label->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004285 }
4286
4287 case CXCursor_OverloadedDeclRef: {
4288 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004289 if (const Decl *D = Storage.dyn_cast<const Decl *>()) {
4290 if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004291 return cxstring::createDup(ND->getNameAsString());
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004292 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004293 }
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004294 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004295 return cxstring::createDup(E->getName().getAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004296 OverloadedTemplateStorage *Ovl
4297 = Storage.get<OverloadedTemplateStorage*>();
4298 if (Ovl->size() == 0)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004299 return cxstring::createEmpty();
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004300 return cxstring::createDup((*Ovl->begin())->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004301 }
4302
4303 case CXCursor_VariableRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004304 const VarDecl *Var = getCursorVariableRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004305 assert(Var && "Missing variable decl");
4306
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004307 return cxstring::createDup(Var->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004308 }
4309
4310 default:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004311 return cxstring::createRef("<not implemented>");
Guy Benyei11169dd2012-12-18 14:30:41 +00004312 }
4313 }
4314
4315 if (clang_isExpression(C.kind)) {
Argyrios Kyrtzidis3227d862014-03-03 19:40:52 +00004316 const Expr *E = getCursorExpr(C);
4317
4318 if (C.kind == CXCursor_ObjCStringLiteral ||
4319 C.kind == CXCursor_StringLiteral) {
4320 const StringLiteral *SLit;
4321 if (const ObjCStringLiteral *OSL = dyn_cast<ObjCStringLiteral>(E)) {
4322 SLit = OSL->getString();
4323 } else {
4324 SLit = cast<StringLiteral>(E);
4325 }
4326 SmallString<256> Buf;
4327 llvm::raw_svector_ostream OS(Buf);
4328 SLit->outputString(OS);
4329 return cxstring::createDup(OS.str());
4330 }
4331
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004332 const Decl *D = getDeclFromExpr(getCursorExpr(C));
Guy Benyei11169dd2012-12-18 14:30:41 +00004333 if (D)
4334 return getDeclSpelling(D);
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004335 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004336 }
4337
4338 if (clang_isStatement(C.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004339 const Stmt *S = getCursorStmt(C);
4340 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004341 return cxstring::createRef(Label->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004342
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004343 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004344 }
4345
4346 if (C.kind == CXCursor_MacroExpansion)
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004347 return cxstring::createRef(getCursorMacroExpansion(C).getName()
Guy Benyei11169dd2012-12-18 14:30:41 +00004348 ->getNameStart());
4349
4350 if (C.kind == CXCursor_MacroDefinition)
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004351 return cxstring::createRef(getCursorMacroDefinition(C)->getName()
Guy Benyei11169dd2012-12-18 14:30:41 +00004352 ->getNameStart());
4353
4354 if (C.kind == CXCursor_InclusionDirective)
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004355 return cxstring::createDup(getCursorInclusionDirective(C)->getFileName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004356
4357 if (clang_isDeclaration(C.kind))
4358 return getDeclSpelling(getCursorDecl(C));
4359
4360 if (C.kind == CXCursor_AnnotateAttr) {
Dmitri Gribenkoe4baea62013-01-26 18:08:08 +00004361 const AnnotateAttr *AA = cast<AnnotateAttr>(cxcursor::getCursorAttr(C));
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004362 return cxstring::createDup(AA->getAnnotation());
Guy Benyei11169dd2012-12-18 14:30:41 +00004363 }
4364
4365 if (C.kind == CXCursor_AsmLabelAttr) {
Dmitri Gribenkoe4baea62013-01-26 18:08:08 +00004366 const AsmLabelAttr *AA = cast<AsmLabelAttr>(cxcursor::getCursorAttr(C));
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004367 return cxstring::createDup(AA->getLabel());
Guy Benyei11169dd2012-12-18 14:30:41 +00004368 }
4369
Argyrios Kyrtzidis16834f12013-09-25 00:14:38 +00004370 if (C.kind == CXCursor_PackedAttr) {
4371 return cxstring::createRef("packed");
4372 }
4373
Saleem Abdulrasool79c69712015-09-05 18:53:43 +00004374 if (C.kind == CXCursor_VisibilityAttr) {
4375 const VisibilityAttr *AA = cast<VisibilityAttr>(cxcursor::getCursorAttr(C));
4376 switch (AA->getVisibility()) {
4377 case VisibilityAttr::VisibilityType::Default:
4378 return cxstring::createRef("default");
4379 case VisibilityAttr::VisibilityType::Hidden:
4380 return cxstring::createRef("hidden");
4381 case VisibilityAttr::VisibilityType::Protected:
4382 return cxstring::createRef("protected");
4383 }
4384 llvm_unreachable("unknown visibility type");
4385 }
4386
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004387 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004388}
4389
4390CXSourceRange clang_Cursor_getSpellingNameRange(CXCursor C,
4391 unsigned pieceIndex,
4392 unsigned options) {
4393 if (clang_Cursor_isNull(C))
4394 return clang_getNullRange();
4395
4396 ASTContext &Ctx = getCursorContext(C);
4397
4398 if (clang_isStatement(C.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004399 const Stmt *S = getCursorStmt(C);
4400 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004401 if (pieceIndex > 0)
4402 return clang_getNullRange();
4403 return cxloc::translateSourceRange(Ctx, Label->getIdentLoc());
4404 }
4405
4406 return clang_getNullRange();
4407 }
4408
4409 if (C.kind == CXCursor_ObjCMessageExpr) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004410 if (const ObjCMessageExpr *
Guy Benyei11169dd2012-12-18 14:30:41 +00004411 ME = dyn_cast_or_null<ObjCMessageExpr>(getCursorExpr(C))) {
4412 if (pieceIndex >= ME->getNumSelectorLocs())
4413 return clang_getNullRange();
4414 return cxloc::translateSourceRange(Ctx, ME->getSelectorLoc(pieceIndex));
4415 }
4416 }
4417
4418 if (C.kind == CXCursor_ObjCInstanceMethodDecl ||
4419 C.kind == CXCursor_ObjCClassMethodDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004420 if (const ObjCMethodDecl *
Guy Benyei11169dd2012-12-18 14:30:41 +00004421 MD = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(C))) {
4422 if (pieceIndex >= MD->getNumSelectorLocs())
4423 return clang_getNullRange();
4424 return cxloc::translateSourceRange(Ctx, MD->getSelectorLoc(pieceIndex));
4425 }
4426 }
4427
4428 if (C.kind == CXCursor_ObjCCategoryDecl ||
4429 C.kind == CXCursor_ObjCCategoryImplDecl) {
4430 if (pieceIndex > 0)
4431 return clang_getNullRange();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004432 if (const ObjCCategoryDecl *
Guy Benyei11169dd2012-12-18 14:30:41 +00004433 CD = dyn_cast_or_null<ObjCCategoryDecl>(getCursorDecl(C)))
4434 return cxloc::translateSourceRange(Ctx, CD->getCategoryNameLoc());
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004435 if (const ObjCCategoryImplDecl *
Guy Benyei11169dd2012-12-18 14:30:41 +00004436 CID = dyn_cast_or_null<ObjCCategoryImplDecl>(getCursorDecl(C)))
4437 return cxloc::translateSourceRange(Ctx, CID->getCategoryNameLoc());
4438 }
4439
4440 if (C.kind == CXCursor_ModuleImportDecl) {
4441 if (pieceIndex > 0)
4442 return clang_getNullRange();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004443 if (const ImportDecl *ImportD =
4444 dyn_cast_or_null<ImportDecl>(getCursorDecl(C))) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004445 ArrayRef<SourceLocation> Locs = ImportD->getIdentifierLocs();
4446 if (!Locs.empty())
4447 return cxloc::translateSourceRange(Ctx,
4448 SourceRange(Locs.front(), Locs.back()));
4449 }
4450 return clang_getNullRange();
4451 }
4452
Argyrios Kyrtzidisa2a1e532014-08-26 20:23:26 +00004453 if (C.kind == CXCursor_CXXMethod || C.kind == CXCursor_Destructor ||
Kevin Funk4be5d672016-12-20 09:56:56 +00004454 C.kind == CXCursor_ConversionFunction ||
4455 C.kind == CXCursor_FunctionDecl) {
Argyrios Kyrtzidisa2a1e532014-08-26 20:23:26 +00004456 if (pieceIndex > 0)
4457 return clang_getNullRange();
4458 if (const FunctionDecl *FD =
4459 dyn_cast_or_null<FunctionDecl>(getCursorDecl(C))) {
4460 DeclarationNameInfo FunctionName = FD->getNameInfo();
4461 return cxloc::translateSourceRange(Ctx, FunctionName.getSourceRange());
4462 }
4463 return clang_getNullRange();
4464 }
4465
Guy Benyei11169dd2012-12-18 14:30:41 +00004466 // FIXME: A CXCursor_InclusionDirective should give the location of the
4467 // filename, but we don't keep track of this.
4468
4469 // FIXME: A CXCursor_AnnotateAttr should give the location of the annotation
4470 // but we don't keep track of this.
4471
4472 // FIXME: A CXCursor_AsmLabelAttr should give the location of the label
4473 // but we don't keep track of this.
4474
4475 // Default handling, give the location of the cursor.
4476
4477 if (pieceIndex > 0)
4478 return clang_getNullRange();
4479
4480 CXSourceLocation CXLoc = clang_getCursorLocation(C);
4481 SourceLocation Loc = cxloc::translateSourceLocation(CXLoc);
4482 return cxloc::translateSourceRange(Ctx, Loc);
4483}
4484
Eli Bendersky44a206f2014-07-31 18:04:56 +00004485CXString clang_Cursor_getMangling(CXCursor C) {
4486 if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
4487 return cxstring::createEmpty();
4488
Eli Bendersky44a206f2014-07-31 18:04:56 +00004489 // Mangling only works for functions and variables.
Eli Bendersky79759592014-08-01 15:01:10 +00004490 const Decl *D = getCursorDecl(C);
Eli Bendersky44a206f2014-07-31 18:04:56 +00004491 if (!D || !(isa<FunctionDecl>(D) || isa<VarDecl>(D)))
4492 return cxstring::createEmpty();
4493
Argyrios Kyrtzidisca741ce2016-02-14 22:30:14 +00004494 ASTContext &Ctx = D->getASTContext();
4495 index::CodegenNameGenerator CGNameGen(Ctx);
4496 return cxstring::createDup(CGNameGen.getName(D));
Eli Bendersky44a206f2014-07-31 18:04:56 +00004497}
4498
Saleem Abdulrasool60034432015-11-12 03:57:22 +00004499CXStringSet *clang_Cursor_getCXXManglings(CXCursor C) {
4500 if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
4501 return nullptr;
4502
4503 const Decl *D = getCursorDecl(C);
4504 if (!(isa<CXXRecordDecl>(D) || isa<CXXMethodDecl>(D)))
4505 return nullptr;
4506
Argyrios Kyrtzidisca741ce2016-02-14 22:30:14 +00004507 ASTContext &Ctx = D->getASTContext();
4508 index::CodegenNameGenerator CGNameGen(Ctx);
4509 std::vector<std::string> Manglings = CGNameGen.getAllManglings(D);
Saleem Abdulrasool60034432015-11-12 03:57:22 +00004510 return cxstring::createSet(Manglings);
4511}
4512
Guy Benyei11169dd2012-12-18 14:30:41 +00004513CXString clang_getCursorDisplayName(CXCursor C) {
4514 if (!clang_isDeclaration(C.kind))
4515 return clang_getCursorSpelling(C);
4516
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004517 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00004518 if (!D)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004519 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004520
4521 PrintingPolicy Policy = getCursorContext(C).getPrintingPolicy();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004522 if (const FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00004523 D = FunTmpl->getTemplatedDecl();
4524
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004525 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004526 SmallString<64> Str;
4527 llvm::raw_svector_ostream OS(Str);
4528 OS << *Function;
4529 if (Function->getPrimaryTemplate())
4530 OS << "<>";
4531 OS << "(";
4532 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
4533 if (I)
4534 OS << ", ";
4535 OS << Function->getParamDecl(I)->getType().getAsString(Policy);
4536 }
4537
4538 if (Function->isVariadic()) {
4539 if (Function->getNumParams())
4540 OS << ", ";
4541 OS << "...";
4542 }
4543 OS << ")";
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004544 return cxstring::createDup(OS.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00004545 }
4546
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004547 if (const ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004548 SmallString<64> Str;
4549 llvm::raw_svector_ostream OS(Str);
4550 OS << *ClassTemplate;
4551 OS << "<";
4552 TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
4553 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
4554 if (I)
4555 OS << ", ";
4556
4557 NamedDecl *Param = Params->getParam(I);
4558 if (Param->getIdentifier()) {
4559 OS << Param->getIdentifier()->getName();
4560 continue;
4561 }
4562
4563 // There is no parameter name, which makes this tricky. Try to come up
4564 // with something useful that isn't too long.
4565 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
4566 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
4567 else if (NonTypeTemplateParmDecl *NTTP
4568 = dyn_cast<NonTypeTemplateParmDecl>(Param))
4569 OS << NTTP->getType().getAsString(Policy);
4570 else
4571 OS << "template<...> class";
4572 }
4573
4574 OS << ">";
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004575 return cxstring::createDup(OS.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00004576 }
4577
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004578 if (const ClassTemplateSpecializationDecl *ClassSpec
Guy Benyei11169dd2012-12-18 14:30:41 +00004579 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
4580 // If the type was explicitly written, use that.
4581 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004582 return cxstring::createDup(TSInfo->getType().getAsString(Policy));
Guy Benyei11169dd2012-12-18 14:30:41 +00004583
Benjamin Kramer9170e912013-02-22 15:46:01 +00004584 SmallString<128> Str;
Guy Benyei11169dd2012-12-18 14:30:41 +00004585 llvm::raw_svector_ostream OS(Str);
4586 OS << *ClassSpec;
David Majnemer6fbeee32016-07-07 04:43:07 +00004587 TemplateSpecializationType::PrintTemplateArgumentList(
4588 OS, ClassSpec->getTemplateArgs().asArray(), Policy);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004589 return cxstring::createDup(OS.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00004590 }
4591
4592 return clang_getCursorSpelling(C);
4593}
4594
4595CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
4596 switch (Kind) {
4597 case CXCursor_FunctionDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004598 return cxstring::createRef("FunctionDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004599 case CXCursor_TypedefDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004600 return cxstring::createRef("TypedefDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004601 case CXCursor_EnumDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004602 return cxstring::createRef("EnumDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004603 case CXCursor_EnumConstantDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004604 return cxstring::createRef("EnumConstantDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004605 case CXCursor_StructDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004606 return cxstring::createRef("StructDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004607 case CXCursor_UnionDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004608 return cxstring::createRef("UnionDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004609 case CXCursor_ClassDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004610 return cxstring::createRef("ClassDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004611 case CXCursor_FieldDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004612 return cxstring::createRef("FieldDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004613 case CXCursor_VarDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004614 return cxstring::createRef("VarDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004615 case CXCursor_ParmDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004616 return cxstring::createRef("ParmDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004617 case CXCursor_ObjCInterfaceDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004618 return cxstring::createRef("ObjCInterfaceDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004619 case CXCursor_ObjCCategoryDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004620 return cxstring::createRef("ObjCCategoryDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004621 case CXCursor_ObjCProtocolDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004622 return cxstring::createRef("ObjCProtocolDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004623 case CXCursor_ObjCPropertyDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004624 return cxstring::createRef("ObjCPropertyDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004625 case CXCursor_ObjCIvarDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004626 return cxstring::createRef("ObjCIvarDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004627 case CXCursor_ObjCInstanceMethodDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004628 return cxstring::createRef("ObjCInstanceMethodDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004629 case CXCursor_ObjCClassMethodDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004630 return cxstring::createRef("ObjCClassMethodDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004631 case CXCursor_ObjCImplementationDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004632 return cxstring::createRef("ObjCImplementationDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004633 case CXCursor_ObjCCategoryImplDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004634 return cxstring::createRef("ObjCCategoryImplDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004635 case CXCursor_CXXMethod:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004636 return cxstring::createRef("CXXMethod");
Guy Benyei11169dd2012-12-18 14:30:41 +00004637 case CXCursor_UnexposedDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004638 return cxstring::createRef("UnexposedDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004639 case CXCursor_ObjCSuperClassRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004640 return cxstring::createRef("ObjCSuperClassRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00004641 case CXCursor_ObjCProtocolRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004642 return cxstring::createRef("ObjCProtocolRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00004643 case CXCursor_ObjCClassRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004644 return cxstring::createRef("ObjCClassRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00004645 case CXCursor_TypeRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004646 return cxstring::createRef("TypeRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00004647 case CXCursor_TemplateRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004648 return cxstring::createRef("TemplateRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00004649 case CXCursor_NamespaceRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004650 return cxstring::createRef("NamespaceRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00004651 case CXCursor_MemberRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004652 return cxstring::createRef("MemberRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00004653 case CXCursor_LabelRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004654 return cxstring::createRef("LabelRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00004655 case CXCursor_OverloadedDeclRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004656 return cxstring::createRef("OverloadedDeclRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00004657 case CXCursor_VariableRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004658 return cxstring::createRef("VariableRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00004659 case CXCursor_IntegerLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004660 return cxstring::createRef("IntegerLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00004661 case CXCursor_FloatingLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004662 return cxstring::createRef("FloatingLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00004663 case CXCursor_ImaginaryLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004664 return cxstring::createRef("ImaginaryLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00004665 case CXCursor_StringLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004666 return cxstring::createRef("StringLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00004667 case CXCursor_CharacterLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004668 return cxstring::createRef("CharacterLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00004669 case CXCursor_ParenExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004670 return cxstring::createRef("ParenExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004671 case CXCursor_UnaryOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004672 return cxstring::createRef("UnaryOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00004673 case CXCursor_ArraySubscriptExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004674 return cxstring::createRef("ArraySubscriptExpr");
Alexey Bataev1a3320e2015-08-25 14:24:04 +00004675 case CXCursor_OMPArraySectionExpr:
4676 return cxstring::createRef("OMPArraySectionExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004677 case CXCursor_BinaryOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004678 return cxstring::createRef("BinaryOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00004679 case CXCursor_CompoundAssignOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004680 return cxstring::createRef("CompoundAssignOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00004681 case CXCursor_ConditionalOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004682 return cxstring::createRef("ConditionalOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00004683 case CXCursor_CStyleCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004684 return cxstring::createRef("CStyleCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004685 case CXCursor_CompoundLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004686 return cxstring::createRef("CompoundLiteralExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004687 case CXCursor_InitListExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004688 return cxstring::createRef("InitListExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004689 case CXCursor_AddrLabelExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004690 return cxstring::createRef("AddrLabelExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004691 case CXCursor_StmtExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004692 return cxstring::createRef("StmtExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004693 case CXCursor_GenericSelectionExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004694 return cxstring::createRef("GenericSelectionExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004695 case CXCursor_GNUNullExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004696 return cxstring::createRef("GNUNullExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004697 case CXCursor_CXXStaticCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004698 return cxstring::createRef("CXXStaticCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004699 case CXCursor_CXXDynamicCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004700 return cxstring::createRef("CXXDynamicCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004701 case CXCursor_CXXReinterpretCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004702 return cxstring::createRef("CXXReinterpretCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004703 case CXCursor_CXXConstCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004704 return cxstring::createRef("CXXConstCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004705 case CXCursor_CXXFunctionalCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004706 return cxstring::createRef("CXXFunctionalCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004707 case CXCursor_CXXTypeidExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004708 return cxstring::createRef("CXXTypeidExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004709 case CXCursor_CXXBoolLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004710 return cxstring::createRef("CXXBoolLiteralExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004711 case CXCursor_CXXNullPtrLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004712 return cxstring::createRef("CXXNullPtrLiteralExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004713 case CXCursor_CXXThisExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004714 return cxstring::createRef("CXXThisExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004715 case CXCursor_CXXThrowExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004716 return cxstring::createRef("CXXThrowExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004717 case CXCursor_CXXNewExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004718 return cxstring::createRef("CXXNewExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004719 case CXCursor_CXXDeleteExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004720 return cxstring::createRef("CXXDeleteExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004721 case CXCursor_UnaryExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004722 return cxstring::createRef("UnaryExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004723 case CXCursor_ObjCStringLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004724 return cxstring::createRef("ObjCStringLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00004725 case CXCursor_ObjCBoolLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004726 return cxstring::createRef("ObjCBoolLiteralExpr");
Erik Pilkington29099de2016-07-16 00:35:23 +00004727 case CXCursor_ObjCAvailabilityCheckExpr:
4728 return cxstring::createRef("ObjCAvailabilityCheckExpr");
Argyrios Kyrtzidisc2233be2013-04-23 17:57:17 +00004729 case CXCursor_ObjCSelfExpr:
4730 return cxstring::createRef("ObjCSelfExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004731 case CXCursor_ObjCEncodeExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004732 return cxstring::createRef("ObjCEncodeExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004733 case CXCursor_ObjCSelectorExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004734 return cxstring::createRef("ObjCSelectorExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004735 case CXCursor_ObjCProtocolExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004736 return cxstring::createRef("ObjCProtocolExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004737 case CXCursor_ObjCBridgedCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004738 return cxstring::createRef("ObjCBridgedCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004739 case CXCursor_BlockExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004740 return cxstring::createRef("BlockExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004741 case CXCursor_PackExpansionExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004742 return cxstring::createRef("PackExpansionExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004743 case CXCursor_SizeOfPackExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004744 return cxstring::createRef("SizeOfPackExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004745 case CXCursor_LambdaExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004746 return cxstring::createRef("LambdaExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004747 case CXCursor_UnexposedExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004748 return cxstring::createRef("UnexposedExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004749 case CXCursor_DeclRefExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004750 return cxstring::createRef("DeclRefExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004751 case CXCursor_MemberRefExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004752 return cxstring::createRef("MemberRefExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004753 case CXCursor_CallExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004754 return cxstring::createRef("CallExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004755 case CXCursor_ObjCMessageExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004756 return cxstring::createRef("ObjCMessageExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004757 case CXCursor_UnexposedStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004758 return cxstring::createRef("UnexposedStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004759 case CXCursor_DeclStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004760 return cxstring::createRef("DeclStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004761 case CXCursor_LabelStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004762 return cxstring::createRef("LabelStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004763 case CXCursor_CompoundStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004764 return cxstring::createRef("CompoundStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004765 case CXCursor_CaseStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004766 return cxstring::createRef("CaseStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004767 case CXCursor_DefaultStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004768 return cxstring::createRef("DefaultStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004769 case CXCursor_IfStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004770 return cxstring::createRef("IfStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004771 case CXCursor_SwitchStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004772 return cxstring::createRef("SwitchStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004773 case CXCursor_WhileStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004774 return cxstring::createRef("WhileStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004775 case CXCursor_DoStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004776 return cxstring::createRef("DoStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004777 case CXCursor_ForStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004778 return cxstring::createRef("ForStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004779 case CXCursor_GotoStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004780 return cxstring::createRef("GotoStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004781 case CXCursor_IndirectGotoStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004782 return cxstring::createRef("IndirectGotoStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004783 case CXCursor_ContinueStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004784 return cxstring::createRef("ContinueStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004785 case CXCursor_BreakStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004786 return cxstring::createRef("BreakStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004787 case CXCursor_ReturnStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004788 return cxstring::createRef("ReturnStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004789 case CXCursor_GCCAsmStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004790 return cxstring::createRef("GCCAsmStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004791 case CXCursor_MSAsmStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004792 return cxstring::createRef("MSAsmStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004793 case CXCursor_ObjCAtTryStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004794 return cxstring::createRef("ObjCAtTryStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004795 case CXCursor_ObjCAtCatchStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004796 return cxstring::createRef("ObjCAtCatchStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004797 case CXCursor_ObjCAtFinallyStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004798 return cxstring::createRef("ObjCAtFinallyStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004799 case CXCursor_ObjCAtThrowStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004800 return cxstring::createRef("ObjCAtThrowStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004801 case CXCursor_ObjCAtSynchronizedStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004802 return cxstring::createRef("ObjCAtSynchronizedStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004803 case CXCursor_ObjCAutoreleasePoolStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004804 return cxstring::createRef("ObjCAutoreleasePoolStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004805 case CXCursor_ObjCForCollectionStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004806 return cxstring::createRef("ObjCForCollectionStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004807 case CXCursor_CXXCatchStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004808 return cxstring::createRef("CXXCatchStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004809 case CXCursor_CXXTryStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004810 return cxstring::createRef("CXXTryStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004811 case CXCursor_CXXForRangeStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004812 return cxstring::createRef("CXXForRangeStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004813 case CXCursor_SEHTryStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004814 return cxstring::createRef("SEHTryStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004815 case CXCursor_SEHExceptStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004816 return cxstring::createRef("SEHExceptStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004817 case CXCursor_SEHFinallyStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004818 return cxstring::createRef("SEHFinallyStmt");
Nico Weber9b982072014-07-07 00:12:30 +00004819 case CXCursor_SEHLeaveStmt:
4820 return cxstring::createRef("SEHLeaveStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004821 case CXCursor_NullStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004822 return cxstring::createRef("NullStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004823 case CXCursor_InvalidFile:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004824 return cxstring::createRef("InvalidFile");
Guy Benyei11169dd2012-12-18 14:30:41 +00004825 case CXCursor_InvalidCode:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004826 return cxstring::createRef("InvalidCode");
Guy Benyei11169dd2012-12-18 14:30:41 +00004827 case CXCursor_NoDeclFound:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004828 return cxstring::createRef("NoDeclFound");
Guy Benyei11169dd2012-12-18 14:30:41 +00004829 case CXCursor_NotImplemented:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004830 return cxstring::createRef("NotImplemented");
Guy Benyei11169dd2012-12-18 14:30:41 +00004831 case CXCursor_TranslationUnit:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004832 return cxstring::createRef("TranslationUnit");
Guy Benyei11169dd2012-12-18 14:30:41 +00004833 case CXCursor_UnexposedAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004834 return cxstring::createRef("UnexposedAttr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004835 case CXCursor_IBActionAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004836 return cxstring::createRef("attribute(ibaction)");
Guy Benyei11169dd2012-12-18 14:30:41 +00004837 case CXCursor_IBOutletAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004838 return cxstring::createRef("attribute(iboutlet)");
Guy Benyei11169dd2012-12-18 14:30:41 +00004839 case CXCursor_IBOutletCollectionAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004840 return cxstring::createRef("attribute(iboutletcollection)");
Guy Benyei11169dd2012-12-18 14:30:41 +00004841 case CXCursor_CXXFinalAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004842 return cxstring::createRef("attribute(final)");
Guy Benyei11169dd2012-12-18 14:30:41 +00004843 case CXCursor_CXXOverrideAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004844 return cxstring::createRef("attribute(override)");
Guy Benyei11169dd2012-12-18 14:30:41 +00004845 case CXCursor_AnnotateAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004846 return cxstring::createRef("attribute(annotate)");
Guy Benyei11169dd2012-12-18 14:30:41 +00004847 case CXCursor_AsmLabelAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004848 return cxstring::createRef("asm label");
Argyrios Kyrtzidis16834f12013-09-25 00:14:38 +00004849 case CXCursor_PackedAttr:
4850 return cxstring::createRef("attribute(packed)");
Joey Gouly81228382014-05-01 15:41:58 +00004851 case CXCursor_PureAttr:
4852 return cxstring::createRef("attribute(pure)");
4853 case CXCursor_ConstAttr:
4854 return cxstring::createRef("attribute(const)");
4855 case CXCursor_NoDuplicateAttr:
4856 return cxstring::createRef("attribute(noduplicate)");
Eli Bendersky2581e662014-05-28 19:29:58 +00004857 case CXCursor_CUDAConstantAttr:
4858 return cxstring::createRef("attribute(constant)");
4859 case CXCursor_CUDADeviceAttr:
4860 return cxstring::createRef("attribute(device)");
4861 case CXCursor_CUDAGlobalAttr:
4862 return cxstring::createRef("attribute(global)");
4863 case CXCursor_CUDAHostAttr:
4864 return cxstring::createRef("attribute(host)");
Eli Bendersky9b071472014-08-08 14:59:00 +00004865 case CXCursor_CUDASharedAttr:
4866 return cxstring::createRef("attribute(shared)");
Saleem Abdulrasool79c69712015-09-05 18:53:43 +00004867 case CXCursor_VisibilityAttr:
4868 return cxstring::createRef("attribute(visibility)");
Saleem Abdulrasool8aa0b802015-12-10 18:45:18 +00004869 case CXCursor_DLLExport:
4870 return cxstring::createRef("attribute(dllexport)");
4871 case CXCursor_DLLImport:
4872 return cxstring::createRef("attribute(dllimport)");
Guy Benyei11169dd2012-12-18 14:30:41 +00004873 case CXCursor_PreprocessingDirective:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004874 return cxstring::createRef("preprocessing directive");
Guy Benyei11169dd2012-12-18 14:30:41 +00004875 case CXCursor_MacroDefinition:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004876 return cxstring::createRef("macro definition");
Guy Benyei11169dd2012-12-18 14:30:41 +00004877 case CXCursor_MacroExpansion:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004878 return cxstring::createRef("macro expansion");
Guy Benyei11169dd2012-12-18 14:30:41 +00004879 case CXCursor_InclusionDirective:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004880 return cxstring::createRef("inclusion directive");
Guy Benyei11169dd2012-12-18 14:30:41 +00004881 case CXCursor_Namespace:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004882 return cxstring::createRef("Namespace");
Guy Benyei11169dd2012-12-18 14:30:41 +00004883 case CXCursor_LinkageSpec:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004884 return cxstring::createRef("LinkageSpec");
Guy Benyei11169dd2012-12-18 14:30:41 +00004885 case CXCursor_CXXBaseSpecifier:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004886 return cxstring::createRef("C++ base class specifier");
Guy Benyei11169dd2012-12-18 14:30:41 +00004887 case CXCursor_Constructor:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004888 return cxstring::createRef("CXXConstructor");
Guy Benyei11169dd2012-12-18 14:30:41 +00004889 case CXCursor_Destructor:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004890 return cxstring::createRef("CXXDestructor");
Guy Benyei11169dd2012-12-18 14:30:41 +00004891 case CXCursor_ConversionFunction:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004892 return cxstring::createRef("CXXConversion");
Guy Benyei11169dd2012-12-18 14:30:41 +00004893 case CXCursor_TemplateTypeParameter:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004894 return cxstring::createRef("TemplateTypeParameter");
Guy Benyei11169dd2012-12-18 14:30:41 +00004895 case CXCursor_NonTypeTemplateParameter:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004896 return cxstring::createRef("NonTypeTemplateParameter");
Guy Benyei11169dd2012-12-18 14:30:41 +00004897 case CXCursor_TemplateTemplateParameter:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004898 return cxstring::createRef("TemplateTemplateParameter");
Guy Benyei11169dd2012-12-18 14:30:41 +00004899 case CXCursor_FunctionTemplate:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004900 return cxstring::createRef("FunctionTemplate");
Guy Benyei11169dd2012-12-18 14:30:41 +00004901 case CXCursor_ClassTemplate:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004902 return cxstring::createRef("ClassTemplate");
Guy Benyei11169dd2012-12-18 14:30:41 +00004903 case CXCursor_ClassTemplatePartialSpecialization:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004904 return cxstring::createRef("ClassTemplatePartialSpecialization");
Guy Benyei11169dd2012-12-18 14:30:41 +00004905 case CXCursor_NamespaceAlias:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004906 return cxstring::createRef("NamespaceAlias");
Guy Benyei11169dd2012-12-18 14:30:41 +00004907 case CXCursor_UsingDirective:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004908 return cxstring::createRef("UsingDirective");
Guy Benyei11169dd2012-12-18 14:30:41 +00004909 case CXCursor_UsingDeclaration:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004910 return cxstring::createRef("UsingDeclaration");
Guy Benyei11169dd2012-12-18 14:30:41 +00004911 case CXCursor_TypeAliasDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004912 return cxstring::createRef("TypeAliasDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004913 case CXCursor_ObjCSynthesizeDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004914 return cxstring::createRef("ObjCSynthesizeDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004915 case CXCursor_ObjCDynamicDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004916 return cxstring::createRef("ObjCDynamicDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004917 case CXCursor_CXXAccessSpecifier:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004918 return cxstring::createRef("CXXAccessSpecifier");
Guy Benyei11169dd2012-12-18 14:30:41 +00004919 case CXCursor_ModuleImportDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004920 return cxstring::createRef("ModuleImport");
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004921 case CXCursor_OMPParallelDirective:
Alexey Bataev1b59ab52014-02-27 08:29:12 +00004922 return cxstring::createRef("OMPParallelDirective");
4923 case CXCursor_OMPSimdDirective:
4924 return cxstring::createRef("OMPSimdDirective");
Alexey Bataevf29276e2014-06-18 04:14:57 +00004925 case CXCursor_OMPForDirective:
4926 return cxstring::createRef("OMPForDirective");
Alexander Musmanf82886e2014-09-18 05:12:34 +00004927 case CXCursor_OMPForSimdDirective:
4928 return cxstring::createRef("OMPForSimdDirective");
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004929 case CXCursor_OMPSectionsDirective:
4930 return cxstring::createRef("OMPSectionsDirective");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004931 case CXCursor_OMPSectionDirective:
4932 return cxstring::createRef("OMPSectionDirective");
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00004933 case CXCursor_OMPSingleDirective:
4934 return cxstring::createRef("OMPSingleDirective");
Alexander Musman80c22892014-07-17 08:54:58 +00004935 case CXCursor_OMPMasterDirective:
4936 return cxstring::createRef("OMPMasterDirective");
Alexander Musmand9ed09f2014-07-21 09:42:05 +00004937 case CXCursor_OMPCriticalDirective:
4938 return cxstring::createRef("OMPCriticalDirective");
Alexey Bataev4acb8592014-07-07 13:01:15 +00004939 case CXCursor_OMPParallelForDirective:
4940 return cxstring::createRef("OMPParallelForDirective");
Alexander Musmane4e893b2014-09-23 09:33:00 +00004941 case CXCursor_OMPParallelForSimdDirective:
4942 return cxstring::createRef("OMPParallelForSimdDirective");
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004943 case CXCursor_OMPParallelSectionsDirective:
4944 return cxstring::createRef("OMPParallelSectionsDirective");
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004945 case CXCursor_OMPTaskDirective:
4946 return cxstring::createRef("OMPTaskDirective");
Alexey Bataev68446b72014-07-18 07:47:19 +00004947 case CXCursor_OMPTaskyieldDirective:
4948 return cxstring::createRef("OMPTaskyieldDirective");
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00004949 case CXCursor_OMPBarrierDirective:
4950 return cxstring::createRef("OMPBarrierDirective");
Alexey Bataev2df347a2014-07-18 10:17:07 +00004951 case CXCursor_OMPTaskwaitDirective:
4952 return cxstring::createRef("OMPTaskwaitDirective");
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00004953 case CXCursor_OMPTaskgroupDirective:
4954 return cxstring::createRef("OMPTaskgroupDirective");
Alexey Bataev6125da92014-07-21 11:26:11 +00004955 case CXCursor_OMPFlushDirective:
4956 return cxstring::createRef("OMPFlushDirective");
Alexey Bataev9fb6e642014-07-22 06:45:04 +00004957 case CXCursor_OMPOrderedDirective:
4958 return cxstring::createRef("OMPOrderedDirective");
Alexey Bataev0162e452014-07-22 10:10:35 +00004959 case CXCursor_OMPAtomicDirective:
4960 return cxstring::createRef("OMPAtomicDirective");
Alexey Bataev0bd520b2014-09-19 08:19:49 +00004961 case CXCursor_OMPTargetDirective:
4962 return cxstring::createRef("OMPTargetDirective");
Michael Wong65f367f2015-07-21 13:44:28 +00004963 case CXCursor_OMPTargetDataDirective:
4964 return cxstring::createRef("OMPTargetDataDirective");
Samuel Antaodf67fc42016-01-19 19:15:56 +00004965 case CXCursor_OMPTargetEnterDataDirective:
4966 return cxstring::createRef("OMPTargetEnterDataDirective");
Samuel Antao72590762016-01-19 20:04:50 +00004967 case CXCursor_OMPTargetExitDataDirective:
4968 return cxstring::createRef("OMPTargetExitDataDirective");
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00004969 case CXCursor_OMPTargetParallelDirective:
4970 return cxstring::createRef("OMPTargetParallelDirective");
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00004971 case CXCursor_OMPTargetParallelForDirective:
4972 return cxstring::createRef("OMPTargetParallelForDirective");
Samuel Antao686c70c2016-05-26 17:30:50 +00004973 case CXCursor_OMPTargetUpdateDirective:
4974 return cxstring::createRef("OMPTargetUpdateDirective");
Alexey Bataev13314bf2014-10-09 04:18:56 +00004975 case CXCursor_OMPTeamsDirective:
4976 return cxstring::createRef("OMPTeamsDirective");
Alexey Bataev6d4ed052015-07-01 06:57:41 +00004977 case CXCursor_OMPCancellationPointDirective:
4978 return cxstring::createRef("OMPCancellationPointDirective");
Alexey Bataev80909872015-07-02 11:25:17 +00004979 case CXCursor_OMPCancelDirective:
4980 return cxstring::createRef("OMPCancelDirective");
Alexey Bataev49f6e782015-12-01 04:18:41 +00004981 case CXCursor_OMPTaskLoopDirective:
4982 return cxstring::createRef("OMPTaskLoopDirective");
Alexey Bataev0a6ed842015-12-03 09:40:15 +00004983 case CXCursor_OMPTaskLoopSimdDirective:
4984 return cxstring::createRef("OMPTaskLoopSimdDirective");
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004985 case CXCursor_OMPDistributeDirective:
4986 return cxstring::createRef("OMPDistributeDirective");
Carlo Bertolli9925f152016-06-27 14:55:37 +00004987 case CXCursor_OMPDistributeParallelForDirective:
4988 return cxstring::createRef("OMPDistributeParallelForDirective");
Kelvin Li4a39add2016-07-05 05:00:15 +00004989 case CXCursor_OMPDistributeParallelForSimdDirective:
4990 return cxstring::createRef("OMPDistributeParallelForSimdDirective");
Kelvin Li787f3fc2016-07-06 04:45:38 +00004991 case CXCursor_OMPDistributeSimdDirective:
4992 return cxstring::createRef("OMPDistributeSimdDirective");
Kelvin Lia579b912016-07-14 02:54:56 +00004993 case CXCursor_OMPTargetParallelForSimdDirective:
4994 return cxstring::createRef("OMPTargetParallelForSimdDirective");
Kelvin Li986330c2016-07-20 22:57:10 +00004995 case CXCursor_OMPTargetSimdDirective:
4996 return cxstring::createRef("OMPTargetSimdDirective");
Kelvin Li02532872016-08-05 14:37:37 +00004997 case CXCursor_OMPTeamsDistributeDirective:
4998 return cxstring::createRef("OMPTeamsDistributeDirective");
Kelvin Li4e325f72016-10-25 12:50:55 +00004999 case CXCursor_OMPTeamsDistributeSimdDirective:
5000 return cxstring::createRef("OMPTeamsDistributeSimdDirective");
Kelvin Li579e41c2016-11-30 23:51:03 +00005001 case CXCursor_OMPTeamsDistributeParallelForSimdDirective:
5002 return cxstring::createRef("OMPTeamsDistributeParallelForSimdDirective");
Kelvin Li7ade93f2016-12-09 03:24:30 +00005003 case CXCursor_OMPTeamsDistributeParallelForDirective:
5004 return cxstring::createRef("OMPTeamsDistributeParallelForDirective");
Kelvin Libf594a52016-12-17 05:48:59 +00005005 case CXCursor_OMPTargetTeamsDirective:
5006 return cxstring::createRef("OMPTargetTeamsDirective");
Kelvin Li83c451e2016-12-25 04:52:54 +00005007 case CXCursor_OMPTargetTeamsDistributeDirective:
5008 return cxstring::createRef("OMPTargetTeamsDistributeDirective");
Kelvin Li80e8f562016-12-29 22:16:30 +00005009 case CXCursor_OMPTargetTeamsDistributeParallelForDirective:
5010 return cxstring::createRef("OMPTargetTeamsDistributeParallelForDirective");
Kelvin Li1851df52017-01-03 05:23:48 +00005011 case CXCursor_OMPTargetTeamsDistributeParallelForSimdDirective:
5012 return cxstring::createRef(
5013 "OMPTargetTeamsDistributeParallelForSimdDirective");
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005014 case CXCursor_OverloadCandidate:
5015 return cxstring::createRef("OverloadCandidate");
Sergey Kalinichev8f3b1872015-11-15 13:48:32 +00005016 case CXCursor_TypeAliasTemplateDecl:
5017 return cxstring::createRef("TypeAliasTemplateDecl");
Olivier Goffart81978012016-06-09 16:15:55 +00005018 case CXCursor_StaticAssert:
5019 return cxstring::createRef("StaticAssert");
Olivier Goffartd211c642016-11-04 06:29:27 +00005020 case CXCursor_FriendDecl:
5021 return cxstring::createRef("FriendDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005022 }
5023
5024 llvm_unreachable("Unhandled CXCursorKind");
5025}
5026
5027struct GetCursorData {
5028 SourceLocation TokenBeginLoc;
5029 bool PointsAtMacroArgExpansion;
5030 bool VisitedObjCPropertyImplDecl;
5031 SourceLocation VisitedDeclaratorDeclStartLoc;
5032 CXCursor &BestCursor;
5033
5034 GetCursorData(SourceManager &SM,
5035 SourceLocation tokenBegin, CXCursor &outputCursor)
5036 : TokenBeginLoc(tokenBegin), BestCursor(outputCursor) {
5037 PointsAtMacroArgExpansion = SM.isMacroArgExpansion(tokenBegin);
5038 VisitedObjCPropertyImplDecl = false;
5039 }
5040};
5041
5042static enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
5043 CXCursor parent,
5044 CXClientData client_data) {
5045 GetCursorData *Data = static_cast<GetCursorData *>(client_data);
5046 CXCursor *BestCursor = &Data->BestCursor;
5047
5048 // If we point inside a macro argument we should provide info of what the
5049 // token is so use the actual cursor, don't replace it with a macro expansion
5050 // cursor.
5051 if (cursor.kind == CXCursor_MacroExpansion && Data->PointsAtMacroArgExpansion)
5052 return CXChildVisit_Recurse;
5053
5054 if (clang_isDeclaration(cursor.kind)) {
5055 // Avoid having the implicit methods override the property decls.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005056 if (const ObjCMethodDecl *MD
Guy Benyei11169dd2012-12-18 14:30:41 +00005057 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
5058 if (MD->isImplicit())
5059 return CXChildVisit_Break;
5060
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005061 } else if (const ObjCInterfaceDecl *ID
Guy Benyei11169dd2012-12-18 14:30:41 +00005062 = dyn_cast_or_null<ObjCInterfaceDecl>(getCursorDecl(cursor))) {
5063 // Check that when we have multiple @class references in the same line,
5064 // that later ones do not override the previous ones.
5065 // If we have:
5066 // @class Foo, Bar;
5067 // source ranges for both start at '@', so 'Bar' will end up overriding
5068 // 'Foo' even though the cursor location was at 'Foo'.
5069 if (BestCursor->kind == CXCursor_ObjCInterfaceDecl ||
5070 BestCursor->kind == CXCursor_ObjCClassRef)
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005071 if (const ObjCInterfaceDecl *PrevID
Guy Benyei11169dd2012-12-18 14:30:41 +00005072 = dyn_cast_or_null<ObjCInterfaceDecl>(getCursorDecl(*BestCursor))){
5073 if (PrevID != ID &&
5074 !PrevID->isThisDeclarationADefinition() &&
5075 !ID->isThisDeclarationADefinition())
5076 return CXChildVisit_Break;
5077 }
5078
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005079 } else if (const DeclaratorDecl *DD
Guy Benyei11169dd2012-12-18 14:30:41 +00005080 = dyn_cast_or_null<DeclaratorDecl>(getCursorDecl(cursor))) {
5081 SourceLocation StartLoc = DD->getSourceRange().getBegin();
5082 // Check that when we have multiple declarators in the same line,
5083 // that later ones do not override the previous ones.
5084 // If we have:
5085 // int Foo, Bar;
5086 // source ranges for both start at 'int', so 'Bar' will end up overriding
5087 // 'Foo' even though the cursor location was at 'Foo'.
5088 if (Data->VisitedDeclaratorDeclStartLoc == StartLoc)
5089 return CXChildVisit_Break;
5090 Data->VisitedDeclaratorDeclStartLoc = StartLoc;
5091
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005092 } else if (const ObjCPropertyImplDecl *PropImp
Guy Benyei11169dd2012-12-18 14:30:41 +00005093 = dyn_cast_or_null<ObjCPropertyImplDecl>(getCursorDecl(cursor))) {
5094 (void)PropImp;
5095 // Check that when we have multiple @synthesize in the same line,
5096 // that later ones do not override the previous ones.
5097 // If we have:
5098 // @synthesize Foo, Bar;
5099 // source ranges for both start at '@', so 'Bar' will end up overriding
5100 // 'Foo' even though the cursor location was at 'Foo'.
5101 if (Data->VisitedObjCPropertyImplDecl)
5102 return CXChildVisit_Break;
5103 Data->VisitedObjCPropertyImplDecl = true;
5104 }
5105 }
5106
5107 if (clang_isExpression(cursor.kind) &&
5108 clang_isDeclaration(BestCursor->kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005109 if (const Decl *D = getCursorDecl(*BestCursor)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005110 // Avoid having the cursor of an expression replace the declaration cursor
5111 // when the expression source range overlaps the declaration range.
5112 // This can happen for C++ constructor expressions whose range generally
5113 // include the variable declaration, e.g.:
5114 // MyCXXClass foo; // Make sure pointing at 'foo' returns a VarDecl cursor.
5115 if (D->getLocation().isValid() && Data->TokenBeginLoc.isValid() &&
5116 D->getLocation() == Data->TokenBeginLoc)
5117 return CXChildVisit_Break;
5118 }
5119 }
5120
5121 // If our current best cursor is the construction of a temporary object,
5122 // don't replace that cursor with a type reference, because we want
5123 // clang_getCursor() to point at the constructor.
5124 if (clang_isExpression(BestCursor->kind) &&
5125 isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
5126 cursor.kind == CXCursor_TypeRef) {
5127 // Keep the cursor pointing at CXXTemporaryObjectExpr but also mark it
5128 // as having the actual point on the type reference.
5129 *BestCursor = getTypeRefedCallExprCursor(*BestCursor);
5130 return CXChildVisit_Recurse;
5131 }
Douglas Gregore9d95f12015-07-07 03:57:35 +00005132
5133 // If we already have an Objective-C superclass reference, don't
5134 // update it further.
5135 if (BestCursor->kind == CXCursor_ObjCSuperClassRef)
5136 return CXChildVisit_Break;
5137
Guy Benyei11169dd2012-12-18 14:30:41 +00005138 *BestCursor = cursor;
5139 return CXChildVisit_Recurse;
5140}
5141
5142CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00005143 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00005144 LOG_BAD_TU(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00005145 return clang_getNullCursor();
Dmitri Gribenko256454f2014-02-11 14:34:14 +00005146 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005147
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00005148 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00005149 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
5150
5151 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
5152 CXCursor Result = cxcursor::getCursor(TU, SLoc);
5153
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005154 LOG_FUNC_SECTION {
Guy Benyei11169dd2012-12-18 14:30:41 +00005155 CXFile SearchFile;
5156 unsigned SearchLine, SearchColumn;
5157 CXFile ResultFile;
5158 unsigned ResultLine, ResultColumn;
5159 CXString SearchFileName, ResultFileName, KindSpelling, USR;
5160 const char *IsDef = clang_isCursorDefinition(Result)? " (Definition)" : "";
5161 CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
Craig Topper69186e72014-06-08 08:38:04 +00005162
5163 clang_getFileLocation(Loc, &SearchFile, &SearchLine, &SearchColumn,
5164 nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005165 clang_getFileLocation(ResultLoc, &ResultFile, &ResultLine,
Craig Topper69186e72014-06-08 08:38:04 +00005166 &ResultColumn, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005167 SearchFileName = clang_getFileName(SearchFile);
5168 ResultFileName = clang_getFileName(ResultFile);
5169 KindSpelling = clang_getCursorKindSpelling(Result.kind);
5170 USR = clang_getCursorUSR(Result);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005171 *Log << llvm::format("(%s:%d:%d) = %s",
5172 clang_getCString(SearchFileName), SearchLine, SearchColumn,
5173 clang_getCString(KindSpelling))
5174 << llvm::format("(%s:%d:%d):%s%s",
5175 clang_getCString(ResultFileName), ResultLine, ResultColumn,
5176 clang_getCString(USR), IsDef);
Guy Benyei11169dd2012-12-18 14:30:41 +00005177 clang_disposeString(SearchFileName);
5178 clang_disposeString(ResultFileName);
5179 clang_disposeString(KindSpelling);
5180 clang_disposeString(USR);
5181
5182 CXCursor Definition = clang_getCursorDefinition(Result);
5183 if (!clang_equalCursors(Definition, clang_getNullCursor())) {
5184 CXSourceLocation DefinitionLoc = clang_getCursorLocation(Definition);
5185 CXString DefinitionKindSpelling
5186 = clang_getCursorKindSpelling(Definition.kind);
5187 CXFile DefinitionFile;
5188 unsigned DefinitionLine, DefinitionColumn;
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005189 clang_getFileLocation(DefinitionLoc, &DefinitionFile,
Craig Topper69186e72014-06-08 08:38:04 +00005190 &DefinitionLine, &DefinitionColumn, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005191 CXString DefinitionFileName = clang_getFileName(DefinitionFile);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005192 *Log << llvm::format(" -> %s(%s:%d:%d)",
5193 clang_getCString(DefinitionKindSpelling),
5194 clang_getCString(DefinitionFileName),
5195 DefinitionLine, DefinitionColumn);
Guy Benyei11169dd2012-12-18 14:30:41 +00005196 clang_disposeString(DefinitionFileName);
5197 clang_disposeString(DefinitionKindSpelling);
5198 }
5199 }
5200
5201 return Result;
5202}
5203
5204CXCursor clang_getNullCursor(void) {
5205 return MakeCXCursorInvalid(CXCursor_InvalidFile);
5206}
5207
5208unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Argyrios Kyrtzidisbf1be592013-01-08 18:23:28 +00005209 // Clear out the "FirstInDeclGroup" part in a declaration cursor, since we
5210 // can't set consistently. For example, when visiting a DeclStmt we will set
5211 // it but we don't set it on the result of clang_getCursorDefinition for
5212 // a reference of the same declaration.
5213 // FIXME: Setting "FirstInDeclGroup" in CXCursors is a hack that only works
5214 // when visiting a DeclStmt currently, the AST should be enhanced to be able
5215 // to provide that kind of info.
5216 if (clang_isDeclaration(X.kind))
Craig Topper69186e72014-06-08 08:38:04 +00005217 X.data[1] = nullptr;
Argyrios Kyrtzidisbf1be592013-01-08 18:23:28 +00005218 if (clang_isDeclaration(Y.kind))
Craig Topper69186e72014-06-08 08:38:04 +00005219 Y.data[1] = nullptr;
Argyrios Kyrtzidisbf1be592013-01-08 18:23:28 +00005220
Guy Benyei11169dd2012-12-18 14:30:41 +00005221 return X == Y;
5222}
5223
5224unsigned clang_hashCursor(CXCursor C) {
5225 unsigned Index = 0;
5226 if (clang_isExpression(C.kind) || clang_isStatement(C.kind))
5227 Index = 1;
5228
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005229 return llvm::DenseMapInfo<std::pair<unsigned, const void*> >::getHashValue(
Guy Benyei11169dd2012-12-18 14:30:41 +00005230 std::make_pair(C.kind, C.data[Index]));
5231}
5232
5233unsigned clang_isInvalid(enum CXCursorKind K) {
5234 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
5235}
5236
5237unsigned clang_isDeclaration(enum CXCursorKind K) {
5238 return (K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl) ||
5239 (K >= CXCursor_FirstExtraDecl && K <= CXCursor_LastExtraDecl);
5240}
5241
5242unsigned clang_isReference(enum CXCursorKind K) {
5243 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
5244}
5245
5246unsigned clang_isExpression(enum CXCursorKind K) {
5247 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
5248}
5249
5250unsigned clang_isStatement(enum CXCursorKind K) {
5251 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
5252}
5253
5254unsigned clang_isAttribute(enum CXCursorKind K) {
5255 return K >= CXCursor_FirstAttr && K <= CXCursor_LastAttr;
5256}
5257
5258unsigned clang_isTranslationUnit(enum CXCursorKind K) {
5259 return K == CXCursor_TranslationUnit;
5260}
5261
5262unsigned clang_isPreprocessing(enum CXCursorKind K) {
5263 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
5264}
5265
5266unsigned clang_isUnexposed(enum CXCursorKind K) {
5267 switch (K) {
5268 case CXCursor_UnexposedDecl:
5269 case CXCursor_UnexposedExpr:
5270 case CXCursor_UnexposedStmt:
5271 case CXCursor_UnexposedAttr:
5272 return true;
5273 default:
5274 return false;
5275 }
5276}
5277
5278CXCursorKind clang_getCursorKind(CXCursor C) {
5279 return C.kind;
5280}
5281
5282CXSourceLocation clang_getCursorLocation(CXCursor C) {
5283 if (clang_isReference(C.kind)) {
5284 switch (C.kind) {
5285 case CXCursor_ObjCSuperClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005286 std::pair<const ObjCInterfaceDecl *, SourceLocation> P
Guy Benyei11169dd2012-12-18 14:30:41 +00005287 = getCursorObjCSuperClassRef(C);
5288 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5289 }
5290
5291 case CXCursor_ObjCProtocolRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005292 std::pair<const ObjCProtocolDecl *, SourceLocation> P
Guy Benyei11169dd2012-12-18 14:30:41 +00005293 = getCursorObjCProtocolRef(C);
5294 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5295 }
5296
5297 case CXCursor_ObjCClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005298 std::pair<const ObjCInterfaceDecl *, SourceLocation> P
Guy Benyei11169dd2012-12-18 14:30:41 +00005299 = getCursorObjCClassRef(C);
5300 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5301 }
5302
5303 case CXCursor_TypeRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005304 std::pair<const TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005305 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5306 }
5307
5308 case CXCursor_TemplateRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005309 std::pair<const TemplateDecl *, SourceLocation> P =
5310 getCursorTemplateRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005311 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5312 }
5313
5314 case CXCursor_NamespaceRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005315 std::pair<const NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005316 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5317 }
5318
5319 case CXCursor_MemberRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005320 std::pair<const FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005321 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5322 }
5323
5324 case CXCursor_VariableRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005325 std::pair<const VarDecl *, SourceLocation> P = getCursorVariableRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005326 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5327 }
5328
5329 case CXCursor_CXXBaseSpecifier: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005330 const CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005331 if (!BaseSpec)
5332 return clang_getNullLocation();
5333
5334 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
5335 return cxloc::translateSourceLocation(getCursorContext(C),
5336 TSInfo->getTypeLoc().getBeginLoc());
5337
5338 return cxloc::translateSourceLocation(getCursorContext(C),
5339 BaseSpec->getLocStart());
5340 }
5341
5342 case CXCursor_LabelRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005343 std::pair<const LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005344 return cxloc::translateSourceLocation(getCursorContext(C), P.second);
5345 }
5346
5347 case CXCursor_OverloadedDeclRef:
5348 return cxloc::translateSourceLocation(getCursorContext(C),
5349 getCursorOverloadedDeclRef(C).second);
5350
5351 default:
5352 // FIXME: Need a way to enumerate all non-reference cases.
5353 llvm_unreachable("Missed a reference kind");
5354 }
5355 }
5356
5357 if (clang_isExpression(C.kind))
5358 return cxloc::translateSourceLocation(getCursorContext(C),
5359 getLocationFromExpr(getCursorExpr(C)));
5360
5361 if (clang_isStatement(C.kind))
5362 return cxloc::translateSourceLocation(getCursorContext(C),
5363 getCursorStmt(C)->getLocStart());
5364
5365 if (C.kind == CXCursor_PreprocessingDirective) {
5366 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
5367 return cxloc::translateSourceLocation(getCursorContext(C), L);
5368 }
5369
5370 if (C.kind == CXCursor_MacroExpansion) {
5371 SourceLocation L
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00005372 = cxcursor::getCursorMacroExpansion(C).getSourceRange().getBegin();
Guy Benyei11169dd2012-12-18 14:30:41 +00005373 return cxloc::translateSourceLocation(getCursorContext(C), L);
5374 }
5375
5376 if (C.kind == CXCursor_MacroDefinition) {
5377 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
5378 return cxloc::translateSourceLocation(getCursorContext(C), L);
5379 }
5380
5381 if (C.kind == CXCursor_InclusionDirective) {
5382 SourceLocation L
5383 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
5384 return cxloc::translateSourceLocation(getCursorContext(C), L);
5385 }
5386
Argyrios Kyrtzidis16834f12013-09-25 00:14:38 +00005387 if (clang_isAttribute(C.kind)) {
5388 SourceLocation L
5389 = cxcursor::getCursorAttr(C)->getLocation();
5390 return cxloc::translateSourceLocation(getCursorContext(C), L);
5391 }
5392
Guy Benyei11169dd2012-12-18 14:30:41 +00005393 if (!clang_isDeclaration(C.kind))
5394 return clang_getNullLocation();
5395
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005396 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005397 if (!D)
5398 return clang_getNullLocation();
5399
5400 SourceLocation Loc = D->getLocation();
5401 // FIXME: Multiple variables declared in a single declaration
5402 // currently lack the information needed to correctly determine their
5403 // ranges when accounting for the type-specifier. We use context
5404 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
5405 // and if so, whether it is the first decl.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005406 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005407 if (!cxcursor::isFirstInDeclGroup(C))
5408 Loc = VD->getLocation();
5409 }
5410
5411 // For ObjC methods, give the start location of the method name.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005412 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00005413 Loc = MD->getSelectorStartLoc();
5414
5415 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
5416}
5417
NAKAMURA Takumia01f4c32016-12-19 16:50:43 +00005418} // end extern "C"
5419
Guy Benyei11169dd2012-12-18 14:30:41 +00005420CXCursor cxcursor::getCursor(CXTranslationUnit TU, SourceLocation SLoc) {
5421 assert(TU);
5422
5423 // Guard against an invalid SourceLocation, or we may assert in one
5424 // of the following calls.
5425 if (SLoc.isInvalid())
5426 return clang_getNullCursor();
5427
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00005428 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00005429
5430 // Translate the given source location to make it point at the beginning of
5431 // the token under the cursor.
5432 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
5433 CXXUnit->getASTContext().getLangOpts());
5434
5435 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
5436 if (SLoc.isValid()) {
5437 GetCursorData ResultData(CXXUnit->getSourceManager(), SLoc, Result);
5438 CursorVisitor CursorVis(TU, GetCursorVisitor, &ResultData,
5439 /*VisitPreprocessorLast=*/true,
5440 /*VisitIncludedEntities=*/false,
5441 SourceLocation(SLoc));
5442 CursorVis.visitFileRegion();
5443 }
5444
5445 return Result;
5446}
5447
5448static SourceRange getRawCursorExtent(CXCursor C) {
5449 if (clang_isReference(C.kind)) {
5450 switch (C.kind) {
5451 case CXCursor_ObjCSuperClassRef:
5452 return getCursorObjCSuperClassRef(C).second;
5453
5454 case CXCursor_ObjCProtocolRef:
5455 return getCursorObjCProtocolRef(C).second;
5456
5457 case CXCursor_ObjCClassRef:
5458 return getCursorObjCClassRef(C).second;
5459
5460 case CXCursor_TypeRef:
5461 return getCursorTypeRef(C).second;
5462
5463 case CXCursor_TemplateRef:
5464 return getCursorTemplateRef(C).second;
5465
5466 case CXCursor_NamespaceRef:
5467 return getCursorNamespaceRef(C).second;
5468
5469 case CXCursor_MemberRef:
5470 return getCursorMemberRef(C).second;
5471
5472 case CXCursor_CXXBaseSpecifier:
5473 return getCursorCXXBaseSpecifier(C)->getSourceRange();
5474
5475 case CXCursor_LabelRef:
5476 return getCursorLabelRef(C).second;
5477
5478 case CXCursor_OverloadedDeclRef:
5479 return getCursorOverloadedDeclRef(C).second;
5480
5481 case CXCursor_VariableRef:
5482 return getCursorVariableRef(C).second;
5483
5484 default:
5485 // FIXME: Need a way to enumerate all non-reference cases.
5486 llvm_unreachable("Missed a reference kind");
5487 }
5488 }
5489
5490 if (clang_isExpression(C.kind))
5491 return getCursorExpr(C)->getSourceRange();
5492
5493 if (clang_isStatement(C.kind))
5494 return getCursorStmt(C)->getSourceRange();
5495
5496 if (clang_isAttribute(C.kind))
5497 return getCursorAttr(C)->getRange();
5498
5499 if (C.kind == CXCursor_PreprocessingDirective)
5500 return cxcursor::getCursorPreprocessingDirective(C);
5501
5502 if (C.kind == CXCursor_MacroExpansion) {
5503 ASTUnit *TU = getCursorASTUnit(C);
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00005504 SourceRange Range = cxcursor::getCursorMacroExpansion(C).getSourceRange();
Guy Benyei11169dd2012-12-18 14:30:41 +00005505 return TU->mapRangeFromPreamble(Range);
5506 }
5507
5508 if (C.kind == CXCursor_MacroDefinition) {
5509 ASTUnit *TU = getCursorASTUnit(C);
5510 SourceRange Range = cxcursor::getCursorMacroDefinition(C)->getSourceRange();
5511 return TU->mapRangeFromPreamble(Range);
5512 }
5513
5514 if (C.kind == CXCursor_InclusionDirective) {
5515 ASTUnit *TU = getCursorASTUnit(C);
5516 SourceRange Range = cxcursor::getCursorInclusionDirective(C)->getSourceRange();
5517 return TU->mapRangeFromPreamble(Range);
5518 }
5519
5520 if (C.kind == CXCursor_TranslationUnit) {
5521 ASTUnit *TU = getCursorASTUnit(C);
5522 FileID MainID = TU->getSourceManager().getMainFileID();
5523 SourceLocation Start = TU->getSourceManager().getLocForStartOfFile(MainID);
5524 SourceLocation End = TU->getSourceManager().getLocForEndOfFile(MainID);
5525 return SourceRange(Start, End);
5526 }
5527
5528 if (clang_isDeclaration(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005529 const Decl *D = cxcursor::getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005530 if (!D)
5531 return SourceRange();
5532
5533 SourceRange R = D->getSourceRange();
5534 // FIXME: Multiple variables declared in a single declaration
5535 // currently lack the information needed to correctly determine their
5536 // ranges when accounting for the type-specifier. We use context
5537 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
5538 // and if so, whether it is the first decl.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005539 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005540 if (!cxcursor::isFirstInDeclGroup(C))
5541 R.setBegin(VD->getLocation());
5542 }
5543 return R;
5544 }
5545 return SourceRange();
5546}
5547
5548/// \brief Retrieves the "raw" cursor extent, which is then extended to include
5549/// the decl-specifier-seq for declarations.
5550static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr) {
5551 if (clang_isDeclaration(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005552 const Decl *D = cxcursor::getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005553 if (!D)
5554 return SourceRange();
5555
5556 SourceRange R = D->getSourceRange();
5557
5558 // Adjust the start of the location for declarations preceded by
5559 // declaration specifiers.
5560 SourceLocation StartLoc;
5561 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
5562 if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
5563 StartLoc = TI->getTypeLoc().getLocStart();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005564 } else if (const TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005565 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
5566 StartLoc = TI->getTypeLoc().getLocStart();
5567 }
5568
5569 if (StartLoc.isValid() && R.getBegin().isValid() &&
5570 SrcMgr.isBeforeInTranslationUnit(StartLoc, R.getBegin()))
5571 R.setBegin(StartLoc);
5572
5573 // FIXME: Multiple variables declared in a single declaration
5574 // currently lack the information needed to correctly determine their
5575 // ranges when accounting for the type-specifier. We use context
5576 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
5577 // and if so, whether it is the first decl.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005578 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005579 if (!cxcursor::isFirstInDeclGroup(C))
5580 R.setBegin(VD->getLocation());
5581 }
5582
5583 return R;
5584 }
5585
5586 return getRawCursorExtent(C);
5587}
5588
Guy Benyei11169dd2012-12-18 14:30:41 +00005589CXSourceRange clang_getCursorExtent(CXCursor C) {
5590 SourceRange R = getRawCursorExtent(C);
5591 if (R.isInvalid())
5592 return clang_getNullRange();
5593
5594 return cxloc::translateSourceRange(getCursorContext(C), R);
5595}
5596
5597CXCursor clang_getCursorReferenced(CXCursor C) {
5598 if (clang_isInvalid(C.kind))
5599 return clang_getNullCursor();
5600
5601 CXTranslationUnit tu = getCursorTU(C);
5602 if (clang_isDeclaration(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005603 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005604 if (!D)
5605 return clang_getNullCursor();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005606 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00005607 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), tu);
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005608 if (const ObjCPropertyImplDecl *PropImpl =
5609 dyn_cast<ObjCPropertyImplDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00005610 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
5611 return MakeCXCursor(Property, tu);
5612
5613 return C;
5614 }
5615
5616 if (clang_isExpression(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005617 const Expr *E = getCursorExpr(C);
5618 const Decl *D = getDeclFromExpr(E);
Guy Benyei11169dd2012-12-18 14:30:41 +00005619 if (D) {
5620 CXCursor declCursor = MakeCXCursor(D, tu);
5621 declCursor = getSelectorIdentifierCursor(getSelectorIdentifierIndex(C),
5622 declCursor);
5623 return declCursor;
5624 }
5625
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005626 if (const OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00005627 return MakeCursorOverloadedDeclRef(Ovl, tu);
5628
5629 return clang_getNullCursor();
5630 }
5631
5632 if (clang_isStatement(C.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00005633 const Stmt *S = getCursorStmt(C);
5634 if (const GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
Guy Benyei11169dd2012-12-18 14:30:41 +00005635 if (LabelDecl *label = Goto->getLabel())
5636 if (LabelStmt *labelS = label->getStmt())
5637 return MakeCXCursor(labelS, getCursorDecl(C), tu);
5638
5639 return clang_getNullCursor();
5640 }
Richard Smith66a81862015-05-04 02:25:31 +00005641
Guy Benyei11169dd2012-12-18 14:30:41 +00005642 if (C.kind == CXCursor_MacroExpansion) {
Richard Smith66a81862015-05-04 02:25:31 +00005643 if (const MacroDefinitionRecord *Def =
5644 getCursorMacroExpansion(C).getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00005645 return MakeMacroDefinitionCursor(Def, tu);
5646 }
5647
5648 if (!clang_isReference(C.kind))
5649 return clang_getNullCursor();
5650
5651 switch (C.kind) {
5652 case CXCursor_ObjCSuperClassRef:
5653 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, tu);
5654
5655 case CXCursor_ObjCProtocolRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005656 const ObjCProtocolDecl *Prot = getCursorObjCProtocolRef(C).first;
5657 if (const ObjCProtocolDecl *Def = Prot->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00005658 return MakeCXCursor(Def, tu);
5659
5660 return MakeCXCursor(Prot, tu);
5661 }
5662
5663 case CXCursor_ObjCClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005664 const ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
5665 if (const ObjCInterfaceDecl *Def = Class->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00005666 return MakeCXCursor(Def, tu);
5667
5668 return MakeCXCursor(Class, tu);
5669 }
5670
5671 case CXCursor_TypeRef:
5672 return MakeCXCursor(getCursorTypeRef(C).first, tu );
5673
5674 case CXCursor_TemplateRef:
5675 return MakeCXCursor(getCursorTemplateRef(C).first, tu );
5676
5677 case CXCursor_NamespaceRef:
5678 return MakeCXCursor(getCursorNamespaceRef(C).first, tu );
5679
5680 case CXCursor_MemberRef:
5681 return MakeCXCursor(getCursorMemberRef(C).first, tu );
5682
5683 case CXCursor_CXXBaseSpecifier: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005684 const CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005685 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
5686 tu ));
5687 }
5688
5689 case CXCursor_LabelRef:
5690 // FIXME: We end up faking the "parent" declaration here because we
5691 // don't want to make CXCursor larger.
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00005692 return MakeCXCursor(getCursorLabelRef(C).first,
5693 cxtu::getASTUnit(tu)->getASTContext()
5694 .getTranslationUnitDecl(),
Guy Benyei11169dd2012-12-18 14:30:41 +00005695 tu);
5696
5697 case CXCursor_OverloadedDeclRef:
5698 return C;
5699
5700 case CXCursor_VariableRef:
5701 return MakeCXCursor(getCursorVariableRef(C).first, tu);
5702
5703 default:
5704 // We would prefer to enumerate all non-reference cursor kinds here.
5705 llvm_unreachable("Unhandled reference cursor kind");
5706 }
5707}
5708
5709CXCursor clang_getCursorDefinition(CXCursor C) {
5710 if (clang_isInvalid(C.kind))
5711 return clang_getNullCursor();
5712
5713 CXTranslationUnit TU = getCursorTU(C);
5714
5715 bool WasReference = false;
5716 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
5717 C = clang_getCursorReferenced(C);
5718 WasReference = true;
5719 }
5720
5721 if (C.kind == CXCursor_MacroExpansion)
5722 return clang_getCursorReferenced(C);
5723
5724 if (!clang_isDeclaration(C.kind))
5725 return clang_getNullCursor();
5726
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005727 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005728 if (!D)
5729 return clang_getNullCursor();
5730
5731 switch (D->getKind()) {
5732 // Declaration kinds that don't really separate the notions of
5733 // declaration and definition.
5734 case Decl::Namespace:
5735 case Decl::Typedef:
5736 case Decl::TypeAlias:
5737 case Decl::TypeAliasTemplate:
5738 case Decl::TemplateTypeParm:
5739 case Decl::EnumConstant:
5740 case Decl::Field:
Richard Smithbdb84f32016-07-22 23:36:59 +00005741 case Decl::Binding:
John McCall5e77d762013-04-16 07:28:30 +00005742 case Decl::MSProperty:
Guy Benyei11169dd2012-12-18 14:30:41 +00005743 case Decl::IndirectField:
5744 case Decl::ObjCIvar:
5745 case Decl::ObjCAtDefsField:
5746 case Decl::ImplicitParam:
5747 case Decl::ParmVar:
5748 case Decl::NonTypeTemplateParm:
5749 case Decl::TemplateTemplateParm:
5750 case Decl::ObjCCategoryImpl:
5751 case Decl::ObjCImplementation:
5752 case Decl::AccessSpec:
5753 case Decl::LinkageSpec:
Richard Smith8df390f2016-09-08 23:14:54 +00005754 case Decl::Export:
Guy Benyei11169dd2012-12-18 14:30:41 +00005755 case Decl::ObjCPropertyImpl:
5756 case Decl::FileScopeAsm:
5757 case Decl::StaticAssert:
5758 case Decl::Block:
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00005759 case Decl::Captured:
Alexey Bataev4244be22016-02-11 05:35:55 +00005760 case Decl::OMPCapturedExpr:
Guy Benyei11169dd2012-12-18 14:30:41 +00005761 case Decl::Label: // FIXME: Is this right??
5762 case Decl::ClassScopeFunctionSpecialization:
5763 case Decl::Import:
Alexey Bataeva769e072013-03-22 06:34:35 +00005764 case Decl::OMPThreadPrivate:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00005765 case Decl::OMPDeclareReduction:
Douglas Gregor85f3f952015-07-07 03:57:15 +00005766 case Decl::ObjCTypeParam:
David Majnemerd9b1a4f2015-11-04 03:40:30 +00005767 case Decl::BuiltinTemplate:
Nico Weber66220292016-03-02 17:28:48 +00005768 case Decl::PragmaComment:
Nico Webercbbaeb12016-03-02 19:28:54 +00005769 case Decl::PragmaDetectMismatch:
Richard Smith151c4562016-12-20 21:35:28 +00005770 case Decl::UsingPack:
Guy Benyei11169dd2012-12-18 14:30:41 +00005771 return C;
5772
5773 // Declaration kinds that don't make any sense here, but are
5774 // nonetheless harmless.
David Blaikief005d3c2013-02-22 17:44:58 +00005775 case Decl::Empty:
Guy Benyei11169dd2012-12-18 14:30:41 +00005776 case Decl::TranslationUnit:
Richard Smithf19e1272015-03-07 00:04:49 +00005777 case Decl::ExternCContext:
Guy Benyei11169dd2012-12-18 14:30:41 +00005778 break;
5779
5780 // Declaration kinds for which the definition is not resolvable.
5781 case Decl::UnresolvedUsingTypename:
5782 case Decl::UnresolvedUsingValue:
5783 break;
5784
5785 case Decl::UsingDirective:
5786 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
5787 TU);
5788
5789 case Decl::NamespaceAlias:
5790 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), TU);
5791
5792 case Decl::Enum:
5793 case Decl::Record:
5794 case Decl::CXXRecord:
5795 case Decl::ClassTemplateSpecialization:
5796 case Decl::ClassTemplatePartialSpecialization:
5797 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
5798 return MakeCXCursor(Def, TU);
5799 return clang_getNullCursor();
5800
5801 case Decl::Function:
5802 case Decl::CXXMethod:
5803 case Decl::CXXConstructor:
5804 case Decl::CXXDestructor:
5805 case Decl::CXXConversion: {
Craig Topper69186e72014-06-08 08:38:04 +00005806 const FunctionDecl *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005807 if (cast<FunctionDecl>(D)->getBody(Def))
Dmitri Gribenko9c256e32013-01-14 00:46:27 +00005808 return MakeCXCursor(Def, TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00005809 return clang_getNullCursor();
5810 }
5811
Larisse Voufo39a1e502013-08-06 01:03:05 +00005812 case Decl::Var:
5813 case Decl::VarTemplateSpecialization:
Richard Smithbdb84f32016-07-22 23:36:59 +00005814 case Decl::VarTemplatePartialSpecialization:
5815 case Decl::Decomposition: {
Guy Benyei11169dd2012-12-18 14:30:41 +00005816 // Ask the variable if it has a definition.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005817 if (const VarDecl *Def = cast<VarDecl>(D)->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00005818 return MakeCXCursor(Def, TU);
5819 return clang_getNullCursor();
5820 }
5821
5822 case Decl::FunctionTemplate: {
Craig Topper69186e72014-06-08 08:38:04 +00005823 const FunctionDecl *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005824 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
5825 return MakeCXCursor(Def->getDescribedFunctionTemplate(), TU);
5826 return clang_getNullCursor();
5827 }
5828
5829 case Decl::ClassTemplate: {
5830 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
5831 ->getDefinition())
5832 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
5833 TU);
5834 return clang_getNullCursor();
5835 }
5836
Larisse Voufo39a1e502013-08-06 01:03:05 +00005837 case Decl::VarTemplate: {
5838 if (VarDecl *Def =
5839 cast<VarTemplateDecl>(D)->getTemplatedDecl()->getDefinition())
5840 return MakeCXCursor(cast<VarDecl>(Def)->getDescribedVarTemplate(), TU);
5841 return clang_getNullCursor();
5842 }
5843
Guy Benyei11169dd2012-12-18 14:30:41 +00005844 case Decl::Using:
5845 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
5846 D->getLocation(), TU);
5847
5848 case Decl::UsingShadow:
Richard Smith5179eb72016-06-28 19:03:57 +00005849 case Decl::ConstructorUsingShadow:
Guy Benyei11169dd2012-12-18 14:30:41 +00005850 return clang_getCursorDefinition(
5851 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
5852 TU));
5853
5854 case Decl::ObjCMethod: {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005855 const ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00005856 if (Method->isThisDeclarationADefinition())
5857 return C;
5858
5859 // Dig out the method definition in the associated
5860 // @implementation, if we have it.
5861 // FIXME: The ASTs should make finding the definition easier.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005862 if (const ObjCInterfaceDecl *Class
Guy Benyei11169dd2012-12-18 14:30:41 +00005863 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
5864 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
5865 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
5866 Method->isInstanceMethod()))
5867 if (Def->isThisDeclarationADefinition())
5868 return MakeCXCursor(Def, TU);
5869
5870 return clang_getNullCursor();
5871 }
5872
5873 case Decl::ObjCCategory:
5874 if (ObjCCategoryImplDecl *Impl
5875 = cast<ObjCCategoryDecl>(D)->getImplementation())
5876 return MakeCXCursor(Impl, TU);
5877 return clang_getNullCursor();
5878
5879 case Decl::ObjCProtocol:
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005880 if (const ObjCProtocolDecl *Def = cast<ObjCProtocolDecl>(D)->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00005881 return MakeCXCursor(Def, TU);
5882 return clang_getNullCursor();
5883
5884 case Decl::ObjCInterface: {
5885 // There are two notions of a "definition" for an Objective-C
5886 // class: the interface and its implementation. When we resolved a
5887 // reference to an Objective-C class, produce the @interface as
5888 // the definition; when we were provided with the interface,
5889 // produce the @implementation as the definition.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005890 const ObjCInterfaceDecl *IFace = cast<ObjCInterfaceDecl>(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00005891 if (WasReference) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005892 if (const ObjCInterfaceDecl *Def = IFace->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00005893 return MakeCXCursor(Def, TU);
5894 } else if (ObjCImplementationDecl *Impl = IFace->getImplementation())
5895 return MakeCXCursor(Impl, TU);
5896 return clang_getNullCursor();
5897 }
5898
5899 case Decl::ObjCProperty:
5900 // FIXME: We don't really know where to find the
5901 // ObjCPropertyImplDecls that implement this property.
5902 return clang_getNullCursor();
5903
5904 case Decl::ObjCCompatibleAlias:
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005905 if (const ObjCInterfaceDecl *Class
Guy Benyei11169dd2012-12-18 14:30:41 +00005906 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005907 if (const ObjCInterfaceDecl *Def = Class->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00005908 return MakeCXCursor(Def, TU);
5909
5910 return clang_getNullCursor();
5911
5912 case Decl::Friend:
5913 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
5914 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
5915 return clang_getNullCursor();
5916
5917 case Decl::FriendTemplate:
5918 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
5919 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
5920 return clang_getNullCursor();
5921 }
5922
5923 return clang_getNullCursor();
5924}
5925
5926unsigned clang_isCursorDefinition(CXCursor C) {
5927 if (!clang_isDeclaration(C.kind))
5928 return 0;
5929
5930 return clang_getCursorDefinition(C) == C;
5931}
5932
5933CXCursor clang_getCanonicalCursor(CXCursor C) {
5934 if (!clang_isDeclaration(C.kind))
5935 return C;
5936
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005937 if (const Decl *D = getCursorDecl(C)) {
5938 if (const ObjCCategoryImplDecl *CatImplD = dyn_cast<ObjCCategoryImplDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00005939 if (ObjCCategoryDecl *CatD = CatImplD->getCategoryDecl())
5940 return MakeCXCursor(CatD, getCursorTU(C));
5941
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005942 if (const ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
5943 if (const ObjCInterfaceDecl *IFD = ImplD->getClassInterface())
Guy Benyei11169dd2012-12-18 14:30:41 +00005944 return MakeCXCursor(IFD, getCursorTU(C));
5945
5946 return MakeCXCursor(D->getCanonicalDecl(), getCursorTU(C));
5947 }
5948
5949 return C;
5950}
5951
5952int clang_Cursor_getObjCSelectorIndex(CXCursor cursor) {
5953 return cxcursor::getSelectorIdentifierIndexAndLoc(cursor).first;
5954}
5955
5956unsigned clang_getNumOverloadedDecls(CXCursor C) {
5957 if (C.kind != CXCursor_OverloadedDeclRef)
5958 return 0;
5959
5960 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005961 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
Guy Benyei11169dd2012-12-18 14:30:41 +00005962 return E->getNumDecls();
5963
5964 if (OverloadedTemplateStorage *S
5965 = Storage.dyn_cast<OverloadedTemplateStorage*>())
5966 return S->size();
5967
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005968 const Decl *D = Storage.get<const Decl *>();
5969 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00005970 return Using->shadow_size();
5971
5972 return 0;
5973}
5974
5975CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
5976 if (cursor.kind != CXCursor_OverloadedDeclRef)
5977 return clang_getNullCursor();
5978
5979 if (index >= clang_getNumOverloadedDecls(cursor))
5980 return clang_getNullCursor();
5981
5982 CXTranslationUnit TU = getCursorTU(cursor);
5983 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005984 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
Guy Benyei11169dd2012-12-18 14:30:41 +00005985 return MakeCXCursor(E->decls_begin()[index], TU);
5986
5987 if (OverloadedTemplateStorage *S
5988 = Storage.dyn_cast<OverloadedTemplateStorage*>())
5989 return MakeCXCursor(S->begin()[index], TU);
5990
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005991 const Decl *D = Storage.get<const Decl *>();
5992 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005993 // FIXME: This is, unfortunately, linear time.
5994 UsingDecl::shadow_iterator Pos = Using->shadow_begin();
5995 std::advance(Pos, index);
5996 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), TU);
5997 }
5998
5999 return clang_getNullCursor();
6000}
6001
6002void clang_getDefinitionSpellingAndExtent(CXCursor C,
6003 const char **startBuf,
6004 const char **endBuf,
6005 unsigned *startLine,
6006 unsigned *startColumn,
6007 unsigned *endLine,
6008 unsigned *endColumn) {
6009 assert(getCursorDecl(C) && "CXCursor has null decl");
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006010 const FunctionDecl *FD = dyn_cast<FunctionDecl>(getCursorDecl(C));
Guy Benyei11169dd2012-12-18 14:30:41 +00006011 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
6012
6013 SourceManager &SM = FD->getASTContext().getSourceManager();
6014 *startBuf = SM.getCharacterData(Body->getLBracLoc());
6015 *endBuf = SM.getCharacterData(Body->getRBracLoc());
6016 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
6017 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
6018 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
6019 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
6020}
6021
6022
6023CXSourceRange clang_getCursorReferenceNameRange(CXCursor C, unsigned NameFlags,
6024 unsigned PieceIndex) {
6025 RefNamePieces Pieces;
6026
6027 switch (C.kind) {
6028 case CXCursor_MemberRefExpr:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006029 if (const MemberExpr *E = dyn_cast<MemberExpr>(getCursorExpr(C)))
Guy Benyei11169dd2012-12-18 14:30:41 +00006030 Pieces = buildPieces(NameFlags, true, E->getMemberNameInfo(),
6031 E->getQualifierLoc().getSourceRange());
6032 break;
6033
6034 case CXCursor_DeclRefExpr:
James Y Knight04ec5bf2015-12-24 02:59:37 +00006035 if (const DeclRefExpr *E = dyn_cast<DeclRefExpr>(getCursorExpr(C))) {
6036 SourceRange TemplateArgLoc(E->getLAngleLoc(), E->getRAngleLoc());
6037 Pieces =
6038 buildPieces(NameFlags, false, E->getNameInfo(),
6039 E->getQualifierLoc().getSourceRange(), &TemplateArgLoc);
6040 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006041 break;
6042
6043 case CXCursor_CallExpr:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006044 if (const CXXOperatorCallExpr *OCE =
Guy Benyei11169dd2012-12-18 14:30:41 +00006045 dyn_cast<CXXOperatorCallExpr>(getCursorExpr(C))) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006046 const Expr *Callee = OCE->getCallee();
6047 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Callee))
Guy Benyei11169dd2012-12-18 14:30:41 +00006048 Callee = ICE->getSubExpr();
6049
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006050 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Callee))
Guy Benyei11169dd2012-12-18 14:30:41 +00006051 Pieces = buildPieces(NameFlags, false, DRE->getNameInfo(),
6052 DRE->getQualifierLoc().getSourceRange());
6053 }
6054 break;
6055
6056 default:
6057 break;
6058 }
6059
6060 if (Pieces.empty()) {
6061 if (PieceIndex == 0)
6062 return clang_getCursorExtent(C);
6063 } else if (PieceIndex < Pieces.size()) {
6064 SourceRange R = Pieces[PieceIndex];
6065 if (R.isValid())
6066 return cxloc::translateSourceRange(getCursorContext(C), R);
6067 }
6068
6069 return clang_getNullRange();
6070}
6071
6072void clang_enableStackTraces(void) {
Richard Smithdfed58a2016-06-09 00:53:41 +00006073 // FIXME: Provide an argv0 here so we can find llvm-symbolizer.
6074 llvm::sys::PrintStackTraceOnErrorSignal(StringRef());
Guy Benyei11169dd2012-12-18 14:30:41 +00006075}
6076
6077void clang_executeOnThread(void (*fn)(void*), void *user_data,
6078 unsigned stack_size) {
6079 llvm::llvm_execute_on_thread(fn, user_data, stack_size);
6080}
6081
Guy Benyei11169dd2012-12-18 14:30:41 +00006082//===----------------------------------------------------------------------===//
6083// Token-based Operations.
6084//===----------------------------------------------------------------------===//
6085
6086/* CXToken layout:
6087 * int_data[0]: a CXTokenKind
6088 * int_data[1]: starting token location
6089 * int_data[2]: token length
6090 * int_data[3]: reserved
6091 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
6092 * otherwise unused.
6093 */
Guy Benyei11169dd2012-12-18 14:30:41 +00006094CXTokenKind clang_getTokenKind(CXToken CXTok) {
6095 return static_cast<CXTokenKind>(CXTok.int_data[0]);
6096}
6097
6098CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
6099 switch (clang_getTokenKind(CXTok)) {
6100 case CXToken_Identifier:
6101 case CXToken_Keyword:
6102 // We know we have an IdentifierInfo*, so use that.
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00006103 return cxstring::createRef(static_cast<IdentifierInfo *>(CXTok.ptr_data)
Guy Benyei11169dd2012-12-18 14:30:41 +00006104 ->getNameStart());
6105
6106 case CXToken_Literal: {
6107 // We have stashed the starting pointer in the ptr_data field. Use it.
6108 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00006109 return cxstring::createDup(StringRef(Text, CXTok.int_data[2]));
Guy Benyei11169dd2012-12-18 14:30:41 +00006110 }
6111
6112 case CXToken_Punctuation:
6113 case CXToken_Comment:
6114 break;
6115 }
6116
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006117 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006118 LOG_BAD_TU(TU);
6119 return cxstring::createEmpty();
6120 }
6121
Guy Benyei11169dd2012-12-18 14:30:41 +00006122 // We have to find the starting buffer pointer the hard way, by
6123 // deconstructing the source location.
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006124 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006125 if (!CXXUnit)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00006126 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00006127
6128 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
6129 std::pair<FileID, unsigned> LocInfo
6130 = CXXUnit->getSourceManager().getDecomposedSpellingLoc(Loc);
6131 bool Invalid = false;
6132 StringRef Buffer
6133 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
6134 if (Invalid)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00006135 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00006136
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00006137 return cxstring::createDup(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Guy Benyei11169dd2012-12-18 14:30:41 +00006138}
6139
6140CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006141 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006142 LOG_BAD_TU(TU);
6143 return clang_getNullLocation();
6144 }
6145
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006146 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006147 if (!CXXUnit)
6148 return clang_getNullLocation();
6149
6150 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
6151 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
6152}
6153
6154CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006155 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006156 LOG_BAD_TU(TU);
6157 return clang_getNullRange();
6158 }
6159
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006160 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006161 if (!CXXUnit)
6162 return clang_getNullRange();
6163
6164 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
6165 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
6166}
6167
6168static void getTokens(ASTUnit *CXXUnit, SourceRange Range,
6169 SmallVectorImpl<CXToken> &CXTokens) {
6170 SourceManager &SourceMgr = CXXUnit->getSourceManager();
6171 std::pair<FileID, unsigned> BeginLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00006172 = SourceMgr.getDecomposedSpellingLoc(Range.getBegin());
Guy Benyei11169dd2012-12-18 14:30:41 +00006173 std::pair<FileID, unsigned> EndLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00006174 = SourceMgr.getDecomposedSpellingLoc(Range.getEnd());
Guy Benyei11169dd2012-12-18 14:30:41 +00006175
6176 // Cannot tokenize across files.
6177 if (BeginLocInfo.first != EndLocInfo.first)
6178 return;
6179
6180 // Create a lexer
6181 bool Invalid = false;
6182 StringRef Buffer
6183 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
6184 if (Invalid)
6185 return;
6186
6187 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
6188 CXXUnit->getASTContext().getLangOpts(),
6189 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
6190 Lex.SetCommentRetentionState(true);
6191
6192 // Lex tokens until we hit the end of the range.
6193 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
6194 Token Tok;
6195 bool previousWasAt = false;
6196 do {
6197 // Lex the next token
6198 Lex.LexFromRawLexer(Tok);
6199 if (Tok.is(tok::eof))
6200 break;
6201
6202 // Initialize the CXToken.
6203 CXToken CXTok;
6204
6205 // - Common fields
6206 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
6207 CXTok.int_data[2] = Tok.getLength();
6208 CXTok.int_data[3] = 0;
6209
6210 // - Kind-specific fields
6211 if (Tok.isLiteral()) {
6212 CXTok.int_data[0] = CXToken_Literal;
Dmitri Gribenkof9304482013-01-23 15:56:07 +00006213 CXTok.ptr_data = const_cast<char *>(Tok.getLiteralData());
Guy Benyei11169dd2012-12-18 14:30:41 +00006214 } else if (Tok.is(tok::raw_identifier)) {
6215 // Lookup the identifier to determine whether we have a keyword.
6216 IdentifierInfo *II
6217 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok);
6218
6219 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
6220 CXTok.int_data[0] = CXToken_Keyword;
6221 }
6222 else {
6223 CXTok.int_data[0] = Tok.is(tok::identifier)
6224 ? CXToken_Identifier
6225 : CXToken_Keyword;
6226 }
6227 CXTok.ptr_data = II;
6228 } else if (Tok.is(tok::comment)) {
6229 CXTok.int_data[0] = CXToken_Comment;
Craig Topper69186e72014-06-08 08:38:04 +00006230 CXTok.ptr_data = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006231 } else {
6232 CXTok.int_data[0] = CXToken_Punctuation;
Craig Topper69186e72014-06-08 08:38:04 +00006233 CXTok.ptr_data = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006234 }
6235 CXTokens.push_back(CXTok);
6236 previousWasAt = Tok.is(tok::at);
Argyrios Kyrtzidisc7c6a072016-11-09 23:58:39 +00006237 } while (Lex.getBufferLocation() < EffectiveBufferEnd);
Guy Benyei11169dd2012-12-18 14:30:41 +00006238}
6239
6240void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
6241 CXToken **Tokens, unsigned *NumTokens) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00006242 LOG_FUNC_SECTION {
6243 *Log << TU << ' ' << Range;
6244 }
6245
Guy Benyei11169dd2012-12-18 14:30:41 +00006246 if (Tokens)
Craig Topper69186e72014-06-08 08:38:04 +00006247 *Tokens = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006248 if (NumTokens)
6249 *NumTokens = 0;
6250
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006251 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006252 LOG_BAD_TU(TU);
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00006253 return;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006254 }
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00006255
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006256 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006257 if (!CXXUnit || !Tokens || !NumTokens)
6258 return;
6259
6260 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
6261
6262 SourceRange R = cxloc::translateCXSourceRange(Range);
6263 if (R.isInvalid())
6264 return;
6265
6266 SmallVector<CXToken, 32> CXTokens;
6267 getTokens(CXXUnit, R, CXTokens);
6268
6269 if (CXTokens.empty())
6270 return;
6271
6272 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
6273 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
6274 *NumTokens = CXTokens.size();
6275}
6276
6277void clang_disposeTokens(CXTranslationUnit TU,
6278 CXToken *Tokens, unsigned NumTokens) {
6279 free(Tokens);
6280}
6281
Guy Benyei11169dd2012-12-18 14:30:41 +00006282//===----------------------------------------------------------------------===//
6283// Token annotation APIs.
6284//===----------------------------------------------------------------------===//
6285
Guy Benyei11169dd2012-12-18 14:30:41 +00006286static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
6287 CXCursor parent,
6288 CXClientData client_data);
6289static bool AnnotateTokensPostChildrenVisitor(CXCursor cursor,
6290 CXClientData client_data);
6291
6292namespace {
6293class AnnotateTokensWorker {
Guy Benyei11169dd2012-12-18 14:30:41 +00006294 CXToken *Tokens;
6295 CXCursor *Cursors;
6296 unsigned NumTokens;
6297 unsigned TokIdx;
6298 unsigned PreprocessingTokIdx;
6299 CursorVisitor AnnotateVis;
6300 SourceManager &SrcMgr;
6301 bool HasContextSensitiveKeywords;
6302
6303 struct PostChildrenInfo {
6304 CXCursor Cursor;
6305 SourceRange CursorRange;
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006306 unsigned BeforeReachingCursorIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00006307 unsigned BeforeChildrenTokenIdx;
6308 };
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006309 SmallVector<PostChildrenInfo, 8> PostChildrenInfos;
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006310
6311 CXToken &getTok(unsigned Idx) {
6312 assert(Idx < NumTokens);
6313 return Tokens[Idx];
6314 }
6315 const CXToken &getTok(unsigned Idx) const {
6316 assert(Idx < NumTokens);
6317 return Tokens[Idx];
6318 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006319 bool MoreTokens() const { return TokIdx < NumTokens; }
6320 unsigned NextToken() const { return TokIdx; }
6321 void AdvanceToken() { ++TokIdx; }
6322 SourceLocation GetTokenLoc(unsigned tokI) {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006323 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[1]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006324 }
6325 bool isFunctionMacroToken(unsigned tokI) const {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006326 return getTok(tokI).int_data[3] != 0;
Guy Benyei11169dd2012-12-18 14:30:41 +00006327 }
6328 SourceLocation getFunctionMacroTokenLoc(unsigned tokI) const {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006329 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[3]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006330 }
6331
6332 void annotateAndAdvanceTokens(CXCursor, RangeComparisonResult, SourceRange);
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006333 bool annotateAndAdvanceFunctionMacroTokens(CXCursor, RangeComparisonResult,
Guy Benyei11169dd2012-12-18 14:30:41 +00006334 SourceRange);
6335
6336public:
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006337 AnnotateTokensWorker(CXToken *tokens, CXCursor *cursors, unsigned numTokens,
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006338 CXTranslationUnit TU, SourceRange RegionOfInterest)
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006339 : Tokens(tokens), Cursors(cursors),
Guy Benyei11169dd2012-12-18 14:30:41 +00006340 NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006341 AnnotateVis(TU,
Guy Benyei11169dd2012-12-18 14:30:41 +00006342 AnnotateTokensVisitor, this,
6343 /*VisitPreprocessorLast=*/true,
6344 /*VisitIncludedEntities=*/false,
6345 RegionOfInterest,
6346 /*VisitDeclsOnly=*/false,
6347 AnnotateTokensPostChildrenVisitor),
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006348 SrcMgr(cxtu::getASTUnit(TU)->getSourceManager()),
Guy Benyei11169dd2012-12-18 14:30:41 +00006349 HasContextSensitiveKeywords(false) { }
6350
6351 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
6352 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
6353 bool postVisitChildren(CXCursor cursor);
6354 void AnnotateTokens();
6355
6356 /// \brief Determine whether the annotator saw any cursors that have
6357 /// context-sensitive keywords.
6358 bool hasContextSensitiveKeywords() const {
6359 return HasContextSensitiveKeywords;
6360 }
6361
6362 ~AnnotateTokensWorker() {
6363 assert(PostChildrenInfos.empty());
6364 }
6365};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006366}
Guy Benyei11169dd2012-12-18 14:30:41 +00006367
6368void AnnotateTokensWorker::AnnotateTokens() {
6369 // Walk the AST within the region of interest, annotating tokens
6370 // along the way.
6371 AnnotateVis.visitFileRegion();
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006372}
Guy Benyei11169dd2012-12-18 14:30:41 +00006373
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006374static inline void updateCursorAnnotation(CXCursor &Cursor,
6375 const CXCursor &updateC) {
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006376 if (clang_isInvalid(updateC.kind) || !clang_isInvalid(Cursor.kind))
Guy Benyei11169dd2012-12-18 14:30:41 +00006377 return;
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006378 Cursor = updateC;
Guy Benyei11169dd2012-12-18 14:30:41 +00006379}
6380
6381/// \brief It annotates and advances tokens with a cursor until the comparison
6382//// between the cursor location and the source range is the same as
6383/// \arg compResult.
6384///
6385/// Pass RangeBefore to annotate tokens with a cursor until a range is reached.
6386/// Pass RangeOverlap to annotate tokens inside a range.
6387void AnnotateTokensWorker::annotateAndAdvanceTokens(CXCursor updateC,
6388 RangeComparisonResult compResult,
6389 SourceRange range) {
6390 while (MoreTokens()) {
6391 const unsigned I = NextToken();
6392 if (isFunctionMacroToken(I))
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006393 if (!annotateAndAdvanceFunctionMacroTokens(updateC, compResult, range))
6394 return;
Guy Benyei11169dd2012-12-18 14:30:41 +00006395
6396 SourceLocation TokLoc = GetTokenLoc(I);
6397 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006398 updateCursorAnnotation(Cursors[I], updateC);
Guy Benyei11169dd2012-12-18 14:30:41 +00006399 AdvanceToken();
6400 continue;
6401 }
6402 break;
6403 }
6404}
6405
6406/// \brief Special annotation handling for macro argument tokens.
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006407/// \returns true if it advanced beyond all macro tokens, false otherwise.
6408bool AnnotateTokensWorker::annotateAndAdvanceFunctionMacroTokens(
Guy Benyei11169dd2012-12-18 14:30:41 +00006409 CXCursor updateC,
6410 RangeComparisonResult compResult,
6411 SourceRange range) {
6412 assert(MoreTokens());
6413 assert(isFunctionMacroToken(NextToken()) &&
6414 "Should be called only for macro arg tokens");
6415
6416 // This works differently than annotateAndAdvanceTokens; because expanded
6417 // macro arguments can have arbitrary translation-unit source order, we do not
6418 // advance the token index one by one until a token fails the range test.
6419 // We only advance once past all of the macro arg tokens if all of them
6420 // pass the range test. If one of them fails we keep the token index pointing
6421 // at the start of the macro arg tokens so that the failing token will be
6422 // annotated by a subsequent annotation try.
6423
6424 bool atLeastOneCompFail = false;
6425
6426 unsigned I = NextToken();
6427 for (; I < NumTokens && isFunctionMacroToken(I); ++I) {
6428 SourceLocation TokLoc = getFunctionMacroTokenLoc(I);
6429 if (TokLoc.isFileID())
6430 continue; // not macro arg token, it's parens or comma.
6431 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
6432 if (clang_isInvalid(clang_getCursorKind(Cursors[I])))
6433 Cursors[I] = updateC;
6434 } else
6435 atLeastOneCompFail = true;
6436 }
6437
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006438 if (atLeastOneCompFail)
6439 return false;
6440
6441 TokIdx = I; // All of the tokens were handled, advance beyond all of them.
6442 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00006443}
6444
6445enum CXChildVisitResult
6446AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006447 SourceRange cursorRange = getRawCursorExtent(cursor);
6448 if (cursorRange.isInvalid())
6449 return CXChildVisit_Recurse;
6450
6451 if (!HasContextSensitiveKeywords) {
6452 // Objective-C properties can have context-sensitive keywords.
6453 if (cursor.kind == CXCursor_ObjCPropertyDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006454 if (const ObjCPropertyDecl *Property
Guy Benyei11169dd2012-12-18 14:30:41 +00006455 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(cursor)))
6456 HasContextSensitiveKeywords = Property->getPropertyAttributesAsWritten() != 0;
6457 }
6458 // Objective-C methods can have context-sensitive keywords.
6459 else if (cursor.kind == CXCursor_ObjCInstanceMethodDecl ||
6460 cursor.kind == CXCursor_ObjCClassMethodDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006461 if (const ObjCMethodDecl *Method
Guy Benyei11169dd2012-12-18 14:30:41 +00006462 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
6463 if (Method->getObjCDeclQualifier())
6464 HasContextSensitiveKeywords = true;
6465 else {
David Majnemer59f77922016-06-24 04:05:48 +00006466 for (const auto *P : Method->parameters()) {
Aaron Ballman43b68be2014-03-07 17:50:17 +00006467 if (P->getObjCDeclQualifier()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006468 HasContextSensitiveKeywords = true;
6469 break;
6470 }
6471 }
6472 }
6473 }
6474 }
6475 // C++ methods can have context-sensitive keywords.
6476 else if (cursor.kind == CXCursor_CXXMethod) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006477 if (const CXXMethodDecl *Method
Guy Benyei11169dd2012-12-18 14:30:41 +00006478 = dyn_cast_or_null<CXXMethodDecl>(getCursorDecl(cursor))) {
6479 if (Method->hasAttr<FinalAttr>() || Method->hasAttr<OverrideAttr>())
6480 HasContextSensitiveKeywords = true;
6481 }
6482 }
6483 // C++ classes can have context-sensitive keywords.
6484 else if (cursor.kind == CXCursor_StructDecl ||
6485 cursor.kind == CXCursor_ClassDecl ||
6486 cursor.kind == CXCursor_ClassTemplate ||
6487 cursor.kind == CXCursor_ClassTemplatePartialSpecialization) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006488 if (const Decl *D = getCursorDecl(cursor))
Guy Benyei11169dd2012-12-18 14:30:41 +00006489 if (D->hasAttr<FinalAttr>())
6490 HasContextSensitiveKeywords = true;
6491 }
6492 }
Argyrios Kyrtzidis990b3862013-06-04 18:24:30 +00006493
6494 // Don't override a property annotation with its getter/setter method.
6495 if (cursor.kind == CXCursor_ObjCInstanceMethodDecl &&
6496 parent.kind == CXCursor_ObjCPropertyDecl)
6497 return CXChildVisit_Continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00006498
6499 if (clang_isPreprocessing(cursor.kind)) {
6500 // Items in the preprocessing record are kept separate from items in
6501 // declarations, so we keep a separate token index.
6502 unsigned SavedTokIdx = TokIdx;
6503 TokIdx = PreprocessingTokIdx;
6504
6505 // Skip tokens up until we catch up to the beginning of the preprocessing
6506 // entry.
6507 while (MoreTokens()) {
6508 const unsigned I = NextToken();
6509 SourceLocation TokLoc = GetTokenLoc(I);
6510 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
6511 case RangeBefore:
6512 AdvanceToken();
6513 continue;
6514 case RangeAfter:
6515 case RangeOverlap:
6516 break;
6517 }
6518 break;
6519 }
6520
6521 // Look at all of the tokens within this range.
6522 while (MoreTokens()) {
6523 const unsigned I = NextToken();
6524 SourceLocation TokLoc = GetTokenLoc(I);
6525 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
6526 case RangeBefore:
6527 llvm_unreachable("Infeasible");
6528 case RangeAfter:
6529 break;
6530 case RangeOverlap:
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00006531 // For macro expansions, just note where the beginning of the macro
6532 // expansion occurs.
6533 if (cursor.kind == CXCursor_MacroExpansion) {
6534 if (TokLoc == cursorRange.getBegin())
6535 Cursors[I] = cursor;
6536 AdvanceToken();
6537 break;
6538 }
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006539 // We may have already annotated macro names inside macro definitions.
6540 if (Cursors[I].kind != CXCursor_MacroExpansion)
6541 Cursors[I] = cursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00006542 AdvanceToken();
Guy Benyei11169dd2012-12-18 14:30:41 +00006543 continue;
6544 }
6545 break;
6546 }
6547
6548 // Save the preprocessing token index; restore the non-preprocessing
6549 // token index.
6550 PreprocessingTokIdx = TokIdx;
6551 TokIdx = SavedTokIdx;
6552 return CXChildVisit_Recurse;
6553 }
6554
6555 if (cursorRange.isInvalid())
6556 return CXChildVisit_Continue;
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006557
6558 unsigned BeforeReachingCursorIdx = NextToken();
Guy Benyei11169dd2012-12-18 14:30:41 +00006559 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00006560 const enum CXCursorKind K = clang_getCursorKind(parent);
6561 const CXCursor updateC =
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006562 (clang_isInvalid(K) || K == CXCursor_TranslationUnit ||
6563 // Attributes are annotated out-of-order, skip tokens until we reach it.
6564 clang_isAttribute(cursor.kind))
Guy Benyei11169dd2012-12-18 14:30:41 +00006565 ? clang_getNullCursor() : parent;
6566
6567 annotateAndAdvanceTokens(updateC, RangeBefore, cursorRange);
6568
6569 // Avoid having the cursor of an expression "overwrite" the annotation of the
6570 // variable declaration that it belongs to.
6571 // This can happen for C++ constructor expressions whose range generally
6572 // include the variable declaration, e.g.:
6573 // MyCXXClass foo; // Make sure we don't annotate 'foo' as a CallExpr cursor.
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006574 if (clang_isExpression(cursorK) && MoreTokens()) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006575 const Expr *E = getCursorExpr(cursor);
Dmitri Gribenkoa1691182013-01-26 18:12:08 +00006576 if (const Decl *D = getCursorParentDecl(cursor)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006577 const unsigned I = NextToken();
6578 if (E->getLocStart().isValid() && D->getLocation().isValid() &&
6579 E->getLocStart() == D->getLocation() &&
6580 E->getLocStart() == GetTokenLoc(I)) {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006581 updateCursorAnnotation(Cursors[I], updateC);
Guy Benyei11169dd2012-12-18 14:30:41 +00006582 AdvanceToken();
6583 }
6584 }
6585 }
6586
6587 // Before recursing into the children keep some state that we are going
6588 // to use in the AnnotateTokensWorker::postVisitChildren callback to do some
6589 // extra work after the child nodes are visited.
6590 // Note that we don't call VisitChildren here to avoid traversing statements
6591 // code-recursively which can blow the stack.
6592
6593 PostChildrenInfo Info;
6594 Info.Cursor = cursor;
6595 Info.CursorRange = cursorRange;
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006596 Info.BeforeReachingCursorIdx = BeforeReachingCursorIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00006597 Info.BeforeChildrenTokenIdx = NextToken();
6598 PostChildrenInfos.push_back(Info);
6599
6600 return CXChildVisit_Recurse;
6601}
6602
6603bool AnnotateTokensWorker::postVisitChildren(CXCursor cursor) {
6604 if (PostChildrenInfos.empty())
6605 return false;
6606 const PostChildrenInfo &Info = PostChildrenInfos.back();
6607 if (!clang_equalCursors(Info.Cursor, cursor))
6608 return false;
6609
6610 const unsigned BeforeChildren = Info.BeforeChildrenTokenIdx;
6611 const unsigned AfterChildren = NextToken();
6612 SourceRange cursorRange = Info.CursorRange;
6613
6614 // Scan the tokens that are at the end of the cursor, but are not captured
6615 // but the child cursors.
6616 annotateAndAdvanceTokens(cursor, RangeOverlap, cursorRange);
6617
6618 // Scan the tokens that are at the beginning of the cursor, but are not
6619 // capture by the child cursors.
6620 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
6621 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
6622 break;
6623
6624 Cursors[I] = cursor;
6625 }
6626
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006627 // Attributes are annotated out-of-order, rewind TokIdx to when we first
6628 // encountered the attribute cursor.
6629 if (clang_isAttribute(cursor.kind))
6630 TokIdx = Info.BeforeReachingCursorIdx;
6631
Guy Benyei11169dd2012-12-18 14:30:41 +00006632 PostChildrenInfos.pop_back();
6633 return false;
6634}
6635
6636static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
6637 CXCursor parent,
6638 CXClientData client_data) {
6639 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
6640}
6641
6642static bool AnnotateTokensPostChildrenVisitor(CXCursor cursor,
6643 CXClientData client_data) {
6644 return static_cast<AnnotateTokensWorker*>(client_data)->
6645 postVisitChildren(cursor);
6646}
6647
6648namespace {
6649
6650/// \brief Uses the macro expansions in the preprocessing record to find
6651/// and mark tokens that are macro arguments. This info is used by the
6652/// AnnotateTokensWorker.
6653class MarkMacroArgTokensVisitor {
6654 SourceManager &SM;
6655 CXToken *Tokens;
6656 unsigned NumTokens;
6657 unsigned CurIdx;
6658
6659public:
6660 MarkMacroArgTokensVisitor(SourceManager &SM,
6661 CXToken *tokens, unsigned numTokens)
6662 : SM(SM), Tokens(tokens), NumTokens(numTokens), CurIdx(0) { }
6663
6664 CXChildVisitResult visit(CXCursor cursor, CXCursor parent) {
6665 if (cursor.kind != CXCursor_MacroExpansion)
6666 return CXChildVisit_Continue;
6667
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00006668 SourceRange macroRange = getCursorMacroExpansion(cursor).getSourceRange();
Guy Benyei11169dd2012-12-18 14:30:41 +00006669 if (macroRange.getBegin() == macroRange.getEnd())
6670 return CXChildVisit_Continue; // it's not a function macro.
6671
6672 for (; CurIdx < NumTokens; ++CurIdx) {
6673 if (!SM.isBeforeInTranslationUnit(getTokenLoc(CurIdx),
6674 macroRange.getBegin()))
6675 break;
6676 }
6677
6678 if (CurIdx == NumTokens)
6679 return CXChildVisit_Break;
6680
6681 for (; CurIdx < NumTokens; ++CurIdx) {
6682 SourceLocation tokLoc = getTokenLoc(CurIdx);
6683 if (!SM.isBeforeInTranslationUnit(tokLoc, macroRange.getEnd()))
6684 break;
6685
6686 setFunctionMacroTokenLoc(CurIdx, SM.getMacroArgExpandedLocation(tokLoc));
6687 }
6688
6689 if (CurIdx == NumTokens)
6690 return CXChildVisit_Break;
6691
6692 return CXChildVisit_Continue;
6693 }
6694
6695private:
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006696 CXToken &getTok(unsigned Idx) {
6697 assert(Idx < NumTokens);
6698 return Tokens[Idx];
6699 }
6700 const CXToken &getTok(unsigned Idx) const {
6701 assert(Idx < NumTokens);
6702 return Tokens[Idx];
6703 }
6704
Guy Benyei11169dd2012-12-18 14:30:41 +00006705 SourceLocation getTokenLoc(unsigned tokI) {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006706 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[1]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006707 }
6708
6709 void setFunctionMacroTokenLoc(unsigned tokI, SourceLocation loc) {
6710 // The third field is reserved and currently not used. Use it here
6711 // to mark macro arg expanded tokens with their expanded locations.
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006712 getTok(tokI).int_data[3] = loc.getRawEncoding();
Guy Benyei11169dd2012-12-18 14:30:41 +00006713 }
6714};
6715
6716} // end anonymous namespace
6717
6718static CXChildVisitResult
6719MarkMacroArgTokensVisitorDelegate(CXCursor cursor, CXCursor parent,
6720 CXClientData client_data) {
6721 return static_cast<MarkMacroArgTokensVisitor*>(client_data)->visit(cursor,
6722 parent);
6723}
6724
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006725/// \brief Used by \c annotatePreprocessorTokens.
6726/// \returns true if lexing was finished, false otherwise.
6727static bool lexNext(Lexer &Lex, Token &Tok,
6728 unsigned &NextIdx, unsigned NumTokens) {
6729 if (NextIdx >= NumTokens)
6730 return true;
6731
6732 ++NextIdx;
6733 Lex.LexFromRawLexer(Tok);
Alexander Kornienko1a9f1842015-12-28 15:24:08 +00006734 return Tok.is(tok::eof);
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006735}
6736
Guy Benyei11169dd2012-12-18 14:30:41 +00006737static void annotatePreprocessorTokens(CXTranslationUnit TU,
6738 SourceRange RegionOfInterest,
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006739 CXCursor *Cursors,
6740 CXToken *Tokens,
6741 unsigned NumTokens) {
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006742 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006743
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00006744 Preprocessor &PP = CXXUnit->getPreprocessor();
Guy Benyei11169dd2012-12-18 14:30:41 +00006745 SourceManager &SourceMgr = CXXUnit->getSourceManager();
6746 std::pair<FileID, unsigned> BeginLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00006747 = SourceMgr.getDecomposedSpellingLoc(RegionOfInterest.getBegin());
Guy Benyei11169dd2012-12-18 14:30:41 +00006748 std::pair<FileID, unsigned> EndLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00006749 = SourceMgr.getDecomposedSpellingLoc(RegionOfInterest.getEnd());
Guy Benyei11169dd2012-12-18 14:30:41 +00006750
6751 if (BeginLocInfo.first != EndLocInfo.first)
6752 return;
6753
6754 StringRef Buffer;
6755 bool Invalid = false;
6756 Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
6757 if (Buffer.empty() || Invalid)
6758 return;
6759
6760 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
6761 CXXUnit->getASTContext().getLangOpts(),
6762 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
6763 Buffer.end());
6764 Lex.SetCommentRetentionState(true);
6765
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006766 unsigned NextIdx = 0;
Guy Benyei11169dd2012-12-18 14:30:41 +00006767 // Lex tokens in raw mode until we hit the end of the range, to avoid
6768 // entering #includes or expanding macros.
6769 while (true) {
6770 Token Tok;
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006771 if (lexNext(Lex, Tok, NextIdx, NumTokens))
6772 break;
6773 unsigned TokIdx = NextIdx-1;
6774 assert(Tok.getLocation() ==
6775 SourceLocation::getFromRawEncoding(Tokens[TokIdx].int_data[1]));
Guy Benyei11169dd2012-12-18 14:30:41 +00006776
6777 reprocess:
6778 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006779 // We have found a preprocessing directive. Annotate the tokens
6780 // appropriately.
Guy Benyei11169dd2012-12-18 14:30:41 +00006781 //
6782 // FIXME: Some simple tests here could identify macro definitions and
6783 // #undefs, to provide specific cursor kinds for those.
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006784
6785 SourceLocation BeginLoc = Tok.getLocation();
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00006786 if (lexNext(Lex, Tok, NextIdx, NumTokens))
6787 break;
6788
Craig Topper69186e72014-06-08 08:38:04 +00006789 MacroInfo *MI = nullptr;
Alp Toker2d57cea2014-05-17 04:53:25 +00006790 if (Tok.is(tok::raw_identifier) && Tok.getRawIdentifier() == "define") {
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00006791 if (lexNext(Lex, Tok, NextIdx, NumTokens))
6792 break;
6793
6794 if (Tok.is(tok::raw_identifier)) {
Alp Toker2d57cea2014-05-17 04:53:25 +00006795 IdentifierInfo &II =
6796 PP.getIdentifierTable().get(Tok.getRawIdentifier());
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00006797 SourceLocation MappedTokLoc =
6798 CXXUnit->mapLocationToPreamble(Tok.getLocation());
6799 MI = getMacroInfo(II, MappedTokLoc, TU);
6800 }
6801 }
6802
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006803 bool finished = false;
Guy Benyei11169dd2012-12-18 14:30:41 +00006804 do {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006805 if (lexNext(Lex, Tok, NextIdx, NumTokens)) {
6806 finished = true;
6807 break;
6808 }
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00006809 // If we are in a macro definition, check if the token was ever a
6810 // macro name and annotate it if that's the case.
6811 if (MI) {
6812 SourceLocation SaveLoc = Tok.getLocation();
6813 Tok.setLocation(CXXUnit->mapLocationToPreamble(SaveLoc));
Richard Smith66a81862015-05-04 02:25:31 +00006814 MacroDefinitionRecord *MacroDef =
6815 checkForMacroInMacroDefinition(MI, Tok, TU);
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00006816 Tok.setLocation(SaveLoc);
6817 if (MacroDef)
Richard Smith66a81862015-05-04 02:25:31 +00006818 Cursors[NextIdx - 1] =
6819 MakeMacroExpansionCursor(MacroDef, Tok.getLocation(), TU);
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00006820 }
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006821 } while (!Tok.isAtStartOfLine());
6822
6823 unsigned LastIdx = finished ? NextIdx-1 : NextIdx-2;
6824 assert(TokIdx <= LastIdx);
6825 SourceLocation EndLoc =
6826 SourceLocation::getFromRawEncoding(Tokens[LastIdx].int_data[1]);
6827 CXCursor Cursor =
6828 MakePreprocessingDirectiveCursor(SourceRange(BeginLoc, EndLoc), TU);
6829
6830 for (; TokIdx <= LastIdx; ++TokIdx)
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00006831 updateCursorAnnotation(Cursors[TokIdx], Cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00006832
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006833 if (finished)
6834 break;
6835 goto reprocess;
Guy Benyei11169dd2012-12-18 14:30:41 +00006836 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006837 }
6838}
6839
6840// This gets run a separate thread to avoid stack blowout.
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00006841static void clang_annotateTokensImpl(CXTranslationUnit TU, ASTUnit *CXXUnit,
6842 CXToken *Tokens, unsigned NumTokens,
6843 CXCursor *Cursors) {
Dmitri Gribenko183436e2013-01-26 21:49:50 +00006844 CIndexer *CXXIdx = TU->CIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00006845 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing))
6846 setThreadBackgroundPriority();
6847
6848 // Determine the region of interest, which contains all of the tokens.
6849 SourceRange RegionOfInterest;
6850 RegionOfInterest.setBegin(
6851 cxloc::translateSourceLocation(clang_getTokenLocation(TU, Tokens[0])));
6852 RegionOfInterest.setEnd(
6853 cxloc::translateSourceLocation(clang_getTokenLocation(TU,
6854 Tokens[NumTokens-1])));
6855
Guy Benyei11169dd2012-12-18 14:30:41 +00006856 // Relex the tokens within the source range to look for preprocessing
6857 // directives.
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006858 annotatePreprocessorTokens(TU, RegionOfInterest, Cursors, Tokens, NumTokens);
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00006859
6860 // If begin location points inside a macro argument, set it to the expansion
6861 // location so we can have the full context when annotating semantically.
6862 {
6863 SourceManager &SM = CXXUnit->getSourceManager();
6864 SourceLocation Loc =
6865 SM.getMacroArgExpandedLocation(RegionOfInterest.getBegin());
6866 if (Loc.isMacroID())
6867 RegionOfInterest.setBegin(SM.getExpansionLoc(Loc));
6868 }
6869
Guy Benyei11169dd2012-12-18 14:30:41 +00006870 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
6871 // Search and mark tokens that are macro argument expansions.
6872 MarkMacroArgTokensVisitor Visitor(CXXUnit->getSourceManager(),
6873 Tokens, NumTokens);
6874 CursorVisitor MacroArgMarker(TU,
6875 MarkMacroArgTokensVisitorDelegate, &Visitor,
6876 /*VisitPreprocessorLast=*/true,
6877 /*VisitIncludedEntities=*/false,
6878 RegionOfInterest);
6879 MacroArgMarker.visitPreprocessedEntitiesInRegion();
6880 }
6881
6882 // Annotate all of the source locations in the region of interest that map to
6883 // a specific cursor.
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006884 AnnotateTokensWorker W(Tokens, Cursors, NumTokens, TU, RegionOfInterest);
Guy Benyei11169dd2012-12-18 14:30:41 +00006885
6886 // FIXME: We use a ridiculous stack size here because the data-recursion
6887 // algorithm uses a large stack frame than the non-data recursive version,
6888 // and AnnotationTokensWorker currently transforms the data-recursion
6889 // algorithm back into a traditional recursion by explicitly calling
6890 // VisitChildren(). We will need to remove this explicit recursive call.
6891 W.AnnotateTokens();
6892
6893 // If we ran into any entities that involve context-sensitive keywords,
6894 // take another pass through the tokens to mark them as such.
6895 if (W.hasContextSensitiveKeywords()) {
6896 for (unsigned I = 0; I != NumTokens; ++I) {
6897 if (clang_getTokenKind(Tokens[I]) != CXToken_Identifier)
6898 continue;
6899
6900 if (Cursors[I].kind == CXCursor_ObjCPropertyDecl) {
6901 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006902 if (const ObjCPropertyDecl *Property
Guy Benyei11169dd2012-12-18 14:30:41 +00006903 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(Cursors[I]))) {
6904 if (Property->getPropertyAttributesAsWritten() != 0 &&
6905 llvm::StringSwitch<bool>(II->getName())
6906 .Case("readonly", true)
6907 .Case("assign", true)
6908 .Case("unsafe_unretained", true)
6909 .Case("readwrite", true)
6910 .Case("retain", true)
6911 .Case("copy", true)
6912 .Case("nonatomic", true)
6913 .Case("atomic", true)
6914 .Case("getter", true)
6915 .Case("setter", true)
6916 .Case("strong", true)
6917 .Case("weak", true)
Manman Ren04fd4d82016-05-31 23:22:04 +00006918 .Case("class", true)
Guy Benyei11169dd2012-12-18 14:30:41 +00006919 .Default(false))
6920 Tokens[I].int_data[0] = CXToken_Keyword;
6921 }
6922 continue;
6923 }
6924
6925 if (Cursors[I].kind == CXCursor_ObjCInstanceMethodDecl ||
6926 Cursors[I].kind == CXCursor_ObjCClassMethodDecl) {
6927 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
6928 if (llvm::StringSwitch<bool>(II->getName())
6929 .Case("in", true)
6930 .Case("out", true)
6931 .Case("inout", true)
6932 .Case("oneway", true)
6933 .Case("bycopy", true)
6934 .Case("byref", true)
6935 .Default(false))
6936 Tokens[I].int_data[0] = CXToken_Keyword;
6937 continue;
6938 }
6939
6940 if (Cursors[I].kind == CXCursor_CXXFinalAttr ||
6941 Cursors[I].kind == CXCursor_CXXOverrideAttr) {
6942 Tokens[I].int_data[0] = CXToken_Keyword;
6943 continue;
6944 }
6945 }
6946 }
6947}
6948
Guy Benyei11169dd2012-12-18 14:30:41 +00006949void clang_annotateTokens(CXTranslationUnit TU,
6950 CXToken *Tokens, unsigned NumTokens,
6951 CXCursor *Cursors) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006952 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006953 LOG_BAD_TU(TU);
6954 return;
6955 }
6956 if (NumTokens == 0 || !Tokens || !Cursors) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00006957 LOG_FUNC_SECTION { *Log << "<null input>"; }
Guy Benyei11169dd2012-12-18 14:30:41 +00006958 return;
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00006959 }
6960
6961 LOG_FUNC_SECTION {
6962 *Log << TU << ' ';
6963 CXSourceLocation bloc = clang_getTokenLocation(TU, Tokens[0]);
6964 CXSourceLocation eloc = clang_getTokenLocation(TU, Tokens[NumTokens-1]);
6965 *Log << clang_getRange(bloc, eloc);
6966 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006967
6968 // Any token we don't specifically annotate will have a NULL cursor.
6969 CXCursor C = clang_getNullCursor();
6970 for (unsigned I = 0; I != NumTokens; ++I)
6971 Cursors[I] = C;
6972
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006973 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006974 if (!CXXUnit)
6975 return;
6976
6977 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00006978
6979 auto AnnotateTokensImpl = [=]() {
6980 clang_annotateTokensImpl(TU, CXXUnit, Tokens, NumTokens, Cursors);
6981 };
Guy Benyei11169dd2012-12-18 14:30:41 +00006982 llvm::CrashRecoveryContext CRC;
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00006983 if (!RunSafely(CRC, AnnotateTokensImpl, GetSafetyThreadStackSize() * 2)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006984 fprintf(stderr, "libclang: crash detected while annotating tokens\n");
6985 }
6986}
6987
Guy Benyei11169dd2012-12-18 14:30:41 +00006988//===----------------------------------------------------------------------===//
6989// Operations for querying linkage of a cursor.
6990//===----------------------------------------------------------------------===//
6991
Guy Benyei11169dd2012-12-18 14:30:41 +00006992CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
6993 if (!clang_isDeclaration(cursor.kind))
6994 return CXLinkage_Invalid;
6995
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006996 const Decl *D = cxcursor::getCursorDecl(cursor);
6997 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
Rafael Espindola3ae00052013-05-13 00:12:11 +00006998 switch (ND->getLinkageInternal()) {
Rafael Espindola50df3a02013-05-25 17:16:20 +00006999 case NoLinkage:
7000 case VisibleNoLinkage: return CXLinkage_NoLinkage;
Guy Benyei11169dd2012-12-18 14:30:41 +00007001 case InternalLinkage: return CXLinkage_Internal;
7002 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
7003 case ExternalLinkage: return CXLinkage_External;
7004 };
7005
7006 return CXLinkage_Invalid;
7007}
Guy Benyei11169dd2012-12-18 14:30:41 +00007008
7009//===----------------------------------------------------------------------===//
Ehsan Akhgarib743de72016-05-31 15:55:51 +00007010// Operations for querying visibility of a cursor.
7011//===----------------------------------------------------------------------===//
7012
Ehsan Akhgarib743de72016-05-31 15:55:51 +00007013CXVisibilityKind clang_getCursorVisibility(CXCursor cursor) {
7014 if (!clang_isDeclaration(cursor.kind))
7015 return CXVisibility_Invalid;
7016
7017 const Decl *D = cxcursor::getCursorDecl(cursor);
7018 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
7019 switch (ND->getVisibility()) {
7020 case HiddenVisibility: return CXVisibility_Hidden;
7021 case ProtectedVisibility: return CXVisibility_Protected;
7022 case DefaultVisibility: return CXVisibility_Default;
7023 };
7024
7025 return CXVisibility_Invalid;
7026}
Ehsan Akhgarib743de72016-05-31 15:55:51 +00007027
7028//===----------------------------------------------------------------------===//
Guy Benyei11169dd2012-12-18 14:30:41 +00007029// Operations for querying language of a cursor.
7030//===----------------------------------------------------------------------===//
7031
7032static CXLanguageKind getDeclLanguage(const Decl *D) {
7033 if (!D)
7034 return CXLanguage_C;
7035
7036 switch (D->getKind()) {
7037 default:
7038 break;
7039 case Decl::ImplicitParam:
7040 case Decl::ObjCAtDefsField:
7041 case Decl::ObjCCategory:
7042 case Decl::ObjCCategoryImpl:
7043 case Decl::ObjCCompatibleAlias:
7044 case Decl::ObjCImplementation:
7045 case Decl::ObjCInterface:
7046 case Decl::ObjCIvar:
7047 case Decl::ObjCMethod:
7048 case Decl::ObjCProperty:
7049 case Decl::ObjCPropertyImpl:
7050 case Decl::ObjCProtocol:
Douglas Gregor85f3f952015-07-07 03:57:15 +00007051 case Decl::ObjCTypeParam:
Guy Benyei11169dd2012-12-18 14:30:41 +00007052 return CXLanguage_ObjC;
7053 case Decl::CXXConstructor:
7054 case Decl::CXXConversion:
7055 case Decl::CXXDestructor:
7056 case Decl::CXXMethod:
7057 case Decl::CXXRecord:
7058 case Decl::ClassTemplate:
7059 case Decl::ClassTemplatePartialSpecialization:
7060 case Decl::ClassTemplateSpecialization:
7061 case Decl::Friend:
7062 case Decl::FriendTemplate:
7063 case Decl::FunctionTemplate:
7064 case Decl::LinkageSpec:
7065 case Decl::Namespace:
7066 case Decl::NamespaceAlias:
7067 case Decl::NonTypeTemplateParm:
7068 case Decl::StaticAssert:
7069 case Decl::TemplateTemplateParm:
7070 case Decl::TemplateTypeParm:
7071 case Decl::UnresolvedUsingTypename:
7072 case Decl::UnresolvedUsingValue:
7073 case Decl::Using:
7074 case Decl::UsingDirective:
7075 case Decl::UsingShadow:
7076 return CXLanguage_CPlusPlus;
7077 }
7078
7079 return CXLanguage_C;
7080}
7081
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007082static CXAvailabilityKind getCursorAvailabilityForDecl(const Decl *D) {
7083 if (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted())
Manuel Klimek8e3a7ed2015-09-25 17:53:16 +00007084 return CXAvailability_NotAvailable;
Guy Benyei11169dd2012-12-18 14:30:41 +00007085
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007086 switch (D->getAvailability()) {
7087 case AR_Available:
7088 case AR_NotYetIntroduced:
7089 if (const EnumConstantDecl *EnumConst = dyn_cast<EnumConstantDecl>(D))
Benjamin Kramer656363d2013-10-15 18:53:18 +00007090 return getCursorAvailabilityForDecl(
7091 cast<Decl>(EnumConst->getDeclContext()));
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007092 return CXAvailability_Available;
7093
7094 case AR_Deprecated:
7095 return CXAvailability_Deprecated;
7096
7097 case AR_Unavailable:
7098 return CXAvailability_NotAvailable;
7099 }
Benjamin Kramer656363d2013-10-15 18:53:18 +00007100
7101 llvm_unreachable("Unknown availability kind!");
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007102}
7103
Guy Benyei11169dd2012-12-18 14:30:41 +00007104enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
7105 if (clang_isDeclaration(cursor.kind))
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007106 if (const Decl *D = cxcursor::getCursorDecl(cursor))
7107 return getCursorAvailabilityForDecl(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00007108
7109 return CXAvailability_Available;
7110}
7111
7112static CXVersion convertVersion(VersionTuple In) {
7113 CXVersion Out = { -1, -1, -1 };
7114 if (In.empty())
7115 return Out;
7116
7117 Out.Major = In.getMajor();
7118
NAKAMURA Takumic2b5d1f2013-02-21 02:32:34 +00007119 Optional<unsigned> Minor = In.getMinor();
7120 if (Minor.hasValue())
Guy Benyei11169dd2012-12-18 14:30:41 +00007121 Out.Minor = *Minor;
7122 else
7123 return Out;
7124
NAKAMURA Takumic2b5d1f2013-02-21 02:32:34 +00007125 Optional<unsigned> Subminor = In.getSubminor();
7126 if (Subminor.hasValue())
Guy Benyei11169dd2012-12-18 14:30:41 +00007127 Out.Subminor = *Subminor;
7128
7129 return Out;
7130}
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007131
7132static int getCursorPlatformAvailabilityForDecl(const Decl *D,
7133 int *always_deprecated,
7134 CXString *deprecated_message,
7135 int *always_unavailable,
7136 CXString *unavailable_message,
7137 CXPlatformAvailability *availability,
7138 int availability_size) {
7139 bool HadAvailAttr = false;
7140 int N = 0;
Aaron Ballmanb97112e2014-03-08 22:19:01 +00007141 for (auto A : D->attrs()) {
7142 if (DeprecatedAttr *Deprecated = dyn_cast<DeprecatedAttr>(A)) {
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007143 HadAvailAttr = true;
7144 if (always_deprecated)
7145 *always_deprecated = 1;
Nico Weberaacf0312014-04-24 05:16:45 +00007146 if (deprecated_message) {
Argyrios Kyrtzidisedfe07f2014-04-24 06:05:40 +00007147 clang_disposeString(*deprecated_message);
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007148 *deprecated_message = cxstring::createDup(Deprecated->getMessage());
Nico Weberaacf0312014-04-24 05:16:45 +00007149 }
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007150 continue;
7151 }
7152
Aaron Ballmanb97112e2014-03-08 22:19:01 +00007153 if (UnavailableAttr *Unavailable = dyn_cast<UnavailableAttr>(A)) {
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007154 HadAvailAttr = true;
7155 if (always_unavailable)
7156 *always_unavailable = 1;
7157 if (unavailable_message) {
Argyrios Kyrtzidisedfe07f2014-04-24 06:05:40 +00007158 clang_disposeString(*unavailable_message);
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007159 *unavailable_message = cxstring::createDup(Unavailable->getMessage());
7160 }
7161 continue;
7162 }
7163
Aaron Ballmanb97112e2014-03-08 22:19:01 +00007164 if (AvailabilityAttr *Avail = dyn_cast<AvailabilityAttr>(A)) {
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007165 HadAvailAttr = true;
7166 if (N < availability_size) {
7167 availability[N].Platform
7168 = cxstring::createDup(Avail->getPlatform()->getName());
7169 availability[N].Introduced = convertVersion(Avail->getIntroduced());
7170 availability[N].Deprecated = convertVersion(Avail->getDeprecated());
7171 availability[N].Obsoleted = convertVersion(Avail->getObsoleted());
7172 availability[N].Unavailable = Avail->getUnavailable();
7173 availability[N].Message = cxstring::createDup(Avail->getMessage());
7174 }
7175 ++N;
7176 }
7177 }
7178
7179 if (!HadAvailAttr)
7180 if (const EnumConstantDecl *EnumConst = dyn_cast<EnumConstantDecl>(D))
7181 return getCursorPlatformAvailabilityForDecl(
7182 cast<Decl>(EnumConst->getDeclContext()),
7183 always_deprecated,
7184 deprecated_message,
7185 always_unavailable,
7186 unavailable_message,
7187 availability,
7188 availability_size);
Guy Benyei11169dd2012-12-18 14:30:41 +00007189
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007190 return N;
7191}
7192
Guy Benyei11169dd2012-12-18 14:30:41 +00007193int clang_getCursorPlatformAvailability(CXCursor cursor,
7194 int *always_deprecated,
7195 CXString *deprecated_message,
7196 int *always_unavailable,
7197 CXString *unavailable_message,
7198 CXPlatformAvailability *availability,
7199 int availability_size) {
7200 if (always_deprecated)
7201 *always_deprecated = 0;
7202 if (deprecated_message)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00007203 *deprecated_message = cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00007204 if (always_unavailable)
7205 *always_unavailable = 0;
7206 if (unavailable_message)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00007207 *unavailable_message = cxstring::createEmpty();
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007208
Guy Benyei11169dd2012-12-18 14:30:41 +00007209 if (!clang_isDeclaration(cursor.kind))
7210 return 0;
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007211
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007212 const Decl *D = cxcursor::getCursorDecl(cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00007213 if (!D)
7214 return 0;
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007215
7216 return getCursorPlatformAvailabilityForDecl(D, always_deprecated,
7217 deprecated_message,
7218 always_unavailable,
7219 unavailable_message,
7220 availability,
7221 availability_size);
Guy Benyei11169dd2012-12-18 14:30:41 +00007222}
7223
7224void clang_disposeCXPlatformAvailability(CXPlatformAvailability *availability) {
7225 clang_disposeString(availability->Platform);
7226 clang_disposeString(availability->Message);
7227}
7228
7229CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
7230 if (clang_isDeclaration(cursor.kind))
7231 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
7232
7233 return CXLanguage_Invalid;
7234}
7235
7236 /// \brief If the given cursor is the "templated" declaration
7237 /// descibing a class or function template, return the class or
7238 /// function template.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007239static const Decl *maybeGetTemplateCursor(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007240 if (!D)
Craig Topper69186e72014-06-08 08:38:04 +00007241 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007242
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007243 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00007244 if (FunctionTemplateDecl *FunTmpl = FD->getDescribedFunctionTemplate())
7245 return FunTmpl;
7246
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007247 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00007248 if (ClassTemplateDecl *ClassTmpl = RD->getDescribedClassTemplate())
7249 return ClassTmpl;
7250
7251 return D;
7252}
7253
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00007254
7255enum CX_StorageClass clang_Cursor_getStorageClass(CXCursor C) {
7256 StorageClass sc = SC_None;
7257 const Decl *D = getCursorDecl(C);
7258 if (D) {
7259 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7260 sc = FD->getStorageClass();
7261 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7262 sc = VD->getStorageClass();
7263 } else {
7264 return CX_SC_Invalid;
7265 }
7266 } else {
7267 return CX_SC_Invalid;
7268 }
7269 switch (sc) {
7270 case SC_None:
7271 return CX_SC_None;
7272 case SC_Extern:
7273 return CX_SC_Extern;
7274 case SC_Static:
7275 return CX_SC_Static;
7276 case SC_PrivateExtern:
7277 return CX_SC_PrivateExtern;
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00007278 case SC_Auto:
7279 return CX_SC_Auto;
7280 case SC_Register:
7281 return CX_SC_Register;
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00007282 }
Kaelyn Takataab61e702014-10-15 18:03:26 +00007283 llvm_unreachable("Unhandled storage class!");
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00007284}
7285
Guy Benyei11169dd2012-12-18 14:30:41 +00007286CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
7287 if (clang_isDeclaration(cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007288 if (const Decl *D = getCursorDecl(cursor)) {
7289 const DeclContext *DC = D->getDeclContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00007290 if (!DC)
7291 return clang_getNullCursor();
7292
7293 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
7294 getCursorTU(cursor));
7295 }
7296 }
7297
7298 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007299 if (const Decl *D = getCursorDecl(cursor))
Guy Benyei11169dd2012-12-18 14:30:41 +00007300 return MakeCXCursor(D, getCursorTU(cursor));
7301 }
7302
7303 return clang_getNullCursor();
7304}
7305
7306CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
7307 if (clang_isDeclaration(cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007308 if (const Decl *D = getCursorDecl(cursor)) {
7309 const DeclContext *DC = D->getLexicalDeclContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00007310 if (!DC)
7311 return clang_getNullCursor();
7312
7313 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
7314 getCursorTU(cursor));
7315 }
7316 }
7317
7318 // FIXME: Note that we can't easily compute the lexical context of a
7319 // statement or expression, so we return nothing.
7320 return clang_getNullCursor();
7321}
7322
7323CXFile clang_getIncludedFile(CXCursor cursor) {
7324 if (cursor.kind != CXCursor_InclusionDirective)
Craig Topper69186e72014-06-08 08:38:04 +00007325 return nullptr;
7326
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00007327 const InclusionDirective *ID = getCursorInclusionDirective(cursor);
Dmitri Gribenkof9304482013-01-23 15:56:07 +00007328 return const_cast<FileEntry *>(ID->getFile());
Guy Benyei11169dd2012-12-18 14:30:41 +00007329}
7330
Argyrios Kyrtzidis9adfd8a2013-04-18 22:15:49 +00007331unsigned clang_Cursor_getObjCPropertyAttributes(CXCursor C, unsigned reserved) {
7332 if (C.kind != CXCursor_ObjCPropertyDecl)
7333 return CXObjCPropertyAttr_noattr;
7334
7335 unsigned Result = CXObjCPropertyAttr_noattr;
7336 const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(getCursorDecl(C));
7337 ObjCPropertyDecl::PropertyAttributeKind Attr =
7338 PD->getPropertyAttributesAsWritten();
7339
7340#define SET_CXOBJCPROP_ATTR(A) \
7341 if (Attr & ObjCPropertyDecl::OBJC_PR_##A) \
7342 Result |= CXObjCPropertyAttr_##A
7343 SET_CXOBJCPROP_ATTR(readonly);
7344 SET_CXOBJCPROP_ATTR(getter);
7345 SET_CXOBJCPROP_ATTR(assign);
7346 SET_CXOBJCPROP_ATTR(readwrite);
7347 SET_CXOBJCPROP_ATTR(retain);
7348 SET_CXOBJCPROP_ATTR(copy);
7349 SET_CXOBJCPROP_ATTR(nonatomic);
7350 SET_CXOBJCPROP_ATTR(setter);
7351 SET_CXOBJCPROP_ATTR(atomic);
7352 SET_CXOBJCPROP_ATTR(weak);
7353 SET_CXOBJCPROP_ATTR(strong);
7354 SET_CXOBJCPROP_ATTR(unsafe_unretained);
Manman Ren04fd4d82016-05-31 23:22:04 +00007355 SET_CXOBJCPROP_ATTR(class);
Argyrios Kyrtzidis9adfd8a2013-04-18 22:15:49 +00007356#undef SET_CXOBJCPROP_ATTR
7357
7358 return Result;
7359}
7360
Argyrios Kyrtzidis9d9bc012013-04-18 23:29:12 +00007361unsigned clang_Cursor_getObjCDeclQualifiers(CXCursor C) {
7362 if (!clang_isDeclaration(C.kind))
7363 return CXObjCDeclQualifier_None;
7364
7365 Decl::ObjCDeclQualifier QT = Decl::OBJC_TQ_None;
7366 const Decl *D = getCursorDecl(C);
7367 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
7368 QT = MD->getObjCDeclQualifier();
7369 else if (const ParmVarDecl *PD = dyn_cast<ParmVarDecl>(D))
7370 QT = PD->getObjCDeclQualifier();
7371 if (QT == Decl::OBJC_TQ_None)
7372 return CXObjCDeclQualifier_None;
7373
7374 unsigned Result = CXObjCDeclQualifier_None;
7375 if (QT & Decl::OBJC_TQ_In) Result |= CXObjCDeclQualifier_In;
7376 if (QT & Decl::OBJC_TQ_Inout) Result |= CXObjCDeclQualifier_Inout;
7377 if (QT & Decl::OBJC_TQ_Out) Result |= CXObjCDeclQualifier_Out;
7378 if (QT & Decl::OBJC_TQ_Bycopy) Result |= CXObjCDeclQualifier_Bycopy;
7379 if (QT & Decl::OBJC_TQ_Byref) Result |= CXObjCDeclQualifier_Byref;
7380 if (QT & Decl::OBJC_TQ_Oneway) Result |= CXObjCDeclQualifier_Oneway;
7381
7382 return Result;
7383}
7384
Argyrios Kyrtzidis7b50fc52013-07-05 20:44:37 +00007385unsigned clang_Cursor_isObjCOptional(CXCursor C) {
7386 if (!clang_isDeclaration(C.kind))
7387 return 0;
7388
7389 const Decl *D = getCursorDecl(C);
7390 if (const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D))
7391 return PD->getPropertyImplementation() == ObjCPropertyDecl::Optional;
7392 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
7393 return MD->getImplementationControl() == ObjCMethodDecl::Optional;
7394
7395 return 0;
7396}
7397
Argyrios Kyrtzidis23814e42013-04-18 23:53:05 +00007398unsigned clang_Cursor_isVariadic(CXCursor C) {
7399 if (!clang_isDeclaration(C.kind))
7400 return 0;
7401
7402 const Decl *D = getCursorDecl(C);
7403 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
7404 return FD->isVariadic();
7405 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
7406 return MD->isVariadic();
7407
7408 return 0;
7409}
7410
Guy Benyei11169dd2012-12-18 14:30:41 +00007411CXSourceRange clang_Cursor_getCommentRange(CXCursor C) {
7412 if (!clang_isDeclaration(C.kind))
7413 return clang_getNullRange();
7414
7415 const Decl *D = getCursorDecl(C);
7416 ASTContext &Context = getCursorContext(C);
7417 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
7418 if (!RC)
7419 return clang_getNullRange();
7420
7421 return cxloc::translateSourceRange(Context, RC->getSourceRange());
7422}
7423
7424CXString clang_Cursor_getRawCommentText(CXCursor C) {
7425 if (!clang_isDeclaration(C.kind))
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00007426 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00007427
7428 const Decl *D = getCursorDecl(C);
7429 ASTContext &Context = getCursorContext(C);
7430 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
7431 StringRef RawText = RC ? RC->getRawText(Context.getSourceManager()) :
7432 StringRef();
7433
7434 // Don't duplicate the string because RawText points directly into source
7435 // code.
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00007436 return cxstring::createRef(RawText);
Guy Benyei11169dd2012-12-18 14:30:41 +00007437}
7438
7439CXString clang_Cursor_getBriefCommentText(CXCursor C) {
7440 if (!clang_isDeclaration(C.kind))
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00007441 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00007442
7443 const Decl *D = getCursorDecl(C);
7444 const ASTContext &Context = getCursorContext(C);
7445 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
7446
7447 if (RC) {
7448 StringRef BriefText = RC->getBriefText(Context);
7449
7450 // Don't duplicate the string because RawComment ensures that this memory
7451 // will not go away.
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00007452 return cxstring::createRef(BriefText);
Guy Benyei11169dd2012-12-18 14:30:41 +00007453 }
7454
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00007455 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00007456}
7457
Guy Benyei11169dd2012-12-18 14:30:41 +00007458CXModule clang_Cursor_getModule(CXCursor C) {
7459 if (C.kind == CXCursor_ModuleImportDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007460 if (const ImportDecl *ImportD =
7461 dyn_cast_or_null<ImportDecl>(getCursorDecl(C)))
Guy Benyei11169dd2012-12-18 14:30:41 +00007462 return ImportD->getImportedModule();
7463 }
7464
Craig Topper69186e72014-06-08 08:38:04 +00007465 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007466}
7467
Argyrios Kyrtzidisf6d49c32014-05-14 23:14:37 +00007468CXModule clang_getModuleForFile(CXTranslationUnit TU, CXFile File) {
7469 if (isNotUsableTU(TU)) {
7470 LOG_BAD_TU(TU);
7471 return nullptr;
7472 }
7473 if (!File)
7474 return nullptr;
7475 FileEntry *FE = static_cast<FileEntry *>(File);
7476
7477 ASTUnit &Unit = *cxtu::getASTUnit(TU);
7478 HeaderSearch &HS = Unit.getPreprocessor().getHeaderSearchInfo();
7479 ModuleMap::KnownHeader Header = HS.findModuleForHeader(FE);
7480
Richard Smithfeb54b62014-10-23 02:01:19 +00007481 return Header.getModule();
Argyrios Kyrtzidisf6d49c32014-05-14 23:14:37 +00007482}
7483
Argyrios Kyrtzidis12fdb9e2013-04-26 22:47:49 +00007484CXFile clang_Module_getASTFile(CXModule CXMod) {
7485 if (!CXMod)
Craig Topper69186e72014-06-08 08:38:04 +00007486 return nullptr;
Argyrios Kyrtzidis12fdb9e2013-04-26 22:47:49 +00007487 Module *Mod = static_cast<Module*>(CXMod);
7488 return const_cast<FileEntry *>(Mod->getASTFile());
7489}
7490
Guy Benyei11169dd2012-12-18 14:30:41 +00007491CXModule clang_Module_getParent(CXModule CXMod) {
7492 if (!CXMod)
Craig Topper69186e72014-06-08 08:38:04 +00007493 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007494 Module *Mod = static_cast<Module*>(CXMod);
7495 return Mod->Parent;
7496}
7497
7498CXString clang_Module_getName(CXModule CXMod) {
7499 if (!CXMod)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00007500 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00007501 Module *Mod = static_cast<Module*>(CXMod);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00007502 return cxstring::createDup(Mod->Name);
Guy Benyei11169dd2012-12-18 14:30:41 +00007503}
7504
7505CXString clang_Module_getFullName(CXModule CXMod) {
7506 if (!CXMod)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00007507 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00007508 Module *Mod = static_cast<Module*>(CXMod);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00007509 return cxstring::createDup(Mod->getFullModuleName());
Guy Benyei11169dd2012-12-18 14:30:41 +00007510}
7511
Argyrios Kyrtzidis884337f2014-05-15 04:44:25 +00007512int clang_Module_isSystem(CXModule CXMod) {
7513 if (!CXMod)
7514 return 0;
7515 Module *Mod = static_cast<Module*>(CXMod);
7516 return Mod->IsSystem;
7517}
7518
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00007519unsigned clang_Module_getNumTopLevelHeaders(CXTranslationUnit TU,
7520 CXModule CXMod) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00007521 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00007522 LOG_BAD_TU(TU);
7523 return 0;
7524 }
7525 if (!CXMod)
Guy Benyei11169dd2012-12-18 14:30:41 +00007526 return 0;
7527 Module *Mod = static_cast<Module*>(CXMod);
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00007528 FileManager &FileMgr = cxtu::getASTUnit(TU)->getFileManager();
7529 ArrayRef<const FileEntry *> TopHeaders = Mod->getTopHeaders(FileMgr);
7530 return TopHeaders.size();
Guy Benyei11169dd2012-12-18 14:30:41 +00007531}
7532
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00007533CXFile clang_Module_getTopLevelHeader(CXTranslationUnit TU,
7534 CXModule CXMod, unsigned Index) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00007535 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00007536 LOG_BAD_TU(TU);
Craig Topper69186e72014-06-08 08:38:04 +00007537 return nullptr;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00007538 }
7539 if (!CXMod)
Craig Topper69186e72014-06-08 08:38:04 +00007540 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007541 Module *Mod = static_cast<Module*>(CXMod);
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00007542 FileManager &FileMgr = cxtu::getASTUnit(TU)->getFileManager();
Guy Benyei11169dd2012-12-18 14:30:41 +00007543
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00007544 ArrayRef<const FileEntry *> TopHeaders = Mod->getTopHeaders(FileMgr);
7545 if (Index < TopHeaders.size())
7546 return const_cast<FileEntry *>(TopHeaders[Index]);
Guy Benyei11169dd2012-12-18 14:30:41 +00007547
Craig Topper69186e72014-06-08 08:38:04 +00007548 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007549}
7550
Guy Benyei11169dd2012-12-18 14:30:41 +00007551//===----------------------------------------------------------------------===//
7552// C++ AST instrospection.
7553//===----------------------------------------------------------------------===//
7554
Jonathan Coe29565352016-04-27 12:48:25 +00007555unsigned clang_CXXConstructor_isDefaultConstructor(CXCursor C) {
7556 if (!clang_isDeclaration(C.kind))
7557 return 0;
7558
7559 const Decl *D = cxcursor::getCursorDecl(C);
7560 const CXXConstructorDecl *Constructor =
7561 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
7562 return (Constructor && Constructor->isDefaultConstructor()) ? 1 : 0;
7563}
7564
7565unsigned clang_CXXConstructor_isCopyConstructor(CXCursor C) {
7566 if (!clang_isDeclaration(C.kind))
7567 return 0;
7568
7569 const Decl *D = cxcursor::getCursorDecl(C);
7570 const CXXConstructorDecl *Constructor =
7571 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
7572 return (Constructor && Constructor->isCopyConstructor()) ? 1 : 0;
7573}
7574
7575unsigned clang_CXXConstructor_isMoveConstructor(CXCursor C) {
7576 if (!clang_isDeclaration(C.kind))
7577 return 0;
7578
7579 const Decl *D = cxcursor::getCursorDecl(C);
7580 const CXXConstructorDecl *Constructor =
7581 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
7582 return (Constructor && Constructor->isMoveConstructor()) ? 1 : 0;
7583}
7584
7585unsigned clang_CXXConstructor_isConvertingConstructor(CXCursor C) {
7586 if (!clang_isDeclaration(C.kind))
7587 return 0;
7588
7589 const Decl *D = cxcursor::getCursorDecl(C);
7590 const CXXConstructorDecl *Constructor =
7591 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
7592 // Passing 'false' excludes constructors marked 'explicit'.
7593 return (Constructor && Constructor->isConvertingConstructor(false)) ? 1 : 0;
7594}
7595
Saleem Abdulrasool6ea75db2015-10-27 15:50:22 +00007596unsigned clang_CXXField_isMutable(CXCursor C) {
7597 if (!clang_isDeclaration(C.kind))
7598 return 0;
7599
7600 if (const auto D = cxcursor::getCursorDecl(C))
7601 if (const auto FD = dyn_cast_or_null<FieldDecl>(D))
7602 return FD->isMutable() ? 1 : 0;
7603 return 0;
7604}
7605
Dmitri Gribenko62770be2013-05-17 18:38:35 +00007606unsigned clang_CXXMethod_isPureVirtual(CXCursor C) {
7607 if (!clang_isDeclaration(C.kind))
7608 return 0;
7609
Dmitri Gribenko62770be2013-05-17 18:38:35 +00007610 const Decl *D = cxcursor::getCursorDecl(C);
Alp Tokera2794f92014-01-22 07:29:52 +00007611 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00007612 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Dmitri Gribenko62770be2013-05-17 18:38:35 +00007613 return (Method && Method->isVirtual() && Method->isPure()) ? 1 : 0;
7614}
7615
Dmitri Gribenkoe570ede2014-04-07 14:59:13 +00007616unsigned clang_CXXMethod_isConst(CXCursor C) {
7617 if (!clang_isDeclaration(C.kind))
7618 return 0;
7619
7620 const Decl *D = cxcursor::getCursorDecl(C);
7621 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00007622 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Dmitri Gribenkoe570ede2014-04-07 14:59:13 +00007623 return (Method && (Method->getTypeQualifiers() & Qualifiers::Const)) ? 1 : 0;
7624}
7625
Jonathan Coe29565352016-04-27 12:48:25 +00007626unsigned clang_CXXMethod_isDefaulted(CXCursor C) {
7627 if (!clang_isDeclaration(C.kind))
7628 return 0;
7629
7630 const Decl *D = cxcursor::getCursorDecl(C);
7631 const CXXMethodDecl *Method =
7632 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
7633 return (Method && Method->isDefaulted()) ? 1 : 0;
7634}
7635
Guy Benyei11169dd2012-12-18 14:30:41 +00007636unsigned clang_CXXMethod_isStatic(CXCursor C) {
7637 if (!clang_isDeclaration(C.kind))
7638 return 0;
7639
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007640 const Decl *D = cxcursor::getCursorDecl(C);
Alp Tokera2794f92014-01-22 07:29:52 +00007641 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00007642 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007643 return (Method && Method->isStatic()) ? 1 : 0;
7644}
7645
7646unsigned clang_CXXMethod_isVirtual(CXCursor C) {
7647 if (!clang_isDeclaration(C.kind))
7648 return 0;
7649
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007650 const Decl *D = cxcursor::getCursorDecl(C);
Alp Tokera2794f92014-01-22 07:29:52 +00007651 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00007652 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007653 return (Method && Method->isVirtual()) ? 1 : 0;
7654}
Guy Benyei11169dd2012-12-18 14:30:41 +00007655
7656//===----------------------------------------------------------------------===//
7657// Attribute introspection.
7658//===----------------------------------------------------------------------===//
7659
Guy Benyei11169dd2012-12-18 14:30:41 +00007660CXType clang_getIBOutletCollectionType(CXCursor C) {
7661 if (C.kind != CXCursor_IBOutletCollectionAttr)
7662 return cxtype::MakeCXType(QualType(), cxcursor::getCursorTU(C));
7663
Dmitri Gribenkoe4baea62013-01-26 18:08:08 +00007664 const IBOutletCollectionAttr *A =
Guy Benyei11169dd2012-12-18 14:30:41 +00007665 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
7666
7667 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorTU(C));
7668}
Guy Benyei11169dd2012-12-18 14:30:41 +00007669
7670//===----------------------------------------------------------------------===//
7671// Inspecting memory usage.
7672//===----------------------------------------------------------------------===//
7673
7674typedef std::vector<CXTUResourceUsageEntry> MemUsageEntries;
7675
7676static inline void createCXTUResourceUsageEntry(MemUsageEntries &entries,
7677 enum CXTUResourceUsageKind k,
7678 unsigned long amount) {
7679 CXTUResourceUsageEntry entry = { k, amount };
7680 entries.push_back(entry);
7681}
7682
Guy Benyei11169dd2012-12-18 14:30:41 +00007683const char *clang_getTUResourceUsageName(CXTUResourceUsageKind kind) {
7684 const char *str = "";
7685 switch (kind) {
7686 case CXTUResourceUsage_AST:
7687 str = "ASTContext: expressions, declarations, and types";
7688 break;
7689 case CXTUResourceUsage_Identifiers:
7690 str = "ASTContext: identifiers";
7691 break;
7692 case CXTUResourceUsage_Selectors:
7693 str = "ASTContext: selectors";
7694 break;
7695 case CXTUResourceUsage_GlobalCompletionResults:
7696 str = "Code completion: cached global results";
7697 break;
7698 case CXTUResourceUsage_SourceManagerContentCache:
7699 str = "SourceManager: content cache allocator";
7700 break;
7701 case CXTUResourceUsage_AST_SideTables:
7702 str = "ASTContext: side tables";
7703 break;
7704 case CXTUResourceUsage_SourceManager_Membuffer_Malloc:
7705 str = "SourceManager: malloc'ed memory buffers";
7706 break;
7707 case CXTUResourceUsage_SourceManager_Membuffer_MMap:
7708 str = "SourceManager: mmap'ed memory buffers";
7709 break;
7710 case CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc:
7711 str = "ExternalASTSource: malloc'ed memory buffers";
7712 break;
7713 case CXTUResourceUsage_ExternalASTSource_Membuffer_MMap:
7714 str = "ExternalASTSource: mmap'ed memory buffers";
7715 break;
7716 case CXTUResourceUsage_Preprocessor:
7717 str = "Preprocessor: malloc'ed memory";
7718 break;
7719 case CXTUResourceUsage_PreprocessingRecord:
7720 str = "Preprocessor: PreprocessingRecord";
7721 break;
7722 case CXTUResourceUsage_SourceManager_DataStructures:
7723 str = "SourceManager: data structures and tables";
7724 break;
7725 case CXTUResourceUsage_Preprocessor_HeaderSearch:
7726 str = "Preprocessor: header search tables";
7727 break;
7728 }
7729 return str;
7730}
7731
7732CXTUResourceUsage clang_getCXTUResourceUsage(CXTranslationUnit TU) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00007733 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00007734 LOG_BAD_TU(TU);
Craig Topper69186e72014-06-08 08:38:04 +00007735 CXTUResourceUsage usage = { (void*) nullptr, 0, nullptr };
Guy Benyei11169dd2012-12-18 14:30:41 +00007736 return usage;
7737 }
7738
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00007739 ASTUnit *astUnit = cxtu::getASTUnit(TU);
Ahmed Charlesb8984322014-03-07 20:03:18 +00007740 std::unique_ptr<MemUsageEntries> entries(new MemUsageEntries());
Guy Benyei11169dd2012-12-18 14:30:41 +00007741 ASTContext &astContext = astUnit->getASTContext();
7742
7743 // How much memory is used by AST nodes and types?
7744 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST,
7745 (unsigned long) astContext.getASTAllocatedMemory());
7746
7747 // How much memory is used by identifiers?
7748 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Identifiers,
7749 (unsigned long) astContext.Idents.getAllocator().getTotalMemory());
7750
7751 // How much memory is used for selectors?
7752 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Selectors,
7753 (unsigned long) astContext.Selectors.getTotalMemory());
7754
7755 // How much memory is used by ASTContext's side tables?
7756 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST_SideTables,
7757 (unsigned long) astContext.getSideTableAllocatedMemory());
7758
7759 // How much memory is used for caching global code completion results?
7760 unsigned long completionBytes = 0;
7761 if (GlobalCodeCompletionAllocator *completionAllocator =
Alp Tokerf994cef2014-07-05 03:08:06 +00007762 astUnit->getCachedCompletionAllocator().get()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007763 completionBytes = completionAllocator->getTotalMemory();
7764 }
7765 createCXTUResourceUsageEntry(*entries,
7766 CXTUResourceUsage_GlobalCompletionResults,
7767 completionBytes);
7768
7769 // How much memory is being used by SourceManager's content cache?
7770 createCXTUResourceUsageEntry(*entries,
7771 CXTUResourceUsage_SourceManagerContentCache,
7772 (unsigned long) astContext.getSourceManager().getContentCacheSize());
7773
7774 // How much memory is being used by the MemoryBuffer's in SourceManager?
7775 const SourceManager::MemoryBufferSizes &srcBufs =
7776 astUnit->getSourceManager().getMemoryBufferSizes();
7777
7778 createCXTUResourceUsageEntry(*entries,
7779 CXTUResourceUsage_SourceManager_Membuffer_Malloc,
7780 (unsigned long) srcBufs.malloc_bytes);
7781 createCXTUResourceUsageEntry(*entries,
7782 CXTUResourceUsage_SourceManager_Membuffer_MMap,
7783 (unsigned long) srcBufs.mmap_bytes);
7784 createCXTUResourceUsageEntry(*entries,
7785 CXTUResourceUsage_SourceManager_DataStructures,
7786 (unsigned long) astContext.getSourceManager()
7787 .getDataStructureSizes());
7788
7789 // How much memory is being used by the ExternalASTSource?
7790 if (ExternalASTSource *esrc = astContext.getExternalSource()) {
7791 const ExternalASTSource::MemoryBufferSizes &sizes =
7792 esrc->getMemoryBufferSizes();
7793
7794 createCXTUResourceUsageEntry(*entries,
7795 CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc,
7796 (unsigned long) sizes.malloc_bytes);
7797 createCXTUResourceUsageEntry(*entries,
7798 CXTUResourceUsage_ExternalASTSource_Membuffer_MMap,
7799 (unsigned long) sizes.mmap_bytes);
7800 }
7801
7802 // How much memory is being used by the Preprocessor?
7803 Preprocessor &pp = astUnit->getPreprocessor();
7804 createCXTUResourceUsageEntry(*entries,
7805 CXTUResourceUsage_Preprocessor,
7806 pp.getTotalMemory());
7807
7808 if (PreprocessingRecord *pRec = pp.getPreprocessingRecord()) {
7809 createCXTUResourceUsageEntry(*entries,
7810 CXTUResourceUsage_PreprocessingRecord,
7811 pRec->getTotalMemory());
7812 }
7813
7814 createCXTUResourceUsageEntry(*entries,
7815 CXTUResourceUsage_Preprocessor_HeaderSearch,
7816 pp.getHeaderSearchInfo().getTotalMemory());
Craig Topper69186e72014-06-08 08:38:04 +00007817
Guy Benyei11169dd2012-12-18 14:30:41 +00007818 CXTUResourceUsage usage = { (void*) entries.get(),
7819 (unsigned) entries->size(),
Alexander Kornienko6ee521c2015-01-23 15:36:10 +00007820 !entries->empty() ? &(*entries)[0] : nullptr };
Eric Fiseliere95fc442016-11-14 07:03:50 +00007821 (void)entries.release();
Guy Benyei11169dd2012-12-18 14:30:41 +00007822 return usage;
7823}
7824
7825void clang_disposeCXTUResourceUsage(CXTUResourceUsage usage) {
7826 if (usage.data)
7827 delete (MemUsageEntries*) usage.data;
7828}
7829
Argyrios Kyrtzidis0e282ef2013-12-06 18:55:45 +00007830CXSourceRangeList *clang_getSkippedRanges(CXTranslationUnit TU, CXFile file) {
7831 CXSourceRangeList *skipped = new CXSourceRangeList;
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00007832 skipped->count = 0;
Craig Topper69186e72014-06-08 08:38:04 +00007833 skipped->ranges = nullptr;
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00007834
Dmitri Gribenko852d6222014-02-11 15:02:48 +00007835 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00007836 LOG_BAD_TU(TU);
7837 return skipped;
7838 }
7839
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00007840 if (!file)
7841 return skipped;
7842
7843 ASTUnit *astUnit = cxtu::getASTUnit(TU);
7844 PreprocessingRecord *ppRec = astUnit->getPreprocessor().getPreprocessingRecord();
7845 if (!ppRec)
7846 return skipped;
7847
7848 ASTContext &Ctx = astUnit->getASTContext();
7849 SourceManager &sm = Ctx.getSourceManager();
7850 FileEntry *fileEntry = static_cast<FileEntry *>(file);
7851 FileID wantedFileID = sm.translateFile(fileEntry);
7852
7853 const std::vector<SourceRange> &SkippedRanges = ppRec->getSkippedRanges();
7854 std::vector<SourceRange> wantedRanges;
7855 for (std::vector<SourceRange>::const_iterator i = SkippedRanges.begin(), ei = SkippedRanges.end();
7856 i != ei; ++i) {
7857 if (sm.getFileID(i->getBegin()) == wantedFileID || sm.getFileID(i->getEnd()) == wantedFileID)
7858 wantedRanges.push_back(*i);
7859 }
7860
7861 skipped->count = wantedRanges.size();
7862 skipped->ranges = new CXSourceRange[skipped->count];
7863 for (unsigned i = 0, ei = skipped->count; i != ei; ++i)
7864 skipped->ranges[i] = cxloc::translateSourceRange(Ctx, wantedRanges[i]);
7865
7866 return skipped;
7867}
7868
Cameron Desrochersd8091282016-08-18 15:43:55 +00007869CXSourceRangeList *clang_getAllSkippedRanges(CXTranslationUnit TU) {
7870 CXSourceRangeList *skipped = new CXSourceRangeList;
7871 skipped->count = 0;
7872 skipped->ranges = nullptr;
7873
7874 if (isNotUsableTU(TU)) {
7875 LOG_BAD_TU(TU);
7876 return skipped;
7877 }
7878
7879 ASTUnit *astUnit = cxtu::getASTUnit(TU);
7880 PreprocessingRecord *ppRec = astUnit->getPreprocessor().getPreprocessingRecord();
7881 if (!ppRec)
7882 return skipped;
7883
7884 ASTContext &Ctx = astUnit->getASTContext();
7885
7886 const std::vector<SourceRange> &SkippedRanges = ppRec->getSkippedRanges();
7887
7888 skipped->count = SkippedRanges.size();
7889 skipped->ranges = new CXSourceRange[skipped->count];
7890 for (unsigned i = 0, ei = skipped->count; i != ei; ++i)
7891 skipped->ranges[i] = cxloc::translateSourceRange(Ctx, SkippedRanges[i]);
7892
7893 return skipped;
7894}
7895
Argyrios Kyrtzidis0e282ef2013-12-06 18:55:45 +00007896void clang_disposeSourceRangeList(CXSourceRangeList *ranges) {
7897 if (ranges) {
7898 delete[] ranges->ranges;
7899 delete ranges;
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00007900 }
7901}
7902
Guy Benyei11169dd2012-12-18 14:30:41 +00007903void clang::PrintLibclangResourceUsage(CXTranslationUnit TU) {
7904 CXTUResourceUsage Usage = clang_getCXTUResourceUsage(TU);
7905 for (unsigned I = 0; I != Usage.numEntries; ++I)
7906 fprintf(stderr, " %s: %lu\n",
7907 clang_getTUResourceUsageName(Usage.entries[I].kind),
7908 Usage.entries[I].amount);
7909
7910 clang_disposeCXTUResourceUsage(Usage);
7911}
7912
7913//===----------------------------------------------------------------------===//
7914// Misc. utility functions.
7915//===----------------------------------------------------------------------===//
7916
7917/// Default to using an 8 MB stack size on "safety" threads.
7918static unsigned SafetyStackThreadSize = 8 << 20;
7919
7920namespace clang {
7921
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00007922bool RunSafely(llvm::CrashRecoveryContext &CRC, llvm::function_ref<void()> Fn,
Guy Benyei11169dd2012-12-18 14:30:41 +00007923 unsigned Size) {
7924 if (!Size)
7925 Size = GetSafetyThreadStackSize();
7926 if (Size)
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00007927 return CRC.RunSafelyOnThread(Fn, Size);
7928 return CRC.RunSafely(Fn);
Guy Benyei11169dd2012-12-18 14:30:41 +00007929}
7930
7931unsigned GetSafetyThreadStackSize() {
7932 return SafetyStackThreadSize;
7933}
7934
7935void SetSafetyThreadStackSize(unsigned Value) {
7936 SafetyStackThreadSize = Value;
7937}
7938
Alexander Kornienkoab9db512015-06-22 23:07:51 +00007939}
Guy Benyei11169dd2012-12-18 14:30:41 +00007940
7941void clang::setThreadBackgroundPriority() {
7942 if (getenv("LIBCLANG_BGPRIO_DISABLE"))
7943 return;
7944
Alp Toker1a86ad22014-07-06 06:24:00 +00007945#ifdef USE_DARWIN_THREADS
Guy Benyei11169dd2012-12-18 14:30:41 +00007946 setpriority(PRIO_DARWIN_THREAD, 0, PRIO_DARWIN_BG);
7947#endif
7948}
7949
7950void cxindex::printDiagsToStderr(ASTUnit *Unit) {
7951 if (!Unit)
7952 return;
7953
7954 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
7955 DEnd = Unit->stored_diag_end();
7956 D != DEnd; ++D) {
Ben Langmuir749323f2014-04-22 17:40:12 +00007957 CXStoredDiagnostic Diag(*D, Unit->getLangOpts());
Guy Benyei11169dd2012-12-18 14:30:41 +00007958 CXString Msg = clang_formatDiagnostic(&Diag,
7959 clang_defaultDiagnosticDisplayOptions());
7960 fprintf(stderr, "%s\n", clang_getCString(Msg));
7961 clang_disposeString(Msg);
7962 }
7963#ifdef LLVM_ON_WIN32
7964 // On Windows, force a flush, since there may be multiple copies of
7965 // stderr and stdout in the file system, all with different buffers
7966 // but writing to the same device.
7967 fflush(stderr);
7968#endif
7969}
7970
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007971MacroInfo *cxindex::getMacroInfo(const IdentifierInfo &II,
7972 SourceLocation MacroDefLoc,
7973 CXTranslationUnit TU){
7974 if (MacroDefLoc.isInvalid() || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00007975 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007976 if (!II.hadMacroDefinition())
Craig Topper69186e72014-06-08 08:38:04 +00007977 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007978
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00007979 ASTUnit *Unit = cxtu::getASTUnit(TU);
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007980 Preprocessor &PP = Unit->getPreprocessor();
Richard Smith20e883e2015-04-29 23:20:19 +00007981 MacroDirective *MD = PP.getLocalMacroDirectiveHistory(&II);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00007982 if (MD) {
7983 for (MacroDirective::DefInfo
7984 Def = MD->getDefinition(); Def; Def = Def.getPreviousDefinition()) {
7985 if (MacroDefLoc == Def.getMacroInfo()->getDefinitionLoc())
7986 return Def.getMacroInfo();
7987 }
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007988 }
7989
Craig Topper69186e72014-06-08 08:38:04 +00007990 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007991}
7992
Richard Smith66a81862015-05-04 02:25:31 +00007993const MacroInfo *cxindex::getMacroInfo(const MacroDefinitionRecord *MacroDef,
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00007994 CXTranslationUnit TU) {
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007995 if (!MacroDef || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00007996 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007997 const IdentifierInfo *II = MacroDef->getName();
7998 if (!II)
Craig Topper69186e72014-06-08 08:38:04 +00007999 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008000
8001 return getMacroInfo(*II, MacroDef->getLocation(), TU);
8002}
8003
Richard Smith66a81862015-05-04 02:25:31 +00008004MacroDefinitionRecord *
8005cxindex::checkForMacroInMacroDefinition(const MacroInfo *MI, const Token &Tok,
8006 CXTranslationUnit TU) {
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008007 if (!MI || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00008008 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008009 if (Tok.isNot(tok::raw_identifier))
Craig Topper69186e72014-06-08 08:38:04 +00008010 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008011
8012 if (MI->getNumTokens() == 0)
Craig Topper69186e72014-06-08 08:38:04 +00008013 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008014 SourceRange DefRange(MI->getReplacementToken(0).getLocation(),
8015 MI->getDefinitionEndLoc());
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008016 ASTUnit *Unit = cxtu::getASTUnit(TU);
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008017
8018 // Check that the token is inside the definition and not its argument list.
8019 SourceManager &SM = Unit->getSourceManager();
8020 if (SM.isBeforeInTranslationUnit(Tok.getLocation(), DefRange.getBegin()))
Craig Topper69186e72014-06-08 08:38:04 +00008021 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008022 if (SM.isBeforeInTranslationUnit(DefRange.getEnd(), Tok.getLocation()))
Craig Topper69186e72014-06-08 08:38:04 +00008023 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008024
8025 Preprocessor &PP = Unit->getPreprocessor();
8026 PreprocessingRecord *PPRec = PP.getPreprocessingRecord();
8027 if (!PPRec)
Craig Topper69186e72014-06-08 08:38:04 +00008028 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008029
Alp Toker2d57cea2014-05-17 04:53:25 +00008030 IdentifierInfo &II = PP.getIdentifierTable().get(Tok.getRawIdentifier());
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008031 if (!II.hadMacroDefinition())
Craig Topper69186e72014-06-08 08:38:04 +00008032 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008033
8034 // Check that the identifier is not one of the macro arguments.
8035 if (std::find(MI->arg_begin(), MI->arg_end(), &II) != MI->arg_end())
Craig Topper69186e72014-06-08 08:38:04 +00008036 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008037
Richard Smith20e883e2015-04-29 23:20:19 +00008038 MacroDirective *InnerMD = PP.getLocalMacroDirectiveHistory(&II);
Argyrios Kyrtzidis09c9e812013-02-20 00:54:57 +00008039 if (!InnerMD)
Craig Topper69186e72014-06-08 08:38:04 +00008040 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008041
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00008042 return PPRec->findMacroDefinition(InnerMD->getMacroInfo());
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008043}
8044
Richard Smith66a81862015-05-04 02:25:31 +00008045MacroDefinitionRecord *
8046cxindex::checkForMacroInMacroDefinition(const MacroInfo *MI, SourceLocation Loc,
8047 CXTranslationUnit TU) {
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008048 if (Loc.isInvalid() || !MI || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00008049 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008050
8051 if (MI->getNumTokens() == 0)
Craig Topper69186e72014-06-08 08:38:04 +00008052 return nullptr;
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008053 ASTUnit *Unit = cxtu::getASTUnit(TU);
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008054 Preprocessor &PP = Unit->getPreprocessor();
8055 if (!PP.getPreprocessingRecord())
Craig Topper69186e72014-06-08 08:38:04 +00008056 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008057 Loc = Unit->getSourceManager().getSpellingLoc(Loc);
8058 Token Tok;
8059 if (PP.getRawToken(Loc, Tok))
Craig Topper69186e72014-06-08 08:38:04 +00008060 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008061
8062 return checkForMacroInMacroDefinition(MI, Tok, TU);
8063}
8064
Guy Benyei11169dd2012-12-18 14:30:41 +00008065CXString clang_getClangVersion() {
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00008066 return cxstring::createDup(getClangFullVersion());
Guy Benyei11169dd2012-12-18 14:30:41 +00008067}
8068
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008069Logger &cxindex::Logger::operator<<(CXTranslationUnit TU) {
8070 if (TU) {
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008071 if (ASTUnit *Unit = cxtu::getASTUnit(TU)) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008072 LogOS << '<' << Unit->getMainFileName() << '>';
Argyrios Kyrtzidis37f2ab42013-03-05 20:21:14 +00008073 if (Unit->isMainFileAST())
8074 LogOS << " (" << Unit->getASTFileName() << ')';
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008075 return *this;
8076 }
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00008077 } else {
8078 LogOS << "<NULL TU>";
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008079 }
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008080 return *this;
8081}
8082
Argyrios Kyrtzidisba4b5f82013-03-08 02:32:26 +00008083Logger &cxindex::Logger::operator<<(const FileEntry *FE) {
8084 *this << FE->getName();
8085 return *this;
8086}
8087
8088Logger &cxindex::Logger::operator<<(CXCursor cursor) {
8089 CXString cursorName = clang_getCursorDisplayName(cursor);
8090 *this << cursorName << "@" << clang_getCursorLocation(cursor);
8091 clang_disposeString(cursorName);
8092 return *this;
8093}
8094
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008095Logger &cxindex::Logger::operator<<(CXSourceLocation Loc) {
8096 CXFile File;
8097 unsigned Line, Column;
Craig Topper69186e72014-06-08 08:38:04 +00008098 clang_getFileLocation(Loc, &File, &Line, &Column, nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008099 CXString FileName = clang_getFileName(File);
8100 *this << llvm::format("(%s:%d:%d)", clang_getCString(FileName), Line, Column);
8101 clang_disposeString(FileName);
8102 return *this;
8103}
8104
8105Logger &cxindex::Logger::operator<<(CXSourceRange range) {
8106 CXSourceLocation BLoc = clang_getRangeStart(range);
8107 CXSourceLocation ELoc = clang_getRangeEnd(range);
8108
8109 CXFile BFile;
8110 unsigned BLine, BColumn;
Craig Topper69186e72014-06-08 08:38:04 +00008111 clang_getFileLocation(BLoc, &BFile, &BLine, &BColumn, nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008112
8113 CXFile EFile;
8114 unsigned ELine, EColumn;
Craig Topper69186e72014-06-08 08:38:04 +00008115 clang_getFileLocation(ELoc, &EFile, &ELine, &EColumn, nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008116
8117 CXString BFileName = clang_getFileName(BFile);
8118 if (BFile == EFile) {
8119 *this << llvm::format("[%s %d:%d-%d:%d]", clang_getCString(BFileName),
8120 BLine, BColumn, ELine, EColumn);
8121 } else {
8122 CXString EFileName = clang_getFileName(EFile);
8123 *this << llvm::format("[%s:%d:%d - ", clang_getCString(BFileName),
8124 BLine, BColumn)
8125 << llvm::format("%s:%d:%d]", clang_getCString(EFileName),
8126 ELine, EColumn);
8127 clang_disposeString(EFileName);
8128 }
8129 clang_disposeString(BFileName);
8130 return *this;
8131}
8132
8133Logger &cxindex::Logger::operator<<(CXString Str) {
8134 *this << clang_getCString(Str);
8135 return *this;
8136}
8137
8138Logger &cxindex::Logger::operator<<(const llvm::format_object_base &Fmt) {
8139 LogOS << Fmt;
8140 return *this;
8141}
8142
Chandler Carruth37ad2582014-06-27 15:14:39 +00008143static llvm::ManagedStatic<llvm::sys::Mutex> LoggingMutex;
8144
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008145cxindex::Logger::~Logger() {
Chandler Carruth37ad2582014-06-27 15:14:39 +00008146 llvm::sys::ScopedLock L(*LoggingMutex);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008147
8148 static llvm::TimeRecord sBeginTR = llvm::TimeRecord::getCurrentTime();
8149
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008150 raw_ostream &OS = llvm::errs();
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008151 OS << "[libclang:" << Name << ':';
8152
Alp Toker1a86ad22014-07-06 06:24:00 +00008153#ifdef USE_DARWIN_THREADS
8154 // TODO: Portability.
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008155 mach_port_t tid = pthread_mach_thread_np(pthread_self());
8156 OS << tid << ':';
8157#endif
8158
8159 llvm::TimeRecord TR = llvm::TimeRecord::getCurrentTime();
8160 OS << llvm::format("%7.4f] ", TR.getWallTime() - sBeginTR.getWallTime());
Yaron Keren09fb7c62015-03-10 07:33:23 +00008161 OS << Msg << '\n';
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008162
8163 if (Trace) {
Zachary Turner1fe2a8d2015-03-05 19:15:09 +00008164 llvm::sys::PrintStackTrace(OS);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008165 OS << "--------------------------------------------------\n";
8166 }
8167}
Benjamin Kramerc1ffdab2016-03-03 08:58:18 +00008168
8169#ifdef CLANG_TOOL_EXTRA_BUILD
8170// This anchor is used to force the linker to link the clang-tidy plugin.
8171extern volatile int ClangTidyPluginAnchorSource;
8172static int LLVM_ATTRIBUTE_UNUSED ClangTidyPluginAnchorDestination =
8173 ClangTidyPluginAnchorSource;
Benjamin Kramer9eba7352016-11-17 15:22:36 +00008174
8175// This anchor is used to force the linker to link the clang-include-fixer
8176// plugin.
8177extern volatile int ClangIncludeFixerPluginAnchorSource;
8178static int LLVM_ATTRIBUTE_UNUSED ClangIncludeFixerPluginAnchorDestination =
8179 ClangIncludeFixerPluginAnchorSource;
Benjamin Kramerc1ffdab2016-03-03 08:58:18 +00008180#endif