blob: eac74fa8b0ef21510b20963a521f0f857c203908 [file] [log] [blame]
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001//===- 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 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
42public:
43 explicit USRGenerator(ASTContext *Ctx = 0, SmallVectorImpl<char> *extBuf = 0)
44 : OwnedBuf(extBuf ? 0 : new SmallString<128>()),
45 Buf(extBuf ? *extBuf : *OwnedBuf.get()),
46 Out(Buf),
47 IgnoreResults(false),
48 Context(Ctx),
49 generatedLoc(false)
50 {
51 // Add the USR space prefix.
52 Out << "c:";
53 }
54
55 StringRef str() {
56 return Out.str();
57 }
58
59 USRGenerator* operator->() { return this; }
60
61 template <typename T>
62 llvm::raw_svector_ostream &operator<<(const T &x) {
63 Out << x;
64 return Out;
65 }
66
67 bool ignoreResults() const { return IgnoreResults; }
68
69 // Visitation methods from generating USRs from AST elements.
70 void VisitDeclContext(DeclContext *D);
71 void VisitFieldDecl(FieldDecl *D);
72 void VisitFunctionDecl(FunctionDecl *D);
73 void VisitNamedDecl(NamedDecl *D);
74 void VisitNamespaceDecl(NamespaceDecl *D);
75 void VisitNamespaceAliasDecl(NamespaceAliasDecl *D);
76 void VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
77 void VisitClassTemplateDecl(ClassTemplateDecl *D);
78 void VisitObjCContainerDecl(ObjCContainerDecl *CD);
79 void VisitObjCMethodDecl(ObjCMethodDecl *MD);
80 void VisitObjCPropertyDecl(ObjCPropertyDecl *D);
81 void VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D);
82 void VisitTagDecl(TagDecl *D);
83 void VisitTypedefDecl(TypedefDecl *D);
84 void VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
85 void VisitVarDecl(VarDecl *D);
86 void VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D);
87 void VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D);
88 void VisitLinkageSpecDecl(LinkageSpecDecl *D) {
89 IgnoreResults = true;
90 }
91 void VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
92 IgnoreResults = true;
93 }
94 void VisitUsingDecl(UsingDecl *D) {
95 IgnoreResults = true;
96 }
97 void VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
98 IgnoreResults = true;
99 }
100 void VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D) {
101 IgnoreResults = true;
102 }
103
104 /// Generate the string component containing the location of the
105 /// declaration.
106 bool GenLoc(const Decl *D);
107
108 /// String generation methods used both by the visitation methods
109 /// and from other clients that want to directly generate USRs. These
110 /// methods do not construct complete USRs (which incorporate the parents
111 /// of an AST element), but only the fragments concerning the AST element
112 /// itself.
113
114 /// Generate a USR for an Objective-C class.
115 void GenObjCClass(StringRef cls);
116 /// Generate a USR for an Objective-C class category.
117 void GenObjCCategory(StringRef cls, StringRef cat);
118 /// Generate a USR fragment for an Objective-C instance variable. The
119 /// complete USR can be created by concatenating the USR for the
120 /// encompassing class with this USR fragment.
121 void GenObjCIvar(StringRef ivar);
122 /// Generate a USR fragment for an Objective-C method.
123 void GenObjCMethod(StringRef sel, bool isInstanceMethod);
124 /// Generate a USR fragment for an Objective-C property.
125 void GenObjCProperty(StringRef prop);
126 /// Generate a USR for an Objective-C protocol.
127 void GenObjCProtocol(StringRef prot);
128
129 void VisitType(QualType T);
130 void VisitTemplateParameterList(const TemplateParameterList *Params);
131 void VisitTemplateName(TemplateName Name);
132 void VisitTemplateArgument(const TemplateArgument &Arg);
133
134 /// Emit a Decl's name using NamedDecl::printName() and return true if
135 /// the decl had no name.
136 bool EmitDeclName(const NamedDecl *D);
137};
138
139} // end anonymous namespace
140
141//===----------------------------------------------------------------------===//
142// Generating USRs from ASTS.
143//===----------------------------------------------------------------------===//
144
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:
Guy Benyeib13621d2012-12-18 14:38:23 +0000590 case BuiltinType::OCLImage1d:
591 case BuiltinType::OCLImage1dArray:
592 case BuiltinType::OCLImage1dBuffer:
593 case BuiltinType::OCLImage2d:
594 case BuiltinType::OCLImage2dArray:
595 case BuiltinType::OCLImage3d:
Guy Benyeie6b9d802013-01-20 12:31:11 +0000596 case BuiltinType::OCLEvent:
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000597 IgnoreResults = true;
598 return;
599 case BuiltinType::ObjCId:
600 c = 'o'; break;
601 case BuiltinType::ObjCClass:
602 c = 'O'; break;
603 case BuiltinType::ObjCSel:
604 c = 'e'; break;
605 }
606 Out << c;
607 return;
608 }
609
610 // If we have already seen this (non-built-in) type, use a substitution
611 // encoding.
612 llvm::DenseMap<const Type *, unsigned>::iterator Substitution
613 = TypeSubstitutions.find(T.getTypePtr());
614 if (Substitution != TypeSubstitutions.end()) {
615 Out << 'S' << Substitution->second << '_';
616 return;
617 } else {
618 // Record this as a substitution.
619 unsigned Number = TypeSubstitutions.size();
620 TypeSubstitutions[T.getTypePtr()] = Number;
621 }
622
623 if (const PointerType *PT = T->getAs<PointerType>()) {
624 Out << '*';
625 T = PT->getPointeeType();
626 continue;
627 }
628 if (const ReferenceType *RT = T->getAs<ReferenceType>()) {
629 Out << '&';
630 T = RT->getPointeeType();
631 continue;
632 }
633 if (const FunctionProtoType *FT = T->getAs<FunctionProtoType>()) {
634 Out << 'F';
635 VisitType(FT->getResultType());
636 for (FunctionProtoType::arg_type_iterator
637 I = FT->arg_type_begin(), E = FT->arg_type_end(); I!=E; ++I) {
638 VisitType(*I);
639 }
640 if (FT->isVariadic())
641 Out << '.';
642 return;
643 }
644 if (const BlockPointerType *BT = T->getAs<BlockPointerType>()) {
645 Out << 'B';
646 T = BT->getPointeeType();
647 continue;
648 }
649 if (const ComplexType *CT = T->getAs<ComplexType>()) {
650 Out << '<';
651 T = CT->getElementType();
652 continue;
653 }
654 if (const TagType *TT = T->getAs<TagType>()) {
655 Out << '$';
656 VisitTagDecl(TT->getDecl());
657 return;
658 }
659 if (const TemplateTypeParmType *TTP = T->getAs<TemplateTypeParmType>()) {
660 Out << 't' << TTP->getDepth() << '.' << TTP->getIndex();
661 return;
662 }
663 if (const TemplateSpecializationType *Spec
664 = T->getAs<TemplateSpecializationType>()) {
665 Out << '>';
666 VisitTemplateName(Spec->getTemplateName());
667 Out << Spec->getNumArgs();
668 for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I)
669 VisitTemplateArgument(Spec->getArg(I));
670 return;
671 }
672
673 // Unhandled type.
674 Out << ' ';
675 break;
676 } while (true);
677}
678
679void USRGenerator::VisitTemplateParameterList(
680 const TemplateParameterList *Params) {
681 if (!Params)
682 return;
683 Out << '>' << Params->size();
684 for (TemplateParameterList::const_iterator P = Params->begin(),
685 PEnd = Params->end();
686 P != PEnd; ++P) {
687 Out << '#';
688 if (isa<TemplateTypeParmDecl>(*P)) {
689 if (cast<TemplateTypeParmDecl>(*P)->isParameterPack())
690 Out<< 'p';
691 Out << 'T';
692 continue;
693 }
694
695 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
696 if (NTTP->isParameterPack())
697 Out << 'p';
698 Out << 'N';
699 VisitType(NTTP->getType());
700 continue;
701 }
702
703 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
704 if (TTP->isParameterPack())
705 Out << 'p';
706 Out << 't';
707 VisitTemplateParameterList(TTP->getTemplateParameters());
708 }
709}
710
711void USRGenerator::VisitTemplateName(TemplateName Name) {
712 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
713 if (TemplateTemplateParmDecl *TTP
714 = dyn_cast<TemplateTemplateParmDecl>(Template)) {
715 Out << 't' << TTP->getDepth() << '.' << TTP->getIndex();
716 return;
717 }
718
719 Visit(Template);
720 return;
721 }
722
723 // FIXME: Visit dependent template names.
724}
725
726void USRGenerator::VisitTemplateArgument(const TemplateArgument &Arg) {
727 switch (Arg.getKind()) {
728 case TemplateArgument::Null:
729 break;
730
731 case TemplateArgument::Declaration:
732 Visit(Arg.getAsDecl());
733 break;
734
735 case TemplateArgument::NullPtr:
736 break;
737
738 case TemplateArgument::TemplateExpansion:
739 Out << 'P'; // pack expansion of...
740 // Fall through
741 case TemplateArgument::Template:
742 VisitTemplateName(Arg.getAsTemplateOrTemplatePattern());
743 break;
744
745 case TemplateArgument::Expression:
746 // FIXME: Visit expressions.
747 break;
748
749 case TemplateArgument::Pack:
750 Out << 'p' << Arg.pack_size();
751 for (TemplateArgument::pack_iterator P = Arg.pack_begin(), PEnd = Arg.pack_end();
752 P != PEnd; ++P)
753 VisitTemplateArgument(*P);
754 break;
755
756 case TemplateArgument::Type:
757 VisitType(Arg.getAsType());
758 break;
759
760 case TemplateArgument::Integral:
761 Out << 'V';
762 VisitType(Arg.getIntegralType());
763 Out << Arg.getAsIntegral();
764 break;
765 }
766}
767
768//===----------------------------------------------------------------------===//
769// General purpose USR generation methods.
770//===----------------------------------------------------------------------===//
771
772void USRGenerator::GenObjCClass(StringRef cls) {
773 Out << "objc(cs)" << cls;
774}
775
776void USRGenerator::GenObjCCategory(StringRef cls, StringRef cat) {
777 Out << "objc(cy)" << cls << '@' << cat;
778}
779
780void USRGenerator::GenObjCIvar(StringRef ivar) {
781 Out << '@' << ivar;
782}
783
784void USRGenerator::GenObjCMethod(StringRef meth, bool isInstanceMethod) {
785 Out << (isInstanceMethod ? "(im)" : "(cm)") << meth;
786}
787
788void USRGenerator::GenObjCProperty(StringRef prop) {
789 Out << "(py)" << prop;
790}
791
792void USRGenerator::GenObjCProtocol(StringRef prot) {
793 Out << "objc(pl)" << prot;
794}
795
796//===----------------------------------------------------------------------===//
797// API hooks.
798//===----------------------------------------------------------------------===//
799
800static inline StringRef extractUSRSuffix(StringRef s) {
801 return s.startswith("c:") ? s.substr(2) : "";
802}
803
804bool cxcursor::getDeclCursorUSR(const Decl *D, SmallVectorImpl<char> &Buf) {
805 // Don't generate USRs for things with invalid locations.
806 if (!D || D->getLocStart().isInvalid())
807 return true;
808
809 USRGenerator UG(&D->getASTContext(), &Buf);
810 UG->Visit(const_cast<Decl*>(D));
811
812 if (UG->ignoreResults())
813 return true;
814
815 return false;
816}
817
818extern "C" {
819
820CXString clang_getCursorUSR(CXCursor C) {
821 const CXCursorKind &K = clang_getCursorKind(C);
822
823 if (clang_isDeclaration(K)) {
Dmitri Gribenkoe22339c2013-01-23 17:25:27 +0000824 const Decl *D = cxcursor::getCursorDecl(C);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000825 if (!D)
826 return createCXString("");
827
828 CXTranslationUnit TU = cxcursor::getCursorTU(C);
829 if (!TU)
830 return createCXString("");
831
832 CXStringBuf *buf = cxstring::getCXStringBuf(TU);
833 if (!buf)
834 return createCXString("");
835
836 bool Ignore = cxcursor::getDeclCursorUSR(D, buf->Data);
837 if (Ignore) {
Dmitri Gribenko9c48d162013-01-26 22:44:19 +0000838 buf->dispose();
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000839 return createCXString("");
840 }
841
842 // Return the C-string, but don't make a copy since it is already in
843 // the string buffer.
844 buf->Data.push_back('\0');
845 return createCXString(buf);
846 }
847
848 if (K == CXCursor_MacroDefinition) {
849 CXTranslationUnit TU = cxcursor::getCursorTU(C);
850 if (!TU)
851 return createCXString("");
852
853 CXStringBuf *buf = cxstring::getCXStringBuf(TU);
854 if (!buf)
855 return createCXString("");
856
857 {
858 USRGenerator UG(&cxcursor::getCursorASTUnit(C)->getASTContext(),
859 &buf->Data);
860 UG << "macro@"
861 << cxcursor::getCursorMacroDefinition(C)->getName()->getNameStart();
862 }
863 buf->Data.push_back('\0');
864 return createCXString(buf);
865 }
866
867 return createCXString("");
868}
869
870CXString clang_constructUSR_ObjCIvar(const char *name, CXString classUSR) {
871 USRGenerator UG;
872 UG << extractUSRSuffix(clang_getCString(classUSR));
873 UG->GenObjCIvar(name);
874 return createCXString(UG.str(), true);
875}
876
877CXString clang_constructUSR_ObjCMethod(const char *name,
878 unsigned isInstanceMethod,
879 CXString classUSR) {
880 USRGenerator UG;
881 UG << extractUSRSuffix(clang_getCString(classUSR));
882 UG->GenObjCMethod(name, isInstanceMethod);
883 return createCXString(UG.str(), true);
884}
885
886CXString clang_constructUSR_ObjCClass(const char *name) {
887 USRGenerator UG;
888 UG->GenObjCClass(name);
889 return createCXString(UG.str(), true);
890}
891
892CXString clang_constructUSR_ObjCProtocol(const char *name) {
893 USRGenerator UG;
894 UG->GenObjCProtocol(name);
895 return createCXString(UG.str(), true);
896}
897
898CXString clang_constructUSR_ObjCCategory(const char *class_name,
899 const char *category_name) {
900 USRGenerator UG;
901 UG->GenObjCCategory(class_name, category_name);
902 return createCXString(UG.str(), true);
903}
904
905CXString clang_constructUSR_ObjCProperty(const char *property,
906 CXString classUSR) {
907 USRGenerator UG;
908 UG << extractUSRSuffix(clang_getCString(classUSR));
909 UG->GenObjCProperty(property);
910 return createCXString(UG.str(), true);
911}
912
913} // end extern "C"