CIndexUSRs.cpp revision e1c2c2023ee160bd3051682faff04c4f9c5e8ebd
1f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)//===- CIndexUSR.cpp - Clang-C Source Indexing Library --------------------===//
2f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)//
3f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)//                     The LLVM Compiler Infrastructure
4f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)//
5f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)// This file is distributed under the University of Illinois Open Source
6f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)// License. See LICENSE.TXT for details.
7f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)//
8f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)//===----------------------------------------------------------------------===//
9f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)//
10f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)// This file implements the generation and use of USRs from CXEntities.
11f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)//
12f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)//===----------------------------------------------------------------------===//
13f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)
14f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)#include "CIndexer.h"
15f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)#include "CXCursor.h"
16f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)#include "CXString.h"
171320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci#include "clang/AST/DeclTemplate.h"
18f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)#include "clang/AST/DeclVisitor.h"
191320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci#include "clang/Frontend/ASTUnit.h"
20f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)#include "clang/Lex/PreprocessingRecord.h"
21f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)#include "llvm/ADT/SmallString.h"
22f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)#include "llvm/Support/raw_ostream.h"
23f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)
24f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)using namespace clang;
25f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)using namespace clang::cxstring;
26f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)
27f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)//===----------------------------------------------------------------------===//
28f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)// USR generation.
29f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)//===----------------------------------------------------------------------===//
30f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)
31f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)namespace {
32f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)class USRGenerator : public DeclVisitor<USRGenerator> {
33f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)  OwningPtr<SmallString<128> > OwnedBuf;
34f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)  SmallVectorImpl<char> &Buf;
35f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)  llvm::raw_svector_ostream Out;
36f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)  bool IgnoreResults;
37f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)  ASTContext *Context;
38f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)  bool generatedLoc;
39f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)
40f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)  llvm::DenseMap<const Type *, unsigned> TypeSubstitutions;
41f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)
42f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)public:
43f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)  explicit USRGenerator(ASTContext *Ctx = 0, SmallVectorImpl<char> *extBuf = 0)
44f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)  : OwnedBuf(extBuf ? 0 : new SmallString<128>()),
45f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)    Buf(extBuf ? *extBuf : *OwnedBuf.get()),
46f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)    Out(Buf),
47f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)    IgnoreResults(false),
481320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci    Context(Ctx),
49f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)    generatedLoc(false)
50f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)  {
51f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)    // Add the USR space prefix.
52f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)    Out << "c:";
531320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci  }
54f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)
55f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)  StringRef str() {
56f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)    return Out.str();
57f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)  }
58f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)
59f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)  USRGenerator* operator->() { return this; }
60f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)
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
145bool 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
154static inline bool ShouldGenerateLocation(const NamedDecl *D) {
155  return D->getLinkage() != ExternalLinkage;
156}
157
158void USRGenerator::VisitDeclContext(DeclContext *DC) {
159  if (NamedDecl *D = dyn_cast<NamedDecl>(DC))
160    Visit(D);
161}
162
163void 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
178void 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
222void 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
235void 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
257void USRGenerator::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
258  GenLoc(D);
259  return;
260}
261
262void USRGenerator::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
263  GenLoc(D);
264  return;
265}
266
267void 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
278void USRGenerator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
279  VisitFunctionDecl(D->getTemplatedDecl());
280}
281
282void USRGenerator::VisitClassTemplateDecl(ClassTemplateDecl *D) {
283  VisitTagDecl(D->getTemplatedDecl());
284}
285
286void USRGenerator::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
287  VisitDeclContext(D->getDeclContext());
288  if (!IgnoreResults)
289    Out << "@NA@" << D->getName();
290}
291
292void 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
315void 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
365void 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
375void USRGenerator::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D) {
376  if (ObjCPropertyDecl *PD = D->getPropertyDecl()) {
377    VisitObjCPropertyDecl(PD);
378    return;
379  }
380
381  IgnoreResults = true;
382}
383
384void 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
457void 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
467void USRGenerator::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
468  GenLoc(D);
469  return;
470}
471
472bool 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
510void 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          IgnoreResults = true;
591          return;
592        case BuiltinType::ObjCId:
593          c = 'o'; break;
594        case BuiltinType::ObjCClass:
595          c = 'O'; break;
596        case BuiltinType::ObjCSel:
597          c = 'e'; break;
598      }
599      Out << c;
600      return;
601    }
602
603    // If we have already seen this (non-built-in) type, use a substitution
604    // encoding.
605    llvm::DenseMap<const Type *, unsigned>::iterator Substitution
606      = TypeSubstitutions.find(T.getTypePtr());
607    if (Substitution != TypeSubstitutions.end()) {
608      Out << 'S' << Substitution->second << '_';
609      return;
610    } else {
611      // Record this as a substitution.
612      unsigned Number = TypeSubstitutions.size();
613      TypeSubstitutions[T.getTypePtr()] = Number;
614    }
615
616    if (const PointerType *PT = T->getAs<PointerType>()) {
617      Out << '*';
618      T = PT->getPointeeType();
619      continue;
620    }
621    if (const ReferenceType *RT = T->getAs<ReferenceType>()) {
622      Out << '&';
623      T = RT->getPointeeType();
624      continue;
625    }
626    if (const FunctionProtoType *FT = T->getAs<FunctionProtoType>()) {
627      Out << 'F';
628      VisitType(FT->getResultType());
629      for (FunctionProtoType::arg_type_iterator
630            I = FT->arg_type_begin(), E = FT->arg_type_end(); I!=E; ++I) {
631        VisitType(*I);
632      }
633      if (FT->isVariadic())
634        Out << '.';
635      return;
636    }
637    if (const BlockPointerType *BT = T->getAs<BlockPointerType>()) {
638      Out << 'B';
639      T = BT->getPointeeType();
640      continue;
641    }
642    if (const ComplexType *CT = T->getAs<ComplexType>()) {
643      Out << '<';
644      T = CT->getElementType();
645      continue;
646    }
647    if (const TagType *TT = T->getAs<TagType>()) {
648      Out << '$';
649      VisitTagDecl(TT->getDecl());
650      return;
651    }
652    if (const TemplateTypeParmType *TTP = T->getAs<TemplateTypeParmType>()) {
653      Out << 't' << TTP->getDepth() << '.' << TTP->getIndex();
654      return;
655    }
656    if (const TemplateSpecializationType *Spec
657                                    = T->getAs<TemplateSpecializationType>()) {
658      Out << '>';
659      VisitTemplateName(Spec->getTemplateName());
660      Out << Spec->getNumArgs();
661      for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I)
662        VisitTemplateArgument(Spec->getArg(I));
663      return;
664    }
665
666    // Unhandled type.
667    Out << ' ';
668    break;
669  } while (true);
670}
671
672void USRGenerator::VisitTemplateParameterList(
673                                         const TemplateParameterList *Params) {
674  if (!Params)
675    return;
676  Out << '>' << Params->size();
677  for (TemplateParameterList::const_iterator P = Params->begin(),
678                                          PEnd = Params->end();
679       P != PEnd; ++P) {
680    Out << '#';
681    if (isa<TemplateTypeParmDecl>(*P)) {
682      if (cast<TemplateTypeParmDecl>(*P)->isParameterPack())
683        Out<< 'p';
684      Out << 'T';
685      continue;
686    }
687
688    if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
689      if (NTTP->isParameterPack())
690        Out << 'p';
691      Out << 'N';
692      VisitType(NTTP->getType());
693      continue;
694    }
695
696    TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
697    if (TTP->isParameterPack())
698      Out << 'p';
699    Out << 't';
700    VisitTemplateParameterList(TTP->getTemplateParameters());
701  }
702}
703
704void USRGenerator::VisitTemplateName(TemplateName Name) {
705  if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
706    if (TemplateTemplateParmDecl *TTP
707                              = dyn_cast<TemplateTemplateParmDecl>(Template)) {
708      Out << 't' << TTP->getDepth() << '.' << TTP->getIndex();
709      return;
710    }
711
712    Visit(Template);
713    return;
714  }
715
716  // FIXME: Visit dependent template names.
717}
718
719void USRGenerator::VisitTemplateArgument(const TemplateArgument &Arg) {
720  switch (Arg.getKind()) {
721  case TemplateArgument::Null:
722    break;
723
724  case TemplateArgument::Declaration:
725    Visit(Arg.getAsDecl());
726    break;
727
728  case TemplateArgument::NullPtr:
729    break;
730
731  case TemplateArgument::TemplateExpansion:
732    Out << 'P'; // pack expansion of...
733    // Fall through
734  case TemplateArgument::Template:
735    VisitTemplateName(Arg.getAsTemplateOrTemplatePattern());
736    break;
737
738  case TemplateArgument::Expression:
739    // FIXME: Visit expressions.
740    break;
741
742  case TemplateArgument::Pack:
743    Out << 'p' << Arg.pack_size();
744    for (TemplateArgument::pack_iterator P = Arg.pack_begin(), PEnd = Arg.pack_end();
745         P != PEnd; ++P)
746      VisitTemplateArgument(*P);
747    break;
748
749  case TemplateArgument::Type:
750    VisitType(Arg.getAsType());
751    break;
752
753  case TemplateArgument::Integral:
754    Out << 'V';
755    VisitType(Arg.getIntegralType());
756    Out << Arg.getAsIntegral();
757    break;
758  }
759}
760
761//===----------------------------------------------------------------------===//
762// General purpose USR generation methods.
763//===----------------------------------------------------------------------===//
764
765void USRGenerator::GenObjCClass(StringRef cls) {
766  Out << "objc(cs)" << cls;
767}
768
769void USRGenerator::GenObjCCategory(StringRef cls, StringRef cat) {
770  Out << "objc(cy)" << cls << '@' << cat;
771}
772
773void USRGenerator::GenObjCIvar(StringRef ivar) {
774  Out << '@' << ivar;
775}
776
777void USRGenerator::GenObjCMethod(StringRef meth, bool isInstanceMethod) {
778  Out << (isInstanceMethod ? "(im)" : "(cm)") << meth;
779}
780
781void USRGenerator::GenObjCProperty(StringRef prop) {
782  Out << "(py)" << prop;
783}
784
785void USRGenerator::GenObjCProtocol(StringRef prot) {
786  Out << "objc(pl)" << prot;
787}
788
789//===----------------------------------------------------------------------===//
790// API hooks.
791//===----------------------------------------------------------------------===//
792
793static inline StringRef extractUSRSuffix(StringRef s) {
794  return s.startswith("c:") ? s.substr(2) : "";
795}
796
797bool cxcursor::getDeclCursorUSR(const Decl *D, SmallVectorImpl<char> &Buf) {
798  // Don't generate USRs for things with invalid locations.
799  if (!D || D->getLocStart().isInvalid())
800    return true;
801
802  USRGenerator UG(&D->getASTContext(), &Buf);
803  UG->Visit(const_cast<Decl*>(D));
804
805  if (UG->ignoreResults())
806    return true;
807
808  return false;
809}
810
811extern "C" {
812
813CXString clang_getCursorUSR(CXCursor C) {
814  const CXCursorKind &K = clang_getCursorKind(C);
815
816  if (clang_isDeclaration(K)) {
817    Decl *D = cxcursor::getCursorDecl(C);
818    if (!D)
819      return createCXString("");
820
821    CXTranslationUnit TU = cxcursor::getCursorTU(C);
822    if (!TU)
823      return createCXString("");
824
825    CXStringBuf *buf = cxstring::getCXStringBuf(TU);
826    if (!buf)
827      return createCXString("");
828
829    bool Ignore = cxcursor::getDeclCursorUSR(D, buf->Data);
830    if (Ignore) {
831      disposeCXStringBuf(buf);
832      return createCXString("");
833    }
834
835    // Return the C-string, but don't make a copy since it is already in
836    // the string buffer.
837    buf->Data.push_back('\0');
838    return createCXString(buf);
839  }
840
841  if (K == CXCursor_MacroDefinition) {
842    CXTranslationUnit TU = cxcursor::getCursorTU(C);
843    if (!TU)
844      return createCXString("");
845
846    CXStringBuf *buf = cxstring::getCXStringBuf(TU);
847    if (!buf)
848      return createCXString("");
849
850    {
851      USRGenerator UG(&cxcursor::getCursorASTUnit(C)->getASTContext(),
852                      &buf->Data);
853      UG << "macro@"
854        << cxcursor::getCursorMacroDefinition(C)->getName()->getNameStart();
855    }
856    buf->Data.push_back('\0');
857    return createCXString(buf);
858  }
859
860  return createCXString("");
861}
862
863CXString clang_constructUSR_ObjCIvar(const char *name, CXString classUSR) {
864  USRGenerator UG;
865  UG << extractUSRSuffix(clang_getCString(classUSR));
866  UG->GenObjCIvar(name);
867  return createCXString(UG.str(), true);
868}
869
870CXString clang_constructUSR_ObjCMethod(const char *name,
871                                       unsigned isInstanceMethod,
872                                       CXString classUSR) {
873  USRGenerator UG;
874  UG << extractUSRSuffix(clang_getCString(classUSR));
875  UG->GenObjCMethod(name, isInstanceMethod);
876  return createCXString(UG.str(), true);
877}
878
879CXString clang_constructUSR_ObjCClass(const char *name) {
880  USRGenerator UG;
881  UG->GenObjCClass(name);
882  return createCXString(UG.str(), true);
883}
884
885CXString clang_constructUSR_ObjCProtocol(const char *name) {
886  USRGenerator UG;
887  UG->GenObjCProtocol(name);
888  return createCXString(UG.str(), true);
889}
890
891CXString clang_constructUSR_ObjCCategory(const char *class_name,
892                                         const char *category_name) {
893  USRGenerator UG;
894  UG->GenObjCCategory(class_name, category_name);
895  return createCXString(UG.str(), true);
896}
897
898CXString clang_constructUSR_ObjCProperty(const char *property,
899                                         CXString classUSR) {
900  USRGenerator UG;
901  UG << extractUSRSuffix(clang_getCString(classUSR));
902  UG->GenObjCProperty(property);
903  return createCXString(UG.str(), true);
904}
905
906} // end extern "C"
907