blob: 177b3a6d51ec6678efeef12f9dac71d2fa484846 [file] [log] [blame]
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001//===- CIndex.cpp - Clang-C Source Indexing Library -----------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the main API hooks in the Clang-C Source Indexing
11// library.
12//
13//===----------------------------------------------------------------------===//
14
15#include "CIndexer.h"
16#include "CIndexDiagnostic.h"
17#include "CXComment.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"
Fariborz Jahanian88b95212012-12-18 23:02:59 +000024#include "SimpleFormatContext.h"
Guy Benyei7f92f2d2012-12-18 14:30:41 +000025#include "clang/AST/StmtVisitor.h"
26#include "clang/Basic/Diagnostic.h"
27#include "clang/Basic/Version.h"
28#include "clang/Frontend/ASTUnit.h"
29#include "clang/Frontend/CompilerInstance.h"
30#include "clang/Frontend/FrontendDiagnostic.h"
31#include "clang/Lex/HeaderSearch.h"
32#include "clang/Lex/Lexer.h"
33#include "clang/Lex/PreprocessingRecord.h"
34#include "clang/Lex/Preprocessor.h"
35#include "llvm/ADT/Optional.h"
36#include "llvm/ADT/STLExtras.h"
37#include "llvm/ADT/StringSwitch.h"
38#include "llvm/Support/Compiler.h"
39#include "llvm/Support/CrashRecoveryContext.h"
40#include "llvm/Support/MemoryBuffer.h"
41#include "llvm/Support/Mutex.h"
42#include "llvm/Support/PrettyStackTrace.h"
43#include "llvm/Support/Program.h"
44#include "llvm/Support/SaveAndRestore.h"
45#include "llvm/Support/Signals.h"
46#include "llvm/Support/Threading.h"
47#include "llvm/Support/Timer.h"
48#include "llvm/Support/raw_ostream.h"
49
50using namespace clang;
51using namespace clang::cxcursor;
52using namespace clang::cxstring;
53using namespace clang::cxtu;
54using namespace clang::cxindex;
55
56CXTranslationUnit cxtu::MakeCXTranslationUnit(CIndexer *CIdx, ASTUnit *TU) {
57 if (!TU)
58 return 0;
59 CXTranslationUnit D = new CXTranslationUnitImpl();
60 D->CIdx = CIdx;
61 D->TUData = TU;
62 D->StringPool = createCXStringPool();
63 D->Diagnostics = 0;
64 D->OverridenCursorsPool = createOverridenCXCursorsPool();
Fariborz Jahanian88b95212012-12-18 23:02:59 +000065 D->FormatContext = 0;
66 D->FormatInMemoryUniqueId = 0;
Guy Benyei7f92f2d2012-12-18 14:30:41 +000067 return D;
68}
69
70cxtu::CXTUOwner::~CXTUOwner() {
71 if (TU)
72 clang_disposeTranslationUnit(TU);
73}
74
75/// \brief Compare two source ranges to determine their relative position in
76/// the translation unit.
77static RangeComparisonResult RangeCompare(SourceManager &SM,
78 SourceRange R1,
79 SourceRange R2) {
80 assert(R1.isValid() && "First range is invalid?");
81 assert(R2.isValid() && "Second range is invalid?");
82 if (R1.getEnd() != R2.getBegin() &&
83 SM.isBeforeInTranslationUnit(R1.getEnd(), R2.getBegin()))
84 return RangeBefore;
85 if (R2.getEnd() != R1.getBegin() &&
86 SM.isBeforeInTranslationUnit(R2.getEnd(), R1.getBegin()))
87 return RangeAfter;
88 return RangeOverlap;
89}
90
91/// \brief Determine if a source location falls within, before, or after a
92/// a given source range.
93static RangeComparisonResult LocationCompare(SourceManager &SM,
94 SourceLocation L, SourceRange R) {
95 assert(R.isValid() && "First range is invalid?");
96 assert(L.isValid() && "Second range is invalid?");
97 if (L == R.getBegin() || L == R.getEnd())
98 return RangeOverlap;
99 if (SM.isBeforeInTranslationUnit(L, R.getBegin()))
100 return RangeBefore;
101 if (SM.isBeforeInTranslationUnit(R.getEnd(), L))
102 return RangeAfter;
103 return RangeOverlap;
104}
105
106/// \brief Translate a Clang source range into a CIndex source range.
107///
108/// Clang internally represents ranges where the end location points to the
109/// start of the token at the end. However, for external clients it is more
110/// useful to have a CXSourceRange be a proper half-open interval. This routine
111/// does the appropriate translation.
112CXSourceRange cxloc::translateSourceRange(const SourceManager &SM,
113 const LangOptions &LangOpts,
114 const CharSourceRange &R) {
115 // We want the last character in this location, so we will adjust the
116 // location accordingly.
117 SourceLocation EndLoc = R.getEnd();
118 if (EndLoc.isValid() && EndLoc.isMacroID() && !SM.isMacroArgExpansion(EndLoc))
119 EndLoc = SM.getExpansionRange(EndLoc).second;
120 if (R.isTokenRange() && !EndLoc.isInvalid()) {
121 unsigned Length = Lexer::MeasureTokenLength(SM.getSpellingLoc(EndLoc),
122 SM, LangOpts);
123 EndLoc = EndLoc.getLocWithOffset(Length);
124 }
125
126 CXSourceRange Result = { { (void *)&SM, (void *)&LangOpts },
127 R.getBegin().getRawEncoding(),
128 EndLoc.getRawEncoding() };
129 return Result;
130}
131
132//===----------------------------------------------------------------------===//
133// Cursor visitor.
134//===----------------------------------------------------------------------===//
135
136static SourceRange getRawCursorExtent(CXCursor C);
137static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr);
138
139
140RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
141 return RangeCompare(AU->getSourceManager(), R, RegionOfInterest);
142}
143
144/// \brief Visit the given cursor and, if requested by the visitor,
145/// its children.
146///
147/// \param Cursor the cursor to visit.
148///
149/// \param CheckedRegionOfInterest if true, then the caller already checked
150/// that this cursor is within the region of interest.
151///
152/// \returns true if the visitation should be aborted, false if it
153/// should continue.
154bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
155 if (clang_isInvalid(Cursor.kind))
156 return false;
157
158 if (clang_isDeclaration(Cursor.kind)) {
159 Decl *D = getCursorDecl(Cursor);
160 if (!D) {
161 assert(0 && "Invalid declaration cursor");
162 return true; // abort.
163 }
164
165 // Ignore implicit declarations, unless it's an objc method because
166 // currently we should report implicit methods for properties when indexing.
167 if (D->isImplicit() && !isa<ObjCMethodDecl>(D))
168 return false;
169 }
170
171 // If we have a range of interest, and this cursor doesn't intersect with it,
172 // we're done.
173 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
174 SourceRange Range = getRawCursorExtent(Cursor);
175 if (Range.isInvalid() || CompareRegionOfInterest(Range))
176 return false;
177 }
178
179 switch (Visitor(Cursor, Parent, ClientData)) {
180 case CXChildVisit_Break:
181 return true;
182
183 case CXChildVisit_Continue:
184 return false;
185
186 case CXChildVisit_Recurse: {
187 bool ret = VisitChildren(Cursor);
188 if (PostChildrenVisitor)
189 if (PostChildrenVisitor(Cursor, ClientData))
190 return true;
191 return ret;
192 }
193 }
194
195 llvm_unreachable("Invalid CXChildVisitResult!");
196}
197
198static bool visitPreprocessedEntitiesInRange(SourceRange R,
199 PreprocessingRecord &PPRec,
200 CursorVisitor &Visitor) {
201 SourceManager &SM = Visitor.getASTUnit()->getSourceManager();
202 FileID FID;
203
204 if (!Visitor.shouldVisitIncludedEntities()) {
205 // If the begin/end of the range lie in the same FileID, do the optimization
206 // where we skip preprocessed entities that do not come from the same FileID.
207 FID = SM.getFileID(SM.getFileLoc(R.getBegin()));
208 if (FID != SM.getFileID(SM.getFileLoc(R.getEnd())))
209 FID = FileID();
210 }
211
212 std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
213 Entities = PPRec.getPreprocessedEntitiesInRange(R);
214 return Visitor.visitPreprocessedEntities(Entities.first, Entities.second,
215 PPRec, FID);
216}
217
218void CursorVisitor::visitFileRegion() {
219 if (RegionOfInterest.isInvalid())
220 return;
221
222 ASTUnit *Unit = static_cast<ASTUnit *>(TU->TUData);
223 SourceManager &SM = Unit->getSourceManager();
224
225 std::pair<FileID, unsigned>
226 Begin = SM.getDecomposedLoc(SM.getFileLoc(RegionOfInterest.getBegin())),
227 End = SM.getDecomposedLoc(SM.getFileLoc(RegionOfInterest.getEnd()));
228
229 if (End.first != Begin.first) {
230 // If the end does not reside in the same file, try to recover by
231 // picking the end of the file of begin location.
232 End.first = Begin.first;
233 End.second = SM.getFileIDSize(Begin.first);
234 }
235
236 assert(Begin.first == End.first);
237 if (Begin.second > End.second)
238 return;
239
240 FileID File = Begin.first;
241 unsigned Offset = Begin.second;
242 unsigned Length = End.second - Begin.second;
243
244 if (!VisitDeclsOnly && !VisitPreprocessorLast)
245 if (visitPreprocessedEntitiesInRegion())
246 return; // visitation break.
247
248 visitDeclsFromFileRegion(File, Offset, Length);
249
250 if (!VisitDeclsOnly && VisitPreprocessorLast)
251 visitPreprocessedEntitiesInRegion();
252}
253
254static bool isInLexicalContext(Decl *D, DeclContext *DC) {
255 if (!DC)
256 return false;
257
258 for (DeclContext *DeclDC = D->getLexicalDeclContext();
259 DeclDC; DeclDC = DeclDC->getLexicalParent()) {
260 if (DeclDC == DC)
261 return true;
262 }
263 return false;
264}
265
266void CursorVisitor::visitDeclsFromFileRegion(FileID File,
267 unsigned Offset, unsigned Length) {
268 ASTUnit *Unit = static_cast<ASTUnit *>(TU->TUData);
269 SourceManager &SM = Unit->getSourceManager();
270 SourceRange Range = RegionOfInterest;
271
272 SmallVector<Decl *, 16> Decls;
273 Unit->findFileRegionDecls(File, Offset, Length, Decls);
274
275 // If we didn't find any file level decls for the file, try looking at the
276 // file that it was included from.
277 while (Decls.empty() || Decls.front()->isTopLevelDeclInObjCContainer()) {
278 bool Invalid = false;
279 const SrcMgr::SLocEntry &SLEntry = SM.getSLocEntry(File, &Invalid);
280 if (Invalid)
281 return;
282
283 SourceLocation Outer;
284 if (SLEntry.isFile())
285 Outer = SLEntry.getFile().getIncludeLoc();
286 else
287 Outer = SLEntry.getExpansion().getExpansionLocStart();
288 if (Outer.isInvalid())
289 return;
290
291 llvm::tie(File, Offset) = SM.getDecomposedExpansionLoc(Outer);
292 Length = 0;
293 Unit->findFileRegionDecls(File, Offset, Length, Decls);
294 }
295
296 assert(!Decls.empty());
297
298 bool VisitedAtLeastOnce = false;
299 DeclContext *CurDC = 0;
300 SmallVector<Decl *, 16>::iterator DIt = Decls.begin();
301 for (SmallVector<Decl *, 16>::iterator DE = Decls.end(); DIt != DE; ++DIt) {
302 Decl *D = *DIt;
303 if (D->getSourceRange().isInvalid())
304 continue;
305
306 if (isInLexicalContext(D, CurDC))
307 continue;
308
309 CurDC = dyn_cast<DeclContext>(D);
310
311 if (TagDecl *TD = dyn_cast<TagDecl>(D))
312 if (!TD->isFreeStanding())
313 continue;
314
315 RangeComparisonResult CompRes = RangeCompare(SM, D->getSourceRange(),Range);
316 if (CompRes == RangeBefore)
317 continue;
318 if (CompRes == RangeAfter)
319 break;
320
321 assert(CompRes == RangeOverlap);
322 VisitedAtLeastOnce = true;
323
324 if (isa<ObjCContainerDecl>(D)) {
325 FileDI_current = &DIt;
326 FileDE_current = DE;
327 } else {
328 FileDI_current = 0;
329 }
330
331 if (Visit(MakeCXCursor(D, TU, Range), /*CheckedRegionOfInterest=*/true))
332 break;
333 }
334
335 if (VisitedAtLeastOnce)
336 return;
337
338 // No Decls overlapped with the range. Move up the lexical context until there
339 // is a context that contains the range or we reach the translation unit
340 // level.
341 DeclContext *DC = DIt == Decls.begin() ? (*DIt)->getLexicalDeclContext()
342 : (*(DIt-1))->getLexicalDeclContext();
343
344 while (DC && !DC->isTranslationUnit()) {
345 Decl *D = cast<Decl>(DC);
346 SourceRange CurDeclRange = D->getSourceRange();
347 if (CurDeclRange.isInvalid())
348 break;
349
350 if (RangeCompare(SM, CurDeclRange, Range) == RangeOverlap) {
351 Visit(MakeCXCursor(D, TU, Range), /*CheckedRegionOfInterest=*/true);
352 break;
353 }
354
355 DC = D->getLexicalDeclContext();
356 }
357}
358
359bool CursorVisitor::visitPreprocessedEntitiesInRegion() {
360 if (!AU->getPreprocessor().getPreprocessingRecord())
361 return false;
362
363 PreprocessingRecord &PPRec
364 = *AU->getPreprocessor().getPreprocessingRecord();
365 SourceManager &SM = AU->getSourceManager();
366
367 if (RegionOfInterest.isValid()) {
368 SourceRange MappedRange = AU->mapRangeToPreamble(RegionOfInterest);
369 SourceLocation B = MappedRange.getBegin();
370 SourceLocation E = MappedRange.getEnd();
371
372 if (AU->isInPreambleFileID(B)) {
373 if (SM.isLoadedSourceLocation(E))
374 return visitPreprocessedEntitiesInRange(SourceRange(B, E),
375 PPRec, *this);
376
377 // Beginning of range lies in the preamble but it also extends beyond
378 // it into the main file. Split the range into 2 parts, one covering
379 // the preamble and another covering the main file. This allows subsequent
380 // calls to visitPreprocessedEntitiesInRange to accept a source range that
381 // lies in the same FileID, allowing it to skip preprocessed entities that
382 // do not come from the same FileID.
383 bool breaked =
384 visitPreprocessedEntitiesInRange(
385 SourceRange(B, AU->getEndOfPreambleFileID()),
386 PPRec, *this);
387 if (breaked) return true;
388 return visitPreprocessedEntitiesInRange(
389 SourceRange(AU->getStartOfMainFileID(), E),
390 PPRec, *this);
391 }
392
393 return visitPreprocessedEntitiesInRange(SourceRange(B, E), PPRec, *this);
394 }
395
396 bool OnlyLocalDecls
397 = !AU->isMainFileAST() && AU->getOnlyLocalDecls();
398
399 if (OnlyLocalDecls)
400 return visitPreprocessedEntities(PPRec.local_begin(), PPRec.local_end(),
401 PPRec);
402
403 return visitPreprocessedEntities(PPRec.begin(), PPRec.end(), PPRec);
404}
405
406template<typename InputIterator>
407bool CursorVisitor::visitPreprocessedEntities(InputIterator First,
408 InputIterator Last,
409 PreprocessingRecord &PPRec,
410 FileID FID) {
411 for (; First != Last; ++First) {
412 if (!FID.isInvalid() && !PPRec.isEntityInFileID(First, FID))
413 continue;
414
415 PreprocessedEntity *PPE = *First;
416 if (MacroExpansion *ME = dyn_cast<MacroExpansion>(PPE)) {
417 if (Visit(MakeMacroExpansionCursor(ME, TU)))
418 return true;
419
420 continue;
421 }
422
423 if (MacroDefinition *MD = dyn_cast<MacroDefinition>(PPE)) {
424 if (Visit(MakeMacroDefinitionCursor(MD, TU)))
425 return true;
426
427 continue;
428 }
429
430 if (InclusionDirective *ID = dyn_cast<InclusionDirective>(PPE)) {
431 if (Visit(MakeInclusionDirectiveCursor(ID, TU)))
432 return true;
433
434 continue;
435 }
436 }
437
438 return false;
439}
440
441/// \brief Visit the children of the given cursor.
442///
443/// \returns true if the visitation should be aborted, false if it
444/// should continue.
445bool CursorVisitor::VisitChildren(CXCursor Cursor) {
446 if (clang_isReference(Cursor.kind) &&
447 Cursor.kind != CXCursor_CXXBaseSpecifier) {
448 // By definition, references have no children.
449 return false;
450 }
451
452 // Set the Parent field to Cursor, then back to its old value once we're
453 // done.
454 SetParentRAII SetParent(Parent, StmtParent, Cursor);
455
456 if (clang_isDeclaration(Cursor.kind)) {
457 Decl *D = getCursorDecl(Cursor);
458 if (!D)
459 return false;
460
461 return VisitAttributes(D) || Visit(D);
462 }
463
464 if (clang_isStatement(Cursor.kind)) {
465 if (Stmt *S = getCursorStmt(Cursor))
466 return Visit(S);
467
468 return false;
469 }
470
471 if (clang_isExpression(Cursor.kind)) {
472 if (Expr *E = getCursorExpr(Cursor))
473 return Visit(E);
474
475 return false;
476 }
477
478 if (clang_isTranslationUnit(Cursor.kind)) {
479 CXTranslationUnit tu = getCursorTU(Cursor);
480 ASTUnit *CXXUnit = static_cast<ASTUnit*>(tu->TUData);
481
482 int VisitOrder[2] = { VisitPreprocessorLast, !VisitPreprocessorLast };
483 for (unsigned I = 0; I != 2; ++I) {
484 if (VisitOrder[I]) {
485 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
486 RegionOfInterest.isInvalid()) {
487 for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
488 TLEnd = CXXUnit->top_level_end();
489 TL != TLEnd; ++TL) {
490 if (Visit(MakeCXCursor(*TL, tu, RegionOfInterest), true))
491 return true;
492 }
493 } else if (VisitDeclContext(
494 CXXUnit->getASTContext().getTranslationUnitDecl()))
495 return true;
496 continue;
497 }
498
499 // Walk the preprocessing record.
500 if (CXXUnit->getPreprocessor().getPreprocessingRecord())
501 visitPreprocessedEntitiesInRegion();
502 }
503
504 return false;
505 }
506
507 if (Cursor.kind == CXCursor_CXXBaseSpecifier) {
508 if (CXXBaseSpecifier *Base = getCursorCXXBaseSpecifier(Cursor)) {
509 if (TypeSourceInfo *BaseTSInfo = Base->getTypeSourceInfo()) {
510 return Visit(BaseTSInfo->getTypeLoc());
511 }
512 }
513 }
514
515 if (Cursor.kind == CXCursor_IBOutletCollectionAttr) {
516 IBOutletCollectionAttr *A =
517 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(Cursor));
518 if (const ObjCInterfaceType *InterT = A->getInterface()->getAs<ObjCInterfaceType>())
519 return Visit(cxcursor::MakeCursorObjCClassRef(InterT->getInterface(),
520 A->getInterfaceLoc(), TU));
521 }
522
523 // Nothing to visit at the moment.
524 return false;
525}
526
527bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
528 if (TypeSourceInfo *TSInfo = B->getSignatureAsWritten())
529 if (Visit(TSInfo->getTypeLoc()))
530 return true;
531
532 if (Stmt *Body = B->getBody())
533 return Visit(MakeCXCursor(Body, StmtParent, TU, RegionOfInterest));
534
535 return false;
536}
537
538llvm::Optional<bool> CursorVisitor::shouldVisitCursor(CXCursor Cursor) {
539 if (RegionOfInterest.isValid()) {
540 SourceRange Range = getFullCursorExtent(Cursor, AU->getSourceManager());
541 if (Range.isInvalid())
542 return llvm::Optional<bool>();
543
544 switch (CompareRegionOfInterest(Range)) {
545 case RangeBefore:
546 // This declaration comes before the region of interest; skip it.
547 return llvm::Optional<bool>();
548
549 case RangeAfter:
550 // This declaration comes after the region of interest; we're done.
551 return false;
552
553 case RangeOverlap:
554 // This declaration overlaps the region of interest; visit it.
555 break;
556 }
557 }
558 return true;
559}
560
561bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
562 DeclContext::decl_iterator I = DC->decls_begin(), E = DC->decls_end();
563
564 // FIXME: Eventually remove. This part of a hack to support proper
565 // iteration over all Decls contained lexically within an ObjC container.
566 SaveAndRestore<DeclContext::decl_iterator*> DI_saved(DI_current, &I);
567 SaveAndRestore<DeclContext::decl_iterator> DE_saved(DE_current, E);
568
569 for ( ; I != E; ++I) {
570 Decl *D = *I;
571 if (D->getLexicalDeclContext() != DC)
572 continue;
573 CXCursor Cursor = MakeCXCursor(D, TU, RegionOfInterest);
574
575 // Ignore synthesized ivars here, otherwise if we have something like:
576 // @synthesize prop = _prop;
577 // and '_prop' is not declared, we will encounter a '_prop' ivar before
578 // encountering the 'prop' synthesize declaration and we will think that
579 // we passed the region-of-interest.
580 if (ObjCIvarDecl *ivarD = dyn_cast<ObjCIvarDecl>(D)) {
581 if (ivarD->getSynthesize())
582 continue;
583 }
584
585 // FIXME: ObjCClassRef/ObjCProtocolRef for forward class/protocol
586 // declarations is a mismatch with the compiler semantics.
587 if (Cursor.kind == CXCursor_ObjCInterfaceDecl) {
588 ObjCInterfaceDecl *ID = cast<ObjCInterfaceDecl>(D);
589 if (!ID->isThisDeclarationADefinition())
590 Cursor = MakeCursorObjCClassRef(ID, ID->getLocation(), TU);
591
592 } else if (Cursor.kind == CXCursor_ObjCProtocolDecl) {
593 ObjCProtocolDecl *PD = cast<ObjCProtocolDecl>(D);
594 if (!PD->isThisDeclarationADefinition())
595 Cursor = MakeCursorObjCProtocolRef(PD, PD->getLocation(), TU);
596 }
597
598 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
599 if (!V.hasValue())
600 continue;
601 if (!V.getValue())
602 return false;
603 if (Visit(Cursor, true))
604 return true;
605 }
606 return false;
607}
608
609bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
610 llvm_unreachable("Translation units are visited directly by Visit()");
611}
612
613bool CursorVisitor::VisitTypeAliasDecl(TypeAliasDecl *D) {
614 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
615 return Visit(TSInfo->getTypeLoc());
616
617 return false;
618}
619
620bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
621 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
622 return Visit(TSInfo->getTypeLoc());
623
624 return false;
625}
626
627bool CursorVisitor::VisitTagDecl(TagDecl *D) {
628 return VisitDeclContext(D);
629}
630
631bool CursorVisitor::VisitClassTemplateSpecializationDecl(
632 ClassTemplateSpecializationDecl *D) {
633 bool ShouldVisitBody = false;
634 switch (D->getSpecializationKind()) {
635 case TSK_Undeclared:
636 case TSK_ImplicitInstantiation:
637 // Nothing to visit
638 return false;
639
640 case TSK_ExplicitInstantiationDeclaration:
641 case TSK_ExplicitInstantiationDefinition:
642 break;
643
644 case TSK_ExplicitSpecialization:
645 ShouldVisitBody = true;
646 break;
647 }
648
649 // Visit the template arguments used in the specialization.
650 if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) {
651 TypeLoc TL = SpecType->getTypeLoc();
652 if (TemplateSpecializationTypeLoc *TSTLoc
653 = dyn_cast<TemplateSpecializationTypeLoc>(&TL)) {
654 for (unsigned I = 0, N = TSTLoc->getNumArgs(); I != N; ++I)
655 if (VisitTemplateArgumentLoc(TSTLoc->getArgLoc(I)))
656 return true;
657 }
658 }
659
660 if (ShouldVisitBody && VisitCXXRecordDecl(D))
661 return true;
662
663 return false;
664}
665
666bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl(
667 ClassTemplatePartialSpecializationDecl *D) {
668 // FIXME: Visit the "outer" template parameter lists on the TagDecl
669 // before visiting these template parameters.
670 if (VisitTemplateParameters(D->getTemplateParameters()))
671 return true;
672
673 // Visit the partial specialization arguments.
674 const TemplateArgumentLoc *TemplateArgs = D->getTemplateArgsAsWritten();
675 for (unsigned I = 0, N = D->getNumTemplateArgsAsWritten(); I != N; ++I)
676 if (VisitTemplateArgumentLoc(TemplateArgs[I]))
677 return true;
678
679 return VisitCXXRecordDecl(D);
680}
681
682bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
683 // Visit the default argument.
684 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
685 if (TypeSourceInfo *DefArg = D->getDefaultArgumentInfo())
686 if (Visit(DefArg->getTypeLoc()))
687 return true;
688
689 return false;
690}
691
692bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
693 if (Expr *Init = D->getInitExpr())
694 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
695 return false;
696}
697
698bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
699 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
700 if (Visit(TSInfo->getTypeLoc()))
701 return true;
702
703 // Visit the nested-name-specifier, if present.
704 if (NestedNameSpecifierLoc QualifierLoc = DD->getQualifierLoc())
705 if (VisitNestedNameSpecifierLoc(QualifierLoc))
706 return true;
707
708 return false;
709}
710
711/// \brief Compare two base or member initializers based on their source order.
712static int CompareCXXCtorInitializers(const void* Xp, const void *Yp) {
713 CXXCtorInitializer const * const *X
714 = static_cast<CXXCtorInitializer const * const *>(Xp);
715 CXXCtorInitializer const * const *Y
716 = static_cast<CXXCtorInitializer const * const *>(Yp);
717
718 if ((*X)->getSourceOrder() < (*Y)->getSourceOrder())
719 return -1;
720 else if ((*X)->getSourceOrder() > (*Y)->getSourceOrder())
721 return 1;
722 else
723 return 0;
724}
725
726bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
727 if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
728 // Visit the function declaration's syntactic components in the order
729 // written. This requires a bit of work.
730 TypeLoc TL = TSInfo->getTypeLoc().IgnoreParens();
731 FunctionTypeLoc *FTL = dyn_cast<FunctionTypeLoc>(&TL);
732
733 // If we have a function declared directly (without the use of a typedef),
734 // visit just the return type. Otherwise, just visit the function's type
735 // now.
736 if ((FTL && !isa<CXXConversionDecl>(ND) && Visit(FTL->getResultLoc())) ||
737 (!FTL && Visit(TL)))
738 return true;
739
740 // Visit the nested-name-specifier, if present.
741 if (NestedNameSpecifierLoc QualifierLoc = ND->getQualifierLoc())
742 if (VisitNestedNameSpecifierLoc(QualifierLoc))
743 return true;
744
745 // Visit the declaration name.
746 if (VisitDeclarationNameInfo(ND->getNameInfo()))
747 return true;
748
749 // FIXME: Visit explicitly-specified template arguments!
750
751 // Visit the function parameters, if we have a function type.
752 if (FTL && VisitFunctionTypeLoc(*FTL, true))
753 return true;
754
Bill Wendlingad017fa2012-12-20 19:22:21 +0000755 // FIXME: Attributes?
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000756 }
757
758 if (ND->doesThisDeclarationHaveABody() && !ND->isLateTemplateParsed()) {
759 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ND)) {
760 // Find the initializers that were written in the source.
761 SmallVector<CXXCtorInitializer *, 4> WrittenInits;
762 for (CXXConstructorDecl::init_iterator I = Constructor->init_begin(),
763 IEnd = Constructor->init_end();
764 I != IEnd; ++I) {
765 if (!(*I)->isWritten())
766 continue;
767
768 WrittenInits.push_back(*I);
769 }
770
771 // Sort the initializers in source order
772 llvm::array_pod_sort(WrittenInits.begin(), WrittenInits.end(),
773 &CompareCXXCtorInitializers);
774
775 // Visit the initializers in source order
776 for (unsigned I = 0, N = WrittenInits.size(); I != N; ++I) {
777 CXXCtorInitializer *Init = WrittenInits[I];
778 if (Init->isAnyMemberInitializer()) {
779 if (Visit(MakeCursorMemberRef(Init->getAnyMember(),
780 Init->getMemberLocation(), TU)))
781 return true;
782 } else if (TypeSourceInfo *TInfo = Init->getTypeSourceInfo()) {
783 if (Visit(TInfo->getTypeLoc()))
784 return true;
785 }
786
787 // Visit the initializer value.
788 if (Expr *Initializer = Init->getInit())
789 if (Visit(MakeCXCursor(Initializer, ND, TU, RegionOfInterest)))
790 return true;
791 }
792 }
793
794 if (Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest)))
795 return true;
796 }
797
798 return false;
799}
800
801bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
802 if (VisitDeclaratorDecl(D))
803 return true;
804
805 if (Expr *BitWidth = D->getBitWidth())
806 return Visit(MakeCXCursor(BitWidth, StmtParent, TU, RegionOfInterest));
807
808 return false;
809}
810
811bool CursorVisitor::VisitVarDecl(VarDecl *D) {
812 if (VisitDeclaratorDecl(D))
813 return true;
814
815 if (Expr *Init = D->getInit())
816 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
817
818 return false;
819}
820
821bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
822 if (VisitDeclaratorDecl(D))
823 return true;
824
825 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
826 if (Expr *DefArg = D->getDefaultArgument())
827 return Visit(MakeCXCursor(DefArg, StmtParent, TU, RegionOfInterest));
828
829 return false;
830}
831
832bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
833 // FIXME: Visit the "outer" template parameter lists on the FunctionDecl
834 // before visiting these template parameters.
835 if (VisitTemplateParameters(D->getTemplateParameters()))
836 return true;
837
838 return VisitFunctionDecl(D->getTemplatedDecl());
839}
840
841bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) {
842 // FIXME: Visit the "outer" template parameter lists on the TagDecl
843 // before visiting these template parameters.
844 if (VisitTemplateParameters(D->getTemplateParameters()))
845 return true;
846
847 return VisitCXXRecordDecl(D->getTemplatedDecl());
848}
849
850bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
851 if (VisitTemplateParameters(D->getTemplateParameters()))
852 return true;
853
854 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() &&
855 VisitTemplateArgumentLoc(D->getDefaultArgument()))
856 return true;
857
858 return false;
859}
860
861bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
862 if (TypeSourceInfo *TSInfo = ND->getResultTypeSourceInfo())
863 if (Visit(TSInfo->getTypeLoc()))
864 return true;
865
866 for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
867 PEnd = ND->param_end();
868 P != PEnd; ++P) {
869 if (Visit(MakeCXCursor(*P, TU, RegionOfInterest)))
870 return true;
871 }
872
873 if (ND->isThisDeclarationADefinition() &&
874 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest)))
875 return true;
876
877 return false;
878}
879
880template <typename DeclIt>
881static void addRangedDeclsInContainer(DeclIt *DI_current, DeclIt DE_current,
882 SourceManager &SM, SourceLocation EndLoc,
883 SmallVectorImpl<Decl *> &Decls) {
884 DeclIt next = *DI_current;
885 while (++next != DE_current) {
886 Decl *D_next = *next;
887 if (!D_next)
888 break;
889 SourceLocation L = D_next->getLocStart();
890 if (!L.isValid())
891 break;
892 if (SM.isBeforeInTranslationUnit(L, EndLoc)) {
893 *DI_current = next;
894 Decls.push_back(D_next);
895 continue;
896 }
897 break;
898 }
899}
900
901namespace {
902 struct ContainerDeclsSort {
903 SourceManager &SM;
904 ContainerDeclsSort(SourceManager &sm) : SM(sm) {}
905 bool operator()(Decl *A, Decl *B) {
906 SourceLocation L_A = A->getLocStart();
907 SourceLocation L_B = B->getLocStart();
908 assert(L_A.isValid() && L_B.isValid());
909 return SM.isBeforeInTranslationUnit(L_A, L_B);
910 }
911 };
912}
913
914bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
915 // FIXME: Eventually convert back to just 'VisitDeclContext()'. Essentially
916 // an @implementation can lexically contain Decls that are not properly
917 // nested in the AST. When we identify such cases, we need to retrofit
918 // this nesting here.
919 if (!DI_current && !FileDI_current)
920 return VisitDeclContext(D);
921
922 // Scan the Decls that immediately come after the container
923 // in the current DeclContext. If any fall within the
924 // container's lexical region, stash them into a vector
925 // for later processing.
926 SmallVector<Decl *, 24> DeclsInContainer;
927 SourceLocation EndLoc = D->getSourceRange().getEnd();
928 SourceManager &SM = AU->getSourceManager();
929 if (EndLoc.isValid()) {
930 if (DI_current) {
931 addRangedDeclsInContainer(DI_current, DE_current, SM, EndLoc,
932 DeclsInContainer);
933 } else {
934 addRangedDeclsInContainer(FileDI_current, FileDE_current, SM, EndLoc,
935 DeclsInContainer);
936 }
937 }
938
939 // The common case.
940 if (DeclsInContainer.empty())
941 return VisitDeclContext(D);
942
943 // Get all the Decls in the DeclContext, and sort them with the
944 // additional ones we've collected. Then visit them.
945 for (DeclContext::decl_iterator I = D->decls_begin(), E = D->decls_end();
946 I!=E; ++I) {
947 Decl *subDecl = *I;
948 if (!subDecl || subDecl->getLexicalDeclContext() != D ||
949 subDecl->getLocStart().isInvalid())
950 continue;
951 DeclsInContainer.push_back(subDecl);
952 }
953
954 // Now sort the Decls so that they appear in lexical order.
955 std::sort(DeclsInContainer.begin(), DeclsInContainer.end(),
956 ContainerDeclsSort(SM));
957
958 // Now visit the decls.
959 for (SmallVectorImpl<Decl*>::iterator I = DeclsInContainer.begin(),
960 E = DeclsInContainer.end(); I != E; ++I) {
961 CXCursor Cursor = MakeCXCursor(*I, TU, RegionOfInterest);
962 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
963 if (!V.hasValue())
964 continue;
965 if (!V.getValue())
966 return false;
967 if (Visit(Cursor, true))
968 return true;
969 }
970 return false;
971}
972
973bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
974 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
975 TU)))
976 return true;
977
978 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
979 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
980 E = ND->protocol_end(); I != E; ++I, ++PL)
981 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
982 return true;
983
984 return VisitObjCContainerDecl(ND);
985}
986
987bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
988 if (!PID->isThisDeclarationADefinition())
989 return Visit(MakeCursorObjCProtocolRef(PID, PID->getLocation(), TU));
990
991 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
992 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
993 E = PID->protocol_end(); I != E; ++I, ++PL)
994 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
995 return true;
996
997 return VisitObjCContainerDecl(PID);
998}
999
1000bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
1001 if (PD->getTypeSourceInfo() && Visit(PD->getTypeSourceInfo()->getTypeLoc()))
1002 return true;
1003
1004 // FIXME: This implements a workaround with @property declarations also being
1005 // installed in the DeclContext for the @interface. Eventually this code
1006 // should be removed.
1007 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
1008 if (!CDecl || !CDecl->IsClassExtension())
1009 return false;
1010
1011 ObjCInterfaceDecl *ID = CDecl->getClassInterface();
1012 if (!ID)
1013 return false;
1014
1015 IdentifierInfo *PropertyId = PD->getIdentifier();
1016 ObjCPropertyDecl *prevDecl =
1017 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId);
1018
1019 if (!prevDecl)
1020 return false;
1021
1022 // Visit synthesized methods since they will be skipped when visiting
1023 // the @interface.
1024 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
1025 if (MD->isPropertyAccessor() && MD->getLexicalDeclContext() == CDecl)
1026 if (Visit(MakeCXCursor(MD, TU, RegionOfInterest)))
1027 return true;
1028
1029 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
1030 if (MD->isPropertyAccessor() && MD->getLexicalDeclContext() == CDecl)
1031 if (Visit(MakeCXCursor(MD, TU, RegionOfInterest)))
1032 return true;
1033
1034 return false;
1035}
1036
1037bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
1038 if (!D->isThisDeclarationADefinition()) {
1039 // Forward declaration is treated like a reference.
1040 return Visit(MakeCursorObjCClassRef(D, D->getLocation(), TU));
1041 }
1042
1043 // Issue callbacks for super class.
1044 if (D->getSuperClass() &&
1045 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
1046 D->getSuperClassLoc(),
1047 TU)))
1048 return true;
1049
1050 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1051 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
1052 E = D->protocol_end(); I != E; ++I, ++PL)
1053 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
1054 return true;
1055
1056 return VisitObjCContainerDecl(D);
1057}
1058
1059bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
1060 return VisitObjCContainerDecl(D);
1061}
1062
1063bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
1064 // 'ID' could be null when dealing with invalid code.
1065 if (ObjCInterfaceDecl *ID = D->getClassInterface())
1066 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
1067 return true;
1068
1069 return VisitObjCImplDecl(D);
1070}
1071
1072bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
1073#if 0
1074 // Issue callbacks for super class.
1075 // FIXME: No source location information!
1076 if (D->getSuperClass() &&
1077 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
1078 D->getSuperClassLoc(),
1079 TU)))
1080 return true;
1081#endif
1082
1083 return VisitObjCImplDecl(D);
1084}
1085
1086bool CursorVisitor::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *PD) {
1087 if (ObjCIvarDecl *Ivar = PD->getPropertyIvarDecl())
1088 if (PD->isIvarNameSpecified())
1089 return Visit(MakeCursorMemberRef(Ivar, PD->getPropertyIvarDeclLoc(), TU));
1090
1091 return false;
1092}
1093
1094bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
1095 return VisitDeclContext(D);
1096}
1097
1098bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
1099 // Visit nested-name-specifier.
1100 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1101 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1102 return true;
1103
1104 return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(),
1105 D->getTargetNameLoc(), TU));
1106}
1107
1108bool CursorVisitor::VisitUsingDecl(UsingDecl *D) {
1109 // Visit nested-name-specifier.
1110 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1111 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1112 return true;
1113 }
1114
1115 if (Visit(MakeCursorOverloadedDeclRef(D, D->getLocation(), TU)))
1116 return true;
1117
1118 return VisitDeclarationNameInfo(D->getNameInfo());
1119}
1120
1121bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
1122 // Visit nested-name-specifier.
1123 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1124 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1125 return true;
1126
1127 return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(),
1128 D->getIdentLocation(), TU));
1129}
1130
1131bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
1132 // Visit nested-name-specifier.
1133 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1134 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1135 return true;
1136 }
1137
1138 return VisitDeclarationNameInfo(D->getNameInfo());
1139}
1140
1141bool CursorVisitor::VisitUnresolvedUsingTypenameDecl(
1142 UnresolvedUsingTypenameDecl *D) {
1143 // Visit nested-name-specifier.
1144 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1145 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1146 return true;
1147
1148 return false;
1149}
1150
1151bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
1152 switch (Name.getName().getNameKind()) {
1153 case clang::DeclarationName::Identifier:
1154 case clang::DeclarationName::CXXLiteralOperatorName:
1155 case clang::DeclarationName::CXXOperatorName:
1156 case clang::DeclarationName::CXXUsingDirective:
1157 return false;
1158
1159 case clang::DeclarationName::CXXConstructorName:
1160 case clang::DeclarationName::CXXDestructorName:
1161 case clang::DeclarationName::CXXConversionFunctionName:
1162 if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
1163 return Visit(TSInfo->getTypeLoc());
1164 return false;
1165
1166 case clang::DeclarationName::ObjCZeroArgSelector:
1167 case clang::DeclarationName::ObjCOneArgSelector:
1168 case clang::DeclarationName::ObjCMultiArgSelector:
1169 // FIXME: Per-identifier location info?
1170 return false;
1171 }
1172
1173 llvm_unreachable("Invalid DeclarationName::Kind!");
1174}
1175
1176bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS,
1177 SourceRange Range) {
1178 // FIXME: This whole routine is a hack to work around the lack of proper
1179 // source information in nested-name-specifiers (PR5791). Since we do have
1180 // a beginning source location, we can visit the first component of the
1181 // nested-name-specifier, if it's a single-token component.
1182 if (!NNS)
1183 return false;
1184
1185 // Get the first component in the nested-name-specifier.
1186 while (NestedNameSpecifier *Prefix = NNS->getPrefix())
1187 NNS = Prefix;
1188
1189 switch (NNS->getKind()) {
1190 case NestedNameSpecifier::Namespace:
1191 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(),
1192 TU));
1193
1194 case NestedNameSpecifier::NamespaceAlias:
1195 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
1196 Range.getBegin(), TU));
1197
1198 case NestedNameSpecifier::TypeSpec: {
1199 // If the type has a form where we know that the beginning of the source
1200 // range matches up with a reference cursor. Visit the appropriate reference
1201 // cursor.
1202 const Type *T = NNS->getAsType();
1203 if (const TypedefType *Typedef = dyn_cast<TypedefType>(T))
1204 return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU));
1205 if (const TagType *Tag = dyn_cast<TagType>(T))
1206 return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU));
1207 if (const TemplateSpecializationType *TST
1208 = dyn_cast<TemplateSpecializationType>(T))
1209 return VisitTemplateName(TST->getTemplateName(), Range.getBegin());
1210 break;
1211 }
1212
1213 case NestedNameSpecifier::TypeSpecWithTemplate:
1214 case NestedNameSpecifier::Global:
1215 case NestedNameSpecifier::Identifier:
1216 break;
1217 }
1218
1219 return false;
1220}
1221
1222bool
1223CursorVisitor::VisitNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
1224 SmallVector<NestedNameSpecifierLoc, 4> Qualifiers;
1225 for (; Qualifier; Qualifier = Qualifier.getPrefix())
1226 Qualifiers.push_back(Qualifier);
1227
1228 while (!Qualifiers.empty()) {
1229 NestedNameSpecifierLoc Q = Qualifiers.pop_back_val();
1230 NestedNameSpecifier *NNS = Q.getNestedNameSpecifier();
1231 switch (NNS->getKind()) {
1232 case NestedNameSpecifier::Namespace:
1233 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(),
1234 Q.getLocalBeginLoc(),
1235 TU)))
1236 return true;
1237
1238 break;
1239
1240 case NestedNameSpecifier::NamespaceAlias:
1241 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
1242 Q.getLocalBeginLoc(),
1243 TU)))
1244 return true;
1245
1246 break;
1247
1248 case NestedNameSpecifier::TypeSpec:
1249 case NestedNameSpecifier::TypeSpecWithTemplate:
1250 if (Visit(Q.getTypeLoc()))
1251 return true;
1252
1253 break;
1254
1255 case NestedNameSpecifier::Global:
1256 case NestedNameSpecifier::Identifier:
1257 break;
1258 }
1259 }
1260
1261 return false;
1262}
1263
1264bool CursorVisitor::VisitTemplateParameters(
1265 const TemplateParameterList *Params) {
1266 if (!Params)
1267 return false;
1268
1269 for (TemplateParameterList::const_iterator P = Params->begin(),
1270 PEnd = Params->end();
1271 P != PEnd; ++P) {
1272 if (Visit(MakeCXCursor(*P, TU, RegionOfInterest)))
1273 return true;
1274 }
1275
1276 return false;
1277}
1278
1279bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) {
1280 switch (Name.getKind()) {
1281 case TemplateName::Template:
1282 return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
1283
1284 case TemplateName::OverloadedTemplate:
1285 // Visit the overloaded template set.
1286 if (Visit(MakeCursorOverloadedDeclRef(Name, Loc, TU)))
1287 return true;
1288
1289 return false;
1290
1291 case TemplateName::DependentTemplate:
1292 // FIXME: Visit nested-name-specifier.
1293 return false;
1294
1295 case TemplateName::QualifiedTemplate:
1296 // FIXME: Visit nested-name-specifier.
1297 return Visit(MakeCursorTemplateRef(
1298 Name.getAsQualifiedTemplateName()->getDecl(),
1299 Loc, TU));
1300
1301 case TemplateName::SubstTemplateTemplateParm:
1302 return Visit(MakeCursorTemplateRef(
1303 Name.getAsSubstTemplateTemplateParm()->getParameter(),
1304 Loc, TU));
1305
1306 case TemplateName::SubstTemplateTemplateParmPack:
1307 return Visit(MakeCursorTemplateRef(
1308 Name.getAsSubstTemplateTemplateParmPack()->getParameterPack(),
1309 Loc, TU));
1310 }
1311
1312 llvm_unreachable("Invalid TemplateName::Kind!");
1313}
1314
1315bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
1316 switch (TAL.getArgument().getKind()) {
1317 case TemplateArgument::Null:
1318 case TemplateArgument::Integral:
1319 case TemplateArgument::Pack:
1320 return false;
1321
1322 case TemplateArgument::Type:
1323 if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
1324 return Visit(TSInfo->getTypeLoc());
1325 return false;
1326
1327 case TemplateArgument::Declaration:
1328 if (Expr *E = TAL.getSourceDeclExpression())
1329 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
1330 return false;
1331
1332 case TemplateArgument::NullPtr:
1333 if (Expr *E = TAL.getSourceNullPtrExpression())
1334 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
1335 return false;
1336
1337 case TemplateArgument::Expression:
1338 if (Expr *E = TAL.getSourceExpression())
1339 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
1340 return false;
1341
1342 case TemplateArgument::Template:
1343 case TemplateArgument::TemplateExpansion:
1344 if (VisitNestedNameSpecifierLoc(TAL.getTemplateQualifierLoc()))
1345 return true;
1346
1347 return VisitTemplateName(TAL.getArgument().getAsTemplateOrTemplatePattern(),
1348 TAL.getTemplateNameLoc());
1349 }
1350
1351 llvm_unreachable("Invalid TemplateArgument::Kind!");
1352}
1353
1354bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1355 return VisitDeclContext(D);
1356}
1357
1358bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1359 return Visit(TL.getUnqualifiedLoc());
1360}
1361
1362bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
1363 ASTContext &Context = AU->getASTContext();
1364
1365 // Some builtin types (such as Objective-C's "id", "sel", and
1366 // "Class") have associated declarations. Create cursors for those.
1367 QualType VisitType;
1368 switch (TL.getTypePtr()->getKind()) {
1369
1370 case BuiltinType::Void:
1371 case BuiltinType::NullPtr:
1372 case BuiltinType::Dependent:
Guy Benyeib13621d2012-12-18 14:38:23 +00001373 case BuiltinType::OCLImage1d:
1374 case BuiltinType::OCLImage1dArray:
1375 case BuiltinType::OCLImage1dBuffer:
1376 case BuiltinType::OCLImage2d:
1377 case BuiltinType::OCLImage2dArray:
1378 case BuiltinType::OCLImage3d:
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001379#define BUILTIN_TYPE(Id, SingletonId)
1380#define SIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
1381#define UNSIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
1382#define FLOATING_TYPE(Id, SingletonId) case BuiltinType::Id:
1383#define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id:
1384#include "clang/AST/BuiltinTypes.def"
1385 break;
1386
1387 case BuiltinType::ObjCId:
1388 VisitType = Context.getObjCIdType();
1389 break;
1390
1391 case BuiltinType::ObjCClass:
1392 VisitType = Context.getObjCClassType();
1393 break;
1394
1395 case BuiltinType::ObjCSel:
1396 VisitType = Context.getObjCSelType();
1397 break;
1398 }
1399
1400 if (!VisitType.isNull()) {
1401 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
1402 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
1403 TU));
1404 }
1405
1406 return false;
1407}
1408
1409bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
1410 return Visit(MakeCursorTypeRef(TL.getTypedefNameDecl(), TL.getNameLoc(), TU));
1411}
1412
1413bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
1414 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1415}
1416
1417bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
1418 if (TL.isDefinition())
1419 return Visit(MakeCXCursor(TL.getDecl(), TU, RegionOfInterest));
1420
1421 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1422}
1423
1424bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
1425 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1426}
1427
1428bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
1429 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
1430 return true;
1431
1432 return false;
1433}
1434
1435bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1436 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
1437 return true;
1438
1439 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1440 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1441 TU)))
1442 return true;
1443 }
1444
1445 return false;
1446}
1447
1448bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
1449 return Visit(TL.getPointeeLoc());
1450}
1451
1452bool CursorVisitor::VisitParenTypeLoc(ParenTypeLoc TL) {
1453 return Visit(TL.getInnerLoc());
1454}
1455
1456bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
1457 return Visit(TL.getPointeeLoc());
1458}
1459
1460bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1461 return Visit(TL.getPointeeLoc());
1462}
1463
1464bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1465 return Visit(TL.getPointeeLoc());
1466}
1467
1468bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
1469 return Visit(TL.getPointeeLoc());
1470}
1471
1472bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
1473 return Visit(TL.getPointeeLoc());
1474}
1475
1476bool CursorVisitor::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
1477 return Visit(TL.getModifiedLoc());
1478}
1479
1480bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
1481 bool SkipResultType) {
1482 if (!SkipResultType && Visit(TL.getResultLoc()))
1483 return true;
1484
1485 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1486 if (Decl *D = TL.getArg(I))
1487 if (Visit(MakeCXCursor(D, TU, RegionOfInterest)))
1488 return true;
1489
1490 return false;
1491}
1492
1493bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
1494 if (Visit(TL.getElementLoc()))
1495 return true;
1496
1497 if (Expr *Size = TL.getSizeExpr())
1498 return Visit(MakeCXCursor(Size, StmtParent, TU, RegionOfInterest));
1499
1500 return false;
1501}
1502
1503bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
1504 TemplateSpecializationTypeLoc TL) {
1505 // Visit the template name.
1506 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1507 TL.getTemplateNameLoc()))
1508 return true;
1509
1510 // Visit the template arguments.
1511 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1512 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1513 return true;
1514
1515 return false;
1516}
1517
1518bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1519 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
1520}
1521
1522bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1523 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1524 return Visit(TSInfo->getTypeLoc());
1525
1526 return false;
1527}
1528
1529bool CursorVisitor::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
1530 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1531 return Visit(TSInfo->getTypeLoc());
1532
1533 return false;
1534}
1535
1536bool CursorVisitor::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
1537 if (VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1538 return true;
1539
1540 return false;
1541}
1542
1543bool CursorVisitor::VisitDependentTemplateSpecializationTypeLoc(
1544 DependentTemplateSpecializationTypeLoc TL) {
1545 // Visit the nested-name-specifier, if there is one.
1546 if (TL.getQualifierLoc() &&
1547 VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1548 return true;
1549
1550 // Visit the template arguments.
1551 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1552 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1553 return true;
1554
1555 return false;
1556}
1557
1558bool CursorVisitor::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
1559 if (VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1560 return true;
1561
1562 return Visit(TL.getNamedTypeLoc());
1563}
1564
1565bool CursorVisitor::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
1566 return Visit(TL.getPatternLoc());
1567}
1568
1569bool CursorVisitor::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
1570 if (Expr *E = TL.getUnderlyingExpr())
1571 return Visit(MakeCXCursor(E, StmtParent, TU));
1572
1573 return false;
1574}
1575
1576bool CursorVisitor::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
1577 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1578}
1579
1580bool CursorVisitor::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
1581 return Visit(TL.getValueLoc());
1582}
1583
1584#define DEFAULT_TYPELOC_IMPL(CLASS, PARENT) \
1585bool CursorVisitor::Visit##CLASS##TypeLoc(CLASS##TypeLoc TL) { \
1586 return Visit##PARENT##Loc(TL); \
1587}
1588
1589DEFAULT_TYPELOC_IMPL(Complex, Type)
1590DEFAULT_TYPELOC_IMPL(ConstantArray, ArrayType)
1591DEFAULT_TYPELOC_IMPL(IncompleteArray, ArrayType)
1592DEFAULT_TYPELOC_IMPL(VariableArray, ArrayType)
1593DEFAULT_TYPELOC_IMPL(DependentSizedArray, ArrayType)
1594DEFAULT_TYPELOC_IMPL(DependentSizedExtVector, Type)
1595DEFAULT_TYPELOC_IMPL(Vector, Type)
1596DEFAULT_TYPELOC_IMPL(ExtVector, VectorType)
1597DEFAULT_TYPELOC_IMPL(FunctionProto, FunctionType)
1598DEFAULT_TYPELOC_IMPL(FunctionNoProto, FunctionType)
1599DEFAULT_TYPELOC_IMPL(Record, TagType)
1600DEFAULT_TYPELOC_IMPL(Enum, TagType)
1601DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParm, Type)
1602DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParmPack, Type)
1603DEFAULT_TYPELOC_IMPL(Auto, Type)
1604
1605bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
1606 // Visit the nested-name-specifier, if present.
1607 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1608 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1609 return true;
1610
1611 if (D->isCompleteDefinition()) {
1612 for (CXXRecordDecl::base_class_iterator I = D->bases_begin(),
1613 E = D->bases_end(); I != E; ++I) {
1614 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(I, TU)))
1615 return true;
1616 }
1617 }
1618
1619 return VisitTagDecl(D);
1620}
1621
1622bool CursorVisitor::VisitAttributes(Decl *D) {
1623 for (AttrVec::const_iterator i = D->attr_begin(), e = D->attr_end();
1624 i != e; ++i)
1625 if (Visit(MakeCXCursor(*i, D, TU)))
1626 return true;
1627
1628 return false;
1629}
1630
1631//===----------------------------------------------------------------------===//
1632// Data-recursive visitor methods.
1633//===----------------------------------------------------------------------===//
1634
1635namespace {
1636#define DEF_JOB(NAME, DATA, KIND)\
1637class NAME : public VisitorJob {\
1638public:\
1639 NAME(DATA *d, CXCursor parent) : VisitorJob(parent, VisitorJob::KIND, d) {} \
1640 static bool classof(const VisitorJob *VJ) { return VJ->getKind() == KIND; }\
1641 DATA *get() const { return static_cast<DATA*>(data[0]); }\
1642};
1643
1644DEF_JOB(StmtVisit, Stmt, StmtVisitKind)
1645DEF_JOB(MemberExprParts, MemberExpr, MemberExprPartsKind)
1646DEF_JOB(DeclRefExprParts, DeclRefExpr, DeclRefExprPartsKind)
1647DEF_JOB(OverloadExprParts, OverloadExpr, OverloadExprPartsKind)
1648DEF_JOB(ExplicitTemplateArgsVisit, ASTTemplateArgumentListInfo,
1649 ExplicitTemplateArgsVisitKind)
1650DEF_JOB(SizeOfPackExprParts, SizeOfPackExpr, SizeOfPackExprPartsKind)
1651DEF_JOB(LambdaExprParts, LambdaExpr, LambdaExprPartsKind)
1652DEF_JOB(PostChildrenVisit, void, PostChildrenVisitKind)
1653#undef DEF_JOB
1654
1655class DeclVisit : public VisitorJob {
1656public:
1657 DeclVisit(Decl *d, CXCursor parent, bool isFirst) :
1658 VisitorJob(parent, VisitorJob::DeclVisitKind,
1659 d, isFirst ? (void*) 1 : (void*) 0) {}
1660 static bool classof(const VisitorJob *VJ) {
1661 return VJ->getKind() == DeclVisitKind;
1662 }
1663 Decl *get() const { return static_cast<Decl*>(data[0]); }
1664 bool isFirst() const { return data[1] ? true : false; }
1665};
1666class TypeLocVisit : public VisitorJob {
1667public:
1668 TypeLocVisit(TypeLoc tl, CXCursor parent) :
1669 VisitorJob(parent, VisitorJob::TypeLocVisitKind,
1670 tl.getType().getAsOpaquePtr(), tl.getOpaqueData()) {}
1671
1672 static bool classof(const VisitorJob *VJ) {
1673 return VJ->getKind() == TypeLocVisitKind;
1674 }
1675
1676 TypeLoc get() const {
1677 QualType T = QualType::getFromOpaquePtr(data[0]);
1678 return TypeLoc(T, data[1]);
1679 }
1680};
1681
1682class LabelRefVisit : public VisitorJob {
1683public:
1684 LabelRefVisit(LabelDecl *LD, SourceLocation labelLoc, CXCursor parent)
1685 : VisitorJob(parent, VisitorJob::LabelRefVisitKind, LD,
1686 labelLoc.getPtrEncoding()) {}
1687
1688 static bool classof(const VisitorJob *VJ) {
1689 return VJ->getKind() == VisitorJob::LabelRefVisitKind;
1690 }
1691 LabelDecl *get() const { return static_cast<LabelDecl*>(data[0]); }
1692 SourceLocation getLoc() const {
1693 return SourceLocation::getFromPtrEncoding(data[1]); }
1694};
1695
1696class NestedNameSpecifierLocVisit : public VisitorJob {
1697public:
1698 NestedNameSpecifierLocVisit(NestedNameSpecifierLoc Qualifier, CXCursor parent)
1699 : VisitorJob(parent, VisitorJob::NestedNameSpecifierLocVisitKind,
1700 Qualifier.getNestedNameSpecifier(),
1701 Qualifier.getOpaqueData()) { }
1702
1703 static bool classof(const VisitorJob *VJ) {
1704 return VJ->getKind() == VisitorJob::NestedNameSpecifierLocVisitKind;
1705 }
1706
1707 NestedNameSpecifierLoc get() const {
1708 return NestedNameSpecifierLoc(static_cast<NestedNameSpecifier*>(data[0]),
1709 data[1]);
1710 }
1711};
1712
1713class DeclarationNameInfoVisit : public VisitorJob {
1714public:
1715 DeclarationNameInfoVisit(Stmt *S, CXCursor parent)
1716 : VisitorJob(parent, VisitorJob::DeclarationNameInfoVisitKind, S) {}
1717 static bool classof(const VisitorJob *VJ) {
1718 return VJ->getKind() == VisitorJob::DeclarationNameInfoVisitKind;
1719 }
1720 DeclarationNameInfo get() const {
1721 Stmt *S = static_cast<Stmt*>(data[0]);
1722 switch (S->getStmtClass()) {
1723 default:
1724 llvm_unreachable("Unhandled Stmt");
1725 case clang::Stmt::MSDependentExistsStmtClass:
1726 return cast<MSDependentExistsStmt>(S)->getNameInfo();
1727 case Stmt::CXXDependentScopeMemberExprClass:
1728 return cast<CXXDependentScopeMemberExpr>(S)->getMemberNameInfo();
1729 case Stmt::DependentScopeDeclRefExprClass:
1730 return cast<DependentScopeDeclRefExpr>(S)->getNameInfo();
1731 }
1732 }
1733};
1734class MemberRefVisit : public VisitorJob {
1735public:
1736 MemberRefVisit(FieldDecl *D, SourceLocation L, CXCursor parent)
1737 : VisitorJob(parent, VisitorJob::MemberRefVisitKind, D,
1738 L.getPtrEncoding()) {}
1739 static bool classof(const VisitorJob *VJ) {
1740 return VJ->getKind() == VisitorJob::MemberRefVisitKind;
1741 }
1742 FieldDecl *get() const {
1743 return static_cast<FieldDecl*>(data[0]);
1744 }
1745 SourceLocation getLoc() const {
1746 return SourceLocation::getFromRawEncoding((unsigned)(uintptr_t) data[1]);
1747 }
1748};
1749class EnqueueVisitor : public StmtVisitor<EnqueueVisitor, void> {
1750 VisitorWorkList &WL;
1751 CXCursor Parent;
1752public:
1753 EnqueueVisitor(VisitorWorkList &wl, CXCursor parent)
1754 : WL(wl), Parent(parent) {}
1755
1756 void VisitAddrLabelExpr(AddrLabelExpr *E);
1757 void VisitBlockExpr(BlockExpr *B);
1758 void VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
1759 void VisitCompoundStmt(CompoundStmt *S);
1760 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { /* Do nothing. */ }
1761 void VisitMSDependentExistsStmt(MSDependentExistsStmt *S);
1762 void VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E);
1763 void VisitCXXNewExpr(CXXNewExpr *E);
1764 void VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
1765 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E);
1766 void VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E);
1767 void VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E);
1768 void VisitCXXTypeidExpr(CXXTypeidExpr *E);
1769 void VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr *E);
1770 void VisitCXXUuidofExpr(CXXUuidofExpr *E);
1771 void VisitCXXCatchStmt(CXXCatchStmt *S);
1772 void VisitDeclRefExpr(DeclRefExpr *D);
1773 void VisitDeclStmt(DeclStmt *S);
1774 void VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E);
1775 void VisitDesignatedInitExpr(DesignatedInitExpr *E);
1776 void VisitExplicitCastExpr(ExplicitCastExpr *E);
1777 void VisitForStmt(ForStmt *FS);
1778 void VisitGotoStmt(GotoStmt *GS);
1779 void VisitIfStmt(IfStmt *If);
1780 void VisitInitListExpr(InitListExpr *IE);
1781 void VisitMemberExpr(MemberExpr *M);
1782 void VisitOffsetOfExpr(OffsetOfExpr *E);
1783 void VisitObjCEncodeExpr(ObjCEncodeExpr *E);
1784 void VisitObjCMessageExpr(ObjCMessageExpr *M);
1785 void VisitOverloadExpr(OverloadExpr *E);
1786 void VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E);
1787 void VisitStmt(Stmt *S);
1788 void VisitSwitchStmt(SwitchStmt *S);
1789 void VisitWhileStmt(WhileStmt *W);
1790 void VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E);
1791 void VisitBinaryTypeTraitExpr(BinaryTypeTraitExpr *E);
1792 void VisitTypeTraitExpr(TypeTraitExpr *E);
1793 void VisitArrayTypeTraitExpr(ArrayTypeTraitExpr *E);
1794 void VisitExpressionTraitExpr(ExpressionTraitExpr *E);
1795 void VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U);
1796 void VisitVAArgExpr(VAArgExpr *E);
1797 void VisitSizeOfPackExpr(SizeOfPackExpr *E);
1798 void VisitPseudoObjectExpr(PseudoObjectExpr *E);
1799 void VisitOpaqueValueExpr(OpaqueValueExpr *E);
1800 void VisitLambdaExpr(LambdaExpr *E);
1801
1802private:
1803 void AddDeclarationNameInfo(Stmt *S);
1804 void AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier);
1805 void AddExplicitTemplateArgs(const ASTTemplateArgumentListInfo *A);
1806 void AddMemberRef(FieldDecl *D, SourceLocation L);
1807 void AddStmt(Stmt *S);
1808 void AddDecl(Decl *D, bool isFirst = true);
1809 void AddTypeLoc(TypeSourceInfo *TI);
1810 void EnqueueChildren(Stmt *S);
1811};
1812} // end anonyous namespace
1813
1814void EnqueueVisitor::AddDeclarationNameInfo(Stmt *S) {
1815 // 'S' should always be non-null, since it comes from the
1816 // statement we are visiting.
1817 WL.push_back(DeclarationNameInfoVisit(S, Parent));
1818}
1819
1820void
1821EnqueueVisitor::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
1822 if (Qualifier)
1823 WL.push_back(NestedNameSpecifierLocVisit(Qualifier, Parent));
1824}
1825
1826void EnqueueVisitor::AddStmt(Stmt *S) {
1827 if (S)
1828 WL.push_back(StmtVisit(S, Parent));
1829}
1830void EnqueueVisitor::AddDecl(Decl *D, bool isFirst) {
1831 if (D)
1832 WL.push_back(DeclVisit(D, Parent, isFirst));
1833}
1834void EnqueueVisitor::
1835 AddExplicitTemplateArgs(const ASTTemplateArgumentListInfo *A) {
1836 if (A)
1837 WL.push_back(ExplicitTemplateArgsVisit(
1838 const_cast<ASTTemplateArgumentListInfo*>(A), Parent));
1839}
1840void EnqueueVisitor::AddMemberRef(FieldDecl *D, SourceLocation L) {
1841 if (D)
1842 WL.push_back(MemberRefVisit(D, L, Parent));
1843}
1844void EnqueueVisitor::AddTypeLoc(TypeSourceInfo *TI) {
1845 if (TI)
1846 WL.push_back(TypeLocVisit(TI->getTypeLoc(), Parent));
1847 }
1848void EnqueueVisitor::EnqueueChildren(Stmt *S) {
1849 unsigned size = WL.size();
1850 for (Stmt::child_range Child = S->children(); Child; ++Child) {
1851 AddStmt(*Child);
1852 }
1853 if (size == WL.size())
1854 return;
1855 // Now reverse the entries we just added. This will match the DFS
1856 // ordering performed by the worklist.
1857 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1858 std::reverse(I, E);
1859}
1860void EnqueueVisitor::VisitAddrLabelExpr(AddrLabelExpr *E) {
1861 WL.push_back(LabelRefVisit(E->getLabel(), E->getLabelLoc(), Parent));
1862}
1863void EnqueueVisitor::VisitBlockExpr(BlockExpr *B) {
1864 AddDecl(B->getBlockDecl());
1865}
1866void EnqueueVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
1867 EnqueueChildren(E);
1868 AddTypeLoc(E->getTypeSourceInfo());
1869}
1870void EnqueueVisitor::VisitCompoundStmt(CompoundStmt *S) {
1871 for (CompoundStmt::reverse_body_iterator I = S->body_rbegin(),
1872 E = S->body_rend(); I != E; ++I) {
1873 AddStmt(*I);
1874 }
1875}
1876void EnqueueVisitor::
1877VisitMSDependentExistsStmt(MSDependentExistsStmt *S) {
1878 AddStmt(S->getSubStmt());
1879 AddDeclarationNameInfo(S);
1880 if (NestedNameSpecifierLoc QualifierLoc = S->getQualifierLoc())
1881 AddNestedNameSpecifierLoc(QualifierLoc);
1882}
1883
1884void EnqueueVisitor::
1885VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E) {
1886 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
1887 AddDeclarationNameInfo(E);
1888 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
1889 AddNestedNameSpecifierLoc(QualifierLoc);
1890 if (!E->isImplicitAccess())
1891 AddStmt(E->getBase());
1892}
1893void EnqueueVisitor::VisitCXXNewExpr(CXXNewExpr *E) {
1894 // Enqueue the initializer , if any.
1895 AddStmt(E->getInitializer());
1896 // Enqueue the array size, if any.
1897 AddStmt(E->getArraySize());
1898 // Enqueue the allocated type.
1899 AddTypeLoc(E->getAllocatedTypeSourceInfo());
1900 // Enqueue the placement arguments.
1901 for (unsigned I = E->getNumPlacementArgs(); I > 0; --I)
1902 AddStmt(E->getPlacementArg(I-1));
1903}
1904void EnqueueVisitor::VisitCXXOperatorCallExpr(CXXOperatorCallExpr *CE) {
1905 for (unsigned I = CE->getNumArgs(); I > 1 /* Yes, this is 1 */; --I)
1906 AddStmt(CE->getArg(I-1));
1907 AddStmt(CE->getCallee());
1908 AddStmt(CE->getArg(0));
1909}
1910void EnqueueVisitor::VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E) {
1911 // Visit the name of the type being destroyed.
1912 AddTypeLoc(E->getDestroyedTypeInfo());
1913 // Visit the scope type that looks disturbingly like the nested-name-specifier
1914 // but isn't.
1915 AddTypeLoc(E->getScopeTypeInfo());
1916 // Visit the nested-name-specifier.
1917 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
1918 AddNestedNameSpecifierLoc(QualifierLoc);
1919 // Visit base expression.
1920 AddStmt(E->getBase());
1921}
1922void EnqueueVisitor::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
1923 AddTypeLoc(E->getTypeSourceInfo());
1924}
1925void EnqueueVisitor::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E) {
1926 EnqueueChildren(E);
1927 AddTypeLoc(E->getTypeSourceInfo());
1928}
1929void EnqueueVisitor::VisitCXXTypeidExpr(CXXTypeidExpr *E) {
1930 EnqueueChildren(E);
1931 if (E->isTypeOperand())
1932 AddTypeLoc(E->getTypeOperandSourceInfo());
1933}
1934
1935void EnqueueVisitor::VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr
1936 *E) {
1937 EnqueueChildren(E);
1938 AddTypeLoc(E->getTypeSourceInfo());
1939}
1940void EnqueueVisitor::VisitCXXUuidofExpr(CXXUuidofExpr *E) {
1941 EnqueueChildren(E);
1942 if (E->isTypeOperand())
1943 AddTypeLoc(E->getTypeOperandSourceInfo());
1944}
1945
1946void EnqueueVisitor::VisitCXXCatchStmt(CXXCatchStmt *S) {
1947 EnqueueChildren(S);
1948 AddDecl(S->getExceptionDecl());
1949}
1950
1951void EnqueueVisitor::VisitDeclRefExpr(DeclRefExpr *DR) {
1952 if (DR->hasExplicitTemplateArgs()) {
1953 AddExplicitTemplateArgs(&DR->getExplicitTemplateArgs());
1954 }
1955 WL.push_back(DeclRefExprParts(DR, Parent));
1956}
1957void EnqueueVisitor::VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E) {
1958 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
1959 AddDeclarationNameInfo(E);
1960 AddNestedNameSpecifierLoc(E->getQualifierLoc());
1961}
1962void EnqueueVisitor::VisitDeclStmt(DeclStmt *S) {
1963 unsigned size = WL.size();
1964 bool isFirst = true;
1965 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
1966 D != DEnd; ++D) {
1967 AddDecl(*D, isFirst);
1968 isFirst = false;
1969 }
1970 if (size == WL.size())
1971 return;
1972 // Now reverse the entries we just added. This will match the DFS
1973 // ordering performed by the worklist.
1974 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1975 std::reverse(I, E);
1976}
1977void EnqueueVisitor::VisitDesignatedInitExpr(DesignatedInitExpr *E) {
1978 AddStmt(E->getInit());
1979 typedef DesignatedInitExpr::Designator Designator;
1980 for (DesignatedInitExpr::reverse_designators_iterator
1981 D = E->designators_rbegin(), DEnd = E->designators_rend();
1982 D != DEnd; ++D) {
1983 if (D->isFieldDesignator()) {
1984 if (FieldDecl *Field = D->getField())
1985 AddMemberRef(Field, D->getFieldLoc());
1986 continue;
1987 }
1988 if (D->isArrayDesignator()) {
1989 AddStmt(E->getArrayIndex(*D));
1990 continue;
1991 }
1992 assert(D->isArrayRangeDesignator() && "Unknown designator kind");
1993 AddStmt(E->getArrayRangeEnd(*D));
1994 AddStmt(E->getArrayRangeStart(*D));
1995 }
1996}
1997void EnqueueVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
1998 EnqueueChildren(E);
1999 AddTypeLoc(E->getTypeInfoAsWritten());
2000}
2001void EnqueueVisitor::VisitForStmt(ForStmt *FS) {
2002 AddStmt(FS->getBody());
2003 AddStmt(FS->getInc());
2004 AddStmt(FS->getCond());
2005 AddDecl(FS->getConditionVariable());
2006 AddStmt(FS->getInit());
2007}
2008void EnqueueVisitor::VisitGotoStmt(GotoStmt *GS) {
2009 WL.push_back(LabelRefVisit(GS->getLabel(), GS->getLabelLoc(), Parent));
2010}
2011void EnqueueVisitor::VisitIfStmt(IfStmt *If) {
2012 AddStmt(If->getElse());
2013 AddStmt(If->getThen());
2014 AddStmt(If->getCond());
2015 AddDecl(If->getConditionVariable());
2016}
2017void EnqueueVisitor::VisitInitListExpr(InitListExpr *IE) {
2018 // We care about the syntactic form of the initializer list, only.
2019 if (InitListExpr *Syntactic = IE->getSyntacticForm())
2020 IE = Syntactic;
2021 EnqueueChildren(IE);
2022}
2023void EnqueueVisitor::VisitMemberExpr(MemberExpr *M) {
2024 WL.push_back(MemberExprParts(M, Parent));
2025
2026 // If the base of the member access expression is an implicit 'this', don't
2027 // visit it.
2028 // FIXME: If we ever want to show these implicit accesses, this will be
2029 // unfortunate. However, clang_getCursor() relies on this behavior.
2030 if (!M->isImplicitAccess())
2031 AddStmt(M->getBase());
2032}
2033void EnqueueVisitor::VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
2034 AddTypeLoc(E->getEncodedTypeSourceInfo());
2035}
2036void EnqueueVisitor::VisitObjCMessageExpr(ObjCMessageExpr *M) {
2037 EnqueueChildren(M);
2038 AddTypeLoc(M->getClassReceiverTypeInfo());
2039}
2040void EnqueueVisitor::VisitOffsetOfExpr(OffsetOfExpr *E) {
2041 // Visit the components of the offsetof expression.
2042 for (unsigned N = E->getNumComponents(), I = N; I > 0; --I) {
2043 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
2044 const OffsetOfNode &Node = E->getComponent(I-1);
2045 switch (Node.getKind()) {
2046 case OffsetOfNode::Array:
2047 AddStmt(E->getIndexExpr(Node.getArrayExprIndex()));
2048 break;
2049 case OffsetOfNode::Field:
2050 AddMemberRef(Node.getField(), Node.getSourceRange().getEnd());
2051 break;
2052 case OffsetOfNode::Identifier:
2053 case OffsetOfNode::Base:
2054 continue;
2055 }
2056 }
2057 // Visit the type into which we're computing the offset.
2058 AddTypeLoc(E->getTypeSourceInfo());
2059}
2060void EnqueueVisitor::VisitOverloadExpr(OverloadExpr *E) {
2061 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
2062 WL.push_back(OverloadExprParts(E, Parent));
2063}
2064void EnqueueVisitor::VisitUnaryExprOrTypeTraitExpr(
2065 UnaryExprOrTypeTraitExpr *E) {
2066 EnqueueChildren(E);
2067 if (E->isArgumentType())
2068 AddTypeLoc(E->getArgumentTypeInfo());
2069}
2070void EnqueueVisitor::VisitStmt(Stmt *S) {
2071 EnqueueChildren(S);
2072}
2073void EnqueueVisitor::VisitSwitchStmt(SwitchStmt *S) {
2074 AddStmt(S->getBody());
2075 AddStmt(S->getCond());
2076 AddDecl(S->getConditionVariable());
2077}
2078
2079void EnqueueVisitor::VisitWhileStmt(WhileStmt *W) {
2080 AddStmt(W->getBody());
2081 AddStmt(W->getCond());
2082 AddDecl(W->getConditionVariable());
2083}
2084
2085void EnqueueVisitor::VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E) {
2086 AddTypeLoc(E->getQueriedTypeSourceInfo());
2087}
2088
2089void EnqueueVisitor::VisitBinaryTypeTraitExpr(BinaryTypeTraitExpr *E) {
2090 AddTypeLoc(E->getRhsTypeSourceInfo());
2091 AddTypeLoc(E->getLhsTypeSourceInfo());
2092}
2093
2094void EnqueueVisitor::VisitTypeTraitExpr(TypeTraitExpr *E) {
2095 for (unsigned I = E->getNumArgs(); I > 0; --I)
2096 AddTypeLoc(E->getArg(I-1));
2097}
2098
2099void EnqueueVisitor::VisitArrayTypeTraitExpr(ArrayTypeTraitExpr *E) {
2100 AddTypeLoc(E->getQueriedTypeSourceInfo());
2101}
2102
2103void EnqueueVisitor::VisitExpressionTraitExpr(ExpressionTraitExpr *E) {
2104 EnqueueChildren(E);
2105}
2106
2107void EnqueueVisitor::VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U) {
2108 VisitOverloadExpr(U);
2109 if (!U->isImplicitAccess())
2110 AddStmt(U->getBase());
2111}
2112void EnqueueVisitor::VisitVAArgExpr(VAArgExpr *E) {
2113 AddStmt(E->getSubExpr());
2114 AddTypeLoc(E->getWrittenTypeInfo());
2115}
2116void EnqueueVisitor::VisitSizeOfPackExpr(SizeOfPackExpr *E) {
2117 WL.push_back(SizeOfPackExprParts(E, Parent));
2118}
2119void EnqueueVisitor::VisitOpaqueValueExpr(OpaqueValueExpr *E) {
2120 // If the opaque value has a source expression, just transparently
2121 // visit that. This is useful for (e.g.) pseudo-object expressions.
2122 if (Expr *SourceExpr = E->getSourceExpr())
2123 return Visit(SourceExpr);
2124}
2125void EnqueueVisitor::VisitLambdaExpr(LambdaExpr *E) {
2126 AddStmt(E->getBody());
2127 WL.push_back(LambdaExprParts(E, Parent));
2128}
2129void EnqueueVisitor::VisitPseudoObjectExpr(PseudoObjectExpr *E) {
2130 // Treat the expression like its syntactic form.
2131 Visit(E->getSyntacticForm());
2132}
2133
2134void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, Stmt *S) {
2135 EnqueueVisitor(WL, MakeCXCursor(S, StmtParent, TU,RegionOfInterest)).Visit(S);
2136}
2137
2138bool CursorVisitor::IsInRegionOfInterest(CXCursor C) {
2139 if (RegionOfInterest.isValid()) {
2140 SourceRange Range = getRawCursorExtent(C);
2141 if (Range.isInvalid() || CompareRegionOfInterest(Range))
2142 return false;
2143 }
2144 return true;
2145}
2146
2147bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) {
2148 while (!WL.empty()) {
2149 // Dequeue the worklist item.
2150 VisitorJob LI = WL.back();
2151 WL.pop_back();
2152
2153 // Set the Parent field, then back to its old value once we're done.
2154 SetParentRAII SetParent(Parent, StmtParent, LI.getParent());
2155
2156 switch (LI.getKind()) {
2157 case VisitorJob::DeclVisitKind: {
2158 Decl *D = cast<DeclVisit>(&LI)->get();
2159 if (!D)
2160 continue;
2161
2162 // For now, perform default visitation for Decls.
2163 if (Visit(MakeCXCursor(D, TU, RegionOfInterest,
2164 cast<DeclVisit>(&LI)->isFirst())))
2165 return true;
2166
2167 continue;
2168 }
2169 case VisitorJob::ExplicitTemplateArgsVisitKind: {
2170 const ASTTemplateArgumentListInfo *ArgList =
2171 cast<ExplicitTemplateArgsVisit>(&LI)->get();
2172 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
2173 *ArgEnd = Arg + ArgList->NumTemplateArgs;
2174 Arg != ArgEnd; ++Arg) {
2175 if (VisitTemplateArgumentLoc(*Arg))
2176 return true;
2177 }
2178 continue;
2179 }
2180 case VisitorJob::TypeLocVisitKind: {
2181 // Perform default visitation for TypeLocs.
2182 if (Visit(cast<TypeLocVisit>(&LI)->get()))
2183 return true;
2184 continue;
2185 }
2186 case VisitorJob::LabelRefVisitKind: {
2187 LabelDecl *LS = cast<LabelRefVisit>(&LI)->get();
2188 if (LabelStmt *stmt = LS->getStmt()) {
2189 if (Visit(MakeCursorLabelRef(stmt, cast<LabelRefVisit>(&LI)->getLoc(),
2190 TU))) {
2191 return true;
2192 }
2193 }
2194 continue;
2195 }
2196
2197 case VisitorJob::NestedNameSpecifierLocVisitKind: {
2198 NestedNameSpecifierLocVisit *V = cast<NestedNameSpecifierLocVisit>(&LI);
2199 if (VisitNestedNameSpecifierLoc(V->get()))
2200 return true;
2201 continue;
2202 }
2203
2204 case VisitorJob::DeclarationNameInfoVisitKind: {
2205 if (VisitDeclarationNameInfo(cast<DeclarationNameInfoVisit>(&LI)
2206 ->get()))
2207 return true;
2208 continue;
2209 }
2210 case VisitorJob::MemberRefVisitKind: {
2211 MemberRefVisit *V = cast<MemberRefVisit>(&LI);
2212 if (Visit(MakeCursorMemberRef(V->get(), V->getLoc(), TU)))
2213 return true;
2214 continue;
2215 }
2216 case VisitorJob::StmtVisitKind: {
2217 Stmt *S = cast<StmtVisit>(&LI)->get();
2218 if (!S)
2219 continue;
2220
2221 // Update the current cursor.
2222 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU, RegionOfInterest);
2223 if (!IsInRegionOfInterest(Cursor))
2224 continue;
2225 switch (Visitor(Cursor, Parent, ClientData)) {
2226 case CXChildVisit_Break: return true;
2227 case CXChildVisit_Continue: break;
2228 case CXChildVisit_Recurse:
2229 if (PostChildrenVisitor)
2230 WL.push_back(PostChildrenVisit(0, Cursor));
2231 EnqueueWorkList(WL, S);
2232 break;
2233 }
2234 continue;
2235 }
2236 case VisitorJob::MemberExprPartsKind: {
2237 // Handle the other pieces in the MemberExpr besides the base.
2238 MemberExpr *M = cast<MemberExprParts>(&LI)->get();
2239
2240 // Visit the nested-name-specifier
2241 if (NestedNameSpecifierLoc QualifierLoc = M->getQualifierLoc())
2242 if (VisitNestedNameSpecifierLoc(QualifierLoc))
2243 return true;
2244
2245 // Visit the declaration name.
2246 if (VisitDeclarationNameInfo(M->getMemberNameInfo()))
2247 return true;
2248
2249 // Visit the explicitly-specified template arguments, if any.
2250 if (M->hasExplicitTemplateArgs()) {
2251 for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(),
2252 *ArgEnd = Arg + M->getNumTemplateArgs();
2253 Arg != ArgEnd; ++Arg) {
2254 if (VisitTemplateArgumentLoc(*Arg))
2255 return true;
2256 }
2257 }
2258 continue;
2259 }
2260 case VisitorJob::DeclRefExprPartsKind: {
2261 DeclRefExpr *DR = cast<DeclRefExprParts>(&LI)->get();
2262 // Visit nested-name-specifier, if present.
2263 if (NestedNameSpecifierLoc QualifierLoc = DR->getQualifierLoc())
2264 if (VisitNestedNameSpecifierLoc(QualifierLoc))
2265 return true;
2266 // Visit declaration name.
2267 if (VisitDeclarationNameInfo(DR->getNameInfo()))
2268 return true;
2269 continue;
2270 }
2271 case VisitorJob::OverloadExprPartsKind: {
2272 OverloadExpr *O = cast<OverloadExprParts>(&LI)->get();
2273 // Visit the nested-name-specifier.
2274 if (NestedNameSpecifierLoc QualifierLoc = O->getQualifierLoc())
2275 if (VisitNestedNameSpecifierLoc(QualifierLoc))
2276 return true;
2277 // Visit the declaration name.
2278 if (VisitDeclarationNameInfo(O->getNameInfo()))
2279 return true;
2280 // Visit the overloaded declaration reference.
2281 if (Visit(MakeCursorOverloadedDeclRef(O, TU)))
2282 return true;
2283 continue;
2284 }
2285 case VisitorJob::SizeOfPackExprPartsKind: {
2286 SizeOfPackExpr *E = cast<SizeOfPackExprParts>(&LI)->get();
2287 NamedDecl *Pack = E->getPack();
2288 if (isa<TemplateTypeParmDecl>(Pack)) {
2289 if (Visit(MakeCursorTypeRef(cast<TemplateTypeParmDecl>(Pack),
2290 E->getPackLoc(), TU)))
2291 return true;
2292
2293 continue;
2294 }
2295
2296 if (isa<TemplateTemplateParmDecl>(Pack)) {
2297 if (Visit(MakeCursorTemplateRef(cast<TemplateTemplateParmDecl>(Pack),
2298 E->getPackLoc(), TU)))
2299 return true;
2300
2301 continue;
2302 }
2303
2304 // Non-type template parameter packs and function parameter packs are
2305 // treated like DeclRefExpr cursors.
2306 continue;
2307 }
2308
2309 case VisitorJob::LambdaExprPartsKind: {
2310 // Visit captures.
2311 LambdaExpr *E = cast<LambdaExprParts>(&LI)->get();
2312 for (LambdaExpr::capture_iterator C = E->explicit_capture_begin(),
2313 CEnd = E->explicit_capture_end();
2314 C != CEnd; ++C) {
2315 if (C->capturesThis())
2316 continue;
2317
2318 if (Visit(MakeCursorVariableRef(C->getCapturedVar(),
2319 C->getLocation(),
2320 TU)))
2321 return true;
2322 }
2323
2324 // Visit parameters and return type, if present.
2325 if (E->hasExplicitParameters() || E->hasExplicitResultType()) {
2326 TypeLoc TL = E->getCallOperator()->getTypeSourceInfo()->getTypeLoc();
2327 if (E->hasExplicitParameters() && E->hasExplicitResultType()) {
2328 // Visit the whole type.
2329 if (Visit(TL))
2330 return true;
2331 } else if (isa<FunctionProtoTypeLoc>(TL)) {
2332 FunctionProtoTypeLoc Proto = cast<FunctionProtoTypeLoc>(TL);
2333 if (E->hasExplicitParameters()) {
2334 // Visit parameters.
2335 for (unsigned I = 0, N = Proto.getNumArgs(); I != N; ++I)
2336 if (Visit(MakeCXCursor(Proto.getArg(I), TU)))
2337 return true;
2338 } else {
2339 // Visit result type.
2340 if (Visit(Proto.getResultLoc()))
2341 return true;
2342 }
2343 }
2344 }
2345 break;
2346 }
2347
2348 case VisitorJob::PostChildrenVisitKind:
2349 if (PostChildrenVisitor(Parent, ClientData))
2350 return true;
2351 break;
2352 }
2353 }
2354 return false;
2355}
2356
2357bool CursorVisitor::Visit(Stmt *S) {
2358 VisitorWorkList *WL = 0;
2359 if (!WorkListFreeList.empty()) {
2360 WL = WorkListFreeList.back();
2361 WL->clear();
2362 WorkListFreeList.pop_back();
2363 }
2364 else {
2365 WL = new VisitorWorkList();
2366 WorkListCache.push_back(WL);
2367 }
2368 EnqueueWorkList(*WL, S);
2369 bool result = RunVisitorWorkList(*WL);
2370 WorkListFreeList.push_back(WL);
2371 return result;
2372}
2373
2374namespace {
2375typedef llvm::SmallVector<SourceRange, 4> RefNamePieces;
2376RefNamePieces buildPieces(unsigned NameFlags, bool IsMemberRefExpr,
2377 const DeclarationNameInfo &NI,
2378 const SourceRange &QLoc,
2379 const ASTTemplateArgumentListInfo *TemplateArgs = 0){
2380 const bool WantQualifier = NameFlags & CXNameRange_WantQualifier;
2381 const bool WantTemplateArgs = NameFlags & CXNameRange_WantTemplateArgs;
2382 const bool WantSinglePiece = NameFlags & CXNameRange_WantSinglePiece;
2383
2384 const DeclarationName::NameKind Kind = NI.getName().getNameKind();
2385
2386 RefNamePieces Pieces;
2387
2388 if (WantQualifier && QLoc.isValid())
2389 Pieces.push_back(QLoc);
2390
2391 if (Kind != DeclarationName::CXXOperatorName || IsMemberRefExpr)
2392 Pieces.push_back(NI.getLoc());
2393
2394 if (WantTemplateArgs && TemplateArgs)
2395 Pieces.push_back(SourceRange(TemplateArgs->LAngleLoc,
2396 TemplateArgs->RAngleLoc));
2397
2398 if (Kind == DeclarationName::CXXOperatorName) {
2399 Pieces.push_back(SourceLocation::getFromRawEncoding(
2400 NI.getInfo().CXXOperatorName.BeginOpNameLoc));
2401 Pieces.push_back(SourceLocation::getFromRawEncoding(
2402 NI.getInfo().CXXOperatorName.EndOpNameLoc));
2403 }
2404
2405 if (WantSinglePiece) {
2406 SourceRange R(Pieces.front().getBegin(), Pieces.back().getEnd());
2407 Pieces.clear();
2408 Pieces.push_back(R);
2409 }
2410
2411 return Pieces;
2412}
2413}
2414
2415//===----------------------------------------------------------------------===//
2416// Misc. API hooks.
2417//===----------------------------------------------------------------------===//
2418
2419static llvm::sys::Mutex EnableMultithreadingMutex;
2420static bool EnabledMultithreading;
2421
2422static void fatal_error_handler(void *user_data, const std::string& reason) {
2423 // Write the result out to stderr avoiding errs() because raw_ostreams can
2424 // call report_fatal_error.
2425 fprintf(stderr, "LIBCLANG FATAL ERROR: %s\n", reason.c_str());
2426 ::abort();
2427}
2428
2429extern "C" {
2430CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
2431 int displayDiagnostics) {
2432 // Disable pretty stack trace functionality, which will otherwise be a very
2433 // poor citizen of the world and set up all sorts of signal handlers.
2434 llvm::DisablePrettyStackTrace = true;
2435
2436 // We use crash recovery to make some of our APIs more reliable, implicitly
2437 // enable it.
2438 llvm::CrashRecoveryContext::Enable();
2439
2440 // Enable support for multithreading in LLVM.
2441 {
2442 llvm::sys::ScopedLock L(EnableMultithreadingMutex);
2443 if (!EnabledMultithreading) {
2444 llvm::install_fatal_error_handler(fatal_error_handler, 0);
2445 llvm::llvm_start_multithreaded();
2446 EnabledMultithreading = true;
2447 }
2448 }
2449
2450 CIndexer *CIdxr = new CIndexer();
2451 if (excludeDeclarationsFromPCH)
2452 CIdxr->setOnlyLocalDecls();
2453 if (displayDiagnostics)
2454 CIdxr->setDisplayDiagnostics();
2455
2456 if (getenv("LIBCLANG_BGPRIO_INDEX"))
2457 CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() |
2458 CXGlobalOpt_ThreadBackgroundPriorityForIndexing);
2459 if (getenv("LIBCLANG_BGPRIO_EDIT"))
2460 CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() |
2461 CXGlobalOpt_ThreadBackgroundPriorityForEditing);
2462
2463 return CIdxr;
2464}
2465
2466void clang_disposeIndex(CXIndex CIdx) {
2467 if (CIdx)
2468 delete static_cast<CIndexer *>(CIdx);
2469}
2470
2471void clang_CXIndex_setGlobalOptions(CXIndex CIdx, unsigned options) {
2472 if (CIdx)
2473 static_cast<CIndexer *>(CIdx)->setCXGlobalOptFlags(options);
2474}
2475
2476unsigned clang_CXIndex_getGlobalOptions(CXIndex CIdx) {
2477 if (CIdx)
2478 return static_cast<CIndexer *>(CIdx)->getCXGlobalOptFlags();
2479 return 0;
2480}
2481
2482void clang_toggleCrashRecovery(unsigned isEnabled) {
2483 if (isEnabled)
2484 llvm::CrashRecoveryContext::Enable();
2485 else
2486 llvm::CrashRecoveryContext::Disable();
2487}
2488
2489CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
2490 const char *ast_filename) {
2491 if (!CIdx)
2492 return 0;
2493
2494 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
2495 FileSystemOptions FileSystemOpts;
2496
2497 IntrusiveRefCntPtr<DiagnosticsEngine> Diags;
2498 ASTUnit *TU = ASTUnit::LoadFromASTFile(ast_filename, Diags, FileSystemOpts,
2499 CXXIdx->getOnlyLocalDecls(),
2500 0, 0,
2501 /*CaptureDiagnostics=*/true,
2502 /*AllowPCHWithCompilerErrors=*/true,
2503 /*UserFilesAreVolatile=*/true);
2504 return MakeCXTranslationUnit(CXXIdx, TU);
2505}
2506
2507unsigned clang_defaultEditingTranslationUnitOptions() {
2508 return CXTranslationUnit_PrecompiledPreamble |
2509 CXTranslationUnit_CacheCompletionResults;
2510}
2511
2512CXTranslationUnit
2513clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
2514 const char *source_filename,
2515 int num_command_line_args,
2516 const char * const *command_line_args,
2517 unsigned num_unsaved_files,
2518 struct CXUnsavedFile *unsaved_files) {
2519 unsigned Options = CXTranslationUnit_DetailedPreprocessingRecord;
2520 return clang_parseTranslationUnit(CIdx, source_filename,
2521 command_line_args, num_command_line_args,
2522 unsaved_files, num_unsaved_files,
2523 Options);
2524}
2525
2526struct ParseTranslationUnitInfo {
2527 CXIndex CIdx;
2528 const char *source_filename;
2529 const char *const *command_line_args;
2530 int num_command_line_args;
2531 struct CXUnsavedFile *unsaved_files;
2532 unsigned num_unsaved_files;
2533 unsigned options;
2534 CXTranslationUnit result;
2535};
2536static void clang_parseTranslationUnit_Impl(void *UserData) {
2537 ParseTranslationUnitInfo *PTUI =
2538 static_cast<ParseTranslationUnitInfo*>(UserData);
2539 CXIndex CIdx = PTUI->CIdx;
2540 const char *source_filename = PTUI->source_filename;
2541 const char * const *command_line_args = PTUI->command_line_args;
2542 int num_command_line_args = PTUI->num_command_line_args;
2543 struct CXUnsavedFile *unsaved_files = PTUI->unsaved_files;
2544 unsigned num_unsaved_files = PTUI->num_unsaved_files;
2545 unsigned options = PTUI->options;
2546 PTUI->result = 0;
2547
2548 if (!CIdx)
2549 return;
2550
2551 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
2552
2553 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
2554 setThreadBackgroundPriority();
2555
2556 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
2557 // FIXME: Add a flag for modules.
2558 TranslationUnitKind TUKind
2559 = (options & CXTranslationUnit_Incomplete)? TU_Prefix : TU_Complete;
2560 bool CacheCodeCompetionResults
2561 = options & CXTranslationUnit_CacheCompletionResults;
2562 bool IncludeBriefCommentsInCodeCompletion
2563 = options & CXTranslationUnit_IncludeBriefCommentsInCodeCompletion;
2564 bool SkipFunctionBodies = options & CXTranslationUnit_SkipFunctionBodies;
2565 bool ForSerialization = options & CXTranslationUnit_ForSerialization;
2566
2567 // Configure the diagnostics.
2568 IntrusiveRefCntPtr<DiagnosticsEngine>
2569 Diags(CompilerInstance::createDiagnostics(new DiagnosticOptions,
2570 num_command_line_args,
2571 command_line_args));
2572
2573 // Recover resources if we crash before exiting this function.
2574 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
2575 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
2576 DiagCleanup(Diags.getPtr());
2577
2578 OwningPtr<std::vector<ASTUnit::RemappedFile> >
2579 RemappedFiles(new std::vector<ASTUnit::RemappedFile>());
2580
2581 // Recover resources if we crash before exiting this function.
2582 llvm::CrashRecoveryContextCleanupRegistrar<
2583 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
2584
2585 for (unsigned I = 0; I != num_unsaved_files; ++I) {
2586 StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
2587 const llvm::MemoryBuffer *Buffer
2588 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
2589 RemappedFiles->push_back(std::make_pair(unsaved_files[I].Filename,
2590 Buffer));
2591 }
2592
2593 OwningPtr<std::vector<const char *> >
2594 Args(new std::vector<const char*>());
2595
2596 // Recover resources if we crash before exiting this method.
2597 llvm::CrashRecoveryContextCleanupRegistrar<std::vector<const char*> >
2598 ArgsCleanup(Args.get());
2599
2600 // Since the Clang C library is primarily used by batch tools dealing with
2601 // (often very broken) source code, where spell-checking can have a
2602 // significant negative impact on performance (particularly when
2603 // precompiled headers are involved), we disable it by default.
2604 // Only do this if we haven't found a spell-checking-related argument.
2605 bool FoundSpellCheckingArgument = false;
2606 for (int I = 0; I != num_command_line_args; ++I) {
2607 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
2608 strcmp(command_line_args[I], "-fspell-checking") == 0) {
2609 FoundSpellCheckingArgument = true;
2610 break;
2611 }
2612 }
2613 if (!FoundSpellCheckingArgument)
2614 Args->push_back("-fno-spell-checking");
2615
2616 Args->insert(Args->end(), command_line_args,
2617 command_line_args + num_command_line_args);
2618
2619 // The 'source_filename' argument is optional. If the caller does not
2620 // specify it then it is assumed that the source file is specified
2621 // in the actual argument list.
2622 // Put the source file after command_line_args otherwise if '-x' flag is
2623 // present it will be unused.
2624 if (source_filename)
2625 Args->push_back(source_filename);
2626
2627 // Do we need the detailed preprocessing record?
2628 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
2629 Args->push_back("-Xclang");
2630 Args->push_back("-detailed-preprocessing-record");
2631 }
2632
2633 unsigned NumErrors = Diags->getClient()->getNumErrors();
2634 OwningPtr<ASTUnit> ErrUnit;
2635 OwningPtr<ASTUnit> Unit(
2636 ASTUnit::LoadFromCommandLine(Args->size() ? &(*Args)[0] : 0
2637 /* vector::data() not portable */,
2638 Args->size() ? (&(*Args)[0] + Args->size()) :0,
2639 Diags,
2640 CXXIdx->getClangResourcesPath(),
2641 CXXIdx->getOnlyLocalDecls(),
2642 /*CaptureDiagnostics=*/true,
2643 RemappedFiles->size() ? &(*RemappedFiles)[0]:0,
2644 RemappedFiles->size(),
2645 /*RemappedFilesKeepOriginalName=*/true,
2646 PrecompilePreamble,
2647 TUKind,
2648 CacheCodeCompetionResults,
2649 IncludeBriefCommentsInCodeCompletion,
2650 /*AllowPCHWithCompilerErrors=*/true,
2651 SkipFunctionBodies,
2652 /*UserFilesAreVolatile=*/true,
2653 ForSerialization,
2654 &ErrUnit));
2655
2656 if (NumErrors != Diags->getClient()->getNumErrors()) {
2657 // Make sure to check that 'Unit' is non-NULL.
2658 if (CXXIdx->getDisplayDiagnostics())
2659 printDiagsToStderr(Unit ? Unit.get() : ErrUnit.get());
2660 }
2661
2662 PTUI->result = MakeCXTranslationUnit(CXXIdx, Unit.take());
2663}
2664CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx,
2665 const char *source_filename,
2666 const char * const *command_line_args,
2667 int num_command_line_args,
2668 struct CXUnsavedFile *unsaved_files,
2669 unsigned num_unsaved_files,
2670 unsigned options) {
2671 ParseTranslationUnitInfo PTUI = { CIdx, source_filename, command_line_args,
2672 num_command_line_args, unsaved_files,
2673 num_unsaved_files, options, 0 };
2674 llvm::CrashRecoveryContext CRC;
2675
2676 if (!RunSafely(CRC, clang_parseTranslationUnit_Impl, &PTUI)) {
2677 fprintf(stderr, "libclang: crash detected during parsing: {\n");
2678 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
2679 fprintf(stderr, " 'command_line_args' : [");
2680 for (int i = 0; i != num_command_line_args; ++i) {
2681 if (i)
2682 fprintf(stderr, ", ");
2683 fprintf(stderr, "'%s'", command_line_args[i]);
2684 }
2685 fprintf(stderr, "],\n");
2686 fprintf(stderr, " 'unsaved_files' : [");
2687 for (unsigned i = 0; i != num_unsaved_files; ++i) {
2688 if (i)
2689 fprintf(stderr, ", ");
2690 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
2691 unsaved_files[i].Length);
2692 }
2693 fprintf(stderr, "],\n");
2694 fprintf(stderr, " 'options' : %d,\n", options);
2695 fprintf(stderr, "}\n");
2696
2697 return 0;
2698 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
2699 PrintLibclangResourceUsage(PTUI.result);
2700 }
2701
2702 return PTUI.result;
2703}
2704
2705unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
2706 return CXSaveTranslationUnit_None;
2707}
2708
2709namespace {
2710
2711struct SaveTranslationUnitInfo {
2712 CXTranslationUnit TU;
2713 const char *FileName;
2714 unsigned options;
2715 CXSaveError result;
2716};
2717
2718}
2719
2720static void clang_saveTranslationUnit_Impl(void *UserData) {
2721 SaveTranslationUnitInfo *STUI =
2722 static_cast<SaveTranslationUnitInfo*>(UserData);
2723
2724 CIndexer *CXXIdx = (CIndexer*)STUI->TU->CIdx;
2725 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
2726 setThreadBackgroundPriority();
2727
2728 bool hadError = static_cast<ASTUnit *>(STUI->TU->TUData)->Save(STUI->FileName);
2729 STUI->result = hadError ? CXSaveError_Unknown : CXSaveError_None;
2730}
2731
2732int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
2733 unsigned options) {
2734 if (!TU)
2735 return CXSaveError_InvalidTU;
2736
2737 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
2738 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
2739 if (!CXXUnit->hasSema())
2740 return CXSaveError_InvalidTU;
2741
2742 SaveTranslationUnitInfo STUI = { TU, FileName, options, CXSaveError_None };
2743
2744 if (!CXXUnit->getDiagnostics().hasUnrecoverableErrorOccurred() ||
2745 getenv("LIBCLANG_NOTHREADS")) {
2746 clang_saveTranslationUnit_Impl(&STUI);
2747
2748 if (getenv("LIBCLANG_RESOURCE_USAGE"))
2749 PrintLibclangResourceUsage(TU);
2750
2751 return STUI.result;
2752 }
2753
2754 // We have an AST that has invalid nodes due to compiler errors.
2755 // Use a crash recovery thread for protection.
2756
2757 llvm::CrashRecoveryContext CRC;
2758
2759 if (!RunSafely(CRC, clang_saveTranslationUnit_Impl, &STUI)) {
2760 fprintf(stderr, "libclang: crash detected during AST saving: {\n");
2761 fprintf(stderr, " 'filename' : '%s'\n", FileName);
2762 fprintf(stderr, " 'options' : %d,\n", options);
2763 fprintf(stderr, "}\n");
2764
2765 return CXSaveError_Unknown;
2766
2767 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
2768 PrintLibclangResourceUsage(TU);
2769 }
2770
2771 return STUI.result;
2772}
2773
2774void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
2775 if (CTUnit) {
2776 // If the translation unit has been marked as unsafe to free, just discard
2777 // it.
2778 if (static_cast<ASTUnit *>(CTUnit->TUData)->isUnsafeToFree())
2779 return;
2780
2781 delete static_cast<ASTUnit *>(CTUnit->TUData);
2782 disposeCXStringPool(CTUnit->StringPool);
2783 delete static_cast<CXDiagnosticSetImpl *>(CTUnit->Diagnostics);
2784 disposeOverridenCXCursorsPool(CTUnit->OverridenCursorsPool);
Fariborz Jahanian88b95212012-12-18 23:02:59 +00002785 delete static_cast<SimpleFormatContext*>(CTUnit->FormatContext);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002786 delete CTUnit;
2787 }
2788}
2789
2790unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
2791 return CXReparse_None;
2792}
2793
2794struct ReparseTranslationUnitInfo {
2795 CXTranslationUnit TU;
2796 unsigned num_unsaved_files;
2797 struct CXUnsavedFile *unsaved_files;
2798 unsigned options;
2799 int result;
2800};
2801
2802static void clang_reparseTranslationUnit_Impl(void *UserData) {
2803 ReparseTranslationUnitInfo *RTUI =
2804 static_cast<ReparseTranslationUnitInfo*>(UserData);
2805 CXTranslationUnit TU = RTUI->TU;
2806
2807 // Reset the associated diagnostics.
2808 delete static_cast<CXDiagnosticSetImpl*>(TU->Diagnostics);
2809 TU->Diagnostics = 0;
2810
2811 unsigned num_unsaved_files = RTUI->num_unsaved_files;
2812 struct CXUnsavedFile *unsaved_files = RTUI->unsaved_files;
2813 unsigned options = RTUI->options;
2814 (void) options;
2815 RTUI->result = 1;
2816
2817 if (!TU)
2818 return;
2819
2820 CIndexer *CXXIdx = (CIndexer*)TU->CIdx;
2821 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing))
2822 setThreadBackgroundPriority();
2823
2824 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
2825 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
2826
2827 OwningPtr<std::vector<ASTUnit::RemappedFile> >
2828 RemappedFiles(new std::vector<ASTUnit::RemappedFile>());
2829
2830 // Recover resources if we crash before exiting this function.
2831 llvm::CrashRecoveryContextCleanupRegistrar<
2832 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
2833
2834 for (unsigned I = 0; I != num_unsaved_files; ++I) {
2835 StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
2836 const llvm::MemoryBuffer *Buffer
2837 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
2838 RemappedFiles->push_back(std::make_pair(unsaved_files[I].Filename,
2839 Buffer));
2840 }
2841
2842 if (!CXXUnit->Reparse(RemappedFiles->size() ? &(*RemappedFiles)[0] : 0,
2843 RemappedFiles->size()))
2844 RTUI->result = 0;
2845}
2846
2847int clang_reparseTranslationUnit(CXTranslationUnit TU,
2848 unsigned num_unsaved_files,
2849 struct CXUnsavedFile *unsaved_files,
2850 unsigned options) {
2851 ReparseTranslationUnitInfo RTUI = { TU, num_unsaved_files, unsaved_files,
2852 options, 0 };
2853
2854 if (getenv("LIBCLANG_NOTHREADS")) {
2855 clang_reparseTranslationUnit_Impl(&RTUI);
2856 return RTUI.result;
2857 }
2858
2859 llvm::CrashRecoveryContext CRC;
2860
2861 if (!RunSafely(CRC, clang_reparseTranslationUnit_Impl, &RTUI)) {
2862 fprintf(stderr, "libclang: crash detected during reparsing\n");
2863 static_cast<ASTUnit *>(TU->TUData)->setUnsafeToFree(true);
2864 return 1;
2865 } else if (getenv("LIBCLANG_RESOURCE_USAGE"))
2866 PrintLibclangResourceUsage(TU);
2867
2868 return RTUI.result;
2869}
2870
2871
2872CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
2873 if (!CTUnit)
2874 return createCXString("");
2875
2876 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit->TUData);
2877 return createCXString(CXXUnit->getOriginalSourceFileName(), true);
2878}
2879
2880CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
2881 ASTUnit *CXXUnit = static_cast<ASTUnit*>(TU->TUData);
2882 return MakeCXCursor(CXXUnit->getASTContext().getTranslationUnitDecl(), TU);
2883}
2884
2885} // end: extern "C"
2886
2887//===----------------------------------------------------------------------===//
2888// CXFile Operations.
2889//===----------------------------------------------------------------------===//
2890
2891extern "C" {
2892CXString clang_getFileName(CXFile SFile) {
2893 if (!SFile)
2894 return createCXString((const char*)NULL);
2895
2896 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
2897 return createCXString(FEnt->getName());
2898}
2899
2900time_t clang_getFileTime(CXFile SFile) {
2901 if (!SFile)
2902 return 0;
2903
2904 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
2905 return FEnt->getModificationTime();
2906}
2907
2908CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
2909 if (!tu)
2910 return 0;
2911
2912 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
2913
2914 FileManager &FMgr = CXXUnit->getFileManager();
2915 return const_cast<FileEntry *>(FMgr.getFile(file_name));
2916}
2917
2918unsigned clang_isFileMultipleIncludeGuarded(CXTranslationUnit tu, CXFile file) {
2919 if (!tu || !file)
2920 return 0;
2921
2922 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
2923 FileEntry *FEnt = static_cast<FileEntry *>(file);
2924 return CXXUnit->getPreprocessor().getHeaderSearchInfo()
2925 .isFileMultipleIncludeGuarded(FEnt);
2926}
2927
2928} // end: extern "C"
2929
2930//===----------------------------------------------------------------------===//
2931// CXCursor Operations.
2932//===----------------------------------------------------------------------===//
2933
2934static Decl *getDeclFromExpr(Stmt *E) {
2935 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
2936 return getDeclFromExpr(CE->getSubExpr());
2937
2938 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
2939 return RefExpr->getDecl();
2940 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
2941 return ME->getMemberDecl();
2942 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
2943 return RE->getDecl();
2944 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E)) {
2945 if (PRE->isExplicitProperty())
2946 return PRE->getExplicitProperty();
2947 // It could be messaging both getter and setter as in:
2948 // ++myobj.myprop;
2949 // in which case prefer to associate the setter since it is less obvious
2950 // from inspecting the source that the setter is going to get called.
2951 if (PRE->isMessagingSetter())
2952 return PRE->getImplicitPropertySetter();
2953 return PRE->getImplicitPropertyGetter();
2954 }
2955 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
2956 return getDeclFromExpr(POE->getSyntacticForm());
2957 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
2958 if (Expr *Src = OVE->getSourceExpr())
2959 return getDeclFromExpr(Src);
2960
2961 if (CallExpr *CE = dyn_cast<CallExpr>(E))
2962 return getDeclFromExpr(CE->getCallee());
2963 if (CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(E))
2964 if (!CE->isElidable())
2965 return CE->getConstructor();
2966 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
2967 return OME->getMethodDecl();
2968
2969 if (ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
2970 return PE->getProtocol();
2971 if (SubstNonTypeTemplateParmPackExpr *NTTP
2972 = dyn_cast<SubstNonTypeTemplateParmPackExpr>(E))
2973 return NTTP->getParameterPack();
2974 if (SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
2975 if (isa<NonTypeTemplateParmDecl>(SizeOfPack->getPack()) ||
2976 isa<ParmVarDecl>(SizeOfPack->getPack()))
2977 return SizeOfPack->getPack();
2978
2979 return 0;
2980}
2981
2982static SourceLocation getLocationFromExpr(Expr *E) {
2983 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
2984 return getLocationFromExpr(CE->getSubExpr());
2985
2986 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
2987 return /*FIXME:*/Msg->getLeftLoc();
2988 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
2989 return DRE->getLocation();
2990 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
2991 return Member->getMemberLoc();
2992 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
2993 return Ivar->getLocation();
2994 if (SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
2995 return SizeOfPack->getPackLoc();
2996 if (ObjCPropertyRefExpr *PropRef = dyn_cast<ObjCPropertyRefExpr>(E))
2997 return PropRef->getLocation();
2998
2999 return E->getLocStart();
3000}
3001
3002extern "C" {
3003
3004unsigned clang_visitChildren(CXCursor parent,
3005 CXCursorVisitor visitor,
3006 CXClientData client_data) {
3007 CursorVisitor CursorVis(getCursorTU(parent), visitor, client_data,
3008 /*VisitPreprocessorLast=*/false);
3009 return CursorVis.VisitChildren(parent);
3010}
3011
3012#ifndef __has_feature
3013#define __has_feature(x) 0
3014#endif
3015#if __has_feature(blocks)
3016typedef enum CXChildVisitResult
3017 (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
3018
3019static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
3020 CXClientData client_data) {
3021 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
3022 return block(cursor, parent);
3023}
3024#else
3025// If we are compiled with a compiler that doesn't have native blocks support,
3026// define and call the block manually, so the
3027typedef struct _CXChildVisitResult
3028{
3029 void *isa;
3030 int flags;
3031 int reserved;
3032 enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor,
3033 CXCursor);
3034} *CXCursorVisitorBlock;
3035
3036static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
3037 CXClientData client_data) {
3038 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
3039 return block->invoke(block, cursor, parent);
3040}
3041#endif
3042
3043
3044unsigned clang_visitChildrenWithBlock(CXCursor parent,
3045 CXCursorVisitorBlock block) {
3046 return clang_visitChildren(parent, visitWithBlock, block);
3047}
3048
3049static CXString getDeclSpelling(Decl *D) {
3050 if (!D)
3051 return createCXString("");
3052
3053 NamedDecl *ND = dyn_cast<NamedDecl>(D);
3054 if (!ND) {
3055 if (ObjCPropertyImplDecl *PropImpl =dyn_cast<ObjCPropertyImplDecl>(D))
3056 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
3057 return createCXString(Property->getIdentifier()->getName());
3058
3059 if (ImportDecl *ImportD = dyn_cast<ImportDecl>(D))
3060 if (Module *Mod = ImportD->getImportedModule())
3061 return createCXString(Mod->getFullModuleName());
3062
3063 return createCXString("");
3064 }
3065
3066 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
3067 return createCXString(OMD->getSelector().getAsString());
3068
3069 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
3070 // No, this isn't the same as the code below. getIdentifier() is non-virtual
3071 // and returns different names. NamedDecl returns the class name and
3072 // ObjCCategoryImplDecl returns the category name.
3073 return createCXString(CIMP->getIdentifier()->getNameStart());
3074
3075 if (isa<UsingDirectiveDecl>(D))
3076 return createCXString("");
3077
3078 SmallString<1024> S;
3079 llvm::raw_svector_ostream os(S);
3080 ND->printName(os);
3081
3082 return createCXString(os.str());
3083}
3084
3085CXString clang_getCursorSpelling(CXCursor C) {
3086 if (clang_isTranslationUnit(C.kind))
3087 return clang_getTranslationUnitSpelling(
3088 static_cast<CXTranslationUnit>(C.data[2]));
3089
3090 if (clang_isReference(C.kind)) {
3091 switch (C.kind) {
3092 case CXCursor_ObjCSuperClassRef: {
3093 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
3094 return createCXString(Super->getIdentifier()->getNameStart());
3095 }
3096 case CXCursor_ObjCClassRef: {
3097 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
3098 return createCXString(Class->getIdentifier()->getNameStart());
3099 }
3100 case CXCursor_ObjCProtocolRef: {
3101 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
3102 assert(OID && "getCursorSpelling(): Missing protocol decl");
3103 return createCXString(OID->getIdentifier()->getNameStart());
3104 }
3105 case CXCursor_CXXBaseSpecifier: {
3106 CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
3107 return createCXString(B->getType().getAsString());
3108 }
3109 case CXCursor_TypeRef: {
3110 TypeDecl *Type = getCursorTypeRef(C).first;
3111 assert(Type && "Missing type decl");
3112
3113 return createCXString(getCursorContext(C).getTypeDeclType(Type).
3114 getAsString());
3115 }
3116 case CXCursor_TemplateRef: {
3117 TemplateDecl *Template = getCursorTemplateRef(C).first;
3118 assert(Template && "Missing template decl");
3119
3120 return createCXString(Template->getNameAsString());
3121 }
3122
3123 case CXCursor_NamespaceRef: {
3124 NamedDecl *NS = getCursorNamespaceRef(C).first;
3125 assert(NS && "Missing namespace decl");
3126
3127 return createCXString(NS->getNameAsString());
3128 }
3129
3130 case CXCursor_MemberRef: {
3131 FieldDecl *Field = getCursorMemberRef(C).first;
3132 assert(Field && "Missing member decl");
3133
3134 return createCXString(Field->getNameAsString());
3135 }
3136
3137 case CXCursor_LabelRef: {
3138 LabelStmt *Label = getCursorLabelRef(C).first;
3139 assert(Label && "Missing label");
3140
3141 return createCXString(Label->getName());
3142 }
3143
3144 case CXCursor_OverloadedDeclRef: {
3145 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
3146 if (Decl *D = Storage.dyn_cast<Decl *>()) {
3147 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
3148 return createCXString(ND->getNameAsString());
3149 return createCXString("");
3150 }
3151 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
3152 return createCXString(E->getName().getAsString());
3153 OverloadedTemplateStorage *Ovl
3154 = Storage.get<OverloadedTemplateStorage*>();
3155 if (Ovl->size() == 0)
3156 return createCXString("");
3157 return createCXString((*Ovl->begin())->getNameAsString());
3158 }
3159
3160 case CXCursor_VariableRef: {
3161 VarDecl *Var = getCursorVariableRef(C).first;
3162 assert(Var && "Missing variable decl");
3163
3164 return createCXString(Var->getNameAsString());
3165 }
3166
3167 default:
3168 return createCXString("<not implemented>");
3169 }
3170 }
3171
3172 if (clang_isExpression(C.kind)) {
3173 Decl *D = getDeclFromExpr(getCursorExpr(C));
3174 if (D)
3175 return getDeclSpelling(D);
3176 return createCXString("");
3177 }
3178
3179 if (clang_isStatement(C.kind)) {
3180 Stmt *S = getCursorStmt(C);
3181 if (LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
3182 return createCXString(Label->getName());
3183
3184 return createCXString("");
3185 }
3186
3187 if (C.kind == CXCursor_MacroExpansion)
3188 return createCXString(getCursorMacroExpansion(C)->getName()
3189 ->getNameStart());
3190
3191 if (C.kind == CXCursor_MacroDefinition)
3192 return createCXString(getCursorMacroDefinition(C)->getName()
3193 ->getNameStart());
3194
3195 if (C.kind == CXCursor_InclusionDirective)
3196 return createCXString(getCursorInclusionDirective(C)->getFileName());
3197
3198 if (clang_isDeclaration(C.kind))
3199 return getDeclSpelling(getCursorDecl(C));
3200
3201 if (C.kind == CXCursor_AnnotateAttr) {
3202 AnnotateAttr *AA = cast<AnnotateAttr>(cxcursor::getCursorAttr(C));
3203 return createCXString(AA->getAnnotation());
3204 }
3205
3206 if (C.kind == CXCursor_AsmLabelAttr) {
3207 AsmLabelAttr *AA = cast<AsmLabelAttr>(cxcursor::getCursorAttr(C));
3208 return createCXString(AA->getLabel());
3209 }
3210
3211 return createCXString("");
3212}
3213
3214CXSourceRange clang_Cursor_getSpellingNameRange(CXCursor C,
3215 unsigned pieceIndex,
3216 unsigned options) {
3217 if (clang_Cursor_isNull(C))
3218 return clang_getNullRange();
3219
3220 ASTContext &Ctx = getCursorContext(C);
3221
3222 if (clang_isStatement(C.kind)) {
3223 Stmt *S = getCursorStmt(C);
3224 if (LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S)) {
3225 if (pieceIndex > 0)
3226 return clang_getNullRange();
3227 return cxloc::translateSourceRange(Ctx, Label->getIdentLoc());
3228 }
3229
3230 return clang_getNullRange();
3231 }
3232
3233 if (C.kind == CXCursor_ObjCMessageExpr) {
3234 if (ObjCMessageExpr *
3235 ME = dyn_cast_or_null<ObjCMessageExpr>(getCursorExpr(C))) {
3236 if (pieceIndex >= ME->getNumSelectorLocs())
3237 return clang_getNullRange();
3238 return cxloc::translateSourceRange(Ctx, ME->getSelectorLoc(pieceIndex));
3239 }
3240 }
3241
3242 if (C.kind == CXCursor_ObjCInstanceMethodDecl ||
3243 C.kind == CXCursor_ObjCClassMethodDecl) {
3244 if (ObjCMethodDecl *
3245 MD = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(C))) {
3246 if (pieceIndex >= MD->getNumSelectorLocs())
3247 return clang_getNullRange();
3248 return cxloc::translateSourceRange(Ctx, MD->getSelectorLoc(pieceIndex));
3249 }
3250 }
3251
3252 if (C.kind == CXCursor_ObjCCategoryDecl ||
3253 C.kind == CXCursor_ObjCCategoryImplDecl) {
3254 if (pieceIndex > 0)
3255 return clang_getNullRange();
3256 if (ObjCCategoryDecl *
3257 CD = dyn_cast_or_null<ObjCCategoryDecl>(getCursorDecl(C)))
3258 return cxloc::translateSourceRange(Ctx, CD->getCategoryNameLoc());
3259 if (ObjCCategoryImplDecl *
3260 CID = dyn_cast_or_null<ObjCCategoryImplDecl>(getCursorDecl(C)))
3261 return cxloc::translateSourceRange(Ctx, CID->getCategoryNameLoc());
3262 }
3263
3264 if (C.kind == CXCursor_ModuleImportDecl) {
3265 if (pieceIndex > 0)
3266 return clang_getNullRange();
3267 if (ImportDecl *ImportD = dyn_cast_or_null<ImportDecl>(getCursorDecl(C))) {
3268 ArrayRef<SourceLocation> Locs = ImportD->getIdentifierLocs();
3269 if (!Locs.empty())
3270 return cxloc::translateSourceRange(Ctx,
3271 SourceRange(Locs.front(), Locs.back()));
3272 }
3273 return clang_getNullRange();
3274 }
3275
3276 // FIXME: A CXCursor_InclusionDirective should give the location of the
3277 // filename, but we don't keep track of this.
3278
3279 // FIXME: A CXCursor_AnnotateAttr should give the location of the annotation
3280 // but we don't keep track of this.
3281
3282 // FIXME: A CXCursor_AsmLabelAttr should give the location of the label
3283 // but we don't keep track of this.
3284
3285 // Default handling, give the location of the cursor.
3286
3287 if (pieceIndex > 0)
3288 return clang_getNullRange();
3289
3290 CXSourceLocation CXLoc = clang_getCursorLocation(C);
3291 SourceLocation Loc = cxloc::translateSourceLocation(CXLoc);
3292 return cxloc::translateSourceRange(Ctx, Loc);
3293}
3294
3295CXString clang_getCursorDisplayName(CXCursor C) {
3296 if (!clang_isDeclaration(C.kind))
3297 return clang_getCursorSpelling(C);
3298
3299 Decl *D = getCursorDecl(C);
3300 if (!D)
3301 return createCXString("");
3302
3303 PrintingPolicy Policy = getCursorContext(C).getPrintingPolicy();
3304 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
3305 D = FunTmpl->getTemplatedDecl();
3306
3307 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
3308 SmallString<64> Str;
3309 llvm::raw_svector_ostream OS(Str);
3310 OS << *Function;
3311 if (Function->getPrimaryTemplate())
3312 OS << "<>";
3313 OS << "(";
3314 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
3315 if (I)
3316 OS << ", ";
3317 OS << Function->getParamDecl(I)->getType().getAsString(Policy);
3318 }
3319
3320 if (Function->isVariadic()) {
3321 if (Function->getNumParams())
3322 OS << ", ";
3323 OS << "...";
3324 }
3325 OS << ")";
3326 return createCXString(OS.str());
3327 }
3328
3329 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
3330 SmallString<64> Str;
3331 llvm::raw_svector_ostream OS(Str);
3332 OS << *ClassTemplate;
3333 OS << "<";
3334 TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
3335 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
3336 if (I)
3337 OS << ", ";
3338
3339 NamedDecl *Param = Params->getParam(I);
3340 if (Param->getIdentifier()) {
3341 OS << Param->getIdentifier()->getName();
3342 continue;
3343 }
3344
3345 // There is no parameter name, which makes this tricky. Try to come up
3346 // with something useful that isn't too long.
3347 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
3348 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
3349 else if (NonTypeTemplateParmDecl *NTTP
3350 = dyn_cast<NonTypeTemplateParmDecl>(Param))
3351 OS << NTTP->getType().getAsString(Policy);
3352 else
3353 OS << "template<...> class";
3354 }
3355
3356 OS << ">";
3357 return createCXString(OS.str());
3358 }
3359
3360 if (ClassTemplateSpecializationDecl *ClassSpec
3361 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
3362 // If the type was explicitly written, use that.
3363 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
3364 return createCXString(TSInfo->getType().getAsString(Policy));
3365
3366 SmallString<64> Str;
3367 llvm::raw_svector_ostream OS(Str);
3368 OS << *ClassSpec;
3369 OS << TemplateSpecializationType::PrintTemplateArgumentList(
3370 ClassSpec->getTemplateArgs().data(),
3371 ClassSpec->getTemplateArgs().size(),
3372 Policy);
3373 return createCXString(OS.str());
3374 }
3375
3376 return clang_getCursorSpelling(C);
3377}
3378
3379CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
3380 switch (Kind) {
3381 case CXCursor_FunctionDecl:
3382 return createCXString("FunctionDecl");
3383 case CXCursor_TypedefDecl:
3384 return createCXString("TypedefDecl");
3385 case CXCursor_EnumDecl:
3386 return createCXString("EnumDecl");
3387 case CXCursor_EnumConstantDecl:
3388 return createCXString("EnumConstantDecl");
3389 case CXCursor_StructDecl:
3390 return createCXString("StructDecl");
3391 case CXCursor_UnionDecl:
3392 return createCXString("UnionDecl");
3393 case CXCursor_ClassDecl:
3394 return createCXString("ClassDecl");
3395 case CXCursor_FieldDecl:
3396 return createCXString("FieldDecl");
3397 case CXCursor_VarDecl:
3398 return createCXString("VarDecl");
3399 case CXCursor_ParmDecl:
3400 return createCXString("ParmDecl");
3401 case CXCursor_ObjCInterfaceDecl:
3402 return createCXString("ObjCInterfaceDecl");
3403 case CXCursor_ObjCCategoryDecl:
3404 return createCXString("ObjCCategoryDecl");
3405 case CXCursor_ObjCProtocolDecl:
3406 return createCXString("ObjCProtocolDecl");
3407 case CXCursor_ObjCPropertyDecl:
3408 return createCXString("ObjCPropertyDecl");
3409 case CXCursor_ObjCIvarDecl:
3410 return createCXString("ObjCIvarDecl");
3411 case CXCursor_ObjCInstanceMethodDecl:
3412 return createCXString("ObjCInstanceMethodDecl");
3413 case CXCursor_ObjCClassMethodDecl:
3414 return createCXString("ObjCClassMethodDecl");
3415 case CXCursor_ObjCImplementationDecl:
3416 return createCXString("ObjCImplementationDecl");
3417 case CXCursor_ObjCCategoryImplDecl:
3418 return createCXString("ObjCCategoryImplDecl");
3419 case CXCursor_CXXMethod:
3420 return createCXString("CXXMethod");
3421 case CXCursor_UnexposedDecl:
3422 return createCXString("UnexposedDecl");
3423 case CXCursor_ObjCSuperClassRef:
3424 return createCXString("ObjCSuperClassRef");
3425 case CXCursor_ObjCProtocolRef:
3426 return createCXString("ObjCProtocolRef");
3427 case CXCursor_ObjCClassRef:
3428 return createCXString("ObjCClassRef");
3429 case CXCursor_TypeRef:
3430 return createCXString("TypeRef");
3431 case CXCursor_TemplateRef:
3432 return createCXString("TemplateRef");
3433 case CXCursor_NamespaceRef:
3434 return createCXString("NamespaceRef");
3435 case CXCursor_MemberRef:
3436 return createCXString("MemberRef");
3437 case CXCursor_LabelRef:
3438 return createCXString("LabelRef");
3439 case CXCursor_OverloadedDeclRef:
3440 return createCXString("OverloadedDeclRef");
3441 case CXCursor_VariableRef:
3442 return createCXString("VariableRef");
3443 case CXCursor_IntegerLiteral:
3444 return createCXString("IntegerLiteral");
3445 case CXCursor_FloatingLiteral:
3446 return createCXString("FloatingLiteral");
3447 case CXCursor_ImaginaryLiteral:
3448 return createCXString("ImaginaryLiteral");
3449 case CXCursor_StringLiteral:
3450 return createCXString("StringLiteral");
3451 case CXCursor_CharacterLiteral:
3452 return createCXString("CharacterLiteral");
3453 case CXCursor_ParenExpr:
3454 return createCXString("ParenExpr");
3455 case CXCursor_UnaryOperator:
3456 return createCXString("UnaryOperator");
3457 case CXCursor_ArraySubscriptExpr:
3458 return createCXString("ArraySubscriptExpr");
3459 case CXCursor_BinaryOperator:
3460 return createCXString("BinaryOperator");
3461 case CXCursor_CompoundAssignOperator:
3462 return createCXString("CompoundAssignOperator");
3463 case CXCursor_ConditionalOperator:
3464 return createCXString("ConditionalOperator");
3465 case CXCursor_CStyleCastExpr:
3466 return createCXString("CStyleCastExpr");
3467 case CXCursor_CompoundLiteralExpr:
3468 return createCXString("CompoundLiteralExpr");
3469 case CXCursor_InitListExpr:
3470 return createCXString("InitListExpr");
3471 case CXCursor_AddrLabelExpr:
3472 return createCXString("AddrLabelExpr");
3473 case CXCursor_StmtExpr:
3474 return createCXString("StmtExpr");
3475 case CXCursor_GenericSelectionExpr:
3476 return createCXString("GenericSelectionExpr");
3477 case CXCursor_GNUNullExpr:
3478 return createCXString("GNUNullExpr");
3479 case CXCursor_CXXStaticCastExpr:
3480 return createCXString("CXXStaticCastExpr");
3481 case CXCursor_CXXDynamicCastExpr:
3482 return createCXString("CXXDynamicCastExpr");
3483 case CXCursor_CXXReinterpretCastExpr:
3484 return createCXString("CXXReinterpretCastExpr");
3485 case CXCursor_CXXConstCastExpr:
3486 return createCXString("CXXConstCastExpr");
3487 case CXCursor_CXXFunctionalCastExpr:
3488 return createCXString("CXXFunctionalCastExpr");
3489 case CXCursor_CXXTypeidExpr:
3490 return createCXString("CXXTypeidExpr");
3491 case CXCursor_CXXBoolLiteralExpr:
3492 return createCXString("CXXBoolLiteralExpr");
3493 case CXCursor_CXXNullPtrLiteralExpr:
3494 return createCXString("CXXNullPtrLiteralExpr");
3495 case CXCursor_CXXThisExpr:
3496 return createCXString("CXXThisExpr");
3497 case CXCursor_CXXThrowExpr:
3498 return createCXString("CXXThrowExpr");
3499 case CXCursor_CXXNewExpr:
3500 return createCXString("CXXNewExpr");
3501 case CXCursor_CXXDeleteExpr:
3502 return createCXString("CXXDeleteExpr");
3503 case CXCursor_UnaryExpr:
3504 return createCXString("UnaryExpr");
3505 case CXCursor_ObjCStringLiteral:
3506 return createCXString("ObjCStringLiteral");
3507 case CXCursor_ObjCBoolLiteralExpr:
3508 return createCXString("ObjCBoolLiteralExpr");
3509 case CXCursor_ObjCEncodeExpr:
3510 return createCXString("ObjCEncodeExpr");
3511 case CXCursor_ObjCSelectorExpr:
3512 return createCXString("ObjCSelectorExpr");
3513 case CXCursor_ObjCProtocolExpr:
3514 return createCXString("ObjCProtocolExpr");
3515 case CXCursor_ObjCBridgedCastExpr:
3516 return createCXString("ObjCBridgedCastExpr");
3517 case CXCursor_BlockExpr:
3518 return createCXString("BlockExpr");
3519 case CXCursor_PackExpansionExpr:
3520 return createCXString("PackExpansionExpr");
3521 case CXCursor_SizeOfPackExpr:
3522 return createCXString("SizeOfPackExpr");
3523 case CXCursor_LambdaExpr:
3524 return createCXString("LambdaExpr");
3525 case CXCursor_UnexposedExpr:
3526 return createCXString("UnexposedExpr");
3527 case CXCursor_DeclRefExpr:
3528 return createCXString("DeclRefExpr");
3529 case CXCursor_MemberRefExpr:
3530 return createCXString("MemberRefExpr");
3531 case CXCursor_CallExpr:
3532 return createCXString("CallExpr");
3533 case CXCursor_ObjCMessageExpr:
3534 return createCXString("ObjCMessageExpr");
3535 case CXCursor_UnexposedStmt:
3536 return createCXString("UnexposedStmt");
3537 case CXCursor_DeclStmt:
3538 return createCXString("DeclStmt");
3539 case CXCursor_LabelStmt:
3540 return createCXString("LabelStmt");
3541 case CXCursor_CompoundStmt:
3542 return createCXString("CompoundStmt");
3543 case CXCursor_CaseStmt:
3544 return createCXString("CaseStmt");
3545 case CXCursor_DefaultStmt:
3546 return createCXString("DefaultStmt");
3547 case CXCursor_IfStmt:
3548 return createCXString("IfStmt");
3549 case CXCursor_SwitchStmt:
3550 return createCXString("SwitchStmt");
3551 case CXCursor_WhileStmt:
3552 return createCXString("WhileStmt");
3553 case CXCursor_DoStmt:
3554 return createCXString("DoStmt");
3555 case CXCursor_ForStmt:
3556 return createCXString("ForStmt");
3557 case CXCursor_GotoStmt:
3558 return createCXString("GotoStmt");
3559 case CXCursor_IndirectGotoStmt:
3560 return createCXString("IndirectGotoStmt");
3561 case CXCursor_ContinueStmt:
3562 return createCXString("ContinueStmt");
3563 case CXCursor_BreakStmt:
3564 return createCXString("BreakStmt");
3565 case CXCursor_ReturnStmt:
3566 return createCXString("ReturnStmt");
3567 case CXCursor_GCCAsmStmt:
3568 return createCXString("GCCAsmStmt");
3569 case CXCursor_MSAsmStmt:
3570 return createCXString("MSAsmStmt");
3571 case CXCursor_ObjCAtTryStmt:
3572 return createCXString("ObjCAtTryStmt");
3573 case CXCursor_ObjCAtCatchStmt:
3574 return createCXString("ObjCAtCatchStmt");
3575 case CXCursor_ObjCAtFinallyStmt:
3576 return createCXString("ObjCAtFinallyStmt");
3577 case CXCursor_ObjCAtThrowStmt:
3578 return createCXString("ObjCAtThrowStmt");
3579 case CXCursor_ObjCAtSynchronizedStmt:
3580 return createCXString("ObjCAtSynchronizedStmt");
3581 case CXCursor_ObjCAutoreleasePoolStmt:
3582 return createCXString("ObjCAutoreleasePoolStmt");
3583 case CXCursor_ObjCForCollectionStmt:
3584 return createCXString("ObjCForCollectionStmt");
3585 case CXCursor_CXXCatchStmt:
3586 return createCXString("CXXCatchStmt");
3587 case CXCursor_CXXTryStmt:
3588 return createCXString("CXXTryStmt");
3589 case CXCursor_CXXForRangeStmt:
3590 return createCXString("CXXForRangeStmt");
3591 case CXCursor_SEHTryStmt:
3592 return createCXString("SEHTryStmt");
3593 case CXCursor_SEHExceptStmt:
3594 return createCXString("SEHExceptStmt");
3595 case CXCursor_SEHFinallyStmt:
3596 return createCXString("SEHFinallyStmt");
3597 case CXCursor_NullStmt:
3598 return createCXString("NullStmt");
3599 case CXCursor_InvalidFile:
3600 return createCXString("InvalidFile");
3601 case CXCursor_InvalidCode:
3602 return createCXString("InvalidCode");
3603 case CXCursor_NoDeclFound:
3604 return createCXString("NoDeclFound");
3605 case CXCursor_NotImplemented:
3606 return createCXString("NotImplemented");
3607 case CXCursor_TranslationUnit:
3608 return createCXString("TranslationUnit");
3609 case CXCursor_UnexposedAttr:
3610 return createCXString("UnexposedAttr");
3611 case CXCursor_IBActionAttr:
3612 return createCXString("attribute(ibaction)");
3613 case CXCursor_IBOutletAttr:
3614 return createCXString("attribute(iboutlet)");
3615 case CXCursor_IBOutletCollectionAttr:
3616 return createCXString("attribute(iboutletcollection)");
3617 case CXCursor_CXXFinalAttr:
3618 return createCXString("attribute(final)");
3619 case CXCursor_CXXOverrideAttr:
3620 return createCXString("attribute(override)");
3621 case CXCursor_AnnotateAttr:
3622 return createCXString("attribute(annotate)");
3623 case CXCursor_AsmLabelAttr:
3624 return createCXString("asm label");
3625 case CXCursor_PreprocessingDirective:
3626 return createCXString("preprocessing directive");
3627 case CXCursor_MacroDefinition:
3628 return createCXString("macro definition");
3629 case CXCursor_MacroExpansion:
3630 return createCXString("macro expansion");
3631 case CXCursor_InclusionDirective:
3632 return createCXString("inclusion directive");
3633 case CXCursor_Namespace:
3634 return createCXString("Namespace");
3635 case CXCursor_LinkageSpec:
3636 return createCXString("LinkageSpec");
3637 case CXCursor_CXXBaseSpecifier:
3638 return createCXString("C++ base class specifier");
3639 case CXCursor_Constructor:
3640 return createCXString("CXXConstructor");
3641 case CXCursor_Destructor:
3642 return createCXString("CXXDestructor");
3643 case CXCursor_ConversionFunction:
3644 return createCXString("CXXConversion");
3645 case CXCursor_TemplateTypeParameter:
3646 return createCXString("TemplateTypeParameter");
3647 case CXCursor_NonTypeTemplateParameter:
3648 return createCXString("NonTypeTemplateParameter");
3649 case CXCursor_TemplateTemplateParameter:
3650 return createCXString("TemplateTemplateParameter");
3651 case CXCursor_FunctionTemplate:
3652 return createCXString("FunctionTemplate");
3653 case CXCursor_ClassTemplate:
3654 return createCXString("ClassTemplate");
3655 case CXCursor_ClassTemplatePartialSpecialization:
3656 return createCXString("ClassTemplatePartialSpecialization");
3657 case CXCursor_NamespaceAlias:
3658 return createCXString("NamespaceAlias");
3659 case CXCursor_UsingDirective:
3660 return createCXString("UsingDirective");
3661 case CXCursor_UsingDeclaration:
3662 return createCXString("UsingDeclaration");
3663 case CXCursor_TypeAliasDecl:
3664 return createCXString("TypeAliasDecl");
3665 case CXCursor_ObjCSynthesizeDecl:
3666 return createCXString("ObjCSynthesizeDecl");
3667 case CXCursor_ObjCDynamicDecl:
3668 return createCXString("ObjCDynamicDecl");
3669 case CXCursor_CXXAccessSpecifier:
3670 return createCXString("CXXAccessSpecifier");
3671 case CXCursor_ModuleImportDecl:
3672 return createCXString("ModuleImport");
3673 }
3674
3675 llvm_unreachable("Unhandled CXCursorKind");
3676}
3677
3678struct GetCursorData {
3679 SourceLocation TokenBeginLoc;
3680 bool PointsAtMacroArgExpansion;
3681 bool VisitedObjCPropertyImplDecl;
3682 SourceLocation VisitedDeclaratorDeclStartLoc;
3683 CXCursor &BestCursor;
3684
3685 GetCursorData(SourceManager &SM,
3686 SourceLocation tokenBegin, CXCursor &outputCursor)
3687 : TokenBeginLoc(tokenBegin), BestCursor(outputCursor) {
3688 PointsAtMacroArgExpansion = SM.isMacroArgExpansion(tokenBegin);
3689 VisitedObjCPropertyImplDecl = false;
3690 }
3691};
3692
3693static enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
3694 CXCursor parent,
3695 CXClientData client_data) {
3696 GetCursorData *Data = static_cast<GetCursorData *>(client_data);
3697 CXCursor *BestCursor = &Data->BestCursor;
3698
3699 // If we point inside a macro argument we should provide info of what the
3700 // token is so use the actual cursor, don't replace it with a macro expansion
3701 // cursor.
3702 if (cursor.kind == CXCursor_MacroExpansion && Data->PointsAtMacroArgExpansion)
3703 return CXChildVisit_Recurse;
3704
3705 if (clang_isDeclaration(cursor.kind)) {
3706 // Avoid having the implicit methods override the property decls.
3707 if (ObjCMethodDecl *MD
3708 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
3709 if (MD->isImplicit())
3710 return CXChildVisit_Break;
3711
3712 } else if (ObjCInterfaceDecl *ID
3713 = dyn_cast_or_null<ObjCInterfaceDecl>(getCursorDecl(cursor))) {
3714 // Check that when we have multiple @class references in the same line,
3715 // that later ones do not override the previous ones.
3716 // If we have:
3717 // @class Foo, Bar;
3718 // source ranges for both start at '@', so 'Bar' will end up overriding
3719 // 'Foo' even though the cursor location was at 'Foo'.
3720 if (BestCursor->kind == CXCursor_ObjCInterfaceDecl ||
3721 BestCursor->kind == CXCursor_ObjCClassRef)
3722 if (ObjCInterfaceDecl *PrevID
3723 = dyn_cast_or_null<ObjCInterfaceDecl>(getCursorDecl(*BestCursor))){
3724 if (PrevID != ID &&
3725 !PrevID->isThisDeclarationADefinition() &&
3726 !ID->isThisDeclarationADefinition())
3727 return CXChildVisit_Break;
3728 }
3729
3730 } else if (DeclaratorDecl *DD
3731 = dyn_cast_or_null<DeclaratorDecl>(getCursorDecl(cursor))) {
3732 SourceLocation StartLoc = DD->getSourceRange().getBegin();
3733 // Check that when we have multiple declarators in the same line,
3734 // that later ones do not override the previous ones.
3735 // If we have:
3736 // int Foo, Bar;
3737 // source ranges for both start at 'int', so 'Bar' will end up overriding
3738 // 'Foo' even though the cursor location was at 'Foo'.
3739 if (Data->VisitedDeclaratorDeclStartLoc == StartLoc)
3740 return CXChildVisit_Break;
3741 Data->VisitedDeclaratorDeclStartLoc = StartLoc;
3742
3743 } else if (ObjCPropertyImplDecl *PropImp
3744 = dyn_cast_or_null<ObjCPropertyImplDecl>(getCursorDecl(cursor))) {
3745 (void)PropImp;
3746 // Check that when we have multiple @synthesize in the same line,
3747 // that later ones do not override the previous ones.
3748 // If we have:
3749 // @synthesize Foo, Bar;
3750 // source ranges for both start at '@', so 'Bar' will end up overriding
3751 // 'Foo' even though the cursor location was at 'Foo'.
3752 if (Data->VisitedObjCPropertyImplDecl)
3753 return CXChildVisit_Break;
3754 Data->VisitedObjCPropertyImplDecl = true;
3755 }
3756 }
3757
3758 if (clang_isExpression(cursor.kind) &&
3759 clang_isDeclaration(BestCursor->kind)) {
3760 if (Decl *D = getCursorDecl(*BestCursor)) {
3761 // Avoid having the cursor of an expression replace the declaration cursor
3762 // when the expression source range overlaps the declaration range.
3763 // This can happen for C++ constructor expressions whose range generally
3764 // include the variable declaration, e.g.:
3765 // MyCXXClass foo; // Make sure pointing at 'foo' returns a VarDecl cursor.
3766 if (D->getLocation().isValid() && Data->TokenBeginLoc.isValid() &&
3767 D->getLocation() == Data->TokenBeginLoc)
3768 return CXChildVisit_Break;
3769 }
3770 }
3771
3772 // If our current best cursor is the construction of a temporary object,
3773 // don't replace that cursor with a type reference, because we want
3774 // clang_getCursor() to point at the constructor.
3775 if (clang_isExpression(BestCursor->kind) &&
3776 isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
3777 cursor.kind == CXCursor_TypeRef) {
3778 // Keep the cursor pointing at CXXTemporaryObjectExpr but also mark it
3779 // as having the actual point on the type reference.
3780 *BestCursor = getTypeRefedCallExprCursor(*BestCursor);
3781 return CXChildVisit_Recurse;
3782 }
3783
3784 *BestCursor = cursor;
3785 return CXChildVisit_Recurse;
3786}
3787
3788CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
3789 if (!TU)
3790 return clang_getNullCursor();
3791
3792 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
3793 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3794
3795 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
3796 CXCursor Result = cxcursor::getCursor(TU, SLoc);
3797
3798 bool Logging = getenv("LIBCLANG_LOGGING");
3799 if (Logging) {
3800 CXFile SearchFile;
3801 unsigned SearchLine, SearchColumn;
3802 CXFile ResultFile;
3803 unsigned ResultLine, ResultColumn;
3804 CXString SearchFileName, ResultFileName, KindSpelling, USR;
3805 const char *IsDef = clang_isCursorDefinition(Result)? " (Definition)" : "";
3806 CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
3807
3808 clang_getExpansionLocation(Loc, &SearchFile, &SearchLine, &SearchColumn, 0);
3809 clang_getExpansionLocation(ResultLoc, &ResultFile, &ResultLine,
3810 &ResultColumn, 0);
3811 SearchFileName = clang_getFileName(SearchFile);
3812 ResultFileName = clang_getFileName(ResultFile);
3813 KindSpelling = clang_getCursorKindSpelling(Result.kind);
3814 USR = clang_getCursorUSR(Result);
3815 fprintf(stderr, "clang_getCursor(%s:%d:%d) = %s(%s:%d:%d):%s%s\n",
3816 clang_getCString(SearchFileName), SearchLine, SearchColumn,
3817 clang_getCString(KindSpelling),
3818 clang_getCString(ResultFileName), ResultLine, ResultColumn,
3819 clang_getCString(USR), IsDef);
3820 clang_disposeString(SearchFileName);
3821 clang_disposeString(ResultFileName);
3822 clang_disposeString(KindSpelling);
3823 clang_disposeString(USR);
3824
3825 CXCursor Definition = clang_getCursorDefinition(Result);
3826 if (!clang_equalCursors(Definition, clang_getNullCursor())) {
3827 CXSourceLocation DefinitionLoc = clang_getCursorLocation(Definition);
3828 CXString DefinitionKindSpelling
3829 = clang_getCursorKindSpelling(Definition.kind);
3830 CXFile DefinitionFile;
3831 unsigned DefinitionLine, DefinitionColumn;
3832 clang_getExpansionLocation(DefinitionLoc, &DefinitionFile,
3833 &DefinitionLine, &DefinitionColumn, 0);
3834 CXString DefinitionFileName = clang_getFileName(DefinitionFile);
3835 fprintf(stderr, " -> %s(%s:%d:%d)\n",
3836 clang_getCString(DefinitionKindSpelling),
3837 clang_getCString(DefinitionFileName),
3838 DefinitionLine, DefinitionColumn);
3839 clang_disposeString(DefinitionFileName);
3840 clang_disposeString(DefinitionKindSpelling);
3841 }
3842 }
3843
3844 return Result;
3845}
3846
3847CXCursor clang_getNullCursor(void) {
3848 return MakeCXCursorInvalid(CXCursor_InvalidFile);
3849}
3850
3851unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
3852 return X == Y;
3853}
3854
3855unsigned clang_hashCursor(CXCursor C) {
3856 unsigned Index = 0;
3857 if (clang_isExpression(C.kind) || clang_isStatement(C.kind))
3858 Index = 1;
3859
3860 return llvm::DenseMapInfo<std::pair<unsigned, void*> >::getHashValue(
3861 std::make_pair(C.kind, C.data[Index]));
3862}
3863
3864unsigned clang_isInvalid(enum CXCursorKind K) {
3865 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
3866}
3867
3868unsigned clang_isDeclaration(enum CXCursorKind K) {
3869 return (K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl) ||
3870 (K >= CXCursor_FirstExtraDecl && K <= CXCursor_LastExtraDecl);
3871}
3872
3873unsigned clang_isReference(enum CXCursorKind K) {
3874 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
3875}
3876
3877unsigned clang_isExpression(enum CXCursorKind K) {
3878 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
3879}
3880
3881unsigned clang_isStatement(enum CXCursorKind K) {
3882 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
3883}
3884
3885unsigned clang_isAttribute(enum CXCursorKind K) {
3886 return K >= CXCursor_FirstAttr && K <= CXCursor_LastAttr;
3887}
3888
3889unsigned clang_isTranslationUnit(enum CXCursorKind K) {
3890 return K == CXCursor_TranslationUnit;
3891}
3892
3893unsigned clang_isPreprocessing(enum CXCursorKind K) {
3894 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
3895}
3896
3897unsigned clang_isUnexposed(enum CXCursorKind K) {
3898 switch (K) {
3899 case CXCursor_UnexposedDecl:
3900 case CXCursor_UnexposedExpr:
3901 case CXCursor_UnexposedStmt:
3902 case CXCursor_UnexposedAttr:
3903 return true;
3904 default:
3905 return false;
3906 }
3907}
3908
3909CXCursorKind clang_getCursorKind(CXCursor C) {
3910 return C.kind;
3911}
3912
3913CXSourceLocation clang_getCursorLocation(CXCursor C) {
3914 if (clang_isReference(C.kind)) {
3915 switch (C.kind) {
3916 case CXCursor_ObjCSuperClassRef: {
3917 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3918 = getCursorObjCSuperClassRef(C);
3919 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3920 }
3921
3922 case CXCursor_ObjCProtocolRef: {
3923 std::pair<ObjCProtocolDecl *, SourceLocation> P
3924 = getCursorObjCProtocolRef(C);
3925 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3926 }
3927
3928 case CXCursor_ObjCClassRef: {
3929 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3930 = getCursorObjCClassRef(C);
3931 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3932 }
3933
3934 case CXCursor_TypeRef: {
3935 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
3936 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3937 }
3938
3939 case CXCursor_TemplateRef: {
3940 std::pair<TemplateDecl *, SourceLocation> P = getCursorTemplateRef(C);
3941 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3942 }
3943
3944 case CXCursor_NamespaceRef: {
3945 std::pair<NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
3946 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3947 }
3948
3949 case CXCursor_MemberRef: {
3950 std::pair<FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
3951 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3952 }
3953
3954 case CXCursor_VariableRef: {
3955 std::pair<VarDecl *, SourceLocation> P = getCursorVariableRef(C);
3956 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3957 }
3958
3959 case CXCursor_CXXBaseSpecifier: {
3960 CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
3961 if (!BaseSpec)
3962 return clang_getNullLocation();
3963
3964 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
3965 return cxloc::translateSourceLocation(getCursorContext(C),
3966 TSInfo->getTypeLoc().getBeginLoc());
3967
3968 return cxloc::translateSourceLocation(getCursorContext(C),
3969 BaseSpec->getLocStart());
3970 }
3971
3972 case CXCursor_LabelRef: {
3973 std::pair<LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
3974 return cxloc::translateSourceLocation(getCursorContext(C), P.second);
3975 }
3976
3977 case CXCursor_OverloadedDeclRef:
3978 return cxloc::translateSourceLocation(getCursorContext(C),
3979 getCursorOverloadedDeclRef(C).second);
3980
3981 default:
3982 // FIXME: Need a way to enumerate all non-reference cases.
3983 llvm_unreachable("Missed a reference kind");
3984 }
3985 }
3986
3987 if (clang_isExpression(C.kind))
3988 return cxloc::translateSourceLocation(getCursorContext(C),
3989 getLocationFromExpr(getCursorExpr(C)));
3990
3991 if (clang_isStatement(C.kind))
3992 return cxloc::translateSourceLocation(getCursorContext(C),
3993 getCursorStmt(C)->getLocStart());
3994
3995 if (C.kind == CXCursor_PreprocessingDirective) {
3996 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
3997 return cxloc::translateSourceLocation(getCursorContext(C), L);
3998 }
3999
4000 if (C.kind == CXCursor_MacroExpansion) {
4001 SourceLocation L
4002 = cxcursor::getCursorMacroExpansion(C)->getSourceRange().getBegin();
4003 return cxloc::translateSourceLocation(getCursorContext(C), L);
4004 }
4005
4006 if (C.kind == CXCursor_MacroDefinition) {
4007 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
4008 return cxloc::translateSourceLocation(getCursorContext(C), L);
4009 }
4010
4011 if (C.kind == CXCursor_InclusionDirective) {
4012 SourceLocation L
4013 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
4014 return cxloc::translateSourceLocation(getCursorContext(C), L);
4015 }
4016
4017 if (!clang_isDeclaration(C.kind))
4018 return clang_getNullLocation();
4019
4020 Decl *D = getCursorDecl(C);
4021 if (!D)
4022 return clang_getNullLocation();
4023
4024 SourceLocation Loc = D->getLocation();
4025 // FIXME: Multiple variables declared in a single declaration
4026 // currently lack the information needed to correctly determine their
4027 // ranges when accounting for the type-specifier. We use context
4028 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
4029 // and if so, whether it is the first decl.
4030 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
4031 if (!cxcursor::isFirstInDeclGroup(C))
4032 Loc = VD->getLocation();
4033 }
4034
4035 // For ObjC methods, give the start location of the method name.
4036 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
4037 Loc = MD->getSelectorStartLoc();
4038
4039 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
4040}
4041
4042} // end extern "C"
4043
4044CXCursor cxcursor::getCursor(CXTranslationUnit TU, SourceLocation SLoc) {
4045 assert(TU);
4046
4047 // Guard against an invalid SourceLocation, or we may assert in one
4048 // of the following calls.
4049 if (SLoc.isInvalid())
4050 return clang_getNullCursor();
4051
4052 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
4053
4054 // Translate the given source location to make it point at the beginning of
4055 // the token under the cursor.
4056 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
4057 CXXUnit->getASTContext().getLangOpts());
4058
4059 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
4060 if (SLoc.isValid()) {
4061 GetCursorData ResultData(CXXUnit->getSourceManager(), SLoc, Result);
4062 CursorVisitor CursorVis(TU, GetCursorVisitor, &ResultData,
4063 /*VisitPreprocessorLast=*/true,
4064 /*VisitIncludedEntities=*/false,
4065 SourceLocation(SLoc));
4066 CursorVis.visitFileRegion();
4067 }
4068
4069 return Result;
4070}
4071
4072static SourceRange getRawCursorExtent(CXCursor C) {
4073 if (clang_isReference(C.kind)) {
4074 switch (C.kind) {
4075 case CXCursor_ObjCSuperClassRef:
4076 return getCursorObjCSuperClassRef(C).second;
4077
4078 case CXCursor_ObjCProtocolRef:
4079 return getCursorObjCProtocolRef(C).second;
4080
4081 case CXCursor_ObjCClassRef:
4082 return getCursorObjCClassRef(C).second;
4083
4084 case CXCursor_TypeRef:
4085 return getCursorTypeRef(C).second;
4086
4087 case CXCursor_TemplateRef:
4088 return getCursorTemplateRef(C).second;
4089
4090 case CXCursor_NamespaceRef:
4091 return getCursorNamespaceRef(C).second;
4092
4093 case CXCursor_MemberRef:
4094 return getCursorMemberRef(C).second;
4095
4096 case CXCursor_CXXBaseSpecifier:
4097 return getCursorCXXBaseSpecifier(C)->getSourceRange();
4098
4099 case CXCursor_LabelRef:
4100 return getCursorLabelRef(C).second;
4101
4102 case CXCursor_OverloadedDeclRef:
4103 return getCursorOverloadedDeclRef(C).second;
4104
4105 case CXCursor_VariableRef:
4106 return getCursorVariableRef(C).second;
4107
4108 default:
4109 // FIXME: Need a way to enumerate all non-reference cases.
4110 llvm_unreachable("Missed a reference kind");
4111 }
4112 }
4113
4114 if (clang_isExpression(C.kind))
4115 return getCursorExpr(C)->getSourceRange();
4116
4117 if (clang_isStatement(C.kind))
4118 return getCursorStmt(C)->getSourceRange();
4119
4120 if (clang_isAttribute(C.kind))
4121 return getCursorAttr(C)->getRange();
4122
4123 if (C.kind == CXCursor_PreprocessingDirective)
4124 return cxcursor::getCursorPreprocessingDirective(C);
4125
4126 if (C.kind == CXCursor_MacroExpansion) {
4127 ASTUnit *TU = getCursorASTUnit(C);
4128 SourceRange Range = cxcursor::getCursorMacroExpansion(C)->getSourceRange();
4129 return TU->mapRangeFromPreamble(Range);
4130 }
4131
4132 if (C.kind == CXCursor_MacroDefinition) {
4133 ASTUnit *TU = getCursorASTUnit(C);
4134 SourceRange Range = cxcursor::getCursorMacroDefinition(C)->getSourceRange();
4135 return TU->mapRangeFromPreamble(Range);
4136 }
4137
4138 if (C.kind == CXCursor_InclusionDirective) {
4139 ASTUnit *TU = getCursorASTUnit(C);
4140 SourceRange Range = cxcursor::getCursorInclusionDirective(C)->getSourceRange();
4141 return TU->mapRangeFromPreamble(Range);
4142 }
4143
4144 if (C.kind == CXCursor_TranslationUnit) {
4145 ASTUnit *TU = getCursorASTUnit(C);
4146 FileID MainID = TU->getSourceManager().getMainFileID();
4147 SourceLocation Start = TU->getSourceManager().getLocForStartOfFile(MainID);
4148 SourceLocation End = TU->getSourceManager().getLocForEndOfFile(MainID);
4149 return SourceRange(Start, End);
4150 }
4151
4152 if (clang_isDeclaration(C.kind)) {
4153 Decl *D = cxcursor::getCursorDecl(C);
4154 if (!D)
4155 return SourceRange();
4156
4157 SourceRange R = D->getSourceRange();
4158 // FIXME: Multiple variables declared in a single declaration
4159 // currently lack the information needed to correctly determine their
4160 // ranges when accounting for the type-specifier. We use context
4161 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
4162 // and if so, whether it is the first decl.
4163 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
4164 if (!cxcursor::isFirstInDeclGroup(C))
4165 R.setBegin(VD->getLocation());
4166 }
4167 return R;
4168 }
4169 return SourceRange();
4170}
4171
4172/// \brief Retrieves the "raw" cursor extent, which is then extended to include
4173/// the decl-specifier-seq for declarations.
4174static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr) {
4175 if (clang_isDeclaration(C.kind)) {
4176 Decl *D = cxcursor::getCursorDecl(C);
4177 if (!D)
4178 return SourceRange();
4179
4180 SourceRange R = D->getSourceRange();
4181
4182 // Adjust the start of the location for declarations preceded by
4183 // declaration specifiers.
4184 SourceLocation StartLoc;
4185 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
4186 if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
4187 StartLoc = TI->getTypeLoc().getLocStart();
4188 } else if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) {
4189 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
4190 StartLoc = TI->getTypeLoc().getLocStart();
4191 }
4192
4193 if (StartLoc.isValid() && R.getBegin().isValid() &&
4194 SrcMgr.isBeforeInTranslationUnit(StartLoc, R.getBegin()))
4195 R.setBegin(StartLoc);
4196
4197 // FIXME: Multiple variables declared in a single declaration
4198 // currently lack the information needed to correctly determine their
4199 // ranges when accounting for the type-specifier. We use context
4200 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
4201 // and if so, whether it is the first decl.
4202 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
4203 if (!cxcursor::isFirstInDeclGroup(C))
4204 R.setBegin(VD->getLocation());
4205 }
4206
4207 return R;
4208 }
4209
4210 return getRawCursorExtent(C);
4211}
4212
4213extern "C" {
4214
4215CXSourceRange clang_getCursorExtent(CXCursor C) {
4216 SourceRange R = getRawCursorExtent(C);
4217 if (R.isInvalid())
4218 return clang_getNullRange();
4219
4220 return cxloc::translateSourceRange(getCursorContext(C), R);
4221}
4222
4223CXCursor clang_getCursorReferenced(CXCursor C) {
4224 if (clang_isInvalid(C.kind))
4225 return clang_getNullCursor();
4226
4227 CXTranslationUnit tu = getCursorTU(C);
4228 if (clang_isDeclaration(C.kind)) {
4229 Decl *D = getCursorDecl(C);
4230 if (!D)
4231 return clang_getNullCursor();
4232 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
4233 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), tu);
4234 if (ObjCPropertyImplDecl *PropImpl =dyn_cast<ObjCPropertyImplDecl>(D))
4235 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
4236 return MakeCXCursor(Property, tu);
4237
4238 return C;
4239 }
4240
4241 if (clang_isExpression(C.kind)) {
4242 Expr *E = getCursorExpr(C);
4243 Decl *D = getDeclFromExpr(E);
4244 if (D) {
4245 CXCursor declCursor = MakeCXCursor(D, tu);
4246 declCursor = getSelectorIdentifierCursor(getSelectorIdentifierIndex(C),
4247 declCursor);
4248 return declCursor;
4249 }
4250
4251 if (OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
4252 return MakeCursorOverloadedDeclRef(Ovl, tu);
4253
4254 return clang_getNullCursor();
4255 }
4256
4257 if (clang_isStatement(C.kind)) {
4258 Stmt *S = getCursorStmt(C);
4259 if (GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
4260 if (LabelDecl *label = Goto->getLabel())
4261 if (LabelStmt *labelS = label->getStmt())
4262 return MakeCXCursor(labelS, getCursorDecl(C), tu);
4263
4264 return clang_getNullCursor();
4265 }
4266
4267 if (C.kind == CXCursor_MacroExpansion) {
4268 if (MacroDefinition *Def = getCursorMacroExpansion(C)->getDefinition())
4269 return MakeMacroDefinitionCursor(Def, tu);
4270 }
4271
4272 if (!clang_isReference(C.kind))
4273 return clang_getNullCursor();
4274
4275 switch (C.kind) {
4276 case CXCursor_ObjCSuperClassRef:
4277 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, tu);
4278
4279 case CXCursor_ObjCProtocolRef: {
4280 ObjCProtocolDecl *Prot = getCursorObjCProtocolRef(C).first;
4281 if (ObjCProtocolDecl *Def = Prot->getDefinition())
4282 return MakeCXCursor(Def, tu);
4283
4284 return MakeCXCursor(Prot, tu);
4285 }
4286
4287 case CXCursor_ObjCClassRef: {
4288 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
4289 if (ObjCInterfaceDecl *Def = Class->getDefinition())
4290 return MakeCXCursor(Def, tu);
4291
4292 return MakeCXCursor(Class, tu);
4293 }
4294
4295 case CXCursor_TypeRef:
4296 return MakeCXCursor(getCursorTypeRef(C).first, tu );
4297
4298 case CXCursor_TemplateRef:
4299 return MakeCXCursor(getCursorTemplateRef(C).first, tu );
4300
4301 case CXCursor_NamespaceRef:
4302 return MakeCXCursor(getCursorNamespaceRef(C).first, tu );
4303
4304 case CXCursor_MemberRef:
4305 return MakeCXCursor(getCursorMemberRef(C).first, tu );
4306
4307 case CXCursor_CXXBaseSpecifier: {
4308 CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
4309 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
4310 tu ));
4311 }
4312
4313 case CXCursor_LabelRef:
4314 // FIXME: We end up faking the "parent" declaration here because we
4315 // don't want to make CXCursor larger.
4316 return MakeCXCursor(getCursorLabelRef(C).first,
4317 static_cast<ASTUnit*>(tu->TUData)->getASTContext()
4318 .getTranslationUnitDecl(),
4319 tu);
4320
4321 case CXCursor_OverloadedDeclRef:
4322 return C;
4323
4324 case CXCursor_VariableRef:
4325 return MakeCXCursor(getCursorVariableRef(C).first, tu);
4326
4327 default:
4328 // We would prefer to enumerate all non-reference cursor kinds here.
4329 llvm_unreachable("Unhandled reference cursor kind");
4330 }
4331}
4332
4333CXCursor clang_getCursorDefinition(CXCursor C) {
4334 if (clang_isInvalid(C.kind))
4335 return clang_getNullCursor();
4336
4337 CXTranslationUnit TU = getCursorTU(C);
4338
4339 bool WasReference = false;
4340 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
4341 C = clang_getCursorReferenced(C);
4342 WasReference = true;
4343 }
4344
4345 if (C.kind == CXCursor_MacroExpansion)
4346 return clang_getCursorReferenced(C);
4347
4348 if (!clang_isDeclaration(C.kind))
4349 return clang_getNullCursor();
4350
4351 Decl *D = getCursorDecl(C);
4352 if (!D)
4353 return clang_getNullCursor();
4354
4355 switch (D->getKind()) {
4356 // Declaration kinds that don't really separate the notions of
4357 // declaration and definition.
4358 case Decl::Namespace:
4359 case Decl::Typedef:
4360 case Decl::TypeAlias:
4361 case Decl::TypeAliasTemplate:
4362 case Decl::TemplateTypeParm:
4363 case Decl::EnumConstant:
4364 case Decl::Field:
4365 case Decl::IndirectField:
4366 case Decl::ObjCIvar:
4367 case Decl::ObjCAtDefsField:
4368 case Decl::ImplicitParam:
4369 case Decl::ParmVar:
4370 case Decl::NonTypeTemplateParm:
4371 case Decl::TemplateTemplateParm:
4372 case Decl::ObjCCategoryImpl:
4373 case Decl::ObjCImplementation:
4374 case Decl::AccessSpec:
4375 case Decl::LinkageSpec:
4376 case Decl::ObjCPropertyImpl:
4377 case Decl::FileScopeAsm:
4378 case Decl::StaticAssert:
4379 case Decl::Block:
4380 case Decl::Label: // FIXME: Is this right??
4381 case Decl::ClassScopeFunctionSpecialization:
4382 case Decl::Import:
4383 return C;
4384
4385 // Declaration kinds that don't make any sense here, but are
4386 // nonetheless harmless.
4387 case Decl::TranslationUnit:
4388 break;
4389
4390 // Declaration kinds for which the definition is not resolvable.
4391 case Decl::UnresolvedUsingTypename:
4392 case Decl::UnresolvedUsingValue:
4393 break;
4394
4395 case Decl::UsingDirective:
4396 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
4397 TU);
4398
4399 case Decl::NamespaceAlias:
4400 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), TU);
4401
4402 case Decl::Enum:
4403 case Decl::Record:
4404 case Decl::CXXRecord:
4405 case Decl::ClassTemplateSpecialization:
4406 case Decl::ClassTemplatePartialSpecialization:
4407 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
4408 return MakeCXCursor(Def, TU);
4409 return clang_getNullCursor();
4410
4411 case Decl::Function:
4412 case Decl::CXXMethod:
4413 case Decl::CXXConstructor:
4414 case Decl::CXXDestructor:
4415 case Decl::CXXConversion: {
4416 const FunctionDecl *Def = 0;
4417 if (cast<FunctionDecl>(D)->getBody(Def))
4418 return MakeCXCursor(const_cast<FunctionDecl *>(Def), TU);
4419 return clang_getNullCursor();
4420 }
4421
4422 case Decl::Var: {
4423 // Ask the variable if it has a definition.
4424 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
4425 return MakeCXCursor(Def, TU);
4426 return clang_getNullCursor();
4427 }
4428
4429 case Decl::FunctionTemplate: {
4430 const FunctionDecl *Def = 0;
4431 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
4432 return MakeCXCursor(Def->getDescribedFunctionTemplate(), TU);
4433 return clang_getNullCursor();
4434 }
4435
4436 case Decl::ClassTemplate: {
4437 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
4438 ->getDefinition())
4439 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
4440 TU);
4441 return clang_getNullCursor();
4442 }
4443
4444 case Decl::Using:
4445 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
4446 D->getLocation(), TU);
4447
4448 case Decl::UsingShadow:
4449 return clang_getCursorDefinition(
4450 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
4451 TU));
4452
4453 case Decl::ObjCMethod: {
4454 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
4455 if (Method->isThisDeclarationADefinition())
4456 return C;
4457
4458 // Dig out the method definition in the associated
4459 // @implementation, if we have it.
4460 // FIXME: The ASTs should make finding the definition easier.
4461 if (ObjCInterfaceDecl *Class
4462 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
4463 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
4464 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
4465 Method->isInstanceMethod()))
4466 if (Def->isThisDeclarationADefinition())
4467 return MakeCXCursor(Def, TU);
4468
4469 return clang_getNullCursor();
4470 }
4471
4472 case Decl::ObjCCategory:
4473 if (ObjCCategoryImplDecl *Impl
4474 = cast<ObjCCategoryDecl>(D)->getImplementation())
4475 return MakeCXCursor(Impl, TU);
4476 return clang_getNullCursor();
4477
4478 case Decl::ObjCProtocol:
4479 if (ObjCProtocolDecl *Def = cast<ObjCProtocolDecl>(D)->getDefinition())
4480 return MakeCXCursor(Def, TU);
4481 return clang_getNullCursor();
4482
4483 case Decl::ObjCInterface: {
4484 // There are two notions of a "definition" for an Objective-C
4485 // class: the interface and its implementation. When we resolved a
4486 // reference to an Objective-C class, produce the @interface as
4487 // the definition; when we were provided with the interface,
4488 // produce the @implementation as the definition.
4489 ObjCInterfaceDecl *IFace = cast<ObjCInterfaceDecl>(D);
4490 if (WasReference) {
4491 if (ObjCInterfaceDecl *Def = IFace->getDefinition())
4492 return MakeCXCursor(Def, TU);
4493 } else if (ObjCImplementationDecl *Impl = IFace->getImplementation())
4494 return MakeCXCursor(Impl, TU);
4495 return clang_getNullCursor();
4496 }
4497
4498 case Decl::ObjCProperty:
4499 // FIXME: We don't really know where to find the
4500 // ObjCPropertyImplDecls that implement this property.
4501 return clang_getNullCursor();
4502
4503 case Decl::ObjCCompatibleAlias:
4504 if (ObjCInterfaceDecl *Class
4505 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
4506 if (ObjCInterfaceDecl *Def = Class->getDefinition())
4507 return MakeCXCursor(Def, TU);
4508
4509 return clang_getNullCursor();
4510
4511 case Decl::Friend:
4512 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
4513 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
4514 return clang_getNullCursor();
4515
4516 case Decl::FriendTemplate:
4517 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
4518 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
4519 return clang_getNullCursor();
4520 }
4521
4522 return clang_getNullCursor();
4523}
4524
4525unsigned clang_isCursorDefinition(CXCursor C) {
4526 if (!clang_isDeclaration(C.kind))
4527 return 0;
4528
4529 return clang_getCursorDefinition(C) == C;
4530}
4531
4532CXCursor clang_getCanonicalCursor(CXCursor C) {
4533 if (!clang_isDeclaration(C.kind))
4534 return C;
4535
4536 if (Decl *D = getCursorDecl(C)) {
4537 if (ObjCCategoryImplDecl *CatImplD = dyn_cast<ObjCCategoryImplDecl>(D))
4538 if (ObjCCategoryDecl *CatD = CatImplD->getCategoryDecl())
4539 return MakeCXCursor(CatD, getCursorTU(C));
4540
4541 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
4542 if (ObjCInterfaceDecl *IFD = ImplD->getClassInterface())
4543 return MakeCXCursor(IFD, getCursorTU(C));
4544
4545 return MakeCXCursor(D->getCanonicalDecl(), getCursorTU(C));
4546 }
4547
4548 return C;
4549}
4550
4551int clang_Cursor_getObjCSelectorIndex(CXCursor cursor) {
4552 return cxcursor::getSelectorIdentifierIndexAndLoc(cursor).first;
4553}
4554
4555unsigned clang_getNumOverloadedDecls(CXCursor C) {
4556 if (C.kind != CXCursor_OverloadedDeclRef)
4557 return 0;
4558
4559 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
4560 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
4561 return E->getNumDecls();
4562
4563 if (OverloadedTemplateStorage *S
4564 = Storage.dyn_cast<OverloadedTemplateStorage*>())
4565 return S->size();
4566
4567 Decl *D = Storage.get<Decl*>();
4568 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
4569 return Using->shadow_size();
4570
4571 return 0;
4572}
4573
4574CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
4575 if (cursor.kind != CXCursor_OverloadedDeclRef)
4576 return clang_getNullCursor();
4577
4578 if (index >= clang_getNumOverloadedDecls(cursor))
4579 return clang_getNullCursor();
4580
4581 CXTranslationUnit TU = getCursorTU(cursor);
4582 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
4583 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
4584 return MakeCXCursor(E->decls_begin()[index], TU);
4585
4586 if (OverloadedTemplateStorage *S
4587 = Storage.dyn_cast<OverloadedTemplateStorage*>())
4588 return MakeCXCursor(S->begin()[index], TU);
4589
4590 Decl *D = Storage.get<Decl*>();
4591 if (UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
4592 // FIXME: This is, unfortunately, linear time.
4593 UsingDecl::shadow_iterator Pos = Using->shadow_begin();
4594 std::advance(Pos, index);
4595 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), TU);
4596 }
4597
4598 return clang_getNullCursor();
4599}
4600
4601void clang_getDefinitionSpellingAndExtent(CXCursor C,
4602 const char **startBuf,
4603 const char **endBuf,
4604 unsigned *startLine,
4605 unsigned *startColumn,
4606 unsigned *endLine,
4607 unsigned *endColumn) {
4608 assert(getCursorDecl(C) && "CXCursor has null decl");
4609 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
4610 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
4611 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
4612
4613 SourceManager &SM = FD->getASTContext().getSourceManager();
4614 *startBuf = SM.getCharacterData(Body->getLBracLoc());
4615 *endBuf = SM.getCharacterData(Body->getRBracLoc());
4616 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
4617 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
4618 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
4619 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
4620}
4621
4622
4623CXSourceRange clang_getCursorReferenceNameRange(CXCursor C, unsigned NameFlags,
4624 unsigned PieceIndex) {
4625 RefNamePieces Pieces;
4626
4627 switch (C.kind) {
4628 case CXCursor_MemberRefExpr:
4629 if (MemberExpr *E = dyn_cast<MemberExpr>(getCursorExpr(C)))
4630 Pieces = buildPieces(NameFlags, true, E->getMemberNameInfo(),
4631 E->getQualifierLoc().getSourceRange());
4632 break;
4633
4634 case CXCursor_DeclRefExpr:
4635 if (DeclRefExpr *E = dyn_cast<DeclRefExpr>(getCursorExpr(C)))
4636 Pieces = buildPieces(NameFlags, false, E->getNameInfo(),
4637 E->getQualifierLoc().getSourceRange(),
4638 E->getOptionalExplicitTemplateArgs());
4639 break;
4640
4641 case CXCursor_CallExpr:
4642 if (CXXOperatorCallExpr *OCE =
4643 dyn_cast<CXXOperatorCallExpr>(getCursorExpr(C))) {
4644 Expr *Callee = OCE->getCallee();
4645 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Callee))
4646 Callee = ICE->getSubExpr();
4647
4648 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Callee))
4649 Pieces = buildPieces(NameFlags, false, DRE->getNameInfo(),
4650 DRE->getQualifierLoc().getSourceRange());
4651 }
4652 break;
4653
4654 default:
4655 break;
4656 }
4657
4658 if (Pieces.empty()) {
4659 if (PieceIndex == 0)
4660 return clang_getCursorExtent(C);
4661 } else if (PieceIndex < Pieces.size()) {
4662 SourceRange R = Pieces[PieceIndex];
4663 if (R.isValid())
4664 return cxloc::translateSourceRange(getCursorContext(C), R);
4665 }
4666
4667 return clang_getNullRange();
4668}
4669
4670void clang_enableStackTraces(void) {
4671 llvm::sys::PrintStackTraceOnErrorSignal();
4672}
4673
4674void clang_executeOnThread(void (*fn)(void*), void *user_data,
4675 unsigned stack_size) {
4676 llvm::llvm_execute_on_thread(fn, user_data, stack_size);
4677}
4678
4679} // end: extern "C"
4680
4681//===----------------------------------------------------------------------===//
4682// Token-based Operations.
4683//===----------------------------------------------------------------------===//
4684
4685/* CXToken layout:
4686 * int_data[0]: a CXTokenKind
4687 * int_data[1]: starting token location
4688 * int_data[2]: token length
4689 * int_data[3]: reserved
4690 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
4691 * otherwise unused.
4692 */
4693extern "C" {
4694
4695CXTokenKind clang_getTokenKind(CXToken CXTok) {
4696 return static_cast<CXTokenKind>(CXTok.int_data[0]);
4697}
4698
4699CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
4700 switch (clang_getTokenKind(CXTok)) {
4701 case CXToken_Identifier:
4702 case CXToken_Keyword:
4703 // We know we have an IdentifierInfo*, so use that.
4704 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
4705 ->getNameStart());
4706
4707 case CXToken_Literal: {
4708 // We have stashed the starting pointer in the ptr_data field. Use it.
4709 const char *Text = static_cast<const char *>(CXTok.ptr_data);
4710 return createCXString(StringRef(Text, CXTok.int_data[2]));
4711 }
4712
4713 case CXToken_Punctuation:
4714 case CXToken_Comment:
4715 break;
4716 }
4717
4718 // We have to find the starting buffer pointer the hard way, by
4719 // deconstructing the source location.
4720 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
4721 if (!CXXUnit)
4722 return createCXString("");
4723
4724 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
4725 std::pair<FileID, unsigned> LocInfo
4726 = CXXUnit->getSourceManager().getDecomposedSpellingLoc(Loc);
4727 bool Invalid = false;
4728 StringRef Buffer
4729 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
4730 if (Invalid)
4731 return createCXString("");
4732
4733 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
4734}
4735
4736CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
4737 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
4738 if (!CXXUnit)
4739 return clang_getNullLocation();
4740
4741 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
4742 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
4743}
4744
4745CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
4746 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
4747 if (!CXXUnit)
4748 return clang_getNullRange();
4749
4750 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
4751 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
4752}
4753
4754static void getTokens(ASTUnit *CXXUnit, SourceRange Range,
4755 SmallVectorImpl<CXToken> &CXTokens) {
4756 SourceManager &SourceMgr = CXXUnit->getSourceManager();
4757 std::pair<FileID, unsigned> BeginLocInfo
4758 = SourceMgr.getDecomposedLoc(Range.getBegin());
4759 std::pair<FileID, unsigned> EndLocInfo
4760 = SourceMgr.getDecomposedLoc(Range.getEnd());
4761
4762 // Cannot tokenize across files.
4763 if (BeginLocInfo.first != EndLocInfo.first)
4764 return;
4765
4766 // Create a lexer
4767 bool Invalid = false;
4768 StringRef Buffer
4769 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
4770 if (Invalid)
4771 return;
4772
4773 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
4774 CXXUnit->getASTContext().getLangOpts(),
4775 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
4776 Lex.SetCommentRetentionState(true);
4777
4778 // Lex tokens until we hit the end of the range.
4779 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
4780 Token Tok;
4781 bool previousWasAt = false;
4782 do {
4783 // Lex the next token
4784 Lex.LexFromRawLexer(Tok);
4785 if (Tok.is(tok::eof))
4786 break;
4787
4788 // Initialize the CXToken.
4789 CXToken CXTok;
4790
4791 // - Common fields
4792 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
4793 CXTok.int_data[2] = Tok.getLength();
4794 CXTok.int_data[3] = 0;
4795
4796 // - Kind-specific fields
4797 if (Tok.isLiteral()) {
4798 CXTok.int_data[0] = CXToken_Literal;
4799 CXTok.ptr_data = (void *)Tok.getLiteralData();
4800 } else if (Tok.is(tok::raw_identifier)) {
4801 // Lookup the identifier to determine whether we have a keyword.
4802 IdentifierInfo *II
4803 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok);
4804
4805 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
4806 CXTok.int_data[0] = CXToken_Keyword;
4807 }
4808 else {
4809 CXTok.int_data[0] = Tok.is(tok::identifier)
4810 ? CXToken_Identifier
4811 : CXToken_Keyword;
4812 }
4813 CXTok.ptr_data = II;
4814 } else if (Tok.is(tok::comment)) {
4815 CXTok.int_data[0] = CXToken_Comment;
4816 CXTok.ptr_data = 0;
4817 } else {
4818 CXTok.int_data[0] = CXToken_Punctuation;
4819 CXTok.ptr_data = 0;
4820 }
4821 CXTokens.push_back(CXTok);
4822 previousWasAt = Tok.is(tok::at);
4823 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
4824}
4825
4826void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
4827 CXToken **Tokens, unsigned *NumTokens) {
4828 if (Tokens)
4829 *Tokens = 0;
4830 if (NumTokens)
4831 *NumTokens = 0;
4832
4833 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
4834 if (!CXXUnit || !Tokens || !NumTokens)
4835 return;
4836
4837 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
4838
4839 SourceRange R = cxloc::translateCXSourceRange(Range);
4840 if (R.isInvalid())
4841 return;
4842
4843 SmallVector<CXToken, 32> CXTokens;
4844 getTokens(CXXUnit, R, CXTokens);
4845
4846 if (CXTokens.empty())
4847 return;
4848
4849 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
4850 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
4851 *NumTokens = CXTokens.size();
4852}
4853
4854void clang_disposeTokens(CXTranslationUnit TU,
4855 CXToken *Tokens, unsigned NumTokens) {
4856 free(Tokens);
4857}
4858
4859} // end: extern "C"
4860
4861//===----------------------------------------------------------------------===//
4862// Token annotation APIs.
4863//===----------------------------------------------------------------------===//
4864
4865typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
4866static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
4867 CXCursor parent,
4868 CXClientData client_data);
4869static bool AnnotateTokensPostChildrenVisitor(CXCursor cursor,
4870 CXClientData client_data);
4871
4872namespace {
4873class AnnotateTokensWorker {
4874 AnnotateTokensData &Annotated;
4875 CXToken *Tokens;
4876 CXCursor *Cursors;
4877 unsigned NumTokens;
4878 unsigned TokIdx;
4879 unsigned PreprocessingTokIdx;
4880 CursorVisitor AnnotateVis;
4881 SourceManager &SrcMgr;
4882 bool HasContextSensitiveKeywords;
4883
4884 struct PostChildrenInfo {
4885 CXCursor Cursor;
4886 SourceRange CursorRange;
4887 unsigned BeforeChildrenTokenIdx;
4888 };
4889 llvm::SmallVector<PostChildrenInfo, 8> PostChildrenInfos;
4890
4891 bool MoreTokens() const { return TokIdx < NumTokens; }
4892 unsigned NextToken() const { return TokIdx; }
4893 void AdvanceToken() { ++TokIdx; }
4894 SourceLocation GetTokenLoc(unsigned tokI) {
4895 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
4896 }
4897 bool isFunctionMacroToken(unsigned tokI) const {
4898 return Tokens[tokI].int_data[3] != 0;
4899 }
4900 SourceLocation getFunctionMacroTokenLoc(unsigned tokI) const {
4901 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[3]);
4902 }
4903
4904 void annotateAndAdvanceTokens(CXCursor, RangeComparisonResult, SourceRange);
4905 void annotateAndAdvanceFunctionMacroTokens(CXCursor, RangeComparisonResult,
4906 SourceRange);
4907
4908public:
4909 AnnotateTokensWorker(AnnotateTokensData &annotated,
4910 CXToken *tokens, CXCursor *cursors, unsigned numTokens,
4911 CXTranslationUnit tu, SourceRange RegionOfInterest)
4912 : Annotated(annotated), Tokens(tokens), Cursors(cursors),
4913 NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
4914 AnnotateVis(tu,
4915 AnnotateTokensVisitor, this,
4916 /*VisitPreprocessorLast=*/true,
4917 /*VisitIncludedEntities=*/false,
4918 RegionOfInterest,
4919 /*VisitDeclsOnly=*/false,
4920 AnnotateTokensPostChildrenVisitor),
4921 SrcMgr(static_cast<ASTUnit*>(tu->TUData)->getSourceManager()),
4922 HasContextSensitiveKeywords(false) { }
4923
4924 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
4925 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
4926 bool postVisitChildren(CXCursor cursor);
4927 void AnnotateTokens();
4928
4929 /// \brief Determine whether the annotator saw any cursors that have
4930 /// context-sensitive keywords.
4931 bool hasContextSensitiveKeywords() const {
4932 return HasContextSensitiveKeywords;
4933 }
4934
4935 ~AnnotateTokensWorker() {
4936 assert(PostChildrenInfos.empty());
4937 }
4938};
4939}
4940
4941void AnnotateTokensWorker::AnnotateTokens() {
4942 // Walk the AST within the region of interest, annotating tokens
4943 // along the way.
4944 AnnotateVis.visitFileRegion();
4945
4946 for (unsigned I = 0 ; I < TokIdx ; ++I) {
4947 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
4948 if (Pos != Annotated.end() && !clang_isPreprocessing(Cursors[I].kind))
4949 Cursors[I] = Pos->second;
4950 }
4951
4952 // Finish up annotating any tokens left.
4953 if (!MoreTokens())
4954 return;
4955
4956 const CXCursor &C = clang_getNullCursor();
4957 for (unsigned I = TokIdx ; I < NumTokens ; ++I) {
4958 if (I < PreprocessingTokIdx && clang_isPreprocessing(Cursors[I].kind))
4959 continue;
4960
4961 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
4962 Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second;
4963 }
4964}
4965
4966/// \brief It annotates and advances tokens with a cursor until the comparison
4967//// between the cursor location and the source range is the same as
4968/// \arg compResult.
4969///
4970/// Pass RangeBefore to annotate tokens with a cursor until a range is reached.
4971/// Pass RangeOverlap to annotate tokens inside a range.
4972void AnnotateTokensWorker::annotateAndAdvanceTokens(CXCursor updateC,
4973 RangeComparisonResult compResult,
4974 SourceRange range) {
4975 while (MoreTokens()) {
4976 const unsigned I = NextToken();
4977 if (isFunctionMacroToken(I))
4978 return annotateAndAdvanceFunctionMacroTokens(updateC, compResult, range);
4979
4980 SourceLocation TokLoc = GetTokenLoc(I);
4981 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
4982 Cursors[I] = updateC;
4983 AdvanceToken();
4984 continue;
4985 }
4986 break;
4987 }
4988}
4989
4990/// \brief Special annotation handling for macro argument tokens.
4991void AnnotateTokensWorker::annotateAndAdvanceFunctionMacroTokens(
4992 CXCursor updateC,
4993 RangeComparisonResult compResult,
4994 SourceRange range) {
4995 assert(MoreTokens());
4996 assert(isFunctionMacroToken(NextToken()) &&
4997 "Should be called only for macro arg tokens");
4998
4999 // This works differently than annotateAndAdvanceTokens; because expanded
5000 // macro arguments can have arbitrary translation-unit source order, we do not
5001 // advance the token index one by one until a token fails the range test.
5002 // We only advance once past all of the macro arg tokens if all of them
5003 // pass the range test. If one of them fails we keep the token index pointing
5004 // at the start of the macro arg tokens so that the failing token will be
5005 // annotated by a subsequent annotation try.
5006
5007 bool atLeastOneCompFail = false;
5008
5009 unsigned I = NextToken();
5010 for (; I < NumTokens && isFunctionMacroToken(I); ++I) {
5011 SourceLocation TokLoc = getFunctionMacroTokenLoc(I);
5012 if (TokLoc.isFileID())
5013 continue; // not macro arg token, it's parens or comma.
5014 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
5015 if (clang_isInvalid(clang_getCursorKind(Cursors[I])))
5016 Cursors[I] = updateC;
5017 } else
5018 atLeastOneCompFail = true;
5019 }
5020
5021 if (!atLeastOneCompFail)
5022 TokIdx = I; // All of the tokens were handled, advance beyond all of them.
5023}
5024
5025enum CXChildVisitResult
5026AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
5027 CXSourceLocation Loc = clang_getCursorLocation(cursor);
5028 SourceRange cursorRange = getRawCursorExtent(cursor);
5029 if (cursorRange.isInvalid())
5030 return CXChildVisit_Recurse;
5031
5032 if (!HasContextSensitiveKeywords) {
5033 // Objective-C properties can have context-sensitive keywords.
5034 if (cursor.kind == CXCursor_ObjCPropertyDecl) {
5035 if (ObjCPropertyDecl *Property
5036 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(cursor)))
5037 HasContextSensitiveKeywords = Property->getPropertyAttributesAsWritten() != 0;
5038 }
5039 // Objective-C methods can have context-sensitive keywords.
5040 else if (cursor.kind == CXCursor_ObjCInstanceMethodDecl ||
5041 cursor.kind == CXCursor_ObjCClassMethodDecl) {
5042 if (ObjCMethodDecl *Method
5043 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
5044 if (Method->getObjCDeclQualifier())
5045 HasContextSensitiveKeywords = true;
5046 else {
5047 for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
5048 PEnd = Method->param_end();
5049 P != PEnd; ++P) {
5050 if ((*P)->getObjCDeclQualifier()) {
5051 HasContextSensitiveKeywords = true;
5052 break;
5053 }
5054 }
5055 }
5056 }
5057 }
5058 // C++ methods can have context-sensitive keywords.
5059 else if (cursor.kind == CXCursor_CXXMethod) {
5060 if (CXXMethodDecl *Method
5061 = dyn_cast_or_null<CXXMethodDecl>(getCursorDecl(cursor))) {
5062 if (Method->hasAttr<FinalAttr>() || Method->hasAttr<OverrideAttr>())
5063 HasContextSensitiveKeywords = true;
5064 }
5065 }
5066 // C++ classes can have context-sensitive keywords.
5067 else if (cursor.kind == CXCursor_StructDecl ||
5068 cursor.kind == CXCursor_ClassDecl ||
5069 cursor.kind == CXCursor_ClassTemplate ||
5070 cursor.kind == CXCursor_ClassTemplatePartialSpecialization) {
5071 if (Decl *D = getCursorDecl(cursor))
5072 if (D->hasAttr<FinalAttr>())
5073 HasContextSensitiveKeywords = true;
5074 }
5075 }
5076
5077 if (clang_isPreprocessing(cursor.kind)) {
5078 // Items in the preprocessing record are kept separate from items in
5079 // declarations, so we keep a separate token index.
5080 unsigned SavedTokIdx = TokIdx;
5081 TokIdx = PreprocessingTokIdx;
5082
5083 // Skip tokens up until we catch up to the beginning of the preprocessing
5084 // entry.
5085 while (MoreTokens()) {
5086 const unsigned I = NextToken();
5087 SourceLocation TokLoc = GetTokenLoc(I);
5088 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
5089 case RangeBefore:
5090 AdvanceToken();
5091 continue;
5092 case RangeAfter:
5093 case RangeOverlap:
5094 break;
5095 }
5096 break;
5097 }
5098
5099 // Look at all of the tokens within this range.
5100 while (MoreTokens()) {
5101 const unsigned I = NextToken();
5102 SourceLocation TokLoc = GetTokenLoc(I);
5103 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
5104 case RangeBefore:
5105 llvm_unreachable("Infeasible");
5106 case RangeAfter:
5107 break;
5108 case RangeOverlap:
5109 Cursors[I] = cursor;
5110 AdvanceToken();
5111 // For macro expansions, just note where the beginning of the macro
5112 // expansion occurs.
5113 if (cursor.kind == CXCursor_MacroExpansion)
5114 break;
5115 continue;
5116 }
5117 break;
5118 }
5119
5120 // Save the preprocessing token index; restore the non-preprocessing
5121 // token index.
5122 PreprocessingTokIdx = TokIdx;
5123 TokIdx = SavedTokIdx;
5124 return CXChildVisit_Recurse;
5125 }
5126
5127 if (cursorRange.isInvalid())
5128 return CXChildVisit_Continue;
5129
5130 SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data);
5131
5132 // Adjust the annotated range based specific declarations.
5133 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
5134 if (clang_isDeclaration(cursorK)) {
5135 Decl *D = cxcursor::getCursorDecl(cursor);
5136
5137 SourceLocation StartLoc;
5138 if (const DeclaratorDecl *DD = dyn_cast_or_null<DeclaratorDecl>(D)) {
5139 if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
5140 StartLoc = TI->getTypeLoc().getLocStart();
5141 } else if (TypedefDecl *Typedef = dyn_cast_or_null<TypedefDecl>(D)) {
5142 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
5143 StartLoc = TI->getTypeLoc().getLocStart();
5144 }
5145
5146 if (StartLoc.isValid() && L.isValid() &&
5147 SrcMgr.isBeforeInTranslationUnit(StartLoc, L))
5148 cursorRange.setBegin(StartLoc);
5149 }
5150
5151 // If the location of the cursor occurs within a macro instantiation, record
5152 // the spelling location of the cursor in our annotation map. We can then
5153 // paper over the token labelings during a post-processing step to try and
5154 // get cursor mappings for tokens that are the *arguments* of a macro
5155 // instantiation.
5156 if (L.isMacroID()) {
5157 unsigned rawEncoding = SrcMgr.getSpellingLoc(L).getRawEncoding();
5158 // Only invalidate the old annotation if it isn't part of a preprocessing
5159 // directive. Here we assume that the default construction of CXCursor
5160 // results in CXCursor.kind being an initialized value (i.e., 0). If
5161 // this isn't the case, we can fix by doing lookup + insertion.
5162
5163 CXCursor &oldC = Annotated[rawEncoding];
5164 if (!clang_isPreprocessing(oldC.kind))
5165 oldC = cursor;
5166 }
5167
5168 const enum CXCursorKind K = clang_getCursorKind(parent);
5169 const CXCursor updateC =
5170 (clang_isInvalid(K) || K == CXCursor_TranslationUnit)
5171 ? clang_getNullCursor() : parent;
5172
5173 annotateAndAdvanceTokens(updateC, RangeBefore, cursorRange);
5174
5175 // Avoid having the cursor of an expression "overwrite" the annotation of the
5176 // variable declaration that it belongs to.
5177 // This can happen for C++ constructor expressions whose range generally
5178 // include the variable declaration, e.g.:
5179 // MyCXXClass foo; // Make sure we don't annotate 'foo' as a CallExpr cursor.
5180 if (clang_isExpression(cursorK)) {
5181 Expr *E = getCursorExpr(cursor);
5182 if (Decl *D = getCursorParentDecl(cursor)) {
5183 const unsigned I = NextToken();
5184 if (E->getLocStart().isValid() && D->getLocation().isValid() &&
5185 E->getLocStart() == D->getLocation() &&
5186 E->getLocStart() == GetTokenLoc(I)) {
5187 Cursors[I] = updateC;
5188 AdvanceToken();
5189 }
5190 }
5191 }
5192
5193 // Before recursing into the children keep some state that we are going
5194 // to use in the AnnotateTokensWorker::postVisitChildren callback to do some
5195 // extra work after the child nodes are visited.
5196 // Note that we don't call VisitChildren here to avoid traversing statements
5197 // code-recursively which can blow the stack.
5198
5199 PostChildrenInfo Info;
5200 Info.Cursor = cursor;
5201 Info.CursorRange = cursorRange;
5202 Info.BeforeChildrenTokenIdx = NextToken();
5203 PostChildrenInfos.push_back(Info);
5204
5205 return CXChildVisit_Recurse;
5206}
5207
5208bool AnnotateTokensWorker::postVisitChildren(CXCursor cursor) {
5209 if (PostChildrenInfos.empty())
5210 return false;
5211 const PostChildrenInfo &Info = PostChildrenInfos.back();
5212 if (!clang_equalCursors(Info.Cursor, cursor))
5213 return false;
5214
5215 const unsigned BeforeChildren = Info.BeforeChildrenTokenIdx;
5216 const unsigned AfterChildren = NextToken();
5217 SourceRange cursorRange = Info.CursorRange;
5218
5219 // Scan the tokens that are at the end of the cursor, but are not captured
5220 // but the child cursors.
5221 annotateAndAdvanceTokens(cursor, RangeOverlap, cursorRange);
5222
5223 // Scan the tokens that are at the beginning of the cursor, but are not
5224 // capture by the child cursors.
5225 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
5226 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
5227 break;
5228
5229 Cursors[I] = cursor;
5230 }
5231
5232 PostChildrenInfos.pop_back();
5233 return false;
5234}
5235
5236static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
5237 CXCursor parent,
5238 CXClientData client_data) {
5239 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
5240}
5241
5242static bool AnnotateTokensPostChildrenVisitor(CXCursor cursor,
5243 CXClientData client_data) {
5244 return static_cast<AnnotateTokensWorker*>(client_data)->
5245 postVisitChildren(cursor);
5246}
5247
5248namespace {
5249
5250/// \brief Uses the macro expansions in the preprocessing record to find
5251/// and mark tokens that are macro arguments. This info is used by the
5252/// AnnotateTokensWorker.
5253class MarkMacroArgTokensVisitor {
5254 SourceManager &SM;
5255 CXToken *Tokens;
5256 unsigned NumTokens;
5257 unsigned CurIdx;
5258
5259public:
5260 MarkMacroArgTokensVisitor(SourceManager &SM,
5261 CXToken *tokens, unsigned numTokens)
5262 : SM(SM), Tokens(tokens), NumTokens(numTokens), CurIdx(0) { }
5263
5264 CXChildVisitResult visit(CXCursor cursor, CXCursor parent) {
5265 if (cursor.kind != CXCursor_MacroExpansion)
5266 return CXChildVisit_Continue;
5267
5268 SourceRange macroRange = getCursorMacroExpansion(cursor)->getSourceRange();
5269 if (macroRange.getBegin() == macroRange.getEnd())
5270 return CXChildVisit_Continue; // it's not a function macro.
5271
5272 for (; CurIdx < NumTokens; ++CurIdx) {
5273 if (!SM.isBeforeInTranslationUnit(getTokenLoc(CurIdx),
5274 macroRange.getBegin()))
5275 break;
5276 }
5277
5278 if (CurIdx == NumTokens)
5279 return CXChildVisit_Break;
5280
5281 for (; CurIdx < NumTokens; ++CurIdx) {
5282 SourceLocation tokLoc = getTokenLoc(CurIdx);
5283 if (!SM.isBeforeInTranslationUnit(tokLoc, macroRange.getEnd()))
5284 break;
5285
5286 setFunctionMacroTokenLoc(CurIdx, SM.getMacroArgExpandedLocation(tokLoc));
5287 }
5288
5289 if (CurIdx == NumTokens)
5290 return CXChildVisit_Break;
5291
5292 return CXChildVisit_Continue;
5293 }
5294
5295private:
5296 SourceLocation getTokenLoc(unsigned tokI) {
5297 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
5298 }
5299
5300 void setFunctionMacroTokenLoc(unsigned tokI, SourceLocation loc) {
5301 // The third field is reserved and currently not used. Use it here
5302 // to mark macro arg expanded tokens with their expanded locations.
5303 Tokens[tokI].int_data[3] = loc.getRawEncoding();
5304 }
5305};
5306
5307} // end anonymous namespace
5308
5309static CXChildVisitResult
5310MarkMacroArgTokensVisitorDelegate(CXCursor cursor, CXCursor parent,
5311 CXClientData client_data) {
5312 return static_cast<MarkMacroArgTokensVisitor*>(client_data)->visit(cursor,
5313 parent);
5314}
5315
5316namespace {
5317 struct clang_annotateTokens_Data {
5318 CXTranslationUnit TU;
5319 ASTUnit *CXXUnit;
5320 CXToken *Tokens;
5321 unsigned NumTokens;
5322 CXCursor *Cursors;
5323 };
5324}
5325
5326static void annotatePreprocessorTokens(CXTranslationUnit TU,
5327 SourceRange RegionOfInterest,
5328 AnnotateTokensData &Annotated) {
5329 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
5330
5331 SourceManager &SourceMgr = CXXUnit->getSourceManager();
5332 std::pair<FileID, unsigned> BeginLocInfo
5333 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
5334 std::pair<FileID, unsigned> EndLocInfo
5335 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
5336
5337 if (BeginLocInfo.first != EndLocInfo.first)
5338 return;
5339
5340 StringRef Buffer;
5341 bool Invalid = false;
5342 Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
5343 if (Buffer.empty() || Invalid)
5344 return;
5345
5346 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
5347 CXXUnit->getASTContext().getLangOpts(),
5348 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
5349 Buffer.end());
5350 Lex.SetCommentRetentionState(true);
5351
5352 // Lex tokens in raw mode until we hit the end of the range, to avoid
5353 // entering #includes or expanding macros.
5354 while (true) {
5355 Token Tok;
5356 Lex.LexFromRawLexer(Tok);
5357
5358 reprocess:
5359 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
5360 // We have found a preprocessing directive. Gobble it up so that we
5361 // don't see it while preprocessing these tokens later, but keep track
5362 // of all of the token locations inside this preprocessing directive so
5363 // that we can annotate them appropriately.
5364 //
5365 // FIXME: Some simple tests here could identify macro definitions and
5366 // #undefs, to provide specific cursor kinds for those.
5367 SmallVector<SourceLocation, 32> Locations;
5368 do {
5369 Locations.push_back(Tok.getLocation());
5370 Lex.LexFromRawLexer(Tok);
5371 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
5372
5373 using namespace cxcursor;
5374 CXCursor Cursor
5375 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
5376 Locations.back()),
5377 TU);
5378 for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
5379 Annotated[Locations[I].getRawEncoding()] = Cursor;
5380 }
5381
5382 if (Tok.isAtStartOfLine())
5383 goto reprocess;
5384
5385 continue;
5386 }
5387
5388 if (Tok.is(tok::eof))
5389 break;
5390 }
5391}
5392
5393// This gets run a separate thread to avoid stack blowout.
5394static void clang_annotateTokensImpl(void *UserData) {
5395 CXTranslationUnit TU = ((clang_annotateTokens_Data*)UserData)->TU;
5396 ASTUnit *CXXUnit = ((clang_annotateTokens_Data*)UserData)->CXXUnit;
5397 CXToken *Tokens = ((clang_annotateTokens_Data*)UserData)->Tokens;
5398 const unsigned NumTokens = ((clang_annotateTokens_Data*)UserData)->NumTokens;
5399 CXCursor *Cursors = ((clang_annotateTokens_Data*)UserData)->Cursors;
5400
5401 CIndexer *CXXIdx = (CIndexer*)TU->CIdx;
5402 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing))
5403 setThreadBackgroundPriority();
5404
5405 // Determine the region of interest, which contains all of the tokens.
5406 SourceRange RegionOfInterest;
5407 RegionOfInterest.setBegin(
5408 cxloc::translateSourceLocation(clang_getTokenLocation(TU, Tokens[0])));
5409 RegionOfInterest.setEnd(
5410 cxloc::translateSourceLocation(clang_getTokenLocation(TU,
5411 Tokens[NumTokens-1])));
5412
5413 // A mapping from the source locations found when re-lexing or traversing the
5414 // region of interest to the corresponding cursors.
5415 AnnotateTokensData Annotated;
5416
5417 // Relex the tokens within the source range to look for preprocessing
5418 // directives.
5419 annotatePreprocessorTokens(TU, RegionOfInterest, Annotated);
5420
5421 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
5422 // Search and mark tokens that are macro argument expansions.
5423 MarkMacroArgTokensVisitor Visitor(CXXUnit->getSourceManager(),
5424 Tokens, NumTokens);
5425 CursorVisitor MacroArgMarker(TU,
5426 MarkMacroArgTokensVisitorDelegate, &Visitor,
5427 /*VisitPreprocessorLast=*/true,
5428 /*VisitIncludedEntities=*/false,
5429 RegionOfInterest);
5430 MacroArgMarker.visitPreprocessedEntitiesInRegion();
5431 }
5432
5433 // Annotate all of the source locations in the region of interest that map to
5434 // a specific cursor.
5435 AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens,
5436 TU, RegionOfInterest);
5437
5438 // FIXME: We use a ridiculous stack size here because the data-recursion
5439 // algorithm uses a large stack frame than the non-data recursive version,
5440 // and AnnotationTokensWorker currently transforms the data-recursion
5441 // algorithm back into a traditional recursion by explicitly calling
5442 // VisitChildren(). We will need to remove this explicit recursive call.
5443 W.AnnotateTokens();
5444
5445 // If we ran into any entities that involve context-sensitive keywords,
5446 // take another pass through the tokens to mark them as such.
5447 if (W.hasContextSensitiveKeywords()) {
5448 for (unsigned I = 0; I != NumTokens; ++I) {
5449 if (clang_getTokenKind(Tokens[I]) != CXToken_Identifier)
5450 continue;
5451
5452 if (Cursors[I].kind == CXCursor_ObjCPropertyDecl) {
5453 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
5454 if (ObjCPropertyDecl *Property
5455 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(Cursors[I]))) {
5456 if (Property->getPropertyAttributesAsWritten() != 0 &&
5457 llvm::StringSwitch<bool>(II->getName())
5458 .Case("readonly", true)
5459 .Case("assign", true)
5460 .Case("unsafe_unretained", true)
5461 .Case("readwrite", true)
5462 .Case("retain", true)
5463 .Case("copy", true)
5464 .Case("nonatomic", true)
5465 .Case("atomic", true)
5466 .Case("getter", true)
5467 .Case("setter", true)
5468 .Case("strong", true)
5469 .Case("weak", true)
5470 .Default(false))
5471 Tokens[I].int_data[0] = CXToken_Keyword;
5472 }
5473 continue;
5474 }
5475
5476 if (Cursors[I].kind == CXCursor_ObjCInstanceMethodDecl ||
5477 Cursors[I].kind == CXCursor_ObjCClassMethodDecl) {
5478 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
5479 if (llvm::StringSwitch<bool>(II->getName())
5480 .Case("in", true)
5481 .Case("out", true)
5482 .Case("inout", true)
5483 .Case("oneway", true)
5484 .Case("bycopy", true)
5485 .Case("byref", true)
5486 .Default(false))
5487 Tokens[I].int_data[0] = CXToken_Keyword;
5488 continue;
5489 }
5490
5491 if (Cursors[I].kind == CXCursor_CXXFinalAttr ||
5492 Cursors[I].kind == CXCursor_CXXOverrideAttr) {
5493 Tokens[I].int_data[0] = CXToken_Keyword;
5494 continue;
5495 }
5496 }
5497 }
5498}
5499
5500extern "C" {
5501
5502void clang_annotateTokens(CXTranslationUnit TU,
5503 CXToken *Tokens, unsigned NumTokens,
5504 CXCursor *Cursors) {
5505
5506 if (NumTokens == 0 || !Tokens || !Cursors)
5507 return;
5508
5509 // Any token we don't specifically annotate will have a NULL cursor.
5510 CXCursor C = clang_getNullCursor();
5511 for (unsigned I = 0; I != NumTokens; ++I)
5512 Cursors[I] = C;
5513
5514 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
5515 if (!CXXUnit)
5516 return;
5517
5518 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
5519
5520 clang_annotateTokens_Data data = { TU, CXXUnit, Tokens, NumTokens, Cursors };
5521 llvm::CrashRecoveryContext CRC;
5522 if (!RunSafely(CRC, clang_annotateTokensImpl, &data,
5523 GetSafetyThreadStackSize() * 2)) {
5524 fprintf(stderr, "libclang: crash detected while annotating tokens\n");
5525 }
5526}
5527
5528} // end: extern "C"
5529
5530//===----------------------------------------------------------------------===//
5531// Operations for querying linkage of a cursor.
5532//===----------------------------------------------------------------------===//
5533
5534extern "C" {
5535CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
5536 if (!clang_isDeclaration(cursor.kind))
5537 return CXLinkage_Invalid;
5538
5539 Decl *D = cxcursor::getCursorDecl(cursor);
5540 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
5541 switch (ND->getLinkage()) {
5542 case NoLinkage: return CXLinkage_NoLinkage;
5543 case InternalLinkage: return CXLinkage_Internal;
5544 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
5545 case ExternalLinkage: return CXLinkage_External;
5546 };
5547
5548 return CXLinkage_Invalid;
5549}
5550} // end: extern "C"
5551
5552//===----------------------------------------------------------------------===//
5553// Operations for querying language of a cursor.
5554//===----------------------------------------------------------------------===//
5555
5556static CXLanguageKind getDeclLanguage(const Decl *D) {
5557 if (!D)
5558 return CXLanguage_C;
5559
5560 switch (D->getKind()) {
5561 default:
5562 break;
5563 case Decl::ImplicitParam:
5564 case Decl::ObjCAtDefsField:
5565 case Decl::ObjCCategory:
5566 case Decl::ObjCCategoryImpl:
5567 case Decl::ObjCCompatibleAlias:
5568 case Decl::ObjCImplementation:
5569 case Decl::ObjCInterface:
5570 case Decl::ObjCIvar:
5571 case Decl::ObjCMethod:
5572 case Decl::ObjCProperty:
5573 case Decl::ObjCPropertyImpl:
5574 case Decl::ObjCProtocol:
5575 return CXLanguage_ObjC;
5576 case Decl::CXXConstructor:
5577 case Decl::CXXConversion:
5578 case Decl::CXXDestructor:
5579 case Decl::CXXMethod:
5580 case Decl::CXXRecord:
5581 case Decl::ClassTemplate:
5582 case Decl::ClassTemplatePartialSpecialization:
5583 case Decl::ClassTemplateSpecialization:
5584 case Decl::Friend:
5585 case Decl::FriendTemplate:
5586 case Decl::FunctionTemplate:
5587 case Decl::LinkageSpec:
5588 case Decl::Namespace:
5589 case Decl::NamespaceAlias:
5590 case Decl::NonTypeTemplateParm:
5591 case Decl::StaticAssert:
5592 case Decl::TemplateTemplateParm:
5593 case Decl::TemplateTypeParm:
5594 case Decl::UnresolvedUsingTypename:
5595 case Decl::UnresolvedUsingValue:
5596 case Decl::Using:
5597 case Decl::UsingDirective:
5598 case Decl::UsingShadow:
5599 return CXLanguage_CPlusPlus;
5600 }
5601
5602 return CXLanguage_C;
5603}
5604
5605extern "C" {
5606
5607enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
5608 if (clang_isDeclaration(cursor.kind))
5609 if (Decl *D = cxcursor::getCursorDecl(cursor)) {
5610 if (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted())
5611 return CXAvailability_Available;
5612
5613 switch (D->getAvailability()) {
5614 case AR_Available:
5615 case AR_NotYetIntroduced:
5616 return CXAvailability_Available;
5617
5618 case AR_Deprecated:
5619 return CXAvailability_Deprecated;
5620
5621 case AR_Unavailable:
5622 return CXAvailability_NotAvailable;
5623 }
5624 }
5625
5626 return CXAvailability_Available;
5627}
5628
5629static CXVersion convertVersion(VersionTuple In) {
5630 CXVersion Out = { -1, -1, -1 };
5631 if (In.empty())
5632 return Out;
5633
5634 Out.Major = In.getMajor();
5635
5636 if (llvm::Optional<unsigned> Minor = In.getMinor())
5637 Out.Minor = *Minor;
5638 else
5639 return Out;
5640
5641 if (llvm::Optional<unsigned> Subminor = In.getSubminor())
5642 Out.Subminor = *Subminor;
5643
5644 return Out;
5645}
5646
5647int clang_getCursorPlatformAvailability(CXCursor cursor,
5648 int *always_deprecated,
5649 CXString *deprecated_message,
5650 int *always_unavailable,
5651 CXString *unavailable_message,
5652 CXPlatformAvailability *availability,
5653 int availability_size) {
5654 if (always_deprecated)
5655 *always_deprecated = 0;
5656 if (deprecated_message)
5657 *deprecated_message = cxstring::createCXString("", /*DupString=*/false);
5658 if (always_unavailable)
5659 *always_unavailable = 0;
5660 if (unavailable_message)
5661 *unavailable_message = cxstring::createCXString("", /*DupString=*/false);
5662
5663 if (!clang_isDeclaration(cursor.kind))
5664 return 0;
5665
5666 Decl *D = cxcursor::getCursorDecl(cursor);
5667 if (!D)
5668 return 0;
5669
5670 int N = 0;
5671 for (Decl::attr_iterator A = D->attr_begin(), AEnd = D->attr_end(); A != AEnd;
5672 ++A) {
5673 if (DeprecatedAttr *Deprecated = dyn_cast<DeprecatedAttr>(*A)) {
5674 if (always_deprecated)
5675 *always_deprecated = 1;
5676 if (deprecated_message)
5677 *deprecated_message = cxstring::createCXString(Deprecated->getMessage());
5678 continue;
5679 }
5680
5681 if (UnavailableAttr *Unavailable = dyn_cast<UnavailableAttr>(*A)) {
5682 if (always_unavailable)
5683 *always_unavailable = 1;
5684 if (unavailable_message) {
5685 *unavailable_message
5686 = cxstring::createCXString(Unavailable->getMessage());
5687 }
5688 continue;
5689 }
5690
5691 if (AvailabilityAttr *Avail = dyn_cast<AvailabilityAttr>(*A)) {
5692 if (N < availability_size) {
5693 availability[N].Platform
5694 = cxstring::createCXString(Avail->getPlatform()->getName());
5695 availability[N].Introduced = convertVersion(Avail->getIntroduced());
5696 availability[N].Deprecated = convertVersion(Avail->getDeprecated());
5697 availability[N].Obsoleted = convertVersion(Avail->getObsoleted());
5698 availability[N].Unavailable = Avail->getUnavailable();
5699 availability[N].Message = cxstring::createCXString(Avail->getMessage());
5700 }
5701 ++N;
5702 }
5703 }
5704
5705 return N;
5706}
5707
5708void clang_disposeCXPlatformAvailability(CXPlatformAvailability *availability) {
5709 clang_disposeString(availability->Platform);
5710 clang_disposeString(availability->Message);
5711}
5712
5713CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
5714 if (clang_isDeclaration(cursor.kind))
5715 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
5716
5717 return CXLanguage_Invalid;
5718}
5719
5720 /// \brief If the given cursor is the "templated" declaration
5721 /// descibing a class or function template, return the class or
5722 /// function template.
5723static Decl *maybeGetTemplateCursor(Decl *D) {
5724 if (!D)
5725 return 0;
5726
5727 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
5728 if (FunctionTemplateDecl *FunTmpl = FD->getDescribedFunctionTemplate())
5729 return FunTmpl;
5730
5731 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
5732 if (ClassTemplateDecl *ClassTmpl = RD->getDescribedClassTemplate())
5733 return ClassTmpl;
5734
5735 return D;
5736}
5737
5738CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
5739 if (clang_isDeclaration(cursor.kind)) {
5740 if (Decl *D = getCursorDecl(cursor)) {
5741 DeclContext *DC = D->getDeclContext();
5742 if (!DC)
5743 return clang_getNullCursor();
5744
5745 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
5746 getCursorTU(cursor));
5747 }
5748 }
5749
5750 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
5751 if (Decl *D = getCursorDecl(cursor))
5752 return MakeCXCursor(D, getCursorTU(cursor));
5753 }
5754
5755 return clang_getNullCursor();
5756}
5757
5758CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
5759 if (clang_isDeclaration(cursor.kind)) {
5760 if (Decl *D = getCursorDecl(cursor)) {
5761 DeclContext *DC = D->getLexicalDeclContext();
5762 if (!DC)
5763 return clang_getNullCursor();
5764
5765 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
5766 getCursorTU(cursor));
5767 }
5768 }
5769
5770 // FIXME: Note that we can't easily compute the lexical context of a
5771 // statement or expression, so we return nothing.
5772 return clang_getNullCursor();
5773}
5774
5775CXFile clang_getIncludedFile(CXCursor cursor) {
5776 if (cursor.kind != CXCursor_InclusionDirective)
5777 return 0;
5778
5779 InclusionDirective *ID = getCursorInclusionDirective(cursor);
5780 return (void *)ID->getFile();
5781}
5782
5783CXSourceRange clang_Cursor_getCommentRange(CXCursor C) {
5784 if (!clang_isDeclaration(C.kind))
5785 return clang_getNullRange();
5786
5787 const Decl *D = getCursorDecl(C);
5788 ASTContext &Context = getCursorContext(C);
5789 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
5790 if (!RC)
5791 return clang_getNullRange();
5792
5793 return cxloc::translateSourceRange(Context, RC->getSourceRange());
5794}
5795
5796CXString clang_Cursor_getRawCommentText(CXCursor C) {
5797 if (!clang_isDeclaration(C.kind))
5798 return createCXString((const char *) NULL);
5799
5800 const Decl *D = getCursorDecl(C);
5801 ASTContext &Context = getCursorContext(C);
5802 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
5803 StringRef RawText = RC ? RC->getRawText(Context.getSourceManager()) :
5804 StringRef();
5805
5806 // Don't duplicate the string because RawText points directly into source
5807 // code.
5808 return createCXString(RawText, false);
5809}
5810
5811CXString clang_Cursor_getBriefCommentText(CXCursor C) {
5812 if (!clang_isDeclaration(C.kind))
5813 return createCXString((const char *) NULL);
5814
5815 const Decl *D = getCursorDecl(C);
5816 const ASTContext &Context = getCursorContext(C);
5817 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
5818
5819 if (RC) {
5820 StringRef BriefText = RC->getBriefText(Context);
5821
5822 // Don't duplicate the string because RawComment ensures that this memory
5823 // will not go away.
5824 return createCXString(BriefText, false);
5825 }
5826
5827 return createCXString((const char *) NULL);
5828}
5829
5830CXComment clang_Cursor_getParsedComment(CXCursor C) {
5831 if (!clang_isDeclaration(C.kind))
5832 return cxcomment::createCXComment(NULL, NULL);
5833
5834 const Decl *D = getCursorDecl(C);
5835 const ASTContext &Context = getCursorContext(C);
5836 const comments::FullComment *FC = Context.getCommentForDecl(D, /*PP=*/ NULL);
5837
5838 return cxcomment::createCXComment(FC, getCursorTU(C));
5839}
5840
5841CXModule clang_Cursor_getModule(CXCursor C) {
5842 if (C.kind == CXCursor_ModuleImportDecl) {
5843 if (ImportDecl *ImportD = dyn_cast_or_null<ImportDecl>(getCursorDecl(C)))
5844 return ImportD->getImportedModule();
5845 }
5846
5847 return 0;
5848}
5849
5850CXModule clang_Module_getParent(CXModule CXMod) {
5851 if (!CXMod)
5852 return 0;
5853 Module *Mod = static_cast<Module*>(CXMod);
5854 return Mod->Parent;
5855}
5856
5857CXString clang_Module_getName(CXModule CXMod) {
5858 if (!CXMod)
5859 return createCXString("");
5860 Module *Mod = static_cast<Module*>(CXMod);
5861 return createCXString(Mod->Name);
5862}
5863
5864CXString clang_Module_getFullName(CXModule CXMod) {
5865 if (!CXMod)
5866 return createCXString("");
5867 Module *Mod = static_cast<Module*>(CXMod);
5868 return createCXString(Mod->getFullModuleName());
5869}
5870
5871unsigned clang_Module_getNumTopLevelHeaders(CXModule CXMod) {
5872 if (!CXMod)
5873 return 0;
5874 Module *Mod = static_cast<Module*>(CXMod);
5875 return Mod->TopHeaders.size();
5876}
5877
5878CXFile clang_Module_getTopLevelHeader(CXModule CXMod, unsigned Index) {
5879 if (!CXMod)
5880 return 0;
5881 Module *Mod = static_cast<Module*>(CXMod);
5882
5883 if (Index < Mod->TopHeaders.size())
5884 return const_cast<FileEntry *>(Mod->TopHeaders[Index]);
5885
5886 return 0;
5887}
5888
5889} // end: extern "C"
5890
5891//===----------------------------------------------------------------------===//
5892// C++ AST instrospection.
5893//===----------------------------------------------------------------------===//
5894
5895extern "C" {
5896unsigned clang_CXXMethod_isStatic(CXCursor C) {
5897 if (!clang_isDeclaration(C.kind))
5898 return 0;
5899
5900 CXXMethodDecl *Method = 0;
5901 Decl *D = cxcursor::getCursorDecl(C);
5902 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
5903 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
5904 else
5905 Method = dyn_cast_or_null<CXXMethodDecl>(D);
5906 return (Method && Method->isStatic()) ? 1 : 0;
5907}
5908
5909unsigned clang_CXXMethod_isVirtual(CXCursor C) {
5910 if (!clang_isDeclaration(C.kind))
5911 return 0;
5912
5913 CXXMethodDecl *Method = 0;
5914 Decl *D = cxcursor::getCursorDecl(C);
5915 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
5916 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
5917 else
5918 Method = dyn_cast_or_null<CXXMethodDecl>(D);
5919 return (Method && Method->isVirtual()) ? 1 : 0;
5920}
5921} // end: extern "C"
5922
5923//===----------------------------------------------------------------------===//
5924// Attribute introspection.
5925//===----------------------------------------------------------------------===//
5926
5927extern "C" {
5928CXType clang_getIBOutletCollectionType(CXCursor C) {
5929 if (C.kind != CXCursor_IBOutletCollectionAttr)
5930 return cxtype::MakeCXType(QualType(), cxcursor::getCursorTU(C));
5931
5932 IBOutletCollectionAttr *A =
5933 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
5934
5935 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorTU(C));
5936}
5937} // end: extern "C"
5938
5939//===----------------------------------------------------------------------===//
5940// Inspecting memory usage.
5941//===----------------------------------------------------------------------===//
5942
5943typedef std::vector<CXTUResourceUsageEntry> MemUsageEntries;
5944
5945static inline void createCXTUResourceUsageEntry(MemUsageEntries &entries,
5946 enum CXTUResourceUsageKind k,
5947 unsigned long amount) {
5948 CXTUResourceUsageEntry entry = { k, amount };
5949 entries.push_back(entry);
5950}
5951
5952extern "C" {
5953
5954const char *clang_getTUResourceUsageName(CXTUResourceUsageKind kind) {
5955 const char *str = "";
5956 switch (kind) {
5957 case CXTUResourceUsage_AST:
5958 str = "ASTContext: expressions, declarations, and types";
5959 break;
5960 case CXTUResourceUsage_Identifiers:
5961 str = "ASTContext: identifiers";
5962 break;
5963 case CXTUResourceUsage_Selectors:
5964 str = "ASTContext: selectors";
5965 break;
5966 case CXTUResourceUsage_GlobalCompletionResults:
5967 str = "Code completion: cached global results";
5968 break;
5969 case CXTUResourceUsage_SourceManagerContentCache:
5970 str = "SourceManager: content cache allocator";
5971 break;
5972 case CXTUResourceUsage_AST_SideTables:
5973 str = "ASTContext: side tables";
5974 break;
5975 case CXTUResourceUsage_SourceManager_Membuffer_Malloc:
5976 str = "SourceManager: malloc'ed memory buffers";
5977 break;
5978 case CXTUResourceUsage_SourceManager_Membuffer_MMap:
5979 str = "SourceManager: mmap'ed memory buffers";
5980 break;
5981 case CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc:
5982 str = "ExternalASTSource: malloc'ed memory buffers";
5983 break;
5984 case CXTUResourceUsage_ExternalASTSource_Membuffer_MMap:
5985 str = "ExternalASTSource: mmap'ed memory buffers";
5986 break;
5987 case CXTUResourceUsage_Preprocessor:
5988 str = "Preprocessor: malloc'ed memory";
5989 break;
5990 case CXTUResourceUsage_PreprocessingRecord:
5991 str = "Preprocessor: PreprocessingRecord";
5992 break;
5993 case CXTUResourceUsage_SourceManager_DataStructures:
5994 str = "SourceManager: data structures and tables";
5995 break;
5996 case CXTUResourceUsage_Preprocessor_HeaderSearch:
5997 str = "Preprocessor: header search tables";
5998 break;
5999 }
6000 return str;
6001}
6002
6003CXTUResourceUsage clang_getCXTUResourceUsage(CXTranslationUnit TU) {
6004 if (!TU) {
6005 CXTUResourceUsage usage = { (void*) 0, 0, 0 };
6006 return usage;
6007 }
6008
6009 ASTUnit *astUnit = static_cast<ASTUnit*>(TU->TUData);
6010 OwningPtr<MemUsageEntries> entries(new MemUsageEntries());
6011 ASTContext &astContext = astUnit->getASTContext();
6012
6013 // How much memory is used by AST nodes and types?
6014 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST,
6015 (unsigned long) astContext.getASTAllocatedMemory());
6016
6017 // How much memory is used by identifiers?
6018 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Identifiers,
6019 (unsigned long) astContext.Idents.getAllocator().getTotalMemory());
6020
6021 // How much memory is used for selectors?
6022 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Selectors,
6023 (unsigned long) astContext.Selectors.getTotalMemory());
6024
6025 // How much memory is used by ASTContext's side tables?
6026 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST_SideTables,
6027 (unsigned long) astContext.getSideTableAllocatedMemory());
6028
6029 // How much memory is used for caching global code completion results?
6030 unsigned long completionBytes = 0;
6031 if (GlobalCodeCompletionAllocator *completionAllocator =
6032 astUnit->getCachedCompletionAllocator().getPtr()) {
6033 completionBytes = completionAllocator->getTotalMemory();
6034 }
6035 createCXTUResourceUsageEntry(*entries,
6036 CXTUResourceUsage_GlobalCompletionResults,
6037 completionBytes);
6038
6039 // How much memory is being used by SourceManager's content cache?
6040 createCXTUResourceUsageEntry(*entries,
6041 CXTUResourceUsage_SourceManagerContentCache,
6042 (unsigned long) astContext.getSourceManager().getContentCacheSize());
6043
6044 // How much memory is being used by the MemoryBuffer's in SourceManager?
6045 const SourceManager::MemoryBufferSizes &srcBufs =
6046 astUnit->getSourceManager().getMemoryBufferSizes();
6047
6048 createCXTUResourceUsageEntry(*entries,
6049 CXTUResourceUsage_SourceManager_Membuffer_Malloc,
6050 (unsigned long) srcBufs.malloc_bytes);
6051 createCXTUResourceUsageEntry(*entries,
6052 CXTUResourceUsage_SourceManager_Membuffer_MMap,
6053 (unsigned long) srcBufs.mmap_bytes);
6054 createCXTUResourceUsageEntry(*entries,
6055 CXTUResourceUsage_SourceManager_DataStructures,
6056 (unsigned long) astContext.getSourceManager()
6057 .getDataStructureSizes());
6058
6059 // How much memory is being used by the ExternalASTSource?
6060 if (ExternalASTSource *esrc = astContext.getExternalSource()) {
6061 const ExternalASTSource::MemoryBufferSizes &sizes =
6062 esrc->getMemoryBufferSizes();
6063
6064 createCXTUResourceUsageEntry(*entries,
6065 CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc,
6066 (unsigned long) sizes.malloc_bytes);
6067 createCXTUResourceUsageEntry(*entries,
6068 CXTUResourceUsage_ExternalASTSource_Membuffer_MMap,
6069 (unsigned long) sizes.mmap_bytes);
6070 }
6071
6072 // How much memory is being used by the Preprocessor?
6073 Preprocessor &pp = astUnit->getPreprocessor();
6074 createCXTUResourceUsageEntry(*entries,
6075 CXTUResourceUsage_Preprocessor,
6076 pp.getTotalMemory());
6077
6078 if (PreprocessingRecord *pRec = pp.getPreprocessingRecord()) {
6079 createCXTUResourceUsageEntry(*entries,
6080 CXTUResourceUsage_PreprocessingRecord,
6081 pRec->getTotalMemory());
6082 }
6083
6084 createCXTUResourceUsageEntry(*entries,
6085 CXTUResourceUsage_Preprocessor_HeaderSearch,
6086 pp.getHeaderSearchInfo().getTotalMemory());
6087
6088 CXTUResourceUsage usage = { (void*) entries.get(),
6089 (unsigned) entries->size(),
6090 entries->size() ? &(*entries)[0] : 0 };
6091 entries.take();
6092 return usage;
6093}
6094
6095void clang_disposeCXTUResourceUsage(CXTUResourceUsage usage) {
6096 if (usage.data)
6097 delete (MemUsageEntries*) usage.data;
6098}
6099
6100} // end extern "C"
6101
6102void clang::PrintLibclangResourceUsage(CXTranslationUnit TU) {
6103 CXTUResourceUsage Usage = clang_getCXTUResourceUsage(TU);
6104 for (unsigned I = 0; I != Usage.numEntries; ++I)
6105 fprintf(stderr, " %s: %lu\n",
6106 clang_getTUResourceUsageName(Usage.entries[I].kind),
6107 Usage.entries[I].amount);
6108
6109 clang_disposeCXTUResourceUsage(Usage);
6110}
6111
6112//===----------------------------------------------------------------------===//
6113// Misc. utility functions.
6114//===----------------------------------------------------------------------===//
6115
6116/// Default to using an 8 MB stack size on "safety" threads.
6117static unsigned SafetyStackThreadSize = 8 << 20;
6118
6119namespace clang {
6120
6121bool RunSafely(llvm::CrashRecoveryContext &CRC,
6122 void (*Fn)(void*), void *UserData,
6123 unsigned Size) {
6124 if (!Size)
6125 Size = GetSafetyThreadStackSize();
6126 if (Size)
6127 return CRC.RunSafelyOnThread(Fn, UserData, Size);
6128 return CRC.RunSafely(Fn, UserData);
6129}
6130
6131unsigned GetSafetyThreadStackSize() {
6132 return SafetyStackThreadSize;
6133}
6134
6135void SetSafetyThreadStackSize(unsigned Value) {
6136 SafetyStackThreadSize = Value;
6137}
6138
6139}
6140
6141void clang::setThreadBackgroundPriority() {
6142 if (getenv("LIBCLANG_BGPRIO_DISABLE"))
6143 return;
6144
6145 // FIXME: Move to llvm/Support and make it cross-platform.
6146#ifdef __APPLE__
6147 setpriority(PRIO_DARWIN_THREAD, 0, PRIO_DARWIN_BG);
6148#endif
6149}
6150
6151void cxindex::printDiagsToStderr(ASTUnit *Unit) {
6152 if (!Unit)
6153 return;
6154
6155 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
6156 DEnd = Unit->stored_diag_end();
6157 D != DEnd; ++D) {
6158 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOpts());
6159 CXString Msg = clang_formatDiagnostic(&Diag,
6160 clang_defaultDiagnosticDisplayOptions());
6161 fprintf(stderr, "%s\n", clang_getCString(Msg));
6162 clang_disposeString(Msg);
6163 }
6164#ifdef LLVM_ON_WIN32
6165 // On Windows, force a flush, since there may be multiple copies of
6166 // stderr and stdout in the file system, all with different buffers
6167 // but writing to the same device.
6168 fflush(stderr);
6169#endif
6170}
6171
6172extern "C" {
6173
6174CXString clang_getClangVersion() {
6175 return createCXString(getClangFullVersion());
6176}
6177
6178} // end: extern "C"
6179