xref: /llvm-project/clang/tools/libclang/CIndexUSRs.cpp (revision d8a08ea98d974b8efa200abd760dddb995425959)
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 inline bool ShouldGenerateLocation(const NamedDecl *D) {
155   return D->getLinkage() != ExternalLinkage;
156 }
157 
158 void USRGenerator::VisitDeclContext(DeclContext *DC) {
159   if (NamedDecl *D = dyn_cast<NamedDecl>(DC))
160     Visit(D);
161 }
162 
163 void USRGenerator::VisitFieldDecl(FieldDecl *D) {
164   // The USR for an ivar declared in a class extension is based on the
165   // ObjCInterfaceDecl, not the ObjCCategoryDecl.
166   if (ObjCInterfaceDecl *ID = Context->getObjContainingInterface(D))
167     Visit(ID);
168   else
169     VisitDeclContext(D->getDeclContext());
170   Out << (isa<ObjCIvarDecl>(D) ? "@" : "@FI@");
171   if (EmitDeclName(D)) {
172     // Bit fields can be anonymous.
173     IgnoreResults = true;
174     return;
175   }
176 }
177 
178 void USRGenerator::VisitFunctionDecl(FunctionDecl *D) {
179   if (ShouldGenerateLocation(D) && GenLoc(D))
180     return;
181 
182   VisitDeclContext(D->getDeclContext());
183   if (FunctionTemplateDecl *FunTmpl = D->getDescribedFunctionTemplate()) {
184     Out << "@FT@";
185     VisitTemplateParameterList(FunTmpl->getTemplateParameters());
186   } else
187     Out << "@F@";
188   D->printName(Out);
189 
190   ASTContext &Ctx = *Context;
191   if (!Ctx.getLangOpts().CPlusPlus || D->isExternC())
192     return;
193 
194   if (const TemplateArgumentList *
195         SpecArgs = D->getTemplateSpecializationArgs()) {
196     Out << '<';
197     for (unsigned I = 0, N = SpecArgs->size(); I != N; ++I) {
198       Out << '#';
199       VisitTemplateArgument(SpecArgs->get(I));
200     }
201     Out << '>';
202   }
203 
204   // Mangle in type information for the arguments.
205   for (FunctionDecl::param_iterator I = D->param_begin(), E = D->param_end();
206        I != E; ++I) {
207     Out << '#';
208     if (ParmVarDecl *PD = *I)
209       VisitType(PD->getType());
210   }
211   if (D->isVariadic())
212     Out << '.';
213   Out << '#';
214   if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
215     if (MD->isStatic())
216       Out << 'S';
217     if (unsigned quals = MD->getTypeQualifiers())
218       Out << (char)('0' + quals);
219   }
220 }
221 
222 void USRGenerator::VisitNamedDecl(NamedDecl *D) {
223   VisitDeclContext(D->getDeclContext());
224   Out << "@";
225 
226   if (EmitDeclName(D)) {
227     // The string can be empty if the declaration has no name; e.g., it is
228     // the ParmDecl with no name for declaration of a function pointer type,
229     // e.g.: void  (*f)(void *);
230     // In this case, don't generate a USR.
231     IgnoreResults = true;
232   }
233 }
234 
235 void USRGenerator::VisitVarDecl(VarDecl *D) {
236   // VarDecls can be declared 'extern' within a function or method body,
237   // but their enclosing DeclContext is the function, not the TU.  We need
238   // to check the storage class to correctly generate the USR.
239   if (ShouldGenerateLocation(D) && GenLoc(D))
240     return;
241 
242   VisitDeclContext(D->getDeclContext());
243 
244   // Variables always have simple names.
245   StringRef s = D->getName();
246 
247   // The string can be empty if the declaration has no name; e.g., it is
248   // the ParmDecl with no name for declaration of a function pointer type, e.g.:
249   //    void  (*f)(void *);
250   // In this case, don't generate a USR.
251   if (s.empty())
252     IgnoreResults = true;
253   else
254     Out << '@' << s;
255 }
256 
257 void USRGenerator::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
258   GenLoc(D);
259   return;
260 }
261 
262 void USRGenerator::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
263   GenLoc(D);
264   return;
265 }
266 
267 void USRGenerator::VisitNamespaceDecl(NamespaceDecl *D) {
268   if (D->isAnonymousNamespace()) {
269     Out << "@aN";
270     return;
271   }
272 
273   VisitDeclContext(D->getDeclContext());
274   if (!IgnoreResults)
275     Out << "@N@" << D->getName();
276 }
277 
278 void USRGenerator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
279   VisitFunctionDecl(D->getTemplatedDecl());
280 }
281 
282 void USRGenerator::VisitClassTemplateDecl(ClassTemplateDecl *D) {
283   VisitTagDecl(D->getTemplatedDecl());
284 }
285 
286 void USRGenerator::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
287   VisitDeclContext(D->getDeclContext());
288   if (!IgnoreResults)
289     Out << "@NA@" << D->getName();
290 }
291 
292 void USRGenerator::VisitObjCMethodDecl(ObjCMethodDecl *D) {
293   DeclContext *container = D->getDeclContext();
294   if (ObjCProtocolDecl *pd = dyn_cast<ObjCProtocolDecl>(container)) {
295     Visit(pd);
296   }
297   else {
298     // The USR for a method declared in a class extension or category is based on
299     // the ObjCInterfaceDecl, not the ObjCCategoryDecl.
300     ObjCInterfaceDecl *ID = D->getClassInterface();
301     if (!ID) {
302       IgnoreResults = true;
303       return;
304     }
305     Visit(ID);
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 
315 void USRGenerator::VisitObjCContainerDecl(ObjCContainerDecl *D) {
316   switch (D->getKind()) {
317     default:
318       llvm_unreachable("Invalid ObjC container.");
319     case Decl::ObjCInterface:
320     case Decl::ObjCImplementation:
321       GenObjCClass(D->getName());
322       break;
323     case Decl::ObjCCategory: {
324       ObjCCategoryDecl *CD = cast<ObjCCategoryDecl>(D);
325       ObjCInterfaceDecl *ID = CD->getClassInterface();
326       if (!ID) {
327         // Handle invalid code where the @interface might not
328         // have been specified.
329         // FIXME: We should be able to generate this USR even if the
330         // @interface isn't available.
331         IgnoreResults = true;
332         return;
333       }
334       // Specially handle class extensions, which are anonymous categories.
335       // We want to mangle in the location to uniquely distinguish them.
336       if (CD->IsClassExtension()) {
337         Out << "objc(ext)" << ID->getName() << '@';
338         GenLoc(CD);
339       }
340       else
341         GenObjCCategory(ID->getName(), CD->getName());
342 
343       break;
344     }
345     case Decl::ObjCCategoryImpl: {
346       ObjCCategoryImplDecl *CD = cast<ObjCCategoryImplDecl>(D);
347       ObjCInterfaceDecl *ID = CD->getClassInterface();
348       if (!ID) {
349         // Handle invalid code where the @interface might not
350         // have been specified.
351         // FIXME: We should be able to generate this USR even if the
352         // @interface isn't available.
353         IgnoreResults = true;
354         return;
355       }
356       GenObjCCategory(ID->getName(), CD->getName());
357       break;
358     }
359     case Decl::ObjCProtocol:
360       GenObjCProtocol(cast<ObjCProtocolDecl>(D)->getName());
361       break;
362   }
363 }
364 
365 void USRGenerator::VisitObjCPropertyDecl(ObjCPropertyDecl *D) {
366   // The USR for a property declared in a class extension or category is based
367   // on the ObjCInterfaceDecl, not the ObjCCategoryDecl.
368   if (ObjCInterfaceDecl *ID = Context->getObjContainingInterface(D))
369     Visit(ID);
370   else
371     Visit(cast<Decl>(D->getDeclContext()));
372   GenObjCProperty(D->getName());
373 }
374 
375 void USRGenerator::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D) {
376   if (ObjCPropertyDecl *PD = D->getPropertyDecl()) {
377     VisitObjCPropertyDecl(PD);
378     return;
379   }
380 
381   IgnoreResults = true;
382 }
383 
384 void USRGenerator::VisitTagDecl(TagDecl *D) {
385   // Add the location of the tag decl to handle resolution across
386   // translation units.
387   if (ShouldGenerateLocation(D) && GenLoc(D))
388     return;
389 
390   D = D->getCanonicalDecl();
391   VisitDeclContext(D->getDeclContext());
392 
393   bool AlreadyStarted = false;
394   if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(D)) {
395     if (ClassTemplateDecl *ClassTmpl = CXXRecord->getDescribedClassTemplate()) {
396       AlreadyStarted = true;
397 
398       switch (D->getTagKind()) {
399       case TTK_Interface:
400       case TTK_Struct: Out << "@ST"; break;
401       case TTK_Class:  Out << "@CT"; break;
402       case TTK_Union:  Out << "@UT"; break;
403       case TTK_Enum: llvm_unreachable("enum template");
404       }
405       VisitTemplateParameterList(ClassTmpl->getTemplateParameters());
406     } else if (ClassTemplatePartialSpecializationDecl *PartialSpec
407                 = dyn_cast<ClassTemplatePartialSpecializationDecl>(CXXRecord)) {
408       AlreadyStarted = true;
409 
410       switch (D->getTagKind()) {
411       case TTK_Interface:
412       case TTK_Struct: Out << "@SP"; break;
413       case TTK_Class:  Out << "@CP"; break;
414       case TTK_Union:  Out << "@UP"; break;
415       case TTK_Enum: llvm_unreachable("enum partial specialization");
416       }
417       VisitTemplateParameterList(PartialSpec->getTemplateParameters());
418     }
419   }
420 
421   if (!AlreadyStarted) {
422     switch (D->getTagKind()) {
423       case TTK_Interface:
424       case TTK_Struct: Out << "@S"; break;
425       case TTK_Class:  Out << "@C"; break;
426       case TTK_Union:  Out << "@U"; break;
427       case TTK_Enum:   Out << "@E"; break;
428     }
429   }
430 
431   Out << '@';
432   Out.flush();
433   assert(Buf.size() > 0);
434   const unsigned off = Buf.size() - 1;
435 
436   if (EmitDeclName(D)) {
437     if (const TypedefNameDecl *TD = D->getTypedefNameForAnonDecl()) {
438       Buf[off] = 'A';
439       Out << '@' << *TD;
440     }
441     else
442       Buf[off] = 'a';
443   }
444 
445   // For a class template specialization, mangle the template arguments.
446   if (ClassTemplateSpecializationDecl *Spec
447                               = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
448     const TemplateArgumentList &Args = Spec->getTemplateInstantiationArgs();
449     Out << '>';
450     for (unsigned I = 0, N = Args.size(); I != N; ++I) {
451       Out << '#';
452       VisitTemplateArgument(Args.get(I));
453     }
454   }
455 }
456 
457 void USRGenerator::VisitTypedefDecl(TypedefDecl *D) {
458   if (ShouldGenerateLocation(D) && GenLoc(D))
459     return;
460   DeclContext *DC = D->getDeclContext();
461   if (NamedDecl *DCN = dyn_cast<NamedDecl>(DC))
462     Visit(DCN);
463   Out << "@T@";
464   Out << D->getName();
465 }
466 
467 void USRGenerator::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
468   GenLoc(D);
469   return;
470 }
471 
472 bool USRGenerator::GenLoc(const Decl *D) {
473   if (generatedLoc)
474     return IgnoreResults;
475   generatedLoc = true;
476 
477   // Guard against null declarations in invalid code.
478   if (!D) {
479     IgnoreResults = true;
480     return true;
481   }
482 
483   // Use the location of canonical decl.
484   D = D->getCanonicalDecl();
485 
486   const SourceManager &SM = Context->getSourceManager();
487   SourceLocation L = D->getLocStart();
488   if (L.isInvalid()) {
489     IgnoreResults = true;
490     return true;
491   }
492   L = SM.getExpansionLoc(L);
493   const std::pair<FileID, unsigned> &Decomposed = SM.getDecomposedLoc(L);
494   const FileEntry *FE = SM.getFileEntryForID(Decomposed.first);
495   if (FE) {
496     Out << llvm::sys::path::filename(FE->getName());
497   }
498   else {
499     // This case really isn't interesting.
500     IgnoreResults = true;
501     return true;
502   }
503   // Use the offest into the FileID to represent the location.  Using
504   // a line/column can cause us to look back at the original source file,
505   // which is expensive.
506   Out << '@' << Decomposed.second;
507   return IgnoreResults;
508 }
509 
510 void USRGenerator::VisitType(QualType T) {
511   // This method mangles in USR information for types.  It can possibly
512   // just reuse the naming-mangling logic used by codegen, although the
513   // requirements for USRs might not be the same.
514   ASTContext &Ctx = *Context;
515 
516   do {
517     T = Ctx.getCanonicalType(T);
518     Qualifiers Q = T.getQualifiers();
519     unsigned qVal = 0;
520     if (Q.hasConst())
521       qVal |= 0x1;
522     if (Q.hasVolatile())
523       qVal |= 0x2;
524     if (Q.hasRestrict())
525       qVal |= 0x4;
526     if(qVal)
527       Out << ((char) ('0' + qVal));
528 
529     // Mangle in ObjC GC qualifiers?
530 
531     if (const PackExpansionType *Expansion = T->getAs<PackExpansionType>()) {
532       Out << 'P';
533       T = Expansion->getPattern();
534     }
535 
536     if (const BuiltinType *BT = T->getAs<BuiltinType>()) {
537       unsigned char c = '\0';
538       switch (BT->getKind()) {
539         case BuiltinType::Void:
540           c = 'v'; break;
541         case BuiltinType::Bool:
542           c = 'b'; break;
543         case BuiltinType::Char_U:
544         case BuiltinType::UChar:
545           c = 'c'; break;
546         case BuiltinType::Char16:
547           c = 'q'; break;
548         case BuiltinType::Char32:
549           c = 'w'; break;
550         case BuiltinType::UShort:
551           c = 's'; break;
552         case BuiltinType::UInt:
553           c = 'i'; break;
554         case BuiltinType::ULong:
555           c = 'l'; break;
556         case BuiltinType::ULongLong:
557           c = 'k'; break;
558         case BuiltinType::UInt128:
559           c = 'j'; break;
560         case BuiltinType::Char_S:
561         case BuiltinType::SChar:
562           c = 'C'; break;
563         case BuiltinType::WChar_S:
564         case BuiltinType::WChar_U:
565           c = 'W'; break;
566         case BuiltinType::Short:
567           c = 'S'; break;
568         case BuiltinType::Int:
569           c = 'I'; break;
570         case BuiltinType::Long:
571           c = 'L'; break;
572         case BuiltinType::LongLong:
573           c = 'K'; break;
574         case BuiltinType::Int128:
575           c = 'J'; break;
576         case BuiltinType::Half:
577           c = 'h'; break;
578         case BuiltinType::Float:
579           c = 'f'; break;
580         case BuiltinType::Double:
581           c = 'd'; break;
582         case BuiltinType::LongDouble:
583           c = 'D'; break;
584         case BuiltinType::NullPtr:
585           c = 'n'; break;
586 #define BUILTIN_TYPE(Id, SingletonId)
587 #define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id:
588 #include "clang/AST/BuiltinTypes.def"
589         case BuiltinType::Dependent:
590         case BuiltinType::OCLImage1d:
591         case BuiltinType::OCLImage1dArray:
592         case BuiltinType::OCLImage1dBuffer:
593         case BuiltinType::OCLImage2d:
594         case BuiltinType::OCLImage2dArray:
595         case BuiltinType::OCLImage3d:
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     Visit(Arg.getAsDecl());
732     break;
733 
734   case TemplateArgument::NullPtr:
735     break;
736 
737   case TemplateArgument::TemplateExpansion:
738     Out << 'P'; // pack expansion of...
739     // Fall through
740   case TemplateArgument::Template:
741     VisitTemplateName(Arg.getAsTemplateOrTemplatePattern());
742     break;
743 
744   case TemplateArgument::Expression:
745     // FIXME: Visit expressions.
746     break;
747 
748   case TemplateArgument::Pack:
749     Out << 'p' << Arg.pack_size();
750     for (TemplateArgument::pack_iterator P = Arg.pack_begin(), PEnd = Arg.pack_end();
751          P != PEnd; ++P)
752       VisitTemplateArgument(*P);
753     break;
754 
755   case TemplateArgument::Type:
756     VisitType(Arg.getAsType());
757     break;
758 
759   case TemplateArgument::Integral:
760     Out << 'V';
761     VisitType(Arg.getIntegralType());
762     Out << Arg.getAsIntegral();
763     break;
764   }
765 }
766 
767 //===----------------------------------------------------------------------===//
768 // General purpose USR generation methods.
769 //===----------------------------------------------------------------------===//
770 
771 void USRGenerator::GenObjCClass(StringRef cls) {
772   Out << "objc(cs)" << cls;
773 }
774 
775 void USRGenerator::GenObjCCategory(StringRef cls, StringRef cat) {
776   Out << "objc(cy)" << cls << '@' << cat;
777 }
778 
779 void USRGenerator::GenObjCIvar(StringRef ivar) {
780   Out << '@' << ivar;
781 }
782 
783 void USRGenerator::GenObjCMethod(StringRef meth, bool isInstanceMethod) {
784   Out << (isInstanceMethod ? "(im)" : "(cm)") << meth;
785 }
786 
787 void USRGenerator::GenObjCProperty(StringRef prop) {
788   Out << "(py)" << prop;
789 }
790 
791 void USRGenerator::GenObjCProtocol(StringRef prot) {
792   Out << "objc(pl)" << prot;
793 }
794 
795 //===----------------------------------------------------------------------===//
796 // API hooks.
797 //===----------------------------------------------------------------------===//
798 
799 static inline StringRef extractUSRSuffix(StringRef s) {
800   return s.startswith("c:") ? s.substr(2) : "";
801 }
802 
803 bool cxcursor::getDeclCursorUSR(const Decl *D, SmallVectorImpl<char> &Buf) {
804   // Don't generate USRs for things with invalid locations.
805   if (!D || D->getLocStart().isInvalid())
806     return true;
807 
808   USRGenerator UG(&D->getASTContext(), &Buf);
809   UG->Visit(const_cast<Decl*>(D));
810 
811   if (UG->ignoreResults())
812     return true;
813 
814   return false;
815 }
816 
817 extern "C" {
818 
819 CXString clang_getCursorUSR(CXCursor C) {
820   const CXCursorKind &K = clang_getCursorKind(C);
821 
822   if (clang_isDeclaration(K)) {
823     Decl *D = cxcursor::getCursorDecl(C);
824     if (!D)
825       return createCXString("");
826 
827     CXTranslationUnit TU = cxcursor::getCursorTU(C);
828     if (!TU)
829       return createCXString("");
830 
831     CXStringBuf *buf = cxstring::getCXStringBuf(TU);
832     if (!buf)
833       return createCXString("");
834 
835     bool Ignore = cxcursor::getDeclCursorUSR(D, buf->Data);
836     if (Ignore) {
837       disposeCXStringBuf(buf);
838       return createCXString("");
839     }
840 
841     // Return the C-string, but don't make a copy since it is already in
842     // the string buffer.
843     buf->Data.push_back('\0');
844     return createCXString(buf);
845   }
846 
847   if (K == CXCursor_MacroDefinition) {
848     CXTranslationUnit TU = cxcursor::getCursorTU(C);
849     if (!TU)
850       return createCXString("");
851 
852     CXStringBuf *buf = cxstring::getCXStringBuf(TU);
853     if (!buf)
854       return createCXString("");
855 
856     {
857       USRGenerator UG(&cxcursor::getCursorASTUnit(C)->getASTContext(),
858                       &buf->Data);
859       UG << "macro@"
860         << cxcursor::getCursorMacroDefinition(C)->getName()->getNameStart();
861     }
862     buf->Data.push_back('\0');
863     return createCXString(buf);
864   }
865 
866   return createCXString("");
867 }
868 
869 CXString clang_constructUSR_ObjCIvar(const char *name, CXString classUSR) {
870   USRGenerator UG;
871   UG << extractUSRSuffix(clang_getCString(classUSR));
872   UG->GenObjCIvar(name);
873   return createCXString(UG.str(), true);
874 }
875 
876 CXString clang_constructUSR_ObjCMethod(const char *name,
877                                        unsigned isInstanceMethod,
878                                        CXString classUSR) {
879   USRGenerator UG;
880   UG << extractUSRSuffix(clang_getCString(classUSR));
881   UG->GenObjCMethod(name, isInstanceMethod);
882   return createCXString(UG.str(), true);
883 }
884 
885 CXString clang_constructUSR_ObjCClass(const char *name) {
886   USRGenerator UG;
887   UG->GenObjCClass(name);
888   return createCXString(UG.str(), true);
889 }
890 
891 CXString clang_constructUSR_ObjCProtocol(const char *name) {
892   USRGenerator UG;
893   UG->GenObjCProtocol(name);
894   return createCXString(UG.str(), true);
895 }
896 
897 CXString clang_constructUSR_ObjCCategory(const char *class_name,
898                                          const char *category_name) {
899   USRGenerator UG;
900   UG->GenObjCCategory(class_name, category_name);
901   return createCXString(UG.str(), true);
902 }
903 
904 CXString clang_constructUSR_ObjCProperty(const char *property,
905                                          CXString classUSR) {
906   USRGenerator UG;
907   UG << extractUSRSuffix(clang_getCString(classUSR));
908   UG->GenObjCProperty(property);
909   return createCXString(UG.str(), true);
910 }
911 
912 } // end extern "C"
913