blob: b90da16701d7af85cfb947770d3a785898d58fdb [file] [log] [blame]
Guy Benyei11169dd2012-12-18 14:30:41 +00001//===- CIndex.cpp - Clang-C Source Indexing Library -----------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the main API hooks in the Clang-C Source Indexing
11// library.
12//
13//===----------------------------------------------------------------------===//
14
Guy Benyei11169dd2012-12-18 14:30:41 +000015#include "CIndexDiagnostic.h"
Mehdi Amini9670f842016-07-18 19:02:11 +000016#include "CIndexer.h"
Chandler Carruth4b417452013-01-19 08:09:44 +000017#include "CLog.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000018#include "CXCursor.h"
19#include "CXSourceLocation.h"
20#include "CXString.h"
21#include "CXTranslationUnit.h"
22#include "CXType.h"
23#include "CursorVisitor.h"
David Blaikie0a4e61f2013-09-13 18:32:52 +000024#include "clang/AST/Attr.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000025#include "clang/AST/StmtVisitor.h"
26#include "clang/Basic/Diagnostic.h"
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +000027#include "clang/Basic/DiagnosticCategories.h"
28#include "clang/Basic/DiagnosticIDs.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000029#include "clang/Basic/Version.h"
30#include "clang/Frontend/ASTUnit.h"
31#include "clang/Frontend/CompilerInstance.h"
32#include "clang/Frontend/FrontendDiagnostic.h"
Argyrios Kyrtzidisca741ce2016-02-14 22:30:14 +000033#include "clang/Index/CodegenNameGenerator.h"
Dmitri Gribenko9e605112013-11-13 22:16:51 +000034#include "clang/Index/CommentToXML.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000035#include "clang/Lex/HeaderSearch.h"
36#include "clang/Lex/Lexer.h"
37#include "clang/Lex/PreprocessingRecord.h"
38#include "clang/Lex/Preprocessor.h"
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +000039#include "clang/Serialization/SerializationDiagnostic.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000040#include "llvm/ADT/Optional.h"
41#include "llvm/ADT/STLExtras.h"
42#include "llvm/ADT/StringSwitch.h"
Alp Toker1d257e12014-06-04 03:28:55 +000043#include "llvm/Config/llvm-config.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000044#include "llvm/Support/Compiler.h"
45#include "llvm/Support/CrashRecoveryContext.h"
Chandler Carruth4b417452013-01-19 08:09:44 +000046#include "llvm/Support/Format.h"
Chandler Carruth37ad2582014-06-27 15:14:39 +000047#include "llvm/Support/ManagedStatic.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000048#include "llvm/Support/MemoryBuffer.h"
49#include "llvm/Support/Mutex.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000050#include "llvm/Support/Program.h"
51#include "llvm/Support/SaveAndRestore.h"
52#include "llvm/Support/Signals.h"
Adrian Prantlbc068582015-07-08 01:00:30 +000053#include "llvm/Support/TargetSelect.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000054#include "llvm/Support/Threading.h"
55#include "llvm/Support/Timer.h"
56#include "llvm/Support/raw_ostream.h"
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +000057
Alp Toker1a86ad22014-07-06 06:24:00 +000058#if LLVM_ENABLE_THREADS != 0 && defined(__APPLE__)
59#define USE_DARWIN_THREADS
60#endif
61
62#ifdef USE_DARWIN_THREADS
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +000063#include <pthread.h>
64#endif
Guy Benyei11169dd2012-12-18 14:30:41 +000065
66using namespace clang;
67using namespace clang::cxcursor;
Guy Benyei11169dd2012-12-18 14:30:41 +000068using namespace clang::cxtu;
69using namespace clang::cxindex;
70
Dmitri Gribenkod36209e2013-01-26 21:32:42 +000071CXTranslationUnit cxtu::MakeCXTranslationUnit(CIndexer *CIdx, ASTUnit *AU) {
72 if (!AU)
Craig Topper69186e72014-06-08 08:38:04 +000073 return nullptr;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +000074 assert(CIdx);
Guy Benyei11169dd2012-12-18 14:30:41 +000075 CXTranslationUnit D = new CXTranslationUnitImpl();
76 D->CIdx = CIdx;
Dmitri Gribenkod36209e2013-01-26 21:32:42 +000077 D->TheASTUnit = AU;
Dmitri Gribenko74895212013-02-03 13:52:47 +000078 D->StringPool = new cxstring::CXStringPool();
Craig Topper69186e72014-06-08 08:38:04 +000079 D->Diagnostics = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +000080 D->OverridenCursorsPool = createOverridenCXCursorsPool();
Craig Topper69186e72014-06-08 08:38:04 +000081 D->CommentToXML = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +000082 return D;
83}
84
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +000085bool cxtu::isASTReadError(ASTUnit *AU) {
86 for (ASTUnit::stored_diag_iterator D = AU->stored_diag_begin(),
87 DEnd = AU->stored_diag_end();
88 D != DEnd; ++D) {
89 if (D->getLevel() >= DiagnosticsEngine::Error &&
90 DiagnosticIDs::getCategoryNumberForDiag(D->getID()) ==
91 diag::DiagCat_AST_Deserialization_Issue)
92 return true;
93 }
94 return false;
95}
96
Guy Benyei11169dd2012-12-18 14:30:41 +000097cxtu::CXTUOwner::~CXTUOwner() {
98 if (TU)
99 clang_disposeTranslationUnit(TU);
100}
101
102/// \brief Compare two source ranges to determine their relative position in
103/// the translation unit.
104static RangeComparisonResult RangeCompare(SourceManager &SM,
105 SourceRange R1,
106 SourceRange R2) {
107 assert(R1.isValid() && "First range is invalid?");
108 assert(R2.isValid() && "Second range is invalid?");
109 if (R1.getEnd() != R2.getBegin() &&
110 SM.isBeforeInTranslationUnit(R1.getEnd(), R2.getBegin()))
111 return RangeBefore;
112 if (R2.getEnd() != R1.getBegin() &&
113 SM.isBeforeInTranslationUnit(R2.getEnd(), R1.getBegin()))
114 return RangeAfter;
115 return RangeOverlap;
116}
117
118/// \brief Determine if a source location falls within, before, or after a
119/// a given source range.
120static RangeComparisonResult LocationCompare(SourceManager &SM,
121 SourceLocation L, SourceRange R) {
122 assert(R.isValid() && "First range is invalid?");
123 assert(L.isValid() && "Second range is invalid?");
124 if (L == R.getBegin() || L == R.getEnd())
125 return RangeOverlap;
126 if (SM.isBeforeInTranslationUnit(L, R.getBegin()))
127 return RangeBefore;
128 if (SM.isBeforeInTranslationUnit(R.getEnd(), L))
129 return RangeAfter;
130 return RangeOverlap;
131}
132
133/// \brief Translate a Clang source range into a CIndex source range.
134///
135/// Clang internally represents ranges where the end location points to the
136/// start of the token at the end. However, for external clients it is more
137/// useful to have a CXSourceRange be a proper half-open interval. This routine
138/// does the appropriate translation.
139CXSourceRange cxloc::translateSourceRange(const SourceManager &SM,
140 const LangOptions &LangOpts,
141 const CharSourceRange &R) {
142 // We want the last character in this location, so we will adjust the
143 // location accordingly.
144 SourceLocation EndLoc = R.getEnd();
145 if (EndLoc.isValid() && EndLoc.isMacroID() && !SM.isMacroArgExpansion(EndLoc))
146 EndLoc = SM.getExpansionRange(EndLoc).second;
Yaron Keren8b563662015-10-03 10:46:20 +0000147 if (R.isTokenRange() && EndLoc.isValid()) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000148 unsigned Length = Lexer::MeasureTokenLength(SM.getSpellingLoc(EndLoc),
149 SM, LangOpts);
150 EndLoc = EndLoc.getLocWithOffset(Length);
151 }
152
Bill Wendlingeade3622013-01-23 08:25:41 +0000153 CXSourceRange Result = {
Dmitri Gribenkof9304482013-01-23 15:56:07 +0000154 { &SM, &LangOpts },
Bill Wendlingeade3622013-01-23 08:25:41 +0000155 R.getBegin().getRawEncoding(),
156 EndLoc.getRawEncoding()
157 };
Guy Benyei11169dd2012-12-18 14:30:41 +0000158 return Result;
159}
160
161//===----------------------------------------------------------------------===//
162// Cursor visitor.
163//===----------------------------------------------------------------------===//
164
165static SourceRange getRawCursorExtent(CXCursor C);
166static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr);
167
168
169RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
170 return RangeCompare(AU->getSourceManager(), R, RegionOfInterest);
171}
172
173/// \brief Visit the given cursor and, if requested by the visitor,
174/// its children.
175///
176/// \param Cursor the cursor to visit.
177///
178/// \param CheckedRegionOfInterest if true, then the caller already checked
179/// that this cursor is within the region of interest.
180///
181/// \returns true if the visitation should be aborted, false if it
182/// should continue.
183bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
184 if (clang_isInvalid(Cursor.kind))
185 return false;
186
187 if (clang_isDeclaration(Cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +0000188 const Decl *D = getCursorDecl(Cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +0000189 if (!D) {
190 assert(0 && "Invalid declaration cursor");
191 return true; // abort.
192 }
193
194 // Ignore implicit declarations, unless it's an objc method because
195 // currently we should report implicit methods for properties when indexing.
196 if (D->isImplicit() && !isa<ObjCMethodDecl>(D))
197 return false;
198 }
199
200 // If we have a range of interest, and this cursor doesn't intersect with it,
201 // we're done.
202 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
203 SourceRange Range = getRawCursorExtent(Cursor);
204 if (Range.isInvalid() || CompareRegionOfInterest(Range))
205 return false;
206 }
207
208 switch (Visitor(Cursor, Parent, ClientData)) {
209 case CXChildVisit_Break:
210 return true;
211
212 case CXChildVisit_Continue:
213 return false;
214
215 case CXChildVisit_Recurse: {
216 bool ret = VisitChildren(Cursor);
217 if (PostChildrenVisitor)
218 if (PostChildrenVisitor(Cursor, ClientData))
219 return true;
220 return ret;
221 }
222 }
223
224 llvm_unreachable("Invalid CXChildVisitResult!");
225}
226
227static bool visitPreprocessedEntitiesInRange(SourceRange R,
228 PreprocessingRecord &PPRec,
229 CursorVisitor &Visitor) {
230 SourceManager &SM = Visitor.getASTUnit()->getSourceManager();
231 FileID FID;
232
233 if (!Visitor.shouldVisitIncludedEntities()) {
234 // If the begin/end of the range lie in the same FileID, do the optimization
235 // where we skip preprocessed entities that do not come from the same FileID.
236 FID = SM.getFileID(SM.getFileLoc(R.getBegin()));
237 if (FID != SM.getFileID(SM.getFileLoc(R.getEnd())))
238 FID = FileID();
239 }
240
Benjamin Kramerb4ef6682015-02-06 17:25:10 +0000241 const auto &Entities = PPRec.getPreprocessedEntitiesInRange(R);
242 return Visitor.visitPreprocessedEntities(Entities.begin(), Entities.end(),
Guy Benyei11169dd2012-12-18 14:30:41 +0000243 PPRec, FID);
244}
245
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000246bool CursorVisitor::visitFileRegion() {
Guy Benyei11169dd2012-12-18 14:30:41 +0000247 if (RegionOfInterest.isInvalid())
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000248 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000249
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +0000250 ASTUnit *Unit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +0000251 SourceManager &SM = Unit->getSourceManager();
252
253 std::pair<FileID, unsigned>
254 Begin = SM.getDecomposedLoc(SM.getFileLoc(RegionOfInterest.getBegin())),
255 End = SM.getDecomposedLoc(SM.getFileLoc(RegionOfInterest.getEnd()));
256
257 if (End.first != Begin.first) {
258 // If the end does not reside in the same file, try to recover by
259 // picking the end of the file of begin location.
260 End.first = Begin.first;
261 End.second = SM.getFileIDSize(Begin.first);
262 }
263
264 assert(Begin.first == End.first);
265 if (Begin.second > End.second)
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000266 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000267
268 FileID File = Begin.first;
269 unsigned Offset = Begin.second;
270 unsigned Length = End.second - Begin.second;
271
272 if (!VisitDeclsOnly && !VisitPreprocessorLast)
273 if (visitPreprocessedEntitiesInRegion())
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000274 return true; // visitation break.
Guy Benyei11169dd2012-12-18 14:30:41 +0000275
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000276 if (visitDeclsFromFileRegion(File, Offset, Length))
277 return true; // visitation break.
Guy Benyei11169dd2012-12-18 14:30:41 +0000278
279 if (!VisitDeclsOnly && VisitPreprocessorLast)
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000280 return visitPreprocessedEntitiesInRegion();
281
282 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000283}
284
285static bool isInLexicalContext(Decl *D, DeclContext *DC) {
286 if (!DC)
287 return false;
288
289 for (DeclContext *DeclDC = D->getLexicalDeclContext();
290 DeclDC; DeclDC = DeclDC->getLexicalParent()) {
291 if (DeclDC == DC)
292 return true;
293 }
294 return false;
295}
296
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000297bool CursorVisitor::visitDeclsFromFileRegion(FileID File,
Guy Benyei11169dd2012-12-18 14:30:41 +0000298 unsigned Offset, unsigned Length) {
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +0000299 ASTUnit *Unit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +0000300 SourceManager &SM = Unit->getSourceManager();
301 SourceRange Range = RegionOfInterest;
302
303 SmallVector<Decl *, 16> Decls;
304 Unit->findFileRegionDecls(File, Offset, Length, Decls);
305
306 // If we didn't find any file level decls for the file, try looking at the
307 // file that it was included from.
308 while (Decls.empty() || Decls.front()->isTopLevelDeclInObjCContainer()) {
309 bool Invalid = false;
310 const SrcMgr::SLocEntry &SLEntry = SM.getSLocEntry(File, &Invalid);
311 if (Invalid)
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000312 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000313
314 SourceLocation Outer;
315 if (SLEntry.isFile())
316 Outer = SLEntry.getFile().getIncludeLoc();
317 else
318 Outer = SLEntry.getExpansion().getExpansionLocStart();
319 if (Outer.isInvalid())
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000320 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000321
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000322 std::tie(File, Offset) = SM.getDecomposedExpansionLoc(Outer);
Guy Benyei11169dd2012-12-18 14:30:41 +0000323 Length = 0;
324 Unit->findFileRegionDecls(File, Offset, Length, Decls);
325 }
326
327 assert(!Decls.empty());
328
329 bool VisitedAtLeastOnce = false;
Craig Topper69186e72014-06-08 08:38:04 +0000330 DeclContext *CurDC = nullptr;
Craig Topper2341c0d2013-07-04 03:08:24 +0000331 SmallVectorImpl<Decl *>::iterator DIt = Decls.begin();
332 for (SmallVectorImpl<Decl *>::iterator DE = Decls.end(); DIt != DE; ++DIt) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000333 Decl *D = *DIt;
334 if (D->getSourceRange().isInvalid())
335 continue;
336
337 if (isInLexicalContext(D, CurDC))
338 continue;
339
340 CurDC = dyn_cast<DeclContext>(D);
341
342 if (TagDecl *TD = dyn_cast<TagDecl>(D))
343 if (!TD->isFreeStanding())
344 continue;
345
346 RangeComparisonResult CompRes = RangeCompare(SM, D->getSourceRange(),Range);
347 if (CompRes == RangeBefore)
348 continue;
349 if (CompRes == RangeAfter)
350 break;
351
352 assert(CompRes == RangeOverlap);
353 VisitedAtLeastOnce = true;
354
355 if (isa<ObjCContainerDecl>(D)) {
356 FileDI_current = &DIt;
357 FileDE_current = DE;
358 } else {
Craig Topper69186e72014-06-08 08:38:04 +0000359 FileDI_current = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +0000360 }
361
362 if (Visit(MakeCXCursor(D, TU, Range), /*CheckedRegionOfInterest=*/true))
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000363 return true; // visitation break.
Guy Benyei11169dd2012-12-18 14:30:41 +0000364 }
365
366 if (VisitedAtLeastOnce)
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000367 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000368
369 // No Decls overlapped with the range. Move up the lexical context until there
370 // is a context that contains the range or we reach the translation unit
371 // level.
372 DeclContext *DC = DIt == Decls.begin() ? (*DIt)->getLexicalDeclContext()
373 : (*(DIt-1))->getLexicalDeclContext();
374
375 while (DC && !DC->isTranslationUnit()) {
376 Decl *D = cast<Decl>(DC);
377 SourceRange CurDeclRange = D->getSourceRange();
378 if (CurDeclRange.isInvalid())
379 break;
380
381 if (RangeCompare(SM, CurDeclRange, Range) == RangeOverlap) {
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000382 if (Visit(MakeCXCursor(D, TU, Range), /*CheckedRegionOfInterest=*/true))
383 return true; // visitation break.
Guy Benyei11169dd2012-12-18 14:30:41 +0000384 }
385
386 DC = D->getLexicalDeclContext();
387 }
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000388
389 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000390}
391
392bool CursorVisitor::visitPreprocessedEntitiesInRegion() {
393 if (!AU->getPreprocessor().getPreprocessingRecord())
394 return false;
395
396 PreprocessingRecord &PPRec
397 = *AU->getPreprocessor().getPreprocessingRecord();
398 SourceManager &SM = AU->getSourceManager();
399
400 if (RegionOfInterest.isValid()) {
401 SourceRange MappedRange = AU->mapRangeToPreamble(RegionOfInterest);
402 SourceLocation B = MappedRange.getBegin();
403 SourceLocation E = MappedRange.getEnd();
404
405 if (AU->isInPreambleFileID(B)) {
406 if (SM.isLoadedSourceLocation(E))
407 return visitPreprocessedEntitiesInRange(SourceRange(B, E),
408 PPRec, *this);
409
410 // Beginning of range lies in the preamble but it also extends beyond
411 // it into the main file. Split the range into 2 parts, one covering
412 // the preamble and another covering the main file. This allows subsequent
413 // calls to visitPreprocessedEntitiesInRange to accept a source range that
414 // lies in the same FileID, allowing it to skip preprocessed entities that
415 // do not come from the same FileID.
416 bool breaked =
417 visitPreprocessedEntitiesInRange(
418 SourceRange(B, AU->getEndOfPreambleFileID()),
419 PPRec, *this);
420 if (breaked) return true;
421 return visitPreprocessedEntitiesInRange(
422 SourceRange(AU->getStartOfMainFileID(), E),
423 PPRec, *this);
424 }
425
426 return visitPreprocessedEntitiesInRange(SourceRange(B, E), PPRec, *this);
427 }
428
429 bool OnlyLocalDecls
430 = !AU->isMainFileAST() && AU->getOnlyLocalDecls();
431
432 if (OnlyLocalDecls)
433 return visitPreprocessedEntities(PPRec.local_begin(), PPRec.local_end(),
434 PPRec);
435
436 return visitPreprocessedEntities(PPRec.begin(), PPRec.end(), PPRec);
437}
438
439template<typename InputIterator>
440bool CursorVisitor::visitPreprocessedEntities(InputIterator First,
441 InputIterator Last,
442 PreprocessingRecord &PPRec,
443 FileID FID) {
444 for (; First != Last; ++First) {
445 if (!FID.isInvalid() && !PPRec.isEntityInFileID(First, FID))
446 continue;
447
448 PreprocessedEntity *PPE = *First;
Argyrios Kyrtzidis1030f262013-05-07 20:37:17 +0000449 if (!PPE)
450 continue;
451
Guy Benyei11169dd2012-12-18 14:30:41 +0000452 if (MacroExpansion *ME = dyn_cast<MacroExpansion>(PPE)) {
453 if (Visit(MakeMacroExpansionCursor(ME, TU)))
454 return true;
Richard Smith66a81862015-05-04 02:25:31 +0000455
Guy Benyei11169dd2012-12-18 14:30:41 +0000456 continue;
457 }
Richard Smith66a81862015-05-04 02:25:31 +0000458
459 if (MacroDefinitionRecord *MD = dyn_cast<MacroDefinitionRecord>(PPE)) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000460 if (Visit(MakeMacroDefinitionCursor(MD, TU)))
461 return true;
Richard Smith66a81862015-05-04 02:25:31 +0000462
Guy Benyei11169dd2012-12-18 14:30:41 +0000463 continue;
464 }
465
466 if (InclusionDirective *ID = dyn_cast<InclusionDirective>(PPE)) {
467 if (Visit(MakeInclusionDirectiveCursor(ID, TU)))
468 return true;
469
470 continue;
471 }
472 }
473
474 return false;
475}
476
477/// \brief Visit the children of the given cursor.
478///
479/// \returns true if the visitation should be aborted, false if it
480/// should continue.
481bool CursorVisitor::VisitChildren(CXCursor Cursor) {
482 if (clang_isReference(Cursor.kind) &&
483 Cursor.kind != CXCursor_CXXBaseSpecifier) {
484 // By definition, references have no children.
485 return false;
486 }
487
488 // Set the Parent field to Cursor, then back to its old value once we're
489 // done.
490 SetParentRAII SetParent(Parent, StmtParent, Cursor);
491
492 if (clang_isDeclaration(Cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +0000493 Decl *D = const_cast<Decl *>(getCursorDecl(Cursor));
Guy Benyei11169dd2012-12-18 14:30:41 +0000494 if (!D)
495 return false;
496
497 return VisitAttributes(D) || Visit(D);
498 }
499
500 if (clang_isStatement(Cursor.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +0000501 if (const Stmt *S = getCursorStmt(Cursor))
Guy Benyei11169dd2012-12-18 14:30:41 +0000502 return Visit(S);
503
504 return false;
505 }
506
507 if (clang_isExpression(Cursor.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +0000508 if (const Expr *E = getCursorExpr(Cursor))
Guy Benyei11169dd2012-12-18 14:30:41 +0000509 return Visit(E);
510
511 return false;
512 }
513
514 if (clang_isTranslationUnit(Cursor.kind)) {
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +0000515 CXTranslationUnit TU = getCursorTU(Cursor);
516 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +0000517
518 int VisitOrder[2] = { VisitPreprocessorLast, !VisitPreprocessorLast };
519 for (unsigned I = 0; I != 2; ++I) {
520 if (VisitOrder[I]) {
521 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
522 RegionOfInterest.isInvalid()) {
523 for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
524 TLEnd = CXXUnit->top_level_end();
525 TL != TLEnd; ++TL) {
Argyrios Kyrtzidise7c91042016-07-01 19:10:54 +0000526 const Optional<bool> V = handleDeclForVisitation(*TL);
527 if (!V.hasValue())
528 continue;
529 return V.getValue();
Guy Benyei11169dd2012-12-18 14:30:41 +0000530 }
531 } else if (VisitDeclContext(
532 CXXUnit->getASTContext().getTranslationUnitDecl()))
533 return true;
534 continue;
535 }
536
537 // Walk the preprocessing record.
538 if (CXXUnit->getPreprocessor().getPreprocessingRecord())
539 visitPreprocessedEntitiesInRegion();
540 }
541
542 return false;
543 }
544
545 if (Cursor.kind == CXCursor_CXXBaseSpecifier) {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +0000546 if (const CXXBaseSpecifier *Base = getCursorCXXBaseSpecifier(Cursor)) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000547 if (TypeSourceInfo *BaseTSInfo = Base->getTypeSourceInfo()) {
548 return Visit(BaseTSInfo->getTypeLoc());
549 }
550 }
551 }
552
553 if (Cursor.kind == CXCursor_IBOutletCollectionAttr) {
Dmitri Gribenkoe4baea62013-01-26 18:08:08 +0000554 const IBOutletCollectionAttr *A =
Guy Benyei11169dd2012-12-18 14:30:41 +0000555 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(Cursor));
Richard Smithb1f9a282013-10-31 01:56:18 +0000556 if (const ObjCObjectType *ObjT = A->getInterface()->getAs<ObjCObjectType>())
Richard Smithb87c4652013-10-31 21:23:20 +0000557 return Visit(cxcursor::MakeCursorObjCClassRef(
558 ObjT->getInterface(),
559 A->getInterfaceLoc()->getTypeLoc().getLocStart(), TU));
Guy Benyei11169dd2012-12-18 14:30:41 +0000560 }
561
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +0000562 // If pointing inside a macro definition, check if the token is an identifier
563 // that was ever defined as a macro. In such a case, create a "pseudo" macro
564 // expansion cursor for that token.
565 SourceLocation BeginLoc = RegionOfInterest.getBegin();
566 if (Cursor.kind == CXCursor_MacroDefinition &&
567 BeginLoc == RegionOfInterest.getEnd()) {
568 SourceLocation Loc = AU->mapLocationToPreamble(BeginLoc);
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +0000569 const MacroInfo *MI =
570 getMacroInfo(cxcursor::getCursorMacroDefinition(Cursor), TU);
Richard Smith66a81862015-05-04 02:25:31 +0000571 if (MacroDefinitionRecord *MacroDef =
572 checkForMacroInMacroDefinition(MI, Loc, TU))
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +0000573 return Visit(cxcursor::MakeMacroExpansionCursor(MacroDef, BeginLoc, TU));
574 }
575
Guy Benyei11169dd2012-12-18 14:30:41 +0000576 // Nothing to visit at the moment.
577 return false;
578}
579
580bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
581 if (TypeSourceInfo *TSInfo = B->getSignatureAsWritten())
582 if (Visit(TSInfo->getTypeLoc()))
583 return true;
584
585 if (Stmt *Body = B->getBody())
586 return Visit(MakeCXCursor(Body, StmtParent, TU, RegionOfInterest));
587
588 return false;
589}
590
Ted Kremenek03325582013-02-21 01:29:01 +0000591Optional<bool> CursorVisitor::shouldVisitCursor(CXCursor Cursor) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000592 if (RegionOfInterest.isValid()) {
593 SourceRange Range = getFullCursorExtent(Cursor, AU->getSourceManager());
594 if (Range.isInvalid())
David Blaikie7a30dc52013-02-21 01:47:18 +0000595 return None;
Guy Benyei11169dd2012-12-18 14:30:41 +0000596
597 switch (CompareRegionOfInterest(Range)) {
598 case RangeBefore:
599 // This declaration comes before the region of interest; skip it.
David Blaikie7a30dc52013-02-21 01:47:18 +0000600 return None;
Guy Benyei11169dd2012-12-18 14:30:41 +0000601
602 case RangeAfter:
603 // This declaration comes after the region of interest; we're done.
604 return false;
605
606 case RangeOverlap:
607 // This declaration overlaps the region of interest; visit it.
608 break;
609 }
610 }
611 return true;
612}
613
614bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
615 DeclContext::decl_iterator I = DC->decls_begin(), E = DC->decls_end();
616
617 // FIXME: Eventually remove. This part of a hack to support proper
618 // iteration over all Decls contained lexically within an ObjC container.
619 SaveAndRestore<DeclContext::decl_iterator*> DI_saved(DI_current, &I);
620 SaveAndRestore<DeclContext::decl_iterator> DE_saved(DE_current, E);
621
622 for ( ; I != E; ++I) {
623 Decl *D = *I;
624 if (D->getLexicalDeclContext() != DC)
625 continue;
Argyrios Kyrtzidise7c91042016-07-01 19:10:54 +0000626 const Optional<bool> V = handleDeclForVisitation(D);
Guy Benyei11169dd2012-12-18 14:30:41 +0000627 if (!V.hasValue())
628 continue;
Argyrios Kyrtzidise7c91042016-07-01 19:10:54 +0000629 return V.getValue();
Guy Benyei11169dd2012-12-18 14:30:41 +0000630 }
631 return false;
632}
633
Argyrios Kyrtzidise7c91042016-07-01 19:10:54 +0000634Optional<bool> CursorVisitor::handleDeclForVisitation(const Decl *D) {
635 CXCursor Cursor = MakeCXCursor(D, TU, RegionOfInterest);
636
637 // Ignore synthesized ivars here, otherwise if we have something like:
638 // @synthesize prop = _prop;
639 // and '_prop' is not declared, we will encounter a '_prop' ivar before
640 // encountering the 'prop' synthesize declaration and we will think that
641 // we passed the region-of-interest.
642 if (auto *ivarD = dyn_cast<ObjCIvarDecl>(D)) {
643 if (ivarD->getSynthesize())
644 return None;
645 }
646
647 // FIXME: ObjCClassRef/ObjCProtocolRef for forward class/protocol
648 // declarations is a mismatch with the compiler semantics.
649 if (Cursor.kind == CXCursor_ObjCInterfaceDecl) {
650 auto *ID = cast<ObjCInterfaceDecl>(D);
651 if (!ID->isThisDeclarationADefinition())
652 Cursor = MakeCursorObjCClassRef(ID, ID->getLocation(), TU);
653
654 } else if (Cursor.kind == CXCursor_ObjCProtocolDecl) {
655 auto *PD = cast<ObjCProtocolDecl>(D);
656 if (!PD->isThisDeclarationADefinition())
657 Cursor = MakeCursorObjCProtocolRef(PD, PD->getLocation(), TU);
658 }
659
660 const Optional<bool> V = shouldVisitCursor(Cursor);
661 if (!V.hasValue())
662 return None;
663 if (!V.getValue())
664 return false;
665 if (Visit(Cursor, true))
666 return true;
667 return None;
668}
669
Guy Benyei11169dd2012-12-18 14:30:41 +0000670bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
671 llvm_unreachable("Translation units are visited directly by Visit()");
672}
673
Sergey Kalinichev8f3b1872015-11-15 13:48:32 +0000674bool CursorVisitor::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
675 if (VisitTemplateParameters(D->getTemplateParameters()))
676 return true;
677
678 return Visit(MakeCXCursor(D->getTemplatedDecl(), TU, RegionOfInterest));
679}
680
Guy Benyei11169dd2012-12-18 14:30:41 +0000681bool CursorVisitor::VisitTypeAliasDecl(TypeAliasDecl *D) {
682 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
683 return Visit(TSInfo->getTypeLoc());
684
685 return false;
686}
687
688bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
689 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
690 return Visit(TSInfo->getTypeLoc());
691
692 return false;
693}
694
695bool CursorVisitor::VisitTagDecl(TagDecl *D) {
696 return VisitDeclContext(D);
697}
698
699bool CursorVisitor::VisitClassTemplateSpecializationDecl(
700 ClassTemplateSpecializationDecl *D) {
701 bool ShouldVisitBody = false;
702 switch (D->getSpecializationKind()) {
703 case TSK_Undeclared:
704 case TSK_ImplicitInstantiation:
705 // Nothing to visit
706 return false;
707
708 case TSK_ExplicitInstantiationDeclaration:
709 case TSK_ExplicitInstantiationDefinition:
710 break;
711
712 case TSK_ExplicitSpecialization:
713 ShouldVisitBody = true;
714 break;
715 }
716
717 // Visit the template arguments used in the specialization.
718 if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) {
719 TypeLoc TL = SpecType->getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +0000720 if (TemplateSpecializationTypeLoc TSTLoc =
721 TL.getAs<TemplateSpecializationTypeLoc>()) {
722 for (unsigned I = 0, N = TSTLoc.getNumArgs(); I != N; ++I)
723 if (VisitTemplateArgumentLoc(TSTLoc.getArgLoc(I)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000724 return true;
725 }
726 }
Alexander Kornienko1a9f1842015-12-28 15:24:08 +0000727
728 return ShouldVisitBody && VisitCXXRecordDecl(D);
Guy Benyei11169dd2012-12-18 14:30:41 +0000729}
730
731bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl(
732 ClassTemplatePartialSpecializationDecl *D) {
733 // FIXME: Visit the "outer" template parameter lists on the TagDecl
734 // before visiting these template parameters.
735 if (VisitTemplateParameters(D->getTemplateParameters()))
736 return true;
737
738 // Visit the partial specialization arguments.
Enea Zaffanella6dbe1872013-08-10 07:24:53 +0000739 const ASTTemplateArgumentListInfo *Info = D->getTemplateArgsAsWritten();
740 const TemplateArgumentLoc *TemplateArgs = Info->getTemplateArgs();
741 for (unsigned I = 0, N = Info->NumTemplateArgs; I != N; ++I)
Guy Benyei11169dd2012-12-18 14:30:41 +0000742 if (VisitTemplateArgumentLoc(TemplateArgs[I]))
743 return true;
744
745 return VisitCXXRecordDecl(D);
746}
747
748bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
749 // Visit the default argument.
750 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
751 if (TypeSourceInfo *DefArg = D->getDefaultArgumentInfo())
752 if (Visit(DefArg->getTypeLoc()))
753 return true;
754
755 return false;
756}
757
758bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
759 if (Expr *Init = D->getInitExpr())
760 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
761 return false;
762}
763
764bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
Argyrios Kyrtzidis2ec76742013-04-05 21:04:10 +0000765 unsigned NumParamList = DD->getNumTemplateParameterLists();
766 for (unsigned i = 0; i < NumParamList; i++) {
767 TemplateParameterList* Params = DD->getTemplateParameterList(i);
768 if (VisitTemplateParameters(Params))
769 return true;
770 }
771
Guy Benyei11169dd2012-12-18 14:30:41 +0000772 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
773 if (Visit(TSInfo->getTypeLoc()))
774 return true;
775
776 // Visit the nested-name-specifier, if present.
777 if (NestedNameSpecifierLoc QualifierLoc = DD->getQualifierLoc())
778 if (VisitNestedNameSpecifierLoc(QualifierLoc))
779 return true;
780
781 return false;
782}
783
Benjamin Kramer4cadf292014-03-07 21:51:58 +0000784/// \brief Compare two base or member initializers based on their source order.
785static int CompareCXXCtorInitializers(CXXCtorInitializer *const *X,
786 CXXCtorInitializer *const *Y) {
787 return (*X)->getSourceOrder() - (*Y)->getSourceOrder();
788}
789
Guy Benyei11169dd2012-12-18 14:30:41 +0000790bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Argyrios Kyrtzidis2ec76742013-04-05 21:04:10 +0000791 unsigned NumParamList = ND->getNumTemplateParameterLists();
792 for (unsigned i = 0; i < NumParamList; i++) {
793 TemplateParameterList* Params = ND->getTemplateParameterList(i);
794 if (VisitTemplateParameters(Params))
795 return true;
796 }
797
Guy Benyei11169dd2012-12-18 14:30:41 +0000798 if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
799 // Visit the function declaration's syntactic components in the order
800 // written. This requires a bit of work.
801 TypeLoc TL = TSInfo->getTypeLoc().IgnoreParens();
David Blaikie6adc78e2013-02-18 22:06:02 +0000802 FunctionTypeLoc FTL = TL.getAs<FunctionTypeLoc>();
Guy Benyei11169dd2012-12-18 14:30:41 +0000803
804 // If we have a function declared directly (without the use of a typedef),
805 // visit just the return type. Otherwise, just visit the function's type
806 // now.
Alp Toker42a16a62014-01-25 23:51:36 +0000807 if ((FTL && !isa<CXXConversionDecl>(ND) && Visit(FTL.getReturnLoc())) ||
Guy Benyei11169dd2012-12-18 14:30:41 +0000808 (!FTL && Visit(TL)))
809 return true;
810
811 // Visit the nested-name-specifier, if present.
812 if (NestedNameSpecifierLoc QualifierLoc = ND->getQualifierLoc())
813 if (VisitNestedNameSpecifierLoc(QualifierLoc))
814 return true;
815
816 // Visit the declaration name.
Argyrios Kyrtzidis4a4d2b42014-02-09 08:13:47 +0000817 if (!isa<CXXDestructorDecl>(ND))
818 if (VisitDeclarationNameInfo(ND->getNameInfo()))
819 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +0000820
821 // FIXME: Visit explicitly-specified template arguments!
822
823 // Visit the function parameters, if we have a function type.
David Blaikie6adc78e2013-02-18 22:06:02 +0000824 if (FTL && VisitFunctionTypeLoc(FTL, true))
Guy Benyei11169dd2012-12-18 14:30:41 +0000825 return true;
826
Bill Wendling44426052012-12-20 19:22:21 +0000827 // FIXME: Attributes?
Guy Benyei11169dd2012-12-18 14:30:41 +0000828 }
829
830 if (ND->doesThisDeclarationHaveABody() && !ND->isLateTemplateParsed()) {
831 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ND)) {
832 // Find the initializers that were written in the source.
833 SmallVector<CXXCtorInitializer *, 4> WrittenInits;
Aaron Ballman0ad78302014-03-13 17:34:31 +0000834 for (auto *I : Constructor->inits()) {
835 if (!I->isWritten())
Guy Benyei11169dd2012-12-18 14:30:41 +0000836 continue;
837
Aaron Ballman0ad78302014-03-13 17:34:31 +0000838 WrittenInits.push_back(I);
Guy Benyei11169dd2012-12-18 14:30:41 +0000839 }
840
841 // Sort the initializers in source order
Benjamin Kramer4cadf292014-03-07 21:51:58 +0000842 llvm::array_pod_sort(WrittenInits.begin(), WrittenInits.end(),
843 &CompareCXXCtorInitializers);
844
Guy Benyei11169dd2012-12-18 14:30:41 +0000845 // Visit the initializers in source order
846 for (unsigned I = 0, N = WrittenInits.size(); I != N; ++I) {
847 CXXCtorInitializer *Init = WrittenInits[I];
848 if (Init->isAnyMemberInitializer()) {
849 if (Visit(MakeCursorMemberRef(Init->getAnyMember(),
850 Init->getMemberLocation(), TU)))
851 return true;
852 } else if (TypeSourceInfo *TInfo = Init->getTypeSourceInfo()) {
853 if (Visit(TInfo->getTypeLoc()))
854 return true;
855 }
856
857 // Visit the initializer value.
858 if (Expr *Initializer = Init->getInit())
859 if (Visit(MakeCXCursor(Initializer, ND, TU, RegionOfInterest)))
860 return true;
861 }
862 }
863
864 if (Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest)))
865 return true;
866 }
867
868 return false;
869}
870
871bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
872 if (VisitDeclaratorDecl(D))
873 return true;
874
875 if (Expr *BitWidth = D->getBitWidth())
876 return Visit(MakeCXCursor(BitWidth, StmtParent, TU, RegionOfInterest));
877
878 return false;
879}
880
881bool CursorVisitor::VisitVarDecl(VarDecl *D) {
882 if (VisitDeclaratorDecl(D))
883 return true;
884
885 if (Expr *Init = D->getInit())
886 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
887
888 return false;
889}
890
891bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
892 if (VisitDeclaratorDecl(D))
893 return true;
894
895 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
896 if (Expr *DefArg = D->getDefaultArgument())
897 return Visit(MakeCXCursor(DefArg, StmtParent, TU, RegionOfInterest));
898
899 return false;
900}
901
902bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
903 // FIXME: Visit the "outer" template parameter lists on the FunctionDecl
904 // before visiting these template parameters.
905 if (VisitTemplateParameters(D->getTemplateParameters()))
906 return true;
907
908 return VisitFunctionDecl(D->getTemplatedDecl());
909}
910
911bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) {
912 // FIXME: Visit the "outer" template parameter lists on the TagDecl
913 // before visiting these template parameters.
914 if (VisitTemplateParameters(D->getTemplateParameters()))
915 return true;
916
917 return VisitCXXRecordDecl(D->getTemplatedDecl());
918}
919
920bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
921 if (VisitTemplateParameters(D->getTemplateParameters()))
922 return true;
923
924 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() &&
925 VisitTemplateArgumentLoc(D->getDefaultArgument()))
926 return true;
927
928 return false;
929}
930
Douglas Gregor9bda6cf2015-07-07 03:58:14 +0000931bool CursorVisitor::VisitObjCTypeParamDecl(ObjCTypeParamDecl *D) {
932 // Visit the bound, if it's explicit.
933 if (D->hasExplicitBound()) {
934 if (auto TInfo = D->getTypeSourceInfo()) {
935 if (Visit(TInfo->getTypeLoc()))
936 return true;
937 }
938 }
939
940 return false;
941}
942
Guy Benyei11169dd2012-12-18 14:30:41 +0000943bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Alp Toker314cc812014-01-25 16:55:45 +0000944 if (TypeSourceInfo *TSInfo = ND->getReturnTypeSourceInfo())
Guy Benyei11169dd2012-12-18 14:30:41 +0000945 if (Visit(TSInfo->getTypeLoc()))
946 return true;
947
David Majnemer59f77922016-06-24 04:05:48 +0000948 for (const auto *P : ND->parameters()) {
Aaron Ballman43b68be2014-03-07 17:50:17 +0000949 if (Visit(MakeCXCursor(P, TU, RegionOfInterest)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000950 return true;
951 }
952
Alexander Kornienko1a9f1842015-12-28 15:24:08 +0000953 return ND->isThisDeclarationADefinition() &&
954 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest));
Guy Benyei11169dd2012-12-18 14:30:41 +0000955}
956
957template <typename DeclIt>
958static void addRangedDeclsInContainer(DeclIt *DI_current, DeclIt DE_current,
959 SourceManager &SM, SourceLocation EndLoc,
960 SmallVectorImpl<Decl *> &Decls) {
961 DeclIt next = *DI_current;
962 while (++next != DE_current) {
963 Decl *D_next = *next;
964 if (!D_next)
965 break;
966 SourceLocation L = D_next->getLocStart();
967 if (!L.isValid())
968 break;
969 if (SM.isBeforeInTranslationUnit(L, EndLoc)) {
970 *DI_current = next;
971 Decls.push_back(D_next);
972 continue;
973 }
974 break;
975 }
976}
977
Guy Benyei11169dd2012-12-18 14:30:41 +0000978bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
979 // FIXME: Eventually convert back to just 'VisitDeclContext()'. Essentially
980 // an @implementation can lexically contain Decls that are not properly
981 // nested in the AST. When we identify such cases, we need to retrofit
982 // this nesting here.
983 if (!DI_current && !FileDI_current)
984 return VisitDeclContext(D);
985
986 // Scan the Decls that immediately come after the container
987 // in the current DeclContext. If any fall within the
988 // container's lexical region, stash them into a vector
989 // for later processing.
990 SmallVector<Decl *, 24> DeclsInContainer;
991 SourceLocation EndLoc = D->getSourceRange().getEnd();
992 SourceManager &SM = AU->getSourceManager();
993 if (EndLoc.isValid()) {
994 if (DI_current) {
995 addRangedDeclsInContainer(DI_current, DE_current, SM, EndLoc,
996 DeclsInContainer);
997 } else {
998 addRangedDeclsInContainer(FileDI_current, FileDE_current, SM, EndLoc,
999 DeclsInContainer);
1000 }
1001 }
1002
1003 // The common case.
1004 if (DeclsInContainer.empty())
1005 return VisitDeclContext(D);
1006
1007 // Get all the Decls in the DeclContext, and sort them with the
1008 // additional ones we've collected. Then visit them.
Aaron Ballman629afae2014-03-07 19:56:05 +00001009 for (auto *SubDecl : D->decls()) {
1010 if (!SubDecl || SubDecl->getLexicalDeclContext() != D ||
1011 SubDecl->getLocStart().isInvalid())
Guy Benyei11169dd2012-12-18 14:30:41 +00001012 continue;
Aaron Ballman629afae2014-03-07 19:56:05 +00001013 DeclsInContainer.push_back(SubDecl);
Guy Benyei11169dd2012-12-18 14:30:41 +00001014 }
1015
1016 // Now sort the Decls so that they appear in lexical order.
1017 std::sort(DeclsInContainer.begin(), DeclsInContainer.end(),
Benjamin Kramerbbdd7642014-03-01 14:48:57 +00001018 [&SM](Decl *A, Decl *B) {
1019 SourceLocation L_A = A->getLocStart();
1020 SourceLocation L_B = B->getLocStart();
1021 assert(L_A.isValid() && L_B.isValid());
1022 return SM.isBeforeInTranslationUnit(L_A, L_B);
1023 });
Guy Benyei11169dd2012-12-18 14:30:41 +00001024
1025 // Now visit the decls.
1026 for (SmallVectorImpl<Decl*>::iterator I = DeclsInContainer.begin(),
1027 E = DeclsInContainer.end(); I != E; ++I) {
1028 CXCursor Cursor = MakeCXCursor(*I, TU, RegionOfInterest);
Ted Kremenek03325582013-02-21 01:29:01 +00001029 const Optional<bool> &V = shouldVisitCursor(Cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00001030 if (!V.hasValue())
1031 continue;
1032 if (!V.getValue())
1033 return false;
1034 if (Visit(Cursor, true))
1035 return true;
1036 }
1037 return false;
1038}
1039
1040bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
1041 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
1042 TU)))
1043 return true;
1044
Douglas Gregore9d95f12015-07-07 03:57:35 +00001045 if (VisitObjCTypeParamList(ND->getTypeParamList()))
1046 return true;
1047
Guy Benyei11169dd2012-12-18 14:30:41 +00001048 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
1049 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
1050 E = ND->protocol_end(); I != E; ++I, ++PL)
1051 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
1052 return true;
1053
1054 return VisitObjCContainerDecl(ND);
1055}
1056
1057bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
1058 if (!PID->isThisDeclarationADefinition())
1059 return Visit(MakeCursorObjCProtocolRef(PID, PID->getLocation(), TU));
1060
1061 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
1062 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
1063 E = PID->protocol_end(); I != E; ++I, ++PL)
1064 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
1065 return true;
1066
1067 return VisitObjCContainerDecl(PID);
1068}
1069
1070bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
1071 if (PD->getTypeSourceInfo() && Visit(PD->getTypeSourceInfo()->getTypeLoc()))
1072 return true;
1073
1074 // FIXME: This implements a workaround with @property declarations also being
1075 // installed in the DeclContext for the @interface. Eventually this code
1076 // should be removed.
1077 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
1078 if (!CDecl || !CDecl->IsClassExtension())
1079 return false;
1080
1081 ObjCInterfaceDecl *ID = CDecl->getClassInterface();
1082 if (!ID)
1083 return false;
1084
1085 IdentifierInfo *PropertyId = PD->getIdentifier();
1086 ObjCPropertyDecl *prevDecl =
Manman Ren5b786402016-01-28 18:49:28 +00001087 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId,
1088 PD->getQueryKind());
Guy Benyei11169dd2012-12-18 14:30:41 +00001089
1090 if (!prevDecl)
1091 return false;
1092
1093 // Visit synthesized methods since they will be skipped when visiting
1094 // the @interface.
1095 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
1096 if (MD->isPropertyAccessor() && MD->getLexicalDeclContext() == CDecl)
1097 if (Visit(MakeCXCursor(MD, TU, RegionOfInterest)))
1098 return true;
1099
1100 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
1101 if (MD->isPropertyAccessor() && MD->getLexicalDeclContext() == CDecl)
1102 if (Visit(MakeCXCursor(MD, TU, RegionOfInterest)))
1103 return true;
1104
1105 return false;
1106}
1107
Douglas Gregore9d95f12015-07-07 03:57:35 +00001108bool CursorVisitor::VisitObjCTypeParamList(ObjCTypeParamList *typeParamList) {
1109 if (!typeParamList)
1110 return false;
1111
1112 for (auto *typeParam : *typeParamList) {
1113 // Visit the type parameter.
1114 if (Visit(MakeCXCursor(typeParam, TU, RegionOfInterest)))
1115 return true;
Douglas Gregore9d95f12015-07-07 03:57:35 +00001116 }
1117
1118 return false;
1119}
1120
Guy Benyei11169dd2012-12-18 14:30:41 +00001121bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
1122 if (!D->isThisDeclarationADefinition()) {
1123 // Forward declaration is treated like a reference.
1124 return Visit(MakeCursorObjCClassRef(D, D->getLocation(), TU));
1125 }
1126
Douglas Gregore9d95f12015-07-07 03:57:35 +00001127 // Objective-C type parameters.
1128 if (VisitObjCTypeParamList(D->getTypeParamListAsWritten()))
1129 return true;
1130
Guy Benyei11169dd2012-12-18 14:30:41 +00001131 // Issue callbacks for super class.
1132 if (D->getSuperClass() &&
1133 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
1134 D->getSuperClassLoc(),
1135 TU)))
1136 return true;
1137
Douglas Gregore9d95f12015-07-07 03:57:35 +00001138 if (TypeSourceInfo *SuperClassTInfo = D->getSuperClassTInfo())
1139 if (Visit(SuperClassTInfo->getTypeLoc()))
1140 return true;
1141
Guy Benyei11169dd2012-12-18 14:30:41 +00001142 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1143 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
1144 E = D->protocol_end(); I != E; ++I, ++PL)
1145 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
1146 return true;
1147
1148 return VisitObjCContainerDecl(D);
1149}
1150
1151bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
1152 return VisitObjCContainerDecl(D);
1153}
1154
1155bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
1156 // 'ID' could be null when dealing with invalid code.
1157 if (ObjCInterfaceDecl *ID = D->getClassInterface())
1158 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
1159 return true;
1160
1161 return VisitObjCImplDecl(D);
1162}
1163
1164bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
1165#if 0
1166 // Issue callbacks for super class.
1167 // FIXME: No source location information!
1168 if (D->getSuperClass() &&
1169 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
1170 D->getSuperClassLoc(),
1171 TU)))
1172 return true;
1173#endif
1174
1175 return VisitObjCImplDecl(D);
1176}
1177
1178bool CursorVisitor::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *PD) {
1179 if (ObjCIvarDecl *Ivar = PD->getPropertyIvarDecl())
1180 if (PD->isIvarNameSpecified())
1181 return Visit(MakeCursorMemberRef(Ivar, PD->getPropertyIvarDeclLoc(), TU));
1182
1183 return false;
1184}
1185
1186bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
1187 return VisitDeclContext(D);
1188}
1189
1190bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
1191 // Visit nested-name-specifier.
1192 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1193 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1194 return true;
1195
1196 return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(),
1197 D->getTargetNameLoc(), TU));
1198}
1199
1200bool CursorVisitor::VisitUsingDecl(UsingDecl *D) {
1201 // Visit nested-name-specifier.
1202 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1203 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1204 return true;
1205 }
1206
1207 if (Visit(MakeCursorOverloadedDeclRef(D, D->getLocation(), TU)))
1208 return true;
1209
1210 return VisitDeclarationNameInfo(D->getNameInfo());
1211}
1212
1213bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
1214 // Visit nested-name-specifier.
1215 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1216 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1217 return true;
1218
1219 return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(),
1220 D->getIdentLocation(), TU));
1221}
1222
1223bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
1224 // Visit nested-name-specifier.
1225 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1226 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1227 return true;
1228 }
1229
1230 return VisitDeclarationNameInfo(D->getNameInfo());
1231}
1232
1233bool CursorVisitor::VisitUnresolvedUsingTypenameDecl(
1234 UnresolvedUsingTypenameDecl *D) {
1235 // Visit nested-name-specifier.
1236 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1237 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1238 return true;
1239
1240 return false;
1241}
1242
Olivier Goffart81978012016-06-09 16:15:55 +00001243bool CursorVisitor::VisitStaticAssertDecl(StaticAssertDecl *D) {
1244 if (Visit(MakeCXCursor(D->getAssertExpr(), StmtParent, TU, RegionOfInterest)))
1245 return true;
Richard Trieuf3b77662016-09-13 01:37:01 +00001246 if (StringLiteral *Message = D->getMessage())
1247 if (Visit(MakeCXCursor(Message, StmtParent, TU, RegionOfInterest)))
1248 return true;
Olivier Goffart81978012016-06-09 16:15:55 +00001249 return false;
1250}
1251
Olivier Goffartd211c642016-11-04 06:29:27 +00001252bool CursorVisitor::VisitFriendDecl(FriendDecl *D) {
1253 if (NamedDecl *FriendD = D->getFriendDecl()) {
1254 if (Visit(MakeCXCursor(FriendD, TU, RegionOfInterest)))
1255 return true;
1256 } else if (TypeSourceInfo *TI = D->getFriendType()) {
1257 if (Visit(TI->getTypeLoc()))
1258 return true;
1259 }
1260 return false;
1261}
1262
Guy Benyei11169dd2012-12-18 14:30:41 +00001263bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
1264 switch (Name.getName().getNameKind()) {
1265 case clang::DeclarationName::Identifier:
1266 case clang::DeclarationName::CXXLiteralOperatorName:
1267 case clang::DeclarationName::CXXOperatorName:
1268 case clang::DeclarationName::CXXUsingDirective:
1269 return false;
1270
1271 case clang::DeclarationName::CXXConstructorName:
1272 case clang::DeclarationName::CXXDestructorName:
1273 case clang::DeclarationName::CXXConversionFunctionName:
1274 if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
1275 return Visit(TSInfo->getTypeLoc());
1276 return false;
1277
1278 case clang::DeclarationName::ObjCZeroArgSelector:
1279 case clang::DeclarationName::ObjCOneArgSelector:
1280 case clang::DeclarationName::ObjCMultiArgSelector:
1281 // FIXME: Per-identifier location info?
1282 return false;
1283 }
1284
1285 llvm_unreachable("Invalid DeclarationName::Kind!");
1286}
1287
1288bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS,
1289 SourceRange Range) {
1290 // FIXME: This whole routine is a hack to work around the lack of proper
1291 // source information in nested-name-specifiers (PR5791). Since we do have
1292 // a beginning source location, we can visit the first component of the
1293 // nested-name-specifier, if it's a single-token component.
1294 if (!NNS)
1295 return false;
1296
1297 // Get the first component in the nested-name-specifier.
1298 while (NestedNameSpecifier *Prefix = NNS->getPrefix())
1299 NNS = Prefix;
1300
1301 switch (NNS->getKind()) {
1302 case NestedNameSpecifier::Namespace:
1303 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(),
1304 TU));
1305
1306 case NestedNameSpecifier::NamespaceAlias:
1307 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
1308 Range.getBegin(), TU));
1309
1310 case NestedNameSpecifier::TypeSpec: {
1311 // If the type has a form where we know that the beginning of the source
1312 // range matches up with a reference cursor. Visit the appropriate reference
1313 // cursor.
1314 const Type *T = NNS->getAsType();
1315 if (const TypedefType *Typedef = dyn_cast<TypedefType>(T))
1316 return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU));
1317 if (const TagType *Tag = dyn_cast<TagType>(T))
1318 return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU));
1319 if (const TemplateSpecializationType *TST
1320 = dyn_cast<TemplateSpecializationType>(T))
1321 return VisitTemplateName(TST->getTemplateName(), Range.getBegin());
1322 break;
1323 }
1324
1325 case NestedNameSpecifier::TypeSpecWithTemplate:
1326 case NestedNameSpecifier::Global:
1327 case NestedNameSpecifier::Identifier:
Nikola Smiljanic67860242014-09-26 00:28:20 +00001328 case NestedNameSpecifier::Super:
Guy Benyei11169dd2012-12-18 14:30:41 +00001329 break;
1330 }
1331
1332 return false;
1333}
1334
1335bool
1336CursorVisitor::VisitNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
1337 SmallVector<NestedNameSpecifierLoc, 4> Qualifiers;
1338 for (; Qualifier; Qualifier = Qualifier.getPrefix())
1339 Qualifiers.push_back(Qualifier);
1340
1341 while (!Qualifiers.empty()) {
1342 NestedNameSpecifierLoc Q = Qualifiers.pop_back_val();
1343 NestedNameSpecifier *NNS = Q.getNestedNameSpecifier();
1344 switch (NNS->getKind()) {
1345 case NestedNameSpecifier::Namespace:
1346 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(),
1347 Q.getLocalBeginLoc(),
1348 TU)))
1349 return true;
1350
1351 break;
1352
1353 case NestedNameSpecifier::NamespaceAlias:
1354 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
1355 Q.getLocalBeginLoc(),
1356 TU)))
1357 return true;
1358
1359 break;
1360
1361 case NestedNameSpecifier::TypeSpec:
1362 case NestedNameSpecifier::TypeSpecWithTemplate:
1363 if (Visit(Q.getTypeLoc()))
1364 return true;
1365
1366 break;
1367
1368 case NestedNameSpecifier::Global:
1369 case NestedNameSpecifier::Identifier:
Nikola Smiljanic67860242014-09-26 00:28:20 +00001370 case NestedNameSpecifier::Super:
Guy Benyei11169dd2012-12-18 14:30:41 +00001371 break;
1372 }
1373 }
1374
1375 return false;
1376}
1377
1378bool CursorVisitor::VisitTemplateParameters(
1379 const TemplateParameterList *Params) {
1380 if (!Params)
1381 return false;
1382
1383 for (TemplateParameterList::const_iterator P = Params->begin(),
1384 PEnd = Params->end();
1385 P != PEnd; ++P) {
1386 if (Visit(MakeCXCursor(*P, TU, RegionOfInterest)))
1387 return true;
1388 }
1389
1390 return false;
1391}
1392
1393bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) {
1394 switch (Name.getKind()) {
1395 case TemplateName::Template:
1396 return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
1397
1398 case TemplateName::OverloadedTemplate:
1399 // Visit the overloaded template set.
1400 if (Visit(MakeCursorOverloadedDeclRef(Name, Loc, TU)))
1401 return true;
1402
1403 return false;
1404
1405 case TemplateName::DependentTemplate:
1406 // FIXME: Visit nested-name-specifier.
1407 return false;
1408
1409 case TemplateName::QualifiedTemplate:
1410 // FIXME: Visit nested-name-specifier.
1411 return Visit(MakeCursorTemplateRef(
1412 Name.getAsQualifiedTemplateName()->getDecl(),
1413 Loc, TU));
1414
1415 case TemplateName::SubstTemplateTemplateParm:
1416 return Visit(MakeCursorTemplateRef(
1417 Name.getAsSubstTemplateTemplateParm()->getParameter(),
1418 Loc, TU));
1419
1420 case TemplateName::SubstTemplateTemplateParmPack:
1421 return Visit(MakeCursorTemplateRef(
1422 Name.getAsSubstTemplateTemplateParmPack()->getParameterPack(),
1423 Loc, TU));
1424 }
1425
1426 llvm_unreachable("Invalid TemplateName::Kind!");
1427}
1428
1429bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
1430 switch (TAL.getArgument().getKind()) {
1431 case TemplateArgument::Null:
1432 case TemplateArgument::Integral:
1433 case TemplateArgument::Pack:
1434 return false;
1435
1436 case TemplateArgument::Type:
1437 if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
1438 return Visit(TSInfo->getTypeLoc());
1439 return false;
1440
1441 case TemplateArgument::Declaration:
1442 if (Expr *E = TAL.getSourceDeclExpression())
1443 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
1444 return false;
1445
1446 case TemplateArgument::NullPtr:
1447 if (Expr *E = TAL.getSourceNullPtrExpression())
1448 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
1449 return false;
1450
1451 case TemplateArgument::Expression:
1452 if (Expr *E = TAL.getSourceExpression())
1453 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
1454 return false;
1455
1456 case TemplateArgument::Template:
1457 case TemplateArgument::TemplateExpansion:
1458 if (VisitNestedNameSpecifierLoc(TAL.getTemplateQualifierLoc()))
1459 return true;
1460
1461 return VisitTemplateName(TAL.getArgument().getAsTemplateOrTemplatePattern(),
1462 TAL.getTemplateNameLoc());
1463 }
1464
1465 llvm_unreachable("Invalid TemplateArgument::Kind!");
1466}
1467
1468bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1469 return VisitDeclContext(D);
1470}
1471
1472bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1473 return Visit(TL.getUnqualifiedLoc());
1474}
1475
1476bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
1477 ASTContext &Context = AU->getASTContext();
1478
1479 // Some builtin types (such as Objective-C's "id", "sel", and
1480 // "Class") have associated declarations. Create cursors for those.
1481 QualType VisitType;
1482 switch (TL.getTypePtr()->getKind()) {
1483
1484 case BuiltinType::Void:
1485 case BuiltinType::NullPtr:
1486 case BuiltinType::Dependent:
Alexey Bader954ba212016-04-08 13:40:33 +00001487#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1488 case BuiltinType::Id:
Alexey Baderb62f1442016-04-13 08:33:41 +00001489#include "clang/Basic/OpenCLImageTypes.def"
NAKAMURA Takumi288c42e2013-02-07 12:47:42 +00001490 case BuiltinType::OCLSampler:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001491 case BuiltinType::OCLEvent:
Alexey Bader9c8453f2015-09-15 11:18:52 +00001492 case BuiltinType::OCLClkEvent:
1493 case BuiltinType::OCLQueue:
1494 case BuiltinType::OCLNDRange:
1495 case BuiltinType::OCLReserveID:
Guy Benyei11169dd2012-12-18 14:30:41 +00001496#define BUILTIN_TYPE(Id, SingletonId)
1497#define SIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
1498#define UNSIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
1499#define FLOATING_TYPE(Id, SingletonId) case BuiltinType::Id:
1500#define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id:
1501#include "clang/AST/BuiltinTypes.def"
1502 break;
1503
1504 case BuiltinType::ObjCId:
1505 VisitType = Context.getObjCIdType();
1506 break;
1507
1508 case BuiltinType::ObjCClass:
1509 VisitType = Context.getObjCClassType();
1510 break;
1511
1512 case BuiltinType::ObjCSel:
1513 VisitType = Context.getObjCSelType();
1514 break;
1515 }
1516
1517 if (!VisitType.isNull()) {
1518 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
1519 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
1520 TU));
1521 }
1522
1523 return false;
1524}
1525
1526bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
1527 return Visit(MakeCursorTypeRef(TL.getTypedefNameDecl(), TL.getNameLoc(), TU));
1528}
1529
1530bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
1531 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1532}
1533
1534bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
1535 if (TL.isDefinition())
1536 return Visit(MakeCXCursor(TL.getDecl(), TU, RegionOfInterest));
1537
1538 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1539}
1540
1541bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
1542 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1543}
1544
1545bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
Hans Wennborg59dbe862015-09-29 20:56:43 +00001546 return Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU));
Guy Benyei11169dd2012-12-18 14:30:41 +00001547}
1548
Manman Rene6be26c2016-09-13 17:25:08 +00001549bool CursorVisitor::VisitObjCTypeParamTypeLoc(ObjCTypeParamTypeLoc TL) {
1550 if (Visit(MakeCursorTypeRef(TL.getDecl(), TL.getLocStart(), TU)))
1551 return true;
1552 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1553 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1554 TU)))
1555 return true;
1556 }
1557
1558 return false;
1559}
1560
Guy Benyei11169dd2012-12-18 14:30:41 +00001561bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1562 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
1563 return true;
1564
Douglas Gregore9d95f12015-07-07 03:57:35 +00001565 for (unsigned I = 0, N = TL.getNumTypeArgs(); I != N; ++I) {
1566 if (Visit(TL.getTypeArgTInfo(I)->getTypeLoc()))
1567 return true;
1568 }
1569
Guy Benyei11169dd2012-12-18 14:30:41 +00001570 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1571 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1572 TU)))
1573 return true;
1574 }
1575
1576 return false;
1577}
1578
1579bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
1580 return Visit(TL.getPointeeLoc());
1581}
1582
1583bool CursorVisitor::VisitParenTypeLoc(ParenTypeLoc TL) {
1584 return Visit(TL.getInnerLoc());
1585}
1586
1587bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
1588 return Visit(TL.getPointeeLoc());
1589}
1590
1591bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1592 return Visit(TL.getPointeeLoc());
1593}
1594
1595bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1596 return Visit(TL.getPointeeLoc());
1597}
1598
1599bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
1600 return Visit(TL.getPointeeLoc());
1601}
1602
1603bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
1604 return Visit(TL.getPointeeLoc());
1605}
1606
1607bool CursorVisitor::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
1608 return Visit(TL.getModifiedLoc());
1609}
1610
1611bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
1612 bool SkipResultType) {
Alp Toker42a16a62014-01-25 23:51:36 +00001613 if (!SkipResultType && Visit(TL.getReturnLoc()))
Guy Benyei11169dd2012-12-18 14:30:41 +00001614 return true;
1615
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00001616 for (unsigned I = 0, N = TL.getNumParams(); I != N; ++I)
1617 if (Decl *D = TL.getParam(I))
Guy Benyei11169dd2012-12-18 14:30:41 +00001618 if (Visit(MakeCXCursor(D, TU, RegionOfInterest)))
1619 return true;
1620
1621 return false;
1622}
1623
1624bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
1625 if (Visit(TL.getElementLoc()))
1626 return true;
1627
1628 if (Expr *Size = TL.getSizeExpr())
1629 return Visit(MakeCXCursor(Size, StmtParent, TU, RegionOfInterest));
1630
1631 return false;
1632}
1633
Reid Kleckner8a365022013-06-24 17:51:48 +00001634bool CursorVisitor::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
1635 return Visit(TL.getOriginalLoc());
1636}
1637
Reid Kleckner0503a872013-12-05 01:23:43 +00001638bool CursorVisitor::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
1639 return Visit(TL.getOriginalLoc());
1640}
1641
Guy Benyei11169dd2012-12-18 14:30:41 +00001642bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
1643 TemplateSpecializationTypeLoc TL) {
1644 // Visit the template name.
1645 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1646 TL.getTemplateNameLoc()))
1647 return true;
1648
1649 // Visit the template arguments.
1650 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1651 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1652 return true;
1653
1654 return false;
1655}
1656
1657bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1658 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
1659}
1660
1661bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1662 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1663 return Visit(TSInfo->getTypeLoc());
1664
1665 return false;
1666}
1667
1668bool CursorVisitor::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
1669 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1670 return Visit(TSInfo->getTypeLoc());
1671
1672 return false;
1673}
1674
1675bool CursorVisitor::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
Hans Wennborg59dbe862015-09-29 20:56:43 +00001676 return VisitNestedNameSpecifierLoc(TL.getQualifierLoc());
Guy Benyei11169dd2012-12-18 14:30:41 +00001677}
1678
1679bool CursorVisitor::VisitDependentTemplateSpecializationTypeLoc(
1680 DependentTemplateSpecializationTypeLoc TL) {
1681 // Visit the nested-name-specifier, if there is one.
1682 if (TL.getQualifierLoc() &&
1683 VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1684 return true;
1685
1686 // Visit the template arguments.
1687 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1688 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1689 return true;
1690
1691 return false;
1692}
1693
1694bool CursorVisitor::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
1695 if (VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1696 return true;
1697
1698 return Visit(TL.getNamedTypeLoc());
1699}
1700
1701bool CursorVisitor::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
1702 return Visit(TL.getPatternLoc());
1703}
1704
1705bool CursorVisitor::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
1706 if (Expr *E = TL.getUnderlyingExpr())
1707 return Visit(MakeCXCursor(E, StmtParent, TU));
1708
1709 return false;
1710}
1711
1712bool CursorVisitor::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
1713 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1714}
1715
1716bool CursorVisitor::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
1717 return Visit(TL.getValueLoc());
1718}
1719
Xiuli Pan9c14e282016-01-09 12:53:17 +00001720bool CursorVisitor::VisitPipeTypeLoc(PipeTypeLoc TL) {
1721 return Visit(TL.getValueLoc());
1722}
1723
Guy Benyei11169dd2012-12-18 14:30:41 +00001724#define DEFAULT_TYPELOC_IMPL(CLASS, PARENT) \
1725bool CursorVisitor::Visit##CLASS##TypeLoc(CLASS##TypeLoc TL) { \
1726 return Visit##PARENT##Loc(TL); \
1727}
1728
1729DEFAULT_TYPELOC_IMPL(Complex, Type)
1730DEFAULT_TYPELOC_IMPL(ConstantArray, ArrayType)
1731DEFAULT_TYPELOC_IMPL(IncompleteArray, ArrayType)
1732DEFAULT_TYPELOC_IMPL(VariableArray, ArrayType)
1733DEFAULT_TYPELOC_IMPL(DependentSizedArray, ArrayType)
1734DEFAULT_TYPELOC_IMPL(DependentSizedExtVector, Type)
1735DEFAULT_TYPELOC_IMPL(Vector, Type)
1736DEFAULT_TYPELOC_IMPL(ExtVector, VectorType)
1737DEFAULT_TYPELOC_IMPL(FunctionProto, FunctionType)
1738DEFAULT_TYPELOC_IMPL(FunctionNoProto, FunctionType)
1739DEFAULT_TYPELOC_IMPL(Record, TagType)
1740DEFAULT_TYPELOC_IMPL(Enum, TagType)
1741DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParm, Type)
1742DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParmPack, Type)
1743DEFAULT_TYPELOC_IMPL(Auto, Type)
1744
1745bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
1746 // Visit the nested-name-specifier, if present.
1747 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1748 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1749 return true;
1750
1751 if (D->isCompleteDefinition()) {
Aaron Ballman574705e2014-03-13 15:41:46 +00001752 for (const auto &I : D->bases()) {
1753 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(&I, TU)))
Guy Benyei11169dd2012-12-18 14:30:41 +00001754 return true;
1755 }
1756 }
1757
1758 return VisitTagDecl(D);
1759}
1760
1761bool CursorVisitor::VisitAttributes(Decl *D) {
Aaron Ballmanb97112e2014-03-08 22:19:01 +00001762 for (const auto *I : D->attrs())
1763 if (Visit(MakeCXCursor(I, D, TU)))
Guy Benyei11169dd2012-12-18 14:30:41 +00001764 return true;
1765
1766 return false;
1767}
1768
1769//===----------------------------------------------------------------------===//
1770// Data-recursive visitor methods.
1771//===----------------------------------------------------------------------===//
1772
1773namespace {
1774#define DEF_JOB(NAME, DATA, KIND)\
1775class NAME : public VisitorJob {\
1776public:\
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001777 NAME(const DATA *d, CXCursor parent) : \
1778 VisitorJob(parent, VisitorJob::KIND, d) {} \
Guy Benyei11169dd2012-12-18 14:30:41 +00001779 static bool classof(const VisitorJob *VJ) { return VJ->getKind() == KIND; }\
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001780 const DATA *get() const { return static_cast<const DATA*>(data[0]); }\
Guy Benyei11169dd2012-12-18 14:30:41 +00001781};
1782
1783DEF_JOB(StmtVisit, Stmt, StmtVisitKind)
1784DEF_JOB(MemberExprParts, MemberExpr, MemberExprPartsKind)
1785DEF_JOB(DeclRefExprParts, DeclRefExpr, DeclRefExprPartsKind)
1786DEF_JOB(OverloadExprParts, OverloadExpr, OverloadExprPartsKind)
Guy Benyei11169dd2012-12-18 14:30:41 +00001787DEF_JOB(SizeOfPackExprParts, SizeOfPackExpr, SizeOfPackExprPartsKind)
1788DEF_JOB(LambdaExprParts, LambdaExpr, LambdaExprPartsKind)
1789DEF_JOB(PostChildrenVisit, void, PostChildrenVisitKind)
1790#undef DEF_JOB
1791
James Y Knight04ec5bf2015-12-24 02:59:37 +00001792class ExplicitTemplateArgsVisit : public VisitorJob {
1793public:
1794 ExplicitTemplateArgsVisit(const TemplateArgumentLoc *Begin,
1795 const TemplateArgumentLoc *End, CXCursor parent)
1796 : VisitorJob(parent, VisitorJob::ExplicitTemplateArgsVisitKind, Begin,
1797 End) {}
1798 static bool classof(const VisitorJob *VJ) {
1799 return VJ->getKind() == ExplicitTemplateArgsVisitKind;
1800 }
1801 const TemplateArgumentLoc *begin() const {
1802 return static_cast<const TemplateArgumentLoc *>(data[0]);
1803 }
1804 const TemplateArgumentLoc *end() {
1805 return static_cast<const TemplateArgumentLoc *>(data[1]);
1806 }
1807};
Guy Benyei11169dd2012-12-18 14:30:41 +00001808class DeclVisit : public VisitorJob {
1809public:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001810 DeclVisit(const Decl *D, CXCursor parent, bool isFirst) :
Guy Benyei11169dd2012-12-18 14:30:41 +00001811 VisitorJob(parent, VisitorJob::DeclVisitKind,
Craig Topper69186e72014-06-08 08:38:04 +00001812 D, isFirst ? (void*) 1 : (void*) nullptr) {}
Guy Benyei11169dd2012-12-18 14:30:41 +00001813 static bool classof(const VisitorJob *VJ) {
1814 return VJ->getKind() == DeclVisitKind;
1815 }
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001816 const Decl *get() const { return static_cast<const Decl *>(data[0]); }
Dmitri Gribenkoe5423a72015-03-23 19:23:50 +00001817 bool isFirst() const { return data[1] != nullptr; }
Guy Benyei11169dd2012-12-18 14:30:41 +00001818};
1819class TypeLocVisit : public VisitorJob {
1820public:
1821 TypeLocVisit(TypeLoc tl, CXCursor parent) :
1822 VisitorJob(parent, VisitorJob::TypeLocVisitKind,
1823 tl.getType().getAsOpaquePtr(), tl.getOpaqueData()) {}
1824
1825 static bool classof(const VisitorJob *VJ) {
1826 return VJ->getKind() == TypeLocVisitKind;
1827 }
1828
1829 TypeLoc get() const {
1830 QualType T = QualType::getFromOpaquePtr(data[0]);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001831 return TypeLoc(T, const_cast<void *>(data[1]));
Guy Benyei11169dd2012-12-18 14:30:41 +00001832 }
1833};
1834
1835class LabelRefVisit : public VisitorJob {
1836public:
1837 LabelRefVisit(LabelDecl *LD, SourceLocation labelLoc, CXCursor parent)
1838 : VisitorJob(parent, VisitorJob::LabelRefVisitKind, LD,
1839 labelLoc.getPtrEncoding()) {}
1840
1841 static bool classof(const VisitorJob *VJ) {
1842 return VJ->getKind() == VisitorJob::LabelRefVisitKind;
1843 }
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001844 const LabelDecl *get() const {
1845 return static_cast<const LabelDecl *>(data[0]);
1846 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001847 SourceLocation getLoc() const {
1848 return SourceLocation::getFromPtrEncoding(data[1]); }
1849};
1850
1851class NestedNameSpecifierLocVisit : public VisitorJob {
1852public:
1853 NestedNameSpecifierLocVisit(NestedNameSpecifierLoc Qualifier, CXCursor parent)
1854 : VisitorJob(parent, VisitorJob::NestedNameSpecifierLocVisitKind,
1855 Qualifier.getNestedNameSpecifier(),
1856 Qualifier.getOpaqueData()) { }
1857
1858 static bool classof(const VisitorJob *VJ) {
1859 return VJ->getKind() == VisitorJob::NestedNameSpecifierLocVisitKind;
1860 }
1861
1862 NestedNameSpecifierLoc get() const {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001863 return NestedNameSpecifierLoc(
1864 const_cast<NestedNameSpecifier *>(
1865 static_cast<const NestedNameSpecifier *>(data[0])),
1866 const_cast<void *>(data[1]));
Guy Benyei11169dd2012-12-18 14:30:41 +00001867 }
1868};
1869
1870class DeclarationNameInfoVisit : public VisitorJob {
1871public:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001872 DeclarationNameInfoVisit(const Stmt *S, CXCursor parent)
Dmitri Gribenkodd7dacf2013-02-03 13:19:54 +00001873 : VisitorJob(parent, VisitorJob::DeclarationNameInfoVisitKind, S) {}
Guy Benyei11169dd2012-12-18 14:30:41 +00001874 static bool classof(const VisitorJob *VJ) {
1875 return VJ->getKind() == VisitorJob::DeclarationNameInfoVisitKind;
1876 }
1877 DeclarationNameInfo get() const {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001878 const Stmt *S = static_cast<const Stmt *>(data[0]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001879 switch (S->getStmtClass()) {
1880 default:
1881 llvm_unreachable("Unhandled Stmt");
1882 case clang::Stmt::MSDependentExistsStmtClass:
1883 return cast<MSDependentExistsStmt>(S)->getNameInfo();
1884 case Stmt::CXXDependentScopeMemberExprClass:
1885 return cast<CXXDependentScopeMemberExpr>(S)->getMemberNameInfo();
1886 case Stmt::DependentScopeDeclRefExprClass:
1887 return cast<DependentScopeDeclRefExpr>(S)->getNameInfo();
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001888 case Stmt::OMPCriticalDirectiveClass:
1889 return cast<OMPCriticalDirective>(S)->getDirectiveName();
Guy Benyei11169dd2012-12-18 14:30:41 +00001890 }
1891 }
1892};
1893class MemberRefVisit : public VisitorJob {
1894public:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001895 MemberRefVisit(const FieldDecl *D, SourceLocation L, CXCursor parent)
Guy Benyei11169dd2012-12-18 14:30:41 +00001896 : VisitorJob(parent, VisitorJob::MemberRefVisitKind, D,
1897 L.getPtrEncoding()) {}
1898 static bool classof(const VisitorJob *VJ) {
1899 return VJ->getKind() == VisitorJob::MemberRefVisitKind;
1900 }
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001901 const FieldDecl *get() const {
1902 return static_cast<const FieldDecl *>(data[0]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001903 }
1904 SourceLocation getLoc() const {
1905 return SourceLocation::getFromRawEncoding((unsigned)(uintptr_t) data[1]);
1906 }
1907};
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001908class EnqueueVisitor : public ConstStmtVisitor<EnqueueVisitor, void> {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001909 friend class OMPClauseEnqueue;
Guy Benyei11169dd2012-12-18 14:30:41 +00001910 VisitorWorkList &WL;
1911 CXCursor Parent;
1912public:
1913 EnqueueVisitor(VisitorWorkList &wl, CXCursor parent)
1914 : WL(wl), Parent(parent) {}
1915
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001916 void VisitAddrLabelExpr(const AddrLabelExpr *E);
1917 void VisitBlockExpr(const BlockExpr *B);
1918 void VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
1919 void VisitCompoundStmt(const CompoundStmt *S);
1920 void VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) { /* Do nothing. */ }
1921 void VisitMSDependentExistsStmt(const MSDependentExistsStmt *S);
1922 void VisitCXXDependentScopeMemberExpr(const CXXDependentScopeMemberExpr *E);
1923 void VisitCXXNewExpr(const CXXNewExpr *E);
1924 void VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E);
1925 void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *E);
1926 void VisitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *E);
1927 void VisitCXXTemporaryObjectExpr(const CXXTemporaryObjectExpr *E);
1928 void VisitCXXTypeidExpr(const CXXTypeidExpr *E);
1929 void VisitCXXUnresolvedConstructExpr(const CXXUnresolvedConstructExpr *E);
1930 void VisitCXXUuidofExpr(const CXXUuidofExpr *E);
1931 void VisitCXXCatchStmt(const CXXCatchStmt *S);
Argyrios Kyrtzidis99891242014-11-13 09:03:21 +00001932 void VisitCXXForRangeStmt(const CXXForRangeStmt *S);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001933 void VisitDeclRefExpr(const DeclRefExpr *D);
1934 void VisitDeclStmt(const DeclStmt *S);
1935 void VisitDependentScopeDeclRefExpr(const DependentScopeDeclRefExpr *E);
1936 void VisitDesignatedInitExpr(const DesignatedInitExpr *E);
1937 void VisitExplicitCastExpr(const ExplicitCastExpr *E);
1938 void VisitForStmt(const ForStmt *FS);
1939 void VisitGotoStmt(const GotoStmt *GS);
1940 void VisitIfStmt(const IfStmt *If);
1941 void VisitInitListExpr(const InitListExpr *IE);
1942 void VisitMemberExpr(const MemberExpr *M);
1943 void VisitOffsetOfExpr(const OffsetOfExpr *E);
1944 void VisitObjCEncodeExpr(const ObjCEncodeExpr *E);
1945 void VisitObjCMessageExpr(const ObjCMessageExpr *M);
1946 void VisitOverloadExpr(const OverloadExpr *E);
1947 void VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
1948 void VisitStmt(const Stmt *S);
1949 void VisitSwitchStmt(const SwitchStmt *S);
1950 void VisitWhileStmt(const WhileStmt *W);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001951 void VisitTypeTraitExpr(const TypeTraitExpr *E);
1952 void VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E);
1953 void VisitExpressionTraitExpr(const ExpressionTraitExpr *E);
1954 void VisitUnresolvedMemberExpr(const UnresolvedMemberExpr *U);
1955 void VisitVAArgExpr(const VAArgExpr *E);
1956 void VisitSizeOfPackExpr(const SizeOfPackExpr *E);
1957 void VisitPseudoObjectExpr(const PseudoObjectExpr *E);
1958 void VisitOpaqueValueExpr(const OpaqueValueExpr *E);
1959 void VisitLambdaExpr(const LambdaExpr *E);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001960 void VisitOMPExecutableDirective(const OMPExecutableDirective *D);
Alexander Musman3aaab662014-08-19 11:27:13 +00001961 void VisitOMPLoopDirective(const OMPLoopDirective *D);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001962 void VisitOMPParallelDirective(const OMPParallelDirective *D);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00001963 void VisitOMPSimdDirective(const OMPSimdDirective *D);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001964 void VisitOMPForDirective(const OMPForDirective *D);
Alexander Musmanf82886e2014-09-18 05:12:34 +00001965 void VisitOMPForSimdDirective(const OMPForSimdDirective *D);
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00001966 void VisitOMPSectionsDirective(const OMPSectionsDirective *D);
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001967 void VisitOMPSectionDirective(const OMPSectionDirective *D);
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00001968 void VisitOMPSingleDirective(const OMPSingleDirective *D);
Alexander Musman80c22892014-07-17 08:54:58 +00001969 void VisitOMPMasterDirective(const OMPMasterDirective *D);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001970 void VisitOMPCriticalDirective(const OMPCriticalDirective *D);
Alexey Bataev4acb8592014-07-07 13:01:15 +00001971 void VisitOMPParallelForDirective(const OMPParallelForDirective *D);
Alexander Musmane4e893b2014-09-23 09:33:00 +00001972 void VisitOMPParallelForSimdDirective(const OMPParallelForSimdDirective *D);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001973 void VisitOMPParallelSectionsDirective(const OMPParallelSectionsDirective *D);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001974 void VisitOMPTaskDirective(const OMPTaskDirective *D);
Alexey Bataev68446b72014-07-18 07:47:19 +00001975 void VisitOMPTaskyieldDirective(const OMPTaskyieldDirective *D);
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001976 void VisitOMPBarrierDirective(const OMPBarrierDirective *D);
Alexey Bataev2df347a2014-07-18 10:17:07 +00001977 void VisitOMPTaskwaitDirective(const OMPTaskwaitDirective *D);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001978 void VisitOMPTaskgroupDirective(const OMPTaskgroupDirective *D);
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001979 void
1980 VisitOMPCancellationPointDirective(const OMPCancellationPointDirective *D);
Alexey Bataev80909872015-07-02 11:25:17 +00001981 void VisitOMPCancelDirective(const OMPCancelDirective *D);
Alexey Bataev6125da92014-07-21 11:26:11 +00001982 void VisitOMPFlushDirective(const OMPFlushDirective *D);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001983 void VisitOMPOrderedDirective(const OMPOrderedDirective *D);
Alexey Bataev0162e452014-07-22 10:10:35 +00001984 void VisitOMPAtomicDirective(const OMPAtomicDirective *D);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001985 void VisitOMPTargetDirective(const OMPTargetDirective *D);
Michael Wong65f367f2015-07-21 13:44:28 +00001986 void VisitOMPTargetDataDirective(const OMPTargetDataDirective *D);
Samuel Antaodf67fc42016-01-19 19:15:56 +00001987 void VisitOMPTargetEnterDataDirective(const OMPTargetEnterDataDirective *D);
Samuel Antao72590762016-01-19 20:04:50 +00001988 void VisitOMPTargetExitDataDirective(const OMPTargetExitDataDirective *D);
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00001989 void VisitOMPTargetParallelDirective(const OMPTargetParallelDirective *D);
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00001990 void
1991 VisitOMPTargetParallelForDirective(const OMPTargetParallelForDirective *D);
Alexey Bataev13314bf2014-10-09 04:18:56 +00001992 void VisitOMPTeamsDirective(const OMPTeamsDirective *D);
Alexey Bataev49f6e782015-12-01 04:18:41 +00001993 void VisitOMPTaskLoopDirective(const OMPTaskLoopDirective *D);
Alexey Bataev0a6ed842015-12-03 09:40:15 +00001994 void VisitOMPTaskLoopSimdDirective(const OMPTaskLoopSimdDirective *D);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00001995 void VisitOMPDistributeDirective(const OMPDistributeDirective *D);
Carlo Bertolli9925f152016-06-27 14:55:37 +00001996 void VisitOMPDistributeParallelForDirective(
1997 const OMPDistributeParallelForDirective *D);
Kelvin Li4a39add2016-07-05 05:00:15 +00001998 void VisitOMPDistributeParallelForSimdDirective(
1999 const OMPDistributeParallelForSimdDirective *D);
Kelvin Li787f3fc2016-07-06 04:45:38 +00002000 void VisitOMPDistributeSimdDirective(const OMPDistributeSimdDirective *D);
Kelvin Lia579b912016-07-14 02:54:56 +00002001 void VisitOMPTargetParallelForSimdDirective(
2002 const OMPTargetParallelForSimdDirective *D);
Kelvin Li986330c2016-07-20 22:57:10 +00002003 void VisitOMPTargetSimdDirective(const OMPTargetSimdDirective *D);
Kelvin Li02532872016-08-05 14:37:37 +00002004 void VisitOMPTeamsDistributeDirective(const OMPTeamsDistributeDirective *D);
Kelvin Li4e325f72016-10-25 12:50:55 +00002005 void VisitOMPTeamsDistributeSimdDirective(
2006 const OMPTeamsDistributeSimdDirective *D);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002007
Guy Benyei11169dd2012-12-18 14:30:41 +00002008private:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002009 void AddDeclarationNameInfo(const Stmt *S);
Guy Benyei11169dd2012-12-18 14:30:41 +00002010 void AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier);
James Y Knight04ec5bf2015-12-24 02:59:37 +00002011 void AddExplicitTemplateArgs(const TemplateArgumentLoc *A,
2012 unsigned NumTemplateArgs);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002013 void AddMemberRef(const FieldDecl *D, SourceLocation L);
2014 void AddStmt(const Stmt *S);
2015 void AddDecl(const Decl *D, bool isFirst = true);
Guy Benyei11169dd2012-12-18 14:30:41 +00002016 void AddTypeLoc(TypeSourceInfo *TI);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002017 void EnqueueChildren(const Stmt *S);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002018 void EnqueueChildren(const OMPClause *S);
Guy Benyei11169dd2012-12-18 14:30:41 +00002019};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002020} // end anonyous namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00002021
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002022void EnqueueVisitor::AddDeclarationNameInfo(const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002023 // 'S' should always be non-null, since it comes from the
2024 // statement we are visiting.
2025 WL.push_back(DeclarationNameInfoVisit(S, Parent));
2026}
2027
2028void
2029EnqueueVisitor::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
2030 if (Qualifier)
2031 WL.push_back(NestedNameSpecifierLocVisit(Qualifier, Parent));
2032}
2033
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002034void EnqueueVisitor::AddStmt(const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002035 if (S)
2036 WL.push_back(StmtVisit(S, Parent));
2037}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002038void EnqueueVisitor::AddDecl(const Decl *D, bool isFirst) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002039 if (D)
2040 WL.push_back(DeclVisit(D, Parent, isFirst));
2041}
James Y Knight04ec5bf2015-12-24 02:59:37 +00002042void EnqueueVisitor::AddExplicitTemplateArgs(const TemplateArgumentLoc *A,
2043 unsigned NumTemplateArgs) {
2044 WL.push_back(ExplicitTemplateArgsVisit(A, A + NumTemplateArgs, Parent));
Guy Benyei11169dd2012-12-18 14:30:41 +00002045}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002046void EnqueueVisitor::AddMemberRef(const FieldDecl *D, SourceLocation L) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002047 if (D)
2048 WL.push_back(MemberRefVisit(D, L, Parent));
2049}
2050void EnqueueVisitor::AddTypeLoc(TypeSourceInfo *TI) {
2051 if (TI)
2052 WL.push_back(TypeLocVisit(TI->getTypeLoc(), Parent));
2053 }
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002054void EnqueueVisitor::EnqueueChildren(const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002055 unsigned size = WL.size();
Benjamin Kramer642f1732015-07-02 21:03:14 +00002056 for (const Stmt *SubStmt : S->children()) {
2057 AddStmt(SubStmt);
Guy Benyei11169dd2012-12-18 14:30:41 +00002058 }
2059 if (size == WL.size())
2060 return;
2061 // Now reverse the entries we just added. This will match the DFS
2062 // ordering performed by the worklist.
2063 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2064 std::reverse(I, E);
2065}
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002066namespace {
2067class OMPClauseEnqueue : public ConstOMPClauseVisitor<OMPClauseEnqueue> {
2068 EnqueueVisitor *Visitor;
Alexey Bataev756c1962013-09-24 03:17:45 +00002069 /// \brief Process clauses with list of variables.
2070 template <typename T>
2071 void VisitOMPClauseList(T *Node);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002072public:
2073 OMPClauseEnqueue(EnqueueVisitor *Visitor) : Visitor(Visitor) { }
2074#define OPENMP_CLAUSE(Name, Class) \
2075 void Visit##Class(const Class *C);
2076#include "clang/Basic/OpenMPKinds.def"
Alexey Bataev3392d762016-02-16 11:18:12 +00002077 void VisitOMPClauseWithPreInit(const OMPClauseWithPreInit *C);
Alexey Bataev005248a2016-02-25 05:25:57 +00002078 void VisitOMPClauseWithPostUpdate(const OMPClauseWithPostUpdate *C);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002079};
2080
Alexey Bataev3392d762016-02-16 11:18:12 +00002081void OMPClauseEnqueue::VisitOMPClauseWithPreInit(
2082 const OMPClauseWithPreInit *C) {
2083 Visitor->AddStmt(C->getPreInitStmt());
2084}
2085
Alexey Bataev005248a2016-02-25 05:25:57 +00002086void OMPClauseEnqueue::VisitOMPClauseWithPostUpdate(
2087 const OMPClauseWithPostUpdate *C) {
Alexey Bataev37e594c2016-03-04 07:21:16 +00002088 VisitOMPClauseWithPreInit(C);
Alexey Bataev005248a2016-02-25 05:25:57 +00002089 Visitor->AddStmt(C->getPostUpdateExpr());
2090}
2091
Alexey Bataevaadd52e2014-02-13 05:29:23 +00002092void OMPClauseEnqueue::VisitOMPIfClause(const OMPIfClause *C) {
2093 Visitor->AddStmt(C->getCondition());
2094}
2095
Alexey Bataev3778b602014-07-17 07:32:53 +00002096void OMPClauseEnqueue::VisitOMPFinalClause(const OMPFinalClause *C) {
2097 Visitor->AddStmt(C->getCondition());
2098}
2099
Alexey Bataev568a8332014-03-06 06:15:19 +00002100void OMPClauseEnqueue::VisitOMPNumThreadsClause(const OMPNumThreadsClause *C) {
2101 Visitor->AddStmt(C->getNumThreads());
2102}
2103
Alexey Bataev62c87d22014-03-21 04:51:18 +00002104void OMPClauseEnqueue::VisitOMPSafelenClause(const OMPSafelenClause *C) {
2105 Visitor->AddStmt(C->getSafelen());
2106}
2107
Alexey Bataev66b15b52015-08-21 11:14:16 +00002108void OMPClauseEnqueue::VisitOMPSimdlenClause(const OMPSimdlenClause *C) {
2109 Visitor->AddStmt(C->getSimdlen());
2110}
2111
Alexander Musman8bd31e62014-05-27 15:12:19 +00002112void OMPClauseEnqueue::VisitOMPCollapseClause(const OMPCollapseClause *C) {
2113 Visitor->AddStmt(C->getNumForLoops());
2114}
2115
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002116void OMPClauseEnqueue::VisitOMPDefaultClause(const OMPDefaultClause *C) { }
Alexey Bataev756c1962013-09-24 03:17:45 +00002117
Alexey Bataevbcbadb62014-05-06 06:04:14 +00002118void OMPClauseEnqueue::VisitOMPProcBindClause(const OMPProcBindClause *C) { }
2119
Alexey Bataev56dafe82014-06-20 07:16:17 +00002120void OMPClauseEnqueue::VisitOMPScheduleClause(const OMPScheduleClause *C) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002121 VisitOMPClauseWithPreInit(C);
Alexey Bataev56dafe82014-06-20 07:16:17 +00002122 Visitor->AddStmt(C->getChunkSize());
2123}
2124
Alexey Bataev10e775f2015-07-30 11:36:16 +00002125void OMPClauseEnqueue::VisitOMPOrderedClause(const OMPOrderedClause *C) {
2126 Visitor->AddStmt(C->getNumForLoops());
2127}
Alexey Bataev142e1fc2014-06-20 09:44:06 +00002128
Alexey Bataev236070f2014-06-20 11:19:47 +00002129void OMPClauseEnqueue::VisitOMPNowaitClause(const OMPNowaitClause *) {}
2130
Alexey Bataev7aea99a2014-07-17 12:19:31 +00002131void OMPClauseEnqueue::VisitOMPUntiedClause(const OMPUntiedClause *) {}
2132
Alexey Bataev74ba3a52014-07-17 12:47:03 +00002133void OMPClauseEnqueue::VisitOMPMergeableClause(const OMPMergeableClause *) {}
2134
Alexey Bataevf98b00c2014-07-23 02:27:21 +00002135void OMPClauseEnqueue::VisitOMPReadClause(const OMPReadClause *) {}
2136
Alexey Bataevdea47612014-07-23 07:46:59 +00002137void OMPClauseEnqueue::VisitOMPWriteClause(const OMPWriteClause *) {}
2138
Alexey Bataev67a4f222014-07-23 10:25:33 +00002139void OMPClauseEnqueue::VisitOMPUpdateClause(const OMPUpdateClause *) {}
2140
Alexey Bataev459dec02014-07-24 06:46:57 +00002141void OMPClauseEnqueue::VisitOMPCaptureClause(const OMPCaptureClause *) {}
2142
Alexey Bataev82bad8b2014-07-24 08:55:34 +00002143void OMPClauseEnqueue::VisitOMPSeqCstClause(const OMPSeqCstClause *) {}
2144
Alexey Bataev346265e2015-09-25 10:37:12 +00002145void OMPClauseEnqueue::VisitOMPThreadsClause(const OMPThreadsClause *) {}
2146
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002147void OMPClauseEnqueue::VisitOMPSIMDClause(const OMPSIMDClause *) {}
2148
Alexey Bataevb825de12015-12-07 10:51:44 +00002149void OMPClauseEnqueue::VisitOMPNogroupClause(const OMPNogroupClause *) {}
2150
Michael Wonge710d542015-08-07 16:16:36 +00002151void OMPClauseEnqueue::VisitOMPDeviceClause(const OMPDeviceClause *C) {
2152 Visitor->AddStmt(C->getDevice());
2153}
2154
Kelvin Li099bb8c2015-11-24 20:50:12 +00002155void OMPClauseEnqueue::VisitOMPNumTeamsClause(const OMPNumTeamsClause *C) {
2156 Visitor->AddStmt(C->getNumTeams());
2157}
2158
Kelvin Lia15fb1a2015-11-27 18:47:36 +00002159void OMPClauseEnqueue::VisitOMPThreadLimitClause(const OMPThreadLimitClause *C) {
2160 Visitor->AddStmt(C->getThreadLimit());
2161}
2162
Alexey Bataeva0569352015-12-01 10:17:31 +00002163void OMPClauseEnqueue::VisitOMPPriorityClause(const OMPPriorityClause *C) {
2164 Visitor->AddStmt(C->getPriority());
2165}
2166
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00002167void OMPClauseEnqueue::VisitOMPGrainsizeClause(const OMPGrainsizeClause *C) {
2168 Visitor->AddStmt(C->getGrainsize());
2169}
2170
Alexey Bataev382967a2015-12-08 12:06:20 +00002171void OMPClauseEnqueue::VisitOMPNumTasksClause(const OMPNumTasksClause *C) {
2172 Visitor->AddStmt(C->getNumTasks());
2173}
2174
Alexey Bataev28c75412015-12-15 08:19:24 +00002175void OMPClauseEnqueue::VisitOMPHintClause(const OMPHintClause *C) {
2176 Visitor->AddStmt(C->getHint());
2177}
2178
Alexey Bataev756c1962013-09-24 03:17:45 +00002179template<typename T>
2180void OMPClauseEnqueue::VisitOMPClauseList(T *Node) {
Alexey Bataev03b340a2014-10-21 03:16:40 +00002181 for (const auto *I : Node->varlists()) {
Aaron Ballman2205d2a2014-03-14 15:55:35 +00002182 Visitor->AddStmt(I);
Alexey Bataev03b340a2014-10-21 03:16:40 +00002183 }
Alexey Bataev756c1962013-09-24 03:17:45 +00002184}
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002185
2186void OMPClauseEnqueue::VisitOMPPrivateClause(const OMPPrivateClause *C) {
Alexey Bataev756c1962013-09-24 03:17:45 +00002187 VisitOMPClauseList(C);
Alexey Bataev03b340a2014-10-21 03:16:40 +00002188 for (const auto *E : C->private_copies()) {
2189 Visitor->AddStmt(E);
2190 }
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002191}
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002192void OMPClauseEnqueue::VisitOMPFirstprivateClause(
2193 const OMPFirstprivateClause *C) {
2194 VisitOMPClauseList(C);
Alexey Bataev417089f2016-02-17 13:19:37 +00002195 VisitOMPClauseWithPreInit(C);
2196 for (const auto *E : C->private_copies()) {
2197 Visitor->AddStmt(E);
2198 }
2199 for (const auto *E : C->inits()) {
2200 Visitor->AddStmt(E);
2201 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002202}
Alexander Musman1bb328c2014-06-04 13:06:39 +00002203void OMPClauseEnqueue::VisitOMPLastprivateClause(
2204 const OMPLastprivateClause *C) {
2205 VisitOMPClauseList(C);
Alexey Bataev005248a2016-02-25 05:25:57 +00002206 VisitOMPClauseWithPostUpdate(C);
Alexey Bataev38e89532015-04-16 04:54:05 +00002207 for (auto *E : C->private_copies()) {
2208 Visitor->AddStmt(E);
2209 }
2210 for (auto *E : C->source_exprs()) {
2211 Visitor->AddStmt(E);
2212 }
2213 for (auto *E : C->destination_exprs()) {
2214 Visitor->AddStmt(E);
2215 }
2216 for (auto *E : C->assignment_ops()) {
2217 Visitor->AddStmt(E);
2218 }
Alexander Musman1bb328c2014-06-04 13:06:39 +00002219}
Alexey Bataev758e55e2013-09-06 18:03:48 +00002220void OMPClauseEnqueue::VisitOMPSharedClause(const OMPSharedClause *C) {
Alexey Bataev756c1962013-09-24 03:17:45 +00002221 VisitOMPClauseList(C);
Alexey Bataev758e55e2013-09-06 18:03:48 +00002222}
Alexey Bataevc5e02582014-06-16 07:08:35 +00002223void OMPClauseEnqueue::VisitOMPReductionClause(const OMPReductionClause *C) {
2224 VisitOMPClauseList(C);
Alexey Bataev61205072016-03-02 04:57:40 +00002225 VisitOMPClauseWithPostUpdate(C);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00002226 for (auto *E : C->privates()) {
2227 Visitor->AddStmt(E);
2228 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002229 for (auto *E : C->lhs_exprs()) {
2230 Visitor->AddStmt(E);
2231 }
2232 for (auto *E : C->rhs_exprs()) {
2233 Visitor->AddStmt(E);
2234 }
2235 for (auto *E : C->reduction_ops()) {
2236 Visitor->AddStmt(E);
2237 }
Alexey Bataevc5e02582014-06-16 07:08:35 +00002238}
Alexander Musman8dba6642014-04-22 13:09:42 +00002239void OMPClauseEnqueue::VisitOMPLinearClause(const OMPLinearClause *C) {
2240 VisitOMPClauseList(C);
Alexey Bataev78849fb2016-03-09 09:49:00 +00002241 VisitOMPClauseWithPostUpdate(C);
Alexey Bataevbd9fec12015-08-18 06:47:21 +00002242 for (const auto *E : C->privates()) {
2243 Visitor->AddStmt(E);
2244 }
Alexander Musman3276a272015-03-21 10:12:56 +00002245 for (const auto *E : C->inits()) {
2246 Visitor->AddStmt(E);
2247 }
2248 for (const auto *E : C->updates()) {
2249 Visitor->AddStmt(E);
2250 }
2251 for (const auto *E : C->finals()) {
2252 Visitor->AddStmt(E);
2253 }
Alexander Musman8dba6642014-04-22 13:09:42 +00002254 Visitor->AddStmt(C->getStep());
Alexander Musman3276a272015-03-21 10:12:56 +00002255 Visitor->AddStmt(C->getCalcStep());
Alexander Musman8dba6642014-04-22 13:09:42 +00002256}
Alexander Musmanf0d76e72014-05-29 14:36:25 +00002257void OMPClauseEnqueue::VisitOMPAlignedClause(const OMPAlignedClause *C) {
2258 VisitOMPClauseList(C);
2259 Visitor->AddStmt(C->getAlignment());
2260}
Alexey Bataevd48bcd82014-03-31 03:36:38 +00002261void OMPClauseEnqueue::VisitOMPCopyinClause(const OMPCopyinClause *C) {
2262 VisitOMPClauseList(C);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00002263 for (auto *E : C->source_exprs()) {
2264 Visitor->AddStmt(E);
2265 }
2266 for (auto *E : C->destination_exprs()) {
2267 Visitor->AddStmt(E);
2268 }
2269 for (auto *E : C->assignment_ops()) {
2270 Visitor->AddStmt(E);
2271 }
Alexey Bataevd48bcd82014-03-31 03:36:38 +00002272}
Alexey Bataevbae9a792014-06-27 10:37:06 +00002273void
2274OMPClauseEnqueue::VisitOMPCopyprivateClause(const OMPCopyprivateClause *C) {
2275 VisitOMPClauseList(C);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002276 for (auto *E : C->source_exprs()) {
2277 Visitor->AddStmt(E);
2278 }
2279 for (auto *E : C->destination_exprs()) {
2280 Visitor->AddStmt(E);
2281 }
2282 for (auto *E : C->assignment_ops()) {
2283 Visitor->AddStmt(E);
2284 }
Alexey Bataevbae9a792014-06-27 10:37:06 +00002285}
Alexey Bataev6125da92014-07-21 11:26:11 +00002286void OMPClauseEnqueue::VisitOMPFlushClause(const OMPFlushClause *C) {
2287 VisitOMPClauseList(C);
2288}
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00002289void OMPClauseEnqueue::VisitOMPDependClause(const OMPDependClause *C) {
2290 VisitOMPClauseList(C);
2291}
Kelvin Li0bff7af2015-11-23 05:32:03 +00002292void OMPClauseEnqueue::VisitOMPMapClause(const OMPMapClause *C) {
2293 VisitOMPClauseList(C);
2294}
Carlo Bertollib4adf552016-01-15 18:50:31 +00002295void OMPClauseEnqueue::VisitOMPDistScheduleClause(
2296 const OMPDistScheduleClause *C) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002297 VisitOMPClauseWithPreInit(C);
Carlo Bertollib4adf552016-01-15 18:50:31 +00002298 Visitor->AddStmt(C->getChunkSize());
Carlo Bertollib4adf552016-01-15 18:50:31 +00002299}
Alexey Bataev3392d762016-02-16 11:18:12 +00002300void OMPClauseEnqueue::VisitOMPDefaultmapClause(
2301 const OMPDefaultmapClause * /*C*/) {}
Samuel Antao661c0902016-05-26 17:39:58 +00002302void OMPClauseEnqueue::VisitOMPToClause(const OMPToClause *C) {
2303 VisitOMPClauseList(C);
2304}
Samuel Antaoec172c62016-05-26 17:49:04 +00002305void OMPClauseEnqueue::VisitOMPFromClause(const OMPFromClause *C) {
2306 VisitOMPClauseList(C);
2307}
Carlo Bertolli2404b172016-07-13 15:37:16 +00002308void OMPClauseEnqueue::VisitOMPUseDevicePtrClause(const OMPUseDevicePtrClause *C) {
2309 VisitOMPClauseList(C);
2310}
Carlo Bertolli70594e92016-07-13 17:16:49 +00002311void OMPClauseEnqueue::VisitOMPIsDevicePtrClause(const OMPIsDevicePtrClause *C) {
2312 VisitOMPClauseList(C);
2313}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002314}
Alexey Bataev756c1962013-09-24 03:17:45 +00002315
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002316void EnqueueVisitor::EnqueueChildren(const OMPClause *S) {
2317 unsigned size = WL.size();
2318 OMPClauseEnqueue Visitor(this);
2319 Visitor.Visit(S);
2320 if (size == WL.size())
2321 return;
2322 // Now reverse the entries we just added. This will match the DFS
2323 // ordering performed by the worklist.
2324 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2325 std::reverse(I, E);
2326}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002327void EnqueueVisitor::VisitAddrLabelExpr(const AddrLabelExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002328 WL.push_back(LabelRefVisit(E->getLabel(), E->getLabelLoc(), Parent));
2329}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002330void EnqueueVisitor::VisitBlockExpr(const BlockExpr *B) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002331 AddDecl(B->getBlockDecl());
2332}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002333void EnqueueVisitor::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002334 EnqueueChildren(E);
2335 AddTypeLoc(E->getTypeSourceInfo());
2336}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002337void EnqueueVisitor::VisitCompoundStmt(const CompoundStmt *S) {
Pete Cooper57d3f142015-07-30 17:22:52 +00002338 for (auto &I : llvm::reverse(S->body()))
2339 AddStmt(I);
Guy Benyei11169dd2012-12-18 14:30:41 +00002340}
2341void EnqueueVisitor::
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002342VisitMSDependentExistsStmt(const MSDependentExistsStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002343 AddStmt(S->getSubStmt());
2344 AddDeclarationNameInfo(S);
2345 if (NestedNameSpecifierLoc QualifierLoc = S->getQualifierLoc())
2346 AddNestedNameSpecifierLoc(QualifierLoc);
2347}
2348
2349void EnqueueVisitor::
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002350VisitCXXDependentScopeMemberExpr(const CXXDependentScopeMemberExpr *E) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002351 if (E->hasExplicitTemplateArgs())
2352 AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002353 AddDeclarationNameInfo(E);
2354 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
2355 AddNestedNameSpecifierLoc(QualifierLoc);
2356 if (!E->isImplicitAccess())
2357 AddStmt(E->getBase());
2358}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002359void EnqueueVisitor::VisitCXXNewExpr(const CXXNewExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002360 // Enqueue the initializer , if any.
2361 AddStmt(E->getInitializer());
2362 // Enqueue the array size, if any.
2363 AddStmt(E->getArraySize());
2364 // Enqueue the allocated type.
2365 AddTypeLoc(E->getAllocatedTypeSourceInfo());
2366 // Enqueue the placement arguments.
2367 for (unsigned I = E->getNumPlacementArgs(); I > 0; --I)
2368 AddStmt(E->getPlacementArg(I-1));
2369}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002370void EnqueueVisitor::VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CE) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002371 for (unsigned I = CE->getNumArgs(); I > 1 /* Yes, this is 1 */; --I)
2372 AddStmt(CE->getArg(I-1));
2373 AddStmt(CE->getCallee());
2374 AddStmt(CE->getArg(0));
2375}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002376void EnqueueVisitor::VisitCXXPseudoDestructorExpr(
2377 const CXXPseudoDestructorExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002378 // Visit the name of the type being destroyed.
2379 AddTypeLoc(E->getDestroyedTypeInfo());
2380 // Visit the scope type that looks disturbingly like the nested-name-specifier
2381 // but isn't.
2382 AddTypeLoc(E->getScopeTypeInfo());
2383 // Visit the nested-name-specifier.
2384 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
2385 AddNestedNameSpecifierLoc(QualifierLoc);
2386 // Visit base expression.
2387 AddStmt(E->getBase());
2388}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002389void EnqueueVisitor::VisitCXXScalarValueInitExpr(
2390 const CXXScalarValueInitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002391 AddTypeLoc(E->getTypeSourceInfo());
2392}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002393void EnqueueVisitor::VisitCXXTemporaryObjectExpr(
2394 const CXXTemporaryObjectExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002395 EnqueueChildren(E);
2396 AddTypeLoc(E->getTypeSourceInfo());
2397}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002398void EnqueueVisitor::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002399 EnqueueChildren(E);
2400 if (E->isTypeOperand())
2401 AddTypeLoc(E->getTypeOperandSourceInfo());
2402}
2403
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002404void EnqueueVisitor::VisitCXXUnresolvedConstructExpr(
2405 const CXXUnresolvedConstructExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002406 EnqueueChildren(E);
2407 AddTypeLoc(E->getTypeSourceInfo());
2408}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002409void EnqueueVisitor::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002410 EnqueueChildren(E);
2411 if (E->isTypeOperand())
2412 AddTypeLoc(E->getTypeOperandSourceInfo());
2413}
2414
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002415void EnqueueVisitor::VisitCXXCatchStmt(const CXXCatchStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002416 EnqueueChildren(S);
2417 AddDecl(S->getExceptionDecl());
2418}
2419
Argyrios Kyrtzidis99891242014-11-13 09:03:21 +00002420void EnqueueVisitor::VisitCXXForRangeStmt(const CXXForRangeStmt *S) {
Argyrios Kyrtzidiscde70692014-11-13 09:50:19 +00002421 AddStmt(S->getBody());
Argyrios Kyrtzidis99891242014-11-13 09:03:21 +00002422 AddStmt(S->getRangeInit());
Argyrios Kyrtzidiscde70692014-11-13 09:50:19 +00002423 AddDecl(S->getLoopVariable());
Argyrios Kyrtzidis99891242014-11-13 09:03:21 +00002424}
2425
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002426void EnqueueVisitor::VisitDeclRefExpr(const DeclRefExpr *DR) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002427 if (DR->hasExplicitTemplateArgs())
2428 AddExplicitTemplateArgs(DR->getTemplateArgs(), DR->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002429 WL.push_back(DeclRefExprParts(DR, Parent));
2430}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002431void EnqueueVisitor::VisitDependentScopeDeclRefExpr(
2432 const DependentScopeDeclRefExpr *E) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002433 if (E->hasExplicitTemplateArgs())
2434 AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002435 AddDeclarationNameInfo(E);
2436 AddNestedNameSpecifierLoc(E->getQualifierLoc());
2437}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002438void EnqueueVisitor::VisitDeclStmt(const DeclStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002439 unsigned size = WL.size();
2440 bool isFirst = true;
Aaron Ballman535bbcc2014-03-14 17:01:24 +00002441 for (const auto *D : S->decls()) {
2442 AddDecl(D, isFirst);
Guy Benyei11169dd2012-12-18 14:30:41 +00002443 isFirst = false;
2444 }
2445 if (size == WL.size())
2446 return;
2447 // Now reverse the entries we just added. This will match the DFS
2448 // ordering performed by the worklist.
2449 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2450 std::reverse(I, E);
2451}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002452void EnqueueVisitor::VisitDesignatedInitExpr(const DesignatedInitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002453 AddStmt(E->getInit());
David Majnemerf7e36092016-06-23 00:15:04 +00002454 for (const DesignatedInitExpr::Designator &D :
2455 llvm::reverse(E->designators())) {
2456 if (D.isFieldDesignator()) {
2457 if (FieldDecl *Field = D.getField())
2458 AddMemberRef(Field, D.getFieldLoc());
Guy Benyei11169dd2012-12-18 14:30:41 +00002459 continue;
2460 }
David Majnemerf7e36092016-06-23 00:15:04 +00002461 if (D.isArrayDesignator()) {
2462 AddStmt(E->getArrayIndex(D));
Guy Benyei11169dd2012-12-18 14:30:41 +00002463 continue;
2464 }
David Majnemerf7e36092016-06-23 00:15:04 +00002465 assert(D.isArrayRangeDesignator() && "Unknown designator kind");
2466 AddStmt(E->getArrayRangeEnd(D));
2467 AddStmt(E->getArrayRangeStart(D));
Guy Benyei11169dd2012-12-18 14:30:41 +00002468 }
2469}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002470void EnqueueVisitor::VisitExplicitCastExpr(const ExplicitCastExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002471 EnqueueChildren(E);
2472 AddTypeLoc(E->getTypeInfoAsWritten());
2473}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002474void EnqueueVisitor::VisitForStmt(const ForStmt *FS) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002475 AddStmt(FS->getBody());
2476 AddStmt(FS->getInc());
2477 AddStmt(FS->getCond());
2478 AddDecl(FS->getConditionVariable());
2479 AddStmt(FS->getInit());
2480}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002481void EnqueueVisitor::VisitGotoStmt(const GotoStmt *GS) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002482 WL.push_back(LabelRefVisit(GS->getLabel(), GS->getLabelLoc(), Parent));
2483}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002484void EnqueueVisitor::VisitIfStmt(const IfStmt *If) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002485 AddStmt(If->getElse());
2486 AddStmt(If->getThen());
2487 AddStmt(If->getCond());
2488 AddDecl(If->getConditionVariable());
2489}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002490void EnqueueVisitor::VisitInitListExpr(const InitListExpr *IE) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002491 // We care about the syntactic form of the initializer list, only.
2492 if (InitListExpr *Syntactic = IE->getSyntacticForm())
2493 IE = Syntactic;
2494 EnqueueChildren(IE);
2495}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002496void EnqueueVisitor::VisitMemberExpr(const MemberExpr *M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002497 WL.push_back(MemberExprParts(M, Parent));
2498
2499 // If the base of the member access expression is an implicit 'this', don't
2500 // visit it.
2501 // FIXME: If we ever want to show these implicit accesses, this will be
2502 // unfortunate. However, clang_getCursor() relies on this behavior.
Argyrios Kyrtzidis58d0e7a2015-03-13 04:40:07 +00002503 if (M->isImplicitAccess())
2504 return;
2505
2506 // Ignore base anonymous struct/union fields, otherwise they will shadow the
2507 // real field that that we are interested in.
2508 if (auto *SubME = dyn_cast<MemberExpr>(M->getBase())) {
2509 if (auto *FD = dyn_cast_or_null<FieldDecl>(SubME->getMemberDecl())) {
2510 if (FD->isAnonymousStructOrUnion()) {
2511 AddStmt(SubME->getBase());
2512 return;
2513 }
2514 }
2515 }
2516
2517 AddStmt(M->getBase());
Guy Benyei11169dd2012-12-18 14:30:41 +00002518}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002519void EnqueueVisitor::VisitObjCEncodeExpr(const ObjCEncodeExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002520 AddTypeLoc(E->getEncodedTypeSourceInfo());
2521}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002522void EnqueueVisitor::VisitObjCMessageExpr(const ObjCMessageExpr *M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002523 EnqueueChildren(M);
2524 AddTypeLoc(M->getClassReceiverTypeInfo());
2525}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002526void EnqueueVisitor::VisitOffsetOfExpr(const OffsetOfExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002527 // Visit the components of the offsetof expression.
2528 for (unsigned N = E->getNumComponents(), I = N; I > 0; --I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002529 const OffsetOfNode &Node = E->getComponent(I-1);
2530 switch (Node.getKind()) {
2531 case OffsetOfNode::Array:
2532 AddStmt(E->getIndexExpr(Node.getArrayExprIndex()));
2533 break;
2534 case OffsetOfNode::Field:
2535 AddMemberRef(Node.getField(), Node.getSourceRange().getEnd());
2536 break;
2537 case OffsetOfNode::Identifier:
2538 case OffsetOfNode::Base:
2539 continue;
2540 }
2541 }
2542 // Visit the type into which we're computing the offset.
2543 AddTypeLoc(E->getTypeSourceInfo());
2544}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002545void EnqueueVisitor::VisitOverloadExpr(const OverloadExpr *E) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002546 if (E->hasExplicitTemplateArgs())
2547 AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002548 WL.push_back(OverloadExprParts(E, Parent));
2549}
2550void EnqueueVisitor::VisitUnaryExprOrTypeTraitExpr(
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002551 const UnaryExprOrTypeTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002552 EnqueueChildren(E);
2553 if (E->isArgumentType())
2554 AddTypeLoc(E->getArgumentTypeInfo());
2555}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002556void EnqueueVisitor::VisitStmt(const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002557 EnqueueChildren(S);
2558}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002559void EnqueueVisitor::VisitSwitchStmt(const SwitchStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002560 AddStmt(S->getBody());
2561 AddStmt(S->getCond());
2562 AddDecl(S->getConditionVariable());
2563}
2564
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002565void EnqueueVisitor::VisitWhileStmt(const WhileStmt *W) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002566 AddStmt(W->getBody());
2567 AddStmt(W->getCond());
2568 AddDecl(W->getConditionVariable());
2569}
2570
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002571void EnqueueVisitor::VisitTypeTraitExpr(const TypeTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002572 for (unsigned I = E->getNumArgs(); I > 0; --I)
2573 AddTypeLoc(E->getArg(I-1));
2574}
2575
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002576void EnqueueVisitor::VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002577 AddTypeLoc(E->getQueriedTypeSourceInfo());
2578}
2579
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002580void EnqueueVisitor::VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002581 EnqueueChildren(E);
2582}
2583
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002584void EnqueueVisitor::VisitUnresolvedMemberExpr(const UnresolvedMemberExpr *U) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002585 VisitOverloadExpr(U);
2586 if (!U->isImplicitAccess())
2587 AddStmt(U->getBase());
2588}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002589void EnqueueVisitor::VisitVAArgExpr(const VAArgExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002590 AddStmt(E->getSubExpr());
2591 AddTypeLoc(E->getWrittenTypeInfo());
2592}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002593void EnqueueVisitor::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002594 WL.push_back(SizeOfPackExprParts(E, Parent));
2595}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002596void EnqueueVisitor::VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002597 // If the opaque value has a source expression, just transparently
2598 // visit that. This is useful for (e.g.) pseudo-object expressions.
2599 if (Expr *SourceExpr = E->getSourceExpr())
2600 return Visit(SourceExpr);
2601}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002602void EnqueueVisitor::VisitLambdaExpr(const LambdaExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002603 AddStmt(E->getBody());
2604 WL.push_back(LambdaExprParts(E, Parent));
2605}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002606void EnqueueVisitor::VisitPseudoObjectExpr(const PseudoObjectExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002607 // Treat the expression like its syntactic form.
2608 Visit(E->getSyntacticForm());
2609}
2610
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002611void EnqueueVisitor::VisitOMPExecutableDirective(
2612 const OMPExecutableDirective *D) {
2613 EnqueueChildren(D);
2614 for (ArrayRef<OMPClause *>::iterator I = D->clauses().begin(),
2615 E = D->clauses().end();
2616 I != E; ++I)
2617 EnqueueChildren(*I);
2618}
2619
Alexander Musman3aaab662014-08-19 11:27:13 +00002620void EnqueueVisitor::VisitOMPLoopDirective(const OMPLoopDirective *D) {
2621 VisitOMPExecutableDirective(D);
2622}
2623
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002624void EnqueueVisitor::VisitOMPParallelDirective(const OMPParallelDirective *D) {
2625 VisitOMPExecutableDirective(D);
2626}
2627
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002628void EnqueueVisitor::VisitOMPSimdDirective(const OMPSimdDirective *D) {
Alexander Musman3aaab662014-08-19 11:27:13 +00002629 VisitOMPLoopDirective(D);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002630}
2631
Alexey Bataevf29276e2014-06-18 04:14:57 +00002632void EnqueueVisitor::VisitOMPForDirective(const OMPForDirective *D) {
Alexander Musman3aaab662014-08-19 11:27:13 +00002633 VisitOMPLoopDirective(D);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002634}
2635
Alexander Musmanf82886e2014-09-18 05:12:34 +00002636void EnqueueVisitor::VisitOMPForSimdDirective(const OMPForSimdDirective *D) {
2637 VisitOMPLoopDirective(D);
2638}
2639
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002640void EnqueueVisitor::VisitOMPSectionsDirective(const OMPSectionsDirective *D) {
2641 VisitOMPExecutableDirective(D);
2642}
2643
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002644void EnqueueVisitor::VisitOMPSectionDirective(const OMPSectionDirective *D) {
2645 VisitOMPExecutableDirective(D);
2646}
2647
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00002648void EnqueueVisitor::VisitOMPSingleDirective(const OMPSingleDirective *D) {
2649 VisitOMPExecutableDirective(D);
2650}
2651
Alexander Musman80c22892014-07-17 08:54:58 +00002652void EnqueueVisitor::VisitOMPMasterDirective(const OMPMasterDirective *D) {
2653 VisitOMPExecutableDirective(D);
2654}
2655
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002656void EnqueueVisitor::VisitOMPCriticalDirective(const OMPCriticalDirective *D) {
2657 VisitOMPExecutableDirective(D);
2658 AddDeclarationNameInfo(D);
2659}
2660
Alexey Bataev4acb8592014-07-07 13:01:15 +00002661void
2662EnqueueVisitor::VisitOMPParallelForDirective(const OMPParallelForDirective *D) {
Alexander Musman3aaab662014-08-19 11:27:13 +00002663 VisitOMPLoopDirective(D);
Alexey Bataev4acb8592014-07-07 13:01:15 +00002664}
2665
Alexander Musmane4e893b2014-09-23 09:33:00 +00002666void EnqueueVisitor::VisitOMPParallelForSimdDirective(
2667 const OMPParallelForSimdDirective *D) {
2668 VisitOMPLoopDirective(D);
2669}
2670
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002671void EnqueueVisitor::VisitOMPParallelSectionsDirective(
2672 const OMPParallelSectionsDirective *D) {
2673 VisitOMPExecutableDirective(D);
2674}
2675
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002676void EnqueueVisitor::VisitOMPTaskDirective(const OMPTaskDirective *D) {
2677 VisitOMPExecutableDirective(D);
2678}
2679
Alexey Bataev68446b72014-07-18 07:47:19 +00002680void
2681EnqueueVisitor::VisitOMPTaskyieldDirective(const OMPTaskyieldDirective *D) {
2682 VisitOMPExecutableDirective(D);
2683}
2684
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002685void EnqueueVisitor::VisitOMPBarrierDirective(const OMPBarrierDirective *D) {
2686 VisitOMPExecutableDirective(D);
2687}
2688
Alexey Bataev2df347a2014-07-18 10:17:07 +00002689void EnqueueVisitor::VisitOMPTaskwaitDirective(const OMPTaskwaitDirective *D) {
2690 VisitOMPExecutableDirective(D);
2691}
2692
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002693void EnqueueVisitor::VisitOMPTaskgroupDirective(
2694 const OMPTaskgroupDirective *D) {
2695 VisitOMPExecutableDirective(D);
2696}
2697
Alexey Bataev6125da92014-07-21 11:26:11 +00002698void EnqueueVisitor::VisitOMPFlushDirective(const OMPFlushDirective *D) {
2699 VisitOMPExecutableDirective(D);
2700}
2701
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002702void EnqueueVisitor::VisitOMPOrderedDirective(const OMPOrderedDirective *D) {
2703 VisitOMPExecutableDirective(D);
2704}
2705
Alexey Bataev0162e452014-07-22 10:10:35 +00002706void EnqueueVisitor::VisitOMPAtomicDirective(const OMPAtomicDirective *D) {
2707 VisitOMPExecutableDirective(D);
2708}
2709
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002710void EnqueueVisitor::VisitOMPTargetDirective(const OMPTargetDirective *D) {
2711 VisitOMPExecutableDirective(D);
2712}
2713
Michael Wong65f367f2015-07-21 13:44:28 +00002714void EnqueueVisitor::VisitOMPTargetDataDirective(const
2715 OMPTargetDataDirective *D) {
2716 VisitOMPExecutableDirective(D);
2717}
2718
Samuel Antaodf67fc42016-01-19 19:15:56 +00002719void EnqueueVisitor::VisitOMPTargetEnterDataDirective(
2720 const OMPTargetEnterDataDirective *D) {
2721 VisitOMPExecutableDirective(D);
2722}
2723
Samuel Antao72590762016-01-19 20:04:50 +00002724void EnqueueVisitor::VisitOMPTargetExitDataDirective(
2725 const OMPTargetExitDataDirective *D) {
2726 VisitOMPExecutableDirective(D);
2727}
2728
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00002729void EnqueueVisitor::VisitOMPTargetParallelDirective(
2730 const OMPTargetParallelDirective *D) {
2731 VisitOMPExecutableDirective(D);
2732}
2733
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00002734void EnqueueVisitor::VisitOMPTargetParallelForDirective(
2735 const OMPTargetParallelForDirective *D) {
2736 VisitOMPLoopDirective(D);
2737}
2738
Alexey Bataev13314bf2014-10-09 04:18:56 +00002739void EnqueueVisitor::VisitOMPTeamsDirective(const OMPTeamsDirective *D) {
2740 VisitOMPExecutableDirective(D);
2741}
2742
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002743void EnqueueVisitor::VisitOMPCancellationPointDirective(
2744 const OMPCancellationPointDirective *D) {
2745 VisitOMPExecutableDirective(D);
2746}
2747
Alexey Bataev80909872015-07-02 11:25:17 +00002748void EnqueueVisitor::VisitOMPCancelDirective(const OMPCancelDirective *D) {
2749 VisitOMPExecutableDirective(D);
2750}
2751
Alexey Bataev49f6e782015-12-01 04:18:41 +00002752void EnqueueVisitor::VisitOMPTaskLoopDirective(const OMPTaskLoopDirective *D) {
2753 VisitOMPLoopDirective(D);
2754}
2755
Alexey Bataev0a6ed842015-12-03 09:40:15 +00002756void EnqueueVisitor::VisitOMPTaskLoopSimdDirective(
2757 const OMPTaskLoopSimdDirective *D) {
2758 VisitOMPLoopDirective(D);
2759}
2760
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002761void EnqueueVisitor::VisitOMPDistributeDirective(
2762 const OMPDistributeDirective *D) {
2763 VisitOMPLoopDirective(D);
2764}
2765
Carlo Bertolli9925f152016-06-27 14:55:37 +00002766void EnqueueVisitor::VisitOMPDistributeParallelForDirective(
2767 const OMPDistributeParallelForDirective *D) {
2768 VisitOMPLoopDirective(D);
2769}
2770
Kelvin Li4a39add2016-07-05 05:00:15 +00002771void EnqueueVisitor::VisitOMPDistributeParallelForSimdDirective(
2772 const OMPDistributeParallelForSimdDirective *D) {
2773 VisitOMPLoopDirective(D);
2774}
2775
Kelvin Li787f3fc2016-07-06 04:45:38 +00002776void EnqueueVisitor::VisitOMPDistributeSimdDirective(
2777 const OMPDistributeSimdDirective *D) {
2778 VisitOMPLoopDirective(D);
2779}
2780
Kelvin Lia579b912016-07-14 02:54:56 +00002781void EnqueueVisitor::VisitOMPTargetParallelForSimdDirective(
2782 const OMPTargetParallelForSimdDirective *D) {
2783 VisitOMPLoopDirective(D);
2784}
2785
Kelvin Li986330c2016-07-20 22:57:10 +00002786void EnqueueVisitor::VisitOMPTargetSimdDirective(
2787 const OMPTargetSimdDirective *D) {
2788 VisitOMPLoopDirective(D);
2789}
2790
Kelvin Li02532872016-08-05 14:37:37 +00002791void EnqueueVisitor::VisitOMPTeamsDistributeDirective(
2792 const OMPTeamsDistributeDirective *D) {
2793 VisitOMPLoopDirective(D);
2794}
2795
Kelvin Li4e325f72016-10-25 12:50:55 +00002796void EnqueueVisitor::VisitOMPTeamsDistributeSimdDirective(
2797 const OMPTeamsDistributeSimdDirective *D) {
2798 VisitOMPLoopDirective(D);
2799}
2800
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002801void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002802 EnqueueVisitor(WL, MakeCXCursor(S, StmtParent, TU,RegionOfInterest)).Visit(S);
2803}
2804
2805bool CursorVisitor::IsInRegionOfInterest(CXCursor C) {
2806 if (RegionOfInterest.isValid()) {
2807 SourceRange Range = getRawCursorExtent(C);
2808 if (Range.isInvalid() || CompareRegionOfInterest(Range))
2809 return false;
2810 }
2811 return true;
2812}
2813
2814bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) {
2815 while (!WL.empty()) {
2816 // Dequeue the worklist item.
Robert Wilhelm25284cc2013-08-23 16:11:15 +00002817 VisitorJob LI = WL.pop_back_val();
Guy Benyei11169dd2012-12-18 14:30:41 +00002818
2819 // Set the Parent field, then back to its old value once we're done.
2820 SetParentRAII SetParent(Parent, StmtParent, LI.getParent());
2821
2822 switch (LI.getKind()) {
2823 case VisitorJob::DeclVisitKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002824 const Decl *D = cast<DeclVisit>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00002825 if (!D)
2826 continue;
2827
2828 // For now, perform default visitation for Decls.
2829 if (Visit(MakeCXCursor(D, TU, RegionOfInterest,
2830 cast<DeclVisit>(&LI)->isFirst())))
2831 return true;
2832
2833 continue;
2834 }
2835 case VisitorJob::ExplicitTemplateArgsVisitKind: {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002836 for (const TemplateArgumentLoc &Arg :
2837 *cast<ExplicitTemplateArgsVisit>(&LI)) {
2838 if (VisitTemplateArgumentLoc(Arg))
Guy Benyei11169dd2012-12-18 14:30:41 +00002839 return true;
2840 }
2841 continue;
2842 }
2843 case VisitorJob::TypeLocVisitKind: {
2844 // Perform default visitation for TypeLocs.
2845 if (Visit(cast<TypeLocVisit>(&LI)->get()))
2846 return true;
2847 continue;
2848 }
2849 case VisitorJob::LabelRefVisitKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002850 const LabelDecl *LS = cast<LabelRefVisit>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00002851 if (LabelStmt *stmt = LS->getStmt()) {
2852 if (Visit(MakeCursorLabelRef(stmt, cast<LabelRefVisit>(&LI)->getLoc(),
2853 TU))) {
2854 return true;
2855 }
2856 }
2857 continue;
2858 }
2859
2860 case VisitorJob::NestedNameSpecifierLocVisitKind: {
2861 NestedNameSpecifierLocVisit *V = cast<NestedNameSpecifierLocVisit>(&LI);
2862 if (VisitNestedNameSpecifierLoc(V->get()))
2863 return true;
2864 continue;
2865 }
2866
2867 case VisitorJob::DeclarationNameInfoVisitKind: {
2868 if (VisitDeclarationNameInfo(cast<DeclarationNameInfoVisit>(&LI)
2869 ->get()))
2870 return true;
2871 continue;
2872 }
2873 case VisitorJob::MemberRefVisitKind: {
2874 MemberRefVisit *V = cast<MemberRefVisit>(&LI);
2875 if (Visit(MakeCursorMemberRef(V->get(), V->getLoc(), TU)))
2876 return true;
2877 continue;
2878 }
2879 case VisitorJob::StmtVisitKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002880 const Stmt *S = cast<StmtVisit>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00002881 if (!S)
2882 continue;
2883
2884 // Update the current cursor.
2885 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU, RegionOfInterest);
2886 if (!IsInRegionOfInterest(Cursor))
2887 continue;
2888 switch (Visitor(Cursor, Parent, ClientData)) {
2889 case CXChildVisit_Break: return true;
2890 case CXChildVisit_Continue: break;
2891 case CXChildVisit_Recurse:
2892 if (PostChildrenVisitor)
Craig Topper69186e72014-06-08 08:38:04 +00002893 WL.push_back(PostChildrenVisit(nullptr, Cursor));
Guy Benyei11169dd2012-12-18 14:30:41 +00002894 EnqueueWorkList(WL, S);
2895 break;
2896 }
2897 continue;
2898 }
2899 case VisitorJob::MemberExprPartsKind: {
2900 // Handle the other pieces in the MemberExpr besides the base.
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002901 const MemberExpr *M = cast<MemberExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00002902
2903 // Visit the nested-name-specifier
2904 if (NestedNameSpecifierLoc QualifierLoc = M->getQualifierLoc())
2905 if (VisitNestedNameSpecifierLoc(QualifierLoc))
2906 return true;
2907
2908 // Visit the declaration name.
2909 if (VisitDeclarationNameInfo(M->getMemberNameInfo()))
2910 return true;
2911
2912 // Visit the explicitly-specified template arguments, if any.
2913 if (M->hasExplicitTemplateArgs()) {
2914 for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(),
2915 *ArgEnd = Arg + M->getNumTemplateArgs();
2916 Arg != ArgEnd; ++Arg) {
2917 if (VisitTemplateArgumentLoc(*Arg))
2918 return true;
2919 }
2920 }
2921 continue;
2922 }
2923 case VisitorJob::DeclRefExprPartsKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002924 const DeclRefExpr *DR = cast<DeclRefExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00002925 // Visit nested-name-specifier, if present.
2926 if (NestedNameSpecifierLoc QualifierLoc = DR->getQualifierLoc())
2927 if (VisitNestedNameSpecifierLoc(QualifierLoc))
2928 return true;
2929 // Visit declaration name.
2930 if (VisitDeclarationNameInfo(DR->getNameInfo()))
2931 return true;
2932 continue;
2933 }
2934 case VisitorJob::OverloadExprPartsKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002935 const OverloadExpr *O = cast<OverloadExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00002936 // Visit the nested-name-specifier.
2937 if (NestedNameSpecifierLoc QualifierLoc = O->getQualifierLoc())
2938 if (VisitNestedNameSpecifierLoc(QualifierLoc))
2939 return true;
2940 // Visit the declaration name.
2941 if (VisitDeclarationNameInfo(O->getNameInfo()))
2942 return true;
2943 // Visit the overloaded declaration reference.
2944 if (Visit(MakeCursorOverloadedDeclRef(O, TU)))
2945 return true;
2946 continue;
2947 }
2948 case VisitorJob::SizeOfPackExprPartsKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002949 const SizeOfPackExpr *E = cast<SizeOfPackExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00002950 NamedDecl *Pack = E->getPack();
2951 if (isa<TemplateTypeParmDecl>(Pack)) {
2952 if (Visit(MakeCursorTypeRef(cast<TemplateTypeParmDecl>(Pack),
2953 E->getPackLoc(), TU)))
2954 return true;
2955
2956 continue;
2957 }
2958
2959 if (isa<TemplateTemplateParmDecl>(Pack)) {
2960 if (Visit(MakeCursorTemplateRef(cast<TemplateTemplateParmDecl>(Pack),
2961 E->getPackLoc(), TU)))
2962 return true;
2963
2964 continue;
2965 }
2966
2967 // Non-type template parameter packs and function parameter packs are
2968 // treated like DeclRefExpr cursors.
2969 continue;
2970 }
2971
2972 case VisitorJob::LambdaExprPartsKind: {
2973 // Visit captures.
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002974 const LambdaExpr *E = cast<LambdaExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00002975 for (LambdaExpr::capture_iterator C = E->explicit_capture_begin(),
2976 CEnd = E->explicit_capture_end();
2977 C != CEnd; ++C) {
Richard Smithba71c082013-05-16 06:20:58 +00002978 // FIXME: Lambda init-captures.
2979 if (!C->capturesVariable())
Guy Benyei11169dd2012-12-18 14:30:41 +00002980 continue;
Richard Smithba71c082013-05-16 06:20:58 +00002981
Guy Benyei11169dd2012-12-18 14:30:41 +00002982 if (Visit(MakeCursorVariableRef(C->getCapturedVar(),
2983 C->getLocation(),
2984 TU)))
2985 return true;
2986 }
2987
2988 // Visit parameters and return type, if present.
2989 if (E->hasExplicitParameters() || E->hasExplicitResultType()) {
2990 TypeLoc TL = E->getCallOperator()->getTypeSourceInfo()->getTypeLoc();
2991 if (E->hasExplicitParameters() && E->hasExplicitResultType()) {
2992 // Visit the whole type.
2993 if (Visit(TL))
2994 return true;
David Blaikie6adc78e2013-02-18 22:06:02 +00002995 } else if (FunctionProtoTypeLoc Proto =
2996 TL.getAs<FunctionProtoTypeLoc>()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002997 if (E->hasExplicitParameters()) {
2998 // Visit parameters.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00002999 for (unsigned I = 0, N = Proto.getNumParams(); I != N; ++I)
3000 if (Visit(MakeCXCursor(Proto.getParam(I), TU)))
Guy Benyei11169dd2012-12-18 14:30:41 +00003001 return true;
3002 } else {
3003 // Visit result type.
Alp Toker42a16a62014-01-25 23:51:36 +00003004 if (Visit(Proto.getReturnLoc()))
Guy Benyei11169dd2012-12-18 14:30:41 +00003005 return true;
3006 }
3007 }
3008 }
3009 break;
3010 }
3011
3012 case VisitorJob::PostChildrenVisitKind:
3013 if (PostChildrenVisitor(Parent, ClientData))
3014 return true;
3015 break;
3016 }
3017 }
3018 return false;
3019}
3020
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003021bool CursorVisitor::Visit(const Stmt *S) {
Craig Topper69186e72014-06-08 08:38:04 +00003022 VisitorWorkList *WL = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00003023 if (!WorkListFreeList.empty()) {
3024 WL = WorkListFreeList.back();
3025 WL->clear();
3026 WorkListFreeList.pop_back();
3027 }
3028 else {
3029 WL = new VisitorWorkList();
3030 WorkListCache.push_back(WL);
3031 }
3032 EnqueueWorkList(*WL, S);
3033 bool result = RunVisitorWorkList(*WL);
3034 WorkListFreeList.push_back(WL);
3035 return result;
3036}
3037
3038namespace {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003039typedef SmallVector<SourceRange, 4> RefNamePieces;
James Y Knight04ec5bf2015-12-24 02:59:37 +00003040RefNamePieces buildPieces(unsigned NameFlags, bool IsMemberRefExpr,
3041 const DeclarationNameInfo &NI, SourceRange QLoc,
3042 const SourceRange *TemplateArgsLoc = nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003043 const bool WantQualifier = NameFlags & CXNameRange_WantQualifier;
3044 const bool WantTemplateArgs = NameFlags & CXNameRange_WantTemplateArgs;
3045 const bool WantSinglePiece = NameFlags & CXNameRange_WantSinglePiece;
3046
3047 const DeclarationName::NameKind Kind = NI.getName().getNameKind();
3048
3049 RefNamePieces Pieces;
3050
3051 if (WantQualifier && QLoc.isValid())
3052 Pieces.push_back(QLoc);
3053
3054 if (Kind != DeclarationName::CXXOperatorName || IsMemberRefExpr)
3055 Pieces.push_back(NI.getLoc());
James Y Knight04ec5bf2015-12-24 02:59:37 +00003056
3057 if (WantTemplateArgs && TemplateArgsLoc && TemplateArgsLoc->isValid())
3058 Pieces.push_back(*TemplateArgsLoc);
3059
Guy Benyei11169dd2012-12-18 14:30:41 +00003060 if (Kind == DeclarationName::CXXOperatorName) {
3061 Pieces.push_back(SourceLocation::getFromRawEncoding(
3062 NI.getInfo().CXXOperatorName.BeginOpNameLoc));
3063 Pieces.push_back(SourceLocation::getFromRawEncoding(
3064 NI.getInfo().CXXOperatorName.EndOpNameLoc));
3065 }
3066
3067 if (WantSinglePiece) {
3068 SourceRange R(Pieces.front().getBegin(), Pieces.back().getEnd());
3069 Pieces.clear();
3070 Pieces.push_back(R);
3071 }
3072
3073 return Pieces;
3074}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003075}
Guy Benyei11169dd2012-12-18 14:30:41 +00003076
3077//===----------------------------------------------------------------------===//
3078// Misc. API hooks.
3079//===----------------------------------------------------------------------===//
3080
Chad Rosier05c71aa2013-03-27 18:28:23 +00003081static void fatal_error_handler(void *user_data, const std::string& reason,
3082 bool gen_crash_diag) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003083 // Write the result out to stderr avoiding errs() because raw_ostreams can
3084 // call report_fatal_error.
3085 fprintf(stderr, "LIBCLANG FATAL ERROR: %s\n", reason.c_str());
3086 ::abort();
3087}
3088
Chandler Carruth66660742014-06-27 16:37:27 +00003089namespace {
3090struct RegisterFatalErrorHandler {
3091 RegisterFatalErrorHandler() {
3092 llvm::install_fatal_error_handler(fatal_error_handler, nullptr);
3093 }
3094};
3095}
3096
3097static llvm::ManagedStatic<RegisterFatalErrorHandler> RegisterFatalErrorHandlerOnce;
3098
Guy Benyei11169dd2012-12-18 14:30:41 +00003099extern "C" {
3100CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
3101 int displayDiagnostics) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003102 // We use crash recovery to make some of our APIs more reliable, implicitly
3103 // enable it.
Argyrios Kyrtzidis3701f542013-11-27 08:58:09 +00003104 if (!getenv("LIBCLANG_DISABLE_CRASH_RECOVERY"))
3105 llvm::CrashRecoveryContext::Enable();
Guy Benyei11169dd2012-12-18 14:30:41 +00003106
Chandler Carruth66660742014-06-27 16:37:27 +00003107 // Look through the managed static to trigger construction of the managed
3108 // static which registers our fatal error handler. This ensures it is only
3109 // registered once.
3110 (void)*RegisterFatalErrorHandlerOnce;
Guy Benyei11169dd2012-12-18 14:30:41 +00003111
Adrian Prantlbc068582015-07-08 01:00:30 +00003112 // Initialize targets for clang module support.
3113 llvm::InitializeAllTargets();
3114 llvm::InitializeAllTargetMCs();
3115 llvm::InitializeAllAsmPrinters();
3116 llvm::InitializeAllAsmParsers();
3117
Adrian Prantlfb2398d2015-07-17 01:19:54 +00003118 CIndexer *CIdxr = new CIndexer();
3119
Guy Benyei11169dd2012-12-18 14:30:41 +00003120 if (excludeDeclarationsFromPCH)
3121 CIdxr->setOnlyLocalDecls();
3122 if (displayDiagnostics)
3123 CIdxr->setDisplayDiagnostics();
3124
3125 if (getenv("LIBCLANG_BGPRIO_INDEX"))
3126 CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() |
3127 CXGlobalOpt_ThreadBackgroundPriorityForIndexing);
3128 if (getenv("LIBCLANG_BGPRIO_EDIT"))
3129 CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() |
3130 CXGlobalOpt_ThreadBackgroundPriorityForEditing);
3131
3132 return CIdxr;
3133}
3134
3135void clang_disposeIndex(CXIndex CIdx) {
3136 if (CIdx)
3137 delete static_cast<CIndexer *>(CIdx);
3138}
3139
3140void clang_CXIndex_setGlobalOptions(CXIndex CIdx, unsigned options) {
3141 if (CIdx)
3142 static_cast<CIndexer *>(CIdx)->setCXGlobalOptFlags(options);
3143}
3144
3145unsigned clang_CXIndex_getGlobalOptions(CXIndex CIdx) {
3146 if (CIdx)
3147 return static_cast<CIndexer *>(CIdx)->getCXGlobalOptFlags();
3148 return 0;
3149}
3150
3151void clang_toggleCrashRecovery(unsigned isEnabled) {
3152 if (isEnabled)
3153 llvm::CrashRecoveryContext::Enable();
3154 else
3155 llvm::CrashRecoveryContext::Disable();
3156}
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003157
Guy Benyei11169dd2012-12-18 14:30:41 +00003158CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
3159 const char *ast_filename) {
Dmitri Gribenko8850cda2014-02-19 10:24:00 +00003160 CXTranslationUnit TU;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003161 enum CXErrorCode Result =
3162 clang_createTranslationUnit2(CIdx, ast_filename, &TU);
Reid Klecknerfd48fc62014-02-12 23:56:20 +00003163 (void)Result;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003164 assert((TU && Result == CXError_Success) ||
3165 (!TU && Result != CXError_Success));
3166 return TU;
3167}
3168
3169enum CXErrorCode clang_createTranslationUnit2(CXIndex CIdx,
3170 const char *ast_filename,
3171 CXTranslationUnit *out_TU) {
Dmitri Gribenko8850cda2014-02-19 10:24:00 +00003172 if (out_TU)
Craig Topper69186e72014-06-08 08:38:04 +00003173 *out_TU = nullptr;
Dmitri Gribenko8850cda2014-02-19 10:24:00 +00003174
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003175 if (!CIdx || !ast_filename || !out_TU)
3176 return CXError_InvalidArguments;
Guy Benyei11169dd2012-12-18 14:30:41 +00003177
Argyrios Kyrtzidis27021012013-05-24 22:24:07 +00003178 LOG_FUNC_SECTION {
3179 *Log << ast_filename;
3180 }
3181
Guy Benyei11169dd2012-12-18 14:30:41 +00003182 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
3183 FileSystemOptions FileSystemOpts;
3184
Justin Bognerd512c1e2014-10-15 00:33:06 +00003185 IntrusiveRefCntPtr<DiagnosticsEngine> Diags =
3186 CompilerInstance::createDiagnostics(new DiagnosticOptions());
David Blaikie6f7382d2014-08-10 19:08:04 +00003187 std::unique_ptr<ASTUnit> AU = ASTUnit::LoadFromASTFile(
Adrian Prantlfb2398d2015-07-17 01:19:54 +00003188 ast_filename, CXXIdx->getPCHContainerOperations()->getRawReader(), Diags,
Adrian Prantl6b21ab22015-08-27 19:46:20 +00003189 FileSystemOpts, /*UseDebugInfo=*/false,
3190 CXXIdx->getOnlyLocalDecls(), None,
David Blaikie6f7382d2014-08-10 19:08:04 +00003191 /*CaptureDiagnostics=*/true,
3192 /*AllowPCHWithCompilerErrors=*/true,
3193 /*UserFilesAreVolatile=*/true);
3194 *out_TU = MakeCXTranslationUnit(CXXIdx, AU.release());
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003195 return *out_TU ? CXError_Success : CXError_Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003196}
3197
3198unsigned clang_defaultEditingTranslationUnitOptions() {
3199 return CXTranslationUnit_PrecompiledPreamble |
3200 CXTranslationUnit_CacheCompletionResults;
3201}
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003202
Guy Benyei11169dd2012-12-18 14:30:41 +00003203CXTranslationUnit
3204clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
3205 const char *source_filename,
3206 int num_command_line_args,
3207 const char * const *command_line_args,
3208 unsigned num_unsaved_files,
3209 struct CXUnsavedFile *unsaved_files) {
3210 unsigned Options = CXTranslationUnit_DetailedPreprocessingRecord;
3211 return clang_parseTranslationUnit(CIdx, source_filename,
3212 command_line_args, num_command_line_args,
3213 unsaved_files, num_unsaved_files,
3214 Options);
3215}
3216
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003217static CXErrorCode
3218clang_parseTranslationUnit_Impl(CXIndex CIdx, const char *source_filename,
3219 const char *const *command_line_args,
3220 int num_command_line_args,
3221 ArrayRef<CXUnsavedFile> unsaved_files,
3222 unsigned options, CXTranslationUnit *out_TU) {
Dmitri Gribenko1bf8d912014-02-18 15:20:02 +00003223 // Set up the initial return values.
3224 if (out_TU)
Craig Topper69186e72014-06-08 08:38:04 +00003225 *out_TU = nullptr;
Dmitri Gribenko1bf8d912014-02-18 15:20:02 +00003226
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003227 // Check arguments.
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003228 if (!CIdx || !out_TU)
3229 return CXError_InvalidArguments;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003230
Guy Benyei11169dd2012-12-18 14:30:41 +00003231 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
3232
3233 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
3234 setThreadBackgroundPriority();
3235
3236 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Benjamin Kramer5c248d82015-12-15 09:30:31 +00003237 bool CreatePreambleOnFirstParse =
3238 options & CXTranslationUnit_CreatePreambleOnFirstParse;
Guy Benyei11169dd2012-12-18 14:30:41 +00003239 // FIXME: Add a flag for modules.
3240 TranslationUnitKind TUKind
3241 = (options & CXTranslationUnit_Incomplete)? TU_Prefix : TU_Complete;
Alp Toker8c8a8752013-12-03 06:53:35 +00003242 bool CacheCodeCompletionResults
Guy Benyei11169dd2012-12-18 14:30:41 +00003243 = options & CXTranslationUnit_CacheCompletionResults;
3244 bool IncludeBriefCommentsInCodeCompletion
3245 = options & CXTranslationUnit_IncludeBriefCommentsInCodeCompletion;
3246 bool SkipFunctionBodies = options & CXTranslationUnit_SkipFunctionBodies;
3247 bool ForSerialization = options & CXTranslationUnit_ForSerialization;
3248
3249 // Configure the diagnostics.
3250 IntrusiveRefCntPtr<DiagnosticsEngine>
Sean Silvaf1b49e22013-01-20 01:58:28 +00003251 Diags(CompilerInstance::createDiagnostics(new DiagnosticOptions));
Guy Benyei11169dd2012-12-18 14:30:41 +00003252
Manuel Klimek016c0242016-03-01 10:56:19 +00003253 if (options & CXTranslationUnit_KeepGoing)
3254 Diags->setFatalsAsError(true);
3255
Guy Benyei11169dd2012-12-18 14:30:41 +00003256 // Recover resources if we crash before exiting this function.
3257 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
3258 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Alp Tokerf994cef2014-07-05 03:08:06 +00003259 DiagCleanup(Diags.get());
Guy Benyei11169dd2012-12-18 14:30:41 +00003260
Ahmed Charlesb8984322014-03-07 20:03:18 +00003261 std::unique_ptr<std::vector<ASTUnit::RemappedFile>> RemappedFiles(
3262 new std::vector<ASTUnit::RemappedFile>());
Guy Benyei11169dd2012-12-18 14:30:41 +00003263
3264 // Recover resources if we crash before exiting this function.
3265 llvm::CrashRecoveryContextCleanupRegistrar<
3266 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
3267
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003268 for (auto &UF : unsaved_files) {
Rafael Espindolad87f8d72014-08-27 20:03:29 +00003269 std::unique_ptr<llvm::MemoryBuffer> MB =
Alp Toker9d85b182014-07-07 01:23:14 +00003270 llvm::MemoryBuffer::getMemBufferCopy(getContents(UF), UF.Filename);
Rafael Espindolad87f8d72014-08-27 20:03:29 +00003271 RemappedFiles->push_back(std::make_pair(UF.Filename, MB.release()));
Guy Benyei11169dd2012-12-18 14:30:41 +00003272 }
3273
Ahmed Charlesb8984322014-03-07 20:03:18 +00003274 std::unique_ptr<std::vector<const char *>> Args(
3275 new std::vector<const char *>());
Guy Benyei11169dd2012-12-18 14:30:41 +00003276
3277 // Recover resources if we crash before exiting this method.
3278 llvm::CrashRecoveryContextCleanupRegistrar<std::vector<const char*> >
3279 ArgsCleanup(Args.get());
3280
3281 // Since the Clang C library is primarily used by batch tools dealing with
3282 // (often very broken) source code, where spell-checking can have a
3283 // significant negative impact on performance (particularly when
3284 // precompiled headers are involved), we disable it by default.
3285 // Only do this if we haven't found a spell-checking-related argument.
3286 bool FoundSpellCheckingArgument = false;
3287 for (int I = 0; I != num_command_line_args; ++I) {
3288 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
3289 strcmp(command_line_args[I], "-fspell-checking") == 0) {
3290 FoundSpellCheckingArgument = true;
3291 break;
3292 }
3293 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003294 Args->insert(Args->end(), command_line_args,
3295 command_line_args + num_command_line_args);
3296
Benjamin Kramerc02670e2015-11-18 16:14:27 +00003297 if (!FoundSpellCheckingArgument)
3298 Args->insert(Args->begin() + 1, "-fno-spell-checking");
3299
Guy Benyei11169dd2012-12-18 14:30:41 +00003300 // The 'source_filename' argument is optional. If the caller does not
3301 // specify it then it is assumed that the source file is specified
3302 // in the actual argument list.
3303 // Put the source file after command_line_args otherwise if '-x' flag is
3304 // present it will be unused.
3305 if (source_filename)
3306 Args->push_back(source_filename);
3307
3308 // Do we need the detailed preprocessing record?
3309 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
3310 Args->push_back("-Xclang");
3311 Args->push_back("-detailed-preprocessing-record");
3312 }
3313
3314 unsigned NumErrors = Diags->getClient()->getNumErrors();
Ahmed Charlesb8984322014-03-07 20:03:18 +00003315 std::unique_ptr<ASTUnit> ErrUnit;
Benjamin Kramer5c248d82015-12-15 09:30:31 +00003316 // Unless the user specified that they want the preamble on the first parse
3317 // set it up to be created on the first reparse. This makes the first parse
3318 // faster, trading for a slower (first) reparse.
3319 unsigned PrecompilePreambleAfterNParses =
3320 !PrecompilePreamble ? 0 : 2 - CreatePreambleOnFirstParse;
Ahmed Charlesb8984322014-03-07 20:03:18 +00003321 std::unique_ptr<ASTUnit> Unit(ASTUnit::LoadFromCommandLine(
Adrian Prantlbb165fb2015-06-20 18:53:08 +00003322 Args->data(), Args->data() + Args->size(),
3323 CXXIdx->getPCHContainerOperations(), Diags,
Ahmed Charlesb8984322014-03-07 20:03:18 +00003324 CXXIdx->getClangResourcesPath(), CXXIdx->getOnlyLocalDecls(),
3325 /*CaptureDiagnostics=*/true, *RemappedFiles.get(),
Benjamin Kramer5c248d82015-12-15 09:30:31 +00003326 /*RemappedFilesKeepOriginalName=*/true, PrecompilePreambleAfterNParses,
3327 TUKind, CacheCodeCompletionResults, IncludeBriefCommentsInCodeCompletion,
Ahmed Charlesb8984322014-03-07 20:03:18 +00003328 /*AllowPCHWithCompilerErrors=*/true, SkipFunctionBodies,
Argyrios Kyrtzidisa3e2ff12015-11-20 03:36:21 +00003329 /*UserFilesAreVolatile=*/true, ForSerialization,
3330 CXXIdx->getPCHContainerOperations()->getRawReader().getFormat(),
3331 &ErrUnit));
Guy Benyei11169dd2012-12-18 14:30:41 +00003332
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003333 // Early failures in LoadFromCommandLine may return with ErrUnit unset.
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003334 if (!Unit && !ErrUnit)
3335 return CXError_ASTReadError;
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003336
Guy Benyei11169dd2012-12-18 14:30:41 +00003337 if (NumErrors != Diags->getClient()->getNumErrors()) {
3338 // Make sure to check that 'Unit' is non-NULL.
3339 if (CXXIdx->getDisplayDiagnostics())
3340 printDiagsToStderr(Unit ? Unit.get() : ErrUnit.get());
3341 }
3342
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003343 if (isASTReadError(Unit ? Unit.get() : ErrUnit.get()))
3344 return CXError_ASTReadError;
3345
3346 *out_TU = MakeCXTranslationUnit(CXXIdx, Unit.release());
3347 return *out_TU ? CXError_Success : CXError_Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003348}
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003349
3350CXTranslationUnit
3351clang_parseTranslationUnit(CXIndex CIdx,
3352 const char *source_filename,
3353 const char *const *command_line_args,
3354 int num_command_line_args,
3355 struct CXUnsavedFile *unsaved_files,
3356 unsigned num_unsaved_files,
3357 unsigned options) {
3358 CXTranslationUnit TU;
3359 enum CXErrorCode Result = clang_parseTranslationUnit2(
3360 CIdx, source_filename, command_line_args, num_command_line_args,
3361 unsaved_files, num_unsaved_files, options, &TU);
Reid Kleckner6eaf05a2014-02-13 01:19:59 +00003362 (void)Result;
Dmitri Gribenko1bf8d912014-02-18 15:20:02 +00003363 assert((TU && Result == CXError_Success) ||
3364 (!TU && Result != CXError_Success));
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003365 return TU;
3366}
3367
3368enum CXErrorCode clang_parseTranslationUnit2(
Benjamin Kramerc02670e2015-11-18 16:14:27 +00003369 CXIndex CIdx, const char *source_filename,
3370 const char *const *command_line_args, int num_command_line_args,
3371 struct CXUnsavedFile *unsaved_files, unsigned num_unsaved_files,
3372 unsigned options, CXTranslationUnit *out_TU) {
3373 SmallVector<const char *, 4> Args;
3374 Args.push_back("clang");
3375 Args.append(command_line_args, command_line_args + num_command_line_args);
3376 return clang_parseTranslationUnit2FullArgv(
3377 CIdx, source_filename, Args.data(), Args.size(), unsaved_files,
3378 num_unsaved_files, options, out_TU);
3379}
3380
3381enum CXErrorCode clang_parseTranslationUnit2FullArgv(
3382 CXIndex CIdx, const char *source_filename,
3383 const char *const *command_line_args, int num_command_line_args,
3384 struct CXUnsavedFile *unsaved_files, unsigned num_unsaved_files,
3385 unsigned options, CXTranslationUnit *out_TU) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00003386 LOG_FUNC_SECTION {
3387 *Log << source_filename << ": ";
3388 for (int i = 0; i != num_command_line_args; ++i)
3389 *Log << command_line_args[i] << " ";
3390 }
3391
Alp Toker9d85b182014-07-07 01:23:14 +00003392 if (num_unsaved_files && !unsaved_files)
3393 return CXError_InvalidArguments;
3394
Alp Toker5c532982014-07-07 22:42:03 +00003395 CXErrorCode result = CXError_Failure;
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003396 auto ParseTranslationUnitImpl = [=, &result] {
3397 result = clang_parseTranslationUnit_Impl(
3398 CIdx, source_filename, command_line_args, num_command_line_args,
3399 llvm::makeArrayRef(unsaved_files, num_unsaved_files), options, out_TU);
3400 };
Guy Benyei11169dd2012-12-18 14:30:41 +00003401 llvm::CrashRecoveryContext CRC;
3402
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003403 if (!RunSafely(CRC, ParseTranslationUnitImpl)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003404 fprintf(stderr, "libclang: crash detected during parsing: {\n");
3405 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
3406 fprintf(stderr, " 'command_line_args' : [");
3407 for (int i = 0; i != num_command_line_args; ++i) {
3408 if (i)
3409 fprintf(stderr, ", ");
3410 fprintf(stderr, "'%s'", command_line_args[i]);
3411 }
3412 fprintf(stderr, "],\n");
3413 fprintf(stderr, " 'unsaved_files' : [");
3414 for (unsigned i = 0; i != num_unsaved_files; ++i) {
3415 if (i)
3416 fprintf(stderr, ", ");
3417 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
3418 unsaved_files[i].Length);
3419 }
3420 fprintf(stderr, "],\n");
3421 fprintf(stderr, " 'options' : %d,\n", options);
3422 fprintf(stderr, "}\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003423
3424 return CXError_Crashed;
Guy Benyei11169dd2012-12-18 14:30:41 +00003425 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003426 if (CXTranslationUnit *TU = out_TU)
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003427 PrintLibclangResourceUsage(*TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00003428 }
Alp Toker5c532982014-07-07 22:42:03 +00003429
3430 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003431}
3432
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003433CXString clang_Type_getObjCEncoding(CXType CT) {
3434 CXTranslationUnit tu = static_cast<CXTranslationUnit>(CT.data[1]);
3435 ASTContext &Ctx = getASTUnit(tu)->getASTContext();
3436 std::string encoding;
3437 Ctx.getObjCEncodingForType(QualType::getFromOpaquePtr(CT.data[0]),
3438 encoding);
3439
3440 return cxstring::createDup(encoding);
3441}
3442
3443static const IdentifierInfo *getMacroIdentifier(CXCursor C) {
3444 if (C.kind == CXCursor_MacroDefinition) {
3445 if (const MacroDefinitionRecord *MDR = getCursorMacroDefinition(C))
3446 return MDR->getName();
3447 } else if (C.kind == CXCursor_MacroExpansion) {
3448 MacroExpansionCursor ME = getCursorMacroExpansion(C);
3449 return ME.getName();
3450 }
3451 return nullptr;
3452}
3453
3454unsigned clang_Cursor_isMacroFunctionLike(CXCursor C) {
3455 const IdentifierInfo *II = getMacroIdentifier(C);
3456 if (!II) {
3457 return false;
3458 }
3459 ASTUnit *ASTU = getCursorASTUnit(C);
3460 Preprocessor &PP = ASTU->getPreprocessor();
3461 if (const MacroInfo *MI = PP.getMacroInfo(II))
3462 return MI->isFunctionLike();
3463 return false;
3464}
3465
3466unsigned clang_Cursor_isMacroBuiltin(CXCursor C) {
3467 const IdentifierInfo *II = getMacroIdentifier(C);
3468 if (!II) {
3469 return false;
3470 }
3471 ASTUnit *ASTU = getCursorASTUnit(C);
3472 Preprocessor &PP = ASTU->getPreprocessor();
3473 if (const MacroInfo *MI = PP.getMacroInfo(II))
3474 return MI->isBuiltinMacro();
3475 return false;
3476}
3477
3478unsigned clang_Cursor_isFunctionInlined(CXCursor C) {
3479 const Decl *D = getCursorDecl(C);
3480 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
3481 if (!FD) {
3482 return false;
3483 }
3484 return FD->isInlined();
3485}
3486
3487static StringLiteral* getCFSTR_value(CallExpr *callExpr) {
3488 if (callExpr->getNumArgs() != 1) {
3489 return nullptr;
3490 }
3491
3492 StringLiteral *S = nullptr;
3493 auto *arg = callExpr->getArg(0);
3494 if (arg->getStmtClass() == Stmt::ImplicitCastExprClass) {
3495 ImplicitCastExpr *I = static_cast<ImplicitCastExpr *>(arg);
3496 auto *subExpr = I->getSubExprAsWritten();
3497
3498 if(subExpr->getStmtClass() != Stmt::StringLiteralClass){
3499 return nullptr;
3500 }
3501
3502 S = static_cast<StringLiteral *>(I->getSubExprAsWritten());
3503 } else if (arg->getStmtClass() == Stmt::StringLiteralClass) {
3504 S = static_cast<StringLiteral *>(callExpr->getArg(0));
3505 } else {
3506 return nullptr;
3507 }
3508 return S;
3509}
3510
David Blaikie59272572016-04-13 18:23:33 +00003511struct ExprEvalResult {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003512 CXEvalResultKind EvalType;
3513 union {
3514 int intVal;
3515 double floatVal;
3516 char *stringVal;
3517 } EvalData;
David Blaikie59272572016-04-13 18:23:33 +00003518 ~ExprEvalResult() {
3519 if (EvalType != CXEval_UnExposed && EvalType != CXEval_Float &&
3520 EvalType != CXEval_Int) {
3521 delete EvalData.stringVal;
3522 }
3523 }
3524};
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003525
3526void clang_EvalResult_dispose(CXEvalResult E) {
David Blaikie59272572016-04-13 18:23:33 +00003527 delete static_cast<ExprEvalResult *>(E);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003528}
3529
3530CXEvalResultKind clang_EvalResult_getKind(CXEvalResult E) {
3531 if (!E) {
3532 return CXEval_UnExposed;
3533 }
3534 return ((ExprEvalResult *)E)->EvalType;
3535}
3536
3537int clang_EvalResult_getAsInt(CXEvalResult E) {
3538 if (!E) {
3539 return 0;
3540 }
3541 return ((ExprEvalResult *)E)->EvalData.intVal;
3542}
3543
3544double clang_EvalResult_getAsDouble(CXEvalResult E) {
3545 if (!E) {
3546 return 0;
3547 }
3548 return ((ExprEvalResult *)E)->EvalData.floatVal;
3549}
3550
3551const char* clang_EvalResult_getAsStr(CXEvalResult E) {
3552 if (!E) {
3553 return nullptr;
3554 }
3555 return ((ExprEvalResult *)E)->EvalData.stringVal;
3556}
3557
3558static const ExprEvalResult* evaluateExpr(Expr *expr, CXCursor C) {
3559 Expr::EvalResult ER;
3560 ASTContext &ctx = getCursorContext(C);
David Blaikiebbc00882016-04-13 18:36:19 +00003561 if (!expr)
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003562 return nullptr;
David Blaikiebbc00882016-04-13 18:36:19 +00003563
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003564 expr = expr->IgnoreParens();
David Blaikiebbc00882016-04-13 18:36:19 +00003565 if (!expr->EvaluateAsRValue(ER, ctx))
3566 return nullptr;
3567
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003568 QualType rettype;
3569 CallExpr *callExpr;
David Blaikie59272572016-04-13 18:23:33 +00003570 auto result = llvm::make_unique<ExprEvalResult>();
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003571 result->EvalType = CXEval_UnExposed;
3572
David Blaikiebbc00882016-04-13 18:36:19 +00003573 if (ER.Val.isInt()) {
3574 result->EvalType = CXEval_Int;
3575 result->EvalData.intVal = ER.Val.getInt().getExtValue();
3576 return result.release();
3577 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003578
David Blaikiebbc00882016-04-13 18:36:19 +00003579 if (ER.Val.isFloat()) {
3580 llvm::SmallVector<char, 100> Buffer;
3581 ER.Val.getFloat().toString(Buffer);
3582 std::string floatStr(Buffer.data(), Buffer.size());
3583 result->EvalType = CXEval_Float;
3584 bool ignored;
3585 llvm::APFloat apFloat = ER.Val.getFloat();
3586 apFloat.convert(llvm::APFloat::IEEEdouble,
3587 llvm::APFloat::rmNearestTiesToEven, &ignored);
3588 result->EvalData.floatVal = apFloat.convertToDouble();
3589 return result.release();
3590 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003591
David Blaikiebbc00882016-04-13 18:36:19 +00003592 if (expr->getStmtClass() == Stmt::ImplicitCastExprClass) {
3593 const ImplicitCastExpr *I = dyn_cast<ImplicitCastExpr>(expr);
3594 auto *subExpr = I->getSubExprAsWritten();
3595 if (subExpr->getStmtClass() == Stmt::StringLiteralClass ||
3596 subExpr->getStmtClass() == Stmt::ObjCStringLiteralClass) {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003597 const StringLiteral *StrE = nullptr;
3598 const ObjCStringLiteral *ObjCExpr;
David Blaikiebbc00882016-04-13 18:36:19 +00003599 ObjCExpr = dyn_cast<ObjCStringLiteral>(subExpr);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003600
3601 if (ObjCExpr) {
3602 StrE = ObjCExpr->getString();
3603 result->EvalType = CXEval_ObjCStrLiteral;
3604 } else {
David Blaikiebbc00882016-04-13 18:36:19 +00003605 StrE = cast<StringLiteral>(I->getSubExprAsWritten());
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003606 result->EvalType = CXEval_StrLiteral;
3607 }
3608
3609 std::string strRef(StrE->getString().str());
David Blaikie59272572016-04-13 18:23:33 +00003610 result->EvalData.stringVal = new char[strRef.size() + 1];
David Blaikiebbc00882016-04-13 18:36:19 +00003611 strncpy((char *)result->EvalData.stringVal, strRef.c_str(),
3612 strRef.size());
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003613 result->EvalData.stringVal[strRef.size()] = '\0';
David Blaikie59272572016-04-13 18:23:33 +00003614 return result.release();
David Blaikiebbc00882016-04-13 18:36:19 +00003615 }
3616 } else if (expr->getStmtClass() == Stmt::ObjCStringLiteralClass ||
3617 expr->getStmtClass() == Stmt::StringLiteralClass) {
3618 const StringLiteral *StrE = nullptr;
3619 const ObjCStringLiteral *ObjCExpr;
3620 ObjCExpr = dyn_cast<ObjCStringLiteral>(expr);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003621
David Blaikiebbc00882016-04-13 18:36:19 +00003622 if (ObjCExpr) {
3623 StrE = ObjCExpr->getString();
3624 result->EvalType = CXEval_ObjCStrLiteral;
3625 } else {
3626 StrE = cast<StringLiteral>(expr);
3627 result->EvalType = CXEval_StrLiteral;
3628 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003629
David Blaikiebbc00882016-04-13 18:36:19 +00003630 std::string strRef(StrE->getString().str());
3631 result->EvalData.stringVal = new char[strRef.size() + 1];
3632 strncpy((char *)result->EvalData.stringVal, strRef.c_str(), strRef.size());
3633 result->EvalData.stringVal[strRef.size()] = '\0';
3634 return result.release();
3635 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003636
David Blaikiebbc00882016-04-13 18:36:19 +00003637 if (expr->getStmtClass() == Stmt::CStyleCastExprClass) {
3638 CStyleCastExpr *CC = static_cast<CStyleCastExpr *>(expr);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003639
David Blaikiebbc00882016-04-13 18:36:19 +00003640 rettype = CC->getType();
3641 if (rettype.getAsString() == "CFStringRef" &&
3642 CC->getSubExpr()->getStmtClass() == Stmt::CallExprClass) {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003643
David Blaikiebbc00882016-04-13 18:36:19 +00003644 callExpr = static_cast<CallExpr *>(CC->getSubExpr());
3645 StringLiteral *S = getCFSTR_value(callExpr);
3646 if (S) {
3647 std::string strLiteral(S->getString().str());
3648 result->EvalType = CXEval_CFStr;
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003649
David Blaikiebbc00882016-04-13 18:36:19 +00003650 result->EvalData.stringVal = new char[strLiteral.size() + 1];
3651 strncpy((char *)result->EvalData.stringVal, strLiteral.c_str(),
3652 strLiteral.size());
3653 result->EvalData.stringVal[strLiteral.size()] = '\0';
David Blaikie59272572016-04-13 18:23:33 +00003654 return result.release();
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003655 }
3656 }
3657
David Blaikiebbc00882016-04-13 18:36:19 +00003658 } else if (expr->getStmtClass() == Stmt::CallExprClass) {
3659 callExpr = static_cast<CallExpr *>(expr);
3660 rettype = callExpr->getCallReturnType(ctx);
3661
3662 if (rettype->isVectorType() || callExpr->getNumArgs() > 1)
3663 return nullptr;
3664
3665 if (rettype->isIntegralType(ctx) || rettype->isRealFloatingType()) {
3666 if (callExpr->getNumArgs() == 1 &&
3667 !callExpr->getArg(0)->getType()->isIntegralType(ctx))
3668 return nullptr;
3669 } else if (rettype.getAsString() == "CFStringRef") {
3670
3671 StringLiteral *S = getCFSTR_value(callExpr);
3672 if (S) {
3673 std::string strLiteral(S->getString().str());
3674 result->EvalType = CXEval_CFStr;
3675 result->EvalData.stringVal = new char[strLiteral.size() + 1];
3676 strncpy((char *)result->EvalData.stringVal, strLiteral.c_str(),
3677 strLiteral.size());
3678 result->EvalData.stringVal[strLiteral.size()] = '\0';
3679 return result.release();
3680 }
3681 }
3682 } else if (expr->getStmtClass() == Stmt::DeclRefExprClass) {
3683 DeclRefExpr *D = static_cast<DeclRefExpr *>(expr);
3684 ValueDecl *V = D->getDecl();
3685 if (V->getKind() == Decl::Function) {
3686 std::string strName = V->getNameAsString();
3687 result->EvalType = CXEval_Other;
3688 result->EvalData.stringVal = new char[strName.size() + 1];
3689 strncpy(result->EvalData.stringVal, strName.c_str(), strName.size());
3690 result->EvalData.stringVal[strName.size()] = '\0';
3691 return result.release();
3692 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003693 }
3694
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003695 return nullptr;
3696}
3697
3698CXEvalResult clang_Cursor_Evaluate(CXCursor C) {
3699 const Decl *D = getCursorDecl(C);
3700 if (D) {
3701 const Expr *expr = nullptr;
3702 if (auto *Var = dyn_cast<VarDecl>(D)) {
3703 expr = Var->getInit();
3704 } else if (auto *Field = dyn_cast<FieldDecl>(D)) {
3705 expr = Field->getInClassInitializer();
3706 }
3707 if (expr)
Aaron Ballman01dc1572016-01-20 15:25:30 +00003708 return const_cast<CXEvalResult>(reinterpret_cast<const void *>(
3709 evaluateExpr(const_cast<Expr *>(expr), C)));
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003710 return nullptr;
3711 }
3712
3713 const CompoundStmt *compoundStmt = dyn_cast_or_null<CompoundStmt>(getCursorStmt(C));
3714 if (compoundStmt) {
3715 Expr *expr = nullptr;
3716 for (auto *bodyIterator : compoundStmt->body()) {
3717 if ((expr = dyn_cast<Expr>(bodyIterator))) {
3718 break;
3719 }
3720 }
3721 if (expr)
Aaron Ballman01dc1572016-01-20 15:25:30 +00003722 return const_cast<CXEvalResult>(
3723 reinterpret_cast<const void *>(evaluateExpr(expr, C)));
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003724 }
3725 return nullptr;
3726}
3727
3728unsigned clang_Cursor_hasAttrs(CXCursor C) {
3729 const Decl *D = getCursorDecl(C);
3730 if (!D) {
3731 return 0;
3732 }
3733
3734 if (D->hasAttrs()) {
3735 return 1;
3736 }
3737
3738 return 0;
3739}
Guy Benyei11169dd2012-12-18 14:30:41 +00003740unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
3741 return CXSaveTranslationUnit_None;
3742}
3743
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003744static CXSaveError clang_saveTranslationUnit_Impl(CXTranslationUnit TU,
3745 const char *FileName,
3746 unsigned options) {
3747 CIndexer *CXXIdx = TU->CIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00003748 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
3749 setThreadBackgroundPriority();
3750
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003751 bool hadError = cxtu::getASTUnit(TU)->Save(FileName);
3752 return hadError ? CXSaveError_Unknown : CXSaveError_None;
Guy Benyei11169dd2012-12-18 14:30:41 +00003753}
3754
3755int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
3756 unsigned options) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00003757 LOG_FUNC_SECTION {
3758 *Log << TU << ' ' << FileName;
3759 }
3760
Dmitri Gribenko852d6222014-02-11 15:02:48 +00003761 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00003762 LOG_BAD_TU(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00003763 return CXSaveError_InvalidTU;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00003764 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003765
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00003766 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00003767 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3768 if (!CXXUnit->hasSema())
3769 return CXSaveError_InvalidTU;
3770
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003771 CXSaveError result;
3772 auto SaveTranslationUnitImpl = [=, &result]() {
3773 result = clang_saveTranslationUnit_Impl(TU, FileName, options);
3774 };
Guy Benyei11169dd2012-12-18 14:30:41 +00003775
3776 if (!CXXUnit->getDiagnostics().hasUnrecoverableErrorOccurred() ||
3777 getenv("LIBCLANG_NOTHREADS")) {
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003778 SaveTranslationUnitImpl();
Guy Benyei11169dd2012-12-18 14:30:41 +00003779
3780 if (getenv("LIBCLANG_RESOURCE_USAGE"))
3781 PrintLibclangResourceUsage(TU);
3782
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003783 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003784 }
3785
3786 // We have an AST that has invalid nodes due to compiler errors.
3787 // Use a crash recovery thread for protection.
3788
3789 llvm::CrashRecoveryContext CRC;
3790
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003791 if (!RunSafely(CRC, SaveTranslationUnitImpl)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003792 fprintf(stderr, "libclang: crash detected during AST saving: {\n");
3793 fprintf(stderr, " 'filename' : '%s'\n", FileName);
3794 fprintf(stderr, " 'options' : %d,\n", options);
3795 fprintf(stderr, "}\n");
3796
3797 return CXSaveError_Unknown;
3798
3799 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
3800 PrintLibclangResourceUsage(TU);
3801 }
3802
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003803 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003804}
3805
3806void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
3807 if (CTUnit) {
3808 // If the translation unit has been marked as unsafe to free, just discard
3809 // it.
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003810 ASTUnit *Unit = cxtu::getASTUnit(CTUnit);
3811 if (Unit && Unit->isUnsafeToFree())
Guy Benyei11169dd2012-12-18 14:30:41 +00003812 return;
3813
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00003814 delete cxtu::getASTUnit(CTUnit);
Dmitri Gribenkob95b3f12013-01-26 22:44:19 +00003815 delete CTUnit->StringPool;
Guy Benyei11169dd2012-12-18 14:30:41 +00003816 delete static_cast<CXDiagnosticSetImpl *>(CTUnit->Diagnostics);
3817 disposeOverridenCXCursorsPool(CTUnit->OverridenCursorsPool);
Dmitri Gribenko9e605112013-11-13 22:16:51 +00003818 delete CTUnit->CommentToXML;
Guy Benyei11169dd2012-12-18 14:30:41 +00003819 delete CTUnit;
3820 }
3821}
3822
3823unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
3824 return CXReparse_None;
3825}
3826
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003827static CXErrorCode
3828clang_reparseTranslationUnit_Impl(CXTranslationUnit TU,
3829 ArrayRef<CXUnsavedFile> unsaved_files,
3830 unsigned options) {
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003831 // Check arguments.
Dmitri Gribenko852d6222014-02-11 15:02:48 +00003832 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00003833 LOG_BAD_TU(TU);
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003834 return CXError_InvalidArguments;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003835 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003836
3837 // Reset the associated diagnostics.
3838 delete static_cast<CXDiagnosticSetImpl*>(TU->Diagnostics);
Craig Topper69186e72014-06-08 08:38:04 +00003839 TU->Diagnostics = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00003840
Dmitri Gribenko183436e2013-01-26 21:49:50 +00003841 CIndexer *CXXIdx = TU->CIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00003842 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing))
3843 setThreadBackgroundPriority();
3844
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00003845 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00003846 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ahmed Charlesb8984322014-03-07 20:03:18 +00003847
3848 std::unique_ptr<std::vector<ASTUnit::RemappedFile>> RemappedFiles(
3849 new std::vector<ASTUnit::RemappedFile>());
3850
Guy Benyei11169dd2012-12-18 14:30:41 +00003851 // Recover resources if we crash before exiting this function.
3852 llvm::CrashRecoveryContextCleanupRegistrar<
3853 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
Alp Toker9d85b182014-07-07 01:23:14 +00003854
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003855 for (auto &UF : unsaved_files) {
Rafael Espindolad87f8d72014-08-27 20:03:29 +00003856 std::unique_ptr<llvm::MemoryBuffer> MB =
Alp Toker9d85b182014-07-07 01:23:14 +00003857 llvm::MemoryBuffer::getMemBufferCopy(getContents(UF), UF.Filename);
Rafael Espindolad87f8d72014-08-27 20:03:29 +00003858 RemappedFiles->push_back(std::make_pair(UF.Filename, MB.release()));
Guy Benyei11169dd2012-12-18 14:30:41 +00003859 }
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003860
Adrian Prantlbb165fb2015-06-20 18:53:08 +00003861 if (!CXXUnit->Reparse(CXXIdx->getPCHContainerOperations(),
3862 *RemappedFiles.get()))
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003863 return CXError_Success;
3864 if (isASTReadError(CXXUnit))
3865 return CXError_ASTReadError;
3866 return CXError_Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003867}
3868
3869int clang_reparseTranslationUnit(CXTranslationUnit TU,
3870 unsigned num_unsaved_files,
3871 struct CXUnsavedFile *unsaved_files,
3872 unsigned options) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00003873 LOG_FUNC_SECTION {
3874 *Log << TU;
3875 }
3876
Alp Toker9d85b182014-07-07 01:23:14 +00003877 if (num_unsaved_files && !unsaved_files)
3878 return CXError_InvalidArguments;
3879
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003880 CXErrorCode result;
3881 auto ReparseTranslationUnitImpl = [=, &result]() {
3882 result = clang_reparseTranslationUnit_Impl(
3883 TU, llvm::makeArrayRef(unsaved_files, num_unsaved_files), options);
3884 };
Guy Benyei11169dd2012-12-18 14:30:41 +00003885
3886 if (getenv("LIBCLANG_NOTHREADS")) {
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003887 ReparseTranslationUnitImpl();
Alp Toker5c532982014-07-07 22:42:03 +00003888 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003889 }
3890
3891 llvm::CrashRecoveryContext CRC;
3892
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003893 if (!RunSafely(CRC, ReparseTranslationUnitImpl)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003894 fprintf(stderr, "libclang: crash detected during reparsing\n");
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00003895 cxtu::getASTUnit(TU)->setUnsafeToFree(true);
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003896 return CXError_Crashed;
Guy Benyei11169dd2012-12-18 14:30:41 +00003897 } else if (getenv("LIBCLANG_RESOURCE_USAGE"))
3898 PrintLibclangResourceUsage(TU);
3899
Alp Toker5c532982014-07-07 22:42:03 +00003900 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003901}
3902
3903
3904CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00003905 if (isNotUsableTU(CTUnit)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00003906 LOG_BAD_TU(CTUnit);
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00003907 return cxstring::createEmpty();
Dmitri Gribenko256454f2014-02-11 14:34:14 +00003908 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003909
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00003910 ASTUnit *CXXUnit = cxtu::getASTUnit(CTUnit);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00003911 return cxstring::createDup(CXXUnit->getOriginalSourceFileName());
Guy Benyei11169dd2012-12-18 14:30:41 +00003912}
3913
3914CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00003915 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00003916 LOG_BAD_TU(TU);
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00003917 return clang_getNullCursor();
Dmitri Gribenko256454f2014-02-11 14:34:14 +00003918 }
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00003919
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00003920 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00003921 return MakeCXCursor(CXXUnit->getASTContext().getTranslationUnitDecl(), TU);
3922}
3923
3924} // end: extern "C"
3925
3926//===----------------------------------------------------------------------===//
3927// CXFile Operations.
3928//===----------------------------------------------------------------------===//
3929
3930extern "C" {
3931CXString clang_getFileName(CXFile SFile) {
3932 if (!SFile)
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00003933 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00003934
3935 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00003936 return cxstring::createRef(FEnt->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00003937}
3938
3939time_t clang_getFileTime(CXFile SFile) {
3940 if (!SFile)
3941 return 0;
3942
3943 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
3944 return FEnt->getModificationTime();
3945}
3946
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00003947CXFile clang_getFile(CXTranslationUnit TU, const char *file_name) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00003948 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00003949 LOG_BAD_TU(TU);
Craig Topper69186e72014-06-08 08:38:04 +00003950 return nullptr;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00003951 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003952
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00003953 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00003954
3955 FileManager &FMgr = CXXUnit->getFileManager();
3956 return const_cast<FileEntry *>(FMgr.getFile(file_name));
3957}
3958
Dmitri Gribenko256454f2014-02-11 14:34:14 +00003959unsigned clang_isFileMultipleIncludeGuarded(CXTranslationUnit TU,
3960 CXFile file) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00003961 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00003962 LOG_BAD_TU(TU);
3963 return 0;
3964 }
3965
3966 if (!file)
Guy Benyei11169dd2012-12-18 14:30:41 +00003967 return 0;
3968
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00003969 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00003970 FileEntry *FEnt = static_cast<FileEntry *>(file);
3971 return CXXUnit->getPreprocessor().getHeaderSearchInfo()
3972 .isFileMultipleIncludeGuarded(FEnt);
3973}
3974
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00003975int clang_getFileUniqueID(CXFile file, CXFileUniqueID *outID) {
3976 if (!file || !outID)
3977 return 1;
3978
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00003979 FileEntry *FEnt = static_cast<FileEntry *>(file);
Rafael Espindolaf8f91b82013-08-01 21:42:11 +00003980 const llvm::sys::fs::UniqueID &ID = FEnt->getUniqueID();
3981 outID->data[0] = ID.getDevice();
3982 outID->data[1] = ID.getFile();
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00003983 outID->data[2] = FEnt->getModificationTime();
3984 return 0;
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00003985}
3986
Argyrios Kyrtzidisac3997e2014-08-16 00:26:19 +00003987int clang_File_isEqual(CXFile file1, CXFile file2) {
3988 if (file1 == file2)
3989 return true;
3990
3991 if (!file1 || !file2)
3992 return false;
3993
3994 FileEntry *FEnt1 = static_cast<FileEntry *>(file1);
3995 FileEntry *FEnt2 = static_cast<FileEntry *>(file2);
3996 return FEnt1->getUniqueID() == FEnt2->getUniqueID();
3997}
3998
Guy Benyei11169dd2012-12-18 14:30:41 +00003999} // end: extern "C"
4000
4001//===----------------------------------------------------------------------===//
4002// CXCursor Operations.
4003//===----------------------------------------------------------------------===//
4004
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004005static const Decl *getDeclFromExpr(const Stmt *E) {
4006 if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004007 return getDeclFromExpr(CE->getSubExpr());
4008
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004009 if (const DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004010 return RefExpr->getDecl();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004011 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004012 return ME->getMemberDecl();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004013 if (const ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004014 return RE->getDecl();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004015 if (const ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004016 if (PRE->isExplicitProperty())
4017 return PRE->getExplicitProperty();
4018 // It could be messaging both getter and setter as in:
4019 // ++myobj.myprop;
4020 // in which case prefer to associate the setter since it is less obvious
4021 // from inspecting the source that the setter is going to get called.
4022 if (PRE->isMessagingSetter())
4023 return PRE->getImplicitPropertySetter();
4024 return PRE->getImplicitPropertyGetter();
4025 }
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004026 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004027 return getDeclFromExpr(POE->getSyntacticForm());
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004028 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004029 if (Expr *Src = OVE->getSourceExpr())
4030 return getDeclFromExpr(Src);
4031
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004032 if (const CallExpr *CE = dyn_cast<CallExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004033 return getDeclFromExpr(CE->getCallee());
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004034 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004035 if (!CE->isElidable())
4036 return CE->getConstructor();
Richard Smith5179eb72016-06-28 19:03:57 +00004037 if (const CXXInheritedCtorInitExpr *CE =
4038 dyn_cast<CXXInheritedCtorInitExpr>(E))
4039 return CE->getConstructor();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004040 if (const ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004041 return OME->getMethodDecl();
4042
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004043 if (const ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004044 return PE->getProtocol();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004045 if (const SubstNonTypeTemplateParmPackExpr *NTTP
Guy Benyei11169dd2012-12-18 14:30:41 +00004046 = dyn_cast<SubstNonTypeTemplateParmPackExpr>(E))
4047 return NTTP->getParameterPack();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004048 if (const SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004049 if (isa<NonTypeTemplateParmDecl>(SizeOfPack->getPack()) ||
4050 isa<ParmVarDecl>(SizeOfPack->getPack()))
4051 return SizeOfPack->getPack();
Craig Topper69186e72014-06-08 08:38:04 +00004052
4053 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004054}
4055
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004056static SourceLocation getLocationFromExpr(const Expr *E) {
4057 if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004058 return getLocationFromExpr(CE->getSubExpr());
4059
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004060 if (const ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004061 return /*FIXME:*/Msg->getLeftLoc();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004062 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004063 return DRE->getLocation();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004064 if (const MemberExpr *Member = dyn_cast<MemberExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004065 return Member->getMemberLoc();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004066 if (const ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004067 return Ivar->getLocation();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004068 if (const SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004069 return SizeOfPack->getPackLoc();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004070 if (const ObjCPropertyRefExpr *PropRef = dyn_cast<ObjCPropertyRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004071 return PropRef->getLocation();
4072
4073 return E->getLocStart();
4074}
4075
4076extern "C" {
4077
4078unsigned clang_visitChildren(CXCursor parent,
4079 CXCursorVisitor visitor,
4080 CXClientData client_data) {
4081 CursorVisitor CursorVis(getCursorTU(parent), visitor, client_data,
4082 /*VisitPreprocessorLast=*/false);
4083 return CursorVis.VisitChildren(parent);
4084}
4085
4086#ifndef __has_feature
4087#define __has_feature(x) 0
4088#endif
4089#if __has_feature(blocks)
4090typedef enum CXChildVisitResult
4091 (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
4092
4093static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
4094 CXClientData client_data) {
4095 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
4096 return block(cursor, parent);
4097}
4098#else
4099// If we are compiled with a compiler that doesn't have native blocks support,
4100// define and call the block manually, so the
4101typedef struct _CXChildVisitResult
4102{
4103 void *isa;
4104 int flags;
4105 int reserved;
4106 enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor,
4107 CXCursor);
4108} *CXCursorVisitorBlock;
4109
4110static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
4111 CXClientData client_data) {
4112 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
4113 return block->invoke(block, cursor, parent);
4114}
4115#endif
4116
4117
4118unsigned clang_visitChildrenWithBlock(CXCursor parent,
4119 CXCursorVisitorBlock block) {
4120 return clang_visitChildren(parent, visitWithBlock, block);
4121}
4122
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004123static CXString getDeclSpelling(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004124 if (!D)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004125 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004126
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004127 const NamedDecl *ND = dyn_cast<NamedDecl>(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00004128 if (!ND) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004129 if (const ObjCPropertyImplDecl *PropImpl =
4130 dyn_cast<ObjCPropertyImplDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00004131 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004132 return cxstring::createDup(Property->getIdentifier()->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004133
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004134 if (const ImportDecl *ImportD = dyn_cast<ImportDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00004135 if (Module *Mod = ImportD->getImportedModule())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004136 return cxstring::createDup(Mod->getFullModuleName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004137
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004138 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004139 }
4140
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004141 if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004142 return cxstring::createDup(OMD->getSelector().getAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004143
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004144 if (const ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
Guy Benyei11169dd2012-12-18 14:30:41 +00004145 // No, this isn't the same as the code below. getIdentifier() is non-virtual
4146 // and returns different names. NamedDecl returns the class name and
4147 // ObjCCategoryImplDecl returns the category name.
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004148 return cxstring::createRef(CIMP->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004149
4150 if (isa<UsingDirectiveDecl>(D))
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004151 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004152
4153 SmallString<1024> S;
4154 llvm::raw_svector_ostream os(S);
4155 ND->printName(os);
4156
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004157 return cxstring::createDup(os.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00004158}
4159
4160CXString clang_getCursorSpelling(CXCursor C) {
4161 if (clang_isTranslationUnit(C.kind))
Dmitri Gribenko2c173b42013-01-11 19:28:44 +00004162 return clang_getTranslationUnitSpelling(getCursorTU(C));
Guy Benyei11169dd2012-12-18 14:30:41 +00004163
4164 if (clang_isReference(C.kind)) {
4165 switch (C.kind) {
4166 case CXCursor_ObjCSuperClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004167 const ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004168 return cxstring::createRef(Super->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004169 }
4170 case CXCursor_ObjCClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004171 const ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004172 return cxstring::createRef(Class->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004173 }
4174 case CXCursor_ObjCProtocolRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004175 const ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004176 assert(OID && "getCursorSpelling(): Missing protocol decl");
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004177 return cxstring::createRef(OID->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004178 }
4179 case CXCursor_CXXBaseSpecifier: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004180 const CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004181 return cxstring::createDup(B->getType().getAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004182 }
4183 case CXCursor_TypeRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004184 const TypeDecl *Type = getCursorTypeRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004185 assert(Type && "Missing type decl");
4186
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004187 return cxstring::createDup(getCursorContext(C).getTypeDeclType(Type).
Guy Benyei11169dd2012-12-18 14:30:41 +00004188 getAsString());
4189 }
4190 case CXCursor_TemplateRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004191 const TemplateDecl *Template = getCursorTemplateRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004192 assert(Template && "Missing template decl");
4193
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004194 return cxstring::createDup(Template->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004195 }
4196
4197 case CXCursor_NamespaceRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004198 const NamedDecl *NS = getCursorNamespaceRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004199 assert(NS && "Missing namespace decl");
4200
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004201 return cxstring::createDup(NS->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004202 }
4203
4204 case CXCursor_MemberRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004205 const FieldDecl *Field = getCursorMemberRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004206 assert(Field && "Missing member decl");
4207
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004208 return cxstring::createDup(Field->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004209 }
4210
4211 case CXCursor_LabelRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004212 const LabelStmt *Label = getCursorLabelRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004213 assert(Label && "Missing label");
4214
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004215 return cxstring::createRef(Label->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004216 }
4217
4218 case CXCursor_OverloadedDeclRef: {
4219 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004220 if (const Decl *D = Storage.dyn_cast<const Decl *>()) {
4221 if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004222 return cxstring::createDup(ND->getNameAsString());
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004223 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004224 }
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004225 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004226 return cxstring::createDup(E->getName().getAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004227 OverloadedTemplateStorage *Ovl
4228 = Storage.get<OverloadedTemplateStorage*>();
4229 if (Ovl->size() == 0)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004230 return cxstring::createEmpty();
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004231 return cxstring::createDup((*Ovl->begin())->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004232 }
4233
4234 case CXCursor_VariableRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004235 const VarDecl *Var = getCursorVariableRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004236 assert(Var && "Missing variable decl");
4237
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004238 return cxstring::createDup(Var->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004239 }
4240
4241 default:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004242 return cxstring::createRef("<not implemented>");
Guy Benyei11169dd2012-12-18 14:30:41 +00004243 }
4244 }
4245
4246 if (clang_isExpression(C.kind)) {
Argyrios Kyrtzidis3227d862014-03-03 19:40:52 +00004247 const Expr *E = getCursorExpr(C);
4248
4249 if (C.kind == CXCursor_ObjCStringLiteral ||
4250 C.kind == CXCursor_StringLiteral) {
4251 const StringLiteral *SLit;
4252 if (const ObjCStringLiteral *OSL = dyn_cast<ObjCStringLiteral>(E)) {
4253 SLit = OSL->getString();
4254 } else {
4255 SLit = cast<StringLiteral>(E);
4256 }
4257 SmallString<256> Buf;
4258 llvm::raw_svector_ostream OS(Buf);
4259 SLit->outputString(OS);
4260 return cxstring::createDup(OS.str());
4261 }
4262
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004263 const Decl *D = getDeclFromExpr(getCursorExpr(C));
Guy Benyei11169dd2012-12-18 14:30:41 +00004264 if (D)
4265 return getDeclSpelling(D);
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004266 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004267 }
4268
4269 if (clang_isStatement(C.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004270 const Stmt *S = getCursorStmt(C);
4271 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004272 return cxstring::createRef(Label->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004273
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004274 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004275 }
4276
4277 if (C.kind == CXCursor_MacroExpansion)
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004278 return cxstring::createRef(getCursorMacroExpansion(C).getName()
Guy Benyei11169dd2012-12-18 14:30:41 +00004279 ->getNameStart());
4280
4281 if (C.kind == CXCursor_MacroDefinition)
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004282 return cxstring::createRef(getCursorMacroDefinition(C)->getName()
Guy Benyei11169dd2012-12-18 14:30:41 +00004283 ->getNameStart());
4284
4285 if (C.kind == CXCursor_InclusionDirective)
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004286 return cxstring::createDup(getCursorInclusionDirective(C)->getFileName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004287
4288 if (clang_isDeclaration(C.kind))
4289 return getDeclSpelling(getCursorDecl(C));
4290
4291 if (C.kind == CXCursor_AnnotateAttr) {
Dmitri Gribenkoe4baea62013-01-26 18:08:08 +00004292 const AnnotateAttr *AA = cast<AnnotateAttr>(cxcursor::getCursorAttr(C));
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004293 return cxstring::createDup(AA->getAnnotation());
Guy Benyei11169dd2012-12-18 14:30:41 +00004294 }
4295
4296 if (C.kind == CXCursor_AsmLabelAttr) {
Dmitri Gribenkoe4baea62013-01-26 18:08:08 +00004297 const AsmLabelAttr *AA = cast<AsmLabelAttr>(cxcursor::getCursorAttr(C));
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004298 return cxstring::createDup(AA->getLabel());
Guy Benyei11169dd2012-12-18 14:30:41 +00004299 }
4300
Argyrios Kyrtzidis16834f12013-09-25 00:14:38 +00004301 if (C.kind == CXCursor_PackedAttr) {
4302 return cxstring::createRef("packed");
4303 }
4304
Saleem Abdulrasool79c69712015-09-05 18:53:43 +00004305 if (C.kind == CXCursor_VisibilityAttr) {
4306 const VisibilityAttr *AA = cast<VisibilityAttr>(cxcursor::getCursorAttr(C));
4307 switch (AA->getVisibility()) {
4308 case VisibilityAttr::VisibilityType::Default:
4309 return cxstring::createRef("default");
4310 case VisibilityAttr::VisibilityType::Hidden:
4311 return cxstring::createRef("hidden");
4312 case VisibilityAttr::VisibilityType::Protected:
4313 return cxstring::createRef("protected");
4314 }
4315 llvm_unreachable("unknown visibility type");
4316 }
4317
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004318 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004319}
4320
4321CXSourceRange clang_Cursor_getSpellingNameRange(CXCursor C,
4322 unsigned pieceIndex,
4323 unsigned options) {
4324 if (clang_Cursor_isNull(C))
4325 return clang_getNullRange();
4326
4327 ASTContext &Ctx = getCursorContext(C);
4328
4329 if (clang_isStatement(C.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004330 const Stmt *S = getCursorStmt(C);
4331 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004332 if (pieceIndex > 0)
4333 return clang_getNullRange();
4334 return cxloc::translateSourceRange(Ctx, Label->getIdentLoc());
4335 }
4336
4337 return clang_getNullRange();
4338 }
4339
4340 if (C.kind == CXCursor_ObjCMessageExpr) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004341 if (const ObjCMessageExpr *
Guy Benyei11169dd2012-12-18 14:30:41 +00004342 ME = dyn_cast_or_null<ObjCMessageExpr>(getCursorExpr(C))) {
4343 if (pieceIndex >= ME->getNumSelectorLocs())
4344 return clang_getNullRange();
4345 return cxloc::translateSourceRange(Ctx, ME->getSelectorLoc(pieceIndex));
4346 }
4347 }
4348
4349 if (C.kind == CXCursor_ObjCInstanceMethodDecl ||
4350 C.kind == CXCursor_ObjCClassMethodDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004351 if (const ObjCMethodDecl *
Guy Benyei11169dd2012-12-18 14:30:41 +00004352 MD = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(C))) {
4353 if (pieceIndex >= MD->getNumSelectorLocs())
4354 return clang_getNullRange();
4355 return cxloc::translateSourceRange(Ctx, MD->getSelectorLoc(pieceIndex));
4356 }
4357 }
4358
4359 if (C.kind == CXCursor_ObjCCategoryDecl ||
4360 C.kind == CXCursor_ObjCCategoryImplDecl) {
4361 if (pieceIndex > 0)
4362 return clang_getNullRange();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004363 if (const ObjCCategoryDecl *
Guy Benyei11169dd2012-12-18 14:30:41 +00004364 CD = dyn_cast_or_null<ObjCCategoryDecl>(getCursorDecl(C)))
4365 return cxloc::translateSourceRange(Ctx, CD->getCategoryNameLoc());
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004366 if (const ObjCCategoryImplDecl *
Guy Benyei11169dd2012-12-18 14:30:41 +00004367 CID = dyn_cast_or_null<ObjCCategoryImplDecl>(getCursorDecl(C)))
4368 return cxloc::translateSourceRange(Ctx, CID->getCategoryNameLoc());
4369 }
4370
4371 if (C.kind == CXCursor_ModuleImportDecl) {
4372 if (pieceIndex > 0)
4373 return clang_getNullRange();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004374 if (const ImportDecl *ImportD =
4375 dyn_cast_or_null<ImportDecl>(getCursorDecl(C))) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004376 ArrayRef<SourceLocation> Locs = ImportD->getIdentifierLocs();
4377 if (!Locs.empty())
4378 return cxloc::translateSourceRange(Ctx,
4379 SourceRange(Locs.front(), Locs.back()));
4380 }
4381 return clang_getNullRange();
4382 }
4383
Argyrios Kyrtzidisa2a1e532014-08-26 20:23:26 +00004384 if (C.kind == CXCursor_CXXMethod || C.kind == CXCursor_Destructor ||
4385 C.kind == CXCursor_ConversionFunction) {
4386 if (pieceIndex > 0)
4387 return clang_getNullRange();
4388 if (const FunctionDecl *FD =
4389 dyn_cast_or_null<FunctionDecl>(getCursorDecl(C))) {
4390 DeclarationNameInfo FunctionName = FD->getNameInfo();
4391 return cxloc::translateSourceRange(Ctx, FunctionName.getSourceRange());
4392 }
4393 return clang_getNullRange();
4394 }
4395
Guy Benyei11169dd2012-12-18 14:30:41 +00004396 // FIXME: A CXCursor_InclusionDirective should give the location of the
4397 // filename, but we don't keep track of this.
4398
4399 // FIXME: A CXCursor_AnnotateAttr should give the location of the annotation
4400 // but we don't keep track of this.
4401
4402 // FIXME: A CXCursor_AsmLabelAttr should give the location of the label
4403 // but we don't keep track of this.
4404
4405 // Default handling, give the location of the cursor.
4406
4407 if (pieceIndex > 0)
4408 return clang_getNullRange();
4409
4410 CXSourceLocation CXLoc = clang_getCursorLocation(C);
4411 SourceLocation Loc = cxloc::translateSourceLocation(CXLoc);
4412 return cxloc::translateSourceRange(Ctx, Loc);
4413}
4414
Eli Bendersky44a206f2014-07-31 18:04:56 +00004415CXString clang_Cursor_getMangling(CXCursor C) {
4416 if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
4417 return cxstring::createEmpty();
4418
Eli Bendersky44a206f2014-07-31 18:04:56 +00004419 // Mangling only works for functions and variables.
Eli Bendersky79759592014-08-01 15:01:10 +00004420 const Decl *D = getCursorDecl(C);
Eli Bendersky44a206f2014-07-31 18:04:56 +00004421 if (!D || !(isa<FunctionDecl>(D) || isa<VarDecl>(D)))
4422 return cxstring::createEmpty();
4423
Argyrios Kyrtzidisca741ce2016-02-14 22:30:14 +00004424 ASTContext &Ctx = D->getASTContext();
4425 index::CodegenNameGenerator CGNameGen(Ctx);
4426 return cxstring::createDup(CGNameGen.getName(D));
Eli Bendersky44a206f2014-07-31 18:04:56 +00004427}
4428
Saleem Abdulrasool60034432015-11-12 03:57:22 +00004429CXStringSet *clang_Cursor_getCXXManglings(CXCursor C) {
4430 if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
4431 return nullptr;
4432
4433 const Decl *D = getCursorDecl(C);
4434 if (!(isa<CXXRecordDecl>(D) || isa<CXXMethodDecl>(D)))
4435 return nullptr;
4436
Argyrios Kyrtzidisca741ce2016-02-14 22:30:14 +00004437 ASTContext &Ctx = D->getASTContext();
4438 index::CodegenNameGenerator CGNameGen(Ctx);
4439 std::vector<std::string> Manglings = CGNameGen.getAllManglings(D);
Saleem Abdulrasool60034432015-11-12 03:57:22 +00004440 return cxstring::createSet(Manglings);
4441}
4442
Guy Benyei11169dd2012-12-18 14:30:41 +00004443CXString clang_getCursorDisplayName(CXCursor C) {
4444 if (!clang_isDeclaration(C.kind))
4445 return clang_getCursorSpelling(C);
4446
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004447 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00004448 if (!D)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004449 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004450
4451 PrintingPolicy Policy = getCursorContext(C).getPrintingPolicy();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004452 if (const FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00004453 D = FunTmpl->getTemplatedDecl();
4454
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004455 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004456 SmallString<64> Str;
4457 llvm::raw_svector_ostream OS(Str);
4458 OS << *Function;
4459 if (Function->getPrimaryTemplate())
4460 OS << "<>";
4461 OS << "(";
4462 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
4463 if (I)
4464 OS << ", ";
4465 OS << Function->getParamDecl(I)->getType().getAsString(Policy);
4466 }
4467
4468 if (Function->isVariadic()) {
4469 if (Function->getNumParams())
4470 OS << ", ";
4471 OS << "...";
4472 }
4473 OS << ")";
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004474 return cxstring::createDup(OS.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00004475 }
4476
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004477 if (const ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004478 SmallString<64> Str;
4479 llvm::raw_svector_ostream OS(Str);
4480 OS << *ClassTemplate;
4481 OS << "<";
4482 TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
4483 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
4484 if (I)
4485 OS << ", ";
4486
4487 NamedDecl *Param = Params->getParam(I);
4488 if (Param->getIdentifier()) {
4489 OS << Param->getIdentifier()->getName();
4490 continue;
4491 }
4492
4493 // There is no parameter name, which makes this tricky. Try to come up
4494 // with something useful that isn't too long.
4495 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
4496 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
4497 else if (NonTypeTemplateParmDecl *NTTP
4498 = dyn_cast<NonTypeTemplateParmDecl>(Param))
4499 OS << NTTP->getType().getAsString(Policy);
4500 else
4501 OS << "template<...> class";
4502 }
4503
4504 OS << ">";
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004505 return cxstring::createDup(OS.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00004506 }
4507
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004508 if (const ClassTemplateSpecializationDecl *ClassSpec
Guy Benyei11169dd2012-12-18 14:30:41 +00004509 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
4510 // If the type was explicitly written, use that.
4511 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004512 return cxstring::createDup(TSInfo->getType().getAsString(Policy));
Guy Benyei11169dd2012-12-18 14:30:41 +00004513
Benjamin Kramer9170e912013-02-22 15:46:01 +00004514 SmallString<128> Str;
Guy Benyei11169dd2012-12-18 14:30:41 +00004515 llvm::raw_svector_ostream OS(Str);
4516 OS << *ClassSpec;
David Majnemer6fbeee32016-07-07 04:43:07 +00004517 TemplateSpecializationType::PrintTemplateArgumentList(
4518 OS, ClassSpec->getTemplateArgs().asArray(), Policy);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004519 return cxstring::createDup(OS.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00004520 }
4521
4522 return clang_getCursorSpelling(C);
4523}
4524
4525CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
4526 switch (Kind) {
4527 case CXCursor_FunctionDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004528 return cxstring::createRef("FunctionDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004529 case CXCursor_TypedefDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004530 return cxstring::createRef("TypedefDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004531 case CXCursor_EnumDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004532 return cxstring::createRef("EnumDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004533 case CXCursor_EnumConstantDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004534 return cxstring::createRef("EnumConstantDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004535 case CXCursor_StructDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004536 return cxstring::createRef("StructDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004537 case CXCursor_UnionDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004538 return cxstring::createRef("UnionDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004539 case CXCursor_ClassDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004540 return cxstring::createRef("ClassDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004541 case CXCursor_FieldDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004542 return cxstring::createRef("FieldDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004543 case CXCursor_VarDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004544 return cxstring::createRef("VarDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004545 case CXCursor_ParmDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004546 return cxstring::createRef("ParmDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004547 case CXCursor_ObjCInterfaceDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004548 return cxstring::createRef("ObjCInterfaceDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004549 case CXCursor_ObjCCategoryDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004550 return cxstring::createRef("ObjCCategoryDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004551 case CXCursor_ObjCProtocolDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004552 return cxstring::createRef("ObjCProtocolDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004553 case CXCursor_ObjCPropertyDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004554 return cxstring::createRef("ObjCPropertyDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004555 case CXCursor_ObjCIvarDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004556 return cxstring::createRef("ObjCIvarDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004557 case CXCursor_ObjCInstanceMethodDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004558 return cxstring::createRef("ObjCInstanceMethodDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004559 case CXCursor_ObjCClassMethodDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004560 return cxstring::createRef("ObjCClassMethodDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004561 case CXCursor_ObjCImplementationDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004562 return cxstring::createRef("ObjCImplementationDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004563 case CXCursor_ObjCCategoryImplDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004564 return cxstring::createRef("ObjCCategoryImplDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004565 case CXCursor_CXXMethod:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004566 return cxstring::createRef("CXXMethod");
Guy Benyei11169dd2012-12-18 14:30:41 +00004567 case CXCursor_UnexposedDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004568 return cxstring::createRef("UnexposedDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004569 case CXCursor_ObjCSuperClassRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004570 return cxstring::createRef("ObjCSuperClassRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00004571 case CXCursor_ObjCProtocolRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004572 return cxstring::createRef("ObjCProtocolRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00004573 case CXCursor_ObjCClassRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004574 return cxstring::createRef("ObjCClassRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00004575 case CXCursor_TypeRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004576 return cxstring::createRef("TypeRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00004577 case CXCursor_TemplateRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004578 return cxstring::createRef("TemplateRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00004579 case CXCursor_NamespaceRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004580 return cxstring::createRef("NamespaceRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00004581 case CXCursor_MemberRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004582 return cxstring::createRef("MemberRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00004583 case CXCursor_LabelRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004584 return cxstring::createRef("LabelRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00004585 case CXCursor_OverloadedDeclRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004586 return cxstring::createRef("OverloadedDeclRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00004587 case CXCursor_VariableRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004588 return cxstring::createRef("VariableRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00004589 case CXCursor_IntegerLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004590 return cxstring::createRef("IntegerLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00004591 case CXCursor_FloatingLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004592 return cxstring::createRef("FloatingLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00004593 case CXCursor_ImaginaryLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004594 return cxstring::createRef("ImaginaryLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00004595 case CXCursor_StringLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004596 return cxstring::createRef("StringLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00004597 case CXCursor_CharacterLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004598 return cxstring::createRef("CharacterLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00004599 case CXCursor_ParenExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004600 return cxstring::createRef("ParenExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004601 case CXCursor_UnaryOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004602 return cxstring::createRef("UnaryOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00004603 case CXCursor_ArraySubscriptExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004604 return cxstring::createRef("ArraySubscriptExpr");
Alexey Bataev1a3320e2015-08-25 14:24:04 +00004605 case CXCursor_OMPArraySectionExpr:
4606 return cxstring::createRef("OMPArraySectionExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004607 case CXCursor_BinaryOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004608 return cxstring::createRef("BinaryOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00004609 case CXCursor_CompoundAssignOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004610 return cxstring::createRef("CompoundAssignOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00004611 case CXCursor_ConditionalOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004612 return cxstring::createRef("ConditionalOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00004613 case CXCursor_CStyleCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004614 return cxstring::createRef("CStyleCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004615 case CXCursor_CompoundLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004616 return cxstring::createRef("CompoundLiteralExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004617 case CXCursor_InitListExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004618 return cxstring::createRef("InitListExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004619 case CXCursor_AddrLabelExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004620 return cxstring::createRef("AddrLabelExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004621 case CXCursor_StmtExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004622 return cxstring::createRef("StmtExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004623 case CXCursor_GenericSelectionExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004624 return cxstring::createRef("GenericSelectionExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004625 case CXCursor_GNUNullExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004626 return cxstring::createRef("GNUNullExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004627 case CXCursor_CXXStaticCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004628 return cxstring::createRef("CXXStaticCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004629 case CXCursor_CXXDynamicCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004630 return cxstring::createRef("CXXDynamicCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004631 case CXCursor_CXXReinterpretCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004632 return cxstring::createRef("CXXReinterpretCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004633 case CXCursor_CXXConstCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004634 return cxstring::createRef("CXXConstCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004635 case CXCursor_CXXFunctionalCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004636 return cxstring::createRef("CXXFunctionalCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004637 case CXCursor_CXXTypeidExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004638 return cxstring::createRef("CXXTypeidExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004639 case CXCursor_CXXBoolLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004640 return cxstring::createRef("CXXBoolLiteralExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004641 case CXCursor_CXXNullPtrLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004642 return cxstring::createRef("CXXNullPtrLiteralExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004643 case CXCursor_CXXThisExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004644 return cxstring::createRef("CXXThisExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004645 case CXCursor_CXXThrowExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004646 return cxstring::createRef("CXXThrowExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004647 case CXCursor_CXXNewExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004648 return cxstring::createRef("CXXNewExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004649 case CXCursor_CXXDeleteExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004650 return cxstring::createRef("CXXDeleteExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004651 case CXCursor_UnaryExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004652 return cxstring::createRef("UnaryExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004653 case CXCursor_ObjCStringLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004654 return cxstring::createRef("ObjCStringLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00004655 case CXCursor_ObjCBoolLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004656 return cxstring::createRef("ObjCBoolLiteralExpr");
Erik Pilkington29099de2016-07-16 00:35:23 +00004657 case CXCursor_ObjCAvailabilityCheckExpr:
4658 return cxstring::createRef("ObjCAvailabilityCheckExpr");
Argyrios Kyrtzidisc2233be2013-04-23 17:57:17 +00004659 case CXCursor_ObjCSelfExpr:
4660 return cxstring::createRef("ObjCSelfExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004661 case CXCursor_ObjCEncodeExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004662 return cxstring::createRef("ObjCEncodeExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004663 case CXCursor_ObjCSelectorExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004664 return cxstring::createRef("ObjCSelectorExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004665 case CXCursor_ObjCProtocolExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004666 return cxstring::createRef("ObjCProtocolExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004667 case CXCursor_ObjCBridgedCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004668 return cxstring::createRef("ObjCBridgedCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004669 case CXCursor_BlockExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004670 return cxstring::createRef("BlockExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004671 case CXCursor_PackExpansionExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004672 return cxstring::createRef("PackExpansionExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004673 case CXCursor_SizeOfPackExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004674 return cxstring::createRef("SizeOfPackExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004675 case CXCursor_LambdaExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004676 return cxstring::createRef("LambdaExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004677 case CXCursor_UnexposedExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004678 return cxstring::createRef("UnexposedExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004679 case CXCursor_DeclRefExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004680 return cxstring::createRef("DeclRefExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004681 case CXCursor_MemberRefExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004682 return cxstring::createRef("MemberRefExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004683 case CXCursor_CallExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004684 return cxstring::createRef("CallExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004685 case CXCursor_ObjCMessageExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004686 return cxstring::createRef("ObjCMessageExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004687 case CXCursor_UnexposedStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004688 return cxstring::createRef("UnexposedStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004689 case CXCursor_DeclStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004690 return cxstring::createRef("DeclStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004691 case CXCursor_LabelStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004692 return cxstring::createRef("LabelStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004693 case CXCursor_CompoundStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004694 return cxstring::createRef("CompoundStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004695 case CXCursor_CaseStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004696 return cxstring::createRef("CaseStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004697 case CXCursor_DefaultStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004698 return cxstring::createRef("DefaultStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004699 case CXCursor_IfStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004700 return cxstring::createRef("IfStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004701 case CXCursor_SwitchStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004702 return cxstring::createRef("SwitchStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004703 case CXCursor_WhileStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004704 return cxstring::createRef("WhileStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004705 case CXCursor_DoStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004706 return cxstring::createRef("DoStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004707 case CXCursor_ForStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004708 return cxstring::createRef("ForStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004709 case CXCursor_GotoStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004710 return cxstring::createRef("GotoStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004711 case CXCursor_IndirectGotoStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004712 return cxstring::createRef("IndirectGotoStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004713 case CXCursor_ContinueStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004714 return cxstring::createRef("ContinueStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004715 case CXCursor_BreakStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004716 return cxstring::createRef("BreakStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004717 case CXCursor_ReturnStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004718 return cxstring::createRef("ReturnStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004719 case CXCursor_GCCAsmStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004720 return cxstring::createRef("GCCAsmStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004721 case CXCursor_MSAsmStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004722 return cxstring::createRef("MSAsmStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004723 case CXCursor_ObjCAtTryStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004724 return cxstring::createRef("ObjCAtTryStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004725 case CXCursor_ObjCAtCatchStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004726 return cxstring::createRef("ObjCAtCatchStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004727 case CXCursor_ObjCAtFinallyStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004728 return cxstring::createRef("ObjCAtFinallyStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004729 case CXCursor_ObjCAtThrowStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004730 return cxstring::createRef("ObjCAtThrowStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004731 case CXCursor_ObjCAtSynchronizedStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004732 return cxstring::createRef("ObjCAtSynchronizedStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004733 case CXCursor_ObjCAutoreleasePoolStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004734 return cxstring::createRef("ObjCAutoreleasePoolStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004735 case CXCursor_ObjCForCollectionStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004736 return cxstring::createRef("ObjCForCollectionStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004737 case CXCursor_CXXCatchStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004738 return cxstring::createRef("CXXCatchStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004739 case CXCursor_CXXTryStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004740 return cxstring::createRef("CXXTryStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004741 case CXCursor_CXXForRangeStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004742 return cxstring::createRef("CXXForRangeStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004743 case CXCursor_SEHTryStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004744 return cxstring::createRef("SEHTryStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004745 case CXCursor_SEHExceptStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004746 return cxstring::createRef("SEHExceptStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004747 case CXCursor_SEHFinallyStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004748 return cxstring::createRef("SEHFinallyStmt");
Nico Weber9b982072014-07-07 00:12:30 +00004749 case CXCursor_SEHLeaveStmt:
4750 return cxstring::createRef("SEHLeaveStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004751 case CXCursor_NullStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004752 return cxstring::createRef("NullStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004753 case CXCursor_InvalidFile:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004754 return cxstring::createRef("InvalidFile");
Guy Benyei11169dd2012-12-18 14:30:41 +00004755 case CXCursor_InvalidCode:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004756 return cxstring::createRef("InvalidCode");
Guy Benyei11169dd2012-12-18 14:30:41 +00004757 case CXCursor_NoDeclFound:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004758 return cxstring::createRef("NoDeclFound");
Guy Benyei11169dd2012-12-18 14:30:41 +00004759 case CXCursor_NotImplemented:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004760 return cxstring::createRef("NotImplemented");
Guy Benyei11169dd2012-12-18 14:30:41 +00004761 case CXCursor_TranslationUnit:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004762 return cxstring::createRef("TranslationUnit");
Guy Benyei11169dd2012-12-18 14:30:41 +00004763 case CXCursor_UnexposedAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004764 return cxstring::createRef("UnexposedAttr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004765 case CXCursor_IBActionAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004766 return cxstring::createRef("attribute(ibaction)");
Guy Benyei11169dd2012-12-18 14:30:41 +00004767 case CXCursor_IBOutletAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004768 return cxstring::createRef("attribute(iboutlet)");
Guy Benyei11169dd2012-12-18 14:30:41 +00004769 case CXCursor_IBOutletCollectionAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004770 return cxstring::createRef("attribute(iboutletcollection)");
Guy Benyei11169dd2012-12-18 14:30:41 +00004771 case CXCursor_CXXFinalAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004772 return cxstring::createRef("attribute(final)");
Guy Benyei11169dd2012-12-18 14:30:41 +00004773 case CXCursor_CXXOverrideAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004774 return cxstring::createRef("attribute(override)");
Guy Benyei11169dd2012-12-18 14:30:41 +00004775 case CXCursor_AnnotateAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004776 return cxstring::createRef("attribute(annotate)");
Guy Benyei11169dd2012-12-18 14:30:41 +00004777 case CXCursor_AsmLabelAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004778 return cxstring::createRef("asm label");
Argyrios Kyrtzidis16834f12013-09-25 00:14:38 +00004779 case CXCursor_PackedAttr:
4780 return cxstring::createRef("attribute(packed)");
Joey Gouly81228382014-05-01 15:41:58 +00004781 case CXCursor_PureAttr:
4782 return cxstring::createRef("attribute(pure)");
4783 case CXCursor_ConstAttr:
4784 return cxstring::createRef("attribute(const)");
4785 case CXCursor_NoDuplicateAttr:
4786 return cxstring::createRef("attribute(noduplicate)");
Eli Bendersky2581e662014-05-28 19:29:58 +00004787 case CXCursor_CUDAConstantAttr:
4788 return cxstring::createRef("attribute(constant)");
4789 case CXCursor_CUDADeviceAttr:
4790 return cxstring::createRef("attribute(device)");
4791 case CXCursor_CUDAGlobalAttr:
4792 return cxstring::createRef("attribute(global)");
4793 case CXCursor_CUDAHostAttr:
4794 return cxstring::createRef("attribute(host)");
Eli Bendersky9b071472014-08-08 14:59:00 +00004795 case CXCursor_CUDASharedAttr:
4796 return cxstring::createRef("attribute(shared)");
Saleem Abdulrasool79c69712015-09-05 18:53:43 +00004797 case CXCursor_VisibilityAttr:
4798 return cxstring::createRef("attribute(visibility)");
Saleem Abdulrasool8aa0b802015-12-10 18:45:18 +00004799 case CXCursor_DLLExport:
4800 return cxstring::createRef("attribute(dllexport)");
4801 case CXCursor_DLLImport:
4802 return cxstring::createRef("attribute(dllimport)");
Guy Benyei11169dd2012-12-18 14:30:41 +00004803 case CXCursor_PreprocessingDirective:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004804 return cxstring::createRef("preprocessing directive");
Guy Benyei11169dd2012-12-18 14:30:41 +00004805 case CXCursor_MacroDefinition:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004806 return cxstring::createRef("macro definition");
Guy Benyei11169dd2012-12-18 14:30:41 +00004807 case CXCursor_MacroExpansion:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004808 return cxstring::createRef("macro expansion");
Guy Benyei11169dd2012-12-18 14:30:41 +00004809 case CXCursor_InclusionDirective:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004810 return cxstring::createRef("inclusion directive");
Guy Benyei11169dd2012-12-18 14:30:41 +00004811 case CXCursor_Namespace:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004812 return cxstring::createRef("Namespace");
Guy Benyei11169dd2012-12-18 14:30:41 +00004813 case CXCursor_LinkageSpec:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004814 return cxstring::createRef("LinkageSpec");
Guy Benyei11169dd2012-12-18 14:30:41 +00004815 case CXCursor_CXXBaseSpecifier:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004816 return cxstring::createRef("C++ base class specifier");
Guy Benyei11169dd2012-12-18 14:30:41 +00004817 case CXCursor_Constructor:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004818 return cxstring::createRef("CXXConstructor");
Guy Benyei11169dd2012-12-18 14:30:41 +00004819 case CXCursor_Destructor:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004820 return cxstring::createRef("CXXDestructor");
Guy Benyei11169dd2012-12-18 14:30:41 +00004821 case CXCursor_ConversionFunction:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004822 return cxstring::createRef("CXXConversion");
Guy Benyei11169dd2012-12-18 14:30:41 +00004823 case CXCursor_TemplateTypeParameter:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004824 return cxstring::createRef("TemplateTypeParameter");
Guy Benyei11169dd2012-12-18 14:30:41 +00004825 case CXCursor_NonTypeTemplateParameter:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004826 return cxstring::createRef("NonTypeTemplateParameter");
Guy Benyei11169dd2012-12-18 14:30:41 +00004827 case CXCursor_TemplateTemplateParameter:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004828 return cxstring::createRef("TemplateTemplateParameter");
Guy Benyei11169dd2012-12-18 14:30:41 +00004829 case CXCursor_FunctionTemplate:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004830 return cxstring::createRef("FunctionTemplate");
Guy Benyei11169dd2012-12-18 14:30:41 +00004831 case CXCursor_ClassTemplate:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004832 return cxstring::createRef("ClassTemplate");
Guy Benyei11169dd2012-12-18 14:30:41 +00004833 case CXCursor_ClassTemplatePartialSpecialization:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004834 return cxstring::createRef("ClassTemplatePartialSpecialization");
Guy Benyei11169dd2012-12-18 14:30:41 +00004835 case CXCursor_NamespaceAlias:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004836 return cxstring::createRef("NamespaceAlias");
Guy Benyei11169dd2012-12-18 14:30:41 +00004837 case CXCursor_UsingDirective:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004838 return cxstring::createRef("UsingDirective");
Guy Benyei11169dd2012-12-18 14:30:41 +00004839 case CXCursor_UsingDeclaration:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004840 return cxstring::createRef("UsingDeclaration");
Guy Benyei11169dd2012-12-18 14:30:41 +00004841 case CXCursor_TypeAliasDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004842 return cxstring::createRef("TypeAliasDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004843 case CXCursor_ObjCSynthesizeDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004844 return cxstring::createRef("ObjCSynthesizeDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004845 case CXCursor_ObjCDynamicDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004846 return cxstring::createRef("ObjCDynamicDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004847 case CXCursor_CXXAccessSpecifier:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004848 return cxstring::createRef("CXXAccessSpecifier");
Guy Benyei11169dd2012-12-18 14:30:41 +00004849 case CXCursor_ModuleImportDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004850 return cxstring::createRef("ModuleImport");
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004851 case CXCursor_OMPParallelDirective:
Alexey Bataev1b59ab52014-02-27 08:29:12 +00004852 return cxstring::createRef("OMPParallelDirective");
4853 case CXCursor_OMPSimdDirective:
4854 return cxstring::createRef("OMPSimdDirective");
Alexey Bataevf29276e2014-06-18 04:14:57 +00004855 case CXCursor_OMPForDirective:
4856 return cxstring::createRef("OMPForDirective");
Alexander Musmanf82886e2014-09-18 05:12:34 +00004857 case CXCursor_OMPForSimdDirective:
4858 return cxstring::createRef("OMPForSimdDirective");
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004859 case CXCursor_OMPSectionsDirective:
4860 return cxstring::createRef("OMPSectionsDirective");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004861 case CXCursor_OMPSectionDirective:
4862 return cxstring::createRef("OMPSectionDirective");
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00004863 case CXCursor_OMPSingleDirective:
4864 return cxstring::createRef("OMPSingleDirective");
Alexander Musman80c22892014-07-17 08:54:58 +00004865 case CXCursor_OMPMasterDirective:
4866 return cxstring::createRef("OMPMasterDirective");
Alexander Musmand9ed09f2014-07-21 09:42:05 +00004867 case CXCursor_OMPCriticalDirective:
4868 return cxstring::createRef("OMPCriticalDirective");
Alexey Bataev4acb8592014-07-07 13:01:15 +00004869 case CXCursor_OMPParallelForDirective:
4870 return cxstring::createRef("OMPParallelForDirective");
Alexander Musmane4e893b2014-09-23 09:33:00 +00004871 case CXCursor_OMPParallelForSimdDirective:
4872 return cxstring::createRef("OMPParallelForSimdDirective");
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004873 case CXCursor_OMPParallelSectionsDirective:
4874 return cxstring::createRef("OMPParallelSectionsDirective");
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004875 case CXCursor_OMPTaskDirective:
4876 return cxstring::createRef("OMPTaskDirective");
Alexey Bataev68446b72014-07-18 07:47:19 +00004877 case CXCursor_OMPTaskyieldDirective:
4878 return cxstring::createRef("OMPTaskyieldDirective");
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00004879 case CXCursor_OMPBarrierDirective:
4880 return cxstring::createRef("OMPBarrierDirective");
Alexey Bataev2df347a2014-07-18 10:17:07 +00004881 case CXCursor_OMPTaskwaitDirective:
4882 return cxstring::createRef("OMPTaskwaitDirective");
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00004883 case CXCursor_OMPTaskgroupDirective:
4884 return cxstring::createRef("OMPTaskgroupDirective");
Alexey Bataev6125da92014-07-21 11:26:11 +00004885 case CXCursor_OMPFlushDirective:
4886 return cxstring::createRef("OMPFlushDirective");
Alexey Bataev9fb6e642014-07-22 06:45:04 +00004887 case CXCursor_OMPOrderedDirective:
4888 return cxstring::createRef("OMPOrderedDirective");
Alexey Bataev0162e452014-07-22 10:10:35 +00004889 case CXCursor_OMPAtomicDirective:
4890 return cxstring::createRef("OMPAtomicDirective");
Alexey Bataev0bd520b2014-09-19 08:19:49 +00004891 case CXCursor_OMPTargetDirective:
4892 return cxstring::createRef("OMPTargetDirective");
Michael Wong65f367f2015-07-21 13:44:28 +00004893 case CXCursor_OMPTargetDataDirective:
4894 return cxstring::createRef("OMPTargetDataDirective");
Samuel Antaodf67fc42016-01-19 19:15:56 +00004895 case CXCursor_OMPTargetEnterDataDirective:
4896 return cxstring::createRef("OMPTargetEnterDataDirective");
Samuel Antao72590762016-01-19 20:04:50 +00004897 case CXCursor_OMPTargetExitDataDirective:
4898 return cxstring::createRef("OMPTargetExitDataDirective");
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00004899 case CXCursor_OMPTargetParallelDirective:
4900 return cxstring::createRef("OMPTargetParallelDirective");
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00004901 case CXCursor_OMPTargetParallelForDirective:
4902 return cxstring::createRef("OMPTargetParallelForDirective");
Samuel Antao686c70c2016-05-26 17:30:50 +00004903 case CXCursor_OMPTargetUpdateDirective:
4904 return cxstring::createRef("OMPTargetUpdateDirective");
Alexey Bataev13314bf2014-10-09 04:18:56 +00004905 case CXCursor_OMPTeamsDirective:
4906 return cxstring::createRef("OMPTeamsDirective");
Alexey Bataev6d4ed052015-07-01 06:57:41 +00004907 case CXCursor_OMPCancellationPointDirective:
4908 return cxstring::createRef("OMPCancellationPointDirective");
Alexey Bataev80909872015-07-02 11:25:17 +00004909 case CXCursor_OMPCancelDirective:
4910 return cxstring::createRef("OMPCancelDirective");
Alexey Bataev49f6e782015-12-01 04:18:41 +00004911 case CXCursor_OMPTaskLoopDirective:
4912 return cxstring::createRef("OMPTaskLoopDirective");
Alexey Bataev0a6ed842015-12-03 09:40:15 +00004913 case CXCursor_OMPTaskLoopSimdDirective:
4914 return cxstring::createRef("OMPTaskLoopSimdDirective");
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004915 case CXCursor_OMPDistributeDirective:
4916 return cxstring::createRef("OMPDistributeDirective");
Carlo Bertolli9925f152016-06-27 14:55:37 +00004917 case CXCursor_OMPDistributeParallelForDirective:
4918 return cxstring::createRef("OMPDistributeParallelForDirective");
Kelvin Li4a39add2016-07-05 05:00:15 +00004919 case CXCursor_OMPDistributeParallelForSimdDirective:
4920 return cxstring::createRef("OMPDistributeParallelForSimdDirective");
Kelvin Li787f3fc2016-07-06 04:45:38 +00004921 case CXCursor_OMPDistributeSimdDirective:
4922 return cxstring::createRef("OMPDistributeSimdDirective");
Kelvin Lia579b912016-07-14 02:54:56 +00004923 case CXCursor_OMPTargetParallelForSimdDirective:
4924 return cxstring::createRef("OMPTargetParallelForSimdDirective");
Kelvin Li986330c2016-07-20 22:57:10 +00004925 case CXCursor_OMPTargetSimdDirective:
4926 return cxstring::createRef("OMPTargetSimdDirective");
Kelvin Li02532872016-08-05 14:37:37 +00004927 case CXCursor_OMPTeamsDistributeDirective:
4928 return cxstring::createRef("OMPTeamsDistributeDirective");
Kelvin Li4e325f72016-10-25 12:50:55 +00004929 case CXCursor_OMPTeamsDistributeSimdDirective:
4930 return cxstring::createRef("OMPTeamsDistributeSimdDirective");
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00004931 case CXCursor_OverloadCandidate:
4932 return cxstring::createRef("OverloadCandidate");
Sergey Kalinichev8f3b1872015-11-15 13:48:32 +00004933 case CXCursor_TypeAliasTemplateDecl:
4934 return cxstring::createRef("TypeAliasTemplateDecl");
Olivier Goffart81978012016-06-09 16:15:55 +00004935 case CXCursor_StaticAssert:
4936 return cxstring::createRef("StaticAssert");
Olivier Goffartd211c642016-11-04 06:29:27 +00004937 case CXCursor_FriendDecl:
4938 return cxstring::createRef("FriendDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004939 }
4940
4941 llvm_unreachable("Unhandled CXCursorKind");
4942}
4943
4944struct GetCursorData {
4945 SourceLocation TokenBeginLoc;
4946 bool PointsAtMacroArgExpansion;
4947 bool VisitedObjCPropertyImplDecl;
4948 SourceLocation VisitedDeclaratorDeclStartLoc;
4949 CXCursor &BestCursor;
4950
4951 GetCursorData(SourceManager &SM,
4952 SourceLocation tokenBegin, CXCursor &outputCursor)
4953 : TokenBeginLoc(tokenBegin), BestCursor(outputCursor) {
4954 PointsAtMacroArgExpansion = SM.isMacroArgExpansion(tokenBegin);
4955 VisitedObjCPropertyImplDecl = false;
4956 }
4957};
4958
4959static enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
4960 CXCursor parent,
4961 CXClientData client_data) {
4962 GetCursorData *Data = static_cast<GetCursorData *>(client_data);
4963 CXCursor *BestCursor = &Data->BestCursor;
4964
4965 // If we point inside a macro argument we should provide info of what the
4966 // token is so use the actual cursor, don't replace it with a macro expansion
4967 // cursor.
4968 if (cursor.kind == CXCursor_MacroExpansion && Data->PointsAtMacroArgExpansion)
4969 return CXChildVisit_Recurse;
4970
4971 if (clang_isDeclaration(cursor.kind)) {
4972 // Avoid having the implicit methods override the property decls.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004973 if (const ObjCMethodDecl *MD
Guy Benyei11169dd2012-12-18 14:30:41 +00004974 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
4975 if (MD->isImplicit())
4976 return CXChildVisit_Break;
4977
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004978 } else if (const ObjCInterfaceDecl *ID
Guy Benyei11169dd2012-12-18 14:30:41 +00004979 = dyn_cast_or_null<ObjCInterfaceDecl>(getCursorDecl(cursor))) {
4980 // Check that when we have multiple @class references in the same line,
4981 // that later ones do not override the previous ones.
4982 // If we have:
4983 // @class Foo, Bar;
4984 // source ranges for both start at '@', so 'Bar' will end up overriding
4985 // 'Foo' even though the cursor location was at 'Foo'.
4986 if (BestCursor->kind == CXCursor_ObjCInterfaceDecl ||
4987 BestCursor->kind == CXCursor_ObjCClassRef)
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004988 if (const ObjCInterfaceDecl *PrevID
Guy Benyei11169dd2012-12-18 14:30:41 +00004989 = dyn_cast_or_null<ObjCInterfaceDecl>(getCursorDecl(*BestCursor))){
4990 if (PrevID != ID &&
4991 !PrevID->isThisDeclarationADefinition() &&
4992 !ID->isThisDeclarationADefinition())
4993 return CXChildVisit_Break;
4994 }
4995
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004996 } else if (const DeclaratorDecl *DD
Guy Benyei11169dd2012-12-18 14:30:41 +00004997 = dyn_cast_or_null<DeclaratorDecl>(getCursorDecl(cursor))) {
4998 SourceLocation StartLoc = DD->getSourceRange().getBegin();
4999 // Check that when we have multiple declarators in the same line,
5000 // that later ones do not override the previous ones.
5001 // If we have:
5002 // int Foo, Bar;
5003 // source ranges for both start at 'int', so 'Bar' will end up overriding
5004 // 'Foo' even though the cursor location was at 'Foo'.
5005 if (Data->VisitedDeclaratorDeclStartLoc == StartLoc)
5006 return CXChildVisit_Break;
5007 Data->VisitedDeclaratorDeclStartLoc = StartLoc;
5008
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005009 } else if (const ObjCPropertyImplDecl *PropImp
Guy Benyei11169dd2012-12-18 14:30:41 +00005010 = dyn_cast_or_null<ObjCPropertyImplDecl>(getCursorDecl(cursor))) {
5011 (void)PropImp;
5012 // Check that when we have multiple @synthesize in the same line,
5013 // that later ones do not override the previous ones.
5014 // If we have:
5015 // @synthesize Foo, Bar;
5016 // source ranges for both start at '@', so 'Bar' will end up overriding
5017 // 'Foo' even though the cursor location was at 'Foo'.
5018 if (Data->VisitedObjCPropertyImplDecl)
5019 return CXChildVisit_Break;
5020 Data->VisitedObjCPropertyImplDecl = true;
5021 }
5022 }
5023
5024 if (clang_isExpression(cursor.kind) &&
5025 clang_isDeclaration(BestCursor->kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005026 if (const Decl *D = getCursorDecl(*BestCursor)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005027 // Avoid having the cursor of an expression replace the declaration cursor
5028 // when the expression source range overlaps the declaration range.
5029 // This can happen for C++ constructor expressions whose range generally
5030 // include the variable declaration, e.g.:
5031 // MyCXXClass foo; // Make sure pointing at 'foo' returns a VarDecl cursor.
5032 if (D->getLocation().isValid() && Data->TokenBeginLoc.isValid() &&
5033 D->getLocation() == Data->TokenBeginLoc)
5034 return CXChildVisit_Break;
5035 }
5036 }
5037
5038 // If our current best cursor is the construction of a temporary object,
5039 // don't replace that cursor with a type reference, because we want
5040 // clang_getCursor() to point at the constructor.
5041 if (clang_isExpression(BestCursor->kind) &&
5042 isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
5043 cursor.kind == CXCursor_TypeRef) {
5044 // Keep the cursor pointing at CXXTemporaryObjectExpr but also mark it
5045 // as having the actual point on the type reference.
5046 *BestCursor = getTypeRefedCallExprCursor(*BestCursor);
5047 return CXChildVisit_Recurse;
5048 }
Douglas Gregore9d95f12015-07-07 03:57:35 +00005049
5050 // If we already have an Objective-C superclass reference, don't
5051 // update it further.
5052 if (BestCursor->kind == CXCursor_ObjCSuperClassRef)
5053 return CXChildVisit_Break;
5054
Guy Benyei11169dd2012-12-18 14:30:41 +00005055 *BestCursor = cursor;
5056 return CXChildVisit_Recurse;
5057}
5058
5059CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00005060 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00005061 LOG_BAD_TU(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00005062 return clang_getNullCursor();
Dmitri Gribenko256454f2014-02-11 14:34:14 +00005063 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005064
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00005065 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00005066 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
5067
5068 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
5069 CXCursor Result = cxcursor::getCursor(TU, SLoc);
5070
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005071 LOG_FUNC_SECTION {
Guy Benyei11169dd2012-12-18 14:30:41 +00005072 CXFile SearchFile;
5073 unsigned SearchLine, SearchColumn;
5074 CXFile ResultFile;
5075 unsigned ResultLine, ResultColumn;
5076 CXString SearchFileName, ResultFileName, KindSpelling, USR;
5077 const char *IsDef = clang_isCursorDefinition(Result)? " (Definition)" : "";
5078 CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
Craig Topper69186e72014-06-08 08:38:04 +00005079
5080 clang_getFileLocation(Loc, &SearchFile, &SearchLine, &SearchColumn,
5081 nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005082 clang_getFileLocation(ResultLoc, &ResultFile, &ResultLine,
Craig Topper69186e72014-06-08 08:38:04 +00005083 &ResultColumn, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005084 SearchFileName = clang_getFileName(SearchFile);
5085 ResultFileName = clang_getFileName(ResultFile);
5086 KindSpelling = clang_getCursorKindSpelling(Result.kind);
5087 USR = clang_getCursorUSR(Result);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005088 *Log << llvm::format("(%s:%d:%d) = %s",
5089 clang_getCString(SearchFileName), SearchLine, SearchColumn,
5090 clang_getCString(KindSpelling))
5091 << llvm::format("(%s:%d:%d):%s%s",
5092 clang_getCString(ResultFileName), ResultLine, ResultColumn,
5093 clang_getCString(USR), IsDef);
Guy Benyei11169dd2012-12-18 14:30:41 +00005094 clang_disposeString(SearchFileName);
5095 clang_disposeString(ResultFileName);
5096 clang_disposeString(KindSpelling);
5097 clang_disposeString(USR);
5098
5099 CXCursor Definition = clang_getCursorDefinition(Result);
5100 if (!clang_equalCursors(Definition, clang_getNullCursor())) {
5101 CXSourceLocation DefinitionLoc = clang_getCursorLocation(Definition);
5102 CXString DefinitionKindSpelling
5103 = clang_getCursorKindSpelling(Definition.kind);
5104 CXFile DefinitionFile;
5105 unsigned DefinitionLine, DefinitionColumn;
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005106 clang_getFileLocation(DefinitionLoc, &DefinitionFile,
Craig Topper69186e72014-06-08 08:38:04 +00005107 &DefinitionLine, &DefinitionColumn, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005108 CXString DefinitionFileName = clang_getFileName(DefinitionFile);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005109 *Log << llvm::format(" -> %s(%s:%d:%d)",
5110 clang_getCString(DefinitionKindSpelling),
5111 clang_getCString(DefinitionFileName),
5112 DefinitionLine, DefinitionColumn);
Guy Benyei11169dd2012-12-18 14:30:41 +00005113 clang_disposeString(DefinitionFileName);
5114 clang_disposeString(DefinitionKindSpelling);
5115 }
5116 }
5117
5118 return Result;
5119}
5120
5121CXCursor clang_getNullCursor(void) {
5122 return MakeCXCursorInvalid(CXCursor_InvalidFile);
5123}
5124
5125unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Argyrios Kyrtzidisbf1be592013-01-08 18:23:28 +00005126 // Clear out the "FirstInDeclGroup" part in a declaration cursor, since we
5127 // can't set consistently. For example, when visiting a DeclStmt we will set
5128 // it but we don't set it on the result of clang_getCursorDefinition for
5129 // a reference of the same declaration.
5130 // FIXME: Setting "FirstInDeclGroup" in CXCursors is a hack that only works
5131 // when visiting a DeclStmt currently, the AST should be enhanced to be able
5132 // to provide that kind of info.
5133 if (clang_isDeclaration(X.kind))
Craig Topper69186e72014-06-08 08:38:04 +00005134 X.data[1] = nullptr;
Argyrios Kyrtzidisbf1be592013-01-08 18:23:28 +00005135 if (clang_isDeclaration(Y.kind))
Craig Topper69186e72014-06-08 08:38:04 +00005136 Y.data[1] = nullptr;
Argyrios Kyrtzidisbf1be592013-01-08 18:23:28 +00005137
Guy Benyei11169dd2012-12-18 14:30:41 +00005138 return X == Y;
5139}
5140
5141unsigned clang_hashCursor(CXCursor C) {
5142 unsigned Index = 0;
5143 if (clang_isExpression(C.kind) || clang_isStatement(C.kind))
5144 Index = 1;
5145
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005146 return llvm::DenseMapInfo<std::pair<unsigned, const void*> >::getHashValue(
Guy Benyei11169dd2012-12-18 14:30:41 +00005147 std::make_pair(C.kind, C.data[Index]));
5148}
5149
5150unsigned clang_isInvalid(enum CXCursorKind K) {
5151 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
5152}
5153
5154unsigned clang_isDeclaration(enum CXCursorKind K) {
5155 return (K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl) ||
5156 (K >= CXCursor_FirstExtraDecl && K <= CXCursor_LastExtraDecl);
5157}
5158
5159unsigned clang_isReference(enum CXCursorKind K) {
5160 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
5161}
5162
5163unsigned clang_isExpression(enum CXCursorKind K) {
5164 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
5165}
5166
5167unsigned clang_isStatement(enum CXCursorKind K) {
5168 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
5169}
5170
5171unsigned clang_isAttribute(enum CXCursorKind K) {
5172 return K >= CXCursor_FirstAttr && K <= CXCursor_LastAttr;
5173}
5174
5175unsigned clang_isTranslationUnit(enum CXCursorKind K) {
5176 return K == CXCursor_TranslationUnit;
5177}
5178
5179unsigned clang_isPreprocessing(enum CXCursorKind K) {
5180 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
5181}
5182
5183unsigned clang_isUnexposed(enum CXCursorKind K) {
5184 switch (K) {
5185 case CXCursor_UnexposedDecl:
5186 case CXCursor_UnexposedExpr:
5187 case CXCursor_UnexposedStmt:
5188 case CXCursor_UnexposedAttr:
5189 return true;
5190 default:
5191 return false;
5192 }
5193}
5194
5195CXCursorKind clang_getCursorKind(CXCursor C) {
5196 return C.kind;
5197}
5198
5199CXSourceLocation clang_getCursorLocation(CXCursor C) {
5200 if (clang_isReference(C.kind)) {
5201 switch (C.kind) {
5202 case CXCursor_ObjCSuperClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005203 std::pair<const ObjCInterfaceDecl *, SourceLocation> P
Guy Benyei11169dd2012-12-18 14:30:41 +00005204 = getCursorObjCSuperClassRef(C);
5205 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5206 }
5207
5208 case CXCursor_ObjCProtocolRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005209 std::pair<const ObjCProtocolDecl *, SourceLocation> P
Guy Benyei11169dd2012-12-18 14:30:41 +00005210 = getCursorObjCProtocolRef(C);
5211 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5212 }
5213
5214 case CXCursor_ObjCClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005215 std::pair<const ObjCInterfaceDecl *, SourceLocation> P
Guy Benyei11169dd2012-12-18 14:30:41 +00005216 = getCursorObjCClassRef(C);
5217 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5218 }
5219
5220 case CXCursor_TypeRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005221 std::pair<const TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005222 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5223 }
5224
5225 case CXCursor_TemplateRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005226 std::pair<const TemplateDecl *, SourceLocation> P =
5227 getCursorTemplateRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005228 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5229 }
5230
5231 case CXCursor_NamespaceRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005232 std::pair<const NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005233 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5234 }
5235
5236 case CXCursor_MemberRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005237 std::pair<const FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005238 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5239 }
5240
5241 case CXCursor_VariableRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005242 std::pair<const VarDecl *, SourceLocation> P = getCursorVariableRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005243 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5244 }
5245
5246 case CXCursor_CXXBaseSpecifier: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005247 const CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005248 if (!BaseSpec)
5249 return clang_getNullLocation();
5250
5251 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
5252 return cxloc::translateSourceLocation(getCursorContext(C),
5253 TSInfo->getTypeLoc().getBeginLoc());
5254
5255 return cxloc::translateSourceLocation(getCursorContext(C),
5256 BaseSpec->getLocStart());
5257 }
5258
5259 case CXCursor_LabelRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005260 std::pair<const LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005261 return cxloc::translateSourceLocation(getCursorContext(C), P.second);
5262 }
5263
5264 case CXCursor_OverloadedDeclRef:
5265 return cxloc::translateSourceLocation(getCursorContext(C),
5266 getCursorOverloadedDeclRef(C).second);
5267
5268 default:
5269 // FIXME: Need a way to enumerate all non-reference cases.
5270 llvm_unreachable("Missed a reference kind");
5271 }
5272 }
5273
5274 if (clang_isExpression(C.kind))
5275 return cxloc::translateSourceLocation(getCursorContext(C),
5276 getLocationFromExpr(getCursorExpr(C)));
5277
5278 if (clang_isStatement(C.kind))
5279 return cxloc::translateSourceLocation(getCursorContext(C),
5280 getCursorStmt(C)->getLocStart());
5281
5282 if (C.kind == CXCursor_PreprocessingDirective) {
5283 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
5284 return cxloc::translateSourceLocation(getCursorContext(C), L);
5285 }
5286
5287 if (C.kind == CXCursor_MacroExpansion) {
5288 SourceLocation L
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00005289 = cxcursor::getCursorMacroExpansion(C).getSourceRange().getBegin();
Guy Benyei11169dd2012-12-18 14:30:41 +00005290 return cxloc::translateSourceLocation(getCursorContext(C), L);
5291 }
5292
5293 if (C.kind == CXCursor_MacroDefinition) {
5294 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
5295 return cxloc::translateSourceLocation(getCursorContext(C), L);
5296 }
5297
5298 if (C.kind == CXCursor_InclusionDirective) {
5299 SourceLocation L
5300 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
5301 return cxloc::translateSourceLocation(getCursorContext(C), L);
5302 }
5303
Argyrios Kyrtzidis16834f12013-09-25 00:14:38 +00005304 if (clang_isAttribute(C.kind)) {
5305 SourceLocation L
5306 = cxcursor::getCursorAttr(C)->getLocation();
5307 return cxloc::translateSourceLocation(getCursorContext(C), L);
5308 }
5309
Guy Benyei11169dd2012-12-18 14:30:41 +00005310 if (!clang_isDeclaration(C.kind))
5311 return clang_getNullLocation();
5312
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005313 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005314 if (!D)
5315 return clang_getNullLocation();
5316
5317 SourceLocation Loc = D->getLocation();
5318 // FIXME: Multiple variables declared in a single declaration
5319 // currently lack the information needed to correctly determine their
5320 // ranges when accounting for the type-specifier. We use context
5321 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
5322 // and if so, whether it is the first decl.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005323 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005324 if (!cxcursor::isFirstInDeclGroup(C))
5325 Loc = VD->getLocation();
5326 }
5327
5328 // For ObjC methods, give the start location of the method name.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005329 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00005330 Loc = MD->getSelectorStartLoc();
5331
5332 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
5333}
5334
5335} // end extern "C"
5336
5337CXCursor cxcursor::getCursor(CXTranslationUnit TU, SourceLocation SLoc) {
5338 assert(TU);
5339
5340 // Guard against an invalid SourceLocation, or we may assert in one
5341 // of the following calls.
5342 if (SLoc.isInvalid())
5343 return clang_getNullCursor();
5344
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00005345 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00005346
5347 // Translate the given source location to make it point at the beginning of
5348 // the token under the cursor.
5349 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
5350 CXXUnit->getASTContext().getLangOpts());
5351
5352 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
5353 if (SLoc.isValid()) {
5354 GetCursorData ResultData(CXXUnit->getSourceManager(), SLoc, Result);
5355 CursorVisitor CursorVis(TU, GetCursorVisitor, &ResultData,
5356 /*VisitPreprocessorLast=*/true,
5357 /*VisitIncludedEntities=*/false,
5358 SourceLocation(SLoc));
5359 CursorVis.visitFileRegion();
5360 }
5361
5362 return Result;
5363}
5364
5365static SourceRange getRawCursorExtent(CXCursor C) {
5366 if (clang_isReference(C.kind)) {
5367 switch (C.kind) {
5368 case CXCursor_ObjCSuperClassRef:
5369 return getCursorObjCSuperClassRef(C).second;
5370
5371 case CXCursor_ObjCProtocolRef:
5372 return getCursorObjCProtocolRef(C).second;
5373
5374 case CXCursor_ObjCClassRef:
5375 return getCursorObjCClassRef(C).second;
5376
5377 case CXCursor_TypeRef:
5378 return getCursorTypeRef(C).second;
5379
5380 case CXCursor_TemplateRef:
5381 return getCursorTemplateRef(C).second;
5382
5383 case CXCursor_NamespaceRef:
5384 return getCursorNamespaceRef(C).second;
5385
5386 case CXCursor_MemberRef:
5387 return getCursorMemberRef(C).second;
5388
5389 case CXCursor_CXXBaseSpecifier:
5390 return getCursorCXXBaseSpecifier(C)->getSourceRange();
5391
5392 case CXCursor_LabelRef:
5393 return getCursorLabelRef(C).second;
5394
5395 case CXCursor_OverloadedDeclRef:
5396 return getCursorOverloadedDeclRef(C).second;
5397
5398 case CXCursor_VariableRef:
5399 return getCursorVariableRef(C).second;
5400
5401 default:
5402 // FIXME: Need a way to enumerate all non-reference cases.
5403 llvm_unreachable("Missed a reference kind");
5404 }
5405 }
5406
5407 if (clang_isExpression(C.kind))
5408 return getCursorExpr(C)->getSourceRange();
5409
5410 if (clang_isStatement(C.kind))
5411 return getCursorStmt(C)->getSourceRange();
5412
5413 if (clang_isAttribute(C.kind))
5414 return getCursorAttr(C)->getRange();
5415
5416 if (C.kind == CXCursor_PreprocessingDirective)
5417 return cxcursor::getCursorPreprocessingDirective(C);
5418
5419 if (C.kind == CXCursor_MacroExpansion) {
5420 ASTUnit *TU = getCursorASTUnit(C);
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00005421 SourceRange Range = cxcursor::getCursorMacroExpansion(C).getSourceRange();
Guy Benyei11169dd2012-12-18 14:30:41 +00005422 return TU->mapRangeFromPreamble(Range);
5423 }
5424
5425 if (C.kind == CXCursor_MacroDefinition) {
5426 ASTUnit *TU = getCursorASTUnit(C);
5427 SourceRange Range = cxcursor::getCursorMacroDefinition(C)->getSourceRange();
5428 return TU->mapRangeFromPreamble(Range);
5429 }
5430
5431 if (C.kind == CXCursor_InclusionDirective) {
5432 ASTUnit *TU = getCursorASTUnit(C);
5433 SourceRange Range = cxcursor::getCursorInclusionDirective(C)->getSourceRange();
5434 return TU->mapRangeFromPreamble(Range);
5435 }
5436
5437 if (C.kind == CXCursor_TranslationUnit) {
5438 ASTUnit *TU = getCursorASTUnit(C);
5439 FileID MainID = TU->getSourceManager().getMainFileID();
5440 SourceLocation Start = TU->getSourceManager().getLocForStartOfFile(MainID);
5441 SourceLocation End = TU->getSourceManager().getLocForEndOfFile(MainID);
5442 return SourceRange(Start, End);
5443 }
5444
5445 if (clang_isDeclaration(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005446 const Decl *D = cxcursor::getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005447 if (!D)
5448 return SourceRange();
5449
5450 SourceRange R = D->getSourceRange();
5451 // FIXME: Multiple variables declared in a single declaration
5452 // currently lack the information needed to correctly determine their
5453 // ranges when accounting for the type-specifier. We use context
5454 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
5455 // and if so, whether it is the first decl.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005456 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005457 if (!cxcursor::isFirstInDeclGroup(C))
5458 R.setBegin(VD->getLocation());
5459 }
5460 return R;
5461 }
5462 return SourceRange();
5463}
5464
5465/// \brief Retrieves the "raw" cursor extent, which is then extended to include
5466/// the decl-specifier-seq for declarations.
5467static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr) {
5468 if (clang_isDeclaration(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005469 const Decl *D = cxcursor::getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005470 if (!D)
5471 return SourceRange();
5472
5473 SourceRange R = D->getSourceRange();
5474
5475 // Adjust the start of the location for declarations preceded by
5476 // declaration specifiers.
5477 SourceLocation StartLoc;
5478 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
5479 if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
5480 StartLoc = TI->getTypeLoc().getLocStart();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005481 } else if (const TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005482 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
5483 StartLoc = TI->getTypeLoc().getLocStart();
5484 }
5485
5486 if (StartLoc.isValid() && R.getBegin().isValid() &&
5487 SrcMgr.isBeforeInTranslationUnit(StartLoc, R.getBegin()))
5488 R.setBegin(StartLoc);
5489
5490 // FIXME: Multiple variables declared in a single declaration
5491 // currently lack the information needed to correctly determine their
5492 // ranges when accounting for the type-specifier. We use context
5493 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
5494 // and if so, whether it is the first decl.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005495 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005496 if (!cxcursor::isFirstInDeclGroup(C))
5497 R.setBegin(VD->getLocation());
5498 }
5499
5500 return R;
5501 }
5502
5503 return getRawCursorExtent(C);
5504}
5505
5506extern "C" {
5507
5508CXSourceRange clang_getCursorExtent(CXCursor C) {
5509 SourceRange R = getRawCursorExtent(C);
5510 if (R.isInvalid())
5511 return clang_getNullRange();
5512
5513 return cxloc::translateSourceRange(getCursorContext(C), R);
5514}
5515
5516CXCursor clang_getCursorReferenced(CXCursor C) {
5517 if (clang_isInvalid(C.kind))
5518 return clang_getNullCursor();
5519
5520 CXTranslationUnit tu = getCursorTU(C);
5521 if (clang_isDeclaration(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005522 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005523 if (!D)
5524 return clang_getNullCursor();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005525 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00005526 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), tu);
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005527 if (const ObjCPropertyImplDecl *PropImpl =
5528 dyn_cast<ObjCPropertyImplDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00005529 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
5530 return MakeCXCursor(Property, tu);
5531
5532 return C;
5533 }
5534
5535 if (clang_isExpression(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005536 const Expr *E = getCursorExpr(C);
5537 const Decl *D = getDeclFromExpr(E);
Guy Benyei11169dd2012-12-18 14:30:41 +00005538 if (D) {
5539 CXCursor declCursor = MakeCXCursor(D, tu);
5540 declCursor = getSelectorIdentifierCursor(getSelectorIdentifierIndex(C),
5541 declCursor);
5542 return declCursor;
5543 }
5544
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005545 if (const OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00005546 return MakeCursorOverloadedDeclRef(Ovl, tu);
5547
5548 return clang_getNullCursor();
5549 }
5550
5551 if (clang_isStatement(C.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00005552 const Stmt *S = getCursorStmt(C);
5553 if (const GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
Guy Benyei11169dd2012-12-18 14:30:41 +00005554 if (LabelDecl *label = Goto->getLabel())
5555 if (LabelStmt *labelS = label->getStmt())
5556 return MakeCXCursor(labelS, getCursorDecl(C), tu);
5557
5558 return clang_getNullCursor();
5559 }
Richard Smith66a81862015-05-04 02:25:31 +00005560
Guy Benyei11169dd2012-12-18 14:30:41 +00005561 if (C.kind == CXCursor_MacroExpansion) {
Richard Smith66a81862015-05-04 02:25:31 +00005562 if (const MacroDefinitionRecord *Def =
5563 getCursorMacroExpansion(C).getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00005564 return MakeMacroDefinitionCursor(Def, tu);
5565 }
5566
5567 if (!clang_isReference(C.kind))
5568 return clang_getNullCursor();
5569
5570 switch (C.kind) {
5571 case CXCursor_ObjCSuperClassRef:
5572 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, tu);
5573
5574 case CXCursor_ObjCProtocolRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005575 const ObjCProtocolDecl *Prot = getCursorObjCProtocolRef(C).first;
5576 if (const ObjCProtocolDecl *Def = Prot->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00005577 return MakeCXCursor(Def, tu);
5578
5579 return MakeCXCursor(Prot, tu);
5580 }
5581
5582 case CXCursor_ObjCClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005583 const ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
5584 if (const ObjCInterfaceDecl *Def = Class->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00005585 return MakeCXCursor(Def, tu);
5586
5587 return MakeCXCursor(Class, tu);
5588 }
5589
5590 case CXCursor_TypeRef:
5591 return MakeCXCursor(getCursorTypeRef(C).first, tu );
5592
5593 case CXCursor_TemplateRef:
5594 return MakeCXCursor(getCursorTemplateRef(C).first, tu );
5595
5596 case CXCursor_NamespaceRef:
5597 return MakeCXCursor(getCursorNamespaceRef(C).first, tu );
5598
5599 case CXCursor_MemberRef:
5600 return MakeCXCursor(getCursorMemberRef(C).first, tu );
5601
5602 case CXCursor_CXXBaseSpecifier: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005603 const CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005604 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
5605 tu ));
5606 }
5607
5608 case CXCursor_LabelRef:
5609 // FIXME: We end up faking the "parent" declaration here because we
5610 // don't want to make CXCursor larger.
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00005611 return MakeCXCursor(getCursorLabelRef(C).first,
5612 cxtu::getASTUnit(tu)->getASTContext()
5613 .getTranslationUnitDecl(),
Guy Benyei11169dd2012-12-18 14:30:41 +00005614 tu);
5615
5616 case CXCursor_OverloadedDeclRef:
5617 return C;
5618
5619 case CXCursor_VariableRef:
5620 return MakeCXCursor(getCursorVariableRef(C).first, tu);
5621
5622 default:
5623 // We would prefer to enumerate all non-reference cursor kinds here.
5624 llvm_unreachable("Unhandled reference cursor kind");
5625 }
5626}
5627
5628CXCursor clang_getCursorDefinition(CXCursor C) {
5629 if (clang_isInvalid(C.kind))
5630 return clang_getNullCursor();
5631
5632 CXTranslationUnit TU = getCursorTU(C);
5633
5634 bool WasReference = false;
5635 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
5636 C = clang_getCursorReferenced(C);
5637 WasReference = true;
5638 }
5639
5640 if (C.kind == CXCursor_MacroExpansion)
5641 return clang_getCursorReferenced(C);
5642
5643 if (!clang_isDeclaration(C.kind))
5644 return clang_getNullCursor();
5645
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005646 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005647 if (!D)
5648 return clang_getNullCursor();
5649
5650 switch (D->getKind()) {
5651 // Declaration kinds that don't really separate the notions of
5652 // declaration and definition.
5653 case Decl::Namespace:
5654 case Decl::Typedef:
5655 case Decl::TypeAlias:
5656 case Decl::TypeAliasTemplate:
5657 case Decl::TemplateTypeParm:
5658 case Decl::EnumConstant:
5659 case Decl::Field:
Richard Smithbdb84f32016-07-22 23:36:59 +00005660 case Decl::Binding:
John McCall5e77d762013-04-16 07:28:30 +00005661 case Decl::MSProperty:
Guy Benyei11169dd2012-12-18 14:30:41 +00005662 case Decl::IndirectField:
5663 case Decl::ObjCIvar:
5664 case Decl::ObjCAtDefsField:
5665 case Decl::ImplicitParam:
5666 case Decl::ParmVar:
5667 case Decl::NonTypeTemplateParm:
5668 case Decl::TemplateTemplateParm:
5669 case Decl::ObjCCategoryImpl:
5670 case Decl::ObjCImplementation:
5671 case Decl::AccessSpec:
5672 case Decl::LinkageSpec:
Richard Smith8df390f2016-09-08 23:14:54 +00005673 case Decl::Export:
Guy Benyei11169dd2012-12-18 14:30:41 +00005674 case Decl::ObjCPropertyImpl:
5675 case Decl::FileScopeAsm:
5676 case Decl::StaticAssert:
5677 case Decl::Block:
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00005678 case Decl::Captured:
Alexey Bataev4244be22016-02-11 05:35:55 +00005679 case Decl::OMPCapturedExpr:
Guy Benyei11169dd2012-12-18 14:30:41 +00005680 case Decl::Label: // FIXME: Is this right??
5681 case Decl::ClassScopeFunctionSpecialization:
5682 case Decl::Import:
Alexey Bataeva769e072013-03-22 06:34:35 +00005683 case Decl::OMPThreadPrivate:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00005684 case Decl::OMPDeclareReduction:
Douglas Gregor85f3f952015-07-07 03:57:15 +00005685 case Decl::ObjCTypeParam:
David Majnemerd9b1a4f2015-11-04 03:40:30 +00005686 case Decl::BuiltinTemplate:
Nico Weber66220292016-03-02 17:28:48 +00005687 case Decl::PragmaComment:
Nico Webercbbaeb12016-03-02 19:28:54 +00005688 case Decl::PragmaDetectMismatch:
Guy Benyei11169dd2012-12-18 14:30:41 +00005689 return C;
5690
5691 // Declaration kinds that don't make any sense here, but are
5692 // nonetheless harmless.
David Blaikief005d3c2013-02-22 17:44:58 +00005693 case Decl::Empty:
Guy Benyei11169dd2012-12-18 14:30:41 +00005694 case Decl::TranslationUnit:
Richard Smithf19e1272015-03-07 00:04:49 +00005695 case Decl::ExternCContext:
Guy Benyei11169dd2012-12-18 14:30:41 +00005696 break;
5697
5698 // Declaration kinds for which the definition is not resolvable.
5699 case Decl::UnresolvedUsingTypename:
5700 case Decl::UnresolvedUsingValue:
5701 break;
5702
5703 case Decl::UsingDirective:
5704 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
5705 TU);
5706
5707 case Decl::NamespaceAlias:
5708 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), TU);
5709
5710 case Decl::Enum:
5711 case Decl::Record:
5712 case Decl::CXXRecord:
5713 case Decl::ClassTemplateSpecialization:
5714 case Decl::ClassTemplatePartialSpecialization:
5715 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
5716 return MakeCXCursor(Def, TU);
5717 return clang_getNullCursor();
5718
5719 case Decl::Function:
5720 case Decl::CXXMethod:
5721 case Decl::CXXConstructor:
5722 case Decl::CXXDestructor:
5723 case Decl::CXXConversion: {
Craig Topper69186e72014-06-08 08:38:04 +00005724 const FunctionDecl *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005725 if (cast<FunctionDecl>(D)->getBody(Def))
Dmitri Gribenko9c256e32013-01-14 00:46:27 +00005726 return MakeCXCursor(Def, TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00005727 return clang_getNullCursor();
5728 }
5729
Larisse Voufo39a1e502013-08-06 01:03:05 +00005730 case Decl::Var:
5731 case Decl::VarTemplateSpecialization:
Richard Smithbdb84f32016-07-22 23:36:59 +00005732 case Decl::VarTemplatePartialSpecialization:
5733 case Decl::Decomposition: {
Guy Benyei11169dd2012-12-18 14:30:41 +00005734 // Ask the variable if it has a definition.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005735 if (const VarDecl *Def = cast<VarDecl>(D)->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00005736 return MakeCXCursor(Def, TU);
5737 return clang_getNullCursor();
5738 }
5739
5740 case Decl::FunctionTemplate: {
Craig Topper69186e72014-06-08 08:38:04 +00005741 const FunctionDecl *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005742 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
5743 return MakeCXCursor(Def->getDescribedFunctionTemplate(), TU);
5744 return clang_getNullCursor();
5745 }
5746
5747 case Decl::ClassTemplate: {
5748 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
5749 ->getDefinition())
5750 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
5751 TU);
5752 return clang_getNullCursor();
5753 }
5754
Larisse Voufo39a1e502013-08-06 01:03:05 +00005755 case Decl::VarTemplate: {
5756 if (VarDecl *Def =
5757 cast<VarTemplateDecl>(D)->getTemplatedDecl()->getDefinition())
5758 return MakeCXCursor(cast<VarDecl>(Def)->getDescribedVarTemplate(), TU);
5759 return clang_getNullCursor();
5760 }
5761
Guy Benyei11169dd2012-12-18 14:30:41 +00005762 case Decl::Using:
5763 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
5764 D->getLocation(), TU);
5765
5766 case Decl::UsingShadow:
Richard Smith5179eb72016-06-28 19:03:57 +00005767 case Decl::ConstructorUsingShadow:
Guy Benyei11169dd2012-12-18 14:30:41 +00005768 return clang_getCursorDefinition(
5769 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
5770 TU));
5771
5772 case Decl::ObjCMethod: {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005773 const ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00005774 if (Method->isThisDeclarationADefinition())
5775 return C;
5776
5777 // Dig out the method definition in the associated
5778 // @implementation, if we have it.
5779 // FIXME: The ASTs should make finding the definition easier.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005780 if (const ObjCInterfaceDecl *Class
Guy Benyei11169dd2012-12-18 14:30:41 +00005781 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
5782 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
5783 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
5784 Method->isInstanceMethod()))
5785 if (Def->isThisDeclarationADefinition())
5786 return MakeCXCursor(Def, TU);
5787
5788 return clang_getNullCursor();
5789 }
5790
5791 case Decl::ObjCCategory:
5792 if (ObjCCategoryImplDecl *Impl
5793 = cast<ObjCCategoryDecl>(D)->getImplementation())
5794 return MakeCXCursor(Impl, TU);
5795 return clang_getNullCursor();
5796
5797 case Decl::ObjCProtocol:
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005798 if (const ObjCProtocolDecl *Def = cast<ObjCProtocolDecl>(D)->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00005799 return MakeCXCursor(Def, TU);
5800 return clang_getNullCursor();
5801
5802 case Decl::ObjCInterface: {
5803 // There are two notions of a "definition" for an Objective-C
5804 // class: the interface and its implementation. When we resolved a
5805 // reference to an Objective-C class, produce the @interface as
5806 // the definition; when we were provided with the interface,
5807 // produce the @implementation as the definition.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005808 const ObjCInterfaceDecl *IFace = cast<ObjCInterfaceDecl>(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00005809 if (WasReference) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005810 if (const ObjCInterfaceDecl *Def = IFace->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00005811 return MakeCXCursor(Def, TU);
5812 } else if (ObjCImplementationDecl *Impl = IFace->getImplementation())
5813 return MakeCXCursor(Impl, TU);
5814 return clang_getNullCursor();
5815 }
5816
5817 case Decl::ObjCProperty:
5818 // FIXME: We don't really know where to find the
5819 // ObjCPropertyImplDecls that implement this property.
5820 return clang_getNullCursor();
5821
5822 case Decl::ObjCCompatibleAlias:
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005823 if (const ObjCInterfaceDecl *Class
Guy Benyei11169dd2012-12-18 14:30:41 +00005824 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005825 if (const ObjCInterfaceDecl *Def = Class->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00005826 return MakeCXCursor(Def, TU);
5827
5828 return clang_getNullCursor();
5829
5830 case Decl::Friend:
5831 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
5832 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
5833 return clang_getNullCursor();
5834
5835 case Decl::FriendTemplate:
5836 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
5837 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
5838 return clang_getNullCursor();
5839 }
5840
5841 return clang_getNullCursor();
5842}
5843
5844unsigned clang_isCursorDefinition(CXCursor C) {
5845 if (!clang_isDeclaration(C.kind))
5846 return 0;
5847
5848 return clang_getCursorDefinition(C) == C;
5849}
5850
5851CXCursor clang_getCanonicalCursor(CXCursor C) {
5852 if (!clang_isDeclaration(C.kind))
5853 return C;
5854
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005855 if (const Decl *D = getCursorDecl(C)) {
5856 if (const ObjCCategoryImplDecl *CatImplD = dyn_cast<ObjCCategoryImplDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00005857 if (ObjCCategoryDecl *CatD = CatImplD->getCategoryDecl())
5858 return MakeCXCursor(CatD, getCursorTU(C));
5859
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005860 if (const ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
5861 if (const ObjCInterfaceDecl *IFD = ImplD->getClassInterface())
Guy Benyei11169dd2012-12-18 14:30:41 +00005862 return MakeCXCursor(IFD, getCursorTU(C));
5863
5864 return MakeCXCursor(D->getCanonicalDecl(), getCursorTU(C));
5865 }
5866
5867 return C;
5868}
5869
5870int clang_Cursor_getObjCSelectorIndex(CXCursor cursor) {
5871 return cxcursor::getSelectorIdentifierIndexAndLoc(cursor).first;
5872}
5873
5874unsigned clang_getNumOverloadedDecls(CXCursor C) {
5875 if (C.kind != CXCursor_OverloadedDeclRef)
5876 return 0;
5877
5878 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005879 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
Guy Benyei11169dd2012-12-18 14:30:41 +00005880 return E->getNumDecls();
5881
5882 if (OverloadedTemplateStorage *S
5883 = Storage.dyn_cast<OverloadedTemplateStorage*>())
5884 return S->size();
5885
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005886 const Decl *D = Storage.get<const Decl *>();
5887 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00005888 return Using->shadow_size();
5889
5890 return 0;
5891}
5892
5893CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
5894 if (cursor.kind != CXCursor_OverloadedDeclRef)
5895 return clang_getNullCursor();
5896
5897 if (index >= clang_getNumOverloadedDecls(cursor))
5898 return clang_getNullCursor();
5899
5900 CXTranslationUnit TU = getCursorTU(cursor);
5901 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005902 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
Guy Benyei11169dd2012-12-18 14:30:41 +00005903 return MakeCXCursor(E->decls_begin()[index], TU);
5904
5905 if (OverloadedTemplateStorage *S
5906 = Storage.dyn_cast<OverloadedTemplateStorage*>())
5907 return MakeCXCursor(S->begin()[index], TU);
5908
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005909 const Decl *D = Storage.get<const Decl *>();
5910 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005911 // FIXME: This is, unfortunately, linear time.
5912 UsingDecl::shadow_iterator Pos = Using->shadow_begin();
5913 std::advance(Pos, index);
5914 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), TU);
5915 }
5916
5917 return clang_getNullCursor();
5918}
5919
5920void clang_getDefinitionSpellingAndExtent(CXCursor C,
5921 const char **startBuf,
5922 const char **endBuf,
5923 unsigned *startLine,
5924 unsigned *startColumn,
5925 unsigned *endLine,
5926 unsigned *endColumn) {
5927 assert(getCursorDecl(C) && "CXCursor has null decl");
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005928 const FunctionDecl *FD = dyn_cast<FunctionDecl>(getCursorDecl(C));
Guy Benyei11169dd2012-12-18 14:30:41 +00005929 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
5930
5931 SourceManager &SM = FD->getASTContext().getSourceManager();
5932 *startBuf = SM.getCharacterData(Body->getLBracLoc());
5933 *endBuf = SM.getCharacterData(Body->getRBracLoc());
5934 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
5935 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
5936 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
5937 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
5938}
5939
5940
5941CXSourceRange clang_getCursorReferenceNameRange(CXCursor C, unsigned NameFlags,
5942 unsigned PieceIndex) {
5943 RefNamePieces Pieces;
5944
5945 switch (C.kind) {
5946 case CXCursor_MemberRefExpr:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00005947 if (const MemberExpr *E = dyn_cast<MemberExpr>(getCursorExpr(C)))
Guy Benyei11169dd2012-12-18 14:30:41 +00005948 Pieces = buildPieces(NameFlags, true, E->getMemberNameInfo(),
5949 E->getQualifierLoc().getSourceRange());
5950 break;
5951
5952 case CXCursor_DeclRefExpr:
James Y Knight04ec5bf2015-12-24 02:59:37 +00005953 if (const DeclRefExpr *E = dyn_cast<DeclRefExpr>(getCursorExpr(C))) {
5954 SourceRange TemplateArgLoc(E->getLAngleLoc(), E->getRAngleLoc());
5955 Pieces =
5956 buildPieces(NameFlags, false, E->getNameInfo(),
5957 E->getQualifierLoc().getSourceRange(), &TemplateArgLoc);
5958 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005959 break;
5960
5961 case CXCursor_CallExpr:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00005962 if (const CXXOperatorCallExpr *OCE =
Guy Benyei11169dd2012-12-18 14:30:41 +00005963 dyn_cast<CXXOperatorCallExpr>(getCursorExpr(C))) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00005964 const Expr *Callee = OCE->getCallee();
5965 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Callee))
Guy Benyei11169dd2012-12-18 14:30:41 +00005966 Callee = ICE->getSubExpr();
5967
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00005968 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Callee))
Guy Benyei11169dd2012-12-18 14:30:41 +00005969 Pieces = buildPieces(NameFlags, false, DRE->getNameInfo(),
5970 DRE->getQualifierLoc().getSourceRange());
5971 }
5972 break;
5973
5974 default:
5975 break;
5976 }
5977
5978 if (Pieces.empty()) {
5979 if (PieceIndex == 0)
5980 return clang_getCursorExtent(C);
5981 } else if (PieceIndex < Pieces.size()) {
5982 SourceRange R = Pieces[PieceIndex];
5983 if (R.isValid())
5984 return cxloc::translateSourceRange(getCursorContext(C), R);
5985 }
5986
5987 return clang_getNullRange();
5988}
5989
5990void clang_enableStackTraces(void) {
Richard Smithdfed58a2016-06-09 00:53:41 +00005991 // FIXME: Provide an argv0 here so we can find llvm-symbolizer.
5992 llvm::sys::PrintStackTraceOnErrorSignal(StringRef());
Guy Benyei11169dd2012-12-18 14:30:41 +00005993}
5994
5995void clang_executeOnThread(void (*fn)(void*), void *user_data,
5996 unsigned stack_size) {
5997 llvm::llvm_execute_on_thread(fn, user_data, stack_size);
5998}
5999
6000} // end: extern "C"
6001
6002//===----------------------------------------------------------------------===//
6003// Token-based Operations.
6004//===----------------------------------------------------------------------===//
6005
6006/* CXToken layout:
6007 * int_data[0]: a CXTokenKind
6008 * int_data[1]: starting token location
6009 * int_data[2]: token length
6010 * int_data[3]: reserved
6011 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
6012 * otherwise unused.
6013 */
6014extern "C" {
6015
6016CXTokenKind clang_getTokenKind(CXToken CXTok) {
6017 return static_cast<CXTokenKind>(CXTok.int_data[0]);
6018}
6019
6020CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
6021 switch (clang_getTokenKind(CXTok)) {
6022 case CXToken_Identifier:
6023 case CXToken_Keyword:
6024 // We know we have an IdentifierInfo*, so use that.
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00006025 return cxstring::createRef(static_cast<IdentifierInfo *>(CXTok.ptr_data)
Guy Benyei11169dd2012-12-18 14:30:41 +00006026 ->getNameStart());
6027
6028 case CXToken_Literal: {
6029 // We have stashed the starting pointer in the ptr_data field. Use it.
6030 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00006031 return cxstring::createDup(StringRef(Text, CXTok.int_data[2]));
Guy Benyei11169dd2012-12-18 14:30:41 +00006032 }
6033
6034 case CXToken_Punctuation:
6035 case CXToken_Comment:
6036 break;
6037 }
6038
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006039 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006040 LOG_BAD_TU(TU);
6041 return cxstring::createEmpty();
6042 }
6043
Guy Benyei11169dd2012-12-18 14:30:41 +00006044 // We have to find the starting buffer pointer the hard way, by
6045 // deconstructing the source location.
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006046 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006047 if (!CXXUnit)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00006048 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00006049
6050 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
6051 std::pair<FileID, unsigned> LocInfo
6052 = CXXUnit->getSourceManager().getDecomposedSpellingLoc(Loc);
6053 bool Invalid = false;
6054 StringRef Buffer
6055 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
6056 if (Invalid)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00006057 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00006058
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00006059 return cxstring::createDup(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Guy Benyei11169dd2012-12-18 14:30:41 +00006060}
6061
6062CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006063 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006064 LOG_BAD_TU(TU);
6065 return clang_getNullLocation();
6066 }
6067
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006068 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006069 if (!CXXUnit)
6070 return clang_getNullLocation();
6071
6072 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
6073 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
6074}
6075
6076CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006077 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006078 LOG_BAD_TU(TU);
6079 return clang_getNullRange();
6080 }
6081
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006082 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006083 if (!CXXUnit)
6084 return clang_getNullRange();
6085
6086 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
6087 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
6088}
6089
6090static void getTokens(ASTUnit *CXXUnit, SourceRange Range,
6091 SmallVectorImpl<CXToken> &CXTokens) {
6092 SourceManager &SourceMgr = CXXUnit->getSourceManager();
6093 std::pair<FileID, unsigned> BeginLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00006094 = SourceMgr.getDecomposedSpellingLoc(Range.getBegin());
Guy Benyei11169dd2012-12-18 14:30:41 +00006095 std::pair<FileID, unsigned> EndLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00006096 = SourceMgr.getDecomposedSpellingLoc(Range.getEnd());
Guy Benyei11169dd2012-12-18 14:30:41 +00006097
6098 // Cannot tokenize across files.
6099 if (BeginLocInfo.first != EndLocInfo.first)
6100 return;
6101
6102 // Create a lexer
6103 bool Invalid = false;
6104 StringRef Buffer
6105 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
6106 if (Invalid)
6107 return;
6108
6109 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
6110 CXXUnit->getASTContext().getLangOpts(),
6111 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
6112 Lex.SetCommentRetentionState(true);
6113
6114 // Lex tokens until we hit the end of the range.
6115 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
6116 Token Tok;
6117 bool previousWasAt = false;
6118 do {
6119 // Lex the next token
6120 Lex.LexFromRawLexer(Tok);
6121 if (Tok.is(tok::eof))
6122 break;
6123
6124 // Initialize the CXToken.
6125 CXToken CXTok;
6126
6127 // - Common fields
6128 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
6129 CXTok.int_data[2] = Tok.getLength();
6130 CXTok.int_data[3] = 0;
6131
6132 // - Kind-specific fields
6133 if (Tok.isLiteral()) {
6134 CXTok.int_data[0] = CXToken_Literal;
Dmitri Gribenkof9304482013-01-23 15:56:07 +00006135 CXTok.ptr_data = const_cast<char *>(Tok.getLiteralData());
Guy Benyei11169dd2012-12-18 14:30:41 +00006136 } else if (Tok.is(tok::raw_identifier)) {
6137 // Lookup the identifier to determine whether we have a keyword.
6138 IdentifierInfo *II
6139 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok);
6140
6141 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
6142 CXTok.int_data[0] = CXToken_Keyword;
6143 }
6144 else {
6145 CXTok.int_data[0] = Tok.is(tok::identifier)
6146 ? CXToken_Identifier
6147 : CXToken_Keyword;
6148 }
6149 CXTok.ptr_data = II;
6150 } else if (Tok.is(tok::comment)) {
6151 CXTok.int_data[0] = CXToken_Comment;
Craig Topper69186e72014-06-08 08:38:04 +00006152 CXTok.ptr_data = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006153 } else {
6154 CXTok.int_data[0] = CXToken_Punctuation;
Craig Topper69186e72014-06-08 08:38:04 +00006155 CXTok.ptr_data = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006156 }
6157 CXTokens.push_back(CXTok);
6158 previousWasAt = Tok.is(tok::at);
Argyrios Kyrtzidisc7c6a072016-11-09 23:58:39 +00006159 } while (Lex.getBufferLocation() < EffectiveBufferEnd);
Guy Benyei11169dd2012-12-18 14:30:41 +00006160}
6161
6162void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
6163 CXToken **Tokens, unsigned *NumTokens) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00006164 LOG_FUNC_SECTION {
6165 *Log << TU << ' ' << Range;
6166 }
6167
Guy Benyei11169dd2012-12-18 14:30:41 +00006168 if (Tokens)
Craig Topper69186e72014-06-08 08:38:04 +00006169 *Tokens = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006170 if (NumTokens)
6171 *NumTokens = 0;
6172
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006173 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006174 LOG_BAD_TU(TU);
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00006175 return;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006176 }
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00006177
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006178 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006179 if (!CXXUnit || !Tokens || !NumTokens)
6180 return;
6181
6182 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
6183
6184 SourceRange R = cxloc::translateCXSourceRange(Range);
6185 if (R.isInvalid())
6186 return;
6187
6188 SmallVector<CXToken, 32> CXTokens;
6189 getTokens(CXXUnit, R, CXTokens);
6190
6191 if (CXTokens.empty())
6192 return;
6193
6194 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
6195 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
6196 *NumTokens = CXTokens.size();
6197}
6198
6199void clang_disposeTokens(CXTranslationUnit TU,
6200 CXToken *Tokens, unsigned NumTokens) {
6201 free(Tokens);
6202}
6203
6204} // end: extern "C"
6205
6206//===----------------------------------------------------------------------===//
6207// Token annotation APIs.
6208//===----------------------------------------------------------------------===//
6209
Guy Benyei11169dd2012-12-18 14:30:41 +00006210static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
6211 CXCursor parent,
6212 CXClientData client_data);
6213static bool AnnotateTokensPostChildrenVisitor(CXCursor cursor,
6214 CXClientData client_data);
6215
6216namespace {
6217class AnnotateTokensWorker {
Guy Benyei11169dd2012-12-18 14:30:41 +00006218 CXToken *Tokens;
6219 CXCursor *Cursors;
6220 unsigned NumTokens;
6221 unsigned TokIdx;
6222 unsigned PreprocessingTokIdx;
6223 CursorVisitor AnnotateVis;
6224 SourceManager &SrcMgr;
6225 bool HasContextSensitiveKeywords;
6226
6227 struct PostChildrenInfo {
6228 CXCursor Cursor;
6229 SourceRange CursorRange;
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006230 unsigned BeforeReachingCursorIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00006231 unsigned BeforeChildrenTokenIdx;
6232 };
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006233 SmallVector<PostChildrenInfo, 8> PostChildrenInfos;
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006234
6235 CXToken &getTok(unsigned Idx) {
6236 assert(Idx < NumTokens);
6237 return Tokens[Idx];
6238 }
6239 const CXToken &getTok(unsigned Idx) const {
6240 assert(Idx < NumTokens);
6241 return Tokens[Idx];
6242 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006243 bool MoreTokens() const { return TokIdx < NumTokens; }
6244 unsigned NextToken() const { return TokIdx; }
6245 void AdvanceToken() { ++TokIdx; }
6246 SourceLocation GetTokenLoc(unsigned tokI) {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006247 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[1]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006248 }
6249 bool isFunctionMacroToken(unsigned tokI) const {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006250 return getTok(tokI).int_data[3] != 0;
Guy Benyei11169dd2012-12-18 14:30:41 +00006251 }
6252 SourceLocation getFunctionMacroTokenLoc(unsigned tokI) const {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006253 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[3]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006254 }
6255
6256 void annotateAndAdvanceTokens(CXCursor, RangeComparisonResult, SourceRange);
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006257 bool annotateAndAdvanceFunctionMacroTokens(CXCursor, RangeComparisonResult,
Guy Benyei11169dd2012-12-18 14:30:41 +00006258 SourceRange);
6259
6260public:
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006261 AnnotateTokensWorker(CXToken *tokens, CXCursor *cursors, unsigned numTokens,
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006262 CXTranslationUnit TU, SourceRange RegionOfInterest)
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006263 : Tokens(tokens), Cursors(cursors),
Guy Benyei11169dd2012-12-18 14:30:41 +00006264 NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006265 AnnotateVis(TU,
Guy Benyei11169dd2012-12-18 14:30:41 +00006266 AnnotateTokensVisitor, this,
6267 /*VisitPreprocessorLast=*/true,
6268 /*VisitIncludedEntities=*/false,
6269 RegionOfInterest,
6270 /*VisitDeclsOnly=*/false,
6271 AnnotateTokensPostChildrenVisitor),
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006272 SrcMgr(cxtu::getASTUnit(TU)->getSourceManager()),
Guy Benyei11169dd2012-12-18 14:30:41 +00006273 HasContextSensitiveKeywords(false) { }
6274
6275 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
6276 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
6277 bool postVisitChildren(CXCursor cursor);
6278 void AnnotateTokens();
6279
6280 /// \brief Determine whether the annotator saw any cursors that have
6281 /// context-sensitive keywords.
6282 bool hasContextSensitiveKeywords() const {
6283 return HasContextSensitiveKeywords;
6284 }
6285
6286 ~AnnotateTokensWorker() {
6287 assert(PostChildrenInfos.empty());
6288 }
6289};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006290}
Guy Benyei11169dd2012-12-18 14:30:41 +00006291
6292void AnnotateTokensWorker::AnnotateTokens() {
6293 // Walk the AST within the region of interest, annotating tokens
6294 // along the way.
6295 AnnotateVis.visitFileRegion();
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006296}
Guy Benyei11169dd2012-12-18 14:30:41 +00006297
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006298static inline void updateCursorAnnotation(CXCursor &Cursor,
6299 const CXCursor &updateC) {
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006300 if (clang_isInvalid(updateC.kind) || !clang_isInvalid(Cursor.kind))
Guy Benyei11169dd2012-12-18 14:30:41 +00006301 return;
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006302 Cursor = updateC;
Guy Benyei11169dd2012-12-18 14:30:41 +00006303}
6304
6305/// \brief It annotates and advances tokens with a cursor until the comparison
6306//// between the cursor location and the source range is the same as
6307/// \arg compResult.
6308///
6309/// Pass RangeBefore to annotate tokens with a cursor until a range is reached.
6310/// Pass RangeOverlap to annotate tokens inside a range.
6311void AnnotateTokensWorker::annotateAndAdvanceTokens(CXCursor updateC,
6312 RangeComparisonResult compResult,
6313 SourceRange range) {
6314 while (MoreTokens()) {
6315 const unsigned I = NextToken();
6316 if (isFunctionMacroToken(I))
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006317 if (!annotateAndAdvanceFunctionMacroTokens(updateC, compResult, range))
6318 return;
Guy Benyei11169dd2012-12-18 14:30:41 +00006319
6320 SourceLocation TokLoc = GetTokenLoc(I);
6321 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006322 updateCursorAnnotation(Cursors[I], updateC);
Guy Benyei11169dd2012-12-18 14:30:41 +00006323 AdvanceToken();
6324 continue;
6325 }
6326 break;
6327 }
6328}
6329
6330/// \brief Special annotation handling for macro argument tokens.
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006331/// \returns true if it advanced beyond all macro tokens, false otherwise.
6332bool AnnotateTokensWorker::annotateAndAdvanceFunctionMacroTokens(
Guy Benyei11169dd2012-12-18 14:30:41 +00006333 CXCursor updateC,
6334 RangeComparisonResult compResult,
6335 SourceRange range) {
6336 assert(MoreTokens());
6337 assert(isFunctionMacroToken(NextToken()) &&
6338 "Should be called only for macro arg tokens");
6339
6340 // This works differently than annotateAndAdvanceTokens; because expanded
6341 // macro arguments can have arbitrary translation-unit source order, we do not
6342 // advance the token index one by one until a token fails the range test.
6343 // We only advance once past all of the macro arg tokens if all of them
6344 // pass the range test. If one of them fails we keep the token index pointing
6345 // at the start of the macro arg tokens so that the failing token will be
6346 // annotated by a subsequent annotation try.
6347
6348 bool atLeastOneCompFail = false;
6349
6350 unsigned I = NextToken();
6351 for (; I < NumTokens && isFunctionMacroToken(I); ++I) {
6352 SourceLocation TokLoc = getFunctionMacroTokenLoc(I);
6353 if (TokLoc.isFileID())
6354 continue; // not macro arg token, it's parens or comma.
6355 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
6356 if (clang_isInvalid(clang_getCursorKind(Cursors[I])))
6357 Cursors[I] = updateC;
6358 } else
6359 atLeastOneCompFail = true;
6360 }
6361
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006362 if (atLeastOneCompFail)
6363 return false;
6364
6365 TokIdx = I; // All of the tokens were handled, advance beyond all of them.
6366 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00006367}
6368
6369enum CXChildVisitResult
6370AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006371 SourceRange cursorRange = getRawCursorExtent(cursor);
6372 if (cursorRange.isInvalid())
6373 return CXChildVisit_Recurse;
6374
6375 if (!HasContextSensitiveKeywords) {
6376 // Objective-C properties can have context-sensitive keywords.
6377 if (cursor.kind == CXCursor_ObjCPropertyDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006378 if (const ObjCPropertyDecl *Property
Guy Benyei11169dd2012-12-18 14:30:41 +00006379 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(cursor)))
6380 HasContextSensitiveKeywords = Property->getPropertyAttributesAsWritten() != 0;
6381 }
6382 // Objective-C methods can have context-sensitive keywords.
6383 else if (cursor.kind == CXCursor_ObjCInstanceMethodDecl ||
6384 cursor.kind == CXCursor_ObjCClassMethodDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006385 if (const ObjCMethodDecl *Method
Guy Benyei11169dd2012-12-18 14:30:41 +00006386 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
6387 if (Method->getObjCDeclQualifier())
6388 HasContextSensitiveKeywords = true;
6389 else {
David Majnemer59f77922016-06-24 04:05:48 +00006390 for (const auto *P : Method->parameters()) {
Aaron Ballman43b68be2014-03-07 17:50:17 +00006391 if (P->getObjCDeclQualifier()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006392 HasContextSensitiveKeywords = true;
6393 break;
6394 }
6395 }
6396 }
6397 }
6398 }
6399 // C++ methods can have context-sensitive keywords.
6400 else if (cursor.kind == CXCursor_CXXMethod) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006401 if (const CXXMethodDecl *Method
Guy Benyei11169dd2012-12-18 14:30:41 +00006402 = dyn_cast_or_null<CXXMethodDecl>(getCursorDecl(cursor))) {
6403 if (Method->hasAttr<FinalAttr>() || Method->hasAttr<OverrideAttr>())
6404 HasContextSensitiveKeywords = true;
6405 }
6406 }
6407 // C++ classes can have context-sensitive keywords.
6408 else if (cursor.kind == CXCursor_StructDecl ||
6409 cursor.kind == CXCursor_ClassDecl ||
6410 cursor.kind == CXCursor_ClassTemplate ||
6411 cursor.kind == CXCursor_ClassTemplatePartialSpecialization) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006412 if (const Decl *D = getCursorDecl(cursor))
Guy Benyei11169dd2012-12-18 14:30:41 +00006413 if (D->hasAttr<FinalAttr>())
6414 HasContextSensitiveKeywords = true;
6415 }
6416 }
Argyrios Kyrtzidis990b3862013-06-04 18:24:30 +00006417
6418 // Don't override a property annotation with its getter/setter method.
6419 if (cursor.kind == CXCursor_ObjCInstanceMethodDecl &&
6420 parent.kind == CXCursor_ObjCPropertyDecl)
6421 return CXChildVisit_Continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00006422
6423 if (clang_isPreprocessing(cursor.kind)) {
6424 // Items in the preprocessing record are kept separate from items in
6425 // declarations, so we keep a separate token index.
6426 unsigned SavedTokIdx = TokIdx;
6427 TokIdx = PreprocessingTokIdx;
6428
6429 // Skip tokens up until we catch up to the beginning of the preprocessing
6430 // entry.
6431 while (MoreTokens()) {
6432 const unsigned I = NextToken();
6433 SourceLocation TokLoc = GetTokenLoc(I);
6434 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
6435 case RangeBefore:
6436 AdvanceToken();
6437 continue;
6438 case RangeAfter:
6439 case RangeOverlap:
6440 break;
6441 }
6442 break;
6443 }
6444
6445 // Look at all of the tokens within this range.
6446 while (MoreTokens()) {
6447 const unsigned I = NextToken();
6448 SourceLocation TokLoc = GetTokenLoc(I);
6449 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
6450 case RangeBefore:
6451 llvm_unreachable("Infeasible");
6452 case RangeAfter:
6453 break;
6454 case RangeOverlap:
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00006455 // For macro expansions, just note where the beginning of the macro
6456 // expansion occurs.
6457 if (cursor.kind == CXCursor_MacroExpansion) {
6458 if (TokLoc == cursorRange.getBegin())
6459 Cursors[I] = cursor;
6460 AdvanceToken();
6461 break;
6462 }
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006463 // We may have already annotated macro names inside macro definitions.
6464 if (Cursors[I].kind != CXCursor_MacroExpansion)
6465 Cursors[I] = cursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00006466 AdvanceToken();
Guy Benyei11169dd2012-12-18 14:30:41 +00006467 continue;
6468 }
6469 break;
6470 }
6471
6472 // Save the preprocessing token index; restore the non-preprocessing
6473 // token index.
6474 PreprocessingTokIdx = TokIdx;
6475 TokIdx = SavedTokIdx;
6476 return CXChildVisit_Recurse;
6477 }
6478
6479 if (cursorRange.isInvalid())
6480 return CXChildVisit_Continue;
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006481
6482 unsigned BeforeReachingCursorIdx = NextToken();
Guy Benyei11169dd2012-12-18 14:30:41 +00006483 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00006484 const enum CXCursorKind K = clang_getCursorKind(parent);
6485 const CXCursor updateC =
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006486 (clang_isInvalid(K) || K == CXCursor_TranslationUnit ||
6487 // Attributes are annotated out-of-order, skip tokens until we reach it.
6488 clang_isAttribute(cursor.kind))
Guy Benyei11169dd2012-12-18 14:30:41 +00006489 ? clang_getNullCursor() : parent;
6490
6491 annotateAndAdvanceTokens(updateC, RangeBefore, cursorRange);
6492
6493 // Avoid having the cursor of an expression "overwrite" the annotation of the
6494 // variable declaration that it belongs to.
6495 // This can happen for C++ constructor expressions whose range generally
6496 // include the variable declaration, e.g.:
6497 // MyCXXClass foo; // Make sure we don't annotate 'foo' as a CallExpr cursor.
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006498 if (clang_isExpression(cursorK) && MoreTokens()) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006499 const Expr *E = getCursorExpr(cursor);
Dmitri Gribenkoa1691182013-01-26 18:12:08 +00006500 if (const Decl *D = getCursorParentDecl(cursor)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006501 const unsigned I = NextToken();
6502 if (E->getLocStart().isValid() && D->getLocation().isValid() &&
6503 E->getLocStart() == D->getLocation() &&
6504 E->getLocStart() == GetTokenLoc(I)) {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006505 updateCursorAnnotation(Cursors[I], updateC);
Guy Benyei11169dd2012-12-18 14:30:41 +00006506 AdvanceToken();
6507 }
6508 }
6509 }
6510
6511 // Before recursing into the children keep some state that we are going
6512 // to use in the AnnotateTokensWorker::postVisitChildren callback to do some
6513 // extra work after the child nodes are visited.
6514 // Note that we don't call VisitChildren here to avoid traversing statements
6515 // code-recursively which can blow the stack.
6516
6517 PostChildrenInfo Info;
6518 Info.Cursor = cursor;
6519 Info.CursorRange = cursorRange;
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006520 Info.BeforeReachingCursorIdx = BeforeReachingCursorIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00006521 Info.BeforeChildrenTokenIdx = NextToken();
6522 PostChildrenInfos.push_back(Info);
6523
6524 return CXChildVisit_Recurse;
6525}
6526
6527bool AnnotateTokensWorker::postVisitChildren(CXCursor cursor) {
6528 if (PostChildrenInfos.empty())
6529 return false;
6530 const PostChildrenInfo &Info = PostChildrenInfos.back();
6531 if (!clang_equalCursors(Info.Cursor, cursor))
6532 return false;
6533
6534 const unsigned BeforeChildren = Info.BeforeChildrenTokenIdx;
6535 const unsigned AfterChildren = NextToken();
6536 SourceRange cursorRange = Info.CursorRange;
6537
6538 // Scan the tokens that are at the end of the cursor, but are not captured
6539 // but the child cursors.
6540 annotateAndAdvanceTokens(cursor, RangeOverlap, cursorRange);
6541
6542 // Scan the tokens that are at the beginning of the cursor, but are not
6543 // capture by the child cursors.
6544 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
6545 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
6546 break;
6547
6548 Cursors[I] = cursor;
6549 }
6550
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006551 // Attributes are annotated out-of-order, rewind TokIdx to when we first
6552 // encountered the attribute cursor.
6553 if (clang_isAttribute(cursor.kind))
6554 TokIdx = Info.BeforeReachingCursorIdx;
6555
Guy Benyei11169dd2012-12-18 14:30:41 +00006556 PostChildrenInfos.pop_back();
6557 return false;
6558}
6559
6560static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
6561 CXCursor parent,
6562 CXClientData client_data) {
6563 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
6564}
6565
6566static bool AnnotateTokensPostChildrenVisitor(CXCursor cursor,
6567 CXClientData client_data) {
6568 return static_cast<AnnotateTokensWorker*>(client_data)->
6569 postVisitChildren(cursor);
6570}
6571
6572namespace {
6573
6574/// \brief Uses the macro expansions in the preprocessing record to find
6575/// and mark tokens that are macro arguments. This info is used by the
6576/// AnnotateTokensWorker.
6577class MarkMacroArgTokensVisitor {
6578 SourceManager &SM;
6579 CXToken *Tokens;
6580 unsigned NumTokens;
6581 unsigned CurIdx;
6582
6583public:
6584 MarkMacroArgTokensVisitor(SourceManager &SM,
6585 CXToken *tokens, unsigned numTokens)
6586 : SM(SM), Tokens(tokens), NumTokens(numTokens), CurIdx(0) { }
6587
6588 CXChildVisitResult visit(CXCursor cursor, CXCursor parent) {
6589 if (cursor.kind != CXCursor_MacroExpansion)
6590 return CXChildVisit_Continue;
6591
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00006592 SourceRange macroRange = getCursorMacroExpansion(cursor).getSourceRange();
Guy Benyei11169dd2012-12-18 14:30:41 +00006593 if (macroRange.getBegin() == macroRange.getEnd())
6594 return CXChildVisit_Continue; // it's not a function macro.
6595
6596 for (; CurIdx < NumTokens; ++CurIdx) {
6597 if (!SM.isBeforeInTranslationUnit(getTokenLoc(CurIdx),
6598 macroRange.getBegin()))
6599 break;
6600 }
6601
6602 if (CurIdx == NumTokens)
6603 return CXChildVisit_Break;
6604
6605 for (; CurIdx < NumTokens; ++CurIdx) {
6606 SourceLocation tokLoc = getTokenLoc(CurIdx);
6607 if (!SM.isBeforeInTranslationUnit(tokLoc, macroRange.getEnd()))
6608 break;
6609
6610 setFunctionMacroTokenLoc(CurIdx, SM.getMacroArgExpandedLocation(tokLoc));
6611 }
6612
6613 if (CurIdx == NumTokens)
6614 return CXChildVisit_Break;
6615
6616 return CXChildVisit_Continue;
6617 }
6618
6619private:
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006620 CXToken &getTok(unsigned Idx) {
6621 assert(Idx < NumTokens);
6622 return Tokens[Idx];
6623 }
6624 const CXToken &getTok(unsigned Idx) const {
6625 assert(Idx < NumTokens);
6626 return Tokens[Idx];
6627 }
6628
Guy Benyei11169dd2012-12-18 14:30:41 +00006629 SourceLocation getTokenLoc(unsigned tokI) {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006630 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[1]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006631 }
6632
6633 void setFunctionMacroTokenLoc(unsigned tokI, SourceLocation loc) {
6634 // The third field is reserved and currently not used. Use it here
6635 // to mark macro arg expanded tokens with their expanded locations.
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006636 getTok(tokI).int_data[3] = loc.getRawEncoding();
Guy Benyei11169dd2012-12-18 14:30:41 +00006637 }
6638};
6639
6640} // end anonymous namespace
6641
6642static CXChildVisitResult
6643MarkMacroArgTokensVisitorDelegate(CXCursor cursor, CXCursor parent,
6644 CXClientData client_data) {
6645 return static_cast<MarkMacroArgTokensVisitor*>(client_data)->visit(cursor,
6646 parent);
6647}
6648
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006649/// \brief Used by \c annotatePreprocessorTokens.
6650/// \returns true if lexing was finished, false otherwise.
6651static bool lexNext(Lexer &Lex, Token &Tok,
6652 unsigned &NextIdx, unsigned NumTokens) {
6653 if (NextIdx >= NumTokens)
6654 return true;
6655
6656 ++NextIdx;
6657 Lex.LexFromRawLexer(Tok);
Alexander Kornienko1a9f1842015-12-28 15:24:08 +00006658 return Tok.is(tok::eof);
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006659}
6660
Guy Benyei11169dd2012-12-18 14:30:41 +00006661static void annotatePreprocessorTokens(CXTranslationUnit TU,
6662 SourceRange RegionOfInterest,
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006663 CXCursor *Cursors,
6664 CXToken *Tokens,
6665 unsigned NumTokens) {
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006666 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006667
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00006668 Preprocessor &PP = CXXUnit->getPreprocessor();
Guy Benyei11169dd2012-12-18 14:30:41 +00006669 SourceManager &SourceMgr = CXXUnit->getSourceManager();
6670 std::pair<FileID, unsigned> BeginLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00006671 = SourceMgr.getDecomposedSpellingLoc(RegionOfInterest.getBegin());
Guy Benyei11169dd2012-12-18 14:30:41 +00006672 std::pair<FileID, unsigned> EndLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00006673 = SourceMgr.getDecomposedSpellingLoc(RegionOfInterest.getEnd());
Guy Benyei11169dd2012-12-18 14:30:41 +00006674
6675 if (BeginLocInfo.first != EndLocInfo.first)
6676 return;
6677
6678 StringRef Buffer;
6679 bool Invalid = false;
6680 Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
6681 if (Buffer.empty() || Invalid)
6682 return;
6683
6684 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
6685 CXXUnit->getASTContext().getLangOpts(),
6686 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
6687 Buffer.end());
6688 Lex.SetCommentRetentionState(true);
6689
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006690 unsigned NextIdx = 0;
Guy Benyei11169dd2012-12-18 14:30:41 +00006691 // Lex tokens in raw mode until we hit the end of the range, to avoid
6692 // entering #includes or expanding macros.
6693 while (true) {
6694 Token Tok;
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006695 if (lexNext(Lex, Tok, NextIdx, NumTokens))
6696 break;
6697 unsigned TokIdx = NextIdx-1;
6698 assert(Tok.getLocation() ==
6699 SourceLocation::getFromRawEncoding(Tokens[TokIdx].int_data[1]));
Guy Benyei11169dd2012-12-18 14:30:41 +00006700
6701 reprocess:
6702 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006703 // We have found a preprocessing directive. Annotate the tokens
6704 // appropriately.
Guy Benyei11169dd2012-12-18 14:30:41 +00006705 //
6706 // FIXME: Some simple tests here could identify macro definitions and
6707 // #undefs, to provide specific cursor kinds for those.
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006708
6709 SourceLocation BeginLoc = Tok.getLocation();
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00006710 if (lexNext(Lex, Tok, NextIdx, NumTokens))
6711 break;
6712
Craig Topper69186e72014-06-08 08:38:04 +00006713 MacroInfo *MI = nullptr;
Alp Toker2d57cea2014-05-17 04:53:25 +00006714 if (Tok.is(tok::raw_identifier) && Tok.getRawIdentifier() == "define") {
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00006715 if (lexNext(Lex, Tok, NextIdx, NumTokens))
6716 break;
6717
6718 if (Tok.is(tok::raw_identifier)) {
Alp Toker2d57cea2014-05-17 04:53:25 +00006719 IdentifierInfo &II =
6720 PP.getIdentifierTable().get(Tok.getRawIdentifier());
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00006721 SourceLocation MappedTokLoc =
6722 CXXUnit->mapLocationToPreamble(Tok.getLocation());
6723 MI = getMacroInfo(II, MappedTokLoc, TU);
6724 }
6725 }
6726
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006727 bool finished = false;
Guy Benyei11169dd2012-12-18 14:30:41 +00006728 do {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006729 if (lexNext(Lex, Tok, NextIdx, NumTokens)) {
6730 finished = true;
6731 break;
6732 }
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00006733 // If we are in a macro definition, check if the token was ever a
6734 // macro name and annotate it if that's the case.
6735 if (MI) {
6736 SourceLocation SaveLoc = Tok.getLocation();
6737 Tok.setLocation(CXXUnit->mapLocationToPreamble(SaveLoc));
Richard Smith66a81862015-05-04 02:25:31 +00006738 MacroDefinitionRecord *MacroDef =
6739 checkForMacroInMacroDefinition(MI, Tok, TU);
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00006740 Tok.setLocation(SaveLoc);
6741 if (MacroDef)
Richard Smith66a81862015-05-04 02:25:31 +00006742 Cursors[NextIdx - 1] =
6743 MakeMacroExpansionCursor(MacroDef, Tok.getLocation(), TU);
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00006744 }
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006745 } while (!Tok.isAtStartOfLine());
6746
6747 unsigned LastIdx = finished ? NextIdx-1 : NextIdx-2;
6748 assert(TokIdx <= LastIdx);
6749 SourceLocation EndLoc =
6750 SourceLocation::getFromRawEncoding(Tokens[LastIdx].int_data[1]);
6751 CXCursor Cursor =
6752 MakePreprocessingDirectiveCursor(SourceRange(BeginLoc, EndLoc), TU);
6753
6754 for (; TokIdx <= LastIdx; ++TokIdx)
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00006755 updateCursorAnnotation(Cursors[TokIdx], Cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00006756
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006757 if (finished)
6758 break;
6759 goto reprocess;
Guy Benyei11169dd2012-12-18 14:30:41 +00006760 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006761 }
6762}
6763
6764// This gets run a separate thread to avoid stack blowout.
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00006765static void clang_annotateTokensImpl(CXTranslationUnit TU, ASTUnit *CXXUnit,
6766 CXToken *Tokens, unsigned NumTokens,
6767 CXCursor *Cursors) {
Dmitri Gribenko183436e2013-01-26 21:49:50 +00006768 CIndexer *CXXIdx = TU->CIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00006769 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing))
6770 setThreadBackgroundPriority();
6771
6772 // Determine the region of interest, which contains all of the tokens.
6773 SourceRange RegionOfInterest;
6774 RegionOfInterest.setBegin(
6775 cxloc::translateSourceLocation(clang_getTokenLocation(TU, Tokens[0])));
6776 RegionOfInterest.setEnd(
6777 cxloc::translateSourceLocation(clang_getTokenLocation(TU,
6778 Tokens[NumTokens-1])));
6779
Guy Benyei11169dd2012-12-18 14:30:41 +00006780 // Relex the tokens within the source range to look for preprocessing
6781 // directives.
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006782 annotatePreprocessorTokens(TU, RegionOfInterest, Cursors, Tokens, NumTokens);
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00006783
6784 // If begin location points inside a macro argument, set it to the expansion
6785 // location so we can have the full context when annotating semantically.
6786 {
6787 SourceManager &SM = CXXUnit->getSourceManager();
6788 SourceLocation Loc =
6789 SM.getMacroArgExpandedLocation(RegionOfInterest.getBegin());
6790 if (Loc.isMacroID())
6791 RegionOfInterest.setBegin(SM.getExpansionLoc(Loc));
6792 }
6793
Guy Benyei11169dd2012-12-18 14:30:41 +00006794 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
6795 // Search and mark tokens that are macro argument expansions.
6796 MarkMacroArgTokensVisitor Visitor(CXXUnit->getSourceManager(),
6797 Tokens, NumTokens);
6798 CursorVisitor MacroArgMarker(TU,
6799 MarkMacroArgTokensVisitorDelegate, &Visitor,
6800 /*VisitPreprocessorLast=*/true,
6801 /*VisitIncludedEntities=*/false,
6802 RegionOfInterest);
6803 MacroArgMarker.visitPreprocessedEntitiesInRegion();
6804 }
6805
6806 // Annotate all of the source locations in the region of interest that map to
6807 // a specific cursor.
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006808 AnnotateTokensWorker W(Tokens, Cursors, NumTokens, TU, RegionOfInterest);
Guy Benyei11169dd2012-12-18 14:30:41 +00006809
6810 // FIXME: We use a ridiculous stack size here because the data-recursion
6811 // algorithm uses a large stack frame than the non-data recursive version,
6812 // and AnnotationTokensWorker currently transforms the data-recursion
6813 // algorithm back into a traditional recursion by explicitly calling
6814 // VisitChildren(). We will need to remove this explicit recursive call.
6815 W.AnnotateTokens();
6816
6817 // If we ran into any entities that involve context-sensitive keywords,
6818 // take another pass through the tokens to mark them as such.
6819 if (W.hasContextSensitiveKeywords()) {
6820 for (unsigned I = 0; I != NumTokens; ++I) {
6821 if (clang_getTokenKind(Tokens[I]) != CXToken_Identifier)
6822 continue;
6823
6824 if (Cursors[I].kind == CXCursor_ObjCPropertyDecl) {
6825 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006826 if (const ObjCPropertyDecl *Property
Guy Benyei11169dd2012-12-18 14:30:41 +00006827 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(Cursors[I]))) {
6828 if (Property->getPropertyAttributesAsWritten() != 0 &&
6829 llvm::StringSwitch<bool>(II->getName())
6830 .Case("readonly", true)
6831 .Case("assign", true)
6832 .Case("unsafe_unretained", true)
6833 .Case("readwrite", true)
6834 .Case("retain", true)
6835 .Case("copy", true)
6836 .Case("nonatomic", true)
6837 .Case("atomic", true)
6838 .Case("getter", true)
6839 .Case("setter", true)
6840 .Case("strong", true)
6841 .Case("weak", true)
Manman Ren04fd4d82016-05-31 23:22:04 +00006842 .Case("class", true)
Guy Benyei11169dd2012-12-18 14:30:41 +00006843 .Default(false))
6844 Tokens[I].int_data[0] = CXToken_Keyword;
6845 }
6846 continue;
6847 }
6848
6849 if (Cursors[I].kind == CXCursor_ObjCInstanceMethodDecl ||
6850 Cursors[I].kind == CXCursor_ObjCClassMethodDecl) {
6851 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
6852 if (llvm::StringSwitch<bool>(II->getName())
6853 .Case("in", true)
6854 .Case("out", true)
6855 .Case("inout", true)
6856 .Case("oneway", true)
6857 .Case("bycopy", true)
6858 .Case("byref", true)
6859 .Default(false))
6860 Tokens[I].int_data[0] = CXToken_Keyword;
6861 continue;
6862 }
6863
6864 if (Cursors[I].kind == CXCursor_CXXFinalAttr ||
6865 Cursors[I].kind == CXCursor_CXXOverrideAttr) {
6866 Tokens[I].int_data[0] = CXToken_Keyword;
6867 continue;
6868 }
6869 }
6870 }
6871}
6872
6873extern "C" {
6874
6875void clang_annotateTokens(CXTranslationUnit TU,
6876 CXToken *Tokens, unsigned NumTokens,
6877 CXCursor *Cursors) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006878 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006879 LOG_BAD_TU(TU);
6880 return;
6881 }
6882 if (NumTokens == 0 || !Tokens || !Cursors) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00006883 LOG_FUNC_SECTION { *Log << "<null input>"; }
Guy Benyei11169dd2012-12-18 14:30:41 +00006884 return;
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00006885 }
6886
6887 LOG_FUNC_SECTION {
6888 *Log << TU << ' ';
6889 CXSourceLocation bloc = clang_getTokenLocation(TU, Tokens[0]);
6890 CXSourceLocation eloc = clang_getTokenLocation(TU, Tokens[NumTokens-1]);
6891 *Log << clang_getRange(bloc, eloc);
6892 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006893
6894 // Any token we don't specifically annotate will have a NULL cursor.
6895 CXCursor C = clang_getNullCursor();
6896 for (unsigned I = 0; I != NumTokens; ++I)
6897 Cursors[I] = C;
6898
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006899 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006900 if (!CXXUnit)
6901 return;
6902
6903 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00006904
6905 auto AnnotateTokensImpl = [=]() {
6906 clang_annotateTokensImpl(TU, CXXUnit, Tokens, NumTokens, Cursors);
6907 };
Guy Benyei11169dd2012-12-18 14:30:41 +00006908 llvm::CrashRecoveryContext CRC;
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00006909 if (!RunSafely(CRC, AnnotateTokensImpl, GetSafetyThreadStackSize() * 2)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006910 fprintf(stderr, "libclang: crash detected while annotating tokens\n");
6911 }
6912}
6913
6914} // end: extern "C"
6915
6916//===----------------------------------------------------------------------===//
6917// Operations for querying linkage of a cursor.
6918//===----------------------------------------------------------------------===//
6919
6920extern "C" {
6921CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
6922 if (!clang_isDeclaration(cursor.kind))
6923 return CXLinkage_Invalid;
6924
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006925 const Decl *D = cxcursor::getCursorDecl(cursor);
6926 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
Rafael Espindola3ae00052013-05-13 00:12:11 +00006927 switch (ND->getLinkageInternal()) {
Rafael Espindola50df3a02013-05-25 17:16:20 +00006928 case NoLinkage:
6929 case VisibleNoLinkage: return CXLinkage_NoLinkage;
Guy Benyei11169dd2012-12-18 14:30:41 +00006930 case InternalLinkage: return CXLinkage_Internal;
6931 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
6932 case ExternalLinkage: return CXLinkage_External;
6933 };
6934
6935 return CXLinkage_Invalid;
6936}
6937} // end: extern "C"
6938
6939//===----------------------------------------------------------------------===//
Ehsan Akhgarib743de72016-05-31 15:55:51 +00006940// Operations for querying visibility of a cursor.
6941//===----------------------------------------------------------------------===//
6942
6943extern "C" {
6944CXVisibilityKind clang_getCursorVisibility(CXCursor cursor) {
6945 if (!clang_isDeclaration(cursor.kind))
6946 return CXVisibility_Invalid;
6947
6948 const Decl *D = cxcursor::getCursorDecl(cursor);
6949 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
6950 switch (ND->getVisibility()) {
6951 case HiddenVisibility: return CXVisibility_Hidden;
6952 case ProtectedVisibility: return CXVisibility_Protected;
6953 case DefaultVisibility: return CXVisibility_Default;
6954 };
6955
6956 return CXVisibility_Invalid;
6957}
6958} // end: extern "C"
6959
6960//===----------------------------------------------------------------------===//
Guy Benyei11169dd2012-12-18 14:30:41 +00006961// Operations for querying language of a cursor.
6962//===----------------------------------------------------------------------===//
6963
6964static CXLanguageKind getDeclLanguage(const Decl *D) {
6965 if (!D)
6966 return CXLanguage_C;
6967
6968 switch (D->getKind()) {
6969 default:
6970 break;
6971 case Decl::ImplicitParam:
6972 case Decl::ObjCAtDefsField:
6973 case Decl::ObjCCategory:
6974 case Decl::ObjCCategoryImpl:
6975 case Decl::ObjCCompatibleAlias:
6976 case Decl::ObjCImplementation:
6977 case Decl::ObjCInterface:
6978 case Decl::ObjCIvar:
6979 case Decl::ObjCMethod:
6980 case Decl::ObjCProperty:
6981 case Decl::ObjCPropertyImpl:
6982 case Decl::ObjCProtocol:
Douglas Gregor85f3f952015-07-07 03:57:15 +00006983 case Decl::ObjCTypeParam:
Guy Benyei11169dd2012-12-18 14:30:41 +00006984 return CXLanguage_ObjC;
6985 case Decl::CXXConstructor:
6986 case Decl::CXXConversion:
6987 case Decl::CXXDestructor:
6988 case Decl::CXXMethod:
6989 case Decl::CXXRecord:
6990 case Decl::ClassTemplate:
6991 case Decl::ClassTemplatePartialSpecialization:
6992 case Decl::ClassTemplateSpecialization:
6993 case Decl::Friend:
6994 case Decl::FriendTemplate:
6995 case Decl::FunctionTemplate:
6996 case Decl::LinkageSpec:
6997 case Decl::Namespace:
6998 case Decl::NamespaceAlias:
6999 case Decl::NonTypeTemplateParm:
7000 case Decl::StaticAssert:
7001 case Decl::TemplateTemplateParm:
7002 case Decl::TemplateTypeParm:
7003 case Decl::UnresolvedUsingTypename:
7004 case Decl::UnresolvedUsingValue:
7005 case Decl::Using:
7006 case Decl::UsingDirective:
7007 case Decl::UsingShadow:
7008 return CXLanguage_CPlusPlus;
7009 }
7010
7011 return CXLanguage_C;
7012}
7013
7014extern "C" {
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007015
7016static CXAvailabilityKind getCursorAvailabilityForDecl(const Decl *D) {
7017 if (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted())
Manuel Klimek8e3a7ed2015-09-25 17:53:16 +00007018 return CXAvailability_NotAvailable;
Guy Benyei11169dd2012-12-18 14:30:41 +00007019
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007020 switch (D->getAvailability()) {
7021 case AR_Available:
7022 case AR_NotYetIntroduced:
7023 if (const EnumConstantDecl *EnumConst = dyn_cast<EnumConstantDecl>(D))
Benjamin Kramer656363d2013-10-15 18:53:18 +00007024 return getCursorAvailabilityForDecl(
7025 cast<Decl>(EnumConst->getDeclContext()));
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007026 return CXAvailability_Available;
7027
7028 case AR_Deprecated:
7029 return CXAvailability_Deprecated;
7030
7031 case AR_Unavailable:
7032 return CXAvailability_NotAvailable;
7033 }
Benjamin Kramer656363d2013-10-15 18:53:18 +00007034
7035 llvm_unreachable("Unknown availability kind!");
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007036}
7037
Guy Benyei11169dd2012-12-18 14:30:41 +00007038enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
7039 if (clang_isDeclaration(cursor.kind))
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007040 if (const Decl *D = cxcursor::getCursorDecl(cursor))
7041 return getCursorAvailabilityForDecl(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00007042
7043 return CXAvailability_Available;
7044}
7045
7046static CXVersion convertVersion(VersionTuple In) {
7047 CXVersion Out = { -1, -1, -1 };
7048 if (In.empty())
7049 return Out;
7050
7051 Out.Major = In.getMajor();
7052
NAKAMURA Takumic2b5d1f2013-02-21 02:32:34 +00007053 Optional<unsigned> Minor = In.getMinor();
7054 if (Minor.hasValue())
Guy Benyei11169dd2012-12-18 14:30:41 +00007055 Out.Minor = *Minor;
7056 else
7057 return Out;
7058
NAKAMURA Takumic2b5d1f2013-02-21 02:32:34 +00007059 Optional<unsigned> Subminor = In.getSubminor();
7060 if (Subminor.hasValue())
Guy Benyei11169dd2012-12-18 14:30:41 +00007061 Out.Subminor = *Subminor;
7062
7063 return Out;
7064}
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007065
7066static int getCursorPlatformAvailabilityForDecl(const Decl *D,
7067 int *always_deprecated,
7068 CXString *deprecated_message,
7069 int *always_unavailable,
7070 CXString *unavailable_message,
7071 CXPlatformAvailability *availability,
7072 int availability_size) {
7073 bool HadAvailAttr = false;
7074 int N = 0;
Aaron Ballmanb97112e2014-03-08 22:19:01 +00007075 for (auto A : D->attrs()) {
7076 if (DeprecatedAttr *Deprecated = dyn_cast<DeprecatedAttr>(A)) {
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007077 HadAvailAttr = true;
7078 if (always_deprecated)
7079 *always_deprecated = 1;
Nico Weberaacf0312014-04-24 05:16:45 +00007080 if (deprecated_message) {
Argyrios Kyrtzidisedfe07f2014-04-24 06:05:40 +00007081 clang_disposeString(*deprecated_message);
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007082 *deprecated_message = cxstring::createDup(Deprecated->getMessage());
Nico Weberaacf0312014-04-24 05:16:45 +00007083 }
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007084 continue;
7085 }
7086
Aaron Ballmanb97112e2014-03-08 22:19:01 +00007087 if (UnavailableAttr *Unavailable = dyn_cast<UnavailableAttr>(A)) {
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007088 HadAvailAttr = true;
7089 if (always_unavailable)
7090 *always_unavailable = 1;
7091 if (unavailable_message) {
Argyrios Kyrtzidisedfe07f2014-04-24 06:05:40 +00007092 clang_disposeString(*unavailable_message);
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007093 *unavailable_message = cxstring::createDup(Unavailable->getMessage());
7094 }
7095 continue;
7096 }
7097
Aaron Ballmanb97112e2014-03-08 22:19:01 +00007098 if (AvailabilityAttr *Avail = dyn_cast<AvailabilityAttr>(A)) {
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007099 HadAvailAttr = true;
7100 if (N < availability_size) {
7101 availability[N].Platform
7102 = cxstring::createDup(Avail->getPlatform()->getName());
7103 availability[N].Introduced = convertVersion(Avail->getIntroduced());
7104 availability[N].Deprecated = convertVersion(Avail->getDeprecated());
7105 availability[N].Obsoleted = convertVersion(Avail->getObsoleted());
7106 availability[N].Unavailable = Avail->getUnavailable();
7107 availability[N].Message = cxstring::createDup(Avail->getMessage());
7108 }
7109 ++N;
7110 }
7111 }
7112
7113 if (!HadAvailAttr)
7114 if (const EnumConstantDecl *EnumConst = dyn_cast<EnumConstantDecl>(D))
7115 return getCursorPlatformAvailabilityForDecl(
7116 cast<Decl>(EnumConst->getDeclContext()),
7117 always_deprecated,
7118 deprecated_message,
7119 always_unavailable,
7120 unavailable_message,
7121 availability,
7122 availability_size);
Guy Benyei11169dd2012-12-18 14:30:41 +00007123
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007124 return N;
7125}
7126
Guy Benyei11169dd2012-12-18 14:30:41 +00007127int clang_getCursorPlatformAvailability(CXCursor cursor,
7128 int *always_deprecated,
7129 CXString *deprecated_message,
7130 int *always_unavailable,
7131 CXString *unavailable_message,
7132 CXPlatformAvailability *availability,
7133 int availability_size) {
7134 if (always_deprecated)
7135 *always_deprecated = 0;
7136 if (deprecated_message)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00007137 *deprecated_message = cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00007138 if (always_unavailable)
7139 *always_unavailable = 0;
7140 if (unavailable_message)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00007141 *unavailable_message = cxstring::createEmpty();
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007142
Guy Benyei11169dd2012-12-18 14:30:41 +00007143 if (!clang_isDeclaration(cursor.kind))
7144 return 0;
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007145
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007146 const Decl *D = cxcursor::getCursorDecl(cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00007147 if (!D)
7148 return 0;
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007149
7150 return getCursorPlatformAvailabilityForDecl(D, always_deprecated,
7151 deprecated_message,
7152 always_unavailable,
7153 unavailable_message,
7154 availability,
7155 availability_size);
Guy Benyei11169dd2012-12-18 14:30:41 +00007156}
7157
7158void clang_disposeCXPlatformAvailability(CXPlatformAvailability *availability) {
7159 clang_disposeString(availability->Platform);
7160 clang_disposeString(availability->Message);
7161}
7162
7163CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
7164 if (clang_isDeclaration(cursor.kind))
7165 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
7166
7167 return CXLanguage_Invalid;
7168}
7169
7170 /// \brief If the given cursor is the "templated" declaration
7171 /// descibing a class or function template, return the class or
7172 /// function template.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007173static const Decl *maybeGetTemplateCursor(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007174 if (!D)
Craig Topper69186e72014-06-08 08:38:04 +00007175 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007176
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007177 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00007178 if (FunctionTemplateDecl *FunTmpl = FD->getDescribedFunctionTemplate())
7179 return FunTmpl;
7180
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007181 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00007182 if (ClassTemplateDecl *ClassTmpl = RD->getDescribedClassTemplate())
7183 return ClassTmpl;
7184
7185 return D;
7186}
7187
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00007188
7189enum CX_StorageClass clang_Cursor_getStorageClass(CXCursor C) {
7190 StorageClass sc = SC_None;
7191 const Decl *D = getCursorDecl(C);
7192 if (D) {
7193 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7194 sc = FD->getStorageClass();
7195 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7196 sc = VD->getStorageClass();
7197 } else {
7198 return CX_SC_Invalid;
7199 }
7200 } else {
7201 return CX_SC_Invalid;
7202 }
7203 switch (sc) {
7204 case SC_None:
7205 return CX_SC_None;
7206 case SC_Extern:
7207 return CX_SC_Extern;
7208 case SC_Static:
7209 return CX_SC_Static;
7210 case SC_PrivateExtern:
7211 return CX_SC_PrivateExtern;
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00007212 case SC_Auto:
7213 return CX_SC_Auto;
7214 case SC_Register:
7215 return CX_SC_Register;
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00007216 }
Kaelyn Takataab61e702014-10-15 18:03:26 +00007217 llvm_unreachable("Unhandled storage class!");
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00007218}
7219
Guy Benyei11169dd2012-12-18 14:30:41 +00007220CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
7221 if (clang_isDeclaration(cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007222 if (const Decl *D = getCursorDecl(cursor)) {
7223 const DeclContext *DC = D->getDeclContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00007224 if (!DC)
7225 return clang_getNullCursor();
7226
7227 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
7228 getCursorTU(cursor));
7229 }
7230 }
7231
7232 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007233 if (const Decl *D = getCursorDecl(cursor))
Guy Benyei11169dd2012-12-18 14:30:41 +00007234 return MakeCXCursor(D, getCursorTU(cursor));
7235 }
7236
7237 return clang_getNullCursor();
7238}
7239
7240CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
7241 if (clang_isDeclaration(cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007242 if (const Decl *D = getCursorDecl(cursor)) {
7243 const DeclContext *DC = D->getLexicalDeclContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00007244 if (!DC)
7245 return clang_getNullCursor();
7246
7247 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
7248 getCursorTU(cursor));
7249 }
7250 }
7251
7252 // FIXME: Note that we can't easily compute the lexical context of a
7253 // statement or expression, so we return nothing.
7254 return clang_getNullCursor();
7255}
7256
7257CXFile clang_getIncludedFile(CXCursor cursor) {
7258 if (cursor.kind != CXCursor_InclusionDirective)
Craig Topper69186e72014-06-08 08:38:04 +00007259 return nullptr;
7260
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00007261 const InclusionDirective *ID = getCursorInclusionDirective(cursor);
Dmitri Gribenkof9304482013-01-23 15:56:07 +00007262 return const_cast<FileEntry *>(ID->getFile());
Guy Benyei11169dd2012-12-18 14:30:41 +00007263}
7264
Argyrios Kyrtzidis9adfd8a2013-04-18 22:15:49 +00007265unsigned clang_Cursor_getObjCPropertyAttributes(CXCursor C, unsigned reserved) {
7266 if (C.kind != CXCursor_ObjCPropertyDecl)
7267 return CXObjCPropertyAttr_noattr;
7268
7269 unsigned Result = CXObjCPropertyAttr_noattr;
7270 const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(getCursorDecl(C));
7271 ObjCPropertyDecl::PropertyAttributeKind Attr =
7272 PD->getPropertyAttributesAsWritten();
7273
7274#define SET_CXOBJCPROP_ATTR(A) \
7275 if (Attr & ObjCPropertyDecl::OBJC_PR_##A) \
7276 Result |= CXObjCPropertyAttr_##A
7277 SET_CXOBJCPROP_ATTR(readonly);
7278 SET_CXOBJCPROP_ATTR(getter);
7279 SET_CXOBJCPROP_ATTR(assign);
7280 SET_CXOBJCPROP_ATTR(readwrite);
7281 SET_CXOBJCPROP_ATTR(retain);
7282 SET_CXOBJCPROP_ATTR(copy);
7283 SET_CXOBJCPROP_ATTR(nonatomic);
7284 SET_CXOBJCPROP_ATTR(setter);
7285 SET_CXOBJCPROP_ATTR(atomic);
7286 SET_CXOBJCPROP_ATTR(weak);
7287 SET_CXOBJCPROP_ATTR(strong);
7288 SET_CXOBJCPROP_ATTR(unsafe_unretained);
Manman Ren04fd4d82016-05-31 23:22:04 +00007289 SET_CXOBJCPROP_ATTR(class);
Argyrios Kyrtzidis9adfd8a2013-04-18 22:15:49 +00007290#undef SET_CXOBJCPROP_ATTR
7291
7292 return Result;
7293}
7294
Argyrios Kyrtzidis9d9bc012013-04-18 23:29:12 +00007295unsigned clang_Cursor_getObjCDeclQualifiers(CXCursor C) {
7296 if (!clang_isDeclaration(C.kind))
7297 return CXObjCDeclQualifier_None;
7298
7299 Decl::ObjCDeclQualifier QT = Decl::OBJC_TQ_None;
7300 const Decl *D = getCursorDecl(C);
7301 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
7302 QT = MD->getObjCDeclQualifier();
7303 else if (const ParmVarDecl *PD = dyn_cast<ParmVarDecl>(D))
7304 QT = PD->getObjCDeclQualifier();
7305 if (QT == Decl::OBJC_TQ_None)
7306 return CXObjCDeclQualifier_None;
7307
7308 unsigned Result = CXObjCDeclQualifier_None;
7309 if (QT & Decl::OBJC_TQ_In) Result |= CXObjCDeclQualifier_In;
7310 if (QT & Decl::OBJC_TQ_Inout) Result |= CXObjCDeclQualifier_Inout;
7311 if (QT & Decl::OBJC_TQ_Out) Result |= CXObjCDeclQualifier_Out;
7312 if (QT & Decl::OBJC_TQ_Bycopy) Result |= CXObjCDeclQualifier_Bycopy;
7313 if (QT & Decl::OBJC_TQ_Byref) Result |= CXObjCDeclQualifier_Byref;
7314 if (QT & Decl::OBJC_TQ_Oneway) Result |= CXObjCDeclQualifier_Oneway;
7315
7316 return Result;
7317}
7318
Argyrios Kyrtzidis7b50fc52013-07-05 20:44:37 +00007319unsigned clang_Cursor_isObjCOptional(CXCursor C) {
7320 if (!clang_isDeclaration(C.kind))
7321 return 0;
7322
7323 const Decl *D = getCursorDecl(C);
7324 if (const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D))
7325 return PD->getPropertyImplementation() == ObjCPropertyDecl::Optional;
7326 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
7327 return MD->getImplementationControl() == ObjCMethodDecl::Optional;
7328
7329 return 0;
7330}
7331
Argyrios Kyrtzidis23814e42013-04-18 23:53:05 +00007332unsigned clang_Cursor_isVariadic(CXCursor C) {
7333 if (!clang_isDeclaration(C.kind))
7334 return 0;
7335
7336 const Decl *D = getCursorDecl(C);
7337 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
7338 return FD->isVariadic();
7339 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
7340 return MD->isVariadic();
7341
7342 return 0;
7343}
7344
Guy Benyei11169dd2012-12-18 14:30:41 +00007345CXSourceRange clang_Cursor_getCommentRange(CXCursor C) {
7346 if (!clang_isDeclaration(C.kind))
7347 return clang_getNullRange();
7348
7349 const Decl *D = getCursorDecl(C);
7350 ASTContext &Context = getCursorContext(C);
7351 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
7352 if (!RC)
7353 return clang_getNullRange();
7354
7355 return cxloc::translateSourceRange(Context, RC->getSourceRange());
7356}
7357
7358CXString clang_Cursor_getRawCommentText(CXCursor C) {
7359 if (!clang_isDeclaration(C.kind))
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00007360 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00007361
7362 const Decl *D = getCursorDecl(C);
7363 ASTContext &Context = getCursorContext(C);
7364 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
7365 StringRef RawText = RC ? RC->getRawText(Context.getSourceManager()) :
7366 StringRef();
7367
7368 // Don't duplicate the string because RawText points directly into source
7369 // code.
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00007370 return cxstring::createRef(RawText);
Guy Benyei11169dd2012-12-18 14:30:41 +00007371}
7372
7373CXString clang_Cursor_getBriefCommentText(CXCursor C) {
7374 if (!clang_isDeclaration(C.kind))
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00007375 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00007376
7377 const Decl *D = getCursorDecl(C);
7378 const ASTContext &Context = getCursorContext(C);
7379 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
7380
7381 if (RC) {
7382 StringRef BriefText = RC->getBriefText(Context);
7383
7384 // Don't duplicate the string because RawComment ensures that this memory
7385 // will not go away.
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00007386 return cxstring::createRef(BriefText);
Guy Benyei11169dd2012-12-18 14:30:41 +00007387 }
7388
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00007389 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00007390}
7391
Guy Benyei11169dd2012-12-18 14:30:41 +00007392CXModule clang_Cursor_getModule(CXCursor C) {
7393 if (C.kind == CXCursor_ModuleImportDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007394 if (const ImportDecl *ImportD =
7395 dyn_cast_or_null<ImportDecl>(getCursorDecl(C)))
Guy Benyei11169dd2012-12-18 14:30:41 +00007396 return ImportD->getImportedModule();
7397 }
7398
Craig Topper69186e72014-06-08 08:38:04 +00007399 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007400}
7401
Argyrios Kyrtzidisf6d49c32014-05-14 23:14:37 +00007402CXModule clang_getModuleForFile(CXTranslationUnit TU, CXFile File) {
7403 if (isNotUsableTU(TU)) {
7404 LOG_BAD_TU(TU);
7405 return nullptr;
7406 }
7407 if (!File)
7408 return nullptr;
7409 FileEntry *FE = static_cast<FileEntry *>(File);
7410
7411 ASTUnit &Unit = *cxtu::getASTUnit(TU);
7412 HeaderSearch &HS = Unit.getPreprocessor().getHeaderSearchInfo();
7413 ModuleMap::KnownHeader Header = HS.findModuleForHeader(FE);
7414
Richard Smithfeb54b62014-10-23 02:01:19 +00007415 return Header.getModule();
Argyrios Kyrtzidisf6d49c32014-05-14 23:14:37 +00007416}
7417
Argyrios Kyrtzidis12fdb9e2013-04-26 22:47:49 +00007418CXFile clang_Module_getASTFile(CXModule CXMod) {
7419 if (!CXMod)
Craig Topper69186e72014-06-08 08:38:04 +00007420 return nullptr;
Argyrios Kyrtzidis12fdb9e2013-04-26 22:47:49 +00007421 Module *Mod = static_cast<Module*>(CXMod);
7422 return const_cast<FileEntry *>(Mod->getASTFile());
7423}
7424
Guy Benyei11169dd2012-12-18 14:30:41 +00007425CXModule clang_Module_getParent(CXModule CXMod) {
7426 if (!CXMod)
Craig Topper69186e72014-06-08 08:38:04 +00007427 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007428 Module *Mod = static_cast<Module*>(CXMod);
7429 return Mod->Parent;
7430}
7431
7432CXString clang_Module_getName(CXModule CXMod) {
7433 if (!CXMod)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00007434 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00007435 Module *Mod = static_cast<Module*>(CXMod);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00007436 return cxstring::createDup(Mod->Name);
Guy Benyei11169dd2012-12-18 14:30:41 +00007437}
7438
7439CXString clang_Module_getFullName(CXModule CXMod) {
7440 if (!CXMod)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00007441 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00007442 Module *Mod = static_cast<Module*>(CXMod);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00007443 return cxstring::createDup(Mod->getFullModuleName());
Guy Benyei11169dd2012-12-18 14:30:41 +00007444}
7445
Argyrios Kyrtzidis884337f2014-05-15 04:44:25 +00007446int clang_Module_isSystem(CXModule CXMod) {
7447 if (!CXMod)
7448 return 0;
7449 Module *Mod = static_cast<Module*>(CXMod);
7450 return Mod->IsSystem;
7451}
7452
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00007453unsigned clang_Module_getNumTopLevelHeaders(CXTranslationUnit TU,
7454 CXModule CXMod) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00007455 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00007456 LOG_BAD_TU(TU);
7457 return 0;
7458 }
7459 if (!CXMod)
Guy Benyei11169dd2012-12-18 14:30:41 +00007460 return 0;
7461 Module *Mod = static_cast<Module*>(CXMod);
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00007462 FileManager &FileMgr = cxtu::getASTUnit(TU)->getFileManager();
7463 ArrayRef<const FileEntry *> TopHeaders = Mod->getTopHeaders(FileMgr);
7464 return TopHeaders.size();
Guy Benyei11169dd2012-12-18 14:30:41 +00007465}
7466
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00007467CXFile clang_Module_getTopLevelHeader(CXTranslationUnit TU,
7468 CXModule CXMod, unsigned Index) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00007469 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00007470 LOG_BAD_TU(TU);
Craig Topper69186e72014-06-08 08:38:04 +00007471 return nullptr;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00007472 }
7473 if (!CXMod)
Craig Topper69186e72014-06-08 08:38:04 +00007474 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007475 Module *Mod = static_cast<Module*>(CXMod);
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00007476 FileManager &FileMgr = cxtu::getASTUnit(TU)->getFileManager();
Guy Benyei11169dd2012-12-18 14:30:41 +00007477
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00007478 ArrayRef<const FileEntry *> TopHeaders = Mod->getTopHeaders(FileMgr);
7479 if (Index < TopHeaders.size())
7480 return const_cast<FileEntry *>(TopHeaders[Index]);
Guy Benyei11169dd2012-12-18 14:30:41 +00007481
Craig Topper69186e72014-06-08 08:38:04 +00007482 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007483}
7484
7485} // end: extern "C"
7486
7487//===----------------------------------------------------------------------===//
7488// C++ AST instrospection.
7489//===----------------------------------------------------------------------===//
7490
7491extern "C" {
Jonathan Coe29565352016-04-27 12:48:25 +00007492
7493unsigned clang_CXXConstructor_isDefaultConstructor(CXCursor C) {
7494 if (!clang_isDeclaration(C.kind))
7495 return 0;
7496
7497 const Decl *D = cxcursor::getCursorDecl(C);
7498 const CXXConstructorDecl *Constructor =
7499 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
7500 return (Constructor && Constructor->isDefaultConstructor()) ? 1 : 0;
7501}
7502
7503unsigned clang_CXXConstructor_isCopyConstructor(CXCursor C) {
7504 if (!clang_isDeclaration(C.kind))
7505 return 0;
7506
7507 const Decl *D = cxcursor::getCursorDecl(C);
7508 const CXXConstructorDecl *Constructor =
7509 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
7510 return (Constructor && Constructor->isCopyConstructor()) ? 1 : 0;
7511}
7512
7513unsigned clang_CXXConstructor_isMoveConstructor(CXCursor C) {
7514 if (!clang_isDeclaration(C.kind))
7515 return 0;
7516
7517 const Decl *D = cxcursor::getCursorDecl(C);
7518 const CXXConstructorDecl *Constructor =
7519 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
7520 return (Constructor && Constructor->isMoveConstructor()) ? 1 : 0;
7521}
7522
7523unsigned clang_CXXConstructor_isConvertingConstructor(CXCursor C) {
7524 if (!clang_isDeclaration(C.kind))
7525 return 0;
7526
7527 const Decl *D = cxcursor::getCursorDecl(C);
7528 const CXXConstructorDecl *Constructor =
7529 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
7530 // Passing 'false' excludes constructors marked 'explicit'.
7531 return (Constructor && Constructor->isConvertingConstructor(false)) ? 1 : 0;
7532}
7533
Saleem Abdulrasool6ea75db2015-10-27 15:50:22 +00007534unsigned clang_CXXField_isMutable(CXCursor C) {
7535 if (!clang_isDeclaration(C.kind))
7536 return 0;
7537
7538 if (const auto D = cxcursor::getCursorDecl(C))
7539 if (const auto FD = dyn_cast_or_null<FieldDecl>(D))
7540 return FD->isMutable() ? 1 : 0;
7541 return 0;
7542}
7543
Dmitri Gribenko62770be2013-05-17 18:38:35 +00007544unsigned clang_CXXMethod_isPureVirtual(CXCursor C) {
7545 if (!clang_isDeclaration(C.kind))
7546 return 0;
7547
Dmitri Gribenko62770be2013-05-17 18:38:35 +00007548 const Decl *D = cxcursor::getCursorDecl(C);
Alp Tokera2794f92014-01-22 07:29:52 +00007549 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00007550 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Dmitri Gribenko62770be2013-05-17 18:38:35 +00007551 return (Method && Method->isVirtual() && Method->isPure()) ? 1 : 0;
7552}
7553
Dmitri Gribenkoe570ede2014-04-07 14:59:13 +00007554unsigned clang_CXXMethod_isConst(CXCursor C) {
7555 if (!clang_isDeclaration(C.kind))
7556 return 0;
7557
7558 const Decl *D = cxcursor::getCursorDecl(C);
7559 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00007560 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Dmitri Gribenkoe570ede2014-04-07 14:59:13 +00007561 return (Method && (Method->getTypeQualifiers() & Qualifiers::Const)) ? 1 : 0;
7562}
7563
Jonathan Coe29565352016-04-27 12:48:25 +00007564unsigned clang_CXXMethod_isDefaulted(CXCursor C) {
7565 if (!clang_isDeclaration(C.kind))
7566 return 0;
7567
7568 const Decl *D = cxcursor::getCursorDecl(C);
7569 const CXXMethodDecl *Method =
7570 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
7571 return (Method && Method->isDefaulted()) ? 1 : 0;
7572}
7573
Guy Benyei11169dd2012-12-18 14:30:41 +00007574unsigned clang_CXXMethod_isStatic(CXCursor C) {
7575 if (!clang_isDeclaration(C.kind))
7576 return 0;
7577
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007578 const Decl *D = cxcursor::getCursorDecl(C);
Alp Tokera2794f92014-01-22 07:29:52 +00007579 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00007580 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007581 return (Method && Method->isStatic()) ? 1 : 0;
7582}
7583
7584unsigned clang_CXXMethod_isVirtual(CXCursor C) {
7585 if (!clang_isDeclaration(C.kind))
7586 return 0;
7587
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007588 const Decl *D = cxcursor::getCursorDecl(C);
Alp Tokera2794f92014-01-22 07:29:52 +00007589 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00007590 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007591 return (Method && Method->isVirtual()) ? 1 : 0;
7592}
7593} // end: extern "C"
7594
7595//===----------------------------------------------------------------------===//
7596// Attribute introspection.
7597//===----------------------------------------------------------------------===//
7598
7599extern "C" {
7600CXType clang_getIBOutletCollectionType(CXCursor C) {
7601 if (C.kind != CXCursor_IBOutletCollectionAttr)
7602 return cxtype::MakeCXType(QualType(), cxcursor::getCursorTU(C));
7603
Dmitri Gribenkoe4baea62013-01-26 18:08:08 +00007604 const IBOutletCollectionAttr *A =
Guy Benyei11169dd2012-12-18 14:30:41 +00007605 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
7606
7607 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorTU(C));
7608}
7609} // end: extern "C"
7610
7611//===----------------------------------------------------------------------===//
7612// Inspecting memory usage.
7613//===----------------------------------------------------------------------===//
7614
7615typedef std::vector<CXTUResourceUsageEntry> MemUsageEntries;
7616
7617static inline void createCXTUResourceUsageEntry(MemUsageEntries &entries,
7618 enum CXTUResourceUsageKind k,
7619 unsigned long amount) {
7620 CXTUResourceUsageEntry entry = { k, amount };
7621 entries.push_back(entry);
7622}
7623
7624extern "C" {
7625
7626const char *clang_getTUResourceUsageName(CXTUResourceUsageKind kind) {
7627 const char *str = "";
7628 switch (kind) {
7629 case CXTUResourceUsage_AST:
7630 str = "ASTContext: expressions, declarations, and types";
7631 break;
7632 case CXTUResourceUsage_Identifiers:
7633 str = "ASTContext: identifiers";
7634 break;
7635 case CXTUResourceUsage_Selectors:
7636 str = "ASTContext: selectors";
7637 break;
7638 case CXTUResourceUsage_GlobalCompletionResults:
7639 str = "Code completion: cached global results";
7640 break;
7641 case CXTUResourceUsage_SourceManagerContentCache:
7642 str = "SourceManager: content cache allocator";
7643 break;
7644 case CXTUResourceUsage_AST_SideTables:
7645 str = "ASTContext: side tables";
7646 break;
7647 case CXTUResourceUsage_SourceManager_Membuffer_Malloc:
7648 str = "SourceManager: malloc'ed memory buffers";
7649 break;
7650 case CXTUResourceUsage_SourceManager_Membuffer_MMap:
7651 str = "SourceManager: mmap'ed memory buffers";
7652 break;
7653 case CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc:
7654 str = "ExternalASTSource: malloc'ed memory buffers";
7655 break;
7656 case CXTUResourceUsage_ExternalASTSource_Membuffer_MMap:
7657 str = "ExternalASTSource: mmap'ed memory buffers";
7658 break;
7659 case CXTUResourceUsage_Preprocessor:
7660 str = "Preprocessor: malloc'ed memory";
7661 break;
7662 case CXTUResourceUsage_PreprocessingRecord:
7663 str = "Preprocessor: PreprocessingRecord";
7664 break;
7665 case CXTUResourceUsage_SourceManager_DataStructures:
7666 str = "SourceManager: data structures and tables";
7667 break;
7668 case CXTUResourceUsage_Preprocessor_HeaderSearch:
7669 str = "Preprocessor: header search tables";
7670 break;
7671 }
7672 return str;
7673}
7674
7675CXTUResourceUsage clang_getCXTUResourceUsage(CXTranslationUnit TU) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00007676 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00007677 LOG_BAD_TU(TU);
Craig Topper69186e72014-06-08 08:38:04 +00007678 CXTUResourceUsage usage = { (void*) nullptr, 0, nullptr };
Guy Benyei11169dd2012-12-18 14:30:41 +00007679 return usage;
7680 }
7681
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00007682 ASTUnit *astUnit = cxtu::getASTUnit(TU);
Ahmed Charlesb8984322014-03-07 20:03:18 +00007683 std::unique_ptr<MemUsageEntries> entries(new MemUsageEntries());
Guy Benyei11169dd2012-12-18 14:30:41 +00007684 ASTContext &astContext = astUnit->getASTContext();
7685
7686 // How much memory is used by AST nodes and types?
7687 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST,
7688 (unsigned long) astContext.getASTAllocatedMemory());
7689
7690 // How much memory is used by identifiers?
7691 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Identifiers,
7692 (unsigned long) astContext.Idents.getAllocator().getTotalMemory());
7693
7694 // How much memory is used for selectors?
7695 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Selectors,
7696 (unsigned long) astContext.Selectors.getTotalMemory());
7697
7698 // How much memory is used by ASTContext's side tables?
7699 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST_SideTables,
7700 (unsigned long) astContext.getSideTableAllocatedMemory());
7701
7702 // How much memory is used for caching global code completion results?
7703 unsigned long completionBytes = 0;
7704 if (GlobalCodeCompletionAllocator *completionAllocator =
Alp Tokerf994cef2014-07-05 03:08:06 +00007705 astUnit->getCachedCompletionAllocator().get()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007706 completionBytes = completionAllocator->getTotalMemory();
7707 }
7708 createCXTUResourceUsageEntry(*entries,
7709 CXTUResourceUsage_GlobalCompletionResults,
7710 completionBytes);
7711
7712 // How much memory is being used by SourceManager's content cache?
7713 createCXTUResourceUsageEntry(*entries,
7714 CXTUResourceUsage_SourceManagerContentCache,
7715 (unsigned long) astContext.getSourceManager().getContentCacheSize());
7716
7717 // How much memory is being used by the MemoryBuffer's in SourceManager?
7718 const SourceManager::MemoryBufferSizes &srcBufs =
7719 astUnit->getSourceManager().getMemoryBufferSizes();
7720
7721 createCXTUResourceUsageEntry(*entries,
7722 CXTUResourceUsage_SourceManager_Membuffer_Malloc,
7723 (unsigned long) srcBufs.malloc_bytes);
7724 createCXTUResourceUsageEntry(*entries,
7725 CXTUResourceUsage_SourceManager_Membuffer_MMap,
7726 (unsigned long) srcBufs.mmap_bytes);
7727 createCXTUResourceUsageEntry(*entries,
7728 CXTUResourceUsage_SourceManager_DataStructures,
7729 (unsigned long) astContext.getSourceManager()
7730 .getDataStructureSizes());
7731
7732 // How much memory is being used by the ExternalASTSource?
7733 if (ExternalASTSource *esrc = astContext.getExternalSource()) {
7734 const ExternalASTSource::MemoryBufferSizes &sizes =
7735 esrc->getMemoryBufferSizes();
7736
7737 createCXTUResourceUsageEntry(*entries,
7738 CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc,
7739 (unsigned long) sizes.malloc_bytes);
7740 createCXTUResourceUsageEntry(*entries,
7741 CXTUResourceUsage_ExternalASTSource_Membuffer_MMap,
7742 (unsigned long) sizes.mmap_bytes);
7743 }
7744
7745 // How much memory is being used by the Preprocessor?
7746 Preprocessor &pp = astUnit->getPreprocessor();
7747 createCXTUResourceUsageEntry(*entries,
7748 CXTUResourceUsage_Preprocessor,
7749 pp.getTotalMemory());
7750
7751 if (PreprocessingRecord *pRec = pp.getPreprocessingRecord()) {
7752 createCXTUResourceUsageEntry(*entries,
7753 CXTUResourceUsage_PreprocessingRecord,
7754 pRec->getTotalMemory());
7755 }
7756
7757 createCXTUResourceUsageEntry(*entries,
7758 CXTUResourceUsage_Preprocessor_HeaderSearch,
7759 pp.getHeaderSearchInfo().getTotalMemory());
Craig Topper69186e72014-06-08 08:38:04 +00007760
Guy Benyei11169dd2012-12-18 14:30:41 +00007761 CXTUResourceUsage usage = { (void*) entries.get(),
7762 (unsigned) entries->size(),
Alexander Kornienko6ee521c2015-01-23 15:36:10 +00007763 !entries->empty() ? &(*entries)[0] : nullptr };
Eric Fiseliere95fc442016-11-14 07:03:50 +00007764 (void)entries.release();
Guy Benyei11169dd2012-12-18 14:30:41 +00007765 return usage;
7766}
7767
7768void clang_disposeCXTUResourceUsage(CXTUResourceUsage usage) {
7769 if (usage.data)
7770 delete (MemUsageEntries*) usage.data;
7771}
7772
Argyrios Kyrtzidis0e282ef2013-12-06 18:55:45 +00007773CXSourceRangeList *clang_getSkippedRanges(CXTranslationUnit TU, CXFile file) {
7774 CXSourceRangeList *skipped = new CXSourceRangeList;
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00007775 skipped->count = 0;
Craig Topper69186e72014-06-08 08:38:04 +00007776 skipped->ranges = nullptr;
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00007777
Dmitri Gribenko852d6222014-02-11 15:02:48 +00007778 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00007779 LOG_BAD_TU(TU);
7780 return skipped;
7781 }
7782
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00007783 if (!file)
7784 return skipped;
7785
7786 ASTUnit *astUnit = cxtu::getASTUnit(TU);
7787 PreprocessingRecord *ppRec = astUnit->getPreprocessor().getPreprocessingRecord();
7788 if (!ppRec)
7789 return skipped;
7790
7791 ASTContext &Ctx = astUnit->getASTContext();
7792 SourceManager &sm = Ctx.getSourceManager();
7793 FileEntry *fileEntry = static_cast<FileEntry *>(file);
7794 FileID wantedFileID = sm.translateFile(fileEntry);
7795
7796 const std::vector<SourceRange> &SkippedRanges = ppRec->getSkippedRanges();
7797 std::vector<SourceRange> wantedRanges;
7798 for (std::vector<SourceRange>::const_iterator i = SkippedRanges.begin(), ei = SkippedRanges.end();
7799 i != ei; ++i) {
7800 if (sm.getFileID(i->getBegin()) == wantedFileID || sm.getFileID(i->getEnd()) == wantedFileID)
7801 wantedRanges.push_back(*i);
7802 }
7803
7804 skipped->count = wantedRanges.size();
7805 skipped->ranges = new CXSourceRange[skipped->count];
7806 for (unsigned i = 0, ei = skipped->count; i != ei; ++i)
7807 skipped->ranges[i] = cxloc::translateSourceRange(Ctx, wantedRanges[i]);
7808
7809 return skipped;
7810}
7811
Cameron Desrochersd8091282016-08-18 15:43:55 +00007812CXSourceRangeList *clang_getAllSkippedRanges(CXTranslationUnit TU) {
7813 CXSourceRangeList *skipped = new CXSourceRangeList;
7814 skipped->count = 0;
7815 skipped->ranges = nullptr;
7816
7817 if (isNotUsableTU(TU)) {
7818 LOG_BAD_TU(TU);
7819 return skipped;
7820 }
7821
7822 ASTUnit *astUnit = cxtu::getASTUnit(TU);
7823 PreprocessingRecord *ppRec = astUnit->getPreprocessor().getPreprocessingRecord();
7824 if (!ppRec)
7825 return skipped;
7826
7827 ASTContext &Ctx = astUnit->getASTContext();
7828
7829 const std::vector<SourceRange> &SkippedRanges = ppRec->getSkippedRanges();
7830
7831 skipped->count = SkippedRanges.size();
7832 skipped->ranges = new CXSourceRange[skipped->count];
7833 for (unsigned i = 0, ei = skipped->count; i != ei; ++i)
7834 skipped->ranges[i] = cxloc::translateSourceRange(Ctx, SkippedRanges[i]);
7835
7836 return skipped;
7837}
7838
Argyrios Kyrtzidis0e282ef2013-12-06 18:55:45 +00007839void clang_disposeSourceRangeList(CXSourceRangeList *ranges) {
7840 if (ranges) {
7841 delete[] ranges->ranges;
7842 delete ranges;
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00007843 }
7844}
7845
Guy Benyei11169dd2012-12-18 14:30:41 +00007846} // end extern "C"
7847
7848void clang::PrintLibclangResourceUsage(CXTranslationUnit TU) {
7849 CXTUResourceUsage Usage = clang_getCXTUResourceUsage(TU);
7850 for (unsigned I = 0; I != Usage.numEntries; ++I)
7851 fprintf(stderr, " %s: %lu\n",
7852 clang_getTUResourceUsageName(Usage.entries[I].kind),
7853 Usage.entries[I].amount);
7854
7855 clang_disposeCXTUResourceUsage(Usage);
7856}
7857
7858//===----------------------------------------------------------------------===//
7859// Misc. utility functions.
7860//===----------------------------------------------------------------------===//
7861
7862/// Default to using an 8 MB stack size on "safety" threads.
7863static unsigned SafetyStackThreadSize = 8 << 20;
7864
7865namespace clang {
7866
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00007867bool RunSafely(llvm::CrashRecoveryContext &CRC, llvm::function_ref<void()> Fn,
Guy Benyei11169dd2012-12-18 14:30:41 +00007868 unsigned Size) {
7869 if (!Size)
7870 Size = GetSafetyThreadStackSize();
7871 if (Size)
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00007872 return CRC.RunSafelyOnThread(Fn, Size);
7873 return CRC.RunSafely(Fn);
Guy Benyei11169dd2012-12-18 14:30:41 +00007874}
7875
7876unsigned GetSafetyThreadStackSize() {
7877 return SafetyStackThreadSize;
7878}
7879
7880void SetSafetyThreadStackSize(unsigned Value) {
7881 SafetyStackThreadSize = Value;
7882}
7883
Alexander Kornienkoab9db512015-06-22 23:07:51 +00007884}
Guy Benyei11169dd2012-12-18 14:30:41 +00007885
7886void clang::setThreadBackgroundPriority() {
7887 if (getenv("LIBCLANG_BGPRIO_DISABLE"))
7888 return;
7889
Alp Toker1a86ad22014-07-06 06:24:00 +00007890#ifdef USE_DARWIN_THREADS
Guy Benyei11169dd2012-12-18 14:30:41 +00007891 setpriority(PRIO_DARWIN_THREAD, 0, PRIO_DARWIN_BG);
7892#endif
7893}
7894
7895void cxindex::printDiagsToStderr(ASTUnit *Unit) {
7896 if (!Unit)
7897 return;
7898
7899 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
7900 DEnd = Unit->stored_diag_end();
7901 D != DEnd; ++D) {
Ben Langmuir749323f2014-04-22 17:40:12 +00007902 CXStoredDiagnostic Diag(*D, Unit->getLangOpts());
Guy Benyei11169dd2012-12-18 14:30:41 +00007903 CXString Msg = clang_formatDiagnostic(&Diag,
7904 clang_defaultDiagnosticDisplayOptions());
7905 fprintf(stderr, "%s\n", clang_getCString(Msg));
7906 clang_disposeString(Msg);
7907 }
7908#ifdef LLVM_ON_WIN32
7909 // On Windows, force a flush, since there may be multiple copies of
7910 // stderr and stdout in the file system, all with different buffers
7911 // but writing to the same device.
7912 fflush(stderr);
7913#endif
7914}
7915
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007916MacroInfo *cxindex::getMacroInfo(const IdentifierInfo &II,
7917 SourceLocation MacroDefLoc,
7918 CXTranslationUnit TU){
7919 if (MacroDefLoc.isInvalid() || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00007920 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007921 if (!II.hadMacroDefinition())
Craig Topper69186e72014-06-08 08:38:04 +00007922 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007923
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00007924 ASTUnit *Unit = cxtu::getASTUnit(TU);
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007925 Preprocessor &PP = Unit->getPreprocessor();
Richard Smith20e883e2015-04-29 23:20:19 +00007926 MacroDirective *MD = PP.getLocalMacroDirectiveHistory(&II);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00007927 if (MD) {
7928 for (MacroDirective::DefInfo
7929 Def = MD->getDefinition(); Def; Def = Def.getPreviousDefinition()) {
7930 if (MacroDefLoc == Def.getMacroInfo()->getDefinitionLoc())
7931 return Def.getMacroInfo();
7932 }
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007933 }
7934
Craig Topper69186e72014-06-08 08:38:04 +00007935 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007936}
7937
Richard Smith66a81862015-05-04 02:25:31 +00007938const MacroInfo *cxindex::getMacroInfo(const MacroDefinitionRecord *MacroDef,
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00007939 CXTranslationUnit TU) {
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007940 if (!MacroDef || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00007941 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007942 const IdentifierInfo *II = MacroDef->getName();
7943 if (!II)
Craig Topper69186e72014-06-08 08:38:04 +00007944 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007945
7946 return getMacroInfo(*II, MacroDef->getLocation(), TU);
7947}
7948
Richard Smith66a81862015-05-04 02:25:31 +00007949MacroDefinitionRecord *
7950cxindex::checkForMacroInMacroDefinition(const MacroInfo *MI, const Token &Tok,
7951 CXTranslationUnit TU) {
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007952 if (!MI || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00007953 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007954 if (Tok.isNot(tok::raw_identifier))
Craig Topper69186e72014-06-08 08:38:04 +00007955 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007956
7957 if (MI->getNumTokens() == 0)
Craig Topper69186e72014-06-08 08:38:04 +00007958 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007959 SourceRange DefRange(MI->getReplacementToken(0).getLocation(),
7960 MI->getDefinitionEndLoc());
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00007961 ASTUnit *Unit = cxtu::getASTUnit(TU);
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007962
7963 // Check that the token is inside the definition and not its argument list.
7964 SourceManager &SM = Unit->getSourceManager();
7965 if (SM.isBeforeInTranslationUnit(Tok.getLocation(), DefRange.getBegin()))
Craig Topper69186e72014-06-08 08:38:04 +00007966 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007967 if (SM.isBeforeInTranslationUnit(DefRange.getEnd(), Tok.getLocation()))
Craig Topper69186e72014-06-08 08:38:04 +00007968 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007969
7970 Preprocessor &PP = Unit->getPreprocessor();
7971 PreprocessingRecord *PPRec = PP.getPreprocessingRecord();
7972 if (!PPRec)
Craig Topper69186e72014-06-08 08:38:04 +00007973 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007974
Alp Toker2d57cea2014-05-17 04:53:25 +00007975 IdentifierInfo &II = PP.getIdentifierTable().get(Tok.getRawIdentifier());
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
7979 // Check that the identifier is not one of the macro arguments.
7980 if (std::find(MI->arg_begin(), MI->arg_end(), &II) != MI->arg_end())
Craig Topper69186e72014-06-08 08:38:04 +00007981 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007982
Richard Smith20e883e2015-04-29 23:20:19 +00007983 MacroDirective *InnerMD = PP.getLocalMacroDirectiveHistory(&II);
Argyrios Kyrtzidis09c9e812013-02-20 00:54:57 +00007984 if (!InnerMD)
Craig Topper69186e72014-06-08 08:38:04 +00007985 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007986
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00007987 return PPRec->findMacroDefinition(InnerMD->getMacroInfo());
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007988}
7989
Richard Smith66a81862015-05-04 02:25:31 +00007990MacroDefinitionRecord *
7991cxindex::checkForMacroInMacroDefinition(const MacroInfo *MI, SourceLocation Loc,
7992 CXTranslationUnit TU) {
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007993 if (Loc.isInvalid() || !MI || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00007994 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007995
7996 if (MI->getNumTokens() == 0)
Craig Topper69186e72014-06-08 08:38:04 +00007997 return nullptr;
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00007998 ASTUnit *Unit = cxtu::getASTUnit(TU);
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007999 Preprocessor &PP = Unit->getPreprocessor();
8000 if (!PP.getPreprocessingRecord())
Craig Topper69186e72014-06-08 08:38:04 +00008001 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008002 Loc = Unit->getSourceManager().getSpellingLoc(Loc);
8003 Token Tok;
8004 if (PP.getRawToken(Loc, Tok))
Craig Topper69186e72014-06-08 08:38:04 +00008005 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008006
8007 return checkForMacroInMacroDefinition(MI, Tok, TU);
8008}
8009
Guy Benyei11169dd2012-12-18 14:30:41 +00008010extern "C" {
8011
8012CXString clang_getClangVersion() {
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00008013 return cxstring::createDup(getClangFullVersion());
Guy Benyei11169dd2012-12-18 14:30:41 +00008014}
8015
8016} // end: extern "C"
8017
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008018Logger &cxindex::Logger::operator<<(CXTranslationUnit TU) {
8019 if (TU) {
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008020 if (ASTUnit *Unit = cxtu::getASTUnit(TU)) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008021 LogOS << '<' << Unit->getMainFileName() << '>';
Argyrios Kyrtzidis37f2ab42013-03-05 20:21:14 +00008022 if (Unit->isMainFileAST())
8023 LogOS << " (" << Unit->getASTFileName() << ')';
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008024 return *this;
8025 }
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00008026 } else {
8027 LogOS << "<NULL TU>";
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008028 }
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008029 return *this;
8030}
8031
Argyrios Kyrtzidisba4b5f82013-03-08 02:32:26 +00008032Logger &cxindex::Logger::operator<<(const FileEntry *FE) {
8033 *this << FE->getName();
8034 return *this;
8035}
8036
8037Logger &cxindex::Logger::operator<<(CXCursor cursor) {
8038 CXString cursorName = clang_getCursorDisplayName(cursor);
8039 *this << cursorName << "@" << clang_getCursorLocation(cursor);
8040 clang_disposeString(cursorName);
8041 return *this;
8042}
8043
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008044Logger &cxindex::Logger::operator<<(CXSourceLocation Loc) {
8045 CXFile File;
8046 unsigned Line, Column;
Craig Topper69186e72014-06-08 08:38:04 +00008047 clang_getFileLocation(Loc, &File, &Line, &Column, nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008048 CXString FileName = clang_getFileName(File);
8049 *this << llvm::format("(%s:%d:%d)", clang_getCString(FileName), Line, Column);
8050 clang_disposeString(FileName);
8051 return *this;
8052}
8053
8054Logger &cxindex::Logger::operator<<(CXSourceRange range) {
8055 CXSourceLocation BLoc = clang_getRangeStart(range);
8056 CXSourceLocation ELoc = clang_getRangeEnd(range);
8057
8058 CXFile BFile;
8059 unsigned BLine, BColumn;
Craig Topper69186e72014-06-08 08:38:04 +00008060 clang_getFileLocation(BLoc, &BFile, &BLine, &BColumn, nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008061
8062 CXFile EFile;
8063 unsigned ELine, EColumn;
Craig Topper69186e72014-06-08 08:38:04 +00008064 clang_getFileLocation(ELoc, &EFile, &ELine, &EColumn, nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008065
8066 CXString BFileName = clang_getFileName(BFile);
8067 if (BFile == EFile) {
8068 *this << llvm::format("[%s %d:%d-%d:%d]", clang_getCString(BFileName),
8069 BLine, BColumn, ELine, EColumn);
8070 } else {
8071 CXString EFileName = clang_getFileName(EFile);
8072 *this << llvm::format("[%s:%d:%d - ", clang_getCString(BFileName),
8073 BLine, BColumn)
8074 << llvm::format("%s:%d:%d]", clang_getCString(EFileName),
8075 ELine, EColumn);
8076 clang_disposeString(EFileName);
8077 }
8078 clang_disposeString(BFileName);
8079 return *this;
8080}
8081
8082Logger &cxindex::Logger::operator<<(CXString Str) {
8083 *this << clang_getCString(Str);
8084 return *this;
8085}
8086
8087Logger &cxindex::Logger::operator<<(const llvm::format_object_base &Fmt) {
8088 LogOS << Fmt;
8089 return *this;
8090}
8091
Chandler Carruth37ad2582014-06-27 15:14:39 +00008092static llvm::ManagedStatic<llvm::sys::Mutex> LoggingMutex;
8093
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008094cxindex::Logger::~Logger() {
Chandler Carruth37ad2582014-06-27 15:14:39 +00008095 llvm::sys::ScopedLock L(*LoggingMutex);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008096
8097 static llvm::TimeRecord sBeginTR = llvm::TimeRecord::getCurrentTime();
8098
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008099 raw_ostream &OS = llvm::errs();
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008100 OS << "[libclang:" << Name << ':';
8101
Alp Toker1a86ad22014-07-06 06:24:00 +00008102#ifdef USE_DARWIN_THREADS
8103 // TODO: Portability.
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008104 mach_port_t tid = pthread_mach_thread_np(pthread_self());
8105 OS << tid << ':';
8106#endif
8107
8108 llvm::TimeRecord TR = llvm::TimeRecord::getCurrentTime();
8109 OS << llvm::format("%7.4f] ", TR.getWallTime() - sBeginTR.getWallTime());
Yaron Keren09fb7c62015-03-10 07:33:23 +00008110 OS << Msg << '\n';
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008111
8112 if (Trace) {
Zachary Turner1fe2a8d2015-03-05 19:15:09 +00008113 llvm::sys::PrintStackTrace(OS);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008114 OS << "--------------------------------------------------\n";
8115 }
8116}
Benjamin Kramerc1ffdab2016-03-03 08:58:18 +00008117
8118#ifdef CLANG_TOOL_EXTRA_BUILD
8119// This anchor is used to force the linker to link the clang-tidy plugin.
8120extern volatile int ClangTidyPluginAnchorSource;
8121static int LLVM_ATTRIBUTE_UNUSED ClangTidyPluginAnchorDestination =
8122 ClangTidyPluginAnchorSource;
8123#endif