Bug Summary

File:tools/clang/tools/libclang/CIndex.cpp
Warning:line 8007, column 42
Dereference of null pointer

Annotated Source Code

1//===- CIndex.cpp - Clang-C Source Indexing Library -----------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the main API hooks in the Clang-C Source Indexing
11// library.
12//
13//===----------------------------------------------------------------------===//
14
15#include "CIndexDiagnostic.h"
16#include "CIndexer.h"
17#include "CLog.h"
18#include "CXCursor.h"
19#include "CXSourceLocation.h"
20#include "CXString.h"
21#include "CXTranslationUnit.h"
22#include "CXType.h"
23#include "CursorVisitor.h"
24#include "clang/AST/Attr.h"
25#include "clang/AST/StmtVisitor.h"
26#include "clang/Basic/Diagnostic.h"
27#include "clang/Basic/DiagnosticCategories.h"
28#include "clang/Basic/DiagnosticIDs.h"
29#include "clang/Basic/TargetInfo.h"
30#include "clang/Basic/Version.h"
31#include "clang/Frontend/ASTUnit.h"
32#include "clang/Frontend/CompilerInstance.h"
33#include "clang/Frontend/FrontendDiagnostic.h"
34#include "clang/Index/CodegenNameGenerator.h"
35#include "clang/Index/CommentToXML.h"
36#include "clang/Lex/HeaderSearch.h"
37#include "clang/Lex/Lexer.h"
38#include "clang/Lex/PreprocessingRecord.h"
39#include "clang/Lex/Preprocessor.h"
40#include "clang/Serialization/SerializationDiagnostic.h"
41#include "llvm/ADT/Optional.h"
42#include "llvm/ADT/STLExtras.h"
43#include "llvm/ADT/StringSwitch.h"
44#include "llvm/Config/llvm-config.h"
45#include "llvm/Support/Compiler.h"
46#include "llvm/Support/CrashRecoveryContext.h"
47#include "llvm/Support/Format.h"
48#include "llvm/Support/ManagedStatic.h"
49#include "llvm/Support/MemoryBuffer.h"
50#include "llvm/Support/Mutex.h"
51#include "llvm/Support/Program.h"
52#include "llvm/Support/SaveAndRestore.h"
53#include "llvm/Support/Signals.h"
54#include "llvm/Support/TargetSelect.h"
55#include "llvm/Support/Threading.h"
56#include "llvm/Support/Timer.h"
57#include "llvm/Support/raw_ostream.h"
58
59#if LLVM_ENABLE_THREADS1 != 0 && defined(__APPLE__)
60#define USE_DARWIN_THREADS
61#endif
62
63#ifdef USE_DARWIN_THREADS
64#include <pthread.h>
65#endif
66
67using namespace clang;
68using namespace clang::cxcursor;
69using namespace clang::cxtu;
70using namespace clang::cxindex;
71
72CXTranslationUnit cxtu::MakeCXTranslationUnit(CIndexer *CIdx,
73 std::unique_ptr<ASTUnit> AU) {
74 if (!AU)
75 return nullptr;
76 assert(CIdx)((CIdx) ? static_cast<void> (0) : __assert_fail ("CIdx"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/tools/libclang/CIndex.cpp"
, 76, __PRETTY_FUNCTION__))
;
77 CXTranslationUnit D = new CXTranslationUnitImpl();
78 D->CIdx = CIdx;
79 D->TheASTUnit = AU.release();
80 D->StringPool = new cxstring::CXStringPool();
81 D->Diagnostics = nullptr;
82 D->OverridenCursorsPool = createOverridenCXCursorsPool();
83 D->CommentToXML = nullptr;
84 return D;
85}
86
87bool cxtu::isASTReadError(ASTUnit *AU) {
88 for (ASTUnit::stored_diag_iterator D = AU->stored_diag_begin(),
89 DEnd = AU->stored_diag_end();
90 D != DEnd; ++D) {
91 if (D->getLevel() >= DiagnosticsEngine::Error &&
92 DiagnosticIDs::getCategoryNumberForDiag(D->getID()) ==
93 diag::DiagCat_AST_Deserialization_Issue)
94 return true;
95 }
96 return false;
97}
98
99cxtu::CXTUOwner::~CXTUOwner() {
100 if (TU)
101 clang_disposeTranslationUnit(TU);
102}
103
104/// \brief Compare two source ranges to determine their relative position in
105/// the translation unit.
106static RangeComparisonResult RangeCompare(SourceManager &SM,
107 SourceRange R1,
108 SourceRange R2) {
109 assert(R1.isValid() && "First range is invalid?")((R1.isValid() && "First range is invalid?") ? static_cast
<void> (0) : __assert_fail ("R1.isValid() && \"First range is invalid?\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/tools/libclang/CIndex.cpp"
, 109, __PRETTY_FUNCTION__))
;
110 assert(R2.isValid() && "Second range is invalid?")((R2.isValid() && "Second range is invalid?") ? static_cast
<void> (0) : __assert_fail ("R2.isValid() && \"Second range is invalid?\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/tools/libclang/CIndex.cpp"
, 110, __PRETTY_FUNCTION__))
;
111 if (R1.getEnd() != R2.getBegin() &&
112 SM.isBeforeInTranslationUnit(R1.getEnd(), R2.getBegin()))
113 return RangeBefore;
114 if (R2.getEnd() != R1.getBegin() &&
115 SM.isBeforeInTranslationUnit(R2.getEnd(), R1.getBegin()))
116 return RangeAfter;
117 return RangeOverlap;
118}
119
120/// \brief Determine if a source location falls within, before, or after a
121/// a given source range.
122static RangeComparisonResult LocationCompare(SourceManager &SM,
123 SourceLocation L, SourceRange R) {
124 assert(R.isValid() && "First range is invalid?")((R.isValid() && "First range is invalid?") ? static_cast
<void> (0) : __assert_fail ("R.isValid() && \"First range is invalid?\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/tools/libclang/CIndex.cpp"
, 124, __PRETTY_FUNCTION__))
;
125 assert(L.isValid() && "Second range is invalid?")((L.isValid() && "Second range is invalid?") ? static_cast
<void> (0) : __assert_fail ("L.isValid() && \"Second range is invalid?\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/tools/libclang/CIndex.cpp"
, 125, __PRETTY_FUNCTION__))
;
126 if (L == R.getBegin() || L == R.getEnd())
127 return RangeOverlap;
128 if (SM.isBeforeInTranslationUnit(L, R.getBegin()))
129 return RangeBefore;
130 if (SM.isBeforeInTranslationUnit(R.getEnd(), L))
131 return RangeAfter;
132 return RangeOverlap;
133}
134
135/// \brief Translate a Clang source range into a CIndex source range.
136///
137/// Clang internally represents ranges where the end location points to the
138/// start of the token at the end. However, for external clients it is more
139/// useful to have a CXSourceRange be a proper half-open interval. This routine
140/// does the appropriate translation.
141CXSourceRange cxloc::translateSourceRange(const SourceManager &SM,
142 const LangOptions &LangOpts,
143 const CharSourceRange &R) {
144 // We want the last character in this location, so we will adjust the
145 // location accordingly.
146 SourceLocation EndLoc = R.getEnd();
147 if (EndLoc.isValid() && EndLoc.isMacroID() && !SM.isMacroArgExpansion(EndLoc))
148 EndLoc = SM.getExpansionRange(EndLoc).second;
149 if (R.isTokenRange() && EndLoc.isValid()) {
150 unsigned Length = Lexer::MeasureTokenLength(SM.getSpellingLoc(EndLoc),
151 SM, LangOpts);
152 EndLoc = EndLoc.getLocWithOffset(Length);
153 }
154
155 CXSourceRange Result = {
156 { &SM, &LangOpts },
157 R.getBegin().getRawEncoding(),
158 EndLoc.getRawEncoding()
159 };
160 return Result;
161}
162
163//===----------------------------------------------------------------------===//
164// Cursor visitor.
165//===----------------------------------------------------------------------===//
166
167static SourceRange getRawCursorExtent(CXCursor C);
168static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr);
169
170
171RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
172 return RangeCompare(AU->getSourceManager(), R, RegionOfInterest);
173}
174
175/// \brief Visit the given cursor and, if requested by the visitor,
176/// its children.
177///
178/// \param Cursor the cursor to visit.
179///
180/// \param CheckedRegionOfInterest if true, then the caller already checked
181/// that this cursor is within the region of interest.
182///
183/// \returns true if the visitation should be aborted, false if it
184/// should continue.
185bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
186 if (clang_isInvalid(Cursor.kind))
187 return false;
188
189 if (clang_isDeclaration(Cursor.kind)) {
190 const Decl *D = getCursorDecl(Cursor);
191 if (!D) {
192 assert(0 && "Invalid declaration cursor")((0 && "Invalid declaration cursor") ? static_cast<
void> (0) : __assert_fail ("0 && \"Invalid declaration cursor\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/tools/libclang/CIndex.cpp"
, 192, __PRETTY_FUNCTION__))
;
193 return true; // abort.
194 }
195
196 // Ignore implicit declarations, unless it's an objc method because
197 // currently we should report implicit methods for properties when indexing.
198 if (D->isImplicit() && !isa<ObjCMethodDecl>(D))
199 return false;
200 }
201
202 // If we have a range of interest, and this cursor doesn't intersect with it,
203 // we're done.
204 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
205 SourceRange Range = getRawCursorExtent(Cursor);
206 if (Range.isInvalid() || CompareRegionOfInterest(Range))
207 return false;
208 }
209
210 switch (Visitor(Cursor, Parent, ClientData)) {
211 case CXChildVisit_Break:
212 return true;
213
214 case CXChildVisit_Continue:
215 return false;
216
217 case CXChildVisit_Recurse: {
218 bool ret = VisitChildren(Cursor);
219 if (PostChildrenVisitor)
220 if (PostChildrenVisitor(Cursor, ClientData))
221 return true;
222 return ret;
223 }
224 }
225
226 llvm_unreachable("Invalid CXChildVisitResult!")::llvm::llvm_unreachable_internal("Invalid CXChildVisitResult!"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/tools/libclang/CIndex.cpp"
, 226)
;
227}
228
229static bool visitPreprocessedEntitiesInRange(SourceRange R,
230 PreprocessingRecord &PPRec,
231 CursorVisitor &Visitor) {
232 SourceManager &SM = Visitor.getASTUnit()->getSourceManager();
233 FileID FID;
234
235 if (!Visitor.shouldVisitIncludedEntities()) {
236 // If the begin/end of the range lie in the same FileID, do the optimization
237 // where we skip preprocessed entities that do not come from the same FileID.
238 FID = SM.getFileID(SM.getFileLoc(R.getBegin()));
239 if (FID != SM.getFileID(SM.getFileLoc(R.getEnd())))
240 FID = FileID();
241 }
242
243 const auto &Entities = PPRec.getPreprocessedEntitiesInRange(R);
244 return Visitor.visitPreprocessedEntities(Entities.begin(), Entities.end(),
245 PPRec, FID);
246}
247
248bool CursorVisitor::visitFileRegion() {
249 if (RegionOfInterest.isInvalid())
250 return false;
251
252 ASTUnit *Unit = cxtu::getASTUnit(TU);
253 SourceManager &SM = Unit->getSourceManager();
254
255 std::pair<FileID, unsigned>
256 Begin = SM.getDecomposedLoc(SM.getFileLoc(RegionOfInterest.getBegin())),
257 End = SM.getDecomposedLoc(SM.getFileLoc(RegionOfInterest.getEnd()));
258
259 if (End.first != Begin.first) {
260 // If the end does not reside in the same file, try to recover by
261 // picking the end of the file of begin location.
262 End.first = Begin.first;
263 End.second = SM.getFileIDSize(Begin.first);
264 }
265
266 assert(Begin.first == End.first)((Begin.first == End.first) ? static_cast<void> (0) : __assert_fail
("Begin.first == End.first", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/tools/libclang/CIndex.cpp"
, 266, __PRETTY_FUNCTION__))
;
267 if (Begin.second > End.second)
268 return false;
269
270 FileID File = Begin.first;
271 unsigned Offset = Begin.second;
272 unsigned Length = End.second - Begin.second;
273
274 if (!VisitDeclsOnly && !VisitPreprocessorLast)
275 if (visitPreprocessedEntitiesInRegion())
276 return true; // visitation break.
277
278 if (visitDeclsFromFileRegion(File, Offset, Length))
279 return true; // visitation break.
280
281 if (!VisitDeclsOnly && VisitPreprocessorLast)
282 return visitPreprocessedEntitiesInRegion();
283
284 return false;
285}
286
287static bool isInLexicalContext(Decl *D, DeclContext *DC) {
288 if (!DC)
289 return false;
290
291 for (DeclContext *DeclDC = D->getLexicalDeclContext();
292 DeclDC; DeclDC = DeclDC->getLexicalParent()) {
293 if (DeclDC == DC)
294 return true;
295 }
296 return false;
297}
298
299bool CursorVisitor::visitDeclsFromFileRegion(FileID File,
300 unsigned Offset, unsigned Length) {
301 ASTUnit *Unit = cxtu::getASTUnit(TU);
302 SourceManager &SM = Unit->getSourceManager();
303 SourceRange Range = RegionOfInterest;
304
305 SmallVector<Decl *, 16> Decls;
306 Unit->findFileRegionDecls(File, Offset, Length, Decls);
307
308 // If we didn't find any file level decls for the file, try looking at the
309 // file that it was included from.
310 while (Decls.empty() || Decls.front()->isTopLevelDeclInObjCContainer()) {
311 bool Invalid = false;
312 const SrcMgr::SLocEntry &SLEntry = SM.getSLocEntry(File, &Invalid);
313 if (Invalid)
314 return false;
315
316 SourceLocation Outer;
317 if (SLEntry.isFile())
318 Outer = SLEntry.getFile().getIncludeLoc();
319 else
320 Outer = SLEntry.getExpansion().getExpansionLocStart();
321 if (Outer.isInvalid())
322 return false;
323
324 std::tie(File, Offset) = SM.getDecomposedExpansionLoc(Outer);
325 Length = 0;
326 Unit->findFileRegionDecls(File, Offset, Length, Decls);
327 }
328
329 assert(!Decls.empty())((!Decls.empty()) ? static_cast<void> (0) : __assert_fail
("!Decls.empty()", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/tools/libclang/CIndex.cpp"
, 329, __PRETTY_FUNCTION__))
;
330
331 bool VisitedAtLeastOnce = false;
332 DeclContext *CurDC = nullptr;
333 SmallVectorImpl<Decl *>::iterator DIt = Decls.begin();
334 for (SmallVectorImpl<Decl *>::iterator DE = Decls.end(); DIt != DE; ++DIt) {
335 Decl *D = *DIt;
336 if (D->getSourceRange().isInvalid())
337 continue;
338
339 if (isInLexicalContext(D, CurDC))
340 continue;
341
342 CurDC = dyn_cast<DeclContext>(D);
343
344 if (TagDecl *TD = dyn_cast<TagDecl>(D))
345 if (!TD->isFreeStanding())
346 continue;
347
348 RangeComparisonResult CompRes = RangeCompare(SM, D->getSourceRange(),Range);
349 if (CompRes == RangeBefore)
350 continue;
351 if (CompRes == RangeAfter)
352 break;
353
354 assert(CompRes == RangeOverlap)((CompRes == RangeOverlap) ? static_cast<void> (0) : __assert_fail
("CompRes == RangeOverlap", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/tools/libclang/CIndex.cpp"
, 354, __PRETTY_FUNCTION__))
;
355 VisitedAtLeastOnce = true;
356
357 if (isa<ObjCContainerDecl>(D)) {
358 FileDI_current = &DIt;
359 FileDE_current = DE;
360 } else {
361 FileDI_current = nullptr;
362 }
363
364 if (Visit(MakeCXCursor(D, TU, Range), /*CheckedRegionOfInterest=*/true))
365 return true; // visitation break.
366 }
367
368 if (VisitedAtLeastOnce)
369 return false;
370
371 // No Decls overlapped with the range. Move up the lexical context until there
372 // is a context that contains the range or we reach the translation unit
373 // level.
374 DeclContext *DC = DIt == Decls.begin() ? (*DIt)->getLexicalDeclContext()
375 : (*(DIt-1))->getLexicalDeclContext();
376
377 while (DC && !DC->isTranslationUnit()) {
378 Decl *D = cast<Decl>(DC);
379 SourceRange CurDeclRange = D->getSourceRange();
380 if (CurDeclRange.isInvalid())
381 break;
382
383 if (RangeCompare(SM, CurDeclRange, Range) == RangeOverlap) {
384 if (Visit(MakeCXCursor(D, TU, Range), /*CheckedRegionOfInterest=*/true))
385 return true; // visitation break.
386 }
387
388 DC = D->getLexicalDeclContext();
389 }
390
391 return false;
392}
393
394bool CursorVisitor::visitPreprocessedEntitiesInRegion() {
395 if (!AU->getPreprocessor().getPreprocessingRecord())
396 return false;
397
398 PreprocessingRecord &PPRec
399 = *AU->getPreprocessor().getPreprocessingRecord();
400 SourceManager &SM = AU->getSourceManager();
401
402 if (RegionOfInterest.isValid()) {
403 SourceRange MappedRange = AU->mapRangeToPreamble(RegionOfInterest);
404 SourceLocation B = MappedRange.getBegin();
405 SourceLocation E = MappedRange.getEnd();
406
407 if (AU->isInPreambleFileID(B)) {
408 if (SM.isLoadedSourceLocation(E))
409 return visitPreprocessedEntitiesInRange(SourceRange(B, E),
410 PPRec, *this);
411
412 // Beginning of range lies in the preamble but it also extends beyond
413 // it into the main file. Split the range into 2 parts, one covering
414 // the preamble and another covering the main file. This allows subsequent
415 // calls to visitPreprocessedEntitiesInRange to accept a source range that
416 // lies in the same FileID, allowing it to skip preprocessed entities that
417 // do not come from the same FileID.
418 bool breaked =
419 visitPreprocessedEntitiesInRange(
420 SourceRange(B, AU->getEndOfPreambleFileID()),
421 PPRec, *this);
422 if (breaked) return true;
423 return visitPreprocessedEntitiesInRange(
424 SourceRange(AU->getStartOfMainFileID(), E),
425 PPRec, *this);
426 }
427
428 return visitPreprocessedEntitiesInRange(SourceRange(B, E), PPRec, *this);
429 }
430
431 bool OnlyLocalDecls
432 = !AU->isMainFileAST() && AU->getOnlyLocalDecls();
433
434 if (OnlyLocalDecls)
435 return visitPreprocessedEntities(PPRec.local_begin(), PPRec.local_end(),
436 PPRec);
437
438 return visitPreprocessedEntities(PPRec.begin(), PPRec.end(), PPRec);
439}
440
441template<typename InputIterator>
442bool CursorVisitor::visitPreprocessedEntities(InputIterator First,
443 InputIterator Last,
444 PreprocessingRecord &PPRec,
445 FileID FID) {
446 for (; First != Last; ++First) {
447 if (!FID.isInvalid() && !PPRec.isEntityInFileID(First, FID))
448 continue;
449
450 PreprocessedEntity *PPE = *First;
451 if (!PPE)
452 continue;
453
454 if (MacroExpansion *ME = dyn_cast<MacroExpansion>(PPE)) {
455 if (Visit(MakeMacroExpansionCursor(ME, TU)))
456 return true;
457
458 continue;
459 }
460
461 if (MacroDefinitionRecord *MD = dyn_cast<MacroDefinitionRecord>(PPE)) {
462 if (Visit(MakeMacroDefinitionCursor(MD, TU)))
463 return true;
464
465 continue;
466 }
467
468 if (InclusionDirective *ID = dyn_cast<InclusionDirective>(PPE)) {
469 if (Visit(MakeInclusionDirectiveCursor(ID, TU)))
470 return true;
471
472 continue;
473 }
474 }
475
476 return false;
477}
478
479/// \brief Visit the children of the given cursor.
480///
481/// \returns true if the visitation should be aborted, false if it
482/// should continue.
483bool CursorVisitor::VisitChildren(CXCursor Cursor) {
484 if (clang_isReference(Cursor.kind) &&
485 Cursor.kind != CXCursor_CXXBaseSpecifier) {
486 // By definition, references have no children.
487 return false;
488 }
489
490 // Set the Parent field to Cursor, then back to its old value once we're
491 // done.
492 SetParentRAII SetParent(Parent, StmtParent, Cursor);
493
494 if (clang_isDeclaration(Cursor.kind)) {
495 Decl *D = const_cast<Decl *>(getCursorDecl(Cursor));
496 if (!D)
497 return false;
498
499 return VisitAttributes(D) || Visit(D);
500 }
501
502 if (clang_isStatement(Cursor.kind)) {
503 if (const Stmt *S = getCursorStmt(Cursor))
504 return Visit(S);
505
506 return false;
507 }
508
509 if (clang_isExpression(Cursor.kind)) {
510 if (const Expr *E = getCursorExpr(Cursor))
511 return Visit(E);
512
513 return false;
514 }
515
516 if (clang_isTranslationUnit(Cursor.kind)) {
517 CXTranslationUnit TU = getCursorTU(Cursor);
518 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
519
520 int VisitOrder[2] = { VisitPreprocessorLast, !VisitPreprocessorLast };
521 for (unsigned I = 0; I != 2; ++I) {
522 if (VisitOrder[I]) {
523 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
524 RegionOfInterest.isInvalid()) {
525 for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
526 TLEnd = CXXUnit->top_level_end();
527 TL != TLEnd; ++TL) {
528 const Optional<bool> V = handleDeclForVisitation(*TL);
529 if (!V.hasValue())
530 continue;
531 return V.getValue();
532 }
533 } else if (VisitDeclContext(
534 CXXUnit->getASTContext().getTranslationUnitDecl()))
535 return true;
536 continue;
537 }
538
539 // Walk the preprocessing record.
540 if (CXXUnit->getPreprocessor().getPreprocessingRecord())
541 visitPreprocessedEntitiesInRegion();
542 }
543
544 return false;
545 }
546
547 if (Cursor.kind == CXCursor_CXXBaseSpecifier) {
548 if (const CXXBaseSpecifier *Base = getCursorCXXBaseSpecifier(Cursor)) {
549 if (TypeSourceInfo *BaseTSInfo = Base->getTypeSourceInfo()) {
550 return Visit(BaseTSInfo->getTypeLoc());
551 }
552 }
553 }
554
555 if (Cursor.kind == CXCursor_IBOutletCollectionAttr) {
556 const IBOutletCollectionAttr *A =
557 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(Cursor));
558 if (const ObjCObjectType *ObjT = A->getInterface()->getAs<ObjCObjectType>())
559 return Visit(cxcursor::MakeCursorObjCClassRef(
560 ObjT->getInterface(),
561 A->getInterfaceLoc()->getTypeLoc().getLocStart(), TU));
562 }
563
564 // If pointing inside a macro definition, check if the token is an identifier
565 // that was ever defined as a macro. In such a case, create a "pseudo" macro
566 // expansion cursor for that token.
567 SourceLocation BeginLoc = RegionOfInterest.getBegin();
568 if (Cursor.kind == CXCursor_MacroDefinition &&
569 BeginLoc == RegionOfInterest.getEnd()) {
570 SourceLocation Loc = AU->mapLocationToPreamble(BeginLoc);
571 const MacroInfo *MI =
572 getMacroInfo(cxcursor::getCursorMacroDefinition(Cursor), TU);
573 if (MacroDefinitionRecord *MacroDef =
574 checkForMacroInMacroDefinition(MI, Loc, TU))
575 return Visit(cxcursor::MakeMacroExpansionCursor(MacroDef, BeginLoc, TU));
576 }
577
578 // Nothing to visit at the moment.
579 return false;
580}
581
582bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
583 if (TypeSourceInfo *TSInfo = B->getSignatureAsWritten())
584 if (Visit(TSInfo->getTypeLoc()))
585 return true;
586
587 if (Stmt *Body = B->getBody())
588 return Visit(MakeCXCursor(Body, StmtParent, TU, RegionOfInterest));
589
590 return false;
591}
592
593Optional<bool> CursorVisitor::shouldVisitCursor(CXCursor Cursor) {
594 if (RegionOfInterest.isValid()) {
595 SourceRange Range = getFullCursorExtent(Cursor, AU->getSourceManager());
596 if (Range.isInvalid())
597 return None;
598
599 switch (CompareRegionOfInterest(Range)) {
600 case RangeBefore:
601 // This declaration comes before the region of interest; skip it.
602 return None;
603
604 case RangeAfter:
605 // This declaration comes after the region of interest; we're done.
606 return false;
607
608 case RangeOverlap:
609 // This declaration overlaps the region of interest; visit it.
610 break;
611 }
612 }
613 return true;
614}
615
616bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
617 DeclContext::decl_iterator I = DC->decls_begin(), E = DC->decls_end();
618
619 // FIXME: Eventually remove. This part of a hack to support proper
620 // iteration over all Decls contained lexically within an ObjC container.
621 SaveAndRestore<DeclContext::decl_iterator*> DI_saved(DI_current, &I);
622 SaveAndRestore<DeclContext::decl_iterator> DE_saved(DE_current, E);
623
624 for ( ; I != E; ++I) {
625 Decl *D = *I;
626 if (D->getLexicalDeclContext() != DC)
627 continue;
628 const Optional<bool> V = handleDeclForVisitation(D);
629 if (!V.hasValue())
630 continue;
631 return V.getValue();
632 }
633 return false;
634}
635
636Optional<bool> CursorVisitor::handleDeclForVisitation(const Decl *D) {
637 CXCursor Cursor = MakeCXCursor(D, TU, RegionOfInterest);
638
639 // Ignore synthesized ivars here, otherwise if we have something like:
640 // @synthesize prop = _prop;
641 // and '_prop' is not declared, we will encounter a '_prop' ivar before
642 // encountering the 'prop' synthesize declaration and we will think that
643 // we passed the region-of-interest.
644 if (auto *ivarD = dyn_cast<ObjCIvarDecl>(D)) {
645 if (ivarD->getSynthesize())
646 return None;
647 }
648
649 // FIXME: ObjCClassRef/ObjCProtocolRef for forward class/protocol
650 // declarations is a mismatch with the compiler semantics.
651 if (Cursor.kind == CXCursor_ObjCInterfaceDecl) {
652 auto *ID = cast<ObjCInterfaceDecl>(D);
653 if (!ID->isThisDeclarationADefinition())
654 Cursor = MakeCursorObjCClassRef(ID, ID->getLocation(), TU);
655
656 } else if (Cursor.kind == CXCursor_ObjCProtocolDecl) {
657 auto *PD = cast<ObjCProtocolDecl>(D);
658 if (!PD->isThisDeclarationADefinition())
659 Cursor = MakeCursorObjCProtocolRef(PD, PD->getLocation(), TU);
660 }
661
662 const Optional<bool> V = shouldVisitCursor(Cursor);
663 if (!V.hasValue())
664 return None;
665 if (!V.getValue())
666 return false;
667 if (Visit(Cursor, true))
668 return true;
669 return None;
670}
671
672bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
673 llvm_unreachable("Translation units are visited directly by Visit()")::llvm::llvm_unreachable_internal("Translation units are visited directly by Visit()"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/tools/libclang/CIndex.cpp"
, 673)
;
674}
675
676bool CursorVisitor::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
677 if (VisitTemplateParameters(D->getTemplateParameters()))
678 return true;
679
680 return Visit(MakeCXCursor(D->getTemplatedDecl(), TU, RegionOfInterest));
681}
682
683bool CursorVisitor::VisitTypeAliasDecl(TypeAliasDecl *D) {
684 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
685 return Visit(TSInfo->getTypeLoc());
686
687 return false;
688}
689
690bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
691 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
692 return Visit(TSInfo->getTypeLoc());
693
694 return false;
695}
696
697bool CursorVisitor::VisitTagDecl(TagDecl *D) {
698 return VisitDeclContext(D);
699}
700
701bool CursorVisitor::VisitClassTemplateSpecializationDecl(
702 ClassTemplateSpecializationDecl *D) {
703 bool ShouldVisitBody = false;
704 switch (D->getSpecializationKind()) {
705 case TSK_Undeclared:
706 case TSK_ImplicitInstantiation:
707 // Nothing to visit
708 return false;
709
710 case TSK_ExplicitInstantiationDeclaration:
711 case TSK_ExplicitInstantiationDefinition:
712 break;
713
714 case TSK_ExplicitSpecialization:
715 ShouldVisitBody = true;
716 break;
717 }
718
719 // Visit the template arguments used in the specialization.
720 if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) {
721 TypeLoc TL = SpecType->getTypeLoc();
722 if (TemplateSpecializationTypeLoc TSTLoc =
723 TL.getAs<TemplateSpecializationTypeLoc>()) {
724 for (unsigned I = 0, N = TSTLoc.getNumArgs(); I != N; ++I)
725 if (VisitTemplateArgumentLoc(TSTLoc.getArgLoc(I)))
726 return true;
727 }
728 }
729
730 return ShouldVisitBody && VisitCXXRecordDecl(D);
731}
732
733bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl(
734 ClassTemplatePartialSpecializationDecl *D) {
735 // FIXME: Visit the "outer" template parameter lists on the TagDecl
736 // before visiting these template parameters.
737 if (VisitTemplateParameters(D->getTemplateParameters()))
738 return true;
739
740 // Visit the partial specialization arguments.
741 const ASTTemplateArgumentListInfo *Info = D->getTemplateArgsAsWritten();
742 const TemplateArgumentLoc *TemplateArgs = Info->getTemplateArgs();
743 for (unsigned I = 0, N = Info->NumTemplateArgs; I != N; ++I)
744 if (VisitTemplateArgumentLoc(TemplateArgs[I]))
745 return true;
746
747 return VisitCXXRecordDecl(D);
748}
749
750bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
751 // Visit the default argument.
752 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
753 if (TypeSourceInfo *DefArg = D->getDefaultArgumentInfo())
754 if (Visit(DefArg->getTypeLoc()))
755 return true;
756
757 return false;
758}
759
760bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
761 if (Expr *Init = D->getInitExpr())
762 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
763 return false;
764}
765
766bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
767 unsigned NumParamList = DD->getNumTemplateParameterLists();
768 for (unsigned i = 0; i < NumParamList; i++) {
769 TemplateParameterList* Params = DD->getTemplateParameterList(i);
770 if (VisitTemplateParameters(Params))
771 return true;
772 }
773
774 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
775 if (Visit(TSInfo->getTypeLoc()))
776 return true;
777
778 // Visit the nested-name-specifier, if present.
779 if (NestedNameSpecifierLoc QualifierLoc = DD->getQualifierLoc())
780 if (VisitNestedNameSpecifierLoc(QualifierLoc))
781 return true;
782
783 return false;
784}
785
786/// \brief Compare two base or member initializers based on their source order.
787static int CompareCXXCtorInitializers(CXXCtorInitializer *const *X,
788 CXXCtorInitializer *const *Y) {
789 return (*X)->getSourceOrder() - (*Y)->getSourceOrder();
790}
791
792bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
793 unsigned NumParamList = ND->getNumTemplateParameterLists();
794 for (unsigned i = 0; i < NumParamList; i++) {
795 TemplateParameterList* Params = ND->getTemplateParameterList(i);
796 if (VisitTemplateParameters(Params))
797 return true;
798 }
799
800 if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
801 // Visit the function declaration's syntactic components in the order
802 // written. This requires a bit of work.
803 TypeLoc TL = TSInfo->getTypeLoc().IgnoreParens();
804 FunctionTypeLoc FTL = TL.getAs<FunctionTypeLoc>();
805
806 // If we have a function declared directly (without the use of a typedef),
807 // visit just the return type. Otherwise, just visit the function's type
808 // now.
809 if ((FTL && !isa<CXXConversionDecl>(ND) && Visit(FTL.getReturnLoc())) ||
810 (!FTL && Visit(TL)))
811 return true;
812
813 // Visit the nested-name-specifier, if present.
814 if (NestedNameSpecifierLoc QualifierLoc = ND->getQualifierLoc())
815 if (VisitNestedNameSpecifierLoc(QualifierLoc))
816 return true;
817
818 // Visit the declaration name.
819 if (!isa<CXXDestructorDecl>(ND))
820 if (VisitDeclarationNameInfo(ND->getNameInfo()))
821 return true;
822
823 // FIXME: Visit explicitly-specified template arguments!
824
825 // Visit the function parameters, if we have a function type.
826 if (FTL && VisitFunctionTypeLoc(FTL, true))
827 return true;
828
829 // FIXME: Attributes?
830 }
831
832 if (ND->doesThisDeclarationHaveABody() && !ND->isLateTemplateParsed()) {
833 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ND)) {
834 // Find the initializers that were written in the source.
835 SmallVector<CXXCtorInitializer *, 4> WrittenInits;
836 for (auto *I : Constructor->inits()) {
837 if (!I->isWritten())
838 continue;
839
840 WrittenInits.push_back(I);
841 }
842
843 // Sort the initializers in source order
844 llvm::array_pod_sort(WrittenInits.begin(), WrittenInits.end(),
845 &CompareCXXCtorInitializers);
846
847 // Visit the initializers in source order
848 for (unsigned I = 0, N = WrittenInits.size(); I != N; ++I) {
849 CXXCtorInitializer *Init = WrittenInits[I];
850 if (Init->isAnyMemberInitializer()) {
851 if (Visit(MakeCursorMemberRef(Init->getAnyMember(),
852 Init->getMemberLocation(), TU)))
853 return true;
854 } else if (TypeSourceInfo *TInfo = Init->getTypeSourceInfo()) {
855 if (Visit(TInfo->getTypeLoc()))
856 return true;
857 }
858
859 // Visit the initializer value.
860 if (Expr *Initializer = Init->getInit())
861 if (Visit(MakeCXCursor(Initializer, ND, TU, RegionOfInterest)))
862 return true;
863 }
864 }
865
866 if (Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest)))
867 return true;
868 }
869
870 return false;
871}
872
873bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
874 if (VisitDeclaratorDecl(D))
875 return true;
876
877 if (Expr *BitWidth = D->getBitWidth())
878 return Visit(MakeCXCursor(BitWidth, StmtParent, TU, RegionOfInterest));
879
880 return false;
881}
882
883bool CursorVisitor::VisitVarDecl(VarDecl *D) {
884 if (VisitDeclaratorDecl(D))
885 return true;
886
887 if (Expr *Init = D->getInit())
888 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
889
890 return false;
891}
892
893bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
894 if (VisitDeclaratorDecl(D))
895 return true;
896
897 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
898 if (Expr *DefArg = D->getDefaultArgument())
899 return Visit(MakeCXCursor(DefArg, StmtParent, TU, RegionOfInterest));
900
901 return false;
902}
903
904bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
905 // FIXME: Visit the "outer" template parameter lists on the FunctionDecl
906 // before visiting these template parameters.
907 if (VisitTemplateParameters(D->getTemplateParameters()))
908 return true;
909
910 return VisitFunctionDecl(D->getTemplatedDecl());
911}
912
913bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) {
914 // FIXME: Visit the "outer" template parameter lists on the TagDecl
915 // before visiting these template parameters.
916 if (VisitTemplateParameters(D->getTemplateParameters()))
917 return true;
918
919 return VisitCXXRecordDecl(D->getTemplatedDecl());
920}
921
922bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
923 if (VisitTemplateParameters(D->getTemplateParameters()))
924 return true;
925
926 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() &&
927 VisitTemplateArgumentLoc(D->getDefaultArgument()))
928 return true;
929
930 return false;
931}
932
933bool CursorVisitor::VisitObjCTypeParamDecl(ObjCTypeParamDecl *D) {
934 // Visit the bound, if it's explicit.
935 if (D->hasExplicitBound()) {
936 if (auto TInfo = D->getTypeSourceInfo()) {
937 if (Visit(TInfo->getTypeLoc()))
938 return true;
939 }
940 }
941
942 return false;
943}
944
945bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
946 if (TypeSourceInfo *TSInfo = ND->getReturnTypeSourceInfo())
947 if (Visit(TSInfo->getTypeLoc()))
948 return true;
949
950 for (const auto *P : ND->parameters()) {
951 if (Visit(MakeCXCursor(P, TU, RegionOfInterest)))
952 return true;
953 }
954
955 return ND->isThisDeclarationADefinition() &&
956 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest));
957}
958
959template <typename DeclIt>
960static void addRangedDeclsInContainer(DeclIt *DI_current, DeclIt DE_current,
961 SourceManager &SM, SourceLocation EndLoc,
962 SmallVectorImpl<Decl *> &Decls) {
963 DeclIt next = *DI_current;
964 while (++next != DE_current) {
965 Decl *D_next = *next;
966 if (!D_next)
967 break;
968 SourceLocation L = D_next->getLocStart();
969 if (!L.isValid())
970 break;
971 if (SM.isBeforeInTranslationUnit(L, EndLoc)) {
972 *DI_current = next;
973 Decls.push_back(D_next);
974 continue;
975 }
976 break;
977 }
978}
979
980bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
981 // FIXME: Eventually convert back to just 'VisitDeclContext()'. Essentially
982 // an @implementation can lexically contain Decls that are not properly
983 // nested in the AST. When we identify such cases, we need to retrofit
984 // this nesting here.
985 if (!DI_current && !FileDI_current)
986 return VisitDeclContext(D);
987
988 // Scan the Decls that immediately come after the container
989 // in the current DeclContext. If any fall within the
990 // container's lexical region, stash them into a vector
991 // for later processing.
992 SmallVector<Decl *, 24> DeclsInContainer;
993 SourceLocation EndLoc = D->getSourceRange().getEnd();
994 SourceManager &SM = AU->getSourceManager();
995 if (EndLoc.isValid()) {
996 if (DI_current) {
997 addRangedDeclsInContainer(DI_current, DE_current, SM, EndLoc,
998 DeclsInContainer);
999 } else {
1000 addRangedDeclsInContainer(FileDI_current, FileDE_current, SM, EndLoc,
1001 DeclsInContainer);
1002 }
1003 }
1004
1005 // The common case.
1006 if (DeclsInContainer.empty())
1007 return VisitDeclContext(D);
1008
1009 // Get all the Decls in the DeclContext, and sort them with the
1010 // additional ones we've collected. Then visit them.
1011 for (auto *SubDecl : D->decls()) {
1012 if (!SubDecl || SubDecl->getLexicalDeclContext() != D ||
1013 SubDecl->getLocStart().isInvalid())
1014 continue;
1015 DeclsInContainer.push_back(SubDecl);
1016 }
1017
1018 // Now sort the Decls so that they appear in lexical order.
1019 std::sort(DeclsInContainer.begin(), DeclsInContainer.end(),
1020 [&SM](Decl *A, Decl *B) {
1021 SourceLocation L_A = A->getLocStart();
1022 SourceLocation L_B = B->getLocStart();
1023 assert(L_A.isValid() && L_B.isValid())((L_A.isValid() && L_B.isValid()) ? static_cast<void
> (0) : __assert_fail ("L_A.isValid() && L_B.isValid()"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/tools/libclang/CIndex.cpp"
, 1023, __PRETTY_FUNCTION__))
;
1024 return SM.isBeforeInTranslationUnit(L_A, L_B);
1025 });
1026
1027 // Now visit the decls.
1028 for (SmallVectorImpl<Decl*>::iterator I = DeclsInContainer.begin(),
1029 E = DeclsInContainer.end(); I != E; ++I) {
1030 CXCursor Cursor = MakeCXCursor(*I, TU, RegionOfInterest);
1031 const Optional<bool> &V = shouldVisitCursor(Cursor);
1032 if (!V.hasValue())
1033 continue;
1034 if (!V.getValue())
1035 return false;
1036 if (Visit(Cursor, true))
1037 return true;
1038 }
1039 return false;
1040}
1041
1042bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
1043 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
1044 TU)))
1045 return true;
1046
1047 if (VisitObjCTypeParamList(ND->getTypeParamList()))
1048 return true;
1049
1050 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
1051 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
1052 E = ND->protocol_end(); I != E; ++I, ++PL)
1053 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
1054 return true;
1055
1056 return VisitObjCContainerDecl(ND);
1057}
1058
1059bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
1060 if (!PID->isThisDeclarationADefinition())
1061 return Visit(MakeCursorObjCProtocolRef(PID, PID->getLocation(), TU));
1062
1063 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
1064 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
1065 E = PID->protocol_end(); I != E; ++I, ++PL)
1066 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
1067 return true;
1068
1069 return VisitObjCContainerDecl(PID);
1070}
1071
1072bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
1073 if (PD->getTypeSourceInfo() && Visit(PD->getTypeSourceInfo()->getTypeLoc()))
1074 return true;
1075
1076 // FIXME: This implements a workaround with @property declarations also being
1077 // installed in the DeclContext for the @interface. Eventually this code
1078 // should be removed.
1079 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
1080 if (!CDecl || !CDecl->IsClassExtension())
1081 return false;
1082
1083 ObjCInterfaceDecl *ID = CDecl->getClassInterface();
1084 if (!ID)
1085 return false;
1086
1087 IdentifierInfo *PropertyId = PD->getIdentifier();
1088 ObjCPropertyDecl *prevDecl =
1089 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId,
1090 PD->getQueryKind());
1091
1092 if (!prevDecl)
1093 return false;
1094
1095 // Visit synthesized methods since they will be skipped when visiting
1096 // the @interface.
1097 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
1098 if (MD->isPropertyAccessor() && MD->getLexicalDeclContext() == CDecl)
1099 if (Visit(MakeCXCursor(MD, TU, RegionOfInterest)))
1100 return true;
1101
1102 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
1103 if (MD->isPropertyAccessor() && MD->getLexicalDeclContext() == CDecl)
1104 if (Visit(MakeCXCursor(MD, TU, RegionOfInterest)))
1105 return true;
1106
1107 return false;
1108}
1109
1110bool CursorVisitor::VisitObjCTypeParamList(ObjCTypeParamList *typeParamList) {
1111 if (!typeParamList)
1112 return false;
1113
1114 for (auto *typeParam : *typeParamList) {
1115 // Visit the type parameter.
1116 if (Visit(MakeCXCursor(typeParam, TU, RegionOfInterest)))
1117 return true;
1118 }
1119
1120 return false;
1121}
1122
1123bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
1124 if (!D->isThisDeclarationADefinition()) {
1125 // Forward declaration is treated like a reference.
1126 return Visit(MakeCursorObjCClassRef(D, D->getLocation(), TU));
1127 }
1128
1129 // Objective-C type parameters.
1130 if (VisitObjCTypeParamList(D->getTypeParamListAsWritten()))
1131 return true;
1132
1133 // Issue callbacks for super class.
1134 if (D->getSuperClass() &&
1135 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
1136 D->getSuperClassLoc(),
1137 TU)))
1138 return true;
1139
1140 if (TypeSourceInfo *SuperClassTInfo = D->getSuperClassTInfo())
1141 if (Visit(SuperClassTInfo->getTypeLoc()))
1142 return true;
1143
1144 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1145 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
1146 E = D->protocol_end(); I != E; ++I, ++PL)
1147 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
1148 return true;
1149
1150 return VisitObjCContainerDecl(D);
1151}
1152
1153bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
1154 return VisitObjCContainerDecl(D);
1155}
1156
1157bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
1158 // 'ID' could be null when dealing with invalid code.
1159 if (ObjCInterfaceDecl *ID = D->getClassInterface())
1160 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
1161 return true;
1162
1163 return VisitObjCImplDecl(D);
1164}
1165
1166bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
1167#if 0
1168 // Issue callbacks for super class.
1169 // FIXME: No source location information!
1170 if (D->getSuperClass() &&
1171 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
1172 D->getSuperClassLoc(),
1173 TU)))
1174 return true;
1175#endif
1176
1177 return VisitObjCImplDecl(D);
1178}
1179
1180bool CursorVisitor::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *PD) {
1181 if (ObjCIvarDecl *Ivar = PD->getPropertyIvarDecl())
1182 if (PD->isIvarNameSpecified())
1183 return Visit(MakeCursorMemberRef(Ivar, PD->getPropertyIvarDeclLoc(), TU));
1184
1185 return false;
1186}
1187
1188bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
1189 return VisitDeclContext(D);
1190}
1191
1192bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
1193 // Visit nested-name-specifier.
1194 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1195 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1196 return true;
1197
1198 return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(),
1199 D->getTargetNameLoc(), TU));
1200}
1201
1202bool CursorVisitor::VisitUsingDecl(UsingDecl *D) {
1203 // Visit nested-name-specifier.
1204 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1205 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1206 return true;
1207 }
1208
1209 if (Visit(MakeCursorOverloadedDeclRef(D, D->getLocation(), TU)))
1210 return true;
1211
1212 return VisitDeclarationNameInfo(D->getNameInfo());
1213}
1214
1215bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
1216 // Visit nested-name-specifier.
1217 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1218 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1219 return true;
1220
1221 return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(),
1222 D->getIdentLocation(), TU));
1223}
1224
1225bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
1226 // Visit nested-name-specifier.
1227 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1228 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1229 return true;
1230 }
1231
1232 return VisitDeclarationNameInfo(D->getNameInfo());
1233}
1234
1235bool CursorVisitor::VisitUnresolvedUsingTypenameDecl(
1236 UnresolvedUsingTypenameDecl *D) {
1237 // Visit nested-name-specifier.
1238 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1239 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1240 return true;
1241
1242 return false;
1243}
1244
1245bool CursorVisitor::VisitStaticAssertDecl(StaticAssertDecl *D) {
1246 if (Visit(MakeCXCursor(D->getAssertExpr(), StmtParent, TU, RegionOfInterest)))
1247 return true;
1248 if (StringLiteral *Message = D->getMessage())
1249 if (Visit(MakeCXCursor(Message, StmtParent, TU, RegionOfInterest)))
1250 return true;
1251 return false;
1252}
1253
1254bool CursorVisitor::VisitFriendDecl(FriendDecl *D) {
1255 if (NamedDecl *FriendD = D->getFriendDecl()) {
1256 if (Visit(MakeCXCursor(FriendD, TU, RegionOfInterest)))
1257 return true;
1258 } else if (TypeSourceInfo *TI = D->getFriendType()) {
1259 if (Visit(TI->getTypeLoc()))
1260 return true;
1261 }
1262 return false;
1263}
1264
1265bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
1266 switch (Name.getName().getNameKind()) {
1267 case clang::DeclarationName::Identifier:
1268 case clang::DeclarationName::CXXLiteralOperatorName:
1269 case clang::DeclarationName::CXXDeductionGuideName:
1270 case clang::DeclarationName::CXXOperatorName:
1271 case clang::DeclarationName::CXXUsingDirective:
1272 return false;
1273
1274 case clang::DeclarationName::CXXConstructorName:
1275 case clang::DeclarationName::CXXDestructorName:
1276 case clang::DeclarationName::CXXConversionFunctionName:
1277 if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
1278 return Visit(TSInfo->getTypeLoc());
1279 return false;
1280
1281 case clang::DeclarationName::ObjCZeroArgSelector:
1282 case clang::DeclarationName::ObjCOneArgSelector:
1283 case clang::DeclarationName::ObjCMultiArgSelector:
1284 // FIXME: Per-identifier location info?
1285 return false;
1286 }
1287
1288 llvm_unreachable("Invalid DeclarationName::Kind!")::llvm::llvm_unreachable_internal("Invalid DeclarationName::Kind!"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/tools/libclang/CIndex.cpp"
, 1288)
;
1289}
1290
1291bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS,
1292 SourceRange Range) {
1293 // FIXME: This whole routine is a hack to work around the lack of proper
1294 // source information in nested-name-specifiers (PR5791). Since we do have
1295 // a beginning source location, we can visit the first component of the
1296 // nested-name-specifier, if it's a single-token component.
1297 if (!NNS)
1298 return false;
1299
1300 // Get the first component in the nested-name-specifier.
1301 while (NestedNameSpecifier *Prefix = NNS->getPrefix())
1302 NNS = Prefix;
1303
1304 switch (NNS->getKind()) {
1305 case NestedNameSpecifier::Namespace:
1306 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(),
1307 TU));
1308
1309 case NestedNameSpecifier::NamespaceAlias:
1310 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
1311 Range.getBegin(), TU));
1312
1313 case NestedNameSpecifier::TypeSpec: {
1314 // If the type has a form where we know that the beginning of the source
1315 // range matches up with a reference cursor. Visit the appropriate reference
1316 // cursor.
1317 const Type *T = NNS->getAsType();
1318 if (const TypedefType *Typedef = dyn_cast<TypedefType>(T))
1319 return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU));
1320 if (const TagType *Tag = dyn_cast<TagType>(T))
1321 return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU));
1322 if (const TemplateSpecializationType *TST
1323 = dyn_cast<TemplateSpecializationType>(T))
1324 return VisitTemplateName(TST->getTemplateName(), Range.getBegin());
1325 break;
1326 }
1327
1328 case NestedNameSpecifier::TypeSpecWithTemplate:
1329 case NestedNameSpecifier::Global:
1330 case NestedNameSpecifier::Identifier:
1331 case NestedNameSpecifier::Super:
1332 break;
1333 }
1334
1335 return false;
1336}
1337
1338bool
1339CursorVisitor::VisitNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
1340 SmallVector<NestedNameSpecifierLoc, 4> Qualifiers;
1341 for (; Qualifier; Qualifier = Qualifier.getPrefix())
1342 Qualifiers.push_back(Qualifier);
1343
1344 while (!Qualifiers.empty()) {
1345 NestedNameSpecifierLoc Q = Qualifiers.pop_back_val();
1346 NestedNameSpecifier *NNS = Q.getNestedNameSpecifier();
1347 switch (NNS->getKind()) {
1348 case NestedNameSpecifier::Namespace:
1349 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(),
1350 Q.getLocalBeginLoc(),
1351 TU)))
1352 return true;
1353
1354 break;
1355
1356 case NestedNameSpecifier::NamespaceAlias:
1357 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
1358 Q.getLocalBeginLoc(),
1359 TU)))
1360 return true;
1361
1362 break;
1363
1364 case NestedNameSpecifier::TypeSpec:
1365 case NestedNameSpecifier::TypeSpecWithTemplate:
1366 if (Visit(Q.getTypeLoc()))
1367 return true;
1368
1369 break;
1370
1371 case NestedNameSpecifier::Global:
1372 case NestedNameSpecifier::Identifier:
1373 case NestedNameSpecifier::Super:
1374 break;
1375 }
1376 }
1377
1378 return false;
1379}
1380
1381bool CursorVisitor::VisitTemplateParameters(
1382 const TemplateParameterList *Params) {
1383 if (!Params)
1384 return false;
1385
1386 for (TemplateParameterList::const_iterator P = Params->begin(),
1387 PEnd = Params->end();
1388 P != PEnd; ++P) {
1389 if (Visit(MakeCXCursor(*P, TU, RegionOfInterest)))
1390 return true;
1391 }
1392
1393 return false;
1394}
1395
1396bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) {
1397 switch (Name.getKind()) {
1398 case TemplateName::Template:
1399 return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
1400
1401 case TemplateName::OverloadedTemplate:
1402 // Visit the overloaded template set.
1403 if (Visit(MakeCursorOverloadedDeclRef(Name, Loc, TU)))
1404 return true;
1405
1406 return false;
1407
1408 case TemplateName::DependentTemplate:
1409 // FIXME: Visit nested-name-specifier.
1410 return false;
1411
1412 case TemplateName::QualifiedTemplate:
1413 // FIXME: Visit nested-name-specifier.
1414 return Visit(MakeCursorTemplateRef(
1415 Name.getAsQualifiedTemplateName()->getDecl(),
1416 Loc, TU));
1417
1418 case TemplateName::SubstTemplateTemplateParm:
1419 return Visit(MakeCursorTemplateRef(
1420 Name.getAsSubstTemplateTemplateParm()->getParameter(),
1421 Loc, TU));
1422
1423 case TemplateName::SubstTemplateTemplateParmPack:
1424 return Visit(MakeCursorTemplateRef(
1425 Name.getAsSubstTemplateTemplateParmPack()->getParameterPack(),
1426 Loc, TU));
1427 }
1428
1429 llvm_unreachable("Invalid TemplateName::Kind!")::llvm::llvm_unreachable_internal("Invalid TemplateName::Kind!"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/tools/libclang/CIndex.cpp"
, 1429)
;
1430}
1431
1432bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
1433 switch (TAL.getArgument().getKind()) {
1434 case TemplateArgument::Null:
1435 case TemplateArgument::Integral:
1436 case TemplateArgument::Pack:
1437 return false;
1438
1439 case TemplateArgument::Type:
1440 if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
1441 return Visit(TSInfo->getTypeLoc());
1442 return false;
1443
1444 case TemplateArgument::Declaration:
1445 if (Expr *E = TAL.getSourceDeclExpression())
1446 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
1447 return false;
1448
1449 case TemplateArgument::NullPtr:
1450 if (Expr *E = TAL.getSourceNullPtrExpression())
1451 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
1452 return false;
1453
1454 case TemplateArgument::Expression:
1455 if (Expr *E = TAL.getSourceExpression())
1456 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
1457 return false;
1458
1459 case TemplateArgument::Template:
1460 case TemplateArgument::TemplateExpansion:
1461 if (VisitNestedNameSpecifierLoc(TAL.getTemplateQualifierLoc()))
1462 return true;
1463
1464 return VisitTemplateName(TAL.getArgument().getAsTemplateOrTemplatePattern(),
1465 TAL.getTemplateNameLoc());
1466 }
1467
1468 llvm_unreachable("Invalid TemplateArgument::Kind!")::llvm::llvm_unreachable_internal("Invalid TemplateArgument::Kind!"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/tools/libclang/CIndex.cpp"
, 1468)
;
1469}
1470
1471bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1472 return VisitDeclContext(D);
1473}
1474
1475bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1476 return Visit(TL.getUnqualifiedLoc());
1477}
1478
1479bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
1480 ASTContext &Context = AU->getASTContext();
1481
1482 // Some builtin types (such as Objective-C's "id", "sel", and
1483 // "Class") have associated declarations. Create cursors for those.
1484 QualType VisitType;
1485 switch (TL.getTypePtr()->getKind()) {
1486
1487 case BuiltinType::Void:
1488 case BuiltinType::NullPtr:
1489 case BuiltinType::Dependent:
1490#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1491 case BuiltinType::Id:
1492#include "clang/Basic/OpenCLImageTypes.def"
1493 case BuiltinType::OCLSampler:
1494 case BuiltinType::OCLEvent:
1495 case BuiltinType::OCLClkEvent:
1496 case BuiltinType::OCLQueue:
1497 case BuiltinType::OCLReserveID:
1498#define BUILTIN_TYPE(Id, SingletonId)
1499#define SIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
1500#define UNSIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
1501#define FLOATING_TYPE(Id, SingletonId) case BuiltinType::Id:
1502#define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id:
1503#include "clang/AST/BuiltinTypes.def"
1504 break;
1505
1506 case BuiltinType::ObjCId:
1507 VisitType = Context.getObjCIdType();
1508 break;
1509
1510 case BuiltinType::ObjCClass:
1511 VisitType = Context.getObjCClassType();
1512 break;
1513
1514 case BuiltinType::ObjCSel:
1515 VisitType = Context.getObjCSelType();
1516 break;
1517 }
1518
1519 if (!VisitType.isNull()) {
1520 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
1521 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
1522 TU));
1523 }
1524
1525 return false;
1526}
1527
1528bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
1529 return Visit(MakeCursorTypeRef(TL.getTypedefNameDecl(), TL.getNameLoc(), TU));
1530}
1531
1532bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
1533 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1534}
1535
1536bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
1537 if (TL.isDefinition())
1538 return Visit(MakeCXCursor(TL.getDecl(), TU, RegionOfInterest));
1539
1540 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1541}
1542
1543bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
1544 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1545}
1546
1547bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
1548 return Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU));
1549}
1550
1551bool CursorVisitor::VisitObjCTypeParamTypeLoc(ObjCTypeParamTypeLoc TL) {
1552 if (Visit(MakeCursorTypeRef(TL.getDecl(), TL.getLocStart(), TU)))
1553 return true;
1554 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1555 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1556 TU)))
1557 return true;
1558 }
1559
1560 return false;
1561}
1562
1563bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1564 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
1565 return true;
1566
1567 for (unsigned I = 0, N = TL.getNumTypeArgs(); I != N; ++I) {
1568 if (Visit(TL.getTypeArgTInfo(I)->getTypeLoc()))
1569 return true;
1570 }
1571
1572 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1573 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1574 TU)))
1575 return true;
1576 }
1577
1578 return false;
1579}
1580
1581bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
1582 return Visit(TL.getPointeeLoc());
1583}
1584
1585bool CursorVisitor::VisitParenTypeLoc(ParenTypeLoc TL) {
1586 return Visit(TL.getInnerLoc());
1587}
1588
1589bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
1590 return Visit(TL.getPointeeLoc());
1591}
1592
1593bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1594 return Visit(TL.getPointeeLoc());
1595}
1596
1597bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1598 return Visit(TL.getPointeeLoc());
1599}
1600
1601bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
1602 return Visit(TL.getPointeeLoc());
1603}
1604
1605bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
1606 return Visit(TL.getPointeeLoc());
1607}
1608
1609bool CursorVisitor::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
1610 return Visit(TL.getModifiedLoc());
1611}
1612
1613bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
1614 bool SkipResultType) {
1615 if (!SkipResultType && Visit(TL.getReturnLoc()))
1616 return true;
1617
1618 for (unsigned I = 0, N = TL.getNumParams(); I != N; ++I)
1619 if (Decl *D = TL.getParam(I))
1620 if (Visit(MakeCXCursor(D, TU, RegionOfInterest)))
1621 return true;
1622
1623 return false;
1624}
1625
1626bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
1627 if (Visit(TL.getElementLoc()))
1628 return true;
1629
1630 if (Expr *Size = TL.getSizeExpr())
1631 return Visit(MakeCXCursor(Size, StmtParent, TU, RegionOfInterest));
1632
1633 return false;
1634}
1635
1636bool CursorVisitor::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
1637 return Visit(TL.getOriginalLoc());
1638}
1639
1640bool CursorVisitor::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
1641 return Visit(TL.getOriginalLoc());
1642}
1643
1644bool CursorVisitor::VisitDeducedTemplateSpecializationTypeLoc(
1645 DeducedTemplateSpecializationTypeLoc TL) {
1646 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1647 TL.getTemplateNameLoc()))
1648 return true;
1649
1650 return false;
1651}
1652
1653bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
1654 TemplateSpecializationTypeLoc TL) {
1655 // Visit the template name.
1656 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1657 TL.getTemplateNameLoc()))
1658 return true;
1659
1660 // Visit the template arguments.
1661 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1662 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1663 return true;
1664
1665 return false;
1666}
1667
1668bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1669 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
1670}
1671
1672bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1673 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1674 return Visit(TSInfo->getTypeLoc());
1675
1676 return false;
1677}
1678
1679bool CursorVisitor::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
1680 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1681 return Visit(TSInfo->getTypeLoc());
1682
1683 return false;
1684}
1685
1686bool CursorVisitor::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
1687 return VisitNestedNameSpecifierLoc(TL.getQualifierLoc());
1688}
1689
1690bool CursorVisitor::VisitDependentTemplateSpecializationTypeLoc(
1691 DependentTemplateSpecializationTypeLoc TL) {
1692 // Visit the nested-name-specifier, if there is one.
1693 if (TL.getQualifierLoc() &&
1694 VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1695 return true;
1696
1697 // Visit the template arguments.
1698 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1699 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1700 return true;
1701
1702 return false;
1703}
1704
1705bool CursorVisitor::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
1706 if (VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1707 return true;
1708
1709 return Visit(TL.getNamedTypeLoc());
1710}
1711
1712bool CursorVisitor::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
1713 return Visit(TL.getPatternLoc());
1714}
1715
1716bool CursorVisitor::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
1717 if (Expr *E = TL.getUnderlyingExpr())
1718 return Visit(MakeCXCursor(E, StmtParent, TU));
1719
1720 return false;
1721}
1722
1723bool CursorVisitor::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
1724 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1725}
1726
1727bool CursorVisitor::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
1728 return Visit(TL.getValueLoc());
1729}
1730
1731bool CursorVisitor::VisitPipeTypeLoc(PipeTypeLoc TL) {
1732 return Visit(TL.getValueLoc());
1733}
1734
1735#define DEFAULT_TYPELOC_IMPL(CLASS, PARENT)bool CursorVisitor::VisitCLASSTypeLoc(CLASSTypeLoc TL) { return
VisitPARENTLoc(TL); }
\
1736bool CursorVisitor::Visit##CLASS##TypeLoc(CLASS##TypeLoc TL) { \
1737 return Visit##PARENT##Loc(TL); \
1738}
1739
1740DEFAULT_TYPELOC_IMPL(Complex, Type)bool CursorVisitor::VisitComplexTypeLoc(ComplexTypeLoc TL) { return
VisitTypeLoc(TL); }
1741DEFAULT_TYPELOC_IMPL(ConstantArray, ArrayType)bool CursorVisitor::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc
TL) { return VisitArrayTypeLoc(TL); }
1742DEFAULT_TYPELOC_IMPL(IncompleteArray, ArrayType)bool CursorVisitor::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc
TL) { return VisitArrayTypeLoc(TL); }
1743DEFAULT_TYPELOC_IMPL(VariableArray, ArrayType)bool CursorVisitor::VisitVariableArrayTypeLoc(VariableArrayTypeLoc
TL) { return VisitArrayTypeLoc(TL); }
1744DEFAULT_TYPELOC_IMPL(DependentSizedArray, ArrayType)bool CursorVisitor::VisitDependentSizedArrayTypeLoc(DependentSizedArrayTypeLoc
TL) { return VisitArrayTypeLoc(TL); }
1745DEFAULT_TYPELOC_IMPL(DependentSizedExtVector, Type)bool CursorVisitor::VisitDependentSizedExtVectorTypeLoc(DependentSizedExtVectorTypeLoc
TL) { return VisitTypeLoc(TL); }
1746DEFAULT_TYPELOC_IMPL(Vector, Type)bool CursorVisitor::VisitVectorTypeLoc(VectorTypeLoc TL) { return
VisitTypeLoc(TL); }
1747DEFAULT_TYPELOC_IMPL(ExtVector, VectorType)bool CursorVisitor::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL
) { return VisitVectorTypeLoc(TL); }
1748DEFAULT_TYPELOC_IMPL(FunctionProto, FunctionType)bool CursorVisitor::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc
TL) { return VisitFunctionTypeLoc(TL); }
1749DEFAULT_TYPELOC_IMPL(FunctionNoProto, FunctionType)bool CursorVisitor::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc
TL) { return VisitFunctionTypeLoc(TL); }
1750DEFAULT_TYPELOC_IMPL(Record, TagType)bool CursorVisitor::VisitRecordTypeLoc(RecordTypeLoc TL) { return
VisitTagTypeLoc(TL); }
1751DEFAULT_TYPELOC_IMPL(Enum, TagType)bool CursorVisitor::VisitEnumTypeLoc(EnumTypeLoc TL) { return
VisitTagTypeLoc(TL); }
1752DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParm, Type)bool CursorVisitor::VisitSubstTemplateTypeParmTypeLoc(SubstTemplateTypeParmTypeLoc
TL) { return VisitTypeLoc(TL); }
1753DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParmPack, Type)bool CursorVisitor::VisitSubstTemplateTypeParmPackTypeLoc(SubstTemplateTypeParmPackTypeLoc
TL) { return VisitTypeLoc(TL); }
1754DEFAULT_TYPELOC_IMPL(Auto, Type)bool CursorVisitor::VisitAutoTypeLoc(AutoTypeLoc TL) { return
VisitTypeLoc(TL); }
1755
1756bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
1757 // Visit the nested-name-specifier, if present.
1758 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1759 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1760 return true;
1761
1762 if (D->isCompleteDefinition()) {
1763 for (const auto &I : D->bases()) {
1764 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(&I, TU)))
1765 return true;
1766 }
1767 }
1768
1769 return VisitTagDecl(D);
1770}
1771
1772bool CursorVisitor::VisitAttributes(Decl *D) {
1773 for (const auto *I : D->attrs())
1774 if (Visit(MakeCXCursor(I, D, TU)))
1775 return true;
1776
1777 return false;
1778}
1779
1780//===----------------------------------------------------------------------===//
1781// Data-recursive visitor methods.
1782//===----------------------------------------------------------------------===//
1783
1784namespace {
1785#define DEF_JOB(NAME, DATA, KIND)\
1786class NAME : public VisitorJob {\
1787public:\
1788 NAME(const DATA *d, CXCursor parent) : \
1789 VisitorJob(parent, VisitorJob::KIND, d) {} \
1790 static bool classof(const VisitorJob *VJ) { return VJ->getKind() == KIND; }\
1791 const DATA *get() const { return static_cast<const DATA*>(data[0]); }\
1792};
1793
1794DEF_JOB(StmtVisit, Stmt, StmtVisitKind)
1795DEF_JOB(MemberExprParts, MemberExpr, MemberExprPartsKind)
1796DEF_JOB(DeclRefExprParts, DeclRefExpr, DeclRefExprPartsKind)
1797DEF_JOB(OverloadExprParts, OverloadExpr, OverloadExprPartsKind)
1798DEF_JOB(SizeOfPackExprParts, SizeOfPackExpr, SizeOfPackExprPartsKind)
1799DEF_JOB(LambdaExprParts, LambdaExpr, LambdaExprPartsKind)
1800DEF_JOB(PostChildrenVisit, void, PostChildrenVisitKind)
1801#undef DEF_JOB
1802
1803class ExplicitTemplateArgsVisit : public VisitorJob {
1804public:
1805 ExplicitTemplateArgsVisit(const TemplateArgumentLoc *Begin,
1806 const TemplateArgumentLoc *End, CXCursor parent)
1807 : VisitorJob(parent, VisitorJob::ExplicitTemplateArgsVisitKind, Begin,
1808 End) {}
1809 static bool classof(const VisitorJob *VJ) {
1810 return VJ->getKind() == ExplicitTemplateArgsVisitKind;
1811 }
1812 const TemplateArgumentLoc *begin() const {
1813 return static_cast<const TemplateArgumentLoc *>(data[0]);
1814 }
1815 const TemplateArgumentLoc *end() {
1816 return static_cast<const TemplateArgumentLoc *>(data[1]);
1817 }
1818};
1819class DeclVisit : public VisitorJob {
1820public:
1821 DeclVisit(const Decl *D, CXCursor parent, bool isFirst) :
1822 VisitorJob(parent, VisitorJob::DeclVisitKind,
1823 D, isFirst ? (void*) 1 : (void*) nullptr) {}
1824 static bool classof(const VisitorJob *VJ) {
1825 return VJ->getKind() == DeclVisitKind;
1826 }
1827 const Decl *get() const { return static_cast<const Decl *>(data[0]); }
1828 bool isFirst() const { return data[1] != nullptr; }
1829};
1830class TypeLocVisit : public VisitorJob {
1831public:
1832 TypeLocVisit(TypeLoc tl, CXCursor parent) :
1833 VisitorJob(parent, VisitorJob::TypeLocVisitKind,
1834 tl.getType().getAsOpaquePtr(), tl.getOpaqueData()) {}
1835
1836 static bool classof(const VisitorJob *VJ) {
1837 return VJ->getKind() == TypeLocVisitKind;
1838 }
1839
1840 TypeLoc get() const {
1841 QualType T = QualType::getFromOpaquePtr(data[0]);
1842 return TypeLoc(T, const_cast<void *>(data[1]));
1843 }
1844};
1845
1846class LabelRefVisit : public VisitorJob {
1847public:
1848 LabelRefVisit(LabelDecl *LD, SourceLocation labelLoc, CXCursor parent)
1849 : VisitorJob(parent, VisitorJob::LabelRefVisitKind, LD,
1850 labelLoc.getPtrEncoding()) {}
1851
1852 static bool classof(const VisitorJob *VJ) {
1853 return VJ->getKind() == VisitorJob::LabelRefVisitKind;
1854 }
1855 const LabelDecl *get() const {
1856 return static_cast<const LabelDecl *>(data[0]);
1857 }
1858 SourceLocation getLoc() const {
1859 return SourceLocation::getFromPtrEncoding(data[1]); }
1860};
1861
1862class NestedNameSpecifierLocVisit : public VisitorJob {
1863public:
1864 NestedNameSpecifierLocVisit(NestedNameSpecifierLoc Qualifier, CXCursor parent)
1865 : VisitorJob(parent, VisitorJob::NestedNameSpecifierLocVisitKind,
1866 Qualifier.getNestedNameSpecifier(),
1867 Qualifier.getOpaqueData()) { }
1868
1869 static bool classof(const VisitorJob *VJ) {
1870 return VJ->getKind() == VisitorJob::NestedNameSpecifierLocVisitKind;
1871 }
1872
1873 NestedNameSpecifierLoc get() const {
1874 return NestedNameSpecifierLoc(
1875 const_cast<NestedNameSpecifier *>(
1876 static_cast<const NestedNameSpecifier *>(data[0])),
1877 const_cast<void *>(data[1]));
1878 }
1879};
1880
1881class DeclarationNameInfoVisit : public VisitorJob {
1882public:
1883 DeclarationNameInfoVisit(const Stmt *S, CXCursor parent)
1884 : VisitorJob(parent, VisitorJob::DeclarationNameInfoVisitKind, S) {}
1885 static bool classof(const VisitorJob *VJ) {
1886 return VJ->getKind() == VisitorJob::DeclarationNameInfoVisitKind;
1887 }
1888 DeclarationNameInfo get() const {
1889 const Stmt *S = static_cast<const Stmt *>(data[0]);
1890 switch (S->getStmtClass()) {
1891 default:
1892 llvm_unreachable("Unhandled Stmt")::llvm::llvm_unreachable_internal("Unhandled Stmt", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/tools/libclang/CIndex.cpp"
, 1892)
;
1893 case clang::Stmt::MSDependentExistsStmtClass:
1894 return cast<MSDependentExistsStmt>(S)->getNameInfo();
1895 case Stmt::CXXDependentScopeMemberExprClass:
1896 return cast<CXXDependentScopeMemberExpr>(S)->getMemberNameInfo();
1897 case Stmt::DependentScopeDeclRefExprClass:
1898 return cast<DependentScopeDeclRefExpr>(S)->getNameInfo();
1899 case Stmt::OMPCriticalDirectiveClass:
1900 return cast<OMPCriticalDirective>(S)->getDirectiveName();
1901 }
1902 }
1903};
1904class MemberRefVisit : public VisitorJob {
1905public:
1906 MemberRefVisit(const FieldDecl *D, SourceLocation L, CXCursor parent)
1907 : VisitorJob(parent, VisitorJob::MemberRefVisitKind, D,
1908 L.getPtrEncoding()) {}
1909 static bool classof(const VisitorJob *VJ) {
1910 return VJ->getKind() == VisitorJob::MemberRefVisitKind;
1911 }
1912 const FieldDecl *get() const {
1913 return static_cast<const FieldDecl *>(data[0]);
1914 }
1915 SourceLocation getLoc() const {
1916 return SourceLocation::getFromRawEncoding((unsigned)(uintptr_t) data[1]);
1917 }
1918};
1919class EnqueueVisitor : public ConstStmtVisitor<EnqueueVisitor, void> {
1920 friend class OMPClauseEnqueue;
1921 VisitorWorkList &WL;
1922 CXCursor Parent;
1923public:
1924 EnqueueVisitor(VisitorWorkList &wl, CXCursor parent)
1925 : WL(wl), Parent(parent) {}
1926
1927 void VisitAddrLabelExpr(const AddrLabelExpr *E);
1928 void VisitBlockExpr(const BlockExpr *B);
1929 void VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
1930 void VisitCompoundStmt(const CompoundStmt *S);
1931 void VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) { /* Do nothing. */ }
1932 void VisitMSDependentExistsStmt(const MSDependentExistsStmt *S);
1933 void VisitCXXDependentScopeMemberExpr(const CXXDependentScopeMemberExpr *E);
1934 void VisitCXXNewExpr(const CXXNewExpr *E);
1935 void VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E);
1936 void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *E);
1937 void VisitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *E);
1938 void VisitCXXTemporaryObjectExpr(const CXXTemporaryObjectExpr *E);
1939 void VisitCXXTypeidExpr(const CXXTypeidExpr *E);
1940 void VisitCXXUnresolvedConstructExpr(const CXXUnresolvedConstructExpr *E);
1941 void VisitCXXUuidofExpr(const CXXUuidofExpr *E);
1942 void VisitCXXCatchStmt(const CXXCatchStmt *S);
1943 void VisitCXXForRangeStmt(const CXXForRangeStmt *S);
1944 void VisitDeclRefExpr(const DeclRefExpr *D);
1945 void VisitDeclStmt(const DeclStmt *S);
1946 void VisitDependentScopeDeclRefExpr(const DependentScopeDeclRefExpr *E);
1947 void VisitDesignatedInitExpr(const DesignatedInitExpr *E);
1948 void VisitExplicitCastExpr(const ExplicitCastExpr *E);
1949 void VisitForStmt(const ForStmt *FS);
1950 void VisitGotoStmt(const GotoStmt *GS);
1951 void VisitIfStmt(const IfStmt *If);
1952 void VisitInitListExpr(const InitListExpr *IE);
1953 void VisitMemberExpr(const MemberExpr *M);
1954 void VisitOffsetOfExpr(const OffsetOfExpr *E);
1955 void VisitObjCEncodeExpr(const ObjCEncodeExpr *E);
1956 void VisitObjCMessageExpr(const ObjCMessageExpr *M);
1957 void VisitOverloadExpr(const OverloadExpr *E);
1958 void VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
1959 void VisitStmt(const Stmt *S);
1960 void VisitSwitchStmt(const SwitchStmt *S);
1961 void VisitWhileStmt(const WhileStmt *W);
1962 void VisitTypeTraitExpr(const TypeTraitExpr *E);
1963 void VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E);
1964 void VisitExpressionTraitExpr(const ExpressionTraitExpr *E);
1965 void VisitUnresolvedMemberExpr(const UnresolvedMemberExpr *U);
1966 void VisitVAArgExpr(const VAArgExpr *E);
1967 void VisitSizeOfPackExpr(const SizeOfPackExpr *E);
1968 void VisitPseudoObjectExpr(const PseudoObjectExpr *E);
1969 void VisitOpaqueValueExpr(const OpaqueValueExpr *E);
1970 void VisitLambdaExpr(const LambdaExpr *E);
1971 void VisitOMPExecutableDirective(const OMPExecutableDirective *D);
1972 void VisitOMPLoopDirective(const OMPLoopDirective *D);
1973 void VisitOMPParallelDirective(const OMPParallelDirective *D);
1974 void VisitOMPSimdDirective(const OMPSimdDirective *D);
1975 void VisitOMPForDirective(const OMPForDirective *D);
1976 void VisitOMPForSimdDirective(const OMPForSimdDirective *D);
1977 void VisitOMPSectionsDirective(const OMPSectionsDirective *D);
1978 void VisitOMPSectionDirective(const OMPSectionDirective *D);
1979 void VisitOMPSingleDirective(const OMPSingleDirective *D);
1980 void VisitOMPMasterDirective(const OMPMasterDirective *D);
1981 void VisitOMPCriticalDirective(const OMPCriticalDirective *D);
1982 void VisitOMPParallelForDirective(const OMPParallelForDirective *D);
1983 void VisitOMPParallelForSimdDirective(const OMPParallelForSimdDirective *D);
1984 void VisitOMPParallelSectionsDirective(const OMPParallelSectionsDirective *D);
1985 void VisitOMPTaskDirective(const OMPTaskDirective *D);
1986 void VisitOMPTaskyieldDirective(const OMPTaskyieldDirective *D);
1987 void VisitOMPBarrierDirective(const OMPBarrierDirective *D);
1988 void VisitOMPTaskwaitDirective(const OMPTaskwaitDirective *D);
1989 void VisitOMPTaskgroupDirective(const OMPTaskgroupDirective *D);
1990 void
1991 VisitOMPCancellationPointDirective(const OMPCancellationPointDirective *D);
1992 void VisitOMPCancelDirective(const OMPCancelDirective *D);
1993 void VisitOMPFlushDirective(const OMPFlushDirective *D);
1994 void VisitOMPOrderedDirective(const OMPOrderedDirective *D);
1995 void VisitOMPAtomicDirective(const OMPAtomicDirective *D);
1996 void VisitOMPTargetDirective(const OMPTargetDirective *D);
1997 void VisitOMPTargetDataDirective(const OMPTargetDataDirective *D);
1998 void VisitOMPTargetEnterDataDirective(const OMPTargetEnterDataDirective *D);
1999 void VisitOMPTargetExitDataDirective(const OMPTargetExitDataDirective *D);
2000 void VisitOMPTargetParallelDirective(const OMPTargetParallelDirective *D);
2001 void
2002 VisitOMPTargetParallelForDirective(const OMPTargetParallelForDirective *D);
2003 void VisitOMPTeamsDirective(const OMPTeamsDirective *D);
2004 void VisitOMPTaskLoopDirective(const OMPTaskLoopDirective *D);
2005 void VisitOMPTaskLoopSimdDirective(const OMPTaskLoopSimdDirective *D);
2006 void VisitOMPDistributeDirective(const OMPDistributeDirective *D);
2007 void VisitOMPDistributeParallelForDirective(
2008 const OMPDistributeParallelForDirective *D);
2009 void VisitOMPDistributeParallelForSimdDirective(
2010 const OMPDistributeParallelForSimdDirective *D);
2011 void VisitOMPDistributeSimdDirective(const OMPDistributeSimdDirective *D);
2012 void VisitOMPTargetParallelForSimdDirective(
2013 const OMPTargetParallelForSimdDirective *D);
2014 void VisitOMPTargetSimdDirective(const OMPTargetSimdDirective *D);
2015 void VisitOMPTeamsDistributeDirective(const OMPTeamsDistributeDirective *D);
2016 void VisitOMPTeamsDistributeSimdDirective(
2017 const OMPTeamsDistributeSimdDirective *D);
2018 void VisitOMPTeamsDistributeParallelForSimdDirective(
2019 const OMPTeamsDistributeParallelForSimdDirective *D);
2020 void VisitOMPTeamsDistributeParallelForDirective(
2021 const OMPTeamsDistributeParallelForDirective *D);
2022 void VisitOMPTargetTeamsDirective(const OMPTargetTeamsDirective *D);
2023 void VisitOMPTargetTeamsDistributeDirective(
2024 const OMPTargetTeamsDistributeDirective *D);
2025 void VisitOMPTargetTeamsDistributeParallelForDirective(
2026 const OMPTargetTeamsDistributeParallelForDirective *D);
2027 void VisitOMPTargetTeamsDistributeParallelForSimdDirective(
2028 const OMPTargetTeamsDistributeParallelForSimdDirective *D);
2029 void VisitOMPTargetTeamsDistributeSimdDirective(
2030 const OMPTargetTeamsDistributeSimdDirective *D);
2031
2032private:
2033 void AddDeclarationNameInfo(const Stmt *S);
2034 void AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier);
2035 void AddExplicitTemplateArgs(const TemplateArgumentLoc *A,
2036 unsigned NumTemplateArgs);
2037 void AddMemberRef(const FieldDecl *D, SourceLocation L);
2038 void AddStmt(const Stmt *S);
2039 void AddDecl(const Decl *D, bool isFirst = true);
2040 void AddTypeLoc(TypeSourceInfo *TI);
2041 void EnqueueChildren(const Stmt *S);
2042 void EnqueueChildren(const OMPClause *S);
2043};
2044} // end anonyous namespace
2045
2046void EnqueueVisitor::AddDeclarationNameInfo(const Stmt *S) {
2047 // 'S' should always be non-null, since it comes from the
2048 // statement we are visiting.
2049 WL.push_back(DeclarationNameInfoVisit(S, Parent));
2050}
2051
2052void
2053EnqueueVisitor::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
2054 if (Qualifier)
2055 WL.push_back(NestedNameSpecifierLocVisit(Qualifier, Parent));
2056}
2057
2058void EnqueueVisitor::AddStmt(const Stmt *S) {
2059 if (S)
2060 WL.push_back(StmtVisit(S, Parent));
2061}
2062void EnqueueVisitor::AddDecl(const Decl *D, bool isFirst) {
2063 if (D)
2064 WL.push_back(DeclVisit(D, Parent, isFirst));
2065}
2066void EnqueueVisitor::AddExplicitTemplateArgs(const TemplateArgumentLoc *A,
2067 unsigned NumTemplateArgs) {
2068 WL.push_back(ExplicitTemplateArgsVisit(A, A + NumTemplateArgs, Parent));
2069}
2070void EnqueueVisitor::AddMemberRef(const FieldDecl *D, SourceLocation L) {
2071 if (D)
2072 WL.push_back(MemberRefVisit(D, L, Parent));
2073}
2074void EnqueueVisitor::AddTypeLoc(TypeSourceInfo *TI) {
2075 if (TI)
2076 WL.push_back(TypeLocVisit(TI->getTypeLoc(), Parent));
2077 }
2078void EnqueueVisitor::EnqueueChildren(const Stmt *S) {
2079 unsigned size = WL.size();
2080 for (const Stmt *SubStmt : S->children()) {
2081 AddStmt(SubStmt);
2082 }
2083 if (size == WL.size())
2084 return;
2085 // Now reverse the entries we just added. This will match the DFS
2086 // ordering performed by the worklist.
2087 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2088 std::reverse(I, E);
2089}
2090namespace {
2091class OMPClauseEnqueue : public ConstOMPClauseVisitor<OMPClauseEnqueue> {
2092 EnqueueVisitor *Visitor;
2093 /// \brief Process clauses with list of variables.
2094 template <typename T>
2095 void VisitOMPClauseList(T *Node);
2096public:
2097 OMPClauseEnqueue(EnqueueVisitor *Visitor) : Visitor(Visitor) { }
2098#define OPENMP_CLAUSE(Name, Class) \
2099 void Visit##Class(const Class *C);
2100#include "clang/Basic/OpenMPKinds.def"
2101 void VisitOMPClauseWithPreInit(const OMPClauseWithPreInit *C);
2102 void VisitOMPClauseWithPostUpdate(const OMPClauseWithPostUpdate *C);
2103};
2104
2105void OMPClauseEnqueue::VisitOMPClauseWithPreInit(
2106 const OMPClauseWithPreInit *C) {
2107 Visitor->AddStmt(C->getPreInitStmt());
2108}
2109
2110void OMPClauseEnqueue::VisitOMPClauseWithPostUpdate(
2111 const OMPClauseWithPostUpdate *C) {
2112 VisitOMPClauseWithPreInit(C);
2113 Visitor->AddStmt(C->getPostUpdateExpr());
2114}
2115
2116void OMPClauseEnqueue::VisitOMPIfClause(const OMPIfClause *C) {
2117 VisitOMPClauseWithPreInit(C);
2118 Visitor->AddStmt(C->getCondition());
2119}
2120
2121void OMPClauseEnqueue::VisitOMPFinalClause(const OMPFinalClause *C) {
2122 Visitor->AddStmt(C->getCondition());
2123}
2124
2125void OMPClauseEnqueue::VisitOMPNumThreadsClause(const OMPNumThreadsClause *C) {
2126 VisitOMPClauseWithPreInit(C);
2127 Visitor->AddStmt(C->getNumThreads());
2128}
2129
2130void OMPClauseEnqueue::VisitOMPSafelenClause(const OMPSafelenClause *C) {
2131 Visitor->AddStmt(C->getSafelen());
2132}
2133
2134void OMPClauseEnqueue::VisitOMPSimdlenClause(const OMPSimdlenClause *C) {
2135 Visitor->AddStmt(C->getSimdlen());
2136}
2137
2138void OMPClauseEnqueue::VisitOMPCollapseClause(const OMPCollapseClause *C) {
2139 Visitor->AddStmt(C->getNumForLoops());
2140}
2141
2142void OMPClauseEnqueue::VisitOMPDefaultClause(const OMPDefaultClause *C) { }
2143
2144void OMPClauseEnqueue::VisitOMPProcBindClause(const OMPProcBindClause *C) { }
2145
2146void OMPClauseEnqueue::VisitOMPScheduleClause(const OMPScheduleClause *C) {
2147 VisitOMPClauseWithPreInit(C);
2148 Visitor->AddStmt(C->getChunkSize());
2149}
2150
2151void OMPClauseEnqueue::VisitOMPOrderedClause(const OMPOrderedClause *C) {
2152 Visitor->AddStmt(C->getNumForLoops());
2153}
2154
2155void OMPClauseEnqueue::VisitOMPNowaitClause(const OMPNowaitClause *) {}
2156
2157void OMPClauseEnqueue::VisitOMPUntiedClause(const OMPUntiedClause *) {}
2158
2159void OMPClauseEnqueue::VisitOMPMergeableClause(const OMPMergeableClause *) {}
2160
2161void OMPClauseEnqueue::VisitOMPReadClause(const OMPReadClause *) {}
2162
2163void OMPClauseEnqueue::VisitOMPWriteClause(const OMPWriteClause *) {}
2164
2165void OMPClauseEnqueue::VisitOMPUpdateClause(const OMPUpdateClause *) {}
2166
2167void OMPClauseEnqueue::VisitOMPCaptureClause(const OMPCaptureClause *) {}
2168
2169void OMPClauseEnqueue::VisitOMPSeqCstClause(const OMPSeqCstClause *) {}
2170
2171void OMPClauseEnqueue::VisitOMPThreadsClause(const OMPThreadsClause *) {}
2172
2173void OMPClauseEnqueue::VisitOMPSIMDClause(const OMPSIMDClause *) {}
2174
2175void OMPClauseEnqueue::VisitOMPNogroupClause(const OMPNogroupClause *) {}
2176
2177void OMPClauseEnqueue::VisitOMPDeviceClause(const OMPDeviceClause *C) {
2178 Visitor->AddStmt(C->getDevice());
2179}
2180
2181void OMPClauseEnqueue::VisitOMPNumTeamsClause(const OMPNumTeamsClause *C) {
2182 VisitOMPClauseWithPreInit(C);
2183 Visitor->AddStmt(C->getNumTeams());
2184}
2185
2186void OMPClauseEnqueue::VisitOMPThreadLimitClause(const OMPThreadLimitClause *C) {
2187 VisitOMPClauseWithPreInit(C);
2188 Visitor->AddStmt(C->getThreadLimit());
2189}
2190
2191void OMPClauseEnqueue::VisitOMPPriorityClause(const OMPPriorityClause *C) {
2192 Visitor->AddStmt(C->getPriority());
2193}
2194
2195void OMPClauseEnqueue::VisitOMPGrainsizeClause(const OMPGrainsizeClause *C) {
2196 Visitor->AddStmt(C->getGrainsize());
2197}
2198
2199void OMPClauseEnqueue::VisitOMPNumTasksClause(const OMPNumTasksClause *C) {
2200 Visitor->AddStmt(C->getNumTasks());
2201}
2202
2203void OMPClauseEnqueue::VisitOMPHintClause(const OMPHintClause *C) {
2204 Visitor->AddStmt(C->getHint());
2205}
2206
2207template<typename T>
2208void OMPClauseEnqueue::VisitOMPClauseList(T *Node) {
2209 for (const auto *I : Node->varlists()) {
2210 Visitor->AddStmt(I);
2211 }
2212}
2213
2214void OMPClauseEnqueue::VisitOMPPrivateClause(const OMPPrivateClause *C) {
2215 VisitOMPClauseList(C);
2216 for (const auto *E : C->private_copies()) {
2217 Visitor->AddStmt(E);
2218 }
2219}
2220void OMPClauseEnqueue::VisitOMPFirstprivateClause(
2221 const OMPFirstprivateClause *C) {
2222 VisitOMPClauseList(C);
2223 VisitOMPClauseWithPreInit(C);
2224 for (const auto *E : C->private_copies()) {
2225 Visitor->AddStmt(E);
2226 }
2227 for (const auto *E : C->inits()) {
2228 Visitor->AddStmt(E);
2229 }
2230}
2231void OMPClauseEnqueue::VisitOMPLastprivateClause(
2232 const OMPLastprivateClause *C) {
2233 VisitOMPClauseList(C);
2234 VisitOMPClauseWithPostUpdate(C);
2235 for (auto *E : C->private_copies()) {
2236 Visitor->AddStmt(E);
2237 }
2238 for (auto *E : C->source_exprs()) {
2239 Visitor->AddStmt(E);
2240 }
2241 for (auto *E : C->destination_exprs()) {
2242 Visitor->AddStmt(E);
2243 }
2244 for (auto *E : C->assignment_ops()) {
2245 Visitor->AddStmt(E);
2246 }
2247}
2248void OMPClauseEnqueue::VisitOMPSharedClause(const OMPSharedClause *C) {
2249 VisitOMPClauseList(C);
2250}
2251void OMPClauseEnqueue::VisitOMPReductionClause(const OMPReductionClause *C) {
2252 VisitOMPClauseList(C);
2253 VisitOMPClauseWithPostUpdate(C);
2254 for (auto *E : C->privates()) {
2255 Visitor->AddStmt(E);
2256 }
2257 for (auto *E : C->lhs_exprs()) {
2258 Visitor->AddStmt(E);
2259 }
2260 for (auto *E : C->rhs_exprs()) {
2261 Visitor->AddStmt(E);
2262 }
2263 for (auto *E : C->reduction_ops()) {
2264 Visitor->AddStmt(E);
2265 }
2266}
2267void OMPClauseEnqueue::VisitOMPLinearClause(const OMPLinearClause *C) {
2268 VisitOMPClauseList(C);
2269 VisitOMPClauseWithPostUpdate(C);
2270 for (const auto *E : C->privates()) {
2271 Visitor->AddStmt(E);
2272 }
2273 for (const auto *E : C->inits()) {
2274 Visitor->AddStmt(E);
2275 }
2276 for (const auto *E : C->updates()) {
2277 Visitor->AddStmt(E);
2278 }
2279 for (const auto *E : C->finals()) {
2280 Visitor->AddStmt(E);
2281 }
2282 Visitor->AddStmt(C->getStep());
2283 Visitor->AddStmt(C->getCalcStep());
2284}
2285void OMPClauseEnqueue::VisitOMPAlignedClause(const OMPAlignedClause *C) {
2286 VisitOMPClauseList(C);
2287 Visitor->AddStmt(C->getAlignment());
2288}
2289void OMPClauseEnqueue::VisitOMPCopyinClause(const OMPCopyinClause *C) {
2290 VisitOMPClauseList(C);
2291 for (auto *E : C->source_exprs()) {
2292 Visitor->AddStmt(E);
2293 }
2294 for (auto *E : C->destination_exprs()) {
2295 Visitor->AddStmt(E);
2296 }
2297 for (auto *E : C->assignment_ops()) {
2298 Visitor->AddStmt(E);
2299 }
2300}
2301void
2302OMPClauseEnqueue::VisitOMPCopyprivateClause(const OMPCopyprivateClause *C) {
2303 VisitOMPClauseList(C);
2304 for (auto *E : C->source_exprs()) {
2305 Visitor->AddStmt(E);
2306 }
2307 for (auto *E : C->destination_exprs()) {
2308 Visitor->AddStmt(E);
2309 }
2310 for (auto *E : C->assignment_ops()) {
2311 Visitor->AddStmt(E);
2312 }
2313}
2314void OMPClauseEnqueue::VisitOMPFlushClause(const OMPFlushClause *C) {
2315 VisitOMPClauseList(C);
2316}
2317void OMPClauseEnqueue::VisitOMPDependClause(const OMPDependClause *C) {
2318 VisitOMPClauseList(C);
2319}
2320void OMPClauseEnqueue::VisitOMPMapClause(const OMPMapClause *C) {
2321 VisitOMPClauseList(C);
2322}
2323void OMPClauseEnqueue::VisitOMPDistScheduleClause(
2324 const OMPDistScheduleClause *C) {
2325 VisitOMPClauseWithPreInit(C);
2326 Visitor->AddStmt(C->getChunkSize());
2327}
2328void OMPClauseEnqueue::VisitOMPDefaultmapClause(
2329 const OMPDefaultmapClause * /*C*/) {}
2330void OMPClauseEnqueue::VisitOMPToClause(const OMPToClause *C) {
2331 VisitOMPClauseList(C);
2332}
2333void OMPClauseEnqueue::VisitOMPFromClause(const OMPFromClause *C) {
2334 VisitOMPClauseList(C);
2335}
2336void OMPClauseEnqueue::VisitOMPUseDevicePtrClause(const OMPUseDevicePtrClause *C) {
2337 VisitOMPClauseList(C);
2338}
2339void OMPClauseEnqueue::VisitOMPIsDevicePtrClause(const OMPIsDevicePtrClause *C) {
2340 VisitOMPClauseList(C);
2341}
2342}
2343
2344void EnqueueVisitor::EnqueueChildren(const OMPClause *S) {
2345 unsigned size = WL.size();
2346 OMPClauseEnqueue Visitor(this);
2347 Visitor.Visit(S);
2348 if (size == WL.size())
2349 return;
2350 // Now reverse the entries we just added. This will match the DFS
2351 // ordering performed by the worklist.
2352 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2353 std::reverse(I, E);
2354}
2355void EnqueueVisitor::VisitAddrLabelExpr(const AddrLabelExpr *E) {
2356 WL.push_back(LabelRefVisit(E->getLabel(), E->getLabelLoc(), Parent));
2357}
2358void EnqueueVisitor::VisitBlockExpr(const BlockExpr *B) {
2359 AddDecl(B->getBlockDecl());
2360}
2361void EnqueueVisitor::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
2362 EnqueueChildren(E);
2363 AddTypeLoc(E->getTypeSourceInfo());
2364}
2365void EnqueueVisitor::VisitCompoundStmt(const CompoundStmt *S) {
2366 for (auto &I : llvm::reverse(S->body()))
2367 AddStmt(I);
2368}
2369void EnqueueVisitor::
2370VisitMSDependentExistsStmt(const MSDependentExistsStmt *S) {
2371 AddStmt(S->getSubStmt());
2372 AddDeclarationNameInfo(S);
2373 if (NestedNameSpecifierLoc QualifierLoc = S->getQualifierLoc())
2374 AddNestedNameSpecifierLoc(QualifierLoc);
2375}
2376
2377void EnqueueVisitor::
2378VisitCXXDependentScopeMemberExpr(const CXXDependentScopeMemberExpr *E) {
2379 if (E->hasExplicitTemplateArgs())
2380 AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
2381 AddDeclarationNameInfo(E);
2382 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
2383 AddNestedNameSpecifierLoc(QualifierLoc);
2384 if (!E->isImplicitAccess())
2385 AddStmt(E->getBase());
2386}
2387void EnqueueVisitor::VisitCXXNewExpr(const CXXNewExpr *E) {
2388 // Enqueue the initializer , if any.
2389 AddStmt(E->getInitializer());
2390 // Enqueue the array size, if any.
2391 AddStmt(E->getArraySize());
2392 // Enqueue the allocated type.
2393 AddTypeLoc(E->getAllocatedTypeSourceInfo());
2394 // Enqueue the placement arguments.
2395 for (unsigned I = E->getNumPlacementArgs(); I > 0; --I)
2396 AddStmt(E->getPlacementArg(I-1));
2397}
2398void EnqueueVisitor::VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CE) {
2399 for (unsigned I = CE->getNumArgs(); I > 1 /* Yes, this is 1 */; --I)
2400 AddStmt(CE->getArg(I-1));
2401 AddStmt(CE->getCallee());
2402 AddStmt(CE->getArg(0));
2403}
2404void EnqueueVisitor::VisitCXXPseudoDestructorExpr(
2405 const CXXPseudoDestructorExpr *E) {
2406 // Visit the name of the type being destroyed.
2407 AddTypeLoc(E->getDestroyedTypeInfo());
2408 // Visit the scope type that looks disturbingly like the nested-name-specifier
2409 // but isn't.
2410 AddTypeLoc(E->getScopeTypeInfo());
2411 // Visit the nested-name-specifier.
2412 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
2413 AddNestedNameSpecifierLoc(QualifierLoc);
2414 // Visit base expression.
2415 AddStmt(E->getBase());
2416}
2417void EnqueueVisitor::VisitCXXScalarValueInitExpr(
2418 const CXXScalarValueInitExpr *E) {
2419 AddTypeLoc(E->getTypeSourceInfo());
2420}
2421void EnqueueVisitor::VisitCXXTemporaryObjectExpr(
2422 const CXXTemporaryObjectExpr *E) {
2423 EnqueueChildren(E);
2424 AddTypeLoc(E->getTypeSourceInfo());
2425}
2426void EnqueueVisitor::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
2427 EnqueueChildren(E);
2428 if (E->isTypeOperand())
2429 AddTypeLoc(E->getTypeOperandSourceInfo());
2430}
2431
2432void EnqueueVisitor::VisitCXXUnresolvedConstructExpr(
2433 const CXXUnresolvedConstructExpr *E) {
2434 EnqueueChildren(E);
2435 AddTypeLoc(E->getTypeSourceInfo());
2436}
2437void EnqueueVisitor::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
2438 EnqueueChildren(E);
2439 if (E->isTypeOperand())
2440 AddTypeLoc(E->getTypeOperandSourceInfo());
2441}
2442
2443void EnqueueVisitor::VisitCXXCatchStmt(const CXXCatchStmt *S) {
2444 EnqueueChildren(S);
2445 AddDecl(S->getExceptionDecl());
2446}
2447
2448void EnqueueVisitor::VisitCXXForRangeStmt(const CXXForRangeStmt *S) {
2449 AddStmt(S->getBody());
2450 AddStmt(S->getRangeInit());
2451 AddDecl(S->getLoopVariable());
2452}
2453
2454void EnqueueVisitor::VisitDeclRefExpr(const DeclRefExpr *DR) {
2455 if (DR->hasExplicitTemplateArgs())
2456 AddExplicitTemplateArgs(DR->getTemplateArgs(), DR->getNumTemplateArgs());
2457 WL.push_back(DeclRefExprParts(DR, Parent));
2458}
2459void EnqueueVisitor::VisitDependentScopeDeclRefExpr(
2460 const DependentScopeDeclRefExpr *E) {
2461 if (E->hasExplicitTemplateArgs())
2462 AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
2463 AddDeclarationNameInfo(E);
2464 AddNestedNameSpecifierLoc(E->getQualifierLoc());
2465}
2466void EnqueueVisitor::VisitDeclStmt(const DeclStmt *S) {
2467 unsigned size = WL.size();
2468 bool isFirst = true;
2469 for (const auto *D : S->decls()) {
2470 AddDecl(D, isFirst);
2471 isFirst = false;
2472 }
2473 if (size == WL.size())
2474 return;
2475 // Now reverse the entries we just added. This will match the DFS
2476 // ordering performed by the worklist.
2477 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2478 std::reverse(I, E);
2479}
2480void EnqueueVisitor::VisitDesignatedInitExpr(const DesignatedInitExpr *E) {
2481 AddStmt(E->getInit());
2482 for (const DesignatedInitExpr::Designator &D :
2483 llvm::reverse(E->designators())) {
2484 if (D.isFieldDesignator()) {
2485 if (FieldDecl *Field = D.getField())
2486 AddMemberRef(Field, D.getFieldLoc());
2487 continue;
2488 }
2489 if (D.isArrayDesignator()) {
2490 AddStmt(E->getArrayIndex(D));
2491 continue;
2492 }
2493 assert(D.isArrayRangeDesignator() && "Unknown designator kind")((D.isArrayRangeDesignator() && "Unknown designator kind"
) ? static_cast<void> (0) : __assert_fail ("D.isArrayRangeDesignator() && \"Unknown designator kind\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/tools/libclang/CIndex.cpp"
, 2493, __PRETTY_FUNCTION__))
;
2494 AddStmt(E->getArrayRangeEnd(D));
2495 AddStmt(E->getArrayRangeStart(D));
2496 }
2497}
2498void EnqueueVisitor::VisitExplicitCastExpr(const ExplicitCastExpr *E) {
2499 EnqueueChildren(E);
2500 AddTypeLoc(E->getTypeInfoAsWritten());
2501}
2502void EnqueueVisitor::VisitForStmt(const ForStmt *FS) {
2503 AddStmt(FS->getBody());
2504 AddStmt(FS->getInc());
2505 AddStmt(FS->getCond());
2506 AddDecl(FS->getConditionVariable());
2507 AddStmt(FS->getInit());
2508}
2509void EnqueueVisitor::VisitGotoStmt(const GotoStmt *GS) {
2510 WL.push_back(LabelRefVisit(GS->getLabel(), GS->getLabelLoc(), Parent));
2511}
2512void EnqueueVisitor::VisitIfStmt(const IfStmt *If) {
2513 AddStmt(If->getElse());
2514 AddStmt(If->getThen());
2515 AddStmt(If->getCond());
2516 AddDecl(If->getConditionVariable());
2517}
2518void EnqueueVisitor::VisitInitListExpr(const InitListExpr *IE) {
2519 // We care about the syntactic form of the initializer list, only.
2520 if (InitListExpr *Syntactic = IE->getSyntacticForm())
2521 IE = Syntactic;
2522 EnqueueChildren(IE);
2523}
2524void EnqueueVisitor::VisitMemberExpr(const MemberExpr *M) {
2525 WL.push_back(MemberExprParts(M, Parent));
2526
2527 // If the base of the member access expression is an implicit 'this', don't
2528 // visit it.
2529 // FIXME: If we ever want to show these implicit accesses, this will be
2530 // unfortunate. However, clang_getCursor() relies on this behavior.
2531 if (M->isImplicitAccess())
2532 return;
2533
2534 // Ignore base anonymous struct/union fields, otherwise they will shadow the
2535 // real field that that we are interested in.
2536 if (auto *SubME = dyn_cast<MemberExpr>(M->getBase())) {
2537 if (auto *FD = dyn_cast_or_null<FieldDecl>(SubME->getMemberDecl())) {
2538 if (FD->isAnonymousStructOrUnion()) {
2539 AddStmt(SubME->getBase());
2540 return;
2541 }
2542 }
2543 }
2544
2545 AddStmt(M->getBase());
2546}
2547void EnqueueVisitor::VisitObjCEncodeExpr(const ObjCEncodeExpr *E) {
2548 AddTypeLoc(E->getEncodedTypeSourceInfo());
2549}
2550void EnqueueVisitor::VisitObjCMessageExpr(const ObjCMessageExpr *M) {
2551 EnqueueChildren(M);
2552 AddTypeLoc(M->getClassReceiverTypeInfo());
2553}
2554void EnqueueVisitor::VisitOffsetOfExpr(const OffsetOfExpr *E) {
2555 // Visit the components of the offsetof expression.
2556 for (unsigned N = E->getNumComponents(), I = N; I > 0; --I) {
2557 const OffsetOfNode &Node = E->getComponent(I-1);
2558 switch (Node.getKind()) {
2559 case OffsetOfNode::Array:
2560 AddStmt(E->getIndexExpr(Node.getArrayExprIndex()));
2561 break;
2562 case OffsetOfNode::Field:
2563 AddMemberRef(Node.getField(), Node.getSourceRange().getEnd());
2564 break;
2565 case OffsetOfNode::Identifier:
2566 case OffsetOfNode::Base:
2567 continue;
2568 }
2569 }
2570 // Visit the type into which we're computing the offset.
2571 AddTypeLoc(E->getTypeSourceInfo());
2572}
2573void EnqueueVisitor::VisitOverloadExpr(const OverloadExpr *E) {
2574 if (E->hasExplicitTemplateArgs())
2575 AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
2576 WL.push_back(OverloadExprParts(E, Parent));
2577}
2578void EnqueueVisitor::VisitUnaryExprOrTypeTraitExpr(
2579 const UnaryExprOrTypeTraitExpr *E) {
2580 EnqueueChildren(E);
2581 if (E->isArgumentType())
2582 AddTypeLoc(E->getArgumentTypeInfo());
2583}
2584void EnqueueVisitor::VisitStmt(const Stmt *S) {
2585 EnqueueChildren(S);
2586}
2587void EnqueueVisitor::VisitSwitchStmt(const SwitchStmt *S) {
2588 AddStmt(S->getBody());
2589 AddStmt(S->getCond());
2590 AddDecl(S->getConditionVariable());
2591}
2592
2593void EnqueueVisitor::VisitWhileStmt(const WhileStmt *W) {
2594 AddStmt(W->getBody());
2595 AddStmt(W->getCond());
2596 AddDecl(W->getConditionVariable());
2597}
2598
2599void EnqueueVisitor::VisitTypeTraitExpr(const TypeTraitExpr *E) {
2600 for (unsigned I = E->getNumArgs(); I > 0; --I)
2601 AddTypeLoc(E->getArg(I-1));
2602}
2603
2604void EnqueueVisitor::VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
2605 AddTypeLoc(E->getQueriedTypeSourceInfo());
2606}
2607
2608void EnqueueVisitor::VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
2609 EnqueueChildren(E);
2610}
2611
2612void EnqueueVisitor::VisitUnresolvedMemberExpr(const UnresolvedMemberExpr *U) {
2613 VisitOverloadExpr(U);
2614 if (!U->isImplicitAccess())
2615 AddStmt(U->getBase());
2616}
2617void EnqueueVisitor::VisitVAArgExpr(const VAArgExpr *E) {
2618 AddStmt(E->getSubExpr());
2619 AddTypeLoc(E->getWrittenTypeInfo());
2620}
2621void EnqueueVisitor::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
2622 WL.push_back(SizeOfPackExprParts(E, Parent));
2623}
2624void EnqueueVisitor::VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
2625 // If the opaque value has a source expression, just transparently
2626 // visit that. This is useful for (e.g.) pseudo-object expressions.
2627 if (Expr *SourceExpr = E->getSourceExpr())
2628 return Visit(SourceExpr);
2629}
2630void EnqueueVisitor::VisitLambdaExpr(const LambdaExpr *E) {
2631 AddStmt(E->getBody());
2632 WL.push_back(LambdaExprParts(E, Parent));
2633}
2634void EnqueueVisitor::VisitPseudoObjectExpr(const PseudoObjectExpr *E) {
2635 // Treat the expression like its syntactic form.
2636 Visit(E->getSyntacticForm());
2637}
2638
2639void EnqueueVisitor::VisitOMPExecutableDirective(
2640 const OMPExecutableDirective *D) {
2641 EnqueueChildren(D);
2642 for (ArrayRef<OMPClause *>::iterator I = D->clauses().begin(),
2643 E = D->clauses().end();
2644 I != E; ++I)
2645 EnqueueChildren(*I);
2646}
2647
2648void EnqueueVisitor::VisitOMPLoopDirective(const OMPLoopDirective *D) {
2649 VisitOMPExecutableDirective(D);
2650}
2651
2652void EnqueueVisitor::VisitOMPParallelDirective(const OMPParallelDirective *D) {
2653 VisitOMPExecutableDirective(D);
2654}
2655
2656void EnqueueVisitor::VisitOMPSimdDirective(const OMPSimdDirective *D) {
2657 VisitOMPLoopDirective(D);
2658}
2659
2660void EnqueueVisitor::VisitOMPForDirective(const OMPForDirective *D) {
2661 VisitOMPLoopDirective(D);
2662}
2663
2664void EnqueueVisitor::VisitOMPForSimdDirective(const OMPForSimdDirective *D) {
2665 VisitOMPLoopDirective(D);
2666}
2667
2668void EnqueueVisitor::VisitOMPSectionsDirective(const OMPSectionsDirective *D) {
2669 VisitOMPExecutableDirective(D);
2670}
2671
2672void EnqueueVisitor::VisitOMPSectionDirective(const OMPSectionDirective *D) {
2673 VisitOMPExecutableDirective(D);
2674}
2675
2676void EnqueueVisitor::VisitOMPSingleDirective(const OMPSingleDirective *D) {
2677 VisitOMPExecutableDirective(D);
2678}
2679
2680void EnqueueVisitor::VisitOMPMasterDirective(const OMPMasterDirective *D) {
2681 VisitOMPExecutableDirective(D);
2682}
2683
2684void EnqueueVisitor::VisitOMPCriticalDirective(const OMPCriticalDirective *D) {
2685 VisitOMPExecutableDirective(D);
2686 AddDeclarationNameInfo(D);
2687}
2688
2689void
2690EnqueueVisitor::VisitOMPParallelForDirective(const OMPParallelForDirective *D) {
2691 VisitOMPLoopDirective(D);
2692}
2693
2694void EnqueueVisitor::VisitOMPParallelForSimdDirective(
2695 const OMPParallelForSimdDirective *D) {
2696 VisitOMPLoopDirective(D);
2697}
2698
2699void EnqueueVisitor::VisitOMPParallelSectionsDirective(
2700 const OMPParallelSectionsDirective *D) {
2701 VisitOMPExecutableDirective(D);
2702}
2703
2704void EnqueueVisitor::VisitOMPTaskDirective(const OMPTaskDirective *D) {
2705 VisitOMPExecutableDirective(D);
2706}
2707
2708void
2709EnqueueVisitor::VisitOMPTaskyieldDirective(const OMPTaskyieldDirective *D) {
2710 VisitOMPExecutableDirective(D);
2711}
2712
2713void EnqueueVisitor::VisitOMPBarrierDirective(const OMPBarrierDirective *D) {
2714 VisitOMPExecutableDirective(D);
2715}
2716
2717void EnqueueVisitor::VisitOMPTaskwaitDirective(const OMPTaskwaitDirective *D) {
2718 VisitOMPExecutableDirective(D);
2719}
2720
2721void EnqueueVisitor::VisitOMPTaskgroupDirective(
2722 const OMPTaskgroupDirective *D) {
2723 VisitOMPExecutableDirective(D);
2724}
2725
2726void EnqueueVisitor::VisitOMPFlushDirective(const OMPFlushDirective *D) {
2727 VisitOMPExecutableDirective(D);
2728}
2729
2730void EnqueueVisitor::VisitOMPOrderedDirective(const OMPOrderedDirective *D) {
2731 VisitOMPExecutableDirective(D);
2732}
2733
2734void EnqueueVisitor::VisitOMPAtomicDirective(const OMPAtomicDirective *D) {
2735 VisitOMPExecutableDirective(D);
2736}
2737
2738void EnqueueVisitor::VisitOMPTargetDirective(const OMPTargetDirective *D) {
2739 VisitOMPExecutableDirective(D);
2740}
2741
2742void EnqueueVisitor::VisitOMPTargetDataDirective(const
2743 OMPTargetDataDirective *D) {
2744 VisitOMPExecutableDirective(D);
2745}
2746
2747void EnqueueVisitor::VisitOMPTargetEnterDataDirective(
2748 const OMPTargetEnterDataDirective *D) {
2749 VisitOMPExecutableDirective(D);
2750}
2751
2752void EnqueueVisitor::VisitOMPTargetExitDataDirective(
2753 const OMPTargetExitDataDirective *D) {
2754 VisitOMPExecutableDirective(D);
2755}
2756
2757void EnqueueVisitor::VisitOMPTargetParallelDirective(
2758 const OMPTargetParallelDirective *D) {
2759 VisitOMPExecutableDirective(D);
2760}
2761
2762void EnqueueVisitor::VisitOMPTargetParallelForDirective(
2763 const OMPTargetParallelForDirective *D) {
2764 VisitOMPLoopDirective(D);
2765}
2766
2767void EnqueueVisitor::VisitOMPTeamsDirective(const OMPTeamsDirective *D) {
2768 VisitOMPExecutableDirective(D);
2769}
2770
2771void EnqueueVisitor::VisitOMPCancellationPointDirective(
2772 const OMPCancellationPointDirective *D) {
2773 VisitOMPExecutableDirective(D);
2774}
2775
2776void EnqueueVisitor::VisitOMPCancelDirective(const OMPCancelDirective *D) {
2777 VisitOMPExecutableDirective(D);
2778}
2779
2780void EnqueueVisitor::VisitOMPTaskLoopDirective(const OMPTaskLoopDirective *D) {
2781 VisitOMPLoopDirective(D);
2782}
2783
2784void EnqueueVisitor::VisitOMPTaskLoopSimdDirective(
2785 const OMPTaskLoopSimdDirective *D) {
2786 VisitOMPLoopDirective(D);
2787}
2788
2789void EnqueueVisitor::VisitOMPDistributeDirective(
2790 const OMPDistributeDirective *D) {
2791 VisitOMPLoopDirective(D);
2792}
2793
2794void EnqueueVisitor::VisitOMPDistributeParallelForDirective(
2795 const OMPDistributeParallelForDirective *D) {
2796 VisitOMPLoopDirective(D);
2797}
2798
2799void EnqueueVisitor::VisitOMPDistributeParallelForSimdDirective(
2800 const OMPDistributeParallelForSimdDirective *D) {
2801 VisitOMPLoopDirective(D);
2802}
2803
2804void EnqueueVisitor::VisitOMPDistributeSimdDirective(
2805 const OMPDistributeSimdDirective *D) {
2806 VisitOMPLoopDirective(D);
2807}
2808
2809void EnqueueVisitor::VisitOMPTargetParallelForSimdDirective(
2810 const OMPTargetParallelForSimdDirective *D) {
2811 VisitOMPLoopDirective(D);
2812}
2813
2814void EnqueueVisitor::VisitOMPTargetSimdDirective(
2815 const OMPTargetSimdDirective *D) {
2816 VisitOMPLoopDirective(D);
2817}
2818
2819void EnqueueVisitor::VisitOMPTeamsDistributeDirective(
2820 const OMPTeamsDistributeDirective *D) {
2821 VisitOMPLoopDirective(D);
2822}
2823
2824void EnqueueVisitor::VisitOMPTeamsDistributeSimdDirective(
2825 const OMPTeamsDistributeSimdDirective *D) {
2826 VisitOMPLoopDirective(D);
2827}
2828
2829void EnqueueVisitor::VisitOMPTeamsDistributeParallelForSimdDirective(
2830 const OMPTeamsDistributeParallelForSimdDirective *D) {
2831 VisitOMPLoopDirective(D);
2832}
2833
2834void EnqueueVisitor::VisitOMPTeamsDistributeParallelForDirective(
2835 const OMPTeamsDistributeParallelForDirective *D) {
2836 VisitOMPLoopDirective(D);
2837}
2838
2839void EnqueueVisitor::VisitOMPTargetTeamsDirective(
2840 const OMPTargetTeamsDirective *D) {
2841 VisitOMPExecutableDirective(D);
2842}
2843
2844void EnqueueVisitor::VisitOMPTargetTeamsDistributeDirective(
2845 const OMPTargetTeamsDistributeDirective *D) {
2846 VisitOMPLoopDirective(D);
2847}
2848
2849void EnqueueVisitor::VisitOMPTargetTeamsDistributeParallelForDirective(
2850 const OMPTargetTeamsDistributeParallelForDirective *D) {
2851 VisitOMPLoopDirective(D);
2852}
2853
2854void EnqueueVisitor::VisitOMPTargetTeamsDistributeParallelForSimdDirective(
2855 const OMPTargetTeamsDistributeParallelForSimdDirective *D) {
2856 VisitOMPLoopDirective(D);
2857}
2858
2859void EnqueueVisitor::VisitOMPTargetTeamsDistributeSimdDirective(
2860 const OMPTargetTeamsDistributeSimdDirective *D) {
2861 VisitOMPLoopDirective(D);
2862}
2863
2864void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, const Stmt *S) {
2865 EnqueueVisitor(WL, MakeCXCursor(S, StmtParent, TU,RegionOfInterest)).Visit(S);
2866}
2867
2868bool CursorVisitor::IsInRegionOfInterest(CXCursor C) {
2869 if (RegionOfInterest.isValid()) {
2870 SourceRange Range = getRawCursorExtent(C);
2871 if (Range.isInvalid() || CompareRegionOfInterest(Range))
2872 return false;
2873 }
2874 return true;
2875}
2876
2877bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) {
2878 while (!WL.empty()) {
2879 // Dequeue the worklist item.
2880 VisitorJob LI = WL.pop_back_val();
2881
2882 // Set the Parent field, then back to its old value once we're done.
2883 SetParentRAII SetParent(Parent, StmtParent, LI.getParent());
2884
2885 switch (LI.getKind()) {
2886 case VisitorJob::DeclVisitKind: {
2887 const Decl *D = cast<DeclVisit>(&LI)->get();
2888 if (!D)
2889 continue;
2890
2891 // For now, perform default visitation for Decls.
2892 if (Visit(MakeCXCursor(D, TU, RegionOfInterest,
2893 cast<DeclVisit>(&LI)->isFirst())))
2894 return true;
2895
2896 continue;
2897 }
2898 case VisitorJob::ExplicitTemplateArgsVisitKind: {
2899 for (const TemplateArgumentLoc &Arg :
2900 *cast<ExplicitTemplateArgsVisit>(&LI)) {
2901 if (VisitTemplateArgumentLoc(Arg))
2902 return true;
2903 }
2904 continue;
2905 }
2906 case VisitorJob::TypeLocVisitKind: {
2907 // Perform default visitation for TypeLocs.
2908 if (Visit(cast<TypeLocVisit>(&LI)->get()))
2909 return true;
2910 continue;
2911 }
2912 case VisitorJob::LabelRefVisitKind: {
2913 const LabelDecl *LS = cast<LabelRefVisit>(&LI)->get();
2914 if (LabelStmt *stmt = LS->getStmt()) {
2915 if (Visit(MakeCursorLabelRef(stmt, cast<LabelRefVisit>(&LI)->getLoc(),
2916 TU))) {
2917 return true;
2918 }
2919 }
2920 continue;
2921 }
2922
2923 case VisitorJob::NestedNameSpecifierLocVisitKind: {
2924 NestedNameSpecifierLocVisit *V = cast<NestedNameSpecifierLocVisit>(&LI);
2925 if (VisitNestedNameSpecifierLoc(V->get()))
2926 return true;
2927 continue;
2928 }
2929
2930 case VisitorJob::DeclarationNameInfoVisitKind: {
2931 if (VisitDeclarationNameInfo(cast<DeclarationNameInfoVisit>(&LI)
2932 ->get()))
2933 return true;
2934 continue;
2935 }
2936 case VisitorJob::MemberRefVisitKind: {
2937 MemberRefVisit *V = cast<MemberRefVisit>(&LI);
2938 if (Visit(MakeCursorMemberRef(V->get(), V->getLoc(), TU)))
2939 return true;
2940 continue;
2941 }
2942 case VisitorJob::StmtVisitKind: {
2943 const Stmt *S = cast<StmtVisit>(&LI)->get();
2944 if (!S)
2945 continue;
2946
2947 // Update the current cursor.
2948 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU, RegionOfInterest);
2949 if (!IsInRegionOfInterest(Cursor))
2950 continue;
2951 switch (Visitor(Cursor, Parent, ClientData)) {
2952 case CXChildVisit_Break: return true;
2953 case CXChildVisit_Continue: break;
2954 case CXChildVisit_Recurse:
2955 if (PostChildrenVisitor)
2956 WL.push_back(PostChildrenVisit(nullptr, Cursor));
2957 EnqueueWorkList(WL, S);
2958 break;
2959 }
2960 continue;
2961 }
2962 case VisitorJob::MemberExprPartsKind: {
2963 // Handle the other pieces in the MemberExpr besides the base.
2964 const MemberExpr *M = cast<MemberExprParts>(&LI)->get();
2965
2966 // Visit the nested-name-specifier
2967 if (NestedNameSpecifierLoc QualifierLoc = M->getQualifierLoc())
2968 if (VisitNestedNameSpecifierLoc(QualifierLoc))
2969 return true;
2970
2971 // Visit the declaration name.
2972 if (VisitDeclarationNameInfo(M->getMemberNameInfo()))
2973 return true;
2974
2975 // Visit the explicitly-specified template arguments, if any.
2976 if (M->hasExplicitTemplateArgs()) {
2977 for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(),
2978 *ArgEnd = Arg + M->getNumTemplateArgs();
2979 Arg != ArgEnd; ++Arg) {
2980 if (VisitTemplateArgumentLoc(*Arg))
2981 return true;
2982 }
2983 }
2984 continue;
2985 }
2986 case VisitorJob::DeclRefExprPartsKind: {
2987 const DeclRefExpr *DR = cast<DeclRefExprParts>(&LI)->get();
2988 // Visit nested-name-specifier, if present.
2989 if (NestedNameSpecifierLoc QualifierLoc = DR->getQualifierLoc())
2990 if (VisitNestedNameSpecifierLoc(QualifierLoc))
2991 return true;
2992 // Visit declaration name.
2993 if (VisitDeclarationNameInfo(DR->getNameInfo()))
2994 return true;
2995 continue;
2996 }
2997 case VisitorJob::OverloadExprPartsKind: {
2998 const OverloadExpr *O = cast<OverloadExprParts>(&LI)->get();
2999 // Visit the nested-name-specifier.
3000 if (NestedNameSpecifierLoc QualifierLoc = O->getQualifierLoc())
3001 if (VisitNestedNameSpecifierLoc(QualifierLoc))
3002 return true;
3003 // Visit the declaration name.
3004 if (VisitDeclarationNameInfo(O->getNameInfo()))
3005 return true;
3006 // Visit the overloaded declaration reference.
3007 if (Visit(MakeCursorOverloadedDeclRef(O, TU)))
3008 return true;
3009 continue;
3010 }
3011 case VisitorJob::SizeOfPackExprPartsKind: {
3012 const SizeOfPackExpr *E = cast<SizeOfPackExprParts>(&LI)->get();
3013 NamedDecl *Pack = E->getPack();
3014 if (isa<TemplateTypeParmDecl>(Pack)) {
3015 if (Visit(MakeCursorTypeRef(cast<TemplateTypeParmDecl>(Pack),
3016 E->getPackLoc(), TU)))
3017 return true;
3018
3019 continue;
3020 }
3021
3022 if (isa<TemplateTemplateParmDecl>(Pack)) {
3023 if (Visit(MakeCursorTemplateRef(cast<TemplateTemplateParmDecl>(Pack),
3024 E->getPackLoc(), TU)))
3025 return true;
3026
3027 continue;
3028 }
3029
3030 // Non-type template parameter packs and function parameter packs are
3031 // treated like DeclRefExpr cursors.
3032 continue;
3033 }
3034
3035 case VisitorJob::LambdaExprPartsKind: {
3036 // Visit captures.
3037 const LambdaExpr *E = cast<LambdaExprParts>(&LI)->get();
3038 for (LambdaExpr::capture_iterator C = E->explicit_capture_begin(),
3039 CEnd = E->explicit_capture_end();
3040 C != CEnd; ++C) {
3041 // FIXME: Lambda init-captures.
3042 if (!C->capturesVariable())
3043 continue;
3044
3045 if (Visit(MakeCursorVariableRef(C->getCapturedVar(),
3046 C->getLocation(),
3047 TU)))
3048 return true;
3049 }
3050
3051 // Visit parameters and return type, if present.
3052 if (E->hasExplicitParameters() || E->hasExplicitResultType()) {
3053 TypeLoc TL = E->getCallOperator()->getTypeSourceInfo()->getTypeLoc();
3054 if (E->hasExplicitParameters() && E->hasExplicitResultType()) {
3055 // Visit the whole type.
3056 if (Visit(TL))
3057 return true;
3058 } else if (FunctionProtoTypeLoc Proto =
3059 TL.getAs<FunctionProtoTypeLoc>()) {
3060 if (E->hasExplicitParameters()) {
3061 // Visit parameters.
3062 for (unsigned I = 0, N = Proto.getNumParams(); I != N; ++I)
3063 if (Visit(MakeCXCursor(Proto.getParam(I), TU)))
3064 return true;
3065 } else {
3066 // Visit result type.
3067 if (Visit(Proto.getReturnLoc()))
3068 return true;
3069 }
3070 }
3071 }
3072 break;
3073 }
3074
3075 case VisitorJob::PostChildrenVisitKind:
3076 if (PostChildrenVisitor(Parent, ClientData))
3077 return true;
3078 break;
3079 }
3080 }
3081 return false;
3082}
3083
3084bool CursorVisitor::Visit(const Stmt *S) {
3085 VisitorWorkList *WL = nullptr;
3086 if (!WorkListFreeList.empty()) {
3087 WL = WorkListFreeList.back();
3088 WL->clear();
3089 WorkListFreeList.pop_back();
3090 }
3091 else {
3092 WL = new VisitorWorkList();
3093 WorkListCache.push_back(WL);
3094 }
3095 EnqueueWorkList(*WL, S);
3096 bool result = RunVisitorWorkList(*WL);
3097 WorkListFreeList.push_back(WL);
3098 return result;
3099}
3100
3101namespace {
3102typedef SmallVector<SourceRange, 4> RefNamePieces;
3103RefNamePieces buildPieces(unsigned NameFlags, bool IsMemberRefExpr,
3104 const DeclarationNameInfo &NI, SourceRange QLoc,
3105 const SourceRange *TemplateArgsLoc = nullptr) {
3106 const bool WantQualifier = NameFlags & CXNameRange_WantQualifier;
3107 const bool WantTemplateArgs = NameFlags & CXNameRange_WantTemplateArgs;
3108 const bool WantSinglePiece = NameFlags & CXNameRange_WantSinglePiece;
3109
3110 const DeclarationName::NameKind Kind = NI.getName().getNameKind();
3111
3112 RefNamePieces Pieces;
3113
3114 if (WantQualifier && QLoc.isValid())
3115 Pieces.push_back(QLoc);
3116
3117 if (Kind != DeclarationName::CXXOperatorName || IsMemberRefExpr)
3118 Pieces.push_back(NI.getLoc());
3119
3120 if (WantTemplateArgs && TemplateArgsLoc && TemplateArgsLoc->isValid())
3121 Pieces.push_back(*TemplateArgsLoc);
3122
3123 if (Kind == DeclarationName::CXXOperatorName) {
3124 Pieces.push_back(SourceLocation::getFromRawEncoding(
3125 NI.getInfo().CXXOperatorName.BeginOpNameLoc));
3126 Pieces.push_back(SourceLocation::getFromRawEncoding(
3127 NI.getInfo().CXXOperatorName.EndOpNameLoc));
3128 }
3129
3130 if (WantSinglePiece) {
3131 SourceRange R(Pieces.front().getBegin(), Pieces.back().getEnd());
3132 Pieces.clear();
3133 Pieces.push_back(R);
3134 }
3135
3136 return Pieces;
3137}
3138}
3139
3140//===----------------------------------------------------------------------===//
3141// Misc. API hooks.
3142//===----------------------------------------------------------------------===//
3143
3144static void fatal_error_handler(void *user_data, const std::string& reason,
3145 bool gen_crash_diag) {
3146 // Write the result out to stderr avoiding errs() because raw_ostreams can
3147 // call report_fatal_error.
3148 fprintf(stderrstderr, "LIBCLANG FATAL ERROR: %s\n", reason.c_str());
3149 ::abort();
3150}
3151
3152namespace {
3153struct RegisterFatalErrorHandler {
3154 RegisterFatalErrorHandler() {
3155 llvm::install_fatal_error_handler(fatal_error_handler, nullptr);
3156 }
3157};
3158}
3159
3160static llvm::ManagedStatic<RegisterFatalErrorHandler> RegisterFatalErrorHandlerOnce;
3161
3162CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
3163 int displayDiagnostics) {
3164 // We use crash recovery to make some of our APIs more reliable, implicitly
3165 // enable it.
3166 if (!getenv("LIBCLANG_DISABLE_CRASH_RECOVERY"))
3167 llvm::CrashRecoveryContext::Enable();
3168
3169 // Look through the managed static to trigger construction of the managed
3170 // static which registers our fatal error handler. This ensures it is only
3171 // registered once.
3172 (void)*RegisterFatalErrorHandlerOnce;
3173
3174 // Initialize targets for clang module support.
3175 llvm::InitializeAllTargets();
3176 llvm::InitializeAllTargetMCs();
3177 llvm::InitializeAllAsmPrinters();
3178 llvm::InitializeAllAsmParsers();
3179
3180 CIndexer *CIdxr = new CIndexer();
3181
3182 if (excludeDeclarationsFromPCH)
3183 CIdxr->setOnlyLocalDecls();
3184 if (displayDiagnostics)
3185 CIdxr->setDisplayDiagnostics();
3186
3187 if (getenv("LIBCLANG_BGPRIO_INDEX"))
3188 CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() |
3189 CXGlobalOpt_ThreadBackgroundPriorityForIndexing);
3190 if (getenv("LIBCLANG_BGPRIO_EDIT"))
3191 CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() |
3192 CXGlobalOpt_ThreadBackgroundPriorityForEditing);
3193
3194 return CIdxr;
3195}
3196
3197void clang_disposeIndex(CXIndex CIdx) {
3198 if (CIdx)
3199 delete static_cast<CIndexer *>(CIdx);
3200}
3201
3202void clang_CXIndex_setGlobalOptions(CXIndex CIdx, unsigned options) {
3203 if (CIdx)
3204 static_cast<CIndexer *>(CIdx)->setCXGlobalOptFlags(options);
3205}
3206
3207unsigned clang_CXIndex_getGlobalOptions(CXIndex CIdx) {
3208 if (CIdx)
3209 return static_cast<CIndexer *>(CIdx)->getCXGlobalOptFlags();
3210 return 0;
3211}
3212
3213void clang_toggleCrashRecovery(unsigned isEnabled) {
3214 if (isEnabled)
3215 llvm::CrashRecoveryContext::Enable();
3216 else
3217 llvm::CrashRecoveryContext::Disable();
3218}
3219
3220CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
3221 const char *ast_filename) {
3222 CXTranslationUnit TU;
3223 enum CXErrorCode Result =
3224 clang_createTranslationUnit2(CIdx, ast_filename, &TU);
3225 (void)Result;
3226 assert((TU && Result == CXError_Success) ||(((TU && Result == CXError_Success) || (!TU &&
Result != CXError_Success)) ? static_cast<void> (0) : __assert_fail
("(TU && Result == CXError_Success) || (!TU && Result != CXError_Success)"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/tools/libclang/CIndex.cpp"
, 3227, __PRETTY_FUNCTION__))
3227 (!TU && Result != CXError_Success))(((TU && Result == CXError_Success) || (!TU &&
Result != CXError_Success)) ? static_cast<void> (0) : __assert_fail
("(TU && Result == CXError_Success) || (!TU && Result != CXError_Success)"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/tools/libclang/CIndex.cpp"
, 3227, __PRETTY_FUNCTION__))
;
3228 return TU;
3229}
3230
3231enum CXErrorCode clang_createTranslationUnit2(CXIndex CIdx,
3232 const char *ast_filename,
3233 CXTranslationUnit *out_TU) {
3234 if (out_TU)
3235 *out_TU = nullptr;
3236
3237 if (!CIdx || !ast_filename || !out_TU)
3238 return CXError_InvalidArguments;
3239
3240 LOG_FUNC_SECTIONif (clang::cxindex::LogRef Log = clang::cxindex::Logger::make
(__func__))
{
3241 *Log << ast_filename;
3242 }
3243
3244 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
3245 FileSystemOptions FileSystemOpts;
3246
3247 IntrusiveRefCntPtr<DiagnosticsEngine> Diags =
3248 CompilerInstance::createDiagnostics(new DiagnosticOptions());
3249 std::unique_ptr<ASTUnit> AU = ASTUnit::LoadFromASTFile(
3250 ast_filename, CXXIdx->getPCHContainerOperations()->getRawReader(), Diags,
3251 FileSystemOpts, /*UseDebugInfo=*/false,
3252 CXXIdx->getOnlyLocalDecls(), None,
3253 /*CaptureDiagnostics=*/true,
3254 /*AllowPCHWithCompilerErrors=*/true,
3255 /*UserFilesAreVolatile=*/true);
3256 *out_TU = MakeCXTranslationUnit(CXXIdx, std::move(AU));
3257 return *out_TU ? CXError_Success : CXError_Failure;
3258}
3259
3260unsigned clang_defaultEditingTranslationUnitOptions() {
3261 return CXTranslationUnit_PrecompiledPreamble |
3262 CXTranslationUnit_CacheCompletionResults;
3263}
3264
3265CXTranslationUnit
3266clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
3267 const char *source_filename,
3268 int num_command_line_args,
3269 const char * const *command_line_args,
3270 unsigned num_unsaved_files,
3271 struct CXUnsavedFile *unsaved_files) {
3272 unsigned Options = CXTranslationUnit_DetailedPreprocessingRecord;
3273 return clang_parseTranslationUnit(CIdx, source_filename,
3274 command_line_args, num_command_line_args,
3275 unsaved_files, num_unsaved_files,
3276 Options);
3277}
3278
3279static CXErrorCode
3280clang_parseTranslationUnit_Impl(CXIndex CIdx, const char *source_filename,
3281 const char *const *command_line_args,
3282 int num_command_line_args,
3283 ArrayRef<CXUnsavedFile> unsaved_files,
3284 unsigned options, CXTranslationUnit *out_TU) {
3285 // Set up the initial return values.
3286 if (out_TU)
3287 *out_TU = nullptr;
3288
3289 // Check arguments.
3290 if (!CIdx || !out_TU)
3291 return CXError_InvalidArguments;
3292
3293 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
3294
3295 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
3296 setThreadBackgroundPriority();
3297
3298 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
3299 bool CreatePreambleOnFirstParse =
3300 options & CXTranslationUnit_CreatePreambleOnFirstParse;
3301 // FIXME: Add a flag for modules.
3302 TranslationUnitKind TUKind
3303 = (options & CXTranslationUnit_Incomplete)? TU_Prefix : TU_Complete;
3304 bool CacheCodeCompletionResults
3305 = options & CXTranslationUnit_CacheCompletionResults;
3306 bool IncludeBriefCommentsInCodeCompletion
3307 = options & CXTranslationUnit_IncludeBriefCommentsInCodeCompletion;
3308 bool SkipFunctionBodies = options & CXTranslationUnit_SkipFunctionBodies;
3309 bool ForSerialization = options & CXTranslationUnit_ForSerialization;
3310
3311 // Configure the diagnostics.
3312 IntrusiveRefCntPtr<DiagnosticsEngine>
3313 Diags(CompilerInstance::createDiagnostics(new DiagnosticOptions));
3314
3315 if (options & CXTranslationUnit_KeepGoing)
3316 Diags->setSuppressAfterFatalError(false);
3317
3318 // Recover resources if we crash before exiting this function.
3319 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
3320 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
3321 DiagCleanup(Diags.get());
3322
3323 std::unique_ptr<std::vector<ASTUnit::RemappedFile>> RemappedFiles(
3324 new std::vector<ASTUnit::RemappedFile>());
3325
3326 // Recover resources if we crash before exiting this function.
3327 llvm::CrashRecoveryContextCleanupRegistrar<
3328 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
3329
3330 for (auto &UF : unsaved_files) {
3331 std::unique_ptr<llvm::MemoryBuffer> MB =
3332 llvm::MemoryBuffer::getMemBufferCopy(getContents(UF), UF.Filename);
3333 RemappedFiles->push_back(std::make_pair(UF.Filename, MB.release()));
3334 }
3335
3336 std::unique_ptr<std::vector<const char *>> Args(
3337 new std::vector<const char *>());
3338
3339 // Recover resources if we crash before exiting this method.
3340 llvm::CrashRecoveryContextCleanupRegistrar<std::vector<const char*> >
3341 ArgsCleanup(Args.get());
3342
3343 // Since the Clang C library is primarily used by batch tools dealing with
3344 // (often very broken) source code, where spell-checking can have a
3345 // significant negative impact on performance (particularly when
3346 // precompiled headers are involved), we disable it by default.
3347 // Only do this if we haven't found a spell-checking-related argument.
3348 bool FoundSpellCheckingArgument = false;
3349 for (int I = 0; I != num_command_line_args; ++I) {
3350 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
3351 strcmp(command_line_args[I], "-fspell-checking") == 0) {
3352 FoundSpellCheckingArgument = true;
3353 break;
3354 }
3355 }
3356 Args->insert(Args->end(), command_line_args,
3357 command_line_args + num_command_line_args);
3358
3359 if (!FoundSpellCheckingArgument)
3360 Args->insert(Args->begin() + 1, "-fno-spell-checking");
3361
3362 // The 'source_filename' argument is optional. If the caller does not
3363 // specify it then it is assumed that the source file is specified
3364 // in the actual argument list.
3365 // Put the source file after command_line_args otherwise if '-x' flag is
3366 // present it will be unused.
3367 if (source_filename)
3368 Args->push_back(source_filename);
3369
3370 // Do we need the detailed preprocessing record?
3371 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
3372 Args->push_back("-Xclang");
3373 Args->push_back("-detailed-preprocessing-record");
3374 }
3375
3376 // Suppress any editor placeholder diagnostics.
3377 Args->push_back("-fallow-editor-placeholders");
3378
3379 unsigned NumErrors = Diags->getClient()->getNumErrors();
3380 std::unique_ptr<ASTUnit> ErrUnit;
3381 // Unless the user specified that they want the preamble on the first parse
3382 // set it up to be created on the first reparse. This makes the first parse
3383 // faster, trading for a slower (first) reparse.
3384 unsigned PrecompilePreambleAfterNParses =
3385 !PrecompilePreamble ? 0 : 2 - CreatePreambleOnFirstParse;
3386 std::unique_ptr<ASTUnit> Unit(ASTUnit::LoadFromCommandLine(
3387 Args->data(), Args->data() + Args->size(),
3388 CXXIdx->getPCHContainerOperations(), Diags,
3389 CXXIdx->getClangResourcesPath(), CXXIdx->getOnlyLocalDecls(),
3390 /*CaptureDiagnostics=*/true, *RemappedFiles.get(),
3391 /*RemappedFilesKeepOriginalName=*/true, PrecompilePreambleAfterNParses,
3392 TUKind, CacheCodeCompletionResults, IncludeBriefCommentsInCodeCompletion,
3393 /*AllowPCHWithCompilerErrors=*/true, SkipFunctionBodies,
3394 /*UserFilesAreVolatile=*/true, ForSerialization,
3395 CXXIdx->getPCHContainerOperations()->getRawReader().getFormat(),
3396 &ErrUnit));
3397
3398 // Early failures in LoadFromCommandLine may return with ErrUnit unset.
3399 if (!Unit && !ErrUnit)
3400 return CXError_ASTReadError;
3401
3402 if (NumErrors != Diags->getClient()->getNumErrors()) {
3403 // Make sure to check that 'Unit' is non-NULL.
3404 if (CXXIdx->getDisplayDiagnostics())
3405 printDiagsToStderr(Unit ? Unit.get() : ErrUnit.get());
3406 }
3407
3408 if (isASTReadError(Unit ? Unit.get() : ErrUnit.get()))
3409 return CXError_ASTReadError;
3410
3411 *out_TU = MakeCXTranslationUnit(CXXIdx, std::move(Unit));
3412 return *out_TU ? CXError_Success : CXError_Failure;
3413}
3414
3415CXTranslationUnit
3416clang_parseTranslationUnit(CXIndex CIdx,
3417 const char *source_filename,
3418 const char *const *command_line_args,
3419 int num_command_line_args,
3420 struct CXUnsavedFile *unsaved_files,
3421 unsigned num_unsaved_files,
3422 unsigned options) {
3423 CXTranslationUnit TU;
3424 enum CXErrorCode Result = clang_parseTranslationUnit2(
3425 CIdx, source_filename, command_line_args, num_command_line_args,
3426 unsaved_files, num_unsaved_files, options, &TU);
3427 (void)Result;
3428 assert((TU && Result == CXError_Success) ||(((TU && Result == CXError_Success) || (!TU &&
Result != CXError_Success)) ? static_cast<void> (0) : __assert_fail
("(TU && Result == CXError_Success) || (!TU && Result != CXError_Success)"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/tools/libclang/CIndex.cpp"
, 3429, __PRETTY_FUNCTION__))
3429 (!TU && Result != CXError_Success))(((TU && Result == CXError_Success) || (!TU &&
Result != CXError_Success)) ? static_cast<void> (0) : __assert_fail
("(TU && Result == CXError_Success) || (!TU && Result != CXError_Success)"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/tools/libclang/CIndex.cpp"
, 3429, __PRETTY_FUNCTION__))
;
3430 return TU;
3431}
3432
3433enum CXErrorCode clang_parseTranslationUnit2(
3434 CXIndex CIdx, const char *source_filename,
3435 const char *const *command_line_args, int num_command_line_args,
3436 struct CXUnsavedFile *unsaved_files, unsigned num_unsaved_files,
3437 unsigned options, CXTranslationUnit *out_TU) {
3438 SmallVector<const char *, 4> Args;
3439 Args.push_back("clang");
3440 Args.append(command_line_args, command_line_args + num_command_line_args);
3441 return clang_parseTranslationUnit2FullArgv(
3442 CIdx, source_filename, Args.data(), Args.size(), unsaved_files,
3443 num_unsaved_files, options, out_TU);
3444}
3445
3446enum CXErrorCode clang_parseTranslationUnit2FullArgv(
3447 CXIndex CIdx, const char *source_filename,
3448 const char *const *command_line_args, int num_command_line_args,
3449 struct CXUnsavedFile *unsaved_files, unsigned num_unsaved_files,
3450 unsigned options, CXTranslationUnit *out_TU) {
3451 LOG_FUNC_SECTIONif (clang::cxindex::LogRef Log = clang::cxindex::Logger::make
(__func__))
{
3452 *Log << source_filename << ": ";
3453 for (int i = 0; i != num_command_line_args; ++i)
3454 *Log << command_line_args[i] << " ";
3455 }
3456
3457 if (num_unsaved_files && !unsaved_files)
3458 return CXError_InvalidArguments;
3459
3460 CXErrorCode result = CXError_Failure;
3461 auto ParseTranslationUnitImpl = [=, &result] {
3462 result = clang_parseTranslationUnit_Impl(
3463 CIdx, source_filename, command_line_args, num_command_line_args,
3464 llvm::makeArrayRef(unsaved_files, num_unsaved_files), options, out_TU);
3465 };
3466 llvm::CrashRecoveryContext CRC;
3467
3468 if (!RunSafely(CRC, ParseTranslationUnitImpl)) {
3469 fprintf(stderrstderr, "libclang: crash detected during parsing: {\n");
3470 fprintf(stderrstderr, " 'source_filename' : '%s'\n", source_filename);
3471 fprintf(stderrstderr, " 'command_line_args' : [");
3472 for (int i = 0; i != num_command_line_args; ++i) {
3473 if (i)
3474 fprintf(stderrstderr, ", ");
3475 fprintf(stderrstderr, "'%s'", command_line_args[i]);
3476 }
3477 fprintf(stderrstderr, "],\n");
3478 fprintf(stderrstderr, " 'unsaved_files' : [");
3479 for (unsigned i = 0; i != num_unsaved_files; ++i) {
3480 if (i)
3481 fprintf(stderrstderr, ", ");
3482 fprintf(stderrstderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
3483 unsaved_files[i].Length);
3484 }
3485 fprintf(stderrstderr, "],\n");
3486 fprintf(stderrstderr, " 'options' : %d,\n", options);
3487 fprintf(stderrstderr, "}\n");
3488
3489 return CXError_Crashed;
3490 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
3491 if (CXTranslationUnit *TU = out_TU)
3492 PrintLibclangResourceUsage(*TU);
3493 }
3494
3495 return result;
3496}
3497
3498CXString clang_Type_getObjCEncoding(CXType CT) {
3499 CXTranslationUnit tu = static_cast<CXTranslationUnit>(CT.data[1]);
3500 ASTContext &Ctx = getASTUnit(tu)->getASTContext();
3501 std::string encoding;
3502 Ctx.getObjCEncodingForType(QualType::getFromOpaquePtr(CT.data[0]),
3503 encoding);
3504
3505 return cxstring::createDup(encoding);
3506}
3507
3508static const IdentifierInfo *getMacroIdentifier(CXCursor C) {
3509 if (C.kind == CXCursor_MacroDefinition) {
3510 if (const MacroDefinitionRecord *MDR = getCursorMacroDefinition(C))
3511 return MDR->getName();
3512 } else if (C.kind == CXCursor_MacroExpansion) {
3513 MacroExpansionCursor ME = getCursorMacroExpansion(C);
3514 return ME.getName();
3515 }
3516 return nullptr;
3517}
3518
3519unsigned clang_Cursor_isMacroFunctionLike(CXCursor C) {
3520 const IdentifierInfo *II = getMacroIdentifier(C);
3521 if (!II) {
3522 return false;
3523 }
3524 ASTUnit *ASTU = getCursorASTUnit(C);
3525 Preprocessor &PP = ASTU->getPreprocessor();
3526 if (const MacroInfo *MI = PP.getMacroInfo(II))
3527 return MI->isFunctionLike();
3528 return false;
3529}
3530
3531unsigned clang_Cursor_isMacroBuiltin(CXCursor C) {
3532 const IdentifierInfo *II = getMacroIdentifier(C);
3533 if (!II) {
3534 return false;
3535 }
3536 ASTUnit *ASTU = getCursorASTUnit(C);
3537 Preprocessor &PP = ASTU->getPreprocessor();
3538 if (const MacroInfo *MI = PP.getMacroInfo(II))
3539 return MI->isBuiltinMacro();
3540 return false;
3541}
3542
3543unsigned clang_Cursor_isFunctionInlined(CXCursor C) {
3544 const Decl *D = getCursorDecl(C);
3545 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
3546 if (!FD) {
3547 return false;
3548 }
3549 return FD->isInlined();
3550}
3551
3552static StringLiteral* getCFSTR_value(CallExpr *callExpr) {
3553 if (callExpr->getNumArgs() != 1) {
3554 return nullptr;
3555 }
3556
3557 StringLiteral *S = nullptr;
3558 auto *arg = callExpr->getArg(0);
3559 if (arg->getStmtClass() == Stmt::ImplicitCastExprClass) {
3560 ImplicitCastExpr *I = static_cast<ImplicitCastExpr *>(arg);
3561 auto *subExpr = I->getSubExprAsWritten();
3562
3563 if(subExpr->getStmtClass() != Stmt::StringLiteralClass){
3564 return nullptr;
3565 }
3566
3567 S = static_cast<StringLiteral *>(I->getSubExprAsWritten());
3568 } else if (arg->getStmtClass() == Stmt::StringLiteralClass) {
3569 S = static_cast<StringLiteral *>(callExpr->getArg(0));
3570 } else {
3571 return nullptr;
3572 }
3573 return S;
3574}
3575
3576struct ExprEvalResult {
3577 CXEvalResultKind EvalType;
3578 union {
3579 unsigned long long unsignedVal;
3580 long long intVal;
3581 double floatVal;
3582 char *stringVal;
3583 } EvalData;
3584 bool IsUnsignedInt;
3585 ~ExprEvalResult() {
3586 if (EvalType != CXEval_UnExposed && EvalType != CXEval_Float &&
3587 EvalType != CXEval_Int) {
3588 delete EvalData.stringVal;
3589 }
3590 }
3591};
3592
3593void clang_EvalResult_dispose(CXEvalResult E) {
3594 delete static_cast<ExprEvalResult *>(E);
3595}
3596
3597CXEvalResultKind clang_EvalResult_getKind(CXEvalResult E) {
3598 if (!E) {
3599 return CXEval_UnExposed;
3600 }
3601 return ((ExprEvalResult *)E)->EvalType;
3602}
3603
3604int clang_EvalResult_getAsInt(CXEvalResult E) {
3605 return clang_EvalResult_getAsLongLong(E);
3606}
3607
3608long long clang_EvalResult_getAsLongLong(CXEvalResult E) {
3609 if (!E) {
3610 return 0;
3611 }
3612 ExprEvalResult *Result = (ExprEvalResult*)E;
3613 if (Result->IsUnsignedInt)
3614 return Result->EvalData.unsignedVal;
3615 return Result->EvalData.intVal;
3616}
3617
3618unsigned clang_EvalResult_isUnsignedInt(CXEvalResult E) {
3619 return ((ExprEvalResult *)E)->IsUnsignedInt;
3620}
3621
3622unsigned long long clang_EvalResult_getAsUnsigned(CXEvalResult E) {
3623 if (!E) {
3624 return 0;
3625 }
3626
3627 ExprEvalResult *Result = (ExprEvalResult*)E;
3628 if (Result->IsUnsignedInt)
3629 return Result->EvalData.unsignedVal;
3630 return Result->EvalData.intVal;
3631}
3632
3633double clang_EvalResult_getAsDouble(CXEvalResult E) {
3634 if (!E) {
3635 return 0;
3636 }
3637 return ((ExprEvalResult *)E)->EvalData.floatVal;
3638}
3639
3640const char* clang_EvalResult_getAsStr(CXEvalResult E) {
3641 if (!E) {
3642 return nullptr;
3643 }
3644 return ((ExprEvalResult *)E)->EvalData.stringVal;
3645}
3646
3647static const ExprEvalResult* evaluateExpr(Expr *expr, CXCursor C) {
3648 Expr::EvalResult ER;
3649 ASTContext &ctx = getCursorContext(C);
3650 if (!expr)
3651 return nullptr;
3652
3653 expr = expr->IgnoreParens();
3654 if (!expr->EvaluateAsRValue(ER, ctx))
3655 return nullptr;
3656
3657 QualType rettype;
3658 CallExpr *callExpr;
3659 auto result = llvm::make_unique<ExprEvalResult>();
3660 result->EvalType = CXEval_UnExposed;
3661 result->IsUnsignedInt = false;
3662
3663 if (ER.Val.isInt()) {
3664 result->EvalType = CXEval_Int;
3665
3666 auto& val = ER.Val.getInt();
3667 if (val.isUnsigned()) {
3668 result->IsUnsignedInt = true;
3669 result->EvalData.unsignedVal = val.getZExtValue();
3670 } else {
3671 result->EvalData.intVal = val.getExtValue();
3672 }
3673
3674 return result.release();
3675 }
3676
3677 if (ER.Val.isFloat()) {
3678 llvm::SmallVector<char, 100> Buffer;
3679 ER.Val.getFloat().toString(Buffer);
3680 std::string floatStr(Buffer.data(), Buffer.size());
3681 result->EvalType = CXEval_Float;
3682 bool ignored;
3683 llvm::APFloat apFloat = ER.Val.getFloat();
3684 apFloat.convert(llvm::APFloat::IEEEdouble(),
3685 llvm::APFloat::rmNearestTiesToEven, &ignored);
3686 result->EvalData.floatVal = apFloat.convertToDouble();
3687 return result.release();
3688 }
3689
3690 if (expr->getStmtClass() == Stmt::ImplicitCastExprClass) {
3691 const ImplicitCastExpr *I = dyn_cast<ImplicitCastExpr>(expr);
3692 auto *subExpr = I->getSubExprAsWritten();
3693 if (subExpr->getStmtClass() == Stmt::StringLiteralClass ||
3694 subExpr->getStmtClass() == Stmt::ObjCStringLiteralClass) {
3695 const StringLiteral *StrE = nullptr;
3696 const ObjCStringLiteral *ObjCExpr;
3697 ObjCExpr = dyn_cast<ObjCStringLiteral>(subExpr);
3698
3699 if (ObjCExpr) {
3700 StrE = ObjCExpr->getString();
3701 result->EvalType = CXEval_ObjCStrLiteral;
3702 } else {
3703 StrE = cast<StringLiteral>(I->getSubExprAsWritten());
3704 result->EvalType = CXEval_StrLiteral;
3705 }
3706
3707 std::string strRef(StrE->getString().str());
3708 result->EvalData.stringVal = new char[strRef.size() + 1];
3709 strncpy((char *)result->EvalData.stringVal, strRef.c_str(),
3710 strRef.size());
3711 result->EvalData.stringVal[strRef.size()] = '\0';
3712 return result.release();
3713 }
3714 } else if (expr->getStmtClass() == Stmt::ObjCStringLiteralClass ||
3715 expr->getStmtClass() == Stmt::StringLiteralClass) {
3716 const StringLiteral *StrE = nullptr;
3717 const ObjCStringLiteral *ObjCExpr;
3718 ObjCExpr = dyn_cast<ObjCStringLiteral>(expr);
3719
3720 if (ObjCExpr) {
3721 StrE = ObjCExpr->getString();
3722 result->EvalType = CXEval_ObjCStrLiteral;
3723 } else {
3724 StrE = cast<StringLiteral>(expr);
3725 result->EvalType = CXEval_StrLiteral;
3726 }
3727
3728 std::string strRef(StrE->getString().str());
3729 result->EvalData.stringVal = new char[strRef.size() + 1];
3730 strncpy((char *)result->EvalData.stringVal, strRef.c_str(), strRef.size());
3731 result->EvalData.stringVal[strRef.size()] = '\0';
3732 return result.release();
3733 }
3734
3735 if (expr->getStmtClass() == Stmt::CStyleCastExprClass) {
3736 CStyleCastExpr *CC = static_cast<CStyleCastExpr *>(expr);
3737
3738 rettype = CC->getType();
3739 if (rettype.getAsString() == "CFStringRef" &&
3740 CC->getSubExpr()->getStmtClass() == Stmt::CallExprClass) {
3741
3742 callExpr = static_cast<CallExpr *>(CC->getSubExpr());
3743 StringLiteral *S = getCFSTR_value(callExpr);
3744 if (S) {
3745 std::string strLiteral(S->getString().str());
3746 result->EvalType = CXEval_CFStr;
3747
3748 result->EvalData.stringVal = new char[strLiteral.size() + 1];
3749 strncpy((char *)result->EvalData.stringVal, strLiteral.c_str(),
3750 strLiteral.size());
3751 result->EvalData.stringVal[strLiteral.size()] = '\0';
3752 return result.release();
3753 }
3754 }
3755
3756 } else if (expr->getStmtClass() == Stmt::CallExprClass) {
3757 callExpr = static_cast<CallExpr *>(expr);
3758 rettype = callExpr->getCallReturnType(ctx);
3759
3760 if (rettype->isVectorType() || callExpr->getNumArgs() > 1)
3761 return nullptr;
3762
3763 if (rettype->isIntegralType(ctx) || rettype->isRealFloatingType()) {
3764 if (callExpr->getNumArgs() == 1 &&
3765 !callExpr->getArg(0)->getType()->isIntegralType(ctx))
3766 return nullptr;
3767 } else if (rettype.getAsString() == "CFStringRef") {
3768
3769 StringLiteral *S = getCFSTR_value(callExpr);
3770 if (S) {
3771 std::string strLiteral(S->getString().str());
3772 result->EvalType = CXEval_CFStr;
3773 result->EvalData.stringVal = new char[strLiteral.size() + 1];
3774 strncpy((char *)result->EvalData.stringVal, strLiteral.c_str(),
3775 strLiteral.size());
3776 result->EvalData.stringVal[strLiteral.size()] = '\0';
3777 return result.release();
3778 }
3779 }
3780 } else if (expr->getStmtClass() == Stmt::DeclRefExprClass) {
3781 DeclRefExpr *D = static_cast<DeclRefExpr *>(expr);
3782 ValueDecl *V = D->getDecl();
3783 if (V->getKind() == Decl::Function) {
3784 std::string strName = V->getNameAsString();
3785 result->EvalType = CXEval_Other;
3786 result->EvalData.stringVal = new char[strName.size() + 1];
3787 strncpy(result->EvalData.stringVal, strName.c_str(), strName.size());
3788 result->EvalData.stringVal[strName.size()] = '\0';
3789 return result.release();
3790 }
3791 }
3792
3793 return nullptr;
3794}
3795
3796CXEvalResult clang_Cursor_Evaluate(CXCursor C) {
3797 const Decl *D = getCursorDecl(C);
3798 if (D) {
3799 const Expr *expr = nullptr;
3800 if (auto *Var = dyn_cast<VarDecl>(D)) {
3801 expr = Var->getInit();
3802 } else if (auto *Field = dyn_cast<FieldDecl>(D)) {
3803 expr = Field->getInClassInitializer();
3804 }
3805 if (expr)
3806 return const_cast<CXEvalResult>(reinterpret_cast<const void *>(
3807 evaluateExpr(const_cast<Expr *>(expr), C)));
3808 return nullptr;
3809 }
3810
3811 const CompoundStmt *compoundStmt = dyn_cast_or_null<CompoundStmt>(getCursorStmt(C));
3812 if (compoundStmt) {
3813 Expr *expr = nullptr;
3814 for (auto *bodyIterator : compoundStmt->body()) {
3815 if ((expr = dyn_cast<Expr>(bodyIterator))) {
3816 break;
3817 }
3818 }
3819 if (expr)
3820 return const_cast<CXEvalResult>(
3821 reinterpret_cast<const void *>(evaluateExpr(expr, C)));
3822 }
3823 return nullptr;
3824}
3825
3826unsigned clang_Cursor_hasAttrs(CXCursor C) {
3827 const Decl *D = getCursorDecl(C);
3828 if (!D) {
3829 return 0;
3830 }
3831
3832 if (D->hasAttrs()) {
3833 return 1;
3834 }
3835
3836 return 0;
3837}
3838unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
3839 return CXSaveTranslationUnit_None;
3840}
3841
3842static CXSaveError clang_saveTranslationUnit_Impl(CXTranslationUnit TU,
3843 const char *FileName,
3844 unsigned options) {
3845 CIndexer *CXXIdx = TU->CIdx;
3846 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
3847 setThreadBackgroundPriority();
3848
3849 bool hadError = cxtu::getASTUnit(TU)->Save(FileName);
3850 return hadError ? CXSaveError_Unknown : CXSaveError_None;
3851}
3852
3853int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
3854 unsigned options) {
3855 LOG_FUNC_SECTIONif (clang::cxindex::LogRef Log = clang::cxindex::Logger::make
(__func__))
{
3856 *Log << TU << ' ' << FileName;
3857 }
3858
3859 if (isNotUsableTU(TU)) {
3860 LOG_BAD_TU(TU)do { if (clang::cxindex::LogRef Log = clang::cxindex::Logger::
make(__func__)) { *Log << "called with a bad TU: " <<
TU; } } while(false)
;
3861 return CXSaveError_InvalidTU;
3862 }
3863
3864 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
3865 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3866 if (!CXXUnit->hasSema())
3867 return CXSaveError_InvalidTU;
3868
3869 CXSaveError result;
3870 auto SaveTranslationUnitImpl = [=, &result]() {
3871 result = clang_saveTranslationUnit_Impl(TU, FileName, options);
3872 };
3873
3874 if (!CXXUnit->getDiagnostics().hasUnrecoverableErrorOccurred() ||
3875 getenv("LIBCLANG_NOTHREADS")) {
3876 SaveTranslationUnitImpl();
3877
3878 if (getenv("LIBCLANG_RESOURCE_USAGE"))
3879 PrintLibclangResourceUsage(TU);
3880
3881 return result;
3882 }
3883
3884 // We have an AST that has invalid nodes due to compiler errors.
3885 // Use a crash recovery thread for protection.
3886
3887 llvm::CrashRecoveryContext CRC;
3888
3889 if (!RunSafely(CRC, SaveTranslationUnitImpl)) {
3890 fprintf(stderrstderr, "libclang: crash detected during AST saving: {\n");
3891 fprintf(stderrstderr, " 'filename' : '%s'\n", FileName);
3892 fprintf(stderrstderr, " 'options' : %d,\n", options);
3893 fprintf(stderrstderr, "}\n");
3894
3895 return CXSaveError_Unknown;
3896
3897 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
3898 PrintLibclangResourceUsage(TU);
3899 }
3900
3901 return result;
3902}
3903
3904void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
3905 if (CTUnit) {
3906 // If the translation unit has been marked as unsafe to free, just discard
3907 // it.
3908 ASTUnit *Unit = cxtu::getASTUnit(CTUnit);
3909 if (Unit && Unit->isUnsafeToFree())
3910 return;
3911
3912 delete cxtu::getASTUnit(CTUnit);
3913 delete CTUnit->StringPool;
3914 delete static_cast<CXDiagnosticSetImpl *>(CTUnit->Diagnostics);
3915 disposeOverridenCXCursorsPool(CTUnit->OverridenCursorsPool);
3916 delete CTUnit->CommentToXML;
3917 delete CTUnit;
3918 }
3919}
3920
3921unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
3922 return CXReparse_None;
3923}
3924
3925static CXErrorCode
3926clang_reparseTranslationUnit_Impl(CXTranslationUnit TU,
3927 ArrayRef<CXUnsavedFile> unsaved_files,
3928 unsigned options) {
3929 // Check arguments.
3930 if (isNotUsableTU(TU)) {
3931 LOG_BAD_TU(TU)do { if (clang::cxindex::LogRef Log = clang::cxindex::Logger::
make(__func__)) { *Log << "called with a bad TU: " <<
TU; } } while(false)
;
3932 return CXError_InvalidArguments;
3933 }
3934
3935 // Reset the associated diagnostics.
3936 delete static_cast<CXDiagnosticSetImpl*>(TU->Diagnostics);
3937 TU->Diagnostics = nullptr;
3938
3939 CIndexer *CXXIdx = TU->CIdx;
3940 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing))
3941 setThreadBackgroundPriority();
3942
3943 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
3944 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3945
3946 std::unique_ptr<std::vector<ASTUnit::RemappedFile>> RemappedFiles(
3947 new std::vector<ASTUnit::RemappedFile>());
3948
3949 // Recover resources if we crash before exiting this function.
3950 llvm::CrashRecoveryContextCleanupRegistrar<
3951 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
3952
3953 for (auto &UF : unsaved_files) {
3954 std::unique_ptr<llvm::MemoryBuffer> MB =
3955 llvm::MemoryBuffer::getMemBufferCopy(getContents(UF), UF.Filename);
3956 RemappedFiles->push_back(std::make_pair(UF.Filename, MB.release()));
3957 }
3958
3959 if (!CXXUnit->Reparse(CXXIdx->getPCHContainerOperations(),
3960 *RemappedFiles.get()))
3961 return CXError_Success;
3962 if (isASTReadError(CXXUnit))
3963 return CXError_ASTReadError;
3964 return CXError_Failure;
3965}
3966
3967int clang_reparseTranslationUnit(CXTranslationUnit TU,
3968 unsigned num_unsaved_files,
3969 struct CXUnsavedFile *unsaved_files,
3970 unsigned options) {
3971 LOG_FUNC_SECTIONif (clang::cxindex::LogRef Log = clang::cxindex::Logger::make
(__func__))
{
3972 *Log << TU;
3973 }
3974
3975 if (num_unsaved_files && !unsaved_files)
1
Assuming 'num_unsaved_files' is 0
3976 return CXError_InvalidArguments;
3977
3978 CXErrorCode result;
3979 auto ReparseTranslationUnitImpl = [=, &result]() {
3980 result = clang_reparseTranslationUnit_Impl(
3981 TU, llvm::makeArrayRef(unsaved_files, num_unsaved_files), options);
3982 };
3983
3984 if (getenv("LIBCLANG_NOTHREADS")) {
2
Assuming the condition is false
3
Taking false branch
3985 ReparseTranslationUnitImpl();
3986 return result;
3987 }
3988
3989 llvm::CrashRecoveryContext CRC;
3990
3991 if (!RunSafely(CRC, ReparseTranslationUnitImpl)) {
4
Assuming the condition is false
5
Taking false branch
3992 fprintf(stderrstderr, "libclang: crash detected during reparsing\n");
3993 cxtu::getASTUnit(TU)->setUnsafeToFree(true);
3994 return CXError_Crashed;
3995 } else if (getenv("LIBCLANG_RESOURCE_USAGE"))
6
Assuming the condition is true
7
Taking true branch
3996 PrintLibclangResourceUsage(TU);
8
Calling 'PrintLibclangResourceUsage'
3997
3998 return result;
3999}
4000
4001
4002CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
4003 if (isNotUsableTU(CTUnit)) {
4004 LOG_BAD_TU(CTUnit)do { if (clang::cxindex::LogRef Log = clang::cxindex::Logger::
make(__func__)) { *Log << "called with a bad TU: " <<
CTUnit; } } while(false)
;
4005 return cxstring::createEmpty();
4006 }
4007
4008 ASTUnit *CXXUnit = cxtu::getASTUnit(CTUnit);
4009 return cxstring::createDup(CXXUnit->getOriginalSourceFileName());
4010}
4011
4012CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
4013 if (isNotUsableTU(TU)) {
4014 LOG_BAD_TU(TU)do { if (clang::cxindex::LogRef Log = clang::cxindex::Logger::
make(__func__)) { *Log << "called with a bad TU: " <<
TU; } } while(false)
;
4015 return clang_getNullCursor();
4016 }
4017
4018 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
4019 return MakeCXCursor(CXXUnit->getASTContext().getTranslationUnitDecl(), TU);
4020}
4021
4022CXTargetInfo clang_getTranslationUnitTargetInfo(CXTranslationUnit CTUnit) {
4023 if (isNotUsableTU(CTUnit)) {
4024 LOG_BAD_TU(CTUnit)do { if (clang::cxindex::LogRef Log = clang::cxindex::Logger::
make(__func__)) { *Log << "called with a bad TU: " <<
CTUnit; } } while(false)
;
4025 return nullptr;
4026 }
4027
4028 CXTargetInfoImpl* impl = new CXTargetInfoImpl();
4029 impl->TranslationUnit = CTUnit;
4030 return impl;
4031}
4032
4033CXString clang_TargetInfo_getTriple(CXTargetInfo TargetInfo) {
4034 if (!TargetInfo)
4035 return cxstring::createEmpty();
4036
4037 CXTranslationUnit CTUnit = TargetInfo->TranslationUnit;
4038 assert(!isNotUsableTU(CTUnit) &&((!isNotUsableTU(CTUnit) && "Unexpected unusable translation unit in TargetInfo"
) ? static_cast<void> (0) : __assert_fail ("!isNotUsableTU(CTUnit) && \"Unexpected unusable translation unit in TargetInfo\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/tools/libclang/CIndex.cpp"
, 4039, __PRETTY_FUNCTION__))
4039 "Unexpected unusable translation unit in TargetInfo")((!isNotUsableTU(CTUnit) && "Unexpected unusable translation unit in TargetInfo"
) ? static_cast<void> (0) : __assert_fail ("!isNotUsableTU(CTUnit) && \"Unexpected unusable translation unit in TargetInfo\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/tools/libclang/CIndex.cpp"
, 4039, __PRETTY_FUNCTION__))
;
4040
4041 ASTUnit *CXXUnit = cxtu::getASTUnit(CTUnit);
4042 std::string Triple =
4043 CXXUnit->getASTContext().getTargetInfo().getTriple().normalize();
4044 return cxstring::createDup(Triple);
4045}
4046
4047int clang_TargetInfo_getPointerWidth(CXTargetInfo TargetInfo) {
4048 if (!TargetInfo)
4049 return -1;
4050
4051 CXTranslationUnit CTUnit = TargetInfo->TranslationUnit;
4052 assert(!isNotUsableTU(CTUnit) &&((!isNotUsableTU(CTUnit) && "Unexpected unusable translation unit in TargetInfo"
) ? static_cast<void> (0) : __assert_fail ("!isNotUsableTU(CTUnit) && \"Unexpected unusable translation unit in TargetInfo\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/tools/libclang/CIndex.cpp"
, 4053, __PRETTY_FUNCTION__))
4053 "Unexpected unusable translation unit in TargetInfo")((!isNotUsableTU(CTUnit) && "Unexpected unusable translation unit in TargetInfo"
) ? static_cast<void> (0) : __assert_fail ("!isNotUsableTU(CTUnit) && \"Unexpected unusable translation unit in TargetInfo\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/tools/libclang/CIndex.cpp"
, 4053, __PRETTY_FUNCTION__))
;
4054
4055 ASTUnit *CXXUnit = cxtu::getASTUnit(CTUnit);
4056 return CXXUnit->getASTContext().getTargetInfo().getMaxPointerWidth();
4057}
4058
4059void clang_TargetInfo_dispose(CXTargetInfo TargetInfo) {
4060 if (!TargetInfo)
4061 return;
4062
4063 delete TargetInfo;
4064}
4065
4066//===----------------------------------------------------------------------===//
4067// CXFile Operations.
4068//===----------------------------------------------------------------------===//
4069
4070CXString clang_getFileName(CXFile SFile) {
4071 if (!SFile)
4072 return cxstring::createNull();
4073
4074 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
4075 return cxstring::createRef(FEnt->getName());
4076}
4077
4078time_t clang_getFileTime(CXFile SFile) {
4079 if (!SFile)
4080 return 0;
4081
4082 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
4083 return FEnt->getModificationTime();
4084}
4085
4086CXFile clang_getFile(CXTranslationUnit TU, const char *file_name) {
4087 if (isNotUsableTU(TU)) {
4088 LOG_BAD_TU(TU)do { if (clang::cxindex::LogRef Log = clang::cxindex::Logger::
make(__func__)) { *Log << "called with a bad TU: " <<
TU; } } while(false)
;
4089 return nullptr;
4090 }
4091
4092 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
4093
4094 FileManager &FMgr = CXXUnit->getFileManager();
4095 return const_cast<FileEntry *>(FMgr.getFile(file_name));
4096}
4097
4098unsigned clang_isFileMultipleIncludeGuarded(CXTranslationUnit TU,
4099 CXFile file) {
4100 if (isNotUsableTU(TU)) {
4101 LOG_BAD_TU(TU)do { if (clang::cxindex::LogRef Log = clang::cxindex::Logger::
make(__func__)) { *Log << "called with a bad TU: " <<
TU; } } while(false)
;
4102 return 0;
4103 }
4104
4105 if (!file)
4106 return 0;
4107
4108 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
4109 FileEntry *FEnt = static_cast<FileEntry *>(file);
4110 return CXXUnit->getPreprocessor().getHeaderSearchInfo()
4111 .isFileMultipleIncludeGuarded(FEnt);
4112}
4113
4114int clang_getFileUniqueID(CXFile file, CXFileUniqueID *outID) {
4115 if (!file || !outID)
4116 return 1;
4117
4118 FileEntry *FEnt = static_cast<FileEntry *>(file);
4119 const llvm::sys::fs::UniqueID &ID = FEnt->getUniqueID();
4120 outID->data[0] = ID.getDevice();
4121 outID->data[1] = ID.getFile();
4122 outID->data[2] = FEnt->getModificationTime();
4123 return 0;
4124}
4125
4126int clang_File_isEqual(CXFile file1, CXFile file2) {
4127 if (file1 == file2)
4128 return true;
4129
4130 if (!file1 || !file2)
4131 return false;
4132
4133 FileEntry *FEnt1 = static_cast<FileEntry *>(file1);
4134 FileEntry *FEnt2 = static_cast<FileEntry *>(file2);
4135 return FEnt1->getUniqueID() == FEnt2->getUniqueID();
4136}
4137
4138//===----------------------------------------------------------------------===//
4139// CXCursor Operations.
4140//===----------------------------------------------------------------------===//
4141
4142static const Decl *getDeclFromExpr(const Stmt *E) {
4143 if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
4144 return getDeclFromExpr(CE->getSubExpr());
4145
4146 if (const DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
4147 return RefExpr->getDecl();
4148 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
4149 return ME->getMemberDecl();
4150 if (const ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
4151 return RE->getDecl();
4152 if (const ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E)) {
4153 if (PRE->isExplicitProperty())
4154 return PRE->getExplicitProperty();
4155 // It could be messaging both getter and setter as in:
4156 // ++myobj.myprop;
4157 // in which case prefer to associate the setter since it is less obvious
4158 // from inspecting the source that the setter is going to get called.
4159 if (PRE->isMessagingSetter())
4160 return PRE->getImplicitPropertySetter();
4161 return PRE->getImplicitPropertyGetter();
4162 }
4163 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
4164 return getDeclFromExpr(POE->getSyntacticForm());
4165 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
4166 if (Expr *Src = OVE->getSourceExpr())
4167 return getDeclFromExpr(Src);
4168
4169 if (const CallExpr *CE = dyn_cast<CallExpr>(E))
4170 return getDeclFromExpr(CE->getCallee());
4171 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(E))
4172 if (!CE->isElidable())
4173 return CE->getConstructor();
4174 if (const CXXInheritedCtorInitExpr *CE =
4175 dyn_cast<CXXInheritedCtorInitExpr>(E))
4176 return CE->getConstructor();
4177 if (const ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
4178 return OME->getMethodDecl();
4179
4180 if (const ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
4181 return PE->getProtocol();
4182 if (const SubstNonTypeTemplateParmPackExpr *NTTP
4183 = dyn_cast<SubstNonTypeTemplateParmPackExpr>(E))
4184 return NTTP->getParameterPack();
4185 if (const SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
4186 if (isa<NonTypeTemplateParmDecl>(SizeOfPack->getPack()) ||
4187 isa<ParmVarDecl>(SizeOfPack->getPack()))
4188 return SizeOfPack->getPack();
4189
4190 return nullptr;
4191}
4192
4193static SourceLocation getLocationFromExpr(const Expr *E) {
4194 if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
4195 return getLocationFromExpr(CE->getSubExpr());
4196
4197 if (const ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
4198 return /*FIXME:*/Msg->getLeftLoc();
4199 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
4200 return DRE->getLocation();
4201 if (const MemberExpr *Member = dyn_cast<MemberExpr>(E))
4202 return Member->getMemberLoc();
4203 if (const ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
4204 return Ivar->getLocation();
4205 if (const SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
4206 return SizeOfPack->getPackLoc();
4207 if (const ObjCPropertyRefExpr *PropRef = dyn_cast<ObjCPropertyRefExpr>(E))
4208 return PropRef->getLocation();
4209
4210 return E->getLocStart();
4211}
4212
4213extern "C" {
4214
4215unsigned clang_visitChildren(CXCursor parent,
4216 CXCursorVisitor visitor,
4217 CXClientData client_data) {
4218 CursorVisitor CursorVis(getCursorTU(parent), visitor, client_data,
4219 /*VisitPreprocessorLast=*/false);
4220 return CursorVis.VisitChildren(parent);
4221}
4222
4223#ifndef __has_feature
4224#define0 __has_feature(x)0 0
4225#endif
4226#if __has_feature(blocks)0
4227typedef enum CXChildVisitResult
4228 (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
4229
4230static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
4231 CXClientData client_data) {
4232 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
4233 return block(cursor, parent);
4234}
4235#else
4236// If we are compiled with a compiler that doesn't have native blocks support,
4237// define and call the block manually, so the
4238typedef struct _CXChildVisitResult
4239{
4240 void *isa;
4241 int flags;
4242 int reserved;
4243 enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor,
4244 CXCursor);
4245} *CXCursorVisitorBlock;
4246
4247static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
4248 CXClientData client_data) {
4249 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
4250 return block->invoke(block, cursor, parent);
4251}
4252#endif
4253
4254
4255unsigned clang_visitChildrenWithBlock(CXCursor parent,
4256 CXCursorVisitorBlock block) {
4257 return clang_visitChildren(parent, visitWithBlock, block);
4258}
4259
4260static CXString getDeclSpelling(const Decl *D) {
4261 if (!D)
4262 return cxstring::createEmpty();
4263
4264 const NamedDecl *ND = dyn_cast<NamedDecl>(D);
4265 if (!ND) {
4266 if (const ObjCPropertyImplDecl *PropImpl =
4267 dyn_cast<ObjCPropertyImplDecl>(D))
4268 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
4269 return cxstring::createDup(Property->getIdentifier()->getName());
4270
4271 if (const ImportDecl *ImportD = dyn_cast<ImportDecl>(D))
4272 if (Module *Mod = ImportD->getImportedModule())
4273 return cxstring::createDup(Mod->getFullModuleName());
4274
4275 return cxstring::createEmpty();
4276 }
4277
4278 if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
4279 return cxstring::createDup(OMD->getSelector().getAsString());
4280
4281 if (const ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
4282 // No, this isn't the same as the code below. getIdentifier() is non-virtual
4283 // and returns different names. NamedDecl returns the class name and
4284 // ObjCCategoryImplDecl returns the category name.
4285 return cxstring::createRef(CIMP->getIdentifier()->getNameStart());
4286
4287 if (isa<UsingDirectiveDecl>(D))
4288 return cxstring::createEmpty();
4289
4290 SmallString<1024> S;
4291 llvm::raw_svector_ostream os(S);
4292 ND->printName(os);
4293
4294 return cxstring::createDup(os.str());
4295}
4296
4297CXString clang_getCursorSpelling(CXCursor C) {
4298 if (clang_isTranslationUnit(C.kind))
4299 return clang_getTranslationUnitSpelling(getCursorTU(C));
4300
4301 if (clang_isReference(C.kind)) {
4302 switch (C.kind) {
4303 case CXCursor_ObjCSuperClassRef: {
4304 const ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
4305 return cxstring::createRef(Super->getIdentifier()->getNameStart());
4306 }
4307 case CXCursor_ObjCClassRef: {
4308 const ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
4309 return cxstring::createRef(Class->getIdentifier()->getNameStart());
4310 }
4311 case CXCursor_ObjCProtocolRef: {
4312 const ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
4313 assert(OID && "getCursorSpelling(): Missing protocol decl")((OID && "getCursorSpelling(): Missing protocol decl"
) ? static_cast<void> (0) : __assert_fail ("OID && \"getCursorSpelling(): Missing protocol decl\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/tools/libclang/CIndex.cpp"
, 4313, __PRETTY_FUNCTION__))
;
4314 return cxstring::createRef(OID->getIdentifier()->getNameStart());
4315 }
4316 case CXCursor_CXXBaseSpecifier: {
4317 const CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
4318 return cxstring::createDup(B->getType().getAsString());
4319 }
4320 case CXCursor_TypeRef: {
4321 const TypeDecl *Type = getCursorTypeRef(C).first;
4322 assert(Type && "Missing type decl")((Type && "Missing type decl") ? static_cast<void>
(0) : __assert_fail ("Type && \"Missing type decl\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/tools/libclang/CIndex.cpp"
, 4322, __PRETTY_FUNCTION__))
;
4323
4324 return cxstring::createDup(getCursorContext(C).getTypeDeclType(Type).
4325 getAsString());
4326 }
4327 case CXCursor_TemplateRef: {
4328 const TemplateDecl *Template = getCursorTemplateRef(C).first;
4329 assert(Template && "Missing template decl")((Template && "Missing template decl") ? static_cast<
void> (0) : __assert_fail ("Template && \"Missing template decl\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/tools/libclang/CIndex.cpp"
, 4329, __PRETTY_FUNCTION__))
;
4330
4331 return cxstring::createDup(Template->getNameAsString());
4332 }
4333
4334 case CXCursor_NamespaceRef: {
4335 const NamedDecl *NS = getCursorNamespaceRef(C).first;
4336 assert(NS && "Missing namespace decl")((NS && "Missing namespace decl") ? static_cast<void
> (0) : __assert_fail ("NS && \"Missing namespace decl\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/tools/libclang/CIndex.cpp"
, 4336, __PRETTY_FUNCTION__))
;
4337
4338 return cxstring::createDup(NS->getNameAsString());
4339 }
4340
4341 case CXCursor_MemberRef: {
4342 const FieldDecl *Field = getCursorMemberRef(C).first;
4343 assert(Field && "Missing member decl")((Field && "Missing member decl") ? static_cast<void
> (0) : __assert_fail ("Field && \"Missing member decl\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/tools/libclang/CIndex.cpp"
, 4343, __PRETTY_FUNCTION__))
;
4344
4345 return cxstring::createDup(Field->getNameAsString());
4346 }
4347
4348 case CXCursor_LabelRef: {
4349 const LabelStmt *Label = getCursorLabelRef(C).first;
4350 assert(Label && "Missing label")((Label && "Missing label") ? static_cast<void>
(0) : __assert_fail ("Label && \"Missing label\"", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/tools/libclang/CIndex.cpp"
, 4350, __PRETTY_FUNCTION__))
;
4351
4352 return cxstring::createRef(Label->getName());
4353 }
4354
4355 case CXCursor_OverloadedDeclRef: {
4356 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
4357 if (const Decl *D = Storage.dyn_cast<const Decl *>()) {
4358 if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
4359 return cxstring::createDup(ND->getNameAsString());
4360 return cxstring::createEmpty();
4361 }
4362 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
4363 return cxstring::createDup(E->getName().getAsString());
4364 OverloadedTemplateStorage *Ovl
4365 = Storage.get<OverloadedTemplateStorage*>();
4366 if (Ovl->size() == 0)
4367 return cxstring::createEmpty();
4368 return cxstring::createDup((*Ovl->begin())->getNameAsString());
4369 }
4370
4371 case CXCursor_VariableRef: {
4372 const VarDecl *Var = getCursorVariableRef(C).first;
4373 assert(Var && "Missing variable decl")((Var && "Missing variable decl") ? static_cast<void
> (0) : __assert_fail ("Var && \"Missing variable decl\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/tools/libclang/CIndex.cpp"
, 4373, __PRETTY_FUNCTION__))
;
4374
4375 return cxstring::createDup(Var->getNameAsString());
4376 }
4377
4378 default:
4379 return cxstring::createRef("<not implemented>");
4380 }
4381 }
4382
4383 if (clang_isExpression(C.kind)) {
4384 const Expr *E = getCursorExpr(C);
4385
4386 if (C.kind == CXCursor_ObjCStringLiteral ||
4387 C.kind == CXCursor_StringLiteral) {
4388 const StringLiteral *SLit;
4389 if (const ObjCStringLiteral *OSL = dyn_cast<ObjCStringLiteral>(E)) {
4390 SLit = OSL->getString();
4391 } else {
4392 SLit = cast<StringLiteral>(E);
4393 }
4394 SmallString<256> Buf;
4395 llvm::raw_svector_ostream OS(Buf);
4396 SLit->outputString(OS);
4397 return cxstring::createDup(OS.str());
4398 }
4399
4400 const Decl *D = getDeclFromExpr(getCursorExpr(C));
4401 if (D)
4402 return getDeclSpelling(D);
4403 return cxstring::createEmpty();
4404 }
4405
4406 if (clang_isStatement(C.kind)) {
4407 const Stmt *S = getCursorStmt(C);
4408 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
4409 return cxstring::createRef(Label->getName());
4410
4411 return cxstring::createEmpty();
4412 }
4413
4414 if (C.kind == CXCursor_MacroExpansion)
4415 return cxstring::createRef(getCursorMacroExpansion(C).getName()
4416 ->getNameStart());
4417
4418 if (C.kind == CXCursor_MacroDefinition)
4419 return cxstring::createRef(getCursorMacroDefinition(C)->getName()
4420 ->getNameStart());
4421
4422 if (C.kind == CXCursor_InclusionDirective)
4423 return cxstring::createDup(getCursorInclusionDirective(C)->getFileName());
4424
4425 if (clang_isDeclaration(C.kind))
4426 return getDeclSpelling(getCursorDecl(C));
4427
4428 if (C.kind == CXCursor_AnnotateAttr) {
4429 const AnnotateAttr *AA = cast<AnnotateAttr>(cxcursor::getCursorAttr(C));
4430 return cxstring::createDup(AA->getAnnotation());
4431 }
4432
4433 if (C.kind == CXCursor_AsmLabelAttr) {
4434 const AsmLabelAttr *AA = cast<AsmLabelAttr>(cxcursor::getCursorAttr(C));
4435 return cxstring::createDup(AA->getLabel());
4436 }
4437
4438 if (C.kind == CXCursor_PackedAttr) {
4439 return cxstring::createRef("packed");
4440 }
4441
4442 if (C.kind == CXCursor_VisibilityAttr) {
4443 const VisibilityAttr *AA = cast<VisibilityAttr>(cxcursor::getCursorAttr(C));
4444 switch (AA->getVisibility()) {
4445 case VisibilityAttr::VisibilityType::Default:
4446 return cxstring::createRef("default");
4447 case VisibilityAttr::VisibilityType::Hidden:
4448 return cxstring::createRef("hidden");
4449 case VisibilityAttr::VisibilityType::Protected:
4450 return cxstring::createRef("protected");
4451 }
4452 llvm_unreachable("unknown visibility type")::llvm::llvm_unreachable_internal("unknown visibility type", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/tools/libclang/CIndex.cpp"
, 4452)
;
4453 }
4454
4455 return cxstring::createEmpty();
4456}
4457
4458CXSourceRange clang_Cursor_getSpellingNameRange(CXCursor C,
4459 unsigned pieceIndex,
4460 unsigned options) {
4461 if (clang_Cursor_isNull(C))
4462 return clang_getNullRange();
4463
4464 ASTContext &Ctx = getCursorContext(C);
4465
4466 if (clang_isStatement(C.kind)) {
4467 const Stmt *S = getCursorStmt(C);
4468 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S)) {
4469 if (pieceIndex > 0)
4470 return clang_getNullRange();
4471 return cxloc::translateSourceRange(Ctx, Label->getIdentLoc());
4472 }
4473
4474 return clang_getNullRange();
4475 }
4476
4477 if (C.kind == CXCursor_ObjCMessageExpr) {
4478 if (const ObjCMessageExpr *
4479 ME = dyn_cast_or_null<ObjCMessageExpr>(getCursorExpr(C))) {
4480 if (pieceIndex >= ME->getNumSelectorLocs())
4481 return clang_getNullRange();
4482 return cxloc::translateSourceRange(Ctx, ME->getSelectorLoc(pieceIndex));
4483 }
4484 }
4485
4486 if (C.kind == CXCursor_ObjCInstanceMethodDecl ||
4487 C.kind == CXCursor_ObjCClassMethodDecl) {
4488 if (const ObjCMethodDecl *
4489 MD = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(C))) {
4490 if (pieceIndex >= MD->getNumSelectorLocs())
4491 return clang_getNullRange();
4492 return cxloc::translateSourceRange(Ctx, MD->getSelectorLoc(pieceIndex));
4493 }
4494 }
4495
4496 if (C.kind == CXCursor_ObjCCategoryDecl ||
4497 C.kind == CXCursor_ObjCCategoryImplDecl) {
4498 if (pieceIndex > 0)
4499 return clang_getNullRange();
4500 if (const ObjCCategoryDecl *
4501 CD = dyn_cast_or_null<ObjCCategoryDecl>(getCursorDecl(C)))
4502 return cxloc::translateSourceRange(Ctx, CD->getCategoryNameLoc());
4503 if (const ObjCCategoryImplDecl *
4504 CID = dyn_cast_or_null<ObjCCategoryImplDecl>(getCursorDecl(C)))
4505 return cxloc::translateSourceRange(Ctx, CID->getCategoryNameLoc());
4506 }
4507
4508 if (C.kind == CXCursor_ModuleImportDecl) {
4509 if (pieceIndex > 0)
4510 return clang_getNullRange();
4511 if (const ImportDecl *ImportD =
4512 dyn_cast_or_null<ImportDecl>(getCursorDecl(C))) {
4513 ArrayRef<SourceLocation> Locs = ImportD->getIdentifierLocs();
4514 if (!Locs.empty())
4515 return cxloc::translateSourceRange(Ctx,
4516 SourceRange(Locs.front(), Locs.back()));
4517 }
4518 return clang_getNullRange();
4519 }
4520
4521 if (C.kind == CXCursor_CXXMethod || C.kind == CXCursor_Destructor ||
4522 C.kind == CXCursor_ConversionFunction ||
4523 C.kind == CXCursor_FunctionDecl) {
4524 if (pieceIndex > 0)
4525 return clang_getNullRange();
4526 if (const FunctionDecl *FD =
4527 dyn_cast_or_null<FunctionDecl>(getCursorDecl(C))) {
4528 DeclarationNameInfo FunctionName = FD->getNameInfo();
4529 return cxloc::translateSourceRange(Ctx, FunctionName.getSourceRange());
4530 }
4531 return clang_getNullRange();
4532 }
4533
4534 // FIXME: A CXCursor_InclusionDirective should give the location of the
4535 // filename, but we don't keep track of this.
4536
4537 // FIXME: A CXCursor_AnnotateAttr should give the location of the annotation
4538 // but we don't keep track of this.
4539
4540 // FIXME: A CXCursor_AsmLabelAttr should give the location of the label
4541 // but we don't keep track of this.
4542
4543 // Default handling, give the location of the cursor.
4544
4545 if (pieceIndex > 0)
4546 return clang_getNullRange();
4547
4548 CXSourceLocation CXLoc = clang_getCursorLocation(C);
4549 SourceLocation Loc = cxloc::translateSourceLocation(CXLoc);
4550 return cxloc::translateSourceRange(Ctx, Loc);
4551}
4552
4553CXString clang_Cursor_getMangling(CXCursor C) {
4554 if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
4555 return cxstring::createEmpty();
4556
4557 // Mangling only works for functions and variables.
4558 const Decl *D = getCursorDecl(C);
4559 if (!D || !(isa<FunctionDecl>(D) || isa<VarDecl>(D)))
4560 return cxstring::createEmpty();
4561
4562 ASTContext &Ctx = D->getASTContext();
4563 index::CodegenNameGenerator CGNameGen(Ctx);
4564 return cxstring::createDup(CGNameGen.getName(D));
4565}
4566
4567CXStringSet *clang_Cursor_getCXXManglings(CXCursor C) {
4568 if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
4569 return nullptr;
4570
4571 const Decl *D = getCursorDecl(C);
4572 if (!(isa<CXXRecordDecl>(D) || isa<CXXMethodDecl>(D)))
4573 return nullptr;
4574
4575 ASTContext &Ctx = D->getASTContext();
4576 index::CodegenNameGenerator CGNameGen(Ctx);
4577 std::vector<std::string> Manglings = CGNameGen.getAllManglings(D);
4578 return cxstring::createSet(Manglings);
4579}
4580
4581CXString clang_getCursorDisplayName(CXCursor C) {
4582 if (!clang_isDeclaration(C.kind))
4583 return clang_getCursorSpelling(C);
4584
4585 const Decl *D = getCursorDecl(C);
4586 if (!D)
4587 return cxstring::createEmpty();
4588
4589 PrintingPolicy Policy = getCursorContext(C).getPrintingPolicy();
4590 if (const FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
4591 D = FunTmpl->getTemplatedDecl();
4592
4593 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
4594 SmallString<64> Str;
4595 llvm::raw_svector_ostream OS(Str);
4596 OS << *Function;
4597 if (Function->getPrimaryTemplate())
4598 OS << "<>";
4599 OS << "(";
4600 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
4601 if (I)
4602 OS << ", ";
4603 OS << Function->getParamDecl(I)->getType().getAsString(Policy);
4604 }
4605
4606 if (Function->isVariadic()) {
4607 if (Function->getNumParams())
4608 OS << ", ";
4609 OS << "...";
4610 }
4611 OS << ")";
4612 return cxstring::createDup(OS.str());
4613 }
4614
4615 if (const ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
4616 SmallString<64> Str;
4617 llvm::raw_svector_ostream OS(Str);
4618 OS << *ClassTemplate;
4619 OS << "<";
4620 TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
4621 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
4622 if (I)
4623 OS << ", ";
4624
4625 NamedDecl *Param = Params->getParam(I);
4626 if (Param->getIdentifier()) {
4627 OS << Param->getIdentifier()->getName();
4628 continue;
4629 }
4630
4631 // There is no parameter name, which makes this tricky. Try to come up
4632 // with something useful that isn't too long.
4633 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
4634 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
4635 else if (NonTypeTemplateParmDecl *NTTP
4636 = dyn_cast<NonTypeTemplateParmDecl>(Param))
4637 OS << NTTP->getType().getAsString(Policy);
4638 else
4639 OS << "template<...> class";
4640 }
4641
4642 OS << ">";
4643 return cxstring::createDup(OS.str());
4644 }
4645
4646 if (const ClassTemplateSpecializationDecl *ClassSpec
4647 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
4648 // If the type was explicitly written, use that.
4649 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
4650 return cxstring::createDup(TSInfo->getType().getAsString(Policy));
4651
4652 SmallString<128> Str;
4653 llvm::raw_svector_ostream OS(Str);
4654 OS << *ClassSpec;
4655 TemplateSpecializationType::PrintTemplateArgumentList(
4656 OS, ClassSpec->getTemplateArgs().asArray(), Policy);
4657 return cxstring::createDup(OS.str());
4658 }
4659
4660 return clang_getCursorSpelling(C);
4661}
4662
4663CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
4664 switch (Kind) {
4665 case CXCursor_FunctionDecl:
4666 return cxstring::createRef("FunctionDecl");
4667 case CXCursor_TypedefDecl:
4668 return cxstring::createRef("TypedefDecl");
4669 case CXCursor_EnumDecl:
4670 return cxstring::createRef("EnumDecl");
4671 case CXCursor_EnumConstantDecl:
4672 return cxstring::createRef("EnumConstantDecl");
4673 case CXCursor_StructDecl:
4674 return cxstring::createRef("StructDecl");
4675 case CXCursor_UnionDecl:
4676 return cxstring::createRef("UnionDecl");
4677 case CXCursor_ClassDecl:
4678 return cxstring::createRef("ClassDecl");
4679 case CXCursor_FieldDecl:
4680 return cxstring::createRef("FieldDecl");
4681 case CXCursor_VarDecl:
4682 return cxstring::createRef("VarDecl");
4683 case CXCursor_ParmDecl:
4684 return cxstring::createRef("ParmDecl");
4685 case CXCursor_ObjCInterfaceDecl:
4686 return cxstring::createRef("ObjCInterfaceDecl");
4687 case CXCursor_ObjCCategoryDecl:
4688 return cxstring::createRef("ObjCCategoryDecl");
4689 case CXCursor_ObjCProtocolDecl:
4690 return cxstring::createRef("ObjCProtocolDecl");
4691 case CXCursor_ObjCPropertyDecl:
4692 return cxstring::createRef("ObjCPropertyDecl");
4693 case CXCursor_ObjCIvarDecl:
4694 return cxstring::createRef("ObjCIvarDecl");
4695 case CXCursor_ObjCInstanceMethodDecl:
4696 return cxstring::createRef("ObjCInstanceMethodDecl");
4697 case CXCursor_ObjCClassMethodDecl:
4698 return cxstring::createRef("ObjCClassMethodDecl");
4699 case CXCursor_ObjCImplementationDecl:
4700 return cxstring::createRef("ObjCImplementationDecl");
4701 case CXCursor_ObjCCategoryImplDecl:
4702 return cxstring::createRef("ObjCCategoryImplDecl");
4703 case CXCursor_CXXMethod:
4704 return cxstring::createRef("CXXMethod");
4705 case CXCursor_UnexposedDecl:
4706 return cxstring::createRef("UnexposedDecl");
4707 case CXCursor_ObjCSuperClassRef:
4708 return cxstring::createRef("ObjCSuperClassRef");
4709 case CXCursor_ObjCProtocolRef:
4710 return cxstring::createRef("ObjCProtocolRef");
4711 case CXCursor_ObjCClassRef:
4712 return cxstring::createRef("ObjCClassRef");
4713 case CXCursor_TypeRef:
4714 return cxstring::createRef("TypeRef");
4715 case CXCursor_TemplateRef:
4716 return cxstring::createRef("TemplateRef");
4717 case CXCursor_NamespaceRef:
4718 return cxstring::createRef("NamespaceRef");
4719 case CXCursor_MemberRef:
4720 return cxstring::createRef("MemberRef");
4721 case CXCursor_LabelRef:
4722 return cxstring::createRef("LabelRef");
4723 case CXCursor_OverloadedDeclRef:
4724 return cxstring::createRef("OverloadedDeclRef");
4725 case CXCursor_VariableRef:
4726 return cxstring::createRef("VariableRef");
4727 case CXCursor_IntegerLiteral:
4728 return cxstring::createRef("IntegerLiteral");
4729 case CXCursor_FloatingLiteral:
4730 return cxstring::createRef("FloatingLiteral");
4731 case CXCursor_ImaginaryLiteral:
4732 return cxstring::createRef("ImaginaryLiteral");
4733 case CXCursor_StringLiteral:
4734 return cxstring::createRef("StringLiteral");
4735 case CXCursor_CharacterLiteral:
4736 return cxstring::createRef("CharacterLiteral");
4737 case CXCursor_ParenExpr:
4738 return cxstring::createRef("ParenExpr");
4739 case CXCursor_UnaryOperator:
4740 return cxstring::createRef("UnaryOperator");
4741 case CXCursor_ArraySubscriptExpr:
4742 return cxstring::createRef("ArraySubscriptExpr");
4743 case CXCursor_OMPArraySectionExpr:
4744 return cxstring::createRef("OMPArraySectionExpr");
4745 case CXCursor_BinaryOperator:
4746 return cxstring::createRef("BinaryOperator");
4747 case CXCursor_CompoundAssignOperator:
4748 return cxstring::createRef("CompoundAssignOperator");
4749 case CXCursor_ConditionalOperator:
4750 return cxstring::createRef("ConditionalOperator");
4751 case CXCursor_CStyleCastExpr:
4752 return cxstring::createRef("CStyleCastExpr");
4753 case CXCursor_CompoundLiteralExpr:
4754 return cxstring::createRef("CompoundLiteralExpr");
4755 case CXCursor_InitListExpr:
4756 return cxstring::createRef("InitListExpr");
4757 case CXCursor_AddrLabelExpr:
4758 return cxstring::createRef("AddrLabelExpr");
4759 case CXCursor_StmtExpr:
4760 return cxstring::createRef("StmtExpr");
4761 case CXCursor_GenericSelectionExpr:
4762 return cxstring::createRef("GenericSelectionExpr");
4763 case CXCursor_GNUNullExpr:
4764 return cxstring::createRef("GNUNullExpr");
4765 case CXCursor_CXXStaticCastExpr:
4766 return cxstring::createRef("CXXStaticCastExpr");
4767 case CXCursor_CXXDynamicCastExpr:
4768 return cxstring::createRef("CXXDynamicCastExpr");
4769 case CXCursor_CXXReinterpretCastExpr:
4770 return cxstring::createRef("CXXReinterpretCastExpr");
4771 case CXCursor_CXXConstCastExpr:
4772 return cxstring::createRef("CXXConstCastExpr");
4773 case CXCursor_CXXFunctionalCastExpr:
4774 return cxstring::createRef("CXXFunctionalCastExpr");
4775 case CXCursor_CXXTypeidExpr:
4776 return cxstring::createRef("CXXTypeidExpr");
4777 case CXCursor_CXXBoolLiteralExpr:
4778 return cxstring::createRef("CXXBoolLiteralExpr");
4779 case CXCursor_CXXNullPtrLiteralExpr:
4780 return cxstring::createRef("CXXNullPtrLiteralExpr");
4781 case CXCursor_CXXThisExpr:
4782 return cxstring::createRef("CXXThisExpr");
4783 case CXCursor_CXXThrowExpr:
4784 return cxstring::createRef("CXXThrowExpr");
4785 case CXCursor_CXXNewExpr:
4786 return cxstring::createRef("CXXNewExpr");
4787 case CXCursor_CXXDeleteExpr:
4788 return cxstring::createRef("CXXDeleteExpr");
4789 case CXCursor_UnaryExpr:
4790 return cxstring::createRef("UnaryExpr");
4791 case CXCursor_ObjCStringLiteral:
4792 return cxstring::createRef("ObjCStringLiteral");
4793 case CXCursor_ObjCBoolLiteralExpr:
4794 return cxstring::createRef("ObjCBoolLiteralExpr");
4795 case CXCursor_ObjCAvailabilityCheckExpr:
4796 return cxstring::createRef("ObjCAvailabilityCheckExpr");
4797 case CXCursor_ObjCSelfExpr:
4798 return cxstring::createRef("ObjCSelfExpr");
4799 case CXCursor_ObjCEncodeExpr:
4800 return cxstring::createRef("ObjCEncodeExpr");
4801 case CXCursor_ObjCSelectorExpr:
4802 return cxstring::createRef("ObjCSelectorExpr");
4803 case CXCursor_ObjCProtocolExpr:
4804 return cxstring::createRef("ObjCProtocolExpr");
4805 case CXCursor_ObjCBridgedCastExpr:
4806 return cxstring::createRef("ObjCBridgedCastExpr");
4807 case CXCursor_BlockExpr:
4808 return cxstring::createRef("BlockExpr");
4809 case CXCursor_PackExpansionExpr:
4810 return cxstring::createRef("PackExpansionExpr");
4811 case CXCursor_SizeOfPackExpr:
4812 return cxstring::createRef("SizeOfPackExpr");
4813 case CXCursor_LambdaExpr:
4814 return cxstring::createRef("LambdaExpr");
4815 case CXCursor_UnexposedExpr:
4816 return cxstring::createRef("UnexposedExpr");
4817 case CXCursor_DeclRefExpr:
4818 return cxstring::createRef("DeclRefExpr");
4819 case CXCursor_MemberRefExpr:
4820 return cxstring::createRef("MemberRefExpr");
4821 case CXCursor_CallExpr:
4822 return cxstring::createRef("CallExpr");
4823 case CXCursor_ObjCMessageExpr:
4824 return cxstring::createRef("ObjCMessageExpr");
4825 case CXCursor_UnexposedStmt:
4826 return cxstring::createRef("UnexposedStmt");
4827 case CXCursor_DeclStmt:
4828 return cxstring::createRef("DeclStmt");
4829 case CXCursor_LabelStmt:
4830 return cxstring::createRef("LabelStmt");
4831 case CXCursor_CompoundStmt:
4832 return cxstring::createRef("CompoundStmt");
4833 case CXCursor_CaseStmt:
4834 return cxstring::createRef("CaseStmt");
4835 case CXCursor_DefaultStmt:
4836 return cxstring::createRef("DefaultStmt");
4837 case CXCursor_IfStmt:
4838 return cxstring::createRef("IfStmt");
4839 case CXCursor_SwitchStmt:
4840 return cxstring::createRef("SwitchStmt");
4841 case CXCursor_WhileStmt:
4842 return cxstring::createRef("WhileStmt");
4843 case CXCursor_DoStmt:
4844 return cxstring::createRef("DoStmt");
4845 case CXCursor_ForStmt:
4846 return cxstring::createRef("ForStmt");
4847 case CXCursor_GotoStmt:
4848 return cxstring::createRef("GotoStmt");
4849 case CXCursor_IndirectGotoStmt:
4850 return cxstring::createRef("IndirectGotoStmt");
4851 case CXCursor_ContinueStmt:
4852 return cxstring::createRef("ContinueStmt");
4853 case CXCursor_BreakStmt:
4854 return cxstring::createRef("BreakStmt");
4855 case CXCursor_ReturnStmt:
4856 return cxstring::createRef("ReturnStmt");
4857 case CXCursor_GCCAsmStmt:
4858 return cxstring::createRef("GCCAsmStmt");
4859 case CXCursor_MSAsmStmt:
4860 return cxstring::createRef("MSAsmStmt");
4861 case CXCursor_ObjCAtTryStmt:
4862 return cxstring::createRef("ObjCAtTryStmt");
4863 case CXCursor_ObjCAtCatchStmt:
4864 return cxstring::createRef("ObjCAtCatchStmt");
4865 case CXCursor_ObjCAtFinallyStmt:
4866 return cxstring::createRef("ObjCAtFinallyStmt");
4867 case CXCursor_ObjCAtThrowStmt:
4868 return cxstring::createRef("ObjCAtThrowStmt");
4869 case CXCursor_ObjCAtSynchronizedStmt:
4870 return cxstring::createRef("ObjCAtSynchronizedStmt");
4871 case CXCursor_ObjCAutoreleasePoolStmt:
4872 return cxstring::createRef("ObjCAutoreleasePoolStmt");
4873 case CXCursor_ObjCForCollectionStmt:
4874 return cxstring::createRef("ObjCForCollectionStmt");
4875 case CXCursor_CXXCatchStmt:
4876 return cxstring::createRef("CXXCatchStmt");
4877 case CXCursor_CXXTryStmt:
4878 return cxstring::createRef("CXXTryStmt");
4879 case CXCursor_CXXForRangeStmt:
4880 return cxstring::createRef("CXXForRangeStmt");
4881 case CXCursor_SEHTryStmt:
4882 return cxstring::createRef("SEHTryStmt");
4883 case CXCursor_SEHExceptStmt:
4884 return cxstring::createRef("SEHExceptStmt");
4885 case CXCursor_SEHFinallyStmt:
4886 return cxstring::createRef("SEHFinallyStmt");
4887 case CXCursor_SEHLeaveStmt:
4888 return cxstring::createRef("SEHLeaveStmt");
4889 case CXCursor_NullStmt:
4890 return cxstring::createRef("NullStmt");
4891 case CXCursor_InvalidFile:
4892 return cxstring::createRef("InvalidFile");
4893 case CXCursor_InvalidCode:
4894 return cxstring::createRef("InvalidCode");
4895 case CXCursor_NoDeclFound:
4896 return cxstring::createRef("NoDeclFound");
4897 case CXCursor_NotImplemented:
4898 return cxstring::createRef("NotImplemented");
4899 case CXCursor_TranslationUnit:
4900 return cxstring::createRef("TranslationUnit");
4901 case CXCursor_UnexposedAttr:
4902 return cxstring::createRef("UnexposedAttr");
4903 case CXCursor_IBActionAttr:
4904 return cxstring::createRef("attribute(ibaction)");
4905 case CXCursor_IBOutletAttr:
4906 return cxstring::createRef("attribute(iboutlet)");
4907 case CXCursor_IBOutletCollectionAttr:
4908 return cxstring::createRef("attribute(iboutletcollection)");
4909 case CXCursor_CXXFinalAttr:
4910 return cxstring::createRef("attribute(final)");
4911 case CXCursor_CXXOverrideAttr:
4912 return cxstring::createRef("attribute(override)");
4913 case CXCursor_AnnotateAttr:
4914 return cxstring::createRef("attribute(annotate)");
4915 case CXCursor_AsmLabelAttr:
4916 return cxstring::createRef("asm label");
4917 case CXCursor_PackedAttr:
4918 return cxstring::createRef("attribute(packed)");
4919 case CXCursor_PureAttr:
4920 return cxstring::createRef("attribute(pure)");
4921 case CXCursor_ConstAttr:
4922 return cxstring::createRef("attribute(const)");
4923 case CXCursor_NoDuplicateAttr:
4924 return cxstring::createRef("attribute(noduplicate)");
4925 case CXCursor_CUDAConstantAttr:
4926 return cxstring::createRef("attribute(constant)");
4927 case CXCursor_CUDADeviceAttr:
4928 return cxstring::createRef("attribute(device)");
4929 case CXCursor_CUDAGlobalAttr:
4930 return cxstring::createRef("attribute(global)");
4931 case CXCursor_CUDAHostAttr:
4932 return cxstring::createRef("attribute(host)");
4933 case CXCursor_CUDASharedAttr:
4934 return cxstring::createRef("attribute(shared)");
4935 case CXCursor_VisibilityAttr:
4936 return cxstring::createRef("attribute(visibility)");
4937 case CXCursor_DLLExport:
4938 return cxstring::createRef("attribute(dllexport)");
4939 case CXCursor_DLLImport:
4940 return cxstring::createRef("attribute(dllimport)");
4941 case CXCursor_PreprocessingDirective:
4942 return cxstring::createRef("preprocessing directive");
4943 case CXCursor_MacroDefinition:
4944 return cxstring::createRef("macro definition");
4945 case CXCursor_MacroExpansion:
4946 return cxstring::createRef("macro expansion");
4947 case CXCursor_InclusionDirective:
4948 return cxstring::createRef("inclusion directive");
4949 case CXCursor_Namespace:
4950 return cxstring::createRef("Namespace");
4951 case CXCursor_LinkageSpec:
4952 return cxstring::createRef("LinkageSpec");
4953 case CXCursor_CXXBaseSpecifier:
4954 return cxstring::createRef("C++ base class specifier");
4955 case CXCursor_Constructor:
4956 return cxstring::createRef("CXXConstructor");
4957 case CXCursor_Destructor:
4958 return cxstring::createRef("CXXDestructor");
4959 case CXCursor_ConversionFunction:
4960 return cxstring::createRef("CXXConversion");
4961 case CXCursor_TemplateTypeParameter:
4962 return cxstring::createRef("TemplateTypeParameter");
4963 case CXCursor_NonTypeTemplateParameter:
4964 return cxstring::createRef("NonTypeTemplateParameter");
4965 case CXCursor_TemplateTemplateParameter:
4966 return cxstring::createRef("TemplateTemplateParameter");
4967 case CXCursor_FunctionTemplate:
4968 return cxstring::createRef("FunctionTemplate");
4969 case CXCursor_ClassTemplate:
4970 return cxstring::createRef("ClassTemplate");
4971 case CXCursor_ClassTemplatePartialSpecialization:
4972 return cxstring::createRef("ClassTemplatePartialSpecialization");
4973 case CXCursor_NamespaceAlias:
4974 return cxstring::createRef("NamespaceAlias");
4975 case CXCursor_UsingDirective:
4976 return cxstring::createRef("UsingDirective");
4977 case CXCursor_UsingDeclaration:
4978 return cxstring::createRef("UsingDeclaration");
4979 case CXCursor_TypeAliasDecl:
4980 return cxstring::createRef("TypeAliasDecl");
4981 case CXCursor_ObjCSynthesizeDecl:
4982 return cxstring::createRef("ObjCSynthesizeDecl");
4983 case CXCursor_ObjCDynamicDecl:
4984 return cxstring::createRef("ObjCDynamicDecl");
4985 case CXCursor_CXXAccessSpecifier:
4986 return cxstring::createRef("CXXAccessSpecifier");
4987 case CXCursor_ModuleImportDecl:
4988 return cxstring::createRef("ModuleImport");
4989 case CXCursor_OMPParallelDirective:
4990 return cxstring::createRef("OMPParallelDirective");
4991 case CXCursor_OMPSimdDirective:
4992 return cxstring::createRef("OMPSimdDirective");
4993 case CXCursor_OMPForDirective:
4994 return cxstring::createRef("OMPForDirective");
4995 case CXCursor_OMPForSimdDirective:
4996 return cxstring::createRef("OMPForSimdDirective");
4997 case CXCursor_OMPSectionsDirective:
4998 return cxstring::createRef("OMPSectionsDirective");
4999 case CXCursor_OMPSectionDirective:
5000 return cxstring::createRef("OMPSectionDirective");
5001 case CXCursor_OMPSingleDirective:
5002 return cxstring::createRef("OMPSingleDirective");
5003 case CXCursor_OMPMasterDirective:
5004 return cxstring::createRef("OMPMasterDirective");
5005 case CXCursor_OMPCriticalDirective:
5006 return cxstring::createRef("OMPCriticalDirective");
5007 case CXCursor_OMPParallelForDirective:
5008 return cxstring::createRef("OMPParallelForDirective");
5009 case CXCursor_OMPParallelForSimdDirective:
5010 return cxstring::createRef("OMPParallelForSimdDirective");
5011 case CXCursor_OMPParallelSectionsDirective:
5012 return cxstring::createRef("OMPParallelSectionsDirective");
5013 case CXCursor_OMPTaskDirective:
5014 return cxstring::createRef("OMPTaskDirective");
5015 case CXCursor_OMPTaskyieldDirective:
5016 return cxstring::createRef("OMPTaskyieldDirective");
5017 case CXCursor_OMPBarrierDirective:
5018 return cxstring::createRef("OMPBarrierDirective");
5019 case CXCursor_OMPTaskwaitDirective:
5020 return cxstring::createRef("OMPTaskwaitDirective");
5021 case CXCursor_OMPTaskgroupDirective:
5022 return cxstring::createRef("OMPTaskgroupDirective");
5023 case CXCursor_OMPFlushDirective:
5024 return cxstring::createRef("OMPFlushDirective");
5025 case CXCursor_OMPOrderedDirective:
5026 return cxstring::createRef("OMPOrderedDirective");
5027 case CXCursor_OMPAtomicDirective:
5028 return cxstring::createRef("OMPAtomicDirective");
5029 case CXCursor_OMPTargetDirective:
5030 return cxstring::createRef("OMPTargetDirective");
5031 case CXCursor_OMPTargetDataDirective:
5032 return cxstring::createRef("OMPTargetDataDirective");
5033 case CXCursor_OMPTargetEnterDataDirective:
5034 return cxstring::createRef("OMPTargetEnterDataDirective");
5035 case CXCursor_OMPTargetExitDataDirective:
5036 return cxstring::createRef("OMPTargetExitDataDirective");
5037 case CXCursor_OMPTargetParallelDirective:
5038 return cxstring::createRef("OMPTargetParallelDirective");
5039 case CXCursor_OMPTargetParallelForDirective:
5040 return cxstring::createRef("OMPTargetParallelForDirective");
5041 case CXCursor_OMPTargetUpdateDirective:
5042 return cxstring::createRef("OMPTargetUpdateDirective");
5043 case CXCursor_OMPTeamsDirective:
5044 return cxstring::createRef("OMPTeamsDirective");
5045 case CXCursor_OMPCancellationPointDirective:
5046 return cxstring::createRef("OMPCancellationPointDirective");
5047 case CXCursor_OMPCancelDirective:
5048 return cxstring::createRef("OMPCancelDirective");
5049 case CXCursor_OMPTaskLoopDirective:
5050 return cxstring::createRef("OMPTaskLoopDirective");
5051 case CXCursor_OMPTaskLoopSimdDirective:
5052 return cxstring::createRef("OMPTaskLoopSimdDirective");
5053 case CXCursor_OMPDistributeDirective:
5054 return cxstring::createRef("OMPDistributeDirective");
5055 case CXCursor_OMPDistributeParallelForDirective:
5056 return cxstring::createRef("OMPDistributeParallelForDirective");
5057 case CXCursor_OMPDistributeParallelForSimdDirective:
5058 return cxstring::createRef("OMPDistributeParallelForSimdDirective");
5059 case CXCursor_OMPDistributeSimdDirective:
5060 return cxstring::createRef("OMPDistributeSimdDirective");
5061 case CXCursor_OMPTargetParallelForSimdDirective:
5062 return cxstring::createRef("OMPTargetParallelForSimdDirective");
5063 case CXCursor_OMPTargetSimdDirective:
5064 return cxstring::createRef("OMPTargetSimdDirective");
5065 case CXCursor_OMPTeamsDistributeDirective:
5066 return cxstring::createRef("OMPTeamsDistributeDirective");
5067 case CXCursor_OMPTeamsDistributeSimdDirective:
5068 return cxstring::createRef("OMPTeamsDistributeSimdDirective");
5069 case CXCursor_OMPTeamsDistributeParallelForSimdDirective:
5070 return cxstring::createRef("OMPTeamsDistributeParallelForSimdDirective");
5071 case CXCursor_OMPTeamsDistributeParallelForDirective:
5072 return cxstring::createRef("OMPTeamsDistributeParallelForDirective");
5073 case CXCursor_OMPTargetTeamsDirective:
5074 return cxstring::createRef("OMPTargetTeamsDirective");
5075 case CXCursor_OMPTargetTeamsDistributeDirective:
5076 return cxstring::createRef("OMPTargetTeamsDistributeDirective");
5077 case CXCursor_OMPTargetTeamsDistributeParallelForDirective:
5078 return cxstring::createRef("OMPTargetTeamsDistributeParallelForDirective");
5079 case CXCursor_OMPTargetTeamsDistributeParallelForSimdDirective:
5080 return cxstring::createRef(
5081 "OMPTargetTeamsDistributeParallelForSimdDirective");
5082 case CXCursor_OMPTargetTeamsDistributeSimdDirective:
5083 return cxstring::createRef("OMPTargetTeamsDistributeSimdDirective");
5084 case CXCursor_OverloadCandidate:
5085 return cxstring::createRef("OverloadCandidate");
5086 case CXCursor_TypeAliasTemplateDecl:
5087 return cxstring::createRef("TypeAliasTemplateDecl");
5088 case CXCursor_StaticAssert:
5089 return cxstring::createRef("StaticAssert");
5090 case CXCursor_FriendDecl:
5091 return cxstring::createRef("FriendDecl");
5092 }
5093
5094 llvm_unreachable("Unhandled CXCursorKind")::llvm::llvm_unreachable_internal("Unhandled CXCursorKind", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/tools/libclang/CIndex.cpp"
, 5094)
;
5095}
5096
5097struct GetCursorData {
5098 SourceLocation TokenBeginLoc;
5099 bool PointsAtMacroArgExpansion;
5100 bool VisitedObjCPropertyImplDecl;
5101 SourceLocation VisitedDeclaratorDeclStartLoc;
5102 CXCursor &BestCursor;
5103
5104 GetCursorData(SourceManager &SM,
5105 SourceLocation tokenBegin, CXCursor &outputCursor)
5106 : TokenBeginLoc(tokenBegin), BestCursor(outputCursor) {
5107 PointsAtMacroArgExpansion = SM.isMacroArgExpansion(tokenBegin);
5108 VisitedObjCPropertyImplDecl = false;
5109 }
5110};
5111
5112static enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
5113 CXCursor parent,
5114 CXClientData client_data) {
5115 GetCursorData *Data = static_cast<GetCursorData *>(client_data);
5116 CXCursor *BestCursor = &Data->BestCursor;
5117
5118 // If we point inside a macro argument we should provide info of what the
5119 // token is so use the actual cursor, don't replace it with a macro expansion
5120 // cursor.
5121 if (cursor.kind == CXCursor_MacroExpansion && Data->PointsAtMacroArgExpansion)
5122 return CXChildVisit_Recurse;
5123
5124 if (clang_isDeclaration(cursor.kind)) {
5125 // Avoid having the implicit methods override the property decls.
5126 if (const ObjCMethodDecl *MD
5127 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
5128 if (MD->isImplicit())
5129 return CXChildVisit_Break;
5130
5131 } else if (const ObjCInterfaceDecl *ID
5132 = dyn_cast_or_null<ObjCInterfaceDecl>(getCursorDecl(cursor))) {
5133 // Check that when we have multiple @class references in the same line,
5134 // that later ones do not override the previous ones.
5135 // If we have:
5136 // @class Foo, Bar;
5137 // source ranges for both start at '@', so 'Bar' will end up overriding
5138 // 'Foo' even though the cursor location was at 'Foo'.
5139 if (BestCursor->kind == CXCursor_ObjCInterfaceDecl ||
5140 BestCursor->kind == CXCursor_ObjCClassRef)
5141 if (const ObjCInterfaceDecl *PrevID
5142 = dyn_cast_or_null<ObjCInterfaceDecl>(getCursorDecl(*BestCursor))){
5143 if (PrevID != ID &&
5144 !PrevID->isThisDeclarationADefinition() &&
5145 !ID->isThisDeclarationADefinition())
5146 return CXChildVisit_Break;
5147 }
5148
5149 } else if (const DeclaratorDecl *DD
5150 = dyn_cast_or_null<DeclaratorDecl>(getCursorDecl(cursor))) {
5151 SourceLocation StartLoc = DD->getSourceRange().getBegin();
5152 // Check that when we have multiple declarators in the same line,
5153 // that later ones do not override the previous ones.
5154 // If we have:
5155 // int Foo, Bar;
5156 // source ranges for both start at 'int', so 'Bar' will end up overriding
5157 // 'Foo' even though the cursor location was at 'Foo'.
5158 if (Data->VisitedDeclaratorDeclStartLoc == StartLoc)
5159 return CXChildVisit_Break;
5160 Data->VisitedDeclaratorDeclStartLoc = StartLoc;
5161
5162 } else if (const ObjCPropertyImplDecl *PropImp
5163 = dyn_cast_or_null<ObjCPropertyImplDecl>(getCursorDecl(cursor))) {
5164 (void)PropImp;
5165 // Check that when we have multiple @synthesize in the same line,
5166 // that later ones do not override the previous ones.
5167 // If we have:
5168 // @synthesize Foo, Bar;
5169 // source ranges for both start at '@', so 'Bar' will end up overriding
5170 // 'Foo' even though the cursor location was at 'Foo'.
5171 if (Data->VisitedObjCPropertyImplDecl)
5172 return CXChildVisit_Break;
5173 Data->VisitedObjCPropertyImplDecl = true;
5174 }
5175 }
5176
5177 if (clang_isExpression(cursor.kind) &&
5178 clang_isDeclaration(BestCursor->kind)) {
5179 if (const Decl *D = getCursorDecl(*BestCursor)) {
5180 // Avoid having the cursor of an expression replace the declaration cursor
5181 // when the expression source range overlaps the declaration range.
5182 // This can happen for C++ constructor expressions whose range generally
5183 // include the variable declaration, e.g.:
5184 // MyCXXClass foo; // Make sure pointing at 'foo' returns a VarDecl cursor.
5185 if (D->getLocation().isValid() && Data->TokenBeginLoc.isValid() &&
5186 D->getLocation() == Data->TokenBeginLoc)
5187 return CXChildVisit_Break;
5188 }
5189 }
5190
5191 // If our current best cursor is the construction of a temporary object,
5192 // don't replace that cursor with a type reference, because we want
5193 // clang_getCursor() to point at the constructor.
5194 if (clang_isExpression(BestCursor->kind) &&
5195 isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
5196 cursor.kind == CXCursor_TypeRef) {
5197 // Keep the cursor pointing at CXXTemporaryObjectExpr but also mark it
5198 // as having the actual point on the type reference.
5199 *BestCursor = getTypeRefedCallExprCursor(*BestCursor);
5200 return CXChildVisit_Recurse;
5201 }
5202
5203 // If we already have an Objective-C superclass reference, don't
5204 // update it further.
5205 if (BestCursor->kind == CXCursor_ObjCSuperClassRef)
5206 return CXChildVisit_Break;
5207
5208 *BestCursor = cursor;
5209 return CXChildVisit_Recurse;
5210}
5211
5212CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
5213 if (isNotUsableTU(TU)) {
5214 LOG_BAD_TU(TU)do { if (clang::cxindex::LogRef Log = clang::cxindex::Logger::
make(__func__)) { *Log << "called with a bad TU: " <<
TU; } } while(false)
;
5215 return clang_getNullCursor();
5216 }
5217
5218 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
5219 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
5220
5221 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
5222 CXCursor Result = cxcursor::getCursor(TU, SLoc);
5223
5224 LOG_FUNC_SECTIONif (clang::cxindex::LogRef Log = clang::cxindex::Logger::make
(__func__))
{
5225 CXFile SearchFile;
5226 unsigned SearchLine, SearchColumn;
5227 CXFile ResultFile;
5228 unsigned ResultLine, ResultColumn;
5229 CXString SearchFileName, ResultFileName, KindSpelling, USR;
5230 const char *IsDef = clang_isCursorDefinition(Result)? " (Definition)" : "";
5231 CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
5232
5233 clang_getFileLocation(Loc, &SearchFile, &SearchLine, &SearchColumn,
5234 nullptr);
5235 clang_getFileLocation(ResultLoc, &ResultFile, &ResultLine,
5236 &ResultColumn, nullptr);
5237 SearchFileName = clang_getFileName(SearchFile);
5238 ResultFileName = clang_getFileName(ResultFile);
5239 KindSpelling = clang_getCursorKindSpelling(Result.kind);
5240 USR = clang_getCursorUSR(Result);
5241 *Log << llvm::format("(%s:%d:%d) = %s",
5242 clang_getCString(SearchFileName), SearchLine, SearchColumn,
5243 clang_getCString(KindSpelling))
5244 << llvm::format("(%s:%d:%d):%s%s",
5245 clang_getCString(ResultFileName), ResultLine, ResultColumn,
5246 clang_getCString(USR), IsDef);
5247 clang_disposeString(SearchFileName);
5248 clang_disposeString(ResultFileName);
5249 clang_disposeString(KindSpelling);
5250 clang_disposeString(USR);
5251
5252 CXCursor Definition = clang_getCursorDefinition(Result);
5253 if (!clang_equalCursors(Definition, clang_getNullCursor())) {
5254 CXSourceLocation DefinitionLoc = clang_getCursorLocation(Definition);
5255 CXString DefinitionKindSpelling
5256 = clang_getCursorKindSpelling(Definition.kind);
5257 CXFile DefinitionFile;
5258 unsigned DefinitionLine, DefinitionColumn;
5259 clang_getFileLocation(DefinitionLoc, &DefinitionFile,
5260 &DefinitionLine, &DefinitionColumn, nullptr);
5261 CXString DefinitionFileName = clang_getFileName(DefinitionFile);
5262 *Log << llvm::format(" -> %s(%s:%d:%d)",
5263 clang_getCString(DefinitionKindSpelling),
5264 clang_getCString(DefinitionFileName),
5265 DefinitionLine, DefinitionColumn);
5266 clang_disposeString(DefinitionFileName);
5267 clang_disposeString(DefinitionKindSpelling);
5268 }
5269 }
5270
5271 return Result;
5272}
5273
5274CXCursor clang_getNullCursor(void) {
5275 return MakeCXCursorInvalid(CXCursor_InvalidFile);
5276}
5277
5278unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
5279 // Clear out the "FirstInDeclGroup" part in a declaration cursor, since we
5280 // can't set consistently. For example, when visiting a DeclStmt we will set
5281 // it but we don't set it on the result of clang_getCursorDefinition for
5282 // a reference of the same declaration.
5283 // FIXME: Setting "FirstInDeclGroup" in CXCursors is a hack that only works
5284 // when visiting a DeclStmt currently, the AST should be enhanced to be able
5285 // to provide that kind of info.
5286 if (clang_isDeclaration(X.kind))
5287 X.data[1] = nullptr;
5288 if (clang_isDeclaration(Y.kind))
5289 Y.data[1] = nullptr;
5290
5291 return X == Y;
5292}
5293
5294unsigned clang_hashCursor(CXCursor C) {
5295 unsigned Index = 0;
5296 if (clang_isExpression(C.kind) || clang_isStatement(C.kind))
5297 Index = 1;
5298
5299 return llvm::DenseMapInfo<std::pair<unsigned, const void*> >::getHashValue(
5300 std::make_pair(C.kind, C.data[Index]));
5301}
5302
5303unsigned clang_isInvalid(enum CXCursorKind K) {
5304 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
5305}
5306
5307unsigned clang_isDeclaration(enum CXCursorKind K) {
5308 return (K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl) ||
5309 (K >= CXCursor_FirstExtraDecl && K <= CXCursor_LastExtraDecl);
5310}
5311
5312unsigned clang_isReference(enum CXCursorKind K) {
5313 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
5314}
5315
5316unsigned clang_isExpression(enum CXCursorKind K) {
5317 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
5318}
5319
5320unsigned clang_isStatement(enum CXCursorKind K) {
5321 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
5322}
5323
5324unsigned clang_isAttribute(enum CXCursorKind K) {
5325 return K >= CXCursor_FirstAttr && K <= CXCursor_LastAttr;
5326}
5327
5328unsigned clang_isTranslationUnit(enum CXCursorKind K) {
5329 return K == CXCursor_TranslationUnit;
5330}
5331
5332unsigned clang_isPreprocessing(enum CXCursorKind K) {
5333 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
5334}
5335
5336unsigned clang_isUnexposed(enum CXCursorKind K) {
5337 switch (K) {
5338 case CXCursor_UnexposedDecl:
5339 case CXCursor_UnexposedExpr:
5340 case CXCursor_UnexposedStmt:
5341 case CXCursor_UnexposedAttr:
5342 return true;
5343 default:
5344 return false;
5345 }
5346}
5347
5348CXCursorKind clang_getCursorKind(CXCursor C) {
5349 return C.kind;
5350}
5351
5352CXSourceLocation clang_getCursorLocation(CXCursor C) {
5353 if (clang_isReference(C.kind)) {
5354 switch (C.kind) {
5355 case CXCursor_ObjCSuperClassRef: {
5356 std::pair<const ObjCInterfaceDecl *, SourceLocation> P
5357 = getCursorObjCSuperClassRef(C);
5358 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5359 }
5360
5361 case CXCursor_ObjCProtocolRef: {
5362 std::pair<const ObjCProtocolDecl *, SourceLocation> P
5363 = getCursorObjCProtocolRef(C);
5364 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5365 }
5366
5367 case CXCursor_ObjCClassRef: {
5368 std::pair<const ObjCInterfaceDecl *, SourceLocation> P
5369 = getCursorObjCClassRef(C);
5370 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5371 }
5372
5373 case CXCursor_TypeRef: {
5374 std::pair<const TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
5375 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5376 }
5377
5378 case CXCursor_TemplateRef: {
5379 std::pair<const TemplateDecl *, SourceLocation> P =
5380 getCursorTemplateRef(C);
5381 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5382 }
5383
5384 case CXCursor_NamespaceRef: {
5385 std::pair<const NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
5386 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5387 }
5388
5389 case CXCursor_MemberRef: {
5390 std::pair<const FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
5391 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5392 }
5393
5394 case CXCursor_VariableRef: {
5395 std::pair<const VarDecl *, SourceLocation> P = getCursorVariableRef(C);
5396 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5397 }
5398
5399 case CXCursor_CXXBaseSpecifier: {
5400 const CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
5401 if (!BaseSpec)
5402 return clang_getNullLocation();
5403
5404 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
5405 return cxloc::translateSourceLocation(getCursorContext(C),
5406 TSInfo->getTypeLoc().getBeginLoc());
5407
5408 return cxloc::translateSourceLocation(getCursorContext(C),
5409 BaseSpec->getLocStart());
5410 }
5411
5412 case CXCursor_LabelRef: {
5413 std::pair<const LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
5414 return cxloc::translateSourceLocation(getCursorContext(C), P.second);
5415 }
5416
5417 case CXCursor_OverloadedDeclRef:
5418 return cxloc::translateSourceLocation(getCursorContext(C),
5419 getCursorOverloadedDeclRef(C).second);
5420
5421 default:
5422 // FIXME: Need a way to enumerate all non-reference cases.
5423 llvm_unreachable("Missed a reference kind")::llvm::llvm_unreachable_internal("Missed a reference kind", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/tools/libclang/CIndex.cpp"
, 5423)
;
5424 }
5425 }
5426
5427 if (clang_isExpression(C.kind))
5428 return cxloc::translateSourceLocation(getCursorContext(C),
5429 getLocationFromExpr(getCursorExpr(C)));
5430
5431 if (clang_isStatement(C.kind))
5432 return cxloc::translateSourceLocation(getCursorContext(C),
5433 getCursorStmt(C)->getLocStart());
5434
5435 if (C.kind == CXCursor_PreprocessingDirective) {
5436 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
5437 return cxloc::translateSourceLocation(getCursorContext(C), L);
5438 }
5439
5440 if (C.kind == CXCursor_MacroExpansion) {
5441 SourceLocation L
5442 = cxcursor::getCursorMacroExpansion(C).getSourceRange().getBegin();
5443 return cxloc::translateSourceLocation(getCursorContext(C), L);
5444 }
5445
5446 if (C.kind == CXCursor_MacroDefinition) {
5447 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
5448 return cxloc::translateSourceLocation(getCursorContext(C), L);
5449 }
5450
5451 if (C.kind == CXCursor_InclusionDirective) {
5452 SourceLocation L
5453 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
5454 return cxloc::translateSourceLocation(getCursorContext(C), L);
5455 }
5456
5457 if (clang_isAttribute(C.kind)) {
5458 SourceLocation L
5459 = cxcursor::getCursorAttr(C)->getLocation();
5460 return cxloc::translateSourceLocation(getCursorContext(C), L);
5461 }
5462
5463 if (!clang_isDeclaration(C.kind))
5464 return clang_getNullLocation();
5465
5466 const Decl *D = getCursorDecl(C);
5467 if (!D)
5468 return clang_getNullLocation();
5469
5470 SourceLocation Loc = D->getLocation();
5471 // FIXME: Multiple variables declared in a single declaration
5472 // currently lack the information needed to correctly determine their
5473 // ranges when accounting for the type-specifier. We use context
5474 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
5475 // and if so, whether it is the first decl.
5476 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
5477 if (!cxcursor::isFirstInDeclGroup(C))
5478 Loc = VD->getLocation();
5479 }
5480
5481 // For ObjC methods, give the start location of the method name.
5482 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
5483 Loc = MD->getSelectorStartLoc();
5484
5485 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
5486}
5487
5488} // end extern "C"
5489
5490CXCursor cxcursor::getCursor(CXTranslationUnit TU, SourceLocation SLoc) {
5491 assert(TU)((TU) ? static_cast<void> (0) : __assert_fail ("TU", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/tools/libclang/CIndex.cpp"
, 5491, __PRETTY_FUNCTION__))
;
5492
5493 // Guard against an invalid SourceLocation, or we may assert in one
5494 // of the following calls.
5495 if (SLoc.isInvalid())
5496 return clang_getNullCursor();
5497
5498 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
5499
5500 // Translate the given source location to make it point at the beginning of
5501 // the token under the cursor.
5502 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
5503 CXXUnit->getASTContext().getLangOpts());
5504
5505 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
5506 if (SLoc.isValid()) {
5507 GetCursorData ResultData(CXXUnit->getSourceManager(), SLoc, Result);
5508 CursorVisitor CursorVis(TU, GetCursorVisitor, &ResultData,
5509 /*VisitPreprocessorLast=*/true,
5510 /*VisitIncludedEntities=*/false,
5511 SourceLocation(SLoc));
5512 CursorVis.visitFileRegion();
5513 }
5514
5515 return Result;
5516}
5517
5518static SourceRange getRawCursorExtent(CXCursor C) {
5519 if (clang_isReference(C.kind)) {
5520 switch (C.kind) {
5521 case CXCursor_ObjCSuperClassRef:
5522 return getCursorObjCSuperClassRef(C).second;
5523
5524 case CXCursor_ObjCProtocolRef:
5525 return getCursorObjCProtocolRef(C).second;
5526
5527 case CXCursor_ObjCClassRef:
5528 return getCursorObjCClassRef(C).second;
5529
5530 case CXCursor_TypeRef:
5531 return getCursorTypeRef(C).second;
5532
5533 case CXCursor_TemplateRef:
5534 return getCursorTemplateRef(C).second;
5535
5536 case CXCursor_NamespaceRef:
5537 return getCursorNamespaceRef(C).second;
5538
5539 case CXCursor_MemberRef:
5540 return getCursorMemberRef(C).second;
5541
5542 case CXCursor_CXXBaseSpecifier:
5543 return getCursorCXXBaseSpecifier(C)->getSourceRange();
5544
5545 case CXCursor_LabelRef:
5546 return getCursorLabelRef(C).second;
5547
5548 case CXCursor_OverloadedDeclRef:
5549 return getCursorOverloadedDeclRef(C).second;
5550
5551 case CXCursor_VariableRef:
5552 return getCursorVariableRef(C).second;
5553
5554 default:
5555 // FIXME: Need a way to enumerate all non-reference cases.
5556 llvm_unreachable("Missed a reference kind")::llvm::llvm_unreachable_internal("Missed a reference kind", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/tools/libclang/CIndex.cpp"
, 5556)
;
5557 }
5558 }
5559
5560 if (clang_isExpression(C.kind))
5561 return getCursorExpr(C)->getSourceRange();
5562
5563 if (clang_isStatement(C.kind))
5564 return getCursorStmt(C)->getSourceRange();
5565
5566 if (clang_isAttribute(C.kind))
5567 return getCursorAttr(C)->getRange();
5568
5569 if (C.kind == CXCursor_PreprocessingDirective)
5570 return cxcursor::getCursorPreprocessingDirective(C);
5571
5572 if (C.kind == CXCursor_MacroExpansion) {
5573 ASTUnit *TU = getCursorASTUnit(C);
5574 SourceRange Range = cxcursor::getCursorMacroExpansion(C).getSourceRange();
5575 return TU->mapRangeFromPreamble(Range);
5576 }
5577
5578 if (C.kind == CXCursor_MacroDefinition) {
5579 ASTUnit *TU = getCursorASTUnit(C);
5580 SourceRange Range = cxcursor::getCursorMacroDefinition(C)->getSourceRange();
5581 return TU->mapRangeFromPreamble(Range);
5582 }
5583
5584 if (C.kind == CXCursor_InclusionDirective) {
5585 ASTUnit *TU = getCursorASTUnit(C);
5586 SourceRange Range = cxcursor::getCursorInclusionDirective(C)->getSourceRange();
5587 return TU->mapRangeFromPreamble(Range);
5588 }
5589
5590 if (C.kind == CXCursor_TranslationUnit) {
5591 ASTUnit *TU = getCursorASTUnit(C);
5592 FileID MainID = TU->getSourceManager().getMainFileID();
5593 SourceLocation Start = TU->getSourceManager().getLocForStartOfFile(MainID);
5594 SourceLocation End = TU->getSourceManager().getLocForEndOfFile(MainID);
5595 return SourceRange(Start, End);
5596 }
5597
5598 if (clang_isDeclaration(C.kind)) {
5599 const Decl *D = cxcursor::getCursorDecl(C);
5600 if (!D)
5601 return SourceRange();
5602
5603 SourceRange R = D->getSourceRange();
5604 // FIXME: Multiple variables declared in a single declaration
5605 // currently lack the information needed to correctly determine their
5606 // ranges when accounting for the type-specifier. We use context
5607 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
5608 // and if so, whether it is the first decl.
5609 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
5610 if (!cxcursor::isFirstInDeclGroup(C))
5611 R.setBegin(VD->getLocation());
5612 }
5613 return R;
5614 }
5615 return SourceRange();
5616}
5617
5618/// \brief Retrieves the "raw" cursor extent, which is then extended to include
5619/// the decl-specifier-seq for declarations.
5620static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr) {
5621 if (clang_isDeclaration(C.kind)) {
5622 const Decl *D = cxcursor::getCursorDecl(C);
5623 if (!D)
5624 return SourceRange();
5625
5626 SourceRange R = D->getSourceRange();
5627
5628 // Adjust the start of the location for declarations preceded by
5629 // declaration specifiers.
5630 SourceLocation StartLoc;
5631 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
5632 if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
5633 StartLoc = TI->getTypeLoc().getLocStart();
5634 } else if (const TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) {
5635 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
5636 StartLoc = TI->getTypeLoc().getLocStart();
5637 }
5638
5639 if (StartLoc.isValid() && R.getBegin().isValid() &&
5640 SrcMgr.isBeforeInTranslationUnit(StartLoc, R.getBegin()))
5641 R.setBegin(StartLoc);
5642
5643 // FIXME: Multiple variables declared in a single declaration
5644 // currently lack the information needed to correctly determine their
5645 // ranges when accounting for the type-specifier. We use context
5646 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
5647 // and if so, whether it is the first decl.
5648 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
5649 if (!cxcursor::isFirstInDeclGroup(C))
5650 R.setBegin(VD->getLocation());
5651 }
5652
5653 return R;
5654 }
5655
5656 return getRawCursorExtent(C);
5657}
5658
5659CXSourceRange clang_getCursorExtent(CXCursor C) {
5660 SourceRange R = getRawCursorExtent(C);
5661 if (R.isInvalid())
5662 return clang_getNullRange();
5663
5664 return cxloc::translateSourceRange(getCursorContext(C), R);
5665}
5666
5667CXCursor clang_getCursorReferenced(CXCursor C) {
5668 if (clang_isInvalid(C.kind))
5669 return clang_getNullCursor();
5670
5671 CXTranslationUnit tu = getCursorTU(C);
5672 if (clang_isDeclaration(C.kind)) {
5673 const Decl *D = getCursorDecl(C);
5674 if (!D)
5675 return clang_getNullCursor();
5676 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D))
5677 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), tu);
5678 if (const ObjCPropertyImplDecl *PropImpl =
5679 dyn_cast<ObjCPropertyImplDecl>(D))
5680 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
5681 return MakeCXCursor(Property, tu);
5682
5683 return C;
5684 }
5685
5686 if (clang_isExpression(C.kind)) {
5687 const Expr *E = getCursorExpr(C);
5688 const Decl *D = getDeclFromExpr(E);
5689 if (D) {
5690 CXCursor declCursor = MakeCXCursor(D, tu);
5691 declCursor = getSelectorIdentifierCursor(getSelectorIdentifierIndex(C),
5692 declCursor);
5693 return declCursor;
5694 }
5695
5696 if (const OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
5697 return MakeCursorOverloadedDeclRef(Ovl, tu);
5698
5699 return clang_getNullCursor();
5700 }
5701
5702 if (clang_isStatement(C.kind)) {
5703 const Stmt *S = getCursorStmt(C);
5704 if (const GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
5705 if (LabelDecl *label = Goto->getLabel())
5706 if (LabelStmt *labelS = label->getStmt())
5707 return MakeCXCursor(labelS, getCursorDecl(C), tu);
5708
5709 return clang_getNullCursor();
5710 }
5711
5712 if (C.kind == CXCursor_MacroExpansion) {
5713 if (const MacroDefinitionRecord *Def =
5714 getCursorMacroExpansion(C).getDefinition())
5715 return MakeMacroDefinitionCursor(Def, tu);
5716 }
5717
5718 if (!clang_isReference(C.kind))
5719 return clang_getNullCursor();
5720
5721 switch (C.kind) {
5722 case CXCursor_ObjCSuperClassRef:
5723 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, tu);
5724
5725 case CXCursor_ObjCProtocolRef: {
5726 const ObjCProtocolDecl *Prot = getCursorObjCProtocolRef(C).first;
5727 if (const ObjCProtocolDecl *Def = Prot->getDefinition())
5728 return MakeCXCursor(Def, tu);
5729
5730 return MakeCXCursor(Prot, tu);
5731 }
5732
5733 case CXCursor_ObjCClassRef: {
5734 const ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
5735 if (const ObjCInterfaceDecl *Def = Class->getDefinition())
5736 return MakeCXCursor(Def, tu);
5737
5738 return MakeCXCursor(Class, tu);
5739 }
5740
5741 case CXCursor_TypeRef:
5742 return MakeCXCursor(getCursorTypeRef(C).first, tu );
5743
5744 case CXCursor_TemplateRef:
5745 return MakeCXCursor(getCursorTemplateRef(C).first, tu );
5746
5747 case CXCursor_NamespaceRef:
5748 return MakeCXCursor(getCursorNamespaceRef(C).first, tu );
5749
5750 case CXCursor_MemberRef:
5751 return MakeCXCursor(getCursorMemberRef(C).first, tu );
5752
5753 case CXCursor_CXXBaseSpecifier: {
5754 const CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
5755 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
5756 tu ));
5757 }
5758
5759 case CXCursor_LabelRef:
5760 // FIXME: We end up faking the "parent" declaration here because we
5761 // don't want to make CXCursor larger.
5762 return MakeCXCursor(getCursorLabelRef(C).first,
5763 cxtu::getASTUnit(tu)->getASTContext()
5764 .getTranslationUnitDecl(),
5765 tu);
5766
5767 case CXCursor_OverloadedDeclRef:
5768 return C;
5769
5770 case CXCursor_VariableRef:
5771 return MakeCXCursor(getCursorVariableRef(C).first, tu);
5772
5773 default:
5774 // We would prefer to enumerate all non-reference cursor kinds here.
5775 llvm_unreachable("Unhandled reference cursor kind")::llvm::llvm_unreachable_internal("Unhandled reference cursor kind"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/tools/libclang/CIndex.cpp"
, 5775)
;
5776 }
5777}
5778
5779CXCursor clang_getCursorDefinition(CXCursor C) {
5780 if (clang_isInvalid(C.kind))
5781 return clang_getNullCursor();
5782
5783 CXTranslationUnit TU = getCursorTU(C);
5784
5785 bool WasReference = false;
5786 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
5787 C = clang_getCursorReferenced(C);
5788 WasReference = true;
5789 }
5790
5791 if (C.kind == CXCursor_MacroExpansion)
5792 return clang_getCursorReferenced(C);
5793
5794 if (!clang_isDeclaration(C.kind))
5795 return clang_getNullCursor();
5796
5797 const Decl *D = getCursorDecl(C);
5798 if (!D)
5799 return clang_getNullCursor();
5800
5801 switch (D->getKind()) {
5802 // Declaration kinds that don't really separate the notions of
5803 // declaration and definition.
5804 case Decl::Namespace:
5805 case Decl::Typedef:
5806 case Decl::TypeAlias:
5807 case Decl::TypeAliasTemplate:
5808 case Decl::TemplateTypeParm:
5809 case Decl::EnumConstant:
5810 case Decl::Field:
5811 case Decl::Binding:
5812 case Decl::MSProperty:
5813 case Decl::IndirectField:
5814 case Decl::ObjCIvar:
5815 case Decl::ObjCAtDefsField:
5816 case Decl::ImplicitParam:
5817 case Decl::ParmVar:
5818 case Decl::NonTypeTemplateParm:
5819 case Decl::TemplateTemplateParm:
5820 case Decl::ObjCCategoryImpl:
5821 case Decl::ObjCImplementation:
5822 case Decl::AccessSpec:
5823 case Decl::LinkageSpec:
5824 case Decl::Export:
5825 case Decl::ObjCPropertyImpl:
5826 case Decl::FileScopeAsm:
5827 case Decl::StaticAssert:
5828 case Decl::Block:
5829 case Decl::Captured:
5830 case Decl::OMPCapturedExpr:
5831 case Decl::Label: // FIXME: Is this right??
5832 case Decl::ClassScopeFunctionSpecialization:
5833 case Decl::CXXDeductionGuide:
5834 case Decl::Import:
5835 case Decl::OMPThreadPrivate:
5836 case Decl::OMPDeclareReduction:
5837 case Decl::ObjCTypeParam:
5838 case Decl::BuiltinTemplate:
5839 case Decl::PragmaComment:
5840 case Decl::PragmaDetectMismatch:
5841 case Decl::UsingPack:
5842 return C;
5843
5844 // Declaration kinds that don't make any sense here, but are
5845 // nonetheless harmless.
5846 case Decl::Empty:
5847 case Decl::TranslationUnit:
5848 case Decl::ExternCContext:
5849 break;
5850
5851 // Declaration kinds for which the definition is not resolvable.
5852 case Decl::UnresolvedUsingTypename:
5853 case Decl::UnresolvedUsingValue:
5854 break;
5855
5856 case Decl::UsingDirective:
5857 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
5858 TU);
5859
5860 case Decl::NamespaceAlias:
5861 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), TU);
5862
5863 case Decl::Enum:
5864 case Decl::Record:
5865 case Decl::CXXRecord:
5866 case Decl::ClassTemplateSpecialization:
5867 case Decl::ClassTemplatePartialSpecialization:
5868 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
5869 return MakeCXCursor(Def, TU);
5870 return clang_getNullCursor();
5871
5872 case Decl::Function:
5873 case Decl::CXXMethod:
5874 case Decl::CXXConstructor:
5875 case Decl::CXXDestructor:
5876 case Decl::CXXConversion: {
5877 const FunctionDecl *Def = nullptr;
5878 if (cast<FunctionDecl>(D)->getBody(Def))
5879 return MakeCXCursor(Def, TU);
5880 return clang_getNullCursor();
5881 }
5882
5883 case Decl::Var:
5884 case Decl::VarTemplateSpecialization:
5885 case Decl::VarTemplatePartialSpecialization:
5886 case Decl::Decomposition: {
5887 // Ask the variable if it has a definition.
5888 if (const VarDecl *Def = cast<VarDecl>(D)->getDefinition())
5889 return MakeCXCursor(Def, TU);
5890 return clang_getNullCursor();
5891 }
5892
5893 case Decl::FunctionTemplate: {
5894 const FunctionDecl *Def = nullptr;
5895 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
5896 return MakeCXCursor(Def->getDescribedFunctionTemplate(), TU);
5897 return clang_getNullCursor();
5898 }
5899
5900 case Decl::ClassTemplate: {
5901 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
5902 ->getDefinition())
5903 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
5904 TU);
5905 return clang_getNullCursor();
5906 }
5907
5908 case Decl::VarTemplate: {
5909 if (VarDecl *Def =
5910 cast<VarTemplateDecl>(D)->getTemplatedDecl()->getDefinition())
5911 return MakeCXCursor(cast<VarDecl>(Def)->getDescribedVarTemplate(), TU);
5912 return clang_getNullCursor();
5913 }
5914
5915 case Decl::Using:
5916 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
5917 D->getLocation(), TU);
5918
5919 case Decl::UsingShadow:
5920 case Decl::ConstructorUsingShadow:
5921 return clang_getCursorDefinition(
5922 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
5923 TU));
5924
5925 case Decl::ObjCMethod: {
5926 const ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
5927 if (Method->isThisDeclarationADefinition())
5928 return C;
5929
5930 // Dig out the method definition in the associated
5931 // @implementation, if we have it.
5932 // FIXME: The ASTs should make finding the definition easier.
5933 if (const ObjCInterfaceDecl *Class
5934 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
5935 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
5936 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
5937 Method->isInstanceMethod()))
5938 if (Def->isThisDeclarationADefinition())
5939 return MakeCXCursor(Def, TU);
5940
5941 return clang_getNullCursor();
5942 }
5943
5944 case Decl::ObjCCategory:
5945 if (ObjCCategoryImplDecl *Impl
5946 = cast<ObjCCategoryDecl>(D)->getImplementation())
5947 return MakeCXCursor(Impl, TU);
5948 return clang_getNullCursor();
5949
5950 case Decl::ObjCProtocol:
5951 if (const ObjCProtocolDecl *Def = cast<ObjCProtocolDecl>(D)->getDefinition())
5952 return MakeCXCursor(Def, TU);
5953 return clang_getNullCursor();
5954
5955 case Decl::ObjCInterface: {
5956 // There are two notions of a "definition" for an Objective-C
5957 // class: the interface and its implementation. When we resolved a
5958 // reference to an Objective-C class, produce the @interface as
5959 // the definition; when we were provided with the interface,
5960 // produce the @implementation as the definition.
5961 const ObjCInterfaceDecl *IFace = cast<ObjCInterfaceDecl>(D);
5962 if (WasReference) {
5963 if (const ObjCInterfaceDecl *Def = IFace->getDefinition())
5964 return MakeCXCursor(Def, TU);
5965 } else if (ObjCImplementationDecl *Impl = IFace->getImplementation())
5966 return MakeCXCursor(Impl, TU);
5967 return clang_getNullCursor();
5968 }
5969
5970 case Decl::ObjCProperty:
5971 // FIXME: We don't really know where to find the
5972 // ObjCPropertyImplDecls that implement this property.
5973 return clang_getNullCursor();
5974
5975 case Decl::ObjCCompatibleAlias:
5976 if (const ObjCInterfaceDecl *Class
5977 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
5978 if (const ObjCInterfaceDecl *Def = Class->getDefinition())
5979 return MakeCXCursor(Def, TU);
5980
5981 return clang_getNullCursor();
5982
5983 case Decl::Friend:
5984 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
5985 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
5986 return clang_getNullCursor();
5987
5988 case Decl::FriendTemplate:
5989 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
5990 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
5991 return clang_getNullCursor();
5992 }
5993
5994 return clang_getNullCursor();
5995}
5996
5997unsigned clang_isCursorDefinition(CXCursor C) {
5998 if (!clang_isDeclaration(C.kind))
5999 return 0;
6000
6001 return clang_getCursorDefinition(C) == C;
6002}
6003
6004CXCursor clang_getCanonicalCursor(CXCursor C) {
6005 if (!clang_isDeclaration(C.kind))
6006 return C;
6007
6008 if (const Decl *D = getCursorDecl(C)) {
6009 if (const ObjCCategoryImplDecl *CatImplD = dyn_cast<ObjCCategoryImplDecl>(D))
6010 if (ObjCCategoryDecl *CatD = CatImplD->getCategoryDecl())
6011 return MakeCXCursor(CatD, getCursorTU(C));
6012
6013 if (const ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
6014 if (const ObjCInterfaceDecl *IFD = ImplD->getClassInterface())
6015 return MakeCXCursor(IFD, getCursorTU(C));
6016
6017 return MakeCXCursor(D->getCanonicalDecl(), getCursorTU(C));
6018 }
6019
6020 return C;
6021}
6022
6023int clang_Cursor_getObjCSelectorIndex(CXCursor cursor) {
6024 return cxcursor::getSelectorIdentifierIndexAndLoc(cursor).first;
6025}
6026
6027unsigned clang_getNumOverloadedDecls(CXCursor C) {
6028 if (C.kind != CXCursor_OverloadedDeclRef)
6029 return 0;
6030
6031 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
6032 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
6033 return E->getNumDecls();
6034
6035 if (OverloadedTemplateStorage *S
6036 = Storage.dyn_cast<OverloadedTemplateStorage*>())
6037 return S->size();
6038
6039 const Decl *D = Storage.get<const Decl *>();
6040 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D))
6041 return Using->shadow_size();
6042
6043 return 0;
6044}
6045
6046CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
6047 if (cursor.kind != CXCursor_OverloadedDeclRef)
6048 return clang_getNullCursor();
6049
6050 if (index >= clang_getNumOverloadedDecls(cursor))
6051 return clang_getNullCursor();
6052
6053 CXTranslationUnit TU = getCursorTU(cursor);
6054 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
6055 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
6056 return MakeCXCursor(E->decls_begin()[index], TU);
6057
6058 if (OverloadedTemplateStorage *S
6059 = Storage.dyn_cast<OverloadedTemplateStorage*>())
6060 return MakeCXCursor(S->begin()[index], TU);
6061
6062 const Decl *D = Storage.get<const Decl *>();
6063 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
6064 // FIXME: This is, unfortunately, linear time.
6065 UsingDecl::shadow_iterator Pos = Using->shadow_begin();
6066 std::advance(Pos, index);
6067 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), TU);
6068 }
6069
6070 return clang_getNullCursor();
6071}
6072
6073void clang_getDefinitionSpellingAndExtent(CXCursor C,
6074 const char **startBuf,
6075 const char **endBuf,
6076 unsigned *startLine,
6077 unsigned *startColumn,
6078 unsigned *endLine,
6079 unsigned *endColumn) {
6080 assert(getCursorDecl(C) && "CXCursor has null decl")((getCursorDecl(C) && "CXCursor has null decl") ? static_cast
<void> (0) : __assert_fail ("getCursorDecl(C) && \"CXCursor has null decl\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/tools/libclang/CIndex.cpp"
, 6080, __PRETTY_FUNCTION__))
;
6081 const FunctionDecl *FD = dyn_cast<FunctionDecl>(getCursorDecl(C));
6082 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
6083
6084 SourceManager &SM = FD->getASTContext().getSourceManager();
6085 *startBuf = SM.getCharacterData(Body->getLBracLoc());
6086 *endBuf = SM.getCharacterData(Body->getRBracLoc());
6087 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
6088 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
6089 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
6090 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
6091}
6092
6093
6094CXSourceRange clang_getCursorReferenceNameRange(CXCursor C, unsigned NameFlags,
6095 unsigned PieceIndex) {
6096 RefNamePieces Pieces;
6097
6098 switch (C.kind) {
6099 case CXCursor_MemberRefExpr:
6100 if (const MemberExpr *E = dyn_cast<MemberExpr>(getCursorExpr(C)))
6101 Pieces = buildPieces(NameFlags, true, E->getMemberNameInfo(),
6102 E->getQualifierLoc().getSourceRange());
6103 break;
6104
6105 case CXCursor_DeclRefExpr:
6106 if (const DeclRefExpr *E = dyn_cast<DeclRefExpr>(getCursorExpr(C))) {
6107 SourceRange TemplateArgLoc(E->getLAngleLoc(), E->getRAngleLoc());
6108 Pieces =
6109 buildPieces(NameFlags, false, E->getNameInfo(),
6110 E->getQualifierLoc().getSourceRange(), &TemplateArgLoc);
6111 }
6112 break;
6113
6114 case CXCursor_CallExpr:
6115 if (const CXXOperatorCallExpr *OCE =
6116 dyn_cast<CXXOperatorCallExpr>(getCursorExpr(C))) {
6117 const Expr *Callee = OCE->getCallee();
6118 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Callee))
6119 Callee = ICE->getSubExpr();
6120
6121 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Callee))
6122 Pieces = buildPieces(NameFlags, false, DRE->getNameInfo(),
6123 DRE->getQualifierLoc().getSourceRange());
6124 }
6125 break;
6126
6127 default:
6128 break;
6129 }
6130
6131 if (Pieces.empty()) {
6132 if (PieceIndex == 0)
6133 return clang_getCursorExtent(C);
6134 } else if (PieceIndex < Pieces.size()) {
6135 SourceRange R = Pieces[PieceIndex];
6136 if (R.isValid())
6137 return cxloc::translateSourceRange(getCursorContext(C), R);
6138 }
6139
6140 return clang_getNullRange();
6141}
6142
6143void clang_enableStackTraces(void) {
6144 // FIXME: Provide an argv0 here so we can find llvm-symbolizer.
6145 llvm::sys::PrintStackTraceOnErrorSignal(StringRef());
6146}
6147
6148void clang_executeOnThread(void (*fn)(void*), void *user_data,
6149 unsigned stack_size) {
6150 llvm::llvm_execute_on_thread(fn, user_data, stack_size);
6151}
6152
6153//===----------------------------------------------------------------------===//
6154// Token-based Operations.
6155//===----------------------------------------------------------------------===//
6156
6157/* CXToken layout:
6158 * int_data[0]: a CXTokenKind
6159 * int_data[1]: starting token location
6160 * int_data[2]: token length
6161 * int_data[3]: reserved
6162 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
6163 * otherwise unused.
6164 */
6165CXTokenKind clang_getTokenKind(CXToken CXTok) {
6166 return static_cast<CXTokenKind>(CXTok.int_data[0]);
6167}
6168
6169CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
6170 switch (clang_getTokenKind(CXTok)) {
6171 case CXToken_Identifier:
6172 case CXToken_Keyword:
6173 // We know we have an IdentifierInfo*, so use that.
6174 return cxstring::createRef(static_cast<IdentifierInfo *>(CXTok.ptr_data)
6175 ->getNameStart());
6176
6177 case CXToken_Literal: {
6178 // We have stashed the starting pointer in the ptr_data field. Use it.
6179 const char *Text = static_cast<const char *>(CXTok.ptr_data);
6180 return cxstring::createDup(StringRef(Text, CXTok.int_data[2]));
6181 }
6182
6183 case CXToken_Punctuation:
6184 case CXToken_Comment:
6185 break;
6186 }
6187
6188 if (isNotUsableTU(TU)) {
6189 LOG_BAD_TU(TU)do { if (clang::cxindex::LogRef Log = clang::cxindex::Logger::
make(__func__)) { *Log << "called with a bad TU: " <<
TU; } } while(false)
;
6190 return cxstring::createEmpty();
6191 }
6192
6193 // We have to find the starting buffer pointer the hard way, by
6194 // deconstructing the source location.
6195 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
6196 if (!CXXUnit)
6197 return cxstring::createEmpty();
6198
6199 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
6200 std::pair<FileID, unsigned> LocInfo
6201 = CXXUnit->getSourceManager().getDecomposedSpellingLoc(Loc);
6202 bool Invalid = false;
6203 StringRef Buffer
6204 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
6205 if (Invalid)
6206 return cxstring::createEmpty();
6207
6208 return cxstring::createDup(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
6209}
6210
6211CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
6212 if (isNotUsableTU(TU)) {
6213 LOG_BAD_TU(TU)do { if (clang::cxindex::LogRef Log = clang::cxindex::Logger::
make(__func__)) { *Log << "called with a bad TU: " <<
TU; } } while(false)
;
6214 return clang_getNullLocation();
6215 }
6216
6217 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
6218 if (!CXXUnit)
6219 return clang_getNullLocation();
6220
6221 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
6222 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
6223}
6224
6225CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
6226 if (isNotUsableTU(TU)) {
6227 LOG_BAD_TU(TU)do { if (clang::cxindex::LogRef Log = clang::cxindex::Logger::
make(__func__)) { *Log << "called with a bad TU: " <<
TU; } } while(false)
;
6228 return clang_getNullRange();
6229 }
6230
6231 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
6232 if (!CXXUnit)
6233 return clang_getNullRange();
6234
6235 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
6236 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
6237}
6238
6239static void getTokens(ASTUnit *CXXUnit, SourceRange Range,
6240 SmallVectorImpl<CXToken> &CXTokens) {
6241 SourceManager &SourceMgr = CXXUnit->getSourceManager();
6242 std::pair<FileID, unsigned> BeginLocInfo
6243 = SourceMgr.getDecomposedSpellingLoc(Range.getBegin());
6244 std::pair<FileID, unsigned> EndLocInfo
6245 = SourceMgr.getDecomposedSpellingLoc(Range.getEnd());
6246
6247 // Cannot tokenize across files.
6248 if (BeginLocInfo.first != EndLocInfo.first)
6249 return;
6250
6251 // Create a lexer
6252 bool Invalid = false;
6253 StringRef Buffer
6254 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
6255 if (Invalid)
6256 return;
6257
6258 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
6259 CXXUnit->getASTContext().getLangOpts(),
6260 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
6261 Lex.SetCommentRetentionState(true);
6262
6263 // Lex tokens until we hit the end of the range.
6264 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
6265 Token Tok;
6266 bool previousWasAt = false;
6267 do {
6268 // Lex the next token
6269 Lex.LexFromRawLexer(Tok);
6270 if (Tok.is(tok::eof))
6271 break;
6272
6273 // Initialize the CXToken.
6274 CXToken CXTok;
6275
6276 // - Common fields
6277 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
6278 CXTok.int_data[2] = Tok.getLength();
6279 CXTok.int_data[3] = 0;
6280
6281 // - Kind-specific fields
6282 if (Tok.isLiteral()) {
6283 CXTok.int_data[0] = CXToken_Literal;
6284 CXTok.ptr_data = const_cast<char *>(Tok.getLiteralData());
6285 } else if (Tok.is(tok::raw_identifier)) {
6286 // Lookup the identifier to determine whether we have a keyword.
6287 IdentifierInfo *II
6288 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok);
6289
6290 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
6291 CXTok.int_data[0] = CXToken_Keyword;
6292 }
6293 else {
6294 CXTok.int_data[0] = Tok.is(tok::identifier)
6295 ? CXToken_Identifier
6296 : CXToken_Keyword;
6297 }
6298 CXTok.ptr_data = II;
6299 } else if (Tok.is(tok::comment)) {
6300 CXTok.int_data[0] = CXToken_Comment;
6301 CXTok.ptr_data = nullptr;
6302 } else {
6303 CXTok.int_data[0] = CXToken_Punctuation;
6304 CXTok.ptr_data = nullptr;
6305 }
6306 CXTokens.push_back(CXTok);
6307 previousWasAt = Tok.is(tok::at);
6308 } while (Lex.getBufferLocation() < EffectiveBufferEnd);
6309}
6310
6311void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
6312 CXToken **Tokens, unsigned *NumTokens) {
6313 LOG_FUNC_SECTIONif (clang::cxindex::LogRef Log = clang::cxindex::Logger::make
(__func__))
{
6314 *Log << TU << ' ' << Range;
6315 }
6316
6317 if (Tokens)
6318 *Tokens = nullptr;
6319 if (NumTokens)
6320 *NumTokens = 0;
6321
6322 if (isNotUsableTU(TU)) {
6323 LOG_BAD_TU(TU)do { if (clang::cxindex::LogRef Log = clang::cxindex::Logger::
make(__func__)) { *Log << "called with a bad TU: " <<
TU; } } while(false)
;
6324 return;
6325 }
6326
6327 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
6328 if (!CXXUnit || !Tokens || !NumTokens)
6329 return;
6330
6331 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
6332
6333 SourceRange R = cxloc::translateCXSourceRange(Range);
6334 if (R.isInvalid())
6335 return;
6336
6337 SmallVector<CXToken, 32> CXTokens;
6338 getTokens(CXXUnit, R, CXTokens);
6339
6340 if (CXTokens.empty())
6341 return;
6342
6343 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
6344 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
6345 *NumTokens = CXTokens.size();
6346}
6347
6348void clang_disposeTokens(CXTranslationUnit TU,
6349 CXToken *Tokens, unsigned NumTokens) {
6350 free(Tokens);
6351}
6352
6353//===----------------------------------------------------------------------===//
6354// Token annotation APIs.
6355//===----------------------------------------------------------------------===//
6356
6357static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
6358 CXCursor parent,
6359 CXClientData client_data);
6360static bool AnnotateTokensPostChildrenVisitor(CXCursor cursor,
6361 CXClientData client_data);
6362
6363namespace {
6364class AnnotateTokensWorker {
6365 CXToken *Tokens;
6366 CXCursor *Cursors;
6367 unsigned NumTokens;
6368 unsigned TokIdx;
6369 unsigned PreprocessingTokIdx;
6370 CursorVisitor AnnotateVis;
6371 SourceManager &SrcMgr;
6372 bool HasContextSensitiveKeywords;
6373
6374 struct PostChildrenInfo {
6375 CXCursor Cursor;
6376 SourceRange CursorRange;
6377 unsigned BeforeReachingCursorIdx;
6378 unsigned BeforeChildrenTokenIdx;
6379 };
6380 SmallVector<PostChildrenInfo, 8> PostChildrenInfos;
6381
6382 CXToken &getTok(unsigned Idx) {
6383 assert(Idx < NumTokens)((Idx < NumTokens) ? static_cast<void> (0) : __assert_fail
("Idx < NumTokens", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/tools/libclang/CIndex.cpp"
, 6383, __PRETTY_FUNCTION__))
;
6384 return Tokens[Idx];
6385 }
6386 const CXToken &getTok(unsigned Idx) const {
6387 assert(Idx < NumTokens)((Idx < NumTokens) ? static_cast<void> (0) : __assert_fail
("Idx < NumTokens", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/tools/libclang/CIndex.cpp"
, 6387, __PRETTY_FUNCTION__))
;
6388 return Tokens[Idx];
6389 }
6390 bool MoreTokens() const { return TokIdx < NumTokens; }
6391 unsigned NextToken() const { return TokIdx; }
6392 void AdvanceToken() { ++TokIdx; }
6393 SourceLocation GetTokenLoc(unsigned tokI) {
6394 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[1]);
6395 }
6396 bool isFunctionMacroToken(unsigned tokI) const {
6397 return getTok(tokI).int_data[3] != 0;
6398 }
6399 SourceLocation getFunctionMacroTokenLoc(unsigned tokI) const {
6400 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[3]);
6401 }
6402
6403 void annotateAndAdvanceTokens(CXCursor, RangeComparisonResult, SourceRange);
6404 bool annotateAndAdvanceFunctionMacroTokens(CXCursor, RangeComparisonResult,
6405 SourceRange);
6406
6407public:
6408 AnnotateTokensWorker(CXToken *tokens, CXCursor *cursors, unsigned numTokens,
6409 CXTranslationUnit TU, SourceRange RegionOfInterest)
6410 : Tokens(tokens), Cursors(cursors),
6411 NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
6412 AnnotateVis(TU,
6413 AnnotateTokensVisitor, this,
6414 /*VisitPreprocessorLast=*/true,
6415 /*VisitIncludedEntities=*/false,
6416 RegionOfInterest,
6417 /*VisitDeclsOnly=*/false,
6418 AnnotateTokensPostChildrenVisitor),
6419 SrcMgr(cxtu::getASTUnit(TU)->getSourceManager()),
6420 HasContextSensitiveKeywords(false) { }
6421
6422 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
6423 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
6424 bool postVisitChildren(CXCursor cursor);
6425 void AnnotateTokens();
6426
6427 /// \brief Determine whether the annotator saw any cursors that have
6428 /// context-sensitive keywords.
6429 bool hasContextSensitiveKeywords() const {
6430 return HasContextSensitiveKeywords;
6431 }
6432
6433 ~AnnotateTokensWorker() {
6434 assert(PostChildrenInfos.empty())((PostChildrenInfos.empty()) ? static_cast<void> (0) : __assert_fail
("PostChildrenInfos.empty()", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/tools/libclang/CIndex.cpp"
, 6434, __PRETTY_FUNCTION__))
;
6435 }
6436};
6437}
6438
6439void AnnotateTokensWorker::AnnotateTokens() {
6440 // Walk the AST within the region of interest, annotating tokens
6441 // along the way.
6442 AnnotateVis.visitFileRegion();
6443}
6444
6445static inline void updateCursorAnnotation(CXCursor &Cursor,
6446 const CXCursor &updateC) {
6447 if (clang_isInvalid(updateC.kind) || !clang_isInvalid(Cursor.kind))
6448 return;
6449 Cursor = updateC;
6450}
6451
6452/// \brief It annotates and advances tokens with a cursor until the comparison
6453//// between the cursor location and the source range is the same as
6454/// \arg compResult.
6455///
6456/// Pass RangeBefore to annotate tokens with a cursor until a range is reached.
6457/// Pass RangeOverlap to annotate tokens inside a range.
6458void AnnotateTokensWorker::annotateAndAdvanceTokens(CXCursor updateC,
6459 RangeComparisonResult compResult,
6460 SourceRange range) {
6461 while (MoreTokens()) {
6462 const unsigned I = NextToken();
6463 if (isFunctionMacroToken(I))
6464 if (!annotateAndAdvanceFunctionMacroTokens(updateC, compResult, range))
6465 return;
6466
6467 SourceLocation TokLoc = GetTokenLoc(I);
6468 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
6469 updateCursorAnnotation(Cursors[I], updateC);
6470 AdvanceToken();
6471 continue;
6472 }
6473 break;
6474 }
6475}
6476
6477/// \brief Special annotation handling for macro argument tokens.
6478/// \returns true if it advanced beyond all macro tokens, false otherwise.
6479bool AnnotateTokensWorker::annotateAndAdvanceFunctionMacroTokens(
6480 CXCursor updateC,
6481 RangeComparisonResult compResult,
6482 SourceRange range) {
6483 assert(MoreTokens())((MoreTokens()) ? static_cast<void> (0) : __assert_fail
("MoreTokens()", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/tools/libclang/CIndex.cpp"
, 6483, __PRETTY_FUNCTION__))
;
6484 assert(isFunctionMacroToken(NextToken()) &&((isFunctionMacroToken(NextToken()) && "Should be called only for macro arg tokens"
) ? static_cast<void> (0) : __assert_fail ("isFunctionMacroToken(NextToken()) && \"Should be called only for macro arg tokens\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/tools/libclang/CIndex.cpp"
, 6485, __PRETTY_FUNCTION__))
6485 "Should be called only for macro arg tokens")((isFunctionMacroToken(NextToken()) && "Should be called only for macro arg tokens"
) ? static_cast<void> (0) : __assert_fail ("isFunctionMacroToken(NextToken()) && \"Should be called only for macro arg tokens\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/tools/libclang/CIndex.cpp"
, 6485, __PRETTY_FUNCTION__))
;
6486
6487 // This works differently than annotateAndAdvanceTokens; because expanded
6488 // macro arguments can have arbitrary translation-unit source order, we do not
6489 // advance the token index one by one until a token fails the range test.
6490 // We only advance once past all of the macro arg tokens if all of them
6491 // pass the range test. If one of them fails we keep the token index pointing
6492 // at the start of the macro arg tokens so that the failing token will be
6493 // annotated by a subsequent annotation try.
6494
6495 bool atLeastOneCompFail = false;
6496
6497 unsigned I = NextToken();
6498 for (; I < NumTokens && isFunctionMacroToken(I); ++I) {
6499 SourceLocation TokLoc = getFunctionMacroTokenLoc(I);
6500 if (TokLoc.isFileID())
6501 continue; // not macro arg token, it's parens or comma.
6502 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
6503 if (clang_isInvalid(clang_getCursorKind(Cursors[I])))
6504 Cursors[I] = updateC;
6505 } else
6506 atLeastOneCompFail = true;
6507 }
6508
6509 if (atLeastOneCompFail)
6510 return false;
6511
6512 TokIdx = I; // All of the tokens were handled, advance beyond all of them.
6513 return true;
6514}
6515
6516enum CXChildVisitResult
6517AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
6518 SourceRange cursorRange = getRawCursorExtent(cursor);
6519 if (cursorRange.isInvalid())
6520 return CXChildVisit_Recurse;
6521
6522 if (!HasContextSensitiveKeywords) {
6523 // Objective-C properties can have context-sensitive keywords.
6524 if (cursor.kind == CXCursor_ObjCPropertyDecl) {
6525 if (const ObjCPropertyDecl *Property
6526 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(cursor)))
6527 HasContextSensitiveKeywords = Property->getPropertyAttributesAsWritten() != 0;
6528 }
6529 // Objective-C methods can have context-sensitive keywords.
6530 else if (cursor.kind == CXCursor_ObjCInstanceMethodDecl ||
6531 cursor.kind == CXCursor_ObjCClassMethodDecl) {
6532 if (const ObjCMethodDecl *Method
6533 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
6534 if (Method->getObjCDeclQualifier())
6535 HasContextSensitiveKeywords = true;
6536 else {
6537 for (const auto *P : Method->parameters()) {
6538 if (P->getObjCDeclQualifier()) {
6539 HasContextSensitiveKeywords = true;
6540 break;
6541 }
6542 }
6543 }
6544 }
6545 }
6546 // C++ methods can have context-sensitive keywords.
6547 else if (cursor.kind == CXCursor_CXXMethod) {
6548 if (const CXXMethodDecl *Method
6549 = dyn_cast_or_null<CXXMethodDecl>(getCursorDecl(cursor))) {
6550 if (Method->hasAttr<FinalAttr>() || Method->hasAttr<OverrideAttr>())
6551 HasContextSensitiveKeywords = true;
6552 }
6553 }
6554 // C++ classes can have context-sensitive keywords.
6555 else if (cursor.kind == CXCursor_StructDecl ||
6556 cursor.kind == CXCursor_ClassDecl ||
6557 cursor.kind == CXCursor_ClassTemplate ||
6558 cursor.kind == CXCursor_ClassTemplatePartialSpecialization) {
6559 if (const Decl *D = getCursorDecl(cursor))
6560 if (D->hasAttr<FinalAttr>())
6561 HasContextSensitiveKeywords = true;
6562 }
6563 }
6564
6565 // Don't override a property annotation with its getter/setter method.
6566 if (cursor.kind == CXCursor_ObjCInstanceMethodDecl &&
6567 parent.kind == CXCursor_ObjCPropertyDecl)
6568 return CXChildVisit_Continue;
6569
6570 if (clang_isPreprocessing(cursor.kind)) {
6571 // Items in the preprocessing record are kept separate from items in
6572 // declarations, so we keep a separate token index.
6573 unsigned SavedTokIdx = TokIdx;
6574 TokIdx = PreprocessingTokIdx;
6575
6576 // Skip tokens up until we catch up to the beginning of the preprocessing
6577 // entry.
6578 while (MoreTokens()) {
6579 const unsigned I = NextToken();
6580 SourceLocation TokLoc = GetTokenLoc(I);
6581 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
6582 case RangeBefore:
6583 AdvanceToken();
6584 continue;
6585 case RangeAfter:
6586 case RangeOverlap:
6587 break;
6588 }
6589 break;
6590 }
6591
6592 // Look at all of the tokens within this range.
6593 while (MoreTokens()) {
6594 const unsigned I = NextToken();
6595 SourceLocation TokLoc = GetTokenLoc(I);
6596 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
6597 case RangeBefore:
6598 llvm_unreachable("Infeasible")::llvm::llvm_unreachable_internal("Infeasible", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/tools/libclang/CIndex.cpp"
, 6598)
;
6599 case RangeAfter:
6600 break;
6601 case RangeOverlap:
6602 // For macro expansions, just note where the beginning of the macro
6603 // expansion occurs.
6604 if (cursor.kind == CXCursor_MacroExpansion) {
6605 if (TokLoc == cursorRange.getBegin())
6606 Cursors[I] = cursor;
6607 AdvanceToken();
6608 break;
6609 }
6610 // We may have already annotated macro names inside macro definitions.
6611 if (Cursors[I].kind != CXCursor_MacroExpansion)
6612 Cursors[I] = cursor;
6613 AdvanceToken();
6614 continue;
6615 }
6616 break;
6617 }
6618
6619 // Save the preprocessing token index; restore the non-preprocessing
6620 // token index.
6621 PreprocessingTokIdx = TokIdx;
6622 TokIdx = SavedTokIdx;
6623 return CXChildVisit_Recurse;
6624 }
6625
6626 if (cursorRange.isInvalid())
6627 return CXChildVisit_Continue;
6628
6629 unsigned BeforeReachingCursorIdx = NextToken();
6630 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
6631 const enum CXCursorKind K = clang_getCursorKind(parent);
6632 const CXCursor updateC =
6633 (clang_isInvalid(K) || K == CXCursor_TranslationUnit ||
6634 // Attributes are annotated out-of-order, skip tokens until we reach it.
6635 clang_isAttribute(cursor.kind))
6636 ? clang_getNullCursor() : parent;
6637
6638 annotateAndAdvanceTokens(updateC, RangeBefore, cursorRange);
6639
6640 // Avoid having the cursor of an expression "overwrite" the annotation of the
6641 // variable declaration that it belongs to.
6642 // This can happen for C++ constructor expressions whose range generally
6643 // include the variable declaration, e.g.:
6644 // MyCXXClass foo; // Make sure we don't annotate 'foo' as a CallExpr cursor.
6645 if (clang_isExpression(cursorK) && MoreTokens()) {
6646 const Expr *E = getCursorExpr(cursor);
6647 if (const Decl *D = getCursorParentDecl(cursor)) {
6648 const unsigned I = NextToken();
6649 if (E->getLocStart().isValid() && D->getLocation().isValid() &&
6650 E->getLocStart() == D->getLocation() &&
6651 E->getLocStart() == GetTokenLoc(I)) {
6652 updateCursorAnnotation(Cursors[I], updateC);
6653 AdvanceToken();
6654 }
6655 }
6656 }
6657
6658 // Before recursing into the children keep some state that we are going
6659 // to use in the AnnotateTokensWorker::postVisitChildren callback to do some
6660 // extra work after the child nodes are visited.
6661 // Note that we don't call VisitChildren here to avoid traversing statements
6662 // code-recursively which can blow the stack.
6663
6664 PostChildrenInfo Info;
6665 Info.Cursor = cursor;
6666 Info.CursorRange = cursorRange;
6667 Info.BeforeReachingCursorIdx = BeforeReachingCursorIdx;
6668 Info.BeforeChildrenTokenIdx = NextToken();
6669 PostChildrenInfos.push_back(Info);
6670
6671 return CXChildVisit_Recurse;
6672}
6673
6674bool AnnotateTokensWorker::postVisitChildren(CXCursor cursor) {
6675 if (PostChildrenInfos.empty())
6676 return false;
6677 const PostChildrenInfo &Info = PostChildrenInfos.back();
6678 if (!clang_equalCursors(Info.Cursor, cursor))
6679 return false;
6680
6681 const unsigned BeforeChildren = Info.BeforeChildrenTokenIdx;
6682 const unsigned AfterChildren = NextToken();
6683 SourceRange cursorRange = Info.CursorRange;
6684
6685 // Scan the tokens that are at the end of the cursor, but are not captured
6686 // but the child cursors.
6687 annotateAndAdvanceTokens(cursor, RangeOverlap, cursorRange);
6688
6689 // Scan the tokens that are at the beginning of the cursor, but are not
6690 // capture by the child cursors.
6691 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
6692 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
6693 break;
6694
6695 Cursors[I] = cursor;
6696 }
6697
6698 // Attributes are annotated out-of-order, rewind TokIdx to when we first
6699 // encountered the attribute cursor.
6700 if (clang_isAttribute(cursor.kind))
6701 TokIdx = Info.BeforeReachingCursorIdx;
6702
6703 PostChildrenInfos.pop_back();
6704 return false;
6705}
6706
6707static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
6708 CXCursor parent,
6709 CXClientData client_data) {
6710 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
6711}
6712
6713static bool AnnotateTokensPostChildrenVisitor(CXCursor cursor,
6714 CXClientData client_data) {
6715 return static_cast<AnnotateTokensWorker*>(client_data)->
6716 postVisitChildren(cursor);
6717}
6718
6719namespace {
6720
6721/// \brief Uses the macro expansions in the preprocessing record to find
6722/// and mark tokens that are macro arguments. This info is used by the
6723/// AnnotateTokensWorker.
6724class MarkMacroArgTokensVisitor {
6725 SourceManager &SM;
6726 CXToken *Tokens;
6727 unsigned NumTokens;
6728 unsigned CurIdx;
6729
6730public:
6731 MarkMacroArgTokensVisitor(SourceManager &SM,
6732 CXToken *tokens, unsigned numTokens)
6733 : SM(SM), Tokens(tokens), NumTokens(numTokens), CurIdx(0) { }
6734
6735 CXChildVisitResult visit(CXCursor cursor, CXCursor parent) {
6736 if (cursor.kind != CXCursor_MacroExpansion)
6737 return CXChildVisit_Continue;
6738
6739 SourceRange macroRange = getCursorMacroExpansion(cursor).getSourceRange();
6740 if (macroRange.getBegin() == macroRange.getEnd())
6741 return CXChildVisit_Continue; // it's not a function macro.
6742
6743 for (; CurIdx < NumTokens; ++CurIdx) {
6744 if (!SM.isBeforeInTranslationUnit(getTokenLoc(CurIdx),
6745 macroRange.getBegin()))
6746 break;
6747 }
6748
6749 if (CurIdx == NumTokens)
6750 return CXChildVisit_Break;
6751
6752 for (; CurIdx < NumTokens; ++CurIdx) {
6753 SourceLocation tokLoc = getTokenLoc(CurIdx);
6754 if (!SM.isBeforeInTranslationUnit(tokLoc, macroRange.getEnd()))
6755 break;
6756
6757 setFunctionMacroTokenLoc(CurIdx, SM.getMacroArgExpandedLocation(tokLoc));
6758 }
6759
6760 if (CurIdx == NumTokens)
6761 return CXChildVisit_Break;
6762
6763 return CXChildVisit_Continue;
6764 }
6765
6766private:
6767 CXToken &getTok(unsigned Idx) {
6768 assert(Idx < NumTokens)((Idx < NumTokens) ? static_cast<void> (0) : __assert_fail
("Idx < NumTokens", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/tools/libclang/CIndex.cpp"
, 6768, __PRETTY_FUNCTION__))
;
6769 return Tokens[Idx];
6770 }
6771 const CXToken &getTok(unsigned Idx) const {
6772 assert(Idx < NumTokens)((Idx < NumTokens) ? static_cast<void> (0) : __assert_fail
("Idx < NumTokens", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/tools/libclang/CIndex.cpp"
, 6772, __PRETTY_FUNCTION__))
;
6773 return Tokens[Idx];
6774 }
6775
6776 SourceLocation getTokenLoc(unsigned tokI) {
6777 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[1]);
6778 }
6779
6780 void setFunctionMacroTokenLoc(unsigned tokI, SourceLocation loc) {
6781 // The third field is reserved and currently not used. Use it here
6782 // to mark macro arg expanded tokens with their expanded locations.
6783 getTok(tokI).int_data[3] = loc.getRawEncoding();
6784 }
6785};
6786
6787} // end anonymous namespace
6788
6789static CXChildVisitResult
6790MarkMacroArgTokensVisitorDelegate(CXCursor cursor, CXCursor parent,
6791 CXClientData client_data) {
6792 return static_cast<MarkMacroArgTokensVisitor*>(client_data)->visit(cursor,
6793 parent);
6794}
6795
6796/// \brief Used by \c annotatePreprocessorTokens.
6797/// \returns true if lexing was finished, false otherwise.
6798static bool lexNext(Lexer &Lex, Token &Tok,
6799 unsigned &NextIdx, unsigned NumTokens) {
6800 if (NextIdx >= NumTokens)
6801 return true;
6802
6803 ++NextIdx;
6804 Lex.LexFromRawLexer(Tok);
6805 return Tok.is(tok::eof);
6806}
6807
6808static void annotatePreprocessorTokens(CXTranslationUnit TU,
6809 SourceRange RegionOfInterest,
6810 CXCursor *Cursors,
6811 CXToken *Tokens,
6812 unsigned NumTokens) {
6813 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
6814
6815 Preprocessor &PP = CXXUnit->getPreprocessor();
6816 SourceManager &SourceMgr = CXXUnit->getSourceManager();
6817 std::pair<FileID, unsigned> BeginLocInfo
6818 = SourceMgr.getDecomposedSpellingLoc(RegionOfInterest.getBegin());
6819 std::pair<FileID, unsigned> EndLocInfo
6820 = SourceMgr.getDecomposedSpellingLoc(RegionOfInterest.getEnd());
6821
6822 if (BeginLocInfo.first != EndLocInfo.first)
6823 return;
6824
6825 StringRef Buffer;
6826 bool Invalid = false;
6827 Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
6828 if (Buffer.empty() || Invalid)
6829 return;
6830
6831 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
6832 CXXUnit->getASTContext().getLangOpts(),
6833 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
6834 Buffer.end());
6835 Lex.SetCommentRetentionState(true);
6836
6837 unsigned NextIdx = 0;
6838 // Lex tokens in raw mode until we hit the end of the range, to avoid
6839 // entering #includes or expanding macros.
6840 while (true) {
6841 Token Tok;
6842 if (lexNext(Lex, Tok, NextIdx, NumTokens))
6843 break;
6844 unsigned TokIdx = NextIdx-1;
6845 assert(Tok.getLocation() ==((Tok.getLocation() == SourceLocation::getFromRawEncoding(Tokens
[TokIdx].int_data[1])) ? static_cast<void> (0) : __assert_fail
("Tok.getLocation() == SourceLocation::getFromRawEncoding(Tokens[TokIdx].int_data[1])"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/tools/libclang/CIndex.cpp"
, 6846, __PRETTY_FUNCTION__))
6846 SourceLocation::getFromRawEncoding(Tokens[TokIdx].int_data[1]))((Tok.getLocation() == SourceLocation::getFromRawEncoding(Tokens
[TokIdx].int_data[1])) ? static_cast<void> (0) : __assert_fail
("Tok.getLocation() == SourceLocation::getFromRawEncoding(Tokens[TokIdx].int_data[1])"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/tools/libclang/CIndex.cpp"
, 6846, __PRETTY_FUNCTION__))
;
6847
6848 reprocess:
6849 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
6850 // We have found a preprocessing directive. Annotate the tokens
6851 // appropriately.
6852 //
6853 // FIXME: Some simple tests here could identify macro definitions and
6854 // #undefs, to provide specific cursor kinds for those.
6855
6856 SourceLocation BeginLoc = Tok.getLocation();
6857 if (lexNext(Lex, Tok, NextIdx, NumTokens))
6858 break;
6859
6860 MacroInfo *MI = nullptr;
6861 if (Tok.is(tok::raw_identifier) && Tok.getRawIdentifier() == "define") {
6862 if (lexNext(Lex, Tok, NextIdx, NumTokens))
6863 break;
6864
6865 if (Tok.is(tok::raw_identifier)) {
6866 IdentifierInfo &II =
6867 PP.getIdentifierTable().get(Tok.getRawIdentifier());
6868 SourceLocation MappedTokLoc =
6869 CXXUnit->mapLocationToPreamble(Tok.getLocation());
6870 MI = getMacroInfo(II, MappedTokLoc, TU);
6871 }
6872 }
6873
6874 bool finished = false;
6875 do {
6876 if (lexNext(Lex, Tok, NextIdx, NumTokens)) {
6877 finished = true;
6878 break;
6879 }
6880 // If we are in a macro definition, check if the token was ever a
6881 // macro name and annotate it if that's the case.
6882 if (MI) {
6883 SourceLocation SaveLoc = Tok.getLocation();
6884 Tok.setLocation(CXXUnit->mapLocationToPreamble(SaveLoc));
6885 MacroDefinitionRecord *MacroDef =
6886 checkForMacroInMacroDefinition(MI, Tok, TU);
6887 Tok.setLocation(SaveLoc);
6888 if (MacroDef)
6889 Cursors[NextIdx - 1] =
6890 MakeMacroExpansionCursor(MacroDef, Tok.getLocation(), TU);
6891 }
6892 } while (!Tok.isAtStartOfLine());
6893
6894 unsigned LastIdx = finished ? NextIdx-1 : NextIdx-2;
6895 assert(TokIdx <= LastIdx)((TokIdx <= LastIdx) ? static_cast<void> (0) : __assert_fail
("TokIdx <= LastIdx", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/tools/libclang/CIndex.cpp"
, 6895, __PRETTY_FUNCTION__))
;
6896 SourceLocation EndLoc =
6897 SourceLocation::getFromRawEncoding(Tokens[LastIdx].int_data[1]);
6898 CXCursor Cursor =
6899 MakePreprocessingDirectiveCursor(SourceRange(BeginLoc, EndLoc), TU);
6900
6901 for (; TokIdx <= LastIdx; ++TokIdx)
6902 updateCursorAnnotation(Cursors[TokIdx], Cursor);
6903
6904 if (finished)
6905 break;
6906 goto reprocess;
6907 }
6908 }
6909}
6910
6911// This gets run a separate thread to avoid stack blowout.
6912static void clang_annotateTokensImpl(CXTranslationUnit TU, ASTUnit *CXXUnit,
6913 CXToken *Tokens, unsigned NumTokens,
6914 CXCursor *Cursors) {
6915 CIndexer *CXXIdx = TU->CIdx;
6916 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing))
6917 setThreadBackgroundPriority();
6918
6919 // Determine the region of interest, which contains all of the tokens.
6920 SourceRange RegionOfInterest;
6921 RegionOfInterest.setBegin(
6922 cxloc::translateSourceLocation(clang_getTokenLocation(TU, Tokens[0])));
6923 RegionOfInterest.setEnd(
6924 cxloc::translateSourceLocation(clang_getTokenLocation(TU,
6925 Tokens[NumTokens-1])));
6926
6927 // Relex the tokens within the source range to look for preprocessing
6928 // directives.
6929 annotatePreprocessorTokens(TU, RegionOfInterest, Cursors, Tokens, NumTokens);
6930
6931 // If begin location points inside a macro argument, set it to the expansion
6932 // location so we can have the full context when annotating semantically.
6933 {
6934 SourceManager &SM = CXXUnit->getSourceManager();
6935 SourceLocation Loc =
6936 SM.getMacroArgExpandedLocation(RegionOfInterest.getBegin());
6937 if (Loc.isMacroID())
6938 RegionOfInterest.setBegin(SM.getExpansionLoc(Loc));
6939 }
6940
6941 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
6942 // Search and mark tokens that are macro argument expansions.
6943 MarkMacroArgTokensVisitor Visitor(CXXUnit->getSourceManager(),
6944 Tokens, NumTokens);
6945 CursorVisitor MacroArgMarker(TU,
6946 MarkMacroArgTokensVisitorDelegate, &Visitor,
6947 /*VisitPreprocessorLast=*/true,
6948 /*VisitIncludedEntities=*/false,
6949 RegionOfInterest);
6950 MacroArgMarker.visitPreprocessedEntitiesInRegion();
6951 }
6952
6953 // Annotate all of the source locations in the region of interest that map to
6954 // a specific cursor.
6955 AnnotateTokensWorker W(Tokens, Cursors, NumTokens, TU, RegionOfInterest);
6956
6957 // FIXME: We use a ridiculous stack size here because the data-recursion
6958 // algorithm uses a large stack frame than the non-data recursive version,
6959 // and AnnotationTokensWorker currently transforms the data-recursion
6960 // algorithm back into a traditional recursion by explicitly calling
6961 // VisitChildren(). We will need to remove this explicit recursive call.
6962 W.AnnotateTokens();
6963
6964 // If we ran into any entities that involve context-sensitive keywords,
6965 // take another pass through the tokens to mark them as such.
6966 if (W.hasContextSensitiveKeywords()) {
6967 for (unsigned I = 0; I != NumTokens; ++I) {
6968 if (clang_getTokenKind(Tokens[I]) != CXToken_Identifier)
6969 continue;
6970
6971 if (Cursors[I].kind == CXCursor_ObjCPropertyDecl) {
6972 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
6973 if (const ObjCPropertyDecl *Property
6974 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(Cursors[I]))) {
6975 if (Property->getPropertyAttributesAsWritten() != 0 &&
6976 llvm::StringSwitch<bool>(II->getName())
6977 .Case("readonly", true)
6978 .Case("assign", true)
6979 .Case("unsafe_unretained", true)
6980 .Case("readwrite", true)
6981 .Case("retain", true)
6982 .Case("copy", true)
6983 .Case("nonatomic", true)
6984 .Case("atomic", true)
6985 .Case("getter", true)
6986 .Case("setter", true)
6987 .Case("strong", true)
6988 .Case("weak", true)
6989 .Case("class", true)
6990 .Default(false))
6991 Tokens[I].int_data[0] = CXToken_Keyword;
6992 }
6993 continue;
6994 }
6995
6996 if (Cursors[I].kind == CXCursor_ObjCInstanceMethodDecl ||
6997 Cursors[I].kind == CXCursor_ObjCClassMethodDecl) {
6998 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
6999 if (llvm::StringSwitch<bool>(II->getName())
7000 .Case("in", true)
7001 .Case("out", true)
7002 .Case("inout", true)
7003 .Case("oneway", true)
7004 .Case("bycopy", true)
7005 .Case("byref", true)
7006 .Default(false))
7007 Tokens[I].int_data[0] = CXToken_Keyword;
7008 continue;
7009 }
7010
7011 if (Cursors[I].kind == CXCursor_CXXFinalAttr ||
7012 Cursors[I].kind == CXCursor_CXXOverrideAttr) {
7013 Tokens[I].int_data[0] = CXToken_Keyword;
7014 continue;
7015 }
7016 }
7017 }
7018}
7019
7020void clang_annotateTokens(CXTranslationUnit TU,
7021 CXToken *Tokens, unsigned NumTokens,
7022 CXCursor *Cursors) {
7023 if (isNotUsableTU(TU)) {
7024 LOG_BAD_TU(TU)do { if (clang::cxindex::LogRef Log = clang::cxindex::Logger::
make(__func__)) { *Log << "called with a bad TU: " <<
TU; } } while(false)
;
7025 return;
7026 }
7027 if (NumTokens == 0 || !Tokens || !Cursors) {
7028 LOG_FUNC_SECTIONif (clang::cxindex::LogRef Log = clang::cxindex::Logger::make
(__func__))
{ *Log << "<null input>"; }
7029 return;
7030 }
7031
7032 LOG_FUNC_SECTIONif (clang::cxindex::LogRef Log = clang::cxindex::Logger::make
(__func__))
{
7033 *Log << TU << ' ';
7034 CXSourceLocation bloc = clang_getTokenLocation(TU, Tokens[0]);
7035 CXSourceLocation eloc = clang_getTokenLocation(TU, Tokens[NumTokens-1]);
7036 *Log << clang_getRange(bloc, eloc);
7037 }
7038
7039 // Any token we don't specifically annotate will have a NULL cursor.
7040 CXCursor C = clang_getNullCursor();
7041 for (unsigned I = 0; I != NumTokens; ++I)
7042 Cursors[I] = C;
7043
7044 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
7045 if (!CXXUnit)
7046 return;
7047
7048 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
7049
7050 auto AnnotateTokensImpl = [=]() {
7051 clang_annotateTokensImpl(TU, CXXUnit, Tokens, NumTokens, Cursors);
7052 };
7053 llvm::CrashRecoveryContext CRC;
7054 if (!RunSafely(CRC, AnnotateTokensImpl, GetSafetyThreadStackSize() * 2)) {
7055 fprintf(stderrstderr, "libclang: crash detected while annotating tokens\n");
7056 }
7057}
7058
7059//===----------------------------------------------------------------------===//
7060// Operations for querying linkage of a cursor.
7061//===----------------------------------------------------------------------===//
7062
7063CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
7064 if (!clang_isDeclaration(cursor.kind))
7065 return CXLinkage_Invalid;
7066
7067 const Decl *D = cxcursor::getCursorDecl(cursor);
7068 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
7069 switch (ND->getLinkageInternal()) {
7070 case NoLinkage:
7071 case VisibleNoLinkage: return CXLinkage_NoLinkage;
7072 case InternalLinkage: return CXLinkage_Internal;
7073 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
7074 case ExternalLinkage: return CXLinkage_External;
7075 };
7076
7077 return CXLinkage_Invalid;
7078}
7079
7080//===----------------------------------------------------------------------===//
7081// Operations for querying visibility of a cursor.
7082//===----------------------------------------------------------------------===//
7083
7084CXVisibilityKind clang_getCursorVisibility(CXCursor cursor) {
7085 if (!clang_isDeclaration(cursor.kind))
7086 return CXVisibility_Invalid;
7087
7088 const Decl *D = cxcursor::getCursorDecl(cursor);
7089 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
7090 switch (ND->getVisibility()) {
7091 case HiddenVisibility: return CXVisibility_Hidden;
7092 case ProtectedVisibility: return CXVisibility_Protected;
7093 case DefaultVisibility: return CXVisibility_Default;
7094 };
7095
7096 return CXVisibility_Invalid;
7097}
7098
7099//===----------------------------------------------------------------------===//
7100// Operations for querying language of a cursor.
7101//===----------------------------------------------------------------------===//
7102
7103static CXLanguageKind getDeclLanguage(const Decl *D) {
7104 if (!D)
7105 return CXLanguage_C;
7106
7107 switch (D->getKind()) {
7108 default:
7109 break;
7110 case Decl::ImplicitParam:
7111 case Decl::ObjCAtDefsField:
7112 case Decl::ObjCCategory:
7113 case Decl::ObjCCategoryImpl:
7114 case Decl::ObjCCompatibleAlias:
7115 case Decl::ObjCImplementation:
7116 case Decl::ObjCInterface:
7117 case Decl::ObjCIvar:
7118 case Decl::ObjCMethod:
7119 case Decl::ObjCProperty:
7120 case Decl::ObjCPropertyImpl:
7121 case Decl::ObjCProtocol:
7122 case Decl::ObjCTypeParam:
7123 return CXLanguage_ObjC;
7124 case Decl::CXXConstructor:
7125 case Decl::CXXConversion:
7126 case Decl::CXXDestructor:
7127 case Decl::CXXMethod:
7128 case Decl::CXXRecord:
7129 case Decl::ClassTemplate:
7130 case Decl::ClassTemplatePartialSpecialization:
7131 case Decl::ClassTemplateSpecialization:
7132 case Decl::Friend:
7133 case Decl::FriendTemplate:
7134 case Decl::FunctionTemplate:
7135 case Decl::LinkageSpec:
7136 case Decl::Namespace:
7137 case Decl::NamespaceAlias:
7138 case Decl::NonTypeTemplateParm:
7139 case Decl::StaticAssert:
7140 case Decl::TemplateTemplateParm:
7141 case Decl::TemplateTypeParm:
7142 case Decl::UnresolvedUsingTypename:
7143 case Decl::UnresolvedUsingValue:
7144 case Decl::Using:
7145 case Decl::UsingDirective:
7146 case Decl::UsingShadow:
7147 return CXLanguage_CPlusPlus;
7148 }
7149
7150 return CXLanguage_C;
7151}
7152
7153static CXAvailabilityKind getCursorAvailabilityForDecl(const Decl *D) {
7154 if (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted())
7155 return CXAvailability_NotAvailable;
7156
7157 switch (D->getAvailability()) {
7158 case AR_Available:
7159 case AR_NotYetIntroduced:
7160 if (const EnumConstantDecl *EnumConst = dyn_cast<EnumConstantDecl>(D))
7161 return getCursorAvailabilityForDecl(
7162 cast<Decl>(EnumConst->getDeclContext()));
7163 return CXAvailability_Available;
7164
7165 case AR_Deprecated:
7166 return CXAvailability_Deprecated;
7167
7168 case AR_Unavailable:
7169 return CXAvailability_NotAvailable;
7170 }
7171
7172 llvm_unreachable("Unknown availability kind!")::llvm::llvm_unreachable_internal("Unknown availability kind!"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/tools/libclang/CIndex.cpp"
, 7172)
;
7173}
7174
7175enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
7176 if (clang_isDeclaration(cursor.kind))
7177 if (const Decl *D = cxcursor::getCursorDecl(cursor))
7178 return getCursorAvailabilityForDecl(D);
7179
7180 return CXAvailability_Available;
7181}
7182
7183static CXVersion convertVersion(VersionTuple In) {
7184 CXVersion Out = { -1, -1, -1 };
7185 if (In.empty())
7186 return Out;
7187
7188 Out.Major = In.getMajor();
7189
7190 Optional<unsigned> Minor = In.getMinor();
7191 if (Minor.hasValue())
7192 Out.Minor = *Minor;
7193 else
7194 return Out;
7195
7196 Optional<unsigned> Subminor = In.getSubminor();
7197 if (Subminor.hasValue())
7198 Out.Subminor = *Subminor;
7199
7200 return Out;
7201}
7202
7203static int getCursorPlatformAvailabilityForDecl(const Decl *D,
7204 int *always_deprecated,
7205 CXString *deprecated_message,
7206 int *always_unavailable,
7207 CXString *unavailable_message,
7208 CXPlatformAvailability *availability,
7209 int availability_size) {
7210 bool HadAvailAttr = false;
7211 int N = 0;
7212 for (auto A : D->attrs()) {
7213 if (DeprecatedAttr *Deprecated = dyn_cast<DeprecatedAttr>(A)) {
7214 HadAvailAttr = true;
7215 if (always_deprecated)
7216 *always_deprecated = 1;
7217 if (deprecated_message) {
7218 clang_disposeString(*deprecated_message);
7219 *deprecated_message = cxstring::createDup(Deprecated->getMessage());
7220 }
7221 continue;
7222 }
7223
7224 if (UnavailableAttr *Unavailable = dyn_cast<UnavailableAttr>(A)) {
7225 HadAvailAttr = true;
7226 if (always_unavailable)
7227 *always_unavailable = 1;
7228 if (unavailable_message) {
7229 clang_disposeString(*unavailable_message);
7230 *unavailable_message = cxstring::createDup(Unavailable->getMessage());
7231 }
7232 continue;
7233 }
7234
7235 if (AvailabilityAttr *Avail = dyn_cast<AvailabilityAttr>(A)) {
7236 HadAvailAttr = true;
7237 if (N < availability_size) {
7238 availability[N].Platform
7239 = cxstring::createDup(Avail->getPlatform()->getName());
7240 availability[N].Introduced = convertVersion(Avail->getIntroduced());
7241 availability[N].Deprecated = convertVersion(Avail->getDeprecated());
7242 availability[N].Obsoleted = convertVersion(Avail->getObsoleted());
7243 availability[N].Unavailable = Avail->getUnavailable();
7244 availability[N].Message = cxstring::createDup(Avail->getMessage());
7245 }
7246 ++N;
7247 }
7248 }
7249
7250 if (!HadAvailAttr)
7251 if (const EnumConstantDecl *EnumConst = dyn_cast<EnumConstantDecl>(D))
7252 return getCursorPlatformAvailabilityForDecl(
7253 cast<Decl>(EnumConst->getDeclContext()),
7254 always_deprecated,
7255 deprecated_message,
7256 always_unavailable,
7257 unavailable_message,
7258 availability,
7259 availability_size);
7260
7261 return N;
7262}
7263
7264int clang_getCursorPlatformAvailability(CXCursor cursor,
7265 int *always_deprecated,
7266 CXString *deprecated_message,
7267 int *always_unavailable,
7268 CXString *unavailable_message,
7269 CXPlatformAvailability *availability,
7270 int availability_size) {
7271 if (always_deprecated)
7272 *always_deprecated = 0;
7273 if (deprecated_message)
7274 *deprecated_message = cxstring::createEmpty();
7275 if (always_unavailable)
7276 *always_unavailable = 0;
7277 if (unavailable_message)
7278 *unavailable_message = cxstring::createEmpty();
7279
7280 if (!clang_isDeclaration(cursor.kind))
7281 return 0;
7282
7283 const Decl *D = cxcursor::getCursorDecl(cursor);
7284 if (!D)
7285 return 0;
7286
7287 return getCursorPlatformAvailabilityForDecl(D, always_deprecated,
7288 deprecated_message,
7289 always_unavailable,
7290 unavailable_message,
7291 availability,
7292 availability_size);
7293}
7294
7295void clang_disposeCXPlatformAvailability(CXPlatformAvailability *availability) {
7296 clang_disposeString(availability->Platform);
7297 clang_disposeString(availability->Message);
7298}
7299
7300CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
7301 if (clang_isDeclaration(cursor.kind))
7302 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
7303
7304 return CXLanguage_Invalid;
7305}
7306
7307 /// \brief If the given cursor is the "templated" declaration
7308 /// descibing a class or function template, return the class or
7309 /// function template.
7310static const Decl *maybeGetTemplateCursor(const Decl *D) {
7311 if (!D)
7312 return nullptr;
7313
7314 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
7315 if (FunctionTemplateDecl *FunTmpl = FD->getDescribedFunctionTemplate())
7316 return FunTmpl;
7317
7318 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
7319 if (ClassTemplateDecl *ClassTmpl = RD->getDescribedClassTemplate())
7320 return ClassTmpl;
7321
7322 return D;
7323}
7324
7325
7326enum CX_StorageClass clang_Cursor_getStorageClass(CXCursor C) {
7327 StorageClass sc = SC_None;
7328 const Decl *D = getCursorDecl(C);
7329 if (D) {
7330 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7331 sc = FD->getStorageClass();
7332 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7333 sc = VD->getStorageClass();
7334 } else {
7335 return CX_SC_Invalid;
7336 }
7337 } else {
7338 return CX_SC_Invalid;
7339 }
7340 switch (sc) {
7341 case SC_None:
7342 return CX_SC_None;
7343 case SC_Extern:
7344 return CX_SC_Extern;
7345 case SC_Static:
7346 return CX_SC_Static;
7347 case SC_PrivateExtern:
7348 return CX_SC_PrivateExtern;
7349 case SC_Auto:
7350 return CX_SC_Auto;
7351 case SC_Register:
7352 return CX_SC_Register;
7353 }
7354 llvm_unreachable("Unhandled storage class!")::llvm::llvm_unreachable_internal("Unhandled storage class!",
"/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/tools/libclang/CIndex.cpp"
, 7354)
;
7355}
7356
7357CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
7358 if (clang_isDeclaration(cursor.kind)) {
7359 if (const Decl *D = getCursorDecl(cursor)) {
7360 const DeclContext *DC = D->getDeclContext();
7361 if (!DC)
7362 return clang_getNullCursor();
7363
7364 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
7365 getCursorTU(cursor));
7366 }
7367 }
7368
7369 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
7370 if (const Decl *D = getCursorDecl(cursor))
7371 return MakeCXCursor(D, getCursorTU(cursor));
7372 }
7373
7374 return clang_getNullCursor();
7375}
7376
7377CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
7378 if (clang_isDeclaration(cursor.kind)) {
7379 if (const Decl *D = getCursorDecl(cursor)) {
7380 const DeclContext *DC = D->getLexicalDeclContext();
7381 if (!DC)
7382 return clang_getNullCursor();
7383
7384 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
7385 getCursorTU(cursor));
7386 }
7387 }
7388
7389 // FIXME: Note that we can't easily compute the lexical context of a
7390 // statement or expression, so we return nothing.
7391 return clang_getNullCursor();
7392}
7393
7394CXFile clang_getIncludedFile(CXCursor cursor) {
7395 if (cursor.kind != CXCursor_InclusionDirective)
7396 return nullptr;
7397
7398 const InclusionDirective *ID = getCursorInclusionDirective(cursor);
7399 return const_cast<FileEntry *>(ID->getFile());
7400}
7401
7402unsigned clang_Cursor_getObjCPropertyAttributes(CXCursor C, unsigned reserved) {
7403 if (C.kind != CXCursor_ObjCPropertyDecl)
7404 return CXObjCPropertyAttr_noattr;
7405
7406 unsigned Result = CXObjCPropertyAttr_noattr;
7407 const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(getCursorDecl(C));
7408 ObjCPropertyDecl::PropertyAttributeKind Attr =
7409 PD->getPropertyAttributesAsWritten();
7410
7411#define SET_CXOBJCPROP_ATTR(A) \
7412 if (Attr & ObjCPropertyDecl::OBJC_PR_##A) \
7413 Result |= CXObjCPropertyAttr_##A
7414 SET_CXOBJCPROP_ATTR(readonly);
7415 SET_CXOBJCPROP_ATTR(getter);
7416 SET_CXOBJCPROP_ATTR(assign);
7417 SET_CXOBJCPROP_ATTR(readwrite);
7418 SET_CXOBJCPROP_ATTR(retain);
7419 SET_CXOBJCPROP_ATTR(copy);
7420 SET_CXOBJCPROP_ATTR(nonatomic);
7421 SET_CXOBJCPROP_ATTR(setter);
7422 SET_CXOBJCPROP_ATTR(atomic);
7423 SET_CXOBJCPROP_ATTR(weak);
7424 SET_CXOBJCPROP_ATTR(strong);
7425 SET_CXOBJCPROP_ATTR(unsafe_unretained);
7426 SET_CXOBJCPROP_ATTR(class);
7427#undef SET_CXOBJCPROP_ATTR
7428
7429 return Result;
7430}
7431
7432unsigned clang_Cursor_getObjCDeclQualifiers(CXCursor C) {
7433 if (!clang_isDeclaration(C.kind))
7434 return CXObjCDeclQualifier_None;
7435
7436 Decl::ObjCDeclQualifier QT = Decl::OBJC_TQ_None;
7437 const Decl *D = getCursorDecl(C);
7438 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
7439 QT = MD->getObjCDeclQualifier();
7440 else if (const ParmVarDecl *PD = dyn_cast<ParmVarDecl>(D))
7441 QT = PD->getObjCDeclQualifier();
7442 if (QT == Decl::OBJC_TQ_None)
7443 return CXObjCDeclQualifier_None;
7444
7445 unsigned Result = CXObjCDeclQualifier_None;
7446 if (QT & Decl::OBJC_TQ_In) Result |= CXObjCDeclQualifier_In;
7447 if (QT & Decl::OBJC_TQ_Inout) Result |= CXObjCDeclQualifier_Inout;
7448 if (QT & Decl::OBJC_TQ_Out) Result |= CXObjCDeclQualifier_Out;
7449 if (QT & Decl::OBJC_TQ_Bycopy) Result |= CXObjCDeclQualifier_Bycopy;
7450 if (QT & Decl::OBJC_TQ_Byref) Result |= CXObjCDeclQualifier_Byref;
7451 if (QT & Decl::OBJC_TQ_Oneway) Result |= CXObjCDeclQualifier_Oneway;
7452
7453 return Result;
7454}
7455
7456unsigned clang_Cursor_isObjCOptional(CXCursor C) {
7457 if (!clang_isDeclaration(C.kind))
7458 return 0;
7459
7460 const Decl *D = getCursorDecl(C);
7461 if (const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D))
7462 return PD->getPropertyImplementation() == ObjCPropertyDecl::Optional;
7463 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
7464 return MD->getImplementationControl() == ObjCMethodDecl::Optional;
7465
7466 return 0;
7467}
7468
7469unsigned clang_Cursor_isVariadic(CXCursor C) {
7470 if (!clang_isDeclaration(C.kind))
7471 return 0;
7472
7473 const Decl *D = getCursorDecl(C);
7474 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
7475 return FD->isVariadic();
7476 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
7477 return MD->isVariadic();
7478
7479 return 0;
7480}
7481
7482unsigned clang_Cursor_isExternalSymbol(CXCursor C,
7483 CXString *language, CXString *definedIn,
7484 unsigned *isGenerated) {
7485 if (!clang_isDeclaration(C.kind))
7486 return 0;
7487
7488 const Decl *D = getCursorDecl(C);
7489
7490 auto getExternalSymAttr = [](const Decl *D) -> ExternalSourceSymbolAttr* {
7491 if (auto *attr = D->getAttr<ExternalSourceSymbolAttr>())
7492 return attr;
7493 if (auto *dcd = dyn_cast<Decl>(D->getDeclContext())) {
7494 if (auto *attr = dcd->getAttr<ExternalSourceSymbolAttr>())
7495 return attr;
7496 }
7497 return nullptr;
7498 };
7499 if (auto *attr = getExternalSymAttr(D)) {
7500 if (language)
7501 *language = cxstring::createDup(attr->getLanguage());
7502 if (definedIn)
7503 *definedIn = cxstring::createDup(attr->getDefinedIn());
7504 if (isGenerated)
7505 *isGenerated = attr->getGeneratedDeclaration();
7506 return 1;
7507 }
7508 return 0;
7509}
7510
7511CXSourceRange clang_Cursor_getCommentRange(CXCursor C) {
7512 if (!clang_isDeclaration(C.kind))
7513 return clang_getNullRange();
7514
7515 const Decl *D = getCursorDecl(C);
7516 ASTContext &Context = getCursorContext(C);
7517 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
7518 if (!RC)
7519 return clang_getNullRange();
7520
7521 return cxloc::translateSourceRange(Context, RC->getSourceRange());
7522}
7523
7524CXString clang_Cursor_getRawCommentText(CXCursor C) {
7525 if (!clang_isDeclaration(C.kind))
7526 return cxstring::createNull();
7527
7528 const Decl *D = getCursorDecl(C);
7529 ASTContext &Context = getCursorContext(C);
7530 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
7531 StringRef RawText = RC ? RC->getRawText(Context.getSourceManager()) :
7532 StringRef();
7533
7534 // Don't duplicate the string because RawText points directly into source
7535 // code.
7536 return cxstring::createRef(RawText);
7537}
7538
7539CXString clang_Cursor_getBriefCommentText(CXCursor C) {
7540 if (!clang_isDeclaration(C.kind))
7541 return cxstring::createNull();
7542
7543 const Decl *D = getCursorDecl(C);
7544 const ASTContext &Context = getCursorContext(C);
7545 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
7546
7547 if (RC) {
7548 StringRef BriefText = RC->getBriefText(Context);
7549
7550 // Don't duplicate the string because RawComment ensures that this memory
7551 // will not go away.
7552 return cxstring::createRef(BriefText);
7553 }
7554
7555 return cxstring::createNull();
7556}
7557
7558CXModule clang_Cursor_getModule(CXCursor C) {
7559 if (C.kind == CXCursor_ModuleImportDecl) {
7560 if (const ImportDecl *ImportD =
7561 dyn_cast_or_null<ImportDecl>(getCursorDecl(C)))
7562 return ImportD->getImportedModule();
7563 }
7564
7565 return nullptr;
7566}
7567
7568CXModule clang_getModuleForFile(CXTranslationUnit TU, CXFile File) {
7569 if (isNotUsableTU(TU)) {
7570 LOG_BAD_TU(TU)do { if (clang::cxindex::LogRef Log = clang::cxindex::Logger::
make(__func__)) { *Log << "called with a bad TU: " <<
TU; } } while(false)
;
7571 return nullptr;
7572 }
7573 if (!File)
7574 return nullptr;
7575 FileEntry *FE = static_cast<FileEntry *>(File);
7576
7577 ASTUnit &Unit = *cxtu::getASTUnit(TU);
7578 HeaderSearch &HS = Unit.getPreprocessor().getHeaderSearchInfo();
7579 ModuleMap::KnownHeader Header = HS.findModuleForHeader(FE);
7580
7581 return Header.getModule();
7582}
7583
7584CXFile clang_Module_getASTFile(CXModule CXMod) {
7585 if (!CXMod)
7586 return nullptr;
7587 Module *Mod = static_cast<Module*>(CXMod);
7588 return const_cast<FileEntry *>(Mod->getASTFile());
7589}
7590
7591CXModule clang_Module_getParent(CXModule CXMod) {
7592 if (!CXMod)
7593 return nullptr;
7594 Module *Mod = static_cast<Module*>(CXMod);
7595 return Mod->Parent;
7596}
7597
7598CXString clang_Module_getName(CXModule CXMod) {
7599 if (!CXMod)
7600 return cxstring::createEmpty();
7601 Module *Mod = static_cast<Module*>(CXMod);
7602 return cxstring::createDup(Mod->Name);
7603}
7604
7605CXString clang_Module_getFullName(CXModule CXMod) {
7606 if (!CXMod)
7607 return cxstring::createEmpty();
7608 Module *Mod = static_cast<Module*>(CXMod);
7609 return cxstring::createDup(Mod->getFullModuleName());
7610}
7611
7612int clang_Module_isSystem(CXModule CXMod) {
7613 if (!CXMod)
7614 return 0;
7615 Module *Mod = static_cast<Module*>(CXMod);
7616 return Mod->IsSystem;
7617}
7618
7619unsigned clang_Module_getNumTopLevelHeaders(CXTranslationUnit TU,
7620 CXModule CXMod) {
7621 if (isNotUsableTU(TU)) {
7622 LOG_BAD_TU(TU)do { if (clang::cxindex::LogRef Log = clang::cxindex::Logger::
make(__func__)) { *Log << "called with a bad TU: " <<
TU; } } while(false)
;
7623 return 0;
7624 }
7625 if (!CXMod)
7626 return 0;
7627 Module *Mod = static_cast<Module*>(CXMod);
7628 FileManager &FileMgr = cxtu::getASTUnit(TU)->getFileManager();
7629 ArrayRef<const FileEntry *> TopHeaders = Mod->getTopHeaders(FileMgr);
7630 return TopHeaders.size();
7631}
7632
7633CXFile clang_Module_getTopLevelHeader(CXTranslationUnit TU,
7634 CXModule CXMod, unsigned Index) {
7635 if (isNotUsableTU(TU)) {
7636 LOG_BAD_TU(TU)do { if (clang::cxindex::LogRef Log = clang::cxindex::Logger::
make(__func__)) { *Log << "called with a bad TU: " <<
TU; } } while(false)
;
7637 return nullptr;
7638 }
7639 if (!CXMod)
7640 return nullptr;
7641 Module *Mod = static_cast<Module*>(CXMod);
7642 FileManager &FileMgr = cxtu::getASTUnit(TU)->getFileManager();
7643
7644 ArrayRef<const FileEntry *> TopHeaders = Mod->getTopHeaders(FileMgr);
7645 if (Index < TopHeaders.size())
7646 return const_cast<FileEntry *>(TopHeaders[Index]);
7647
7648 return nullptr;
7649}
7650
7651//===----------------------------------------------------------------------===//
7652// C++ AST instrospection.
7653//===----------------------------------------------------------------------===//
7654
7655unsigned clang_CXXConstructor_isDefaultConstructor(CXCursor C) {
7656 if (!clang_isDeclaration(C.kind))
7657 return 0;
7658
7659 const Decl *D = cxcursor::getCursorDecl(C);
7660 const CXXConstructorDecl *Constructor =
7661 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
7662 return (Constructor && Constructor->isDefaultConstructor()) ? 1 : 0;
7663}
7664
7665unsigned clang_CXXConstructor_isCopyConstructor(CXCursor C) {
7666 if (!clang_isDeclaration(C.kind))
7667 return 0;
7668
7669 const Decl *D = cxcursor::getCursorDecl(C);
7670 const CXXConstructorDecl *Constructor =
7671 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
7672 return (Constructor && Constructor->isCopyConstructor()) ? 1 : 0;
7673}
7674
7675unsigned clang_CXXConstructor_isMoveConstructor(CXCursor C) {
7676 if (!clang_isDeclaration(C.kind))
7677 return 0;
7678
7679 const Decl *D = cxcursor::getCursorDecl(C);
7680 const CXXConstructorDecl *Constructor =
7681 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
7682 return (Constructor && Constructor->isMoveConstructor()) ? 1 : 0;
7683}
7684
7685unsigned clang_CXXConstructor_isConvertingConstructor(CXCursor C) {
7686 if (!clang_isDeclaration(C.kind))
7687 return 0;
7688
7689 const Decl *D = cxcursor::getCursorDecl(C);
7690 const CXXConstructorDecl *Constructor =
7691 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
7692 // Passing 'false' excludes constructors marked 'explicit'.
7693 return (Constructor && Constructor->isConvertingConstructor(false)) ? 1 : 0;
7694}
7695
7696unsigned clang_CXXField_isMutable(CXCursor C) {
7697 if (!clang_isDeclaration(C.kind))
7698 return 0;
7699
7700 if (const auto D = cxcursor::getCursorDecl(C))
7701 if (const auto FD = dyn_cast_or_null<FieldDecl>(D))
7702 return FD->isMutable() ? 1 : 0;
7703 return 0;
7704}
7705
7706unsigned clang_CXXMethod_isPureVirtual(CXCursor C) {
7707 if (!clang_isDeclaration(C.kind))
7708 return 0;
7709
7710 const Decl *D = cxcursor::getCursorDecl(C);
7711 const CXXMethodDecl *Method =
7712 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
7713 return (Method && Method->isVirtual() && Method->isPure()) ? 1 : 0;
7714}
7715
7716unsigned clang_CXXMethod_isConst(CXCursor C) {
7717 if (!clang_isDeclaration(C.kind))
7718 return 0;
7719
7720 const Decl *D = cxcursor::getCursorDecl(C);
7721 const CXXMethodDecl *Method =
7722 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
7723 return (Method && (Method->getTypeQualifiers() & Qualifiers::Const)) ? 1 : 0;
7724}
7725
7726unsigned clang_CXXMethod_isDefaulted(CXCursor C) {
7727 if (!clang_isDeclaration(C.kind))
7728 return 0;
7729
7730 const Decl *D = cxcursor::getCursorDecl(C);
7731 const CXXMethodDecl *Method =
7732 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
7733 return (Method && Method->isDefaulted()) ? 1 : 0;
7734}
7735
7736unsigned clang_CXXMethod_isStatic(CXCursor C) {
7737 if (!clang_isDeclaration(C.kind))
7738 return 0;
7739
7740 const Decl *D = cxcursor::getCursorDecl(C);
7741 const CXXMethodDecl *Method =
7742 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
7743 return (Method && Method->isStatic()) ? 1 : 0;
7744}
7745
7746unsigned clang_CXXMethod_isVirtual(CXCursor C) {
7747 if (!clang_isDeclaration(C.kind))
7748 return 0;
7749
7750 const Decl *D = cxcursor::getCursorDecl(C);
7751 const CXXMethodDecl *Method =
7752 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
7753 return (Method && Method->isVirtual()) ? 1 : 0;
7754}
7755
7756//===----------------------------------------------------------------------===//
7757// Attribute introspection.
7758//===----------------------------------------------------------------------===//
7759
7760CXType clang_getIBOutletCollectionType(CXCursor C) {
7761 if (C.kind != CXCursor_IBOutletCollectionAttr)
7762 return cxtype::MakeCXType(QualType(), cxcursor::getCursorTU(C));
7763
7764 const IBOutletCollectionAttr *A =
7765 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
7766
7767 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorTU(C));
7768}
7769
7770//===----------------------------------------------------------------------===//
7771// Inspecting memory usage.
7772//===----------------------------------------------------------------------===//
7773
7774typedef std::vector<CXTUResourceUsageEntry> MemUsageEntries;
7775
7776static inline void createCXTUResourceUsageEntry(MemUsageEntries &entries,
7777 enum CXTUResourceUsageKind k,
7778 unsigned long amount) {
7779 CXTUResourceUsageEntry entry = { k, amount };
7780 entries.push_back(entry);
7781}
7782
7783const char *clang_getTUResourceUsageName(CXTUResourceUsageKind kind) {
7784 const char *str = "";
7785 switch (kind) {
7786 case CXTUResourceUsage_AST:
7787 str = "ASTContext: expressions, declarations, and types";
7788 break;
7789 case CXTUResourceUsage_Identifiers:
7790 str = "ASTContext: identifiers";
7791 break;
7792 case CXTUResourceUsage_Selectors:
7793 str = "ASTContext: selectors";
7794 break;
7795 case CXTUResourceUsage_GlobalCompletionResults:
7796 str = "Code completion: cached global results";
7797 break;
7798 case CXTUResourceUsage_SourceManagerContentCache:
7799 str = "SourceManager: content cache allocator";
7800 break;
7801 case CXTUResourceUsage_AST_SideTables:
7802 str = "ASTContext: side tables";
7803 break;
7804 case CXTUResourceUsage_SourceManager_Membuffer_Malloc:
7805 str = "SourceManager: malloc'ed memory buffers";
7806 break;
7807 case CXTUResourceUsage_SourceManager_Membuffer_MMap:
7808 str = "SourceManager: mmap'ed memory buffers";
7809 break;
7810 case CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc:
7811 str = "ExternalASTSource: malloc'ed memory buffers";
7812 break;
7813 case CXTUResourceUsage_ExternalASTSource_Membuffer_MMap:
7814 str = "ExternalASTSource: mmap'ed memory buffers";
7815 break;
7816 case CXTUResourceUsage_Preprocessor:
7817 str = "Preprocessor: malloc'ed memory";
7818 break;
7819 case CXTUResourceUsage_PreprocessingRecord:
7820 str = "Preprocessor: PreprocessingRecord";
7821 break;
7822 case CXTUResourceUsage_SourceManager_DataStructures:
7823 str = "SourceManager: data structures and tables";
7824 break;
7825 case CXTUResourceUsage_Preprocessor_HeaderSearch:
7826 str = "Preprocessor: header search tables";
7827 break;
7828 }
7829 return str;
7830}
7831
7832CXTUResourceUsage clang_getCXTUResourceUsage(CXTranslationUnit TU) {
7833 if (isNotUsableTU(TU)) {
7834 LOG_BAD_TU(TU)do { if (clang::cxindex::LogRef Log = clang::cxindex::Logger::
make(__func__)) { *Log << "called with a bad TU: " <<
TU; } } while(false)
;
7835 CXTUResourceUsage usage = { (void*) nullptr, 0, nullptr };
7836 return usage;
7837 }
7838
7839 ASTUnit *astUnit = cxtu::getASTUnit(TU);
7840 std::unique_ptr<MemUsageEntries> entries(new MemUsageEntries());
7841 ASTContext &astContext = astUnit->getASTContext();
7842
7843 // How much memory is used by AST nodes and types?
7844 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST,
7845 (unsigned long) astContext.getASTAllocatedMemory());
7846
7847 // How much memory is used by identifiers?
7848 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Identifiers,
7849 (unsigned long) astContext.Idents.getAllocator().getTotalMemory());
7850
7851 // How much memory is used for selectors?
7852 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Selectors,
7853 (unsigned long) astContext.Selectors.getTotalMemory());
7854
7855 // How much memory is used by ASTContext's side tables?
7856 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST_SideTables,
7857 (unsigned long) astContext.getSideTableAllocatedMemory());
7858
7859 // How much memory is used for caching global code completion results?
7860 unsigned long completionBytes = 0;
7861 if (GlobalCodeCompletionAllocator *completionAllocator =
7862 astUnit->getCachedCompletionAllocator().get()) {
7863 completionBytes = completionAllocator->getTotalMemory();
7864 }
7865 createCXTUResourceUsageEntry(*entries,
7866 CXTUResourceUsage_GlobalCompletionResults,
7867 completionBytes);
7868
7869 // How much memory is being used by SourceManager's content cache?
7870 createCXTUResourceUsageEntry(*entries,
7871 CXTUResourceUsage_SourceManagerContentCache,
7872 (unsigned long) astContext.getSourceManager().getContentCacheSize());
7873
7874 // How much memory is being used by the MemoryBuffer's in SourceManager?
7875 const SourceManager::MemoryBufferSizes &srcBufs =
7876 astUnit->getSourceManager().getMemoryBufferSizes();
7877
7878 createCXTUResourceUsageEntry(*entries,
7879 CXTUResourceUsage_SourceManager_Membuffer_Malloc,
7880 (unsigned long) srcBufs.malloc_bytes);
7881 createCXTUResourceUsageEntry(*entries,
7882 CXTUResourceUsage_SourceManager_Membuffer_MMap,
7883 (unsigned long) srcBufs.mmap_bytes);
7884 createCXTUResourceUsageEntry(*entries,
7885 CXTUResourceUsage_SourceManager_DataStructures,
7886 (unsigned long) astContext.getSourceManager()
7887 .getDataStructureSizes());
7888
7889 // How much memory is being used by the ExternalASTSource?
7890 if (ExternalASTSource *esrc = astContext.getExternalSource()) {
7891 const ExternalASTSource::MemoryBufferSizes &sizes =
7892 esrc->getMemoryBufferSizes();
7893
7894 createCXTUResourceUsageEntry(*entries,
7895 CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc,
7896 (unsigned long) sizes.malloc_bytes);
7897 createCXTUResourceUsageEntry(*entries,
7898 CXTUResourceUsage_ExternalASTSource_Membuffer_MMap,
7899 (unsigned long) sizes.mmap_bytes);
7900 }
7901
7902 // How much memory is being used by the Preprocessor?
7903 Preprocessor &pp = astUnit->getPreprocessor();
7904 createCXTUResourceUsageEntry(*entries,
7905 CXTUResourceUsage_Preprocessor,
7906 pp.getTotalMemory());
7907
7908 if (PreprocessingRecord *pRec = pp.getPreprocessingRecord()) {
7909 createCXTUResourceUsageEntry(*entries,
7910 CXTUResourceUsage_PreprocessingRecord,
7911 pRec->getTotalMemory());
7912 }
7913
7914 createCXTUResourceUsageEntry(*entries,
7915 CXTUResourceUsage_Preprocessor_HeaderSearch,
7916 pp.getHeaderSearchInfo().getTotalMemory());
7917
7918 CXTUResourceUsage usage = { (void*) entries.get(),
7919 (unsigned) entries->size(),
7920 !entries->empty() ? &(*entries)[0] : nullptr };
7921 (void)entries.release();
7922 return usage;
7923}
7924
7925void clang_disposeCXTUResourceUsage(CXTUResourceUsage usage) {
7926 if (usage.data)
7927 delete (MemUsageEntries*) usage.data;
7928}
7929
7930CXSourceRangeList *clang_getSkippedRanges(CXTranslationUnit TU, CXFile file) {
7931 CXSourceRangeList *skipped = new CXSourceRangeList;
7932 skipped->count = 0;
7933 skipped->ranges = nullptr;
7934
7935 if (isNotUsableTU(TU)) {
7936 LOG_BAD_TU(TU)do { if (clang::cxindex::LogRef Log = clang::cxindex::Logger::
make(__func__)) { *Log << "called with a bad TU: " <<
TU; } } while(false)
;
7937 return skipped;
7938 }
7939
7940 if (!file)
7941 return skipped;
7942
7943 ASTUnit *astUnit = cxtu::getASTUnit(TU);
7944 PreprocessingRecord *ppRec = astUnit->getPreprocessor().getPreprocessingRecord();
7945 if (!ppRec)
7946 return skipped;
7947
7948 ASTContext &Ctx = astUnit->getASTContext();
7949 SourceManager &sm = Ctx.getSourceManager();
7950 FileEntry *fileEntry = static_cast<FileEntry *>(file);
7951 FileID wantedFileID = sm.translateFile(fileEntry);
7952
7953 const std::vector<SourceRange> &SkippedRanges = ppRec->getSkippedRanges();
7954 std::vector<SourceRange> wantedRanges;
7955 for (std::vector<SourceRange>::const_iterator i = SkippedRanges.begin(), ei = SkippedRanges.end();
7956 i != ei; ++i) {
7957 if (sm.getFileID(i->getBegin()) == wantedFileID || sm.getFileID(i->getEnd()) == wantedFileID)
7958 wantedRanges.push_back(*i);
7959 }
7960
7961 skipped->count = wantedRanges.size();
7962 skipped->ranges = new CXSourceRange[skipped->count];
7963 for (unsigned i = 0, ei = skipped->count; i != ei; ++i)
7964 skipped->ranges[i] = cxloc::translateSourceRange(Ctx, wantedRanges[i]);
7965
7966 return skipped;
7967}
7968
7969CXSourceRangeList *clang_getAllSkippedRanges(CXTranslationUnit TU) {
7970 CXSourceRangeList *skipped = new CXSourceRangeList;
7971 skipped->count = 0;
7972 skipped->ranges = nullptr;
7973
7974 if (isNotUsableTU(TU)) {
7975 LOG_BAD_TU(TU)do { if (clang::cxindex::LogRef Log = clang::cxindex::Logger::
make(__func__)) { *Log << "called with a bad TU: " <<
TU; } } while(false)
;
7976 return skipped;
7977 }
7978
7979 ASTUnit *astUnit = cxtu::getASTUnit(TU);
7980 PreprocessingRecord *ppRec = astUnit->getPreprocessor().getPreprocessingRecord();
7981 if (!ppRec)
7982 return skipped;
7983
7984 ASTContext &Ctx = astUnit->getASTContext();
7985
7986 const std::vector<SourceRange> &SkippedRanges = ppRec->getSkippedRanges();
7987
7988 skipped->count = SkippedRanges.size();
7989 skipped->ranges = new CXSourceRange[skipped->count];
7990 for (unsigned i = 0, ei = skipped->count; i != ei; ++i)
7991 skipped->ranges[i] = cxloc::translateSourceRange(Ctx, SkippedRanges[i]);
7992
7993 return skipped;
7994}
7995
7996void clang_disposeSourceRangeList(CXSourceRangeList *ranges) {
7997 if (ranges) {
7998 delete[] ranges->ranges;
7999 delete ranges;
8000 }
8001}
8002
8003void clang::PrintLibclangResourceUsage(CXTranslationUnit TU) {
8004 CXTUResourceUsage Usage = clang_getCXTUResourceUsage(TU);
9
'Usage' initialized here
8005 for (unsigned I = 0; I != Usage.numEntries; ++I)
10
Assuming the condition is true
11
Loop condition is true. Entering loop body
8006 fprintf(stderrstderr, " %s: %lu\n",
8007 clang_getTUResourceUsageName(Usage.entries[I].kind),
12
Dereference of null pointer
8008 Usage.entries[I].amount);
8009
8010 clang_disposeCXTUResourceUsage(Usage);
8011}
8012
8013//===----------------------------------------------------------------------===//
8014// Misc. utility functions.
8015//===----------------------------------------------------------------------===//
8016
8017/// Default to using an 8 MB stack size on "safety" threads.
8018static unsigned SafetyStackThreadSize = 8 << 20;
8019
8020namespace clang {
8021
8022bool RunSafely(llvm::CrashRecoveryContext &CRC, llvm::function_ref<void()> Fn,
8023 unsigned Size) {
8024 if (!Size)
8025 Size = GetSafetyThreadStackSize();
8026 if (Size)
8027 return CRC.RunSafelyOnThread(Fn, Size);
8028 return CRC.RunSafely(Fn);
8029}
8030
8031unsigned GetSafetyThreadStackSize() {
8032 return SafetyStackThreadSize;
8033}
8034
8035void SetSafetyThreadStackSize(unsigned Value) {
8036 SafetyStackThreadSize = Value;
8037}
8038
8039}
8040
8041void clang::setThreadBackgroundPriority() {
8042 if (getenv("LIBCLANG_BGPRIO_DISABLE"))
8043 return;
8044
8045#ifdef USE_DARWIN_THREADS
8046 setpriority(PRIO_DARWIN_THREAD, 0, PRIO_DARWIN_BG);
8047#endif
8048}
8049
8050void cxindex::printDiagsToStderr(ASTUnit *Unit) {
8051 if (!Unit)
8052 return;
8053
8054 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
8055 DEnd = Unit->stored_diag_end();
8056 D != DEnd; ++D) {
8057 CXStoredDiagnostic Diag(*D, Unit->getLangOpts());
8058 CXString Msg = clang_formatDiagnostic(&Diag,
8059 clang_defaultDiagnosticDisplayOptions());
8060 fprintf(stderrstderr, "%s\n", clang_getCString(Msg));
8061 clang_disposeString(Msg);
8062 }
8063#ifdef LLVM_ON_WIN32
8064 // On Windows, force a flush, since there may be multiple copies of
8065 // stderr and stdout in the file system, all with different buffers
8066 // but writing to the same device.
8067 fflush(stderrstderr);
8068#endif
8069}
8070
8071MacroInfo *cxindex::getMacroInfo(const IdentifierInfo &II,
8072 SourceLocation MacroDefLoc,
8073 CXTranslationUnit TU){
8074 if (MacroDefLoc.isInvalid() || !TU)
8075 return nullptr;
8076 if (!II.hadMacroDefinition())
8077 return nullptr;
8078
8079 ASTUnit *Unit = cxtu::getASTUnit(TU);
8080 Preprocessor &PP = Unit->getPreprocessor();
8081 MacroDirective *MD = PP.getLocalMacroDirectiveHistory(&II);
8082 if (MD) {
8083 for (MacroDirective::DefInfo
8084 Def = MD->getDefinition(); Def; Def = Def.getPreviousDefinition()) {
8085 if (MacroDefLoc == Def.getMacroInfo()->getDefinitionLoc())
8086 return Def.getMacroInfo();
8087 }
8088 }
8089
8090 return nullptr;
8091}
8092
8093const MacroInfo *cxindex::getMacroInfo(const MacroDefinitionRecord *MacroDef,
8094 CXTranslationUnit TU) {
8095 if (!MacroDef || !TU)
8096 return nullptr;
8097 const IdentifierInfo *II = MacroDef->getName();
8098 if (!II)
8099 return nullptr;
8100
8101 return getMacroInfo(*II, MacroDef->getLocation(), TU);
8102}
8103
8104MacroDefinitionRecord *
8105cxindex::checkForMacroInMacroDefinition(const MacroInfo *MI, const Token &Tok,
8106 CXTranslationUnit TU) {
8107 if (!MI || !TU)
8108 return nullptr;
8109 if (Tok.isNot(tok::raw_identifier))
8110 return nullptr;
8111
8112 if (MI->getNumTokens() == 0)
8113 return nullptr;
8114 SourceRange DefRange(MI->getReplacementToken(0).getLocation(),
8115 MI->getDefinitionEndLoc());
8116 ASTUnit *Unit = cxtu::getASTUnit(TU);
8117
8118 // Check that the token is inside the definition and not its argument list.
8119 SourceManager &SM = Unit->getSourceManager();
8120 if (SM.isBeforeInTranslationUnit(Tok.getLocation(), DefRange.getBegin()))
8121 return nullptr;
8122 if (SM.isBeforeInTranslationUnit(DefRange.getEnd(), Tok.getLocation()))
8123 return nullptr;
8124
8125 Preprocessor &PP = Unit->getPreprocessor();
8126 PreprocessingRecord *PPRec = PP.getPreprocessingRecord();
8127 if (!PPRec)
8128 return nullptr;
8129
8130 IdentifierInfo &II = PP.getIdentifierTable().get(Tok.getRawIdentifier());
8131 if (!II.hadMacroDefinition())
8132 return nullptr;
8133
8134 // Check that the identifier is not one of the macro arguments.
8135 if (std::find(MI->arg_begin(), MI->arg_end(), &II) != MI->arg_end())
8136 return nullptr;