1 //===- USRGeneration.cpp - Routines for USR generation --------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "clang/Index/USRGeneration.h"
11 #include "clang/AST/ASTContext.h"
12 #include "clang/AST/DeclTemplate.h"
13 #include "clang/AST/DeclVisitor.h"
14 #include "clang/Lex/PreprocessingRecord.h"
15 #include "llvm/Support/Path.h"
16 #include "llvm/Support/raw_ostream.h"
18 using namespace clang;
19 using namespace clang::index;
21 //===----------------------------------------------------------------------===//
23 //===----------------------------------------------------------------------===//
25 /// \returns true on error.
26 static bool printLoc(llvm::raw_ostream &OS, SourceLocation Loc,
27 const SourceManager &SM, bool IncludeOffset) {
28 if (Loc.isInvalid()) {
31 Loc = SM.getExpansionLoc(Loc);
32 const std::pair<FileID, unsigned> &Decomposed = SM.getDecomposedLoc(Loc);
33 const FileEntry *FE = SM.getFileEntryForID(Decomposed.first);
35 OS << llvm::sys::path::filename(FE->getName());
37 // This case really isn't interesting.
41 // Use the offest into the FileID to represent the location. Using
42 // a line/column can cause us to look back at the original source file,
43 // which is expensive.
44 OS << '@' << Decomposed.second;
49 static StringRef GetExternalSourceContainer(const NamedDecl *D) {
52 if (auto *attr = D->getExternalSourceSymbolAttr()) {
53 return attr->getDefinedIn();
59 class USRGenerator : public ConstDeclVisitor<USRGenerator> {
60 SmallVectorImpl<char> &Buf;
61 llvm::raw_svector_ostream Out;
66 llvm::DenseMap<const Type *, unsigned> TypeSubstitutions;
69 explicit USRGenerator(ASTContext *Ctx, SmallVectorImpl<char> &Buf)
76 // Add the USR space prefix.
77 Out << getUSRSpacePrefix();
80 bool ignoreResults() const { return IgnoreResults; }
82 // Visitation methods from generating USRs from AST elements.
83 void VisitDeclContext(const DeclContext *D);
84 void VisitFieldDecl(const FieldDecl *D);
85 void VisitFunctionDecl(const FunctionDecl *D);
86 void VisitNamedDecl(const NamedDecl *D);
87 void VisitNamespaceDecl(const NamespaceDecl *D);
88 void VisitNamespaceAliasDecl(const NamespaceAliasDecl *D);
89 void VisitFunctionTemplateDecl(const FunctionTemplateDecl *D);
90 void VisitClassTemplateDecl(const ClassTemplateDecl *D);
91 void VisitObjCContainerDecl(const ObjCContainerDecl *CD,
92 const ObjCCategoryDecl *CatD = nullptr);
93 void VisitObjCMethodDecl(const ObjCMethodDecl *MD);
94 void VisitObjCPropertyDecl(const ObjCPropertyDecl *D);
95 void VisitObjCPropertyImplDecl(const ObjCPropertyImplDecl *D);
96 void VisitTagDecl(const TagDecl *D);
97 void VisitTypedefDecl(const TypedefDecl *D);
98 void VisitTemplateTypeParmDecl(const TemplateTypeParmDecl *D);
99 void VisitVarDecl(const VarDecl *D);
100 void VisitNonTypeTemplateParmDecl(const NonTypeTemplateParmDecl *D);
101 void VisitTemplateTemplateParmDecl(const TemplateTemplateParmDecl *D);
103 void VisitLinkageSpecDecl(const LinkageSpecDecl *D) {
104 IgnoreResults = true;
107 void VisitUsingDirectiveDecl(const UsingDirectiveDecl *D) {
108 IgnoreResults = true;
111 void VisitUsingDecl(const UsingDecl *D) {
112 IgnoreResults = true;
115 void VisitUnresolvedUsingValueDecl(const UnresolvedUsingValueDecl *D) {
116 IgnoreResults = true;
119 void VisitUnresolvedUsingTypenameDecl(const UnresolvedUsingTypenameDecl *D) {
120 IgnoreResults = true;
123 bool ShouldGenerateLocation(const NamedDecl *D);
125 bool isLocal(const NamedDecl *D) {
126 return D->getParentFunctionOrMethod() != nullptr;
129 void GenExtSymbolContainer(const NamedDecl *D);
131 /// Generate the string component containing the location of the
133 bool GenLoc(const Decl *D, bool IncludeOffset);
135 /// String generation methods used both by the visitation methods
136 /// and from other clients that want to directly generate USRs. These
137 /// methods do not construct complete USRs (which incorporate the parents
138 /// of an AST element), but only the fragments concerning the AST element
141 /// Generate a USR for an Objective-C class.
142 void GenObjCClass(StringRef cls, StringRef ExtSymDefinedIn,
143 StringRef CategoryContextExtSymbolDefinedIn) {
144 generateUSRForObjCClass(cls, Out, ExtSymDefinedIn,
145 CategoryContextExtSymbolDefinedIn);
148 /// Generate a USR for an Objective-C class category.
149 void GenObjCCategory(StringRef cls, StringRef cat,
150 StringRef clsExt, StringRef catExt) {
151 generateUSRForObjCCategory(cls, cat, Out, clsExt, catExt);
154 /// Generate a USR fragment for an Objective-C property.
155 void GenObjCProperty(StringRef prop, bool isClassProp) {
156 generateUSRForObjCProperty(prop, isClassProp, Out);
159 /// Generate a USR for an Objective-C protocol.
160 void GenObjCProtocol(StringRef prot, StringRef ext) {
161 generateUSRForObjCProtocol(prot, Out, ext);
164 void VisitType(QualType T);
165 void VisitTemplateParameterList(const TemplateParameterList *Params);
166 void VisitTemplateName(TemplateName Name);
167 void VisitTemplateArgument(const TemplateArgument &Arg);
169 /// Emit a Decl's name using NamedDecl::printName() and return true if
170 /// the decl had no name.
171 bool EmitDeclName(const NamedDecl *D);
173 } // end anonymous namespace
175 //===----------------------------------------------------------------------===//
176 // Generating USRs from ASTS.
177 //===----------------------------------------------------------------------===//
179 bool USRGenerator::EmitDeclName(const NamedDecl *D) {
180 const unsigned startSize = Buf.size();
182 const unsigned endSize = Buf.size();
183 return startSize == endSize;
186 bool USRGenerator::ShouldGenerateLocation(const NamedDecl *D) {
187 if (D->isExternallyVisible())
189 if (D->getParentFunctionOrMethod())
191 SourceLocation Loc = D->getLocation();
194 const SourceManager &SM = Context->getSourceManager();
195 return !SM.isInSystemHeader(Loc);
198 void USRGenerator::VisitDeclContext(const DeclContext *DC) {
199 if (const NamedDecl *D = dyn_cast<NamedDecl>(DC))
203 void USRGenerator::VisitFieldDecl(const FieldDecl *D) {
204 // The USR for an ivar declared in a class extension is based on the
205 // ObjCInterfaceDecl, not the ObjCCategoryDecl.
206 if (const ObjCInterfaceDecl *ID = Context->getObjContainingInterface(D))
209 VisitDeclContext(D->getDeclContext());
210 Out << (isa<ObjCIvarDecl>(D) ? "@" : "@FI@");
211 if (EmitDeclName(D)) {
212 // Bit fields can be anonymous.
213 IgnoreResults = true;
218 void USRGenerator::VisitFunctionDecl(const FunctionDecl *D) {
219 if (ShouldGenerateLocation(D) && GenLoc(D, /*IncludeOffset=*/isLocal(D)))
222 const unsigned StartSize = Buf.size();
223 VisitDeclContext(D->getDeclContext());
224 if (Buf.size() == StartSize)
225 GenExtSymbolContainer(D);
227 bool IsTemplate = false;
228 if (FunctionTemplateDecl *FunTmpl = D->getDescribedFunctionTemplate()) {
231 VisitTemplateParameterList(FunTmpl->getTemplateParameters());
235 PrintingPolicy Policy(Context->getLangOpts());
236 // Forward references can have different template argument names. Suppress the
237 // template argument names in constructors to make their USR more stable.
238 Policy.SuppressTemplateArgsInCXXConstructors = true;
239 D->getDeclName().print(Out, Policy);
241 ASTContext &Ctx = *Context;
242 if ((!Ctx.getLangOpts().CPlusPlus || D->isExternC()) &&
243 !D->hasAttr<OverloadableAttr>())
246 if (const TemplateArgumentList *
247 SpecArgs = D->getTemplateSpecializationArgs()) {
249 for (unsigned I = 0, N = SpecArgs->size(); I != N; ++I) {
251 VisitTemplateArgument(SpecArgs->get(I));
256 // Mangle in type information for the arguments.
257 for (auto PD : D->parameters()) {
259 VisitType(PD->getType());
264 // Function templates can be overloaded by return type, for example:
266 // template <class T> typename T::A foo() {}
267 // template <class T> typename T::B foo() {}
270 VisitType(D->getReturnType());
273 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
276 if (unsigned quals = MD->getTypeQualifiers())
277 Out << (char)('0' + quals);
278 switch (MD->getRefQualifier()) {
280 case RQ_LValue: Out << '&'; break;
281 case RQ_RValue: Out << "&&"; break;
286 void USRGenerator::VisitNamedDecl(const NamedDecl *D) {
287 VisitDeclContext(D->getDeclContext());
290 if (EmitDeclName(D)) {
291 // The string can be empty if the declaration has no name; e.g., it is
292 // the ParmDecl with no name for declaration of a function pointer type,
293 // e.g.: void (*f)(void *);
294 // In this case, don't generate a USR.
295 IgnoreResults = true;
299 void USRGenerator::VisitVarDecl(const VarDecl *D) {
300 // VarDecls can be declared 'extern' within a function or method body,
301 // but their enclosing DeclContext is the function, not the TU. We need
302 // to check the storage class to correctly generate the USR.
303 if (ShouldGenerateLocation(D) && GenLoc(D, /*IncludeOffset=*/isLocal(D)))
306 VisitDeclContext(D->getDeclContext());
308 if (VarTemplateDecl *VarTmpl = D->getDescribedVarTemplate()) {
310 VisitTemplateParameterList(VarTmpl->getTemplateParameters());
311 } else if (const VarTemplatePartialSpecializationDecl *PartialSpec
312 = dyn_cast<VarTemplatePartialSpecializationDecl>(D)) {
314 VisitTemplateParameterList(PartialSpec->getTemplateParameters());
317 // Variables always have simple names.
318 StringRef s = D->getName();
320 // The string can be empty if the declaration has no name; e.g., it is
321 // the ParmDecl with no name for declaration of a function pointer type, e.g.:
322 // void (*f)(void *);
323 // In this case, don't generate a USR.
325 IgnoreResults = true;
329 // For a template specialization, mangle the template arguments.
330 if (const VarTemplateSpecializationDecl *Spec
331 = dyn_cast<VarTemplateSpecializationDecl>(D)) {
332 const TemplateArgumentList &Args = Spec->getTemplateArgs();
334 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
336 VisitTemplateArgument(Args.get(I));
341 void USRGenerator::VisitNonTypeTemplateParmDecl(
342 const NonTypeTemplateParmDecl *D) {
343 GenLoc(D, /*IncludeOffset=*/true);
346 void USRGenerator::VisitTemplateTemplateParmDecl(
347 const TemplateTemplateParmDecl *D) {
348 GenLoc(D, /*IncludeOffset=*/true);
351 void USRGenerator::VisitNamespaceDecl(const NamespaceDecl *D) {
352 if (D->isAnonymousNamespace()) {
357 VisitDeclContext(D->getDeclContext());
359 Out << "@N@" << D->getName();
362 void USRGenerator::VisitFunctionTemplateDecl(const FunctionTemplateDecl *D) {
363 VisitFunctionDecl(D->getTemplatedDecl());
366 void USRGenerator::VisitClassTemplateDecl(const ClassTemplateDecl *D) {
367 VisitTagDecl(D->getTemplatedDecl());
370 void USRGenerator::VisitNamespaceAliasDecl(const NamespaceAliasDecl *D) {
371 VisitDeclContext(D->getDeclContext());
373 Out << "@NA@" << D->getName();
376 void USRGenerator::VisitObjCMethodDecl(const ObjCMethodDecl *D) {
377 const DeclContext *container = D->getDeclContext();
378 if (const ObjCProtocolDecl *pd = dyn_cast<ObjCProtocolDecl>(container)) {
382 // The USR for a method declared in a class extension or category is based on
383 // the ObjCInterfaceDecl, not the ObjCCategoryDecl.
384 const ObjCInterfaceDecl *ID = D->getClassInterface();
386 IgnoreResults = true;
389 auto getCategoryContext = [](const ObjCMethodDecl *D) ->
390 const ObjCCategoryDecl * {
391 if (auto *CD = dyn_cast<ObjCCategoryDecl>(D->getDeclContext()))
393 if (auto *ICD = dyn_cast<ObjCCategoryImplDecl>(D->getDeclContext()))
394 return ICD->getCategoryDecl();
397 auto *CD = getCategoryContext(D);
398 VisitObjCContainerDecl(ID, CD);
400 // Ideally we would use 'GenObjCMethod', but this is such a hot path
401 // for Objective-C code that we don't want to use
402 // DeclarationName::getAsString().
403 Out << (D->isInstanceMethod() ? "(im)" : "(cm)")
404 << DeclarationName(D->getSelector());
407 void USRGenerator::VisitObjCContainerDecl(const ObjCContainerDecl *D,
408 const ObjCCategoryDecl *CatD) {
409 switch (D->getKind()) {
411 llvm_unreachable("Invalid ObjC container.");
412 case Decl::ObjCInterface:
413 case Decl::ObjCImplementation:
414 GenObjCClass(D->getName(), GetExternalSourceContainer(D),
415 GetExternalSourceContainer(CatD));
417 case Decl::ObjCCategory: {
418 const ObjCCategoryDecl *CD = cast<ObjCCategoryDecl>(D);
419 const ObjCInterfaceDecl *ID = CD->getClassInterface();
421 // Handle invalid code where the @interface might not
422 // have been specified.
423 // FIXME: We should be able to generate this USR even if the
424 // @interface isn't available.
425 IgnoreResults = true;
428 // Specially handle class extensions, which are anonymous categories.
429 // We want to mangle in the location to uniquely distinguish them.
430 if (CD->IsClassExtension()) {
431 Out << "objc(ext)" << ID->getName() << '@';
432 GenLoc(CD, /*IncludeOffset=*/true);
435 GenObjCCategory(ID->getName(), CD->getName(),
436 GetExternalSourceContainer(ID),
437 GetExternalSourceContainer(CD));
441 case Decl::ObjCCategoryImpl: {
442 const ObjCCategoryImplDecl *CD = cast<ObjCCategoryImplDecl>(D);
443 const ObjCInterfaceDecl *ID = CD->getClassInterface();
445 // Handle invalid code where the @interface might not
446 // have been specified.
447 // FIXME: We should be able to generate this USR even if the
448 // @interface isn't available.
449 IgnoreResults = true;
452 GenObjCCategory(ID->getName(), CD->getName(),
453 GetExternalSourceContainer(ID),
454 GetExternalSourceContainer(CD));
457 case Decl::ObjCProtocol: {
458 const ObjCProtocolDecl *PD = cast<ObjCProtocolDecl>(D);
459 GenObjCProtocol(PD->getName(), GetExternalSourceContainer(PD));
465 void USRGenerator::VisitObjCPropertyDecl(const ObjCPropertyDecl *D) {
466 // The USR for a property declared in a class extension or category is based
467 // on the ObjCInterfaceDecl, not the ObjCCategoryDecl.
468 if (const ObjCInterfaceDecl *ID = Context->getObjContainingInterface(D))
471 Visit(cast<Decl>(D->getDeclContext()));
472 GenObjCProperty(D->getName(), D->isClassProperty());
475 void USRGenerator::VisitObjCPropertyImplDecl(const ObjCPropertyImplDecl *D) {
476 if (ObjCPropertyDecl *PD = D->getPropertyDecl()) {
477 VisitObjCPropertyDecl(PD);
481 IgnoreResults = true;
484 void USRGenerator::VisitTagDecl(const TagDecl *D) {
485 // Add the location of the tag decl to handle resolution across
486 // translation units.
487 if (!isa<EnumDecl>(D) &&
488 ShouldGenerateLocation(D) && GenLoc(D, /*IncludeOffset=*/isLocal(D)))
491 GenExtSymbolContainer(D);
493 D = D->getCanonicalDecl();
494 VisitDeclContext(D->getDeclContext());
496 bool AlreadyStarted = false;
497 if (const CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(D)) {
498 if (ClassTemplateDecl *ClassTmpl = CXXRecord->getDescribedClassTemplate()) {
499 AlreadyStarted = true;
501 switch (D->getTagKind()) {
504 case TTK_Struct: Out << "@ST"; break;
505 case TTK_Union: Out << "@UT"; break;
506 case TTK_Enum: llvm_unreachable("enum template");
508 VisitTemplateParameterList(ClassTmpl->getTemplateParameters());
509 } else if (const ClassTemplatePartialSpecializationDecl *PartialSpec
510 = dyn_cast<ClassTemplatePartialSpecializationDecl>(CXXRecord)) {
511 AlreadyStarted = true;
513 switch (D->getTagKind()) {
516 case TTK_Struct: Out << "@SP"; break;
517 case TTK_Union: Out << "@UP"; break;
518 case TTK_Enum: llvm_unreachable("enum partial specialization");
520 VisitTemplateParameterList(PartialSpec->getTemplateParameters());
524 if (!AlreadyStarted) {
525 switch (D->getTagKind()) {
528 case TTK_Struct: Out << "@S"; break;
529 case TTK_Union: Out << "@U"; break;
530 case TTK_Enum: Out << "@E"; break;
535 assert(Buf.size() > 0);
536 const unsigned off = Buf.size() - 1;
538 if (EmitDeclName(D)) {
539 if (const TypedefNameDecl *TD = D->getTypedefNameForAnonDecl()) {
544 if (D->isEmbeddedInDeclarator() && !D->isFreeStanding()) {
545 printLoc(Out, D->getLocation(), Context->getSourceManager(), true);
548 if (auto *ED = dyn_cast<EnumDecl>(D)) {
549 // Distinguish USRs of anonymous enums by using their first enumerator.
550 auto enum_range = ED->enumerators();
551 if (enum_range.begin() != enum_range.end()) {
552 Out << '@' << **enum_range.begin();
559 // For a class template specialization, mangle the template arguments.
560 if (const ClassTemplateSpecializationDecl *Spec
561 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
562 const TemplateArgumentList &Args = Spec->getTemplateArgs();
564 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
566 VisitTemplateArgument(Args.get(I));
571 void USRGenerator::VisitTypedefDecl(const TypedefDecl *D) {
572 if (ShouldGenerateLocation(D) && GenLoc(D, /*IncludeOffset=*/isLocal(D)))
574 const DeclContext *DC = D->getDeclContext();
575 if (const NamedDecl *DCN = dyn_cast<NamedDecl>(DC))
581 void USRGenerator::VisitTemplateTypeParmDecl(const TemplateTypeParmDecl *D) {
582 GenLoc(D, /*IncludeOffset=*/true);
585 void USRGenerator::GenExtSymbolContainer(const NamedDecl *D) {
586 StringRef Container = GetExternalSourceContainer(D);
587 if (!Container.empty())
588 Out << "@M@" << Container;
591 bool USRGenerator::GenLoc(const Decl *D, bool IncludeOffset) {
593 return IgnoreResults;
596 // Guard against null declarations in invalid code.
598 IgnoreResults = true;
602 // Use the location of canonical decl.
603 D = D->getCanonicalDecl();
606 IgnoreResults || printLoc(Out, D->getLocStart(),
607 Context->getSourceManager(), IncludeOffset);
609 return IgnoreResults;
612 void USRGenerator::VisitType(QualType T) {
613 // This method mangles in USR information for types. It can possibly
614 // just reuse the naming-mangling logic used by codegen, although the
615 // requirements for USRs might not be the same.
616 ASTContext &Ctx = *Context;
619 T = Ctx.getCanonicalType(T);
620 Qualifiers Q = T.getQualifiers();
629 Out << ((char) ('0' + qVal));
631 // Mangle in ObjC GC qualifiers?
633 if (const PackExpansionType *Expansion = T->getAs<PackExpansionType>()) {
635 T = Expansion->getPattern();
638 if (const BuiltinType *BT = T->getAs<BuiltinType>()) {
639 unsigned char c = '\0';
640 switch (BT->getKind()) {
641 case BuiltinType::Void:
643 case BuiltinType::Bool:
645 case BuiltinType::UChar:
647 case BuiltinType::Char16:
649 case BuiltinType::Char32:
651 case BuiltinType::UShort:
653 case BuiltinType::UInt:
655 case BuiltinType::ULong:
657 case BuiltinType::ULongLong:
659 case BuiltinType::UInt128:
661 case BuiltinType::Char_U:
662 case BuiltinType::Char_S:
664 case BuiltinType::SChar:
666 case BuiltinType::WChar_S:
667 case BuiltinType::WChar_U:
669 case BuiltinType::Short:
671 case BuiltinType::Int:
673 case BuiltinType::Long:
675 case BuiltinType::LongLong:
677 case BuiltinType::Int128:
679 case BuiltinType::Half:
681 case BuiltinType::Float:
683 case BuiltinType::Double:
685 case BuiltinType::LongDouble:
687 case BuiltinType::Float128:
689 case BuiltinType::NullPtr:
691 #define BUILTIN_TYPE(Id, SingletonId)
692 #define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id:
693 #include "clang/AST/BuiltinTypes.def"
694 case BuiltinType::Dependent:
695 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
696 case BuiltinType::Id:
697 #include "clang/Basic/OpenCLImageTypes.def"
698 case BuiltinType::OCLEvent:
699 case BuiltinType::OCLClkEvent:
700 case BuiltinType::OCLQueue:
701 case BuiltinType::OCLReserveID:
702 case BuiltinType::OCLSampler:
703 IgnoreResults = true;
705 case BuiltinType::ObjCId:
707 case BuiltinType::ObjCClass:
709 case BuiltinType::ObjCSel:
716 // If we have already seen this (non-built-in) type, use a substitution
718 llvm::DenseMap<const Type *, unsigned>::iterator Substitution
719 = TypeSubstitutions.find(T.getTypePtr());
720 if (Substitution != TypeSubstitutions.end()) {
721 Out << 'S' << Substitution->second << '_';
724 // Record this as a substitution.
725 unsigned Number = TypeSubstitutions.size();
726 TypeSubstitutions[T.getTypePtr()] = Number;
729 if (const PointerType *PT = T->getAs<PointerType>()) {
731 T = PT->getPointeeType();
734 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
736 T = OPT->getPointeeType();
739 if (const RValueReferenceType *RT = T->getAs<RValueReferenceType>()) {
741 T = RT->getPointeeType();
744 if (const ReferenceType *RT = T->getAs<ReferenceType>()) {
746 T = RT->getPointeeType();
749 if (const FunctionProtoType *FT = T->getAs<FunctionProtoType>()) {
751 VisitType(FT->getReturnType());
752 for (const auto &I : FT->param_types())
754 if (FT->isVariadic())
758 if (const BlockPointerType *BT = T->getAs<BlockPointerType>()) {
760 T = BT->getPointeeType();
763 if (const ComplexType *CT = T->getAs<ComplexType>()) {
765 T = CT->getElementType();
768 if (const TagType *TT = T->getAs<TagType>()) {
770 VisitTagDecl(TT->getDecl());
773 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
775 VisitObjCInterfaceDecl(OIT->getDecl());
778 if (const ObjCObjectType *OIT = T->getAs<ObjCObjectType>()) {
780 VisitType(OIT->getBaseType());
781 for (auto *Prot : OIT->getProtocols())
782 VisitObjCProtocolDecl(Prot);
785 if (const TemplateTypeParmType *TTP = T->getAs<TemplateTypeParmType>()) {
786 Out << 't' << TTP->getDepth() << '.' << TTP->getIndex();
789 if (const TemplateSpecializationType *Spec
790 = T->getAs<TemplateSpecializationType>()) {
792 VisitTemplateName(Spec->getTemplateName());
793 Out << Spec->getNumArgs();
794 for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I)
795 VisitTemplateArgument(Spec->getArg(I));
798 if (const DependentNameType *DNT = T->getAs<DependentNameType>()) {
800 // FIXME: Encode the qualifier, don't just print it.
801 PrintingPolicy PO(Ctx.getLangOpts());
802 PO.SuppressTagKeyword = true;
803 PO.SuppressUnwrittenScope = true;
804 PO.ConstantArraySizeAsWritten = false;
805 PO.AnonymousTagLocations = false;
806 DNT->getQualifier()->print(Out, PO);
807 Out << ':' << DNT->getIdentifier()->getName();
810 if (const InjectedClassNameType *InjT = T->getAs<InjectedClassNameType>()) {
811 T = InjT->getInjectedSpecializationType();
814 if (const auto *VT = T->getAs<VectorType>()) {
815 Out << (T->isExtVectorType() ? ']' : '[');
816 Out << VT->getNumElements();
817 T = VT->getElementType();
827 void USRGenerator::VisitTemplateParameterList(
828 const TemplateParameterList *Params) {
831 Out << '>' << Params->size();
832 for (TemplateParameterList::const_iterator P = Params->begin(),
833 PEnd = Params->end();
836 if (isa<TemplateTypeParmDecl>(*P)) {
837 if (cast<TemplateTypeParmDecl>(*P)->isParameterPack())
843 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
844 if (NTTP->isParameterPack())
847 VisitType(NTTP->getType());
851 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
852 if (TTP->isParameterPack())
855 VisitTemplateParameterList(TTP->getTemplateParameters());
859 void USRGenerator::VisitTemplateName(TemplateName Name) {
860 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
861 if (TemplateTemplateParmDecl *TTP
862 = dyn_cast<TemplateTemplateParmDecl>(Template)) {
863 Out << 't' << TTP->getDepth() << '.' << TTP->getIndex();
871 // FIXME: Visit dependent template names.
874 void USRGenerator::VisitTemplateArgument(const TemplateArgument &Arg) {
875 switch (Arg.getKind()) {
876 case TemplateArgument::Null:
879 case TemplateArgument::Declaration:
880 Visit(Arg.getAsDecl());
883 case TemplateArgument::NullPtr:
886 case TemplateArgument::TemplateExpansion:
887 Out << 'P'; // pack expansion of...
889 case TemplateArgument::Template:
890 VisitTemplateName(Arg.getAsTemplateOrTemplatePattern());
893 case TemplateArgument::Expression:
894 // FIXME: Visit expressions.
897 case TemplateArgument::Pack:
898 Out << 'p' << Arg.pack_size();
899 for (const auto &P : Arg.pack_elements())
900 VisitTemplateArgument(P);
903 case TemplateArgument::Type:
904 VisitType(Arg.getAsType());
907 case TemplateArgument::Integral:
909 VisitType(Arg.getIntegralType());
910 Out << Arg.getAsIntegral();
915 //===----------------------------------------------------------------------===//
916 // USR generation functions.
917 //===----------------------------------------------------------------------===//
919 static void combineClassAndCategoryExtContainers(StringRef ClsSymDefinedIn,
920 StringRef CatSymDefinedIn,
922 if (ClsSymDefinedIn.empty() && CatSymDefinedIn.empty())
924 if (CatSymDefinedIn.empty()) {
925 OS << "@M@" << ClsSymDefinedIn << '@';
928 OS << "@CM@" << CatSymDefinedIn << '@';
929 if (ClsSymDefinedIn != CatSymDefinedIn) {
930 OS << ClsSymDefinedIn << '@';
934 void clang::index::generateUSRForObjCClass(StringRef Cls, raw_ostream &OS,
935 StringRef ExtSymDefinedIn,
936 StringRef CategoryContextExtSymbolDefinedIn) {
937 combineClassAndCategoryExtContainers(ExtSymDefinedIn,
938 CategoryContextExtSymbolDefinedIn, OS);
939 OS << "objc(cs)" << Cls;
942 void clang::index::generateUSRForObjCCategory(StringRef Cls, StringRef Cat,
944 StringRef ClsSymDefinedIn,
945 StringRef CatSymDefinedIn) {
946 combineClassAndCategoryExtContainers(ClsSymDefinedIn, CatSymDefinedIn, OS);
947 OS << "objc(cy)" << Cls << '@' << Cat;
950 void clang::index::generateUSRForObjCIvar(StringRef Ivar, raw_ostream &OS) {
954 void clang::index::generateUSRForObjCMethod(StringRef Sel,
955 bool IsInstanceMethod,
957 OS << (IsInstanceMethod ? "(im)" : "(cm)") << Sel;
960 void clang::index::generateUSRForObjCProperty(StringRef Prop, bool isClassProp,
962 OS << (isClassProp ? "(cpy)" : "(py)") << Prop;
965 void clang::index::generateUSRForObjCProtocol(StringRef Prot, raw_ostream &OS,
966 StringRef ExtSymDefinedIn) {
967 if (!ExtSymDefinedIn.empty())
968 OS << "@M@" << ExtSymDefinedIn << '@';
969 OS << "objc(pl)" << Prot;
972 void clang::index::generateUSRForGlobalEnum(StringRef EnumName, raw_ostream &OS,
973 StringRef ExtSymDefinedIn) {
974 if (!ExtSymDefinedIn.empty())
975 OS << "@M@" << ExtSymDefinedIn;
976 OS << "@E@" << EnumName;
979 void clang::index::generateUSRForEnumConstant(StringRef EnumConstantName,
981 OS << '@' << EnumConstantName;
984 bool clang::index::generateUSRForDecl(const Decl *D,
985 SmallVectorImpl<char> &Buf) {
988 // We don't ignore decls with invalid source locations. Implicit decls, like
989 // C++'s operator new function, can have invalid locations but it is fine to
990 // create USRs that can identify them.
992 USRGenerator UG(&D->getASTContext(), Buf);
994 return UG.ignoreResults();
997 bool clang::index::generateUSRForMacro(const MacroDefinitionRecord *MD,
998 const SourceManager &SM,
999 SmallVectorImpl<char> &Buf) {
1002 return generateUSRForMacro(MD->getName()->getName(), MD->getLocation(),
1007 bool clang::index::generateUSRForMacro(StringRef MacroName, SourceLocation Loc,
1008 const SourceManager &SM,
1009 SmallVectorImpl<char> &Buf) {
1010 // Don't generate USRs for things with invalid locations.
1011 if (MacroName.empty() || Loc.isInvalid())
1014 llvm::raw_svector_ostream Out(Buf);
1016 // Assume that system headers are sane. Don't put source location
1017 // information into the USR if the macro comes from a system header.
1018 bool ShouldGenerateLocation = !SM.isInSystemHeader(Loc);
1020 Out << getUSRSpacePrefix();
1021 if (ShouldGenerateLocation)
1022 printLoc(Out, Loc, SM, /*IncludeOffset=*/true);