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