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