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