clang-tools 23.0.0git
AST.h
Go to the documentation of this file.
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-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// Various code that examines C++ source code using AST.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANGD_AST_H
14#define LLVM_CLANG_TOOLS_EXTRA_CLANGD_AST_H
15
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/TypeLoc.h"
22#include "clang/Basic/SourceLocation.h"
23#include "clang/Lex/MacroInfo.h"
24#include "llvm/ADT/ArrayRef.h"
25#include "llvm/ADT/DenseMap.h"
26#include "llvm/ADT/SmallVector.h"
27#include "llvm/ADT/StringRef.h"
28#include <optional>
29#include <string>
30#include <vector>
31
32namespace clang {
33class SourceManager;
34class Decl;
35class DynTypedNode;
36class HeuristicResolver;
37
38namespace clangd {
39
40/// Returns true if the declaration is considered implementation detail based on
41/// heuristics. For example, a declaration whose name is not explicitly spelled
42/// in code is considered implementation detail.
43bool isImplementationDetail(const Decl *D);
44
45/// Find the source location of the identifier for \p D.
46/// Transforms macro locations to locations spelled inside files. All code
47/// that needs locations of declaration names (e.g. the index) should go through
48/// this function.
49SourceLocation nameLocation(const clang::Decl &D, const SourceManager &SM);
50
51/// Returns the qualified name of ND. The scope doesn't contain unwritten scopes
52/// like inline namespaces.
53std::string printQualifiedName(const NamedDecl &ND);
54
55/// Returns the first enclosing namespace scope starting from \p DC.
56std::string printNamespaceScope(const DeclContext &DC);
57
58/// Returns the name of the namespace inside the 'using namespace' directive, as
59/// written in the code. E.g., passing 'using namespace ::std' will result in
60/// '::std'.
61std::string printUsingNamespaceName(const ASTContext &Ctx,
62 const UsingDirectiveDecl &D);
63
64/// Prints unqualified name of the decl for the purpose of displaying it to the
65/// user. Anonymous decls return names of the form "(anonymous {kind})", e.g.
66/// "(anonymous struct)" or "(anonymous namespace)".
67std::string printName(const ASTContext &Ctx, const NamedDecl &ND);
68
69/// Prints template arguments of a decl as written in the source code, including
70/// enclosing '<' and '>', e.g for a partial specialization like: template
71/// <typename U> struct Foo<int, U> will return '<int, U>'. Returns an empty
72/// string if decl is not a template specialization.
73std::string printTemplateSpecializationArgs(const NamedDecl &ND);
74
75/// Print the Objective-C method name, including the full container name, e.g.
76/// `-[MyClass(Category) method:]`
77std::string printObjCMethod(const ObjCMethodDecl &Method);
78
79/// Print the Objective-C container name including categories, e.g. `MyClass`,
80// `MyClass()`, `MyClass(Category)`, and `MyProtocol`.
81std::string printObjCContainer(const ObjCContainerDecl &C);
82
83/// Returns true if this is a NamedDecl with a reserved name.
84bool hasReservedName(const Decl &);
85/// Returns true if this scope would be written with a reserved name.
86/// This does not include unwritten scope elements like __1 in std::__1::vector.
87bool hasReservedScope(const DeclContext &);
88
89/// Gets the symbol ID for a declaration. Returned SymbolID might be null.
90SymbolID getSymbolID(const Decl *D);
91
92/// Gets the symbol ID for a macro. Returned SymbolID might be null.
93/// Currently, this is an encoded USR of the macro, which incorporates macro
94/// locations (e.g. file name, offset in file).
95/// FIXME: the USR semantics might not be stable enough as the ID for index
96/// macro (e.g. a change in definition offset can result in a different USR). We
97/// could change these semantics in the future by reimplementing this funcure
98/// (e.g. avoid USR for macros).
99SymbolID getSymbolID(const llvm::StringRef MacroName, const MacroInfo *MI,
100 const SourceManager &SM);
101
102/// Return the corresponding implementation/definition for the given ObjC
103/// container if it has one, otherwise, return nullptr.
104///
105/// Objective-C classes can have three types of declarations:
106///
107/// - forward declaration: "@class MyClass;"
108/// - true declaration (interface definition): "@interface MyClass ... @end"
109/// - true definition (implementation): "@implementation MyClass ... @end"
110///
111/// Objective-C categories are extensions on classes:
112///
113/// - declaration: "@interface MyClass (Ext) ... @end"
114/// - definition: "@implementation MyClass (Ext) ... @end"
115///
116/// With one special case, a class extension, which is normally used to keep
117/// some declarations internal to a file without exposing them in a header.
118///
119/// - class extension declaration: "@interface MyClass () ... @end"
120/// - which really links to class definition: "@implementation MyClass ... @end"
121///
122/// For Objective-C protocols, e.g. "@protocol MyProtocol ... @end" this will
123/// return nullptr as protocols don't have an implementation.
124const ObjCImplDecl *getCorrespondingObjCImpl(const ObjCContainerDecl *D);
125
126/// Infer the include directive to use for the given \p FileName. It aims for
127/// #import for ObjC files and #include for the rest.
128///
129/// - For source files we use LangOpts directly to infer ObjC-ness.
130/// - For header files we also check for symbols declared by the file and
131/// existing include directives, as the language can be set to ObjC++ as a
132/// fallback in the absence of compile flags.
134preferredIncludeDirective(llvm::StringRef FileName, const LangOptions &LangOpts,
135 ArrayRef<Inclusion> MainFileIncludes,
136 ArrayRef<const Decl *> TopLevelDecls);
137
138/// Returns a QualType as string. The result doesn't contain unwritten scopes
139/// like anonymous/inline namespace.
140std::string printType(const QualType QT, const DeclContext &CurContext,
141 llvm::StringRef Placeholder = "",
142 bool FullyQualify = false);
143
144/// Indicates if \p D is a template instantiation implicitly generated by the
145/// compiler, e.g.
146/// template <class T> struct vector {};
147/// vector<int> v; // 'vector<int>' is an implicit instantiation
148bool isImplicitTemplateInstantiation(const NamedDecl *D);
149/// Indicates if \p D is an explicit template specialization, e.g.
150/// template <class T> struct vector {};
151/// template <> struct vector<bool> {}; // <-- explicit specialization
152///
153/// Note that explicit instantiations are NOT explicit specializations, albeit
154/// they look similar.
155/// template struct vector<bool>; // <-- explicit instantiation, NOT an
156/// explicit specialization.
157bool isExplicitTemplateSpecialization(const NamedDecl *D);
158
159/// Returns a nested name specifier loc of \p ND if it was present in the
160/// source, e.g.
161/// void ns::something::foo() -> returns 'ns::something'
162/// void foo() -> returns null
163NestedNameSpecifierLoc getQualifierLoc(const NamedDecl &ND);
164
165// Returns a type corresponding to a declaration of that type.
166// Unlike the method on ASTContext, attempts to preserve the type as-written
167// (i.e. vector<T*> rather than vector<type-parameter-0-0 *>.
168QualType declaredType(const TypeDecl *D);
169
170/// Retrieves the deduced type at a given location (auto, decltype).
171/// It will return the underlying type.
172/// If the type is an undeduced auto, returns the type itself.
173std::optional<QualType> getDeducedType(ASTContext &, const HeuristicResolver *,
174 SourceLocation Loc);
175
176// Find the abbreviated-function-template `auto` within a type, or returns null.
177// Similar to getContainedAutoTypeLoc, but these `auto`s are
178// TemplateTypeParmTypes for implicit TTPs, instead of AutoTypes.
179// Also we don't look very hard, just stripping const, references, pointers.
180// FIXME: handle more type patterns.
181TemplateTypeParmTypeLoc getContainedAutoParamType(TypeLoc TL);
182
183// If TemplatedDecl is the generic body of a template, and the template has
184// exactly one visible instantiation, return the instantiated body.
185NamedDecl *getOnlyInstantiation(NamedDecl *TemplatedDecl);
186
187/// Return attributes attached directly to a node.
188std::vector<const Attr *> getAttributes(const DynTypedNode &);
189
190/// Gets the nested name specifier necessary for spelling \p ND in \p
191/// DestContext, at \p InsertionPoint. It selects the shortest suffix of \p ND
192/// such that it is visible in \p DestContext.
193/// Returns an empty string if no qualification is necessary. For example, if
194/// you want to qualify clang::clangd::bar::foo in clang::clangd::x, this
195/// function will return bar. Note that the result might be sub-optimal for
196/// classes, e.g. when the \p ND is a member of the base class.
197///
198/// This version considers all the using namespace directives before \p
199/// InsertionPoint. i.e, if you have `using namespace
200/// clang::clangd::bar`, this function will return an empty string for the
201/// example above since no qualification is necessary in that case.
202/// FIXME: Also take using directives and namespace aliases inside function body
203/// into account.
204std::string getQualification(ASTContext &Context,
205 const DeclContext *DestContext,
206 SourceLocation InsertionPoint,
207 const NamedDecl *ND);
208
209/// This function uses the \p VisibleNamespaces to figure out if a shorter
210/// qualification is sufficient for \p ND, and ignores any using namespace
211/// directives. It can be useful if there's no AST for the DestContext, but some
212/// pseudo-parsing is done. i.e. if \p ND is ns1::ns2::X and \p DestContext is
213/// ns1::, users can provide `ns2::` as visible to change the result to be
214/// empty.
215/// Elements in VisibleNamespaces should be in the form: `ns::`, with trailing
216/// "::".
217/// Note that this is just textual and might be incorrect. e.g. when there are
218/// two namespaces ns1::a and ns2::a, the function will early exit if "a::" is
219/// present in \p VisibleNamespaces, no matter whether it is from ns1:: or ns2::
220std::string getQualification(ASTContext &Context,
221 const DeclContext *DestContext,
222 const NamedDecl *ND,
223 llvm::ArrayRef<std::string> VisibleNamespaces);
224
225/// Whether we must avoid computing linkage for D during code completion.
226/// Clang aggressively caches linkage computation, which is stable after the AST
227/// is built. Unfortunately the AST is incomplete during code completion, so
228/// linkage may still change.
229///
230/// Example: `auto x = []{^}` at file scope.
231/// During code completion, the initializer for x hasn't been parsed yet.
232/// x has type `undeduced auto`, and external linkage.
233/// If we compute linkage at this point, the external linkage will be cached.
234///
235/// After code completion the initializer is attached, and x has a lambda type.
236/// This means x has "unique external" linkage. If we computed linkage above,
237/// the cached value is incorrect. (clang catches this with an assertion).
238bool hasUnstableLinkage(const Decl *D);
239
240/// Checks whether \p D is more than \p MaxDepth away from translation unit
241/// scope.
242/// This is useful for limiting traversals to keep operation latencies
243/// reasonable.
244bool isDeeplyNested(const Decl *D, unsigned MaxDepth = 10);
245
246/// Recursively resolves the parameters of a FunctionDecl that forwards its
247/// parameters to another function via variadic template parameters. This can
248/// for example be used to retrieve the constructor parameter ParmVarDecl for a
249/// make_unique or emplace_back call.
250llvm::SmallVector<const ParmVarDecl *>
251resolveForwardingParameters(const FunctionDecl *D, unsigned MaxDepth = 10);
252
253/// Checks whether D is instantiated from a function parameter pack
254/// whose type is a bare type parameter pack (e.g. `Args...`), or a
255/// reference to one (e.g. `Args&...` or `Args&&...`).
256bool isExpandedFromParameterPack(const ParmVarDecl *D);
257
258/// Heuristic that checks if FT is likely to be forwarding a parameter pack to
259/// another function (e.g. `make_unique`).
260bool isLikelyForwardingFunction(const FunctionTemplateDecl *FT);
261
262/// Only call if FD is a likely forwarding function. Returns
263/// constructors that might be forwarded to.
264SmallVector<const CXXConstructorDecl *, 1>
265searchConstructorsInForwardingFunction(const FunctionDecl *FD);
266
267/// Cache mapping forwarding function instantiations (e.g. `make_unique<T>`)
268/// to the constructors they ultimately call.
270 llvm::DenseMap<const FunctionDecl *,
272
273/// Returns the constructors that FD forwards to, if FD is a template
274/// instantiation of a likely forwarding function (see
275/// `isLikelyForwardingFunction`). Results are memoized in `Cache`. Returns
276/// an empty range for non-forwarding functions; the cache is only populated
277/// for true forwarding instantiations to keep its size bounded.
278///
279/// FD must not be null. The returned ArrayRef is owned by `Cache`; consume
280/// it before any other call that may insert into the same cache.
281ArrayRef<const CXXConstructorDecl *>
282getForwardedConstructors(const FunctionDecl *FD,
284
285} // namespace clangd
286} // namespace clang
287
288#endif // LLVM_CLANG_TOOLS_EXTRA_CLANGD_AST_H
A context is an immutable container for per-request data that must be propagated through layers that ...
Definition Context.h:69
FIXME: Skip testing on windows temporarily due to the different escaping code mode.
Definition AST.cpp:44
SmallVector< const ParmVarDecl * > resolveForwardingParameters(const FunctionDecl *D, unsigned MaxDepth)
Recursively resolves the parameters of a FunctionDecl that forwards its parameters to another functio...
Definition AST.cpp:982
std::string printTemplateSpecializationArgs(const NamedDecl &ND)
Prints template arguments of a decl as written in the source code, including enclosing '<' and '>',...
Definition AST.cpp:287
std::string printObjCMethod(const ObjCMethodDecl &Method)
Print the Objective-C method name, including the full container name, e.g.
Definition AST.cpp:316
bool isLikelyForwardingFunction(const FunctionTemplateDecl *FT)
Heuristic that checks if FT is likely to be forwarding a parameter pack to another function (e....
Definition AST.cpp:1043
SymbolID getSymbolID(const Decl *D)
Gets the symbol ID for a declaration. Returned SymbolID might be null.
Definition AST.cpp:354
std::string printName(const ASTContext &Ctx, const NamedDecl &ND)
Prints unqualified name of the decl for the purpose of displaying it to the user.
Definition AST.cpp:248
std::string printObjCContainer(const ObjCContainerDecl &C)
Print the Objective-C container name including categories, e.g. MyClass,.
Definition AST.cpp:335
std::string printType(const QualType QT, const DeclContext &CurContext, const llvm::StringRef Placeholder, bool FullyQualify)
Returns a QualType as string.
Definition AST.cpp:417
std::string getQualification(ASTContext &Context, const DeclContext *DestContext, SourceLocation InsertionPoint, const NamedDecl *ND)
Gets the nested name specifier necessary for spelling ND in DestContext, at InsertionPoint.
Definition AST.cpp:698
bool isExplicitTemplateSpecialization(const NamedDecl *D)
Indicates if D is an explicit template specialization, e.g.
Definition AST.cpp:187
NamedDecl * getOnlyInstantiation(NamedDecl *TemplatedDecl)
Definition AST.cpp:662
SourceLocation nameLocation(const clang::Decl &D, const SourceManager &SM)
Find the source location of the identifier for D.
Definition AST.cpp:196
NestedNameSpecifierLoc getQualifierLoc(const NamedDecl &ND)
Returns a nested name specifier loc of ND if it was present in the source, e.g.
Definition AST.cpp:229
std::optional< QualType > getDeducedType(ASTContext &ASTCtx, const HeuristicResolver *Resolver, SourceLocation Loc)
Retrieves the deduced type at a given location (auto, decltype).
Definition AST.cpp:623
Symbol::IncludeDirective preferredIncludeDirective(llvm::StringRef FileName, const LangOptions &LangOpts, ArrayRef< Inclusion > MainFileIncludes, ArrayRef< const Decl * > TopLevelDecls)
Infer the include directive to use for the given FileName.
Definition AST.cpp:386
bool isExpandedFromParameterPack(const ParmVarDecl *D)
Checks whether D is instantiated from a function parameter pack whose type is a bare type parameter p...
Definition AST.cpp:1039
bool hasUnstableLinkage(const Decl *D)
Whether we must avoid computing linkage for D during code completion.
Definition AST.cpp:735
std::string printUsingNamespaceName(const ASTContext &Ctx, const UsingDirectiveDecl &D)
Returns the name of the namespace inside the 'using namespace' directive, as written in the code.
Definition AST.cpp:237
bool hasReservedName(const Decl &D)
Returns true if this is a NamedDecl with a reserved name.
Definition AST.cpp:444
std::vector< const Attr * > getAttributes(const DynTypedNode &N)
Return attributes attached directly to a node.
Definition AST.cpp:674
SmallVector< const CXXConstructorDecl *, 1 > searchConstructorsInForwardingFunction(const FunctionDecl *FD)
Only call if FD is a likely forwarding function.
Definition AST.cpp:1110
ArrayRef< const CXXConstructorDecl * > getForwardedConstructors(const FunctionDecl *FD, ForwardingToConstructorCache &Cache)
Returns the constructors that FD forwards to, if FD is a template instantiation of a likely forwardin...
Definition AST.cpp:1119
QualType declaredType(const TypeDecl *D)
Definition AST.cpp:462
bool isImplementationDetail(const Decl *D)
Returns true if the declaration is considered implementation detail based on heuristics.
Definition AST.cpp:191
const ObjCImplDecl * getCorrespondingObjCImpl(const ObjCContainerDecl *D)
Return the corresponding implementation/definition for the given ObjC container if it has one,...
Definition AST.cpp:371
llvm::DenseMap< const FunctionDecl *, SmallVector< const CXXConstructorDecl *, 1 > > ForwardingToConstructorCache
Cache mapping forwarding function instantiations (e.g.
Definition AST.h:269
bool isImplicitTemplateInstantiation(const NamedDecl *D)
Indicates if D is a template instantiation implicitly generated by the compiler, e....
Definition AST.cpp:183
bool hasReservedScope(const DeclContext &DC)
Returns true if this scope would be written with a reserved name.
Definition AST.cpp:451
std::string printQualifiedName(const NamedDecl &ND)
Returns the qualified name of ND.
Definition AST.cpp:206
TemplateTypeParmTypeLoc getContainedAutoParamType(TypeLoc TL)
Definition AST.cpp:635
bool isDeeplyNested(const Decl *D, unsigned MaxDepth)
Checks whether D is more than MaxDepth away from translation unit scope.
Definition AST.cpp:742
std::string printNamespaceScope(const DeclContext &DC)
Returns the first enclosing namespace scope starting from DC.
Definition AST.cpp:303
===– Representation.cpp - ClangDoc Representation --------—*- C++ -*-===//