brintos

brintos / llvm-project-archived public Read only

0
0
Text · 12.0 KiB · 2b83595 Raw
260 lines · c
1//===--- AST.h - Utility AST functions  -------------------------*- C++ -*-===//2//3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.4// See https://llvm.org/LICENSE.txt for license information.5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception6//7//===----------------------------------------------------------------------===//8//9// Various code that examines C++ source code using AST.10//11//===----------------------------------------------------------------------===//12 13#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANGD_AST_H14#define LLVM_CLANG_TOOLS_EXTRA_CLANGD_AST_H15 16#include "Headers.h"17#include "index/Symbol.h"18#include "index/SymbolID.h"19#include "clang/AST/Decl.h"20#include "clang/AST/DeclObjC.h"21#include "clang/AST/NestedNameSpecifier.h"22#include "clang/AST/TypeLoc.h"23#include "clang/Basic/SourceLocation.h"24#include "clang/Lex/MacroInfo.h"25#include "llvm/ADT/StringRef.h"26#include <optional>27#include <string>28#include <vector>29 30namespace clang {31class SourceManager;32class Decl;33class DynTypedNode;34class HeuristicResolver;35 36namespace clangd {37 38/// Returns true if the declaration is considered implementation detail based on39/// heuristics. For example, a declaration whose name is not explicitly spelled40/// in code is considered implementation detail.41bool isImplementationDetail(const Decl *D);42 43/// Find the source location of the identifier for \p D.44/// Transforms macro locations to locations spelled inside files. All code45/// that needs locations of declaration names (e.g. the index) should go through46/// this function.47SourceLocation nameLocation(const clang::Decl &D, const SourceManager &SM);48 49/// Returns the qualified name of ND. The scope doesn't contain unwritten scopes50/// like inline namespaces.51std::string printQualifiedName(const NamedDecl &ND);52 53/// Returns the first enclosing namespace scope starting from \p DC.54std::string printNamespaceScope(const DeclContext &DC);55 56/// Returns the name of the namespace inside the 'using namespace' directive, as57/// written in the code. E.g., passing 'using namespace ::std' will result in58/// '::std'.59std::string printUsingNamespaceName(const ASTContext &Ctx,60                                    const UsingDirectiveDecl &D);61 62/// Prints unqualified name of the decl for the purpose of displaying it to the63/// user. Anonymous decls return names of the form "(anonymous {kind})", e.g.64/// "(anonymous struct)" or "(anonymous namespace)".65std::string printName(const ASTContext &Ctx, const NamedDecl &ND);66 67/// Prints template arguments of a decl as written in the source code, including68/// enclosing '<' and '>', e.g for a partial specialization like: template69/// <typename U> struct Foo<int, U> will return '<int, U>'. Returns an empty70/// string if decl is not a template specialization.71std::string printTemplateSpecializationArgs(const NamedDecl &ND);72 73/// Print the Objective-C method name, including the full container name, e.g.74/// `-[MyClass(Category) method:]`75std::string printObjCMethod(const ObjCMethodDecl &Method);76 77/// Print the Objective-C container name including categories, e.g. `MyClass`,78// `MyClass()`, `MyClass(Category)`, and `MyProtocol`.79std::string printObjCContainer(const ObjCContainerDecl &C);80 81/// Returns true if this is a NamedDecl with a reserved name.82bool hasReservedName(const Decl &);83/// Returns true if this scope would be written with a reserved name.84/// This does not include unwritten scope elements like __1 in std::__1::vector.85bool hasReservedScope(const DeclContext &);86 87/// Gets the symbol ID for a declaration. Returned SymbolID might be null.88SymbolID getSymbolID(const Decl *D);89 90/// Gets the symbol ID for a macro. Returned SymbolID might be null.91/// Currently, this is an encoded USR of the macro, which incorporates macro92/// locations (e.g. file name, offset in file).93/// FIXME: the USR semantics might not be stable enough as the ID for index94/// macro (e.g. a change in definition offset can result in a different USR). We95/// could change these semantics in the future by reimplementing this funcure96/// (e.g. avoid USR for macros).97SymbolID getSymbolID(const llvm::StringRef MacroName, const MacroInfo *MI,98                     const SourceManager &SM);99 100/// Return the corresponding implementation/definition for the given ObjC101/// container if it has one, otherwise, return nullptr.102///103/// Objective-C classes can have three types of declarations:104///105/// - forward declaration: "@class MyClass;"106/// - true declaration (interface definition): "@interface MyClass ... @end"107/// - true definition (implementation): "@implementation MyClass ... @end"108///109/// Objective-C categories are extensions on classes:110///111/// - declaration: "@interface MyClass (Ext) ... @end"112/// - definition: "@implementation MyClass (Ext) ... @end"113///114/// With one special case, a class extension, which is normally used to keep115/// some declarations internal to a file without exposing them in a header.116///117/// - class extension declaration: "@interface MyClass () ... @end"118/// - which really links to class definition: "@implementation MyClass ... @end"119///120/// For Objective-C protocols, e.g. "@protocol MyProtocol ... @end" this will121/// return nullptr as protocols don't have an implementation.122const ObjCImplDecl *getCorrespondingObjCImpl(const ObjCContainerDecl *D);123 124/// Infer the include directive to use for the given \p FileName. It aims for125/// #import for ObjC files and #include for the rest.126///127/// - For source files we use LangOpts directly to infer ObjC-ness.128/// - For header files we also check for symbols declared by the file and129///   existing include directives, as the language can be set to ObjC++ as a130///   fallback in the absence of compile flags.131Symbol::IncludeDirective132preferredIncludeDirective(llvm::StringRef FileName, const LangOptions &LangOpts,133                          ArrayRef<Inclusion> MainFileIncludes,134                          ArrayRef<const Decl *> TopLevelDecls);135 136/// Returns a QualType as string. The result doesn't contain unwritten scopes137/// like anonymous/inline namespace.138std::string printType(const QualType QT, const DeclContext &CurContext,139                      llvm::StringRef Placeholder = "",140                      bool FullyQualify = false);141 142/// Indicates if \p D is a template instantiation implicitly generated by the143/// compiler, e.g.144///     template <class T> struct vector {};145///     vector<int> v; // 'vector<int>' is an implicit instantiation146bool isImplicitTemplateInstantiation(const NamedDecl *D);147/// Indicates if \p D is an explicit template specialization, e.g.148///   template <class T> struct vector {};149///   template <> struct vector<bool> {}; // <-- explicit specialization150///151/// Note that explicit instantiations are NOT explicit specializations, albeit152/// they look similar.153///   template struct vector<bool>; // <-- explicit instantiation, NOT an154///   explicit specialization.155bool isExplicitTemplateSpecialization(const NamedDecl *D);156 157/// Returns a nested name specifier loc of \p ND if it was present in the158/// source, e.g.159///     void ns::something::foo() -> returns 'ns::something'160///     void foo() -> returns null161NestedNameSpecifierLoc getQualifierLoc(const NamedDecl &ND);162 163// Returns a type corresponding to a declaration of that type.164// Unlike the method on ASTContext, attempts to preserve the type as-written165// (i.e. vector<T*> rather than vector<type-parameter-0-0 *>.166QualType declaredType(const TypeDecl *D);167 168/// Retrieves the deduced type at a given location (auto, decltype).169/// It will return the underlying type.170/// If the type is an undeduced auto, returns the type itself.171std::optional<QualType> getDeducedType(ASTContext &, const HeuristicResolver *,172                                       SourceLocation Loc);173 174// Find the abbreviated-function-template `auto` within a type, or returns null.175// Similar to getContainedAutoTypeLoc, but these `auto`s are176// TemplateTypeParmTypes for implicit TTPs, instead of AutoTypes.177// Also we don't look very hard, just stripping const, references, pointers.178// FIXME: handle more type patterns.179TemplateTypeParmTypeLoc getContainedAutoParamType(TypeLoc TL);180 181// If TemplatedDecl is the generic body of a template, and the template has182// exactly one visible instantiation, return the instantiated body.183NamedDecl *getOnlyInstantiation(NamedDecl *TemplatedDecl);184 185/// Return attributes attached directly to a node.186std::vector<const Attr *> getAttributes(const DynTypedNode &);187 188/// Gets the nested name specifier necessary for spelling \p ND in \p189/// DestContext, at \p InsertionPoint. It selects the shortest suffix of \p ND190/// such that it is visible in \p DestContext.191/// Returns an empty string if no qualification is necessary. For example, if192/// you want to qualify clang::clangd::bar::foo in clang::clangd::x, this193/// function will return bar. Note that the result might be sub-optimal for194/// classes, e.g. when the \p ND is a member of the base class.195///196/// This version considers all the using namespace directives before \p197/// InsertionPoint. i.e, if you have `using namespace198/// clang::clangd::bar`, this function will return an empty string for the199/// example above since no qualification is necessary in that case.200/// FIXME: Also take using directives and namespace aliases inside function body201/// into account.202std::string getQualification(ASTContext &Context,203                             const DeclContext *DestContext,204                             SourceLocation InsertionPoint,205                             const NamedDecl *ND);206 207/// This function uses the \p VisibleNamespaces to figure out if a shorter208/// qualification is sufficient for \p ND, and ignores any using namespace209/// directives. It can be useful if there's no AST for the DestContext, but some210/// pseudo-parsing is done. i.e. if \p ND is ns1::ns2::X and \p DestContext is211/// ns1::, users can provide `ns2::` as visible to change the result to be212/// empty.213/// Elements in VisibleNamespaces should be in the form: `ns::`, with trailing214/// "::".215/// Note that this is just textual and might be incorrect. e.g. when there are216/// two namespaces ns1::a and ns2::a, the function will early exit if "a::" is217/// present in \p VisibleNamespaces, no matter whether it is from ns1:: or ns2::218std::string getQualification(ASTContext &Context,219                             const DeclContext *DestContext,220                             const NamedDecl *ND,221                             llvm::ArrayRef<std::string> VisibleNamespaces);222 223/// Whether we must avoid computing linkage for D during code completion.224/// Clang aggressively caches linkage computation, which is stable after the AST225/// is built. Unfortunately the AST is incomplete during code completion, so226/// linkage may still change.227///228/// Example: `auto x = []{^}` at file scope.229/// During code completion, the initializer for x hasn't been parsed yet.230/// x has type `undeduced auto`, and external linkage.231/// If we compute linkage at this point, the external linkage will be cached.232///233/// After code completion the initializer is attached, and x has a lambda type.234/// This means x has "unique external" linkage. If we computed linkage above,235/// the cached value is incorrect. (clang catches this with an assertion).236bool hasUnstableLinkage(const Decl *D);237 238/// Checks whether \p D is more than \p MaxDepth away from translation unit239/// scope.240/// This is useful for limiting traversals to keep operation latencies241/// reasonable.242bool isDeeplyNested(const Decl *D, unsigned MaxDepth = 10);243 244/// Recursively resolves the parameters of a FunctionDecl that forwards its245/// parameters to another function via variadic template parameters. This can246/// for example be used to retrieve the constructor parameter ParmVarDecl for a247/// make_unique or emplace_back call.248llvm::SmallVector<const ParmVarDecl *>249resolveForwardingParameters(const FunctionDecl *D, unsigned MaxDepth = 10);250 251/// Checks whether D is instantiated from a function parameter pack252/// whose type is a bare type parameter pack (e.g. `Args...`), or a253/// reference to one (e.g. `Args&...` or `Args&&...`).254bool isExpandedFromParameterPack(const ParmVarDecl *D);255 256} // namespace clangd257} // namespace clang258 259#endif // LLVM_CLANG_TOOLS_EXTRA_CLANGD_AST_H260