blob: e15e532be19ee4b440f4c18cf23511a7dd5a65df [file] [log] [blame]
Douglas Gregor34074322009-01-14 22:20:51 +00001//===--------------------- SemaLookup.cpp - Name Lookup ------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements name lookup for C, C++, Objective-C, and
11// Objective-C++.
12//
13//===----------------------------------------------------------------------===//
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000014#include "clang/Sema/Lookup.h"
Douglas Gregor960b5bc2009-01-15 00:26:24 +000015#include "clang/AST/ASTContext.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000016#include "clang/AST/CXXInheritance.h"
Douglas Gregor34074322009-01-14 22:20:51 +000017#include "clang/AST/Decl.h"
18#include "clang/AST/DeclCXX.h"
Nick Lewyckyc3921482012-04-03 21:44:08 +000019#include "clang/AST/DeclLookups.h"
Douglas Gregor34074322009-01-14 22:20:51 +000020#include "clang/AST/DeclObjC.h"
Douglas Gregorc9f9b862009-05-11 19:58:34 +000021#include "clang/AST/DeclTemplate.h"
Douglas Gregore254f902009-02-04 00:32:51 +000022#include "clang/AST/Expr.h"
Douglas Gregorbe759252009-07-08 10:57:20 +000023#include "clang/AST/ExprCXX.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000024#include "clang/Basic/Builtins.h"
Douglas Gregor34074322009-01-14 22:20:51 +000025#include "clang/Basic/LangOptions.h"
Alp Tokerb6cc5922014-05-03 03:45:55 +000026#include "clang/Lex/ModuleLoader.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000027#include "clang/Sema/DeclSpec.h"
28#include "clang/Sema/ExternalSemaSource.h"
29#include "clang/Sema/Overload.h"
30#include "clang/Sema/Scope.h"
31#include "clang/Sema/ScopeInfo.h"
32#include "clang/Sema/Sema.h"
33#include "clang/Sema/SemaInternal.h"
34#include "clang/Sema/TemplateDeduction.h"
35#include "clang/Sema/TypoCorrection.h"
Douglas Gregor34074322009-01-14 22:20:51 +000036#include "llvm/ADT/STLExtras.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000037#include "llvm/ADT/SetVector.h"
Douglas Gregore254f902009-02-04 00:32:51 +000038#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor0afa7f62010-10-14 20:34:08 +000039#include "llvm/ADT/StringMap.h"
Chris Lattner83cfc7c2011-07-18 01:54:02 +000040#include "llvm/ADT/TinyPtrVector.h"
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +000041#include "llvm/ADT/edit_distance.h"
John McCall6538c932009-10-10 05:48:19 +000042#include "llvm/Support/ErrorHandling.h"
Nick Lewycky13668f22012-04-03 20:26:45 +000043#include <algorithm>
44#include <iterator>
Douglas Gregor0afa7f62010-10-14 20:34:08 +000045#include <limits>
Douglas Gregor2d435302009-12-30 17:04:44 +000046#include <list>
Douglas Gregorc2fa1692011-06-28 16:20:02 +000047#include <map>
Nick Lewycky13668f22012-04-03 20:26:45 +000048#include <set>
49#include <utility>
50#include <vector>
Douglas Gregor34074322009-01-14 22:20:51 +000051
52using namespace clang;
John McCall19c1bfd2010-08-25 05:32:35 +000053using namespace sema;
Douglas Gregor34074322009-01-14 22:20:51 +000054
John McCallf6c8a4e2009-11-10 07:01:13 +000055namespace {
56 class UnqualUsingEntry {
57 const DeclContext *Nominated;
58 const DeclContext *CommonAncestor;
Douglas Gregor889ceb72009-02-03 19:21:40 +000059
John McCallf6c8a4e2009-11-10 07:01:13 +000060 public:
61 UnqualUsingEntry(const DeclContext *Nominated,
62 const DeclContext *CommonAncestor)
63 : Nominated(Nominated), CommonAncestor(CommonAncestor) {
64 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000065
John McCallf6c8a4e2009-11-10 07:01:13 +000066 const DeclContext *getCommonAncestor() const {
67 return CommonAncestor;
68 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000069
John McCallf6c8a4e2009-11-10 07:01:13 +000070 const DeclContext *getNominatedNamespace() const {
71 return Nominated;
72 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000073
John McCallf6c8a4e2009-11-10 07:01:13 +000074 // Sort by the pointer value of the common ancestor.
75 struct Comparator {
76 bool operator()(const UnqualUsingEntry &L, const UnqualUsingEntry &R) {
77 return L.getCommonAncestor() < R.getCommonAncestor();
78 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000079
John McCallf6c8a4e2009-11-10 07:01:13 +000080 bool operator()(const UnqualUsingEntry &E, const DeclContext *DC) {
81 return E.getCommonAncestor() < DC;
82 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000083
John McCallf6c8a4e2009-11-10 07:01:13 +000084 bool operator()(const DeclContext *DC, const UnqualUsingEntry &E) {
85 return DC < E.getCommonAncestor();
86 }
87 };
88 };
Douglas Gregor889ceb72009-02-03 19:21:40 +000089
John McCallf6c8a4e2009-11-10 07:01:13 +000090 /// A collection of using directives, as used by C++ unqualified
91 /// lookup.
92 class UnqualUsingDirectiveSet {
Chris Lattner0e62c1c2011-07-23 10:55:15 +000093 typedef SmallVector<UnqualUsingEntry, 8> ListTy;
Douglas Gregor889ceb72009-02-03 19:21:40 +000094
John McCallf6c8a4e2009-11-10 07:01:13 +000095 ListTy list;
96 llvm::SmallPtrSet<DeclContext*, 8> visited;
Douglas Gregor889ceb72009-02-03 19:21:40 +000097
John McCallf6c8a4e2009-11-10 07:01:13 +000098 public:
99 UnqualUsingDirectiveSet() {}
Douglas Gregor889ceb72009-02-03 19:21:40 +0000100
John McCallf6c8a4e2009-11-10 07:01:13 +0000101 void visitScopeChain(Scope *S, Scope *InnermostFileScope) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000102 // C++ [namespace.udir]p1:
John McCallf6c8a4e2009-11-10 07:01:13 +0000103 // During unqualified name lookup, the names appear as if they
104 // were declared in the nearest enclosing namespace which contains
105 // both the using-directive and the nominated namespace.
Ted Kremenekc37877d2013-10-08 17:08:03 +0000106 DeclContext *InnermostFileDC = InnermostFileScope->getEntity();
John McCallf6c8a4e2009-11-10 07:01:13 +0000107 assert(InnermostFileDC && InnermostFileDC->isFileContext());
Douglas Gregor889ceb72009-02-03 19:21:40 +0000108
John McCallf6c8a4e2009-11-10 07:01:13 +0000109 for (; S; S = S->getParent()) {
Nick Lewycky2bd636f2012-03-13 04:12:34 +0000110 // C++ [namespace.udir]p1:
111 // A using-directive shall not appear in class scope, but may
112 // appear in namespace scope or in block scope.
Ted Kremenekc37877d2013-10-08 17:08:03 +0000113 DeclContext *Ctx = S->getEntity();
Nick Lewycky2bd636f2012-03-13 04:12:34 +0000114 if (Ctx && Ctx->isFileContext()) {
115 visit(Ctx, Ctx);
116 } else if (!Ctx || Ctx->isFunctionOrMethod()) {
Aaron Ballman5df6aa42014-03-17 17:03:37 +0000117 for (auto *I : S->using_directives())
118 visit(I, InnermostFileDC);
John McCallf6c8a4e2009-11-10 07:01:13 +0000119 }
Douglas Gregor889ceb72009-02-03 19:21:40 +0000120 }
121 }
John McCallf6c8a4e2009-11-10 07:01:13 +0000122
123 // Visits a context and collect all of its using directives
124 // recursively. Treats all using directives as if they were
125 // declared in the context.
126 //
127 // A given context is only every visited once, so it is important
128 // that contexts be visited from the inside out in order to get
129 // the effective DCs right.
130 void visit(DeclContext *DC, DeclContext *EffectiveDC) {
David Blaikie82e95a32014-11-19 07:49:47 +0000131 if (!visited.insert(DC).second)
John McCallf6c8a4e2009-11-10 07:01:13 +0000132 return;
133
134 addUsingDirectives(DC, EffectiveDC);
135 }
136
137 // Visits a using directive and collects all of its using
138 // directives recursively. Treats all using directives as if they
139 // were declared in the effective DC.
140 void visit(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
141 DeclContext *NS = UD->getNominatedNamespace();
David Blaikie82e95a32014-11-19 07:49:47 +0000142 if (!visited.insert(NS).second)
John McCallf6c8a4e2009-11-10 07:01:13 +0000143 return;
144
145 addUsingDirective(UD, EffectiveDC);
146 addUsingDirectives(NS, EffectiveDC);
147 }
148
149 // Adds all the using directives in a context (and those nominated
150 // by its using directives, transitively) as if they appeared in
151 // the given effective context.
152 void addUsingDirectives(DeclContext *DC, DeclContext *EffectiveDC) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000153 SmallVector<DeclContext*,4> queue;
John McCallf6c8a4e2009-11-10 07:01:13 +0000154 while (true) {
Aaron Ballman804a7fb2014-03-17 17:14:12 +0000155 for (auto UD : DC->using_directives()) {
John McCallf6c8a4e2009-11-10 07:01:13 +0000156 DeclContext *NS = UD->getNominatedNamespace();
David Blaikie82e95a32014-11-19 07:49:47 +0000157 if (visited.insert(NS).second) {
John McCallf6c8a4e2009-11-10 07:01:13 +0000158 addUsingDirective(UD, EffectiveDC);
159 queue.push_back(NS);
160 }
161 }
162
163 if (queue.empty())
164 return;
165
Robert Wilhelm25284cc2013-08-23 16:11:15 +0000166 DC = queue.pop_back_val();
John McCallf6c8a4e2009-11-10 07:01:13 +0000167 }
168 }
169
170 // Add a using directive as if it had been declared in the given
171 // context. This helps implement C++ [namespace.udir]p3:
172 // The using-directive is transitive: if a scope contains a
173 // using-directive that nominates a second namespace that itself
174 // contains using-directives, the effect is as if the
175 // using-directives from the second namespace also appeared in
176 // the first.
177 void addUsingDirective(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
178 // Find the common ancestor between the effective context and
179 // the nominated namespace.
180 DeclContext *Common = UD->getNominatedNamespace();
181 while (!Common->Encloses(EffectiveDC))
182 Common = Common->getParent();
John McCall9757d032009-11-10 09:20:04 +0000183 Common = Common->getPrimaryContext();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000184
John McCallf6c8a4e2009-11-10 07:01:13 +0000185 list.push_back(UnqualUsingEntry(UD->getNominatedNamespace(), Common));
186 }
187
188 void done() {
189 std::sort(list.begin(), list.end(), UnqualUsingEntry::Comparator());
190 }
191
John McCallf6c8a4e2009-11-10 07:01:13 +0000192 typedef ListTy::const_iterator const_iterator;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000193
John McCallf6c8a4e2009-11-10 07:01:13 +0000194 const_iterator begin() const { return list.begin(); }
195 const_iterator end() const { return list.end(); }
196
Benjamin Kramerb4ef6682015-02-06 17:25:10 +0000197 llvm::iterator_range<const_iterator>
John McCallf6c8a4e2009-11-10 07:01:13 +0000198 getNamespacesFor(DeclContext *DC) const {
Benjamin Kramerb4ef6682015-02-06 17:25:10 +0000199 return llvm::make_range(std::equal_range(begin(), end(),
200 DC->getPrimaryContext(),
201 UnqualUsingEntry::Comparator()));
John McCallf6c8a4e2009-11-10 07:01:13 +0000202 }
203 };
Douglas Gregor889ceb72009-02-03 19:21:40 +0000204}
205
Douglas Gregor889ceb72009-02-03 19:21:40 +0000206// Retrieve the set of identifier namespaces that correspond to a
207// specific kind of name lookup.
John McCallea305ed2009-12-18 10:40:03 +0000208static inline unsigned getIDNS(Sema::LookupNameKind NameKind,
209 bool CPlusPlus,
210 bool Redeclaration) {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000211 unsigned IDNS = 0;
212 switch (NameKind) {
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +0000213 case Sema::LookupObjCImplicitSelfParam:
Douglas Gregor889ceb72009-02-03 19:21:40 +0000214 case Sema::LookupOrdinaryName:
Douglas Gregoreddf4332009-02-24 20:03:32 +0000215 case Sema::LookupRedeclarationWithLinkage:
Richard Smith114394f2013-08-09 04:35:01 +0000216 case Sema::LookupLocalFriendName:
Douglas Gregor889ceb72009-02-03 19:21:40 +0000217 IDNS = Decl::IDNS_Ordinary;
John McCallea305ed2009-12-18 10:40:03 +0000218 if (CPlusPlus) {
John McCalle87beb22010-04-23 18:46:30 +0000219 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Member | Decl::IDNS_Namespace;
Chris Lattnerebb5c6c2011-02-18 01:27:55 +0000220 if (Redeclaration)
221 IDNS |= Decl::IDNS_TagFriend | Decl::IDNS_OrdinaryFriend;
John McCallea305ed2009-12-18 10:40:03 +0000222 }
Richard Smith541b38b2013-09-20 01:15:31 +0000223 if (Redeclaration)
224 IDNS |= Decl::IDNS_LocalExtern;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000225 break;
226
John McCallb9467b62010-04-24 01:30:58 +0000227 case Sema::LookupOperatorName:
228 // Operator lookup is its own crazy thing; it is not the same
229 // as (e.g.) looking up an operator name for redeclaration.
230 assert(!Redeclaration && "cannot do redeclaration operator lookup");
231 IDNS = Decl::IDNS_NonMemberOperator;
232 break;
233
Douglas Gregor889ceb72009-02-03 19:21:40 +0000234 case Sema::LookupTagName:
John McCalle87beb22010-04-23 18:46:30 +0000235 if (CPlusPlus) {
236 IDNS = Decl::IDNS_Type;
237
238 // When looking for a redeclaration of a tag name, we add:
239 // 1) TagFriend to find undeclared friend decls
240 // 2) Namespace because they can't "overload" with tag decls.
241 // 3) Tag because it includes class templates, which can't
242 // "overload" with tag decls.
243 if (Redeclaration)
244 IDNS |= Decl::IDNS_Tag | Decl::IDNS_TagFriend | Decl::IDNS_Namespace;
245 } else {
246 IDNS = Decl::IDNS_Tag;
247 }
Douglas Gregor889ceb72009-02-03 19:21:40 +0000248 break;
Richard Smith83e78f52014-04-11 01:03:38 +0000249
Chris Lattnerebb5c6c2011-02-18 01:27:55 +0000250 case Sema::LookupLabel:
251 IDNS = Decl::IDNS_Label;
252 break;
Richard Smith83e78f52014-04-11 01:03:38 +0000253
Douglas Gregor889ceb72009-02-03 19:21:40 +0000254 case Sema::LookupMemberName:
255 IDNS = Decl::IDNS_Member;
256 if (CPlusPlus)
Mike Stump11289f42009-09-09 15:08:12 +0000257 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Ordinary;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000258 break;
259
260 case Sema::LookupNestedNameSpecifierName:
John McCalle87beb22010-04-23 18:46:30 +0000261 IDNS = Decl::IDNS_Type | Decl::IDNS_Namespace;
262 break;
263
Douglas Gregor889ceb72009-02-03 19:21:40 +0000264 case Sema::LookupNamespaceName:
John McCalle87beb22010-04-23 18:46:30 +0000265 IDNS = Decl::IDNS_Namespace;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000266 break;
Douglas Gregorde9f17e2009-04-23 23:18:26 +0000267
John McCall84d87672009-12-10 09:41:52 +0000268 case Sema::LookupUsingDeclName:
Richard Smith83e78f52014-04-11 01:03:38 +0000269 assert(Redeclaration && "should only be used for redecl lookup");
270 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Member |
271 Decl::IDNS_Using | Decl::IDNS_TagFriend | Decl::IDNS_OrdinaryFriend |
272 Decl::IDNS_LocalExtern;
John McCall84d87672009-12-10 09:41:52 +0000273 break;
274
Douglas Gregor79947a22009-04-24 00:11:27 +0000275 case Sema::LookupObjCProtocolName:
276 IDNS = Decl::IDNS_ObjCProtocol;
277 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000278
Douglas Gregor39982192010-08-15 06:18:01 +0000279 case Sema::LookupAnyName:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000280 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Member
Douglas Gregor39982192010-08-15 06:18:01 +0000281 | Decl::IDNS_Using | Decl::IDNS_Namespace | Decl::IDNS_ObjCProtocol
282 | Decl::IDNS_Type;
283 break;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000284 }
285 return IDNS;
286}
287
John McCallea305ed2009-12-18 10:40:03 +0000288void LookupResult::configure() {
Kaelyn Takatafc8c61a2014-11-11 23:00:42 +0000289 IDNS = getIDNS(LookupKind, getSema().getLangOpts().CPlusPlus,
John McCallea305ed2009-12-18 10:40:03 +0000290 isForRedeclaration());
Douglas Gregorbcf0a472010-03-24 05:07:21 +0000291
Richard Smithbdd14642014-02-04 01:14:30 +0000292 // If we're looking for one of the allocation or deallocation
293 // operators, make sure that the implicitly-declared new and delete
294 // operators can be found.
295 switch (NameInfo.getName().getCXXOverloadedOperator()) {
296 case OO_New:
297 case OO_Delete:
298 case OO_Array_New:
299 case OO_Array_Delete:
Kaelyn Takatafc8c61a2014-11-11 23:00:42 +0000300 getSema().DeclareGlobalNewDelete();
Richard Smithbdd14642014-02-04 01:14:30 +0000301 break;
Douglas Gregorbcf0a472010-03-24 05:07:21 +0000302
Richard Smithbdd14642014-02-04 01:14:30 +0000303 default:
304 break;
305 }
Douglas Gregor15197662013-04-03 23:06:26 +0000306
Richard Smithbdd14642014-02-04 01:14:30 +0000307 // Compiler builtins are always visible, regardless of where they end
308 // up being declared.
309 if (IdentifierInfo *Id = NameInfo.getName().getAsIdentifierInfo()) {
310 if (unsigned BuiltinID = Id->getBuiltinID()) {
Kaelyn Takatafc8c61a2014-11-11 23:00:42 +0000311 if (!getSema().Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
Richard Smithbdd14642014-02-04 01:14:30 +0000312 AllowHidden = true;
Douglas Gregor15197662013-04-03 23:06:26 +0000313 }
Douglas Gregorbcf0a472010-03-24 05:07:21 +0000314 }
John McCallea305ed2009-12-18 10:40:03 +0000315}
316
Alp Tokerc1086762013-12-07 13:51:35 +0000317bool LookupResult::sanity() const {
Richard Smithf97ad222014-04-01 18:33:50 +0000318 // This function is never called by NDEBUG builds.
John McCall19c1bfd2010-08-25 05:32:35 +0000319 assert(ResultKind != NotFound || Decls.size() == 0);
320 assert(ResultKind != Found || Decls.size() == 1);
321 assert(ResultKind != FoundOverloaded || Decls.size() > 1 ||
322 (Decls.size() == 1 &&
323 isa<FunctionTemplateDecl>((*begin())->getUnderlyingDecl())));
324 assert(ResultKind != FoundUnresolvedValue || sanityCheckUnresolved());
325 assert(ResultKind != Ambiguous || Decls.size() > 1 ||
Douglas Gregorc0d24902010-10-22 22:08:47 +0000326 (Decls.size() == 1 && (Ambiguity == AmbiguousBaseSubobjects ||
327 Ambiguity == AmbiguousBaseSubobjectTypes)));
Craig Topperc3ec1492014-05-26 06:22:03 +0000328 assert((Paths != nullptr) == (ResultKind == Ambiguous &&
329 (Ambiguity == AmbiguousBaseSubobjectTypes ||
330 Ambiguity == AmbiguousBaseSubobjects)));
Alp Tokerc1086762013-12-07 13:51:35 +0000331 return true;
John McCall19c1bfd2010-08-25 05:32:35 +0000332}
John McCall19c1bfd2010-08-25 05:32:35 +0000333
John McCall9f3059a2009-10-09 21:13:30 +0000334// Necessary because CXXBasePaths is not complete in Sema.h
John McCall5cebab12009-11-18 07:57:50 +0000335void LookupResult::deletePaths(CXXBasePaths *Paths) {
John McCall9f3059a2009-10-09 21:13:30 +0000336 delete Paths;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000337}
338
Richard Smith3876cc82013-10-30 01:02:04 +0000339/// Get a representative context for a declaration such that two declarations
340/// will have the same context if they were found within the same scope.
Benjamin Kramerfc58b042013-11-01 11:50:55 +0000341static DeclContext *getContextForScopeMatching(Decl *D) {
Richard Smith3876cc82013-10-30 01:02:04 +0000342 // For function-local declarations, use that function as the context. This
343 // doesn't account for scopes within the function; the caller must deal with
344 // those.
345 DeclContext *DC = D->getLexicalDeclContext();
346 if (DC->isFunctionOrMethod())
347 return DC;
348
349 // Otherwise, look at the semantic context of the declaration. The
350 // declaration must have been found there.
351 return D->getDeclContext()->getRedeclContext();
352}
353
John McCall283b9012009-11-22 00:44:51 +0000354/// Resolves the result kind of this lookup.
John McCall5cebab12009-11-18 07:57:50 +0000355void LookupResult::resolveKind() {
John McCall9f3059a2009-10-09 21:13:30 +0000356 unsigned N = Decls.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000357
John McCall9f3059a2009-10-09 21:13:30 +0000358 // Fast case: no possible ambiguity.
John McCall1f82f242009-11-18 22:49:29 +0000359 if (N == 0) {
John McCall7fe6e9c2010-01-15 21:27:01 +0000360 assert(ResultKind == NotFound || ResultKind == NotFoundInCurrentInstantiation);
John McCall1f82f242009-11-18 22:49:29 +0000361 return;
362 }
363
John McCall283b9012009-11-22 00:44:51 +0000364 // If there's a single decl, we need to examine it to decide what
365 // kind of lookup this is.
John McCalle61f2ba2009-11-18 02:36:19 +0000366 if (N == 1) {
Douglas Gregor516d6722010-04-25 21:15:30 +0000367 NamedDecl *D = (*Decls.begin())->getUnderlyingDecl();
368 if (isa<FunctionTemplateDecl>(D))
John McCall283b9012009-11-22 00:44:51 +0000369 ResultKind = FoundOverloaded;
Douglas Gregor516d6722010-04-25 21:15:30 +0000370 else if (isa<UnresolvedUsingValueDecl>(D))
John McCalle61f2ba2009-11-18 02:36:19 +0000371 ResultKind = FoundUnresolvedValue;
372 return;
373 }
John McCall9f3059a2009-10-09 21:13:30 +0000374
John McCall6538c932009-10-10 05:48:19 +0000375 // Don't do any extra resolution if we've already resolved as ambiguous.
John McCall27b18f82009-11-17 02:14:36 +0000376 if (ResultKind == Ambiguous) return;
John McCall6538c932009-10-10 05:48:19 +0000377
John McCall9f3059a2009-10-09 21:13:30 +0000378 llvm::SmallPtrSet<NamedDecl*, 16> Unique;
Douglas Gregor13e65872010-08-11 14:45:53 +0000379 llvm::SmallPtrSet<QualType, 16> UniqueTypes;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000380
John McCall9f3059a2009-10-09 21:13:30 +0000381 bool Ambiguous = false;
382 bool HasTag = false, HasFunction = false, HasNonFunction = false;
John McCall283b9012009-11-22 00:44:51 +0000383 bool HasFunctionTemplate = false, HasUnresolved = false;
John McCall9f3059a2009-10-09 21:13:30 +0000384
385 unsigned UniqueTagIndex = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000386
John McCall9f3059a2009-10-09 21:13:30 +0000387 unsigned I = 0;
388 while (I < N) {
John McCallf0f1cf02009-11-17 07:50:12 +0000389 NamedDecl *D = Decls[I]->getUnderlyingDecl();
390 D = cast<NamedDecl>(D->getCanonicalDecl());
John McCall9f3059a2009-10-09 21:13:30 +0000391
Argyrios Kyrtzidis1fcd7fd2013-02-22 06:58:37 +0000392 // Ignore an invalid declaration unless it's the only one left.
393 if (D->isInvalidDecl() && I < N-1) {
394 Decls[I] = Decls[--N];
395 continue;
396 }
397
Douglas Gregor13e65872010-08-11 14:45:53 +0000398 // Redeclarations of types via typedef can occur both within a scope
399 // and, through using declarations and directives, across scopes. There is
400 // no ambiguity if they all refer to the same type, so unique based on the
401 // canonical type.
402 if (TypeDecl *TD = dyn_cast<TypeDecl>(D)) {
403 if (!TD->getDeclContext()->isRecord()) {
Kaelyn Takatafc8c61a2014-11-11 23:00:42 +0000404 QualType T = getSema().Context.getTypeDeclType(TD);
David Blaikie82e95a32014-11-19 07:49:47 +0000405 if (!UniqueTypes.insert(getSema().Context.getCanonicalType(T)).second) {
Douglas Gregor13e65872010-08-11 14:45:53 +0000406 // The type is not unique; pull something off the back and continue
407 // at this index.
408 Decls[I] = Decls[--N];
409 continue;
410 }
411 }
412 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000413
David Blaikie82e95a32014-11-19 07:49:47 +0000414 if (!Unique.insert(D).second) {
John McCall9f3059a2009-10-09 21:13:30 +0000415 // If it's not unique, pull something off the back (and
416 // continue at this index).
Richard Smithe8292b12015-02-10 03:28:10 +0000417 // FIXME: This is wrong. We need to take the more recent declaration in
Richard Smithfe620d22015-03-05 23:24:12 +0000418 // order to get the right type, default arguments, etc. We also need to
419 // prefer visible declarations to hidden ones (for redeclaration lookup
420 // in modules builds).
John McCall9f3059a2009-10-09 21:13:30 +0000421 Decls[I] = Decls[--N];
Douglas Gregor13e65872010-08-11 14:45:53 +0000422 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000423 }
424
Douglas Gregor13e65872010-08-11 14:45:53 +0000425 // Otherwise, do some decl type analysis and then continue.
John McCalle61f2ba2009-11-18 02:36:19 +0000426
Douglas Gregor13e65872010-08-11 14:45:53 +0000427 if (isa<UnresolvedUsingValueDecl>(D)) {
428 HasUnresolved = true;
429 } else if (isa<TagDecl>(D)) {
430 if (HasTag)
431 Ambiguous = true;
432 UniqueTagIndex = I;
433 HasTag = true;
434 } else if (isa<FunctionTemplateDecl>(D)) {
435 HasFunction = true;
436 HasFunctionTemplate = true;
437 } else if (isa<FunctionDecl>(D)) {
438 HasFunction = true;
439 } else {
440 if (HasNonFunction)
441 Ambiguous = true;
442 HasNonFunction = true;
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000443 }
Douglas Gregor13e65872010-08-11 14:45:53 +0000444 I++;
Mike Stump11289f42009-09-09 15:08:12 +0000445 }
Douglas Gregor38feed82009-04-24 02:57:34 +0000446
John McCall9f3059a2009-10-09 21:13:30 +0000447 // C++ [basic.scope.hiding]p2:
448 // A class name or enumeration name can be hidden by the name of
449 // an object, function, or enumerator declared in the same
450 // scope. If a class or enumeration name and an object, function,
451 // or enumerator are declared in the same scope (in any order)
452 // with the same name, the class or enumeration name is hidden
453 // wherever the object, function, or enumerator name is visible.
454 // But it's still an error if there are distinct tag types found,
455 // even if they're not visible. (ref?)
John McCall80053822009-12-03 00:58:24 +0000456 if (HideTags && HasTag && !Ambiguous &&
Douglas Gregore63d0872010-10-23 16:06:17 +0000457 (HasFunction || HasNonFunction || HasUnresolved)) {
Richard Smith3876cc82013-10-30 01:02:04 +0000458 if (getContextForScopeMatching(Decls[UniqueTagIndex])->Equals(
459 getContextForScopeMatching(Decls[UniqueTagIndex ? 0 : N - 1])))
Douglas Gregore63d0872010-10-23 16:06:17 +0000460 Decls[UniqueTagIndex] = Decls[--N];
461 else
462 Ambiguous = true;
463 }
Anders Carlsson8d0f6b72009-06-26 03:37:05 +0000464
John McCall9f3059a2009-10-09 21:13:30 +0000465 Decls.set_size(N);
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000466
John McCall80053822009-12-03 00:58:24 +0000467 if (HasNonFunction && (HasFunction || HasUnresolved))
John McCall9f3059a2009-10-09 21:13:30 +0000468 Ambiguous = true;
Douglas Gregorf23311d2009-01-17 01:13:24 +0000469
John McCall9f3059a2009-10-09 21:13:30 +0000470 if (Ambiguous)
John McCall6538c932009-10-10 05:48:19 +0000471 setAmbiguous(LookupResult::AmbiguousReference);
John McCalle61f2ba2009-11-18 02:36:19 +0000472 else if (HasUnresolved)
473 ResultKind = LookupResult::FoundUnresolvedValue;
John McCall283b9012009-11-22 00:44:51 +0000474 else if (N > 1 || HasFunctionTemplate)
John McCall27b18f82009-11-17 02:14:36 +0000475 ResultKind = LookupResult::FoundOverloaded;
John McCall9f3059a2009-10-09 21:13:30 +0000476 else
John McCall27b18f82009-11-17 02:14:36 +0000477 ResultKind = LookupResult::Found;
Douglas Gregor34074322009-01-14 22:20:51 +0000478}
479
John McCall5cebab12009-11-18 07:57:50 +0000480void LookupResult::addDeclsFromBasePaths(const CXXBasePaths &P) {
John McCall5b0829a2010-02-10 09:31:12 +0000481 CXXBasePaths::const_paths_iterator I, E;
John McCall9f3059a2009-10-09 21:13:30 +0000482 for (I = P.begin(), E = P.end(); I != E; ++I)
David Blaikieff7d47a2012-12-19 00:45:41 +0000483 for (DeclContext::lookup_iterator DI = I->Decls.begin(),
484 DE = I->Decls.end(); DI != DE; ++DI)
John McCall9f3059a2009-10-09 21:13:30 +0000485 addDecl(*DI);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +0000486}
487
John McCall5cebab12009-11-18 07:57:50 +0000488void LookupResult::setAmbiguousBaseSubobjects(CXXBasePaths &P) {
John McCall9f3059a2009-10-09 21:13:30 +0000489 Paths = new CXXBasePaths;
490 Paths->swap(P);
491 addDeclsFromBasePaths(*Paths);
492 resolveKind();
John McCall6538c932009-10-10 05:48:19 +0000493 setAmbiguous(AmbiguousBaseSubobjects);
Douglas Gregor0e8fc3c2009-02-02 21:35:47 +0000494}
495
John McCall5cebab12009-11-18 07:57:50 +0000496void LookupResult::setAmbiguousBaseSubobjectTypes(CXXBasePaths &P) {
John McCall9f3059a2009-10-09 21:13:30 +0000497 Paths = new CXXBasePaths;
498 Paths->swap(P);
499 addDeclsFromBasePaths(*Paths);
500 resolveKind();
John McCall6538c932009-10-10 05:48:19 +0000501 setAmbiguous(AmbiguousBaseSubobjectTypes);
John McCall9f3059a2009-10-09 21:13:30 +0000502}
503
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000504void LookupResult::print(raw_ostream &Out) {
John McCall9f3059a2009-10-09 21:13:30 +0000505 Out << Decls.size() << " result(s)";
506 if (isAmbiguous()) Out << ", ambiguous";
507 if (Paths) Out << ", base paths present";
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000508
John McCall9f3059a2009-10-09 21:13:30 +0000509 for (iterator I = begin(), E = end(); I != E; ++I) {
510 Out << "\n";
511 (*I)->print(Out, 2);
512 }
513}
514
Douglas Gregord3a59182010-02-12 05:48:04 +0000515/// \brief Lookup a builtin function, when name lookup would otherwise
516/// fail.
517static bool LookupBuiltin(Sema &S, LookupResult &R) {
518 Sema::LookupNameKind NameKind = R.getLookupKind();
519
520 // If we didn't find a use of this identifier, and if the identifier
521 // corresponds to a compiler builtin, create the decl object for the builtin
522 // now, injecting it into translation unit scope, and return it.
523 if (NameKind == Sema::LookupOrdinaryName ||
524 NameKind == Sema::LookupRedeclarationWithLinkage) {
525 IdentifierInfo *II = R.getLookupName().getAsIdentifierInfo();
526 if (II) {
Nico Webere1687c52013-06-20 21:44:55 +0000527 if (S.getLangOpts().CPlusPlus11 && S.getLangOpts().GNUMode &&
528 II == S.getFloat128Identifier()) {
529 // libstdc++4.7's type_traits expects type __float128 to exist, so
530 // insert a dummy type to make that header build in gnu++11 mode.
531 R.addDecl(S.getASTContext().getFloat128StubType());
532 return true;
533 }
534
Douglas Gregord3a59182010-02-12 05:48:04 +0000535 // If this is a builtin on this (or all) targets, create the decl.
536 if (unsigned BuiltinID = II->getBuiltinID()) {
537 // In C++, we don't have any predefined library functions like
538 // 'malloc'. Instead, we'll just error.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000539 if (S.getLangOpts().CPlusPlus &&
Douglas Gregord3a59182010-02-12 05:48:04 +0000540 S.Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
541 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000542
543 if (NamedDecl *D = S.LazilyCreateBuiltin((IdentifierInfo *)II,
544 BuiltinID, S.TUScope,
Douglas Gregorbfe022c2011-01-03 09:37:44 +0000545 R.isForRedeclaration(),
546 R.getNameLoc())) {
Douglas Gregord3a59182010-02-12 05:48:04 +0000547 R.addDecl(D);
Douglas Gregorbfe022c2011-01-03 09:37:44 +0000548 return true;
549 }
Douglas Gregord3a59182010-02-12 05:48:04 +0000550 }
551 }
552 }
553
554 return false;
555}
556
Douglas Gregor7454c562010-07-02 20:37:36 +0000557/// \brief Determine whether we can declare a special member function within
558/// the class at this point.
Richard Smith7d125a12012-11-27 21:20:31 +0000559static bool CanDeclareSpecialMemberFunction(const CXXRecordDecl *Class) {
Douglas Gregor7454c562010-07-02 20:37:36 +0000560 // We need to have a definition for the class.
561 if (!Class->getDefinition() || Class->isDependentContext())
562 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000563
Douglas Gregor7454c562010-07-02 20:37:36 +0000564 // We can't be in the middle of defining the class.
Richard Smith7d125a12012-11-27 21:20:31 +0000565 return !Class->isBeingDefined();
Douglas Gregor7454c562010-07-02 20:37:36 +0000566}
567
568void Sema::ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class) {
Richard Smith7d125a12012-11-27 21:20:31 +0000569 if (!CanDeclareSpecialMemberFunction(Class))
Douglas Gregora6d69502010-07-02 23:41:54 +0000570 return;
Douglas Gregor9672f922010-07-03 00:47:00 +0000571
572 // If the default constructor has not yet been declared, do so now.
Alexis Huntea6f0322011-05-11 22:34:38 +0000573 if (Class->needsImplicitDefaultConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +0000574 DeclareImplicitDefaultConstructor(Class);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000575
Douglas Gregora6d69502010-07-02 23:41:54 +0000576 // If the copy constructor has not yet been declared, do so now.
Richard Smith2be35f52012-12-01 02:35:44 +0000577 if (Class->needsImplicitCopyConstructor())
Douglas Gregora6d69502010-07-02 23:41:54 +0000578 DeclareImplicitCopyConstructor(Class);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000579
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000580 // If the copy assignment operator has not yet been declared, do so now.
Richard Smith2be35f52012-12-01 02:35:44 +0000581 if (Class->needsImplicitCopyAssignment())
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000582 DeclareImplicitCopyAssignment(Class);
583
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000584 if (getLangOpts().CPlusPlus11) {
Sebastian Redl22653ba2011-08-30 19:58:05 +0000585 // If the move constructor has not yet been declared, do so now.
586 if (Class->needsImplicitMoveConstructor())
587 DeclareImplicitMoveConstructor(Class); // might not actually do it
588
589 // If the move assignment operator has not yet been declared, do so now.
590 if (Class->needsImplicitMoveAssignment())
591 DeclareImplicitMoveAssignment(Class); // might not actually do it
592 }
593
Douglas Gregor7454c562010-07-02 20:37:36 +0000594 // If the destructor has not yet been declared, do so now.
Richard Smith2be35f52012-12-01 02:35:44 +0000595 if (Class->needsImplicitDestructor())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000596 DeclareImplicitDestructor(Class);
Douglas Gregor7454c562010-07-02 20:37:36 +0000597}
598
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000599/// \brief Determine whether this is the name of an implicitly-declared
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000600/// special member function.
601static bool isImplicitlyDeclaredMemberFunctionName(DeclarationName Name) {
602 switch (Name.getNameKind()) {
Douglas Gregora6d69502010-07-02 23:41:54 +0000603 case DeclarationName::CXXConstructorName:
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000604 case DeclarationName::CXXDestructorName:
605 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000606
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000607 case DeclarationName::CXXOperatorName:
608 return Name.getCXXOverloadedOperator() == OO_Equal;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000609
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000610 default:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000611 break;
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000612 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000613
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000614 return false;
615}
616
617/// \brief If there are any implicit member functions with the given name
618/// that need to be declared in the given declaration context, do so.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000619static void DeclareImplicitMemberFunctionsWithName(Sema &S,
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000620 DeclarationName Name,
621 const DeclContext *DC) {
622 if (!DC)
623 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000624
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000625 switch (Name.getNameKind()) {
Douglas Gregora6d69502010-07-02 23:41:54 +0000626 case DeclarationName::CXXConstructorName:
627 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
Richard Smith7d125a12012-11-27 21:20:31 +0000628 if (Record->getDefinition() && CanDeclareSpecialMemberFunction(Record)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +0000629 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(Record);
Alexis Huntea6f0322011-05-11 22:34:38 +0000630 if (Record->needsImplicitDefaultConstructor())
Sebastian Redl22653ba2011-08-30 19:58:05 +0000631 S.DeclareImplicitDefaultConstructor(Class);
Richard Smith2be35f52012-12-01 02:35:44 +0000632 if (Record->needsImplicitCopyConstructor())
Sebastian Redl22653ba2011-08-30 19:58:05 +0000633 S.DeclareImplicitCopyConstructor(Class);
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000634 if (S.getLangOpts().CPlusPlus11 &&
Sebastian Redl22653ba2011-08-30 19:58:05 +0000635 Record->needsImplicitMoveConstructor())
636 S.DeclareImplicitMoveConstructor(Class);
Douglas Gregor9672f922010-07-03 00:47:00 +0000637 }
Douglas Gregora6d69502010-07-02 23:41:54 +0000638 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000639
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000640 case DeclarationName::CXXDestructorName:
641 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
Richard Smith2be35f52012-12-01 02:35:44 +0000642 if (Record->getDefinition() && Record->needsImplicitDestructor() &&
Richard Smith7d125a12012-11-27 21:20:31 +0000643 CanDeclareSpecialMemberFunction(Record))
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000644 S.DeclareImplicitDestructor(const_cast<CXXRecordDecl *>(Record));
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000645 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000646
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000647 case DeclarationName::CXXOperatorName:
648 if (Name.getCXXOverloadedOperator() != OO_Equal)
649 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000650
Sebastian Redl22653ba2011-08-30 19:58:05 +0000651 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC)) {
Richard Smith7d125a12012-11-27 21:20:31 +0000652 if (Record->getDefinition() && CanDeclareSpecialMemberFunction(Record)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +0000653 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(Record);
Richard Smith2be35f52012-12-01 02:35:44 +0000654 if (Record->needsImplicitCopyAssignment())
Sebastian Redl22653ba2011-08-30 19:58:05 +0000655 S.DeclareImplicitCopyAssignment(Class);
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000656 if (S.getLangOpts().CPlusPlus11 &&
Sebastian Redl22653ba2011-08-30 19:58:05 +0000657 Record->needsImplicitMoveAssignment())
658 S.DeclareImplicitMoveAssignment(Class);
659 }
660 }
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000661 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000662
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000663 default:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000664 break;
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000665 }
666}
Douglas Gregor7454c562010-07-02 20:37:36 +0000667
John McCall9f3059a2009-10-09 21:13:30 +0000668// Adds all qualifying matches for a name within a decl context to the
669// given lookup result. Returns true if any matches were found.
Douglas Gregord3a59182010-02-12 05:48:04 +0000670static bool LookupDirect(Sema &S, LookupResult &R, const DeclContext *DC) {
John McCall9f3059a2009-10-09 21:13:30 +0000671 bool Found = false;
672
Douglas Gregor7454c562010-07-02 20:37:36 +0000673 // Lazily declare C++ special member functions.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000674 if (S.getLangOpts().CPlusPlus)
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000675 DeclareImplicitMemberFunctionsWithName(S, R.getLookupName(), DC);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000676
Douglas Gregor7454c562010-07-02 20:37:36 +0000677 // Perform lookup into this declaration context.
Richard Smithcf4bdde2015-02-21 02:45:19 +0000678 DeclContext::lookup_result DR = DC->lookup(R.getLookupName());
679 for (DeclContext::lookup_iterator I = DR.begin(), E = DR.end(); I != E;
David Blaikieff7d47a2012-12-19 00:45:41 +0000680 ++I) {
John McCall401982f2010-01-20 21:53:11 +0000681 NamedDecl *D = *I;
Douglas Gregor4a814562011-12-14 16:03:29 +0000682 if ((D = R.getAcceptableDecl(D))) {
John McCall401982f2010-01-20 21:53:11 +0000683 R.addDecl(D);
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000684 Found = true;
685 }
686 }
John McCall9f3059a2009-10-09 21:13:30 +0000687
Douglas Gregord3a59182010-02-12 05:48:04 +0000688 if (!Found && DC->isTranslationUnit() && LookupBuiltin(S, R))
689 return true;
690
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000691 if (R.getLookupName().getNameKind()
Chandler Carruth3a693b72010-01-31 11:44:02 +0000692 != DeclarationName::CXXConversionFunctionName ||
693 R.getLookupName().getCXXNameType()->isDependentType() ||
694 !isa<CXXRecordDecl>(DC))
695 return Found;
696
697 // C++ [temp.mem]p6:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000698 // A specialization of a conversion function template is not found by
Chandler Carruth3a693b72010-01-31 11:44:02 +0000699 // name lookup. Instead, any conversion function templates visible in the
700 // context of the use are considered. [...]
701 const CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
John McCallf937c022011-10-07 06:10:15 +0000702 if (!Record->isCompleteDefinition())
Chandler Carruth3a693b72010-01-31 11:44:02 +0000703 return Found;
704
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +0000705 for (CXXRecordDecl::conversion_iterator U = Record->conversion_begin(),
706 UEnd = Record->conversion_end(); U != UEnd; ++U) {
Chandler Carruth3a693b72010-01-31 11:44:02 +0000707 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(*U);
708 if (!ConvTemplate)
709 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000710
Chandler Carruth3a693b72010-01-31 11:44:02 +0000711 // When we're performing lookup for the purposes of redeclaration, just
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000712 // add the conversion function template. When we deduce template
713 // arguments for specializations, we'll end up unifying the return
Chandler Carruth3a693b72010-01-31 11:44:02 +0000714 // type of the new declaration with the type of the function template.
715 if (R.isForRedeclaration()) {
716 R.addDecl(ConvTemplate);
717 Found = true;
718 continue;
719 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000720
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000721 // C++ [temp.mem]p6:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000722 // [...] For each such operator, if argument deduction succeeds
723 // (14.9.2.3), the resulting specialization is used as if found by
Chandler Carruth3a693b72010-01-31 11:44:02 +0000724 // name lookup.
725 //
726 // When referencing a conversion function for any purpose other than
727 // a redeclaration (such that we'll be building an expression with the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000728 // result), perform template argument deduction and place the
Chandler Carruth3a693b72010-01-31 11:44:02 +0000729 // specialization into the result set. We do this to avoid forcing all
730 // callers to perform special deduction for conversion functions.
Craig Toppere6706e42012-09-19 02:26:47 +0000731 TemplateDeductionInfo Info(R.getNameLoc());
Craig Topperc3ec1492014-05-26 06:22:03 +0000732 FunctionDecl *Specialization = nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000733
734 const FunctionProtoType *ConvProto
Chandler Carruth3a693b72010-01-31 11:44:02 +0000735 = ConvTemplate->getTemplatedDecl()->getType()->getAs<FunctionProtoType>();
736 assert(ConvProto && "Nonsensical conversion function template type");
Douglas Gregor3c96a462010-01-12 01:17:50 +0000737
Chandler Carruth3a693b72010-01-31 11:44:02 +0000738 // Compute the type of the function that we would expect the conversion
739 // function to have, if it were to match the name given.
740 // FIXME: Calling convention!
John McCalldb40c7f2010-12-14 08:05:40 +0000741 FunctionProtoType::ExtProtoInfo EPI = ConvProto->getExtProtoInfo();
Reid Kleckner78af0702013-08-27 23:08:25 +0000742 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(CC_C);
Richard Smith8acb4282014-07-31 21:57:55 +0000743 EPI.ExceptionSpec = EST_None;
Chandler Carruth3a693b72010-01-31 11:44:02 +0000744 QualType ExpectedType
745 = R.getSema().Context.getFunctionType(R.getLookupName().getCXXNameType(),
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +0000746 None, EPI);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000747
Chandler Carruth3a693b72010-01-31 11:44:02 +0000748 // Perform template argument deduction against the type that we would
749 // expect the function to have.
Craig Topperc3ec1492014-05-26 06:22:03 +0000750 if (R.getSema().DeduceTemplateArguments(ConvTemplate, nullptr, ExpectedType,
Chandler Carruth3a693b72010-01-31 11:44:02 +0000751 Specialization, Info)
752 == Sema::TDK_Success) {
753 R.addDecl(Specialization);
754 Found = true;
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000755 }
756 }
Chandler Carruth3a693b72010-01-31 11:44:02 +0000757
John McCall9f3059a2009-10-09 21:13:30 +0000758 return Found;
759}
760
John McCallf6c8a4e2009-11-10 07:01:13 +0000761// Performs C++ unqualified lookup into the given file context.
John McCall9f3059a2009-10-09 21:13:30 +0000762static bool
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000763CppNamespaceLookup(Sema &S, LookupResult &R, ASTContext &Context,
Douglas Gregord3a59182010-02-12 05:48:04 +0000764 DeclContext *NS, UnqualUsingDirectiveSet &UDirs) {
Douglas Gregor700792c2009-02-05 19:25:20 +0000765
766 assert(NS && NS->isFileContext() && "CppNamespaceLookup() requires namespace!");
767
John McCallf6c8a4e2009-11-10 07:01:13 +0000768 // Perform direct name lookup into the LookupCtx.
Douglas Gregord3a59182010-02-12 05:48:04 +0000769 bool Found = LookupDirect(S, R, NS);
Douglas Gregor700792c2009-02-05 19:25:20 +0000770
John McCallf6c8a4e2009-11-10 07:01:13 +0000771 // Perform direct name lookup into the namespaces nominated by the
772 // using directives whose common ancestor is this namespace.
Benjamin Kramerb4ef6682015-02-06 17:25:10 +0000773 for (const UnqualUsingEntry &UUE : UDirs.getNamespacesFor(NS))
774 if (LookupDirect(S, R, UUE.getNominatedNamespace()))
John McCallf6c8a4e2009-11-10 07:01:13 +0000775 Found = true;
John McCall9f3059a2009-10-09 21:13:30 +0000776
777 R.resolveKind();
778
779 return Found;
Douglas Gregor700792c2009-02-05 19:25:20 +0000780}
781
782static bool isNamespaceOrTranslationUnitScope(Scope *S) {
Ted Kremenekc37877d2013-10-08 17:08:03 +0000783 if (DeclContext *Ctx = S->getEntity())
Douglas Gregor700792c2009-02-05 19:25:20 +0000784 return Ctx->isFileContext();
785 return false;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000786}
Douglas Gregored8f2882009-01-30 01:04:22 +0000787
Douglas Gregor66230062010-03-15 14:33:29 +0000788// Find the next outer declaration context from this scope. This
789// routine actually returns the semantic outer context, which may
790// differ from the lexical context (encoded directly in the Scope
791// stack) when we are parsing a member of a class template. In this
792// case, the second element of the pair will be true, to indicate that
793// name lookup should continue searching in this semantic context when
794// it leaves the current template parameter scope.
795static std::pair<DeclContext *, bool> findOuterContext(Scope *S) {
Ted Kremenekc37877d2013-10-08 17:08:03 +0000796 DeclContext *DC = S->getEntity();
Craig Topperc3ec1492014-05-26 06:22:03 +0000797 DeclContext *Lexical = nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000798 for (Scope *OuterS = S->getParent(); OuterS;
Douglas Gregor66230062010-03-15 14:33:29 +0000799 OuterS = OuterS->getParent()) {
800 if (OuterS->getEntity()) {
Ted Kremenekc37877d2013-10-08 17:08:03 +0000801 Lexical = OuterS->getEntity();
Douglas Gregor66230062010-03-15 14:33:29 +0000802 break;
803 }
804 }
805
806 // C++ [temp.local]p8:
807 // In the definition of a member of a class template that appears
808 // outside of the namespace containing the class template
809 // definition, the name of a template-parameter hides the name of
810 // a member of this namespace.
811 //
812 // Example:
813 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000814 // namespace N {
815 // class C { };
Douglas Gregor66230062010-03-15 14:33:29 +0000816 //
817 // template<class T> class B {
818 // void f(T);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000819 // };
Douglas Gregor66230062010-03-15 14:33:29 +0000820 // }
821 //
822 // template<class C> void N::B<C>::f(C) {
823 // C b; // C is the template parameter, not N::C
824 // }
825 //
826 // In this example, the lexical context we return is the
827 // TranslationUnit, while the semantic context is the namespace N.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000828 if (!Lexical || !DC || !S->getParent() ||
Douglas Gregor66230062010-03-15 14:33:29 +0000829 !S->getParent()->isTemplateParamScope())
830 return std::make_pair(Lexical, false);
831
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000832 // Find the outermost template parameter scope.
Douglas Gregor66230062010-03-15 14:33:29 +0000833 // For the example, this is the scope for the template parameters of
834 // template<class C>.
835 Scope *OutermostTemplateScope = S->getParent();
836 while (OutermostTemplateScope->getParent() &&
837 OutermostTemplateScope->getParent()->isTemplateParamScope())
838 OutermostTemplateScope = OutermostTemplateScope->getParent();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000839
Douglas Gregor66230062010-03-15 14:33:29 +0000840 // Find the namespace context in which the original scope occurs. In
841 // the example, this is namespace N.
842 DeclContext *Semantic = DC;
843 while (!Semantic->isFileContext())
844 Semantic = Semantic->getParent();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000845
Douglas Gregor66230062010-03-15 14:33:29 +0000846 // Find the declaration context just outside of the template
847 // parameter scope. This is the context in which the template is
848 // being lexically declaration (a namespace context). In the
849 // example, this is the global scope.
850 if (Lexical->isFileContext() && !Lexical->Equals(Semantic) &&
851 Lexical->Encloses(Semantic))
852 return std::make_pair(Semantic, true);
853
854 return std::make_pair(Lexical, false);
Douglas Gregor7f737c02009-09-10 16:57:35 +0000855}
856
Richard Smith541b38b2013-09-20 01:15:31 +0000857namespace {
858/// An RAII object to specify that we want to find block scope extern
859/// declarations.
860struct FindLocalExternScope {
861 FindLocalExternScope(LookupResult &R)
862 : R(R), OldFindLocalExtern(R.getIdentifierNamespace() &
863 Decl::IDNS_LocalExtern) {
864 R.setFindLocalExtern(R.getIdentifierNamespace() & Decl::IDNS_Ordinary);
865 }
866 void restore() {
867 R.setFindLocalExtern(OldFindLocalExtern);
868 }
869 ~FindLocalExternScope() {
870 restore();
871 }
872 LookupResult &R;
873 bool OldFindLocalExtern;
874};
875}
876
John McCall27b18f82009-11-17 02:14:36 +0000877bool Sema::CppLookupName(LookupResult &R, Scope *S) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000878 assert(getLangOpts().CPlusPlus && "Can perform only C++ lookup");
John McCall27b18f82009-11-17 02:14:36 +0000879
880 DeclarationName Name = R.getLookupName();
Richard Smith1c34fb72013-08-13 18:18:50 +0000881 Sema::LookupNameKind NameKind = R.getLookupKind();
John McCall27b18f82009-11-17 02:14:36 +0000882
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000883 // If this is the name of an implicitly-declared special member function,
884 // go through the scope stack to implicitly declare
885 if (isImplicitlyDeclaredMemberFunctionName(Name)) {
886 for (Scope *PreS = S; PreS; PreS = PreS->getParent())
Ted Kremenekc37877d2013-10-08 17:08:03 +0000887 if (DeclContext *DC = PreS->getEntity())
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000888 DeclareImplicitMemberFunctionsWithName(*this, Name, DC);
889 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000890
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000891 // Implicitly declare member functions with the name we're looking for, if in
892 // fact we are in a scope where it matters.
893
Douglas Gregor889ceb72009-02-03 19:21:40 +0000894 Scope *Initial = S;
Mike Stump11289f42009-09-09 15:08:12 +0000895 IdentifierResolver::iterator
Douglas Gregor889ceb72009-02-03 19:21:40 +0000896 I = IdResolver.begin(Name),
897 IEnd = IdResolver.end();
Douglas Gregored8f2882009-01-30 01:04:22 +0000898
Douglas Gregor889ceb72009-02-03 19:21:40 +0000899 // First we lookup local scope.
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000900 // We don't consider using-directives, as per 7.3.4.p1 [namespace.udir]
Douglas Gregor889ceb72009-02-03 19:21:40 +0000901 // ...During unqualified name lookup (3.4.1), the names appear as if
902 // they were declared in the nearest enclosing namespace which contains
903 // both the using-directive and the nominated namespace.
Eli Friedman44b83ee2009-08-05 19:21:58 +0000904 // [Note: in this context, "contains" means "contains directly or
Mike Stump11289f42009-09-09 15:08:12 +0000905 // indirectly".
Douglas Gregor889ceb72009-02-03 19:21:40 +0000906 //
907 // For example:
908 // namespace A { int i; }
909 // void foo() {
910 // int i;
911 // {
912 // using namespace A;
913 // ++i; // finds local 'i', A::i appears at global scope
914 // }
915 // }
Douglas Gregor2ada0482009-02-04 17:27:36 +0000916 //
Douglas Gregorcc9406c2013-04-08 23:11:25 +0000917 UnqualUsingDirectiveSet UDirs;
918 bool VisitedUsingDirectives = false;
Richard Smith1c34fb72013-08-13 18:18:50 +0000919 bool LeftStartingScope = false;
Craig Topperc3ec1492014-05-26 06:22:03 +0000920 DeclContext *OutsideOfTemplateParamDC = nullptr;
Richard Smith541b38b2013-09-20 01:15:31 +0000921
922 // When performing a scope lookup, we want to find local extern decls.
923 FindLocalExternScope FindLocals(R);
924
Douglas Gregor700792c2009-02-05 19:25:20 +0000925 for (; S && !isNamespaceOrTranslationUnitScope(S); S = S->getParent()) {
Ted Kremenekc37877d2013-10-08 17:08:03 +0000926 DeclContext *Ctx = S->getEntity();
Douglas Gregor3e51e172010-05-20 20:58:56 +0000927
Douglas Gregor889ceb72009-02-03 19:21:40 +0000928 // Check whether the IdResolver has anything in this scope.
John McCall9f3059a2009-10-09 21:13:30 +0000929 bool Found = false;
John McCall48871652010-08-21 09:40:31 +0000930 for (; I != IEnd && S->isDeclScope(*I); ++I) {
Douglas Gregor4a814562011-12-14 16:03:29 +0000931 if (NamedDecl *ND = R.getAcceptableDecl(*I)) {
Richard Smith1c34fb72013-08-13 18:18:50 +0000932 if (NameKind == LookupRedeclarationWithLinkage) {
933 // Determine whether this (or a previous) declaration is
934 // out-of-scope.
935 if (!LeftStartingScope && !Initial->isDeclScope(*I))
936 LeftStartingScope = true;
937
938 // If we found something outside of our starting scope that
Richard Smith9a00bbf2013-10-16 21:12:00 +0000939 // does not have linkage, skip it. If it's a template parameter,
940 // we still find it, so we can diagnose the invalid redeclaration.
941 if (LeftStartingScope && !((*I)->hasLinkage()) &&
942 !(*I)->isTemplateParameter()) {
Richard Smith1c34fb72013-08-13 18:18:50 +0000943 R.setShadowed();
944 continue;
945 }
946 }
947
John McCall9f3059a2009-10-09 21:13:30 +0000948 Found = true;
Douglas Gregor4a814562011-12-14 16:03:29 +0000949 R.addDecl(ND);
Douglas Gregor889ceb72009-02-03 19:21:40 +0000950 }
951 }
John McCall9f3059a2009-10-09 21:13:30 +0000952 if (Found) {
953 R.resolveKind();
Douglas Gregor3e51e172010-05-20 20:58:56 +0000954 if (S->isClassScope())
955 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(Ctx))
956 R.setNamingClass(Record);
John McCall9f3059a2009-10-09 21:13:30 +0000957 return true;
958 }
959
Richard Smith1c34fb72013-08-13 18:18:50 +0000960 if (NameKind == LookupLocalFriendName && !S->isClassScope()) {
Richard Smith114394f2013-08-09 04:35:01 +0000961 // C++11 [class.friend]p11:
962 // If a friend declaration appears in a local class and the name
963 // specified is an unqualified name, a prior declaration is
964 // looked up without considering scopes that are outside the
965 // innermost enclosing non-class scope.
966 return false;
967 }
968
Douglas Gregor66230062010-03-15 14:33:29 +0000969 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
970 S->getParent() && !S->getParent()->isTemplateParamScope()) {
971 // We've just searched the last template parameter scope and
Sylvestre Ledru830885c2012-07-23 08:59:39 +0000972 // found nothing, so look into the contexts between the
Douglas Gregor66230062010-03-15 14:33:29 +0000973 // lexical and semantic declaration contexts returned by
974 // findOuterContext(). This implements the name lookup behavior
975 // of C++ [temp.local]p8.
976 Ctx = OutsideOfTemplateParamDC;
Craig Topperc3ec1492014-05-26 06:22:03 +0000977 OutsideOfTemplateParamDC = nullptr;
Douglas Gregor66230062010-03-15 14:33:29 +0000978 }
979
980 if (Ctx) {
981 DeclContext *OuterCtx;
982 bool SearchAfterTemplateScope;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000983 std::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
Douglas Gregor66230062010-03-15 14:33:29 +0000984 if (SearchAfterTemplateScope)
985 OutsideOfTemplateParamDC = OuterCtx;
986
Douglas Gregorea166062010-03-15 15:26:48 +0000987 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
Douglas Gregor337caf92010-02-19 16:08:35 +0000988 // We do not directly look into transparent contexts, since
989 // those entities will be found in the nearest enclosing
990 // non-transparent context.
991 if (Ctx->isTransparentContext())
Douglas Gregor7f737c02009-09-10 16:57:35 +0000992 continue;
Douglas Gregor337caf92010-02-19 16:08:35 +0000993
994 // We do not look directly into function or method contexts,
995 // since all of the local variables and parameters of the
996 // function/method are present within the Scope.
997 if (Ctx->isFunctionOrMethod()) {
998 // If we have an Objective-C instance method, look for ivars
999 // in the corresponding interface.
1000 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
1001 if (Method->isInstanceMethod() && Name.getAsIdentifierInfo())
1002 if (ObjCInterfaceDecl *Class = Method->getClassInterface()) {
1003 ObjCInterfaceDecl *ClassDeclared;
1004 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001005 Name.getAsIdentifierInfo(),
Douglas Gregor337caf92010-02-19 16:08:35 +00001006 ClassDeclared)) {
Douglas Gregor4a814562011-12-14 16:03:29 +00001007 if (NamedDecl *ND = R.getAcceptableDecl(Ivar)) {
1008 R.addDecl(ND);
Douglas Gregor337caf92010-02-19 16:08:35 +00001009 R.resolveKind();
1010 return true;
1011 }
1012 }
1013 }
1014 }
1015
1016 continue;
1017 }
1018
Douglas Gregorb0d0aa52013-03-27 12:51:49 +00001019 // If this is a file context, we need to perform unqualified name
1020 // lookup considering using directives.
1021 if (Ctx->isFileContext()) {
Douglas Gregorcc9406c2013-04-08 23:11:25 +00001022 // If we haven't handled using directives yet, do so now.
1023 if (!VisitedUsingDirectives) {
1024 // Add using directives from this context up to the top level.
Douglas Gregor8ccbc182013-04-09 01:49:26 +00001025 for (DeclContext *UCtx = Ctx; UCtx; UCtx = UCtx->getParent()) {
1026 if (UCtx->isTransparentContext())
1027 continue;
1028
Douglas Gregorcc9406c2013-04-08 23:11:25 +00001029 UDirs.visit(UCtx, UCtx);
Douglas Gregor8ccbc182013-04-09 01:49:26 +00001030 }
Douglas Gregorcc9406c2013-04-08 23:11:25 +00001031
1032 // Find the innermost file scope, so we can add using directives
1033 // from local scopes.
1034 Scope *InnermostFileScope = S;
1035 while (InnermostFileScope &&
1036 !isNamespaceOrTranslationUnitScope(InnermostFileScope))
1037 InnermostFileScope = InnermostFileScope->getParent();
1038 UDirs.visitScopeChain(Initial, InnermostFileScope);
1039
1040 UDirs.done();
1041
1042 VisitedUsingDirectives = true;
1043 }
Douglas Gregorb0d0aa52013-03-27 12:51:49 +00001044
1045 if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs)) {
1046 R.resolveKind();
1047 return true;
1048 }
1049
1050 continue;
1051 }
1052
Douglas Gregor7f737c02009-09-10 16:57:35 +00001053 // Perform qualified name lookup into this context.
1054 // FIXME: In some cases, we know that every name that could be found by
1055 // this qualified name lookup will also be on the identifier chain. For
1056 // example, inside a class without any base classes, we never need to
1057 // perform qualified lookup because all of the members are on top of the
1058 // identifier chain.
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001059 if (LookupQualifiedName(R, Ctx, /*InUnqualifiedLookup=*/true))
John McCall9f3059a2009-10-09 21:13:30 +00001060 return true;
Douglas Gregorfdca4a72009-03-27 04:21:56 +00001061 }
Douglas Gregor700792c2009-02-05 19:25:20 +00001062 }
Douglas Gregored8f2882009-01-30 01:04:22 +00001063 }
Douglas Gregor889ceb72009-02-03 19:21:40 +00001064
John McCallf6c8a4e2009-11-10 07:01:13 +00001065 // Stop if we ran out of scopes.
1066 // FIXME: This really, really shouldn't be happening.
1067 if (!S) return false;
1068
Argyrios Kyrtzidis706bbf82010-10-29 16:12:50 +00001069 // If we are looking for members, no need to look into global/namespace scope.
Richard Smith1c34fb72013-08-13 18:18:50 +00001070 if (NameKind == LookupMemberName)
Argyrios Kyrtzidis706bbf82010-10-29 16:12:50 +00001071 return false;
1072
Douglas Gregor700792c2009-02-05 19:25:20 +00001073 // Collect UsingDirectiveDecls in all scopes, and recursively all
Douglas Gregor889ceb72009-02-03 19:21:40 +00001074 // nominated namespaces by those using-directives.
John McCallf6c8a4e2009-11-10 07:01:13 +00001075 //
Mike Stump87c57ac2009-05-16 07:39:55 +00001076 // FIXME: Cache this sorted list in Scope structure, and DeclContext, so we
1077 // don't build it for each lookup!
Douglas Gregorcc9406c2013-04-08 23:11:25 +00001078 if (!VisitedUsingDirectives) {
1079 UDirs.visitScopeChain(Initial, S);
1080 UDirs.done();
1081 }
Richard Smith541b38b2013-09-20 01:15:31 +00001082
1083 // If we're not performing redeclaration lookup, do not look for local
1084 // extern declarations outside of a function scope.
1085 if (!R.isForRedeclaration())
1086 FindLocals.restore();
1087
Douglas Gregor700792c2009-02-05 19:25:20 +00001088 // Lookup namespace scope, and global scope.
Douglas Gregor889ceb72009-02-03 19:21:40 +00001089 // Unqualified name lookup in C++ requires looking into scopes
1090 // that aren't strictly lexical, and therefore we walk through the
1091 // context as well as walking through the scopes.
1092 for (; S; S = S->getParent()) {
Douglas Gregor889ceb72009-02-03 19:21:40 +00001093 // Check whether the IdResolver has anything in this scope.
John McCall9f3059a2009-10-09 21:13:30 +00001094 bool Found = false;
John McCall48871652010-08-21 09:40:31 +00001095 for (; I != IEnd && S->isDeclScope(*I); ++I) {
Douglas Gregor4a814562011-12-14 16:03:29 +00001096 if (NamedDecl *ND = R.getAcceptableDecl(*I)) {
Douglas Gregor889ceb72009-02-03 19:21:40 +00001097 // We found something. Look for anything else in our scope
1098 // with this same name and in an acceptable identifier
1099 // namespace, so that we can construct an overload set if we
1100 // need to.
John McCall9f3059a2009-10-09 21:13:30 +00001101 Found = true;
Douglas Gregor4a814562011-12-14 16:03:29 +00001102 R.addDecl(ND);
Douglas Gregor889ceb72009-02-03 19:21:40 +00001103 }
1104 }
1105
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001106 if (Found && S->isTemplateParamScope()) {
John McCall9f3059a2009-10-09 21:13:30 +00001107 R.resolveKind();
1108 return true;
1109 }
1110
Ted Kremenekc37877d2013-10-08 17:08:03 +00001111 DeclContext *Ctx = S->getEntity();
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001112 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
1113 S->getParent() && !S->getParent()->isTemplateParamScope()) {
1114 // We've just searched the last template parameter scope and
Sylvestre Ledru830885c2012-07-23 08:59:39 +00001115 // found nothing, so look into the contexts between the
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001116 // lexical and semantic declaration contexts returned by
1117 // findOuterContext(). This implements the name lookup behavior
1118 // of C++ [temp.local]p8.
1119 Ctx = OutsideOfTemplateParamDC;
Craig Topperc3ec1492014-05-26 06:22:03 +00001120 OutsideOfTemplateParamDC = nullptr;
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001121 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001122
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001123 if (Ctx) {
1124 DeclContext *OuterCtx;
1125 bool SearchAfterTemplateScope;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001126 std::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001127 if (SearchAfterTemplateScope)
1128 OutsideOfTemplateParamDC = OuterCtx;
1129
1130 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
1131 // We do not directly look into transparent contexts, since
1132 // those entities will be found in the nearest enclosing
1133 // non-transparent context.
1134 if (Ctx->isTransparentContext())
1135 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001136
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001137 // If we have a context, and it's not a context stashed in the
1138 // template parameter scope for an out-of-line definition, also
1139 // look into that context.
1140 if (!(Found && S && S->isTemplateParamScope())) {
1141 assert(Ctx->isFileContext() &&
1142 "We should have been looking only at file context here already.");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001143
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001144 // Look into context considering using-directives.
1145 if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs))
1146 Found = true;
1147 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001148
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001149 if (Found) {
1150 R.resolveKind();
1151 return true;
1152 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001153
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001154 if (R.isForRedeclaration() && !Ctx->isTransparentContext())
1155 return false;
1156 }
1157 }
1158
Douglas Gregor3ce74932010-02-05 07:07:10 +00001159 if (R.isForRedeclaration() && Ctx && !Ctx->isTransparentContext())
John McCall9f3059a2009-10-09 21:13:30 +00001160 return false;
Douglas Gregor700792c2009-02-05 19:25:20 +00001161 }
Douglas Gregor889ceb72009-02-03 19:21:40 +00001162
John McCall9f3059a2009-10-09 21:13:30 +00001163 return !R.empty();
Douglas Gregored8f2882009-01-30 01:04:22 +00001164}
1165
Richard Smith0e5d7b82013-07-25 23:08:39 +00001166/// \brief Find the declaration that a class temploid member specialization was
1167/// instantiated from, or the member itself if it is an explicit specialization.
1168static Decl *getInstantiatedFrom(Decl *D, MemberSpecializationInfo *MSInfo) {
1169 return MSInfo->isExplicitSpecialization() ? D : MSInfo->getInstantiatedFrom();
1170}
1171
1172/// \brief Find the module in which the given declaration was defined.
1173static Module *getDefiningModule(Decl *Entity) {
1174 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Entity)) {
1175 // If this function was instantiated from a template, the defining module is
1176 // the module containing the pattern.
1177 if (FunctionDecl *Pattern = FD->getTemplateInstantiationPattern())
1178 Entity = Pattern;
1179 } else if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Entity)) {
Reid Klecknere7367d62014-10-14 20:28:40 +00001180 if (CXXRecordDecl *Pattern = RD->getTemplateInstantiationPattern())
1181 Entity = Pattern;
Richard Smith0e5d7b82013-07-25 23:08:39 +00001182 } else if (EnumDecl *ED = dyn_cast<EnumDecl>(Entity)) {
1183 if (MemberSpecializationInfo *MSInfo = ED->getMemberSpecializationInfo())
1184 Entity = getInstantiatedFrom(ED, MSInfo);
1185 } else if (VarDecl *VD = dyn_cast<VarDecl>(Entity)) {
1186 // FIXME: Map from variable template specializations back to the template.
1187 if (MemberSpecializationInfo *MSInfo = VD->getMemberSpecializationInfo())
1188 Entity = getInstantiatedFrom(VD, MSInfo);
1189 }
1190
1191 // Walk up to the containing context. That might also have been instantiated
1192 // from a template.
1193 DeclContext *Context = Entity->getDeclContext();
1194 if (Context->isFileContext())
1195 return Entity->getOwningModule();
1196 return getDefiningModule(cast<Decl>(Context));
1197}
1198
1199llvm::DenseSet<Module*> &Sema::getLookupModules() {
1200 unsigned N = ActiveTemplateInstantiations.size();
1201 for (unsigned I = ActiveTemplateInstantiationLookupModules.size();
1202 I != N; ++I) {
1203 Module *M = getDefiningModule(ActiveTemplateInstantiations[I].Entity);
1204 if (M && !LookupModulesCache.insert(M).second)
Craig Topperc3ec1492014-05-26 06:22:03 +00001205 M = nullptr;
Richard Smith0e5d7b82013-07-25 23:08:39 +00001206 ActiveTemplateInstantiationLookupModules.push_back(M);
1207 }
1208 return LookupModulesCache;
1209}
1210
1211/// \brief Determine whether a declaration is visible to name lookup.
1212///
1213/// This routine determines whether the declaration D is visible in the current
1214/// lookup context, taking into account the current template instantiation
1215/// stack. During template instantiation, a declaration is visible if it is
1216/// visible from a module containing any entity on the template instantiation
1217/// path (by instantiating a template, you allow it to see the declarations that
1218/// your module can see, including those later on in your module).
1219bool LookupResult::isVisibleSlow(Sema &SemaRef, NamedDecl *D) {
1220 assert(D->isHidden() && !SemaRef.ActiveTemplateInstantiations.empty() &&
1221 "should not call this: not in slow case");
1222 Module *DeclModule = D->getOwningModule();
1223 assert(DeclModule && "hidden decl not from a module");
1224
1225 // Find the extra places where we need to look.
1226 llvm::DenseSet<Module*> &LookupModules = SemaRef.getLookupModules();
1227 if (LookupModules.empty())
1228 return false;
1229
1230 // If our lookup set contains the decl's module, it's visible.
1231 if (LookupModules.count(DeclModule))
1232 return true;
1233
1234 // If the declaration isn't exported, it's not visible in any other module.
1235 if (D->isModulePrivate())
1236 return false;
1237
1238 // Check whether DeclModule is transitively exported to an import of
1239 // the lookup set.
1240 for (llvm::DenseSet<Module *>::iterator I = LookupModules.begin(),
1241 E = LookupModules.end();
1242 I != E; ++I)
1243 if ((*I)->isModuleVisible(DeclModule))
1244 return true;
1245 return false;
1246}
1247
Douglas Gregor4a814562011-12-14 16:03:29 +00001248/// \brief Retrieve the visible declaration corresponding to D, if any.
1249///
1250/// This routine determines whether the declaration D is visible in the current
1251/// module, with the current imports. If not, it checks whether any
1252/// redeclaration of D is visible, and if so, returns that declaration.
Richard Smith0e5d7b82013-07-25 23:08:39 +00001253///
Douglas Gregor4a814562011-12-14 16:03:29 +00001254/// \returns D, or a visible previous declaration of D, whichever is more recent
1255/// and visible. If no declaration of D is visible, returns null.
Richard Smithe156254d2013-08-20 20:35:18 +00001256static NamedDecl *findAcceptableDecl(Sema &SemaRef, NamedDecl *D) {
1257 assert(!LookupResult::isVisible(SemaRef, D) && "not in slow case");
Richard Smith0e5d7b82013-07-25 23:08:39 +00001258
Aaron Ballman86c93902014-03-06 23:45:36 +00001259 for (auto RD : D->redecls()) {
1260 if (auto ND = dyn_cast<NamedDecl>(RD)) {
Richard Smithe8292b12015-02-10 03:28:10 +00001261 // FIXME: This is wrong in the case where the previous declaration is not
1262 // visible in the same scope as D. This needs to be done much more
1263 // carefully.
Richard Smithe156254d2013-08-20 20:35:18 +00001264 if (LookupResult::isVisible(SemaRef, ND))
Douglas Gregor54079202012-01-06 22:05:37 +00001265 return ND;
1266 }
Douglas Gregor4a814562011-12-14 16:03:29 +00001267 }
Richard Smith0e5d7b82013-07-25 23:08:39 +00001268
Craig Topperc3ec1492014-05-26 06:22:03 +00001269 return nullptr;
Douglas Gregor4a814562011-12-14 16:03:29 +00001270}
1271
Richard Smithe156254d2013-08-20 20:35:18 +00001272NamedDecl *LookupResult::getAcceptableDeclSlow(NamedDecl *D) const {
Kaelyn Takatafc8c61a2014-11-11 23:00:42 +00001273 return findAcceptableDecl(getSema(), D);
Richard Smithe156254d2013-08-20 20:35:18 +00001274}
1275
Douglas Gregor34074322009-01-14 22:20:51 +00001276/// @brief Perform unqualified name lookup starting from a given
1277/// scope.
1278///
1279/// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is
1280/// used to find names within the current scope. For example, 'x' in
1281/// @code
1282/// int x;
1283/// int f() {
1284/// return x; // unqualified name look finds 'x' in the global scope
1285/// }
1286/// @endcode
1287///
1288/// Different lookup criteria can find different names. For example, a
1289/// particular scope can have both a struct and a function of the same
1290/// name, and each can be found by certain lookup criteria. For more
1291/// information about lookup criteria, see the documentation for the
1292/// class LookupCriteria.
1293///
1294/// @param S The scope from which unqualified name lookup will
1295/// begin. If the lookup criteria permits, name lookup may also search
1296/// in the parent scopes.
1297///
James Dennett91738ff2012-06-22 10:32:46 +00001298/// @param [in,out] R Specifies the lookup to perform (e.g., the name to
1299/// look up and the lookup kind), and is updated with the results of lookup
1300/// including zero or more declarations and possibly additional information
1301/// used to diagnose ambiguities.
Douglas Gregor34074322009-01-14 22:20:51 +00001302///
James Dennett91738ff2012-06-22 10:32:46 +00001303/// @returns \c true if lookup succeeded and false otherwise.
John McCall27b18f82009-11-17 02:14:36 +00001304bool Sema::LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation) {
1305 DeclarationName Name = R.getLookupName();
John McCall9f3059a2009-10-09 21:13:30 +00001306 if (!Name) return false;
Douglas Gregor34074322009-01-14 22:20:51 +00001307
John McCall27b18f82009-11-17 02:14:36 +00001308 LookupNameKind NameKind = R.getLookupKind();
1309
David Blaikiebbafb8a2012-03-11 07:00:24 +00001310 if (!getLangOpts().CPlusPlus) {
Douglas Gregor34074322009-01-14 22:20:51 +00001311 // Unqualified name lookup in C/Objective-C is purely lexical, so
1312 // search in the declarations attached to the name.
John McCallea305ed2009-12-18 10:40:03 +00001313 if (NameKind == Sema::LookupRedeclarationWithLinkage) {
Douglas Gregoreddf4332009-02-24 20:03:32 +00001314 // Find the nearest non-transparent declaration scope.
1315 while (!(S->getFlags() & Scope::DeclScope) ||
Ted Kremenekc37877d2013-10-08 17:08:03 +00001316 (S->getEntity() && S->getEntity()->isTransparentContext()))
Douglas Gregoreddf4332009-02-24 20:03:32 +00001317 S = S->getParent();
Douglas Gregored8f2882009-01-30 01:04:22 +00001318 }
1319
Richard Smith541b38b2013-09-20 01:15:31 +00001320 // When performing a scope lookup, we want to find local extern decls.
1321 FindLocalExternScope FindLocals(R);
1322
Douglas Gregor34074322009-01-14 22:20:51 +00001323 // Scan up the scope chain looking for a decl that matches this
1324 // identifier that is in the appropriate namespace. This search
1325 // should not take long, as shadowing of names is uncommon, and
1326 // deep shadowing is extremely uncommon.
Douglas Gregoreddf4332009-02-24 20:03:32 +00001327 bool LeftStartingScope = false;
1328
Douglas Gregored8f2882009-01-30 01:04:22 +00001329 for (IdentifierResolver::iterator I = IdResolver.begin(Name),
Mike Stump11289f42009-09-09 15:08:12 +00001330 IEnd = IdResolver.end();
Douglas Gregored8f2882009-01-30 01:04:22 +00001331 I != IEnd; ++I)
Richard Smith0e5d7b82013-07-25 23:08:39 +00001332 if (NamedDecl *D = R.getAcceptableDecl(*I)) {
Douglas Gregoreddf4332009-02-24 20:03:32 +00001333 if (NameKind == LookupRedeclarationWithLinkage) {
1334 // Determine whether this (or a previous) declaration is
1335 // out-of-scope.
John McCall48871652010-08-21 09:40:31 +00001336 if (!LeftStartingScope && !S->isDeclScope(*I))
Douglas Gregoreddf4332009-02-24 20:03:32 +00001337 LeftStartingScope = true;
1338
1339 // If we found something outside of our starting scope that
1340 // does not have linkage, skip it.
Richard Smith1c34fb72013-08-13 18:18:50 +00001341 if (LeftStartingScope && !((*I)->hasLinkage())) {
1342 R.setShadowed();
Douglas Gregoreddf4332009-02-24 20:03:32 +00001343 continue;
Richard Smith1c34fb72013-08-13 18:18:50 +00001344 }
Douglas Gregoreddf4332009-02-24 20:03:32 +00001345 }
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00001346 else if (NameKind == LookupObjCImplicitSelfParam &&
1347 !isa<ImplicitParamDecl>(*I))
1348 continue;
Richard Smith0e5d7b82013-07-25 23:08:39 +00001349
Douglas Gregor4a814562011-12-14 16:03:29 +00001350 R.addDecl(D);
John McCall9f3059a2009-10-09 21:13:30 +00001351
Douglas Gregorb59643b2012-01-03 23:26:26 +00001352 // Check whether there are any other declarations with the same name
1353 // and in the same scope.
Douglas Gregor9b7b3912012-01-04 16:44:10 +00001354 if (I != IEnd) {
Douglas Gregor81bd0382012-01-13 23:06:53 +00001355 // Find the scope in which this declaration was declared (if it
1356 // actually exists in a Scope).
1357 while (S && !S->isDeclScope(D))
1358 S = S->getParent();
1359
1360 // If the scope containing the declaration is the translation unit,
1361 // then we'll need to perform our checks based on the matching
1362 // DeclContexts rather than matching scopes.
1363 if (S && isNamespaceOrTranslationUnitScope(S))
Craig Topperc3ec1492014-05-26 06:22:03 +00001364 S = nullptr;
Douglas Gregor81bd0382012-01-13 23:06:53 +00001365
1366 // Compute the DeclContext, if we need it.
Craig Topperc3ec1492014-05-26 06:22:03 +00001367 DeclContext *DC = nullptr;
Douglas Gregor81bd0382012-01-13 23:06:53 +00001368 if (!S)
1369 DC = (*I)->getDeclContext()->getRedeclContext();
1370
Douglas Gregor9b7b3912012-01-04 16:44:10 +00001371 IdentifierResolver::iterator LastI = I;
1372 for (++LastI; LastI != IEnd; ++LastI) {
Douglas Gregor81bd0382012-01-13 23:06:53 +00001373 if (S) {
1374 // Match based on scope.
1375 if (!S->isDeclScope(*LastI))
1376 break;
1377 } else {
1378 // Match based on DeclContext.
1379 DeclContext *LastDC
1380 = (*LastI)->getDeclContext()->getRedeclContext();
1381 if (!LastDC->Equals(DC))
1382 break;
1383 }
Richard Smith0e5d7b82013-07-25 23:08:39 +00001384
1385 // If the declaration is in the right namespace and visible, add it.
1386 if (NamedDecl *LastD = R.getAcceptableDecl(*LastI))
1387 R.addDecl(LastD);
Douglas Gregor9b7b3912012-01-04 16:44:10 +00001388 }
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001389
Douglas Gregor9b7b3912012-01-04 16:44:10 +00001390 R.resolveKind();
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001391 }
Richard Smith541b38b2013-09-20 01:15:31 +00001392
John McCall9f3059a2009-10-09 21:13:30 +00001393 return true;
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001394 }
Douglas Gregor34074322009-01-14 22:20:51 +00001395 } else {
Douglas Gregor889ceb72009-02-03 19:21:40 +00001396 // Perform C++ unqualified name lookup.
John McCall27b18f82009-11-17 02:14:36 +00001397 if (CppLookupName(R, S))
John McCall9f3059a2009-10-09 21:13:30 +00001398 return true;
Douglas Gregor34074322009-01-14 22:20:51 +00001399 }
1400
1401 // If we didn't find a use of this identifier, and if the identifier
1402 // corresponds to a compiler builtin, create the decl object for the builtin
1403 // now, injecting it into translation unit scope, and return it.
Axel Naumann43dec142011-04-13 13:19:46 +00001404 if (AllowBuiltinCreation && LookupBuiltin(*this, R))
1405 return true;
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001406
Axel Naumann016538a2011-02-24 16:47:47 +00001407 // If we didn't find a use of this identifier, the ExternalSource
1408 // may be able to handle the situation.
1409 // Note: some lookup failures are expected!
1410 // See e.g. R.isForRedeclaration().
1411 return (ExternalSource && ExternalSource->LookupUnqualified(R, S));
Douglas Gregor34074322009-01-14 22:20:51 +00001412}
1413
John McCall6538c932009-10-10 05:48:19 +00001414/// @brief Perform qualified name lookup in the namespaces nominated by
1415/// using directives by the given context.
1416///
1417/// C++98 [namespace.qual]p2:
James Dennett51a8d8b2012-06-19 21:05:49 +00001418/// Given X::m (where X is a user-declared namespace), or given \::m
John McCall6538c932009-10-10 05:48:19 +00001419/// (where X is the global namespace), let S be the set of all
1420/// declarations of m in X and in the transitive closure of all
1421/// namespaces nominated by using-directives in X and its used
1422/// namespaces, except that using-directives are ignored in any
1423/// namespace, including X, directly containing one or more
1424/// declarations of m. No namespace is searched more than once in
1425/// the lookup of a name. If S is the empty set, the program is
1426/// ill-formed. Otherwise, if S has exactly one member, or if the
1427/// context of the reference is a using-declaration
1428/// (namespace.udecl), S is the required set of declarations of
1429/// m. Otherwise if the use of m is not one that allows a unique
1430/// declaration to be chosen from S, the program is ill-formed.
James Dennett51a8d8b2012-06-19 21:05:49 +00001431///
John McCall6538c932009-10-10 05:48:19 +00001432/// C++98 [namespace.qual]p5:
1433/// During the lookup of a qualified namespace member name, if the
1434/// lookup finds more than one declaration of the member, and if one
1435/// declaration introduces a class name or enumeration name and the
1436/// other declarations either introduce the same object, the same
1437/// enumerator or a set of functions, the non-type name hides the
1438/// class or enumeration name if and only if the declarations are
1439/// from the same namespace; otherwise (the declarations are from
1440/// different namespaces), the program is ill-formed.
Douglas Gregord3a59182010-02-12 05:48:04 +00001441static bool LookupQualifiedNameInUsingDirectives(Sema &S, LookupResult &R,
John McCall27b18f82009-11-17 02:14:36 +00001442 DeclContext *StartDC) {
John McCall6538c932009-10-10 05:48:19 +00001443 assert(StartDC->isFileContext() && "start context is not a file context");
1444
Aaron Ballman804a7fb2014-03-17 17:14:12 +00001445 DeclContext::udir_range UsingDirectives = StartDC->using_directives();
1446 if (UsingDirectives.begin() == UsingDirectives.end()) return false;
John McCall6538c932009-10-10 05:48:19 +00001447
1448 // We have at least added all these contexts to the queue.
Benjamin Kramer3adbe1c2012-02-23 16:06:01 +00001449 llvm::SmallPtrSet<DeclContext*, 8> Visited;
John McCall6538c932009-10-10 05:48:19 +00001450 Visited.insert(StartDC);
1451
1452 // We have not yet looked into these namespaces, much less added
1453 // their "using-children" to the queue.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001454 SmallVector<NamespaceDecl*, 8> Queue;
John McCall6538c932009-10-10 05:48:19 +00001455
1456 // We have already looked into the initial namespace; seed the queue
1457 // with its using-children.
Aaron Ballman804a7fb2014-03-17 17:14:12 +00001458 for (auto *I : UsingDirectives) {
1459 NamespaceDecl *ND = I->getNominatedNamespace()->getOriginalNamespace();
David Blaikie82e95a32014-11-19 07:49:47 +00001460 if (Visited.insert(ND).second)
John McCall6538c932009-10-10 05:48:19 +00001461 Queue.push_back(ND);
1462 }
1463
1464 // The easiest way to implement the restriction in [namespace.qual]p5
1465 // is to check whether any of the individual results found a tag
1466 // and, if so, to declare an ambiguity if the final result is not
1467 // a tag.
1468 bool FoundTag = false;
1469 bool FoundNonTag = false;
1470
John McCall5cebab12009-11-18 07:57:50 +00001471 LookupResult LocalR(LookupResult::Temporary, R);
John McCall6538c932009-10-10 05:48:19 +00001472
1473 bool Found = false;
1474 while (!Queue.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00001475 NamespaceDecl *ND = Queue.pop_back_val();
John McCall6538c932009-10-10 05:48:19 +00001476
1477 // We go through some convolutions here to avoid copying results
1478 // between LookupResults.
1479 bool UseLocal = !R.empty();
John McCall5cebab12009-11-18 07:57:50 +00001480 LookupResult &DirectR = UseLocal ? LocalR : R;
Douglas Gregord3a59182010-02-12 05:48:04 +00001481 bool FoundDirect = LookupDirect(S, DirectR, ND);
John McCall6538c932009-10-10 05:48:19 +00001482
1483 if (FoundDirect) {
1484 // First do any local hiding.
1485 DirectR.resolveKind();
1486
1487 // If the local result is a tag, remember that.
1488 if (DirectR.isSingleTagDecl())
1489 FoundTag = true;
1490 else
1491 FoundNonTag = true;
1492
1493 // Append the local results to the total results if necessary.
1494 if (UseLocal) {
1495 R.addAllDecls(LocalR);
1496 LocalR.clear();
1497 }
1498 }
1499
1500 // If we find names in this namespace, ignore its using directives.
1501 if (FoundDirect) {
1502 Found = true;
1503 continue;
1504 }
1505
Aaron Ballman804a7fb2014-03-17 17:14:12 +00001506 for (auto I : ND->using_directives()) {
Aaron Ballman63ab7602014-03-07 13:44:44 +00001507 NamespaceDecl *Nom = I->getNominatedNamespace();
David Blaikie82e95a32014-11-19 07:49:47 +00001508 if (Visited.insert(Nom).second)
John McCall6538c932009-10-10 05:48:19 +00001509 Queue.push_back(Nom);
1510 }
1511 }
1512
1513 if (Found) {
1514 if (FoundTag && FoundNonTag)
1515 R.setAmbiguousQualifiedTagHiding();
1516 else
1517 R.resolveKind();
1518 }
1519
1520 return Found;
1521}
1522
Douglas Gregor39982192010-08-15 06:18:01 +00001523/// \brief Callback that looks for any member of a class with the given name.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001524static bool LookupAnyMember(const CXXBaseSpecifier *Specifier,
Douglas Gregor39982192010-08-15 06:18:01 +00001525 CXXBasePath &Path,
1526 void *Name) {
1527 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001528
Douglas Gregor39982192010-08-15 06:18:01 +00001529 DeclarationName N = DeclarationName::getFromOpaquePtr(Name);
1530 Path.Decls = BaseRecord->lookup(N);
David Blaikieff7d47a2012-12-19 00:45:41 +00001531 return !Path.Decls.empty();
Douglas Gregor39982192010-08-15 06:18:01 +00001532}
1533
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001534/// \brief Determine whether the given set of member declarations contains only
Douglas Gregorc0d24902010-10-22 22:08:47 +00001535/// static members, nested types, and enumerators.
1536template<typename InputIterator>
1537static bool HasOnlyStaticMembers(InputIterator First, InputIterator Last) {
1538 Decl *D = (*First)->getUnderlyingDecl();
1539 if (isa<VarDecl>(D) || isa<TypeDecl>(D) || isa<EnumConstantDecl>(D))
1540 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001541
Douglas Gregorc0d24902010-10-22 22:08:47 +00001542 if (isa<CXXMethodDecl>(D)) {
1543 // Determine whether all of the methods are static.
1544 bool AllMethodsAreStatic = true;
1545 for(; First != Last; ++First) {
1546 D = (*First)->getUnderlyingDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001547
Douglas Gregorc0d24902010-10-22 22:08:47 +00001548 if (!isa<CXXMethodDecl>(D)) {
1549 assert(isa<TagDecl>(D) && "Non-function must be a tag decl");
1550 break;
1551 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001552
Douglas Gregorc0d24902010-10-22 22:08:47 +00001553 if (!cast<CXXMethodDecl>(D)->isStatic()) {
1554 AllMethodsAreStatic = false;
1555 break;
1556 }
1557 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001558
Douglas Gregorc0d24902010-10-22 22:08:47 +00001559 if (AllMethodsAreStatic)
1560 return true;
1561 }
1562
1563 return false;
1564}
1565
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001566/// \brief Perform qualified name lookup into a given context.
Douglas Gregor34074322009-01-14 22:20:51 +00001567///
1568/// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
1569/// names when the context of those names is explicit specified, e.g.,
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001570/// "std::vector" or "x->member", or as part of unqualified name lookup.
Douglas Gregor34074322009-01-14 22:20:51 +00001571///
1572/// Different lookup criteria can find different names. For example, a
1573/// particular scope can have both a struct and a function of the same
1574/// name, and each can be found by certain lookup criteria. For more
1575/// information about lookup criteria, see the documentation for the
1576/// class LookupCriteria.
1577///
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001578/// \param R captures both the lookup criteria and any lookup results found.
1579///
1580/// \param LookupCtx The context in which qualified name lookup will
Douglas Gregor34074322009-01-14 22:20:51 +00001581/// search. If the lookup criteria permits, name lookup may also search
1582/// in the parent contexts or (for C++ classes) base classes.
1583///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001584/// \param InUnqualifiedLookup true if this is qualified name lookup that
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001585/// occurs as part of unqualified name lookup.
Douglas Gregor34074322009-01-14 22:20:51 +00001586///
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001587/// \returns true if lookup succeeded, false if it failed.
1588bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
1589 bool InUnqualifiedLookup) {
Douglas Gregor34074322009-01-14 22:20:51 +00001590 assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context");
Mike Stump11289f42009-09-09 15:08:12 +00001591
John McCall27b18f82009-11-17 02:14:36 +00001592 if (!R.getLookupName())
John McCall9f3059a2009-10-09 21:13:30 +00001593 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001594
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001595 // Make sure that the declaration context is complete.
1596 assert((!isa<TagDecl>(LookupCtx) ||
1597 LookupCtx->isDependentContext() ||
John McCallf937c022011-10-07 06:10:15 +00001598 cast<TagDecl>(LookupCtx)->isCompleteDefinition() ||
Richard Smith7d137e32012-03-23 03:33:32 +00001599 cast<TagDecl>(LookupCtx)->isBeingDefined()) &&
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001600 "Declaration context must already be complete!");
Mike Stump11289f42009-09-09 15:08:12 +00001601
Douglas Gregor34074322009-01-14 22:20:51 +00001602 // Perform qualified name lookup into the LookupCtx.
Douglas Gregord3a59182010-02-12 05:48:04 +00001603 if (LookupDirect(*this, R, LookupCtx)) {
John McCall9f3059a2009-10-09 21:13:30 +00001604 R.resolveKind();
John McCall553c0792010-01-23 00:46:32 +00001605 if (isa<CXXRecordDecl>(LookupCtx))
1606 R.setNamingClass(cast<CXXRecordDecl>(LookupCtx));
John McCall9f3059a2009-10-09 21:13:30 +00001607 return true;
1608 }
Douglas Gregor34074322009-01-14 22:20:51 +00001609
John McCall6538c932009-10-10 05:48:19 +00001610 // Don't descend into implied contexts for redeclarations.
1611 // C++98 [namespace.qual]p6:
1612 // In a declaration for a namespace member in which the
1613 // declarator-id is a qualified-id, given that the qualified-id
1614 // for the namespace member has the form
1615 // nested-name-specifier unqualified-id
1616 // the unqualified-id shall name a member of the namespace
1617 // designated by the nested-name-specifier.
1618 // See also [class.mfct]p5 and [class.static.data]p2.
John McCall27b18f82009-11-17 02:14:36 +00001619 if (R.isForRedeclaration())
John McCall6538c932009-10-10 05:48:19 +00001620 return false;
1621
John McCall27b18f82009-11-17 02:14:36 +00001622 // If this is a namespace, look it up in the implied namespaces.
John McCall6538c932009-10-10 05:48:19 +00001623 if (LookupCtx->isFileContext())
Douglas Gregord3a59182010-02-12 05:48:04 +00001624 return LookupQualifiedNameInUsingDirectives(*this, R, LookupCtx);
John McCall6538c932009-10-10 05:48:19 +00001625
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001626 // If this isn't a C++ class, we aren't allowed to look into base
Douglas Gregorcc2427c2009-09-11 22:57:37 +00001627 // classes, we're done.
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001628 CXXRecordDecl *LookupRec = dyn_cast<CXXRecordDecl>(LookupCtx);
Douglas Gregor5a5fcd82010-07-01 00:21:21 +00001629 if (!LookupRec || !LookupRec->getDefinition())
John McCall9f3059a2009-10-09 21:13:30 +00001630 return false;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001631
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001632 // If we're performing qualified name lookup into a dependent class,
1633 // then we are actually looking into a current instantiation. If we have any
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001634 // dependent base classes, then we either have to delay lookup until
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001635 // template instantiation time (at which point all bases will be available)
1636 // or we have to fail.
1637 if (!InUnqualifiedLookup && LookupRec->isDependentContext() &&
1638 LookupRec->hasAnyDependentBases()) {
1639 R.setNotFoundInCurrentInstantiation();
1640 return false;
1641 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001642
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001643 // Perform lookup into our base classes.
Douglas Gregor36d1b142009-10-06 17:59:45 +00001644 CXXBasePaths Paths;
1645 Paths.setOrigin(LookupRec);
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001646
1647 // Look for this member in our base classes
Craig Topperc3ec1492014-05-26 06:22:03 +00001648 CXXRecordDecl::BaseMatchesCallback *BaseCallback = nullptr;
John McCall27b18f82009-11-17 02:14:36 +00001649 switch (R.getLookupKind()) {
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00001650 case LookupObjCImplicitSelfParam:
Douglas Gregor36d1b142009-10-06 17:59:45 +00001651 case LookupOrdinaryName:
1652 case LookupMemberName:
1653 case LookupRedeclarationWithLinkage:
Richard Smith114394f2013-08-09 04:35:01 +00001654 case LookupLocalFriendName:
Douglas Gregor36d1b142009-10-06 17:59:45 +00001655 BaseCallback = &CXXRecordDecl::FindOrdinaryMember;
1656 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001657
Douglas Gregor36d1b142009-10-06 17:59:45 +00001658 case LookupTagName:
1659 BaseCallback = &CXXRecordDecl::FindTagMember;
1660 break;
John McCall84d87672009-12-10 09:41:52 +00001661
Douglas Gregor39982192010-08-15 06:18:01 +00001662 case LookupAnyName:
1663 BaseCallback = &LookupAnyMember;
1664 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001665
John McCall84d87672009-12-10 09:41:52 +00001666 case LookupUsingDeclName:
1667 // This lookup is for redeclarations only.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001668
Douglas Gregor36d1b142009-10-06 17:59:45 +00001669 case LookupOperatorName:
1670 case LookupNamespaceName:
1671 case LookupObjCProtocolName:
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001672 case LookupLabel:
Douglas Gregor36d1b142009-10-06 17:59:45 +00001673 // These lookups will never find a member in a C++ class (or base class).
John McCall9f3059a2009-10-09 21:13:30 +00001674 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001675
Douglas Gregor36d1b142009-10-06 17:59:45 +00001676 case LookupNestedNameSpecifierName:
1677 BaseCallback = &CXXRecordDecl::FindNestedNameSpecifierMember;
1678 break;
1679 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001680
John McCall27b18f82009-11-17 02:14:36 +00001681 if (!LookupRec->lookupInBases(BaseCallback,
1682 R.getLookupName().getAsOpaquePtr(), Paths))
John McCall9f3059a2009-10-09 21:13:30 +00001683 return false;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001684
John McCall553c0792010-01-23 00:46:32 +00001685 R.setNamingClass(LookupRec);
1686
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001687 // C++ [class.member.lookup]p2:
1688 // [...] If the resulting set of declarations are not all from
1689 // sub-objects of the same type, or the set has a nonstatic member
1690 // and includes members from distinct sub-objects, there is an
1691 // ambiguity and the program is ill-formed. Otherwise that set is
1692 // the result of the lookup.
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001693 QualType SubobjectType;
Daniel Dunbar435bbe02009-01-15 18:32:35 +00001694 int SubobjectNumber = 0;
John McCalla332b952010-03-18 23:49:19 +00001695 AccessSpecifier SubobjectAccess = AS_none;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001696
Douglas Gregor36d1b142009-10-06 17:59:45 +00001697 for (CXXBasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end();
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001698 Path != PathEnd; ++Path) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00001699 const CXXBasePathElement &PathElement = Path->back();
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001700
John McCall401982f2010-01-20 21:53:11 +00001701 // Pick the best (i.e. most permissive i.e. numerically lowest) access
1702 // across all paths.
1703 SubobjectAccess = std::min(SubobjectAccess, Path->Access);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001704
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001705 // Determine whether we're looking at a distinct sub-object or not.
1706 if (SubobjectType.isNull()) {
John McCall9f3059a2009-10-09 21:13:30 +00001707 // This is the first subobject we've looked at. Record its type.
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001708 SubobjectType = Context.getCanonicalType(PathElement.Base->getType());
1709 SubobjectNumber = PathElement.SubobjectNumber;
Douglas Gregorc0d24902010-10-22 22:08:47 +00001710 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001711 }
1712
Douglas Gregorc0d24902010-10-22 22:08:47 +00001713 if (SubobjectType
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001714 != Context.getCanonicalType(PathElement.Base->getType())) {
1715 // We found members of the given name in two subobjects of
Douglas Gregorc0d24902010-10-22 22:08:47 +00001716 // different types. If the declaration sets aren't the same, this
Nikola Smiljanic1c125682014-07-09 05:42:35 +00001717 // lookup is ambiguous.
David Blaikieff7d47a2012-12-19 00:45:41 +00001718 if (HasOnlyStaticMembers(Path->Decls.begin(), Path->Decls.end())) {
Douglas Gregorc0d24902010-10-22 22:08:47 +00001719 CXXBasePaths::paths_iterator FirstPath = Paths.begin();
David Blaikieff7d47a2012-12-19 00:45:41 +00001720 DeclContext::lookup_iterator FirstD = FirstPath->Decls.begin();
1721 DeclContext::lookup_iterator CurrentD = Path->Decls.begin();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001722
David Blaikieff7d47a2012-12-19 00:45:41 +00001723 while (FirstD != FirstPath->Decls.end() &&
1724 CurrentD != Path->Decls.end()) {
Douglas Gregorc0d24902010-10-22 22:08:47 +00001725 if ((*FirstD)->getUnderlyingDecl()->getCanonicalDecl() !=
1726 (*CurrentD)->getUnderlyingDecl()->getCanonicalDecl())
1727 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001728
Douglas Gregorc0d24902010-10-22 22:08:47 +00001729 ++FirstD;
1730 ++CurrentD;
1731 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001732
David Blaikieff7d47a2012-12-19 00:45:41 +00001733 if (FirstD == FirstPath->Decls.end() &&
1734 CurrentD == Path->Decls.end())
Douglas Gregorc0d24902010-10-22 22:08:47 +00001735 continue;
1736 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001737
John McCall9f3059a2009-10-09 21:13:30 +00001738 R.setAmbiguousBaseSubobjectTypes(Paths);
1739 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001740 }
1741
Douglas Gregorc0d24902010-10-22 22:08:47 +00001742 if (SubobjectNumber != PathElement.SubobjectNumber) {
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001743 // We have a different subobject of the same type.
1744
1745 // C++ [class.member.lookup]p5:
1746 // A static member, a nested type or an enumerator defined in
1747 // a base class T can unambiguously be found even if an object
Mike Stump11289f42009-09-09 15:08:12 +00001748 // has more than one base class subobject of type T.
David Blaikieff7d47a2012-12-19 00:45:41 +00001749 if (HasOnlyStaticMembers(Path->Decls.begin(), Path->Decls.end()))
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001750 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001751
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001752 // We have found a nonstatic member name in multiple, distinct
1753 // subobjects. Name lookup is ambiguous.
John McCall9f3059a2009-10-09 21:13:30 +00001754 R.setAmbiguousBaseSubobjects(Paths);
1755 return true;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001756 }
1757 }
1758
1759 // Lookup in a base class succeeded; return these results.
1760
Aaron Ballman1e606f42014-07-15 22:03:49 +00001761 for (auto *D : Paths.front().Decls) {
John McCall553c0792010-01-23 00:46:32 +00001762 AccessSpecifier AS = CXXRecordDecl::MergeAccess(SubobjectAccess,
1763 D->getAccess());
1764 R.addDecl(D, AS);
1765 }
John McCall9f3059a2009-10-09 21:13:30 +00001766 R.resolveKind();
1767 return true;
Douglas Gregor34074322009-01-14 22:20:51 +00001768}
1769
Nikola Smiljanicfce370e2014-12-01 23:15:01 +00001770/// \brief Performs qualified name lookup or special type of lookup for
1771/// "__super::" scope specifier.
1772///
1773/// This routine is a convenience overload meant to be called from contexts
1774/// that need to perform a qualified name lookup with an optional C++ scope
1775/// specifier that might require special kind of lookup.
1776///
1777/// \param R captures both the lookup criteria and any lookup results found.
1778///
1779/// \param LookupCtx The context in which qualified name lookup will
1780/// search.
1781///
1782/// \param SS An optional C++ scope-specifier.
1783///
1784/// \returns true if lookup succeeded, false if it failed.
1785bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
1786 CXXScopeSpec &SS) {
1787 auto *NNS = SS.getScopeRep();
1788 if (NNS && NNS->getKind() == NestedNameSpecifier::Super)
1789 return LookupInSuper(R, NNS->getAsRecordDecl());
1790 else
1791
1792 return LookupQualifiedName(R, LookupCtx);
1793}
1794
Douglas Gregor34074322009-01-14 22:20:51 +00001795/// @brief Performs name lookup for a name that was parsed in the
1796/// source code, and may contain a C++ scope specifier.
1797///
1798/// This routine is a convenience routine meant to be called from
1799/// contexts that receive a name and an optional C++ scope specifier
1800/// (e.g., "N::M::x"). It will then perform either qualified or
1801/// unqualified name lookup (with LookupQualifiedName or LookupName,
Nikola Smiljanic905bfda2014-10-04 10:17:57 +00001802/// respectively) on the given name and return those results. It will
1803/// perform a special type of lookup for "__super::" scope specifier.
Douglas Gregor34074322009-01-14 22:20:51 +00001804///
1805/// @param S The scope from which unqualified name lookup will
1806/// begin.
Mike Stump11289f42009-09-09 15:08:12 +00001807///
Douglas Gregore861bac2009-08-25 22:51:20 +00001808/// @param SS An optional C++ scope-specifier, e.g., "::N::M".
Douglas Gregor34074322009-01-14 22:20:51 +00001809///
Douglas Gregore861bac2009-08-25 22:51:20 +00001810/// @param EnteringContext Indicates whether we are going to enter the
1811/// context of the scope-specifier SS (if present).
1812///
John McCall9f3059a2009-10-09 21:13:30 +00001813/// @returns True if any decls were found (but possibly ambiguous)
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001814bool Sema::LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
John McCall27b18f82009-11-17 02:14:36 +00001815 bool AllowBuiltinCreation, bool EnteringContext) {
Douglas Gregore861bac2009-08-25 22:51:20 +00001816 if (SS && SS->isInvalid()) {
1817 // When the scope specifier is invalid, don't even look for
Douglas Gregorc9f9b862009-05-11 19:58:34 +00001818 // anything.
John McCall9f3059a2009-10-09 21:13:30 +00001819 return false;
Douglas Gregore861bac2009-08-25 22:51:20 +00001820 }
Mike Stump11289f42009-09-09 15:08:12 +00001821
Douglas Gregore861bac2009-08-25 22:51:20 +00001822 if (SS && SS->isSet()) {
Nikola Smiljanic905bfda2014-10-04 10:17:57 +00001823 NestedNameSpecifier *NNS = SS->getScopeRep();
1824 if (NNS->getKind() == NestedNameSpecifier::Super)
1825 return LookupInSuper(R, NNS->getAsRecordDecl());
1826
Douglas Gregore861bac2009-08-25 22:51:20 +00001827 if (DeclContext *DC = computeDeclContext(*SS, EnteringContext)) {
Mike Stump11289f42009-09-09 15:08:12 +00001828 // We have resolved the scope specifier to a particular declaration
Douglas Gregore861bac2009-08-25 22:51:20 +00001829 // contex, and will perform name lookup in that context.
John McCall0b66eb32010-05-01 00:40:08 +00001830 if (!DC->isDependentContext() && RequireCompleteDeclContext(*SS, DC))
John McCall9f3059a2009-10-09 21:13:30 +00001831 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001832
John McCall27b18f82009-11-17 02:14:36 +00001833 R.setContextRange(SS->getRange());
John McCall27b18f82009-11-17 02:14:36 +00001834 return LookupQualifiedName(R, DC);
Douglas Gregor52537682009-03-19 00:18:19 +00001835 }
Douglas Gregorc9f9b862009-05-11 19:58:34 +00001836
Douglas Gregore861bac2009-08-25 22:51:20 +00001837 // We could not resolve the scope specified to a specific declaration
Mike Stump11289f42009-09-09 15:08:12 +00001838 // context, which means that SS refers to an unknown specialization.
Douglas Gregore861bac2009-08-25 22:51:20 +00001839 // Name lookup can't find anything in this case.
Douglas Gregor89ab56d2011-10-24 22:24:50 +00001840 R.setNotFoundInCurrentInstantiation();
1841 R.setContextRange(SS->getRange());
John McCall9f3059a2009-10-09 21:13:30 +00001842 return false;
Douglas Gregored8f2882009-01-30 01:04:22 +00001843 }
1844
Mike Stump11289f42009-09-09 15:08:12 +00001845 // Perform unqualified name lookup starting in the given scope.
John McCall27b18f82009-11-17 02:14:36 +00001846 return LookupName(R, S, AllowBuiltinCreation);
Douglas Gregor34074322009-01-14 22:20:51 +00001847}
1848
Nikola Smiljanic67860242014-09-26 00:28:20 +00001849/// \brief Perform qualified name lookup into all base classes of the given
1850/// class.
1851///
1852/// \param R captures both the lookup criteria and any lookup results found.
1853///
1854/// \param Class The context in which qualified name lookup will
1855/// search. Name lookup will search in all base classes merging the results.
Nikola Smiljanic905bfda2014-10-04 10:17:57 +00001856///
1857/// @returns True if any decls were found (but possibly ambiguous)
1858bool Sema::LookupInSuper(LookupResult &R, CXXRecordDecl *Class) {
Nikola Smiljanic67860242014-09-26 00:28:20 +00001859 for (const auto &BaseSpec : Class->bases()) {
1860 CXXRecordDecl *RD = cast<CXXRecordDecl>(
1861 BaseSpec.getType()->castAs<RecordType>()->getDecl());
1862 LookupResult Result(*this, R.getLookupNameInfo(), R.getLookupKind());
1863 Result.setBaseObjectType(Context.getRecordType(Class));
1864 LookupQualifiedName(Result, RD);
1865 for (auto *Decl : Result)
1866 R.addDecl(Decl);
1867 }
1868
1869 R.resolveKind();
Nikola Smiljanic905bfda2014-10-04 10:17:57 +00001870
1871 return !R.empty();
Nikola Smiljanic67860242014-09-26 00:28:20 +00001872}
Douglas Gregor889ceb72009-02-03 19:21:40 +00001873
James Dennett41725122012-06-22 10:16:05 +00001874/// \brief Produce a diagnostic describing the ambiguity that resulted
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001875/// from name lookup.
1876///
James Dennett41725122012-06-22 10:16:05 +00001877/// \param Result The result of the ambiguous lookup to be diagnosed.
Serge Pavlov99292092013-08-29 07:23:24 +00001878void Sema::DiagnoseAmbiguousLookup(LookupResult &Result) {
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001879 assert(Result.isAmbiguous() && "Lookup result must be ambiguous");
1880
John McCall27b18f82009-11-17 02:14:36 +00001881 DeclarationName Name = Result.getLookupName();
1882 SourceLocation NameLoc = Result.getNameLoc();
1883 SourceRange LookupRange = Result.getContextRange();
1884
John McCall6538c932009-10-10 05:48:19 +00001885 switch (Result.getAmbiguityKind()) {
1886 case LookupResult::AmbiguousBaseSubobjects: {
1887 CXXBasePaths *Paths = Result.getBasePaths();
1888 QualType SubobjectType = Paths->front().back().Base->getType();
1889 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects)
1890 << Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths)
1891 << LookupRange;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001892
David Blaikieff7d47a2012-12-19 00:45:41 +00001893 DeclContext::lookup_iterator Found = Paths->front().Decls.begin();
John McCall6538c932009-10-10 05:48:19 +00001894 while (isa<CXXMethodDecl>(*Found) &&
1895 cast<CXXMethodDecl>(*Found)->isStatic())
1896 ++Found;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001897
John McCall6538c932009-10-10 05:48:19 +00001898 Diag((*Found)->getLocation(), diag::note_ambiguous_member_found);
Serge Pavlov99292092013-08-29 07:23:24 +00001899 break;
John McCall6538c932009-10-10 05:48:19 +00001900 }
Douglas Gregor1c846b02009-01-16 00:38:09 +00001901
John McCall6538c932009-10-10 05:48:19 +00001902 case LookupResult::AmbiguousBaseSubobjectTypes: {
Douglas Gregor889ceb72009-02-03 19:21:40 +00001903 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types)
1904 << Name << LookupRange;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001905
John McCall6538c932009-10-10 05:48:19 +00001906 CXXBasePaths *Paths = Result.getBasePaths();
Douglas Gregor889ceb72009-02-03 19:21:40 +00001907 std::set<Decl *> DeclsPrinted;
John McCall6538c932009-10-10 05:48:19 +00001908 for (CXXBasePaths::paths_iterator Path = Paths->begin(),
1909 PathEnd = Paths->end();
Douglas Gregor889ceb72009-02-03 19:21:40 +00001910 Path != PathEnd; ++Path) {
David Blaikieff7d47a2012-12-19 00:45:41 +00001911 Decl *D = Path->Decls.front();
Douglas Gregor889ceb72009-02-03 19:21:40 +00001912 if (DeclsPrinted.insert(D).second)
1913 Diag(D->getLocation(), diag::note_ambiguous_member_found);
1914 }
Serge Pavlov99292092013-08-29 07:23:24 +00001915 break;
Douglas Gregor1c846b02009-01-16 00:38:09 +00001916 }
1917
John McCall6538c932009-10-10 05:48:19 +00001918 case LookupResult::AmbiguousTagHiding: {
1919 Diag(NameLoc, diag::err_ambiguous_tag_hiding) << Name << LookupRange;
Douglas Gregorf23311d2009-01-17 01:13:24 +00001920
John McCall6538c932009-10-10 05:48:19 +00001921 llvm::SmallPtrSet<NamedDecl*,8> TagDecls;
1922
Aaron Ballman1e606f42014-07-15 22:03:49 +00001923 for (auto *D : Result)
1924 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
John McCall6538c932009-10-10 05:48:19 +00001925 TagDecls.insert(TD);
1926 Diag(TD->getLocation(), diag::note_hidden_tag);
1927 }
1928
Aaron Ballman1e606f42014-07-15 22:03:49 +00001929 for (auto *D : Result)
1930 if (!isa<TagDecl>(D))
1931 Diag(D->getLocation(), diag::note_hiding_object);
John McCall6538c932009-10-10 05:48:19 +00001932
1933 // For recovery purposes, go ahead and implement the hiding.
John McCallad371252010-01-20 00:46:10 +00001934 LookupResult::Filter F = Result.makeFilter();
1935 while (F.hasNext()) {
1936 if (TagDecls.count(F.next()))
1937 F.erase();
1938 }
1939 F.done();
Serge Pavlov99292092013-08-29 07:23:24 +00001940 break;
John McCall6538c932009-10-10 05:48:19 +00001941 }
1942
1943 case LookupResult::AmbiguousReference: {
1944 Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001945
Aaron Ballman1e606f42014-07-15 22:03:49 +00001946 for (auto *D : Result)
1947 Diag(D->getLocation(), diag::note_ambiguous_candidate) << D;
Serge Pavlov99292092013-08-29 07:23:24 +00001948 break;
John McCall6538c932009-10-10 05:48:19 +00001949 }
Serge Pavlov99292092013-08-29 07:23:24 +00001950 }
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001951}
Douglas Gregore254f902009-02-04 00:32:51 +00001952
John McCallf24d7bb2010-05-28 18:45:08 +00001953namespace {
1954 struct AssociatedLookup {
John McCall7d8b0412012-08-24 20:38:34 +00001955 AssociatedLookup(Sema &S, SourceLocation InstantiationLoc,
John McCallf24d7bb2010-05-28 18:45:08 +00001956 Sema::AssociatedNamespaceSet &Namespaces,
1957 Sema::AssociatedClassSet &Classes)
John McCall7d8b0412012-08-24 20:38:34 +00001958 : S(S), Namespaces(Namespaces), Classes(Classes),
1959 InstantiationLoc(InstantiationLoc) {
John McCallf24d7bb2010-05-28 18:45:08 +00001960 }
1961
1962 Sema &S;
1963 Sema::AssociatedNamespaceSet &Namespaces;
1964 Sema::AssociatedClassSet &Classes;
John McCall7d8b0412012-08-24 20:38:34 +00001965 SourceLocation InstantiationLoc;
John McCallf24d7bb2010-05-28 18:45:08 +00001966 };
1967}
1968
Mike Stump11289f42009-09-09 15:08:12 +00001969static void
John McCallf24d7bb2010-05-28 18:45:08 +00001970addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType T);
John McCallc7e8e792009-08-07 22:18:02 +00001971
Douglas Gregor8b895222010-04-30 07:08:38 +00001972static void CollectEnclosingNamespace(Sema::AssociatedNamespaceSet &Namespaces,
1973 DeclContext *Ctx) {
1974 // Add the associated namespace for this class.
1975
1976 // We don't use DeclContext::getEnclosingNamespaceContext() as this may
1977 // be a locally scoped record.
1978
Sebastian Redlbd595762010-08-31 20:53:31 +00001979 // We skip out of inline namespaces. The innermost non-inline namespace
1980 // contains all names of all its nested inline namespaces anyway, so we can
1981 // replace the entire inline namespace tree with its root.
1982 while (Ctx->isRecord() || Ctx->isTransparentContext() ||
1983 Ctx->isInlineNamespace())
Douglas Gregor8b895222010-04-30 07:08:38 +00001984 Ctx = Ctx->getParent();
1985
John McCallc7e8e792009-08-07 22:18:02 +00001986 if (Ctx->isFileContext())
Douglas Gregor8b895222010-04-30 07:08:38 +00001987 Namespaces.insert(Ctx->getPrimaryContext());
John McCallc7e8e792009-08-07 22:18:02 +00001988}
Douglas Gregor197e5f72009-07-08 07:51:57 +00001989
Mike Stump11289f42009-09-09 15:08:12 +00001990// \brief Add the associated classes and namespaces for argument-dependent
Douglas Gregor197e5f72009-07-08 07:51:57 +00001991// lookup that involves a template argument (C++ [basic.lookup.koenig]p2).
Mike Stump11289f42009-09-09 15:08:12 +00001992static void
John McCallf24d7bb2010-05-28 18:45:08 +00001993addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
1994 const TemplateArgument &Arg) {
Douglas Gregor197e5f72009-07-08 07:51:57 +00001995 // C++ [basic.lookup.koenig]p2, last bullet:
Mike Stump11289f42009-09-09 15:08:12 +00001996 // -- [...] ;
Douglas Gregor197e5f72009-07-08 07:51:57 +00001997 switch (Arg.getKind()) {
1998 case TemplateArgument::Null:
1999 break;
Mike Stump11289f42009-09-09 15:08:12 +00002000
Douglas Gregor197e5f72009-07-08 07:51:57 +00002001 case TemplateArgument::Type:
2002 // [...] the namespaces and classes associated with the types of the
2003 // template arguments provided for template type parameters (excluding
2004 // template template parameters)
John McCallf24d7bb2010-05-28 18:45:08 +00002005 addAssociatedClassesAndNamespaces(Result, Arg.getAsType());
Douglas Gregor197e5f72009-07-08 07:51:57 +00002006 break;
Mike Stump11289f42009-09-09 15:08:12 +00002007
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002008 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00002009 case TemplateArgument::TemplateExpansion: {
Mike Stump11289f42009-09-09 15:08:12 +00002010 // [...] the namespaces in which any template template arguments are
2011 // defined; and the classes in which any member templates used as
Douglas Gregor197e5f72009-07-08 07:51:57 +00002012 // template template arguments are defined.
Douglas Gregore4ff4b52011-01-05 18:58:31 +00002013 TemplateName Template = Arg.getAsTemplateOrTemplatePattern();
Mike Stump11289f42009-09-09 15:08:12 +00002014 if (ClassTemplateDecl *ClassTemplate
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002015 = dyn_cast<ClassTemplateDecl>(Template.getAsTemplateDecl())) {
Douglas Gregor197e5f72009-07-08 07:51:57 +00002016 DeclContext *Ctx = ClassTemplate->getDeclContext();
2017 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00002018 Result.Classes.insert(EnclosingClass);
Douglas Gregor197e5f72009-07-08 07:51:57 +00002019 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00002020 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Douglas Gregor197e5f72009-07-08 07:51:57 +00002021 }
2022 break;
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002023 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002024
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002025 case TemplateArgument::Declaration:
Douglas Gregor197e5f72009-07-08 07:51:57 +00002026 case TemplateArgument::Integral:
2027 case TemplateArgument::Expression:
Eli Friedmanb826a002012-09-26 02:36:12 +00002028 case TemplateArgument::NullPtr:
Mike Stump11289f42009-09-09 15:08:12 +00002029 // [Note: non-type template arguments do not contribute to the set of
Douglas Gregor197e5f72009-07-08 07:51:57 +00002030 // associated namespaces. ]
2031 break;
Mike Stump11289f42009-09-09 15:08:12 +00002032
Douglas Gregor197e5f72009-07-08 07:51:57 +00002033 case TemplateArgument::Pack:
Aaron Ballman2a89e852014-07-15 21:32:31 +00002034 for (const auto &P : Arg.pack_elements())
2035 addAssociatedClassesAndNamespaces(Result, P);
Douglas Gregor197e5f72009-07-08 07:51:57 +00002036 break;
2037 }
2038}
2039
Douglas Gregore254f902009-02-04 00:32:51 +00002040// \brief Add the associated classes and namespaces for
Mike Stump11289f42009-09-09 15:08:12 +00002041// argument-dependent lookup with an argument of class type
2042// (C++ [basic.lookup.koenig]p2).
2043static void
John McCallf24d7bb2010-05-28 18:45:08 +00002044addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
2045 CXXRecordDecl *Class) {
2046
2047 // Just silently ignore anything whose name is __va_list_tag.
2048 if (Class->getDeclName() == Result.S.VAListTagName)
2049 return;
2050
Douglas Gregore254f902009-02-04 00:32:51 +00002051 // C++ [basic.lookup.koenig]p2:
2052 // [...]
2053 // -- If T is a class type (including unions), its associated
2054 // classes are: the class itself; the class of which it is a
2055 // member, if any; and its direct and indirect base
2056 // classes. Its associated namespaces are the namespaces in
Mike Stump11289f42009-09-09 15:08:12 +00002057 // which its associated classes are defined.
Douglas Gregore254f902009-02-04 00:32:51 +00002058
2059 // Add the class of which it is a member, if any.
2060 DeclContext *Ctx = Class->getDeclContext();
2061 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00002062 Result.Classes.insert(EnclosingClass);
Douglas Gregore254f902009-02-04 00:32:51 +00002063 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00002064 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Mike Stump11289f42009-09-09 15:08:12 +00002065
Douglas Gregore254f902009-02-04 00:32:51 +00002066 // Add the class itself. If we've already seen this class, we don't
2067 // need to visit base classes.
Richard Smith594461f2014-03-14 22:07:27 +00002068 //
2069 // FIXME: That's not correct, we may have added this class only because it
2070 // was the enclosing class of another class, and in that case we won't have
2071 // added its base classes yet.
David Blaikie82e95a32014-11-19 07:49:47 +00002072 if (!Result.Classes.insert(Class).second)
Douglas Gregore254f902009-02-04 00:32:51 +00002073 return;
2074
Mike Stump11289f42009-09-09 15:08:12 +00002075 // -- If T is a template-id, its associated namespaces and classes are
2076 // the namespace in which the template is defined; for member
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002077 // templates, the member template's class; the namespaces and classes
Mike Stump11289f42009-09-09 15:08:12 +00002078 // associated with the types of the template arguments provided for
Douglas Gregor197e5f72009-07-08 07:51:57 +00002079 // template type parameters (excluding template template parameters); the
Mike Stump11289f42009-09-09 15:08:12 +00002080 // namespaces in which any template template arguments are defined; and
2081 // the classes in which any member templates used as template template
2082 // arguments are defined. [Note: non-type template arguments do not
Douglas Gregor197e5f72009-07-08 07:51:57 +00002083 // contribute to the set of associated namespaces. ]
Mike Stump11289f42009-09-09 15:08:12 +00002084 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregor197e5f72009-07-08 07:51:57 +00002085 = dyn_cast<ClassTemplateSpecializationDecl>(Class)) {
2086 DeclContext *Ctx = Spec->getSpecializedTemplate()->getDeclContext();
2087 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00002088 Result.Classes.insert(EnclosingClass);
Douglas Gregor197e5f72009-07-08 07:51:57 +00002089 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00002090 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Mike Stump11289f42009-09-09 15:08:12 +00002091
Douglas Gregor197e5f72009-07-08 07:51:57 +00002092 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
2093 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
John McCallf24d7bb2010-05-28 18:45:08 +00002094 addAssociatedClassesAndNamespaces(Result, TemplateArgs[I]);
Douglas Gregor197e5f72009-07-08 07:51:57 +00002095 }
Mike Stump11289f42009-09-09 15:08:12 +00002096
John McCall67da35c2010-02-04 22:26:26 +00002097 // Only recurse into base classes for complete types.
Richard Smith594461f2014-03-14 22:07:27 +00002098 if (!Class->hasDefinition())
2099 return;
John McCall67da35c2010-02-04 22:26:26 +00002100
Douglas Gregore254f902009-02-04 00:32:51 +00002101 // Add direct and indirect base classes along with their associated
2102 // namespaces.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002103 SmallVector<CXXRecordDecl *, 32> Bases;
Douglas Gregore254f902009-02-04 00:32:51 +00002104 Bases.push_back(Class);
2105 while (!Bases.empty()) {
2106 // Pop this class off the stack.
Robert Wilhelm25284cc2013-08-23 16:11:15 +00002107 Class = Bases.pop_back_val();
Douglas Gregore254f902009-02-04 00:32:51 +00002108
2109 // Visit the base classes.
Aaron Ballman574705e2014-03-13 15:41:46 +00002110 for (const auto &Base : Class->bases()) {
2111 const RecordType *BaseType = Base.getType()->getAs<RecordType>();
Sebastian Redlc45c03c2009-10-25 09:35:33 +00002112 // In dependent contexts, we do ADL twice, and the first time around,
2113 // the base type might be a dependent TemplateSpecializationType, or a
2114 // TemplateTypeParmType. If that happens, simply ignore it.
2115 // FIXME: If we want to support export, we probably need to add the
2116 // namespace of the template in a TemplateSpecializationType, or even
2117 // the classes and namespaces of known non-dependent arguments.
2118 if (!BaseType)
2119 continue;
Douglas Gregore254f902009-02-04 00:32:51 +00002120 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(BaseType->getDecl());
David Blaikie82e95a32014-11-19 07:49:47 +00002121 if (Result.Classes.insert(BaseDecl).second) {
Douglas Gregore254f902009-02-04 00:32:51 +00002122 // Find the associated namespace for this base class.
2123 DeclContext *BaseCtx = BaseDecl->getDeclContext();
John McCallf24d7bb2010-05-28 18:45:08 +00002124 CollectEnclosingNamespace(Result.Namespaces, BaseCtx);
Douglas Gregore254f902009-02-04 00:32:51 +00002125
2126 // Make sure we visit the bases of this base class.
2127 if (BaseDecl->bases_begin() != BaseDecl->bases_end())
2128 Bases.push_back(BaseDecl);
2129 }
2130 }
2131 }
2132}
2133
2134// \brief Add the associated classes and namespaces for
2135// argument-dependent lookup with an argument of type T
Mike Stump11289f42009-09-09 15:08:12 +00002136// (C++ [basic.lookup.koenig]p2).
2137static void
John McCallf24d7bb2010-05-28 18:45:08 +00002138addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType Ty) {
Douglas Gregore254f902009-02-04 00:32:51 +00002139 // C++ [basic.lookup.koenig]p2:
2140 //
2141 // For each argument type T in the function call, there is a set
2142 // of zero or more associated namespaces and a set of zero or more
2143 // associated classes to be considered. The sets of namespaces and
2144 // classes is determined entirely by the types of the function
2145 // arguments (and the namespace of any template template
2146 // argument). Typedef names and using-declarations used to specify
2147 // the types do not contribute to this set. The sets of namespaces
2148 // and classes are determined in the following way:
Douglas Gregore254f902009-02-04 00:32:51 +00002149
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002150 SmallVector<const Type *, 16> Queue;
John McCall0af3d3b2010-05-28 06:08:54 +00002151 const Type *T = Ty->getCanonicalTypeInternal().getTypePtr();
2152
Douglas Gregore254f902009-02-04 00:32:51 +00002153 while (true) {
John McCall0af3d3b2010-05-28 06:08:54 +00002154 switch (T->getTypeClass()) {
2155
2156#define TYPE(Class, Base)
2157#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2158#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2159#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
2160#define ABSTRACT_TYPE(Class, Base)
2161#include "clang/AST/TypeNodes.def"
2162 // T is canonical. We can also ignore dependent types because
2163 // we don't need to do ADL at the definition point, but if we
2164 // wanted to implement template export (or if we find some other
2165 // use for associated classes and namespaces...) this would be
2166 // wrong.
Douglas Gregore254f902009-02-04 00:32:51 +00002167 break;
Douglas Gregore254f902009-02-04 00:32:51 +00002168
John McCall0af3d3b2010-05-28 06:08:54 +00002169 // -- If T is a pointer to U or an array of U, its associated
2170 // namespaces and classes are those associated with U.
2171 case Type::Pointer:
2172 T = cast<PointerType>(T)->getPointeeType().getTypePtr();
2173 continue;
2174 case Type::ConstantArray:
2175 case Type::IncompleteArray:
2176 case Type::VariableArray:
2177 T = cast<ArrayType>(T)->getElementType().getTypePtr();
2178 continue;
Douglas Gregore254f902009-02-04 00:32:51 +00002179
John McCall0af3d3b2010-05-28 06:08:54 +00002180 // -- If T is a fundamental type, its associated sets of
2181 // namespaces and classes are both empty.
2182 case Type::Builtin:
2183 break;
2184
2185 // -- If T is a class type (including unions), its associated
2186 // classes are: the class itself; the class of which it is a
2187 // member, if any; and its direct and indirect base
2188 // classes. Its associated namespaces are the namespaces in
2189 // which its associated classes are defined.
2190 case Type::Record: {
Richard Smith594461f2014-03-14 22:07:27 +00002191 Result.S.RequireCompleteType(Result.InstantiationLoc, QualType(T, 0),
2192 /*no diagnostic*/ 0);
John McCall0af3d3b2010-05-28 06:08:54 +00002193 CXXRecordDecl *Class
2194 = cast<CXXRecordDecl>(cast<RecordType>(T)->getDecl());
John McCallf24d7bb2010-05-28 18:45:08 +00002195 addAssociatedClassesAndNamespaces(Result, Class);
John McCall0af3d3b2010-05-28 06:08:54 +00002196 break;
Douglas Gregor89ee6822009-02-28 01:32:25 +00002197 }
Douglas Gregorfe60c142010-05-20 02:26:51 +00002198
John McCall0af3d3b2010-05-28 06:08:54 +00002199 // -- If T is an enumeration type, its associated namespace is
2200 // the namespace in which it is defined. If it is class
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002201 // member, its associated class is the member's class; else
John McCall0af3d3b2010-05-28 06:08:54 +00002202 // it has no associated class.
2203 case Type::Enum: {
2204 EnumDecl *Enum = cast<EnumType>(T)->getDecl();
Douglas Gregore254f902009-02-04 00:32:51 +00002205
John McCall0af3d3b2010-05-28 06:08:54 +00002206 DeclContext *Ctx = Enum->getDeclContext();
2207 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00002208 Result.Classes.insert(EnclosingClass);
Douglas Gregore254f902009-02-04 00:32:51 +00002209
John McCall0af3d3b2010-05-28 06:08:54 +00002210 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00002211 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Douglas Gregore254f902009-02-04 00:32:51 +00002212
John McCall0af3d3b2010-05-28 06:08:54 +00002213 break;
2214 }
2215
2216 // -- If T is a function type, its associated namespaces and
2217 // classes are those associated with the function parameter
2218 // types and those associated with the return type.
2219 case Type::FunctionProto: {
2220 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00002221 for (const auto &Arg : Proto->param_types())
2222 Queue.push_back(Arg.getTypePtr());
John McCall0af3d3b2010-05-28 06:08:54 +00002223 // fallthrough
2224 }
2225 case Type::FunctionNoProto: {
2226 const FunctionType *FnType = cast<FunctionType>(T);
Alp Toker314cc812014-01-25 16:55:45 +00002227 T = FnType->getReturnType().getTypePtr();
John McCall0af3d3b2010-05-28 06:08:54 +00002228 continue;
2229 }
2230
2231 // -- If T is a pointer to a member function of a class X, its
2232 // associated namespaces and classes are those associated
2233 // with the function parameter types and return type,
2234 // together with those associated with X.
2235 //
2236 // -- If T is a pointer to a data member of class X, its
2237 // associated namespaces and classes are those associated
2238 // with the member type together with those associated with
2239 // X.
2240 case Type::MemberPointer: {
2241 const MemberPointerType *MemberPtr = cast<MemberPointerType>(T);
2242
2243 // Queue up the class type into which this points.
2244 Queue.push_back(MemberPtr->getClass());
2245
2246 // And directly continue with the pointee type.
2247 T = MemberPtr->getPointeeType().getTypePtr();
2248 continue;
2249 }
2250
2251 // As an extension, treat this like a normal pointer.
2252 case Type::BlockPointer:
2253 T = cast<BlockPointerType>(T)->getPointeeType().getTypePtr();
2254 continue;
2255
2256 // References aren't covered by the standard, but that's such an
2257 // obvious defect that we cover them anyway.
2258 case Type::LValueReference:
2259 case Type::RValueReference:
2260 T = cast<ReferenceType>(T)->getPointeeType().getTypePtr();
2261 continue;
2262
2263 // These are fundamental types.
2264 case Type::Vector:
2265 case Type::ExtVector:
2266 case Type::Complex:
2267 break;
2268
Richard Smith27d807c2013-04-30 13:56:41 +00002269 // Non-deduced auto types only get here for error cases.
2270 case Type::Auto:
2271 break;
2272
Douglas Gregor8e936662011-04-12 01:02:45 +00002273 // If T is an Objective-C object or interface type, or a pointer to an
2274 // object or interface type, the associated namespace is the global
2275 // namespace.
John McCall0af3d3b2010-05-28 06:08:54 +00002276 case Type::ObjCObject:
2277 case Type::ObjCInterface:
2278 case Type::ObjCObjectPointer:
Douglas Gregor8e936662011-04-12 01:02:45 +00002279 Result.Namespaces.insert(Result.S.Context.getTranslationUnitDecl());
John McCall0af3d3b2010-05-28 06:08:54 +00002280 break;
Eli Friedman0dfb8892011-10-06 23:00:33 +00002281
2282 // Atomic types are just wrappers; use the associations of the
2283 // contained type.
2284 case Type::Atomic:
2285 T = cast<AtomicType>(T)->getValueType().getTypePtr();
2286 continue;
John McCall0af3d3b2010-05-28 06:08:54 +00002287 }
2288
Robert Wilhelm25284cc2013-08-23 16:11:15 +00002289 if (Queue.empty())
2290 break;
2291 T = Queue.pop_back_val();
Douglas Gregore254f902009-02-04 00:32:51 +00002292 }
Douglas Gregore254f902009-02-04 00:32:51 +00002293}
2294
2295/// \brief Find the associated classes and namespaces for
2296/// argument-dependent lookup for a call with the given set of
2297/// arguments.
2298///
2299/// This routine computes the sets of associated classes and associated
Mike Stump11289f42009-09-09 15:08:12 +00002300/// namespaces searched by argument-dependent lookup
Douglas Gregore254f902009-02-04 00:32:51 +00002301/// (C++ [basic.lookup.argdep]) for a given set of arguments.
Robert Wilhelm16e94b92013-08-09 18:02:13 +00002302void Sema::FindAssociatedClassesAndNamespaces(
2303 SourceLocation InstantiationLoc, ArrayRef<Expr *> Args,
2304 AssociatedNamespaceSet &AssociatedNamespaces,
2305 AssociatedClassSet &AssociatedClasses) {
Douglas Gregore254f902009-02-04 00:32:51 +00002306 AssociatedNamespaces.clear();
2307 AssociatedClasses.clear();
2308
John McCall7d8b0412012-08-24 20:38:34 +00002309 AssociatedLookup Result(*this, InstantiationLoc,
2310 AssociatedNamespaces, AssociatedClasses);
John McCallf24d7bb2010-05-28 18:45:08 +00002311
Douglas Gregore254f902009-02-04 00:32:51 +00002312 // C++ [basic.lookup.koenig]p2:
2313 // For each argument type T in the function call, there is a set
2314 // of zero or more associated namespaces and a set of zero or more
2315 // associated classes to be considered. The sets of namespaces and
2316 // classes is determined entirely by the types of the function
2317 // arguments (and the namespace of any template template
Mike Stump11289f42009-09-09 15:08:12 +00002318 // argument).
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002319 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
Douglas Gregore254f902009-02-04 00:32:51 +00002320 Expr *Arg = Args[ArgIdx];
2321
2322 if (Arg->getType() != Context.OverloadTy) {
John McCallf24d7bb2010-05-28 18:45:08 +00002323 addAssociatedClassesAndNamespaces(Result, Arg->getType());
Douglas Gregore254f902009-02-04 00:32:51 +00002324 continue;
2325 }
2326
2327 // [...] In addition, if the argument is the name or address of a
2328 // set of overloaded functions and/or function templates, its
2329 // associated classes and namespaces are the union of those
2330 // associated with each of the members of the set: the namespace
2331 // in which the function or function template is defined and the
2332 // classes and namespaces associated with its (non-dependent)
2333 // parameter types and return type.
Douglas Gregorbe759252009-07-08 10:57:20 +00002334 Arg = Arg->IgnoreParens();
John McCalld14a8642009-11-21 08:51:07 +00002335 if (UnaryOperator *unaryOp = dyn_cast<UnaryOperator>(Arg))
John McCalle3027922010-08-25 11:45:40 +00002336 if (unaryOp->getOpcode() == UO_AddrOf)
John McCalld14a8642009-11-21 08:51:07 +00002337 Arg = unaryOp->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00002338
John McCallf24d7bb2010-05-28 18:45:08 +00002339 UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Arg);
2340 if (!ULE) continue;
John McCalld14a8642009-11-21 08:51:07 +00002341
Aaron Ballman1e606f42014-07-15 22:03:49 +00002342 for (const auto *D : ULE->decls()) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00002343 // Look through any using declarations to find the underlying function.
Aaron Ballman1e606f42014-07-15 22:03:49 +00002344 const FunctionDecl *FDecl = D->getUnderlyingDecl()->getAsFunction();
Douglas Gregore254f902009-02-04 00:32:51 +00002345
2346 // Add the classes and namespaces associated with the parameter
2347 // types and return type of this function.
John McCallf24d7bb2010-05-28 18:45:08 +00002348 addAssociatedClassesAndNamespaces(Result, FDecl->getType());
Douglas Gregore254f902009-02-04 00:32:51 +00002349 }
2350 }
2351}
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002352
John McCall5cebab12009-11-18 07:57:50 +00002353NamedDecl *Sema::LookupSingleName(Scope *S, DeclarationName Name,
Douglas Gregorb2ccf012010-04-15 22:33:43 +00002354 SourceLocation Loc,
John McCall5cebab12009-11-18 07:57:50 +00002355 LookupNameKind NameKind,
2356 RedeclarationKind Redecl) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +00002357 LookupResult R(*this, Name, Loc, NameKind, Redecl);
John McCall5cebab12009-11-18 07:57:50 +00002358 LookupName(R, S);
John McCall67c00872009-12-02 08:25:40 +00002359 return R.getAsSingle<NamedDecl>();
John McCall5cebab12009-11-18 07:57:50 +00002360}
2361
Douglas Gregorde9f17e2009-04-23 23:18:26 +00002362/// \brief Find the protocol with the given name, if any.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002363ObjCProtocolDecl *Sema::LookupProtocol(IdentifierInfo *II,
Douglas Gregor32c17572012-01-01 20:30:41 +00002364 SourceLocation IdLoc,
2365 RedeclarationKind Redecl) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +00002366 Decl *D = LookupSingleName(TUScope, II, IdLoc,
Douglas Gregor32c17572012-01-01 20:30:41 +00002367 LookupObjCProtocolName, Redecl);
Douglas Gregorde9f17e2009-04-23 23:18:26 +00002368 return cast_or_null<ObjCProtocolDecl>(D);
2369}
2370
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002371void Sema::LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
Mike Stump11289f42009-09-09 15:08:12 +00002372 QualType T1, QualType T2,
John McCall4c4c1df2010-01-26 03:27:55 +00002373 UnresolvedSetImpl &Functions) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002374 // C++ [over.match.oper]p3:
2375 // -- The set of non-member candidates is the result of the
2376 // unqualified lookup of operator@ in the context of the
2377 // expression according to the usual rules for name lookup in
2378 // unqualified function calls (3.4.2) except that all member
Richard Smith100b24a2014-04-17 01:52:14 +00002379 // functions are ignored.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002380 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
John McCall27b18f82009-11-17 02:14:36 +00002381 LookupResult Operators(*this, OpName, SourceLocation(), LookupOperatorName);
2382 LookupName(Operators, S);
Mike Stump11289f42009-09-09 15:08:12 +00002383
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002384 assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
Richard Smith100b24a2014-04-17 01:52:14 +00002385 Functions.append(Operators.begin(), Operators.end());
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002386}
2387
Alexis Hunt1da39282011-06-24 02:11:39 +00002388Sema::SpecialMemberOverloadResult *Sema::LookupSpecialMember(CXXRecordDecl *RD,
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002389 CXXSpecialMember SM,
2390 bool ConstArg,
2391 bool VolatileArg,
2392 bool RValueThis,
2393 bool ConstThis,
2394 bool VolatileThis) {
Richard Smith7d125a12012-11-27 21:20:31 +00002395 assert(CanDeclareSpecialMemberFunction(RD) &&
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002396 "doing special member lookup into record that isn't fully complete");
Richard Smith7d125a12012-11-27 21:20:31 +00002397 RD = RD->getDefinition();
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002398 if (RValueThis || ConstThis || VolatileThis)
2399 assert((SM == CXXCopyAssignment || SM == CXXMoveAssignment) &&
2400 "constructors and destructors always have unqualified lvalue this");
2401 if (ConstArg || VolatileArg)
2402 assert((SM != CXXDefaultConstructor && SM != CXXDestructor) &&
2403 "parameter-less special members can't have qualified arguments");
2404
2405 llvm::FoldingSetNodeID ID;
Alexis Hunt1da39282011-06-24 02:11:39 +00002406 ID.AddPointer(RD);
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002407 ID.AddInteger(SM);
2408 ID.AddInteger(ConstArg);
2409 ID.AddInteger(VolatileArg);
2410 ID.AddInteger(RValueThis);
2411 ID.AddInteger(ConstThis);
2412 ID.AddInteger(VolatileThis);
2413
2414 void *InsertPoint;
2415 SpecialMemberOverloadResult *Result =
2416 SpecialMemberCache.FindNodeOrInsertPos(ID, InsertPoint);
2417
2418 // This was already cached
2419 if (Result)
2420 return Result;
2421
Alexis Huntba8e18d2011-06-07 00:11:58 +00002422 Result = BumpAlloc.Allocate<SpecialMemberOverloadResult>();
2423 Result = new (Result) SpecialMemberOverloadResult(ID);
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002424 SpecialMemberCache.InsertNode(Result, InsertPoint);
2425
2426 if (SM == CXXDestructor) {
Richard Smith2be35f52012-12-01 02:35:44 +00002427 if (RD->needsImplicitDestructor())
Alexis Hunt1da39282011-06-24 02:11:39 +00002428 DeclareImplicitDestructor(RD);
2429 CXXDestructorDecl *DD = RD->getDestructor();
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002430 assert(DD && "record without a destructor");
2431 Result->setMethod(DD);
Richard Smith852265f2012-03-30 20:53:28 +00002432 Result->setKind(DD->isDeleted() ?
2433 SpecialMemberOverloadResult::NoMemberOrDeleted :
Richard Smith83c478d2012-04-20 18:46:14 +00002434 SpecialMemberOverloadResult::Success);
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002435 return Result;
2436 }
2437
Alexis Hunteef8ee02011-06-10 03:50:41 +00002438 // Prepare for overload resolution. Here we construct a synthetic argument
2439 // if necessary and make sure that implicit functions are declared.
Alexis Hunt1da39282011-06-24 02:11:39 +00002440 CanQualType CanTy = Context.getCanonicalType(Context.getTagDeclType(RD));
Alexis Hunteef8ee02011-06-10 03:50:41 +00002441 DeclarationName Name;
Craig Topperc3ec1492014-05-26 06:22:03 +00002442 Expr *Arg = nullptr;
Alexis Hunteef8ee02011-06-10 03:50:41 +00002443 unsigned NumArgs;
2444
Richard Smith83c478d2012-04-20 18:46:14 +00002445 QualType ArgType = CanTy;
2446 ExprValueKind VK = VK_LValue;
2447
Alexis Hunteef8ee02011-06-10 03:50:41 +00002448 if (SM == CXXDefaultConstructor) {
2449 Name = Context.DeclarationNames.getCXXConstructorName(CanTy);
2450 NumArgs = 0;
Alexis Hunt1da39282011-06-24 02:11:39 +00002451 if (RD->needsImplicitDefaultConstructor())
2452 DeclareImplicitDefaultConstructor(RD);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002453 } else {
2454 if (SM == CXXCopyConstructor || SM == CXXMoveConstructor) {
2455 Name = Context.DeclarationNames.getCXXConstructorName(CanTy);
Richard Smith2be35f52012-12-01 02:35:44 +00002456 if (RD->needsImplicitCopyConstructor())
Alexis Hunt1da39282011-06-24 02:11:39 +00002457 DeclareImplicitCopyConstructor(RD);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002458 if (getLangOpts().CPlusPlus11 && RD->needsImplicitMoveConstructor())
Sebastian Redl22653ba2011-08-30 19:58:05 +00002459 DeclareImplicitMoveConstructor(RD);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002460 } else {
2461 Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Richard Smith2be35f52012-12-01 02:35:44 +00002462 if (RD->needsImplicitCopyAssignment())
Alexis Hunt1da39282011-06-24 02:11:39 +00002463 DeclareImplicitCopyAssignment(RD);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002464 if (getLangOpts().CPlusPlus11 && RD->needsImplicitMoveAssignment())
Sebastian Redl22653ba2011-08-30 19:58:05 +00002465 DeclareImplicitMoveAssignment(RD);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002466 }
2467
Alexis Hunteef8ee02011-06-10 03:50:41 +00002468 if (ConstArg)
2469 ArgType.addConst();
2470 if (VolatileArg)
2471 ArgType.addVolatile();
2472
2473 // This isn't /really/ specified by the standard, but it's implied
2474 // we should be working from an RValue in the case of move to ensure
2475 // that we prefer to bind to rvalue references, and an LValue in the
2476 // case of copy to ensure we don't bind to rvalue references.
2477 // Possibly an XValue is actually correct in the case of move, but
2478 // there is no semantic difference for class types in this restricted
2479 // case.
Alexis Hunt46d1ce22011-06-22 22:13:13 +00002480 if (SM == CXXCopyConstructor || SM == CXXCopyAssignment)
Alexis Hunteef8ee02011-06-10 03:50:41 +00002481 VK = VK_LValue;
2482 else
2483 VK = VK_RValue;
Richard Smith83c478d2012-04-20 18:46:14 +00002484 }
Alexis Hunteef8ee02011-06-10 03:50:41 +00002485
Richard Smith83c478d2012-04-20 18:46:14 +00002486 OpaqueValueExpr FakeArg(SourceLocation(), ArgType, VK);
2487
2488 if (SM != CXXDefaultConstructor) {
Alexis Hunteef8ee02011-06-10 03:50:41 +00002489 NumArgs = 1;
Richard Smith83c478d2012-04-20 18:46:14 +00002490 Arg = &FakeArg;
Alexis Hunteef8ee02011-06-10 03:50:41 +00002491 }
2492
2493 // Create the object argument
2494 QualType ThisTy = CanTy;
2495 if (ConstThis)
2496 ThisTy.addConst();
2497 if (VolatileThis)
2498 ThisTy.addVolatile();
Alexis Hunt080709f2011-06-23 00:26:20 +00002499 Expr::Classification Classification =
Richard Smith83c478d2012-04-20 18:46:14 +00002500 OpaqueValueExpr(SourceLocation(), ThisTy,
2501 RValueThis ? VK_RValue : VK_LValue).Classify(Context);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002502
2503 // Now we perform lookup on the name we computed earlier and do overload
2504 // resolution. Lookup is only performed directly into the class since there
2505 // will always be a (possibly implicit) declaration to shadow any others.
Richard Smith100b24a2014-04-17 01:52:14 +00002506 OverloadCandidateSet OCS(RD->getLocation(), OverloadCandidateSet::CSK_Normal);
David Blaikieff7d47a2012-12-19 00:45:41 +00002507 DeclContext::lookup_result R = RD->lookup(Name);
Richard Smith8c37ab52015-02-11 01:48:47 +00002508
2509 if (R.empty()) {
2510 // We might have no default constructor because we have a lambda's closure
2511 // type, rather than because there's some other declared constructor.
2512 // Every class has a copy/move constructor, copy/move assignment, and
2513 // destructor.
2514 assert(SM == CXXDefaultConstructor &&
2515 "lookup for a constructor or assignment operator was empty");
2516 Result->setMethod(nullptr);
2517 Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);
2518 return Result;
2519 }
Chandler Carruth7deaae72013-08-18 07:20:52 +00002520
2521 // Copy the candidates as our processing of them may load new declarations
2522 // from an external source and invalidate lookup_result.
2523 SmallVector<NamedDecl *, 8> Candidates(R.begin(), R.end());
2524
Aaron Ballman1e606f42014-07-15 22:03:49 +00002525 for (auto *Cand : Candidates) {
Alexis Hunt1da39282011-06-24 02:11:39 +00002526 if (Cand->isInvalidDecl())
Alexis Hunteef8ee02011-06-10 03:50:41 +00002527 continue;
2528
Alexis Hunt1da39282011-06-24 02:11:39 +00002529 if (UsingShadowDecl *U = dyn_cast<UsingShadowDecl>(Cand)) {
2530 // FIXME: [namespace.udecl]p15 says that we should only consider a
2531 // using declaration here if it does not match a declaration in the
2532 // derived class. We do not implement this correctly in other cases
2533 // either.
2534 Cand = U->getTargetDecl();
2535
2536 if (Cand->isInvalidDecl())
2537 continue;
2538 }
2539
2540 if (CXXMethodDecl *M = dyn_cast<CXXMethodDecl>(Cand)) {
Alexis Hunt080709f2011-06-23 00:26:20 +00002541 if (SM == CXXCopyAssignment || SM == CXXMoveAssignment)
Alexis Hunt1da39282011-06-24 02:11:39 +00002542 AddMethodCandidate(M, DeclAccessPair::make(M, AS_public), RD, ThisTy,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002543 Classification, llvm::makeArrayRef(&Arg, NumArgs),
2544 OCS, true);
Alexis Hunt080709f2011-06-23 00:26:20 +00002545 else
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002546 AddOverloadCandidate(M, DeclAccessPair::make(M, AS_public),
2547 llvm::makeArrayRef(&Arg, NumArgs), OCS, true);
Alexis Hunt2949f022011-06-22 02:58:46 +00002548 } else if (FunctionTemplateDecl *Tmpl =
Alexis Hunt1da39282011-06-24 02:11:39 +00002549 dyn_cast<FunctionTemplateDecl>(Cand)) {
Alexis Hunt080709f2011-06-23 00:26:20 +00002550 if (SM == CXXCopyAssignment || SM == CXXMoveAssignment)
2551 AddMethodTemplateCandidate(Tmpl, DeclAccessPair::make(Tmpl, AS_public),
Craig Topperc3ec1492014-05-26 06:22:03 +00002552 RD, nullptr, ThisTy, Classification,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002553 llvm::makeArrayRef(&Arg, NumArgs),
Alexis Hunt080709f2011-06-23 00:26:20 +00002554 OCS, true);
2555 else
2556 AddTemplateOverloadCandidate(Tmpl, DeclAccessPair::make(Tmpl, AS_public),
Craig Topperc3ec1492014-05-26 06:22:03 +00002557 nullptr, llvm::makeArrayRef(&Arg, NumArgs),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002558 OCS, true);
Alexis Hunt1da39282011-06-24 02:11:39 +00002559 } else {
2560 assert(isa<UsingDecl>(Cand) && "illegal Kind of operator = Decl");
Alexis Hunteef8ee02011-06-10 03:50:41 +00002561 }
2562 }
2563
2564 OverloadCandidateSet::iterator Best;
2565 switch (OCS.BestViableFunction(*this, SourceLocation(), Best)) {
2566 case OR_Success:
2567 Result->setMethod(cast<CXXMethodDecl>(Best->Function));
Richard Smith83c478d2012-04-20 18:46:14 +00002568 Result->setKind(SpecialMemberOverloadResult::Success);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002569 break;
2570
2571 case OR_Deleted:
2572 Result->setMethod(cast<CXXMethodDecl>(Best->Function));
Richard Smith852265f2012-03-30 20:53:28 +00002573 Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002574 break;
2575
2576 case OR_Ambiguous:
Craig Topperc3ec1492014-05-26 06:22:03 +00002577 Result->setMethod(nullptr);
Richard Smith852265f2012-03-30 20:53:28 +00002578 Result->setKind(SpecialMemberOverloadResult::Ambiguous);
2579 break;
2580
Alexis Hunteef8ee02011-06-10 03:50:41 +00002581 case OR_No_Viable_Function:
Craig Topperc3ec1492014-05-26 06:22:03 +00002582 Result->setMethod(nullptr);
Richard Smith852265f2012-03-30 20:53:28 +00002583 Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002584 break;
2585 }
2586
2587 return Result;
2588}
2589
2590/// \brief Look up the default constructor for the given class.
2591CXXConstructorDecl *Sema::LookupDefaultConstructor(CXXRecordDecl *Class) {
Alexis Hunt899bd442011-06-10 04:44:37 +00002592 SpecialMemberOverloadResult *Result =
Alexis Hunteef8ee02011-06-10 03:50:41 +00002593 LookupSpecialMember(Class, CXXDefaultConstructor, false, false, false,
2594 false, false);
2595
2596 return cast_or_null<CXXConstructorDecl>(Result->getMethod());
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002597}
2598
Alexis Hunt491ec602011-06-21 23:42:56 +00002599/// \brief Look up the copying constructor for the given class.
2600CXXConstructorDecl *Sema::LookupCopyingConstructor(CXXRecordDecl *Class,
Richard Smith83c478d2012-04-20 18:46:14 +00002601 unsigned Quals) {
Alexis Hunt899bd442011-06-10 04:44:37 +00002602 assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2603 "non-const, non-volatile qualifiers for copy ctor arg");
2604 SpecialMemberOverloadResult *Result =
2605 LookupSpecialMember(Class, CXXCopyConstructor, Quals & Qualifiers::Const,
2606 Quals & Qualifiers::Volatile, false, false, false);
2607
Alexis Hunt899bd442011-06-10 04:44:37 +00002608 return cast_or_null<CXXConstructorDecl>(Result->getMethod());
2609}
2610
Sebastian Redl22653ba2011-08-30 19:58:05 +00002611/// \brief Look up the moving constructor for the given class.
Richard Smith1c6461e2012-07-18 03:36:00 +00002612CXXConstructorDecl *Sema::LookupMovingConstructor(CXXRecordDecl *Class,
2613 unsigned Quals) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00002614 SpecialMemberOverloadResult *Result =
Richard Smith1c6461e2012-07-18 03:36:00 +00002615 LookupSpecialMember(Class, CXXMoveConstructor, Quals & Qualifiers::Const,
2616 Quals & Qualifiers::Volatile, false, false, false);
Sebastian Redl22653ba2011-08-30 19:58:05 +00002617
2618 return cast_or_null<CXXConstructorDecl>(Result->getMethod());
2619}
2620
Douglas Gregor52b72822010-07-02 23:12:18 +00002621/// \brief Look up the constructors for the given class.
2622DeclContext::lookup_result Sema::LookupConstructors(CXXRecordDecl *Class) {
Alexis Hunteef8ee02011-06-10 03:50:41 +00002623 // If the implicit constructors have not yet been declared, do so now.
Richard Smith7d125a12012-11-27 21:20:31 +00002624 if (CanDeclareSpecialMemberFunction(Class)) {
Alexis Huntea6f0322011-05-11 22:34:38 +00002625 if (Class->needsImplicitDefaultConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +00002626 DeclareImplicitDefaultConstructor(Class);
Richard Smith2be35f52012-12-01 02:35:44 +00002627 if (Class->needsImplicitCopyConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +00002628 DeclareImplicitCopyConstructor(Class);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002629 if (getLangOpts().CPlusPlus11 && Class->needsImplicitMoveConstructor())
Sebastian Redl22653ba2011-08-30 19:58:05 +00002630 DeclareImplicitMoveConstructor(Class);
Douglas Gregor9672f922010-07-03 00:47:00 +00002631 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002632
Douglas Gregor52b72822010-07-02 23:12:18 +00002633 CanQualType T = Context.getCanonicalType(Context.getTypeDeclType(Class));
2634 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(T);
2635 return Class->lookup(Name);
2636}
2637
Alexis Hunt491ec602011-06-21 23:42:56 +00002638/// \brief Look up the copying assignment operator for the given class.
2639CXXMethodDecl *Sema::LookupCopyingAssignment(CXXRecordDecl *Class,
2640 unsigned Quals, bool RValueThis,
Richard Smith83c478d2012-04-20 18:46:14 +00002641 unsigned ThisQuals) {
Alexis Hunt491ec602011-06-21 23:42:56 +00002642 assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2643 "non-const, non-volatile qualifiers for copy assignment arg");
2644 assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2645 "non-const, non-volatile qualifiers for copy assignment this");
2646 SpecialMemberOverloadResult *Result =
2647 LookupSpecialMember(Class, CXXCopyAssignment, Quals & Qualifiers::Const,
2648 Quals & Qualifiers::Volatile, RValueThis,
2649 ThisQuals & Qualifiers::Const,
2650 ThisQuals & Qualifiers::Volatile);
2651
Alexis Hunt491ec602011-06-21 23:42:56 +00002652 return Result->getMethod();
2653}
2654
Sebastian Redl22653ba2011-08-30 19:58:05 +00002655/// \brief Look up the moving assignment operator for the given class.
2656CXXMethodDecl *Sema::LookupMovingAssignment(CXXRecordDecl *Class,
Richard Smith1c6461e2012-07-18 03:36:00 +00002657 unsigned Quals,
Sebastian Redl22653ba2011-08-30 19:58:05 +00002658 bool RValueThis,
2659 unsigned ThisQuals) {
2660 assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2661 "non-const, non-volatile qualifiers for copy assignment this");
2662 SpecialMemberOverloadResult *Result =
Richard Smith1c6461e2012-07-18 03:36:00 +00002663 LookupSpecialMember(Class, CXXMoveAssignment, Quals & Qualifiers::Const,
2664 Quals & Qualifiers::Volatile, RValueThis,
Sebastian Redl22653ba2011-08-30 19:58:05 +00002665 ThisQuals & Qualifiers::Const,
2666 ThisQuals & Qualifiers::Volatile);
2667
2668 return Result->getMethod();
2669}
2670
Douglas Gregore71edda2010-07-01 22:47:18 +00002671/// \brief Look for the destructor of the given class.
2672///
Alexis Hunt967ea7c2011-06-03 21:10:40 +00002673/// During semantic analysis, this routine should be used in lieu of
2674/// CXXRecordDecl::getDestructor().
Douglas Gregore71edda2010-07-01 22:47:18 +00002675///
2676/// \returns The destructor for this class.
2677CXXDestructorDecl *Sema::LookupDestructor(CXXRecordDecl *Class) {
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002678 return cast<CXXDestructorDecl>(LookupSpecialMember(Class, CXXDestructor,
2679 false, false, false,
2680 false, false)->getMethod());
Douglas Gregore71edda2010-07-01 22:47:18 +00002681}
2682
Richard Smithbcc22fc2012-03-09 08:00:36 +00002683/// LookupLiteralOperator - Determine which literal operator should be used for
2684/// a user-defined literal, per C++11 [lex.ext].
2685///
2686/// Normal overload resolution is not used to select which literal operator to
2687/// call for a user-defined literal. Look up the provided literal operator name,
2688/// and filter the results to the appropriate set for the given argument types.
2689Sema::LiteralOperatorLookupResult
2690Sema::LookupLiteralOperator(Scope *S, LookupResult &R,
2691 ArrayRef<QualType> ArgTys,
Richard Smithb8b41d32013-10-07 19:57:58 +00002692 bool AllowRaw, bool AllowTemplate,
2693 bool AllowStringTemplate) {
Richard Smithbcc22fc2012-03-09 08:00:36 +00002694 LookupName(R, S);
2695 assert(R.getResultKind() != LookupResult::Ambiguous &&
2696 "literal operator lookup can't be ambiguous");
2697
2698 // Filter the lookup results appropriately.
2699 LookupResult::Filter F = R.makeFilter();
2700
Richard Smithbcc22fc2012-03-09 08:00:36 +00002701 bool FoundRaw = false;
Richard Smithb8b41d32013-10-07 19:57:58 +00002702 bool FoundTemplate = false;
2703 bool FoundStringTemplate = false;
Richard Smithbcc22fc2012-03-09 08:00:36 +00002704 bool FoundExactMatch = false;
2705
2706 while (F.hasNext()) {
2707 Decl *D = F.next();
2708 if (UsingShadowDecl *USD = dyn_cast<UsingShadowDecl>(D))
2709 D = USD->getTargetDecl();
2710
Douglas Gregorc1970572013-04-10 05:18:00 +00002711 // If the declaration we found is invalid, skip it.
2712 if (D->isInvalidDecl()) {
2713 F.erase();
2714 continue;
2715 }
2716
Richard Smithb8b41d32013-10-07 19:57:58 +00002717 bool IsRaw = false;
2718 bool IsTemplate = false;
2719 bool IsStringTemplate = false;
2720 bool IsExactMatch = false;
2721
Richard Smithbcc22fc2012-03-09 08:00:36 +00002722 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2723 if (FD->getNumParams() == 1 &&
2724 FD->getParamDecl(0)->getType()->getAs<PointerType>())
2725 IsRaw = true;
Richard Smith550de452013-01-15 07:12:59 +00002726 else if (FD->getNumParams() == ArgTys.size()) {
Richard Smithbcc22fc2012-03-09 08:00:36 +00002727 IsExactMatch = true;
2728 for (unsigned ArgIdx = 0; ArgIdx != ArgTys.size(); ++ArgIdx) {
2729 QualType ParamTy = FD->getParamDecl(ArgIdx)->getType();
2730 if (!Context.hasSameUnqualifiedType(ArgTys[ArgIdx], ParamTy)) {
2731 IsExactMatch = false;
2732 break;
2733 }
2734 }
2735 }
2736 }
Richard Smithb8b41d32013-10-07 19:57:58 +00002737 if (FunctionTemplateDecl *FD = dyn_cast<FunctionTemplateDecl>(D)) {
2738 TemplateParameterList *Params = FD->getTemplateParameters();
2739 if (Params->size() == 1)
2740 IsTemplate = true;
2741 else
2742 IsStringTemplate = true;
2743 }
Richard Smithbcc22fc2012-03-09 08:00:36 +00002744
2745 if (IsExactMatch) {
2746 FoundExactMatch = true;
Richard Smithb8b41d32013-10-07 19:57:58 +00002747 AllowRaw = false;
2748 AllowTemplate = false;
2749 AllowStringTemplate = false;
2750 if (FoundRaw || FoundTemplate || FoundStringTemplate) {
Richard Smithbcc22fc2012-03-09 08:00:36 +00002751 // Go through again and remove the raw and template decls we've
2752 // already found.
2753 F.restart();
Richard Smithb8b41d32013-10-07 19:57:58 +00002754 FoundRaw = FoundTemplate = FoundStringTemplate = false;
Richard Smithbcc22fc2012-03-09 08:00:36 +00002755 }
Richard Smithb8b41d32013-10-07 19:57:58 +00002756 } else if (AllowRaw && IsRaw) {
2757 FoundRaw = true;
2758 } else if (AllowTemplate && IsTemplate) {
2759 FoundTemplate = true;
2760 } else if (AllowStringTemplate && IsStringTemplate) {
2761 FoundStringTemplate = true;
Richard Smithbcc22fc2012-03-09 08:00:36 +00002762 } else {
2763 F.erase();
2764 }
2765 }
2766
2767 F.done();
2768
2769 // C++11 [lex.ext]p3, p4: If S contains a literal operator with a matching
2770 // parameter type, that is used in preference to a raw literal operator
2771 // or literal operator template.
2772 if (FoundExactMatch)
2773 return LOLR_Cooked;
2774
2775 // C++11 [lex.ext]p3, p4: S shall contain a raw literal operator or a literal
2776 // operator template, but not both.
2777 if (FoundRaw && FoundTemplate) {
2778 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
Alp Tokera2794f92014-01-22 07:29:52 +00002779 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
2780 NoteOverloadCandidate((*I)->getUnderlyingDecl()->getAsFunction());
Richard Smithbcc22fc2012-03-09 08:00:36 +00002781 return LOLR_Error;
2782 }
2783
2784 if (FoundRaw)
2785 return LOLR_Raw;
2786
2787 if (FoundTemplate)
2788 return LOLR_Template;
2789
Richard Smithb8b41d32013-10-07 19:57:58 +00002790 if (FoundStringTemplate)
2791 return LOLR_StringTemplate;
2792
Richard Smithbcc22fc2012-03-09 08:00:36 +00002793 // Didn't find anything we could use.
2794 Diag(R.getNameLoc(), diag::err_ovl_no_viable_literal_operator)
2795 << R.getLookupName() << (int)ArgTys.size() << ArgTys[0]
Richard Smithb8b41d32013-10-07 19:57:58 +00002796 << (ArgTys.size() == 2 ? ArgTys[1] : QualType()) << AllowRaw
2797 << (AllowTemplate || AllowStringTemplate);
Richard Smithbcc22fc2012-03-09 08:00:36 +00002798 return LOLR_Error;
2799}
2800
John McCall8fe68082010-01-26 07:16:45 +00002801void ADLResult::insert(NamedDecl *New) {
2802 NamedDecl *&Old = Decls[cast<NamedDecl>(New->getCanonicalDecl())];
2803
2804 // If we haven't yet seen a decl for this key, or the last decl
2805 // was exactly this one, we're done.
Craig Topperc3ec1492014-05-26 06:22:03 +00002806 if (Old == nullptr || Old == New) {
John McCall8fe68082010-01-26 07:16:45 +00002807 Old = New;
2808 return;
2809 }
2810
2811 // Otherwise, decide which is a more recent redeclaration.
Alp Tokera2794f92014-01-22 07:29:52 +00002812 FunctionDecl *OldFD = Old->getAsFunction();
2813 FunctionDecl *NewFD = New->getAsFunction();
John McCall8fe68082010-01-26 07:16:45 +00002814
2815 FunctionDecl *Cursor = NewFD;
2816 while (true) {
Douglas Gregorec9fd132012-01-14 16:38:05 +00002817 Cursor = Cursor->getPreviousDecl();
John McCall8fe68082010-01-26 07:16:45 +00002818
2819 // If we got to the end without finding OldFD, OldFD is the newer
2820 // declaration; leave things as they are.
2821 if (!Cursor) return;
2822
2823 // If we do find OldFD, then NewFD is newer.
2824 if (Cursor == OldFD) break;
2825
2826 // Otherwise, keep looking.
2827 }
2828
2829 Old = New;
2830}
2831
Richard Smith100b24a2014-04-17 01:52:14 +00002832void Sema::ArgumentDependentLookup(DeclarationName Name, SourceLocation Loc,
2833 ArrayRef<Expr *> Args, ADLResult &Result) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002834 // Find all of the associated namespaces and classes based on the
2835 // arguments we have.
2836 AssociatedNamespaceSet AssociatedNamespaces;
2837 AssociatedClassSet AssociatedClasses;
John McCall7d8b0412012-08-24 20:38:34 +00002838 FindAssociatedClassesAndNamespaces(Loc, Args,
John McCallc7e8e792009-08-07 22:18:02 +00002839 AssociatedNamespaces,
2840 AssociatedClasses);
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002841
2842 // C++ [basic.lookup.argdep]p3:
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002843 // Let X be the lookup set produced by unqualified lookup (3.4.1)
2844 // and let Y be the lookup set produced by argument dependent
2845 // lookup (defined as follows). If X contains [...] then Y is
2846 // empty. Otherwise Y is the set of declarations found in the
2847 // namespaces associated with the argument types as described
2848 // below. The set of declarations found by the lookup of the name
2849 // is the union of X and Y.
2850 //
2851 // Here, we compute Y and add its members to the overloaded
2852 // candidate set.
Aaron Ballman1e606f42014-07-15 22:03:49 +00002853 for (auto *NS : AssociatedNamespaces) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002854 // When considering an associated namespace, the lookup is the
2855 // same as the lookup performed when the associated namespace is
2856 // used as a qualifier (3.4.3.2) except that:
2857 //
2858 // -- Any using-directives in the associated namespace are
2859 // ignored.
2860 //
John McCallc7e8e792009-08-07 22:18:02 +00002861 // -- Any namespace-scope friend functions declared in
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002862 // associated classes are visible within their respective
2863 // namespaces even if they are not visible during an ordinary
2864 // lookup (11.4).
Aaron Ballman1e606f42014-07-15 22:03:49 +00002865 DeclContext::lookup_result R = NS->lookup(Name);
2866 for (auto *D : R) {
John McCallaa74a0c2009-08-28 07:59:38 +00002867 // If the only declaration here is an ordinary friend, consider
2868 // it only if it was declared in an associated classes.
Richard Smith541b38b2013-09-20 01:15:31 +00002869 if ((D->getIdentifierNamespace() & Decl::IDNS_Ordinary) == 0) {
2870 // If it's neither ordinarily visible nor a friend, we can't find it.
2871 if ((D->getIdentifierNamespace() & Decl::IDNS_OrdinaryFriend) == 0)
2872 continue;
2873
Richard Smith64017682013-07-17 23:53:16 +00002874 bool DeclaredInAssociatedClass = false;
2875 for (Decl *DI = D; DI; DI = DI->getPreviousDecl()) {
2876 DeclContext *LexDC = DI->getLexicalDeclContext();
2877 if (isa<CXXRecordDecl>(LexDC) &&
2878 AssociatedClasses.count(cast<CXXRecordDecl>(LexDC))) {
2879 DeclaredInAssociatedClass = true;
2880 break;
2881 }
2882 }
2883 if (!DeclaredInAssociatedClass)
John McCalld1e9d832009-08-11 06:59:38 +00002884 continue;
2885 }
Mike Stump11289f42009-09-09 15:08:12 +00002886
John McCall91f61fc2010-01-26 06:04:06 +00002887 if (isa<UsingShadowDecl>(D))
2888 D = cast<UsingShadowDecl>(D)->getTargetDecl();
John McCall4c4c1df2010-01-26 03:27:55 +00002889
Richard Smith100b24a2014-04-17 01:52:14 +00002890 if (!isa<FunctionDecl>(D) && !isa<FunctionTemplateDecl>(D))
John McCall8fe68082010-01-26 07:16:45 +00002891 continue;
2892
2893 Result.insert(D);
Douglas Gregor6127ca42009-06-23 20:14:09 +00002894 }
2895 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002896}
Douglas Gregor2d435302009-12-30 17:04:44 +00002897
2898//----------------------------------------------------------------------------
2899// Search for all visible declarations.
2900//----------------------------------------------------------------------------
2901VisibleDeclConsumer::~VisibleDeclConsumer() { }
2902
Richard Smithe156254d2013-08-20 20:35:18 +00002903bool VisibleDeclConsumer::includeHiddenDecls() const { return false; }
2904
Douglas Gregor2d435302009-12-30 17:04:44 +00002905namespace {
2906
2907class ShadowContextRAII;
2908
2909class VisibleDeclsRecord {
2910public:
2911 /// \brief An entry in the shadow map, which is optimized to store a
2912 /// single declaration (the common case) but can also store a list
2913 /// of declarations.
Chris Lattner83cfc7c2011-07-18 01:54:02 +00002914 typedef llvm::TinyPtrVector<NamedDecl*> ShadowMapEntry;
Douglas Gregor2d435302009-12-30 17:04:44 +00002915
2916private:
2917 /// \brief A mapping from declaration names to the declarations that have
2918 /// this name within a particular scope.
2919 typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
2920
2921 /// \brief A list of shadow maps, which is used to model name hiding.
2922 std::list<ShadowMap> ShadowMaps;
2923
2924 /// \brief The declaration contexts we have already visited.
2925 llvm::SmallPtrSet<DeclContext *, 8> VisitedContexts;
2926
2927 friend class ShadowContextRAII;
2928
2929public:
2930 /// \brief Determine whether we have already visited this context
2931 /// (and, if not, note that we are going to visit that context now).
2932 bool visitedContext(DeclContext *Ctx) {
David Blaikie82e95a32014-11-19 07:49:47 +00002933 return !VisitedContexts.insert(Ctx).second;
Douglas Gregor2d435302009-12-30 17:04:44 +00002934 }
2935
Douglas Gregor39982192010-08-15 06:18:01 +00002936 bool alreadyVisitedContext(DeclContext *Ctx) {
2937 return VisitedContexts.count(Ctx);
2938 }
2939
Douglas Gregor2d435302009-12-30 17:04:44 +00002940 /// \brief Determine whether the given declaration is hidden in the
2941 /// current scope.
2942 ///
2943 /// \returns the declaration that hides the given declaration, or
2944 /// NULL if no such declaration exists.
2945 NamedDecl *checkHidden(NamedDecl *ND);
2946
2947 /// \brief Add a declaration to the current shadow map.
Chris Lattner83cfc7c2011-07-18 01:54:02 +00002948 void add(NamedDecl *ND) {
2949 ShadowMaps.back()[ND->getDeclName()].push_back(ND);
2950 }
Douglas Gregor2d435302009-12-30 17:04:44 +00002951};
2952
2953/// \brief RAII object that records when we've entered a shadow context.
2954class ShadowContextRAII {
2955 VisibleDeclsRecord &Visible;
2956
2957 typedef VisibleDeclsRecord::ShadowMap ShadowMap;
2958
2959public:
2960 ShadowContextRAII(VisibleDeclsRecord &Visible) : Visible(Visible) {
2961 Visible.ShadowMaps.push_back(ShadowMap());
2962 }
2963
2964 ~ShadowContextRAII() {
Douglas Gregor2d435302009-12-30 17:04:44 +00002965 Visible.ShadowMaps.pop_back();
2966 }
2967};
2968
2969} // end anonymous namespace
2970
Douglas Gregor2d435302009-12-30 17:04:44 +00002971NamedDecl *VisibleDeclsRecord::checkHidden(NamedDecl *ND) {
Douglas Gregor0235c422010-01-14 00:06:47 +00002972 // Look through using declarations.
2973 ND = ND->getUnderlyingDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002974
Douglas Gregor2d435302009-12-30 17:04:44 +00002975 unsigned IDNS = ND->getIdentifierNamespace();
2976 std::list<ShadowMap>::reverse_iterator SM = ShadowMaps.rbegin();
2977 for (std::list<ShadowMap>::reverse_iterator SMEnd = ShadowMaps.rend();
2978 SM != SMEnd; ++SM) {
2979 ShadowMap::iterator Pos = SM->find(ND->getDeclName());
2980 if (Pos == SM->end())
2981 continue;
2982
Aaron Ballman1e606f42014-07-15 22:03:49 +00002983 for (auto *D : Pos->second) {
Douglas Gregor2d435302009-12-30 17:04:44 +00002984 // A tag declaration does not hide a non-tag declaration.
Aaron Ballman1e606f42014-07-15 22:03:49 +00002985 if (D->hasTagIdentifierNamespace() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002986 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
Douglas Gregor2d435302009-12-30 17:04:44 +00002987 Decl::IDNS_ObjCProtocol)))
2988 continue;
2989
2990 // Protocols are in distinct namespaces from everything else.
Aaron Ballman1e606f42014-07-15 22:03:49 +00002991 if (((D->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
Douglas Gregor2d435302009-12-30 17:04:44 +00002992 || (IDNS & Decl::IDNS_ObjCProtocol)) &&
Aaron Ballman1e606f42014-07-15 22:03:49 +00002993 D->getIdentifierNamespace() != IDNS)
Douglas Gregor2d435302009-12-30 17:04:44 +00002994 continue;
2995
Douglas Gregor09bbc652010-01-14 15:47:35 +00002996 // Functions and function templates in the same scope overload
2997 // rather than hide. FIXME: Look for hiding based on function
2998 // signatures!
Aaron Ballman1e606f42014-07-15 22:03:49 +00002999 if (D->getUnderlyingDecl()->isFunctionOrFunctionTemplate() &&
Alp Tokera2794f92014-01-22 07:29:52 +00003000 ND->getUnderlyingDecl()->isFunctionOrFunctionTemplate() &&
Douglas Gregor09bbc652010-01-14 15:47:35 +00003001 SM == ShadowMaps.rbegin())
Douglas Gregor200c99d2010-01-14 03:35:48 +00003002 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003003
Douglas Gregor2d435302009-12-30 17:04:44 +00003004 // We've found a declaration that hides this one.
Aaron Ballman1e606f42014-07-15 22:03:49 +00003005 return D;
Douglas Gregor2d435302009-12-30 17:04:44 +00003006 }
3007 }
3008
Craig Topperc3ec1492014-05-26 06:22:03 +00003009 return nullptr;
Douglas Gregor2d435302009-12-30 17:04:44 +00003010}
3011
3012static void LookupVisibleDecls(DeclContext *Ctx, LookupResult &Result,
3013 bool QualifiedNameLookup,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003014 bool InBaseClass,
Douglas Gregor2d435302009-12-30 17:04:44 +00003015 VisibleDeclConsumer &Consumer,
3016 VisibleDeclsRecord &Visited) {
Douglas Gregor0c8a1722010-02-04 23:42:48 +00003017 if (!Ctx)
3018 return;
3019
Douglas Gregor2d435302009-12-30 17:04:44 +00003020 // Make sure we don't visit the same context twice.
3021 if (Visited.visitedContext(Ctx->getPrimaryContext()))
3022 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003023
Douglas Gregor7454c562010-07-02 20:37:36 +00003024 if (CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(Ctx))
3025 Result.getSema().ForceDeclarationOfImplicitMembers(Class);
3026
Douglas Gregor2d435302009-12-30 17:04:44 +00003027 // Enumerate all of the results in this context.
Aaron Ballman576114e2014-03-14 15:28:49 +00003028 for (const auto &R : Ctx->lookups()) {
3029 for (auto *I : R) {
3030 if (NamedDecl *ND = dyn_cast<NamedDecl>(I)) {
Douglas Gregor4a814562011-12-14 16:03:29 +00003031 if ((ND = Result.getAcceptableDecl(ND))) {
Erik Verbruggen2e657ff2011-10-06 07:27:49 +00003032 Consumer.FoundDecl(ND, Visited.checkHidden(ND), Ctx, InBaseClass);
Douglas Gregor2d435302009-12-30 17:04:44 +00003033 Visited.add(ND);
3034 }
Douglas Gregora3b23b02010-12-09 21:44:02 +00003035 }
Douglas Gregor2d435302009-12-30 17:04:44 +00003036 }
3037 }
3038
3039 // Traverse using directives for qualified name lookup.
3040 if (QualifiedNameLookup) {
3041 ShadowContextRAII Shadow(Visited);
Aaron Ballman804a7fb2014-03-17 17:14:12 +00003042 for (auto I : Ctx->using_directives()) {
Aaron Ballman63ab7602014-03-07 13:44:44 +00003043 LookupVisibleDecls(I->getNominatedNamespace(), Result,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003044 QualifiedNameLookup, InBaseClass, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00003045 }
3046 }
3047
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003048 // Traverse the contexts of inherited C++ classes.
Douglas Gregor2d435302009-12-30 17:04:44 +00003049 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) {
John McCall67da35c2010-02-04 22:26:26 +00003050 if (!Record->hasDefinition())
3051 return;
3052
Aaron Ballman574705e2014-03-13 15:41:46 +00003053 for (const auto &B : Record->bases()) {
3054 QualType BaseType = B.getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003055
Douglas Gregor2d435302009-12-30 17:04:44 +00003056 // Don't look into dependent bases, because name lookup can't look
3057 // there anyway.
3058 if (BaseType->isDependentType())
3059 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003060
Douglas Gregor2d435302009-12-30 17:04:44 +00003061 const RecordType *Record = BaseType->getAs<RecordType>();
3062 if (!Record)
3063 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003064
Douglas Gregor2d435302009-12-30 17:04:44 +00003065 // FIXME: It would be nice to be able to determine whether referencing
3066 // a particular member would be ambiguous. For example, given
3067 //
3068 // struct A { int member; };
3069 // struct B { int member; };
3070 // struct C : A, B { };
3071 //
3072 // void f(C *c) { c->### }
3073 //
3074 // accessing 'member' would result in an ambiguity. However, we
3075 // could be smart enough to qualify the member with the base
3076 // class, e.g.,
3077 //
3078 // c->B::member
3079 //
3080 // or
3081 //
3082 // c->A::member
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003083
Douglas Gregor2d435302009-12-30 17:04:44 +00003084 // Find results in this base class (and its bases).
3085 ShadowContextRAII Shadow(Visited);
3086 LookupVisibleDecls(Record->getDecl(), Result, QualifiedNameLookup,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003087 true, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00003088 }
3089 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003090
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003091 // Traverse the contexts of Objective-C classes.
3092 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Ctx)) {
3093 // Traverse categories.
Aaron Ballman3fe486a2014-03-13 21:23:55 +00003094 for (auto *Cat : IFace->visible_categories()) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003095 ShadowContextRAII Shadow(Visited);
Aaron Ballman3fe486a2014-03-13 21:23:55 +00003096 LookupVisibleDecls(Cat, Result, QualifiedNameLookup, false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003097 Consumer, Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003098 }
3099
3100 // Traverse protocols.
Aaron Ballmana9f49e32014-03-13 20:55:22 +00003101 for (auto *I : IFace->all_referenced_protocols()) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003102 ShadowContextRAII Shadow(Visited);
Aaron Ballmana9f49e32014-03-13 20:55:22 +00003103 LookupVisibleDecls(I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003104 Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003105 }
3106
3107 // Traverse the superclass.
3108 if (IFace->getSuperClass()) {
3109 ShadowContextRAII Shadow(Visited);
3110 LookupVisibleDecls(IFace->getSuperClass(), Result, QualifiedNameLookup,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003111 true, Consumer, Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003112 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003113
Douglas Gregor0b59e802010-04-19 18:02:19 +00003114 // If there is an implementation, traverse it. We do this to find
3115 // synthesized ivars.
3116 if (IFace->getImplementation()) {
3117 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003118 LookupVisibleDecls(IFace->getImplementation(), Result,
Nick Lewycky13668f22012-04-03 20:26:45 +00003119 QualifiedNameLookup, InBaseClass, Consumer, Visited);
Douglas Gregor0b59e802010-04-19 18:02:19 +00003120 }
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003121 } else if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Ctx)) {
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00003122 for (auto *I : Protocol->protocols()) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003123 ShadowContextRAII Shadow(Visited);
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00003124 LookupVisibleDecls(I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003125 Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003126 }
3127 } else if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Ctx)) {
Aaron Ballman19a41762014-03-14 12:55:57 +00003128 for (auto *I : Category->protocols()) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003129 ShadowContextRAII Shadow(Visited);
Aaron Ballman19a41762014-03-14 12:55:57 +00003130 LookupVisibleDecls(I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003131 Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003132 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003133
Douglas Gregor0b59e802010-04-19 18:02:19 +00003134 // If there is an implementation, traverse it.
3135 if (Category->getImplementation()) {
3136 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003137 LookupVisibleDecls(Category->getImplementation(), Result,
Douglas Gregor0b59e802010-04-19 18:02:19 +00003138 QualifiedNameLookup, true, Consumer, Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003139 }
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003140 }
Douglas Gregor2d435302009-12-30 17:04:44 +00003141}
3142
3143static void LookupVisibleDecls(Scope *S, LookupResult &Result,
3144 UnqualUsingDirectiveSet &UDirs,
3145 VisibleDeclConsumer &Consumer,
3146 VisibleDeclsRecord &Visited) {
3147 if (!S)
3148 return;
3149
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003150 if (!S->getEntity() ||
3151 (!S->getParent() &&
Ted Kremenekc37877d2013-10-08 17:08:03 +00003152 !Visited.alreadyVisitedContext(S->getEntity())) ||
3153 (S->getEntity())->isFunctionOrMethod()) {
Richard Smith541b38b2013-09-20 01:15:31 +00003154 FindLocalExternScope FindLocals(Result);
Douglas Gregor712dcfe2010-01-07 00:31:29 +00003155 // Walk through the declarations in this Scope.
Aaron Ballman35c54952014-03-17 16:55:25 +00003156 for (auto *D : S->decls()) {
3157 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
Douglas Gregor4a814562011-12-14 16:03:29 +00003158 if ((ND = Result.getAcceptableDecl(ND))) {
Craig Topperc3ec1492014-05-26 06:22:03 +00003159 Consumer.FoundDecl(ND, Visited.checkHidden(ND), nullptr, false);
Douglas Gregor712dcfe2010-01-07 00:31:29 +00003160 Visited.add(ND);
3161 }
3162 }
3163 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003164
Douglas Gregor66230062010-03-15 14:33:29 +00003165 // FIXME: C++ [temp.local]p8
Craig Topperc3ec1492014-05-26 06:22:03 +00003166 DeclContext *Entity = nullptr;
Douglas Gregor4f248632010-01-01 17:44:25 +00003167 if (S->getEntity()) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003168 // Look into this scope's declaration context, along with any of its
3169 // parent lookup contexts (e.g., enclosing classes), up to the point
3170 // where we hit the context stored in the next outer scope.
Ted Kremenekc37877d2013-10-08 17:08:03 +00003171 Entity = S->getEntity();
Douglas Gregor66230062010-03-15 14:33:29 +00003172 DeclContext *OuterCtx = findOuterContext(S).first; // FIXME
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003173
Douglas Gregorea166062010-03-15 15:26:48 +00003174 for (DeclContext *Ctx = Entity; Ctx && !Ctx->Equals(OuterCtx);
Douglas Gregor2d435302009-12-30 17:04:44 +00003175 Ctx = Ctx->getLookupParent()) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003176 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
3177 if (Method->isInstanceMethod()) {
3178 // For instance methods, look for ivars in the method's interface.
3179 LookupResult IvarResult(Result.getSema(), Result.getLookupName(),
3180 Result.getNameLoc(), Sema::LookupMemberName);
Douglas Gregor05fcf842010-11-02 20:36:02 +00003181 if (ObjCInterfaceDecl *IFace = Method->getClassInterface()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003182 LookupVisibleDecls(IFace, IvarResult, /*QualifiedNameLookup=*/false,
Richard Smithe156254d2013-08-20 20:35:18 +00003183 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor05fcf842010-11-02 20:36:02 +00003184 }
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003185 }
3186
3187 // We've already performed all of the name lookup that we need
3188 // to for Objective-C methods; the next context will be the
3189 // outer scope.
3190 break;
3191 }
3192
Douglas Gregor2d435302009-12-30 17:04:44 +00003193 if (Ctx->isFunctionOrMethod())
3194 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003195
3196 LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003197 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00003198 }
3199 } else if (!S->getParent()) {
3200 // Look into the translation unit scope. We walk through the translation
3201 // unit's declaration context, because the Scope itself won't have all of
3202 // the declarations if we loaded a precompiled header.
3203 // FIXME: We would like the translation unit's Scope object to point to the
3204 // translation unit, so we don't need this special "if" branch. However,
3205 // doing so would force the normal C++ name-lookup code to look into the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003206 // translation unit decl when the IdentifierInfo chains would suffice.
Douglas Gregor2d435302009-12-30 17:04:44 +00003207 // Once we fix that problem (which is part of a more general "don't look
Douglas Gregor712dcfe2010-01-07 00:31:29 +00003208 // in DeclContexts unless we have to" optimization), we can eliminate this.
Douglas Gregor2d435302009-12-30 17:04:44 +00003209 Entity = Result.getSema().Context.getTranslationUnitDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003210 LookupVisibleDecls(Entity, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003211 /*InBaseClass=*/false, Consumer, Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003212 }
3213
Douglas Gregor2d435302009-12-30 17:04:44 +00003214 if (Entity) {
3215 // Lookup visible declarations in any namespaces found by using
3216 // directives.
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00003217 for (const UnqualUsingEntry &UUE : UDirs.getNamespacesFor(Entity))
3218 LookupVisibleDecls(const_cast<DeclContext *>(UUE.getNominatedNamespace()),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003219 Result, /*QualifiedNameLookup=*/false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003220 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00003221 }
3222
3223 // Lookup names in the parent scope.
3224 ShadowContextRAII Shadow(Visited);
3225 LookupVisibleDecls(S->getParent(), Result, UDirs, Consumer, Visited);
3226}
3227
3228void Sema::LookupVisibleDecls(Scope *S, LookupNameKind Kind,
Douglas Gregor39982192010-08-15 06:18:01 +00003229 VisibleDeclConsumer &Consumer,
3230 bool IncludeGlobalScope) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003231 // Determine the set of using directives available during
3232 // unqualified name lookup.
3233 Scope *Initial = S;
3234 UnqualUsingDirectiveSet UDirs;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003235 if (getLangOpts().CPlusPlus) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003236 // Find the first namespace or translation-unit scope.
3237 while (S && !isNamespaceOrTranslationUnitScope(S))
3238 S = S->getParent();
3239
3240 UDirs.visitScopeChain(Initial, S);
3241 }
3242 UDirs.done();
3243
3244 // Look for visible declarations.
3245 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
Richard Smithe156254d2013-08-20 20:35:18 +00003246 Result.setAllowHidden(Consumer.includeHiddenDecls());
Douglas Gregor2d435302009-12-30 17:04:44 +00003247 VisibleDeclsRecord Visited;
Douglas Gregor39982192010-08-15 06:18:01 +00003248 if (!IncludeGlobalScope)
3249 Visited.visitedContext(Context.getTranslationUnitDecl());
Douglas Gregor2d435302009-12-30 17:04:44 +00003250 ShadowContextRAII Shadow(Visited);
3251 ::LookupVisibleDecls(Initial, Result, UDirs, Consumer, Visited);
3252}
3253
3254void Sema::LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
Douglas Gregor39982192010-08-15 06:18:01 +00003255 VisibleDeclConsumer &Consumer,
3256 bool IncludeGlobalScope) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003257 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
Richard Smithe156254d2013-08-20 20:35:18 +00003258 Result.setAllowHidden(Consumer.includeHiddenDecls());
Douglas Gregor2d435302009-12-30 17:04:44 +00003259 VisibleDeclsRecord Visited;
Douglas Gregor39982192010-08-15 06:18:01 +00003260 if (!IncludeGlobalScope)
3261 Visited.visitedContext(Context.getTranslationUnitDecl());
Douglas Gregor2d435302009-12-30 17:04:44 +00003262 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003263 ::LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/true,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003264 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00003265}
3266
Chris Lattner43e7f312011-02-18 02:08:43 +00003267/// LookupOrCreateLabel - Do a name lookup of a label with the specified name.
Abramo Bagnara1c3af962011-03-05 18:21:20 +00003268/// If GnuLabelLoc is a valid source location, then this is a definition
3269/// of an __label__ label name, otherwise it is a normal label definition
3270/// or use.
Chris Lattner43e7f312011-02-18 02:08:43 +00003271LabelDecl *Sema::LookupOrCreateLabel(IdentifierInfo *II, SourceLocation Loc,
Abramo Bagnara1c3af962011-03-05 18:21:20 +00003272 SourceLocation GnuLabelLoc) {
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003273 // Do a lookup to see if we have a label with this name already.
Craig Topperc3ec1492014-05-26 06:22:03 +00003274 NamedDecl *Res = nullptr;
Abramo Bagnara1c3af962011-03-05 18:21:20 +00003275
3276 if (GnuLabelLoc.isValid()) {
3277 // Local label definitions always shadow existing labels.
3278 Res = LabelDecl::Create(Context, CurContext, Loc, II, GnuLabelLoc);
3279 Scope *S = CurScope;
3280 PushOnScopeChains(Res, S, true);
3281 return cast<LabelDecl>(Res);
3282 }
3283
3284 // Not a GNU local label.
3285 Res = LookupSingleName(CurScope, II, Loc, LookupLabel, NotForRedeclaration);
3286 // If we found a label, check to see if it is in the same context as us.
3287 // When in a Block, we don't want to reuse a label in an enclosing function.
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003288 if (Res && Res->getDeclContext() != CurContext)
Craig Topperc3ec1492014-05-26 06:22:03 +00003289 Res = nullptr;
3290 if (!Res) {
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003291 // If not forward referenced or defined already, create the backing decl.
Abramo Bagnara1c3af962011-03-05 18:21:20 +00003292 Res = LabelDecl::Create(Context, CurContext, Loc, II);
3293 Scope *S = CurScope->getFnParent();
Chris Lattner9ba479b2011-02-18 21:16:39 +00003294 assert(S && "Not in a function?");
3295 PushOnScopeChains(Res, S, true);
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003296 }
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003297 return cast<LabelDecl>(Res);
3298}
3299
3300//===----------------------------------------------------------------------===//
Douglas Gregor2d435302009-12-30 17:04:44 +00003301// Typo correction
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003302//===----------------------------------------------------------------------===//
Douglas Gregor2d435302009-12-30 17:04:44 +00003303
Kaelyn Takata0fc75192014-06-11 18:06:56 +00003304static bool isCandidateViable(CorrectionCandidateCallback &CCC,
3305 TypoCorrection &Candidate) {
3306 Candidate.setCallbackDistance(CCC.RankCandidate(Candidate));
3307 return Candidate.getEditDistance(false) != TypoCorrection::InvalidDistance;
3308}
3309
3310static void LookupPotentialTypoResult(Sema &SemaRef,
3311 LookupResult &Res,
3312 IdentifierInfo *Name,
3313 Scope *S, CXXScopeSpec *SS,
3314 DeclContext *MemberContext,
3315 bool EnteringContext,
3316 bool isObjCIvarLookup,
3317 bool FindHidden);
3318
Kaelyn Takata9ab7fb62014-10-27 18:07:40 +00003319/// \brief Check whether the declarations found for a typo correction are
3320/// visible, and if none of them are, convert the correction to an 'import
3321/// a module' correction.
3322static void checkCorrectionVisibility(Sema &SemaRef, TypoCorrection &TC) {
3323 if (TC.begin() == TC.end())
3324 return;
3325
3326 TypoCorrection::decl_iterator DI = TC.begin(), DE = TC.end();
3327
3328 for (/**/; DI != DE; ++DI)
3329 if (!LookupResult::isVisible(SemaRef, *DI))
3330 break;
3331 // Nothing to do if all decls are visible.
3332 if (DI == DE)
3333 return;
3334
3335 llvm::SmallVector<NamedDecl*, 4> NewDecls(TC.begin(), DI);
3336 bool AnyVisibleDecls = !NewDecls.empty();
3337
3338 for (/**/; DI != DE; ++DI) {
3339 NamedDecl *VisibleDecl = *DI;
3340 if (!LookupResult::isVisible(SemaRef, *DI))
3341 VisibleDecl = findAcceptableDecl(SemaRef, *DI);
3342
3343 if (VisibleDecl) {
3344 if (!AnyVisibleDecls) {
3345 // Found a visible decl, discard all hidden ones.
3346 AnyVisibleDecls = true;
3347 NewDecls.clear();
3348 }
3349 NewDecls.push_back(VisibleDecl);
3350 } else if (!AnyVisibleDecls && !(*DI)->isModulePrivate())
3351 NewDecls.push_back(*DI);
3352 }
3353
3354 if (NewDecls.empty())
3355 TC = TypoCorrection();
3356 else {
3357 TC.setCorrectionDecls(NewDecls);
3358 TC.setRequiresImport(!AnyVisibleDecls);
3359 }
3360}
3361
Kaelyn Takata0fc75192014-06-11 18:06:56 +00003362// Fill the supplied vector with the IdentifierInfo pointers for each piece of
3363// the given NestedNameSpecifier (i.e. given a NestedNameSpecifier "foo::bar::",
3364// fill the vector with the IdentifierInfo pointers for "foo" and "bar").
3365static void getNestedNameSpecifierIdentifiers(
3366 NestedNameSpecifier *NNS,
3367 SmallVectorImpl<const IdentifierInfo*> &Identifiers) {
3368 if (NestedNameSpecifier *Prefix = NNS->getPrefix())
3369 getNestedNameSpecifierIdentifiers(Prefix, Identifiers);
3370 else
3371 Identifiers.clear();
3372
3373 const IdentifierInfo *II = nullptr;
3374
3375 switch (NNS->getKind()) {
3376 case NestedNameSpecifier::Identifier:
3377 II = NNS->getAsIdentifier();
3378 break;
3379
3380 case NestedNameSpecifier::Namespace:
3381 if (NNS->getAsNamespace()->isAnonymousNamespace())
3382 return;
3383 II = NNS->getAsNamespace()->getIdentifier();
3384 break;
3385
3386 case NestedNameSpecifier::NamespaceAlias:
3387 II = NNS->getAsNamespaceAlias()->getIdentifier();
3388 break;
3389
3390 case NestedNameSpecifier::TypeSpecWithTemplate:
3391 case NestedNameSpecifier::TypeSpec:
3392 II = QualType(NNS->getAsType(), 0).getBaseTypeIdentifier();
3393 break;
3394
3395 case NestedNameSpecifier::Global:
Nikola Smiljanic67860242014-09-26 00:28:20 +00003396 case NestedNameSpecifier::Super:
Kaelyn Takata0fc75192014-06-11 18:06:56 +00003397 return;
3398 }
3399
3400 if (II)
3401 Identifiers.push_back(II);
3402}
3403
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003404void TypoCorrectionConsumer::FoundDecl(NamedDecl *ND, NamedDecl *Hiding,
Erik Verbruggen2e657ff2011-10-06 07:27:49 +00003405 DeclContext *Ctx, bool InBaseClass) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003406 // Don't consider hidden names for typo correction.
3407 if (Hiding)
3408 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003409
Douglas Gregor2d435302009-12-30 17:04:44 +00003410 // Only consider entities with identifiers for names, ignoring
3411 // special names (constructors, overloaded operators, selectors,
3412 // etc.).
3413 IdentifierInfo *Name = ND->getIdentifier();
3414 if (!Name)
3415 return;
3416
Richard Smithe156254d2013-08-20 20:35:18 +00003417 // Only consider visible declarations and declarations from modules with
3418 // names that exactly match.
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003419 if (!LookupResult::isVisible(SemaRef, ND) && Name != Typo &&
Richard Smithe156254d2013-08-20 20:35:18 +00003420 !findAcceptableDecl(SemaRef, ND))
3421 return;
3422
Douglas Gregor57756ea2010-10-14 22:11:03 +00003423 FoundName(Name->getName());
3424}
3425
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003426void TypoCorrectionConsumer::FoundName(StringRef Name) {
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00003427 // Compute the edit distance between the typo and the name of this
3428 // entity, and add the identifier to the list of results.
Craig Topperc3ec1492014-05-26 06:22:03 +00003429 addName(Name, nullptr);
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00003430}
3431
3432void TypoCorrectionConsumer::addKeywordResult(StringRef Keyword) {
3433 // Compute the edit distance between the typo and this keyword,
3434 // and add the keyword to the list of results.
Craig Topperc3ec1492014-05-26 06:22:03 +00003435 addName(Keyword, nullptr, nullptr, true);
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00003436}
3437
3438void TypoCorrectionConsumer::addName(StringRef Name, NamedDecl *ND,
3439 NestedNameSpecifier *NNS, bool isKeyword) {
Douglas Gregor93910a52010-10-19 19:39:10 +00003440 // Use a simple length-based heuristic to determine the minimum possible
3441 // edit distance. If the minimum isn't good enough, bail out early.
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003442 StringRef TypoStr = Typo->getName();
3443 unsigned MinED = abs((int)Name.size() - (int)TypoStr.size());
3444 if (MinED && TypoStr.size() / MinED < 3)
Douglas Gregor93910a52010-10-19 19:39:10 +00003445 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003446
Douglas Gregorc1fb15e2010-10-19 22:14:33 +00003447 // Compute an upper bound on the allowable edit distance, so that the
3448 // edit-distance algorithm can short-circuit.
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003449 unsigned UpperBound = (TypoStr.size() + 2) / 3 + 1;
3450 unsigned ED = TypoStr.edit_distance(Name, true, UpperBound);
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00003451 if (ED >= UpperBound) return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003452
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00003453 TypoCorrection TC(&SemaRef.Context.Idents.get(Name), ND, NNS, ED);
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00003454 if (isKeyword) TC.makeKeyword();
Kaelyn Takata0a313022014-11-20 22:06:26 +00003455 TC.setCorrectionRange(nullptr, Result.getLookupNameInfo());
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00003456 addCorrection(TC);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003457}
3458
Kaelyn Takatad2287c32014-10-27 18:07:13 +00003459static const unsigned MaxTypoDistanceResultSets = 5;
3460
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003461void TypoCorrectionConsumer::addCorrection(TypoCorrection Correction) {
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003462 StringRef TypoStr = Typo->getName();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003463 StringRef Name = Correction.getCorrectionAsIdentifierInfo()->getName();
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003464
3465 // For very short typos, ignore potential corrections that have a different
3466 // base identifier from the typo or which have a normalized edit distance
3467 // longer than the typo itself.
3468 if (TypoStr.size() < 3 &&
3469 (Name != TypoStr || Correction.getEditDistance(true) > TypoStr.size()))
3470 return;
3471
3472 // If the correction is resolved but is not viable, ignore it.
Kaelyn Takata9ab7fb62014-10-27 18:07:40 +00003473 if (Correction.isResolved()) {
3474 checkCorrectionVisibility(SemaRef, Correction);
3475 if (!Correction || !isCandidateViable(*CorrectionValidator, Correction))
3476 return;
3477 }
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003478
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00003479 TypoResultList &CList =
3480 CorrectionResults[Correction.getEditDistance(false)][Name];
Chandler Carruth7d85c9b2011-06-28 22:48:40 +00003481
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00003482 if (!CList.empty() && !CList.back().isResolved())
3483 CList.pop_back();
3484 if (NamedDecl *NewND = Correction.getCorrectionDecl()) {
3485 std::string CorrectionStr = Correction.getAsString(SemaRef.getLangOpts());
3486 for (TypoResultList::iterator RI = CList.begin(), RIEnd = CList.end();
3487 RI != RIEnd; ++RI) {
3488 // If the Correction refers to a decl already in the result list,
3489 // replace the existing result if the string representation of Correction
3490 // comes before the current result alphabetically, then stop as there is
3491 // nothing more to be done to add Correction to the candidate set.
3492 if (RI->getCorrectionDecl() == NewND) {
3493 if (CorrectionStr < RI->getAsString(SemaRef.getLangOpts()))
3494 *RI = Correction;
3495 return;
3496 }
3497 }
3498 }
3499 if (CList.empty() || Correction.isResolved())
3500 CList.push_back(Correction);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003501
Kaelyn Uhrain34fab552012-05-31 23:32:58 +00003502 while (CorrectionResults.size() > MaxTypoDistanceResultSets)
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003503 CorrectionResults.erase(std::prev(CorrectionResults.end()));
3504}
3505
3506void TypoCorrectionConsumer::addNamespaces(
3507 const llvm::MapVector<NamespaceDecl *, bool> &KnownNamespaces) {
3508 SearchNamespaces = true;
3509
3510 for (auto KNPair : KnownNamespaces)
3511 Namespaces.addNameSpecifier(KNPair.first);
3512
3513 bool SSIsTemplate = false;
3514 if (NestedNameSpecifier *NNS =
3515 (SS && SS->isValid()) ? SS->getScopeRep() : nullptr) {
3516 if (const Type *T = NNS->getAsType())
3517 SSIsTemplate = T->getTypeClass() == Type::TemplateSpecialization;
3518 }
3519 for (const auto *TI : SemaRef.getASTContext().types()) {
3520 if (CXXRecordDecl *CD = TI->getAsCXXRecordDecl()) {
3521 CD = CD->getCanonicalDecl();
3522 if (!CD->isDependentType() && !CD->isAnonymousStructOrUnion() &&
3523 !CD->isUnion() && CD->getIdentifier() &&
3524 (SSIsTemplate || !isa<ClassTemplateSpecializationDecl>(CD)) &&
3525 (CD->isBeingDefined() || CD->isCompleteDefinition()))
3526 Namespaces.addNameSpecifier(CD);
3527 }
3528 }
3529}
3530
Kaelyn Takata0d6a3ed2014-10-27 18:07:34 +00003531const TypoCorrection &TypoCorrectionConsumer::getNextCorrection() {
3532 if (++CurrentTCIndex < ValidatedCorrections.size())
3533 return ValidatedCorrections[CurrentTCIndex];
3534
3535 CurrentTCIndex = ValidatedCorrections.size();
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003536 while (!CorrectionResults.empty()) {
3537 auto DI = CorrectionResults.begin();
3538 if (DI->second.empty()) {
3539 CorrectionResults.erase(DI);
3540 continue;
3541 }
3542
3543 auto RI = DI->second.begin();
3544 if (RI->second.empty()) {
3545 DI->second.erase(RI);
3546 performQualifiedLookups();
3547 continue;
3548 }
3549
3550 TypoCorrection TC = RI->second.pop_back_val();
Kaelyn Takata9ab7fb62014-10-27 18:07:40 +00003551 if (TC.isResolved() || TC.requiresImport() || resolveCorrection(TC)) {
Kaelyn Takata0d6a3ed2014-10-27 18:07:34 +00003552 ValidatedCorrections.push_back(TC);
3553 return ValidatedCorrections[CurrentTCIndex];
3554 }
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003555 }
Kaelyn Takata0d6a3ed2014-10-27 18:07:34 +00003556 return ValidatedCorrections[0]; // The empty correction.
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003557}
3558
3559bool TypoCorrectionConsumer::resolveCorrection(TypoCorrection &Candidate) {
3560 IdentifierInfo *Name = Candidate.getCorrectionAsIdentifierInfo();
3561 DeclContext *TempMemberContext = MemberContext;
Kaelyn Takata6c759512014-10-27 18:07:37 +00003562 CXXScopeSpec *TempSS = SS.get();
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003563retry_lookup:
3564 LookupPotentialTypoResult(SemaRef, Result, Name, S, TempSS, TempMemberContext,
3565 EnteringContext,
Kaelyn Takata89c881b2014-10-27 18:07:29 +00003566 CorrectionValidator->IsObjCIvarLookup,
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003567 Name == Typo && !Candidate.WillReplaceSpecifier());
3568 switch (Result.getResultKind()) {
3569 case LookupResult::NotFound:
3570 case LookupResult::NotFoundInCurrentInstantiation:
3571 case LookupResult::FoundUnresolvedValue:
3572 if (TempSS) {
3573 // Immediately retry the lookup without the given CXXScopeSpec
3574 TempSS = nullptr;
3575 Candidate.WillReplaceSpecifier(true);
3576 goto retry_lookup;
3577 }
3578 if (TempMemberContext) {
3579 if (SS && !TempSS)
Kaelyn Takata6c759512014-10-27 18:07:37 +00003580 TempSS = SS.get();
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003581 TempMemberContext = nullptr;
3582 goto retry_lookup;
3583 }
3584 if (SearchNamespaces)
3585 QualifiedResults.push_back(Candidate);
3586 break;
3587
3588 case LookupResult::Ambiguous:
3589 // We don't deal with ambiguities.
3590 break;
3591
3592 case LookupResult::Found:
3593 case LookupResult::FoundOverloaded:
3594 // Store all of the Decls for overloaded symbols
3595 for (auto *TRD : Result)
3596 Candidate.addCorrectionDecl(TRD);
Kaelyn Takata9ab7fb62014-10-27 18:07:40 +00003597 checkCorrectionVisibility(SemaRef, Candidate);
Kaelyn Takata89c881b2014-10-27 18:07:29 +00003598 if (!isCandidateViable(*CorrectionValidator, Candidate)) {
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003599 if (SearchNamespaces)
3600 QualifiedResults.push_back(Candidate);
3601 break;
3602 }
Kaelyn Takata20deb1d2015-01-28 00:46:09 +00003603 Candidate.setCorrectionRange(SS.get(), Result.getLookupNameInfo());
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003604 return true;
3605 }
3606 return false;
3607}
3608
3609void TypoCorrectionConsumer::performQualifiedLookups() {
3610 unsigned TypoLen = Typo->getName().size();
3611 for (auto QR : QualifiedResults) {
3612 for (auto NSI : Namespaces) {
3613 DeclContext *Ctx = NSI.DeclCtx;
3614 const Type *NSType = NSI.NameSpecifier->getAsType();
3615
3616 // If the current NestedNameSpecifier refers to a class and the
3617 // current correction candidate is the name of that class, then skip
3618 // it as it is unlikely a qualified version of the class' constructor
3619 // is an appropriate correction.
3620 if (CXXRecordDecl *NSDecl = NSType ? NSType->getAsCXXRecordDecl() : 0) {
3621 if (NSDecl->getIdentifier() == QR.getCorrectionAsIdentifierInfo())
3622 continue;
3623 }
3624
3625 TypoCorrection TC(QR);
3626 TC.ClearCorrectionDecls();
3627 TC.setCorrectionSpecifier(NSI.NameSpecifier);
3628 TC.setQualifierDistance(NSI.EditDistance);
3629 TC.setCallbackDistance(0); // Reset the callback distance
3630
3631 // If the current correction candidate and namespace combination are
3632 // too far away from the original typo based on the normalized edit
3633 // distance, then skip performing a qualified name lookup.
3634 unsigned TmpED = TC.getEditDistance(true);
3635 if (QR.getCorrectionAsIdentifierInfo() != Typo && TmpED &&
3636 TypoLen / TmpED < 3)
3637 continue;
3638
3639 Result.clear();
3640 Result.setLookupName(QR.getCorrectionAsIdentifierInfo());
3641 if (!SemaRef.LookupQualifiedName(Result, Ctx))
3642 continue;
3643
3644 // Any corrections added below will be validated in subsequent
3645 // iterations of the main while() loop over the Consumer's contents.
3646 switch (Result.getResultKind()) {
3647 case LookupResult::Found:
3648 case LookupResult::FoundOverloaded: {
3649 if (SS && SS->isValid()) {
3650 std::string NewQualified = TC.getAsString(SemaRef.getLangOpts());
3651 std::string OldQualified;
3652 llvm::raw_string_ostream OldOStream(OldQualified);
3653 SS->getScopeRep()->print(OldOStream, SemaRef.getPrintingPolicy());
3654 OldOStream << Typo->getName();
3655 // If correction candidate would be an identical written qualified
3656 // identifer, then the existing CXXScopeSpec probably included a
3657 // typedef that didn't get accounted for properly.
3658 if (OldOStream.str() == NewQualified)
3659 break;
3660 }
3661 for (LookupResult::iterator TRD = Result.begin(), TRDEnd = Result.end();
3662 TRD != TRDEnd; ++TRD) {
3663 if (SemaRef.CheckMemberAccess(TC.getCorrectionRange().getBegin(),
3664 NSType ? NSType->getAsCXXRecordDecl()
3665 : nullptr,
3666 TRD.getPair()) == Sema::AR_accessible)
3667 TC.addCorrectionDecl(*TRD);
3668 }
Kaelyn Takata0a313022014-11-20 22:06:26 +00003669 if (TC.isResolved()) {
3670 TC.setCorrectionRange(SS.get(), Result.getLookupNameInfo());
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003671 addCorrection(TC);
Kaelyn Takata0a313022014-11-20 22:06:26 +00003672 }
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003673 break;
3674 }
3675 case LookupResult::NotFound:
3676 case LookupResult::NotFoundInCurrentInstantiation:
3677 case LookupResult::Ambiguous:
3678 case LookupResult::FoundUnresolvedValue:
3679 break;
3680 }
3681 }
3682 }
3683 QualifiedResults.clear();
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003684}
3685
Kaelyn Takatacd7c3a92014-06-11 18:33:46 +00003686TypoCorrectionConsumer::NamespaceSpecifierSet::NamespaceSpecifierSet(
3687 ASTContext &Context, DeclContext *CurContext, CXXScopeSpec *CurScopeSpec)
Benjamin Kramer15537272015-03-13 16:10:42 +00003688 : Context(Context), CurContextChain(buildContextChain(CurContext)) {
Kaelyn Takatacd7c3a92014-06-11 18:33:46 +00003689 if (NestedNameSpecifier *NNS =
3690 CurScopeSpec ? CurScopeSpec->getScopeRep() : nullptr) {
3691 llvm::raw_string_ostream SpecifierOStream(CurNameSpecifier);
3692 NNS->print(SpecifierOStream, Context.getPrintingPolicy());
3693
3694 getNestedNameSpecifierIdentifiers(NNS, CurNameSpecifierIdentifiers);
3695 }
3696 // Build the list of identifiers that would be used for an absolute
3697 // (from the global context) NestedNameSpecifier referring to the current
3698 // context.
3699 for (DeclContextList::reverse_iterator C = CurContextChain.rbegin(),
3700 CEnd = CurContextChain.rend();
3701 C != CEnd; ++C) {
3702 if (NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(*C))
3703 CurContextIdentifiers.push_back(ND->getIdentifier());
3704 }
3705
3706 // Add the global context as a NestedNameSpecifier
Hans Wennborg66010132014-06-11 21:24:13 +00003707 SpecifierInfo SI = {cast<DeclContext>(Context.getTranslationUnitDecl()),
3708 NestedNameSpecifier::GlobalSpecifier(Context), 1};
3709 DistanceMap[1].push_back(SI);
Kaelyn Takatacd7c3a92014-06-11 18:33:46 +00003710}
3711
Kaelyn Takata7dcc0e62014-06-11 18:07:08 +00003712auto TypoCorrectionConsumer::NamespaceSpecifierSet::buildContextChain(
3713 DeclContext *Start) -> DeclContextList {
Nick Lewycky0d9b3192013-04-08 21:55:21 +00003714 assert(Start && "Building a context chain from a null context");
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003715 DeclContextList Chain;
Craig Topperc3ec1492014-05-26 06:22:03 +00003716 for (DeclContext *DC = Start->getPrimaryContext(); DC != nullptr;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003717 DC = DC->getLookupParent()) {
3718 NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(DC);
3719 if (!DC->isInlineNamespace() && !DC->isTransparentContext() &&
3720 !(ND && ND->isAnonymousNamespace()))
3721 Chain.push_back(DC->getPrimaryContext());
3722 }
3723 return Chain;
3724}
3725
Kaelyn Takataa5bdbc82014-06-11 18:07:05 +00003726unsigned
3727TypoCorrectionConsumer::NamespaceSpecifierSet::buildNestedNameSpecifier(
3728 DeclContextList &DeclChain, NestedNameSpecifier *&NNS) {
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00003729 unsigned NumSpecifiers = 0;
3730 for (DeclContextList::reverse_iterator C = DeclChain.rbegin(),
3731 CEnd = DeclChain.rend();
3732 C != CEnd; ++C) {
3733 if (NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(*C)) {
3734 NNS = NestedNameSpecifier::Create(Context, NNS, ND);
3735 ++NumSpecifiers;
3736 } else if (RecordDecl *RD = dyn_cast_or_null<RecordDecl>(*C)) {
3737 NNS = NestedNameSpecifier::Create(Context, NNS, RD->isTemplateDecl(),
3738 RD->getTypeForDecl());
3739 ++NumSpecifiers;
3740 }
3741 }
3742 return NumSpecifiers;
3743}
3744
Kaelyn Takataa5bdbc82014-06-11 18:07:05 +00003745void TypoCorrectionConsumer::NamespaceSpecifierSet::addNameSpecifier(
3746 DeclContext *Ctx) {
Craig Topperc3ec1492014-05-26 06:22:03 +00003747 NestedNameSpecifier *NNS = nullptr;
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00003748 unsigned NumSpecifiers = 0;
Kaelyn Takata0fc75192014-06-11 18:06:56 +00003749 DeclContextList NamespaceDeclChain(buildContextChain(Ctx));
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00003750 DeclContextList FullNamespaceDeclChain(NamespaceDeclChain);
3751
3752 // Eliminate common elements from the two DeclContext chains.
3753 for (DeclContextList::reverse_iterator C = CurContextChain.rbegin(),
3754 CEnd = CurContextChain.rend();
3755 C != CEnd && !NamespaceDeclChain.empty() &&
3756 NamespaceDeclChain.back() == *C; ++C) {
3757 NamespaceDeclChain.pop_back();
3758 }
3759
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00003760 // Build the NestedNameSpecifier from what is left of the NamespaceDeclChain
Kaelyn Takataa5bdbc82014-06-11 18:07:05 +00003761 NumSpecifiers = buildNestedNameSpecifier(NamespaceDeclChain, NNS);
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00003762
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00003763 // Add an explicit leading '::' specifier if needed.
3764 if (NamespaceDeclChain.empty()) {
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00003765 // Rebuild the NestedNameSpecifier as a globally-qualified specifier.
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00003766 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00003767 NumSpecifiers =
Kaelyn Takataa5bdbc82014-06-11 18:07:05 +00003768 buildNestedNameSpecifier(FullNamespaceDeclChain, NNS);
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00003769 } else if (NamedDecl *ND =
3770 dyn_cast_or_null<NamedDecl>(NamespaceDeclChain.back())) {
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00003771 IdentifierInfo *Name = ND->getIdentifier();
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00003772 bool SameNameSpecifier = false;
3773 if (std::find(CurNameSpecifierIdentifiers.begin(),
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00003774 CurNameSpecifierIdentifiers.end(),
3775 Name) != CurNameSpecifierIdentifiers.end()) {
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00003776 std::string NewNameSpecifier;
3777 llvm::raw_string_ostream SpecifierOStream(NewNameSpecifier);
3778 SmallVector<const IdentifierInfo *, 4> NewNameSpecifierIdentifiers;
3779 getNestedNameSpecifierIdentifiers(NNS, NewNameSpecifierIdentifiers);
3780 NNS->print(SpecifierOStream, Context.getPrintingPolicy());
3781 SpecifierOStream.flush();
3782 SameNameSpecifier = NewNameSpecifier == CurNameSpecifier;
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00003783 }
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00003784 if (SameNameSpecifier ||
3785 std::find(CurContextIdentifiers.begin(), CurContextIdentifiers.end(),
3786 Name) != CurContextIdentifiers.end()) {
3787 // Rebuild the NestedNameSpecifier as a globally-qualified specifier.
3788 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
3789 NumSpecifiers =
Kaelyn Takataa5bdbc82014-06-11 18:07:05 +00003790 buildNestedNameSpecifier(FullNamespaceDeclChain, NNS);
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00003791 }
3792 }
3793
3794 // If the built NestedNameSpecifier would be replacing an existing
3795 // NestedNameSpecifier, use the number of component identifiers that
3796 // would need to be changed as the edit distance instead of the number
3797 // of components in the built NestedNameSpecifier.
3798 if (NNS && !CurNameSpecifierIdentifiers.empty()) {
3799 SmallVector<const IdentifierInfo*, 4> NewNameSpecifierIdentifiers;
3800 getNestedNameSpecifierIdentifiers(NNS, NewNameSpecifierIdentifiers);
3801 NumSpecifiers = llvm::ComputeEditDistance(
Craig Topper8c2a2a02014-08-30 16:55:39 +00003802 llvm::makeArrayRef(CurNameSpecifierIdentifiers),
3803 llvm::makeArrayRef(NewNameSpecifierIdentifiers));
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00003804 }
3805
Hans Wennborg66010132014-06-11 21:24:13 +00003806 SpecifierInfo SI = {Ctx, NNS, NumSpecifiers};
3807 DistanceMap[NumSpecifiers].push_back(SI);
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00003808}
3809
Douglas Gregord507d772010-10-20 03:06:34 +00003810/// \brief Perform name lookup for a possible result for typo correction.
3811static void LookupPotentialTypoResult(Sema &SemaRef,
3812 LookupResult &Res,
3813 IdentifierInfo *Name,
3814 Scope *S, CXXScopeSpec *SS,
3815 DeclContext *MemberContext,
3816 bool EnteringContext,
Richard Smithe156254d2013-08-20 20:35:18 +00003817 bool isObjCIvarLookup,
3818 bool FindHidden) {
Douglas Gregord507d772010-10-20 03:06:34 +00003819 Res.suppressDiagnostics();
3820 Res.clear();
3821 Res.setLookupName(Name);
Richard Smithe156254d2013-08-20 20:35:18 +00003822 Res.setAllowHidden(FindHidden);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003823 if (MemberContext) {
Douglas Gregord507d772010-10-20 03:06:34 +00003824 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(MemberContext)) {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003825 if (isObjCIvarLookup) {
Douglas Gregord507d772010-10-20 03:06:34 +00003826 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(Name)) {
3827 Res.addDecl(Ivar);
3828 Res.resolveKind();
3829 return;
3830 }
3831 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003832
Douglas Gregord507d772010-10-20 03:06:34 +00003833 if (ObjCPropertyDecl *Prop = Class->FindPropertyDeclaration(Name)) {
3834 Res.addDecl(Prop);
3835 Res.resolveKind();
3836 return;
3837 }
3838 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003839
Douglas Gregord507d772010-10-20 03:06:34 +00003840 SemaRef.LookupQualifiedName(Res, MemberContext);
3841 return;
3842 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003843
3844 SemaRef.LookupParsedName(Res, S, SS, /*AllowBuiltinCreation=*/false,
Douglas Gregord507d772010-10-20 03:06:34 +00003845 EnteringContext);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003846
Douglas Gregord507d772010-10-20 03:06:34 +00003847 // Fake ivar lookup; this should really be part of
3848 // LookupParsedName.
3849 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) {
3850 if (Method->isInstanceMethod() && Method->getClassInterface() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003851 (Res.empty() ||
Douglas Gregord507d772010-10-20 03:06:34 +00003852 (Res.isSingleResult() &&
3853 Res.getFoundDecl()->isDefinedOutsideFunctionOrMethod()))) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003854 if (ObjCIvarDecl *IV
Douglas Gregord507d772010-10-20 03:06:34 +00003855 = Method->getClassInterface()->lookupInstanceVariable(Name)) {
3856 Res.addDecl(IV);
3857 Res.resolveKind();
3858 }
3859 }
3860 }
3861}
3862
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003863/// \brief Add keywords to the consumer as possible typo corrections.
3864static void AddKeywordsToConsumer(Sema &SemaRef,
3865 TypoCorrectionConsumer &Consumer,
Richard Smithb3a1df02012-06-08 21:35:42 +00003866 Scope *S, CorrectionCandidateCallback &CCC,
3867 bool AfterNestedNameSpecifier) {
3868 if (AfterNestedNameSpecifier) {
3869 // For 'X::', we know exactly which keywords can appear next.
3870 Consumer.addKeywordResult("template");
3871 if (CCC.WantExpressionKeywords)
3872 Consumer.addKeywordResult("operator");
3873 return;
3874 }
3875
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003876 if (CCC.WantObjCSuper)
3877 Consumer.addKeywordResult("super");
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003878
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003879 if (CCC.WantTypeSpecifiers) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003880 // Add type-specifier keywords to the set of results.
Craig Topperd6d31ac2013-07-15 08:24:27 +00003881 static const char *const CTypeSpecs[] = {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003882 "char", "const", "double", "enum", "float", "int", "long", "short",
Douglas Gregor3b22a882011-07-01 21:27:45 +00003883 "signed", "struct", "union", "unsigned", "void", "volatile",
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003884 "_Complex", "_Imaginary",
3885 // storage-specifiers as well
3886 "extern", "inline", "static", "typedef"
3887 };
3888
Craig Toppere5ce8312013-07-15 03:38:40 +00003889 const unsigned NumCTypeSpecs = llvm::array_lengthof(CTypeSpecs);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003890 for (unsigned I = 0; I != NumCTypeSpecs; ++I)
3891 Consumer.addKeywordResult(CTypeSpecs[I]);
3892
David Blaikiebbafb8a2012-03-11 07:00:24 +00003893 if (SemaRef.getLangOpts().C99)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003894 Consumer.addKeywordResult("restrict");
David Blaikiebbafb8a2012-03-11 07:00:24 +00003895 if (SemaRef.getLangOpts().Bool || SemaRef.getLangOpts().CPlusPlus)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003896 Consumer.addKeywordResult("bool");
David Blaikiebbafb8a2012-03-11 07:00:24 +00003897 else if (SemaRef.getLangOpts().C99)
Douglas Gregor3b22a882011-07-01 21:27:45 +00003898 Consumer.addKeywordResult("_Bool");
3899
David Blaikiebbafb8a2012-03-11 07:00:24 +00003900 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003901 Consumer.addKeywordResult("class");
3902 Consumer.addKeywordResult("typename");
3903 Consumer.addKeywordResult("wchar_t");
3904
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003905 if (SemaRef.getLangOpts().CPlusPlus11) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003906 Consumer.addKeywordResult("char16_t");
3907 Consumer.addKeywordResult("char32_t");
3908 Consumer.addKeywordResult("constexpr");
3909 Consumer.addKeywordResult("decltype");
3910 Consumer.addKeywordResult("thread_local");
3911 }
3912 }
3913
David Blaikiebbafb8a2012-03-11 07:00:24 +00003914 if (SemaRef.getLangOpts().GNUMode)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003915 Consumer.addKeywordResult("typeof");
Kaelyn Takatab04846b2014-07-28 18:14:02 +00003916 } else if (CCC.WantFunctionLikeCasts) {
3917 static const char *const CastableTypeSpecs[] = {
3918 "char", "double", "float", "int", "long", "short",
3919 "signed", "unsigned", "void"
3920 };
3921 for (auto *kw : CastableTypeSpecs)
3922 Consumer.addKeywordResult(kw);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003923 }
3924
David Blaikiebbafb8a2012-03-11 07:00:24 +00003925 if (CCC.WantCXXNamedCasts && SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003926 Consumer.addKeywordResult("const_cast");
3927 Consumer.addKeywordResult("dynamic_cast");
3928 Consumer.addKeywordResult("reinterpret_cast");
3929 Consumer.addKeywordResult("static_cast");
3930 }
3931
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003932 if (CCC.WantExpressionKeywords) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003933 Consumer.addKeywordResult("sizeof");
David Blaikiebbafb8a2012-03-11 07:00:24 +00003934 if (SemaRef.getLangOpts().Bool || SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003935 Consumer.addKeywordResult("false");
3936 Consumer.addKeywordResult("true");
3937 }
3938
David Blaikiebbafb8a2012-03-11 07:00:24 +00003939 if (SemaRef.getLangOpts().CPlusPlus) {
Craig Topperd6d31ac2013-07-15 08:24:27 +00003940 static const char *const CXXExprs[] = {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003941 "delete", "new", "operator", "throw", "typeid"
3942 };
Craig Toppere5ce8312013-07-15 03:38:40 +00003943 const unsigned NumCXXExprs = llvm::array_lengthof(CXXExprs);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003944 for (unsigned I = 0; I != NumCXXExprs; ++I)
3945 Consumer.addKeywordResult(CXXExprs[I]);
3946
3947 if (isa<CXXMethodDecl>(SemaRef.CurContext) &&
3948 cast<CXXMethodDecl>(SemaRef.CurContext)->isInstance())
3949 Consumer.addKeywordResult("this");
3950
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003951 if (SemaRef.getLangOpts().CPlusPlus11) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003952 Consumer.addKeywordResult("alignof");
3953 Consumer.addKeywordResult("nullptr");
3954 }
3955 }
Jordan Rose58d54722012-06-30 21:33:57 +00003956
3957 if (SemaRef.getLangOpts().C11) {
3958 // FIXME: We should not suggest _Alignof if the alignof macro
3959 // is present.
3960 Consumer.addKeywordResult("_Alignof");
3961 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003962 }
3963
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003964 if (CCC.WantRemainingKeywords) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003965 if (SemaRef.getCurFunctionOrMethodDecl() || SemaRef.getCurBlock()) {
3966 // Statements.
Craig Topperd6d31ac2013-07-15 08:24:27 +00003967 static const char *const CStmts[] = {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003968 "do", "else", "for", "goto", "if", "return", "switch", "while" };
Craig Toppere5ce8312013-07-15 03:38:40 +00003969 const unsigned NumCStmts = llvm::array_lengthof(CStmts);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003970 for (unsigned I = 0; I != NumCStmts; ++I)
3971 Consumer.addKeywordResult(CStmts[I]);
3972
David Blaikiebbafb8a2012-03-11 07:00:24 +00003973 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003974 Consumer.addKeywordResult("catch");
3975 Consumer.addKeywordResult("try");
3976 }
3977
3978 if (S && S->getBreakParent())
3979 Consumer.addKeywordResult("break");
3980
3981 if (S && S->getContinueParent())
3982 Consumer.addKeywordResult("continue");
3983
3984 if (!SemaRef.getCurFunction()->SwitchStack.empty()) {
3985 Consumer.addKeywordResult("case");
3986 Consumer.addKeywordResult("default");
3987 }
3988 } else {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003989 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003990 Consumer.addKeywordResult("namespace");
3991 Consumer.addKeywordResult("template");
3992 }
3993
3994 if (S && S->isClassScope()) {
3995 Consumer.addKeywordResult("explicit");
3996 Consumer.addKeywordResult("friend");
3997 Consumer.addKeywordResult("mutable");
3998 Consumer.addKeywordResult("private");
3999 Consumer.addKeywordResult("protected");
4000 Consumer.addKeywordResult("public");
4001 Consumer.addKeywordResult("virtual");
4002 }
4003 }
4004
David Blaikiebbafb8a2012-03-11 07:00:24 +00004005 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004006 Consumer.addKeywordResult("using");
4007
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004008 if (SemaRef.getLangOpts().CPlusPlus11)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004009 Consumer.addKeywordResult("static_assert");
4010 }
4011 }
4012}
4013
Kaelyn Takata6c759512014-10-27 18:07:37 +00004014std::unique_ptr<TypoCorrectionConsumer> Sema::makeTypoCorrectionConsumer(
4015 const DeclarationNameInfo &TypoName, Sema::LookupNameKind LookupKind,
4016 Scope *S, CXXScopeSpec *SS,
4017 std::unique_ptr<CorrectionCandidateCallback> CCC,
4018 DeclContext *MemberContext, bool EnteringContext,
Nick Lewycky24653262014-12-16 21:39:02 +00004019 const ObjCObjectPointerType *OPT, bool ErrorRecovery) {
Kaelyn Takata6c759512014-10-27 18:07:37 +00004020
4021 if (Diags.hasFatalErrorOccurred() || !getLangOpts().SpellChecking ||
4022 DisableTypoCorrection)
4023 return nullptr;
4024
4025 // In Microsoft mode, don't perform typo correction in a template member
4026 // function dependent context because it interferes with the "lookup into
4027 // dependent bases of class templates" feature.
4028 if (getLangOpts().MSVCCompat && CurContext->isDependentContext() &&
4029 isa<CXXMethodDecl>(CurContext))
4030 return nullptr;
4031
4032 // We only attempt to correct typos for identifiers.
4033 IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo();
4034 if (!Typo)
4035 return nullptr;
4036
4037 // If the scope specifier itself was invalid, don't try to correct
4038 // typos.
4039 if (SS && SS->isInvalid())
4040 return nullptr;
4041
4042 // Never try to correct typos during template deduction or
4043 // instantiation.
4044 if (!ActiveTemplateInstantiations.empty())
4045 return nullptr;
4046
4047 // Don't try to correct 'super'.
4048 if (S && S->isInObjcMethodScope() && Typo == getSuperIdentifier())
4049 return nullptr;
4050
4051 // Abort if typo correction already failed for this specific typo.
4052 IdentifierSourceLocations::iterator locs = TypoCorrectionFailures.find(Typo);
4053 if (locs != TypoCorrectionFailures.end() &&
4054 locs->second.count(TypoName.getLoc()))
4055 return nullptr;
4056
4057 // Don't try to correct the identifier "vector" when in AltiVec mode.
4058 // TODO: Figure out why typo correction misbehaves in this case, fix it, and
4059 // remove this workaround.
4060 if (getLangOpts().AltiVec && Typo->isStr("vector"))
4061 return nullptr;
4062
Nick Lewycky24653262014-12-16 21:39:02 +00004063 // Provide a stop gap for files that are just seriously broken. Trying
4064 // to correct all typos can turn into a HUGE performance penalty, causing
4065 // some files to take minutes to get rejected by the parser.
4066 unsigned Limit = getDiagnostics().getDiagnosticOptions().SpellCheckingLimit;
4067 if (Limit && TyposCorrected >= Limit)
4068 return nullptr;
4069 ++TyposCorrected;
4070
Kaelyn Takata6c759512014-10-27 18:07:37 +00004071 // If we're handling a missing symbol error, using modules, and the
4072 // special search all modules option is used, look for a missing import.
4073 if (ErrorRecovery && getLangOpts().Modules &&
4074 getLangOpts().ModulesSearchAll) {
4075 // The following has the side effect of loading the missing module.
4076 getModuleLoader().lookupMissingImports(Typo->getName(),
4077 TypoName.getLocStart());
4078 }
4079
4080 CorrectionCandidateCallback &CCCRef = *CCC;
4081 auto Consumer = llvm::make_unique<TypoCorrectionConsumer>(
4082 *this, TypoName, LookupKind, S, SS, std::move(CCC), MemberContext,
4083 EnteringContext);
4084
Kaelyn Takata6c759512014-10-27 18:07:37 +00004085 // Perform name lookup to find visible, similarly-named entities.
Nick Lewycky24653262014-12-16 21:39:02 +00004086 bool IsUnqualifiedLookup = false;
Kaelyn Takata6c759512014-10-27 18:07:37 +00004087 DeclContext *QualifiedDC = MemberContext;
4088 if (MemberContext) {
4089 LookupVisibleDecls(MemberContext, LookupKind, *Consumer);
4090
4091 // Look in qualified interfaces.
4092 if (OPT) {
4093 for (auto *I : OPT->quals())
4094 LookupVisibleDecls(I, LookupKind, *Consumer);
4095 }
4096 } else if (SS && SS->isSet()) {
4097 QualifiedDC = computeDeclContext(*SS, EnteringContext);
4098 if (!QualifiedDC)
4099 return nullptr;
4100
Kaelyn Takata6c759512014-10-27 18:07:37 +00004101 LookupVisibleDecls(QualifiedDC, LookupKind, *Consumer);
4102 } else {
4103 IsUnqualifiedLookup = true;
Kaelyn Takata6c759512014-10-27 18:07:37 +00004104 }
4105
4106 // Determine whether we are going to search in the various namespaces for
4107 // corrections.
4108 bool SearchNamespaces
4109 = getLangOpts().CPlusPlus &&
4110 (IsUnqualifiedLookup || (SS && SS->isSet()));
4111
4112 if (IsUnqualifiedLookup || SearchNamespaces) {
4113 // For unqualified lookup, look through all of the names that we have
4114 // seen in this translation unit.
4115 // FIXME: Re-add the ability to skip very unlikely potential corrections.
4116 for (const auto &I : Context.Idents)
4117 Consumer->FoundName(I.getKey());
4118
4119 // Walk through identifiers in external identifier sources.
4120 // FIXME: Re-add the ability to skip very unlikely potential corrections.
4121 if (IdentifierInfoLookup *External
4122 = Context.Idents.getExternalIdentifierLookup()) {
4123 std::unique_ptr<IdentifierIterator> Iter(External->getIdentifiers());
4124 do {
4125 StringRef Name = Iter->Next();
4126 if (Name.empty())
4127 break;
4128
4129 Consumer->FoundName(Name);
4130 } while (true);
4131 }
4132 }
4133
4134 AddKeywordsToConsumer(*this, *Consumer, S, CCCRef, SS && SS->isNotEmpty());
4135
4136 // Build the NestedNameSpecifiers for the KnownNamespaces, if we're going
4137 // to search those namespaces.
4138 if (SearchNamespaces) {
4139 // Load any externally-known namespaces.
4140 if (ExternalSource && !LoadedExternalKnownNamespaces) {
4141 SmallVector<NamespaceDecl *, 4> ExternalKnownNamespaces;
4142 LoadedExternalKnownNamespaces = true;
4143 ExternalSource->ReadKnownNamespaces(ExternalKnownNamespaces);
4144 for (auto *N : ExternalKnownNamespaces)
4145 KnownNamespaces[N] = true;
4146 }
4147
4148 Consumer->addNamespaces(KnownNamespaces);
4149 }
4150
4151 return Consumer;
4152}
4153
Douglas Gregor2d435302009-12-30 17:04:44 +00004154/// \brief Try to "correct" a typo in the source code by finding
4155/// visible declarations whose names are similar to the name that was
4156/// present in the source code.
4157///
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004158/// \param TypoName the \c DeclarationNameInfo structure that contains
4159/// the name that was present in the source code along with its location.
4160///
4161/// \param LookupKind the name-lookup criteria used to search for the name.
Douglas Gregor2d435302009-12-30 17:04:44 +00004162///
4163/// \param S the scope in which name lookup occurs.
4164///
4165/// \param SS the nested-name-specifier that precedes the name we're
4166/// looking for, if present.
4167///
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00004168/// \param CCC A CorrectionCandidateCallback object that provides further
4169/// validation of typo correction candidates. It also provides flags for
4170/// determining the set of keywords permitted.
4171///
Douglas Gregoraf2bd472009-12-31 07:42:17 +00004172/// \param MemberContext if non-NULL, the context in which to look for
4173/// a member access expression.
4174///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004175/// \param EnteringContext whether we're entering the context described by
Douglas Gregor598b08f2009-12-31 05:20:13 +00004176/// the nested-name-specifier SS.
4177///
Douglas Gregor35b0bac2010-01-03 18:01:57 +00004178/// \param OPT when non-NULL, the search for visible declarations will
4179/// also walk the protocols in the qualified interfaces of \p OPT.
4180///
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004181/// \returns a \c TypoCorrection containing the corrected name if the typo
4182/// along with information such as the \c NamedDecl where the corrected name
4183/// was declared, and any additional \c NestedNameSpecifier needed to access
4184/// it (C++ only). The \c TypoCorrection is empty if there is no correction.
4185TypoCorrection Sema::CorrectTypo(const DeclarationNameInfo &TypoName,
4186 Sema::LookupNameKind LookupKind,
4187 Scope *S, CXXScopeSpec *SS,
Kaelyn Takata89c881b2014-10-27 18:07:29 +00004188 std::unique_ptr<CorrectionCandidateCallback> CCC,
John Thompson2255f2c2014-04-23 12:57:01 +00004189 CorrectTypoKind Mode,
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004190 DeclContext *MemberContext,
4191 bool EnteringContext,
Kaelyn Uhrain0e238442013-09-27 19:40:08 +00004192 const ObjCObjectPointerType *OPT,
4193 bool RecordFailure) {
Kaelyn Takata89c881b2014-10-27 18:07:29 +00004194 assert(CCC && "CorrectTypo requires a CorrectionCandidateCallback");
4195
Kaelyn Uhrainf0aabda2013-08-12 19:54:38 +00004196 // Always let the ExternalSource have the first chance at correction, even
4197 // if we would otherwise have given up.
4198 if (ExternalSource) {
4199 if (TypoCorrection Correction = ExternalSource->CorrectTypo(
Kaelyn Takata89c881b2014-10-27 18:07:29 +00004200 TypoName, LookupKind, S, SS, *CCC, MemberContext, EnteringContext, OPT))
Kaelyn Uhrainf0aabda2013-08-12 19:54:38 +00004201 return Correction;
4202 }
4203
Kaelyn Takata6c759512014-10-27 18:07:37 +00004204 // Ugly hack equivalent to CTC == CTC_ObjCMessageReceiver;
4205 // WantObjCSuper is only true for CTC_ObjCMessageReceiver and for
4206 // some instances of CTC_Unknown, while WantRemainingKeywords is true
4207 // for CTC_Unknown but not for CTC_ObjCMessageReceiver.
4208 bool ObjCMessageReceiver = CCC->WantObjCSuper && !CCC->WantRemainingKeywords;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004209
Kaelyn Takata6c759512014-10-27 18:07:37 +00004210 IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo();
Kaelyn Takata6c759512014-10-27 18:07:37 +00004211 auto Consumer = makeTypoCorrectionConsumer(
4212 TypoName, LookupKind, S, SS, std::move(CCC), MemberContext,
Nick Lewycky24653262014-12-16 21:39:02 +00004213 EnteringContext, OPT, Mode == CTK_ErrorRecovery);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00004214
Kaelyn Takata6c759512014-10-27 18:07:37 +00004215 if (!Consumer)
4216 return TypoCorrection();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004217
Douglas Gregor280e1ee2010-04-14 20:04:41 +00004218 // If we haven't found anything, we're done.
Kaelyn Takata6c759512014-10-27 18:07:37 +00004219 if (Consumer->empty())
Nick Lewycky24653262014-12-16 21:39:02 +00004220 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
Douglas Gregor2d435302009-12-30 17:04:44 +00004221
Kaelyn Uhrain493ea632012-06-06 20:54:51 +00004222 // Make sure the best edit distance (prior to adding any namespace qualifiers)
4223 // is not more that about a third of the length of the typo's identifier.
Kaelyn Takata6c759512014-10-27 18:07:37 +00004224 unsigned ED = Consumer->getBestEditDistance(true);
4225 unsigned TypoLen = Typo->getName().size();
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00004226 if (ED > 0 && TypoLen / ED < 3)
Nick Lewycky24653262014-12-16 21:39:02 +00004227 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004228
Kaelyn Takata6c759512014-10-27 18:07:37 +00004229 TypoCorrection BestTC = Consumer->getNextCorrection();
4230 TypoCorrection SecondBestTC = Consumer->getNextCorrection();
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004231 if (!BestTC)
Kaelyn Uhrain0e238442013-09-27 19:40:08 +00004232 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004233
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004234 ED = BestTC.getEditDistance();
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004235
Kaelyn Takata6c759512014-10-27 18:07:37 +00004236 if (TypoLen >= 3 && ED > 0 && TypoLen / ED < 3) {
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00004237 // If this was an unqualified lookup and we believe the callback
4238 // object wouldn't have filtered out possible corrections, note
4239 // that no correction was found.
Nick Lewycky24653262014-12-16 21:39:02 +00004240 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004241 }
4242
Douglas Gregor0afa7f62010-10-14 20:34:08 +00004243 // If only a single name remains, return that result.
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004244 if (!SecondBestTC ||
4245 SecondBestTC.getEditDistance(false) > BestTC.getEditDistance(false)) {
4246 const TypoCorrection &Result = BestTC;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004247
Douglas Gregor2a1d72d2010-10-26 17:18:00 +00004248 // Don't correct to a keyword that's the same as the typo; the keyword
4249 // wasn't actually in scope.
Kaelyn Uhrain0e238442013-09-27 19:40:08 +00004250 if (ED == 0 && Result.isKeyword())
4251 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004252
David Blaikie04ea41c2012-10-12 20:00:44 +00004253 TypoCorrection TC = Result;
4254 TC.setCorrectionRange(SS, TypoName);
Kaelyn Takataa95ebc62014-06-17 23:47:29 +00004255 checkCorrectionVisibility(*this, TC);
David Blaikie04ea41c2012-10-12 20:00:44 +00004256 return TC;
Kaelyn Takata6c759512014-10-27 18:07:37 +00004257 } else if (SecondBestTC && ObjCMessageReceiver) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004258 // Prefer 'super' when we're completing in a message-receiver
4259 // context.
4260
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004261 if (BestTC.getCorrection().getAsString() != "super") {
4262 if (SecondBestTC.getCorrection().getAsString() == "super")
4263 BestTC = SecondBestTC;
Kaelyn Takata6c759512014-10-27 18:07:37 +00004264 else if ((*Consumer)["super"].front().isKeyword())
4265 BestTC = (*Consumer)["super"].front();
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004266 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004267 // Don't correct to a keyword that's the same as the typo; the keyword
4268 // wasn't actually in scope.
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004269 if (BestTC.getEditDistance() == 0 ||
4270 BestTC.getCorrection().getAsString() != "super")
Kaelyn Uhrain0e238442013-09-27 19:40:08 +00004271 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004272
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004273 BestTC.setCorrectionRange(SS, TypoName);
4274 return BestTC;
Douglas Gregoraf9eb592010-10-15 13:35:25 +00004275 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004276
Kaelyn Takata73429fd2014-06-10 21:03:49 +00004277 // Record the failure's location if needed and return an empty correction. If
4278 // this was an unqualified lookup and we believe the callback object did not
4279 // filter out possible corrections, also cache the failure for the typo.
Kaelyn Takataae9e97c2015-01-16 22:11:04 +00004280 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure && !SecondBestTC);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004281}
4282
Kaelyn Takata6c759512014-10-27 18:07:37 +00004283/// \brief Try to "correct" a typo in the source code by finding
4284/// visible declarations whose names are similar to the name that was
4285/// present in the source code.
4286///
4287/// \param TypoName the \c DeclarationNameInfo structure that contains
4288/// the name that was present in the source code along with its location.
4289///
4290/// \param LookupKind the name-lookup criteria used to search for the name.
4291///
4292/// \param S the scope in which name lookup occurs.
4293///
4294/// \param SS the nested-name-specifier that precedes the name we're
4295/// looking for, if present.
4296///
4297/// \param CCC A CorrectionCandidateCallback object that provides further
4298/// validation of typo correction candidates. It also provides flags for
4299/// determining the set of keywords permitted.
4300///
4301/// \param TDG A TypoDiagnosticGenerator functor that will be used to print
4302/// diagnostics when the actual typo correction is attempted.
4303///
Kaelyn Takata8363f042014-10-27 18:07:42 +00004304/// \param TRC A TypoRecoveryCallback functor that will be used to build an
4305/// Expr from a typo correction candidate.
4306///
Kaelyn Takata6c759512014-10-27 18:07:37 +00004307/// \param MemberContext if non-NULL, the context in which to look for
4308/// a member access expression.
4309///
4310/// \param EnteringContext whether we're entering the context described by
4311/// the nested-name-specifier SS.
4312///
4313/// \param OPT when non-NULL, the search for visible declarations will
4314/// also walk the protocols in the qualified interfaces of \p OPT.
4315///
4316/// \returns a new \c TypoExpr that will later be replaced in the AST with an
4317/// Expr representing the result of performing typo correction, or nullptr if
4318/// typo correction is not possible. If nullptr is returned, no diagnostics will
4319/// be emitted and it is the responsibility of the caller to emit any that are
4320/// needed.
4321TypoExpr *Sema::CorrectTypoDelayed(
4322 const DeclarationNameInfo &TypoName, Sema::LookupNameKind LookupKind,
4323 Scope *S, CXXScopeSpec *SS,
4324 std::unique_ptr<CorrectionCandidateCallback> CCC,
Kaelyn Takata8363f042014-10-27 18:07:42 +00004325 TypoDiagnosticGenerator TDG, TypoRecoveryCallback TRC, CorrectTypoKind Mode,
Kaelyn Takata6c759512014-10-27 18:07:37 +00004326 DeclContext *MemberContext, bool EnteringContext,
4327 const ObjCObjectPointerType *OPT) {
4328 assert(CCC && "CorrectTypoDelayed requires a CorrectionCandidateCallback");
4329
4330 TypoCorrection Empty;
Kaelyn Takata6c759512014-10-27 18:07:37 +00004331 auto Consumer = makeTypoCorrectionConsumer(
4332 TypoName, LookupKind, S, SS, std::move(CCC), MemberContext,
Kaelyn Takataae9e97c2015-01-16 22:11:04 +00004333 EnteringContext, OPT, Mode == CTK_ErrorRecovery);
Kaelyn Takata6c759512014-10-27 18:07:37 +00004334
4335 if (!Consumer || Consumer->empty())
4336 return nullptr;
4337
4338 // Make sure the best edit distance (prior to adding any namespace qualifiers)
4339 // is not more that about a third of the length of the typo's identifier.
4340 unsigned ED = Consumer->getBestEditDistance(true);
4341 IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo();
4342 if (ED > 0 && Typo->getName().size() / ED < 3)
4343 return nullptr;
4344
4345 ExprEvalContexts.back().NumTypos++;
Kaelyn Takata8363f042014-10-27 18:07:42 +00004346 return createDelayedTypo(std::move(Consumer), std::move(TDG), std::move(TRC));
Kaelyn Takata6c759512014-10-27 18:07:37 +00004347}
4348
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00004349void TypoCorrection::addCorrectionDecl(NamedDecl *CDecl) {
4350 if (!CDecl) return;
4351
4352 if (isKeyword())
4353 CorrectionDecls.clear();
4354
Kaelyn Uhrainf60b55a2012-11-19 18:49:53 +00004355 CorrectionDecls.push_back(CDecl->getUnderlyingDecl());
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00004356
4357 if (!CorrectionName)
4358 CorrectionName = CDecl->getDeclName();
4359}
4360
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004361std::string TypoCorrection::getAsString(const LangOptions &LO) const {
4362 if (CorrectionNameSpec) {
4363 std::string tmpBuffer;
4364 llvm::raw_string_ostream PrefixOStream(tmpBuffer);
4365 CorrectionNameSpec->print(PrefixOStream, PrintingPolicy(LO));
David Blaikied4da8722013-05-14 21:04:00 +00004366 PrefixOStream << CorrectionName;
Benjamin Kramer73faad62012-04-14 08:26:28 +00004367 return PrefixOStream.str();
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004368 }
4369
4370 return CorrectionName.getAsString();
Douglas Gregor2d435302009-12-30 17:04:44 +00004371}
Kaelyn Uhrain989b7ca2013-04-03 16:59:49 +00004372
Nico Weberb58e51c2014-11-19 05:21:39 +00004373bool CorrectionCandidateCallback::ValidateCandidate(
4374 const TypoCorrection &candidate) {
Kaelyn Uhrain989b7ca2013-04-03 16:59:49 +00004375 if (!candidate.isResolved())
4376 return true;
4377
4378 if (candidate.isKeyword())
4379 return WantTypeSpecifiers || WantExpressionKeywords || WantCXXNamedCasts ||
4380 WantRemainingKeywords || WantObjCSuper;
4381
Nick Lewycky9ea8efa2014-06-23 22:57:51 +00004382 bool HasNonType = false;
4383 bool HasStaticMethod = false;
4384 bool HasNonStaticMethod = false;
4385 for (Decl *D : candidate) {
4386 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(D))
4387 D = FTD->getTemplatedDecl();
4388 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
4389 if (Method->isStatic())
4390 HasStaticMethod = true;
4391 else
4392 HasNonStaticMethod = true;
4393 }
4394 if (!isa<TypeDecl>(D))
4395 HasNonType = true;
Kaelyn Uhrain989b7ca2013-04-03 16:59:49 +00004396 }
4397
Nick Lewycky9ea8efa2014-06-23 22:57:51 +00004398 if (IsAddressOfOperand && HasNonStaticMethod && !HasStaticMethod &&
4399 !candidate.getCorrectionSpecifier())
4400 return false;
4401
4402 return WantTypeSpecifiers || HasNonType;
Kaelyn Uhrain989b7ca2013-04-03 16:59:49 +00004403}
Kaelyn Uhrain53e72192013-07-08 23:13:39 +00004404
4405FunctionCallFilterCCC::FunctionCallFilterCCC(Sema &SemaRef, unsigned NumArgs,
Kaelyn Uhrainb4b14752014-02-28 18:12:42 +00004406 bool HasExplicitTemplateArgs,
Kaelyn Takatafb271f02014-04-04 22:16:30 +00004407 MemberExpr *ME)
Kaelyn Uhrainb4b14752014-02-28 18:12:42 +00004408 : NumArgs(NumArgs), HasExplicitTemplateArgs(HasExplicitTemplateArgs),
Kaelyn Takatafb271f02014-04-04 22:16:30 +00004409 CurContext(SemaRef.CurContext), MemberFn(ME) {
Kaelyn Takatab04846b2014-07-28 18:14:02 +00004410 WantTypeSpecifiers = false;
4411 WantFunctionLikeCasts = SemaRef.getLangOpts().CPlusPlus && NumArgs == 1;
Kaelyn Uhrain53e72192013-07-08 23:13:39 +00004412 WantRemainingKeywords = false;
4413}
4414
4415bool FunctionCallFilterCCC::ValidateCandidate(const TypoCorrection &candidate) {
4416 if (!candidate.getCorrectionDecl())
4417 return candidate.isKeyword();
4418
Aaron Ballman1e606f42014-07-15 22:03:49 +00004419 for (auto *C : candidate) {
Craig Topperc3ec1492014-05-26 06:22:03 +00004420 FunctionDecl *FD = nullptr;
Aaron Ballman1e606f42014-07-15 22:03:49 +00004421 NamedDecl *ND = C->getUnderlyingDecl();
Kaelyn Uhrain53e72192013-07-08 23:13:39 +00004422 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
4423 FD = FTD->getTemplatedDecl();
4424 if (!HasExplicitTemplateArgs && !FD) {
4425 if (!(FD = dyn_cast<FunctionDecl>(ND)) && isa<ValueDecl>(ND)) {
4426 // If the Decl is neither a function nor a template function,
4427 // determine if it is a pointer or reference to a function. If so,
4428 // check against the number of arguments expected for the pointee.
4429 QualType ValType = cast<ValueDecl>(ND)->getType();
4430 if (ValType->isAnyPointerType() || ValType->isReferenceType())
4431 ValType = ValType->getPointeeType();
4432 if (const FunctionProtoType *FPT = ValType->getAs<FunctionProtoType>())
Alp Toker9cacbab2014-01-20 20:26:09 +00004433 if (FPT->getNumParams() == NumArgs)
Kaelyn Uhrain53e72192013-07-08 23:13:39 +00004434 return true;
4435 }
4436 }
Kaelyn Uhrainb4b14752014-02-28 18:12:42 +00004437
4438 // Skip the current candidate if it is not a FunctionDecl or does not accept
4439 // the current number of arguments.
4440 if (!FD || !(FD->getNumParams() >= NumArgs &&
4441 FD->getMinRequiredArguments() <= NumArgs))
4442 continue;
4443
Kaelyn Takatafb271f02014-04-04 22:16:30 +00004444 // If the current candidate is a non-static C++ method, skip the candidate
4445 // unless the method being corrected--or the current DeclContext, if the
4446 // function being corrected is not a method--is a method in the same class
4447 // or a descendent class of the candidate's parent class.
Kaelyn Uhrainb4b14752014-02-28 18:12:42 +00004448 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
Kaelyn Takatafb271f02014-04-04 22:16:30 +00004449 if (MemberFn || !MD->isStatic()) {
4450 CXXMethodDecl *CurMD =
4451 MemberFn
4452 ? dyn_cast_or_null<CXXMethodDecl>(MemberFn->getMemberDecl())
4453 : dyn_cast_or_null<CXXMethodDecl>(CurContext);
Kaelyn Uhrainb4b14752014-02-28 18:12:42 +00004454 CXXRecordDecl *CurRD =
Craig Topperc3ec1492014-05-26 06:22:03 +00004455 CurMD ? CurMD->getParent()->getCanonicalDecl() : nullptr;
Kaelyn Uhrainb4b14752014-02-28 18:12:42 +00004456 CXXRecordDecl *RD = MD->getParent()->getCanonicalDecl();
4457 if (!CurRD || (CurRD != RD && !CurRD->isDerivedFrom(RD)))
4458 continue;
4459 }
4460 }
4461 return true;
Kaelyn Uhrain53e72192013-07-08 23:13:39 +00004462 }
4463 return false;
4464}
Richard Smithf9b15102013-08-17 00:46:16 +00004465
4466void Sema::diagnoseTypo(const TypoCorrection &Correction,
4467 const PartialDiagnostic &TypoDiag,
4468 bool ErrorRecovery) {
4469 diagnoseTypo(Correction, TypoDiag, PDiag(diag::note_previous_decl),
4470 ErrorRecovery);
4471}
4472
Richard Smithe156254d2013-08-20 20:35:18 +00004473/// Find which declaration we should import to provide the definition of
4474/// the given declaration.
4475static const NamedDecl *getDefinitionToImport(const NamedDecl *D) {
4476 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
4477 return VD->getDefinition();
4478 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
Craig Topperc3ec1492014-05-26 06:22:03 +00004479 return FD->isDefined(FD) ? FD : nullptr;
Richard Smithe156254d2013-08-20 20:35:18 +00004480 if (const TagDecl *TD = dyn_cast<TagDecl>(D))
4481 return TD->getDefinition();
4482 if (const ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(D))
4483 return ID->getDefinition();
4484 if (const ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D))
4485 return PD->getDefinition();
4486 if (const TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
4487 return getDefinitionToImport(TD->getTemplatedDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00004488 return nullptr;
Richard Smithe156254d2013-08-20 20:35:18 +00004489}
4490
Richard Smithf9b15102013-08-17 00:46:16 +00004491/// \brief Diagnose a successfully-corrected typo. Separated from the correction
4492/// itself to allow external validation of the result, etc.
4493///
4494/// \param Correction The result of performing typo correction.
4495/// \param TypoDiag The diagnostic to produce. This will have the corrected
4496/// string added to it (and usually also a fixit).
4497/// \param PrevNote A note to use when indicating the location of the entity to
4498/// which we are correcting. Will have the correction string added to it.
4499/// \param ErrorRecovery If \c true (the default), the caller is going to
4500/// recover from the typo as if the corrected string had been typed.
4501/// In this case, \c PDiag must be an error, and we will attach a fixit
4502/// to it.
4503void Sema::diagnoseTypo(const TypoCorrection &Correction,
4504 const PartialDiagnostic &TypoDiag,
4505 const PartialDiagnostic &PrevNote,
4506 bool ErrorRecovery) {
4507 std::string CorrectedStr = Correction.getAsString(getLangOpts());
4508 std::string CorrectedQuotedStr = Correction.getQuoted(getLangOpts());
4509 FixItHint FixTypo = FixItHint::CreateReplacement(
4510 Correction.getCorrectionRange(), CorrectedStr);
4511
Richard Smithe156254d2013-08-20 20:35:18 +00004512 // Maybe we're just missing a module import.
4513 if (Correction.requiresImport()) {
4514 NamedDecl *Decl = Correction.getCorrectionDecl();
4515 assert(Decl && "import required but no declaration to import");
4516
4517 // Suggest importing a module providing the definition of this entity, if
4518 // possible.
4519 const NamedDecl *Def = getDefinitionToImport(Decl);
4520 if (!Def)
4521 Def = Decl;
4522 Module *Owner = Def->getOwningModule();
4523 assert(Owner && "definition of hidden declaration is not in a module");
4524
4525 Diag(Correction.getCorrectionRange().getBegin(),
4526 diag::err_module_private_declaration)
4527 << Def << Owner->getFullModuleName();
4528 Diag(Def->getLocation(), diag::note_previous_declaration);
4529
4530 // Recover by implicitly importing this module.
Richard Smith3d23c422014-05-07 02:25:43 +00004531 if (ErrorRecovery)
4532 createImplicitModuleImportForErrorRecovery(
4533 Correction.getCorrectionRange().getBegin(), Owner);
Richard Smithe156254d2013-08-20 20:35:18 +00004534 return;
4535 }
4536
Richard Smithf9b15102013-08-17 00:46:16 +00004537 Diag(Correction.getCorrectionRange().getBegin(), TypoDiag)
4538 << CorrectedQuotedStr << (ErrorRecovery ? FixTypo : FixItHint());
4539
4540 NamedDecl *ChosenDecl =
Craig Topperc3ec1492014-05-26 06:22:03 +00004541 Correction.isKeyword() ? nullptr : Correction.getCorrectionDecl();
Richard Smithf9b15102013-08-17 00:46:16 +00004542 if (PrevNote.getDiagID() && ChosenDecl)
4543 Diag(ChosenDecl->getLocation(), PrevNote)
4544 << CorrectedQuotedStr << (ErrorRecovery ? FixItHint() : FixTypo);
4545}
Kaelyn Takata6c759512014-10-27 18:07:37 +00004546
Kaelyn Takata8363f042014-10-27 18:07:42 +00004547TypoExpr *Sema::createDelayedTypo(std::unique_ptr<TypoCorrectionConsumer> TCC,
4548 TypoDiagnosticGenerator TDG,
4549 TypoRecoveryCallback TRC) {
Kaelyn Takata6c759512014-10-27 18:07:37 +00004550 assert(TCC && "createDelayedTypo requires a valid TypoCorrectionConsumer");
4551 auto TE = new (Context) TypoExpr(Context.DependentTy);
4552 auto &State = DelayedTypos[TE];
4553 State.Consumer = std::move(TCC);
4554 State.DiagHandler = std::move(TDG);
Kaelyn Takata8363f042014-10-27 18:07:42 +00004555 State.RecoveryHandler = std::move(TRC);
Kaelyn Takata6c759512014-10-27 18:07:37 +00004556 return TE;
4557}
4558
4559const Sema::TypoExprState &Sema::getTypoExprState(TypoExpr *TE) const {
4560 auto Entry = DelayedTypos.find(TE);
4561 assert(Entry != DelayedTypos.end() &&
4562 "Failed to get the state for a TypoExpr!");
4563 return Entry->second;
4564}
4565
4566void Sema::clearDelayedTypo(TypoExpr *TE) {
4567 DelayedTypos.erase(TE);
4568}