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