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