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