Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
clang 20.0.0git
HeuristicResolver.cpp
Go to the documentation of this file.
1//===--- HeuristicResolver.cpp ---------------------------*- 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
13#include "clang/AST/ExprCXX.h"
14#include "clang/AST/Type.h"
15
16namespace clang {
17
18namespace {
19
20// Helper class for implementing HeuristicResolver.
21// Unlike HeuristicResolver which is a long-lived class,
22// a new instance of this class is created for every external
23// call into a HeuristicResolver operation. That allows this
24// class to store state that's local to such a top-level call,
25// particularly "recursion protection sets" that keep track of
26// nodes that have already been seen to avoid infinite recursion.
27class HeuristicResolverImpl {
28public:
29 HeuristicResolverImpl(ASTContext &Ctx) : Ctx(Ctx) {}
30
31 // These functions match the public interface of HeuristicResolver
32 // (but aren't const since they may modify the recursion protection sets).
33 std::vector<const NamedDecl *>
34 resolveMemberExpr(const CXXDependentScopeMemberExpr *ME);
35 std::vector<const NamedDecl *>
36 resolveDeclRefExpr(const DependentScopeDeclRefExpr *RE);
37 std::vector<const NamedDecl *> resolveTypeOfCallExpr(const CallExpr *CE);
38 std::vector<const NamedDecl *> resolveCalleeOfCallExpr(const CallExpr *CE);
39 std::vector<const NamedDecl *>
40 resolveUsingValueDecl(const UnresolvedUsingValueDecl *UUVD);
41 std::vector<const NamedDecl *>
42 resolveDependentNameType(const DependentNameType *DNT);
43 std::vector<const NamedDecl *> resolveTemplateSpecializationType(
44 const DependentTemplateSpecializationType *DTST);
45 QualType resolveNestedNameSpecifierToType(const NestedNameSpecifier *NNS);
46 QualType getPointeeType(QualType T);
47
48private:
49 ASTContext &Ctx;
50
51 // Recursion protection sets
52 llvm::SmallSet<const DependentNameType *, 4> SeenDependentNameTypes;
53
54 // Given a tag-decl type and a member name, heuristically resolve the
55 // name to one or more declarations.
56 // The current heuristic is simply to look up the name in the primary
57 // template. This is a heuristic because the template could potentially
58 // have specializations that declare different members.
59 // Multiple declarations could be returned if the name is overloaded
60 // (e.g. an overloaded method in the primary template).
61 // This heuristic will give the desired answer in many cases, e.g.
62 // for a call to vector<T>::size().
63 std::vector<const NamedDecl *>
64 resolveDependentMember(QualType T, DeclarationName Name,
65 llvm::function_ref<bool(const NamedDecl *ND)> Filter);
66
67 // Try to heuristically resolve the type of a possibly-dependent expression
68 // `E`.
69 QualType resolveExprToType(const Expr *E);
70 std::vector<const NamedDecl *> resolveExprToDecls(const Expr *E);
71
72 // Helper function for HeuristicResolver::resolveDependentMember()
73 // which takes a possibly-dependent type `T` and heuristically
74 // resolves it to a CXXRecordDecl in which we can try name lookup.
75 CXXRecordDecl *resolveTypeToRecordDecl(const Type *T);
76
77 // This is a reimplementation of CXXRecordDecl::lookupDependentName()
78 // so that the implementation can call into other HeuristicResolver helpers.
79 // FIXME: Once HeuristicResolver is upstreamed to the clang libraries
80 // (https://github.com/clangd/clangd/discussions/1662),
81 // CXXRecordDecl::lookupDepenedentName() can be removed, and its call sites
82 // can be modified to benefit from the more comprehensive heuristics offered
83 // by HeuristicResolver instead.
84 std::vector<const NamedDecl *>
85 lookupDependentName(CXXRecordDecl *RD, DeclarationName Name,
86 llvm::function_ref<bool(const NamedDecl *ND)> Filter);
87 bool findOrdinaryMemberInDependentClasses(const CXXBaseSpecifier *Specifier,
88 CXXBasePath &Path,
89 DeclarationName Name);
90};
91
92// Convenience lambdas for use as the 'Filter' parameter of
93// HeuristicResolver::resolveDependentMember().
94const auto NoFilter = [](const NamedDecl *D) { return true; };
95const auto NonStaticFilter = [](const NamedDecl *D) {
96 return D->isCXXInstanceMember();
97};
98const auto StaticFilter = [](const NamedDecl *D) {
99 return !D->isCXXInstanceMember();
100};
101const auto ValueFilter = [](const NamedDecl *D) { return isa<ValueDecl>(D); };
102const auto TypeFilter = [](const NamedDecl *D) { return isa<TypeDecl>(D); };
103const auto TemplateFilter = [](const NamedDecl *D) {
104 return isa<TemplateDecl>(D);
105};
106
107QualType resolveDeclsToType(const std::vector<const NamedDecl *> &Decls,
108 ASTContext &Ctx) {
109 if (Decls.size() != 1) // Names an overload set -- just bail.
110 return QualType();
111 if (const auto *TD = dyn_cast<TypeDecl>(Decls[0])) {
112 return Ctx.getTypeDeclType(TD);
113 }
114 if (const auto *VD = dyn_cast<ValueDecl>(Decls[0])) {
115 return VD->getType();
116 }
117 return QualType();
118}
119
120TemplateName getReferencedTemplateName(const Type *T) {
121 if (const auto *TST = T->getAs<TemplateSpecializationType>()) {
122 return TST->getTemplateName();
123 }
124 if (const auto *DTST = T->getAs<DeducedTemplateSpecializationType>()) {
125 return DTST->getTemplateName();
126 }
127 return TemplateName();
128}
129
130// Helper function for HeuristicResolver::resolveDependentMember()
131// which takes a possibly-dependent type `T` and heuristically
132// resolves it to a CXXRecordDecl in which we can try name lookup.
133CXXRecordDecl *HeuristicResolverImpl::resolveTypeToRecordDecl(const Type *T) {
134 assert(T);
135
136 // Unwrap type sugar such as type aliases.
138
139 if (const auto *DNT = T->getAs<DependentNameType>()) {
140 T = resolveDeclsToType(resolveDependentNameType(DNT), Ctx)
141 .getTypePtrOrNull();
142 if (!T)
143 return nullptr;
145 }
146
147 if (const auto *RT = T->getAs<RecordType>())
148 return dyn_cast<CXXRecordDecl>(RT->getDecl());
149
150 if (const auto *ICNT = T->getAs<InjectedClassNameType>())
151 T = ICNT->getInjectedSpecializationType().getTypePtrOrNull();
152 if (!T)
153 return nullptr;
154
155 TemplateName TN = getReferencedTemplateName(T);
156 if (TN.isNull())
157 return nullptr;
158
159 const ClassTemplateDecl *TD =
160 dyn_cast_or_null<ClassTemplateDecl>(TN.getAsTemplateDecl());
161 if (!TD)
162 return nullptr;
163
164 return TD->getTemplatedDecl();
165}
166
167QualType HeuristicResolverImpl::getPointeeType(QualType T) {
168 if (T.isNull())
169 return QualType();
170
171 if (T->isPointerType())
172 return T->castAs<PointerType>()->getPointeeType();
173
174 // Try to handle smart pointer types.
175
176 // Look up operator-> in the primary template. If we find one, it's probably a
177 // smart pointer type.
178 auto ArrowOps = resolveDependentMember(
179 T, Ctx.DeclarationNames.getCXXOperatorName(OO_Arrow), NonStaticFilter);
180 if (ArrowOps.empty())
181 return QualType();
182
183 // Getting the return type of the found operator-> method decl isn't useful,
184 // because we discarded template arguments to perform lookup in the primary
185 // template scope, so the return type would just have the form U* where U is a
186 // template parameter type.
187 // Instead, just handle the common case where the smart pointer type has the
188 // form of SmartPtr<X, ...>, and assume X is the pointee type.
189 auto *TST = T->getAs<TemplateSpecializationType>();
190 if (!TST)
191 return QualType();
192 if (TST->template_arguments().size() == 0)
193 return QualType();
194 const TemplateArgument &FirstArg = TST->template_arguments()[0];
195 if (FirstArg.getKind() != TemplateArgument::Type)
196 return QualType();
197 return FirstArg.getAsType();
198}
199
200std::vector<const NamedDecl *> HeuristicResolverImpl::resolveMemberExpr(
201 const CXXDependentScopeMemberExpr *ME) {
202 // If the expression has a qualifier, try resolving the member inside the
203 // qualifier's type.
204 // Note that we cannot use a NonStaticFilter in either case, for a couple
205 // of reasons:
206 // 1. It's valid to access a static member using instance member syntax,
207 // e.g. `instance.static_member`.
208 // 2. We can sometimes get a CXXDependentScopeMemberExpr for static
209 // member syntax too, e.g. if `X::static_member` occurs inside
210 // an instance method, it's represented as a CXXDependentScopeMemberExpr
211 // with `this` as the base expression as `X` as the qualifier
212 // (which could be valid if `X` names a base class after instantiation).
213 if (NestedNameSpecifier *NNS = ME->getQualifier()) {
214 if (QualType QualifierType = resolveNestedNameSpecifierToType(NNS);
215 !QualifierType.isNull()) {
216 auto Decls =
217 resolveDependentMember(QualifierType, ME->getMember(), NoFilter);
218 if (!Decls.empty())
219 return Decls;
220 }
221
222 // Do not proceed to try resolving the member in the expression's base type
223 // without regard to the qualifier, as that could produce incorrect results.
224 // For example, `void foo() { this->Base::foo(); }` shouldn't resolve to
225 // foo() itself!
226 return {};
227 }
228
229 // Try resolving the member inside the expression's base type.
230 QualType BaseType = ME->getBaseType();
231 if (ME->isArrow()) {
232 BaseType = getPointeeType(BaseType);
233 }
234 if (BaseType.isNull())
235 return {};
236 if (const auto *BT = BaseType->getAs<BuiltinType>()) {
237 // If BaseType is the type of a dependent expression, it's just
238 // represented as BuiltinType::Dependent which gives us no information. We
239 // can get further by analyzing the dependent expression.
240 Expr *Base = ME->isImplicitAccess() ? nullptr : ME->getBase();
241 if (Base && BT->getKind() == BuiltinType::Dependent) {
242 BaseType = resolveExprToType(Base);
243 }
244 }
245 return resolveDependentMember(BaseType, ME->getMember(), NoFilter);
246}
247
248std::vector<const NamedDecl *>
249HeuristicResolverImpl::resolveDeclRefExpr(const DependentScopeDeclRefExpr *RE) {
250 return resolveDependentMember(QualType(RE->getQualifier()->getAsType(), 0),
251 RE->getDeclName(), StaticFilter);
252}
253
254std::vector<const NamedDecl *>
255HeuristicResolverImpl::resolveTypeOfCallExpr(const CallExpr *CE) {
256 QualType CalleeType = resolveExprToType(CE->getCallee());
257 if (CalleeType.isNull())
258 return {};
259 if (const auto *FnTypePtr = CalleeType->getAs<PointerType>())
260 CalleeType = FnTypePtr->getPointeeType();
261 if (const FunctionType *FnType = CalleeType->getAs<FunctionType>()) {
262 if (const auto *D =
263 resolveTypeToRecordDecl(FnType->getReturnType().getTypePtr())) {
264 return {D};
265 }
266 }
267 return {};
268}
269
270std::vector<const NamedDecl *>
271HeuristicResolverImpl::resolveCalleeOfCallExpr(const CallExpr *CE) {
272 if (const auto *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
273 return {ND};
274 }
275
276 return resolveExprToDecls(CE->getCallee());
277}
278
279std::vector<const NamedDecl *> HeuristicResolverImpl::resolveUsingValueDecl(
280 const UnresolvedUsingValueDecl *UUVD) {
281 return resolveDependentMember(QualType(UUVD->getQualifier()->getAsType(), 0),
282 UUVD->getNameInfo().getName(), ValueFilter);
283}
284
285std::vector<const NamedDecl *>
286HeuristicResolverImpl::resolveDependentNameType(const DependentNameType *DNT) {
287 if (auto [_, inserted] = SeenDependentNameTypes.insert(DNT); !inserted)
288 return {};
289 return resolveDependentMember(
290 resolveNestedNameSpecifierToType(DNT->getQualifier()),
291 DNT->getIdentifier(), TypeFilter);
292}
293
294std::vector<const NamedDecl *>
295HeuristicResolverImpl::resolveTemplateSpecializationType(
296 const DependentTemplateSpecializationType *DTST) {
297 return resolveDependentMember(
298 resolveNestedNameSpecifierToType(DTST->getQualifier()),
299 DTST->getIdentifier(), TemplateFilter);
300}
301
302std::vector<const NamedDecl *>
303HeuristicResolverImpl::resolveExprToDecls(const Expr *E) {
304 if (const auto *ME = dyn_cast<CXXDependentScopeMemberExpr>(E)) {
305 return resolveMemberExpr(ME);
306 }
307 if (const auto *RE = dyn_cast<DependentScopeDeclRefExpr>(E)) {
308 return resolveDeclRefExpr(RE);
309 }
310 if (const auto *OE = dyn_cast<OverloadExpr>(E)) {
311 return {OE->decls_begin(), OE->decls_end()};
312 }
313 if (const auto *CE = dyn_cast<CallExpr>(E)) {
314 return resolveTypeOfCallExpr(CE);
315 }
316 if (const auto *ME = dyn_cast<MemberExpr>(E))
317 return {ME->getMemberDecl()};
318
319 return {};
320}
321
322QualType HeuristicResolverImpl::resolveExprToType(const Expr *E) {
323 std::vector<const NamedDecl *> Decls = resolveExprToDecls(E);
324 if (!Decls.empty())
325 return resolveDeclsToType(Decls, Ctx);
326
327 return E->getType();
328}
329
330QualType HeuristicResolverImpl::resolveNestedNameSpecifierToType(
331 const NestedNameSpecifier *NNS) {
332 if (!NNS)
333 return QualType();
334
335 // The purpose of this function is to handle the dependent (Kind ==
336 // Identifier) case, but we need to recurse on the prefix because
337 // that may be dependent as well, so for convenience handle
338 // the TypeSpec cases too.
339 switch (NNS->getKind()) {
342 return QualType(NNS->getAsType(), 0);
344 return resolveDeclsToType(
345 resolveDependentMember(
346 resolveNestedNameSpecifierToType(NNS->getPrefix()),
347 NNS->getAsIdentifier(), TypeFilter),
348 Ctx);
349 }
350 default:
351 break;
352 }
353 return QualType();
354}
355
356bool isOrdinaryMember(const NamedDecl *ND) {
357 return ND->isInIdentifierNamespace(Decl::IDNS_Ordinary | Decl::IDNS_Tag |
359}
360
361bool findOrdinaryMember(const CXXRecordDecl *RD, CXXBasePath &Path,
362 DeclarationName Name) {
363 Path.Decls = RD->lookup(Name).begin();
364 for (DeclContext::lookup_iterator I = Path.Decls, E = I.end(); I != E; ++I)
365 if (isOrdinaryMember(*I))
366 return true;
367
368 return false;
369}
370
371bool HeuristicResolverImpl::findOrdinaryMemberInDependentClasses(
372 const CXXBaseSpecifier *Specifier, CXXBasePath &Path,
373 DeclarationName Name) {
374 CXXRecordDecl *RD =
375 resolveTypeToRecordDecl(Specifier->getType().getTypePtr());
376 if (!RD)
377 return false;
378 return findOrdinaryMember(RD, Path, Name);
379}
380
381std::vector<const NamedDecl *> HeuristicResolverImpl::lookupDependentName(
382 CXXRecordDecl *RD, DeclarationName Name,
383 llvm::function_ref<bool(const NamedDecl *ND)> Filter) {
384 std::vector<const NamedDecl *> Results;
385
386 // Lookup in the class.
387 bool AnyOrdinaryMembers = false;
388 for (const NamedDecl *ND : RD->lookup(Name)) {
389 if (isOrdinaryMember(ND))
390 AnyOrdinaryMembers = true;
391 if (Filter(ND))
392 Results.push_back(ND);
393 }
394 if (AnyOrdinaryMembers)
395 return Results;
396
397 // Perform lookup into our base classes.
398 CXXBasePaths Paths;
399 Paths.setOrigin(RD);
400 if (!RD->lookupInBases(
401 [&](const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
402 return findOrdinaryMemberInDependentClasses(Specifier, Path, Name);
403 },
404 Paths, /*LookupInDependent=*/true))
405 return Results;
406 for (DeclContext::lookup_iterator I = Paths.front().Decls, E = I.end();
407 I != E; ++I) {
408 if (isOrdinaryMember(*I) && Filter(*I))
409 Results.push_back(*I);
410 }
411 return Results;
412}
413
414std::vector<const NamedDecl *> HeuristicResolverImpl::resolveDependentMember(
415 QualType QT, DeclarationName Name,
416 llvm::function_ref<bool(const NamedDecl *ND)> Filter) {
417 const Type *T = QT.getTypePtrOrNull();
418 if (!T)
419 return {};
420 if (auto *ET = T->getAs<EnumType>()) {
421 auto Result = ET->getDecl()->lookup(Name);
422 return {Result.begin(), Result.end()};
423 }
424 if (auto *RD = resolveTypeToRecordDecl(T)) {
425 if (!RD->hasDefinition())
426 return {};
427 RD = RD->getDefinition();
428 return lookupDependentName(RD, Name, [&](const NamedDecl *ND) {
429 if (!Filter(ND))
430 return false;
431 if (const auto *MD = dyn_cast<CXXMethodDecl>(ND)) {
432 return MD->getMethodQualifiers().compatiblyIncludes(QT.getQualifiers(),
433 Ctx);
434 }
435 return true;
436 });
437 }
438 return {};
439}
440} // namespace
441
442std::vector<const NamedDecl *> HeuristicResolver::resolveMemberExpr(
443 const CXXDependentScopeMemberExpr *ME) const {
444 return HeuristicResolverImpl(Ctx).resolveMemberExpr(ME);
445}
446std::vector<const NamedDecl *> HeuristicResolver::resolveDeclRefExpr(
447 const DependentScopeDeclRefExpr *RE) const {
448 return HeuristicResolverImpl(Ctx).resolveDeclRefExpr(RE);
449}
450std::vector<const NamedDecl *>
452 return HeuristicResolverImpl(Ctx).resolveTypeOfCallExpr(CE);
453}
454std::vector<const NamedDecl *>
456 return HeuristicResolverImpl(Ctx).resolveCalleeOfCallExpr(CE);
457}
458std::vector<const NamedDecl *> HeuristicResolver::resolveUsingValueDecl(
459 const UnresolvedUsingValueDecl *UUVD) const {
460 return HeuristicResolverImpl(Ctx).resolveUsingValueDecl(UUVD);
461}
462std::vector<const NamedDecl *> HeuristicResolver::resolveDependentNameType(
463 const DependentNameType *DNT) const {
464 return HeuristicResolverImpl(Ctx).resolveDependentNameType(DNT);
465}
466std::vector<const NamedDecl *>
468 const DependentTemplateSpecializationType *DTST) const {
469 return HeuristicResolverImpl(Ctx).resolveTemplateSpecializationType(DTST);
470}
472 const NestedNameSpecifier *NNS) const {
473 return HeuristicResolverImpl(Ctx).resolveNestedNameSpecifierToType(NNS);
474}
476 return HeuristicResolverImpl(Ctx).getPointeeType(T);
477}
478
479} // namespace clang
Defines the clang::ASTContext interface.
MatchType Type
static bool findOrdinaryMemberInDependentClasses(const CXXBaseSpecifier *Specifier, CXXBasePath &Path, DeclarationName Name)
static bool isOrdinaryMember(const NamedDecl *ND)
static bool findOrdinaryMember(const CXXRecordDecl *RD, CXXBasePath &Path, DeclarationName Name)
const Decl * D
IndirectLocalPath & Path
Expr * E
Defines the C++ template declaration subclasses.
Defines the clang::Expr interface and subclasses for C++ expressions.
static QualType getPointeeType(const MemRegion *R)
C Language Family Type Representation.
const NestedNameSpecifier * Specifier
DeclarationNameTable DeclarationNames
Definition: ASTContext.h:684
QualType getTypeDeclType(const TypeDecl *Decl, const TypeDecl *PrevDecl=nullptr) const
Return the unique reference to the type for the specified type declaration.
Definition: ASTContext.h:1703
Represents a C++ member access expression where the actual member referenced could not be resolved be...
Definition: ExprCXX.h:3683
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition: Expr.h:2874
lookup_result::iterator lookup_iterator
Definition: DeclBase.h:2569
@ IDNS_Ordinary
Ordinary names.
Definition: DeclBase.h:144
@ IDNS_Member
Members, declared with object declarations within tag definitions.
Definition: DeclBase.h:136
@ IDNS_Tag
Tags, declared with 'struct foo;' and referenced with 'struct foo'.
Definition: DeclBase.h:125
DeclarationName getCXXOperatorName(OverloadedOperatorKind Op)
Get the name of the overloadable C++ operator corresponding to Op.
Represents a qualified type name for which the type name is dependent.
Definition: Type.h:7029
A qualified reference to a name whose declaration cannot yet be resolved.
Definition: ExprCXX.h:3323
Represents a template specialization type whose template cannot be resolved, e.g.
Definition: Type.h:7081
QualType getType() const
Definition: Expr.h:142
std::vector< const NamedDecl * > resolveDeclRefExpr(const DependentScopeDeclRefExpr *RE) const
const QualType getPointeeType(QualType T) const
std::vector< const NamedDecl * > resolveMemberExpr(const CXXDependentScopeMemberExpr *ME) const
QualType resolveNestedNameSpecifierToType(const NestedNameSpecifier *NNS) const
std::vector< const NamedDecl * > resolveCalleeOfCallExpr(const CallExpr *CE) const
std::vector< const NamedDecl * > resolveTypeOfCallExpr(const CallExpr *CE) const
std::vector< const NamedDecl * > resolveUsingValueDecl(const UnresolvedUsingValueDecl *UUVD) const
std::vector< const NamedDecl * > resolveTemplateSpecializationType(const DependentTemplateSpecializationType *DTST) const
std::vector< const NamedDecl * > resolveDependentNameType(const DependentNameType *DNT) const
Represents a C++ nested name specifier, such as "\::std::vector<int>::".
@ TypeSpec
A type, stored as a Type*.
@ TypeSpecWithTemplate
A type that was preceded by the 'template' keyword, stored as a Type*.
@ Identifier
An identifier, stored as an IdentifierInfo*.
A (possibly-)qualified type.
Definition: Type.h:929
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition: Type.h:7936
@ Type
The template argument is a type.
Definition: TemplateBase.h:70
bool isPointerType() const
Definition: Type.h:8191
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:8805
QualType getCanonicalTypeInternal() const
Definition: Type.h:2989
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:8736
Represents a dependent using declaration which was not marked with typename.
Definition: DeclCXX.h:3885
llvm::cl::opt< std::string > Filter
The JSON file list parser is used to communicate input to InstallAPI.
@ Result
The result type of a method or function.
const FunctionProtoType * T