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