CIndexUSRs.cpp revision 472ccff00cdbcd095c3ba933b9e3f202719f118f
1//===- CIndexUSR.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 generation and use of USRs from CXEntities. 11// 12//===----------------------------------------------------------------------===// 13 14#include "CIndexer.h" 15#include "CXCursor.h" 16#include "CXString.h" 17#include "clang/AST/DeclTemplate.h" 18#include "clang/AST/DeclVisitor.h" 19#include "clang/Frontend/ASTUnit.h" 20#include "clang/Lex/PreprocessingRecord.h" 21#include "llvm/ADT/SmallString.h" 22#include "llvm/Support/raw_ostream.h" 23 24using namespace clang; 25using namespace clang::cxstring; 26 27//===----------------------------------------------------------------------===// 28// USR generation. 29//===----------------------------------------------------------------------===// 30 31namespace { 32class USRGenerator : public DeclVisitor<USRGenerator> { 33 llvm::OwningPtr<llvm::SmallString<128> > OwnedBuf; 34 llvm::SmallVectorImpl<char> &Buf; 35 llvm::raw_svector_ostream Out; 36 bool IgnoreResults; 37 ASTUnit *AU; 38 bool generatedLoc; 39 40 llvm::DenseMap<const Type *, unsigned> TypeSubstitutions; 41 42public: 43 USRGenerator(const CXCursor *C = 0, llvm::SmallVectorImpl<char> *extBuf = 0) 44 : OwnedBuf(extBuf ? 0 : new llvm::SmallString<128>()), 45 Buf(extBuf ? *extBuf : *OwnedBuf.get()), 46 Out(Buf), 47 IgnoreResults(false), 48 AU(C ? cxcursor::getCursorASTUnit(*C) : 0), 49 generatedLoc(false) 50 { 51 // Add the USR space prefix. 52 Out << "c:"; 53 } 54 55 llvm::StringRef str() { 56 return Out.str(); 57 } 58 59 USRGenerator* operator->() { return this; } 60 61 template <typename T> 62 llvm::raw_svector_ostream &operator<<(const T &x) { 63 Out << x; 64 return Out; 65 } 66 67 bool ignoreResults() const { return IgnoreResults; } 68 69 // Visitation methods from generating USRs from AST elements. 70 void VisitDeclContext(DeclContext *D); 71 void VisitFieldDecl(FieldDecl *D); 72 void VisitFunctionDecl(FunctionDecl *D); 73 void VisitNamedDecl(NamedDecl *D); 74 void VisitNamespaceDecl(NamespaceDecl *D); 75 void VisitNamespaceAliasDecl(NamespaceAliasDecl *D); 76 void VisitFunctionTemplateDecl(FunctionTemplateDecl *D); 77 void VisitClassTemplateDecl(ClassTemplateDecl *D); 78 void VisitObjCClassDecl(ObjCClassDecl *CD); 79 void VisitObjCContainerDecl(ObjCContainerDecl *CD); 80 void VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *P); 81 void VisitObjCMethodDecl(ObjCMethodDecl *MD); 82 void VisitObjCPropertyDecl(ObjCPropertyDecl *D); 83 void VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D); 84 void VisitTagDecl(TagDecl *D); 85 void VisitTypedefDecl(TypedefDecl *D); 86 void VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D); 87 void VisitVarDecl(VarDecl *D); 88 void VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D); 89 void VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D); 90 void VisitLinkageSpecDecl(LinkageSpecDecl *D) { 91 IgnoreResults = true; 92 } 93 void VisitUsingDirectiveDecl(UsingDirectiveDecl *D) { 94 IgnoreResults = true; 95 } 96 void VisitUsingDecl(UsingDecl *D) { 97 IgnoreResults = true; 98 } 99 void VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) { 100 IgnoreResults = true; 101 } 102 void VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D) { 103 IgnoreResults = true; 104 } 105 106 /// Generate the string component containing the location of the 107 /// declaration. 108 bool GenLoc(const Decl *D); 109 110 /// String generation methods used both by the visitation methods 111 /// and from other clients that want to directly generate USRs. These 112 /// methods do not construct complete USRs (which incorporate the parents 113 /// of an AST element), but only the fragments concerning the AST element 114 /// itself. 115 116 /// Generate a USR for an Objective-C class. 117 void GenObjCClass(llvm::StringRef cls); 118 /// Generate a USR for an Objective-C class category. 119 void GenObjCCategory(llvm::StringRef cls, llvm::StringRef cat); 120 /// Generate a USR fragment for an Objective-C instance variable. The 121 /// complete USR can be created by concatenating the USR for the 122 /// encompassing class with this USR fragment. 123 void GenObjCIvar(llvm::StringRef ivar); 124 /// Generate a USR fragment for an Objective-C method. 125 void GenObjCMethod(llvm::StringRef sel, bool isInstanceMethod); 126 /// Generate a USR fragment for an Objective-C property. 127 void GenObjCProperty(llvm::StringRef prop); 128 /// Generate a USR for an Objective-C protocol. 129 void GenObjCProtocol(llvm::StringRef prot); 130 131 void VisitType(QualType T); 132 void VisitTemplateParameterList(const TemplateParameterList *Params); 133 void VisitTemplateName(TemplateName Name); 134 void VisitTemplateArgument(const TemplateArgument &Arg); 135 136 /// Emit a Decl's name using NamedDecl::printName() and return true if 137 /// the decl had no name. 138 bool EmitDeclName(const NamedDecl *D); 139}; 140 141} // end anonymous namespace 142 143//===----------------------------------------------------------------------===// 144// Generating USRs from ASTS. 145//===----------------------------------------------------------------------===// 146 147bool USRGenerator::EmitDeclName(const NamedDecl *D) { 148 Out.flush(); 149 const unsigned startSize = Buf.size(); 150 D->printName(Out); 151 Out.flush(); 152 const unsigned endSize = Buf.size(); 153 return startSize == endSize; 154} 155 156static bool InAnonymousNamespace(const Decl *D) { 157 if (const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(D->getDeclContext())) 158 return ND->isAnonymousNamespace(); 159 return false; 160} 161 162static inline bool ShouldGenerateLocation(const NamedDecl *D) { 163 return D->getLinkage() != ExternalLinkage && !InAnonymousNamespace(D); 164} 165 166void USRGenerator::VisitDeclContext(DeclContext *DC) { 167 if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) 168 Visit(D); 169} 170 171void USRGenerator::VisitFieldDecl(FieldDecl *D) { 172 VisitDeclContext(D->getDeclContext()); 173 Out << (isa<ObjCIvarDecl>(D) ? "@" : "@FI@"); 174 if (EmitDeclName(D)) { 175 // Bit fields can be anonymous. 176 IgnoreResults = true; 177 return; 178 } 179} 180 181void USRGenerator::VisitFunctionDecl(FunctionDecl *D) { 182 if (ShouldGenerateLocation(D) && GenLoc(D)) 183 return; 184 185 VisitDeclContext(D->getDeclContext()); 186 if (FunctionTemplateDecl *FunTmpl = D->getDescribedFunctionTemplate()) { 187 Out << "@FT@"; 188 VisitTemplateParameterList(FunTmpl->getTemplateParameters()); 189 } else 190 Out << "@F@"; 191 D->printName(Out); 192 193 ASTContext &Ctx = AU->getASTContext(); 194 if (!Ctx.getLangOptions().CPlusPlus || D->isExternC()) 195 return; 196 197 // Mangle in type information for the arguments. 198 for (FunctionDecl::param_iterator I = D->param_begin(), E = D->param_end(); 199 I != E; ++I) { 200 Out << '#'; 201 if (ParmVarDecl *PD = *I) 202 VisitType(PD->getType()); 203 } 204 if (D->isVariadic()) 205 Out << '.'; 206 Out << '#'; 207 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 208 if (MD->isStatic()) 209 Out << 'S'; 210 if (unsigned quals = MD->getTypeQualifiers()) 211 Out << (char)('0' + quals); 212 } 213} 214 215void USRGenerator::VisitNamedDecl(NamedDecl *D) { 216 VisitDeclContext(D->getDeclContext()); 217 Out << "@"; 218 219 if (EmitDeclName(D)) { 220 // The string can be empty if the declaration has no name; e.g., it is 221 // the ParmDecl with no name for declaration of a function pointer type, 222 // e.g.: void (*f)(void *); 223 // In this case, don't generate a USR. 224 IgnoreResults = true; 225 } 226} 227 228void USRGenerator::VisitVarDecl(VarDecl *D) { 229 // VarDecls can be declared 'extern' within a function or method body, 230 // but their enclosing DeclContext is the function, not the TU. We need 231 // to check the storage class to correctly generate the USR. 232 if (ShouldGenerateLocation(D) && GenLoc(D)) 233 return; 234 235 VisitDeclContext(D->getDeclContext()); 236 237 // Variables always have simple names. 238 llvm::StringRef s = D->getName(); 239 240 // The string can be empty if the declaration has no name; e.g., it is 241 // the ParmDecl with no name for declaration of a function pointer type, e.g.: 242 // void (*f)(void *); 243 // In this case, don't generate a USR. 244 if (s.empty()) 245 IgnoreResults = true; 246 else 247 Out << '@' << s; 248} 249 250void USRGenerator::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) { 251 GenLoc(D); 252 return; 253} 254 255void USRGenerator::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) { 256 GenLoc(D); 257 return; 258} 259 260void USRGenerator::VisitNamespaceDecl(NamespaceDecl *D) { 261 if (D->isAnonymousNamespace()) { 262 Out << "@aN"; 263 return; 264 } 265 266 VisitDeclContext(D->getDeclContext()); 267 if (!IgnoreResults) 268 Out << "@N@" << D->getName(); 269} 270 271void USRGenerator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) { 272 VisitFunctionDecl(D->getTemplatedDecl()); 273} 274 275void USRGenerator::VisitClassTemplateDecl(ClassTemplateDecl *D) { 276 VisitTagDecl(D->getTemplatedDecl()); 277} 278 279void USRGenerator::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) { 280 VisitDeclContext(D->getDeclContext()); 281 if (!IgnoreResults) 282 Out << "@NA@" << D->getName(); 283} 284 285void USRGenerator::VisitObjCMethodDecl(ObjCMethodDecl *D) { 286 Decl *container = cast<Decl>(D->getDeclContext()); 287 288 // The USR for a method declared in a class extension is based on 289 // the ObjCInterfaceDecl, not the ObjCCategoryDecl. 290 do { 291 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(container)) 292 if (CD->IsClassExtension()) { 293 // ID can be null with invalid code. 294 if (ObjCInterfaceDecl *ID = CD->getClassInterface()) { 295 Visit(ID); 296 break; 297 } 298 // Invalid code. Can't generate USR. 299 IgnoreResults = true; 300 return; 301 } 302 303 Visit(container); 304 } 305 while (false); 306 307 // Ideally we would use 'GenObjCMethod', but this is such a hot path 308 // for Objective-C code that we don't want to use 309 // DeclarationName::getAsString(). 310 Out << (D->isInstanceMethod() ? "(im)" : "(cm)"); 311 DeclarationName N(D->getSelector()); 312 N.printName(Out); 313} 314 315void USRGenerator::VisitObjCClassDecl(ObjCClassDecl *D) { 316 // FIXME: @class declarations can refer to multiple classes. We need 317 // to be able to traverse these. 318 IgnoreResults = true; 319} 320 321void USRGenerator::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) { 322 // FIXME: @protocol declarations can refer to multiple protocols. We need 323 // to be able to traverse these. 324 IgnoreResults = true; 325} 326 327void USRGenerator::VisitObjCContainerDecl(ObjCContainerDecl *D) { 328 switch (D->getKind()) { 329 default: 330 assert(false && "Invalid ObjC container."); 331 case Decl::ObjCInterface: 332 case Decl::ObjCImplementation: 333 GenObjCClass(D->getName()); 334 break; 335 case Decl::ObjCCategory: { 336 ObjCCategoryDecl *CD = cast<ObjCCategoryDecl>(D); 337 ObjCInterfaceDecl *ID = CD->getClassInterface(); 338 if (!ID) { 339 // Handle invalid code where the @interface might not 340 // have been specified. 341 // FIXME: We should be able to generate this USR even if the 342 // @interface isn't available. 343 IgnoreResults = true; 344 return; 345 } 346 // Specially handle class extensions, which are anonymous categories. 347 // We want to mangle in the location to uniquely distinguish them. 348 if (CD->IsClassExtension()) { 349 Out << "objc(ext)" << ID->getName() << '@'; 350 GenLoc(CD); 351 } 352 else 353 GenObjCCategory(ID->getName(), CD->getName()); 354 355 break; 356 } 357 case Decl::ObjCCategoryImpl: { 358 ObjCCategoryImplDecl *CD = cast<ObjCCategoryImplDecl>(D); 359 ObjCInterfaceDecl *ID = CD->getClassInterface(); 360 if (!ID) { 361 // Handle invalid code where the @interface might not 362 // have been specified. 363 // FIXME: We should be able to generate this USR even if the 364 // @interface isn't available. 365 IgnoreResults = true; 366 return; 367 } 368 GenObjCCategory(ID->getName(), CD->getName()); 369 break; 370 } 371 case Decl::ObjCProtocol: 372 GenObjCProtocol(cast<ObjCProtocolDecl>(D)->getName()); 373 break; 374 } 375} 376 377void USRGenerator::VisitObjCPropertyDecl(ObjCPropertyDecl *D) { 378 Visit(cast<Decl>(D->getDeclContext())); 379 GenObjCProperty(D->getName()); 380} 381 382void USRGenerator::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D) { 383 if (ObjCPropertyDecl *PD = D->getPropertyDecl()) { 384 VisitObjCPropertyDecl(PD); 385 return; 386 } 387 388 IgnoreResults = true; 389} 390 391void USRGenerator::VisitTagDecl(TagDecl *D) { 392 // Add the location of the tag decl to handle resolution across 393 // translation units. 394 if (ShouldGenerateLocation(D) && GenLoc(D)) 395 return; 396 397 D = D->getCanonicalDecl(); 398 VisitDeclContext(D->getDeclContext()); 399 400 bool AlreadyStarted = false; 401 if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(D)) { 402 if (ClassTemplateDecl *ClassTmpl = CXXRecord->getDescribedClassTemplate()) { 403 AlreadyStarted = true; 404 405 switch (D->getTagKind()) { 406 case TTK_Struct: Out << "@ST"; break; 407 case TTK_Class: Out << "@CT"; break; 408 case TTK_Union: Out << "@UT"; break; 409 case TTK_Enum: llvm_unreachable("enum template"); break; 410 } 411 VisitTemplateParameterList(ClassTmpl->getTemplateParameters()); 412 } else if (ClassTemplatePartialSpecializationDecl *PartialSpec 413 = dyn_cast<ClassTemplatePartialSpecializationDecl>(CXXRecord)) { 414 AlreadyStarted = true; 415 416 switch (D->getTagKind()) { 417 case TTK_Struct: Out << "@SP"; break; 418 case TTK_Class: Out << "@CP"; break; 419 case TTK_Union: Out << "@UP"; break; 420 case TTK_Enum: llvm_unreachable("enum partial specialization"); break; 421 } 422 VisitTemplateParameterList(PartialSpec->getTemplateParameters()); 423 } 424 } 425 426 if (!AlreadyStarted) { 427 switch (D->getTagKind()) { 428 case TTK_Struct: Out << "@S"; break; 429 case TTK_Class: Out << "@C"; break; 430 case TTK_Union: Out << "@U"; break; 431 case TTK_Enum: Out << "@E"; break; 432 } 433 } 434 435 Out << '@'; 436 Out.flush(); 437 assert(Buf.size() > 0); 438 const unsigned off = Buf.size() - 1; 439 440 if (EmitDeclName(D)) { 441 if (const TypedefDecl *TD = D->getTypedefForAnonDecl()) { 442 Buf[off] = 'A'; 443 Out << '@' << TD; 444 } 445 else 446 Buf[off] = 'a'; 447 } 448 449 // For a class template specialization, mangle the template arguments. 450 if (ClassTemplateSpecializationDecl *Spec 451 = dyn_cast<ClassTemplateSpecializationDecl>(D)) { 452 const TemplateArgumentList &Args = Spec->getTemplateInstantiationArgs(); 453 Out << '>'; 454 for (unsigned I = 0, N = Args.size(); I != N; ++I) { 455 Out << '#'; 456 VisitTemplateArgument(Args.get(I)); 457 } 458 } 459} 460 461void USRGenerator::VisitTypedefDecl(TypedefDecl *D) { 462 if (ShouldGenerateLocation(D) && GenLoc(D)) 463 return; 464 DeclContext *DC = D->getDeclContext(); 465 if (NamedDecl *DCN = dyn_cast<NamedDecl>(DC)) 466 Visit(DCN); 467 Out << "@T@"; 468 Out << D->getName(); 469} 470 471void USRGenerator::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) { 472 GenLoc(D); 473 return; 474} 475 476bool USRGenerator::GenLoc(const Decl *D) { 477 if (generatedLoc) 478 return IgnoreResults; 479 generatedLoc = true; 480 481 const SourceManager &SM = AU->getSourceManager(); 482 SourceLocation L = D->getLocStart(); 483 if (L.isInvalid()) { 484 IgnoreResults = true; 485 return true; 486 } 487 L = SM.getInstantiationLoc(L); 488 const std::pair<FileID, unsigned> &Decomposed = SM.getDecomposedLoc(L); 489 const FileEntry *FE = SM.getFileEntryForID(Decomposed.first); 490 if (FE) { 491 Out << llvm::sys::path::filename(FE->getName()); 492 } 493 else { 494 // This case really isn't interesting. 495 IgnoreResults = true; 496 return true; 497 } 498 // Use the offest into the FileID to represent the location. Using 499 // a line/column can cause us to look back at the original source file, 500 // which is expensive. 501 Out << '@' << Decomposed.second; 502 return IgnoreResults; 503} 504 505void USRGenerator::VisitType(QualType T) { 506 // This method mangles in USR information for types. It can possibly 507 // just reuse the naming-mangling logic used by codegen, although the 508 // requirements for USRs might not be the same. 509 ASTContext &Ctx = AU->getASTContext(); 510 511 do { 512 T = Ctx.getCanonicalType(T); 513 Qualifiers Q = T.getQualifiers(); 514 unsigned qVal = 0; 515 if (Q.hasConst()) 516 qVal |= 0x1; 517 if (Q.hasVolatile()) 518 qVal |= 0x2; 519 if (Q.hasRestrict()) 520 qVal |= 0x4; 521 if(qVal) 522 Out << ((char) ('0' + qVal)); 523 524 // Mangle in ObjC GC qualifiers? 525 526 if (const BuiltinType *BT = T->getAs<BuiltinType>()) { 527 unsigned char c = '\0'; 528 switch (BT->getKind()) { 529 case BuiltinType::Void: 530 c = 'v'; break; 531 case BuiltinType::Bool: 532 c = 'b'; break; 533 case BuiltinType::Char_U: 534 case BuiltinType::UChar: 535 c = 'c'; break; 536 case BuiltinType::Char16: 537 c = 'q'; break; 538 case BuiltinType::Char32: 539 c = 'w'; break; 540 case BuiltinType::UShort: 541 c = 's'; break; 542 case BuiltinType::UInt: 543 c = 'i'; break; 544 case BuiltinType::ULong: 545 c = 'l'; break; 546 case BuiltinType::ULongLong: 547 c = 'k'; break; 548 case BuiltinType::UInt128: 549 c = 'j'; break; 550 case BuiltinType::Char_S: 551 case BuiltinType::SChar: 552 c = 'C'; break; 553 case BuiltinType::WChar: 554 c = 'W'; break; 555 case BuiltinType::Short: 556 c = 'S'; break; 557 case BuiltinType::Int: 558 c = 'I'; break; 559 case BuiltinType::Long: 560 c = 'L'; break; 561 case BuiltinType::LongLong: 562 c = 'K'; break; 563 case BuiltinType::Int128: 564 c = 'J'; break; 565 case BuiltinType::Float: 566 c = 'f'; break; 567 case BuiltinType::Double: 568 c = 'd'; break; 569 case BuiltinType::LongDouble: 570 c = 'D'; break; 571 case BuiltinType::NullPtr: 572 c = 'n'; break; 573 case BuiltinType::Overload: 574 case BuiltinType::Dependent: 575 case BuiltinType::UndeducedAuto: 576 IgnoreResults = true; 577 return; 578 case BuiltinType::ObjCId: 579 c = 'o'; break; 580 case BuiltinType::ObjCClass: 581 c = 'O'; break; 582 case BuiltinType::ObjCSel: 583 c = 'e'; break; 584 } 585 Out << c; 586 return; 587 } 588 589 // If we have already seen this (non-built-in) type, use a substitution 590 // encoding. 591 llvm::DenseMap<const Type *, unsigned>::iterator Substitution 592 = TypeSubstitutions.find(T.getTypePtr()); 593 if (Substitution != TypeSubstitutions.end()) { 594 Out << 'S' << Substitution->second << '_'; 595 return; 596 } else { 597 // Record this as a substitution. 598 unsigned Number = TypeSubstitutions.size(); 599 TypeSubstitutions[T.getTypePtr()] = Number; 600 } 601 602 if (const PointerType *PT = T->getAs<PointerType>()) { 603 Out << '*'; 604 T = PT->getPointeeType(); 605 continue; 606 } 607 if (const ReferenceType *RT = T->getAs<ReferenceType>()) { 608 Out << '&'; 609 T = RT->getPointeeType(); 610 continue; 611 } 612 if (const FunctionProtoType *FT = T->getAs<FunctionProtoType>()) { 613 Out << 'F'; 614 VisitType(FT->getResultType()); 615 for (FunctionProtoType::arg_type_iterator 616 I = FT->arg_type_begin(), E = FT->arg_type_end(); I!=E; ++I) { 617 VisitType(*I); 618 } 619 if (FT->isVariadic()) 620 Out << '.'; 621 return; 622 } 623 if (const BlockPointerType *BT = T->getAs<BlockPointerType>()) { 624 Out << 'B'; 625 T = BT->getPointeeType(); 626 continue; 627 } 628 if (const ComplexType *CT = T->getAs<ComplexType>()) { 629 Out << '<'; 630 T = CT->getElementType(); 631 continue; 632 } 633 if (const TagType *TT = T->getAs<TagType>()) { 634 Out << '$'; 635 VisitTagDecl(TT->getDecl()); 636 return; 637 } 638 if (const TemplateTypeParmType *TTP = T->getAs<TemplateTypeParmType>()) { 639 Out << 't' << TTP->getDepth() << '.' << TTP->getIndex(); 640 return; 641 } 642 if (const TemplateSpecializationType *Spec 643 = T->getAs<TemplateSpecializationType>()) { 644 Out << '>'; 645 VisitTemplateName(Spec->getTemplateName()); 646 Out << Spec->getNumArgs(); 647 for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I) 648 VisitTemplateArgument(Spec->getArg(I)); 649 return; 650 } 651 652 // Unhandled type. 653 Out << ' '; 654 break; 655 } while (true); 656} 657 658void USRGenerator::VisitTemplateParameterList( 659 const TemplateParameterList *Params) { 660 if (!Params) 661 return; 662 Out << '>' << Params->size(); 663 for (TemplateParameterList::const_iterator P = Params->begin(), 664 PEnd = Params->end(); 665 P != PEnd; ++P) { 666 Out << '#'; 667 if (isa<TemplateTypeParmDecl>(*P)) { 668 Out << 'T'; 669 continue; 670 } 671 672 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) { 673 Out << 'N'; 674 VisitType(NTTP->getType()); 675 continue; 676 } 677 678 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P); 679 Out << 't'; 680 VisitTemplateParameterList(TTP->getTemplateParameters()); 681 } 682} 683 684void USRGenerator::VisitTemplateName(TemplateName Name) { 685 if (TemplateDecl *Template = Name.getAsTemplateDecl()) { 686 if (TemplateTemplateParmDecl *TTP 687 = dyn_cast<TemplateTemplateParmDecl>(Template)) { 688 Out << 't' << TTP->getDepth() << '.' << TTP->getIndex(); 689 return; 690 } 691 692 Visit(Template); 693 return; 694 } 695 696 // FIXME: Visit dependent template names. 697} 698 699void USRGenerator::VisitTemplateArgument(const TemplateArgument &Arg) { 700 switch (Arg.getKind()) { 701 case TemplateArgument::Null: 702 break; 703 704 case TemplateArgument::Declaration: 705 if (Decl *D = Arg.getAsDecl()) 706 Visit(D); 707 break; 708 709 case TemplateArgument::Template: 710 VisitTemplateName(Arg.getAsTemplate()); 711 break; 712 713 case TemplateArgument::Expression: 714 // FIXME: Visit expressions. 715 break; 716 717 case TemplateArgument::Pack: 718 // FIXME: Variadic templates 719 break; 720 721 case TemplateArgument::Type: 722 VisitType(Arg.getAsType()); 723 break; 724 725 case TemplateArgument::Integral: 726 Out << 'V'; 727 VisitType(Arg.getIntegralType()); 728 Out << *Arg.getAsIntegral(); 729 break; 730 } 731} 732 733//===----------------------------------------------------------------------===// 734// General purpose USR generation methods. 735//===----------------------------------------------------------------------===// 736 737void USRGenerator::GenObjCClass(llvm::StringRef cls) { 738 Out << "objc(cs)" << cls; 739} 740 741void USRGenerator::GenObjCCategory(llvm::StringRef cls, llvm::StringRef cat) { 742 Out << "objc(cy)" << cls << '@' << cat; 743} 744 745void USRGenerator::GenObjCIvar(llvm::StringRef ivar) { 746 Out << '@' << ivar; 747} 748 749void USRGenerator::GenObjCMethod(llvm::StringRef meth, bool isInstanceMethod) { 750 Out << (isInstanceMethod ? "(im)" : "(cm)") << meth; 751} 752 753void USRGenerator::GenObjCProperty(llvm::StringRef prop) { 754 Out << "(py)" << prop; 755} 756 757void USRGenerator::GenObjCProtocol(llvm::StringRef prot) { 758 Out << "objc(pl)" << prot; 759} 760 761//===----------------------------------------------------------------------===// 762// API hooks. 763//===----------------------------------------------------------------------===// 764 765static inline llvm::StringRef extractUSRSuffix(llvm::StringRef s) { 766 return s.startswith("c:") ? s.substr(2) : ""; 767} 768 769static CXString getDeclCursorUSR(const CXCursor &C) { 770 Decl *D = cxcursor::getCursorDecl(C); 771 772 // Don't generate USRs for things with invalid locations. 773 if (!D || D->getLocStart().isInvalid()) 774 return createCXString(""); 775 776 // Check if the cursor has 'NoLinkage'. 777 if (const NamedDecl *ND = dyn_cast<NamedDecl>(D)) 778 switch (ND->getLinkage()) { 779 case ExternalLinkage: 780 // Generate USRs for all entities with external linkage. 781 break; 782 case NoLinkage: 783 case UniqueExternalLinkage: 784 // We allow enums, typedefs, and structs that have no linkage to 785 // have USRs that are anchored to the file they were defined in 786 // (e.g., the header). This is a little gross, but in principal 787 // enums/anonymous structs/etc. defined in a common header file 788 // are referred to across multiple translation units. 789 if (isa<TagDecl>(ND) || isa<TypedefDecl>(ND) || 790 isa<EnumConstantDecl>(ND) || isa<FieldDecl>(ND) || 791 isa<VarDecl>(ND) || isa<NamespaceDecl>(ND)) 792 break; 793 // Fall-through. 794 case InternalLinkage: 795 if (isa<FunctionDecl>(ND)) 796 break; 797 } 798 799 CXTranslationUnit TU = cxcursor::getCursorTU(C); 800 if (!TU) 801 return createCXString(""); 802 803 CXStringBuf *buf = cxstring::getCXStringBuf(TU); 804 if (!buf) 805 return createCXString(""); 806 807 { 808 USRGenerator UG(&C, &buf->Data); 809 UG->Visit(D); 810 811 if (UG->ignoreResults()) { 812 disposeCXStringBuf(buf); 813 return createCXString(""); 814 } 815 } 816 // Return the C-string, but don't make a copy since it is already in 817 // the string buffer. 818 buf->Data.push_back('\0'); 819 return createCXString(buf); 820} 821 822extern "C" { 823 824CXString clang_getCursorUSR(CXCursor C) { 825 const CXCursorKind &K = clang_getCursorKind(C); 826 827 if (clang_isDeclaration(K)) 828 return getDeclCursorUSR(C); 829 830 if (K == CXCursor_MacroDefinition) { 831 CXTranslationUnit TU = cxcursor::getCursorTU(C); 832 if (!TU) 833 return createCXString(""); 834 835 CXStringBuf *buf = cxstring::getCXStringBuf(TU); 836 if (!buf) 837 return createCXString(""); 838 839 { 840 USRGenerator UG(&C, &buf->Data); 841 UG << "macro@" 842 << cxcursor::getCursorMacroDefinition(C)->getName()->getNameStart(); 843 } 844 buf->Data.push_back('\0'); 845 return createCXString(buf); 846 } 847 848 return createCXString(""); 849} 850 851CXString clang_constructUSR_ObjCIvar(const char *name, CXString classUSR) { 852 USRGenerator UG; 853 UG << extractUSRSuffix(clang_getCString(classUSR)); 854 UG->GenObjCIvar(name); 855 return createCXString(UG.str(), true); 856} 857 858CXString clang_constructUSR_ObjCMethod(const char *name, 859 unsigned isInstanceMethod, 860 CXString classUSR) { 861 USRGenerator UG; 862 UG << extractUSRSuffix(clang_getCString(classUSR)); 863 UG->GenObjCMethod(name, isInstanceMethod); 864 return createCXString(UG.str(), true); 865} 866 867CXString clang_constructUSR_ObjCClass(const char *name) { 868 USRGenerator UG; 869 UG->GenObjCClass(name); 870 return createCXString(UG.str(), true); 871} 872 873CXString clang_constructUSR_ObjCProtocol(const char *name) { 874 USRGenerator UG; 875 UG->GenObjCProtocol(name); 876 return createCXString(UG.str(), true); 877} 878 879CXString clang_constructUSR_ObjCCategory(const char *class_name, 880 const char *category_name) { 881 USRGenerator UG; 882 UG->GenObjCCategory(class_name, category_name); 883 return createCXString(UG.str(), true); 884} 885 886CXString clang_constructUSR_ObjCProperty(const char *property, 887 CXString classUSR) { 888 USRGenerator UG; 889 UG << extractUSRSuffix(clang_getCString(classUSR)); 890 UG->GenObjCProperty(property); 891 return createCXString(UG.str(), true); 892} 893 894} // end extern "C" 895