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