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