1 | //===--------------------- SemaLookup.cpp - Name Lookup ------------------===// |
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 | // This file implements name lookup for C, C++, Objective-C, and |
10 | // Objective-C++. |
11 | // |
12 | //===----------------------------------------------------------------------===// |
13 | |
14 | #include "clang/AST/ASTContext.h" |
15 | #include "clang/AST/CXXInheritance.h" |
16 | #include "clang/AST/Decl.h" |
17 | #include "clang/AST/DeclCXX.h" |
18 | #include "clang/AST/DeclLookups.h" |
19 | #include "clang/AST/DeclObjC.h" |
20 | #include "clang/AST/DeclTemplate.h" |
21 | #include "clang/AST/Expr.h" |
22 | #include "clang/AST/ExprCXX.h" |
23 | #include "clang/Basic/Builtins.h" |
24 | #include "clang/Basic/FileManager.h" |
25 | #include "clang/Basic/LangOptions.h" |
26 | #include "clang/Lex/HeaderSearch.h" |
27 | #include "clang/Lex/ModuleLoader.h" |
28 | #include "clang/Lex/Preprocessor.h" |
29 | #include "clang/Sema/DeclSpec.h" |
30 | #include "clang/Sema/Lookup.h" |
31 | #include "clang/Sema/Overload.h" |
32 | #include "clang/Sema/RISCVIntrinsicManager.h" |
33 | #include "clang/Sema/Scope.h" |
34 | #include "clang/Sema/ScopeInfo.h" |
35 | #include "clang/Sema/Sema.h" |
36 | #include "clang/Sema/SemaInternal.h" |
37 | #include "clang/Sema/TemplateDeduction.h" |
38 | #include "clang/Sema/TypoCorrection.h" |
39 | #include "llvm/ADT/STLExtras.h" |
40 | #include "llvm/ADT/STLForwardCompat.h" |
41 | #include "llvm/ADT/SmallPtrSet.h" |
42 | #include "llvm/ADT/TinyPtrVector.h" |
43 | #include "llvm/ADT/edit_distance.h" |
44 | #include "llvm/Support/Casting.h" |
45 | #include "llvm/Support/ErrorHandling.h" |
46 | #include <algorithm> |
47 | #include <iterator> |
48 | #include <list> |
49 | #include <optional> |
50 | #include <set> |
51 | #include <utility> |
52 | #include <vector> |
53 | |
54 | #include "OpenCLBuiltins.inc" |
55 | |
56 | using namespace clang; |
57 | using namespace sema; |
58 | |
59 | namespace { |
60 | class UnqualUsingEntry { |
61 | const DeclContext *Nominated; |
62 | const DeclContext *CommonAncestor; |
63 | |
64 | public: |
65 | UnqualUsingEntry(const DeclContext *Nominated, |
66 | const DeclContext *CommonAncestor) |
67 | : Nominated(Nominated), CommonAncestor(CommonAncestor) { |
68 | } |
69 | |
70 | const DeclContext *getCommonAncestor() const { |
71 | return CommonAncestor; |
72 | } |
73 | |
74 | const DeclContext *getNominatedNamespace() const { |
75 | return Nominated; |
76 | } |
77 | |
78 | // Sort by the pointer value of the common ancestor. |
79 | struct Comparator { |
80 | bool operator()(const UnqualUsingEntry &L, const UnqualUsingEntry &R) { |
81 | return L.getCommonAncestor() < R.getCommonAncestor(); |
82 | } |
83 | |
84 | bool operator()(const UnqualUsingEntry &E, const DeclContext *DC) { |
85 | return E.getCommonAncestor() < DC; |
86 | } |
87 | |
88 | bool operator()(const DeclContext *DC, const UnqualUsingEntry &E) { |
89 | return DC < E.getCommonAncestor(); |
90 | } |
91 | }; |
92 | }; |
93 | |
94 | /// A collection of using directives, as used by C++ unqualified |
95 | /// lookup. |
96 | class UnqualUsingDirectiveSet { |
97 | Sema &SemaRef; |
98 | |
99 | typedef SmallVector<UnqualUsingEntry, 8> ListTy; |
100 | |
101 | ListTy list; |
102 | llvm::SmallPtrSet<DeclContext*, 8> visited; |
103 | |
104 | public: |
105 | UnqualUsingDirectiveSet(Sema &SemaRef) : SemaRef(SemaRef) {} |
106 | |
107 | void visitScopeChain(Scope *S, Scope *InnermostFileScope) { |
108 | // C++ [namespace.udir]p1: |
109 | // During unqualified name lookup, the names appear as if they |
110 | // were declared in the nearest enclosing namespace which contains |
111 | // both the using-directive and the nominated namespace. |
112 | DeclContext *InnermostFileDC = InnermostFileScope->getEntity(); |
113 | assert(InnermostFileDC && InnermostFileDC->isFileContext()); |
114 | |
115 | for (; S; S = S->getParent()) { |
116 | // C++ [namespace.udir]p1: |
117 | // A using-directive shall not appear in class scope, but may |
118 | // appear in namespace scope or in block scope. |
119 | DeclContext *Ctx = S->getEntity(); |
120 | if (Ctx && Ctx->isFileContext()) { |
121 | visit(DC: Ctx, EffectiveDC: Ctx); |
122 | } else if (!Ctx || Ctx->isFunctionOrMethod()) { |
123 | for (auto *I : S->using_directives()) |
124 | if (SemaRef.isVisible(I)) |
125 | visit(I, InnermostFileDC); |
126 | } |
127 | } |
128 | } |
129 | |
130 | // Visits a context and collect all of its using directives |
131 | // recursively. Treats all using directives as if they were |
132 | // declared in the context. |
133 | // |
134 | // A given context is only every visited once, so it is important |
135 | // that contexts be visited from the inside out in order to get |
136 | // the effective DCs right. |
137 | void visit(DeclContext *DC, DeclContext *EffectiveDC) { |
138 | if (!visited.insert(DC).second) |
139 | return; |
140 | |
141 | addUsingDirectives(DC, EffectiveDC); |
142 | } |
143 | |
144 | // Visits a using directive and collects all of its using |
145 | // directives recursively. Treats all using directives as if they |
146 | // were declared in the effective DC. |
147 | void visit(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) { |
148 | DeclContext *NS = UD->getNominatedNamespace(); |
149 | if (!visited.insert(NS).second) |
150 | return; |
151 | |
152 | addUsingDirective(UD, EffectiveDC); |
153 | addUsingDirectives(DC: NS, EffectiveDC); |
154 | } |
155 | |
156 | // Adds all the using directives in a context (and those nominated |
157 | // by its using directives, transitively) as if they appeared in |
158 | // the given effective context. |
159 | void addUsingDirectives(DeclContext *DC, DeclContext *EffectiveDC) { |
160 | SmallVector<DeclContext*, 4> queue; |
161 | while (true) { |
162 | for (auto *UD : DC->using_directives()) { |
163 | DeclContext *NS = UD->getNominatedNamespace(); |
164 | if (SemaRef.isVisible(UD) && visited.insert(NS).second) { |
165 | addUsingDirective(UD, EffectiveDC); |
166 | queue.push_back(NS); |
167 | } |
168 | } |
169 | |
170 | if (queue.empty()) |
171 | return; |
172 | |
173 | DC = queue.pop_back_val(); |
174 | } |
175 | } |
176 | |
177 | // Add a using directive as if it had been declared in the given |
178 | // context. This helps implement C++ [namespace.udir]p3: |
179 | // The using-directive is transitive: if a scope contains a |
180 | // using-directive that nominates a second namespace that itself |
181 | // contains using-directives, the effect is as if the |
182 | // using-directives from the second namespace also appeared in |
183 | // the first. |
184 | void addUsingDirective(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) { |
185 | // Find the common ancestor between the effective context and |
186 | // the nominated namespace. |
187 | DeclContext *Common = UD->getNominatedNamespace(); |
188 | while (!Common->Encloses(DC: EffectiveDC)) |
189 | Common = Common->getParent(); |
190 | Common = Common->getPrimaryContext(); |
191 | |
192 | list.push_back(UnqualUsingEntry(UD->getNominatedNamespace(), Common)); |
193 | } |
194 | |
195 | void done() { llvm::sort(list, UnqualUsingEntry::Comparator()); } |
196 | |
197 | typedef ListTy::const_iterator const_iterator; |
198 | |
199 | const_iterator begin() const { return list.begin(); } |
200 | const_iterator end() const { return list.end(); } |
201 | |
202 | llvm::iterator_range<const_iterator> |
203 | getNamespacesFor(const DeclContext *DC) const { |
204 | return llvm::make_range(std::equal_range(begin(), end(), |
205 | DC->getPrimaryContext(), |
206 | UnqualUsingEntry::Comparator())); |
207 | } |
208 | }; |
209 | } // end anonymous namespace |
210 | |
211 | // Retrieve the set of identifier namespaces that correspond to a |
212 | // specific kind of name lookup. |
213 | static inline unsigned getIDNS(Sema::LookupNameKind NameKind, |
214 | bool CPlusPlus, |
215 | bool Redeclaration) { |
216 | unsigned IDNS = 0; |
217 | switch (NameKind) { |
218 | case Sema::LookupObjCImplicitSelfParam: |
219 | case Sema::LookupOrdinaryName: |
220 | case Sema::LookupRedeclarationWithLinkage: |
221 | case Sema::LookupLocalFriendName: |
222 | case Sema::LookupDestructorName: |
223 | IDNS = Decl::IDNS_Ordinary; |
224 | if (CPlusPlus) { |
225 | IDNS |= Decl::IDNS_Tag | Decl::IDNS_Member | Decl::IDNS_Namespace; |
226 | if (Redeclaration) |
227 | IDNS |= Decl::IDNS_TagFriend | Decl::IDNS_OrdinaryFriend; |
228 | } |
229 | if (Redeclaration) |
230 | IDNS |= Decl::IDNS_LocalExtern; |
231 | break; |
232 | |
233 | case Sema::LookupOperatorName: |
234 | // Operator lookup is its own crazy thing; it is not the same |
235 | // as (e.g.) looking up an operator name for redeclaration. |
236 | assert(!Redeclaration && "cannot do redeclaration operator lookup" ); |
237 | IDNS = Decl::IDNS_NonMemberOperator; |
238 | break; |
239 | |
240 | case Sema::LookupTagName: |
241 | if (CPlusPlus) { |
242 | IDNS = Decl::IDNS_Type; |
243 | |
244 | // When looking for a redeclaration of a tag name, we add: |
245 | // 1) TagFriend to find undeclared friend decls |
246 | // 2) Namespace because they can't "overload" with tag decls. |
247 | // 3) Tag because it includes class templates, which can't |
248 | // "overload" with tag decls. |
249 | if (Redeclaration) |
250 | IDNS |= Decl::IDNS_Tag | Decl::IDNS_TagFriend | Decl::IDNS_Namespace; |
251 | } else { |
252 | IDNS = Decl::IDNS_Tag; |
253 | } |
254 | break; |
255 | |
256 | case Sema::LookupLabel: |
257 | IDNS = Decl::IDNS_Label; |
258 | break; |
259 | |
260 | case Sema::LookupMemberName: |
261 | IDNS = Decl::IDNS_Member; |
262 | if (CPlusPlus) |
263 | IDNS |= Decl::IDNS_Tag | Decl::IDNS_Ordinary; |
264 | break; |
265 | |
266 | case Sema::LookupNestedNameSpecifierName: |
267 | IDNS = Decl::IDNS_Type | Decl::IDNS_Namespace; |
268 | break; |
269 | |
270 | case Sema::LookupNamespaceName: |
271 | IDNS = Decl::IDNS_Namespace; |
272 | break; |
273 | |
274 | case Sema::LookupUsingDeclName: |
275 | assert(Redeclaration && "should only be used for redecl lookup" ); |
276 | IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Member | |
277 | Decl::IDNS_Using | Decl::IDNS_TagFriend | Decl::IDNS_OrdinaryFriend | |
278 | Decl::IDNS_LocalExtern; |
279 | break; |
280 | |
281 | case Sema::LookupObjCProtocolName: |
282 | IDNS = Decl::IDNS_ObjCProtocol; |
283 | break; |
284 | |
285 | case Sema::LookupOMPReductionName: |
286 | IDNS = Decl::IDNS_OMPReduction; |
287 | break; |
288 | |
289 | case Sema::LookupOMPMapperName: |
290 | IDNS = Decl::IDNS_OMPMapper; |
291 | break; |
292 | |
293 | case Sema::LookupAnyName: |
294 | IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Member |
295 | | Decl::IDNS_Using | Decl::IDNS_Namespace | Decl::IDNS_ObjCProtocol |
296 | | Decl::IDNS_Type; |
297 | break; |
298 | } |
299 | return IDNS; |
300 | } |
301 | |
302 | void LookupResult::configure() { |
303 | IDNS = getIDNS(NameKind: LookupKind, CPlusPlus: getSema().getLangOpts().CPlusPlus, |
304 | Redeclaration: isForRedeclaration()); |
305 | |
306 | // If we're looking for one of the allocation or deallocation |
307 | // operators, make sure that the implicitly-declared new and delete |
308 | // operators can be found. |
309 | switch (NameInfo.getName().getCXXOverloadedOperator()) { |
310 | case OO_New: |
311 | case OO_Delete: |
312 | case OO_Array_New: |
313 | case OO_Array_Delete: |
314 | getSema().DeclareGlobalNewDelete(); |
315 | break; |
316 | |
317 | default: |
318 | break; |
319 | } |
320 | |
321 | // Compiler builtins are always visible, regardless of where they end |
322 | // up being declared. |
323 | if (IdentifierInfo *Id = NameInfo.getName().getAsIdentifierInfo()) { |
324 | if (unsigned BuiltinID = Id->getBuiltinID()) { |
325 | if (!getSema().Context.BuiltinInfo.isPredefinedLibFunction(ID: BuiltinID)) |
326 | AllowHidden = true; |
327 | } |
328 | } |
329 | } |
330 | |
331 | bool LookupResult::checkDebugAssumptions() const { |
332 | // This function is never called by NDEBUG builds. |
333 | assert(ResultKind != NotFound || Decls.size() == 0); |
334 | assert(ResultKind != Found || Decls.size() == 1); |
335 | assert(ResultKind != FoundOverloaded || Decls.size() > 1 || |
336 | (Decls.size() == 1 && |
337 | isa<FunctionTemplateDecl>((*begin())->getUnderlyingDecl()))); |
338 | assert(ResultKind != FoundUnresolvedValue || checkUnresolved()); |
339 | assert(ResultKind != Ambiguous || Decls.size() > 1 || |
340 | (Decls.size() == 1 && (Ambiguity == AmbiguousBaseSubobjects || |
341 | Ambiguity == AmbiguousBaseSubobjectTypes))); |
342 | assert((Paths != nullptr) == (ResultKind == Ambiguous && |
343 | (Ambiguity == AmbiguousBaseSubobjectTypes || |
344 | Ambiguity == AmbiguousBaseSubobjects))); |
345 | return true; |
346 | } |
347 | |
348 | // Necessary because CXXBasePaths is not complete in Sema.h |
349 | void LookupResult::deletePaths(CXXBasePaths *Paths) { |
350 | delete Paths; |
351 | } |
352 | |
353 | /// Get a representative context for a declaration such that two declarations |
354 | /// will have the same context if they were found within the same scope. |
355 | static const DeclContext *getContextForScopeMatching(const Decl *D) { |
356 | // For function-local declarations, use that function as the context. This |
357 | // doesn't account for scopes within the function; the caller must deal with |
358 | // those. |
359 | if (const DeclContext *DC = D->getLexicalDeclContext(); |
360 | DC->isFunctionOrMethod()) |
361 | return DC; |
362 | |
363 | // Otherwise, look at the semantic context of the declaration. The |
364 | // declaration must have been found there. |
365 | return D->getDeclContext()->getRedeclContext(); |
366 | } |
367 | |
368 | /// Determine whether \p D is a better lookup result than \p Existing, |
369 | /// given that they declare the same entity. |
370 | static bool isPreferredLookupResult(Sema &S, Sema::LookupNameKind Kind, |
371 | const NamedDecl *D, |
372 | const NamedDecl *Existing) { |
373 | // When looking up redeclarations of a using declaration, prefer a using |
374 | // shadow declaration over any other declaration of the same entity. |
375 | if (Kind == Sema::LookupUsingDeclName && isa<UsingShadowDecl>(Val: D) && |
376 | !isa<UsingShadowDecl>(Val: Existing)) |
377 | return true; |
378 | |
379 | const auto *DUnderlying = D->getUnderlyingDecl(); |
380 | const auto *EUnderlying = Existing->getUnderlyingDecl(); |
381 | |
382 | // If they have different underlying declarations, prefer a typedef over the |
383 | // original type (this happens when two type declarations denote the same |
384 | // type), per a generous reading of C++ [dcl.typedef]p3 and p4. The typedef |
385 | // might carry additional semantic information, such as an alignment override. |
386 | // However, per C++ [dcl.typedef]p5, when looking up a tag name, prefer a tag |
387 | // declaration over a typedef. Also prefer a tag over a typedef for |
388 | // destructor name lookup because in some contexts we only accept a |
389 | // class-name in a destructor declaration. |
390 | if (DUnderlying->getCanonicalDecl() != EUnderlying->getCanonicalDecl()) { |
391 | assert(isa<TypeDecl>(DUnderlying) && isa<TypeDecl>(EUnderlying)); |
392 | bool HaveTag = isa<TagDecl>(Val: EUnderlying); |
393 | bool WantTag = |
394 | Kind == Sema::LookupTagName || Kind == Sema::LookupDestructorName; |
395 | return HaveTag != WantTag; |
396 | } |
397 | |
398 | // Pick the function with more default arguments. |
399 | // FIXME: In the presence of ambiguous default arguments, we should keep both, |
400 | // so we can diagnose the ambiguity if the default argument is needed. |
401 | // See C++ [over.match.best]p3. |
402 | if (const auto *DFD = dyn_cast<FunctionDecl>(Val: DUnderlying)) { |
403 | const auto *EFD = cast<FunctionDecl>(Val: EUnderlying); |
404 | unsigned DMin = DFD->getMinRequiredArguments(); |
405 | unsigned EMin = EFD->getMinRequiredArguments(); |
406 | // If D has more default arguments, it is preferred. |
407 | if (DMin != EMin) |
408 | return DMin < EMin; |
409 | // FIXME: When we track visibility for default function arguments, check |
410 | // that we pick the declaration with more visible default arguments. |
411 | } |
412 | |
413 | // Pick the template with more default template arguments. |
414 | if (const auto *DTD = dyn_cast<TemplateDecl>(Val: DUnderlying)) { |
415 | const auto *ETD = cast<TemplateDecl>(Val: EUnderlying); |
416 | unsigned DMin = DTD->getTemplateParameters()->getMinRequiredArguments(); |
417 | unsigned EMin = ETD->getTemplateParameters()->getMinRequiredArguments(); |
418 | // If D has more default arguments, it is preferred. Note that default |
419 | // arguments (and their visibility) is monotonically increasing across the |
420 | // redeclaration chain, so this is a quick proxy for "is more recent". |
421 | if (DMin != EMin) |
422 | return DMin < EMin; |
423 | // If D has more *visible* default arguments, it is preferred. Note, an |
424 | // earlier default argument being visible does not imply that a later |
425 | // default argument is visible, so we can't just check the first one. |
426 | for (unsigned I = DMin, N = DTD->getTemplateParameters()->size(); |
427 | I != N; ++I) { |
428 | if (!S.hasVisibleDefaultArgument( |
429 | D: ETD->getTemplateParameters()->getParam(Idx: I)) && |
430 | S.hasVisibleDefaultArgument( |
431 | D: DTD->getTemplateParameters()->getParam(Idx: I))) |
432 | return true; |
433 | } |
434 | } |
435 | |
436 | // VarDecl can have incomplete array types, prefer the one with more complete |
437 | // array type. |
438 | if (const auto *DVD = dyn_cast<VarDecl>(Val: DUnderlying)) { |
439 | const auto *EVD = cast<VarDecl>(Val: EUnderlying); |
440 | if (EVD->getType()->isIncompleteType() && |
441 | !DVD->getType()->isIncompleteType()) { |
442 | // Prefer the decl with a more complete type if visible. |
443 | return S.isVisible(DVD); |
444 | } |
445 | return false; // Avoid picking up a newer decl, just because it was newer. |
446 | } |
447 | |
448 | // For most kinds of declaration, it doesn't really matter which one we pick. |
449 | if (!isa<FunctionDecl>(Val: DUnderlying) && !isa<VarDecl>(Val: DUnderlying)) { |
450 | // If the existing declaration is hidden, prefer the new one. Otherwise, |
451 | // keep what we've got. |
452 | return !S.isVisible(D: Existing); |
453 | } |
454 | |
455 | // Pick the newer declaration; it might have a more precise type. |
456 | for (const Decl *Prev = DUnderlying->getPreviousDecl(); Prev; |
457 | Prev = Prev->getPreviousDecl()) |
458 | if (Prev == EUnderlying) |
459 | return true; |
460 | return false; |
461 | } |
462 | |
463 | /// Determine whether \p D can hide a tag declaration. |
464 | static bool canHideTag(const NamedDecl *D) { |
465 | // C++ [basic.scope.declarative]p4: |
466 | // Given a set of declarations in a single declarative region [...] |
467 | // exactly one declaration shall declare a class name or enumeration name |
468 | // that is not a typedef name and the other declarations shall all refer to |
469 | // the same variable, non-static data member, or enumerator, or all refer |
470 | // to functions and function templates; in this case the class name or |
471 | // enumeration name is hidden. |
472 | // C++ [basic.scope.hiding]p2: |
473 | // A class name or enumeration name can be hidden by the name of a |
474 | // variable, data member, function, or enumerator declared in the same |
475 | // scope. |
476 | // An UnresolvedUsingValueDecl always instantiates to one of these. |
477 | D = D->getUnderlyingDecl(); |
478 | return isa<VarDecl>(Val: D) || isa<EnumConstantDecl>(Val: D) || isa<FunctionDecl>(Val: D) || |
479 | isa<FunctionTemplateDecl>(Val: D) || isa<FieldDecl>(Val: D) || |
480 | isa<UnresolvedUsingValueDecl>(Val: D); |
481 | } |
482 | |
483 | /// Resolves the result kind of this lookup. |
484 | void LookupResult::resolveKind() { |
485 | unsigned N = Decls.size(); |
486 | |
487 | // Fast case: no possible ambiguity. |
488 | if (N == 0) { |
489 | assert(ResultKind == NotFound || |
490 | ResultKind == NotFoundInCurrentInstantiation); |
491 | return; |
492 | } |
493 | |
494 | // If there's a single decl, we need to examine it to decide what |
495 | // kind of lookup this is. |
496 | if (N == 1) { |
497 | const NamedDecl *D = (*Decls.begin())->getUnderlyingDecl(); |
498 | if (isa<FunctionTemplateDecl>(Val: D)) |
499 | ResultKind = FoundOverloaded; |
500 | else if (isa<UnresolvedUsingValueDecl>(Val: D)) |
501 | ResultKind = FoundUnresolvedValue; |
502 | return; |
503 | } |
504 | |
505 | // Don't do any extra resolution if we've already resolved as ambiguous. |
506 | if (ResultKind == Ambiguous) return; |
507 | |
508 | llvm::SmallDenseMap<const NamedDecl *, unsigned, 16> Unique; |
509 | llvm::SmallDenseMap<QualType, unsigned, 16> UniqueTypes; |
510 | |
511 | bool Ambiguous = false; |
512 | bool ReferenceToPlaceHolderVariable = false; |
513 | bool HasTag = false, HasFunction = false; |
514 | bool HasFunctionTemplate = false, HasUnresolved = false; |
515 | const NamedDecl *HasNonFunction = nullptr; |
516 | |
517 | llvm::SmallVector<const NamedDecl *, 4> EquivalentNonFunctions; |
518 | llvm::BitVector RemovedDecls(N); |
519 | |
520 | for (unsigned I = 0; I < N; I++) { |
521 | const NamedDecl *D = Decls[I]->getUnderlyingDecl(); |
522 | D = cast<NamedDecl>(D->getCanonicalDecl()); |
523 | |
524 | // Ignore an invalid declaration unless it's the only one left. |
525 | // Also ignore HLSLBufferDecl which not have name conflict with other Decls. |
526 | if ((D->isInvalidDecl() || isa<HLSLBufferDecl>(Val: D)) && |
527 | N - RemovedDecls.count() > 1) { |
528 | RemovedDecls.set(I); |
529 | continue; |
530 | } |
531 | |
532 | // C++ [basic.scope.hiding]p2: |
533 | // A class name or enumeration name can be hidden by the name of |
534 | // an object, function, or enumerator declared in the same |
535 | // scope. If a class or enumeration name and an object, function, |
536 | // or enumerator are declared in the same scope (in any order) |
537 | // with the same name, the class or enumeration name is hidden |
538 | // wherever the object, function, or enumerator name is visible. |
539 | if (HideTags && isa<TagDecl>(Val: D)) { |
540 | bool Hidden = false; |
541 | for (auto *OtherDecl : Decls) { |
542 | if (canHideTag(D: OtherDecl) && !OtherDecl->isInvalidDecl() && |
543 | getContextForScopeMatching(OtherDecl)->Equals( |
544 | DC: getContextForScopeMatching(Decls[I]))) { |
545 | RemovedDecls.set(I); |
546 | Hidden = true; |
547 | break; |
548 | } |
549 | } |
550 | if (Hidden) |
551 | continue; |
552 | } |
553 | |
554 | std::optional<unsigned> ExistingI; |
555 | |
556 | // Redeclarations of types via typedef can occur both within a scope |
557 | // and, through using declarations and directives, across scopes. There is |
558 | // no ambiguity if they all refer to the same type, so unique based on the |
559 | // canonical type. |
560 | if (const auto *TD = dyn_cast<TypeDecl>(Val: D)) { |
561 | QualType T = getSema().Context.getTypeDeclType(Decl: TD); |
562 | auto UniqueResult = UniqueTypes.insert( |
563 | std::make_pair(x: getSema().Context.getCanonicalType(T), y&: I)); |
564 | if (!UniqueResult.second) { |
565 | // The type is not unique. |
566 | ExistingI = UniqueResult.first->second; |
567 | } |
568 | } |
569 | |
570 | // For non-type declarations, check for a prior lookup result naming this |
571 | // canonical declaration. |
572 | if (!D->isPlaceholderVar(LangOpts: getSema().getLangOpts()) && !ExistingI) { |
573 | auto UniqueResult = Unique.insert(KV: std::make_pair(x&: D, y&: I)); |
574 | if (!UniqueResult.second) { |
575 | // We've seen this entity before. |
576 | ExistingI = UniqueResult.first->second; |
577 | } |
578 | } |
579 | |
580 | if (ExistingI) { |
581 | // This is not a unique lookup result. Pick one of the results and |
582 | // discard the other. |
583 | if (isPreferredLookupResult(S&: getSema(), Kind: getLookupKind(), D: Decls[I], |
584 | Existing: Decls[*ExistingI])) |
585 | Decls[*ExistingI] = Decls[I]; |
586 | RemovedDecls.set(I); |
587 | continue; |
588 | } |
589 | |
590 | // Otherwise, do some decl type analysis and then continue. |
591 | |
592 | if (isa<UnresolvedUsingValueDecl>(Val: D)) { |
593 | HasUnresolved = true; |
594 | } else if (isa<TagDecl>(Val: D)) { |
595 | if (HasTag) |
596 | Ambiguous = true; |
597 | HasTag = true; |
598 | } else if (isa<FunctionTemplateDecl>(Val: D)) { |
599 | HasFunction = true; |
600 | HasFunctionTemplate = true; |
601 | } else if (isa<FunctionDecl>(Val: D)) { |
602 | HasFunction = true; |
603 | } else { |
604 | if (HasNonFunction) { |
605 | // If we're about to create an ambiguity between two declarations that |
606 | // are equivalent, but one is an internal linkage declaration from one |
607 | // module and the other is an internal linkage declaration from another |
608 | // module, just skip it. |
609 | if (getSema().isEquivalentInternalLinkageDeclaration(A: HasNonFunction, |
610 | B: D)) { |
611 | EquivalentNonFunctions.push_back(Elt: D); |
612 | RemovedDecls.set(I); |
613 | continue; |
614 | } |
615 | if (D->isPlaceholderVar(LangOpts: getSema().getLangOpts()) && |
616 | getContextForScopeMatching(D) == |
617 | getContextForScopeMatching(Decls[I])) { |
618 | ReferenceToPlaceHolderVariable = true; |
619 | } |
620 | Ambiguous = true; |
621 | } |
622 | HasNonFunction = D; |
623 | } |
624 | } |
625 | |
626 | // FIXME: This diagnostic should really be delayed until we're done with |
627 | // the lookup result, in case the ambiguity is resolved by the caller. |
628 | if (!EquivalentNonFunctions.empty() && !Ambiguous) |
629 | getSema().diagnoseEquivalentInternalLinkageDeclarations( |
630 | Loc: getNameLoc(), D: HasNonFunction, Equiv: EquivalentNonFunctions); |
631 | |
632 | // Remove decls by replacing them with decls from the end (which |
633 | // means that we need to iterate from the end) and then truncating |
634 | // to the new size. |
635 | for (int I = RemovedDecls.find_last(); I >= 0; I = RemovedDecls.find_prev(PriorTo: I)) |
636 | Decls[I] = Decls[--N]; |
637 | Decls.truncate(N); |
638 | |
639 | if ((HasNonFunction && (HasFunction || HasUnresolved)) || |
640 | (HideTags && HasTag && (HasFunction || HasNonFunction || HasUnresolved))) |
641 | Ambiguous = true; |
642 | |
643 | if (Ambiguous && ReferenceToPlaceHolderVariable) |
644 | setAmbiguous(LookupResult::AmbiguousReferenceToPlaceholderVariable); |
645 | else if (Ambiguous) |
646 | setAmbiguous(LookupResult::AmbiguousReference); |
647 | else if (HasUnresolved) |
648 | ResultKind = LookupResult::FoundUnresolvedValue; |
649 | else if (N > 1 || HasFunctionTemplate) |
650 | ResultKind = LookupResult::FoundOverloaded; |
651 | else |
652 | ResultKind = LookupResult::Found; |
653 | } |
654 | |
655 | void LookupResult::addDeclsFromBasePaths(const CXXBasePaths &P) { |
656 | CXXBasePaths::const_paths_iterator I, E; |
657 | for (I = P.begin(), E = P.end(); I != E; ++I) |
658 | for (DeclContext::lookup_iterator DI = I->Decls, DE = DI.end(); DI != DE; |
659 | ++DI) |
660 | addDecl(D: *DI); |
661 | } |
662 | |
663 | void LookupResult::setAmbiguousBaseSubobjects(CXXBasePaths &P) { |
664 | Paths = new CXXBasePaths; |
665 | Paths->swap(Other&: P); |
666 | addDeclsFromBasePaths(P: *Paths); |
667 | resolveKind(); |
668 | setAmbiguous(AmbiguousBaseSubobjects); |
669 | } |
670 | |
671 | void LookupResult::setAmbiguousBaseSubobjectTypes(CXXBasePaths &P) { |
672 | Paths = new CXXBasePaths; |
673 | Paths->swap(Other&: P); |
674 | addDeclsFromBasePaths(P: *Paths); |
675 | resolveKind(); |
676 | setAmbiguous(AmbiguousBaseSubobjectTypes); |
677 | } |
678 | |
679 | void LookupResult::print(raw_ostream &Out) { |
680 | Out << Decls.size() << " result(s)" ; |
681 | if (isAmbiguous()) Out << ", ambiguous" ; |
682 | if (Paths) Out << ", base paths present" ; |
683 | |
684 | for (iterator I = begin(), E = end(); I != E; ++I) { |
685 | Out << "\n" ; |
686 | (*I)->print(Out, 2); |
687 | } |
688 | } |
689 | |
690 | LLVM_DUMP_METHOD void LookupResult::dump() { |
691 | llvm::errs() << "lookup results for " << getLookupName().getAsString() |
692 | << ":\n" ; |
693 | for (NamedDecl *D : *this) |
694 | D->dump(); |
695 | } |
696 | |
697 | /// Diagnose a missing builtin type. |
698 | static QualType diagOpenCLBuiltinTypeError(Sema &S, llvm::StringRef TypeClass, |
699 | llvm::StringRef Name) { |
700 | S.Diag(SourceLocation(), diag::err_opencl_type_not_found) |
701 | << TypeClass << Name; |
702 | return S.Context.VoidTy; |
703 | } |
704 | |
705 | /// Lookup an OpenCL enum type. |
706 | static QualType getOpenCLEnumType(Sema &S, llvm::StringRef Name) { |
707 | LookupResult Result(S, &S.Context.Idents.get(Name), SourceLocation(), |
708 | Sema::LookupTagName); |
709 | S.LookupName(R&: Result, S: S.TUScope); |
710 | if (Result.empty()) |
711 | return diagOpenCLBuiltinTypeError(S, TypeClass: "enum" , Name); |
712 | EnumDecl *Decl = Result.getAsSingle<EnumDecl>(); |
713 | if (!Decl) |
714 | return diagOpenCLBuiltinTypeError(S, TypeClass: "enum" , Name); |
715 | return S.Context.getEnumType(Decl); |
716 | } |
717 | |
718 | /// Lookup an OpenCL typedef type. |
719 | static QualType getOpenCLTypedefType(Sema &S, llvm::StringRef Name) { |
720 | LookupResult Result(S, &S.Context.Idents.get(Name), SourceLocation(), |
721 | Sema::LookupOrdinaryName); |
722 | S.LookupName(R&: Result, S: S.TUScope); |
723 | if (Result.empty()) |
724 | return diagOpenCLBuiltinTypeError(S, TypeClass: "typedef" , Name); |
725 | TypedefNameDecl *Decl = Result.getAsSingle<TypedefNameDecl>(); |
726 | if (!Decl) |
727 | return diagOpenCLBuiltinTypeError(S, TypeClass: "typedef" , Name); |
728 | return S.Context.getTypedefType(Decl); |
729 | } |
730 | |
731 | /// Get the QualType instances of the return type and arguments for an OpenCL |
732 | /// builtin function signature. |
733 | /// \param S (in) The Sema instance. |
734 | /// \param OpenCLBuiltin (in) The signature currently handled. |
735 | /// \param GenTypeMaxCnt (out) Maximum number of types contained in a generic |
736 | /// type used as return type or as argument. |
737 | /// Only meaningful for generic types, otherwise equals 1. |
738 | /// \param RetTypes (out) List of the possible return types. |
739 | /// \param ArgTypes (out) List of the possible argument types. For each |
740 | /// argument, ArgTypes contains QualTypes for the Cartesian product |
741 | /// of (vector sizes) x (types) . |
742 | static void GetQualTypesForOpenCLBuiltin( |
743 | Sema &S, const OpenCLBuiltinStruct &OpenCLBuiltin, unsigned &GenTypeMaxCnt, |
744 | SmallVector<QualType, 1> &RetTypes, |
745 | SmallVector<SmallVector<QualType, 1>, 5> &ArgTypes) { |
746 | // Get the QualType instances of the return types. |
747 | unsigned Sig = SignatureTable[OpenCLBuiltin.SigTableIndex]; |
748 | OCL2Qual(S, TypeTable[Sig], RetTypes); |
749 | GenTypeMaxCnt = RetTypes.size(); |
750 | |
751 | // Get the QualType instances of the arguments. |
752 | // First type is the return type, skip it. |
753 | for (unsigned Index = 1; Index < OpenCLBuiltin.NumTypes; Index++) { |
754 | SmallVector<QualType, 1> Ty; |
755 | OCL2Qual(S, TypeTable[SignatureTable[OpenCLBuiltin.SigTableIndex + Index]], |
756 | Ty); |
757 | GenTypeMaxCnt = (Ty.size() > GenTypeMaxCnt) ? Ty.size() : GenTypeMaxCnt; |
758 | ArgTypes.push_back(Elt: std::move(Ty)); |
759 | } |
760 | } |
761 | |
762 | /// Create a list of the candidate function overloads for an OpenCL builtin |
763 | /// function. |
764 | /// \param Context (in) The ASTContext instance. |
765 | /// \param GenTypeMaxCnt (in) Maximum number of types contained in a generic |
766 | /// type used as return type or as argument. |
767 | /// Only meaningful for generic types, otherwise equals 1. |
768 | /// \param FunctionList (out) List of FunctionTypes. |
769 | /// \param RetTypes (in) List of the possible return types. |
770 | /// \param ArgTypes (in) List of the possible types for the arguments. |
771 | static void GetOpenCLBuiltinFctOverloads( |
772 | ASTContext &Context, unsigned GenTypeMaxCnt, |
773 | std::vector<QualType> &FunctionList, SmallVector<QualType, 1> &RetTypes, |
774 | SmallVector<SmallVector<QualType, 1>, 5> &ArgTypes) { |
775 | FunctionProtoType::ExtProtoInfo PI( |
776 | Context.getDefaultCallingConvention(IsVariadic: false, IsCXXMethod: false, IsBuiltin: true)); |
777 | PI.Variadic = false; |
778 | |
779 | // Do not attempt to create any FunctionTypes if there are no return types, |
780 | // which happens when a type belongs to a disabled extension. |
781 | if (RetTypes.size() == 0) |
782 | return; |
783 | |
784 | // Create FunctionTypes for each (gen)type. |
785 | for (unsigned IGenType = 0; IGenType < GenTypeMaxCnt; IGenType++) { |
786 | SmallVector<QualType, 5> ArgList; |
787 | |
788 | for (unsigned A = 0; A < ArgTypes.size(); A++) { |
789 | // Bail out if there is an argument that has no available types. |
790 | if (ArgTypes[A].size() == 0) |
791 | return; |
792 | |
793 | // Builtins such as "max" have an "sgentype" argument that represents |
794 | // the corresponding scalar type of a gentype. The number of gentypes |
795 | // must be a multiple of the number of sgentypes. |
796 | assert(GenTypeMaxCnt % ArgTypes[A].size() == 0 && |
797 | "argument type count not compatible with gentype type count" ); |
798 | unsigned Idx = IGenType % ArgTypes[A].size(); |
799 | ArgList.push_back(Elt: ArgTypes[A][Idx]); |
800 | } |
801 | |
802 | FunctionList.push_back(x: Context.getFunctionType( |
803 | ResultTy: RetTypes[(RetTypes.size() != 1) ? IGenType : 0], Args: ArgList, EPI: PI)); |
804 | } |
805 | } |
806 | |
807 | /// When trying to resolve a function name, if isOpenCLBuiltin() returns a |
808 | /// non-null <Index, Len> pair, then the name is referencing an OpenCL |
809 | /// builtin function. Add all candidate signatures to the LookUpResult. |
810 | /// |
811 | /// \param S (in) The Sema instance. |
812 | /// \param LR (inout) The LookupResult instance. |
813 | /// \param II (in) The identifier being resolved. |
814 | /// \param FctIndex (in) Starting index in the BuiltinTable. |
815 | /// \param Len (in) The signature list has Len elements. |
816 | static void InsertOCLBuiltinDeclarationsFromTable(Sema &S, LookupResult &LR, |
817 | IdentifierInfo *II, |
818 | const unsigned FctIndex, |
819 | const unsigned Len) { |
820 | // The builtin function declaration uses generic types (gentype). |
821 | bool HasGenType = false; |
822 | |
823 | // Maximum number of types contained in a generic type used as return type or |
824 | // as argument. Only meaningful for generic types, otherwise equals 1. |
825 | unsigned GenTypeMaxCnt; |
826 | |
827 | ASTContext &Context = S.Context; |
828 | |
829 | for (unsigned SignatureIndex = 0; SignatureIndex < Len; SignatureIndex++) { |
830 | const OpenCLBuiltinStruct &OpenCLBuiltin = |
831 | BuiltinTable[FctIndex + SignatureIndex]; |
832 | |
833 | // Ignore this builtin function if it is not available in the currently |
834 | // selected language version. |
835 | if (!isOpenCLVersionContainedInMask(Context.getLangOpts(), |
836 | OpenCLBuiltin.Versions)) |
837 | continue; |
838 | |
839 | // Ignore this builtin function if it carries an extension macro that is |
840 | // not defined. This indicates that the extension is not supported by the |
841 | // target, so the builtin function should not be available. |
842 | StringRef Extensions = FunctionExtensionTable[OpenCLBuiltin.Extension]; |
843 | if (!Extensions.empty()) { |
844 | SmallVector<StringRef, 2> ExtVec; |
845 | Extensions.split(A&: ExtVec, Separator: " " ); |
846 | bool AllExtensionsDefined = true; |
847 | for (StringRef Ext : ExtVec) { |
848 | if (!S.getPreprocessor().isMacroDefined(Id: Ext)) { |
849 | AllExtensionsDefined = false; |
850 | break; |
851 | } |
852 | } |
853 | if (!AllExtensionsDefined) |
854 | continue; |
855 | } |
856 | |
857 | SmallVector<QualType, 1> RetTypes; |
858 | SmallVector<SmallVector<QualType, 1>, 5> ArgTypes; |
859 | |
860 | // Obtain QualType lists for the function signature. |
861 | GetQualTypesForOpenCLBuiltin(S, OpenCLBuiltin, GenTypeMaxCnt, RetTypes, |
862 | ArgTypes); |
863 | if (GenTypeMaxCnt > 1) { |
864 | HasGenType = true; |
865 | } |
866 | |
867 | // Create function overload for each type combination. |
868 | std::vector<QualType> FunctionList; |
869 | GetOpenCLBuiltinFctOverloads(Context, GenTypeMaxCnt, FunctionList, RetTypes, |
870 | ArgTypes); |
871 | |
872 | SourceLocation Loc = LR.getNameLoc(); |
873 | DeclContext *Parent = Context.getTranslationUnitDecl(); |
874 | FunctionDecl *NewOpenCLBuiltin; |
875 | |
876 | for (const auto &FTy : FunctionList) { |
877 | NewOpenCLBuiltin = FunctionDecl::Create( |
878 | C&: Context, DC: Parent, StartLoc: Loc, NLoc: Loc, N: II, T: FTy, /*TInfo=*/nullptr, SC: SC_Extern, |
879 | UsesFPIntrin: S.getCurFPFeatures().isFPConstrained(), isInlineSpecified: false, |
880 | hasWrittenPrototype: FTy->isFunctionProtoType()); |
881 | NewOpenCLBuiltin->setImplicit(); |
882 | |
883 | // Create Decl objects for each parameter, adding them to the |
884 | // FunctionDecl. |
885 | const auto *FP = cast<FunctionProtoType>(Val: FTy); |
886 | SmallVector<ParmVarDecl *, 4> ParmList; |
887 | for (unsigned IParm = 0, e = FP->getNumParams(); IParm != e; ++IParm) { |
888 | ParmVarDecl *Parm = ParmVarDecl::Create( |
889 | Context, NewOpenCLBuiltin, SourceLocation(), SourceLocation(), |
890 | nullptr, FP->getParamType(i: IParm), nullptr, SC_None, nullptr); |
891 | Parm->setScopeInfo(scopeDepth: 0, parameterIndex: IParm); |
892 | ParmList.push_back(Elt: Parm); |
893 | } |
894 | NewOpenCLBuiltin->setParams(ParmList); |
895 | |
896 | // Add function attributes. |
897 | if (OpenCLBuiltin.IsPure) |
898 | NewOpenCLBuiltin->addAttr(PureAttr::CreateImplicit(Context)); |
899 | if (OpenCLBuiltin.IsConst) |
900 | NewOpenCLBuiltin->addAttr(ConstAttr::CreateImplicit(Context)); |
901 | if (OpenCLBuiltin.IsConv) |
902 | NewOpenCLBuiltin->addAttr(ConvergentAttr::CreateImplicit(Context)); |
903 | |
904 | if (!S.getLangOpts().OpenCLCPlusPlus) |
905 | NewOpenCLBuiltin->addAttr(OverloadableAttr::CreateImplicit(Context)); |
906 | |
907 | LR.addDecl(NewOpenCLBuiltin); |
908 | } |
909 | } |
910 | |
911 | // If we added overloads, need to resolve the lookup result. |
912 | if (Len > 1 || HasGenType) |
913 | LR.resolveKind(); |
914 | } |
915 | |
916 | /// Lookup a builtin function, when name lookup would otherwise |
917 | /// fail. |
918 | bool Sema::LookupBuiltin(LookupResult &R) { |
919 | Sema::LookupNameKind NameKind = R.getLookupKind(); |
920 | |
921 | // If we didn't find a use of this identifier, and if the identifier |
922 | // corresponds to a compiler builtin, create the decl object for the builtin |
923 | // now, injecting it into translation unit scope, and return it. |
924 | if (NameKind == Sema::LookupOrdinaryName || |
925 | NameKind == Sema::LookupRedeclarationWithLinkage) { |
926 | IdentifierInfo *II = R.getLookupName().getAsIdentifierInfo(); |
927 | if (II) { |
928 | if (getLangOpts().CPlusPlus && NameKind == Sema::LookupOrdinaryName) { |
929 | if (II == getASTContext().getMakeIntegerSeqName()) { |
930 | R.addDecl(getASTContext().getMakeIntegerSeqDecl()); |
931 | return true; |
932 | } else if (II == getASTContext().getTypePackElementName()) { |
933 | R.addDecl(getASTContext().getTypePackElementDecl()); |
934 | return true; |
935 | } |
936 | } |
937 | |
938 | // Check if this is an OpenCL Builtin, and if so, insert its overloads. |
939 | if (getLangOpts().OpenCL && getLangOpts().DeclareOpenCLBuiltins) { |
940 | auto Index = isOpenCLBuiltin(II->getName()); |
941 | if (Index.first) { |
942 | InsertOCLBuiltinDeclarationsFromTable(*this, R, II, Index.first - 1, |
943 | Index.second); |
944 | return true; |
945 | } |
946 | } |
947 | |
948 | if (DeclareRISCVVBuiltins || DeclareRISCVSiFiveVectorBuiltins) { |
949 | if (!RVIntrinsicManager) |
950 | RVIntrinsicManager = CreateRISCVIntrinsicManager(S&: *this); |
951 | |
952 | RVIntrinsicManager->InitIntrinsicList(); |
953 | |
954 | if (RVIntrinsicManager->CreateIntrinsicIfFound(LR&: R, II, PP)) |
955 | return true; |
956 | } |
957 | |
958 | // If this is a builtin on this (or all) targets, create the decl. |
959 | if (unsigned BuiltinID = II->getBuiltinID()) { |
960 | // In C++ and OpenCL (spec v1.2 s6.9.f), we don't have any predefined |
961 | // library functions like 'malloc'. Instead, we'll just error. |
962 | if ((getLangOpts().CPlusPlus || getLangOpts().OpenCL) && |
963 | Context.BuiltinInfo.isPredefinedLibFunction(ID: BuiltinID)) |
964 | return false; |
965 | |
966 | if (NamedDecl *D = |
967 | LazilyCreateBuiltin(II, ID: BuiltinID, S: TUScope, |
968 | ForRedeclaration: R.isForRedeclaration(), Loc: R.getNameLoc())) { |
969 | R.addDecl(D); |
970 | return true; |
971 | } |
972 | } |
973 | } |
974 | } |
975 | |
976 | return false; |
977 | } |
978 | |
979 | /// Looks up the declaration of "struct objc_super" and |
980 | /// saves it for later use in building builtin declaration of |
981 | /// objc_msgSendSuper and objc_msgSendSuper_stret. |
982 | static void LookupPredefedObjCSuperType(Sema &Sema, Scope *S) { |
983 | ASTContext &Context = Sema.Context; |
984 | LookupResult Result(Sema, &Context.Idents.get(Name: "objc_super" ), SourceLocation(), |
985 | Sema::LookupTagName); |
986 | Sema.LookupName(R&: Result, S); |
987 | if (Result.getResultKind() == LookupResult::Found) |
988 | if (const TagDecl *TD = Result.getAsSingle<TagDecl>()) |
989 | Context.setObjCSuperType(Context.getTagDeclType(Decl: TD)); |
990 | } |
991 | |
992 | void Sema::LookupNecessaryTypesForBuiltin(Scope *S, unsigned ID) { |
993 | if (ID == Builtin::BIobjc_msgSendSuper) |
994 | LookupPredefedObjCSuperType(Sema&: *this, S); |
995 | } |
996 | |
997 | /// Determine whether we can declare a special member function within |
998 | /// the class at this point. |
999 | static bool CanDeclareSpecialMemberFunction(const CXXRecordDecl *Class) { |
1000 | // We need to have a definition for the class. |
1001 | if (!Class->getDefinition() || Class->isDependentContext()) |
1002 | return false; |
1003 | |
1004 | // We can't be in the middle of defining the class. |
1005 | return !Class->isBeingDefined(); |
1006 | } |
1007 | |
1008 | void Sema::ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class) { |
1009 | if (!CanDeclareSpecialMemberFunction(Class)) |
1010 | return; |
1011 | |
1012 | // If the default constructor has not yet been declared, do so now. |
1013 | if (Class->needsImplicitDefaultConstructor()) |
1014 | DeclareImplicitDefaultConstructor(ClassDecl: Class); |
1015 | |
1016 | // If the copy constructor has not yet been declared, do so now. |
1017 | if (Class->needsImplicitCopyConstructor()) |
1018 | DeclareImplicitCopyConstructor(ClassDecl: Class); |
1019 | |
1020 | // If the copy assignment operator has not yet been declared, do so now. |
1021 | if (Class->needsImplicitCopyAssignment()) |
1022 | DeclareImplicitCopyAssignment(ClassDecl: Class); |
1023 | |
1024 | if (getLangOpts().CPlusPlus11) { |
1025 | // If the move constructor has not yet been declared, do so now. |
1026 | if (Class->needsImplicitMoveConstructor()) |
1027 | DeclareImplicitMoveConstructor(ClassDecl: Class); |
1028 | |
1029 | // If the move assignment operator has not yet been declared, do so now. |
1030 | if (Class->needsImplicitMoveAssignment()) |
1031 | DeclareImplicitMoveAssignment(ClassDecl: Class); |
1032 | } |
1033 | |
1034 | // If the destructor has not yet been declared, do so now. |
1035 | if (Class->needsImplicitDestructor()) |
1036 | DeclareImplicitDestructor(ClassDecl: Class); |
1037 | } |
1038 | |
1039 | /// Determine whether this is the name of an implicitly-declared |
1040 | /// special member function. |
1041 | static bool isImplicitlyDeclaredMemberFunctionName(DeclarationName Name) { |
1042 | switch (Name.getNameKind()) { |
1043 | case DeclarationName::CXXConstructorName: |
1044 | case DeclarationName::CXXDestructorName: |
1045 | return true; |
1046 | |
1047 | case DeclarationName::CXXOperatorName: |
1048 | return Name.getCXXOverloadedOperator() == OO_Equal; |
1049 | |
1050 | default: |
1051 | break; |
1052 | } |
1053 | |
1054 | return false; |
1055 | } |
1056 | |
1057 | /// If there are any implicit member functions with the given name |
1058 | /// that need to be declared in the given declaration context, do so. |
1059 | static void DeclareImplicitMemberFunctionsWithName(Sema &S, |
1060 | DeclarationName Name, |
1061 | SourceLocation Loc, |
1062 | const DeclContext *DC) { |
1063 | if (!DC) |
1064 | return; |
1065 | |
1066 | switch (Name.getNameKind()) { |
1067 | case DeclarationName::CXXConstructorName: |
1068 | if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Val: DC)) |
1069 | if (Record->getDefinition() && CanDeclareSpecialMemberFunction(Class: Record)) { |
1070 | CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(Record); |
1071 | if (Record->needsImplicitDefaultConstructor()) |
1072 | S.DeclareImplicitDefaultConstructor(ClassDecl: Class); |
1073 | if (Record->needsImplicitCopyConstructor()) |
1074 | S.DeclareImplicitCopyConstructor(ClassDecl: Class); |
1075 | if (S.getLangOpts().CPlusPlus11 && |
1076 | Record->needsImplicitMoveConstructor()) |
1077 | S.DeclareImplicitMoveConstructor(ClassDecl: Class); |
1078 | } |
1079 | break; |
1080 | |
1081 | case DeclarationName::CXXDestructorName: |
1082 | if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Val: DC)) |
1083 | if (Record->getDefinition() && Record->needsImplicitDestructor() && |
1084 | CanDeclareSpecialMemberFunction(Class: Record)) |
1085 | S.DeclareImplicitDestructor(ClassDecl: const_cast<CXXRecordDecl *>(Record)); |
1086 | break; |
1087 | |
1088 | case DeclarationName::CXXOperatorName: |
1089 | if (Name.getCXXOverloadedOperator() != OO_Equal) |
1090 | break; |
1091 | |
1092 | if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Val: DC)) { |
1093 | if (Record->getDefinition() && CanDeclareSpecialMemberFunction(Class: Record)) { |
1094 | CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(Record); |
1095 | if (Record->needsImplicitCopyAssignment()) |
1096 | S.DeclareImplicitCopyAssignment(ClassDecl: Class); |
1097 | if (S.getLangOpts().CPlusPlus11 && |
1098 | Record->needsImplicitMoveAssignment()) |
1099 | S.DeclareImplicitMoveAssignment(ClassDecl: Class); |
1100 | } |
1101 | } |
1102 | break; |
1103 | |
1104 | case DeclarationName::CXXDeductionGuideName: |
1105 | S.DeclareImplicitDeductionGuides(Template: Name.getCXXDeductionGuideTemplate(), Loc); |
1106 | break; |
1107 | |
1108 | default: |
1109 | break; |
1110 | } |
1111 | } |
1112 | |
1113 | // Adds all qualifying matches for a name within a decl context to the |
1114 | // given lookup result. Returns true if any matches were found. |
1115 | static bool LookupDirect(Sema &S, LookupResult &R, const DeclContext *DC) { |
1116 | bool Found = false; |
1117 | |
1118 | // Lazily declare C++ special member functions. |
1119 | if (S.getLangOpts().CPlusPlus) |
1120 | DeclareImplicitMemberFunctionsWithName(S, Name: R.getLookupName(), Loc: R.getNameLoc(), |
1121 | DC); |
1122 | |
1123 | // Perform lookup into this declaration context. |
1124 | DeclContext::lookup_result DR = DC->lookup(Name: R.getLookupName()); |
1125 | for (NamedDecl *D : DR) { |
1126 | if ((D = R.getAcceptableDecl(D))) { |
1127 | R.addDecl(D); |
1128 | Found = true; |
1129 | } |
1130 | } |
1131 | |
1132 | if (!Found && DC->isTranslationUnit() && S.LookupBuiltin(R)) |
1133 | return true; |
1134 | |
1135 | if (R.getLookupName().getNameKind() |
1136 | != DeclarationName::CXXConversionFunctionName || |
1137 | R.getLookupName().getCXXNameType()->isDependentType() || |
1138 | !isa<CXXRecordDecl>(Val: DC)) |
1139 | return Found; |
1140 | |
1141 | // C++ [temp.mem]p6: |
1142 | // A specialization of a conversion function template is not found by |
1143 | // name lookup. Instead, any conversion function templates visible in the |
1144 | // context of the use are considered. [...] |
1145 | const CXXRecordDecl *Record = cast<CXXRecordDecl>(Val: DC); |
1146 | if (!Record->isCompleteDefinition()) |
1147 | return Found; |
1148 | |
1149 | // For conversion operators, 'operator auto' should only match |
1150 | // 'operator auto'. Since 'auto' is not a type, it shouldn't be considered |
1151 | // as a candidate for template substitution. |
1152 | auto *ContainedDeducedType = |
1153 | R.getLookupName().getCXXNameType()->getContainedDeducedType(); |
1154 | if (R.getLookupName().getNameKind() == |
1155 | DeclarationName::CXXConversionFunctionName && |
1156 | ContainedDeducedType && ContainedDeducedType->isUndeducedType()) |
1157 | return Found; |
1158 | |
1159 | for (CXXRecordDecl::conversion_iterator U = Record->conversion_begin(), |
1160 | UEnd = Record->conversion_end(); U != UEnd; ++U) { |
1161 | FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(Val: *U); |
1162 | if (!ConvTemplate) |
1163 | continue; |
1164 | |
1165 | // When we're performing lookup for the purposes of redeclaration, just |
1166 | // add the conversion function template. When we deduce template |
1167 | // arguments for specializations, we'll end up unifying the return |
1168 | // type of the new declaration with the type of the function template. |
1169 | if (R.isForRedeclaration()) { |
1170 | R.addDecl(ConvTemplate); |
1171 | Found = true; |
1172 | continue; |
1173 | } |
1174 | |
1175 | // C++ [temp.mem]p6: |
1176 | // [...] For each such operator, if argument deduction succeeds |
1177 | // (14.9.2.3), the resulting specialization is used as if found by |
1178 | // name lookup. |
1179 | // |
1180 | // When referencing a conversion function for any purpose other than |
1181 | // a redeclaration (such that we'll be building an expression with the |
1182 | // result), perform template argument deduction and place the |
1183 | // specialization into the result set. We do this to avoid forcing all |
1184 | // callers to perform special deduction for conversion functions. |
1185 | TemplateDeductionInfo Info(R.getNameLoc()); |
1186 | FunctionDecl *Specialization = nullptr; |
1187 | |
1188 | const FunctionProtoType *ConvProto |
1189 | = ConvTemplate->getTemplatedDecl()->getType()->getAs<FunctionProtoType>(); |
1190 | assert(ConvProto && "Nonsensical conversion function template type" ); |
1191 | |
1192 | // Compute the type of the function that we would expect the conversion |
1193 | // function to have, if it were to match the name given. |
1194 | // FIXME: Calling convention! |
1195 | FunctionProtoType::ExtProtoInfo EPI = ConvProto->getExtProtoInfo(); |
1196 | EPI.ExtInfo = EPI.ExtInfo.withCallingConv(cc: CC_C); |
1197 | EPI.ExceptionSpec = EST_None; |
1198 | QualType ExpectedType = R.getSema().Context.getFunctionType( |
1199 | ResultTy: R.getLookupName().getCXXNameType(), Args: std::nullopt, EPI); |
1200 | |
1201 | // Perform template argument deduction against the type that we would |
1202 | // expect the function to have. |
1203 | if (R.getSema().DeduceTemplateArguments(FunctionTemplate: ConvTemplate, ExplicitTemplateArgs: nullptr, ArgFunctionType: ExpectedType, |
1204 | Specialization, Info) == |
1205 | TemplateDeductionResult::Success) { |
1206 | R.addDecl(Specialization); |
1207 | Found = true; |
1208 | } |
1209 | } |
1210 | |
1211 | return Found; |
1212 | } |
1213 | |
1214 | // Performs C++ unqualified lookup into the given file context. |
1215 | static bool CppNamespaceLookup(Sema &S, LookupResult &R, ASTContext &Context, |
1216 | const DeclContext *NS, |
1217 | UnqualUsingDirectiveSet &UDirs) { |
1218 | |
1219 | assert(NS && NS->isFileContext() && "CppNamespaceLookup() requires namespace!" ); |
1220 | |
1221 | // Perform direct name lookup into the LookupCtx. |
1222 | bool Found = LookupDirect(S, R, DC: NS); |
1223 | |
1224 | // Perform direct name lookup into the namespaces nominated by the |
1225 | // using directives whose common ancestor is this namespace. |
1226 | for (const UnqualUsingEntry &UUE : UDirs.getNamespacesFor(NS)) |
1227 | if (LookupDirect(S, R, UUE.getNominatedNamespace())) |
1228 | Found = true; |
1229 | |
1230 | R.resolveKind(); |
1231 | |
1232 | return Found; |
1233 | } |
1234 | |
1235 | static bool isNamespaceOrTranslationUnitScope(Scope *S) { |
1236 | if (DeclContext *Ctx = S->getEntity()) |
1237 | return Ctx->isFileContext(); |
1238 | return false; |
1239 | } |
1240 | |
1241 | /// Find the outer declaration context from this scope. This indicates the |
1242 | /// context that we should search up to (exclusive) before considering the |
1243 | /// parent of the specified scope. |
1244 | static DeclContext *findOuterContext(Scope *S) { |
1245 | for (Scope *OuterS = S->getParent(); OuterS; OuterS = OuterS->getParent()) |
1246 | if (DeclContext *DC = OuterS->getLookupEntity()) |
1247 | return DC; |
1248 | return nullptr; |
1249 | } |
1250 | |
1251 | namespace { |
1252 | /// An RAII object to specify that we want to find block scope extern |
1253 | /// declarations. |
1254 | struct FindLocalExternScope { |
1255 | FindLocalExternScope(LookupResult &R) |
1256 | : R(R), OldFindLocalExtern(R.getIdentifierNamespace() & |
1257 | Decl::IDNS_LocalExtern) { |
1258 | R.setFindLocalExtern(R.getIdentifierNamespace() & |
1259 | (Decl::IDNS_Ordinary | Decl::IDNS_NonMemberOperator)); |
1260 | } |
1261 | void restore() { |
1262 | R.setFindLocalExtern(OldFindLocalExtern); |
1263 | } |
1264 | ~FindLocalExternScope() { |
1265 | restore(); |
1266 | } |
1267 | LookupResult &R; |
1268 | bool OldFindLocalExtern; |
1269 | }; |
1270 | } // end anonymous namespace |
1271 | |
1272 | bool Sema::CppLookupName(LookupResult &R, Scope *S) { |
1273 | assert(getLangOpts().CPlusPlus && "Can perform only C++ lookup" ); |
1274 | |
1275 | DeclarationName Name = R.getLookupName(); |
1276 | Sema::LookupNameKind NameKind = R.getLookupKind(); |
1277 | |
1278 | // If this is the name of an implicitly-declared special member function, |
1279 | // go through the scope stack to implicitly declare |
1280 | if (isImplicitlyDeclaredMemberFunctionName(Name)) { |
1281 | for (Scope *PreS = S; PreS; PreS = PreS->getParent()) |
1282 | if (DeclContext *DC = PreS->getEntity()) |
1283 | DeclareImplicitMemberFunctionsWithName(S&: *this, Name, Loc: R.getNameLoc(), DC); |
1284 | } |
1285 | |
1286 | // Implicitly declare member functions with the name we're looking for, if in |
1287 | // fact we are in a scope where it matters. |
1288 | |
1289 | Scope *Initial = S; |
1290 | IdentifierResolver::iterator |
1291 | I = IdResolver.begin(Name), |
1292 | IEnd = IdResolver.end(); |
1293 | |
1294 | // First we lookup local scope. |
1295 | // We don't consider using-directives, as per 7.3.4.p1 [namespace.udir] |
1296 | // ...During unqualified name lookup (3.4.1), the names appear as if |
1297 | // they were declared in the nearest enclosing namespace which contains |
1298 | // both the using-directive and the nominated namespace. |
1299 | // [Note: in this context, "contains" means "contains directly or |
1300 | // indirectly". |
1301 | // |
1302 | // For example: |
1303 | // namespace A { int i; } |
1304 | // void foo() { |
1305 | // int i; |
1306 | // { |
1307 | // using namespace A; |
1308 | // ++i; // finds local 'i', A::i appears at global scope |
1309 | // } |
1310 | // } |
1311 | // |
1312 | UnqualUsingDirectiveSet UDirs(*this); |
1313 | bool VisitedUsingDirectives = false; |
1314 | bool LeftStartingScope = false; |
1315 | |
1316 | // When performing a scope lookup, we want to find local extern decls. |
1317 | FindLocalExternScope FindLocals(R); |
1318 | |
1319 | for (; S && !isNamespaceOrTranslationUnitScope(S); S = S->getParent()) { |
1320 | bool SearchNamespaceScope = true; |
1321 | // Check whether the IdResolver has anything in this scope. |
1322 | for (; I != IEnd && S->isDeclScope(*I); ++I) { |
1323 | if (NamedDecl *ND = R.getAcceptableDecl(D: *I)) { |
1324 | if (NameKind == LookupRedeclarationWithLinkage && |
1325 | !(*I)->isTemplateParameter()) { |
1326 | // If it's a template parameter, we still find it, so we can diagnose |
1327 | // the invalid redeclaration. |
1328 | |
1329 | // Determine whether this (or a previous) declaration is |
1330 | // out-of-scope. |
1331 | if (!LeftStartingScope && !Initial->isDeclScope(*I)) |
1332 | LeftStartingScope = true; |
1333 | |
1334 | // If we found something outside of our starting scope that |
1335 | // does not have linkage, skip it. |
1336 | if (LeftStartingScope && !((*I)->hasLinkage())) { |
1337 | R.setShadowed(); |
1338 | continue; |
1339 | } |
1340 | } else { |
1341 | // We found something in this scope, we should not look at the |
1342 | // namespace scope |
1343 | SearchNamespaceScope = false; |
1344 | } |
1345 | R.addDecl(D: ND); |
1346 | } |
1347 | } |
1348 | if (!SearchNamespaceScope) { |
1349 | R.resolveKind(); |
1350 | if (S->isClassScope()) |
1351 | if (auto *Record = dyn_cast_if_present<CXXRecordDecl>(Val: S->getEntity())) |
1352 | R.setNamingClass(Record); |
1353 | return true; |
1354 | } |
1355 | |
1356 | if (NameKind == LookupLocalFriendName && !S->isClassScope()) { |
1357 | // C++11 [class.friend]p11: |
1358 | // If a friend declaration appears in a local class and the name |
1359 | // specified is an unqualified name, a prior declaration is |
1360 | // looked up without considering scopes that are outside the |
1361 | // innermost enclosing non-class scope. |
1362 | return false; |
1363 | } |
1364 | |
1365 | if (DeclContext *Ctx = S->getLookupEntity()) { |
1366 | DeclContext *OuterCtx = findOuterContext(S); |
1367 | for (; Ctx && !Ctx->Equals(DC: OuterCtx); Ctx = Ctx->getLookupParent()) { |
1368 | // We do not directly look into transparent contexts, since |
1369 | // those entities will be found in the nearest enclosing |
1370 | // non-transparent context. |
1371 | if (Ctx->isTransparentContext()) |
1372 | continue; |
1373 | |
1374 | // We do not look directly into function or method contexts, |
1375 | // since all of the local variables and parameters of the |
1376 | // function/method are present within the Scope. |
1377 | if (Ctx->isFunctionOrMethod()) { |
1378 | // If we have an Objective-C instance method, look for ivars |
1379 | // in the corresponding interface. |
1380 | if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Val: Ctx)) { |
1381 | if (Method->isInstanceMethod() && Name.getAsIdentifierInfo()) |
1382 | if (ObjCInterfaceDecl *Class = Method->getClassInterface()) { |
1383 | ObjCInterfaceDecl *ClassDeclared; |
1384 | if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable( |
1385 | IVarName: Name.getAsIdentifierInfo(), |
1386 | ClassDeclared)) { |
1387 | if (NamedDecl *ND = R.getAcceptableDecl(Ivar)) { |
1388 | R.addDecl(D: ND); |
1389 | R.resolveKind(); |
1390 | return true; |
1391 | } |
1392 | } |
1393 | } |
1394 | } |
1395 | |
1396 | continue; |
1397 | } |
1398 | |
1399 | // If this is a file context, we need to perform unqualified name |
1400 | // lookup considering using directives. |
1401 | if (Ctx->isFileContext()) { |
1402 | // If we haven't handled using directives yet, do so now. |
1403 | if (!VisitedUsingDirectives) { |
1404 | // Add using directives from this context up to the top level. |
1405 | for (DeclContext *UCtx = Ctx; UCtx; UCtx = UCtx->getParent()) { |
1406 | if (UCtx->isTransparentContext()) |
1407 | continue; |
1408 | |
1409 | UDirs.visit(DC: UCtx, EffectiveDC: UCtx); |
1410 | } |
1411 | |
1412 | // Find the innermost file scope, so we can add using directives |
1413 | // from local scopes. |
1414 | Scope *InnermostFileScope = S; |
1415 | while (InnermostFileScope && |
1416 | !isNamespaceOrTranslationUnitScope(S: InnermostFileScope)) |
1417 | InnermostFileScope = InnermostFileScope->getParent(); |
1418 | UDirs.visitScopeChain(S: Initial, InnermostFileScope); |
1419 | |
1420 | UDirs.done(); |
1421 | |
1422 | VisitedUsingDirectives = true; |
1423 | } |
1424 | |
1425 | if (CppNamespaceLookup(S&: *this, R, Context, NS: Ctx, UDirs)) { |
1426 | R.resolveKind(); |
1427 | return true; |
1428 | } |
1429 | |
1430 | continue; |
1431 | } |
1432 | |
1433 | // Perform qualified name lookup into this context. |
1434 | // FIXME: In some cases, we know that every name that could be found by |
1435 | // this qualified name lookup will also be on the identifier chain. For |
1436 | // example, inside a class without any base classes, we never need to |
1437 | // perform qualified lookup because all of the members are on top of the |
1438 | // identifier chain. |
1439 | if (LookupQualifiedName(R, LookupCtx: Ctx, /*InUnqualifiedLookup=*/true)) |
1440 | return true; |
1441 | } |
1442 | } |
1443 | } |
1444 | |
1445 | // Stop if we ran out of scopes. |
1446 | // FIXME: This really, really shouldn't be happening. |
1447 | if (!S) return false; |
1448 | |
1449 | // If we are looking for members, no need to look into global/namespace scope. |
1450 | if (NameKind == LookupMemberName) |
1451 | return false; |
1452 | |
1453 | // Collect UsingDirectiveDecls in all scopes, and recursively all |
1454 | // nominated namespaces by those using-directives. |
1455 | // |
1456 | // FIXME: Cache this sorted list in Scope structure, and DeclContext, so we |
1457 | // don't build it for each lookup! |
1458 | if (!VisitedUsingDirectives) { |
1459 | UDirs.visitScopeChain(S: Initial, InnermostFileScope: S); |
1460 | UDirs.done(); |
1461 | } |
1462 | |
1463 | // If we're not performing redeclaration lookup, do not look for local |
1464 | // extern declarations outside of a function scope. |
1465 | if (!R.isForRedeclaration()) |
1466 | FindLocals.restore(); |
1467 | |
1468 | // Lookup namespace scope, and global scope. |
1469 | // Unqualified name lookup in C++ requires looking into scopes |
1470 | // that aren't strictly lexical, and therefore we walk through the |
1471 | // context as well as walking through the scopes. |
1472 | for (; S; S = S->getParent()) { |
1473 | // Check whether the IdResolver has anything in this scope. |
1474 | bool Found = false; |
1475 | for (; I != IEnd && S->isDeclScope(*I); ++I) { |
1476 | if (NamedDecl *ND = R.getAcceptableDecl(D: *I)) { |
1477 | // We found something. Look for anything else in our scope |
1478 | // with this same name and in an acceptable identifier |
1479 | // namespace, so that we can construct an overload set if we |
1480 | // need to. |
1481 | Found = true; |
1482 | R.addDecl(D: ND); |
1483 | } |
1484 | } |
1485 | |
1486 | if (Found && S->isTemplateParamScope()) { |
1487 | R.resolveKind(); |
1488 | return true; |
1489 | } |
1490 | |
1491 | DeclContext *Ctx = S->getLookupEntity(); |
1492 | if (Ctx) { |
1493 | DeclContext *OuterCtx = findOuterContext(S); |
1494 | for (; Ctx && !Ctx->Equals(DC: OuterCtx); Ctx = Ctx->getLookupParent()) { |
1495 | // We do not directly look into transparent contexts, since |
1496 | // those entities will be found in the nearest enclosing |
1497 | // non-transparent context. |
1498 | if (Ctx->isTransparentContext()) |
1499 | continue; |
1500 | |
1501 | // If we have a context, and it's not a context stashed in the |
1502 | // template parameter scope for an out-of-line definition, also |
1503 | // look into that context. |
1504 | if (!(Found && S->isTemplateParamScope())) { |
1505 | assert(Ctx->isFileContext() && |
1506 | "We should have been looking only at file context here already." ); |
1507 | |
1508 | // Look into context considering using-directives. |
1509 | if (CppNamespaceLookup(S&: *this, R, Context, NS: Ctx, UDirs)) |
1510 | Found = true; |
1511 | } |
1512 | |
1513 | if (Found) { |
1514 | R.resolveKind(); |
1515 | return true; |
1516 | } |
1517 | |
1518 | if (R.isForRedeclaration() && !Ctx->isTransparentContext()) |
1519 | return false; |
1520 | } |
1521 | } |
1522 | |
1523 | if (R.isForRedeclaration() && Ctx && !Ctx->isTransparentContext()) |
1524 | return false; |
1525 | } |
1526 | |
1527 | return !R.empty(); |
1528 | } |
1529 | |
1530 | void Sema::makeMergedDefinitionVisible(NamedDecl *ND) { |
1531 | if (auto *M = getCurrentModule()) |
1532 | Context.mergeDefinitionIntoModule(ND, M); |
1533 | else |
1534 | // We're not building a module; just make the definition visible. |
1535 | ND->setVisibleDespiteOwningModule(); |
1536 | |
1537 | // If ND is a template declaration, make the template parameters |
1538 | // visible too. They're not (necessarily) within a mergeable DeclContext. |
1539 | if (auto *TD = dyn_cast<TemplateDecl>(Val: ND)) |
1540 | for (auto *Param : *TD->getTemplateParameters()) |
1541 | makeMergedDefinitionVisible(ND: Param); |
1542 | } |
1543 | |
1544 | /// Find the module in which the given declaration was defined. |
1545 | static Module *getDefiningModule(Sema &S, Decl *Entity) { |
1546 | if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: Entity)) { |
1547 | // If this function was instantiated from a template, the defining module is |
1548 | // the module containing the pattern. |
1549 | if (FunctionDecl *Pattern = FD->getTemplateInstantiationPattern()) |
1550 | Entity = Pattern; |
1551 | } else if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Val: Entity)) { |
1552 | if (CXXRecordDecl *Pattern = RD->getTemplateInstantiationPattern()) |
1553 | Entity = Pattern; |
1554 | } else if (EnumDecl *ED = dyn_cast<EnumDecl>(Val: Entity)) { |
1555 | if (auto *Pattern = ED->getTemplateInstantiationPattern()) |
1556 | Entity = Pattern; |
1557 | } else if (VarDecl *VD = dyn_cast<VarDecl>(Val: Entity)) { |
1558 | if (VarDecl *Pattern = VD->getTemplateInstantiationPattern()) |
1559 | Entity = Pattern; |
1560 | } |
1561 | |
1562 | // Walk up to the containing context. That might also have been instantiated |
1563 | // from a template. |
1564 | DeclContext *Context = Entity->getLexicalDeclContext(); |
1565 | if (Context->isFileContext()) |
1566 | return S.getOwningModule(Entity); |
1567 | return getDefiningModule(S, Entity: cast<Decl>(Val: Context)); |
1568 | } |
1569 | |
1570 | llvm::DenseSet<Module*> &Sema::getLookupModules() { |
1571 | unsigned N = CodeSynthesisContexts.size(); |
1572 | for (unsigned I = CodeSynthesisContextLookupModules.size(); |
1573 | I != N; ++I) { |
1574 | Module *M = CodeSynthesisContexts[I].Entity ? |
1575 | getDefiningModule(S&: *this, Entity: CodeSynthesisContexts[I].Entity) : |
1576 | nullptr; |
1577 | if (M && !LookupModulesCache.insert(V: M).second) |
1578 | M = nullptr; |
1579 | CodeSynthesisContextLookupModules.push_back(Elt: M); |
1580 | } |
1581 | return LookupModulesCache; |
1582 | } |
1583 | |
1584 | /// Determine if we could use all the declarations in the module. |
1585 | bool Sema::isUsableModule(const Module *M) { |
1586 | assert(M && "We shouldn't check nullness for module here" ); |
1587 | // Return quickly if we cached the result. |
1588 | if (UsableModuleUnitsCache.count(V: M)) |
1589 | return true; |
1590 | |
1591 | // If M is the global module fragment of the current translation unit. So it |
1592 | // should be usable. |
1593 | // [module.global.frag]p1: |
1594 | // The global module fragment can be used to provide declarations that are |
1595 | // attached to the global module and usable within the module unit. |
1596 | if (M == TheGlobalModuleFragment || M == TheImplicitGlobalModuleFragment || |
1597 | // If M is the module we're parsing, it should be usable. This covers the |
1598 | // private module fragment. The private module fragment is usable only if |
1599 | // it is within the current module unit. And it must be the current |
1600 | // parsing module unit if it is within the current module unit according |
1601 | // to the grammar of the private module fragment. NOTE: This is covered by |
1602 | // the following condition. The intention of the check is to avoid string |
1603 | // comparison as much as possible. |
1604 | M == getCurrentModule() || |
1605 | // The module unit which is in the same module with the current module |
1606 | // unit is usable. |
1607 | // |
1608 | // FIXME: Here we judge if they are in the same module by comparing the |
1609 | // string. Is there any better solution? |
1610 | M->getPrimaryModuleInterfaceName() == |
1611 | llvm::StringRef(getLangOpts().CurrentModule).split(Separator: ':').first) { |
1612 | UsableModuleUnitsCache.insert(V: M); |
1613 | return true; |
1614 | } |
1615 | |
1616 | return false; |
1617 | } |
1618 | |
1619 | bool Sema::hasVisibleMergedDefinition(const NamedDecl *Def) { |
1620 | for (const Module *Merged : Context.getModulesWithMergedDefinition(Def)) |
1621 | if (isModuleVisible(M: Merged)) |
1622 | return true; |
1623 | return false; |
1624 | } |
1625 | |
1626 | bool Sema::hasMergedDefinitionInCurrentModule(const NamedDecl *Def) { |
1627 | for (const Module *Merged : Context.getModulesWithMergedDefinition(Def)) |
1628 | if (isUsableModule(M: Merged)) |
1629 | return true; |
1630 | return false; |
1631 | } |
1632 | |
1633 | template <typename ParmDecl> |
1634 | static bool |
1635 | hasAcceptableDefaultArgument(Sema &S, const ParmDecl *D, |
1636 | llvm::SmallVectorImpl<Module *> *Modules, |
1637 | Sema::AcceptableKind Kind) { |
1638 | if (!D->hasDefaultArgument()) |
1639 | return false; |
1640 | |
1641 | llvm::SmallPtrSet<const ParmDecl *, 4> Visited; |
1642 | while (D && Visited.insert(D).second) { |
1643 | auto &DefaultArg = D->getDefaultArgStorage(); |
1644 | if (!DefaultArg.isInherited() && S.isAcceptable(D, Kind)) |
1645 | return true; |
1646 | |
1647 | if (!DefaultArg.isInherited() && Modules) { |
1648 | auto *NonConstD = const_cast<ParmDecl*>(D); |
1649 | Modules->push_back(Elt: S.getOwningModule(Entity: NonConstD)); |
1650 | } |
1651 | |
1652 | // If there was a previous default argument, maybe its parameter is |
1653 | // acceptable. |
1654 | D = DefaultArg.getInheritedFrom(); |
1655 | } |
1656 | return false; |
1657 | } |
1658 | |
1659 | bool Sema::hasAcceptableDefaultArgument( |
1660 | const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules, |
1661 | Sema::AcceptableKind Kind) { |
1662 | if (auto *P = dyn_cast<TemplateTypeParmDecl>(Val: D)) |
1663 | return ::hasAcceptableDefaultArgument(S&: *this, D: P, Modules, Kind); |
1664 | |
1665 | if (auto *P = dyn_cast<NonTypeTemplateParmDecl>(Val: D)) |
1666 | return ::hasAcceptableDefaultArgument(S&: *this, D: P, Modules, Kind); |
1667 | |
1668 | return ::hasAcceptableDefaultArgument( |
1669 | S&: *this, D: cast<TemplateTemplateParmDecl>(Val: D), Modules, Kind); |
1670 | } |
1671 | |
1672 | bool Sema::hasVisibleDefaultArgument(const NamedDecl *D, |
1673 | llvm::SmallVectorImpl<Module *> *Modules) { |
1674 | return hasAcceptableDefaultArgument(D, Modules, |
1675 | Kind: Sema::AcceptableKind::Visible); |
1676 | } |
1677 | |
1678 | bool Sema::hasReachableDefaultArgument( |
1679 | const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules) { |
1680 | return hasAcceptableDefaultArgument(D, Modules, |
1681 | Kind: Sema::AcceptableKind::Reachable); |
1682 | } |
1683 | |
1684 | template <typename Filter> |
1685 | static bool |
1686 | hasAcceptableDeclarationImpl(Sema &S, const NamedDecl *D, |
1687 | llvm::SmallVectorImpl<Module *> *Modules, Filter F, |
1688 | Sema::AcceptableKind Kind) { |
1689 | bool HasFilteredRedecls = false; |
1690 | |
1691 | for (auto *Redecl : D->redecls()) { |
1692 | auto *R = cast<NamedDecl>(Redecl); |
1693 | if (!F(R)) |
1694 | continue; |
1695 | |
1696 | if (S.isAcceptable(R, Kind)) |
1697 | return true; |
1698 | |
1699 | HasFilteredRedecls = true; |
1700 | |
1701 | if (Modules) |
1702 | Modules->push_back(R->getOwningModule()); |
1703 | } |
1704 | |
1705 | // Only return false if there is at least one redecl that is not filtered out. |
1706 | if (HasFilteredRedecls) |
1707 | return false; |
1708 | |
1709 | return true; |
1710 | } |
1711 | |
1712 | static bool |
1713 | hasAcceptableExplicitSpecialization(Sema &S, const NamedDecl *D, |
1714 | llvm::SmallVectorImpl<Module *> *Modules, |
1715 | Sema::AcceptableKind Kind) { |
1716 | return hasAcceptableDeclarationImpl( |
1717 | S, D, Modules, |
1718 | F: [](const NamedDecl *D) { |
1719 | if (auto *RD = dyn_cast<CXXRecordDecl>(Val: D)) |
1720 | return RD->getTemplateSpecializationKind() == |
1721 | TSK_ExplicitSpecialization; |
1722 | if (auto *FD = dyn_cast<FunctionDecl>(Val: D)) |
1723 | return FD->getTemplateSpecializationKind() == |
1724 | TSK_ExplicitSpecialization; |
1725 | if (auto *VD = dyn_cast<VarDecl>(Val: D)) |
1726 | return VD->getTemplateSpecializationKind() == |
1727 | TSK_ExplicitSpecialization; |
1728 | llvm_unreachable("unknown explicit specialization kind" ); |
1729 | }, |
1730 | Kind); |
1731 | } |
1732 | |
1733 | bool Sema::hasVisibleExplicitSpecialization( |
1734 | const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules) { |
1735 | return ::hasAcceptableExplicitSpecialization(S&: *this, D, Modules, |
1736 | Kind: Sema::AcceptableKind::Visible); |
1737 | } |
1738 | |
1739 | bool Sema::hasReachableExplicitSpecialization( |
1740 | const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules) { |
1741 | return ::hasAcceptableExplicitSpecialization(S&: *this, D, Modules, |
1742 | Kind: Sema::AcceptableKind::Reachable); |
1743 | } |
1744 | |
1745 | static bool |
1746 | hasAcceptableMemberSpecialization(Sema &S, const NamedDecl *D, |
1747 | llvm::SmallVectorImpl<Module *> *Modules, |
1748 | Sema::AcceptableKind Kind) { |
1749 | assert(isa<CXXRecordDecl>(D->getDeclContext()) && |
1750 | "not a member specialization" ); |
1751 | return hasAcceptableDeclarationImpl( |
1752 | S, D, Modules, |
1753 | F: [](const NamedDecl *D) { |
1754 | // If the specialization is declared at namespace scope, then it's a |
1755 | // member specialization declaration. If it's lexically inside the class |
1756 | // definition then it was instantiated. |
1757 | // |
1758 | // FIXME: This is a hack. There should be a better way to determine |
1759 | // this. |
1760 | // FIXME: What about MS-style explicit specializations declared within a |
1761 | // class definition? |
1762 | return D->getLexicalDeclContext()->isFileContext(); |
1763 | }, |
1764 | Kind); |
1765 | } |
1766 | |
1767 | bool Sema::hasVisibleMemberSpecialization( |
1768 | const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules) { |
1769 | return hasAcceptableMemberSpecialization(S&: *this, D, Modules, |
1770 | Kind: Sema::AcceptableKind::Visible); |
1771 | } |
1772 | |
1773 | bool Sema::hasReachableMemberSpecialization( |
1774 | const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules) { |
1775 | return hasAcceptableMemberSpecialization(S&: *this, D, Modules, |
1776 | Kind: Sema::AcceptableKind::Reachable); |
1777 | } |
1778 | |
1779 | /// Determine whether a declaration is acceptable to name lookup. |
1780 | /// |
1781 | /// This routine determines whether the declaration D is acceptable in the |
1782 | /// current lookup context, taking into account the current template |
1783 | /// instantiation stack. During template instantiation, a declaration is |
1784 | /// acceptable if it is acceptable from a module containing any entity on the |
1785 | /// template instantiation path (by instantiating a template, you allow it to |
1786 | /// see the declarations that your module can see, including those later on in |
1787 | /// your module). |
1788 | bool LookupResult::isAcceptableSlow(Sema &SemaRef, NamedDecl *D, |
1789 | Sema::AcceptableKind Kind) { |
1790 | assert(!D->isUnconditionallyVisible() && |
1791 | "should not call this: not in slow case" ); |
1792 | |
1793 | Module *DeclModule = SemaRef.getOwningModule(D); |
1794 | assert(DeclModule && "hidden decl has no owning module" ); |
1795 | |
1796 | // If the owning module is visible, the decl is acceptable. |
1797 | if (SemaRef.isModuleVisible(M: DeclModule, |
1798 | ModulePrivate: D->isInvisibleOutsideTheOwningModule())) |
1799 | return true; |
1800 | |
1801 | // Determine whether a decl context is a file context for the purpose of |
1802 | // visibility/reachability. This looks through some (export and linkage spec) |
1803 | // transparent contexts, but not others (enums). |
1804 | auto IsEffectivelyFileContext = [](const DeclContext *DC) { |
1805 | return DC->isFileContext() || isa<LinkageSpecDecl>(Val: DC) || |
1806 | isa<ExportDecl>(Val: DC); |
1807 | }; |
1808 | |
1809 | // If this declaration is not at namespace scope |
1810 | // then it is acceptable if its lexical parent has a acceptable definition. |
1811 | DeclContext *DC = D->getLexicalDeclContext(); |
1812 | if (DC && !IsEffectivelyFileContext(DC)) { |
1813 | // For a parameter, check whether our current template declaration's |
1814 | // lexical context is acceptable, not whether there's some other acceptable |
1815 | // definition of it, because parameters aren't "within" the definition. |
1816 | // |
1817 | // In C++ we need to check for a acceptable definition due to ODR merging, |
1818 | // and in C we must not because each declaration of a function gets its own |
1819 | // set of declarations for tags in prototype scope. |
1820 | bool AcceptableWithinParent; |
1821 | if (D->isTemplateParameter()) { |
1822 | bool SearchDefinitions = true; |
1823 | if (const auto *DCD = dyn_cast<Decl>(DC)) { |
1824 | if (const auto *TD = DCD->getDescribedTemplate()) { |
1825 | TemplateParameterList *TPL = TD->getTemplateParameters(); |
1826 | auto Index = getDepthAndIndex(ND: D).second; |
1827 | SearchDefinitions = Index >= TPL->size() || TPL->getParam(Idx: Index) != D; |
1828 | } |
1829 | } |
1830 | if (SearchDefinitions) |
1831 | AcceptableWithinParent = |
1832 | SemaRef.hasAcceptableDefinition(D: cast<NamedDecl>(Val: DC), Kind); |
1833 | else |
1834 | AcceptableWithinParent = |
1835 | isAcceptable(SemaRef, D: cast<NamedDecl>(Val: DC), Kind); |
1836 | } else if (isa<ParmVarDecl>(Val: D) || |
1837 | (isa<FunctionDecl>(Val: DC) && !SemaRef.getLangOpts().CPlusPlus)) |
1838 | AcceptableWithinParent = isAcceptable(SemaRef, D: cast<NamedDecl>(Val: DC), Kind); |
1839 | else if (D->isModulePrivate()) { |
1840 | // A module-private declaration is only acceptable if an enclosing lexical |
1841 | // parent was merged with another definition in the current module. |
1842 | AcceptableWithinParent = false; |
1843 | do { |
1844 | if (SemaRef.hasMergedDefinitionInCurrentModule(Def: cast<NamedDecl>(Val: DC))) { |
1845 | AcceptableWithinParent = true; |
1846 | break; |
1847 | } |
1848 | DC = DC->getLexicalParent(); |
1849 | } while (!IsEffectivelyFileContext(DC)); |
1850 | } else { |
1851 | AcceptableWithinParent = |
1852 | SemaRef.hasAcceptableDefinition(D: cast<NamedDecl>(Val: DC), Kind); |
1853 | } |
1854 | |
1855 | if (AcceptableWithinParent && SemaRef.CodeSynthesisContexts.empty() && |
1856 | Kind == Sema::AcceptableKind::Visible && |
1857 | // FIXME: Do something better in this case. |
1858 | !SemaRef.getLangOpts().ModulesLocalVisibility) { |
1859 | // Cache the fact that this declaration is implicitly visible because |
1860 | // its parent has a visible definition. |
1861 | D->setVisibleDespiteOwningModule(); |
1862 | } |
1863 | return AcceptableWithinParent; |
1864 | } |
1865 | |
1866 | if (Kind == Sema::AcceptableKind::Visible) |
1867 | return false; |
1868 | |
1869 | assert(Kind == Sema::AcceptableKind::Reachable && |
1870 | "Additional Sema::AcceptableKind?" ); |
1871 | return isReachableSlow(SemaRef, D); |
1872 | } |
1873 | |
1874 | bool Sema::isModuleVisible(const Module *M, bool ModulePrivate) { |
1875 | // The module might be ordinarily visible. For a module-private query, that |
1876 | // means it is part of the current module. |
1877 | if (ModulePrivate && isUsableModule(M)) |
1878 | return true; |
1879 | |
1880 | // For a query which is not module-private, that means it is in our visible |
1881 | // module set. |
1882 | if (!ModulePrivate && VisibleModules.isVisible(M)) |
1883 | return true; |
1884 | |
1885 | // Otherwise, it might be visible by virtue of the query being within a |
1886 | // template instantiation or similar that is permitted to look inside M. |
1887 | |
1888 | // Find the extra places where we need to look. |
1889 | const auto &LookupModules = getLookupModules(); |
1890 | if (LookupModules.empty()) |
1891 | return false; |
1892 | |
1893 | // If our lookup set contains the module, it's visible. |
1894 | if (LookupModules.count(V: M)) |
1895 | return true; |
1896 | |
1897 | // The global module fragments are visible to its corresponding module unit. |
1898 | // So the global module fragment should be visible if the its corresponding |
1899 | // module unit is visible. |
1900 | if (M->isGlobalModule() && LookupModules.count(V: M->getTopLevelModule())) |
1901 | return true; |
1902 | |
1903 | // For a module-private query, that's everywhere we get to look. |
1904 | if (ModulePrivate) |
1905 | return false; |
1906 | |
1907 | // Check whether M is transitively exported to an import of the lookup set. |
1908 | return llvm::any_of(Range: LookupModules, P: [&](const Module *LookupM) { |
1909 | return LookupM->isModuleVisible(M); |
1910 | }); |
1911 | } |
1912 | |
1913 | // FIXME: Return false directly if we don't have an interface dependency on the |
1914 | // translation unit containing D. |
1915 | bool LookupResult::isReachableSlow(Sema &SemaRef, NamedDecl *D) { |
1916 | assert(!isVisible(SemaRef, D) && "Shouldn't call the slow case.\n" ); |
1917 | |
1918 | Module *DeclModule = SemaRef.getOwningModule(D); |
1919 | assert(DeclModule && "hidden decl has no owning module" ); |
1920 | |
1921 | // Entities in header like modules are reachable only if they're visible. |
1922 | if (DeclModule->isHeaderLikeModule()) |
1923 | return false; |
1924 | |
1925 | if (!D->isInAnotherModuleUnit()) |
1926 | return true; |
1927 | |
1928 | // [module.reach]/p3: |
1929 | // A declaration D is reachable from a point P if: |
1930 | // ... |
1931 | // - D is not discarded ([module.global.frag]), appears in a translation unit |
1932 | // that is reachable from P, and does not appear within a private module |
1933 | // fragment. |
1934 | // |
1935 | // A declaration that's discarded in the GMF should be module-private. |
1936 | if (D->isModulePrivate()) |
1937 | return false; |
1938 | |
1939 | // [module.reach]/p1 |
1940 | // A translation unit U is necessarily reachable from a point P if U is a |
1941 | // module interface unit on which the translation unit containing P has an |
1942 | // interface dependency, or the translation unit containing P imports U, in |
1943 | // either case prior to P ([module.import]). |
1944 | // |
1945 | // [module.import]/p10 |
1946 | // A translation unit has an interface dependency on a translation unit U if |
1947 | // it contains a declaration (possibly a module-declaration) that imports U |
1948 | // or if it has an interface dependency on a translation unit that has an |
1949 | // interface dependency on U. |
1950 | // |
1951 | // So we could conclude the module unit U is necessarily reachable if: |
1952 | // (1) The module unit U is module interface unit. |
1953 | // (2) The current unit has an interface dependency on the module unit U. |
1954 | // |
1955 | // Here we only check for the first condition. Since we couldn't see |
1956 | // DeclModule if it isn't (transitively) imported. |
1957 | if (DeclModule->getTopLevelModule()->isModuleInterfaceUnit()) |
1958 | return true; |
1959 | |
1960 | // [module.reach]/p2 |
1961 | // Additional translation units on |
1962 | // which the point within the program has an interface dependency may be |
1963 | // considered reachable, but it is unspecified which are and under what |
1964 | // circumstances. |
1965 | // |
1966 | // The decision here is to treat all additional tranditional units as |
1967 | // unreachable. |
1968 | return false; |
1969 | } |
1970 | |
1971 | bool Sema::isAcceptableSlow(const NamedDecl *D, Sema::AcceptableKind Kind) { |
1972 | return LookupResult::isAcceptable(SemaRef&: *this, D: const_cast<NamedDecl *>(D), Kind); |
1973 | } |
1974 | |
1975 | bool Sema::shouldLinkPossiblyHiddenDecl(LookupResult &R, const NamedDecl *New) { |
1976 | // FIXME: If there are both visible and hidden declarations, we need to take |
1977 | // into account whether redeclaration is possible. Example: |
1978 | // |
1979 | // Non-imported module: |
1980 | // int f(T); // #1 |
1981 | // Some TU: |
1982 | // static int f(U); // #2, not a redeclaration of #1 |
1983 | // int f(T); // #3, finds both, should link with #1 if T != U, but |
1984 | // // with #2 if T == U; neither should be ambiguous. |
1985 | for (auto *D : R) { |
1986 | if (isVisible(D)) |
1987 | return true; |
1988 | assert(D->isExternallyDeclarable() && |
1989 | "should not have hidden, non-externally-declarable result here" ); |
1990 | } |
1991 | |
1992 | // This function is called once "New" is essentially complete, but before a |
1993 | // previous declaration is attached. We can't query the linkage of "New" in |
1994 | // general, because attaching the previous declaration can change the |
1995 | // linkage of New to match the previous declaration. |
1996 | // |
1997 | // However, because we've just determined that there is no *visible* prior |
1998 | // declaration, we can compute the linkage here. There are two possibilities: |
1999 | // |
2000 | // * This is not a redeclaration; it's safe to compute the linkage now. |
2001 | // |
2002 | // * This is a redeclaration of a prior declaration that is externally |
2003 | // redeclarable. In that case, the linkage of the declaration is not |
2004 | // changed by attaching the prior declaration, because both are externally |
2005 | // declarable (and thus ExternalLinkage or VisibleNoLinkage). |
2006 | // |
2007 | // FIXME: This is subtle and fragile. |
2008 | return New->isExternallyDeclarable(); |
2009 | } |
2010 | |
2011 | /// Retrieve the visible declaration corresponding to D, if any. |
2012 | /// |
2013 | /// This routine determines whether the declaration D is visible in the current |
2014 | /// module, with the current imports. If not, it checks whether any |
2015 | /// redeclaration of D is visible, and if so, returns that declaration. |
2016 | /// |
2017 | /// \returns D, or a visible previous declaration of D, whichever is more recent |
2018 | /// and visible. If no declaration of D is visible, returns null. |
2019 | static NamedDecl *findAcceptableDecl(Sema &SemaRef, NamedDecl *D, |
2020 | unsigned IDNS) { |
2021 | assert(!LookupResult::isAvailableForLookup(SemaRef, D) && "not in slow case" ); |
2022 | |
2023 | for (auto *RD : D->redecls()) { |
2024 | // Don't bother with extra checks if we already know this one isn't visible. |
2025 | if (RD == D) |
2026 | continue; |
2027 | |
2028 | auto ND = cast<NamedDecl>(RD); |
2029 | // FIXME: This is wrong in the case where the previous declaration is not |
2030 | // visible in the same scope as D. This needs to be done much more |
2031 | // carefully. |
2032 | if (ND->isInIdentifierNamespace(IDNS) && |
2033 | LookupResult::isAvailableForLookup(SemaRef, ND)) |
2034 | return ND; |
2035 | } |
2036 | |
2037 | return nullptr; |
2038 | } |
2039 | |
2040 | bool Sema::hasVisibleDeclarationSlow(const NamedDecl *D, |
2041 | llvm::SmallVectorImpl<Module *> *Modules) { |
2042 | assert(!isVisible(D) && "not in slow case" ); |
2043 | return hasAcceptableDeclarationImpl( |
2044 | S&: *this, D, Modules, F: [](const NamedDecl *) { return true; }, |
2045 | Kind: Sema::AcceptableKind::Visible); |
2046 | } |
2047 | |
2048 | bool Sema::hasReachableDeclarationSlow( |
2049 | const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules) { |
2050 | assert(!isReachable(D) && "not in slow case" ); |
2051 | return hasAcceptableDeclarationImpl( |
2052 | S&: *this, D, Modules, F: [](const NamedDecl *) { return true; }, |
2053 | Kind: Sema::AcceptableKind::Reachable); |
2054 | } |
2055 | |
2056 | NamedDecl *LookupResult::getAcceptableDeclSlow(NamedDecl *D) const { |
2057 | if (auto *ND = dyn_cast<NamespaceDecl>(Val: D)) { |
2058 | // Namespaces are a bit of a special case: we expect there to be a lot of |
2059 | // redeclarations of some namespaces, all declarations of a namespace are |
2060 | // essentially interchangeable, all declarations are found by name lookup |
2061 | // if any is, and namespaces are never looked up during template |
2062 | // instantiation. So we benefit from caching the check in this case, and |
2063 | // it is correct to do so. |
2064 | auto *Key = ND->getCanonicalDecl(); |
2065 | if (auto *Acceptable = getSema().VisibleNamespaceCache.lookup(Key)) |
2066 | return Acceptable; |
2067 | auto *Acceptable = isVisible(getSema(), Key) |
2068 | ? Key |
2069 | : findAcceptableDecl(getSema(), Key, IDNS); |
2070 | if (Acceptable) |
2071 | getSema().VisibleNamespaceCache.insert(std::make_pair(Key, Acceptable)); |
2072 | return Acceptable; |
2073 | } |
2074 | |
2075 | return findAcceptableDecl(SemaRef&: getSema(), D, IDNS); |
2076 | } |
2077 | |
2078 | bool LookupResult::isVisible(Sema &SemaRef, NamedDecl *D) { |
2079 | // If this declaration is already visible, return it directly. |
2080 | if (D->isUnconditionallyVisible()) |
2081 | return true; |
2082 | |
2083 | // During template instantiation, we can refer to hidden declarations, if |
2084 | // they were visible in any module along the path of instantiation. |
2085 | return isAcceptableSlow(SemaRef, D, Kind: Sema::AcceptableKind::Visible); |
2086 | } |
2087 | |
2088 | bool LookupResult::isReachable(Sema &SemaRef, NamedDecl *D) { |
2089 | if (D->isUnconditionallyVisible()) |
2090 | return true; |
2091 | |
2092 | return isAcceptableSlow(SemaRef, D, Kind: Sema::AcceptableKind::Reachable); |
2093 | } |
2094 | |
2095 | bool LookupResult::isAvailableForLookup(Sema &SemaRef, NamedDecl *ND) { |
2096 | // We should check the visibility at the callsite already. |
2097 | if (isVisible(SemaRef, D: ND)) |
2098 | return true; |
2099 | |
2100 | // Deduction guide lives in namespace scope generally, but it is just a |
2101 | // hint to the compilers. What we actually lookup for is the generated member |
2102 | // of the corresponding template. So it is sufficient to check the |
2103 | // reachability of the template decl. |
2104 | if (auto *DeductionGuide = ND->getDeclName().getCXXDeductionGuideTemplate()) |
2105 | return SemaRef.hasReachableDefinition(DeductionGuide); |
2106 | |
2107 | // FIXME: The lookup for allocation function is a standalone process. |
2108 | // (We can find the logics in Sema::FindAllocationFunctions) |
2109 | // |
2110 | // Such structure makes it a problem when we instantiate a template |
2111 | // declaration using placement allocation function if the placement |
2112 | // allocation function is invisible. |
2113 | // (See https://github.com/llvm/llvm-project/issues/59601) |
2114 | // |
2115 | // Here we workaround it by making the placement allocation functions |
2116 | // always acceptable. The downside is that we can't diagnose the direct |
2117 | // use of the invisible placement allocation functions. (Although such uses |
2118 | // should be rare). |
2119 | if (auto *FD = dyn_cast<FunctionDecl>(Val: ND); |
2120 | FD && FD->isReservedGlobalPlacementOperator()) |
2121 | return true; |
2122 | |
2123 | auto *DC = ND->getDeclContext(); |
2124 | // If ND is not visible and it is at namespace scope, it shouldn't be found |
2125 | // by name lookup. |
2126 | if (DC->isFileContext()) |
2127 | return false; |
2128 | |
2129 | // [module.interface]p7 |
2130 | // Class and enumeration member names can be found by name lookup in any |
2131 | // context in which a definition of the type is reachable. |
2132 | // |
2133 | // FIXME: The current implementation didn't consider about scope. For example, |
2134 | // ``` |
2135 | // // m.cppm |
2136 | // export module m; |
2137 | // enum E1 { e1 }; |
2138 | // // Use.cpp |
2139 | // import m; |
2140 | // void test() { |
2141 | // auto a = E1::e1; // Error as expected. |
2142 | // auto b = e1; // Should be error. namespace-scope name e1 is not visible |
2143 | // } |
2144 | // ``` |
2145 | // For the above example, the current implementation would emit error for `a` |
2146 | // correctly. However, the implementation wouldn't diagnose about `b` now. |
2147 | // Since we only check the reachability for the parent only. |
2148 | // See clang/test/CXX/module/module.interface/p7.cpp for example. |
2149 | if (auto *TD = dyn_cast<TagDecl>(DC)) |
2150 | return SemaRef.hasReachableDefinition(TD); |
2151 | |
2152 | return false; |
2153 | } |
2154 | |
2155 | /// Perform unqualified name lookup starting from a given |
2156 | /// scope. |
2157 | /// |
2158 | /// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is |
2159 | /// used to find names within the current scope. For example, 'x' in |
2160 | /// @code |
2161 | /// int x; |
2162 | /// int f() { |
2163 | /// return x; // unqualified name look finds 'x' in the global scope |
2164 | /// } |
2165 | /// @endcode |
2166 | /// |
2167 | /// Different lookup criteria can find different names. For example, a |
2168 | /// particular scope can have both a struct and a function of the same |
2169 | /// name, and each can be found by certain lookup criteria. For more |
2170 | /// information about lookup criteria, see the documentation for the |
2171 | /// class LookupCriteria. |
2172 | /// |
2173 | /// @param S The scope from which unqualified name lookup will |
2174 | /// begin. If the lookup criteria permits, name lookup may also search |
2175 | /// in the parent scopes. |
2176 | /// |
2177 | /// @param [in,out] R Specifies the lookup to perform (e.g., the name to |
2178 | /// look up and the lookup kind), and is updated with the results of lookup |
2179 | /// including zero or more declarations and possibly additional information |
2180 | /// used to diagnose ambiguities. |
2181 | /// |
2182 | /// @returns \c true if lookup succeeded and false otherwise. |
2183 | bool Sema::LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation, |
2184 | bool ForceNoCPlusPlus) { |
2185 | DeclarationName Name = R.getLookupName(); |
2186 | if (!Name) return false; |
2187 | |
2188 | LookupNameKind NameKind = R.getLookupKind(); |
2189 | |
2190 | if (!getLangOpts().CPlusPlus || ForceNoCPlusPlus) { |
2191 | // Unqualified name lookup in C/Objective-C is purely lexical, so |
2192 | // search in the declarations attached to the name. |
2193 | if (NameKind == Sema::LookupRedeclarationWithLinkage) { |
2194 | // Find the nearest non-transparent declaration scope. |
2195 | while (!(S->getFlags() & Scope::DeclScope) || |
2196 | (S->getEntity() && S->getEntity()->isTransparentContext())) |
2197 | S = S->getParent(); |
2198 | } |
2199 | |
2200 | // When performing a scope lookup, we want to find local extern decls. |
2201 | FindLocalExternScope FindLocals(R); |
2202 | |
2203 | // Scan up the scope chain looking for a decl that matches this |
2204 | // identifier that is in the appropriate namespace. This search |
2205 | // should not take long, as shadowing of names is uncommon, and |
2206 | // deep shadowing is extremely uncommon. |
2207 | bool LeftStartingScope = false; |
2208 | |
2209 | for (IdentifierResolver::iterator I = IdResolver.begin(Name), |
2210 | IEnd = IdResolver.end(); |
2211 | I != IEnd; ++I) |
2212 | if (NamedDecl *D = R.getAcceptableDecl(D: *I)) { |
2213 | if (NameKind == LookupRedeclarationWithLinkage) { |
2214 | // Determine whether this (or a previous) declaration is |
2215 | // out-of-scope. |
2216 | if (!LeftStartingScope && !S->isDeclScope(*I)) |
2217 | LeftStartingScope = true; |
2218 | |
2219 | // If we found something outside of our starting scope that |
2220 | // does not have linkage, skip it. |
2221 | if (LeftStartingScope && !((*I)->hasLinkage())) { |
2222 | R.setShadowed(); |
2223 | continue; |
2224 | } |
2225 | } |
2226 | else if (NameKind == LookupObjCImplicitSelfParam && |
2227 | !isa<ImplicitParamDecl>(Val: *I)) |
2228 | continue; |
2229 | |
2230 | R.addDecl(D); |
2231 | |
2232 | // Check whether there are any other declarations with the same name |
2233 | // and in the same scope. |
2234 | if (I != IEnd) { |
2235 | // Find the scope in which this declaration was declared (if it |
2236 | // actually exists in a Scope). |
2237 | while (S && !S->isDeclScope(D)) |
2238 | S = S->getParent(); |
2239 | |
2240 | // If the scope containing the declaration is the translation unit, |
2241 | // then we'll need to perform our checks based on the matching |
2242 | // DeclContexts rather than matching scopes. |
2243 | if (S && isNamespaceOrTranslationUnitScope(S)) |
2244 | S = nullptr; |
2245 | |
2246 | // Compute the DeclContext, if we need it. |
2247 | DeclContext *DC = nullptr; |
2248 | if (!S) |
2249 | DC = (*I)->getDeclContext()->getRedeclContext(); |
2250 | |
2251 | IdentifierResolver::iterator LastI = I; |
2252 | for (++LastI; LastI != IEnd; ++LastI) { |
2253 | if (S) { |
2254 | // Match based on scope. |
2255 | if (!S->isDeclScope(*LastI)) |
2256 | break; |
2257 | } else { |
2258 | // Match based on DeclContext. |
2259 | DeclContext *LastDC |
2260 | = (*LastI)->getDeclContext()->getRedeclContext(); |
2261 | if (!LastDC->Equals(DC)) |
2262 | break; |
2263 | } |
2264 | |
2265 | // If the declaration is in the right namespace and visible, add it. |
2266 | if (NamedDecl *LastD = R.getAcceptableDecl(D: *LastI)) |
2267 | R.addDecl(D: LastD); |
2268 | } |
2269 | |
2270 | R.resolveKind(); |
2271 | } |
2272 | |
2273 | return true; |
2274 | } |
2275 | } else { |
2276 | // Perform C++ unqualified name lookup. |
2277 | if (CppLookupName(R, S)) |
2278 | return true; |
2279 | } |
2280 | |
2281 | // If we didn't find a use of this identifier, and if the identifier |
2282 | // corresponds to a compiler builtin, create the decl object for the builtin |
2283 | // now, injecting it into translation unit scope, and return it. |
2284 | if (AllowBuiltinCreation && LookupBuiltin(R)) |
2285 | return true; |
2286 | |
2287 | // If we didn't find a use of this identifier, the ExternalSource |
2288 | // may be able to handle the situation. |
2289 | // Note: some lookup failures are expected! |
2290 | // See e.g. R.isForRedeclaration(). |
2291 | return (ExternalSource && ExternalSource->LookupUnqualified(R, S)); |
2292 | } |
2293 | |
2294 | /// Perform qualified name lookup in the namespaces nominated by |
2295 | /// using directives by the given context. |
2296 | /// |
2297 | /// C++98 [namespace.qual]p2: |
2298 | /// Given X::m (where X is a user-declared namespace), or given \::m |
2299 | /// (where X is the global namespace), let S be the set of all |
2300 | /// declarations of m in X and in the transitive closure of all |
2301 | /// namespaces nominated by using-directives in X and its used |
2302 | /// namespaces, except that using-directives are ignored in any |
2303 | /// namespace, including X, directly containing one or more |
2304 | /// declarations of m. No namespace is searched more than once in |
2305 | /// the lookup of a name. If S is the empty set, the program is |
2306 | /// ill-formed. Otherwise, if S has exactly one member, or if the |
2307 | /// context of the reference is a using-declaration |
2308 | /// (namespace.udecl), S is the required set of declarations of |
2309 | /// m. Otherwise if the use of m is not one that allows a unique |
2310 | /// declaration to be chosen from S, the program is ill-formed. |
2311 | /// |
2312 | /// C++98 [namespace.qual]p5: |
2313 | /// During the lookup of a qualified namespace member name, if the |
2314 | /// lookup finds more than one declaration of the member, and if one |
2315 | /// declaration introduces a class name or enumeration name and the |
2316 | /// other declarations either introduce the same object, the same |
2317 | /// enumerator or a set of functions, the non-type name hides the |
2318 | /// class or enumeration name if and only if the declarations are |
2319 | /// from the same namespace; otherwise (the declarations are from |
2320 | /// different namespaces), the program is ill-formed. |
2321 | static bool LookupQualifiedNameInUsingDirectives(Sema &S, LookupResult &R, |
2322 | DeclContext *StartDC) { |
2323 | assert(StartDC->isFileContext() && "start context is not a file context" ); |
2324 | |
2325 | // We have not yet looked into these namespaces, much less added |
2326 | // their "using-children" to the queue. |
2327 | SmallVector<NamespaceDecl*, 8> Queue; |
2328 | |
2329 | // We have at least added all these contexts to the queue. |
2330 | llvm::SmallPtrSet<DeclContext*, 8> Visited; |
2331 | Visited.insert(Ptr: StartDC); |
2332 | |
2333 | // We have already looked into the initial namespace; seed the queue |
2334 | // with its using-children. |
2335 | for (auto *I : StartDC->using_directives()) { |
2336 | NamespaceDecl *ND = I->getNominatedNamespace()->getOriginalNamespace(); |
2337 | if (S.isVisible(I) && Visited.insert(ND).second) |
2338 | Queue.push_back(Elt: ND); |
2339 | } |
2340 | |
2341 | // The easiest way to implement the restriction in [namespace.qual]p5 |
2342 | // is to check whether any of the individual results found a tag |
2343 | // and, if so, to declare an ambiguity if the final result is not |
2344 | // a tag. |
2345 | bool FoundTag = false; |
2346 | bool FoundNonTag = false; |
2347 | |
2348 | LookupResult LocalR(LookupResult::Temporary, R); |
2349 | |
2350 | bool Found = false; |
2351 | while (!Queue.empty()) { |
2352 | NamespaceDecl *ND = Queue.pop_back_val(); |
2353 | |
2354 | // We go through some convolutions here to avoid copying results |
2355 | // between LookupResults. |
2356 | bool UseLocal = !R.empty(); |
2357 | LookupResult &DirectR = UseLocal ? LocalR : R; |
2358 | bool FoundDirect = LookupDirect(S, DirectR, ND); |
2359 | |
2360 | if (FoundDirect) { |
2361 | // First do any local hiding. |
2362 | DirectR.resolveKind(); |
2363 | |
2364 | // If the local result is a tag, remember that. |
2365 | if (DirectR.isSingleTagDecl()) |
2366 | FoundTag = true; |
2367 | else |
2368 | FoundNonTag = true; |
2369 | |
2370 | // Append the local results to the total results if necessary. |
2371 | if (UseLocal) { |
2372 | R.addAllDecls(Other: LocalR); |
2373 | LocalR.clear(); |
2374 | } |
2375 | } |
2376 | |
2377 | // If we find names in this namespace, ignore its using directives. |
2378 | if (FoundDirect) { |
2379 | Found = true; |
2380 | continue; |
2381 | } |
2382 | |
2383 | for (auto *I : ND->using_directives()) { |
2384 | NamespaceDecl *Nom = I->getNominatedNamespace(); |
2385 | if (S.isVisible(I) && Visited.insert(Nom).second) |
2386 | Queue.push_back(Nom); |
2387 | } |
2388 | } |
2389 | |
2390 | if (Found) { |
2391 | if (FoundTag && FoundNonTag) |
2392 | R.setAmbiguousQualifiedTagHiding(); |
2393 | else |
2394 | R.resolveKind(); |
2395 | } |
2396 | |
2397 | return Found; |
2398 | } |
2399 | |
2400 | /// Perform qualified name lookup into a given context. |
2401 | /// |
2402 | /// Qualified name lookup (C++ [basic.lookup.qual]) is used to find |
2403 | /// names when the context of those names is explicit specified, e.g., |
2404 | /// "std::vector" or "x->member", or as part of unqualified name lookup. |
2405 | /// |
2406 | /// Different lookup criteria can find different names. For example, a |
2407 | /// particular scope can have both a struct and a function of the same |
2408 | /// name, and each can be found by certain lookup criteria. For more |
2409 | /// information about lookup criteria, see the documentation for the |
2410 | /// class LookupCriteria. |
2411 | /// |
2412 | /// \param R captures both the lookup criteria and any lookup results found. |
2413 | /// |
2414 | /// \param LookupCtx The context in which qualified name lookup will |
2415 | /// search. If the lookup criteria permits, name lookup may also search |
2416 | /// in the parent contexts or (for C++ classes) base classes. |
2417 | /// |
2418 | /// \param InUnqualifiedLookup true if this is qualified name lookup that |
2419 | /// occurs as part of unqualified name lookup. |
2420 | /// |
2421 | /// \returns true if lookup succeeded, false if it failed. |
2422 | bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, |
2423 | bool InUnqualifiedLookup) { |
2424 | assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context" ); |
2425 | |
2426 | if (!R.getLookupName()) |
2427 | return false; |
2428 | |
2429 | // Make sure that the declaration context is complete. |
2430 | assert((!isa<TagDecl>(LookupCtx) || |
2431 | LookupCtx->isDependentContext() || |
2432 | cast<TagDecl>(LookupCtx)->isCompleteDefinition() || |
2433 | cast<TagDecl>(LookupCtx)->isBeingDefined()) && |
2434 | "Declaration context must already be complete!" ); |
2435 | |
2436 | struct QualifiedLookupInScope { |
2437 | bool oldVal; |
2438 | DeclContext *Context; |
2439 | // Set flag in DeclContext informing debugger that we're looking for qualified name |
2440 | QualifiedLookupInScope(DeclContext *ctx) |
2441 | : oldVal(ctx->shouldUseQualifiedLookup()), Context(ctx) { |
2442 | ctx->setUseQualifiedLookup(); |
2443 | } |
2444 | ~QualifiedLookupInScope() { |
2445 | Context->setUseQualifiedLookup(oldVal); |
2446 | } |
2447 | } QL(LookupCtx); |
2448 | |
2449 | if (LookupDirect(S&: *this, R, DC: LookupCtx)) { |
2450 | R.resolveKind(); |
2451 | if (isa<CXXRecordDecl>(Val: LookupCtx)) |
2452 | R.setNamingClass(cast<CXXRecordDecl>(Val: LookupCtx)); |
2453 | return true; |
2454 | } |
2455 | |
2456 | // Don't descend into implied contexts for redeclarations. |
2457 | // C++98 [namespace.qual]p6: |
2458 | // In a declaration for a namespace member in which the |
2459 | // declarator-id is a qualified-id, given that the qualified-id |
2460 | // for the namespace member has the form |
2461 | // nested-name-specifier unqualified-id |
2462 | // the unqualified-id shall name a member of the namespace |
2463 | // designated by the nested-name-specifier. |
2464 | // See also [class.mfct]p5 and [class.static.data]p2. |
2465 | if (R.isForRedeclaration()) |
2466 | return false; |
2467 | |
2468 | // If this is a namespace, look it up in the implied namespaces. |
2469 | if (LookupCtx->isFileContext()) |
2470 | return LookupQualifiedNameInUsingDirectives(S&: *this, R, StartDC: LookupCtx); |
2471 | |
2472 | // If this isn't a C++ class, we aren't allowed to look into base |
2473 | // classes, we're done. |
2474 | CXXRecordDecl *LookupRec = dyn_cast<CXXRecordDecl>(Val: LookupCtx); |
2475 | if (!LookupRec || !LookupRec->getDefinition()) |
2476 | return false; |
2477 | |
2478 | // We're done for lookups that can never succeed for C++ classes. |
2479 | if (R.getLookupKind() == LookupOperatorName || |
2480 | R.getLookupKind() == LookupNamespaceName || |
2481 | R.getLookupKind() == LookupObjCProtocolName || |
2482 | R.getLookupKind() == LookupLabel) |
2483 | return false; |
2484 | |
2485 | // If we're performing qualified name lookup into a dependent class, |
2486 | // then we are actually looking into a current instantiation. If we have any |
2487 | // dependent base classes, then we either have to delay lookup until |
2488 | // template instantiation time (at which point all bases will be available) |
2489 | // or we have to fail. |
2490 | if (!InUnqualifiedLookup && LookupRec->isDependentContext() && |
2491 | LookupRec->hasAnyDependentBases()) { |
2492 | R.setNotFoundInCurrentInstantiation(); |
2493 | return false; |
2494 | } |
2495 | |
2496 | // Perform lookup into our base classes. |
2497 | |
2498 | DeclarationName Name = R.getLookupName(); |
2499 | unsigned IDNS = R.getIdentifierNamespace(); |
2500 | |
2501 | // Look for this member in our base classes. |
2502 | auto BaseCallback = [Name, IDNS](const CXXBaseSpecifier *Specifier, |
2503 | CXXBasePath &Path) -> bool { |
2504 | CXXRecordDecl *BaseRecord = Specifier->getType()->getAsCXXRecordDecl(); |
2505 | // Drop leading non-matching lookup results from the declaration list so |
2506 | // we don't need to consider them again below. |
2507 | for (Path.Decls = BaseRecord->lookup(Name).begin(); |
2508 | Path.Decls != Path.Decls.end(); ++Path.Decls) { |
2509 | if ((*Path.Decls)->isInIdentifierNamespace(IDNS)) |
2510 | return true; |
2511 | } |
2512 | return false; |
2513 | }; |
2514 | |
2515 | CXXBasePaths Paths; |
2516 | Paths.setOrigin(LookupRec); |
2517 | if (!LookupRec->lookupInBases(BaseMatches: BaseCallback, Paths)) |
2518 | return false; |
2519 | |
2520 | R.setNamingClass(LookupRec); |
2521 | |
2522 | // C++ [class.member.lookup]p2: |
2523 | // [...] If the resulting set of declarations are not all from |
2524 | // sub-objects of the same type, or the set has a nonstatic member |
2525 | // and includes members from distinct sub-objects, there is an |
2526 | // ambiguity and the program is ill-formed. Otherwise that set is |
2527 | // the result of the lookup. |
2528 | QualType SubobjectType; |
2529 | int SubobjectNumber = 0; |
2530 | AccessSpecifier SubobjectAccess = AS_none; |
2531 | |
2532 | // Check whether the given lookup result contains only static members. |
2533 | auto HasOnlyStaticMembers = [&](DeclContext::lookup_iterator Result) { |
2534 | for (DeclContext::lookup_iterator I = Result, E = I.end(); I != E; ++I) |
2535 | if ((*I)->isInIdentifierNamespace(IDNS) && (*I)->isCXXInstanceMember()) |
2536 | return false; |
2537 | return true; |
2538 | }; |
2539 | |
2540 | bool TemplateNameLookup = R.isTemplateNameLookup(); |
2541 | |
2542 | // Determine whether two sets of members contain the same members, as |
2543 | // required by C++ [class.member.lookup]p6. |
2544 | auto HasSameDeclarations = [&](DeclContext::lookup_iterator A, |
2545 | DeclContext::lookup_iterator B) { |
2546 | using Iterator = DeclContextLookupResult::iterator; |
2547 | using Result = const void *; |
2548 | |
2549 | auto Next = [&](Iterator &It, Iterator End) -> Result { |
2550 | while (It != End) { |
2551 | NamedDecl *ND = *It++; |
2552 | if (!ND->isInIdentifierNamespace(IDNS)) |
2553 | continue; |
2554 | |
2555 | // C++ [temp.local]p3: |
2556 | // A lookup that finds an injected-class-name (10.2) can result in |
2557 | // an ambiguity in certain cases (for example, if it is found in |
2558 | // more than one base class). If all of the injected-class-names |
2559 | // that are found refer to specializations of the same class |
2560 | // template, and if the name is used as a template-name, the |
2561 | // reference refers to the class template itself and not a |
2562 | // specialization thereof, and is not ambiguous. |
2563 | if (TemplateNameLookup) |
2564 | if (auto *TD = getAsTemplateNameDecl(D: ND)) |
2565 | ND = TD; |
2566 | |
2567 | // C++ [class.member.lookup]p3: |
2568 | // type declarations (including injected-class-names) are replaced by |
2569 | // the types they designate |
2570 | if (const TypeDecl *TD = dyn_cast<TypeDecl>(Val: ND->getUnderlyingDecl())) { |
2571 | QualType T = Context.getTypeDeclType(Decl: TD); |
2572 | return T.getCanonicalType().getAsOpaquePtr(); |
2573 | } |
2574 | |
2575 | return ND->getUnderlyingDecl()->getCanonicalDecl(); |
2576 | } |
2577 | return nullptr; |
2578 | }; |
2579 | |
2580 | // We'll often find the declarations are in the same order. Handle this |
2581 | // case (and the special case of only one declaration) efficiently. |
2582 | Iterator AIt = A, BIt = B, AEnd, BEnd; |
2583 | while (true) { |
2584 | Result AResult = Next(AIt, AEnd); |
2585 | Result BResult = Next(BIt, BEnd); |
2586 | if (!AResult && !BResult) |
2587 | return true; |
2588 | if (!AResult || !BResult) |
2589 | return false; |
2590 | if (AResult != BResult) { |
2591 | // Found a mismatch; carefully check both lists, accounting for the |
2592 | // possibility of declarations appearing more than once. |
2593 | llvm::SmallDenseMap<Result, bool, 32> AResults; |
2594 | for (; AResult; AResult = Next(AIt, AEnd)) |
2595 | AResults.insert(KV: {AResult, /*FoundInB*/false}); |
2596 | unsigned Found = 0; |
2597 | for (; BResult; BResult = Next(BIt, BEnd)) { |
2598 | auto It = AResults.find(Val: BResult); |
2599 | if (It == AResults.end()) |
2600 | return false; |
2601 | if (!It->second) { |
2602 | It->second = true; |
2603 | ++Found; |
2604 | } |
2605 | } |
2606 | return AResults.size() == Found; |
2607 | } |
2608 | } |
2609 | }; |
2610 | |
2611 | for (CXXBasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end(); |
2612 | Path != PathEnd; ++Path) { |
2613 | const CXXBasePathElement &PathElement = Path->back(); |
2614 | |
2615 | // Pick the best (i.e. most permissive i.e. numerically lowest) access |
2616 | // across all paths. |
2617 | SubobjectAccess = std::min(a: SubobjectAccess, b: Path->Access); |
2618 | |
2619 | // Determine whether we're looking at a distinct sub-object or not. |
2620 | if (SubobjectType.isNull()) { |
2621 | // This is the first subobject we've looked at. Record its type. |
2622 | SubobjectType = Context.getCanonicalType(T: PathElement.Base->getType()); |
2623 | SubobjectNumber = PathElement.SubobjectNumber; |
2624 | continue; |
2625 | } |
2626 | |
2627 | if (SubobjectType != |
2628 | Context.getCanonicalType(T: PathElement.Base->getType())) { |
2629 | // We found members of the given name in two subobjects of |
2630 | // different types. If the declaration sets aren't the same, this |
2631 | // lookup is ambiguous. |
2632 | // |
2633 | // FIXME: The language rule says that this applies irrespective of |
2634 | // whether the sets contain only static members. |
2635 | if (HasOnlyStaticMembers(Path->Decls) && |
2636 | HasSameDeclarations(Paths.begin()->Decls, Path->Decls)) |
2637 | continue; |
2638 | |
2639 | R.setAmbiguousBaseSubobjectTypes(Paths); |
2640 | return true; |
2641 | } |
2642 | |
2643 | // FIXME: This language rule no longer exists. Checking for ambiguous base |
2644 | // subobjects should be done as part of formation of a class member access |
2645 | // expression (when converting the object parameter to the member's type). |
2646 | if (SubobjectNumber != PathElement.SubobjectNumber) { |
2647 | // We have a different subobject of the same type. |
2648 | |
2649 | // C++ [class.member.lookup]p5: |
2650 | // A static member, a nested type or an enumerator defined in |
2651 | // a base class T can unambiguously be found even if an object |
2652 | // has more than one base class subobject of type T. |
2653 | if (HasOnlyStaticMembers(Path->Decls)) |
2654 | continue; |
2655 | |
2656 | // We have found a nonstatic member name in multiple, distinct |
2657 | // subobjects. Name lookup is ambiguous. |
2658 | R.setAmbiguousBaseSubobjects(Paths); |
2659 | return true; |
2660 | } |
2661 | } |
2662 | |
2663 | // Lookup in a base class succeeded; return these results. |
2664 | |
2665 | for (DeclContext::lookup_iterator I = Paths.front().Decls, E = I.end(); |
2666 | I != E; ++I) { |
2667 | AccessSpecifier AS = CXXRecordDecl::MergeAccess(PathAccess: SubobjectAccess, |
2668 | DeclAccess: (*I)->getAccess()); |
2669 | if (NamedDecl *ND = R.getAcceptableDecl(D: *I)) |
2670 | R.addDecl(D: ND, AS); |
2671 | } |
2672 | R.resolveKind(); |
2673 | return true; |
2674 | } |
2675 | |
2676 | /// Performs qualified name lookup or special type of lookup for |
2677 | /// "__super::" scope specifier. |
2678 | /// |
2679 | /// This routine is a convenience overload meant to be called from contexts |
2680 | /// that need to perform a qualified name lookup with an optional C++ scope |
2681 | /// specifier that might require special kind of lookup. |
2682 | /// |
2683 | /// \param R captures both the lookup criteria and any lookup results found. |
2684 | /// |
2685 | /// \param LookupCtx The context in which qualified name lookup will |
2686 | /// search. |
2687 | /// |
2688 | /// \param SS An optional C++ scope-specifier. |
2689 | /// |
2690 | /// \returns true if lookup succeeded, false if it failed. |
2691 | bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, |
2692 | CXXScopeSpec &SS) { |
2693 | auto *NNS = SS.getScopeRep(); |
2694 | if (NNS && NNS->getKind() == NestedNameSpecifier::Super) |
2695 | return LookupInSuper(R, Class: NNS->getAsRecordDecl()); |
2696 | else |
2697 | |
2698 | return LookupQualifiedName(R, LookupCtx); |
2699 | } |
2700 | |
2701 | /// Performs name lookup for a name that was parsed in the |
2702 | /// source code, and may contain a C++ scope specifier. |
2703 | /// |
2704 | /// This routine is a convenience routine meant to be called from |
2705 | /// contexts that receive a name and an optional C++ scope specifier |
2706 | /// (e.g., "N::M::x"). It will then perform either qualified or |
2707 | /// unqualified name lookup (with LookupQualifiedName or LookupName, |
2708 | /// respectively) on the given name and return those results. It will |
2709 | /// perform a special type of lookup for "__super::" scope specifier. |
2710 | /// |
2711 | /// @param S The scope from which unqualified name lookup will |
2712 | /// begin. |
2713 | /// |
2714 | /// @param SS An optional C++ scope-specifier, e.g., "::N::M". |
2715 | /// |
2716 | /// @param EnteringContext Indicates whether we are going to enter the |
2717 | /// context of the scope-specifier SS (if present). |
2718 | /// |
2719 | /// @returns True if any decls were found (but possibly ambiguous) |
2720 | bool Sema::LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS, |
2721 | bool AllowBuiltinCreation, bool EnteringContext) { |
2722 | if (SS && SS->isInvalid()) { |
2723 | // When the scope specifier is invalid, don't even look for |
2724 | // anything. |
2725 | return false; |
2726 | } |
2727 | |
2728 | if (SS && SS->isSet()) { |
2729 | NestedNameSpecifier *NNS = SS->getScopeRep(); |
2730 | if (NNS->getKind() == NestedNameSpecifier::Super) |
2731 | return LookupInSuper(R, Class: NNS->getAsRecordDecl()); |
2732 | |
2733 | if (DeclContext *DC = computeDeclContext(SS: *SS, EnteringContext)) { |
2734 | // We have resolved the scope specifier to a particular declaration |
2735 | // contex, and will perform name lookup in that context. |
2736 | if (!DC->isDependentContext() && RequireCompleteDeclContext(SS&: *SS, DC)) |
2737 | return false; |
2738 | |
2739 | R.setContextRange(SS->getRange()); |
2740 | return LookupQualifiedName(R, LookupCtx: DC); |
2741 | } |
2742 | |
2743 | // We could not resolve the scope specified to a specific declaration |
2744 | // context, which means that SS refers to an unknown specialization. |
2745 | // Name lookup can't find anything in this case. |
2746 | R.setNotFoundInCurrentInstantiation(); |
2747 | R.setContextRange(SS->getRange()); |
2748 | return false; |
2749 | } |
2750 | |
2751 | // Perform unqualified name lookup starting in the given scope. |
2752 | return LookupName(R, S, AllowBuiltinCreation); |
2753 | } |
2754 | |
2755 | /// Perform qualified name lookup into all base classes of the given |
2756 | /// class. |
2757 | /// |
2758 | /// \param R captures both the lookup criteria and any lookup results found. |
2759 | /// |
2760 | /// \param Class The context in which qualified name lookup will |
2761 | /// search. Name lookup will search in all base classes merging the results. |
2762 | /// |
2763 | /// @returns True if any decls were found (but possibly ambiguous) |
2764 | bool Sema::LookupInSuper(LookupResult &R, CXXRecordDecl *Class) { |
2765 | // The access-control rules we use here are essentially the rules for |
2766 | // doing a lookup in Class that just magically skipped the direct |
2767 | // members of Class itself. That is, the naming class is Class, and the |
2768 | // access includes the access of the base. |
2769 | for (const auto &BaseSpec : Class->bases()) { |
2770 | CXXRecordDecl *RD = cast<CXXRecordDecl>( |
2771 | Val: BaseSpec.getType()->castAs<RecordType>()->getDecl()); |
2772 | LookupResult Result(*this, R.getLookupNameInfo(), R.getLookupKind()); |
2773 | Result.setBaseObjectType(Context.getRecordType(Class)); |
2774 | LookupQualifiedName(Result, RD); |
2775 | |
2776 | // Copy the lookup results into the target, merging the base's access into |
2777 | // the path access. |
2778 | for (auto I = Result.begin(), E = Result.end(); I != E; ++I) { |
2779 | R.addDecl(D: I.getDecl(), |
2780 | AS: CXXRecordDecl::MergeAccess(PathAccess: BaseSpec.getAccessSpecifier(), |
2781 | DeclAccess: I.getAccess())); |
2782 | } |
2783 | |
2784 | Result.suppressDiagnostics(); |
2785 | } |
2786 | |
2787 | R.resolveKind(); |
2788 | R.setNamingClass(Class); |
2789 | |
2790 | return !R.empty(); |
2791 | } |
2792 | |
2793 | /// Produce a diagnostic describing the ambiguity that resulted |
2794 | /// from name lookup. |
2795 | /// |
2796 | /// \param Result The result of the ambiguous lookup to be diagnosed. |
2797 | void Sema::DiagnoseAmbiguousLookup(LookupResult &Result) { |
2798 | assert(Result.isAmbiguous() && "Lookup result must be ambiguous" ); |
2799 | |
2800 | DeclarationName Name = Result.getLookupName(); |
2801 | SourceLocation NameLoc = Result.getNameLoc(); |
2802 | SourceRange LookupRange = Result.getContextRange(); |
2803 | |
2804 | switch (Result.getAmbiguityKind()) { |
2805 | case LookupResult::AmbiguousBaseSubobjects: { |
2806 | CXXBasePaths *Paths = Result.getBasePaths(); |
2807 | QualType SubobjectType = Paths->front().back().Base->getType(); |
2808 | Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects) |
2809 | << Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths) |
2810 | << LookupRange; |
2811 | |
2812 | DeclContext::lookup_iterator Found = Paths->front().Decls; |
2813 | while (isa<CXXMethodDecl>(Val: *Found) && |
2814 | cast<CXXMethodDecl>(Val: *Found)->isStatic()) |
2815 | ++Found; |
2816 | |
2817 | Diag((*Found)->getLocation(), diag::note_ambiguous_member_found); |
2818 | break; |
2819 | } |
2820 | |
2821 | case LookupResult::AmbiguousBaseSubobjectTypes: { |
2822 | Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types) |
2823 | << Name << LookupRange; |
2824 | |
2825 | CXXBasePaths *Paths = Result.getBasePaths(); |
2826 | std::set<const NamedDecl *> DeclsPrinted; |
2827 | for (CXXBasePaths::paths_iterator Path = Paths->begin(), |
2828 | PathEnd = Paths->end(); |
2829 | Path != PathEnd; ++Path) { |
2830 | const NamedDecl *D = *Path->Decls; |
2831 | if (!D->isInIdentifierNamespace(Result.getIdentifierNamespace())) |
2832 | continue; |
2833 | if (DeclsPrinted.insert(x: D).second) { |
2834 | if (const auto *TD = dyn_cast<TypedefNameDecl>(D->getUnderlyingDecl())) |
2835 | Diag(D->getLocation(), diag::note_ambiguous_member_type_found) |
2836 | << TD->getUnderlyingType(); |
2837 | else if (const auto *TD = dyn_cast<TypeDecl>(D->getUnderlyingDecl())) |
2838 | Diag(D->getLocation(), diag::note_ambiguous_member_type_found) |
2839 | << Context.getTypeDeclType(TD); |
2840 | else |
2841 | Diag(D->getLocation(), diag::note_ambiguous_member_found); |
2842 | } |
2843 | } |
2844 | break; |
2845 | } |
2846 | |
2847 | case LookupResult::AmbiguousTagHiding: { |
2848 | Diag(NameLoc, diag::err_ambiguous_tag_hiding) << Name << LookupRange; |
2849 | |
2850 | llvm::SmallPtrSet<NamedDecl*, 8> TagDecls; |
2851 | |
2852 | for (auto *D : Result) |
2853 | if (TagDecl *TD = dyn_cast<TagDecl>(Val: D)) { |
2854 | TagDecls.insert(TD); |
2855 | Diag(TD->getLocation(), diag::note_hidden_tag); |
2856 | } |
2857 | |
2858 | for (auto *D : Result) |
2859 | if (!isa<TagDecl>(D)) |
2860 | Diag(D->getLocation(), diag::note_hiding_object); |
2861 | |
2862 | // For recovery purposes, go ahead and implement the hiding. |
2863 | LookupResult::Filter F = Result.makeFilter(); |
2864 | while (F.hasNext()) { |
2865 | if (TagDecls.count(Ptr: F.next())) |
2866 | F.erase(); |
2867 | } |
2868 | F.done(); |
2869 | break; |
2870 | } |
2871 | |
2872 | case LookupResult::AmbiguousReferenceToPlaceholderVariable: { |
2873 | Diag(NameLoc, diag::err_using_placeholder_variable) << Name << LookupRange; |
2874 | DeclContext *DC = nullptr; |
2875 | for (auto *D : Result) { |
2876 | Diag(D->getLocation(), diag::note_reference_placeholder) << D; |
2877 | if (DC != nullptr && DC != D->getDeclContext()) |
2878 | break; |
2879 | DC = D->getDeclContext(); |
2880 | } |
2881 | break; |
2882 | } |
2883 | |
2884 | case LookupResult::AmbiguousReference: { |
2885 | Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange; |
2886 | |
2887 | for (auto *D : Result) |
2888 | Diag(D->getLocation(), diag::note_ambiguous_candidate) << D; |
2889 | break; |
2890 | } |
2891 | } |
2892 | } |
2893 | |
2894 | namespace { |
2895 | struct AssociatedLookup { |
2896 | AssociatedLookup(Sema &S, SourceLocation InstantiationLoc, |
2897 | Sema::AssociatedNamespaceSet &Namespaces, |
2898 | Sema::AssociatedClassSet &Classes) |
2899 | : S(S), Namespaces(Namespaces), Classes(Classes), |
2900 | InstantiationLoc(InstantiationLoc) { |
2901 | } |
2902 | |
2903 | bool addClassTransitive(CXXRecordDecl *RD) { |
2904 | Classes.insert(X: RD); |
2905 | return ClassesTransitive.insert(X: RD); |
2906 | } |
2907 | |
2908 | Sema &S; |
2909 | Sema::AssociatedNamespaceSet &Namespaces; |
2910 | Sema::AssociatedClassSet &Classes; |
2911 | SourceLocation InstantiationLoc; |
2912 | |
2913 | private: |
2914 | Sema::AssociatedClassSet ClassesTransitive; |
2915 | }; |
2916 | } // end anonymous namespace |
2917 | |
2918 | static void |
2919 | addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType T); |
2920 | |
2921 | // Given the declaration context \param Ctx of a class, class template or |
2922 | // enumeration, add the associated namespaces to \param Namespaces as described |
2923 | // in [basic.lookup.argdep]p2. |
2924 | static void CollectEnclosingNamespace(Sema::AssociatedNamespaceSet &Namespaces, |
2925 | DeclContext *Ctx) { |
2926 | // The exact wording has been changed in C++14 as a result of |
2927 | // CWG 1691 (see also CWG 1690 and CWG 1692). We apply it unconditionally |
2928 | // to all language versions since it is possible to return a local type |
2929 | // from a lambda in C++11. |
2930 | // |
2931 | // C++14 [basic.lookup.argdep]p2: |
2932 | // If T is a class type [...]. Its associated namespaces are the innermost |
2933 | // enclosing namespaces of its associated classes. [...] |
2934 | // |
2935 | // If T is an enumeration type, its associated namespace is the innermost |
2936 | // enclosing namespace of its declaration. [...] |
2937 | |
2938 | // We additionally skip inline namespaces. The innermost non-inline namespace |
2939 | // contains all names of all its nested inline namespaces anyway, so we can |
2940 | // replace the entire inline namespace tree with its root. |
2941 | while (!Ctx->isFileContext() || Ctx->isInlineNamespace()) |
2942 | Ctx = Ctx->getParent(); |
2943 | |
2944 | Namespaces.insert(X: Ctx->getPrimaryContext()); |
2945 | } |
2946 | |
2947 | // Add the associated classes and namespaces for argument-dependent |
2948 | // lookup that involves a template argument (C++ [basic.lookup.argdep]p2). |
2949 | static void |
2950 | addAssociatedClassesAndNamespaces(AssociatedLookup &Result, |
2951 | const TemplateArgument &Arg) { |
2952 | // C++ [basic.lookup.argdep]p2, last bullet: |
2953 | // -- [...] ; |
2954 | switch (Arg.getKind()) { |
2955 | case TemplateArgument::Null: |
2956 | break; |
2957 | |
2958 | case TemplateArgument::Type: |
2959 | // [...] the namespaces and classes associated with the types of the |
2960 | // template arguments provided for template type parameters (excluding |
2961 | // template template parameters) |
2962 | addAssociatedClassesAndNamespaces(Result, T: Arg.getAsType()); |
2963 | break; |
2964 | |
2965 | case TemplateArgument::Template: |
2966 | case TemplateArgument::TemplateExpansion: { |
2967 | // [...] the namespaces in which any template template arguments are |
2968 | // defined; and the classes in which any member templates used as |
2969 | // template template arguments are defined. |
2970 | TemplateName Template = Arg.getAsTemplateOrTemplatePattern(); |
2971 | if (ClassTemplateDecl *ClassTemplate |
2972 | = dyn_cast<ClassTemplateDecl>(Val: Template.getAsTemplateDecl())) { |
2973 | DeclContext *Ctx = ClassTemplate->getDeclContext(); |
2974 | if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Val: Ctx)) |
2975 | Result.Classes.insert(X: EnclosingClass); |
2976 | // Add the associated namespace for this class. |
2977 | CollectEnclosingNamespace(Namespaces&: Result.Namespaces, Ctx); |
2978 | } |
2979 | break; |
2980 | } |
2981 | |
2982 | case TemplateArgument::Declaration: |
2983 | case TemplateArgument::Integral: |
2984 | case TemplateArgument::Expression: |
2985 | case TemplateArgument::NullPtr: |
2986 | case TemplateArgument::StructuralValue: |
2987 | // [Note: non-type template arguments do not contribute to the set of |
2988 | // associated namespaces. ] |
2989 | break; |
2990 | |
2991 | case TemplateArgument::Pack: |
2992 | for (const auto &P : Arg.pack_elements()) |
2993 | addAssociatedClassesAndNamespaces(Result, Arg: P); |
2994 | break; |
2995 | } |
2996 | } |
2997 | |
2998 | // Add the associated classes and namespaces for argument-dependent lookup |
2999 | // with an argument of class type (C++ [basic.lookup.argdep]p2). |
3000 | static void |
3001 | addAssociatedClassesAndNamespaces(AssociatedLookup &Result, |
3002 | CXXRecordDecl *Class) { |
3003 | |
3004 | // Just silently ignore anything whose name is __va_list_tag. |
3005 | if (Class->getDeclName() == Result.S.VAListTagName) |
3006 | return; |
3007 | |
3008 | // C++ [basic.lookup.argdep]p2: |
3009 | // [...] |
3010 | // -- If T is a class type (including unions), its associated |
3011 | // classes are: the class itself; the class of which it is a |
3012 | // member, if any; and its direct and indirect base classes. |
3013 | // Its associated namespaces are the innermost enclosing |
3014 | // namespaces of its associated classes. |
3015 | |
3016 | // Add the class of which it is a member, if any. |
3017 | DeclContext *Ctx = Class->getDeclContext(); |
3018 | if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Val: Ctx)) |
3019 | Result.Classes.insert(X: EnclosingClass); |
3020 | |
3021 | // Add the associated namespace for this class. |
3022 | CollectEnclosingNamespace(Namespaces&: Result.Namespaces, Ctx); |
3023 | |
3024 | // -- If T is a template-id, its associated namespaces and classes are |
3025 | // the namespace in which the template is defined; for member |
3026 | // templates, the member template's class; the namespaces and classes |
3027 | // associated with the types of the template arguments provided for |
3028 | // template type parameters (excluding template template parameters); the |
3029 | // namespaces in which any template template arguments are defined; and |
3030 | // the classes in which any member templates used as template template |
3031 | // arguments are defined. [Note: non-type template arguments do not |
3032 | // contribute to the set of associated namespaces. ] |
3033 | if (ClassTemplateSpecializationDecl *Spec |
3034 | = dyn_cast<ClassTemplateSpecializationDecl>(Val: Class)) { |
3035 | DeclContext *Ctx = Spec->getSpecializedTemplate()->getDeclContext(); |
3036 | if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Val: Ctx)) |
3037 | Result.Classes.insert(X: EnclosingClass); |
3038 | // Add the associated namespace for this class. |
3039 | CollectEnclosingNamespace(Namespaces&: Result.Namespaces, Ctx); |
3040 | |
3041 | const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs(); |
3042 | for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I) |
3043 | addAssociatedClassesAndNamespaces(Result, Arg: TemplateArgs[I]); |
3044 | } |
3045 | |
3046 | // Add the class itself. If we've already transitively visited this class, |
3047 | // we don't need to visit base classes. |
3048 | if (!Result.addClassTransitive(RD: Class)) |
3049 | return; |
3050 | |
3051 | // Only recurse into base classes for complete types. |
3052 | if (!Result.S.isCompleteType(Loc: Result.InstantiationLoc, |
3053 | T: Result.S.Context.getRecordType(Class))) |
3054 | return; |
3055 | |
3056 | // Add direct and indirect base classes along with their associated |
3057 | // namespaces. |
3058 | SmallVector<CXXRecordDecl *, 32> Bases; |
3059 | Bases.push_back(Elt: Class); |
3060 | while (!Bases.empty()) { |
3061 | // Pop this class off the stack. |
3062 | Class = Bases.pop_back_val(); |
3063 | |
3064 | // Visit the base classes. |
3065 | for (const auto &Base : Class->bases()) { |
3066 | const RecordType *BaseType = Base.getType()->getAs<RecordType>(); |
3067 | // In dependent contexts, we do ADL twice, and the first time around, |
3068 | // the base type might be a dependent TemplateSpecializationType, or a |
3069 | // TemplateTypeParmType. If that happens, simply ignore it. |
3070 | // FIXME: If we want to support export, we probably need to add the |
3071 | // namespace of the template in a TemplateSpecializationType, or even |
3072 | // the classes and namespaces of known non-dependent arguments. |
3073 | if (!BaseType) |
3074 | continue; |
3075 | CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(Val: BaseType->getDecl()); |
3076 | if (Result.addClassTransitive(RD: BaseDecl)) { |
3077 | // Find the associated namespace for this base class. |
3078 | DeclContext *BaseCtx = BaseDecl->getDeclContext(); |
3079 | CollectEnclosingNamespace(Namespaces&: Result.Namespaces, Ctx: BaseCtx); |
3080 | |
3081 | // Make sure we visit the bases of this base class. |
3082 | if (BaseDecl->bases_begin() != BaseDecl->bases_end()) |
3083 | Bases.push_back(Elt: BaseDecl); |
3084 | } |
3085 | } |
3086 | } |
3087 | } |
3088 | |
3089 | // Add the associated classes and namespaces for |
3090 | // argument-dependent lookup with an argument of type T |
3091 | // (C++ [basic.lookup.koenig]p2). |
3092 | static void |
3093 | addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType Ty) { |
3094 | // C++ [basic.lookup.koenig]p2: |
3095 | // |
3096 | // For each argument type T in the function call, there is a set |
3097 | // of zero or more associated namespaces and a set of zero or more |
3098 | // associated classes to be considered. The sets of namespaces and |
3099 | // classes is determined entirely by the types of the function |
3100 | // arguments (and the namespace of any template template |
3101 | // argument). Typedef names and using-declarations used to specify |
3102 | // the types do not contribute to this set. The sets of namespaces |
3103 | // and classes are determined in the following way: |
3104 | |
3105 | SmallVector<const Type *, 16> Queue; |
3106 | const Type *T = Ty->getCanonicalTypeInternal().getTypePtr(); |
3107 | |
3108 | while (true) { |
3109 | switch (T->getTypeClass()) { |
3110 | |
3111 | #define TYPE(Class, Base) |
3112 | #define DEPENDENT_TYPE(Class, Base) case Type::Class: |
3113 | #define NON_CANONICAL_TYPE(Class, Base) case Type::Class: |
3114 | #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class: |
3115 | #define ABSTRACT_TYPE(Class, Base) |
3116 | #include "clang/AST/TypeNodes.inc" |
3117 | // T is canonical. We can also ignore dependent types because |
3118 | // we don't need to do ADL at the definition point, but if we |
3119 | // wanted to implement template export (or if we find some other |
3120 | // use for associated classes and namespaces...) this would be |
3121 | // wrong. |
3122 | break; |
3123 | |
3124 | // -- If T is a pointer to U or an array of U, its associated |
3125 | // namespaces and classes are those associated with U. |
3126 | case Type::Pointer: |
3127 | T = cast<PointerType>(T)->getPointeeType().getTypePtr(); |
3128 | continue; |
3129 | case Type::ConstantArray: |
3130 | case Type::IncompleteArray: |
3131 | case Type::VariableArray: |
3132 | T = cast<ArrayType>(T)->getElementType().getTypePtr(); |
3133 | continue; |
3134 | |
3135 | // -- If T is a fundamental type, its associated sets of |
3136 | // namespaces and classes are both empty. |
3137 | case Type::Builtin: |
3138 | break; |
3139 | |
3140 | // -- If T is a class type (including unions), its associated |
3141 | // classes are: the class itself; the class of which it is |
3142 | // a member, if any; and its direct and indirect base classes. |
3143 | // Its associated namespaces are the innermost enclosing |
3144 | // namespaces of its associated classes. |
3145 | case Type::Record: { |
3146 | CXXRecordDecl *Class = |
3147 | cast<CXXRecordDecl>(cast<RecordType>(T)->getDecl()); |
3148 | addAssociatedClassesAndNamespaces(Result, Class); |
3149 | break; |
3150 | } |
3151 | |
3152 | // -- If T is an enumeration type, its associated namespace |
3153 | // is the innermost enclosing namespace of its declaration. |
3154 | // If it is a class member, its associated class is the |
3155 | // member’s class; else it has no associated class. |
3156 | case Type::Enum: { |
3157 | EnumDecl *Enum = cast<EnumType>(T)->getDecl(); |
3158 | |
3159 | DeclContext *Ctx = Enum->getDeclContext(); |
3160 | if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx)) |
3161 | Result.Classes.insert(X: EnclosingClass); |
3162 | |
3163 | // Add the associated namespace for this enumeration. |
3164 | CollectEnclosingNamespace(Namespaces&: Result.Namespaces, Ctx); |
3165 | |
3166 | break; |
3167 | } |
3168 | |
3169 | // -- If T is a function type, its associated namespaces and |
3170 | // classes are those associated with the function parameter |
3171 | // types and those associated with the return type. |
3172 | case Type::FunctionProto: { |
3173 | const FunctionProtoType *Proto = cast<FunctionProtoType>(T); |
3174 | for (const auto &Arg : Proto->param_types()) |
3175 | Queue.push_back(Arg.getTypePtr()); |
3176 | // fallthrough |
3177 | [[fallthrough]]; |
3178 | } |
3179 | case Type::FunctionNoProto: { |
3180 | const FunctionType *FnType = cast<FunctionType>(T); |
3181 | T = FnType->getReturnType().getTypePtr(); |
3182 | continue; |
3183 | } |
3184 | |
3185 | // -- If T is a pointer to a member function of a class X, its |
3186 | // associated namespaces and classes are those associated |
3187 | // with the function parameter types and return type, |
3188 | // together with those associated with X. |
3189 | // |
3190 | // -- If T is a pointer to a data member of class X, its |
3191 | // associated namespaces and classes are those associated |
3192 | // with the member type together with those associated with |
3193 | // X. |
3194 | case Type::MemberPointer: { |
3195 | const MemberPointerType *MemberPtr = cast<MemberPointerType>(T); |
3196 | |
3197 | // Queue up the class type into which this points. |
3198 | Queue.push_back(Elt: MemberPtr->getClass()); |
3199 | |
3200 | // And directly continue with the pointee type. |
3201 | T = MemberPtr->getPointeeType().getTypePtr(); |
3202 | continue; |
3203 | } |
3204 | |
3205 | // As an extension, treat this like a normal pointer. |
3206 | case Type::BlockPointer: |
3207 | T = cast<BlockPointerType>(T)->getPointeeType().getTypePtr(); |
3208 | continue; |
3209 | |
3210 | // References aren't covered by the standard, but that's such an |
3211 | // obvious defect that we cover them anyway. |
3212 | case Type::LValueReference: |
3213 | case Type::RValueReference: |
3214 | T = cast<ReferenceType>(T)->getPointeeType().getTypePtr(); |
3215 | continue; |
3216 | |
3217 | // These are fundamental types. |
3218 | case Type::Vector: |
3219 | case Type::ExtVector: |
3220 | case Type::ConstantMatrix: |
3221 | case Type::Complex: |
3222 | case Type::BitInt: |
3223 | break; |
3224 | |
3225 | // Non-deduced auto types only get here for error cases. |
3226 | case Type::Auto: |
3227 | case Type::DeducedTemplateSpecialization: |
3228 | break; |
3229 | |
3230 | // If T is an Objective-C object or interface type, or a pointer to an |
3231 | // object or interface type, the associated namespace is the global |
3232 | // namespace. |
3233 | case Type::ObjCObject: |
3234 | case Type::ObjCInterface: |
3235 | case Type::ObjCObjectPointer: |
3236 | Result.Namespaces.insert(Result.S.Context.getTranslationUnitDecl()); |
3237 | break; |
3238 | |
3239 | // Atomic types are just wrappers; use the associations of the |
3240 | // contained type. |
3241 | case Type::Atomic: |
3242 | T = cast<AtomicType>(T)->getValueType().getTypePtr(); |
3243 | continue; |
3244 | case Type::Pipe: |
3245 | T = cast<PipeType>(T)->getElementType().getTypePtr(); |
3246 | continue; |
3247 | |
3248 | // Array parameter types are treated as fundamental types. |
3249 | case Type::ArrayParameter: |
3250 | break; |
3251 | } |
3252 | |
3253 | if (Queue.empty()) |
3254 | break; |
3255 | T = Queue.pop_back_val(); |
3256 | } |
3257 | } |
3258 | |
3259 | /// Find the associated classes and namespaces for |
3260 | /// argument-dependent lookup for a call with the given set of |
3261 | /// arguments. |
3262 | /// |
3263 | /// This routine computes the sets of associated classes and associated |
3264 | /// namespaces searched by argument-dependent lookup |
3265 | /// (C++ [basic.lookup.argdep]) for a given set of arguments. |
3266 | void Sema::FindAssociatedClassesAndNamespaces( |
3267 | SourceLocation InstantiationLoc, ArrayRef<Expr *> Args, |
3268 | AssociatedNamespaceSet &AssociatedNamespaces, |
3269 | AssociatedClassSet &AssociatedClasses) { |
3270 | AssociatedNamespaces.clear(); |
3271 | AssociatedClasses.clear(); |
3272 | |
3273 | AssociatedLookup Result(*this, InstantiationLoc, |
3274 | AssociatedNamespaces, AssociatedClasses); |
3275 | |
3276 | // C++ [basic.lookup.koenig]p2: |
3277 | // For each argument type T in the function call, there is a set |
3278 | // of zero or more associated namespaces and a set of zero or more |
3279 | // associated classes to be considered. The sets of namespaces and |
3280 | // classes is determined entirely by the types of the function |
3281 | // arguments (and the namespace of any template template |
3282 | // argument). |
3283 | for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) { |
3284 | Expr *Arg = Args[ArgIdx]; |
3285 | |
3286 | if (Arg->getType() != Context.OverloadTy) { |
3287 | addAssociatedClassesAndNamespaces(Result, Ty: Arg->getType()); |
3288 | continue; |
3289 | } |
3290 | |
3291 | // [...] In addition, if the argument is the name or address of a |
3292 | // set of overloaded functions and/or function templates, its |
3293 | // associated classes and namespaces are the union of those |
3294 | // associated with each of the members of the set: the namespace |
3295 | // in which the function or function template is defined and the |
3296 | // classes and namespaces associated with its (non-dependent) |
3297 | // parameter types and return type. |
3298 | OverloadExpr *OE = OverloadExpr::find(E: Arg).Expression; |
3299 | |
3300 | for (const NamedDecl *D : OE->decls()) { |
3301 | // Look through any using declarations to find the underlying function. |
3302 | const FunctionDecl *FDecl = D->getUnderlyingDecl()->getAsFunction(); |
3303 | |
3304 | // Add the classes and namespaces associated with the parameter |
3305 | // types and return type of this function. |
3306 | addAssociatedClassesAndNamespaces(Result, FDecl->getType()); |
3307 | } |
3308 | } |
3309 | } |
3310 | |
3311 | NamedDecl *Sema::LookupSingleName(Scope *S, DeclarationName Name, |
3312 | SourceLocation Loc, |
3313 | LookupNameKind NameKind, |
3314 | RedeclarationKind Redecl) { |
3315 | LookupResult R(*this, Name, Loc, NameKind, Redecl); |
3316 | LookupName(R, S); |
3317 | return R.getAsSingle<NamedDecl>(); |
3318 | } |
3319 | |
3320 | /// Find the protocol with the given name, if any. |
3321 | ObjCProtocolDecl *Sema::LookupProtocol(IdentifierInfo *II, |
3322 | SourceLocation IdLoc, |
3323 | RedeclarationKind Redecl) { |
3324 | Decl *D = LookupSingleName(S: TUScope, Name: II, Loc: IdLoc, |
3325 | NameKind: LookupObjCProtocolName, Redecl); |
3326 | return cast_or_null<ObjCProtocolDecl>(Val: D); |
3327 | } |
3328 | |
3329 | void Sema::LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S, |
3330 | UnresolvedSetImpl &Functions) { |
3331 | // C++ [over.match.oper]p3: |
3332 | // -- The set of non-member candidates is the result of the |
3333 | // unqualified lookup of operator@ in the context of the |
3334 | // expression according to the usual rules for name lookup in |
3335 | // unqualified function calls (3.4.2) except that all member |
3336 | // functions are ignored. |
3337 | DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); |
3338 | LookupResult Operators(*this, OpName, SourceLocation(), LookupOperatorName); |
3339 | LookupName(R&: Operators, S); |
3340 | |
3341 | assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous" ); |
3342 | Functions.append(I: Operators.begin(), E: Operators.end()); |
3343 | } |
3344 | |
3345 | Sema::SpecialMemberOverloadResult |
3346 | Sema::LookupSpecialMember(CXXRecordDecl *RD, CXXSpecialMemberKind SM, |
3347 | bool ConstArg, bool VolatileArg, bool RValueThis, |
3348 | bool ConstThis, bool VolatileThis) { |
3349 | assert(CanDeclareSpecialMemberFunction(RD) && |
3350 | "doing special member lookup into record that isn't fully complete" ); |
3351 | RD = RD->getDefinition(); |
3352 | if (RValueThis || ConstThis || VolatileThis) |
3353 | assert((SM == CXXSpecialMemberKind::CopyAssignment || |
3354 | SM == CXXSpecialMemberKind::MoveAssignment) && |
3355 | "constructors and destructors always have unqualified lvalue this" ); |
3356 | if (ConstArg || VolatileArg) |
3357 | assert((SM != CXXSpecialMemberKind::DefaultConstructor && |
3358 | SM != CXXSpecialMemberKind::Destructor) && |
3359 | "parameter-less special members can't have qualified arguments" ); |
3360 | |
3361 | // FIXME: Get the caller to pass in a location for the lookup. |
3362 | SourceLocation LookupLoc = RD->getLocation(); |
3363 | |
3364 | llvm::FoldingSetNodeID ID; |
3365 | ID.AddPointer(Ptr: RD); |
3366 | ID.AddInteger(I: llvm::to_underlying(E: SM)); |
3367 | ID.AddInteger(I: ConstArg); |
3368 | ID.AddInteger(I: VolatileArg); |
3369 | ID.AddInteger(I: RValueThis); |
3370 | ID.AddInteger(I: ConstThis); |
3371 | ID.AddInteger(I: VolatileThis); |
3372 | |
3373 | void *InsertPoint; |
3374 | SpecialMemberOverloadResultEntry *Result = |
3375 | SpecialMemberCache.FindNodeOrInsertPos(ID, InsertPos&: InsertPoint); |
3376 | |
3377 | // This was already cached |
3378 | if (Result) |
3379 | return *Result; |
3380 | |
3381 | Result = BumpAlloc.Allocate<SpecialMemberOverloadResultEntry>(); |
3382 | Result = new (Result) SpecialMemberOverloadResultEntry(ID); |
3383 | SpecialMemberCache.InsertNode(N: Result, InsertPos: InsertPoint); |
3384 | |
3385 | if (SM == CXXSpecialMemberKind::Destructor) { |
3386 | if (RD->needsImplicitDestructor()) { |
3387 | runWithSufficientStackSpace(Loc: RD->getLocation(), Fn: [&] { |
3388 | DeclareImplicitDestructor(ClassDecl: RD); |
3389 | }); |
3390 | } |
3391 | CXXDestructorDecl *DD = RD->getDestructor(); |
3392 | Result->setMethod(DD); |
3393 | Result->setKind(DD && !DD->isDeleted() |
3394 | ? SpecialMemberOverloadResult::Success |
3395 | : SpecialMemberOverloadResult::NoMemberOrDeleted); |
3396 | return *Result; |
3397 | } |
3398 | |
3399 | // Prepare for overload resolution. Here we construct a synthetic argument |
3400 | // if necessary and make sure that implicit functions are declared. |
3401 | CanQualType CanTy = Context.getCanonicalType(T: Context.getTagDeclType(RD)); |
3402 | DeclarationName Name; |
3403 | Expr *Arg = nullptr; |
3404 | unsigned NumArgs; |
3405 | |
3406 | QualType ArgType = CanTy; |
3407 | ExprValueKind VK = VK_LValue; |
3408 | |
3409 | if (SM == CXXSpecialMemberKind::DefaultConstructor) { |
3410 | Name = Context.DeclarationNames.getCXXConstructorName(Ty: CanTy); |
3411 | NumArgs = 0; |
3412 | if (RD->needsImplicitDefaultConstructor()) { |
3413 | runWithSufficientStackSpace(Loc: RD->getLocation(), Fn: [&] { |
3414 | DeclareImplicitDefaultConstructor(ClassDecl: RD); |
3415 | }); |
3416 | } |
3417 | } else { |
3418 | if (SM == CXXSpecialMemberKind::CopyConstructor || |
3419 | SM == CXXSpecialMemberKind::MoveConstructor) { |
3420 | Name = Context.DeclarationNames.getCXXConstructorName(Ty: CanTy); |
3421 | if (RD->needsImplicitCopyConstructor()) { |
3422 | runWithSufficientStackSpace(Loc: RD->getLocation(), Fn: [&] { |
3423 | DeclareImplicitCopyConstructor(ClassDecl: RD); |
3424 | }); |
3425 | } |
3426 | if (getLangOpts().CPlusPlus11 && RD->needsImplicitMoveConstructor()) { |
3427 | runWithSufficientStackSpace(Loc: RD->getLocation(), Fn: [&] { |
3428 | DeclareImplicitMoveConstructor(ClassDecl: RD); |
3429 | }); |
3430 | } |
3431 | } else { |
3432 | Name = Context.DeclarationNames.getCXXOperatorName(Op: OO_Equal); |
3433 | if (RD->needsImplicitCopyAssignment()) { |
3434 | runWithSufficientStackSpace(Loc: RD->getLocation(), Fn: [&] { |
3435 | DeclareImplicitCopyAssignment(ClassDecl: RD); |
3436 | }); |
3437 | } |
3438 | if (getLangOpts().CPlusPlus11 && RD->needsImplicitMoveAssignment()) { |
3439 | runWithSufficientStackSpace(Loc: RD->getLocation(), Fn: [&] { |
3440 | DeclareImplicitMoveAssignment(ClassDecl: RD); |
3441 | }); |
3442 | } |
3443 | } |
3444 | |
3445 | if (ConstArg) |
3446 | ArgType.addConst(); |
3447 | if (VolatileArg) |
3448 | ArgType.addVolatile(); |
3449 | |
3450 | // This isn't /really/ specified by the standard, but it's implied |
3451 | // we should be working from a PRValue in the case of move to ensure |
3452 | // that we prefer to bind to rvalue references, and an LValue in the |
3453 | // case of copy to ensure we don't bind to rvalue references. |
3454 | // Possibly an XValue is actually correct in the case of move, but |
3455 | // there is no semantic difference for class types in this restricted |
3456 | // case. |
3457 | if (SM == CXXSpecialMemberKind::CopyConstructor || |
3458 | SM == CXXSpecialMemberKind::CopyAssignment) |
3459 | VK = VK_LValue; |
3460 | else |
3461 | VK = VK_PRValue; |
3462 | } |
3463 | |
3464 | OpaqueValueExpr FakeArg(LookupLoc, ArgType, VK); |
3465 | |
3466 | if (SM != CXXSpecialMemberKind::DefaultConstructor) { |
3467 | NumArgs = 1; |
3468 | Arg = &FakeArg; |
3469 | } |
3470 | |
3471 | // Create the object argument |
3472 | QualType ThisTy = CanTy; |
3473 | if (ConstThis) |
3474 | ThisTy.addConst(); |
3475 | if (VolatileThis) |
3476 | ThisTy.addVolatile(); |
3477 | Expr::Classification Classification = |
3478 | OpaqueValueExpr(LookupLoc, ThisTy, RValueThis ? VK_PRValue : VK_LValue) |
3479 | .Classify(Context); |
3480 | |
3481 | // Now we perform lookup on the name we computed earlier and do overload |
3482 | // resolution. Lookup is only performed directly into the class since there |
3483 | // will always be a (possibly implicit) declaration to shadow any others. |
3484 | OverloadCandidateSet OCS(LookupLoc, OverloadCandidateSet::CSK_Normal); |
3485 | DeclContext::lookup_result R = RD->lookup(Name); |
3486 | |
3487 | if (R.empty()) { |
3488 | // We might have no default constructor because we have a lambda's closure |
3489 | // type, rather than because there's some other declared constructor. |
3490 | // Every class has a copy/move constructor, copy/move assignment, and |
3491 | // destructor. |
3492 | assert(SM == CXXSpecialMemberKind::DefaultConstructor && |
3493 | "lookup for a constructor or assignment operator was empty" ); |
3494 | Result->setMethod(nullptr); |
3495 | Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted); |
3496 | return *Result; |
3497 | } |
3498 | |
3499 | // Copy the candidates as our processing of them may load new declarations |
3500 | // from an external source and invalidate lookup_result. |
3501 | SmallVector<NamedDecl *, 8> Candidates(R.begin(), R.end()); |
3502 | |
3503 | for (NamedDecl *CandDecl : Candidates) { |
3504 | if (CandDecl->isInvalidDecl()) |
3505 | continue; |
3506 | |
3507 | DeclAccessPair Cand = DeclAccessPair::make(CandDecl, AS_public); |
3508 | auto CtorInfo = getConstructorInfo(Cand); |
3509 | if (CXXMethodDecl *M = dyn_cast<CXXMethodDecl>(Cand->getUnderlyingDecl())) { |
3510 | if (SM == CXXSpecialMemberKind::CopyAssignment || |
3511 | SM == CXXSpecialMemberKind::MoveAssignment) |
3512 | AddMethodCandidate(M, Cand, RD, ThisTy, Classification, |
3513 | llvm::ArrayRef(&Arg, NumArgs), OCS, true); |
3514 | else if (CtorInfo) |
3515 | AddOverloadCandidate(CtorInfo.Constructor, CtorInfo.FoundDecl, |
3516 | llvm::ArrayRef(&Arg, NumArgs), OCS, |
3517 | /*SuppressUserConversions*/ true); |
3518 | else |
3519 | AddOverloadCandidate(M, Cand, llvm::ArrayRef(&Arg, NumArgs), OCS, |
3520 | /*SuppressUserConversions*/ true); |
3521 | } else if (FunctionTemplateDecl *Tmpl = |
3522 | dyn_cast<FunctionTemplateDecl>(Cand->getUnderlyingDecl())) { |
3523 | if (SM == CXXSpecialMemberKind::CopyAssignment || |
3524 | SM == CXXSpecialMemberKind::MoveAssignment) |
3525 | AddMethodTemplateCandidate(Tmpl, Cand, RD, nullptr, ThisTy, |
3526 | Classification, |
3527 | llvm::ArrayRef(&Arg, NumArgs), OCS, true); |
3528 | else if (CtorInfo) |
3529 | AddTemplateOverloadCandidate(CtorInfo.ConstructorTmpl, |
3530 | CtorInfo.FoundDecl, nullptr, |
3531 | llvm::ArrayRef(&Arg, NumArgs), OCS, true); |
3532 | else |
3533 | AddTemplateOverloadCandidate(Tmpl, Cand, nullptr, |
3534 | llvm::ArrayRef(&Arg, NumArgs), OCS, true); |
3535 | } else { |
3536 | assert(isa<UsingDecl>(Cand.getDecl()) && |
3537 | "illegal Kind of operator = Decl" ); |
3538 | } |
3539 | } |
3540 | |
3541 | OverloadCandidateSet::iterator Best; |
3542 | switch (OCS.BestViableFunction(S&: *this, Loc: LookupLoc, Best)) { |
3543 | case OR_Success: |
3544 | Result->setMethod(cast<CXXMethodDecl>(Val: Best->Function)); |
3545 | Result->setKind(SpecialMemberOverloadResult::Success); |
3546 | break; |
3547 | |
3548 | case OR_Deleted: |
3549 | Result->setMethod(cast<CXXMethodDecl>(Val: Best->Function)); |
3550 | Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted); |
3551 | break; |
3552 | |
3553 | case OR_Ambiguous: |
3554 | Result->setMethod(nullptr); |
3555 | Result->setKind(SpecialMemberOverloadResult::Ambiguous); |
3556 | break; |
3557 | |
3558 | case OR_No_Viable_Function: |
3559 | Result->setMethod(nullptr); |
3560 | Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted); |
3561 | break; |
3562 | } |
3563 | |
3564 | return *Result; |
3565 | } |
3566 | |
3567 | /// Look up the default constructor for the given class. |
3568 | CXXConstructorDecl *Sema::LookupDefaultConstructor(CXXRecordDecl *Class) { |
3569 | SpecialMemberOverloadResult Result = |
3570 | LookupSpecialMember(RD: Class, SM: CXXSpecialMemberKind::DefaultConstructor, |
3571 | ConstArg: false, VolatileArg: false, RValueThis: false, ConstThis: false, VolatileThis: false); |
3572 | |
3573 | return cast_or_null<CXXConstructorDecl>(Val: Result.getMethod()); |
3574 | } |
3575 | |
3576 | /// Look up the copying constructor for the given class. |
3577 | CXXConstructorDecl *Sema::LookupCopyingConstructor(CXXRecordDecl *Class, |
3578 | unsigned Quals) { |
3579 | assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) && |
3580 | "non-const, non-volatile qualifiers for copy ctor arg" ); |
3581 | SpecialMemberOverloadResult Result = LookupSpecialMember( |
3582 | RD: Class, SM: CXXSpecialMemberKind::CopyConstructor, ConstArg: Quals & Qualifiers::Const, |
3583 | VolatileArg: Quals & Qualifiers::Volatile, RValueThis: false, ConstThis: false, VolatileThis: false); |
3584 | |
3585 | return cast_or_null<CXXConstructorDecl>(Val: Result.getMethod()); |
3586 | } |
3587 | |
3588 | /// Look up the moving constructor for the given class. |
3589 | CXXConstructorDecl *Sema::LookupMovingConstructor(CXXRecordDecl *Class, |
3590 | unsigned Quals) { |
3591 | SpecialMemberOverloadResult Result = LookupSpecialMember( |
3592 | RD: Class, SM: CXXSpecialMemberKind::MoveConstructor, ConstArg: Quals & Qualifiers::Const, |
3593 | VolatileArg: Quals & Qualifiers::Volatile, RValueThis: false, ConstThis: false, VolatileThis: false); |
3594 | |
3595 | return cast_or_null<CXXConstructorDecl>(Val: Result.getMethod()); |
3596 | } |
3597 | |
3598 | /// Look up the constructors for the given class. |
3599 | DeclContext::lookup_result Sema::LookupConstructors(CXXRecordDecl *Class) { |
3600 | // If the implicit constructors have not yet been declared, do so now. |
3601 | if (CanDeclareSpecialMemberFunction(Class)) { |
3602 | runWithSufficientStackSpace(Loc: Class->getLocation(), Fn: [&] { |
3603 | if (Class->needsImplicitDefaultConstructor()) |
3604 | DeclareImplicitDefaultConstructor(ClassDecl: Class); |
3605 | if (Class->needsImplicitCopyConstructor()) |
3606 | DeclareImplicitCopyConstructor(ClassDecl: Class); |
3607 | if (getLangOpts().CPlusPlus11 && Class->needsImplicitMoveConstructor()) |
3608 | DeclareImplicitMoveConstructor(ClassDecl: Class); |
3609 | }); |
3610 | } |
3611 | |
3612 | CanQualType T = Context.getCanonicalType(T: Context.getTypeDeclType(Class)); |
3613 | DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(Ty: T); |
3614 | return Class->lookup(Name); |
3615 | } |
3616 | |
3617 | /// Look up the copying assignment operator for the given class. |
3618 | CXXMethodDecl *Sema::LookupCopyingAssignment(CXXRecordDecl *Class, |
3619 | unsigned Quals, bool RValueThis, |
3620 | unsigned ThisQuals) { |
3621 | assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) && |
3622 | "non-const, non-volatile qualifiers for copy assignment arg" ); |
3623 | assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) && |
3624 | "non-const, non-volatile qualifiers for copy assignment this" ); |
3625 | SpecialMemberOverloadResult Result = LookupSpecialMember( |
3626 | RD: Class, SM: CXXSpecialMemberKind::CopyAssignment, ConstArg: Quals & Qualifiers::Const, |
3627 | VolatileArg: Quals & Qualifiers::Volatile, RValueThis, ConstThis: ThisQuals & Qualifiers::Const, |
3628 | VolatileThis: ThisQuals & Qualifiers::Volatile); |
3629 | |
3630 | return Result.getMethod(); |
3631 | } |
3632 | |
3633 | /// Look up the moving assignment operator for the given class. |
3634 | CXXMethodDecl *Sema::LookupMovingAssignment(CXXRecordDecl *Class, |
3635 | unsigned Quals, |
3636 | bool RValueThis, |
3637 | unsigned ThisQuals) { |
3638 | assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) && |
3639 | "non-const, non-volatile qualifiers for copy assignment this" ); |
3640 | SpecialMemberOverloadResult Result = LookupSpecialMember( |
3641 | RD: Class, SM: CXXSpecialMemberKind::MoveAssignment, ConstArg: Quals & Qualifiers::Const, |
3642 | VolatileArg: Quals & Qualifiers::Volatile, RValueThis, ConstThis: ThisQuals & Qualifiers::Const, |
3643 | VolatileThis: ThisQuals & Qualifiers::Volatile); |
3644 | |
3645 | return Result.getMethod(); |
3646 | } |
3647 | |
3648 | /// Look for the destructor of the given class. |
3649 | /// |
3650 | /// During semantic analysis, this routine should be used in lieu of |
3651 | /// CXXRecordDecl::getDestructor(). |
3652 | /// |
3653 | /// \returns The destructor for this class. |
3654 | CXXDestructorDecl *Sema::LookupDestructor(CXXRecordDecl *Class) { |
3655 | return cast_or_null<CXXDestructorDecl>( |
3656 | Val: LookupSpecialMember(RD: Class, SM: CXXSpecialMemberKind::Destructor, ConstArg: false, VolatileArg: false, |
3657 | RValueThis: false, ConstThis: false, VolatileThis: false) |
3658 | .getMethod()); |
3659 | } |
3660 | |
3661 | /// LookupLiteralOperator - Determine which literal operator should be used for |
3662 | /// a user-defined literal, per C++11 [lex.ext]. |
3663 | /// |
3664 | /// Normal overload resolution is not used to select which literal operator to |
3665 | /// call for a user-defined literal. Look up the provided literal operator name, |
3666 | /// and filter the results to the appropriate set for the given argument types. |
3667 | Sema::LiteralOperatorLookupResult |
3668 | Sema::LookupLiteralOperator(Scope *S, LookupResult &R, |
3669 | ArrayRef<QualType> ArgTys, bool AllowRaw, |
3670 | bool AllowTemplate, bool AllowStringTemplatePack, |
3671 | bool DiagnoseMissing, StringLiteral *StringLit) { |
3672 | LookupName(R, S); |
3673 | assert(R.getResultKind() != LookupResult::Ambiguous && |
3674 | "literal operator lookup can't be ambiguous" ); |
3675 | |
3676 | // Filter the lookup results appropriately. |
3677 | LookupResult::Filter F = R.makeFilter(); |
3678 | |
3679 | bool AllowCooked = true; |
3680 | bool FoundRaw = false; |
3681 | bool FoundTemplate = false; |
3682 | bool FoundStringTemplatePack = false; |
3683 | bool FoundCooked = false; |
3684 | |
3685 | while (F.hasNext()) { |
3686 | Decl *D = F.next(); |
3687 | if (UsingShadowDecl *USD = dyn_cast<UsingShadowDecl>(Val: D)) |
3688 | D = USD->getTargetDecl(); |
3689 | |
3690 | // If the declaration we found is invalid, skip it. |
3691 | if (D->isInvalidDecl()) { |
3692 | F.erase(); |
3693 | continue; |
3694 | } |
3695 | |
3696 | bool IsRaw = false; |
3697 | bool IsTemplate = false; |
3698 | bool IsStringTemplatePack = false; |
3699 | bool IsCooked = false; |
3700 | |
3701 | if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: D)) { |
3702 | if (FD->getNumParams() == 1 && |
3703 | FD->getParamDecl(i: 0)->getType()->getAs<PointerType>()) |
3704 | IsRaw = true; |
3705 | else if (FD->getNumParams() == ArgTys.size()) { |
3706 | IsCooked = true; |
3707 | for (unsigned ArgIdx = 0; ArgIdx != ArgTys.size(); ++ArgIdx) { |
3708 | QualType ParamTy = FD->getParamDecl(i: ArgIdx)->getType(); |
3709 | if (!Context.hasSameUnqualifiedType(T1: ArgTys[ArgIdx], T2: ParamTy)) { |
3710 | IsCooked = false; |
3711 | break; |
3712 | } |
3713 | } |
3714 | } |
3715 | } |
3716 | if (FunctionTemplateDecl *FD = dyn_cast<FunctionTemplateDecl>(Val: D)) { |
3717 | TemplateParameterList *Params = FD->getTemplateParameters(); |
3718 | if (Params->size() == 1) { |
3719 | IsTemplate = true; |
3720 | if (!Params->getParam(Idx: 0)->isTemplateParameterPack() && !StringLit) { |
3721 | // Implied but not stated: user-defined integer and floating literals |
3722 | // only ever use numeric literal operator templates, not templates |
3723 | // taking a parameter of class type. |
3724 | F.erase(); |
3725 | continue; |
3726 | } |
3727 | |
3728 | // A string literal template is only considered if the string literal |
3729 | // is a well-formed template argument for the template parameter. |
3730 | if (StringLit) { |
3731 | SFINAETrap Trap(*this); |
3732 | SmallVector<TemplateArgument, 1> SugaredChecked, CanonicalChecked; |
3733 | TemplateArgumentLoc Arg(TemplateArgument(StringLit), StringLit); |
3734 | if (CheckTemplateArgument( |
3735 | Params->getParam(Idx: 0), Arg, FD, R.getNameLoc(), R.getNameLoc(), |
3736 | 0, SugaredChecked, CanonicalChecked, CTAK_Specified) || |
3737 | Trap.hasErrorOccurred()) |
3738 | IsTemplate = false; |
3739 | } |
3740 | } else { |
3741 | IsStringTemplatePack = true; |
3742 | } |
3743 | } |
3744 | |
3745 | if (AllowTemplate && StringLit && IsTemplate) { |
3746 | FoundTemplate = true; |
3747 | AllowRaw = false; |
3748 | AllowCooked = false; |
3749 | AllowStringTemplatePack = false; |
3750 | if (FoundRaw || FoundCooked || FoundStringTemplatePack) { |
3751 | F.restart(); |
3752 | FoundRaw = FoundCooked = FoundStringTemplatePack = false; |
3753 | } |
3754 | } else if (AllowCooked && IsCooked) { |
3755 | FoundCooked = true; |
3756 | AllowRaw = false; |
3757 | AllowTemplate = StringLit; |
3758 | AllowStringTemplatePack = false; |
3759 | if (FoundRaw || FoundTemplate || FoundStringTemplatePack) { |
3760 | // Go through again and remove the raw and template decls we've |
3761 | // already found. |
3762 | F.restart(); |
3763 | FoundRaw = FoundTemplate = FoundStringTemplatePack = false; |
3764 | } |
3765 | } else if (AllowRaw && IsRaw) { |
3766 | FoundRaw = true; |
3767 | } else if (AllowTemplate && IsTemplate) { |
3768 | FoundTemplate = true; |
3769 | } else if (AllowStringTemplatePack && IsStringTemplatePack) { |
3770 | FoundStringTemplatePack = true; |
3771 | } else { |
3772 | F.erase(); |
3773 | } |
3774 | } |
3775 | |
3776 | F.done(); |
3777 | |
3778 | // Per C++20 [lex.ext]p5, we prefer the template form over the non-template |
3779 | // form for string literal operator templates. |
3780 | if (StringLit && FoundTemplate) |
3781 | return LOLR_Template; |
3782 | |
3783 | // C++11 [lex.ext]p3, p4: If S contains a literal operator with a matching |
3784 | // parameter type, that is used in preference to a raw literal operator |
3785 | // or literal operator template. |
3786 | if (FoundCooked) |
3787 | return LOLR_Cooked; |
3788 | |
3789 | // C++11 [lex.ext]p3, p4: S shall contain a raw literal operator or a literal |
3790 | // operator template, but not both. |
3791 | if (FoundRaw && FoundTemplate) { |
3792 | Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName(); |
3793 | for (const NamedDecl *D : R) |
3794 | NoteOverloadCandidate(Found: D, Fn: D->getUnderlyingDecl()->getAsFunction()); |
3795 | return LOLR_Error; |
3796 | } |
3797 | |
3798 | if (FoundRaw) |
3799 | return LOLR_Raw; |
3800 | |
3801 | if (FoundTemplate) |
3802 | return LOLR_Template; |
3803 | |
3804 | if (FoundStringTemplatePack) |
3805 | return LOLR_StringTemplatePack; |
3806 | |
3807 | // Didn't find anything we could use. |
3808 | if (DiagnoseMissing) { |
3809 | Diag(R.getNameLoc(), diag::err_ovl_no_viable_literal_operator) |
3810 | << R.getLookupName() << (int)ArgTys.size() << ArgTys[0] |
3811 | << (ArgTys.size() == 2 ? ArgTys[1] : QualType()) << AllowRaw |
3812 | << (AllowTemplate || AllowStringTemplatePack); |
3813 | return LOLR_Error; |
3814 | } |
3815 | |
3816 | return LOLR_ErrorNoDiagnostic; |
3817 | } |
3818 | |
3819 | void ADLResult::insert(NamedDecl *New) { |
3820 | NamedDecl *&Old = Decls[cast<NamedDecl>(New->getCanonicalDecl())]; |
3821 | |
3822 | // If we haven't yet seen a decl for this key, or the last decl |
3823 | // was exactly this one, we're done. |
3824 | if (Old == nullptr || Old == New) { |
3825 | Old = New; |
3826 | return; |
3827 | } |
3828 | |
3829 | // Otherwise, decide which is a more recent redeclaration. |
3830 | FunctionDecl *OldFD = Old->getAsFunction(); |
3831 | FunctionDecl *NewFD = New->getAsFunction(); |
3832 | |
3833 | FunctionDecl *Cursor = NewFD; |
3834 | while (true) { |
3835 | Cursor = Cursor->getPreviousDecl(); |
3836 | |
3837 | // If we got to the end without finding OldFD, OldFD is the newer |
3838 | // declaration; leave things as they are. |
3839 | if (!Cursor) return; |
3840 | |
3841 | // If we do find OldFD, then NewFD is newer. |
3842 | if (Cursor == OldFD) break; |
3843 | |
3844 | // Otherwise, keep looking. |
3845 | } |
3846 | |
3847 | Old = New; |
3848 | } |
3849 | |
3850 | void Sema::ArgumentDependentLookup(DeclarationName Name, SourceLocation Loc, |
3851 | ArrayRef<Expr *> Args, ADLResult &Result) { |
3852 | // Find all of the associated namespaces and classes based on the |
3853 | // arguments we have. |
3854 | AssociatedNamespaceSet AssociatedNamespaces; |
3855 | AssociatedClassSet AssociatedClasses; |
3856 | FindAssociatedClassesAndNamespaces(InstantiationLoc: Loc, Args, |
3857 | AssociatedNamespaces, |
3858 | AssociatedClasses); |
3859 | |
3860 | // C++ [basic.lookup.argdep]p3: |
3861 | // Let X be the lookup set produced by unqualified lookup (3.4.1) |
3862 | // and let Y be the lookup set produced by argument dependent |
3863 | // lookup (defined as follows). If X contains [...] then Y is |
3864 | // empty. Otherwise Y is the set of declarations found in the |
3865 | // namespaces associated with the argument types as described |
3866 | // below. The set of declarations found by the lookup of the name |
3867 | // is the union of X and Y. |
3868 | // |
3869 | // Here, we compute Y and add its members to the overloaded |
3870 | // candidate set. |
3871 | for (auto *NS : AssociatedNamespaces) { |
3872 | // When considering an associated namespace, the lookup is the |
3873 | // same as the lookup performed when the associated namespace is |
3874 | // used as a qualifier (3.4.3.2) except that: |
3875 | // |
3876 | // -- Any using-directives in the associated namespace are |
3877 | // ignored. |
3878 | // |
3879 | // -- Any namespace-scope friend functions declared in |
3880 | // associated classes are visible within their respective |
3881 | // namespaces even if they are not visible during an ordinary |
3882 | // lookup (11.4). |
3883 | // |
3884 | // C++20 [basic.lookup.argdep] p4.3 |
3885 | // -- are exported, are attached to a named module M, do not appear |
3886 | // in the translation unit containing the point of the lookup, and |
3887 | // have the same innermost enclosing non-inline namespace scope as |
3888 | // a declaration of an associated entity attached to M. |
3889 | DeclContext::lookup_result R = NS->lookup(Name); |
3890 | for (auto *D : R) { |
3891 | auto *Underlying = D; |
3892 | if (auto *USD = dyn_cast<UsingShadowDecl>(Val: D)) |
3893 | Underlying = USD->getTargetDecl(); |
3894 | |
3895 | if (!isa<FunctionDecl>(Val: Underlying) && |
3896 | !isa<FunctionTemplateDecl>(Val: Underlying)) |
3897 | continue; |
3898 | |
3899 | // The declaration is visible to argument-dependent lookup if either |
3900 | // it's ordinarily visible or declared as a friend in an associated |
3901 | // class. |
3902 | bool Visible = false; |
3903 | for (D = D->getMostRecentDecl(); D; |
3904 | D = cast_or_null<NamedDecl>(D->getPreviousDecl())) { |
3905 | if (D->getIdentifierNamespace() & Decl::IDNS_Ordinary) { |
3906 | if (isVisible(D)) { |
3907 | Visible = true; |
3908 | break; |
3909 | } |
3910 | |
3911 | if (!getLangOpts().CPlusPlusModules) |
3912 | continue; |
3913 | |
3914 | if (D->isInExportDeclContext()) { |
3915 | Module *FM = D->getOwningModule(); |
3916 | // C++20 [basic.lookup.argdep] p4.3 .. are exported ... |
3917 | // exports are only valid in module purview and outside of any |
3918 | // PMF (although a PMF should not even be present in a module |
3919 | // with an import). |
3920 | assert(FM && FM->isNamedModule() && !FM->isPrivateModule() && |
3921 | "bad export context" ); |
3922 | // .. are attached to a named module M, do not appear in the |
3923 | // translation unit containing the point of the lookup.. |
3924 | if (D->isInAnotherModuleUnit() && |
3925 | llvm::any_of(Range&: AssociatedClasses, P: [&](auto *E) { |
3926 | // ... and have the same innermost enclosing non-inline |
3927 | // namespace scope as a declaration of an associated entity |
3928 | // attached to M |
3929 | if (E->getOwningModule() != FM) |
3930 | return false; |
3931 | // TODO: maybe this could be cached when generating the |
3932 | // associated namespaces / entities. |
3933 | DeclContext *Ctx = E->getDeclContext(); |
3934 | while (!Ctx->isFileContext() || Ctx->isInlineNamespace()) |
3935 | Ctx = Ctx->getParent(); |
3936 | return Ctx == NS; |
3937 | })) { |
3938 | Visible = true; |
3939 | break; |
3940 | } |
3941 | } |
3942 | } else if (D->getFriendObjectKind()) { |
3943 | auto *RD = cast<CXXRecordDecl>(D->getLexicalDeclContext()); |
3944 | // [basic.lookup.argdep]p4: |
3945 | // Argument-dependent lookup finds all declarations of functions and |
3946 | // function templates that |
3947 | // - ... |
3948 | // - are declared as a friend ([class.friend]) of any class with a |
3949 | // reachable definition in the set of associated entities, |
3950 | // |
3951 | // FIXME: If there's a merged definition of D that is reachable, then |
3952 | // the friend declaration should be considered. |
3953 | if (AssociatedClasses.count(key: RD) && isReachable(D)) { |
3954 | Visible = true; |
3955 | break; |
3956 | } |
3957 | } |
3958 | } |
3959 | |
3960 | // FIXME: Preserve D as the FoundDecl. |
3961 | if (Visible) |
3962 | Result.insert(New: Underlying); |
3963 | } |
3964 | } |
3965 | } |
3966 | |
3967 | //---------------------------------------------------------------------------- |
3968 | // Search for all visible declarations. |
3969 | //---------------------------------------------------------------------------- |
3970 | VisibleDeclConsumer::~VisibleDeclConsumer() { } |
3971 | |
3972 | bool VisibleDeclConsumer::includeHiddenDecls() const { return false; } |
3973 | |
3974 | namespace { |
3975 | |
3976 | class ShadowContextRAII; |
3977 | |
3978 | class VisibleDeclsRecord { |
3979 | public: |
3980 | /// An entry in the shadow map, which is optimized to store a |
3981 | /// single declaration (the common case) but can also store a list |
3982 | /// of declarations. |
3983 | typedef llvm::TinyPtrVector<NamedDecl*> ShadowMapEntry; |
3984 | |
3985 | private: |
3986 | /// A mapping from declaration names to the declarations that have |
3987 | /// this name within a particular scope. |
3988 | typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap; |
3989 | |
3990 | /// A list of shadow maps, which is used to model name hiding. |
3991 | std::list<ShadowMap> ShadowMaps; |
3992 | |
3993 | /// The declaration contexts we have already visited. |
3994 | llvm::SmallPtrSet<DeclContext *, 8> VisitedContexts; |
3995 | |
3996 | friend class ShadowContextRAII; |
3997 | |
3998 | public: |
3999 | /// Determine whether we have already visited this context |
4000 | /// (and, if not, note that we are going to visit that context now). |
4001 | bool visitedContext(DeclContext *Ctx) { |
4002 | return !VisitedContexts.insert(Ptr: Ctx).second; |
4003 | } |
4004 | |
4005 | bool alreadyVisitedContext(DeclContext *Ctx) { |
4006 | return VisitedContexts.count(Ptr: Ctx); |
4007 | } |
4008 | |
4009 | /// Determine whether the given declaration is hidden in the |
4010 | /// current scope. |
4011 | /// |
4012 | /// \returns the declaration that hides the given declaration, or |
4013 | /// NULL if no such declaration exists. |
4014 | NamedDecl *checkHidden(NamedDecl *ND); |
4015 | |
4016 | /// Add a declaration to the current shadow map. |
4017 | void add(NamedDecl *ND) { |
4018 | ShadowMaps.back()[ND->getDeclName()].push_back(NewVal: ND); |
4019 | } |
4020 | }; |
4021 | |
4022 | /// RAII object that records when we've entered a shadow context. |
4023 | class ShadowContextRAII { |
4024 | VisibleDeclsRecord &Visible; |
4025 | |
4026 | typedef VisibleDeclsRecord::ShadowMap ShadowMap; |
4027 | |
4028 | public: |
4029 | ShadowContextRAII(VisibleDeclsRecord &Visible) : Visible(Visible) { |
4030 | Visible.ShadowMaps.emplace_back(); |
4031 | } |
4032 | |
4033 | ~ShadowContextRAII() { |
4034 | Visible.ShadowMaps.pop_back(); |
4035 | } |
4036 | }; |
4037 | |
4038 | } // end anonymous namespace |
4039 | |
4040 | NamedDecl *VisibleDeclsRecord::checkHidden(NamedDecl *ND) { |
4041 | unsigned IDNS = ND->getIdentifierNamespace(); |
4042 | std::list<ShadowMap>::reverse_iterator SM = ShadowMaps.rbegin(); |
4043 | for (std::list<ShadowMap>::reverse_iterator SMEnd = ShadowMaps.rend(); |
4044 | SM != SMEnd; ++SM) { |
4045 | ShadowMap::iterator Pos = SM->find(Val: ND->getDeclName()); |
4046 | if (Pos == SM->end()) |
4047 | continue; |
4048 | |
4049 | for (auto *D : Pos->second) { |
4050 | // A tag declaration does not hide a non-tag declaration. |
4051 | if (D->hasTagIdentifierNamespace() && |
4052 | (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary | |
4053 | Decl::IDNS_ObjCProtocol))) |
4054 | continue; |
4055 | |
4056 | // Protocols are in distinct namespaces from everything else. |
4057 | if (((D->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol) |
4058 | || (IDNS & Decl::IDNS_ObjCProtocol)) && |
4059 | D->getIdentifierNamespace() != IDNS) |
4060 | continue; |
4061 | |
4062 | // Functions and function templates in the same scope overload |
4063 | // rather than hide. FIXME: Look for hiding based on function |
4064 | // signatures! |
4065 | if (D->getUnderlyingDecl()->isFunctionOrFunctionTemplate() && |
4066 | ND->getUnderlyingDecl()->isFunctionOrFunctionTemplate() && |
4067 | SM == ShadowMaps.rbegin()) |
4068 | continue; |
4069 | |
4070 | // A shadow declaration that's created by a resolved using declaration |
4071 | // is not hidden by the same using declaration. |
4072 | if (isa<UsingShadowDecl>(Val: ND) && isa<UsingDecl>(Val: D) && |
4073 | cast<UsingShadowDecl>(Val: ND)->getIntroducer() == D) |
4074 | continue; |
4075 | |
4076 | // We've found a declaration that hides this one. |
4077 | return D; |
4078 | } |
4079 | } |
4080 | |
4081 | return nullptr; |
4082 | } |
4083 | |
4084 | namespace { |
4085 | class LookupVisibleHelper { |
4086 | public: |
4087 | LookupVisibleHelper(VisibleDeclConsumer &Consumer, bool IncludeDependentBases, |
4088 | bool LoadExternal) |
4089 | : Consumer(Consumer), IncludeDependentBases(IncludeDependentBases), |
4090 | LoadExternal(LoadExternal) {} |
4091 | |
4092 | void lookupVisibleDecls(Sema &SemaRef, Scope *S, Sema::LookupNameKind Kind, |
4093 | bool IncludeGlobalScope) { |
4094 | // Determine the set of using directives available during |
4095 | // unqualified name lookup. |
4096 | Scope *Initial = S; |
4097 | UnqualUsingDirectiveSet UDirs(SemaRef); |
4098 | if (SemaRef.getLangOpts().CPlusPlus) { |
4099 | // Find the first namespace or translation-unit scope. |
4100 | while (S && !isNamespaceOrTranslationUnitScope(S)) |
4101 | S = S->getParent(); |
4102 | |
4103 | UDirs.visitScopeChain(S: Initial, InnermostFileScope: S); |
4104 | } |
4105 | UDirs.done(); |
4106 | |
4107 | // Look for visible declarations. |
4108 | LookupResult Result(SemaRef, DeclarationName(), SourceLocation(), Kind); |
4109 | Result.setAllowHidden(Consumer.includeHiddenDecls()); |
4110 | if (!IncludeGlobalScope) |
4111 | Visited.visitedContext(SemaRef.getASTContext().getTranslationUnitDecl()); |
4112 | ShadowContextRAII Shadow(Visited); |
4113 | lookupInScope(S: Initial, Result, UDirs); |
4114 | } |
4115 | |
4116 | void lookupVisibleDecls(Sema &SemaRef, DeclContext *Ctx, |
4117 | Sema::LookupNameKind Kind, bool IncludeGlobalScope) { |
4118 | LookupResult Result(SemaRef, DeclarationName(), SourceLocation(), Kind); |
4119 | Result.setAllowHidden(Consumer.includeHiddenDecls()); |
4120 | if (!IncludeGlobalScope) |
4121 | Visited.visitedContext(SemaRef.getASTContext().getTranslationUnitDecl()); |
4122 | |
4123 | ShadowContextRAII Shadow(Visited); |
4124 | lookupInDeclContext(Ctx, Result, /*QualifiedNameLookup=*/true, |
4125 | /*InBaseClass=*/false); |
4126 | } |
4127 | |
4128 | private: |
4129 | void lookupInDeclContext(DeclContext *Ctx, LookupResult &Result, |
4130 | bool QualifiedNameLookup, bool InBaseClass) { |
4131 | if (!Ctx) |
4132 | return; |
4133 | |
4134 | // Make sure we don't visit the same context twice. |
4135 | if (Visited.visitedContext(Ctx: Ctx->getPrimaryContext())) |
4136 | return; |
4137 | |
4138 | Consumer.EnteredContext(Ctx); |
4139 | |
4140 | // Outside C++, lookup results for the TU live on identifiers. |
4141 | if (isa<TranslationUnitDecl>(Val: Ctx) && |
4142 | !Result.getSema().getLangOpts().CPlusPlus) { |
4143 | auto &S = Result.getSema(); |
4144 | auto &Idents = S.Context.Idents; |
4145 | |
4146 | // Ensure all external identifiers are in the identifier table. |
4147 | if (LoadExternal) |
4148 | if (IdentifierInfoLookup *External = |
4149 | Idents.getExternalIdentifierLookup()) { |
4150 | std::unique_ptr<IdentifierIterator> Iter(External->getIdentifiers()); |
4151 | for (StringRef Name = Iter->Next(); !Name.empty(); |
4152 | Name = Iter->Next()) |
4153 | Idents.get(Name); |
4154 | } |
4155 | |
4156 | // Walk all lookup results in the TU for each identifier. |
4157 | for (const auto &Ident : Idents) { |
4158 | for (auto I = S.IdResolver.begin(Ident.getValue()), |
4159 | E = S.IdResolver.end(); |
4160 | I != E; ++I) { |
4161 | if (S.IdResolver.isDeclInScope(*I, Ctx)) { |
4162 | if (NamedDecl *ND = Result.getAcceptableDecl(*I)) { |
4163 | Consumer.FoundDecl(ND, Visited.checkHidden(ND), Ctx, InBaseClass); |
4164 | Visited.add(ND); |
4165 | } |
4166 | } |
4167 | } |
4168 | } |
4169 | |
4170 | return; |
4171 | } |
4172 | |
4173 | if (CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(Val: Ctx)) |
4174 | Result.getSema().ForceDeclarationOfImplicitMembers(Class); |
4175 | |
4176 | llvm::SmallVector<NamedDecl *, 4> DeclsToVisit; |
4177 | // We sometimes skip loading namespace-level results (they tend to be huge). |
4178 | bool Load = LoadExternal || |
4179 | !(isa<TranslationUnitDecl>(Val: Ctx) || isa<NamespaceDecl>(Val: Ctx)); |
4180 | // Enumerate all of the results in this context. |
4181 | for (DeclContextLookupResult R : |
4182 | Load ? Ctx->lookups() |
4183 | : Ctx->noload_lookups(/*PreserveInternalState=*/false)) |
4184 | for (auto *D : R) |
4185 | // Rather than visit immediately, we put ND into a vector and visit |
4186 | // all decls, in order, outside of this loop. The reason is that |
4187 | // Consumer.FoundDecl() and LookupResult::getAcceptableDecl(D) |
4188 | // may invalidate the iterators used in the two |
4189 | // loops above. |
4190 | DeclsToVisit.push_back(Elt: D); |
4191 | |
4192 | for (auto *D : DeclsToVisit) |
4193 | if (auto *ND = Result.getAcceptableDecl(D)) { |
4194 | Consumer.FoundDecl(ND, Hiding: Visited.checkHidden(ND), Ctx, InBaseClass); |
4195 | Visited.add(ND); |
4196 | } |
4197 | |
4198 | DeclsToVisit.clear(); |
4199 | |
4200 | // Traverse using directives for qualified name lookup. |
4201 | if (QualifiedNameLookup) { |
4202 | ShadowContextRAII Shadow(Visited); |
4203 | for (auto *I : Ctx->using_directives()) { |
4204 | if (!Result.getSema().isVisible(I)) |
4205 | continue; |
4206 | lookupInDeclContext(I->getNominatedNamespace(), Result, |
4207 | QualifiedNameLookup, InBaseClass); |
4208 | } |
4209 | } |
4210 | |
4211 | // Traverse the contexts of inherited C++ classes. |
4212 | if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Val: Ctx)) { |
4213 | if (!Record->hasDefinition()) |
4214 | return; |
4215 | |
4216 | for (const auto &B : Record->bases()) { |
4217 | QualType BaseType = B.getType(); |
4218 | |
4219 | RecordDecl *RD; |
4220 | if (BaseType->isDependentType()) { |
4221 | if (!IncludeDependentBases) { |
4222 | // Don't look into dependent bases, because name lookup can't look |
4223 | // there anyway. |
4224 | continue; |
4225 | } |
4226 | const auto *TST = BaseType->getAs<TemplateSpecializationType>(); |
4227 | if (!TST) |
4228 | continue; |
4229 | TemplateName TN = TST->getTemplateName(); |
4230 | const auto *TD = |
4231 | dyn_cast_or_null<ClassTemplateDecl>(Val: TN.getAsTemplateDecl()); |
4232 | if (!TD) |
4233 | continue; |
4234 | RD = TD->getTemplatedDecl(); |
4235 | } else { |
4236 | const auto *Record = BaseType->getAs<RecordType>(); |
4237 | if (!Record) |
4238 | continue; |
4239 | RD = Record->getDecl(); |
4240 | } |
4241 | |
4242 | // FIXME: It would be nice to be able to determine whether referencing |
4243 | // a particular member would be ambiguous. For example, given |
4244 | // |
4245 | // struct A { int member; }; |
4246 | // struct B { int member; }; |
4247 | // struct C : A, B { }; |
4248 | // |
4249 | // void f(C *c) { c->### } |
4250 | // |
4251 | // accessing 'member' would result in an ambiguity. However, we |
4252 | // could be smart enough to qualify the member with the base |
4253 | // class, e.g., |
4254 | // |
4255 | // c->B::member |
4256 | // |
4257 | // or |
4258 | // |
4259 | // c->A::member |
4260 | |
4261 | // Find results in this base class (and its bases). |
4262 | ShadowContextRAII Shadow(Visited); |
4263 | lookupInDeclContext(RD, Result, QualifiedNameLookup, |
4264 | /*InBaseClass=*/true); |
4265 | } |
4266 | } |
4267 | |
4268 | // Traverse the contexts of Objective-C classes. |
4269 | if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Val: Ctx)) { |
4270 | // Traverse categories. |
4271 | for (auto *Cat : IFace->visible_categories()) { |
4272 | ShadowContextRAII Shadow(Visited); |
4273 | lookupInDeclContext(Cat, Result, QualifiedNameLookup, |
4274 | /*InBaseClass=*/false); |
4275 | } |
4276 | |
4277 | // Traverse protocols. |
4278 | for (auto *I : IFace->all_referenced_protocols()) { |
4279 | ShadowContextRAII Shadow(Visited); |
4280 | lookupInDeclContext(I, Result, QualifiedNameLookup, |
4281 | /*InBaseClass=*/false); |
4282 | } |
4283 | |
4284 | // Traverse the superclass. |
4285 | if (IFace->getSuperClass()) { |
4286 | ShadowContextRAII Shadow(Visited); |
4287 | lookupInDeclContext(IFace->getSuperClass(), Result, QualifiedNameLookup, |
4288 | /*InBaseClass=*/true); |
4289 | } |
4290 | |
4291 | // If there is an implementation, traverse it. We do this to find |
4292 | // synthesized ivars. |
4293 | if (IFace->getImplementation()) { |
4294 | ShadowContextRAII Shadow(Visited); |
4295 | lookupInDeclContext(IFace->getImplementation(), Result, |
4296 | QualifiedNameLookup, InBaseClass); |
4297 | } |
4298 | } else if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Val: Ctx)) { |
4299 | for (auto *I : Protocol->protocols()) { |
4300 | ShadowContextRAII Shadow(Visited); |
4301 | lookupInDeclContext(I, Result, QualifiedNameLookup, |
4302 | /*InBaseClass=*/false); |
4303 | } |
4304 | } else if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Val: Ctx)) { |
4305 | for (auto *I : Category->protocols()) { |
4306 | ShadowContextRAII Shadow(Visited); |
4307 | lookupInDeclContext(I, Result, QualifiedNameLookup, |
4308 | /*InBaseClass=*/false); |
4309 | } |
4310 | |
4311 | // If there is an implementation, traverse it. |
4312 | if (Category->getImplementation()) { |
4313 | ShadowContextRAII Shadow(Visited); |
4314 | lookupInDeclContext(Category->getImplementation(), Result, |
4315 | QualifiedNameLookup, /*InBaseClass=*/true); |
4316 | } |
4317 | } |
4318 | } |
4319 | |
4320 | void lookupInScope(Scope *S, LookupResult &Result, |
4321 | UnqualUsingDirectiveSet &UDirs) { |
4322 | // No clients run in this mode and it's not supported. Please add tests and |
4323 | // remove the assertion if you start relying on it. |
4324 | assert(!IncludeDependentBases && "Unsupported flag for lookupInScope" ); |
4325 | |
4326 | if (!S) |
4327 | return; |
4328 | |
4329 | if (!S->getEntity() || |
4330 | (!S->getParent() && !Visited.alreadyVisitedContext(Ctx: S->getEntity())) || |
4331 | (S->getEntity())->isFunctionOrMethod()) { |
4332 | FindLocalExternScope FindLocals(Result); |
4333 | // Walk through the declarations in this Scope. The consumer might add new |
4334 | // decls to the scope as part of deserialization, so make a copy first. |
4335 | SmallVector<Decl *, 8> ScopeDecls(S->decls().begin(), S->decls().end()); |
4336 | for (Decl *D : ScopeDecls) { |
4337 | if (NamedDecl *ND = dyn_cast<NamedDecl>(Val: D)) |
4338 | if ((ND = Result.getAcceptableDecl(D: ND))) { |
4339 | Consumer.FoundDecl(ND, Hiding: Visited.checkHidden(ND), Ctx: nullptr, InBaseClass: false); |
4340 | Visited.add(ND); |
4341 | } |
4342 | } |
4343 | } |
4344 | |
4345 | DeclContext *Entity = S->getLookupEntity(); |
4346 | if (Entity) { |
4347 | // Look into this scope's declaration context, along with any of its |
4348 | // parent lookup contexts (e.g., enclosing classes), up to the point |
4349 | // where we hit the context stored in the next outer scope. |
4350 | DeclContext *OuterCtx = findOuterContext(S); |
4351 | |
4352 | for (DeclContext *Ctx = Entity; Ctx && !Ctx->Equals(DC: OuterCtx); |
4353 | Ctx = Ctx->getLookupParent()) { |
4354 | if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Val: Ctx)) { |
4355 | if (Method->isInstanceMethod()) { |
4356 | // For instance methods, look for ivars in the method's interface. |
4357 | LookupResult IvarResult(Result.getSema(), Result.getLookupName(), |
4358 | Result.getNameLoc(), |
4359 | Sema::LookupMemberName); |
4360 | if (ObjCInterfaceDecl *IFace = Method->getClassInterface()) { |
4361 | lookupInDeclContext(IFace, IvarResult, |
4362 | /*QualifiedNameLookup=*/false, |
4363 | /*InBaseClass=*/false); |
4364 | } |
4365 | } |
4366 | |
4367 | // We've already performed all of the name lookup that we need |
4368 | // to for Objective-C methods; the next context will be the |
4369 | // outer scope. |
4370 | break; |
4371 | } |
4372 | |
4373 | if (Ctx->isFunctionOrMethod()) |
4374 | continue; |
4375 | |
4376 | lookupInDeclContext(Ctx, Result, /*QualifiedNameLookup=*/false, |
4377 | /*InBaseClass=*/false); |
4378 | } |
4379 | } else if (!S->getParent()) { |
4380 | // Look into the translation unit scope. We walk through the translation |
4381 | // unit's declaration context, because the Scope itself won't have all of |
4382 | // the declarations if we loaded a precompiled header. |
4383 | // FIXME: We would like the translation unit's Scope object to point to |
4384 | // the translation unit, so we don't need this special "if" branch. |
4385 | // However, doing so would force the normal C++ name-lookup code to look |
4386 | // into the translation unit decl when the IdentifierInfo chains would |
4387 | // suffice. Once we fix that problem (which is part of a more general |
4388 | // "don't look in DeclContexts unless we have to" optimization), we can |
4389 | // eliminate this. |
4390 | Entity = Result.getSema().Context.getTranslationUnitDecl(); |
4391 | lookupInDeclContext(Ctx: Entity, Result, /*QualifiedNameLookup=*/false, |
4392 | /*InBaseClass=*/false); |
4393 | } |
4394 | |
4395 | if (Entity) { |
4396 | // Lookup visible declarations in any namespaces found by using |
4397 | // directives. |
4398 | for (const UnqualUsingEntry &UUE : UDirs.getNamespacesFor(Entity)) |
4399 | lookupInDeclContext( |
4400 | const_cast<DeclContext *>(UUE.getNominatedNamespace()), Result, |
4401 | /*QualifiedNameLookup=*/false, |
4402 | /*InBaseClass=*/false); |
4403 | } |
4404 | |
4405 | // Lookup names in the parent scope. |
4406 | ShadowContextRAII Shadow(Visited); |
4407 | lookupInScope(S: S->getParent(), Result, UDirs); |
4408 | } |
4409 | |
4410 | private: |
4411 | VisibleDeclsRecord Visited; |
4412 | VisibleDeclConsumer &Consumer; |
4413 | bool IncludeDependentBases; |
4414 | bool LoadExternal; |
4415 | }; |
4416 | } // namespace |
4417 | |
4418 | void Sema::LookupVisibleDecls(Scope *S, LookupNameKind Kind, |
4419 | VisibleDeclConsumer &Consumer, |
4420 | bool IncludeGlobalScope, bool LoadExternal) { |
4421 | LookupVisibleHelper H(Consumer, /*IncludeDependentBases=*/false, |
4422 | LoadExternal); |
4423 | H.lookupVisibleDecls(SemaRef&: *this, S, Kind, IncludeGlobalScope); |
4424 | } |
4425 | |
4426 | void Sema::LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind, |
4427 | VisibleDeclConsumer &Consumer, |
4428 | bool IncludeGlobalScope, |
4429 | bool IncludeDependentBases, bool LoadExternal) { |
4430 | LookupVisibleHelper H(Consumer, IncludeDependentBases, LoadExternal); |
4431 | H.lookupVisibleDecls(SemaRef&: *this, Ctx, Kind, IncludeGlobalScope); |
4432 | } |
4433 | |
4434 | /// LookupOrCreateLabel - Do a name lookup of a label with the specified name. |
4435 | /// If GnuLabelLoc is a valid source location, then this is a definition |
4436 | /// of an __label__ label name, otherwise it is a normal label definition |
4437 | /// or use. |
4438 | LabelDecl *Sema::LookupOrCreateLabel(IdentifierInfo *II, SourceLocation Loc, |
4439 | SourceLocation GnuLabelLoc) { |
4440 | // Do a lookup to see if we have a label with this name already. |
4441 | NamedDecl *Res = nullptr; |
4442 | |
4443 | if (GnuLabelLoc.isValid()) { |
4444 | // Local label definitions always shadow existing labels. |
4445 | Res = LabelDecl::Create(C&: Context, DC: CurContext, IdentL: Loc, II, GnuLabelL: GnuLabelLoc); |
4446 | Scope *S = CurScope; |
4447 | PushOnScopeChains(D: Res, S, AddToContext: true); |
4448 | return cast<LabelDecl>(Val: Res); |
4449 | } |
4450 | |
4451 | // Not a GNU local label. |
4452 | Res = LookupSingleName(S: CurScope, Name: II, Loc, NameKind: LookupLabel, |
4453 | Redecl: RedeclarationKind::NotForRedeclaration); |
4454 | // If we found a label, check to see if it is in the same context as us. |
4455 | // When in a Block, we don't want to reuse a label in an enclosing function. |
4456 | if (Res && Res->getDeclContext() != CurContext) |
4457 | Res = nullptr; |
4458 | if (!Res) { |
4459 | // If not forward referenced or defined already, create the backing decl. |
4460 | Res = LabelDecl::Create(C&: Context, DC: CurContext, IdentL: Loc, II); |
4461 | Scope *S = CurScope->getFnParent(); |
4462 | assert(S && "Not in a function?" ); |
4463 | PushOnScopeChains(D: Res, S, AddToContext: true); |
4464 | } |
4465 | return cast<LabelDecl>(Val: Res); |
4466 | } |
4467 | |
4468 | //===----------------------------------------------------------------------===// |
4469 | // Typo correction |
4470 | //===----------------------------------------------------------------------===// |
4471 | |
4472 | static bool isCandidateViable(CorrectionCandidateCallback &CCC, |
4473 | TypoCorrection &Candidate) { |
4474 | Candidate.setCallbackDistance(CCC.RankCandidate(candidate: Candidate)); |
4475 | return Candidate.getEditDistance(Normalized: false) != TypoCorrection::InvalidDistance; |
4476 | } |
4477 | |
4478 | static void LookupPotentialTypoResult(Sema &SemaRef, |
4479 | LookupResult &Res, |
4480 | IdentifierInfo *Name, |
4481 | Scope *S, CXXScopeSpec *SS, |
4482 | DeclContext *MemberContext, |
4483 | bool EnteringContext, |
4484 | bool isObjCIvarLookup, |
4485 | bool FindHidden); |
4486 | |
4487 | /// Check whether the declarations found for a typo correction are |
4488 | /// visible. Set the correction's RequiresImport flag to true if none of the |
4489 | /// declarations are visible, false otherwise. |
4490 | static void checkCorrectionVisibility(Sema &SemaRef, TypoCorrection &TC) { |
4491 | TypoCorrection::decl_iterator DI = TC.begin(), DE = TC.end(); |
4492 | |
4493 | for (/**/; DI != DE; ++DI) |
4494 | if (!LookupResult::isVisible(SemaRef, D: *DI)) |
4495 | break; |
4496 | // No filtering needed if all decls are visible. |
4497 | if (DI == DE) { |
4498 | TC.setRequiresImport(false); |
4499 | return; |
4500 | } |
4501 | |
4502 | llvm::SmallVector<NamedDecl*, 4> NewDecls(TC.begin(), DI); |
4503 | bool AnyVisibleDecls = !NewDecls.empty(); |
4504 | |
4505 | for (/**/; DI != DE; ++DI) { |
4506 | if (LookupResult::isVisible(SemaRef, D: *DI)) { |
4507 | if (!AnyVisibleDecls) { |
4508 | // Found a visible decl, discard all hidden ones. |
4509 | AnyVisibleDecls = true; |
4510 | NewDecls.clear(); |
4511 | } |
4512 | NewDecls.push_back(Elt: *DI); |
4513 | } else if (!AnyVisibleDecls && !(*DI)->isModulePrivate()) |
4514 | NewDecls.push_back(Elt: *DI); |
4515 | } |
4516 | |
4517 | if (NewDecls.empty()) |
4518 | TC = TypoCorrection(); |
4519 | else { |
4520 | TC.setCorrectionDecls(NewDecls); |
4521 | TC.setRequiresImport(!AnyVisibleDecls); |
4522 | } |
4523 | } |
4524 | |
4525 | // Fill the supplied vector with the IdentifierInfo pointers for each piece of |
4526 | // the given NestedNameSpecifier (i.e. given a NestedNameSpecifier "foo::bar::", |
4527 | // fill the vector with the IdentifierInfo pointers for "foo" and "bar"). |
4528 | static void getNestedNameSpecifierIdentifiers( |
4529 | NestedNameSpecifier *NNS, |
4530 | SmallVectorImpl<const IdentifierInfo*> &Identifiers) { |
4531 | if (NestedNameSpecifier *Prefix = NNS->getPrefix()) |
4532 | getNestedNameSpecifierIdentifiers(NNS: Prefix, Identifiers); |
4533 | else |
4534 | Identifiers.clear(); |
4535 | |
4536 | const IdentifierInfo *II = nullptr; |
4537 | |
4538 | switch (NNS->getKind()) { |
4539 | case NestedNameSpecifier::Identifier: |
4540 | II = NNS->getAsIdentifier(); |
4541 | break; |
4542 | |
4543 | case NestedNameSpecifier::Namespace: |
4544 | if (NNS->getAsNamespace()->isAnonymousNamespace()) |
4545 | return; |
4546 | II = NNS->getAsNamespace()->getIdentifier(); |
4547 | break; |
4548 | |
4549 | case NestedNameSpecifier::NamespaceAlias: |
4550 | II = NNS->getAsNamespaceAlias()->getIdentifier(); |
4551 | break; |
4552 | |
4553 | case NestedNameSpecifier::TypeSpecWithTemplate: |
4554 | case NestedNameSpecifier::TypeSpec: |
4555 | II = QualType(NNS->getAsType(), 0).getBaseTypeIdentifier(); |
4556 | break; |
4557 | |
4558 | case NestedNameSpecifier::Global: |
4559 | case NestedNameSpecifier::Super: |
4560 | return; |
4561 | } |
4562 | |
4563 | if (II) |
4564 | Identifiers.push_back(Elt: II); |
4565 | } |
4566 | |
4567 | void TypoCorrectionConsumer::FoundDecl(NamedDecl *ND, NamedDecl *Hiding, |
4568 | DeclContext *Ctx, bool InBaseClass) { |
4569 | // Don't consider hidden names for typo correction. |
4570 | if (Hiding) |
4571 | return; |
4572 | |
4573 | // Only consider entities with identifiers for names, ignoring |
4574 | // special names (constructors, overloaded operators, selectors, |
4575 | // etc.). |
4576 | IdentifierInfo *Name = ND->getIdentifier(); |
4577 | if (!Name) |
4578 | return; |
4579 | |
4580 | // Only consider visible declarations and declarations from modules with |
4581 | // names that exactly match. |
4582 | if (!LookupResult::isVisible(SemaRef, D: ND) && Name != Typo) |
4583 | return; |
4584 | |
4585 | FoundName(Name: Name->getName()); |
4586 | } |
4587 | |
4588 | void TypoCorrectionConsumer::FoundName(StringRef Name) { |
4589 | // Compute the edit distance between the typo and the name of this |
4590 | // entity, and add the identifier to the list of results. |
4591 | addName(Name, ND: nullptr); |
4592 | } |
4593 | |
4594 | void TypoCorrectionConsumer::addKeywordResult(StringRef Keyword) { |
4595 | // Compute the edit distance between the typo and this keyword, |
4596 | // and add the keyword to the list of results. |
4597 | addName(Name: Keyword, ND: nullptr, NNS: nullptr, isKeyword: true); |
4598 | } |
4599 | |
4600 | void TypoCorrectionConsumer::addName(StringRef Name, NamedDecl *ND, |
4601 | NestedNameSpecifier *NNS, bool isKeyword) { |
4602 | // Use a simple length-based heuristic to determine the minimum possible |
4603 | // edit distance. If the minimum isn't good enough, bail out early. |
4604 | StringRef TypoStr = Typo->getName(); |
4605 | unsigned MinED = abs(x: (int)Name.size() - (int)TypoStr.size()); |
4606 | if (MinED && TypoStr.size() / MinED < 3) |
4607 | return; |
4608 | |
4609 | // Compute an upper bound on the allowable edit distance, so that the |
4610 | // edit-distance algorithm can short-circuit. |
4611 | unsigned UpperBound = (TypoStr.size() + 2) / 3; |
4612 | unsigned ED = TypoStr.edit_distance(Other: Name, AllowReplacements: true, MaxEditDistance: UpperBound); |
4613 | if (ED > UpperBound) return; |
4614 | |
4615 | TypoCorrection TC(&SemaRef.Context.Idents.get(Name), ND, NNS, ED); |
4616 | if (isKeyword) TC.makeKeyword(); |
4617 | TC.setCorrectionRange(nullptr, Result.getLookupNameInfo()); |
4618 | addCorrection(Correction: TC); |
4619 | } |
4620 | |
4621 | static const unsigned MaxTypoDistanceResultSets = 5; |
4622 | |
4623 | void TypoCorrectionConsumer::addCorrection(TypoCorrection Correction) { |
4624 | StringRef TypoStr = Typo->getName(); |
4625 | StringRef Name = Correction.getCorrectionAsIdentifierInfo()->getName(); |
4626 | |
4627 | // For very short typos, ignore potential corrections that have a different |
4628 | // base identifier from the typo or which have a normalized edit distance |
4629 | // longer than the typo itself. |
4630 | if (TypoStr.size() < 3 && |
4631 | (Name != TypoStr || Correction.getEditDistance(Normalized: true) > TypoStr.size())) |
4632 | return; |
4633 | |
4634 | // If the correction is resolved but is not viable, ignore it. |
4635 | if (Correction.isResolved()) { |
4636 | checkCorrectionVisibility(SemaRef, TC&: Correction); |
4637 | if (!Correction || !isCandidateViable(CCC&: *CorrectionValidator, Candidate&: Correction)) |
4638 | return; |
4639 | } |
4640 | |
4641 | TypoResultList &CList = |
4642 | CorrectionResults[Correction.getEditDistance(Normalized: false)][Name]; |
4643 | |
4644 | if (!CList.empty() && !CList.back().isResolved()) |
4645 | CList.pop_back(); |
4646 | if (NamedDecl *NewND = Correction.getCorrectionDecl()) { |
4647 | auto RI = llvm::find_if(Range&: CList, P: [NewND](const TypoCorrection &TypoCorr) { |
4648 | return TypoCorr.getCorrectionDecl() == NewND; |
4649 | }); |
4650 | if (RI != CList.end()) { |
4651 | // The Correction refers to a decl already in the list. No insertion is |
4652 | // necessary and all further cases will return. |
4653 | |
4654 | auto IsDeprecated = [](Decl *D) { |
4655 | while (D) { |
4656 | if (D->isDeprecated()) |
4657 | return true; |
4658 | D = llvm::dyn_cast_or_null<NamespaceDecl>(Val: D->getDeclContext()); |
4659 | } |
4660 | return false; |
4661 | }; |
4662 | |
4663 | // Prefer non deprecated Corrections over deprecated and only then |
4664 | // sort using an alphabetical order. |
4665 | std::pair<bool, std::string> NewKey = { |
4666 | IsDeprecated(Correction.getFoundDecl()), |
4667 | Correction.getAsString(LO: SemaRef.getLangOpts())}; |
4668 | |
4669 | std::pair<bool, std::string> PrevKey = { |
4670 | IsDeprecated(RI->getFoundDecl()), |
4671 | RI->getAsString(LO: SemaRef.getLangOpts())}; |
4672 | |
4673 | if (NewKey < PrevKey) |
4674 | *RI = Correction; |
4675 | return; |
4676 | } |
4677 | } |
4678 | if (CList.empty() || Correction.isResolved()) |
4679 | CList.push_back(Elt: Correction); |
4680 | |
4681 | while (CorrectionResults.size() > MaxTypoDistanceResultSets) |
4682 | CorrectionResults.erase(position: std::prev(x: CorrectionResults.end())); |
4683 | } |
4684 | |
4685 | void TypoCorrectionConsumer::addNamespaces( |
4686 | const llvm::MapVector<NamespaceDecl *, bool> &KnownNamespaces) { |
4687 | SearchNamespaces = true; |
4688 | |
4689 | for (auto KNPair : KnownNamespaces) |
4690 | Namespaces.addNameSpecifier(KNPair.first); |
4691 | |
4692 | bool SSIsTemplate = false; |
4693 | if (NestedNameSpecifier *NNS = |
4694 | (SS && SS->isValid()) ? SS->getScopeRep() : nullptr) { |
4695 | if (const Type *T = NNS->getAsType()) |
4696 | SSIsTemplate = T->getTypeClass() == Type::TemplateSpecialization; |
4697 | } |
4698 | // Do not transform this into an iterator-based loop. The loop body can |
4699 | // trigger the creation of further types (through lazy deserialization) and |
4700 | // invalid iterators into this list. |
4701 | auto &Types = SemaRef.getASTContext().getTypes(); |
4702 | for (unsigned I = 0; I != Types.size(); ++I) { |
4703 | const auto *TI = Types[I]; |
4704 | if (CXXRecordDecl *CD = TI->getAsCXXRecordDecl()) { |
4705 | CD = CD->getCanonicalDecl(); |
4706 | if (!CD->isDependentType() && !CD->isAnonymousStructOrUnion() && |
4707 | !CD->isUnion() && CD->getIdentifier() && |
4708 | (SSIsTemplate || !isa<ClassTemplateSpecializationDecl>(Val: CD)) && |
4709 | (CD->isBeingDefined() || CD->isCompleteDefinition())) |
4710 | Namespaces.addNameSpecifier(CD); |
4711 | } |
4712 | } |
4713 | } |
4714 | |
4715 | const TypoCorrection &TypoCorrectionConsumer::getNextCorrection() { |
4716 | if (++CurrentTCIndex < ValidatedCorrections.size()) |
4717 | return ValidatedCorrections[CurrentTCIndex]; |
4718 | |
4719 | CurrentTCIndex = ValidatedCorrections.size(); |
4720 | while (!CorrectionResults.empty()) { |
4721 | auto DI = CorrectionResults.begin(); |
4722 | if (DI->second.empty()) { |
4723 | CorrectionResults.erase(position: DI); |
4724 | continue; |
4725 | } |
4726 | |
4727 | auto RI = DI->second.begin(); |
4728 | if (RI->second.empty()) { |
4729 | DI->second.erase(I: RI); |
4730 | performQualifiedLookups(); |
4731 | continue; |
4732 | } |
4733 | |
4734 | TypoCorrection TC = RI->second.pop_back_val(); |
4735 | if (TC.isResolved() || TC.requiresImport() || resolveCorrection(Candidate&: TC)) { |
4736 | ValidatedCorrections.push_back(Elt: TC); |
4737 | return ValidatedCorrections[CurrentTCIndex]; |
4738 | } |
4739 | } |
4740 | return ValidatedCorrections[0]; // The empty correction. |
4741 | } |
4742 | |
4743 | bool TypoCorrectionConsumer::resolveCorrection(TypoCorrection &Candidate) { |
4744 | IdentifierInfo *Name = Candidate.getCorrectionAsIdentifierInfo(); |
4745 | DeclContext *TempMemberContext = MemberContext; |
4746 | CXXScopeSpec *TempSS = SS.get(); |
4747 | retry_lookup: |
4748 | LookupPotentialTypoResult(SemaRef, Result, Name, S, TempSS, TempMemberContext, |
4749 | EnteringContext, |
4750 | CorrectionValidator->IsObjCIvarLookup, |
4751 | Name == Typo && !Candidate.WillReplaceSpecifier()); |
4752 | switch (Result.getResultKind()) { |
4753 | case LookupResult::NotFound: |
4754 | case LookupResult::NotFoundInCurrentInstantiation: |
4755 | case LookupResult::FoundUnresolvedValue: |
4756 | if (TempSS) { |
4757 | // Immediately retry the lookup without the given CXXScopeSpec |
4758 | TempSS = nullptr; |
4759 | Candidate.WillReplaceSpecifier(ForceReplacement: true); |
4760 | goto retry_lookup; |
4761 | } |
4762 | if (TempMemberContext) { |
4763 | if (SS && !TempSS) |
4764 | TempSS = SS.get(); |
4765 | TempMemberContext = nullptr; |
4766 | goto retry_lookup; |
4767 | } |
4768 | if (SearchNamespaces) |
4769 | QualifiedResults.push_back(Elt: Candidate); |
4770 | break; |
4771 | |
4772 | case LookupResult::Ambiguous: |
4773 | // We don't deal with ambiguities. |
4774 | break; |
4775 | |
4776 | case LookupResult::Found: |
4777 | case LookupResult::FoundOverloaded: |
4778 | // Store all of the Decls for overloaded symbols |
4779 | for (auto *TRD : Result) |
4780 | Candidate.addCorrectionDecl(TRD); |
4781 | checkCorrectionVisibility(SemaRef, TC&: Candidate); |
4782 | if (!isCandidateViable(CCC&: *CorrectionValidator, Candidate)) { |
4783 | if (SearchNamespaces) |
4784 | QualifiedResults.push_back(Elt: Candidate); |
4785 | break; |
4786 | } |
4787 | Candidate.setCorrectionRange(SS.get(), Result.getLookupNameInfo()); |
4788 | return true; |
4789 | } |
4790 | return false; |
4791 | } |
4792 | |
4793 | void TypoCorrectionConsumer::performQualifiedLookups() { |
4794 | unsigned TypoLen = Typo->getName().size(); |
4795 | for (const TypoCorrection &QR : QualifiedResults) { |
4796 | for (const auto &NSI : Namespaces) { |
4797 | DeclContext *Ctx = NSI.DeclCtx; |
4798 | const Type *NSType = NSI.NameSpecifier->getAsType(); |
4799 | |
4800 | // If the current NestedNameSpecifier refers to a class and the |
4801 | // current correction candidate is the name of that class, then skip |
4802 | // it as it is unlikely a qualified version of the class' constructor |
4803 | // is an appropriate correction. |
4804 | if (CXXRecordDecl *NSDecl = NSType ? NSType->getAsCXXRecordDecl() : |
4805 | nullptr) { |
4806 | if (NSDecl->getIdentifier() == QR.getCorrectionAsIdentifierInfo()) |
4807 | continue; |
4808 | } |
4809 | |
4810 | TypoCorrection TC(QR); |
4811 | TC.ClearCorrectionDecls(); |
4812 | TC.setCorrectionSpecifier(NSI.NameSpecifier); |
4813 | TC.setQualifierDistance(NSI.EditDistance); |
4814 | TC.setCallbackDistance(0); // Reset the callback distance |
4815 | |
4816 | // If the current correction candidate and namespace combination are |
4817 | // too far away from the original typo based on the normalized edit |
4818 | // distance, then skip performing a qualified name lookup. |
4819 | unsigned TmpED = TC.getEditDistance(Normalized: true); |
4820 | if (QR.getCorrectionAsIdentifierInfo() != Typo && TmpED && |
4821 | TypoLen / TmpED < 3) |
4822 | continue; |
4823 | |
4824 | Result.clear(); |
4825 | Result.setLookupName(QR.getCorrectionAsIdentifierInfo()); |
4826 | if (!SemaRef.LookupQualifiedName(Result, Ctx)) |
4827 | continue; |
4828 | |
4829 | // Any corrections added below will be validated in subsequent |
4830 | // iterations of the main while() loop over the Consumer's contents. |
4831 | switch (Result.getResultKind()) { |
4832 | case LookupResult::Found: |
4833 | case LookupResult::FoundOverloaded: { |
4834 | if (SS && SS->isValid()) { |
4835 | std::string NewQualified = TC.getAsString(LO: SemaRef.getLangOpts()); |
4836 | std::string OldQualified; |
4837 | llvm::raw_string_ostream OldOStream(OldQualified); |
4838 | SS->getScopeRep()->print(OS&: OldOStream, Policy: SemaRef.getPrintingPolicy()); |
4839 | OldOStream << Typo->getName(); |
4840 | // If correction candidate would be an identical written qualified |
4841 | // identifier, then the existing CXXScopeSpec probably included a |
4842 | // typedef that didn't get accounted for properly. |
4843 | if (OldOStream.str() == NewQualified) |
4844 | break; |
4845 | } |
4846 | for (LookupResult::iterator TRD = Result.begin(), TRDEnd = Result.end(); |
4847 | TRD != TRDEnd; ++TRD) { |
4848 | if (SemaRef.CheckMemberAccess(UseLoc: TC.getCorrectionRange().getBegin(), |
4849 | NamingClass: NSType ? NSType->getAsCXXRecordDecl() |
4850 | : nullptr, |
4851 | Found: TRD.getPair()) == Sema::AR_accessible) |
4852 | TC.addCorrectionDecl(CDecl: *TRD); |
4853 | } |
4854 | if (TC.isResolved()) { |
4855 | TC.setCorrectionRange(SS.get(), Result.getLookupNameInfo()); |
4856 | addCorrection(Correction: TC); |
4857 | } |
4858 | break; |
4859 | } |
4860 | case LookupResult::NotFound: |
4861 | case LookupResult::NotFoundInCurrentInstantiation: |
4862 | case LookupResult::Ambiguous: |
4863 | case LookupResult::FoundUnresolvedValue: |
4864 | break; |
4865 | } |
4866 | } |
4867 | } |
4868 | QualifiedResults.clear(); |
4869 | } |
4870 | |
4871 | TypoCorrectionConsumer::NamespaceSpecifierSet::NamespaceSpecifierSet( |
4872 | ASTContext &Context, DeclContext *CurContext, CXXScopeSpec *CurScopeSpec) |
4873 | : Context(Context), CurContextChain(buildContextChain(Start: CurContext)) { |
4874 | if (NestedNameSpecifier *NNS = |
4875 | CurScopeSpec ? CurScopeSpec->getScopeRep() : nullptr) { |
4876 | llvm::raw_string_ostream SpecifierOStream(CurNameSpecifier); |
4877 | NNS->print(OS&: SpecifierOStream, Policy: Context.getPrintingPolicy()); |
4878 | |
4879 | getNestedNameSpecifierIdentifiers(NNS, Identifiers&: CurNameSpecifierIdentifiers); |
4880 | } |
4881 | // Build the list of identifiers that would be used for an absolute |
4882 | // (from the global context) NestedNameSpecifier referring to the current |
4883 | // context. |
4884 | for (DeclContext *C : llvm::reverse(C&: CurContextChain)) { |
4885 | if (auto *ND = dyn_cast_or_null<NamespaceDecl>(Val: C)) |
4886 | CurContextIdentifiers.push_back(Elt: ND->getIdentifier()); |
4887 | } |
4888 | |
4889 | // Add the global context as a NestedNameSpecifier |
4890 | SpecifierInfo SI = {.DeclCtx: cast<DeclContext>(Val: Context.getTranslationUnitDecl()), |
4891 | .NameSpecifier: NestedNameSpecifier::GlobalSpecifier(Context), .EditDistance: 1}; |
4892 | DistanceMap[1].push_back(Elt: SI); |
4893 | } |
4894 | |
4895 | auto TypoCorrectionConsumer::NamespaceSpecifierSet::buildContextChain( |
4896 | DeclContext *Start) -> DeclContextList { |
4897 | assert(Start && "Building a context chain from a null context" ); |
4898 | DeclContextList Chain; |
4899 | for (DeclContext *DC = Start->getPrimaryContext(); DC != nullptr; |
4900 | DC = DC->getLookupParent()) { |
4901 | NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(Val: DC); |
4902 | if (!DC->isInlineNamespace() && !DC->isTransparentContext() && |
4903 | !(ND && ND->isAnonymousNamespace())) |
4904 | Chain.push_back(Elt: DC->getPrimaryContext()); |
4905 | } |
4906 | return Chain; |
4907 | } |
4908 | |
4909 | unsigned |
4910 | TypoCorrectionConsumer::NamespaceSpecifierSet::buildNestedNameSpecifier( |
4911 | DeclContextList &DeclChain, NestedNameSpecifier *&NNS) { |
4912 | unsigned NumSpecifiers = 0; |
4913 | for (DeclContext *C : llvm::reverse(C&: DeclChain)) { |
4914 | if (auto *ND = dyn_cast_or_null<NamespaceDecl>(Val: C)) { |
4915 | NNS = NestedNameSpecifier::Create(Context, Prefix: NNS, NS: ND); |
4916 | ++NumSpecifiers; |
4917 | } else if (auto *RD = dyn_cast_or_null<RecordDecl>(Val: C)) { |
4918 | NNS = NestedNameSpecifier::Create(Context, NNS, RD->isTemplateDecl(), |
4919 | RD->getTypeForDecl()); |
4920 | ++NumSpecifiers; |
4921 | } |
4922 | } |
4923 | return NumSpecifiers; |
4924 | } |
4925 | |
4926 | void TypoCorrectionConsumer::NamespaceSpecifierSet::addNameSpecifier( |
4927 | DeclContext *Ctx) { |
4928 | NestedNameSpecifier *NNS = nullptr; |
4929 | unsigned NumSpecifiers = 0; |
4930 | DeclContextList NamespaceDeclChain(buildContextChain(Start: Ctx)); |
4931 | DeclContextList FullNamespaceDeclChain(NamespaceDeclChain); |
4932 | |
4933 | // Eliminate common elements from the two DeclContext chains. |
4934 | for (DeclContext *C : llvm::reverse(C&: CurContextChain)) { |
4935 | if (NamespaceDeclChain.empty() || NamespaceDeclChain.back() != C) |
4936 | break; |
4937 | NamespaceDeclChain.pop_back(); |
4938 | } |
4939 | |
4940 | // Build the NestedNameSpecifier from what is left of the NamespaceDeclChain |
4941 | NumSpecifiers = buildNestedNameSpecifier(DeclChain&: NamespaceDeclChain, NNS); |
4942 | |
4943 | // Add an explicit leading '::' specifier if needed. |
4944 | if (NamespaceDeclChain.empty()) { |
4945 | // Rebuild the NestedNameSpecifier as a globally-qualified specifier. |
4946 | NNS = NestedNameSpecifier::GlobalSpecifier(Context); |
4947 | NumSpecifiers = |
4948 | buildNestedNameSpecifier(DeclChain&: FullNamespaceDeclChain, NNS); |
4949 | } else if (NamedDecl *ND = |
4950 | dyn_cast_or_null<NamedDecl>(Val: NamespaceDeclChain.back())) { |
4951 | IdentifierInfo *Name = ND->getIdentifier(); |
4952 | bool SameNameSpecifier = false; |
4953 | if (llvm::is_contained(Range&: CurNameSpecifierIdentifiers, Element: Name)) { |
4954 | std::string NewNameSpecifier; |
4955 | llvm::raw_string_ostream SpecifierOStream(NewNameSpecifier); |
4956 | SmallVector<const IdentifierInfo *, 4> NewNameSpecifierIdentifiers; |
4957 | getNestedNameSpecifierIdentifiers(NNS, Identifiers&: NewNameSpecifierIdentifiers); |
4958 | NNS->print(OS&: SpecifierOStream, Policy: Context.getPrintingPolicy()); |
4959 | SpecifierOStream.flush(); |
4960 | SameNameSpecifier = NewNameSpecifier == CurNameSpecifier; |
4961 | } |
4962 | if (SameNameSpecifier || llvm::is_contained(Range&: CurContextIdentifiers, Element: Name)) { |
4963 | // Rebuild the NestedNameSpecifier as a globally-qualified specifier. |
4964 | NNS = NestedNameSpecifier::GlobalSpecifier(Context); |
4965 | NumSpecifiers = |
4966 | buildNestedNameSpecifier(DeclChain&: FullNamespaceDeclChain, NNS); |
4967 | } |
4968 | } |
4969 | |
4970 | // If the built NestedNameSpecifier would be replacing an existing |
4971 | // NestedNameSpecifier, use the number of component identifiers that |
4972 | // would need to be changed as the edit distance instead of the number |
4973 | // of components in the built NestedNameSpecifier. |
4974 | if (NNS && !CurNameSpecifierIdentifiers.empty()) { |
4975 | SmallVector<const IdentifierInfo*, 4> NewNameSpecifierIdentifiers; |
4976 | getNestedNameSpecifierIdentifiers(NNS, Identifiers&: NewNameSpecifierIdentifiers); |
4977 | NumSpecifiers = |
4978 | llvm::ComputeEditDistance(FromArray: llvm::ArrayRef(CurNameSpecifierIdentifiers), |
4979 | ToArray: llvm::ArrayRef(NewNameSpecifierIdentifiers)); |
4980 | } |
4981 | |
4982 | SpecifierInfo SI = {.DeclCtx: Ctx, .NameSpecifier: NNS, .EditDistance: NumSpecifiers}; |
4983 | DistanceMap[NumSpecifiers].push_back(Elt: SI); |
4984 | } |
4985 | |
4986 | /// Perform name lookup for a possible result for typo correction. |
4987 | static void LookupPotentialTypoResult(Sema &SemaRef, |
4988 | LookupResult &Res, |
4989 | IdentifierInfo *Name, |
4990 | Scope *S, CXXScopeSpec *SS, |
4991 | DeclContext *MemberContext, |
4992 | bool EnteringContext, |
4993 | bool isObjCIvarLookup, |
4994 | bool FindHidden) { |
4995 | Res.suppressDiagnostics(); |
4996 | Res.clear(); |
4997 | Res.setLookupName(Name); |
4998 | Res.setAllowHidden(FindHidden); |
4999 | if (MemberContext) { |
5000 | if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(Val: MemberContext)) { |
5001 | if (isObjCIvarLookup) { |
5002 | if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(IVarName: Name)) { |
5003 | Res.addDecl(Ivar); |
5004 | Res.resolveKind(); |
5005 | return; |
5006 | } |
5007 | } |
5008 | |
5009 | if (ObjCPropertyDecl *Prop = Class->FindPropertyDeclaration( |
5010 | Name, ObjCPropertyQueryKind::OBJC_PR_query_instance)) { |
5011 | Res.addDecl(Prop); |
5012 | Res.resolveKind(); |
5013 | return; |
5014 | } |
5015 | } |
5016 | |
5017 | SemaRef.LookupQualifiedName(R&: Res, LookupCtx: MemberContext); |
5018 | return; |
5019 | } |
5020 | |
5021 | SemaRef.LookupParsedName(R&: Res, S, SS, /*AllowBuiltinCreation=*/false, |
5022 | EnteringContext); |
5023 | |
5024 | // Fake ivar lookup; this should really be part of |
5025 | // LookupParsedName. |
5026 | if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) { |
5027 | if (Method->isInstanceMethod() && Method->getClassInterface() && |
5028 | (Res.empty() || |
5029 | (Res.isSingleResult() && |
5030 | Res.getFoundDecl()->isDefinedOutsideFunctionOrMethod()))) { |
5031 | if (ObjCIvarDecl *IV |
5032 | = Method->getClassInterface()->lookupInstanceVariable(IVarName: Name)) { |
5033 | Res.addDecl(IV); |
5034 | Res.resolveKind(); |
5035 | } |
5036 | } |
5037 | } |
5038 | } |
5039 | |
5040 | /// Add keywords to the consumer as possible typo corrections. |
5041 | static void AddKeywordsToConsumer(Sema &SemaRef, |
5042 | TypoCorrectionConsumer &Consumer, |
5043 | Scope *S, CorrectionCandidateCallback &CCC, |
5044 | bool AfterNestedNameSpecifier) { |
5045 | if (AfterNestedNameSpecifier) { |
5046 | // For 'X::', we know exactly which keywords can appear next. |
5047 | Consumer.addKeywordResult(Keyword: "template" ); |
5048 | if (CCC.WantExpressionKeywords) |
5049 | Consumer.addKeywordResult(Keyword: "operator" ); |
5050 | return; |
5051 | } |
5052 | |
5053 | if (CCC.WantObjCSuper) |
5054 | Consumer.addKeywordResult(Keyword: "super" ); |
5055 | |
5056 | if (CCC.WantTypeSpecifiers) { |
5057 | // Add type-specifier keywords to the set of results. |
5058 | static const char *const CTypeSpecs[] = { |
5059 | "char" , "const" , "double" , "enum" , "float" , "int" , "long" , "short" , |
5060 | "signed" , "struct" , "union" , "unsigned" , "void" , "volatile" , |
5061 | "_Complex" , "_Imaginary" , |
5062 | // storage-specifiers as well |
5063 | "extern" , "inline" , "static" , "typedef" |
5064 | }; |
5065 | |
5066 | for (const auto *CTS : CTypeSpecs) |
5067 | Consumer.addKeywordResult(Keyword: CTS); |
5068 | |
5069 | if (SemaRef.getLangOpts().C99) |
5070 | Consumer.addKeywordResult(Keyword: "restrict" ); |
5071 | if (SemaRef.getLangOpts().Bool || SemaRef.getLangOpts().CPlusPlus) |
5072 | Consumer.addKeywordResult(Keyword: "bool" ); |
5073 | else if (SemaRef.getLangOpts().C99) |
5074 | Consumer.addKeywordResult(Keyword: "_Bool" ); |
5075 | |
5076 | if (SemaRef.getLangOpts().CPlusPlus) { |
5077 | Consumer.addKeywordResult(Keyword: "class" ); |
5078 | Consumer.addKeywordResult(Keyword: "typename" ); |
5079 | Consumer.addKeywordResult(Keyword: "wchar_t" ); |
5080 | |
5081 | if (SemaRef.getLangOpts().CPlusPlus11) { |
5082 | Consumer.addKeywordResult(Keyword: "char16_t" ); |
5083 | Consumer.addKeywordResult(Keyword: "char32_t" ); |
5084 | Consumer.addKeywordResult(Keyword: "constexpr" ); |
5085 | Consumer.addKeywordResult(Keyword: "decltype" ); |
5086 | Consumer.addKeywordResult(Keyword: "thread_local" ); |
5087 | } |
5088 | } |
5089 | |
5090 | if (SemaRef.getLangOpts().GNUKeywords) |
5091 | Consumer.addKeywordResult(Keyword: "typeof" ); |
5092 | } else if (CCC.WantFunctionLikeCasts) { |
5093 | static const char *const CastableTypeSpecs[] = { |
5094 | "char" , "double" , "float" , "int" , "long" , "short" , |
5095 | "signed" , "unsigned" , "void" |
5096 | }; |
5097 | for (auto *kw : CastableTypeSpecs) |
5098 | Consumer.addKeywordResult(Keyword: kw); |
5099 | } |
5100 | |
5101 | if (CCC.WantCXXNamedCasts && SemaRef.getLangOpts().CPlusPlus) { |
5102 | Consumer.addKeywordResult(Keyword: "const_cast" ); |
5103 | Consumer.addKeywordResult(Keyword: "dynamic_cast" ); |
5104 | Consumer.addKeywordResult(Keyword: "reinterpret_cast" ); |
5105 | Consumer.addKeywordResult(Keyword: "static_cast" ); |
5106 | } |
5107 | |
5108 | if (CCC.WantExpressionKeywords) { |
5109 | Consumer.addKeywordResult(Keyword: "sizeof" ); |
5110 | if (SemaRef.getLangOpts().Bool || SemaRef.getLangOpts().CPlusPlus) { |
5111 | Consumer.addKeywordResult(Keyword: "false" ); |
5112 | Consumer.addKeywordResult(Keyword: "true" ); |
5113 | } |
5114 | |
5115 | if (SemaRef.getLangOpts().CPlusPlus) { |
5116 | static const char *const CXXExprs[] = { |
5117 | "delete" , "new" , "operator" , "throw" , "typeid" |
5118 | }; |
5119 | for (const auto *CE : CXXExprs) |
5120 | Consumer.addKeywordResult(Keyword: CE); |
5121 | |
5122 | if (isa<CXXMethodDecl>(Val: SemaRef.CurContext) && |
5123 | cast<CXXMethodDecl>(Val: SemaRef.CurContext)->isInstance()) |
5124 | Consumer.addKeywordResult(Keyword: "this" ); |
5125 | |
5126 | if (SemaRef.getLangOpts().CPlusPlus11) { |
5127 | Consumer.addKeywordResult(Keyword: "alignof" ); |
5128 | Consumer.addKeywordResult(Keyword: "nullptr" ); |
5129 | } |
5130 | } |
5131 | |
5132 | if (SemaRef.getLangOpts().C11) { |
5133 | // FIXME: We should not suggest _Alignof if the alignof macro |
5134 | // is present. |
5135 | Consumer.addKeywordResult(Keyword: "_Alignof" ); |
5136 | } |
5137 | } |
5138 | |
5139 | if (CCC.WantRemainingKeywords) { |
5140 | if (SemaRef.getCurFunctionOrMethodDecl() || SemaRef.getCurBlock()) { |
5141 | // Statements. |
5142 | static const char *const CStmts[] = { |
5143 | "do" , "else" , "for" , "goto" , "if" , "return" , "switch" , "while" }; |
5144 | for (const auto *CS : CStmts) |
5145 | Consumer.addKeywordResult(Keyword: CS); |
5146 | |
5147 | if (SemaRef.getLangOpts().CPlusPlus) { |
5148 | Consumer.addKeywordResult(Keyword: "catch" ); |
5149 | Consumer.addKeywordResult(Keyword: "try" ); |
5150 | } |
5151 | |
5152 | if (S && S->getBreakParent()) |
5153 | Consumer.addKeywordResult(Keyword: "break" ); |
5154 | |
5155 | if (S && S->getContinueParent()) |
5156 | Consumer.addKeywordResult(Keyword: "continue" ); |
5157 | |
5158 | if (SemaRef.getCurFunction() && |
5159 | !SemaRef.getCurFunction()->SwitchStack.empty()) { |
5160 | Consumer.addKeywordResult(Keyword: "case" ); |
5161 | Consumer.addKeywordResult(Keyword: "default" ); |
5162 | } |
5163 | } else { |
5164 | if (SemaRef.getLangOpts().CPlusPlus) { |
5165 | Consumer.addKeywordResult(Keyword: "namespace" ); |
5166 | Consumer.addKeywordResult(Keyword: "template" ); |
5167 | } |
5168 | |
5169 | if (S && S->isClassScope()) { |
5170 | Consumer.addKeywordResult(Keyword: "explicit" ); |
5171 | Consumer.addKeywordResult(Keyword: "friend" ); |
5172 | Consumer.addKeywordResult(Keyword: "mutable" ); |
5173 | Consumer.addKeywordResult(Keyword: "private" ); |
5174 | Consumer.addKeywordResult(Keyword: "protected" ); |
5175 | Consumer.addKeywordResult(Keyword: "public" ); |
5176 | Consumer.addKeywordResult(Keyword: "virtual" ); |
5177 | } |
5178 | } |
5179 | |
5180 | if (SemaRef.getLangOpts().CPlusPlus) { |
5181 | Consumer.addKeywordResult(Keyword: "using" ); |
5182 | |
5183 | if (SemaRef.getLangOpts().CPlusPlus11) |
5184 | Consumer.addKeywordResult(Keyword: "static_assert" ); |
5185 | } |
5186 | } |
5187 | } |
5188 | |
5189 | std::unique_ptr<TypoCorrectionConsumer> Sema::makeTypoCorrectionConsumer( |
5190 | const DeclarationNameInfo &TypoName, Sema::LookupNameKind LookupKind, |
5191 | Scope *S, CXXScopeSpec *SS, CorrectionCandidateCallback &CCC, |
5192 | DeclContext *MemberContext, bool EnteringContext, |
5193 | const ObjCObjectPointerType *OPT, bool ErrorRecovery) { |
5194 | |
5195 | if (Diags.hasFatalErrorOccurred() || !getLangOpts().SpellChecking || |
5196 | DisableTypoCorrection) |
5197 | return nullptr; |
5198 | |
5199 | // In Microsoft mode, don't perform typo correction in a template member |
5200 | // function dependent context because it interferes with the "lookup into |
5201 | // dependent bases of class templates" feature. |
5202 | if (getLangOpts().MSVCCompat && CurContext->isDependentContext() && |
5203 | isa<CXXMethodDecl>(Val: CurContext)) |
5204 | return nullptr; |
5205 | |
5206 | // We only attempt to correct typos for identifiers. |
5207 | IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo(); |
5208 | if (!Typo) |
5209 | return nullptr; |
5210 | |
5211 | // If the scope specifier itself was invalid, don't try to correct |
5212 | // typos. |
5213 | if (SS && SS->isInvalid()) |
5214 | return nullptr; |
5215 | |
5216 | // Never try to correct typos during any kind of code synthesis. |
5217 | if (!CodeSynthesisContexts.empty()) |
5218 | return nullptr; |
5219 | |
5220 | // Don't try to correct 'super'. |
5221 | if (S && S->isInObjcMethodScope() && Typo == getSuperIdentifier()) |
5222 | return nullptr; |
5223 | |
5224 | // Abort if typo correction already failed for this specific typo. |
5225 | IdentifierSourceLocations::iterator locs = TypoCorrectionFailures.find(Val: Typo); |
5226 | if (locs != TypoCorrectionFailures.end() && |
5227 | locs->second.count(V: TypoName.getLoc())) |
5228 | return nullptr; |
5229 | |
5230 | // Don't try to correct the identifier "vector" when in AltiVec mode. |
5231 | // TODO: Figure out why typo correction misbehaves in this case, fix it, and |
5232 | // remove this workaround. |
5233 | if ((getLangOpts().AltiVec || getLangOpts().ZVector) && Typo->isStr(Str: "vector" )) |
5234 | return nullptr; |
5235 | |
5236 | // Provide a stop gap for files that are just seriously broken. Trying |
5237 | // to correct all typos can turn into a HUGE performance penalty, causing |
5238 | // some files to take minutes to get rejected by the parser. |
5239 | unsigned Limit = getDiagnostics().getDiagnosticOptions().SpellCheckingLimit; |
5240 | if (Limit && TyposCorrected >= Limit) |
5241 | return nullptr; |
5242 | ++TyposCorrected; |
5243 | |
5244 | // If we're handling a missing symbol error, using modules, and the |
5245 | // special search all modules option is used, look for a missing import. |
5246 | if (ErrorRecovery && getLangOpts().Modules && |
5247 | getLangOpts().ModulesSearchAll) { |
5248 | // The following has the side effect of loading the missing module. |
5249 | getModuleLoader().lookupMissingImports(Name: Typo->getName(), |
5250 | TriggerLoc: TypoName.getBeginLoc()); |
5251 | } |
5252 | |
5253 | // Extend the lifetime of the callback. We delayed this until here |
5254 | // to avoid allocations in the hot path (which is where no typo correction |
5255 | // occurs). Note that CorrectionCandidateCallback is polymorphic and |
5256 | // initially stack-allocated. |
5257 | std::unique_ptr<CorrectionCandidateCallback> ClonedCCC = CCC.clone(); |
5258 | auto Consumer = std::make_unique<TypoCorrectionConsumer>( |
5259 | args&: *this, args: TypoName, args&: LookupKind, args&: S, args&: SS, args: std::move(ClonedCCC), args&: MemberContext, |
5260 | args&: EnteringContext); |
5261 | |
5262 | // Perform name lookup to find visible, similarly-named entities. |
5263 | bool IsUnqualifiedLookup = false; |
5264 | DeclContext *QualifiedDC = MemberContext; |
5265 | if (MemberContext) { |
5266 | LookupVisibleDecls(MemberContext, LookupKind, *Consumer); |
5267 | |
5268 | // Look in qualified interfaces. |
5269 | if (OPT) { |
5270 | for (auto *I : OPT->quals()) |
5271 | LookupVisibleDecls(I, LookupKind, *Consumer); |
5272 | } |
5273 | } else if (SS && SS->isSet()) { |
5274 | QualifiedDC = computeDeclContext(SS: *SS, EnteringContext); |
5275 | if (!QualifiedDC) |
5276 | return nullptr; |
5277 | |
5278 | LookupVisibleDecls(QualifiedDC, LookupKind, *Consumer); |
5279 | } else { |
5280 | IsUnqualifiedLookup = true; |
5281 | } |
5282 | |
5283 | // Determine whether we are going to search in the various namespaces for |
5284 | // corrections. |
5285 | bool SearchNamespaces |
5286 | = getLangOpts().CPlusPlus && |
5287 | (IsUnqualifiedLookup || (SS && SS->isSet())); |
5288 | |
5289 | if (IsUnqualifiedLookup || SearchNamespaces) { |
5290 | // For unqualified lookup, look through all of the names that we have |
5291 | // seen in this translation unit. |
5292 | // FIXME: Re-add the ability to skip very unlikely potential corrections. |
5293 | for (const auto &I : Context.Idents) |
5294 | Consumer->FoundName(I.getKey()); |
5295 | |
5296 | // Walk through identifiers in external identifier sources. |
5297 | // FIXME: Re-add the ability to skip very unlikely potential corrections. |
5298 | if (IdentifierInfoLookup *External |
5299 | = Context.Idents.getExternalIdentifierLookup()) { |
5300 | std::unique_ptr<IdentifierIterator> Iter(External->getIdentifiers()); |
5301 | do { |
5302 | StringRef Name = Iter->Next(); |
5303 | if (Name.empty()) |
5304 | break; |
5305 | |
5306 | Consumer->FoundName(Name); |
5307 | } while (true); |
5308 | } |
5309 | } |
5310 | |
5311 | AddKeywordsToConsumer(SemaRef&: *this, Consumer&: *Consumer, S, |
5312 | CCC&: *Consumer->getCorrectionValidator(), |
5313 | AfterNestedNameSpecifier: SS && SS->isNotEmpty()); |
5314 | |
5315 | // Build the NestedNameSpecifiers for the KnownNamespaces, if we're going |
5316 | // to search those namespaces. |
5317 | if (SearchNamespaces) { |
5318 | // Load any externally-known namespaces. |
5319 | if (ExternalSource && !LoadedExternalKnownNamespaces) { |
5320 | SmallVector<NamespaceDecl *, 4> ExternalKnownNamespaces; |
5321 | LoadedExternalKnownNamespaces = true; |
5322 | ExternalSource->ReadKnownNamespaces(Namespaces&: ExternalKnownNamespaces); |
5323 | for (auto *N : ExternalKnownNamespaces) |
5324 | KnownNamespaces[N] = true; |
5325 | } |
5326 | |
5327 | Consumer->addNamespaces(KnownNamespaces); |
5328 | } |
5329 | |
5330 | return Consumer; |
5331 | } |
5332 | |
5333 | /// Try to "correct" a typo in the source code by finding |
5334 | /// visible declarations whose names are similar to the name that was |
5335 | /// present in the source code. |
5336 | /// |
5337 | /// \param TypoName the \c DeclarationNameInfo structure that contains |
5338 | /// the name that was present in the source code along with its location. |
5339 | /// |
5340 | /// \param LookupKind the name-lookup criteria used to search for the name. |
5341 | /// |
5342 | /// \param S the scope in which name lookup occurs. |
5343 | /// |
5344 | /// \param SS the nested-name-specifier that precedes the name we're |
5345 | /// looking for, if present. |
5346 | /// |
5347 | /// \param CCC A CorrectionCandidateCallback object that provides further |
5348 | /// validation of typo correction candidates. It also provides flags for |
5349 | /// determining the set of keywords permitted. |
5350 | /// |
5351 | /// \param MemberContext if non-NULL, the context in which to look for |
5352 | /// a member access expression. |
5353 | /// |
5354 | /// \param EnteringContext whether we're entering the context described by |
5355 | /// the nested-name-specifier SS. |
5356 | /// |
5357 | /// \param OPT when non-NULL, the search for visible declarations will |
5358 | /// also walk the protocols in the qualified interfaces of \p OPT. |
5359 | /// |
5360 | /// \returns a \c TypoCorrection containing the corrected name if the typo |
5361 | /// along with information such as the \c NamedDecl where the corrected name |
5362 | /// was declared, and any additional \c NestedNameSpecifier needed to access |
5363 | /// it (C++ only). The \c TypoCorrection is empty if there is no correction. |
5364 | TypoCorrection Sema::CorrectTypo(const DeclarationNameInfo &TypoName, |
5365 | Sema::LookupNameKind LookupKind, |
5366 | Scope *S, CXXScopeSpec *SS, |
5367 | CorrectionCandidateCallback &CCC, |
5368 | CorrectTypoKind Mode, |
5369 | DeclContext *MemberContext, |
5370 | bool EnteringContext, |
5371 | const ObjCObjectPointerType *OPT, |
5372 | bool RecordFailure) { |
5373 | // Always let the ExternalSource have the first chance at correction, even |
5374 | // if we would otherwise have given up. |
5375 | if (ExternalSource) { |
5376 | if (TypoCorrection Correction = |
5377 | ExternalSource->CorrectTypo(Typo: TypoName, LookupKind, S, SS, CCC, |
5378 | MemberContext, EnteringContext, OPT)) |
5379 | return Correction; |
5380 | } |
5381 | |
5382 | // Ugly hack equivalent to CTC == CTC_ObjCMessageReceiver; |
5383 | // WantObjCSuper is only true for CTC_ObjCMessageReceiver and for |
5384 | // some instances of CTC_Unknown, while WantRemainingKeywords is true |
5385 | // for CTC_Unknown but not for CTC_ObjCMessageReceiver. |
5386 | bool ObjCMessageReceiver = CCC.WantObjCSuper && !CCC.WantRemainingKeywords; |
5387 | |
5388 | IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo(); |
5389 | auto Consumer = makeTypoCorrectionConsumer(TypoName, LookupKind, S, SS, CCC, |
5390 | MemberContext, EnteringContext, |
5391 | OPT, ErrorRecovery: Mode == CTK_ErrorRecovery); |
5392 | |
5393 | if (!Consumer) |
5394 | return TypoCorrection(); |
5395 | |
5396 | // If we haven't found anything, we're done. |
5397 | if (Consumer->empty()) |
5398 | return FailedCorrection(Typo, TypoLoc: TypoName.getLoc(), RecordFailure); |
5399 | |
5400 | // Make sure the best edit distance (prior to adding any namespace qualifiers) |
5401 | // is not more that about a third of the length of the typo's identifier. |
5402 | unsigned ED = Consumer->getBestEditDistance(Normalized: true); |
5403 | unsigned TypoLen = Typo->getName().size(); |
5404 | if (ED > 0 && TypoLen / ED < 3) |
5405 | return FailedCorrection(Typo, TypoLoc: TypoName.getLoc(), RecordFailure); |
5406 | |
5407 | TypoCorrection BestTC = Consumer->getNextCorrection(); |
5408 | TypoCorrection SecondBestTC = Consumer->getNextCorrection(); |
5409 | if (!BestTC) |
5410 | return FailedCorrection(Typo, TypoLoc: TypoName.getLoc(), RecordFailure); |
5411 | |
5412 | ED = BestTC.getEditDistance(); |
5413 | |
5414 | if (TypoLen >= 3 && ED > 0 && TypoLen / ED < 3) { |
5415 | // If this was an unqualified lookup and we believe the callback |
5416 | // object wouldn't have filtered out possible corrections, note |
5417 | // that no correction was found. |
5418 | return FailedCorrection(Typo, TypoLoc: TypoName.getLoc(), RecordFailure); |
5419 | } |
5420 | |
5421 | // If only a single name remains, return that result. |
5422 | if (!SecondBestTC || |
5423 | SecondBestTC.getEditDistance(Normalized: false) > BestTC.getEditDistance(Normalized: false)) { |
5424 | const TypoCorrection &Result = BestTC; |
5425 | |
5426 | // Don't correct to a keyword that's the same as the typo; the keyword |
5427 | // wasn't actually in scope. |
5428 | if (ED == 0 && Result.isKeyword()) |
5429 | return FailedCorrection(Typo, TypoLoc: TypoName.getLoc(), RecordFailure); |
5430 | |
5431 | TypoCorrection TC = Result; |
5432 | TC.setCorrectionRange(SS, TypoName); |
5433 | checkCorrectionVisibility(SemaRef&: *this, TC); |
5434 | return TC; |
5435 | } else if (SecondBestTC && ObjCMessageReceiver) { |
5436 | // Prefer 'super' when we're completing in a message-receiver |
5437 | // context. |
5438 | |
5439 | if (BestTC.getCorrection().getAsString() != "super" ) { |
5440 | if (SecondBestTC.getCorrection().getAsString() == "super" ) |
5441 | BestTC = SecondBestTC; |
5442 | else if ((*Consumer)["super" ].front().isKeyword()) |
5443 | BestTC = (*Consumer)["super" ].front(); |
5444 | } |
5445 | // Don't correct to a keyword that's the same as the typo; the keyword |
5446 | // wasn't actually in scope. |
5447 | if (BestTC.getEditDistance() == 0 || |
5448 | BestTC.getCorrection().getAsString() != "super" ) |
5449 | return FailedCorrection(Typo, TypoLoc: TypoName.getLoc(), RecordFailure); |
5450 | |
5451 | BestTC.setCorrectionRange(SS, TypoName); |
5452 | return BestTC; |
5453 | } |
5454 | |
5455 | // Record the failure's location if needed and return an empty correction. If |
5456 | // this was an unqualified lookup and we believe the callback object did not |
5457 | // filter out possible corrections, also cache the failure for the typo. |
5458 | return FailedCorrection(Typo, TypoLoc: TypoName.getLoc(), RecordFailure: RecordFailure && !SecondBestTC); |
5459 | } |
5460 | |
5461 | /// Try to "correct" a typo in the source code by finding |
5462 | /// visible declarations whose names are similar to the name that was |
5463 | /// present in the source code. |
5464 | /// |
5465 | /// \param TypoName the \c DeclarationNameInfo structure that contains |
5466 | /// the name that was present in the source code along with its location. |
5467 | /// |
5468 | /// \param LookupKind the name-lookup criteria used to search for the name. |
5469 | /// |
5470 | /// \param S the scope in which name lookup occurs. |
5471 | /// |
5472 | /// \param SS the nested-name-specifier that precedes the name we're |
5473 | /// looking for, if present. |
5474 | /// |
5475 | /// \param CCC A CorrectionCandidateCallback object that provides further |
5476 | /// validation of typo correction candidates. It also provides flags for |
5477 | /// determining the set of keywords permitted. |
5478 | /// |
5479 | /// \param TDG A TypoDiagnosticGenerator functor that will be used to print |
5480 | /// diagnostics when the actual typo correction is attempted. |
5481 | /// |
5482 | /// \param TRC A TypoRecoveryCallback functor that will be used to build an |
5483 | /// Expr from a typo correction candidate. |
5484 | /// |
5485 | /// \param MemberContext if non-NULL, the context in which to look for |
5486 | /// a member access expression. |
5487 | /// |
5488 | /// \param EnteringContext whether we're entering the context described by |
5489 | /// the nested-name-specifier SS. |
5490 | /// |
5491 | /// \param OPT when non-NULL, the search for visible declarations will |
5492 | /// also walk the protocols in the qualified interfaces of \p OPT. |
5493 | /// |
5494 | /// \returns a new \c TypoExpr that will later be replaced in the AST with an |
5495 | /// Expr representing the result of performing typo correction, or nullptr if |
5496 | /// typo correction is not possible. If nullptr is returned, no diagnostics will |
5497 | /// be emitted and it is the responsibility of the caller to emit any that are |
5498 | /// needed. |
5499 | TypoExpr *Sema::CorrectTypoDelayed( |
5500 | const DeclarationNameInfo &TypoName, Sema::LookupNameKind LookupKind, |
5501 | Scope *S, CXXScopeSpec *SS, CorrectionCandidateCallback &CCC, |
5502 | TypoDiagnosticGenerator TDG, TypoRecoveryCallback TRC, CorrectTypoKind Mode, |
5503 | DeclContext *MemberContext, bool EnteringContext, |
5504 | const ObjCObjectPointerType *OPT) { |
5505 | auto Consumer = makeTypoCorrectionConsumer(TypoName, LookupKind, S, SS, CCC, |
5506 | MemberContext, EnteringContext, |
5507 | OPT, ErrorRecovery: Mode == CTK_ErrorRecovery); |
5508 | |
5509 | // Give the external sema source a chance to correct the typo. |
5510 | TypoCorrection ExternalTypo; |
5511 | if (ExternalSource && Consumer) { |
5512 | ExternalTypo = ExternalSource->CorrectTypo( |
5513 | Typo: TypoName, LookupKind, S, SS, CCC&: *Consumer->getCorrectionValidator(), |
5514 | MemberContext, EnteringContext, OPT); |
5515 | if (ExternalTypo) |
5516 | Consumer->addCorrection(Correction: ExternalTypo); |
5517 | } |
5518 | |
5519 | if (!Consumer || Consumer->empty()) |
5520 | return nullptr; |
5521 | |
5522 | // Make sure the best edit distance (prior to adding any namespace qualifiers) |
5523 | // is not more that about a third of the length of the typo's identifier. |
5524 | unsigned ED = Consumer->getBestEditDistance(Normalized: true); |
5525 | IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo(); |
5526 | if (!ExternalTypo && ED > 0 && Typo->getName().size() / ED < 3) |
5527 | return nullptr; |
5528 | ExprEvalContexts.back().NumTypos++; |
5529 | return createDelayedTypo(TCC: std::move(Consumer), TDG: std::move(TDG), TRC: std::move(TRC), |
5530 | TypoLoc: TypoName.getLoc()); |
5531 | } |
5532 | |
5533 | void TypoCorrection::addCorrectionDecl(NamedDecl *CDecl) { |
5534 | if (!CDecl) return; |
5535 | |
5536 | if (isKeyword()) |
5537 | CorrectionDecls.clear(); |
5538 | |
5539 | CorrectionDecls.push_back(Elt: CDecl); |
5540 | |
5541 | if (!CorrectionName) |
5542 | CorrectionName = CDecl->getDeclName(); |
5543 | } |
5544 | |
5545 | std::string TypoCorrection::getAsString(const LangOptions &LO) const { |
5546 | if (CorrectionNameSpec) { |
5547 | std::string tmpBuffer; |
5548 | llvm::raw_string_ostream PrefixOStream(tmpBuffer); |
5549 | CorrectionNameSpec->print(OS&: PrefixOStream, Policy: PrintingPolicy(LO)); |
5550 | PrefixOStream << CorrectionName; |
5551 | return PrefixOStream.str(); |
5552 | } |
5553 | |
5554 | return CorrectionName.getAsString(); |
5555 | } |
5556 | |
5557 | bool CorrectionCandidateCallback::ValidateCandidate( |
5558 | const TypoCorrection &candidate) { |
5559 | if (!candidate.isResolved()) |
5560 | return true; |
5561 | |
5562 | if (candidate.isKeyword()) |
5563 | return WantTypeSpecifiers || WantExpressionKeywords || WantCXXNamedCasts || |
5564 | WantRemainingKeywords || WantObjCSuper; |
5565 | |
5566 | bool HasNonType = false; |
5567 | bool HasStaticMethod = false; |
5568 | bool HasNonStaticMethod = false; |
5569 | for (Decl *D : candidate) { |
5570 | if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(Val: D)) |
5571 | D = FTD->getTemplatedDecl(); |
5572 | if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: D)) { |
5573 | if (Method->isStatic()) |
5574 | HasStaticMethod = true; |
5575 | else |
5576 | HasNonStaticMethod = true; |
5577 | } |
5578 | if (!isa<TypeDecl>(Val: D)) |
5579 | HasNonType = true; |
5580 | } |
5581 | |
5582 | if (IsAddressOfOperand && HasNonStaticMethod && !HasStaticMethod && |
5583 | !candidate.getCorrectionSpecifier()) |
5584 | return false; |
5585 | |
5586 | return WantTypeSpecifiers || HasNonType; |
5587 | } |
5588 | |
5589 | FunctionCallFilterCCC::FunctionCallFilterCCC(Sema &SemaRef, unsigned NumArgs, |
5590 | bool HasExplicitTemplateArgs, |
5591 | MemberExpr *ME) |
5592 | : NumArgs(NumArgs), HasExplicitTemplateArgs(HasExplicitTemplateArgs), |
5593 | CurContext(SemaRef.CurContext), MemberFn(ME) { |
5594 | WantTypeSpecifiers = false; |
5595 | WantFunctionLikeCasts = SemaRef.getLangOpts().CPlusPlus && |
5596 | !HasExplicitTemplateArgs && NumArgs == 1; |
5597 | WantCXXNamedCasts = HasExplicitTemplateArgs && NumArgs == 1; |
5598 | WantRemainingKeywords = false; |
5599 | } |
5600 | |
5601 | bool FunctionCallFilterCCC::ValidateCandidate(const TypoCorrection &candidate) { |
5602 | if (!candidate.getCorrectionDecl()) |
5603 | return candidate.isKeyword(); |
5604 | |
5605 | for (auto *C : candidate) { |
5606 | FunctionDecl *FD = nullptr; |
5607 | NamedDecl *ND = C->getUnderlyingDecl(); |
5608 | if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(Val: ND)) |
5609 | FD = FTD->getTemplatedDecl(); |
5610 | if (!HasExplicitTemplateArgs && !FD) { |
5611 | if (!(FD = dyn_cast<FunctionDecl>(Val: ND)) && isa<ValueDecl>(Val: ND)) { |
5612 | // If the Decl is neither a function nor a template function, |
5613 | // determine if it is a pointer or reference to a function. If so, |
5614 | // check against the number of arguments expected for the pointee. |
5615 | QualType ValType = cast<ValueDecl>(Val: ND)->getType(); |
5616 | if (ValType.isNull()) |
5617 | continue; |
5618 | if (ValType->isAnyPointerType() || ValType->isReferenceType()) |
5619 | ValType = ValType->getPointeeType(); |
5620 | if (const FunctionProtoType *FPT = ValType->getAs<FunctionProtoType>()) |
5621 | if (FPT->getNumParams() == NumArgs) |
5622 | return true; |
5623 | } |
5624 | } |
5625 | |
5626 | // A typo for a function-style cast can look like a function call in C++. |
5627 | if ((HasExplicitTemplateArgs ? getAsTypeTemplateDecl(ND) != nullptr |
5628 | : isa<TypeDecl>(Val: ND)) && |
5629 | CurContext->getParentASTContext().getLangOpts().CPlusPlus) |
5630 | // Only a class or class template can take two or more arguments. |
5631 | return NumArgs <= 1 || HasExplicitTemplateArgs || isa<CXXRecordDecl>(Val: ND); |
5632 | |
5633 | // Skip the current candidate if it is not a FunctionDecl or does not accept |
5634 | // the current number of arguments. |
5635 | if (!FD || !(FD->getNumParams() >= NumArgs && |
5636 | FD->getMinRequiredArguments() <= NumArgs)) |
5637 | continue; |
5638 | |
5639 | // If the current candidate is a non-static C++ method, skip the candidate |
5640 | // unless the method being corrected--or the current DeclContext, if the |
5641 | // function being corrected is not a method--is a method in the same class |
5642 | // or a descendent class of the candidate's parent class. |
5643 | if (const auto *MD = dyn_cast<CXXMethodDecl>(Val: FD)) { |
5644 | if (MemberFn || !MD->isStatic()) { |
5645 | const auto *CurMD = |
5646 | MemberFn |
5647 | ? dyn_cast_if_present<CXXMethodDecl>(Val: MemberFn->getMemberDecl()) |
5648 | : dyn_cast_if_present<CXXMethodDecl>(Val: CurContext); |
5649 | const CXXRecordDecl *CurRD = |
5650 | CurMD ? CurMD->getParent()->getCanonicalDecl() : nullptr; |
5651 | const CXXRecordDecl *RD = MD->getParent()->getCanonicalDecl(); |
5652 | if (!CurRD || (CurRD != RD && !CurRD->isDerivedFrom(Base: RD))) |
5653 | continue; |
5654 | } |
5655 | } |
5656 | return true; |
5657 | } |
5658 | return false; |
5659 | } |
5660 | |
5661 | void Sema::diagnoseTypo(const TypoCorrection &Correction, |
5662 | const PartialDiagnostic &TypoDiag, |
5663 | bool ErrorRecovery) { |
5664 | diagnoseTypo(Correction, TypoDiag, PDiag(diag::note_previous_decl), |
5665 | ErrorRecovery); |
5666 | } |
5667 | |
5668 | /// Find which declaration we should import to provide the definition of |
5669 | /// the given declaration. |
5670 | static const NamedDecl *getDefinitionToImport(const NamedDecl *D) { |
5671 | if (const auto *VD = dyn_cast<VarDecl>(Val: D)) |
5672 | return VD->getDefinition(); |
5673 | if (const auto *FD = dyn_cast<FunctionDecl>(Val: D)) |
5674 | return FD->getDefinition(); |
5675 | if (const auto *TD = dyn_cast<TagDecl>(Val: D)) |
5676 | return TD->getDefinition(); |
5677 | if (const auto *ID = dyn_cast<ObjCInterfaceDecl>(Val: D)) |
5678 | return ID->getDefinition(); |
5679 | if (const auto *PD = dyn_cast<ObjCProtocolDecl>(Val: D)) |
5680 | return PD->getDefinition(); |
5681 | if (const auto *TD = dyn_cast<TemplateDecl>(Val: D)) |
5682 | if (const NamedDecl *TTD = TD->getTemplatedDecl()) |
5683 | return getDefinitionToImport(D: TTD); |
5684 | return nullptr; |
5685 | } |
5686 | |
5687 | void Sema::diagnoseMissingImport(SourceLocation Loc, const NamedDecl *Decl, |
5688 | MissingImportKind MIK, bool Recover) { |
5689 | // Suggest importing a module providing the definition of this entity, if |
5690 | // possible. |
5691 | const NamedDecl *Def = getDefinitionToImport(D: Decl); |
5692 | if (!Def) |
5693 | Def = Decl; |
5694 | |
5695 | Module *Owner = getOwningModule(Def); |
5696 | assert(Owner && "definition of hidden declaration is not in a module" ); |
5697 | |
5698 | llvm::SmallVector<Module*, 8> OwningModules; |
5699 | OwningModules.push_back(Elt: Owner); |
5700 | auto Merged = Context.getModulesWithMergedDefinition(Def); |
5701 | OwningModules.insert(I: OwningModules.end(), From: Merged.begin(), To: Merged.end()); |
5702 | |
5703 | diagnoseMissingImport(Loc, Def, Def->getLocation(), OwningModules, MIK, |
5704 | Recover); |
5705 | } |
5706 | |
5707 | /// Get a "quoted.h" or <angled.h> include path to use in a diagnostic |
5708 | /// suggesting the addition of a #include of the specified file. |
5709 | static std::string (Preprocessor &PP, FileEntryRef E, |
5710 | llvm::StringRef IncludingFile) { |
5711 | bool IsAngled = false; |
5712 | auto Path = PP.getHeaderSearchInfo().suggestPathToFileForDiagnostics( |
5713 | File: E, MainFile: IncludingFile, IsAngled: &IsAngled); |
5714 | return (IsAngled ? '<' : '"') + Path + (IsAngled ? '>' : '"'); |
5715 | } |
5716 | |
5717 | void Sema::diagnoseMissingImport(SourceLocation UseLoc, const NamedDecl *Decl, |
5718 | SourceLocation DeclLoc, |
5719 | ArrayRef<Module *> Modules, |
5720 | MissingImportKind MIK, bool Recover) { |
5721 | assert(!Modules.empty()); |
5722 | |
5723 | // See https://github.com/llvm/llvm-project/issues/73893. It is generally |
5724 | // confusing than helpful to show the namespace is not visible. |
5725 | if (isa<NamespaceDecl>(Val: Decl)) |
5726 | return; |
5727 | |
5728 | auto NotePrevious = [&] { |
5729 | // FIXME: Suppress the note backtrace even under |
5730 | // -fdiagnostics-show-note-include-stack. We don't care how this |
5731 | // declaration was previously reached. |
5732 | Diag(DeclLoc, diag::note_unreachable_entity) << (int)MIK; |
5733 | }; |
5734 | |
5735 | // Weed out duplicates from module list. |
5736 | llvm::SmallVector<Module*, 8> UniqueModules; |
5737 | llvm::SmallDenseSet<Module*, 8> UniqueModuleSet; |
5738 | for (auto *M : Modules) { |
5739 | if (M->isExplicitGlobalModule() || M->isPrivateModule()) |
5740 | continue; |
5741 | if (UniqueModuleSet.insert(V: M).second) |
5742 | UniqueModules.push_back(Elt: M); |
5743 | } |
5744 | |
5745 | // Try to find a suitable header-name to #include. |
5746 | std::string ; |
5747 | if (OptionalFileEntryRef = |
5748 | PP.getHeaderToIncludeForDiagnostics(IncLoc: UseLoc, MLoc: DeclLoc)) { |
5749 | if (const FileEntry *FE = |
5750 | SourceMgr.getFileEntryForID(FID: SourceMgr.getFileID(SpellingLoc: UseLoc))) |
5751 | HeaderName = |
5752 | getHeaderNameForHeader(PP, E: *Header, IncludingFile: FE->tryGetRealPathName()); |
5753 | } |
5754 | |
5755 | // If we have a #include we should suggest, or if all definition locations |
5756 | // were in global module fragments, don't suggest an import. |
5757 | if (!HeaderName.empty() || UniqueModules.empty()) { |
5758 | // FIXME: Find a smart place to suggest inserting a #include, and add |
5759 | // a FixItHint there. |
5760 | Diag(UseLoc, diag::err_module_unimported_use_header) |
5761 | << (int)MIK << Decl << !HeaderName.empty() << HeaderName; |
5762 | // Produce a note showing where the entity was declared. |
5763 | NotePrevious(); |
5764 | if (Recover) |
5765 | createImplicitModuleImportForErrorRecovery(Loc: UseLoc, Mod: Modules[0]); |
5766 | return; |
5767 | } |
5768 | |
5769 | Modules = UniqueModules; |
5770 | |
5771 | auto GetModuleNameForDiagnostic = [this](const Module *M) -> std::string { |
5772 | if (M->isModuleMapModule()) |
5773 | return M->getFullModuleName(); |
5774 | |
5775 | Module *CurrentModule = getCurrentModule(); |
5776 | |
5777 | if (M->isImplicitGlobalModule()) |
5778 | M = M->getTopLevelModule(); |
5779 | |
5780 | bool IsInTheSameModule = |
5781 | CurrentModule && CurrentModule->getPrimaryModuleInterfaceName() == |
5782 | M->getPrimaryModuleInterfaceName(); |
5783 | |
5784 | // If the current module unit is in the same module with M, it is OK to show |
5785 | // the partition name. Otherwise, it'll be sufficient to show the primary |
5786 | // module name. |
5787 | if (IsInTheSameModule) |
5788 | return M->getTopLevelModuleName().str(); |
5789 | else |
5790 | return M->getPrimaryModuleInterfaceName().str(); |
5791 | }; |
5792 | |
5793 | if (Modules.size() > 1) { |
5794 | std::string ModuleList; |
5795 | unsigned N = 0; |
5796 | for (const auto *M : Modules) { |
5797 | ModuleList += "\n " ; |
5798 | if (++N == 5 && N != Modules.size()) { |
5799 | ModuleList += "[...]" ; |
5800 | break; |
5801 | } |
5802 | ModuleList += GetModuleNameForDiagnostic(M); |
5803 | } |
5804 | |
5805 | Diag(UseLoc, diag::err_module_unimported_use_multiple) |
5806 | << (int)MIK << Decl << ModuleList; |
5807 | } else { |
5808 | // FIXME: Add a FixItHint that imports the corresponding module. |
5809 | Diag(UseLoc, diag::err_module_unimported_use) |
5810 | << (int)MIK << Decl << GetModuleNameForDiagnostic(Modules[0]); |
5811 | } |
5812 | |
5813 | NotePrevious(); |
5814 | |
5815 | // Try to recover by implicitly importing this module. |
5816 | if (Recover) |
5817 | createImplicitModuleImportForErrorRecovery(Loc: UseLoc, Mod: Modules[0]); |
5818 | } |
5819 | |
5820 | /// Diagnose a successfully-corrected typo. Separated from the correction |
5821 | /// itself to allow external validation of the result, etc. |
5822 | /// |
5823 | /// \param Correction The result of performing typo correction. |
5824 | /// \param TypoDiag The diagnostic to produce. This will have the corrected |
5825 | /// string added to it (and usually also a fixit). |
5826 | /// \param PrevNote A note to use when indicating the location of the entity to |
5827 | /// which we are correcting. Will have the correction string added to it. |
5828 | /// \param ErrorRecovery If \c true (the default), the caller is going to |
5829 | /// recover from the typo as if the corrected string had been typed. |
5830 | /// In this case, \c PDiag must be an error, and we will attach a fixit |
5831 | /// to it. |
5832 | void Sema::diagnoseTypo(const TypoCorrection &Correction, |
5833 | const PartialDiagnostic &TypoDiag, |
5834 | const PartialDiagnostic &PrevNote, |
5835 | bool ErrorRecovery) { |
5836 | std::string CorrectedStr = Correction.getAsString(LO: getLangOpts()); |
5837 | std::string CorrectedQuotedStr = Correction.getQuoted(LO: getLangOpts()); |
5838 | FixItHint FixTypo = FixItHint::CreateReplacement( |
5839 | RemoveRange: Correction.getCorrectionRange(), Code: CorrectedStr); |
5840 | |
5841 | // Maybe we're just missing a module import. |
5842 | if (Correction.requiresImport()) { |
5843 | NamedDecl *Decl = Correction.getFoundDecl(); |
5844 | assert(Decl && "import required but no declaration to import" ); |
5845 | |
5846 | diagnoseMissingImport(Loc: Correction.getCorrectionRange().getBegin(), Decl, |
5847 | MIK: MissingImportKind::Declaration, Recover: ErrorRecovery); |
5848 | return; |
5849 | } |
5850 | |
5851 | Diag(Correction.getCorrectionRange().getBegin(), TypoDiag) |
5852 | << CorrectedQuotedStr << (ErrorRecovery ? FixTypo : FixItHint()); |
5853 | |
5854 | NamedDecl *ChosenDecl = |
5855 | Correction.isKeyword() ? nullptr : Correction.getFoundDecl(); |
5856 | if (PrevNote.getDiagID() && ChosenDecl) |
5857 | Diag(ChosenDecl->getLocation(), PrevNote) |
5858 | << CorrectedQuotedStr << (ErrorRecovery ? FixItHint() : FixTypo); |
5859 | |
5860 | // Add any extra diagnostics. |
5861 | for (const PartialDiagnostic &PD : Correction.getExtraDiagnostics()) |
5862 | Diag(Correction.getCorrectionRange().getBegin(), PD); |
5863 | } |
5864 | |
5865 | TypoExpr *Sema::createDelayedTypo(std::unique_ptr<TypoCorrectionConsumer> TCC, |
5866 | TypoDiagnosticGenerator TDG, |
5867 | TypoRecoveryCallback TRC, |
5868 | SourceLocation TypoLoc) { |
5869 | assert(TCC && "createDelayedTypo requires a valid TypoCorrectionConsumer" ); |
5870 | auto TE = new (Context) TypoExpr(Context.DependentTy, TypoLoc); |
5871 | auto &State = DelayedTypos[TE]; |
5872 | State.Consumer = std::move(TCC); |
5873 | State.DiagHandler = std::move(TDG); |
5874 | State.RecoveryHandler = std::move(TRC); |
5875 | if (TE) |
5876 | TypoExprs.push_back(Elt: TE); |
5877 | return TE; |
5878 | } |
5879 | |
5880 | const Sema::TypoExprState &Sema::getTypoExprState(TypoExpr *TE) const { |
5881 | auto Entry = DelayedTypos.find(Key: TE); |
5882 | assert(Entry != DelayedTypos.end() && |
5883 | "Failed to get the state for a TypoExpr!" ); |
5884 | return Entry->second; |
5885 | } |
5886 | |
5887 | void Sema::clearDelayedTypo(TypoExpr *TE) { |
5888 | DelayedTypos.erase(Key: TE); |
5889 | } |
5890 | |
5891 | void Sema::ActOnPragmaDump(Scope *S, SourceLocation IILoc, IdentifierInfo *II) { |
5892 | DeclarationNameInfo Name(II, IILoc); |
5893 | LookupResult R(*this, Name, LookupAnyName, |
5894 | RedeclarationKind::NotForRedeclaration); |
5895 | R.suppressDiagnostics(); |
5896 | R.setHideTags(false); |
5897 | LookupName(R, S); |
5898 | R.dump(); |
5899 | } |
5900 | |
5901 | void Sema::ActOnPragmaDump(Expr *E) { |
5902 | E->dump(); |
5903 | } |
5904 | |
5905 | RedeclarationKind Sema::forRedeclarationInCurContext() const { |
5906 | // A declaration with an owning module for linkage can never link against |
5907 | // anything that is not visible. We don't need to check linkage here; if |
5908 | // the context has internal linkage, redeclaration lookup won't find things |
5909 | // from other TUs, and we can't safely compute linkage yet in general. |
5910 | if (cast<Decl>(Val: CurContext)->getOwningModuleForLinkage(/*IgnoreLinkage*/ true)) |
5911 | return RedeclarationKind::ForVisibleRedeclaration; |
5912 | return RedeclarationKind::ForExternalRedeclaration; |
5913 | } |
5914 | |