Bug Summary

File:tools/clang/tools/libclang/CIndex.cpp
Warning:line 3496, column 3
Branch condition evaluates to a garbage value

Annotated Source Code

/build/llvm-toolchain-snapshot-6.0~svn320417/tools/clang/tools/libclang/CIndex.cpp

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