-//===- CIndexUSR.cpp - Clang-C Source Indexing Library --------------------===//\r
-//\r
-// The LLVM Compiler Infrastructure\r
-//\r
-// This file is distributed under the University of Illinois Open Source\r
-// License. See LICENSE.TXT for details.\r
-//\r
-//===----------------------------------------------------------------------===//\r
-//\r
-// This file implements the generation and use of USRs from CXEntities.\r
-//\r
-//===----------------------------------------------------------------------===//\r
-\r
-#include "CIndexer.h"\r
-#include "CXCursor.h"\r
-#include "CXString.h"\r
-#include "clang/AST/DeclTemplate.h"\r
-#include "clang/AST/DeclVisitor.h"\r
-#include "clang/Frontend/ASTUnit.h"\r
-#include "clang/Lex/PreprocessingRecord.h"\r
-#include "llvm/ADT/SmallString.h"\r
-#include "llvm/Support/raw_ostream.h"\r
-\r
-using namespace clang;\r
-using namespace clang::cxstring;\r
-\r
-//===----------------------------------------------------------------------===//\r
-// USR generation.\r
-//===----------------------------------------------------------------------===//\r
-\r
-namespace {\r
-class USRGenerator : public DeclVisitor<USRGenerator> {\r
- OwningPtr<SmallString<128> > OwnedBuf;\r
- SmallVectorImpl<char> &Buf;\r
- llvm::raw_svector_ostream Out;\r
- bool IgnoreResults;\r
- ASTContext *Context;\r
- bool generatedLoc;\r
- \r
- llvm::DenseMap<const Type *, unsigned> TypeSubstitutions;\r
- \r
-public:\r
- explicit USRGenerator(ASTContext *Ctx = 0, SmallVectorImpl<char> *extBuf = 0)\r
- : OwnedBuf(extBuf ? 0 : new SmallString<128>()),\r
- Buf(extBuf ? *extBuf : *OwnedBuf.get()),\r
- Out(Buf),\r
- IgnoreResults(false),\r
- Context(Ctx),\r
- generatedLoc(false)\r
- {\r
- // Add the USR space prefix.\r
- Out << "c:";\r
- }\r
-\r
- StringRef str() {\r
- return Out.str();\r
- }\r
-\r
- USRGenerator* operator->() { return this; }\r
-\r
- template <typename T>\r
- llvm::raw_svector_ostream &operator<<(const T &x) {\r
- Out << x;\r
- return Out;\r
- }\r
-\r
- bool ignoreResults() const { return IgnoreResults; }\r
-\r
- // Visitation methods from generating USRs from AST elements.\r
- void VisitDeclContext(DeclContext *D);\r
- void VisitFieldDecl(FieldDecl *D);\r
- void VisitFunctionDecl(FunctionDecl *D);\r
- void VisitNamedDecl(NamedDecl *D);\r
- void VisitNamespaceDecl(NamespaceDecl *D);\r
- void VisitNamespaceAliasDecl(NamespaceAliasDecl *D);\r
- void VisitFunctionTemplateDecl(FunctionTemplateDecl *D);\r
- void VisitClassTemplateDecl(ClassTemplateDecl *D);\r
- void VisitObjCContainerDecl(ObjCContainerDecl *CD);\r
- void VisitObjCMethodDecl(ObjCMethodDecl *MD);\r
- void VisitObjCPropertyDecl(ObjCPropertyDecl *D);\r
- void VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D);\r
- void VisitTagDecl(TagDecl *D);\r
- void VisitTypedefDecl(TypedefDecl *D);\r
- void VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);\r
- void VisitVarDecl(VarDecl *D);\r
- void VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D);\r
- void VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D);\r
- void VisitLinkageSpecDecl(LinkageSpecDecl *D) {\r
- IgnoreResults = true;\r
- }\r
- void VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {\r
- IgnoreResults = true;\r
- }\r
- void VisitUsingDecl(UsingDecl *D) { \r
- IgnoreResults = true;\r
- }\r
- void VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) { \r
- IgnoreResults = true;\r
- }\r
- void VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D) { \r
- IgnoreResults = true;\r
- }\r
- \r
- /// Generate the string component containing the location of the\r
- /// declaration.\r
- bool GenLoc(const Decl *D);\r
-\r
- /// String generation methods used both by the visitation methods\r
- /// and from other clients that want to directly generate USRs. These\r
- /// methods do not construct complete USRs (which incorporate the parents\r
- /// of an AST element), but only the fragments concerning the AST element\r
- /// itself.\r
-\r
- /// Generate a USR for an Objective-C class.\r
- void GenObjCClass(StringRef cls);\r
- /// Generate a USR for an Objective-C class category.\r
- void GenObjCCategory(StringRef cls, StringRef cat);\r
- /// Generate a USR fragment for an Objective-C instance variable. The\r
- /// complete USR can be created by concatenating the USR for the\r
- /// encompassing class with this USR fragment.\r
- void GenObjCIvar(StringRef ivar);\r
- /// Generate a USR fragment for an Objective-C method.\r
- void GenObjCMethod(StringRef sel, bool isInstanceMethod);\r
- /// Generate a USR fragment for an Objective-C property.\r
- void GenObjCProperty(StringRef prop);\r
- /// Generate a USR for an Objective-C protocol.\r
- void GenObjCProtocol(StringRef prot);\r
-\r
- void VisitType(QualType T);\r
- void VisitTemplateParameterList(const TemplateParameterList *Params);\r
- void VisitTemplateName(TemplateName Name);\r
- void VisitTemplateArgument(const TemplateArgument &Arg);\r
- \r
- /// Emit a Decl's name using NamedDecl::printName() and return true if\r
- /// the decl had no name.\r
- bool EmitDeclName(const NamedDecl *D);\r
-};\r
-\r
-} // end anonymous namespace\r
-\r
-//===----------------------------------------------------------------------===//\r
-// Generating USRs from ASTS.\r
-//===----------------------------------------------------------------------===//\r
-\r
-bool USRGenerator::EmitDeclName(const NamedDecl *D) {\r
- Out.flush();\r
- const unsigned startSize = Buf.size();\r
- D->printName(Out);\r
- Out.flush();\r
- const unsigned endSize = Buf.size();\r
- return startSize == endSize;\r
-}\r
-\r
-static bool InAnonymousNamespace(const Decl *D) {\r
- if (const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(D->getDeclContext()))\r
- return ND->isAnonymousNamespace();\r
- return false;\r
-}\r
-\r
-static inline bool ShouldGenerateLocation(const NamedDecl *D) {\r
- return D->getLinkage() != ExternalLinkage && !InAnonymousNamespace(D);\r
-}\r
-\r
-void USRGenerator::VisitDeclContext(DeclContext *DC) {\r
- if (NamedDecl *D = dyn_cast<NamedDecl>(DC))\r
- Visit(D);\r
-}\r
-\r
-void USRGenerator::VisitFieldDecl(FieldDecl *D) {\r
- // The USR for an ivar declared in a class extension is based on the\r
- // ObjCInterfaceDecl, not the ObjCCategoryDecl.\r
- if (ObjCInterfaceDecl *ID = Context->getObjContainingInterface(D))\r
- Visit(ID);\r
- else\r
- VisitDeclContext(D->getDeclContext());\r
- Out << (isa<ObjCIvarDecl>(D) ? "@" : "@FI@");\r
- if (EmitDeclName(D)) {\r
- // Bit fields can be anonymous.\r
- IgnoreResults = true;\r
- return;\r
- }\r
-}\r
-\r
-void USRGenerator::VisitFunctionDecl(FunctionDecl *D) {\r
- if (ShouldGenerateLocation(D) && GenLoc(D))\r
- return;\r
-\r
- VisitDeclContext(D->getDeclContext());\r
- if (FunctionTemplateDecl *FunTmpl = D->getDescribedFunctionTemplate()) {\r
- Out << "@FT@";\r
- VisitTemplateParameterList(FunTmpl->getTemplateParameters());\r
- } else\r
- Out << "@F@";\r
- D->printName(Out);\r
-\r
- ASTContext &Ctx = *Context;\r
- if (!Ctx.getLangOpts().CPlusPlus || D->isExternC())\r
- return;\r
-\r
- if (const TemplateArgumentList *\r
- SpecArgs = D->getTemplateSpecializationArgs()) {\r
- Out << '<';\r
- for (unsigned I = 0, N = SpecArgs->size(); I != N; ++I) {\r
- Out << '#';\r
- VisitTemplateArgument(SpecArgs->get(I));\r
- }\r
- Out << '>';\r
- }\r
-\r
- // Mangle in type information for the arguments.\r
- for (FunctionDecl::param_iterator I = D->param_begin(), E = D->param_end();\r
- I != E; ++I) {\r
- Out << '#';\r
- if (ParmVarDecl *PD = *I)\r
- VisitType(PD->getType());\r
- }\r
- if (D->isVariadic())\r
- Out << '.';\r
- Out << '#';\r
- if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {\r
- if (MD->isStatic())\r
- Out << 'S';\r
- if (unsigned quals = MD->getTypeQualifiers())\r
- Out << (char)('0' + quals);\r
- }\r
-}\r
-\r
-void USRGenerator::VisitNamedDecl(NamedDecl *D) {\r
- VisitDeclContext(D->getDeclContext());\r
- Out << "@";\r
-\r
- if (EmitDeclName(D)) {\r
- // The string can be empty if the declaration has no name; e.g., it is\r
- // the ParmDecl with no name for declaration of a function pointer type,\r
- // e.g.: void (*f)(void *);\r
- // In this case, don't generate a USR.\r
- IgnoreResults = true;\r
- }\r
-}\r
-\r
-void USRGenerator::VisitVarDecl(VarDecl *D) {\r
- // VarDecls can be declared 'extern' within a function or method body,\r
- // but their enclosing DeclContext is the function, not the TU. We need\r
- // to check the storage class to correctly generate the USR.\r
- if (ShouldGenerateLocation(D) && GenLoc(D))\r
- return;\r
-\r
- VisitDeclContext(D->getDeclContext());\r
-\r
- // Variables always have simple names.\r
- StringRef s = D->getName();\r
-\r
- // The string can be empty if the declaration has no name; e.g., it is\r
- // the ParmDecl with no name for declaration of a function pointer type, e.g.:\r
- // void (*f)(void *);\r
- // In this case, don't generate a USR.\r
- if (s.empty())\r
- IgnoreResults = true;\r
- else\r
- Out << '@' << s;\r
-}\r
-\r
-void USRGenerator::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {\r
- GenLoc(D);\r
- return;\r
-}\r
-\r
-void USRGenerator::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {\r
- GenLoc(D);\r
- return;\r
-}\r
-\r
-void USRGenerator::VisitNamespaceDecl(NamespaceDecl *D) {\r
- if (D->isAnonymousNamespace()) {\r
- Out << "@aN";\r
- return;\r
- }\r
-\r
- VisitDeclContext(D->getDeclContext());\r
- if (!IgnoreResults)\r
- Out << "@N@" << D->getName();\r
-}\r
-\r
-void USRGenerator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {\r
- VisitFunctionDecl(D->getTemplatedDecl());\r
-}\r
-\r
-void USRGenerator::VisitClassTemplateDecl(ClassTemplateDecl *D) {\r
- VisitTagDecl(D->getTemplatedDecl());\r
-}\r
-\r
-void USRGenerator::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {\r
- VisitDeclContext(D->getDeclContext());\r
- if (!IgnoreResults)\r
- Out << "@NA@" << D->getName(); \r
-}\r
-\r
-void USRGenerator::VisitObjCMethodDecl(ObjCMethodDecl *D) {\r
- DeclContext *container = D->getDeclContext();\r
- if (ObjCProtocolDecl *pd = dyn_cast<ObjCProtocolDecl>(container)) {\r
- Visit(pd);\r
- }\r
- else {\r
- // The USR for a method declared in a class extension or category is based on\r
- // the ObjCInterfaceDecl, not the ObjCCategoryDecl.\r
- ObjCInterfaceDecl *ID = D->getClassInterface();\r
- if (!ID) {\r
- IgnoreResults = true;\r
- return;\r
- }\r
- Visit(ID);\r
- }\r
- // Ideally we would use 'GenObjCMethod', but this is such a hot path\r
- // for Objective-C code that we don't want to use\r
- // DeclarationName::getAsString().\r
- Out << (D->isInstanceMethod() ? "(im)" : "(cm)");\r
- DeclarationName N(D->getSelector());\r
- N.printName(Out);\r
-}\r
-\r
-void USRGenerator::VisitObjCContainerDecl(ObjCContainerDecl *D) {\r
- switch (D->getKind()) {\r
- default:\r
- llvm_unreachable("Invalid ObjC container.");\r
- case Decl::ObjCInterface:\r
- case Decl::ObjCImplementation:\r
- GenObjCClass(D->getName());\r
- break;\r
- case Decl::ObjCCategory: {\r
- ObjCCategoryDecl *CD = cast<ObjCCategoryDecl>(D);\r
- ObjCInterfaceDecl *ID = CD->getClassInterface();\r
- if (!ID) {\r
- // Handle invalid code where the @interface might not\r
- // have been specified.\r
- // FIXME: We should be able to generate this USR even if the\r
- // @interface isn't available.\r
- IgnoreResults = true;\r
- return;\r
- }\r
- // Specially handle class extensions, which are anonymous categories.\r
- // We want to mangle in the location to uniquely distinguish them.\r
- if (CD->IsClassExtension()) {\r
- Out << "objc(ext)" << ID->getName() << '@';\r
- GenLoc(CD);\r
- }\r
- else\r
- GenObjCCategory(ID->getName(), CD->getName());\r
-\r
- break;\r
- }\r
- case Decl::ObjCCategoryImpl: {\r
- ObjCCategoryImplDecl *CD = cast<ObjCCategoryImplDecl>(D);\r
- ObjCInterfaceDecl *ID = CD->getClassInterface();\r
- if (!ID) {\r
- // Handle invalid code where the @interface might not\r
- // have been specified.\r
- // FIXME: We should be able to generate this USR even if the\r
- // @interface isn't available.\r
- IgnoreResults = true;\r
- return;\r
- }\r
- GenObjCCategory(ID->getName(), CD->getName());\r
- break;\r
- }\r
- case Decl::ObjCProtocol:\r
- GenObjCProtocol(cast<ObjCProtocolDecl>(D)->getName());\r
- break;\r
- }\r
-}\r
-\r
-void USRGenerator::VisitObjCPropertyDecl(ObjCPropertyDecl *D) {\r
- // The USR for a property declared in a class extension or category is based\r
- // on the ObjCInterfaceDecl, not the ObjCCategoryDecl.\r
- if (ObjCInterfaceDecl *ID = Context->getObjContainingInterface(D))\r
- Visit(ID);\r
- else\r
- Visit(cast<Decl>(D->getDeclContext()));\r
- GenObjCProperty(D->getName());\r
-}\r
-\r
-void USRGenerator::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D) {\r
- if (ObjCPropertyDecl *PD = D->getPropertyDecl()) {\r
- VisitObjCPropertyDecl(PD);\r
- return;\r
- }\r
-\r
- IgnoreResults = true;\r
-}\r
-\r
-void USRGenerator::VisitTagDecl(TagDecl *D) {\r
- // Add the location of the tag decl to handle resolution across\r
- // translation units.\r
- if (ShouldGenerateLocation(D) && GenLoc(D))\r
- return;\r
-\r
- D = D->getCanonicalDecl();\r
- VisitDeclContext(D->getDeclContext());\r
-\r
- bool AlreadyStarted = false;\r
- if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(D)) {\r
- if (ClassTemplateDecl *ClassTmpl = CXXRecord->getDescribedClassTemplate()) {\r
- AlreadyStarted = true;\r
- \r
- switch (D->getTagKind()) {\r
- case TTK_Interface:\r
- case TTK_Struct: Out << "@ST"; break;\r
- case TTK_Class: Out << "@CT"; break;\r
- case TTK_Union: Out << "@UT"; break;\r
- case TTK_Enum: llvm_unreachable("enum template");\r
- }\r
- VisitTemplateParameterList(ClassTmpl->getTemplateParameters());\r
- } else if (ClassTemplatePartialSpecializationDecl *PartialSpec\r
- = dyn_cast<ClassTemplatePartialSpecializationDecl>(CXXRecord)) {\r
- AlreadyStarted = true;\r
- \r
- switch (D->getTagKind()) {\r
- case TTK_Interface:\r
- case TTK_Struct: Out << "@SP"; break;\r
- case TTK_Class: Out << "@CP"; break;\r
- case TTK_Union: Out << "@UP"; break;\r
- case TTK_Enum: llvm_unreachable("enum partial specialization");\r
- } \r
- VisitTemplateParameterList(PartialSpec->getTemplateParameters());\r
- }\r
- }\r
- \r
- if (!AlreadyStarted) {\r
- switch (D->getTagKind()) {\r
- case TTK_Interface:\r
- case TTK_Struct: Out << "@S"; break;\r
- case TTK_Class: Out << "@C"; break;\r
- case TTK_Union: Out << "@U"; break;\r
- case TTK_Enum: Out << "@E"; break;\r
- }\r
- }\r
- \r
- Out << '@';\r
- Out.flush();\r
- assert(Buf.size() > 0);\r
- const unsigned off = Buf.size() - 1;\r
-\r
- if (EmitDeclName(D)) {\r
- if (const TypedefNameDecl *TD = D->getTypedefNameForAnonDecl()) {\r
- Buf[off] = 'A';\r
- Out << '@' << *TD;\r
- }\r
- else\r
- Buf[off] = 'a';\r
- }\r
- \r
- // For a class template specialization, mangle the template arguments.\r
- if (ClassTemplateSpecializationDecl *Spec\r
- = dyn_cast<ClassTemplateSpecializationDecl>(D)) {\r
- const TemplateArgumentList &Args = Spec->getTemplateInstantiationArgs();\r
- Out << '>';\r
- for (unsigned I = 0, N = Args.size(); I != N; ++I) {\r
- Out << '#';\r
- VisitTemplateArgument(Args.get(I));\r
- }\r
- }\r
-}\r
-\r
-void USRGenerator::VisitTypedefDecl(TypedefDecl *D) {\r
- if (ShouldGenerateLocation(D) && GenLoc(D))\r
- return;\r
- DeclContext *DC = D->getDeclContext();\r
- if (NamedDecl *DCN = dyn_cast<NamedDecl>(DC))\r
- Visit(DCN);\r
- Out << "@T@";\r
- Out << D->getName();\r
-}\r
-\r
-void USRGenerator::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {\r
- GenLoc(D);\r
- return;\r
-}\r
-\r
-bool USRGenerator::GenLoc(const Decl *D) {\r
- if (generatedLoc)\r
- return IgnoreResults;\r
- generatedLoc = true;\r
- \r
- // Guard against null declarations in invalid code.\r
- if (!D) {\r
- IgnoreResults = true;\r
- return true;\r
- }\r
-\r
- // Use the location of canonical decl.\r
- D = D->getCanonicalDecl();\r
-\r
- const SourceManager &SM = Context->getSourceManager();\r
- SourceLocation L = D->getLocStart();\r
- if (L.isInvalid()) {\r
- IgnoreResults = true;\r
- return true;\r
- }\r
- L = SM.getExpansionLoc(L);\r
- const std::pair<FileID, unsigned> &Decomposed = SM.getDecomposedLoc(L);\r
- const FileEntry *FE = SM.getFileEntryForID(Decomposed.first);\r
- if (FE) {\r
- Out << llvm::sys::path::filename(FE->getName());\r
- }\r
- else {\r
- // This case really isn't interesting.\r
- IgnoreResults = true;\r
- return true;\r
- }\r
- // Use the offest into the FileID to represent the location. Using\r
- // a line/column can cause us to look back at the original source file,\r
- // which is expensive.\r
- Out << '@' << Decomposed.second;\r
- return IgnoreResults;\r
-}\r
-\r
-void USRGenerator::VisitType(QualType T) {\r
- // This method mangles in USR information for types. It can possibly\r
- // just reuse the naming-mangling logic used by codegen, although the\r
- // requirements for USRs might not be the same.\r
- ASTContext &Ctx = *Context;\r
-\r
- do {\r
- T = Ctx.getCanonicalType(T);\r
- Qualifiers Q = T.getQualifiers();\r
- unsigned qVal = 0;\r
- if (Q.hasConst())\r
- qVal |= 0x1;\r
- if (Q.hasVolatile())\r
- qVal |= 0x2;\r
- if (Q.hasRestrict())\r
- qVal |= 0x4;\r
- if(qVal)\r
- Out << ((char) ('0' + qVal));\r
-\r
- // Mangle in ObjC GC qualifiers?\r
-\r
- if (const PackExpansionType *Expansion = T->getAs<PackExpansionType>()) {\r
- Out << 'P';\r
- T = Expansion->getPattern();\r
- }\r
- \r
- if (const BuiltinType *BT = T->getAs<BuiltinType>()) {\r
- unsigned char c = '\0';\r
- switch (BT->getKind()) {\r
- case BuiltinType::Void:\r
- c = 'v'; break;\r
- case BuiltinType::Bool:\r
- c = 'b'; break;\r
- case BuiltinType::Char_U:\r
- case BuiltinType::UChar:\r
- c = 'c'; break;\r
- case BuiltinType::Char16:\r
- c = 'q'; break;\r
- case BuiltinType::Char32:\r
- c = 'w'; break;\r
- case BuiltinType::UShort:\r
- c = 's'; break;\r
- case BuiltinType::UInt:\r
- c = 'i'; break;\r
- case BuiltinType::ULong:\r
- c = 'l'; break;\r
- case BuiltinType::ULongLong:\r
- c = 'k'; break;\r
- case BuiltinType::UInt128:\r
- c = 'j'; break;\r
- case BuiltinType::Char_S:\r
- case BuiltinType::SChar:\r
- c = 'C'; break;\r
- case BuiltinType::WChar_S:\r
- case BuiltinType::WChar_U:\r
- c = 'W'; break;\r
- case BuiltinType::Short:\r
- c = 'S'; break;\r
- case BuiltinType::Int:\r
- c = 'I'; break;\r
- case BuiltinType::Long:\r
- c = 'L'; break;\r
- case BuiltinType::LongLong:\r
- c = 'K'; break;\r
- case BuiltinType::Int128:\r
- c = 'J'; break;\r
- case BuiltinType::Half:\r
- c = 'h'; break;\r
- case BuiltinType::Float:\r
- c = 'f'; break;\r
- case BuiltinType::Double:\r
- c = 'd'; break;\r
- case BuiltinType::LongDouble:\r
- c = 'D'; break;\r
- case BuiltinType::NullPtr:\r
- c = 'n'; break;\r
-#define BUILTIN_TYPE(Id, SingletonId)\r
-#define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id:\r
-#include "clang/AST/BuiltinTypes.def"\r
- case BuiltinType::Dependent:\r
- IgnoreResults = true;\r
- return;\r
- case BuiltinType::ObjCId:\r
- c = 'o'; break;\r
- case BuiltinType::ObjCClass:\r
- c = 'O'; break;\r
- case BuiltinType::ObjCSel:\r
- c = 'e'; break;\r
- }\r
- Out << c;\r
- return;\r
- }\r
-\r
- // If we have already seen this (non-built-in) type, use a substitution\r
- // encoding.\r
- llvm::DenseMap<const Type *, unsigned>::iterator Substitution\r
- = TypeSubstitutions.find(T.getTypePtr());\r
- if (Substitution != TypeSubstitutions.end()) {\r
- Out << 'S' << Substitution->second << '_';\r
- return;\r
- } else {\r
- // Record this as a substitution.\r
- unsigned Number = TypeSubstitutions.size();\r
- TypeSubstitutions[T.getTypePtr()] = Number;\r
- }\r
- \r
- if (const PointerType *PT = T->getAs<PointerType>()) {\r
- Out << '*';\r
- T = PT->getPointeeType();\r
- continue;\r
- }\r
- if (const ReferenceType *RT = T->getAs<ReferenceType>()) {\r
- Out << '&';\r
- T = RT->getPointeeType();\r
- continue;\r
- }\r
- if (const FunctionProtoType *FT = T->getAs<FunctionProtoType>()) {\r
- Out << 'F';\r
- VisitType(FT->getResultType());\r
- for (FunctionProtoType::arg_type_iterator\r
- I = FT->arg_type_begin(), E = FT->arg_type_end(); I!=E; ++I) {\r
- VisitType(*I);\r
- }\r
- if (FT->isVariadic())\r
- Out << '.';\r
- return;\r
- }\r
- if (const BlockPointerType *BT = T->getAs<BlockPointerType>()) {\r
- Out << 'B';\r
- T = BT->getPointeeType();\r
- continue;\r
- }\r
- if (const ComplexType *CT = T->getAs<ComplexType>()) {\r
- Out << '<';\r
- T = CT->getElementType();\r
- continue;\r
- }\r
- if (const TagType *TT = T->getAs<TagType>()) {\r
- Out << '$';\r
- VisitTagDecl(TT->getDecl());\r
- return;\r
- }\r
- if (const TemplateTypeParmType *TTP = T->getAs<TemplateTypeParmType>()) {\r
- Out << 't' << TTP->getDepth() << '.' << TTP->getIndex();\r
- return;\r
- }\r
- if (const TemplateSpecializationType *Spec\r
- = T->getAs<TemplateSpecializationType>()) {\r
- Out << '>';\r
- VisitTemplateName(Spec->getTemplateName());\r
- Out << Spec->getNumArgs();\r
- for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I)\r
- VisitTemplateArgument(Spec->getArg(I));\r
- return;\r
- }\r
- \r
- // Unhandled type.\r
- Out << ' ';\r
- break;\r
- } while (true);\r
-}\r
-\r
-void USRGenerator::VisitTemplateParameterList(\r
- const TemplateParameterList *Params) {\r
- if (!Params)\r
- return;\r
- Out << '>' << Params->size();\r
- for (TemplateParameterList::const_iterator P = Params->begin(),\r
- PEnd = Params->end();\r
- P != PEnd; ++P) {\r
- Out << '#';\r
- if (isa<TemplateTypeParmDecl>(*P)) {\r
- if (cast<TemplateTypeParmDecl>(*P)->isParameterPack())\r
- Out<< 'p';\r
- Out << 'T';\r
- continue;\r
- }\r
- \r
- if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {\r
- if (NTTP->isParameterPack())\r
- Out << 'p';\r
- Out << 'N';\r
- VisitType(NTTP->getType());\r
- continue;\r
- }\r
- \r
- TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);\r
- if (TTP->isParameterPack())\r
- Out << 'p';\r
- Out << 't';\r
- VisitTemplateParameterList(TTP->getTemplateParameters());\r
- }\r
-}\r
-\r
-void USRGenerator::VisitTemplateName(TemplateName Name) {\r
- if (TemplateDecl *Template = Name.getAsTemplateDecl()) {\r
- if (TemplateTemplateParmDecl *TTP\r
- = dyn_cast<TemplateTemplateParmDecl>(Template)) {\r
- Out << 't' << TTP->getDepth() << '.' << TTP->getIndex();\r
- return;\r
- }\r
- \r
- Visit(Template);\r
- return;\r
- }\r
- \r
- // FIXME: Visit dependent template names.\r
-}\r
-\r
-void USRGenerator::VisitTemplateArgument(const TemplateArgument &Arg) {\r
- switch (Arg.getKind()) {\r
- case TemplateArgument::Null:\r
- break;\r
-\r
- case TemplateArgument::Declaration:\r
- if (Decl *D = Arg.getAsDecl())\r
- Visit(D);\r
- break;\r
- \r
- case TemplateArgument::TemplateExpansion:\r
- Out << 'P'; // pack expansion of...\r
- // Fall through\r
- case TemplateArgument::Template:\r
- VisitTemplateName(Arg.getAsTemplateOrTemplatePattern());\r
- break;\r
- \r
- case TemplateArgument::Expression:\r
- // FIXME: Visit expressions.\r
- break;\r
- \r
- case TemplateArgument::Pack:\r
- Out << 'p' << Arg.pack_size();\r
- for (TemplateArgument::pack_iterator P = Arg.pack_begin(), PEnd = Arg.pack_end();\r
- P != PEnd; ++P)\r
- VisitTemplateArgument(*P);\r
- break;\r
- \r
- case TemplateArgument::Type:\r
- VisitType(Arg.getAsType());\r
- break;\r
- \r
- case TemplateArgument::Integral:\r
- Out << 'V';\r
- VisitType(Arg.getIntegralType());\r
- Out << Arg.getAsIntegral();\r
- break;\r
- }\r
-}\r
-\r
-//===----------------------------------------------------------------------===//\r
-// General purpose USR generation methods.\r
-//===----------------------------------------------------------------------===//\r
-\r
-void USRGenerator::GenObjCClass(StringRef cls) {\r
- Out << "objc(cs)" << cls;\r
-}\r
-\r
-void USRGenerator::GenObjCCategory(StringRef cls, StringRef cat) {\r
- Out << "objc(cy)" << cls << '@' << cat;\r
-}\r
-\r
-void USRGenerator::GenObjCIvar(StringRef ivar) {\r
- Out << '@' << ivar;\r
-}\r
-\r
-void USRGenerator::GenObjCMethod(StringRef meth, bool isInstanceMethod) {\r
- Out << (isInstanceMethod ? "(im)" : "(cm)") << meth;\r
-}\r
-\r
-void USRGenerator::GenObjCProperty(StringRef prop) {\r
- Out << "(py)" << prop;\r
-}\r
-\r
-void USRGenerator::GenObjCProtocol(StringRef prot) {\r
- Out << "objc(pl)" << prot;\r
-}\r
-\r
-//===----------------------------------------------------------------------===//\r
-// API hooks.\r
-//===----------------------------------------------------------------------===//\r
-\r
-static inline StringRef extractUSRSuffix(StringRef s) {\r
- return s.startswith("c:") ? s.substr(2) : "";\r
-}\r
-\r
-bool cxcursor::getDeclCursorUSR(const Decl *D, SmallVectorImpl<char> &Buf) {\r
- // Don't generate USRs for things with invalid locations.\r
- if (!D || D->getLocStart().isInvalid())\r
- return true;\r
-\r
- // Check if the cursor has 'NoLinkage'.\r
- if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))\r
- switch (ND->getLinkage()) {\r
- case ExternalLinkage:\r
- // Generate USRs for all entities with external linkage.\r
- break;\r
- case NoLinkage:\r
- case UniqueExternalLinkage:\r
- // We allow enums, typedefs, and structs that have no linkage to\r
- // have USRs that are anchored to the file they were defined in\r
- // (e.g., the header). This is a little gross, but in principal\r
- // enums/anonymous structs/etc. defined in a common header file\r
- // are referred to across multiple translation units.\r
- if (isa<TagDecl>(ND) || isa<TypedefDecl>(ND) ||\r
- isa<EnumConstantDecl>(ND) || isa<FieldDecl>(ND) ||\r
- isa<VarDecl>(ND) || isa<NamespaceDecl>(ND))\r
- break;\r
- // Fall-through.\r
- case InternalLinkage:\r
- if (isa<FunctionDecl>(ND))\r
- break;\r
- }\r
-\r
- {\r
- USRGenerator UG(&D->getASTContext(), &Buf);\r
- UG->Visit(const_cast<Decl*>(D));\r
-\r
- if (UG->ignoreResults())\r
- return true;\r
- }\r
-\r
- return false;\r
-}\r
-\r
-extern "C" {\r
-\r
-CXString clang_getCursorUSR(CXCursor C) {\r
- const CXCursorKind &K = clang_getCursorKind(C);\r
-\r
- if (clang_isDeclaration(K)) {\r
- Decl *D = cxcursor::getCursorDecl(C);\r
- if (!D)\r
- return createCXString("");\r
-\r
- CXTranslationUnit TU = cxcursor::getCursorTU(C);\r
- if (!TU)\r
- return createCXString("");\r
-\r
- CXStringBuf *buf = cxstring::getCXStringBuf(TU);\r
- if (!buf)\r
- return createCXString("");\r
-\r
- bool Ignore = cxcursor::getDeclCursorUSR(D, buf->Data);\r
- if (Ignore) {\r
- disposeCXStringBuf(buf);\r
- return createCXString("");\r
- }\r
-\r
- // Return the C-string, but don't make a copy since it is already in\r
- // the string buffer.\r
- buf->Data.push_back('\0');\r
- return createCXString(buf);\r
- }\r
-\r
- if (K == CXCursor_MacroDefinition) {\r
- CXTranslationUnit TU = cxcursor::getCursorTU(C);\r
- if (!TU)\r
- return createCXString("");\r
-\r
- CXStringBuf *buf = cxstring::getCXStringBuf(TU);\r
- if (!buf)\r
- return createCXString("");\r
-\r
- {\r
- USRGenerator UG(&cxcursor::getCursorASTUnit(C)->getASTContext(),\r
- &buf->Data);\r
- UG << "macro@"\r
- << cxcursor::getCursorMacroDefinition(C)->getName()->getNameStart();\r
- }\r
- buf->Data.push_back('\0');\r
- return createCXString(buf);\r
- }\r
-\r
- return createCXString("");\r
-}\r
-\r
-CXString clang_constructUSR_ObjCIvar(const char *name, CXString classUSR) {\r
- USRGenerator UG;\r
- UG << extractUSRSuffix(clang_getCString(classUSR));\r
- UG->GenObjCIvar(name);\r
- return createCXString(UG.str(), true);\r
-}\r
-\r
-CXString clang_constructUSR_ObjCMethod(const char *name,\r
- unsigned isInstanceMethod,\r
- CXString classUSR) {\r
- USRGenerator UG;\r
- UG << extractUSRSuffix(clang_getCString(classUSR));\r
- UG->GenObjCMethod(name, isInstanceMethod);\r
- return createCXString(UG.str(), true);\r
-}\r
-\r
-CXString clang_constructUSR_ObjCClass(const char *name) {\r
- USRGenerator UG;\r
- UG->GenObjCClass(name);\r
- return createCXString(UG.str(), true);\r
-}\r
-\r
-CXString clang_constructUSR_ObjCProtocol(const char *name) {\r
- USRGenerator UG;\r
- UG->GenObjCProtocol(name);\r
- return createCXString(UG.str(), true);\r
-}\r
-\r
-CXString clang_constructUSR_ObjCCategory(const char *class_name,\r
- const char *category_name) {\r
- USRGenerator UG;\r
- UG->GenObjCCategory(class_name, category_name);\r
- return createCXString(UG.str(), true);\r
-}\r
-\r
-CXString clang_constructUSR_ObjCProperty(const char *property,\r
- CXString classUSR) {\r
- USRGenerator UG;\r
- UG << extractUSRSuffix(clang_getCString(classUSR));\r
- UG->GenObjCProperty(property);\r
- return createCXString(UG.str(), true);\r
-}\r
-\r
-} // end extern "C"\r
+//===- CIndexUSR.cpp - Clang-C Source Indexing Library --------------------===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file implements the generation and use of USRs from CXEntities.
+//
+//===----------------------------------------------------------------------===//
+
+#include "CIndexer.h"
+#include "CXCursor.h"
+#include "CXString.h"
+#include "clang/AST/DeclTemplate.h"
+#include "clang/AST/DeclVisitor.h"
+#include "clang/Frontend/ASTUnit.h"
+#include "clang/Lex/PreprocessingRecord.h"
+#include "llvm/ADT/SmallString.h"
+#include "llvm/Support/raw_ostream.h"
+
+using namespace clang;
+using namespace clang::cxstring;
+
+//===----------------------------------------------------------------------===//
+// USR generation.
+//===----------------------------------------------------------------------===//
+
+namespace {
+class USRGenerator : public DeclVisitor<USRGenerator> {
+ OwningPtr<SmallString<128> > OwnedBuf;
+ SmallVectorImpl<char> &Buf;
+ llvm::raw_svector_ostream Out;
+ bool IgnoreResults;
+ ASTContext *Context;
+ bool generatedLoc;
+
+ llvm::DenseMap<const Type *, unsigned> TypeSubstitutions;
+
+public:
+ explicit USRGenerator(ASTContext *Ctx = 0, SmallVectorImpl<char> *extBuf = 0)
+ : OwnedBuf(extBuf ? 0 : new SmallString<128>()),
+ Buf(extBuf ? *extBuf : *OwnedBuf.get()),
+ Out(Buf),
+ IgnoreResults(false),
+ Context(Ctx),
+ generatedLoc(false)
+ {
+ // Add the USR space prefix.
+ Out << "c:";
+ }
+
+ StringRef str() {
+ return Out.str();
+ }
+
+ USRGenerator* operator->() { return this; }
+
+ template <typename T>
+ llvm::raw_svector_ostream &operator<<(const T &x) {
+ Out << x;
+ return Out;
+ }
+
+ bool ignoreResults() const { return IgnoreResults; }
+
+ // Visitation methods from generating USRs from AST elements.
+ void VisitDeclContext(DeclContext *D);
+ void VisitFieldDecl(FieldDecl *D);
+ void VisitFunctionDecl(FunctionDecl *D);
+ void VisitNamedDecl(NamedDecl *D);
+ void VisitNamespaceDecl(NamespaceDecl *D);
+ void VisitNamespaceAliasDecl(NamespaceAliasDecl *D);
+ void VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
+ void VisitClassTemplateDecl(ClassTemplateDecl *D);
+ void VisitObjCContainerDecl(ObjCContainerDecl *CD);
+ void VisitObjCMethodDecl(ObjCMethodDecl *MD);
+ void VisitObjCPropertyDecl(ObjCPropertyDecl *D);
+ void VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D);
+ void VisitTagDecl(TagDecl *D);
+ void VisitTypedefDecl(TypedefDecl *D);
+ void VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
+ void VisitVarDecl(VarDecl *D);
+ void VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D);
+ void VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D);
+ void VisitLinkageSpecDecl(LinkageSpecDecl *D) {
+ IgnoreResults = true;
+ }
+ void VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
+ IgnoreResults = true;
+ }
+ void VisitUsingDecl(UsingDecl *D) {
+ IgnoreResults = true;
+ }
+ void VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
+ IgnoreResults = true;
+ }
+ void VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D) {
+ IgnoreResults = true;
+ }
+
+ /// Generate the string component containing the location of the
+ /// declaration.
+ bool GenLoc(const Decl *D);
+
+ /// String generation methods used both by the visitation methods
+ /// and from other clients that want to directly generate USRs. These
+ /// methods do not construct complete USRs (which incorporate the parents
+ /// of an AST element), but only the fragments concerning the AST element
+ /// itself.
+
+ /// Generate a USR for an Objective-C class.
+ void GenObjCClass(StringRef cls);
+ /// Generate a USR for an Objective-C class category.
+ void GenObjCCategory(StringRef cls, StringRef cat);
+ /// Generate a USR fragment for an Objective-C instance variable. The
+ /// complete USR can be created by concatenating the USR for the
+ /// encompassing class with this USR fragment.
+ void GenObjCIvar(StringRef ivar);
+ /// Generate a USR fragment for an Objective-C method.
+ void GenObjCMethod(StringRef sel, bool isInstanceMethod);
+ /// Generate a USR fragment for an Objective-C property.
+ void GenObjCProperty(StringRef prop);
+ /// Generate a USR for an Objective-C protocol.
+ void GenObjCProtocol(StringRef prot);
+
+ void VisitType(QualType T);
+ void VisitTemplateParameterList(const TemplateParameterList *Params);
+ void VisitTemplateName(TemplateName Name);
+ void VisitTemplateArgument(const TemplateArgument &Arg);
+
+ /// Emit a Decl's name using NamedDecl::printName() and return true if
+ /// the decl had no name.
+ bool EmitDeclName(const NamedDecl *D);
+};
+
+} // end anonymous namespace
+
+//===----------------------------------------------------------------------===//
+// Generating USRs from ASTS.
+//===----------------------------------------------------------------------===//
+
+bool USRGenerator::EmitDeclName(const NamedDecl *D) {
+ Out.flush();
+ const unsigned startSize = Buf.size();
+ D->printName(Out);
+ Out.flush();
+ const unsigned endSize = Buf.size();
+ return startSize == endSize;
+}
+
+static bool InAnonymousNamespace(const Decl *D) {
+ if (const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(D->getDeclContext()))
+ return ND->isAnonymousNamespace();
+ return false;
+}
+
+static inline bool ShouldGenerateLocation(const NamedDecl *D) {
+ return D->getLinkage() != ExternalLinkage && !InAnonymousNamespace(D);
+}
+
+void USRGenerator::VisitDeclContext(DeclContext *DC) {
+ if (NamedDecl *D = dyn_cast<NamedDecl>(DC))
+ Visit(D);
+}
+
+void USRGenerator::VisitFieldDecl(FieldDecl *D) {
+ // The USR for an ivar declared in a class extension is based on the
+ // ObjCInterfaceDecl, not the ObjCCategoryDecl.
+ if (ObjCInterfaceDecl *ID = Context->getObjContainingInterface(D))
+ Visit(ID);
+ else
+ VisitDeclContext(D->getDeclContext());
+ Out << (isa<ObjCIvarDecl>(D) ? "@" : "@FI@");
+ if (EmitDeclName(D)) {
+ // Bit fields can be anonymous.
+ IgnoreResults = true;
+ return;
+ }
+}
+
+void USRGenerator::VisitFunctionDecl(FunctionDecl *D) {
+ if (ShouldGenerateLocation(D) && GenLoc(D))
+ return;
+
+ VisitDeclContext(D->getDeclContext());
+ if (FunctionTemplateDecl *FunTmpl = D->getDescribedFunctionTemplate()) {
+ Out << "@FT@";
+ VisitTemplateParameterList(FunTmpl->getTemplateParameters());
+ } else
+ Out << "@F@";
+ D->printName(Out);
+
+ ASTContext &Ctx = *Context;
+ if (!Ctx.getLangOpts().CPlusPlus || D->isExternC())
+ return;
+
+ if (const TemplateArgumentList *
+ SpecArgs = D->getTemplateSpecializationArgs()) {
+ Out << '<';
+ for (unsigned I = 0, N = SpecArgs->size(); I != N; ++I) {
+ Out << '#';
+ VisitTemplateArgument(SpecArgs->get(I));
+ }
+ Out << '>';
+ }
+
+ // Mangle in type information for the arguments.
+ for (FunctionDecl::param_iterator I = D->param_begin(), E = D->param_end();
+ I != E; ++I) {
+ Out << '#';
+ if (ParmVarDecl *PD = *I)
+ VisitType(PD->getType());
+ }
+ if (D->isVariadic())
+ Out << '.';
+ Out << '#';
+ if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
+ if (MD->isStatic())
+ Out << 'S';
+ if (unsigned quals = MD->getTypeQualifiers())
+ Out << (char)('0' + quals);
+ }
+}
+
+void USRGenerator::VisitNamedDecl(NamedDecl *D) {
+ VisitDeclContext(D->getDeclContext());
+ Out << "@";
+
+ if (EmitDeclName(D)) {
+ // The string can be empty if the declaration has no name; e.g., it is
+ // the ParmDecl with no name for declaration of a function pointer type,
+ // e.g.: void (*f)(void *);
+ // In this case, don't generate a USR.
+ IgnoreResults = true;
+ }
+}
+
+void USRGenerator::VisitVarDecl(VarDecl *D) {
+ // VarDecls can be declared 'extern' within a function or method body,
+ // but their enclosing DeclContext is the function, not the TU. We need
+ // to check the storage class to correctly generate the USR.
+ if (ShouldGenerateLocation(D) && GenLoc(D))
+ return;
+
+ VisitDeclContext(D->getDeclContext());
+
+ // Variables always have simple names.
+ StringRef s = D->getName();
+
+ // The string can be empty if the declaration has no name; e.g., it is
+ // the ParmDecl with no name for declaration of a function pointer type, e.g.:
+ // void (*f)(void *);
+ // In this case, don't generate a USR.
+ if (s.empty())
+ IgnoreResults = true;
+ else
+ Out << '@' << s;
+}
+
+void USRGenerator::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
+ GenLoc(D);
+ return;
+}
+
+void USRGenerator::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
+ GenLoc(D);
+ return;
+}
+
+void USRGenerator::VisitNamespaceDecl(NamespaceDecl *D) {
+ if (D->isAnonymousNamespace()) {
+ Out << "@aN";
+ return;
+ }
+
+ VisitDeclContext(D->getDeclContext());
+ if (!IgnoreResults)
+ Out << "@N@" << D->getName();
+}
+
+void USRGenerator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
+ VisitFunctionDecl(D->getTemplatedDecl());
+}
+
+void USRGenerator::VisitClassTemplateDecl(ClassTemplateDecl *D) {
+ VisitTagDecl(D->getTemplatedDecl());
+}
+
+void USRGenerator::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
+ VisitDeclContext(D->getDeclContext());
+ if (!IgnoreResults)
+ Out << "@NA@" << D->getName();
+}
+
+void USRGenerator::VisitObjCMethodDecl(ObjCMethodDecl *D) {
+ DeclContext *container = D->getDeclContext();
+ if (ObjCProtocolDecl *pd = dyn_cast<ObjCProtocolDecl>(container)) {
+ Visit(pd);
+ }
+ else {
+ // The USR for a method declared in a class extension or category is based on
+ // the ObjCInterfaceDecl, not the ObjCCategoryDecl.
+ ObjCInterfaceDecl *ID = D->getClassInterface();
+ if (!ID) {
+ IgnoreResults = true;
+ return;
+ }
+ Visit(ID);
+ }
+ // Ideally we would use 'GenObjCMethod', but this is such a hot path
+ // for Objective-C code that we don't want to use
+ // DeclarationName::getAsString().
+ Out << (D->isInstanceMethod() ? "(im)" : "(cm)");
+ DeclarationName N(D->getSelector());
+ N.printName(Out);
+}
+
+void USRGenerator::VisitObjCContainerDecl(ObjCContainerDecl *D) {
+ switch (D->getKind()) {
+ default:
+ llvm_unreachable("Invalid ObjC container.");
+ case Decl::ObjCInterface:
+ case Decl::ObjCImplementation:
+ GenObjCClass(D->getName());
+ break;
+ case Decl::ObjCCategory: {
+ ObjCCategoryDecl *CD = cast<ObjCCategoryDecl>(D);
+ ObjCInterfaceDecl *ID = CD->getClassInterface();
+ if (!ID) {
+ // Handle invalid code where the @interface might not
+ // have been specified.
+ // FIXME: We should be able to generate this USR even if the
+ // @interface isn't available.
+ IgnoreResults = true;
+ return;
+ }
+ // Specially handle class extensions, which are anonymous categories.
+ // We want to mangle in the location to uniquely distinguish them.
+ if (CD->IsClassExtension()) {
+ Out << "objc(ext)" << ID->getName() << '@';
+ GenLoc(CD);
+ }
+ else
+ GenObjCCategory(ID->getName(), CD->getName());
+
+ break;
+ }
+ case Decl::ObjCCategoryImpl: {
+ ObjCCategoryImplDecl *CD = cast<ObjCCategoryImplDecl>(D);
+ ObjCInterfaceDecl *ID = CD->getClassInterface();
+ if (!ID) {
+ // Handle invalid code where the @interface might not
+ // have been specified.
+ // FIXME: We should be able to generate this USR even if the
+ // @interface isn't available.
+ IgnoreResults = true;
+ return;
+ }
+ GenObjCCategory(ID->getName(), CD->getName());
+ break;
+ }
+ case Decl::ObjCProtocol:
+ GenObjCProtocol(cast<ObjCProtocolDecl>(D)->getName());
+ break;
+ }
+}
+
+void USRGenerator::VisitObjCPropertyDecl(ObjCPropertyDecl *D) {
+ // The USR for a property declared in a class extension or category is based
+ // on the ObjCInterfaceDecl, not the ObjCCategoryDecl.
+ if (ObjCInterfaceDecl *ID = Context->getObjContainingInterface(D))
+ Visit(ID);
+ else
+ Visit(cast<Decl>(D->getDeclContext()));
+ GenObjCProperty(D->getName());
+}
+
+void USRGenerator::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D) {
+ if (ObjCPropertyDecl *PD = D->getPropertyDecl()) {
+ VisitObjCPropertyDecl(PD);
+ return;
+ }
+
+ IgnoreResults = true;
+}
+
+void USRGenerator::VisitTagDecl(TagDecl *D) {
+ // Add the location of the tag decl to handle resolution across
+ // translation units.
+ if (ShouldGenerateLocation(D) && GenLoc(D))
+ return;
+
+ D = D->getCanonicalDecl();
+ VisitDeclContext(D->getDeclContext());
+
+ bool AlreadyStarted = false;
+ if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(D)) {
+ if (ClassTemplateDecl *ClassTmpl = CXXRecord->getDescribedClassTemplate()) {
+ AlreadyStarted = true;
+
+ switch (D->getTagKind()) {
+ case TTK_Interface:
+ case TTK_Struct: Out << "@ST"; break;
+ case TTK_Class: Out << "@CT"; break;
+ case TTK_Union: Out << "@UT"; break;
+ case TTK_Enum: llvm_unreachable("enum template");
+ }
+ VisitTemplateParameterList(ClassTmpl->getTemplateParameters());
+ } else if (ClassTemplatePartialSpecializationDecl *PartialSpec
+ = dyn_cast<ClassTemplatePartialSpecializationDecl>(CXXRecord)) {
+ AlreadyStarted = true;
+
+ switch (D->getTagKind()) {
+ case TTK_Interface:
+ case TTK_Struct: Out << "@SP"; break;
+ case TTK_Class: Out << "@CP"; break;
+ case TTK_Union: Out << "@UP"; break;
+ case TTK_Enum: llvm_unreachable("enum partial specialization");
+ }
+ VisitTemplateParameterList(PartialSpec->getTemplateParameters());
+ }
+ }
+
+ if (!AlreadyStarted) {
+ switch (D->getTagKind()) {
+ case TTK_Interface:
+ case TTK_Struct: Out << "@S"; break;
+ case TTK_Class: Out << "@C"; break;
+ case TTK_Union: Out << "@U"; break;
+ case TTK_Enum: Out << "@E"; break;
+ }
+ }
+
+ Out << '@';
+ Out.flush();
+ assert(Buf.size() > 0);
+ const unsigned off = Buf.size() - 1;
+
+ if (EmitDeclName(D)) {
+ if (const TypedefNameDecl *TD = D->getTypedefNameForAnonDecl()) {
+ Buf[off] = 'A';
+ Out << '@' << *TD;
+ }
+ else
+ Buf[off] = 'a';
+ }
+
+ // For a class template specialization, mangle the template arguments.
+ if (ClassTemplateSpecializationDecl *Spec
+ = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
+ const TemplateArgumentList &Args = Spec->getTemplateInstantiationArgs();
+ Out << '>';
+ for (unsigned I = 0, N = Args.size(); I != N; ++I) {
+ Out << '#';
+ VisitTemplateArgument(Args.get(I));
+ }
+ }
+}
+
+void USRGenerator::VisitTypedefDecl(TypedefDecl *D) {
+ if (ShouldGenerateLocation(D) && GenLoc(D))
+ return;
+ DeclContext *DC = D->getDeclContext();
+ if (NamedDecl *DCN = dyn_cast<NamedDecl>(DC))
+ Visit(DCN);
+ Out << "@T@";
+ Out << D->getName();
+}
+
+void USRGenerator::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
+ GenLoc(D);
+ return;
+}
+
+bool USRGenerator::GenLoc(const Decl *D) {
+ if (generatedLoc)
+ return IgnoreResults;
+ generatedLoc = true;
+
+ // Guard against null declarations in invalid code.
+ if (!D) {
+ IgnoreResults = true;
+ return true;
+ }
+
+ // Use the location of canonical decl.
+ D = D->getCanonicalDecl();
+
+ const SourceManager &SM = Context->getSourceManager();
+ SourceLocation L = D->getLocStart();
+ if (L.isInvalid()) {
+ IgnoreResults = true;
+ return true;
+ }
+ L = SM.getExpansionLoc(L);
+ const std::pair<FileID, unsigned> &Decomposed = SM.getDecomposedLoc(L);
+ const FileEntry *FE = SM.getFileEntryForID(Decomposed.first);
+ if (FE) {
+ Out << llvm::sys::path::filename(FE->getName());
+ }
+ else {
+ // This case really isn't interesting.
+ IgnoreResults = true;
+ return true;
+ }
+ // Use the offest into the FileID to represent the location. Using
+ // a line/column can cause us to look back at the original source file,
+ // which is expensive.
+ Out << '@' << Decomposed.second;
+ return IgnoreResults;
+}
+
+void USRGenerator::VisitType(QualType T) {
+ // This method mangles in USR information for types. It can possibly
+ // just reuse the naming-mangling logic used by codegen, although the
+ // requirements for USRs might not be the same.
+ ASTContext &Ctx = *Context;
+
+ do {
+ T = Ctx.getCanonicalType(T);
+ Qualifiers Q = T.getQualifiers();
+ unsigned qVal = 0;
+ if (Q.hasConst())
+ qVal |= 0x1;
+ if (Q.hasVolatile())
+ qVal |= 0x2;
+ if (Q.hasRestrict())
+ qVal |= 0x4;
+ if(qVal)
+ Out << ((char) ('0' + qVal));
+
+ // Mangle in ObjC GC qualifiers?
+
+ if (const PackExpansionType *Expansion = T->getAs<PackExpansionType>()) {
+ Out << 'P';
+ T = Expansion->getPattern();
+ }
+
+ if (const BuiltinType *BT = T->getAs<BuiltinType>()) {
+ unsigned char c = '\0';
+ switch (BT->getKind()) {
+ case BuiltinType::Void:
+ c = 'v'; break;
+ case BuiltinType::Bool:
+ c = 'b'; break;
+ case BuiltinType::Char_U:
+ case BuiltinType::UChar:
+ c = 'c'; break;
+ case BuiltinType::Char16:
+ c = 'q'; break;
+ case BuiltinType::Char32:
+ c = 'w'; break;
+ case BuiltinType::UShort:
+ c = 's'; break;
+ case BuiltinType::UInt:
+ c = 'i'; break;
+ case BuiltinType::ULong:
+ c = 'l'; break;
+ case BuiltinType::ULongLong:
+ c = 'k'; break;
+ case BuiltinType::UInt128:
+ c = 'j'; break;
+ case BuiltinType::Char_S:
+ case BuiltinType::SChar:
+ c = 'C'; break;
+ case BuiltinType::WChar_S:
+ case BuiltinType::WChar_U:
+ c = 'W'; break;
+ case BuiltinType::Short:
+ c = 'S'; break;
+ case BuiltinType::Int:
+ c = 'I'; break;
+ case BuiltinType::Long:
+ c = 'L'; break;
+ case BuiltinType::LongLong:
+ c = 'K'; break;
+ case BuiltinType::Int128:
+ c = 'J'; break;
+ case BuiltinType::Half:
+ c = 'h'; break;
+ case BuiltinType::Float:
+ c = 'f'; break;
+ case BuiltinType::Double:
+ c = 'd'; break;
+ case BuiltinType::LongDouble:
+ c = 'D'; break;
+ case BuiltinType::NullPtr:
+ c = 'n'; break;
+#define BUILTIN_TYPE(Id, SingletonId)
+#define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id:
+#include "clang/AST/BuiltinTypes.def"
+ case BuiltinType::Dependent:
+ IgnoreResults = true;
+ return;
+ case BuiltinType::ObjCId:
+ c = 'o'; break;
+ case BuiltinType::ObjCClass:
+ c = 'O'; break;
+ case BuiltinType::ObjCSel:
+ c = 'e'; break;
+ }
+ Out << c;
+ return;
+ }
+
+ // If we have already seen this (non-built-in) type, use a substitution
+ // encoding.
+ llvm::DenseMap<const Type *, unsigned>::iterator Substitution
+ = TypeSubstitutions.find(T.getTypePtr());
+ if (Substitution != TypeSubstitutions.end()) {
+ Out << 'S' << Substitution->second << '_';
+ return;
+ } else {
+ // Record this as a substitution.
+ unsigned Number = TypeSubstitutions.size();
+ TypeSubstitutions[T.getTypePtr()] = Number;
+ }
+
+ if (const PointerType *PT = T->getAs<PointerType>()) {
+ Out << '*';
+ T = PT->getPointeeType();
+ continue;
+ }
+ if (const ReferenceType *RT = T->getAs<ReferenceType>()) {
+ Out << '&';
+ T = RT->getPointeeType();
+ continue;
+ }
+ if (const FunctionProtoType *FT = T->getAs<FunctionProtoType>()) {
+ Out << 'F';
+ VisitType(FT->getResultType());
+ for (FunctionProtoType::arg_type_iterator
+ I = FT->arg_type_begin(), E = FT->arg_type_end(); I!=E; ++I) {
+ VisitType(*I);
+ }
+ if (FT->isVariadic())
+ Out << '.';
+ return;
+ }
+ if (const BlockPointerType *BT = T->getAs<BlockPointerType>()) {
+ Out << 'B';
+ T = BT->getPointeeType();
+ continue;
+ }
+ if (const ComplexType *CT = T->getAs<ComplexType>()) {
+ Out << '<';
+ T = CT->getElementType();
+ continue;
+ }
+ if (const TagType *TT = T->getAs<TagType>()) {
+ Out << '$';
+ VisitTagDecl(TT->getDecl());
+ return;
+ }
+ if (const TemplateTypeParmType *TTP = T->getAs<TemplateTypeParmType>()) {
+ Out << 't' << TTP->getDepth() << '.' << TTP->getIndex();
+ return;
+ }
+ if (const TemplateSpecializationType *Spec
+ = T->getAs<TemplateSpecializationType>()) {
+ Out << '>';
+ VisitTemplateName(Spec->getTemplateName());
+ Out << Spec->getNumArgs();
+ for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I)
+ VisitTemplateArgument(Spec->getArg(I));
+ return;
+ }
+
+ // Unhandled type.
+ Out << ' ';
+ break;
+ } while (true);
+}
+
+void USRGenerator::VisitTemplateParameterList(
+ const TemplateParameterList *Params) {
+ if (!Params)
+ return;
+ Out << '>' << Params->size();
+ for (TemplateParameterList::const_iterator P = Params->begin(),
+ PEnd = Params->end();
+ P != PEnd; ++P) {
+ Out << '#';
+ if (isa<TemplateTypeParmDecl>(*P)) {
+ if (cast<TemplateTypeParmDecl>(*P)->isParameterPack())
+ Out<< 'p';
+ Out << 'T';
+ continue;
+ }
+
+ if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
+ if (NTTP->isParameterPack())
+ Out << 'p';
+ Out << 'N';
+ VisitType(NTTP->getType());
+ continue;
+ }
+
+ TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
+ if (TTP->isParameterPack())
+ Out << 'p';
+ Out << 't';
+ VisitTemplateParameterList(TTP->getTemplateParameters());
+ }
+}
+
+void USRGenerator::VisitTemplateName(TemplateName Name) {
+ if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
+ if (TemplateTemplateParmDecl *TTP
+ = dyn_cast<TemplateTemplateParmDecl>(Template)) {
+ Out << 't' << TTP->getDepth() << '.' << TTP->getIndex();
+ return;
+ }
+
+ Visit(Template);
+ return;
+ }
+
+ // FIXME: Visit dependent template names.
+}
+
+void USRGenerator::VisitTemplateArgument(const TemplateArgument &Arg) {
+ switch (Arg.getKind()) {
+ case TemplateArgument::Null:
+ break;
+
+ case TemplateArgument::Declaration:
+ if (Decl *D = Arg.getAsDecl())
+ Visit(D);
+ break;
+
+ case TemplateArgument::TemplateExpansion:
+ Out << 'P'; // pack expansion of...
+ // Fall through
+ case TemplateArgument::Template:
+ VisitTemplateName(Arg.getAsTemplateOrTemplatePattern());
+ break;
+
+ case TemplateArgument::Expression:
+ // FIXME: Visit expressions.
+ break;
+
+ case TemplateArgument::Pack:
+ Out << 'p' << Arg.pack_size();
+ for (TemplateArgument::pack_iterator P = Arg.pack_begin(), PEnd = Arg.pack_end();
+ P != PEnd; ++P)
+ VisitTemplateArgument(*P);
+ break;
+
+ case TemplateArgument::Type:
+ VisitType(Arg.getAsType());
+ break;
+
+ case TemplateArgument::Integral:
+ Out << 'V';
+ VisitType(Arg.getIntegralType());
+ Out << Arg.getAsIntegral();
+ break;
+ }
+}
+
+//===----------------------------------------------------------------------===//
+// General purpose USR generation methods.
+//===----------------------------------------------------------------------===//
+
+void USRGenerator::GenObjCClass(StringRef cls) {
+ Out << "objc(cs)" << cls;
+}
+
+void USRGenerator::GenObjCCategory(StringRef cls, StringRef cat) {
+ Out << "objc(cy)" << cls << '@' << cat;
+}
+
+void USRGenerator::GenObjCIvar(StringRef ivar) {
+ Out << '@' << ivar;
+}
+
+void USRGenerator::GenObjCMethod(StringRef meth, bool isInstanceMethod) {
+ Out << (isInstanceMethod ? "(im)" : "(cm)") << meth;
+}
+
+void USRGenerator::GenObjCProperty(StringRef prop) {
+ Out << "(py)" << prop;
+}
+
+void USRGenerator::GenObjCProtocol(StringRef prot) {
+ Out << "objc(pl)" << prot;
+}
+
+//===----------------------------------------------------------------------===//
+// API hooks.
+//===----------------------------------------------------------------------===//
+
+static inline StringRef extractUSRSuffix(StringRef s) {
+ return s.startswith("c:") ? s.substr(2) : "";
+}
+
+bool cxcursor::getDeclCursorUSR(const Decl *D, SmallVectorImpl<char> &Buf) {
+ // Don't generate USRs for things with invalid locations.
+ if (!D || D->getLocStart().isInvalid())
+ return true;
+
+ // Check if the cursor has 'NoLinkage'.
+ if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
+ switch (ND->getLinkage()) {
+ case ExternalLinkage:
+ // Generate USRs for all entities with external linkage.
+ break;
+ case NoLinkage:
+ case UniqueExternalLinkage:
+ // We allow enums, typedefs, and structs that have no linkage to
+ // have USRs that are anchored to the file they were defined in
+ // (e.g., the header). This is a little gross, but in principal
+ // enums/anonymous structs/etc. defined in a common header file
+ // are referred to across multiple translation units.
+ if (isa<TagDecl>(ND) || isa<TypedefDecl>(ND) ||
+ isa<EnumConstantDecl>(ND) || isa<FieldDecl>(ND) ||
+ isa<VarDecl>(ND) || isa<NamespaceDecl>(ND))
+ break;
+ // Fall-through.
+ case InternalLinkage:
+ if (isa<FunctionDecl>(ND))
+ break;
+ }
+
+ {
+ USRGenerator UG(&D->getASTContext(), &Buf);
+ UG->Visit(const_cast<Decl*>(D));
+
+ if (UG->ignoreResults())
+ return true;
+ }
+
+ return false;
+}
+
+extern "C" {
+
+CXString clang_getCursorUSR(CXCursor C) {
+ const CXCursorKind &K = clang_getCursorKind(C);
+
+ if (clang_isDeclaration(K)) {
+ Decl *D = cxcursor::getCursorDecl(C);
+ if (!D)
+ return createCXString("");
+
+ CXTranslationUnit TU = cxcursor::getCursorTU(C);
+ if (!TU)
+ return createCXString("");
+
+ CXStringBuf *buf = cxstring::getCXStringBuf(TU);
+ if (!buf)
+ return createCXString("");
+
+ bool Ignore = cxcursor::getDeclCursorUSR(D, buf->Data);
+ if (Ignore) {
+ disposeCXStringBuf(buf);
+ return createCXString("");
+ }
+
+ // Return the C-string, but don't make a copy since it is already in
+ // the string buffer.
+ buf->Data.push_back('\0');
+ return createCXString(buf);
+ }
+
+ if (K == CXCursor_MacroDefinition) {
+ CXTranslationUnit TU = cxcursor::getCursorTU(C);
+ if (!TU)
+ return createCXString("");
+
+ CXStringBuf *buf = cxstring::getCXStringBuf(TU);
+ if (!buf)
+ return createCXString("");
+
+ {
+ USRGenerator UG(&cxcursor::getCursorASTUnit(C)->getASTContext(),
+ &buf->Data);
+ UG << "macro@"
+ << cxcursor::getCursorMacroDefinition(C)->getName()->getNameStart();
+ }
+ buf->Data.push_back('\0');
+ return createCXString(buf);
+ }
+
+ return createCXString("");
+}
+
+CXString clang_constructUSR_ObjCIvar(const char *name, CXString classUSR) {
+ USRGenerator UG;
+ UG << extractUSRSuffix(clang_getCString(classUSR));
+ UG->GenObjCIvar(name);
+ return createCXString(UG.str(), true);
+}
+
+CXString clang_constructUSR_ObjCMethod(const char *name,
+ unsigned isInstanceMethod,
+ CXString classUSR) {
+ USRGenerator UG;
+ UG << extractUSRSuffix(clang_getCString(classUSR));
+ UG->GenObjCMethod(name, isInstanceMethod);
+ return createCXString(UG.str(), true);
+}
+
+CXString clang_constructUSR_ObjCClass(const char *name) {
+ USRGenerator UG;
+ UG->GenObjCClass(name);
+ return createCXString(UG.str(), true);
+}
+
+CXString clang_constructUSR_ObjCProtocol(const char *name) {
+ USRGenerator UG;
+ UG->GenObjCProtocol(name);
+ return createCXString(UG.str(), true);
+}
+
+CXString clang_constructUSR_ObjCCategory(const char *class_name,
+ const char *category_name) {
+ USRGenerator UG;
+ UG->GenObjCCategory(class_name, category_name);
+ return createCXString(UG.str(), true);
+}
+
+CXString clang_constructUSR_ObjCProperty(const char *property,
+ CXString classUSR) {
+ USRGenerator UG;
+ UG << extractUSRSuffix(clang_getCString(classUSR));
+ UG->GenObjCProperty(property);
+ return createCXString(UG.str(), true);
+}
+
+} // end extern "C"