blob: 8495c97e4ea367c811ed88b2c682a2603c63b961 [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"
Chandler Carruth3a022472012-12-04 09:13:33 +000026#include "clang/Sema/DeclSpec.h"
27#include "clang/Sema/ExternalSemaSource.h"
28#include "clang/Sema/Overload.h"
29#include "clang/Sema/Scope.h"
30#include "clang/Sema/ScopeInfo.h"
31#include "clang/Sema/Sema.h"
32#include "clang/Sema/SemaInternal.h"
33#include "clang/Sema/TemplateDeduction.h"
34#include "clang/Sema/TypoCorrection.h"
Douglas Gregor34074322009-01-14 22:20:51 +000035#include "llvm/ADT/STLExtras.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000036#include "llvm/ADT/SetVector.h"
Douglas Gregore254f902009-02-04 00:32:51 +000037#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor0afa7f62010-10-14 20:34:08 +000038#include "llvm/ADT/StringMap.h"
Chris Lattner83cfc7c2011-07-18 01:54:02 +000039#include "llvm/ADT/TinyPtrVector.h"
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +000040#include "llvm/ADT/edit_distance.h"
John McCall6538c932009-10-10 05:48:19 +000041#include "llvm/Support/ErrorHandling.h"
Nick Lewycky13668f22012-04-03 20:26:45 +000042#include <algorithm>
43#include <iterator>
Douglas Gregor0afa7f62010-10-14 20:34:08 +000044#include <limits>
Douglas Gregor2d435302009-12-30 17:04:44 +000045#include <list>
Douglas Gregorc2fa1692011-06-28 16:20:02 +000046#include <map>
Nick Lewycky13668f22012-04-03 20:26:45 +000047#include <set>
48#include <utility>
49#include <vector>
Douglas Gregor34074322009-01-14 22:20:51 +000050
51using namespace clang;
John McCall19c1bfd2010-08-25 05:32:35 +000052using namespace sema;
Douglas Gregor34074322009-01-14 22:20:51 +000053
John McCallf6c8a4e2009-11-10 07:01:13 +000054namespace {
55 class UnqualUsingEntry {
56 const DeclContext *Nominated;
57 const DeclContext *CommonAncestor;
Douglas Gregor889ceb72009-02-03 19:21:40 +000058
John McCallf6c8a4e2009-11-10 07:01:13 +000059 public:
60 UnqualUsingEntry(const DeclContext *Nominated,
61 const DeclContext *CommonAncestor)
62 : Nominated(Nominated), CommonAncestor(CommonAncestor) {
63 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000064
John McCallf6c8a4e2009-11-10 07:01:13 +000065 const DeclContext *getCommonAncestor() const {
66 return CommonAncestor;
67 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000068
John McCallf6c8a4e2009-11-10 07:01:13 +000069 const DeclContext *getNominatedNamespace() const {
70 return Nominated;
71 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000072
John McCallf6c8a4e2009-11-10 07:01:13 +000073 // Sort by the pointer value of the common ancestor.
74 struct Comparator {
75 bool operator()(const UnqualUsingEntry &L, const UnqualUsingEntry &R) {
76 return L.getCommonAncestor() < R.getCommonAncestor();
77 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000078
John McCallf6c8a4e2009-11-10 07:01:13 +000079 bool operator()(const UnqualUsingEntry &E, const DeclContext *DC) {
80 return E.getCommonAncestor() < DC;
81 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000082
John McCallf6c8a4e2009-11-10 07:01:13 +000083 bool operator()(const DeclContext *DC, const UnqualUsingEntry &E) {
84 return DC < E.getCommonAncestor();
85 }
86 };
87 };
Douglas Gregor889ceb72009-02-03 19:21:40 +000088
John McCallf6c8a4e2009-11-10 07:01:13 +000089 /// A collection of using directives, as used by C++ unqualified
90 /// lookup.
91 class UnqualUsingDirectiveSet {
Chris Lattner0e62c1c2011-07-23 10:55:15 +000092 typedef SmallVector<UnqualUsingEntry, 8> ListTy;
Douglas Gregor889ceb72009-02-03 19:21:40 +000093
John McCallf6c8a4e2009-11-10 07:01:13 +000094 ListTy list;
95 llvm::SmallPtrSet<DeclContext*, 8> visited;
Douglas Gregor889ceb72009-02-03 19:21:40 +000096
John McCallf6c8a4e2009-11-10 07:01:13 +000097 public:
98 UnqualUsingDirectiveSet() {}
Douglas Gregor889ceb72009-02-03 19:21:40 +000099
John McCallf6c8a4e2009-11-10 07:01:13 +0000100 void visitScopeChain(Scope *S, Scope *InnermostFileScope) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000101 // C++ [namespace.udir]p1:
John McCallf6c8a4e2009-11-10 07:01:13 +0000102 // During unqualified name lookup, the names appear as if they
103 // were declared in the nearest enclosing namespace which contains
104 // both the using-directive and the nominated namespace.
Ted Kremenekc37877d2013-10-08 17:08:03 +0000105 DeclContext *InnermostFileDC = InnermostFileScope->getEntity();
John McCallf6c8a4e2009-11-10 07:01:13 +0000106 assert(InnermostFileDC && InnermostFileDC->isFileContext());
Douglas Gregor889ceb72009-02-03 19:21:40 +0000107
John McCallf6c8a4e2009-11-10 07:01:13 +0000108 for (; S; S = S->getParent()) {
Nick Lewycky2bd636f2012-03-13 04:12:34 +0000109 // C++ [namespace.udir]p1:
110 // A using-directive shall not appear in class scope, but may
111 // appear in namespace scope or in block scope.
Ted Kremenekc37877d2013-10-08 17:08:03 +0000112 DeclContext *Ctx = S->getEntity();
Nick Lewycky2bd636f2012-03-13 04:12:34 +0000113 if (Ctx && Ctx->isFileContext()) {
114 visit(Ctx, Ctx);
115 } else if (!Ctx || Ctx->isFunctionOrMethod()) {
John McCallf6c8a4e2009-11-10 07:01:13 +0000116 Scope::udir_iterator I = S->using_directives_begin(),
117 End = S->using_directives_end();
John McCallf6c8a4e2009-11-10 07:01:13 +0000118 for (; I != End; ++I)
John McCall48871652010-08-21 09:40:31 +0000119 visit(*I, InnermostFileDC);
John McCallf6c8a4e2009-11-10 07:01:13 +0000120 }
Douglas Gregor889ceb72009-02-03 19:21:40 +0000121 }
122 }
John McCallf6c8a4e2009-11-10 07:01:13 +0000123
124 // Visits a context and collect all of its using directives
125 // recursively. Treats all using directives as if they were
126 // declared in the context.
127 //
128 // A given context is only every visited once, so it is important
129 // that contexts be visited from the inside out in order to get
130 // the effective DCs right.
131 void visit(DeclContext *DC, DeclContext *EffectiveDC) {
132 if (!visited.insert(DC))
133 return;
134
135 addUsingDirectives(DC, EffectiveDC);
136 }
137
138 // Visits a using directive and collects all of its using
139 // directives recursively. Treats all using directives as if they
140 // were declared in the effective DC.
141 void visit(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
142 DeclContext *NS = UD->getNominatedNamespace();
143 if (!visited.insert(NS))
144 return;
145
146 addUsingDirective(UD, EffectiveDC);
147 addUsingDirectives(NS, EffectiveDC);
148 }
149
150 // Adds all the using directives in a context (and those nominated
151 // by its using directives, transitively) as if they appeared in
152 // the given effective context.
153 void addUsingDirectives(DeclContext *DC, DeclContext *EffectiveDC) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000154 SmallVector<DeclContext*,4> queue;
John McCallf6c8a4e2009-11-10 07:01:13 +0000155 while (true) {
Aaron Ballman63ab7602014-03-07 13:44:44 +0000156 for (auto UD : DC->getUsingDirectives()) {
John McCallf6c8a4e2009-11-10 07:01:13 +0000157 DeclContext *NS = UD->getNominatedNamespace();
158 if (visited.insert(NS)) {
159 addUsingDirective(UD, EffectiveDC);
160 queue.push_back(NS);
161 }
162 }
163
164 if (queue.empty())
165 return;
166
Robert Wilhelm25284cc2013-08-23 16:11:15 +0000167 DC = queue.pop_back_val();
John McCallf6c8a4e2009-11-10 07:01:13 +0000168 }
169 }
170
171 // Add a using directive as if it had been declared in the given
172 // context. This helps implement C++ [namespace.udir]p3:
173 // The using-directive is transitive: if a scope contains a
174 // using-directive that nominates a second namespace that itself
175 // contains using-directives, the effect is as if the
176 // using-directives from the second namespace also appeared in
177 // the first.
178 void addUsingDirective(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
179 // Find the common ancestor between the effective context and
180 // the nominated namespace.
181 DeclContext *Common = UD->getNominatedNamespace();
182 while (!Common->Encloses(EffectiveDC))
183 Common = Common->getParent();
John McCall9757d032009-11-10 09:20:04 +0000184 Common = Common->getPrimaryContext();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000185
John McCallf6c8a4e2009-11-10 07:01:13 +0000186 list.push_back(UnqualUsingEntry(UD->getNominatedNamespace(), Common));
187 }
188
189 void done() {
190 std::sort(list.begin(), list.end(), UnqualUsingEntry::Comparator());
191 }
192
John McCallf6c8a4e2009-11-10 07:01:13 +0000193 typedef ListTy::const_iterator const_iterator;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000194
John McCallf6c8a4e2009-11-10 07:01:13 +0000195 const_iterator begin() const { return list.begin(); }
196 const_iterator end() const { return list.end(); }
197
198 std::pair<const_iterator,const_iterator>
199 getNamespacesFor(DeclContext *DC) const {
John McCall9757d032009-11-10 09:20:04 +0000200 return std::equal_range(begin(), end(), DC->getPrimaryContext(),
John McCallf6c8a4e2009-11-10 07:01:13 +0000201 UnqualUsingEntry::Comparator());
202 }
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;
Chris Lattnerebb5c6c2011-02-18 01:27:55 +0000249 case Sema::LookupLabel:
250 IDNS = Decl::IDNS_Label;
251 break;
252
Douglas Gregor889ceb72009-02-03 19:21:40 +0000253 case Sema::LookupMemberName:
254 IDNS = Decl::IDNS_Member;
255 if (CPlusPlus)
Mike Stump11289f42009-09-09 15:08:12 +0000256 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Ordinary;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000257 break;
258
259 case Sema::LookupNestedNameSpecifierName:
John McCalle87beb22010-04-23 18:46:30 +0000260 IDNS = Decl::IDNS_Type | Decl::IDNS_Namespace;
261 break;
262
Douglas Gregor889ceb72009-02-03 19:21:40 +0000263 case Sema::LookupNamespaceName:
John McCalle87beb22010-04-23 18:46:30 +0000264 IDNS = Decl::IDNS_Namespace;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000265 break;
Douglas Gregorde9f17e2009-04-23 23:18:26 +0000266
John McCall84d87672009-12-10 09:41:52 +0000267 case Sema::LookupUsingDeclName:
268 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag
269 | Decl::IDNS_Member | Decl::IDNS_Using;
270 break;
271
Douglas Gregor79947a22009-04-24 00:11:27 +0000272 case Sema::LookupObjCProtocolName:
273 IDNS = Decl::IDNS_ObjCProtocol;
274 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000275
Douglas Gregor39982192010-08-15 06:18:01 +0000276 case Sema::LookupAnyName:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000277 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Member
Douglas Gregor39982192010-08-15 06:18:01 +0000278 | Decl::IDNS_Using | Decl::IDNS_Namespace | Decl::IDNS_ObjCProtocol
279 | Decl::IDNS_Type;
280 break;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000281 }
282 return IDNS;
283}
284
John McCallea305ed2009-12-18 10:40:03 +0000285void LookupResult::configure() {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000286 IDNS = getIDNS(LookupKind, SemaRef.getLangOpts().CPlusPlus,
John McCallea305ed2009-12-18 10:40:03 +0000287 isForRedeclaration());
Douglas Gregorbcf0a472010-03-24 05:07:21 +0000288
Richard Smithbdd14642014-02-04 01:14:30 +0000289 // If we're looking for one of the allocation or deallocation
290 // operators, make sure that the implicitly-declared new and delete
291 // operators can be found.
292 switch (NameInfo.getName().getCXXOverloadedOperator()) {
293 case OO_New:
294 case OO_Delete:
295 case OO_Array_New:
296 case OO_Array_Delete:
297 SemaRef.DeclareGlobalNewDelete();
298 break;
Douglas Gregorbcf0a472010-03-24 05:07:21 +0000299
Richard Smithbdd14642014-02-04 01:14:30 +0000300 default:
301 break;
302 }
Douglas Gregor15197662013-04-03 23:06:26 +0000303
Richard Smithbdd14642014-02-04 01:14:30 +0000304 // Compiler builtins are always visible, regardless of where they end
305 // up being declared.
306 if (IdentifierInfo *Id = NameInfo.getName().getAsIdentifierInfo()) {
307 if (unsigned BuiltinID = Id->getBuiltinID()) {
308 if (!SemaRef.Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
309 AllowHidden = true;
Douglas Gregor15197662013-04-03 23:06:26 +0000310 }
Douglas Gregorbcf0a472010-03-24 05:07:21 +0000311 }
John McCallea305ed2009-12-18 10:40:03 +0000312}
313
Alp Tokerc1086762013-12-07 13:51:35 +0000314bool LookupResult::sanity() const {
Daniel Dunbar9e19f132012-03-08 01:43:06 +0000315 // Note that this function is never called by NDEBUG builds. See
316 // LookupResult::sanity().
John McCall19c1bfd2010-08-25 05:32:35 +0000317 assert(ResultKind != NotFound || Decls.size() == 0);
318 assert(ResultKind != Found || Decls.size() == 1);
319 assert(ResultKind != FoundOverloaded || Decls.size() > 1 ||
320 (Decls.size() == 1 &&
321 isa<FunctionTemplateDecl>((*begin())->getUnderlyingDecl())));
322 assert(ResultKind != FoundUnresolvedValue || sanityCheckUnresolved());
323 assert(ResultKind != Ambiguous || Decls.size() > 1 ||
Douglas Gregorc0d24902010-10-22 22:08:47 +0000324 (Decls.size() == 1 && (Ambiguity == AmbiguousBaseSubobjects ||
325 Ambiguity == AmbiguousBaseSubobjectTypes)));
John McCall19c1bfd2010-08-25 05:32:35 +0000326 assert((Paths != NULL) == (ResultKind == Ambiguous &&
327 (Ambiguity == AmbiguousBaseSubobjectTypes ||
328 Ambiguity == AmbiguousBaseSubobjects)));
Alp Tokerc1086762013-12-07 13:51:35 +0000329 return true;
John McCall19c1bfd2010-08-25 05:32:35 +0000330}
John McCall19c1bfd2010-08-25 05:32:35 +0000331
John McCall9f3059a2009-10-09 21:13:30 +0000332// Necessary because CXXBasePaths is not complete in Sema.h
John McCall5cebab12009-11-18 07:57:50 +0000333void LookupResult::deletePaths(CXXBasePaths *Paths) {
John McCall9f3059a2009-10-09 21:13:30 +0000334 delete Paths;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000335}
336
Richard Smith3876cc82013-10-30 01:02:04 +0000337/// Get a representative context for a declaration such that two declarations
338/// will have the same context if they were found within the same scope.
Benjamin Kramerfc58b042013-11-01 11:50:55 +0000339static DeclContext *getContextForScopeMatching(Decl *D) {
Richard Smith3876cc82013-10-30 01:02:04 +0000340 // For function-local declarations, use that function as the context. This
341 // doesn't account for scopes within the function; the caller must deal with
342 // those.
343 DeclContext *DC = D->getLexicalDeclContext();
344 if (DC->isFunctionOrMethod())
345 return DC;
346
347 // Otherwise, look at the semantic context of the declaration. The
348 // declaration must have been found there.
349 return D->getDeclContext()->getRedeclContext();
350}
351
John McCall283b9012009-11-22 00:44:51 +0000352/// Resolves the result kind of this lookup.
John McCall5cebab12009-11-18 07:57:50 +0000353void LookupResult::resolveKind() {
John McCall9f3059a2009-10-09 21:13:30 +0000354 unsigned N = Decls.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000355
John McCall9f3059a2009-10-09 21:13:30 +0000356 // Fast case: no possible ambiguity.
John McCall1f82f242009-11-18 22:49:29 +0000357 if (N == 0) {
John McCall7fe6e9c2010-01-15 21:27:01 +0000358 assert(ResultKind == NotFound || ResultKind == NotFoundInCurrentInstantiation);
John McCall1f82f242009-11-18 22:49:29 +0000359 return;
360 }
361
John McCall283b9012009-11-22 00:44:51 +0000362 // If there's a single decl, we need to examine it to decide what
363 // kind of lookup this is.
John McCalle61f2ba2009-11-18 02:36:19 +0000364 if (N == 1) {
Douglas Gregor516d6722010-04-25 21:15:30 +0000365 NamedDecl *D = (*Decls.begin())->getUnderlyingDecl();
366 if (isa<FunctionTemplateDecl>(D))
John McCall283b9012009-11-22 00:44:51 +0000367 ResultKind = FoundOverloaded;
Douglas Gregor516d6722010-04-25 21:15:30 +0000368 else if (isa<UnresolvedUsingValueDecl>(D))
John McCalle61f2ba2009-11-18 02:36:19 +0000369 ResultKind = FoundUnresolvedValue;
370 return;
371 }
John McCall9f3059a2009-10-09 21:13:30 +0000372
John McCall6538c932009-10-10 05:48:19 +0000373 // Don't do any extra resolution if we've already resolved as ambiguous.
John McCall27b18f82009-11-17 02:14:36 +0000374 if (ResultKind == Ambiguous) return;
John McCall6538c932009-10-10 05:48:19 +0000375
John McCall9f3059a2009-10-09 21:13:30 +0000376 llvm::SmallPtrSet<NamedDecl*, 16> Unique;
Douglas Gregor13e65872010-08-11 14:45:53 +0000377 llvm::SmallPtrSet<QualType, 16> UniqueTypes;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000378
John McCall9f3059a2009-10-09 21:13:30 +0000379 bool Ambiguous = false;
380 bool HasTag = false, HasFunction = false, HasNonFunction = false;
John McCall283b9012009-11-22 00:44:51 +0000381 bool HasFunctionTemplate = false, HasUnresolved = false;
John McCall9f3059a2009-10-09 21:13:30 +0000382
383 unsigned UniqueTagIndex = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000384
John McCall9f3059a2009-10-09 21:13:30 +0000385 unsigned I = 0;
386 while (I < N) {
John McCallf0f1cf02009-11-17 07:50:12 +0000387 NamedDecl *D = Decls[I]->getUnderlyingDecl();
388 D = cast<NamedDecl>(D->getCanonicalDecl());
John McCall9f3059a2009-10-09 21:13:30 +0000389
Argyrios Kyrtzidis1fcd7fd2013-02-22 06:58:37 +0000390 // Ignore an invalid declaration unless it's the only one left.
391 if (D->isInvalidDecl() && I < N-1) {
392 Decls[I] = Decls[--N];
393 continue;
394 }
395
Douglas Gregor13e65872010-08-11 14:45:53 +0000396 // Redeclarations of types via typedef can occur both within a scope
397 // and, through using declarations and directives, across scopes. There is
398 // no ambiguity if they all refer to the same type, so unique based on the
399 // canonical type.
400 if (TypeDecl *TD = dyn_cast<TypeDecl>(D)) {
401 if (!TD->getDeclContext()->isRecord()) {
402 QualType T = SemaRef.Context.getTypeDeclType(TD);
403 if (!UniqueTypes.insert(SemaRef.Context.getCanonicalType(T))) {
404 // The type is not unique; pull something off the back and continue
405 // at this index.
406 Decls[I] = Decls[--N];
407 continue;
408 }
409 }
410 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000411
John McCallf0f1cf02009-11-17 07:50:12 +0000412 if (!Unique.insert(D)) {
John McCall9f3059a2009-10-09 21:13:30 +0000413 // If it's not unique, pull something off the back (and
414 // continue at this index).
415 Decls[I] = Decls[--N];
Douglas Gregor13e65872010-08-11 14:45:53 +0000416 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000417 }
418
Douglas Gregor13e65872010-08-11 14:45:53 +0000419 // Otherwise, do some decl type analysis and then continue.
John McCalle61f2ba2009-11-18 02:36:19 +0000420
Douglas Gregor13e65872010-08-11 14:45:53 +0000421 if (isa<UnresolvedUsingValueDecl>(D)) {
422 HasUnresolved = true;
423 } else if (isa<TagDecl>(D)) {
424 if (HasTag)
425 Ambiguous = true;
426 UniqueTagIndex = I;
427 HasTag = true;
428 } else if (isa<FunctionTemplateDecl>(D)) {
429 HasFunction = true;
430 HasFunctionTemplate = true;
431 } else if (isa<FunctionDecl>(D)) {
432 HasFunction = true;
433 } else {
434 if (HasNonFunction)
435 Ambiguous = true;
436 HasNonFunction = true;
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000437 }
Douglas Gregor13e65872010-08-11 14:45:53 +0000438 I++;
Mike Stump11289f42009-09-09 15:08:12 +0000439 }
Douglas Gregor38feed82009-04-24 02:57:34 +0000440
John McCall9f3059a2009-10-09 21:13:30 +0000441 // C++ [basic.scope.hiding]p2:
442 // A class name or enumeration name can be hidden by the name of
443 // an object, function, or enumerator declared in the same
444 // scope. If a class or enumeration name and an object, function,
445 // or enumerator are declared in the same scope (in any order)
446 // with the same name, the class or enumeration name is hidden
447 // wherever the object, function, or enumerator name is visible.
448 // But it's still an error if there are distinct tag types found,
449 // even if they're not visible. (ref?)
John McCall80053822009-12-03 00:58:24 +0000450 if (HideTags && HasTag && !Ambiguous &&
Douglas Gregore63d0872010-10-23 16:06:17 +0000451 (HasFunction || HasNonFunction || HasUnresolved)) {
Richard Smith3876cc82013-10-30 01:02:04 +0000452 if (getContextForScopeMatching(Decls[UniqueTagIndex])->Equals(
453 getContextForScopeMatching(Decls[UniqueTagIndex ? 0 : N - 1])))
Douglas Gregore63d0872010-10-23 16:06:17 +0000454 Decls[UniqueTagIndex] = Decls[--N];
455 else
456 Ambiguous = true;
457 }
Anders Carlsson8d0f6b72009-06-26 03:37:05 +0000458
John McCall9f3059a2009-10-09 21:13:30 +0000459 Decls.set_size(N);
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000460
John McCall80053822009-12-03 00:58:24 +0000461 if (HasNonFunction && (HasFunction || HasUnresolved))
John McCall9f3059a2009-10-09 21:13:30 +0000462 Ambiguous = true;
Douglas Gregorf23311d2009-01-17 01:13:24 +0000463
John McCall9f3059a2009-10-09 21:13:30 +0000464 if (Ambiguous)
John McCall6538c932009-10-10 05:48:19 +0000465 setAmbiguous(LookupResult::AmbiguousReference);
John McCalle61f2ba2009-11-18 02:36:19 +0000466 else if (HasUnresolved)
467 ResultKind = LookupResult::FoundUnresolvedValue;
John McCall283b9012009-11-22 00:44:51 +0000468 else if (N > 1 || HasFunctionTemplate)
John McCall27b18f82009-11-17 02:14:36 +0000469 ResultKind = LookupResult::FoundOverloaded;
John McCall9f3059a2009-10-09 21:13:30 +0000470 else
John McCall27b18f82009-11-17 02:14:36 +0000471 ResultKind = LookupResult::Found;
Douglas Gregor34074322009-01-14 22:20:51 +0000472}
473
John McCall5cebab12009-11-18 07:57:50 +0000474void LookupResult::addDeclsFromBasePaths(const CXXBasePaths &P) {
John McCall5b0829a2010-02-10 09:31:12 +0000475 CXXBasePaths::const_paths_iterator I, E;
John McCall9f3059a2009-10-09 21:13:30 +0000476 for (I = P.begin(), E = P.end(); I != E; ++I)
David Blaikieff7d47a2012-12-19 00:45:41 +0000477 for (DeclContext::lookup_iterator DI = I->Decls.begin(),
478 DE = I->Decls.end(); DI != DE; ++DI)
John McCall9f3059a2009-10-09 21:13:30 +0000479 addDecl(*DI);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +0000480}
481
John McCall5cebab12009-11-18 07:57:50 +0000482void LookupResult::setAmbiguousBaseSubobjects(CXXBasePaths &P) {
John McCall9f3059a2009-10-09 21:13:30 +0000483 Paths = new CXXBasePaths;
484 Paths->swap(P);
485 addDeclsFromBasePaths(*Paths);
486 resolveKind();
John McCall6538c932009-10-10 05:48:19 +0000487 setAmbiguous(AmbiguousBaseSubobjects);
Douglas Gregor0e8fc3c2009-02-02 21:35:47 +0000488}
489
John McCall5cebab12009-11-18 07:57:50 +0000490void LookupResult::setAmbiguousBaseSubobjectTypes(CXXBasePaths &P) {
John McCall9f3059a2009-10-09 21:13:30 +0000491 Paths = new CXXBasePaths;
492 Paths->swap(P);
493 addDeclsFromBasePaths(*Paths);
494 resolveKind();
John McCall6538c932009-10-10 05:48:19 +0000495 setAmbiguous(AmbiguousBaseSubobjectTypes);
John McCall9f3059a2009-10-09 21:13:30 +0000496}
497
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000498void LookupResult::print(raw_ostream &Out) {
John McCall9f3059a2009-10-09 21:13:30 +0000499 Out << Decls.size() << " result(s)";
500 if (isAmbiguous()) Out << ", ambiguous";
501 if (Paths) Out << ", base paths present";
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000502
John McCall9f3059a2009-10-09 21:13:30 +0000503 for (iterator I = begin(), E = end(); I != E; ++I) {
504 Out << "\n";
505 (*I)->print(Out, 2);
506 }
507}
508
Douglas Gregord3a59182010-02-12 05:48:04 +0000509/// \brief Lookup a builtin function, when name lookup would otherwise
510/// fail.
511static bool LookupBuiltin(Sema &S, LookupResult &R) {
512 Sema::LookupNameKind NameKind = R.getLookupKind();
513
514 // If we didn't find a use of this identifier, and if the identifier
515 // corresponds to a compiler builtin, create the decl object for the builtin
516 // now, injecting it into translation unit scope, and return it.
517 if (NameKind == Sema::LookupOrdinaryName ||
518 NameKind == Sema::LookupRedeclarationWithLinkage) {
519 IdentifierInfo *II = R.getLookupName().getAsIdentifierInfo();
520 if (II) {
Nico Webere1687c52013-06-20 21:44:55 +0000521 if (S.getLangOpts().CPlusPlus11 && S.getLangOpts().GNUMode &&
522 II == S.getFloat128Identifier()) {
523 // libstdc++4.7's type_traits expects type __float128 to exist, so
524 // insert a dummy type to make that header build in gnu++11 mode.
525 R.addDecl(S.getASTContext().getFloat128StubType());
526 return true;
527 }
528
Douglas Gregord3a59182010-02-12 05:48:04 +0000529 // If this is a builtin on this (or all) targets, create the decl.
530 if (unsigned BuiltinID = II->getBuiltinID()) {
531 // In C++, we don't have any predefined library functions like
532 // 'malloc'. Instead, we'll just error.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000533 if (S.getLangOpts().CPlusPlus &&
Douglas Gregord3a59182010-02-12 05:48:04 +0000534 S.Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
535 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000536
537 if (NamedDecl *D = S.LazilyCreateBuiltin((IdentifierInfo *)II,
538 BuiltinID, S.TUScope,
Douglas Gregorbfe022c2011-01-03 09:37:44 +0000539 R.isForRedeclaration(),
540 R.getNameLoc())) {
Douglas Gregord3a59182010-02-12 05:48:04 +0000541 R.addDecl(D);
Douglas Gregorbfe022c2011-01-03 09:37:44 +0000542 return true;
543 }
Douglas Gregord3a59182010-02-12 05:48:04 +0000544 }
545 }
546 }
547
548 return false;
549}
550
Douglas Gregor7454c562010-07-02 20:37:36 +0000551/// \brief Determine whether we can declare a special member function within
552/// the class at this point.
Richard Smith7d125a12012-11-27 21:20:31 +0000553static bool CanDeclareSpecialMemberFunction(const CXXRecordDecl *Class) {
Douglas Gregor7454c562010-07-02 20:37:36 +0000554 // We need to have a definition for the class.
555 if (!Class->getDefinition() || Class->isDependentContext())
556 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000557
Douglas Gregor7454c562010-07-02 20:37:36 +0000558 // We can't be in the middle of defining the class.
Richard Smith7d125a12012-11-27 21:20:31 +0000559 return !Class->isBeingDefined();
Douglas Gregor7454c562010-07-02 20:37:36 +0000560}
561
562void Sema::ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class) {
Richard Smith7d125a12012-11-27 21:20:31 +0000563 if (!CanDeclareSpecialMemberFunction(Class))
Douglas Gregora6d69502010-07-02 23:41:54 +0000564 return;
Douglas Gregor9672f922010-07-03 00:47:00 +0000565
566 // If the default constructor has not yet been declared, do so now.
Alexis Huntea6f0322011-05-11 22:34:38 +0000567 if (Class->needsImplicitDefaultConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +0000568 DeclareImplicitDefaultConstructor(Class);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000569
Douglas Gregora6d69502010-07-02 23:41:54 +0000570 // If the copy constructor has not yet been declared, do so now.
Richard Smith2be35f52012-12-01 02:35:44 +0000571 if (Class->needsImplicitCopyConstructor())
Douglas Gregora6d69502010-07-02 23:41:54 +0000572 DeclareImplicitCopyConstructor(Class);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000573
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000574 // If the copy assignment operator has not yet been declared, do so now.
Richard Smith2be35f52012-12-01 02:35:44 +0000575 if (Class->needsImplicitCopyAssignment())
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000576 DeclareImplicitCopyAssignment(Class);
577
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000578 if (getLangOpts().CPlusPlus11) {
Sebastian Redl22653ba2011-08-30 19:58:05 +0000579 // If the move constructor has not yet been declared, do so now.
580 if (Class->needsImplicitMoveConstructor())
581 DeclareImplicitMoveConstructor(Class); // might not actually do it
582
583 // If the move assignment operator has not yet been declared, do so now.
584 if (Class->needsImplicitMoveAssignment())
585 DeclareImplicitMoveAssignment(Class); // might not actually do it
586 }
587
Douglas Gregor7454c562010-07-02 20:37:36 +0000588 // If the destructor has not yet been declared, do so now.
Richard Smith2be35f52012-12-01 02:35:44 +0000589 if (Class->needsImplicitDestructor())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000590 DeclareImplicitDestructor(Class);
Douglas Gregor7454c562010-07-02 20:37:36 +0000591}
592
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000593/// \brief Determine whether this is the name of an implicitly-declared
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000594/// special member function.
595static bool isImplicitlyDeclaredMemberFunctionName(DeclarationName Name) {
596 switch (Name.getNameKind()) {
Douglas Gregora6d69502010-07-02 23:41:54 +0000597 case DeclarationName::CXXConstructorName:
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000598 case DeclarationName::CXXDestructorName:
599 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000600
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000601 case DeclarationName::CXXOperatorName:
602 return Name.getCXXOverloadedOperator() == OO_Equal;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000603
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000604 default:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000605 break;
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000606 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000607
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000608 return false;
609}
610
611/// \brief If there are any implicit member functions with the given name
612/// that need to be declared in the given declaration context, do so.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000613static void DeclareImplicitMemberFunctionsWithName(Sema &S,
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000614 DeclarationName Name,
615 const DeclContext *DC) {
616 if (!DC)
617 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000618
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000619 switch (Name.getNameKind()) {
Douglas Gregora6d69502010-07-02 23:41:54 +0000620 case DeclarationName::CXXConstructorName:
621 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
Richard Smith7d125a12012-11-27 21:20:31 +0000622 if (Record->getDefinition() && CanDeclareSpecialMemberFunction(Record)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +0000623 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(Record);
Alexis Huntea6f0322011-05-11 22:34:38 +0000624 if (Record->needsImplicitDefaultConstructor())
Sebastian Redl22653ba2011-08-30 19:58:05 +0000625 S.DeclareImplicitDefaultConstructor(Class);
Richard Smith2be35f52012-12-01 02:35:44 +0000626 if (Record->needsImplicitCopyConstructor())
Sebastian Redl22653ba2011-08-30 19:58:05 +0000627 S.DeclareImplicitCopyConstructor(Class);
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000628 if (S.getLangOpts().CPlusPlus11 &&
Sebastian Redl22653ba2011-08-30 19:58:05 +0000629 Record->needsImplicitMoveConstructor())
630 S.DeclareImplicitMoveConstructor(Class);
Douglas Gregor9672f922010-07-03 00:47:00 +0000631 }
Douglas Gregora6d69502010-07-02 23:41:54 +0000632 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000633
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000634 case DeclarationName::CXXDestructorName:
635 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
Richard Smith2be35f52012-12-01 02:35:44 +0000636 if (Record->getDefinition() && Record->needsImplicitDestructor() &&
Richard Smith7d125a12012-11-27 21:20:31 +0000637 CanDeclareSpecialMemberFunction(Record))
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000638 S.DeclareImplicitDestructor(const_cast<CXXRecordDecl *>(Record));
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000639 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000640
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000641 case DeclarationName::CXXOperatorName:
642 if (Name.getCXXOverloadedOperator() != OO_Equal)
643 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000644
Sebastian Redl22653ba2011-08-30 19:58:05 +0000645 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC)) {
Richard Smith7d125a12012-11-27 21:20:31 +0000646 if (Record->getDefinition() && CanDeclareSpecialMemberFunction(Record)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +0000647 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(Record);
Richard Smith2be35f52012-12-01 02:35:44 +0000648 if (Record->needsImplicitCopyAssignment())
Sebastian Redl22653ba2011-08-30 19:58:05 +0000649 S.DeclareImplicitCopyAssignment(Class);
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000650 if (S.getLangOpts().CPlusPlus11 &&
Sebastian Redl22653ba2011-08-30 19:58:05 +0000651 Record->needsImplicitMoveAssignment())
652 S.DeclareImplicitMoveAssignment(Class);
653 }
654 }
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000655 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000656
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000657 default:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000658 break;
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000659 }
660}
Douglas Gregor7454c562010-07-02 20:37:36 +0000661
John McCall9f3059a2009-10-09 21:13:30 +0000662// Adds all qualifying matches for a name within a decl context to the
663// given lookup result. Returns true if any matches were found.
Douglas Gregord3a59182010-02-12 05:48:04 +0000664static bool LookupDirect(Sema &S, LookupResult &R, const DeclContext *DC) {
John McCall9f3059a2009-10-09 21:13:30 +0000665 bool Found = false;
666
Douglas Gregor7454c562010-07-02 20:37:36 +0000667 // Lazily declare C++ special member functions.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000668 if (S.getLangOpts().CPlusPlus)
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000669 DeclareImplicitMemberFunctionsWithName(S, R.getLookupName(), DC);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000670
Douglas Gregor7454c562010-07-02 20:37:36 +0000671 // Perform lookup into this declaration context.
David Blaikieff7d47a2012-12-19 00:45:41 +0000672 DeclContext::lookup_const_result DR = DC->lookup(R.getLookupName());
673 for (DeclContext::lookup_const_iterator I = DR.begin(), E = DR.end(); I != E;
674 ++I) {
John McCall401982f2010-01-20 21:53:11 +0000675 NamedDecl *D = *I;
Douglas Gregor4a814562011-12-14 16:03:29 +0000676 if ((D = R.getAcceptableDecl(D))) {
John McCall401982f2010-01-20 21:53:11 +0000677 R.addDecl(D);
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000678 Found = true;
679 }
680 }
John McCall9f3059a2009-10-09 21:13:30 +0000681
Douglas Gregord3a59182010-02-12 05:48:04 +0000682 if (!Found && DC->isTranslationUnit() && LookupBuiltin(S, R))
683 return true;
684
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000685 if (R.getLookupName().getNameKind()
Chandler Carruth3a693b72010-01-31 11:44:02 +0000686 != DeclarationName::CXXConversionFunctionName ||
687 R.getLookupName().getCXXNameType()->isDependentType() ||
688 !isa<CXXRecordDecl>(DC))
689 return Found;
690
691 // C++ [temp.mem]p6:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000692 // A specialization of a conversion function template is not found by
Chandler Carruth3a693b72010-01-31 11:44:02 +0000693 // name lookup. Instead, any conversion function templates visible in the
694 // context of the use are considered. [...]
695 const CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
John McCallf937c022011-10-07 06:10:15 +0000696 if (!Record->isCompleteDefinition())
Chandler Carruth3a693b72010-01-31 11:44:02 +0000697 return Found;
698
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +0000699 for (CXXRecordDecl::conversion_iterator U = Record->conversion_begin(),
700 UEnd = Record->conversion_end(); U != UEnd; ++U) {
Chandler Carruth3a693b72010-01-31 11:44:02 +0000701 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(*U);
702 if (!ConvTemplate)
703 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000704
Chandler Carruth3a693b72010-01-31 11:44:02 +0000705 // When we're performing lookup for the purposes of redeclaration, just
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000706 // add the conversion function template. When we deduce template
707 // arguments for specializations, we'll end up unifying the return
Chandler Carruth3a693b72010-01-31 11:44:02 +0000708 // type of the new declaration with the type of the function template.
709 if (R.isForRedeclaration()) {
710 R.addDecl(ConvTemplate);
711 Found = true;
712 continue;
713 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000714
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000715 // C++ [temp.mem]p6:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000716 // [...] For each such operator, if argument deduction succeeds
717 // (14.9.2.3), the resulting specialization is used as if found by
Chandler Carruth3a693b72010-01-31 11:44:02 +0000718 // name lookup.
719 //
720 // When referencing a conversion function for any purpose other than
721 // a redeclaration (such that we'll be building an expression with the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000722 // result), perform template argument deduction and place the
Chandler Carruth3a693b72010-01-31 11:44:02 +0000723 // specialization into the result set. We do this to avoid forcing all
724 // callers to perform special deduction for conversion functions.
Craig Toppere6706e42012-09-19 02:26:47 +0000725 TemplateDeductionInfo Info(R.getNameLoc());
Chandler Carruth3a693b72010-01-31 11:44:02 +0000726 FunctionDecl *Specialization = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000727
728 const FunctionProtoType *ConvProto
Chandler Carruth3a693b72010-01-31 11:44:02 +0000729 = ConvTemplate->getTemplatedDecl()->getType()->getAs<FunctionProtoType>();
730 assert(ConvProto && "Nonsensical conversion function template type");
Douglas Gregor3c96a462010-01-12 01:17:50 +0000731
Chandler Carruth3a693b72010-01-31 11:44:02 +0000732 // Compute the type of the function that we would expect the conversion
733 // function to have, if it were to match the name given.
734 // FIXME: Calling convention!
John McCalldb40c7f2010-12-14 08:05:40 +0000735 FunctionProtoType::ExtProtoInfo EPI = ConvProto->getExtProtoInfo();
Reid Kleckner78af0702013-08-27 23:08:25 +0000736 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(CC_C);
Sebastian Redl7c6c9e92011-03-06 10:52:04 +0000737 EPI.ExceptionSpecType = EST_None;
John McCalldb40c7f2010-12-14 08:05:40 +0000738 EPI.NumExceptions = 0;
Chandler Carruth3a693b72010-01-31 11:44:02 +0000739 QualType ExpectedType
740 = R.getSema().Context.getFunctionType(R.getLookupName().getCXXNameType(),
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +0000741 None, EPI);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000742
Chandler Carruth3a693b72010-01-31 11:44:02 +0000743 // Perform template argument deduction against the type that we would
744 // expect the function to have.
745 if (R.getSema().DeduceTemplateArguments(ConvTemplate, 0, ExpectedType,
746 Specialization, Info)
747 == Sema::TDK_Success) {
748 R.addDecl(Specialization);
749 Found = true;
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000750 }
751 }
Chandler Carruth3a693b72010-01-31 11:44:02 +0000752
John McCall9f3059a2009-10-09 21:13:30 +0000753 return Found;
754}
755
John McCallf6c8a4e2009-11-10 07:01:13 +0000756// Performs C++ unqualified lookup into the given file context.
John McCall9f3059a2009-10-09 21:13:30 +0000757static bool
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000758CppNamespaceLookup(Sema &S, LookupResult &R, ASTContext &Context,
Douglas Gregord3a59182010-02-12 05:48:04 +0000759 DeclContext *NS, UnqualUsingDirectiveSet &UDirs) {
Douglas Gregor700792c2009-02-05 19:25:20 +0000760
761 assert(NS && NS->isFileContext() && "CppNamespaceLookup() requires namespace!");
762
John McCallf6c8a4e2009-11-10 07:01:13 +0000763 // Perform direct name lookup into the LookupCtx.
Douglas Gregord3a59182010-02-12 05:48:04 +0000764 bool Found = LookupDirect(S, R, NS);
Douglas Gregor700792c2009-02-05 19:25:20 +0000765
John McCallf6c8a4e2009-11-10 07:01:13 +0000766 // Perform direct name lookup into the namespaces nominated by the
767 // using directives whose common ancestor is this namespace.
768 UnqualUsingDirectiveSet::const_iterator UI, UEnd;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000769 std::tie(UI, UEnd) = UDirs.getNamespacesFor(NS);
Mike Stump11289f42009-09-09 15:08:12 +0000770
John McCallf6c8a4e2009-11-10 07:01:13 +0000771 for (; UI != UEnd; ++UI)
Douglas Gregord3a59182010-02-12 05:48:04 +0000772 if (LookupDirect(S, R, UI->getNominatedNamespace()))
John McCallf6c8a4e2009-11-10 07:01:13 +0000773 Found = true;
John McCall9f3059a2009-10-09 21:13:30 +0000774
775 R.resolveKind();
776
777 return Found;
Douglas Gregor700792c2009-02-05 19:25:20 +0000778}
779
780static bool isNamespaceOrTranslationUnitScope(Scope *S) {
Ted Kremenekc37877d2013-10-08 17:08:03 +0000781 if (DeclContext *Ctx = S->getEntity())
Douglas Gregor700792c2009-02-05 19:25:20 +0000782 return Ctx->isFileContext();
783 return false;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000784}
Douglas Gregored8f2882009-01-30 01:04:22 +0000785
Douglas Gregor66230062010-03-15 14:33:29 +0000786// Find the next outer declaration context from this scope. This
787// routine actually returns the semantic outer context, which may
788// differ from the lexical context (encoded directly in the Scope
789// stack) when we are parsing a member of a class template. In this
790// case, the second element of the pair will be true, to indicate that
791// name lookup should continue searching in this semantic context when
792// it leaves the current template parameter scope.
793static std::pair<DeclContext *, bool> findOuterContext(Scope *S) {
Ted Kremenekc37877d2013-10-08 17:08:03 +0000794 DeclContext *DC = S->getEntity();
Douglas Gregor66230062010-03-15 14:33:29 +0000795 DeclContext *Lexical = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000796 for (Scope *OuterS = S->getParent(); OuterS;
Douglas Gregor66230062010-03-15 14:33:29 +0000797 OuterS = OuterS->getParent()) {
798 if (OuterS->getEntity()) {
Ted Kremenekc37877d2013-10-08 17:08:03 +0000799 Lexical = OuterS->getEntity();
Douglas Gregor66230062010-03-15 14:33:29 +0000800 break;
801 }
802 }
803
804 // C++ [temp.local]p8:
805 // In the definition of a member of a class template that appears
806 // outside of the namespace containing the class template
807 // definition, the name of a template-parameter hides the name of
808 // a member of this namespace.
809 //
810 // Example:
811 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000812 // namespace N {
813 // class C { };
Douglas Gregor66230062010-03-15 14:33:29 +0000814 //
815 // template<class T> class B {
816 // void f(T);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000817 // };
Douglas Gregor66230062010-03-15 14:33:29 +0000818 // }
819 //
820 // template<class C> void N::B<C>::f(C) {
821 // C b; // C is the template parameter, not N::C
822 // }
823 //
824 // In this example, the lexical context we return is the
825 // TranslationUnit, while the semantic context is the namespace N.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000826 if (!Lexical || !DC || !S->getParent() ||
Douglas Gregor66230062010-03-15 14:33:29 +0000827 !S->getParent()->isTemplateParamScope())
828 return std::make_pair(Lexical, false);
829
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000830 // Find the outermost template parameter scope.
Douglas Gregor66230062010-03-15 14:33:29 +0000831 // For the example, this is the scope for the template parameters of
832 // template<class C>.
833 Scope *OutermostTemplateScope = S->getParent();
834 while (OutermostTemplateScope->getParent() &&
835 OutermostTemplateScope->getParent()->isTemplateParamScope())
836 OutermostTemplateScope = OutermostTemplateScope->getParent();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000837
Douglas Gregor66230062010-03-15 14:33:29 +0000838 // Find the namespace context in which the original scope occurs. In
839 // the example, this is namespace N.
840 DeclContext *Semantic = DC;
841 while (!Semantic->isFileContext())
842 Semantic = Semantic->getParent();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000843
Douglas Gregor66230062010-03-15 14:33:29 +0000844 // Find the declaration context just outside of the template
845 // parameter scope. This is the context in which the template is
846 // being lexically declaration (a namespace context). In the
847 // example, this is the global scope.
848 if (Lexical->isFileContext() && !Lexical->Equals(Semantic) &&
849 Lexical->Encloses(Semantic))
850 return std::make_pair(Semantic, true);
851
852 return std::make_pair(Lexical, false);
Douglas Gregor7f737c02009-09-10 16:57:35 +0000853}
854
Richard Smith541b38b2013-09-20 01:15:31 +0000855namespace {
856/// An RAII object to specify that we want to find block scope extern
857/// declarations.
858struct FindLocalExternScope {
859 FindLocalExternScope(LookupResult &R)
860 : R(R), OldFindLocalExtern(R.getIdentifierNamespace() &
861 Decl::IDNS_LocalExtern) {
862 R.setFindLocalExtern(R.getIdentifierNamespace() & Decl::IDNS_Ordinary);
863 }
864 void restore() {
865 R.setFindLocalExtern(OldFindLocalExtern);
866 }
867 ~FindLocalExternScope() {
868 restore();
869 }
870 LookupResult &R;
871 bool OldFindLocalExtern;
872};
873}
874
John McCall27b18f82009-11-17 02:14:36 +0000875bool Sema::CppLookupName(LookupResult &R, Scope *S) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000876 assert(getLangOpts().CPlusPlus && "Can perform only C++ lookup");
John McCall27b18f82009-11-17 02:14:36 +0000877
878 DeclarationName Name = R.getLookupName();
Richard Smith1c34fb72013-08-13 18:18:50 +0000879 Sema::LookupNameKind NameKind = R.getLookupKind();
John McCall27b18f82009-11-17 02:14:36 +0000880
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000881 // If this is the name of an implicitly-declared special member function,
882 // go through the scope stack to implicitly declare
883 if (isImplicitlyDeclaredMemberFunctionName(Name)) {
884 for (Scope *PreS = S; PreS; PreS = PreS->getParent())
Ted Kremenekc37877d2013-10-08 17:08:03 +0000885 if (DeclContext *DC = PreS->getEntity())
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000886 DeclareImplicitMemberFunctionsWithName(*this, Name, DC);
887 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000888
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000889 // Implicitly declare member functions with the name we're looking for, if in
890 // fact we are in a scope where it matters.
891
Douglas Gregor889ceb72009-02-03 19:21:40 +0000892 Scope *Initial = S;
Mike Stump11289f42009-09-09 15:08:12 +0000893 IdentifierResolver::iterator
Douglas Gregor889ceb72009-02-03 19:21:40 +0000894 I = IdResolver.begin(Name),
895 IEnd = IdResolver.end();
Douglas Gregored8f2882009-01-30 01:04:22 +0000896
Douglas Gregor889ceb72009-02-03 19:21:40 +0000897 // First we lookup local scope.
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000898 // We don't consider using-directives, as per 7.3.4.p1 [namespace.udir]
Douglas Gregor889ceb72009-02-03 19:21:40 +0000899 // ...During unqualified name lookup (3.4.1), the names appear as if
900 // they were declared in the nearest enclosing namespace which contains
901 // both the using-directive and the nominated namespace.
Eli Friedman44b83ee2009-08-05 19:21:58 +0000902 // [Note: in this context, "contains" means "contains directly or
Mike Stump11289f42009-09-09 15:08:12 +0000903 // indirectly".
Douglas Gregor889ceb72009-02-03 19:21:40 +0000904 //
905 // For example:
906 // namespace A { int i; }
907 // void foo() {
908 // int i;
909 // {
910 // using namespace A;
911 // ++i; // finds local 'i', A::i appears at global scope
912 // }
913 // }
Douglas Gregor2ada0482009-02-04 17:27:36 +0000914 //
Douglas Gregorcc9406c2013-04-08 23:11:25 +0000915 UnqualUsingDirectiveSet UDirs;
916 bool VisitedUsingDirectives = false;
Richard Smith1c34fb72013-08-13 18:18:50 +0000917 bool LeftStartingScope = false;
Douglas Gregor66230062010-03-15 14:33:29 +0000918 DeclContext *OutsideOfTemplateParamDC = 0;
Richard Smith541b38b2013-09-20 01:15:31 +0000919
920 // When performing a scope lookup, we want to find local extern decls.
921 FindLocalExternScope FindLocals(R);
922
Douglas Gregor700792c2009-02-05 19:25:20 +0000923 for (; S && !isNamespaceOrTranslationUnitScope(S); S = S->getParent()) {
Ted Kremenekc37877d2013-10-08 17:08:03 +0000924 DeclContext *Ctx = S->getEntity();
Douglas Gregor3e51e172010-05-20 20:58:56 +0000925
Douglas Gregor889ceb72009-02-03 19:21:40 +0000926 // Check whether the IdResolver has anything in this scope.
John McCall9f3059a2009-10-09 21:13:30 +0000927 bool Found = false;
John McCall48871652010-08-21 09:40:31 +0000928 for (; I != IEnd && S->isDeclScope(*I); ++I) {
Douglas Gregor4a814562011-12-14 16:03:29 +0000929 if (NamedDecl *ND = R.getAcceptableDecl(*I)) {
Richard Smith1c34fb72013-08-13 18:18:50 +0000930 if (NameKind == LookupRedeclarationWithLinkage) {
931 // Determine whether this (or a previous) declaration is
932 // out-of-scope.
933 if (!LeftStartingScope && !Initial->isDeclScope(*I))
934 LeftStartingScope = true;
935
936 // If we found something outside of our starting scope that
Richard Smith9a00bbf2013-10-16 21:12:00 +0000937 // does not have linkage, skip it. If it's a template parameter,
938 // we still find it, so we can diagnose the invalid redeclaration.
939 if (LeftStartingScope && !((*I)->hasLinkage()) &&
940 !(*I)->isTemplateParameter()) {
Richard Smith1c34fb72013-08-13 18:18:50 +0000941 R.setShadowed();
942 continue;
943 }
944 }
945
John McCall9f3059a2009-10-09 21:13:30 +0000946 Found = true;
Douglas Gregor4a814562011-12-14 16:03:29 +0000947 R.addDecl(ND);
Douglas Gregor889ceb72009-02-03 19:21:40 +0000948 }
949 }
John McCall9f3059a2009-10-09 21:13:30 +0000950 if (Found) {
951 R.resolveKind();
Douglas Gregor3e51e172010-05-20 20:58:56 +0000952 if (S->isClassScope())
953 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(Ctx))
954 R.setNamingClass(Record);
John McCall9f3059a2009-10-09 21:13:30 +0000955 return true;
956 }
957
Richard Smith1c34fb72013-08-13 18:18:50 +0000958 if (NameKind == LookupLocalFriendName && !S->isClassScope()) {
Richard Smith114394f2013-08-09 04:35:01 +0000959 // C++11 [class.friend]p11:
960 // If a friend declaration appears in a local class and the name
961 // specified is an unqualified name, a prior declaration is
962 // looked up without considering scopes that are outside the
963 // innermost enclosing non-class scope.
964 return false;
965 }
966
Douglas Gregor66230062010-03-15 14:33:29 +0000967 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
968 S->getParent() && !S->getParent()->isTemplateParamScope()) {
969 // We've just searched the last template parameter scope and
Sylvestre Ledru830885c2012-07-23 08:59:39 +0000970 // found nothing, so look into the contexts between the
Douglas Gregor66230062010-03-15 14:33:29 +0000971 // lexical and semantic declaration contexts returned by
972 // findOuterContext(). This implements the name lookup behavior
973 // of C++ [temp.local]p8.
974 Ctx = OutsideOfTemplateParamDC;
975 OutsideOfTemplateParamDC = 0;
976 }
977
978 if (Ctx) {
979 DeclContext *OuterCtx;
980 bool SearchAfterTemplateScope;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000981 std::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
Douglas Gregor66230062010-03-15 14:33:29 +0000982 if (SearchAfterTemplateScope)
983 OutsideOfTemplateParamDC = OuterCtx;
984
Douglas Gregorea166062010-03-15 15:26:48 +0000985 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
Douglas Gregor337caf92010-02-19 16:08:35 +0000986 // We do not directly look into transparent contexts, since
987 // those entities will be found in the nearest enclosing
988 // non-transparent context.
989 if (Ctx->isTransparentContext())
Douglas Gregor7f737c02009-09-10 16:57:35 +0000990 continue;
Douglas Gregor337caf92010-02-19 16:08:35 +0000991
992 // We do not look directly into function or method contexts,
993 // since all of the local variables and parameters of the
994 // function/method are present within the Scope.
995 if (Ctx->isFunctionOrMethod()) {
996 // If we have an Objective-C instance method, look for ivars
997 // in the corresponding interface.
998 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
999 if (Method->isInstanceMethod() && Name.getAsIdentifierInfo())
1000 if (ObjCInterfaceDecl *Class = Method->getClassInterface()) {
1001 ObjCInterfaceDecl *ClassDeclared;
1002 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001003 Name.getAsIdentifierInfo(),
Douglas Gregor337caf92010-02-19 16:08:35 +00001004 ClassDeclared)) {
Douglas Gregor4a814562011-12-14 16:03:29 +00001005 if (NamedDecl *ND = R.getAcceptableDecl(Ivar)) {
1006 R.addDecl(ND);
Douglas Gregor337caf92010-02-19 16:08:35 +00001007 R.resolveKind();
1008 return true;
1009 }
1010 }
1011 }
1012 }
1013
1014 continue;
1015 }
1016
Douglas Gregorb0d0aa52013-03-27 12:51:49 +00001017 // If this is a file context, we need to perform unqualified name
1018 // lookup considering using directives.
1019 if (Ctx->isFileContext()) {
Douglas Gregorcc9406c2013-04-08 23:11:25 +00001020 // If we haven't handled using directives yet, do so now.
1021 if (!VisitedUsingDirectives) {
1022 // Add using directives from this context up to the top level.
Douglas Gregor8ccbc182013-04-09 01:49:26 +00001023 for (DeclContext *UCtx = Ctx; UCtx; UCtx = UCtx->getParent()) {
1024 if (UCtx->isTransparentContext())
1025 continue;
1026
Douglas Gregorcc9406c2013-04-08 23:11:25 +00001027 UDirs.visit(UCtx, UCtx);
Douglas Gregor8ccbc182013-04-09 01:49:26 +00001028 }
Douglas Gregorcc9406c2013-04-08 23:11:25 +00001029
1030 // Find the innermost file scope, so we can add using directives
1031 // from local scopes.
1032 Scope *InnermostFileScope = S;
1033 while (InnermostFileScope &&
1034 !isNamespaceOrTranslationUnitScope(InnermostFileScope))
1035 InnermostFileScope = InnermostFileScope->getParent();
1036 UDirs.visitScopeChain(Initial, InnermostFileScope);
1037
1038 UDirs.done();
1039
1040 VisitedUsingDirectives = true;
1041 }
Douglas Gregorb0d0aa52013-03-27 12:51:49 +00001042
1043 if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs)) {
1044 R.resolveKind();
1045 return true;
1046 }
1047
1048 continue;
1049 }
1050
Douglas Gregor7f737c02009-09-10 16:57:35 +00001051 // Perform qualified name lookup into this context.
1052 // FIXME: In some cases, we know that every name that could be found by
1053 // this qualified name lookup will also be on the identifier chain. For
1054 // example, inside a class without any base classes, we never need to
1055 // perform qualified lookup because all of the members are on top of the
1056 // identifier chain.
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001057 if (LookupQualifiedName(R, Ctx, /*InUnqualifiedLookup=*/true))
John McCall9f3059a2009-10-09 21:13:30 +00001058 return true;
Douglas Gregorfdca4a72009-03-27 04:21:56 +00001059 }
Douglas Gregor700792c2009-02-05 19:25:20 +00001060 }
Douglas Gregored8f2882009-01-30 01:04:22 +00001061 }
Douglas Gregor889ceb72009-02-03 19:21:40 +00001062
John McCallf6c8a4e2009-11-10 07:01:13 +00001063 // Stop if we ran out of scopes.
1064 // FIXME: This really, really shouldn't be happening.
1065 if (!S) return false;
1066
Argyrios Kyrtzidis706bbf82010-10-29 16:12:50 +00001067 // If we are looking for members, no need to look into global/namespace scope.
Richard Smith1c34fb72013-08-13 18:18:50 +00001068 if (NameKind == LookupMemberName)
Argyrios Kyrtzidis706bbf82010-10-29 16:12:50 +00001069 return false;
1070
Douglas Gregor700792c2009-02-05 19:25:20 +00001071 // Collect UsingDirectiveDecls in all scopes, and recursively all
Douglas Gregor889ceb72009-02-03 19:21:40 +00001072 // nominated namespaces by those using-directives.
John McCallf6c8a4e2009-11-10 07:01:13 +00001073 //
Mike Stump87c57ac2009-05-16 07:39:55 +00001074 // FIXME: Cache this sorted list in Scope structure, and DeclContext, so we
1075 // don't build it for each lookup!
Douglas Gregorcc9406c2013-04-08 23:11:25 +00001076 if (!VisitedUsingDirectives) {
1077 UDirs.visitScopeChain(Initial, S);
1078 UDirs.done();
1079 }
Richard Smith541b38b2013-09-20 01:15:31 +00001080
1081 // If we're not performing redeclaration lookup, do not look for local
1082 // extern declarations outside of a function scope.
1083 if (!R.isForRedeclaration())
1084 FindLocals.restore();
1085
Douglas Gregor700792c2009-02-05 19:25:20 +00001086 // Lookup namespace scope, and global scope.
Douglas Gregor889ceb72009-02-03 19:21:40 +00001087 // Unqualified name lookup in C++ requires looking into scopes
1088 // that aren't strictly lexical, and therefore we walk through the
1089 // context as well as walking through the scopes.
1090 for (; S; S = S->getParent()) {
Douglas Gregor889ceb72009-02-03 19:21:40 +00001091 // Check whether the IdResolver has anything in this scope.
John McCall9f3059a2009-10-09 21:13:30 +00001092 bool Found = false;
John McCall48871652010-08-21 09:40:31 +00001093 for (; I != IEnd && S->isDeclScope(*I); ++I) {
Douglas Gregor4a814562011-12-14 16:03:29 +00001094 if (NamedDecl *ND = R.getAcceptableDecl(*I)) {
Douglas Gregor889ceb72009-02-03 19:21:40 +00001095 // We found something. Look for anything else in our scope
1096 // with this same name and in an acceptable identifier
1097 // namespace, so that we can construct an overload set if we
1098 // need to.
John McCall9f3059a2009-10-09 21:13:30 +00001099 Found = true;
Douglas Gregor4a814562011-12-14 16:03:29 +00001100 R.addDecl(ND);
Douglas Gregor889ceb72009-02-03 19:21:40 +00001101 }
1102 }
1103
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001104 if (Found && S->isTemplateParamScope()) {
John McCall9f3059a2009-10-09 21:13:30 +00001105 R.resolveKind();
1106 return true;
1107 }
1108
Ted Kremenekc37877d2013-10-08 17:08:03 +00001109 DeclContext *Ctx = S->getEntity();
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001110 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
1111 S->getParent() && !S->getParent()->isTemplateParamScope()) {
1112 // We've just searched the last template parameter scope and
Sylvestre Ledru830885c2012-07-23 08:59:39 +00001113 // found nothing, so look into the contexts between the
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001114 // lexical and semantic declaration contexts returned by
1115 // findOuterContext(). This implements the name lookup behavior
1116 // of C++ [temp.local]p8.
1117 Ctx = OutsideOfTemplateParamDC;
1118 OutsideOfTemplateParamDC = 0;
1119 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001120
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001121 if (Ctx) {
1122 DeclContext *OuterCtx;
1123 bool SearchAfterTemplateScope;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001124 std::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001125 if (SearchAfterTemplateScope)
1126 OutsideOfTemplateParamDC = OuterCtx;
1127
1128 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
1129 // We do not directly look into transparent contexts, since
1130 // those entities will be found in the nearest enclosing
1131 // non-transparent context.
1132 if (Ctx->isTransparentContext())
1133 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001134
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001135 // If we have a context, and it's not a context stashed in the
1136 // template parameter scope for an out-of-line definition, also
1137 // look into that context.
1138 if (!(Found && S && S->isTemplateParamScope())) {
1139 assert(Ctx->isFileContext() &&
1140 "We should have been looking only at file context here already.");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001141
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001142 // Look into context considering using-directives.
1143 if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs))
1144 Found = true;
1145 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001146
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001147 if (Found) {
1148 R.resolveKind();
1149 return true;
1150 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001151
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001152 if (R.isForRedeclaration() && !Ctx->isTransparentContext())
1153 return false;
1154 }
1155 }
1156
Douglas Gregor3ce74932010-02-05 07:07:10 +00001157 if (R.isForRedeclaration() && Ctx && !Ctx->isTransparentContext())
John McCall9f3059a2009-10-09 21:13:30 +00001158 return false;
Douglas Gregor700792c2009-02-05 19:25:20 +00001159 }
Douglas Gregor889ceb72009-02-03 19:21:40 +00001160
John McCall9f3059a2009-10-09 21:13:30 +00001161 return !R.empty();
Douglas Gregored8f2882009-01-30 01:04:22 +00001162}
1163
Richard Smith0e5d7b82013-07-25 23:08:39 +00001164/// \brief Find the declaration that a class temploid member specialization was
1165/// instantiated from, or the member itself if it is an explicit specialization.
1166static Decl *getInstantiatedFrom(Decl *D, MemberSpecializationInfo *MSInfo) {
1167 return MSInfo->isExplicitSpecialization() ? D : MSInfo->getInstantiatedFrom();
1168}
1169
1170/// \brief Find the module in which the given declaration was defined.
1171static Module *getDefiningModule(Decl *Entity) {
1172 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Entity)) {
1173 // If this function was instantiated from a template, the defining module is
1174 // the module containing the pattern.
1175 if (FunctionDecl *Pattern = FD->getTemplateInstantiationPattern())
1176 Entity = Pattern;
1177 } else if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Entity)) {
1178 // If it's a class template specialization, find the template or partial
1179 // specialization from which it was instantiated.
1180 if (ClassTemplateSpecializationDecl *SpecRD =
1181 dyn_cast<ClassTemplateSpecializationDecl>(RD)) {
1182 llvm::PointerUnion<ClassTemplateDecl*,
1183 ClassTemplatePartialSpecializationDecl*> From =
1184 SpecRD->getInstantiatedFrom();
1185 if (ClassTemplateDecl *FromTemplate = From.dyn_cast<ClassTemplateDecl*>())
1186 Entity = FromTemplate->getTemplatedDecl();
1187 else if (From)
1188 Entity = From.get<ClassTemplatePartialSpecializationDecl*>();
1189 // Otherwise, it's an explicit specialization.
1190 } else if (MemberSpecializationInfo *MSInfo =
1191 RD->getMemberSpecializationInfo())
1192 Entity = getInstantiatedFrom(RD, MSInfo);
1193 } else if (EnumDecl *ED = dyn_cast<EnumDecl>(Entity)) {
1194 if (MemberSpecializationInfo *MSInfo = ED->getMemberSpecializationInfo())
1195 Entity = getInstantiatedFrom(ED, MSInfo);
1196 } else if (VarDecl *VD = dyn_cast<VarDecl>(Entity)) {
1197 // FIXME: Map from variable template specializations back to the template.
1198 if (MemberSpecializationInfo *MSInfo = VD->getMemberSpecializationInfo())
1199 Entity = getInstantiatedFrom(VD, MSInfo);
1200 }
1201
1202 // Walk up to the containing context. That might also have been instantiated
1203 // from a template.
1204 DeclContext *Context = Entity->getDeclContext();
1205 if (Context->isFileContext())
1206 return Entity->getOwningModule();
1207 return getDefiningModule(cast<Decl>(Context));
1208}
1209
1210llvm::DenseSet<Module*> &Sema::getLookupModules() {
1211 unsigned N = ActiveTemplateInstantiations.size();
1212 for (unsigned I = ActiveTemplateInstantiationLookupModules.size();
1213 I != N; ++I) {
1214 Module *M = getDefiningModule(ActiveTemplateInstantiations[I].Entity);
1215 if (M && !LookupModulesCache.insert(M).second)
1216 M = 0;
1217 ActiveTemplateInstantiationLookupModules.push_back(M);
1218 }
1219 return LookupModulesCache;
1220}
1221
1222/// \brief Determine whether a declaration is visible to name lookup.
1223///
1224/// This routine determines whether the declaration D is visible in the current
1225/// lookup context, taking into account the current template instantiation
1226/// stack. During template instantiation, a declaration is visible if it is
1227/// visible from a module containing any entity on the template instantiation
1228/// path (by instantiating a template, you allow it to see the declarations that
1229/// your module can see, including those later on in your module).
1230bool LookupResult::isVisibleSlow(Sema &SemaRef, NamedDecl *D) {
1231 assert(D->isHidden() && !SemaRef.ActiveTemplateInstantiations.empty() &&
1232 "should not call this: not in slow case");
1233 Module *DeclModule = D->getOwningModule();
1234 assert(DeclModule && "hidden decl not from a module");
1235
1236 // Find the extra places where we need to look.
1237 llvm::DenseSet<Module*> &LookupModules = SemaRef.getLookupModules();
1238 if (LookupModules.empty())
1239 return false;
1240
1241 // If our lookup set contains the decl's module, it's visible.
1242 if (LookupModules.count(DeclModule))
1243 return true;
1244
1245 // If the declaration isn't exported, it's not visible in any other module.
1246 if (D->isModulePrivate())
1247 return false;
1248
1249 // Check whether DeclModule is transitively exported to an import of
1250 // the lookup set.
1251 for (llvm::DenseSet<Module *>::iterator I = LookupModules.begin(),
1252 E = LookupModules.end();
1253 I != E; ++I)
1254 if ((*I)->isModuleVisible(DeclModule))
1255 return true;
1256 return false;
1257}
1258
Douglas Gregor4a814562011-12-14 16:03:29 +00001259/// \brief Retrieve the visible declaration corresponding to D, if any.
1260///
1261/// This routine determines whether the declaration D is visible in the current
1262/// module, with the current imports. If not, it checks whether any
1263/// redeclaration of D is visible, and if so, returns that declaration.
Richard Smith0e5d7b82013-07-25 23:08:39 +00001264///
Douglas Gregor4a814562011-12-14 16:03:29 +00001265/// \returns D, or a visible previous declaration of D, whichever is more recent
1266/// and visible. If no declaration of D is visible, returns null.
Richard Smithe156254d2013-08-20 20:35:18 +00001267static NamedDecl *findAcceptableDecl(Sema &SemaRef, NamedDecl *D) {
1268 assert(!LookupResult::isVisible(SemaRef, D) && "not in slow case");
Richard Smith0e5d7b82013-07-25 23:08:39 +00001269
Aaron Ballman86c93902014-03-06 23:45:36 +00001270 for (auto RD : D->redecls()) {
1271 if (auto ND = dyn_cast<NamedDecl>(RD)) {
Richard Smithe156254d2013-08-20 20:35:18 +00001272 if (LookupResult::isVisible(SemaRef, ND))
Douglas Gregor54079202012-01-06 22:05:37 +00001273 return ND;
1274 }
Douglas Gregor4a814562011-12-14 16:03:29 +00001275 }
Richard Smith0e5d7b82013-07-25 23:08:39 +00001276
Douglas Gregor4a814562011-12-14 16:03:29 +00001277 return 0;
1278}
1279
Richard Smithe156254d2013-08-20 20:35:18 +00001280NamedDecl *LookupResult::getAcceptableDeclSlow(NamedDecl *D) const {
1281 return findAcceptableDecl(SemaRef, D);
1282}
1283
Douglas Gregor34074322009-01-14 22:20:51 +00001284/// @brief Perform unqualified name lookup starting from a given
1285/// scope.
1286///
1287/// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is
1288/// used to find names within the current scope. For example, 'x' in
1289/// @code
1290/// int x;
1291/// int f() {
1292/// return x; // unqualified name look finds 'x' in the global scope
1293/// }
1294/// @endcode
1295///
1296/// Different lookup criteria can find different names. For example, a
1297/// particular scope can have both a struct and a function of the same
1298/// name, and each can be found by certain lookup criteria. For more
1299/// information about lookup criteria, see the documentation for the
1300/// class LookupCriteria.
1301///
1302/// @param S The scope from which unqualified name lookup will
1303/// begin. If the lookup criteria permits, name lookup may also search
1304/// in the parent scopes.
1305///
James Dennett91738ff2012-06-22 10:32:46 +00001306/// @param [in,out] R Specifies the lookup to perform (e.g., the name to
1307/// look up and the lookup kind), and is updated with the results of lookup
1308/// including zero or more declarations and possibly additional information
1309/// used to diagnose ambiguities.
Douglas Gregor34074322009-01-14 22:20:51 +00001310///
James Dennett91738ff2012-06-22 10:32:46 +00001311/// @returns \c true if lookup succeeded and false otherwise.
John McCall27b18f82009-11-17 02:14:36 +00001312bool Sema::LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation) {
1313 DeclarationName Name = R.getLookupName();
John McCall9f3059a2009-10-09 21:13:30 +00001314 if (!Name) return false;
Douglas Gregor34074322009-01-14 22:20:51 +00001315
John McCall27b18f82009-11-17 02:14:36 +00001316 LookupNameKind NameKind = R.getLookupKind();
1317
David Blaikiebbafb8a2012-03-11 07:00:24 +00001318 if (!getLangOpts().CPlusPlus) {
Douglas Gregor34074322009-01-14 22:20:51 +00001319 // Unqualified name lookup in C/Objective-C is purely lexical, so
1320 // search in the declarations attached to the name.
John McCallea305ed2009-12-18 10:40:03 +00001321 if (NameKind == Sema::LookupRedeclarationWithLinkage) {
Douglas Gregoreddf4332009-02-24 20:03:32 +00001322 // Find the nearest non-transparent declaration scope.
1323 while (!(S->getFlags() & Scope::DeclScope) ||
Ted Kremenekc37877d2013-10-08 17:08:03 +00001324 (S->getEntity() && S->getEntity()->isTransparentContext()))
Douglas Gregoreddf4332009-02-24 20:03:32 +00001325 S = S->getParent();
Douglas Gregored8f2882009-01-30 01:04:22 +00001326 }
1327
Richard Smith541b38b2013-09-20 01:15:31 +00001328 // When performing a scope lookup, we want to find local extern decls.
1329 FindLocalExternScope FindLocals(R);
1330
Douglas Gregor34074322009-01-14 22:20:51 +00001331 // Scan up the scope chain looking for a decl that matches this
1332 // identifier that is in the appropriate namespace. This search
1333 // should not take long, as shadowing of names is uncommon, and
1334 // deep shadowing is extremely uncommon.
Douglas Gregoreddf4332009-02-24 20:03:32 +00001335 bool LeftStartingScope = false;
1336
Douglas Gregored8f2882009-01-30 01:04:22 +00001337 for (IdentifierResolver::iterator I = IdResolver.begin(Name),
Mike Stump11289f42009-09-09 15:08:12 +00001338 IEnd = IdResolver.end();
Douglas Gregored8f2882009-01-30 01:04:22 +00001339 I != IEnd; ++I)
Richard Smith0e5d7b82013-07-25 23:08:39 +00001340 if (NamedDecl *D = R.getAcceptableDecl(*I)) {
Douglas Gregoreddf4332009-02-24 20:03:32 +00001341 if (NameKind == LookupRedeclarationWithLinkage) {
1342 // Determine whether this (or a previous) declaration is
1343 // out-of-scope.
John McCall48871652010-08-21 09:40:31 +00001344 if (!LeftStartingScope && !S->isDeclScope(*I))
Douglas Gregoreddf4332009-02-24 20:03:32 +00001345 LeftStartingScope = true;
1346
1347 // If we found something outside of our starting scope that
1348 // does not have linkage, skip it.
Richard Smith1c34fb72013-08-13 18:18:50 +00001349 if (LeftStartingScope && !((*I)->hasLinkage())) {
1350 R.setShadowed();
Douglas Gregoreddf4332009-02-24 20:03:32 +00001351 continue;
Richard Smith1c34fb72013-08-13 18:18:50 +00001352 }
Douglas Gregoreddf4332009-02-24 20:03:32 +00001353 }
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00001354 else if (NameKind == LookupObjCImplicitSelfParam &&
1355 !isa<ImplicitParamDecl>(*I))
1356 continue;
Richard Smith0e5d7b82013-07-25 23:08:39 +00001357
Douglas Gregor4a814562011-12-14 16:03:29 +00001358 R.addDecl(D);
John McCall9f3059a2009-10-09 21:13:30 +00001359
Douglas Gregorb59643b2012-01-03 23:26:26 +00001360 // Check whether there are any other declarations with the same name
1361 // and in the same scope.
Douglas Gregor9b7b3912012-01-04 16:44:10 +00001362 if (I != IEnd) {
Douglas Gregor81bd0382012-01-13 23:06:53 +00001363 // Find the scope in which this declaration was declared (if it
1364 // actually exists in a Scope).
1365 while (S && !S->isDeclScope(D))
1366 S = S->getParent();
1367
1368 // If the scope containing the declaration is the translation unit,
1369 // then we'll need to perform our checks based on the matching
1370 // DeclContexts rather than matching scopes.
1371 if (S && isNamespaceOrTranslationUnitScope(S))
1372 S = 0;
1373
1374 // Compute the DeclContext, if we need it.
1375 DeclContext *DC = 0;
1376 if (!S)
1377 DC = (*I)->getDeclContext()->getRedeclContext();
1378
Douglas Gregor9b7b3912012-01-04 16:44:10 +00001379 IdentifierResolver::iterator LastI = I;
1380 for (++LastI; LastI != IEnd; ++LastI) {
Douglas Gregor81bd0382012-01-13 23:06:53 +00001381 if (S) {
1382 // Match based on scope.
1383 if (!S->isDeclScope(*LastI))
1384 break;
1385 } else {
1386 // Match based on DeclContext.
1387 DeclContext *LastDC
1388 = (*LastI)->getDeclContext()->getRedeclContext();
1389 if (!LastDC->Equals(DC))
1390 break;
1391 }
Richard Smith0e5d7b82013-07-25 23:08:39 +00001392
1393 // If the declaration is in the right namespace and visible, add it.
1394 if (NamedDecl *LastD = R.getAcceptableDecl(*LastI))
1395 R.addDecl(LastD);
Douglas Gregor9b7b3912012-01-04 16:44:10 +00001396 }
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001397
Douglas Gregor9b7b3912012-01-04 16:44:10 +00001398 R.resolveKind();
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001399 }
Richard Smith541b38b2013-09-20 01:15:31 +00001400
John McCall9f3059a2009-10-09 21:13:30 +00001401 return true;
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001402 }
Douglas Gregor34074322009-01-14 22:20:51 +00001403 } else {
Douglas Gregor889ceb72009-02-03 19:21:40 +00001404 // Perform C++ unqualified name lookup.
John McCall27b18f82009-11-17 02:14:36 +00001405 if (CppLookupName(R, S))
John McCall9f3059a2009-10-09 21:13:30 +00001406 return true;
Douglas Gregor34074322009-01-14 22:20:51 +00001407 }
1408
1409 // If we didn't find a use of this identifier, and if the identifier
1410 // corresponds to a compiler builtin, create the decl object for the builtin
1411 // now, injecting it into translation unit scope, and return it.
Axel Naumann43dec142011-04-13 13:19:46 +00001412 if (AllowBuiltinCreation && LookupBuiltin(*this, R))
1413 return true;
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001414
Axel Naumann016538a2011-02-24 16:47:47 +00001415 // If we didn't find a use of this identifier, the ExternalSource
1416 // may be able to handle the situation.
1417 // Note: some lookup failures are expected!
1418 // See e.g. R.isForRedeclaration().
1419 return (ExternalSource && ExternalSource->LookupUnqualified(R, S));
Douglas Gregor34074322009-01-14 22:20:51 +00001420}
1421
John McCall6538c932009-10-10 05:48:19 +00001422/// @brief Perform qualified name lookup in the namespaces nominated by
1423/// using directives by the given context.
1424///
1425/// C++98 [namespace.qual]p2:
James Dennett51a8d8b2012-06-19 21:05:49 +00001426/// Given X::m (where X is a user-declared namespace), or given \::m
John McCall6538c932009-10-10 05:48:19 +00001427/// (where X is the global namespace), let S be the set of all
1428/// declarations of m in X and in the transitive closure of all
1429/// namespaces nominated by using-directives in X and its used
1430/// namespaces, except that using-directives are ignored in any
1431/// namespace, including X, directly containing one or more
1432/// declarations of m. No namespace is searched more than once in
1433/// the lookup of a name. If S is the empty set, the program is
1434/// ill-formed. Otherwise, if S has exactly one member, or if the
1435/// context of the reference is a using-declaration
1436/// (namespace.udecl), S is the required set of declarations of
1437/// m. Otherwise if the use of m is not one that allows a unique
1438/// declaration to be chosen from S, the program is ill-formed.
James Dennett51a8d8b2012-06-19 21:05:49 +00001439///
John McCall6538c932009-10-10 05:48:19 +00001440/// C++98 [namespace.qual]p5:
1441/// During the lookup of a qualified namespace member name, if the
1442/// lookup finds more than one declaration of the member, and if one
1443/// declaration introduces a class name or enumeration name and the
1444/// other declarations either introduce the same object, the same
1445/// enumerator or a set of functions, the non-type name hides the
1446/// class or enumeration name if and only if the declarations are
1447/// from the same namespace; otherwise (the declarations are from
1448/// different namespaces), the program is ill-formed.
Douglas Gregord3a59182010-02-12 05:48:04 +00001449static bool LookupQualifiedNameInUsingDirectives(Sema &S, LookupResult &R,
John McCall27b18f82009-11-17 02:14:36 +00001450 DeclContext *StartDC) {
John McCall6538c932009-10-10 05:48:19 +00001451 assert(StartDC->isFileContext() && "start context is not a file context");
1452
1453 DeclContext::udir_iterator I = StartDC->using_directives_begin();
1454 DeclContext::udir_iterator E = StartDC->using_directives_end();
1455
1456 if (I == E) return false;
1457
1458 // We have at least added all these contexts to the queue.
Benjamin Kramer3adbe1c2012-02-23 16:06:01 +00001459 llvm::SmallPtrSet<DeclContext*, 8> Visited;
John McCall6538c932009-10-10 05:48:19 +00001460 Visited.insert(StartDC);
1461
1462 // We have not yet looked into these namespaces, much less added
1463 // their "using-children" to the queue.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001464 SmallVector<NamespaceDecl*, 8> Queue;
John McCall6538c932009-10-10 05:48:19 +00001465
1466 // We have already looked into the initial namespace; seed the queue
1467 // with its using-children.
1468 for (; I != E; ++I) {
John McCallb8be78b2009-11-10 09:25:37 +00001469 NamespaceDecl *ND = (*I)->getNominatedNamespace()->getOriginalNamespace();
Benjamin Kramer3adbe1c2012-02-23 16:06:01 +00001470 if (Visited.insert(ND))
John McCall6538c932009-10-10 05:48:19 +00001471 Queue.push_back(ND);
1472 }
1473
1474 // The easiest way to implement the restriction in [namespace.qual]p5
1475 // is to check whether any of the individual results found a tag
1476 // and, if so, to declare an ambiguity if the final result is not
1477 // a tag.
1478 bool FoundTag = false;
1479 bool FoundNonTag = false;
1480
John McCall5cebab12009-11-18 07:57:50 +00001481 LookupResult LocalR(LookupResult::Temporary, R);
John McCall6538c932009-10-10 05:48:19 +00001482
1483 bool Found = false;
1484 while (!Queue.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00001485 NamespaceDecl *ND = Queue.pop_back_val();
John McCall6538c932009-10-10 05:48:19 +00001486
1487 // We go through some convolutions here to avoid copying results
1488 // between LookupResults.
1489 bool UseLocal = !R.empty();
John McCall5cebab12009-11-18 07:57:50 +00001490 LookupResult &DirectR = UseLocal ? LocalR : R;
Douglas Gregord3a59182010-02-12 05:48:04 +00001491 bool FoundDirect = LookupDirect(S, DirectR, ND);
John McCall6538c932009-10-10 05:48:19 +00001492
1493 if (FoundDirect) {
1494 // First do any local hiding.
1495 DirectR.resolveKind();
1496
1497 // If the local result is a tag, remember that.
1498 if (DirectR.isSingleTagDecl())
1499 FoundTag = true;
1500 else
1501 FoundNonTag = true;
1502
1503 // Append the local results to the total results if necessary.
1504 if (UseLocal) {
1505 R.addAllDecls(LocalR);
1506 LocalR.clear();
1507 }
1508 }
1509
1510 // If we find names in this namespace, ignore its using directives.
1511 if (FoundDirect) {
1512 Found = true;
1513 continue;
1514 }
1515
Aaron Ballman63ab7602014-03-07 13:44:44 +00001516 for (auto I : ND->getUsingDirectives()) {
1517 NamespaceDecl *Nom = I->getNominatedNamespace();
Benjamin Kramer3adbe1c2012-02-23 16:06:01 +00001518 if (Visited.insert(Nom))
John McCall6538c932009-10-10 05:48:19 +00001519 Queue.push_back(Nom);
1520 }
1521 }
1522
1523 if (Found) {
1524 if (FoundTag && FoundNonTag)
1525 R.setAmbiguousQualifiedTagHiding();
1526 else
1527 R.resolveKind();
1528 }
1529
1530 return Found;
1531}
1532
Douglas Gregor39982192010-08-15 06:18:01 +00001533/// \brief Callback that looks for any member of a class with the given name.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001534static bool LookupAnyMember(const CXXBaseSpecifier *Specifier,
Douglas Gregor39982192010-08-15 06:18:01 +00001535 CXXBasePath &Path,
1536 void *Name) {
1537 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001538
Douglas Gregor39982192010-08-15 06:18:01 +00001539 DeclarationName N = DeclarationName::getFromOpaquePtr(Name);
1540 Path.Decls = BaseRecord->lookup(N);
David Blaikieff7d47a2012-12-19 00:45:41 +00001541 return !Path.Decls.empty();
Douglas Gregor39982192010-08-15 06:18:01 +00001542}
1543
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001544/// \brief Determine whether the given set of member declarations contains only
Douglas Gregorc0d24902010-10-22 22:08:47 +00001545/// static members, nested types, and enumerators.
1546template<typename InputIterator>
1547static bool HasOnlyStaticMembers(InputIterator First, InputIterator Last) {
1548 Decl *D = (*First)->getUnderlyingDecl();
1549 if (isa<VarDecl>(D) || isa<TypeDecl>(D) || isa<EnumConstantDecl>(D))
1550 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001551
Douglas Gregorc0d24902010-10-22 22:08:47 +00001552 if (isa<CXXMethodDecl>(D)) {
1553 // Determine whether all of the methods are static.
1554 bool AllMethodsAreStatic = true;
1555 for(; First != Last; ++First) {
1556 D = (*First)->getUnderlyingDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001557
Douglas Gregorc0d24902010-10-22 22:08:47 +00001558 if (!isa<CXXMethodDecl>(D)) {
1559 assert(isa<TagDecl>(D) && "Non-function must be a tag decl");
1560 break;
1561 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001562
Douglas Gregorc0d24902010-10-22 22:08:47 +00001563 if (!cast<CXXMethodDecl>(D)->isStatic()) {
1564 AllMethodsAreStatic = false;
1565 break;
1566 }
1567 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001568
Douglas Gregorc0d24902010-10-22 22:08:47 +00001569 if (AllMethodsAreStatic)
1570 return true;
1571 }
1572
1573 return false;
1574}
1575
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001576/// \brief Perform qualified name lookup into a given context.
Douglas Gregor34074322009-01-14 22:20:51 +00001577///
1578/// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
1579/// names when the context of those names is explicit specified, e.g.,
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001580/// "std::vector" or "x->member", or as part of unqualified name lookup.
Douglas Gregor34074322009-01-14 22:20:51 +00001581///
1582/// Different lookup criteria can find different names. For example, a
1583/// particular scope can have both a struct and a function of the same
1584/// name, and each can be found by certain lookup criteria. For more
1585/// information about lookup criteria, see the documentation for the
1586/// class LookupCriteria.
1587///
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001588/// \param R captures both the lookup criteria and any lookup results found.
1589///
1590/// \param LookupCtx The context in which qualified name lookup will
Douglas Gregor34074322009-01-14 22:20:51 +00001591/// search. If the lookup criteria permits, name lookup may also search
1592/// in the parent contexts or (for C++ classes) base classes.
1593///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001594/// \param InUnqualifiedLookup true if this is qualified name lookup that
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001595/// occurs as part of unqualified name lookup.
Douglas Gregor34074322009-01-14 22:20:51 +00001596///
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001597/// \returns true if lookup succeeded, false if it failed.
1598bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
1599 bool InUnqualifiedLookup) {
Douglas Gregor34074322009-01-14 22:20:51 +00001600 assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context");
Mike Stump11289f42009-09-09 15:08:12 +00001601
John McCall27b18f82009-11-17 02:14:36 +00001602 if (!R.getLookupName())
John McCall9f3059a2009-10-09 21:13:30 +00001603 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001604
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001605 // Make sure that the declaration context is complete.
1606 assert((!isa<TagDecl>(LookupCtx) ||
1607 LookupCtx->isDependentContext() ||
John McCallf937c022011-10-07 06:10:15 +00001608 cast<TagDecl>(LookupCtx)->isCompleteDefinition() ||
Richard Smith7d137e32012-03-23 03:33:32 +00001609 cast<TagDecl>(LookupCtx)->isBeingDefined()) &&
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001610 "Declaration context must already be complete!");
Mike Stump11289f42009-09-09 15:08:12 +00001611
Douglas Gregor34074322009-01-14 22:20:51 +00001612 // Perform qualified name lookup into the LookupCtx.
Douglas Gregord3a59182010-02-12 05:48:04 +00001613 if (LookupDirect(*this, R, LookupCtx)) {
John McCall9f3059a2009-10-09 21:13:30 +00001614 R.resolveKind();
John McCall553c0792010-01-23 00:46:32 +00001615 if (isa<CXXRecordDecl>(LookupCtx))
1616 R.setNamingClass(cast<CXXRecordDecl>(LookupCtx));
John McCall9f3059a2009-10-09 21:13:30 +00001617 return true;
1618 }
Douglas Gregor34074322009-01-14 22:20:51 +00001619
John McCall6538c932009-10-10 05:48:19 +00001620 // Don't descend into implied contexts for redeclarations.
1621 // C++98 [namespace.qual]p6:
1622 // In a declaration for a namespace member in which the
1623 // declarator-id is a qualified-id, given that the qualified-id
1624 // for the namespace member has the form
1625 // nested-name-specifier unqualified-id
1626 // the unqualified-id shall name a member of the namespace
1627 // designated by the nested-name-specifier.
1628 // See also [class.mfct]p5 and [class.static.data]p2.
John McCall27b18f82009-11-17 02:14:36 +00001629 if (R.isForRedeclaration())
John McCall6538c932009-10-10 05:48:19 +00001630 return false;
1631
John McCall27b18f82009-11-17 02:14:36 +00001632 // If this is a namespace, look it up in the implied namespaces.
John McCall6538c932009-10-10 05:48:19 +00001633 if (LookupCtx->isFileContext())
Douglas Gregord3a59182010-02-12 05:48:04 +00001634 return LookupQualifiedNameInUsingDirectives(*this, R, LookupCtx);
John McCall6538c932009-10-10 05:48:19 +00001635
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001636 // If this isn't a C++ class, we aren't allowed to look into base
Douglas Gregorcc2427c2009-09-11 22:57:37 +00001637 // classes, we're done.
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001638 CXXRecordDecl *LookupRec = dyn_cast<CXXRecordDecl>(LookupCtx);
Douglas Gregor5a5fcd82010-07-01 00:21:21 +00001639 if (!LookupRec || !LookupRec->getDefinition())
John McCall9f3059a2009-10-09 21:13:30 +00001640 return false;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001641
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001642 // If we're performing qualified name lookup into a dependent class,
1643 // then we are actually looking into a current instantiation. If we have any
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001644 // dependent base classes, then we either have to delay lookup until
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001645 // template instantiation time (at which point all bases will be available)
1646 // or we have to fail.
1647 if (!InUnqualifiedLookup && LookupRec->isDependentContext() &&
1648 LookupRec->hasAnyDependentBases()) {
1649 R.setNotFoundInCurrentInstantiation();
1650 return false;
1651 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001652
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001653 // Perform lookup into our base classes.
Douglas Gregor36d1b142009-10-06 17:59:45 +00001654 CXXBasePaths Paths;
1655 Paths.setOrigin(LookupRec);
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001656
1657 // Look for this member in our base classes
Douglas Gregor36d1b142009-10-06 17:59:45 +00001658 CXXRecordDecl::BaseMatchesCallback *BaseCallback = 0;
John McCall27b18f82009-11-17 02:14:36 +00001659 switch (R.getLookupKind()) {
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00001660 case LookupObjCImplicitSelfParam:
Douglas Gregor36d1b142009-10-06 17:59:45 +00001661 case LookupOrdinaryName:
1662 case LookupMemberName:
1663 case LookupRedeclarationWithLinkage:
Richard Smith114394f2013-08-09 04:35:01 +00001664 case LookupLocalFriendName:
Douglas Gregor36d1b142009-10-06 17:59:45 +00001665 BaseCallback = &CXXRecordDecl::FindOrdinaryMember;
1666 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001667
Douglas Gregor36d1b142009-10-06 17:59:45 +00001668 case LookupTagName:
1669 BaseCallback = &CXXRecordDecl::FindTagMember;
1670 break;
John McCall84d87672009-12-10 09:41:52 +00001671
Douglas Gregor39982192010-08-15 06:18:01 +00001672 case LookupAnyName:
1673 BaseCallback = &LookupAnyMember;
1674 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001675
John McCall84d87672009-12-10 09:41:52 +00001676 case LookupUsingDeclName:
1677 // This lookup is for redeclarations only.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001678
Douglas Gregor36d1b142009-10-06 17:59:45 +00001679 case LookupOperatorName:
1680 case LookupNamespaceName:
1681 case LookupObjCProtocolName:
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001682 case LookupLabel:
Douglas Gregor36d1b142009-10-06 17:59:45 +00001683 // These lookups will never find a member in a C++ class (or base class).
John McCall9f3059a2009-10-09 21:13:30 +00001684 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001685
Douglas Gregor36d1b142009-10-06 17:59:45 +00001686 case LookupNestedNameSpecifierName:
1687 BaseCallback = &CXXRecordDecl::FindNestedNameSpecifierMember;
1688 break;
1689 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001690
John McCall27b18f82009-11-17 02:14:36 +00001691 if (!LookupRec->lookupInBases(BaseCallback,
1692 R.getLookupName().getAsOpaquePtr(), Paths))
John McCall9f3059a2009-10-09 21:13:30 +00001693 return false;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001694
John McCall553c0792010-01-23 00:46:32 +00001695 R.setNamingClass(LookupRec);
1696
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001697 // C++ [class.member.lookup]p2:
1698 // [...] If the resulting set of declarations are not all from
1699 // sub-objects of the same type, or the set has a nonstatic member
1700 // and includes members from distinct sub-objects, there is an
1701 // ambiguity and the program is ill-formed. Otherwise that set is
1702 // the result of the lookup.
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001703 QualType SubobjectType;
Daniel Dunbar435bbe02009-01-15 18:32:35 +00001704 int SubobjectNumber = 0;
John McCalla332b952010-03-18 23:49:19 +00001705 AccessSpecifier SubobjectAccess = AS_none;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001706
Douglas Gregor36d1b142009-10-06 17:59:45 +00001707 for (CXXBasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end();
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001708 Path != PathEnd; ++Path) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00001709 const CXXBasePathElement &PathElement = Path->back();
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001710
John McCall401982f2010-01-20 21:53:11 +00001711 // Pick the best (i.e. most permissive i.e. numerically lowest) access
1712 // across all paths.
1713 SubobjectAccess = std::min(SubobjectAccess, Path->Access);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001714
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001715 // Determine whether we're looking at a distinct sub-object or not.
1716 if (SubobjectType.isNull()) {
John McCall9f3059a2009-10-09 21:13:30 +00001717 // This is the first subobject we've looked at. Record its type.
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001718 SubobjectType = Context.getCanonicalType(PathElement.Base->getType());
1719 SubobjectNumber = PathElement.SubobjectNumber;
Douglas Gregorc0d24902010-10-22 22:08:47 +00001720 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001721 }
1722
Douglas Gregorc0d24902010-10-22 22:08:47 +00001723 if (SubobjectType
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001724 != Context.getCanonicalType(PathElement.Base->getType())) {
1725 // We found members of the given name in two subobjects of
Douglas Gregorc0d24902010-10-22 22:08:47 +00001726 // different types. If the declaration sets aren't the same, this
1727 // this lookup is ambiguous.
David Blaikieff7d47a2012-12-19 00:45:41 +00001728 if (HasOnlyStaticMembers(Path->Decls.begin(), Path->Decls.end())) {
Douglas Gregorc0d24902010-10-22 22:08:47 +00001729 CXXBasePaths::paths_iterator FirstPath = Paths.begin();
David Blaikieff7d47a2012-12-19 00:45:41 +00001730 DeclContext::lookup_iterator FirstD = FirstPath->Decls.begin();
1731 DeclContext::lookup_iterator CurrentD = Path->Decls.begin();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001732
David Blaikieff7d47a2012-12-19 00:45:41 +00001733 while (FirstD != FirstPath->Decls.end() &&
1734 CurrentD != Path->Decls.end()) {
Douglas Gregorc0d24902010-10-22 22:08:47 +00001735 if ((*FirstD)->getUnderlyingDecl()->getCanonicalDecl() !=
1736 (*CurrentD)->getUnderlyingDecl()->getCanonicalDecl())
1737 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001738
Douglas Gregorc0d24902010-10-22 22:08:47 +00001739 ++FirstD;
1740 ++CurrentD;
1741 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001742
David Blaikieff7d47a2012-12-19 00:45:41 +00001743 if (FirstD == FirstPath->Decls.end() &&
1744 CurrentD == Path->Decls.end())
Douglas Gregorc0d24902010-10-22 22:08:47 +00001745 continue;
1746 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001747
John McCall9f3059a2009-10-09 21:13:30 +00001748 R.setAmbiguousBaseSubobjectTypes(Paths);
1749 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001750 }
1751
Douglas Gregorc0d24902010-10-22 22:08:47 +00001752 if (SubobjectNumber != PathElement.SubobjectNumber) {
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001753 // We have a different subobject of the same type.
1754
1755 // C++ [class.member.lookup]p5:
1756 // A static member, a nested type or an enumerator defined in
1757 // a base class T can unambiguously be found even if an object
Mike Stump11289f42009-09-09 15:08:12 +00001758 // has more than one base class subobject of type T.
David Blaikieff7d47a2012-12-19 00:45:41 +00001759 if (HasOnlyStaticMembers(Path->Decls.begin(), Path->Decls.end()))
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001760 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001761
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001762 // We have found a nonstatic member name in multiple, distinct
1763 // subobjects. Name lookup is ambiguous.
John McCall9f3059a2009-10-09 21:13:30 +00001764 R.setAmbiguousBaseSubobjects(Paths);
1765 return true;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001766 }
1767 }
1768
1769 // Lookup in a base class succeeded; return these results.
1770
David Blaikieff7d47a2012-12-19 00:45:41 +00001771 DeclContext::lookup_result DR = Paths.front().Decls;
1772 for (DeclContext::lookup_iterator I = DR.begin(), E = DR.end(); I != E; ++I) {
John McCall553c0792010-01-23 00:46:32 +00001773 NamedDecl *D = *I;
1774 AccessSpecifier AS = CXXRecordDecl::MergeAccess(SubobjectAccess,
1775 D->getAccess());
1776 R.addDecl(D, AS);
1777 }
John McCall9f3059a2009-10-09 21:13:30 +00001778 R.resolveKind();
1779 return true;
Douglas Gregor34074322009-01-14 22:20:51 +00001780}
1781
1782/// @brief Performs name lookup for a name that was parsed in the
1783/// source code, and may contain a C++ scope specifier.
1784///
1785/// This routine is a convenience routine meant to be called from
1786/// contexts that receive a name and an optional C++ scope specifier
1787/// (e.g., "N::M::x"). It will then perform either qualified or
1788/// unqualified name lookup (with LookupQualifiedName or LookupName,
1789/// respectively) on the given name and return those results.
1790///
1791/// @param S The scope from which unqualified name lookup will
1792/// begin.
Mike Stump11289f42009-09-09 15:08:12 +00001793///
Douglas Gregore861bac2009-08-25 22:51:20 +00001794/// @param SS An optional C++ scope-specifier, e.g., "::N::M".
Douglas Gregor34074322009-01-14 22:20:51 +00001795///
Douglas Gregore861bac2009-08-25 22:51:20 +00001796/// @param EnteringContext Indicates whether we are going to enter the
1797/// context of the scope-specifier SS (if present).
1798///
John McCall9f3059a2009-10-09 21:13:30 +00001799/// @returns True if any decls were found (but possibly ambiguous)
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001800bool Sema::LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
John McCall27b18f82009-11-17 02:14:36 +00001801 bool AllowBuiltinCreation, bool EnteringContext) {
Douglas Gregore861bac2009-08-25 22:51:20 +00001802 if (SS && SS->isInvalid()) {
1803 // When the scope specifier is invalid, don't even look for
Douglas Gregorc9f9b862009-05-11 19:58:34 +00001804 // anything.
John McCall9f3059a2009-10-09 21:13:30 +00001805 return false;
Douglas Gregore861bac2009-08-25 22:51:20 +00001806 }
Mike Stump11289f42009-09-09 15:08:12 +00001807
Douglas Gregore861bac2009-08-25 22:51:20 +00001808 if (SS && SS->isSet()) {
1809 if (DeclContext *DC = computeDeclContext(*SS, EnteringContext)) {
Mike Stump11289f42009-09-09 15:08:12 +00001810 // We have resolved the scope specifier to a particular declaration
Douglas Gregore861bac2009-08-25 22:51:20 +00001811 // contex, and will perform name lookup in that context.
John McCall0b66eb32010-05-01 00:40:08 +00001812 if (!DC->isDependentContext() && RequireCompleteDeclContext(*SS, DC))
John McCall9f3059a2009-10-09 21:13:30 +00001813 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001814
John McCall27b18f82009-11-17 02:14:36 +00001815 R.setContextRange(SS->getRange());
John McCall27b18f82009-11-17 02:14:36 +00001816 return LookupQualifiedName(R, DC);
Douglas Gregor52537682009-03-19 00:18:19 +00001817 }
Douglas Gregorc9f9b862009-05-11 19:58:34 +00001818
Douglas Gregore861bac2009-08-25 22:51:20 +00001819 // We could not resolve the scope specified to a specific declaration
Mike Stump11289f42009-09-09 15:08:12 +00001820 // context, which means that SS refers to an unknown specialization.
Douglas Gregore861bac2009-08-25 22:51:20 +00001821 // Name lookup can't find anything in this case.
Douglas Gregor89ab56d2011-10-24 22:24:50 +00001822 R.setNotFoundInCurrentInstantiation();
1823 R.setContextRange(SS->getRange());
John McCall9f3059a2009-10-09 21:13:30 +00001824 return false;
Douglas Gregored8f2882009-01-30 01:04:22 +00001825 }
1826
Mike Stump11289f42009-09-09 15:08:12 +00001827 // Perform unqualified name lookup starting in the given scope.
John McCall27b18f82009-11-17 02:14:36 +00001828 return LookupName(R, S, AllowBuiltinCreation);
Douglas Gregor34074322009-01-14 22:20:51 +00001829}
1830
Douglas Gregor889ceb72009-02-03 19:21:40 +00001831
James Dennett41725122012-06-22 10:16:05 +00001832/// \brief Produce a diagnostic describing the ambiguity that resulted
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001833/// from name lookup.
1834///
James Dennett41725122012-06-22 10:16:05 +00001835/// \param Result The result of the ambiguous lookup to be diagnosed.
Serge Pavlov99292092013-08-29 07:23:24 +00001836void Sema::DiagnoseAmbiguousLookup(LookupResult &Result) {
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001837 assert(Result.isAmbiguous() && "Lookup result must be ambiguous");
1838
John McCall27b18f82009-11-17 02:14:36 +00001839 DeclarationName Name = Result.getLookupName();
1840 SourceLocation NameLoc = Result.getNameLoc();
1841 SourceRange LookupRange = Result.getContextRange();
1842
John McCall6538c932009-10-10 05:48:19 +00001843 switch (Result.getAmbiguityKind()) {
1844 case LookupResult::AmbiguousBaseSubobjects: {
1845 CXXBasePaths *Paths = Result.getBasePaths();
1846 QualType SubobjectType = Paths->front().back().Base->getType();
1847 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects)
1848 << Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths)
1849 << LookupRange;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001850
David Blaikieff7d47a2012-12-19 00:45:41 +00001851 DeclContext::lookup_iterator Found = Paths->front().Decls.begin();
John McCall6538c932009-10-10 05:48:19 +00001852 while (isa<CXXMethodDecl>(*Found) &&
1853 cast<CXXMethodDecl>(*Found)->isStatic())
1854 ++Found;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001855
John McCall6538c932009-10-10 05:48:19 +00001856 Diag((*Found)->getLocation(), diag::note_ambiguous_member_found);
Serge Pavlov99292092013-08-29 07:23:24 +00001857 break;
John McCall6538c932009-10-10 05:48:19 +00001858 }
Douglas Gregor1c846b02009-01-16 00:38:09 +00001859
John McCall6538c932009-10-10 05:48:19 +00001860 case LookupResult::AmbiguousBaseSubobjectTypes: {
Douglas Gregor889ceb72009-02-03 19:21:40 +00001861 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types)
1862 << Name << LookupRange;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001863
John McCall6538c932009-10-10 05:48:19 +00001864 CXXBasePaths *Paths = Result.getBasePaths();
Douglas Gregor889ceb72009-02-03 19:21:40 +00001865 std::set<Decl *> DeclsPrinted;
John McCall6538c932009-10-10 05:48:19 +00001866 for (CXXBasePaths::paths_iterator Path = Paths->begin(),
1867 PathEnd = Paths->end();
Douglas Gregor889ceb72009-02-03 19:21:40 +00001868 Path != PathEnd; ++Path) {
David Blaikieff7d47a2012-12-19 00:45:41 +00001869 Decl *D = Path->Decls.front();
Douglas Gregor889ceb72009-02-03 19:21:40 +00001870 if (DeclsPrinted.insert(D).second)
1871 Diag(D->getLocation(), diag::note_ambiguous_member_found);
1872 }
Serge Pavlov99292092013-08-29 07:23:24 +00001873 break;
Douglas Gregor1c846b02009-01-16 00:38:09 +00001874 }
1875
John McCall6538c932009-10-10 05:48:19 +00001876 case LookupResult::AmbiguousTagHiding: {
1877 Diag(NameLoc, diag::err_ambiguous_tag_hiding) << Name << LookupRange;
Douglas Gregorf23311d2009-01-17 01:13:24 +00001878
John McCall6538c932009-10-10 05:48:19 +00001879 llvm::SmallPtrSet<NamedDecl*,8> TagDecls;
1880
1881 LookupResult::iterator DI, DE = Result.end();
1882 for (DI = Result.begin(); DI != DE; ++DI)
1883 if (TagDecl *TD = dyn_cast<TagDecl>(*DI)) {
1884 TagDecls.insert(TD);
1885 Diag(TD->getLocation(), diag::note_hidden_tag);
1886 }
1887
1888 for (DI = Result.begin(); DI != DE; ++DI)
1889 if (!isa<TagDecl>(*DI))
1890 Diag((*DI)->getLocation(), diag::note_hiding_object);
1891
1892 // For recovery purposes, go ahead and implement the hiding.
John McCallad371252010-01-20 00:46:10 +00001893 LookupResult::Filter F = Result.makeFilter();
1894 while (F.hasNext()) {
1895 if (TagDecls.count(F.next()))
1896 F.erase();
1897 }
1898 F.done();
Serge Pavlov99292092013-08-29 07:23:24 +00001899 break;
John McCall6538c932009-10-10 05:48:19 +00001900 }
1901
1902 case LookupResult::AmbiguousReference: {
1903 Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001904
John McCall6538c932009-10-10 05:48:19 +00001905 LookupResult::iterator DI = Result.begin(), DE = Result.end();
1906 for (; DI != DE; ++DI)
1907 Diag((*DI)->getLocation(), diag::note_ambiguous_candidate) << *DI;
Serge Pavlov99292092013-08-29 07:23:24 +00001908 break;
John McCall6538c932009-10-10 05:48:19 +00001909 }
Serge Pavlov99292092013-08-29 07:23:24 +00001910 }
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001911}
Douglas Gregore254f902009-02-04 00:32:51 +00001912
John McCallf24d7bb2010-05-28 18:45:08 +00001913namespace {
1914 struct AssociatedLookup {
John McCall7d8b0412012-08-24 20:38:34 +00001915 AssociatedLookup(Sema &S, SourceLocation InstantiationLoc,
John McCallf24d7bb2010-05-28 18:45:08 +00001916 Sema::AssociatedNamespaceSet &Namespaces,
1917 Sema::AssociatedClassSet &Classes)
John McCall7d8b0412012-08-24 20:38:34 +00001918 : S(S), Namespaces(Namespaces), Classes(Classes),
1919 InstantiationLoc(InstantiationLoc) {
John McCallf24d7bb2010-05-28 18:45:08 +00001920 }
1921
1922 Sema &S;
1923 Sema::AssociatedNamespaceSet &Namespaces;
1924 Sema::AssociatedClassSet &Classes;
John McCall7d8b0412012-08-24 20:38:34 +00001925 SourceLocation InstantiationLoc;
John McCallf24d7bb2010-05-28 18:45:08 +00001926 };
1927}
1928
Mike Stump11289f42009-09-09 15:08:12 +00001929static void
John McCallf24d7bb2010-05-28 18:45:08 +00001930addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType T);
John McCallc7e8e792009-08-07 22:18:02 +00001931
Douglas Gregor8b895222010-04-30 07:08:38 +00001932static void CollectEnclosingNamespace(Sema::AssociatedNamespaceSet &Namespaces,
1933 DeclContext *Ctx) {
1934 // Add the associated namespace for this class.
1935
1936 // We don't use DeclContext::getEnclosingNamespaceContext() as this may
1937 // be a locally scoped record.
1938
Sebastian Redlbd595762010-08-31 20:53:31 +00001939 // We skip out of inline namespaces. The innermost non-inline namespace
1940 // contains all names of all its nested inline namespaces anyway, so we can
1941 // replace the entire inline namespace tree with its root.
1942 while (Ctx->isRecord() || Ctx->isTransparentContext() ||
1943 Ctx->isInlineNamespace())
Douglas Gregor8b895222010-04-30 07:08:38 +00001944 Ctx = Ctx->getParent();
1945
John McCallc7e8e792009-08-07 22:18:02 +00001946 if (Ctx->isFileContext())
Douglas Gregor8b895222010-04-30 07:08:38 +00001947 Namespaces.insert(Ctx->getPrimaryContext());
John McCallc7e8e792009-08-07 22:18:02 +00001948}
Douglas Gregor197e5f72009-07-08 07:51:57 +00001949
Mike Stump11289f42009-09-09 15:08:12 +00001950// \brief Add the associated classes and namespaces for argument-dependent
Douglas Gregor197e5f72009-07-08 07:51:57 +00001951// lookup that involves a template argument (C++ [basic.lookup.koenig]p2).
Mike Stump11289f42009-09-09 15:08:12 +00001952static void
John McCallf24d7bb2010-05-28 18:45:08 +00001953addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
1954 const TemplateArgument &Arg) {
Douglas Gregor197e5f72009-07-08 07:51:57 +00001955 // C++ [basic.lookup.koenig]p2, last bullet:
Mike Stump11289f42009-09-09 15:08:12 +00001956 // -- [...] ;
Douglas Gregor197e5f72009-07-08 07:51:57 +00001957 switch (Arg.getKind()) {
1958 case TemplateArgument::Null:
1959 break;
Mike Stump11289f42009-09-09 15:08:12 +00001960
Douglas Gregor197e5f72009-07-08 07:51:57 +00001961 case TemplateArgument::Type:
1962 // [...] the namespaces and classes associated with the types of the
1963 // template arguments provided for template type parameters (excluding
1964 // template template parameters)
John McCallf24d7bb2010-05-28 18:45:08 +00001965 addAssociatedClassesAndNamespaces(Result, Arg.getAsType());
Douglas Gregor197e5f72009-07-08 07:51:57 +00001966 break;
Mike Stump11289f42009-09-09 15:08:12 +00001967
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001968 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00001969 case TemplateArgument::TemplateExpansion: {
Mike Stump11289f42009-09-09 15:08:12 +00001970 // [...] the namespaces in which any template template arguments are
1971 // defined; and the classes in which any member templates used as
Douglas Gregor197e5f72009-07-08 07:51:57 +00001972 // template template arguments are defined.
Douglas Gregore4ff4b52011-01-05 18:58:31 +00001973 TemplateName Template = Arg.getAsTemplateOrTemplatePattern();
Mike Stump11289f42009-09-09 15:08:12 +00001974 if (ClassTemplateDecl *ClassTemplate
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001975 = dyn_cast<ClassTemplateDecl>(Template.getAsTemplateDecl())) {
Douglas Gregor197e5f72009-07-08 07:51:57 +00001976 DeclContext *Ctx = ClassTemplate->getDeclContext();
1977 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00001978 Result.Classes.insert(EnclosingClass);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001979 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00001980 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001981 }
1982 break;
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001983 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001984
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001985 case TemplateArgument::Declaration:
Douglas Gregor197e5f72009-07-08 07:51:57 +00001986 case TemplateArgument::Integral:
1987 case TemplateArgument::Expression:
Eli Friedmanb826a002012-09-26 02:36:12 +00001988 case TemplateArgument::NullPtr:
Mike Stump11289f42009-09-09 15:08:12 +00001989 // [Note: non-type template arguments do not contribute to the set of
Douglas Gregor197e5f72009-07-08 07:51:57 +00001990 // associated namespaces. ]
1991 break;
Mike Stump11289f42009-09-09 15:08:12 +00001992
Douglas Gregor197e5f72009-07-08 07:51:57 +00001993 case TemplateArgument::Pack:
1994 for (TemplateArgument::pack_iterator P = Arg.pack_begin(),
1995 PEnd = Arg.pack_end();
1996 P != PEnd; ++P)
John McCallf24d7bb2010-05-28 18:45:08 +00001997 addAssociatedClassesAndNamespaces(Result, *P);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001998 break;
1999 }
2000}
2001
Douglas Gregore254f902009-02-04 00:32:51 +00002002// \brief Add the associated classes and namespaces for
Mike Stump11289f42009-09-09 15:08:12 +00002003// argument-dependent lookup with an argument of class type
2004// (C++ [basic.lookup.koenig]p2).
2005static void
John McCallf24d7bb2010-05-28 18:45:08 +00002006addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
2007 CXXRecordDecl *Class) {
2008
2009 // Just silently ignore anything whose name is __va_list_tag.
2010 if (Class->getDeclName() == Result.S.VAListTagName)
2011 return;
2012
Douglas Gregore254f902009-02-04 00:32:51 +00002013 // C++ [basic.lookup.koenig]p2:
2014 // [...]
2015 // -- If T is a class type (including unions), its associated
2016 // classes are: the class itself; the class of which it is a
2017 // member, if any; and its direct and indirect base
2018 // classes. Its associated namespaces are the namespaces in
Mike Stump11289f42009-09-09 15:08:12 +00002019 // which its associated classes are defined.
Douglas Gregore254f902009-02-04 00:32:51 +00002020
2021 // Add the class of which it is a member, if any.
2022 DeclContext *Ctx = Class->getDeclContext();
2023 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00002024 Result.Classes.insert(EnclosingClass);
Douglas Gregore254f902009-02-04 00:32:51 +00002025 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00002026 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Mike Stump11289f42009-09-09 15:08:12 +00002027
Douglas Gregore254f902009-02-04 00:32:51 +00002028 // Add the class itself. If we've already seen this class, we don't
2029 // need to visit base classes.
Richard Smith594461f2014-03-14 22:07:27 +00002030 //
2031 // FIXME: That's not correct, we may have added this class only because it
2032 // was the enclosing class of another class, and in that case we won't have
2033 // added its base classes yet.
John McCallf24d7bb2010-05-28 18:45:08 +00002034 if (!Result.Classes.insert(Class))
Douglas Gregore254f902009-02-04 00:32:51 +00002035 return;
2036
Mike Stump11289f42009-09-09 15:08:12 +00002037 // -- If T is a template-id, its associated namespaces and classes are
2038 // the namespace in which the template is defined; for member
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002039 // templates, the member template's class; the namespaces and classes
Mike Stump11289f42009-09-09 15:08:12 +00002040 // associated with the types of the template arguments provided for
Douglas Gregor197e5f72009-07-08 07:51:57 +00002041 // template type parameters (excluding template template parameters); the
Mike Stump11289f42009-09-09 15:08:12 +00002042 // namespaces in which any template template arguments are defined; and
2043 // the classes in which any member templates used as template template
2044 // arguments are defined. [Note: non-type template arguments do not
Douglas Gregor197e5f72009-07-08 07:51:57 +00002045 // contribute to the set of associated namespaces. ]
Mike Stump11289f42009-09-09 15:08:12 +00002046 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregor197e5f72009-07-08 07:51:57 +00002047 = dyn_cast<ClassTemplateSpecializationDecl>(Class)) {
2048 DeclContext *Ctx = Spec->getSpecializedTemplate()->getDeclContext();
2049 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00002050 Result.Classes.insert(EnclosingClass);
Douglas Gregor197e5f72009-07-08 07:51:57 +00002051 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00002052 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Mike Stump11289f42009-09-09 15:08:12 +00002053
Douglas Gregor197e5f72009-07-08 07:51:57 +00002054 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
2055 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
John McCallf24d7bb2010-05-28 18:45:08 +00002056 addAssociatedClassesAndNamespaces(Result, TemplateArgs[I]);
Douglas Gregor197e5f72009-07-08 07:51:57 +00002057 }
Mike Stump11289f42009-09-09 15:08:12 +00002058
John McCall67da35c2010-02-04 22:26:26 +00002059 // Only recurse into base classes for complete types.
Richard Smith594461f2014-03-14 22:07:27 +00002060 if (!Class->hasDefinition())
2061 return;
John McCall67da35c2010-02-04 22:26:26 +00002062
Douglas Gregore254f902009-02-04 00:32:51 +00002063 // Add direct and indirect base classes along with their associated
2064 // namespaces.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002065 SmallVector<CXXRecordDecl *, 32> Bases;
Douglas Gregore254f902009-02-04 00:32:51 +00002066 Bases.push_back(Class);
2067 while (!Bases.empty()) {
2068 // Pop this class off the stack.
Robert Wilhelm25284cc2013-08-23 16:11:15 +00002069 Class = Bases.pop_back_val();
Douglas Gregore254f902009-02-04 00:32:51 +00002070
2071 // Visit the base classes.
Aaron Ballman574705e2014-03-13 15:41:46 +00002072 for (const auto &Base : Class->bases()) {
2073 const RecordType *BaseType = Base.getType()->getAs<RecordType>();
Sebastian Redlc45c03c2009-10-25 09:35:33 +00002074 // In dependent contexts, we do ADL twice, and the first time around,
2075 // the base type might be a dependent TemplateSpecializationType, or a
2076 // TemplateTypeParmType. If that happens, simply ignore it.
2077 // FIXME: If we want to support export, we probably need to add the
2078 // namespace of the template in a TemplateSpecializationType, or even
2079 // the classes and namespaces of known non-dependent arguments.
2080 if (!BaseType)
2081 continue;
Douglas Gregore254f902009-02-04 00:32:51 +00002082 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(BaseType->getDecl());
John McCallf24d7bb2010-05-28 18:45:08 +00002083 if (Result.Classes.insert(BaseDecl)) {
Douglas Gregore254f902009-02-04 00:32:51 +00002084 // Find the associated namespace for this base class.
2085 DeclContext *BaseCtx = BaseDecl->getDeclContext();
John McCallf24d7bb2010-05-28 18:45:08 +00002086 CollectEnclosingNamespace(Result.Namespaces, BaseCtx);
Douglas Gregore254f902009-02-04 00:32:51 +00002087
2088 // Make sure we visit the bases of this base class.
2089 if (BaseDecl->bases_begin() != BaseDecl->bases_end())
2090 Bases.push_back(BaseDecl);
2091 }
2092 }
2093 }
2094}
2095
2096// \brief Add the associated classes and namespaces for
2097// argument-dependent lookup with an argument of type T
Mike Stump11289f42009-09-09 15:08:12 +00002098// (C++ [basic.lookup.koenig]p2).
2099static void
John McCallf24d7bb2010-05-28 18:45:08 +00002100addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType Ty) {
Douglas Gregore254f902009-02-04 00:32:51 +00002101 // C++ [basic.lookup.koenig]p2:
2102 //
2103 // For each argument type T in the function call, there is a set
2104 // of zero or more associated namespaces and a set of zero or more
2105 // associated classes to be considered. The sets of namespaces and
2106 // classes is determined entirely by the types of the function
2107 // arguments (and the namespace of any template template
2108 // argument). Typedef names and using-declarations used to specify
2109 // the types do not contribute to this set. The sets of namespaces
2110 // and classes are determined in the following way:
Douglas Gregore254f902009-02-04 00:32:51 +00002111
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002112 SmallVector<const Type *, 16> Queue;
John McCall0af3d3b2010-05-28 06:08:54 +00002113 const Type *T = Ty->getCanonicalTypeInternal().getTypePtr();
2114
Douglas Gregore254f902009-02-04 00:32:51 +00002115 while (true) {
John McCall0af3d3b2010-05-28 06:08:54 +00002116 switch (T->getTypeClass()) {
2117
2118#define TYPE(Class, Base)
2119#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2120#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2121#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
2122#define ABSTRACT_TYPE(Class, Base)
2123#include "clang/AST/TypeNodes.def"
2124 // T is canonical. We can also ignore dependent types because
2125 // we don't need to do ADL at the definition point, but if we
2126 // wanted to implement template export (or if we find some other
2127 // use for associated classes and namespaces...) this would be
2128 // wrong.
Douglas Gregore254f902009-02-04 00:32:51 +00002129 break;
Douglas Gregore254f902009-02-04 00:32:51 +00002130
John McCall0af3d3b2010-05-28 06:08:54 +00002131 // -- If T is a pointer to U or an array of U, its associated
2132 // namespaces and classes are those associated with U.
2133 case Type::Pointer:
2134 T = cast<PointerType>(T)->getPointeeType().getTypePtr();
2135 continue;
2136 case Type::ConstantArray:
2137 case Type::IncompleteArray:
2138 case Type::VariableArray:
2139 T = cast<ArrayType>(T)->getElementType().getTypePtr();
2140 continue;
Douglas Gregore254f902009-02-04 00:32:51 +00002141
John McCall0af3d3b2010-05-28 06:08:54 +00002142 // -- If T is a fundamental type, its associated sets of
2143 // namespaces and classes are both empty.
2144 case Type::Builtin:
2145 break;
2146
2147 // -- If T is a class type (including unions), its associated
2148 // classes are: the class itself; the class of which it is a
2149 // member, if any; and its direct and indirect base
2150 // classes. Its associated namespaces are the namespaces in
2151 // which its associated classes are defined.
2152 case Type::Record: {
Richard Smith594461f2014-03-14 22:07:27 +00002153 Result.S.RequireCompleteType(Result.InstantiationLoc, QualType(T, 0),
2154 /*no diagnostic*/ 0);
John McCall0af3d3b2010-05-28 06:08:54 +00002155 CXXRecordDecl *Class
2156 = cast<CXXRecordDecl>(cast<RecordType>(T)->getDecl());
John McCallf24d7bb2010-05-28 18:45:08 +00002157 addAssociatedClassesAndNamespaces(Result, Class);
John McCall0af3d3b2010-05-28 06:08:54 +00002158 break;
Douglas Gregor89ee6822009-02-28 01:32:25 +00002159 }
Douglas Gregorfe60c142010-05-20 02:26:51 +00002160
John McCall0af3d3b2010-05-28 06:08:54 +00002161 // -- If T is an enumeration type, its associated namespace is
2162 // the namespace in which it is defined. If it is class
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002163 // member, its associated class is the member's class; else
John McCall0af3d3b2010-05-28 06:08:54 +00002164 // it has no associated class.
2165 case Type::Enum: {
2166 EnumDecl *Enum = cast<EnumType>(T)->getDecl();
Douglas Gregore254f902009-02-04 00:32:51 +00002167
John McCall0af3d3b2010-05-28 06:08:54 +00002168 DeclContext *Ctx = Enum->getDeclContext();
2169 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00002170 Result.Classes.insert(EnclosingClass);
Douglas Gregore254f902009-02-04 00:32:51 +00002171
John McCall0af3d3b2010-05-28 06:08:54 +00002172 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00002173 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Douglas Gregore254f902009-02-04 00:32:51 +00002174
John McCall0af3d3b2010-05-28 06:08:54 +00002175 break;
2176 }
2177
2178 // -- If T is a function type, its associated namespaces and
2179 // classes are those associated with the function parameter
2180 // types and those associated with the return type.
2181 case Type::FunctionProto: {
2182 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00002183 for (const auto &Arg : Proto->param_types())
2184 Queue.push_back(Arg.getTypePtr());
John McCall0af3d3b2010-05-28 06:08:54 +00002185 // fallthrough
2186 }
2187 case Type::FunctionNoProto: {
2188 const FunctionType *FnType = cast<FunctionType>(T);
Alp Toker314cc812014-01-25 16:55:45 +00002189 T = FnType->getReturnType().getTypePtr();
John McCall0af3d3b2010-05-28 06:08:54 +00002190 continue;
2191 }
2192
2193 // -- If T is a pointer to a member function of a class X, its
2194 // associated namespaces and classes are those associated
2195 // with the function parameter types and return type,
2196 // together with those associated with X.
2197 //
2198 // -- If T is a pointer to a data member of class X, its
2199 // associated namespaces and classes are those associated
2200 // with the member type together with those associated with
2201 // X.
2202 case Type::MemberPointer: {
2203 const MemberPointerType *MemberPtr = cast<MemberPointerType>(T);
2204
2205 // Queue up the class type into which this points.
2206 Queue.push_back(MemberPtr->getClass());
2207
2208 // And directly continue with the pointee type.
2209 T = MemberPtr->getPointeeType().getTypePtr();
2210 continue;
2211 }
2212
2213 // As an extension, treat this like a normal pointer.
2214 case Type::BlockPointer:
2215 T = cast<BlockPointerType>(T)->getPointeeType().getTypePtr();
2216 continue;
2217
2218 // References aren't covered by the standard, but that's such an
2219 // obvious defect that we cover them anyway.
2220 case Type::LValueReference:
2221 case Type::RValueReference:
2222 T = cast<ReferenceType>(T)->getPointeeType().getTypePtr();
2223 continue;
2224
2225 // These are fundamental types.
2226 case Type::Vector:
2227 case Type::ExtVector:
2228 case Type::Complex:
2229 break;
2230
Richard Smith27d807c2013-04-30 13:56:41 +00002231 // Non-deduced auto types only get here for error cases.
2232 case Type::Auto:
2233 break;
2234
Douglas Gregor8e936662011-04-12 01:02:45 +00002235 // If T is an Objective-C object or interface type, or a pointer to an
2236 // object or interface type, the associated namespace is the global
2237 // namespace.
John McCall0af3d3b2010-05-28 06:08:54 +00002238 case Type::ObjCObject:
2239 case Type::ObjCInterface:
2240 case Type::ObjCObjectPointer:
Douglas Gregor8e936662011-04-12 01:02:45 +00002241 Result.Namespaces.insert(Result.S.Context.getTranslationUnitDecl());
John McCall0af3d3b2010-05-28 06:08:54 +00002242 break;
Eli Friedman0dfb8892011-10-06 23:00:33 +00002243
2244 // Atomic types are just wrappers; use the associations of the
2245 // contained type.
2246 case Type::Atomic:
2247 T = cast<AtomicType>(T)->getValueType().getTypePtr();
2248 continue;
John McCall0af3d3b2010-05-28 06:08:54 +00002249 }
2250
Robert Wilhelm25284cc2013-08-23 16:11:15 +00002251 if (Queue.empty())
2252 break;
2253 T = Queue.pop_back_val();
Douglas Gregore254f902009-02-04 00:32:51 +00002254 }
Douglas Gregore254f902009-02-04 00:32:51 +00002255}
2256
2257/// \brief Find the associated classes and namespaces for
2258/// argument-dependent lookup for a call with the given set of
2259/// arguments.
2260///
2261/// This routine computes the sets of associated classes and associated
Mike Stump11289f42009-09-09 15:08:12 +00002262/// namespaces searched by argument-dependent lookup
Douglas Gregore254f902009-02-04 00:32:51 +00002263/// (C++ [basic.lookup.argdep]) for a given set of arguments.
Robert Wilhelm16e94b92013-08-09 18:02:13 +00002264void Sema::FindAssociatedClassesAndNamespaces(
2265 SourceLocation InstantiationLoc, ArrayRef<Expr *> Args,
2266 AssociatedNamespaceSet &AssociatedNamespaces,
2267 AssociatedClassSet &AssociatedClasses) {
Douglas Gregore254f902009-02-04 00:32:51 +00002268 AssociatedNamespaces.clear();
2269 AssociatedClasses.clear();
2270
John McCall7d8b0412012-08-24 20:38:34 +00002271 AssociatedLookup Result(*this, InstantiationLoc,
2272 AssociatedNamespaces, AssociatedClasses);
John McCallf24d7bb2010-05-28 18:45:08 +00002273
Douglas Gregore254f902009-02-04 00:32:51 +00002274 // C++ [basic.lookup.koenig]p2:
2275 // For each argument type T in the function call, there is a set
2276 // of zero or more associated namespaces and a set of zero or more
2277 // associated classes to be considered. The sets of namespaces and
2278 // classes is determined entirely by the types of the function
2279 // arguments (and the namespace of any template template
Mike Stump11289f42009-09-09 15:08:12 +00002280 // argument).
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002281 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
Douglas Gregore254f902009-02-04 00:32:51 +00002282 Expr *Arg = Args[ArgIdx];
2283
2284 if (Arg->getType() != Context.OverloadTy) {
John McCallf24d7bb2010-05-28 18:45:08 +00002285 addAssociatedClassesAndNamespaces(Result, Arg->getType());
Douglas Gregore254f902009-02-04 00:32:51 +00002286 continue;
2287 }
2288
2289 // [...] In addition, if the argument is the name or address of a
2290 // set of overloaded functions and/or function templates, its
2291 // associated classes and namespaces are the union of those
2292 // associated with each of the members of the set: the namespace
2293 // in which the function or function template is defined and the
2294 // classes and namespaces associated with its (non-dependent)
2295 // parameter types and return type.
Douglas Gregorbe759252009-07-08 10:57:20 +00002296 Arg = Arg->IgnoreParens();
John McCalld14a8642009-11-21 08:51:07 +00002297 if (UnaryOperator *unaryOp = dyn_cast<UnaryOperator>(Arg))
John McCalle3027922010-08-25 11:45:40 +00002298 if (unaryOp->getOpcode() == UO_AddrOf)
John McCalld14a8642009-11-21 08:51:07 +00002299 Arg = unaryOp->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00002300
John McCallf24d7bb2010-05-28 18:45:08 +00002301 UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Arg);
2302 if (!ULE) continue;
John McCalld14a8642009-11-21 08:51:07 +00002303
John McCallf24d7bb2010-05-28 18:45:08 +00002304 for (UnresolvedSetIterator I = ULE->decls_begin(), E = ULE->decls_end();
2305 I != E; ++I) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00002306 // Look through any using declarations to find the underlying function.
Alp Tokera2794f92014-01-22 07:29:52 +00002307 FunctionDecl *FDecl = (*I)->getUnderlyingDecl()->getAsFunction();
Douglas Gregore254f902009-02-04 00:32:51 +00002308
2309 // Add the classes and namespaces associated with the parameter
2310 // types and return type of this function.
John McCallf24d7bb2010-05-28 18:45:08 +00002311 addAssociatedClassesAndNamespaces(Result, FDecl->getType());
Douglas Gregore254f902009-02-04 00:32:51 +00002312 }
2313 }
2314}
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002315
2316/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
2317/// an acceptable non-member overloaded operator for a call whose
2318/// arguments have types T1 (and, if non-empty, T2). This routine
2319/// implements the check in C++ [over.match.oper]p3b2 concerning
2320/// enumeration types.
Mike Stump11289f42009-09-09 15:08:12 +00002321static bool
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002322IsAcceptableNonMemberOperatorCandidate(FunctionDecl *Fn,
2323 QualType T1, QualType T2,
2324 ASTContext &Context) {
Douglas Gregor0950e412009-03-13 21:01:28 +00002325 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
2326 return true;
2327
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002328 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
2329 return true;
2330
John McCall9dd450b2009-09-21 23:43:11 +00002331 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00002332 if (Proto->getNumParams() < 1)
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002333 return false;
2334
2335 if (T1->isEnumeralType()) {
Alp Toker9cacbab2014-01-20 20:26:09 +00002336 QualType ArgType = Proto->getParamType(0).getNonReferenceType();
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002337 if (Context.hasSameUnqualifiedType(T1, ArgType))
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002338 return true;
2339 }
2340
Alp Toker9cacbab2014-01-20 20:26:09 +00002341 if (Proto->getNumParams() < 2)
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002342 return false;
2343
2344 if (!T2.isNull() && T2->isEnumeralType()) {
Alp Toker9cacbab2014-01-20 20:26:09 +00002345 QualType ArgType = Proto->getParamType(1).getNonReferenceType();
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002346 if (Context.hasSameUnqualifiedType(T2, ArgType))
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002347 return true;
2348 }
2349
2350 return false;
2351}
2352
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
2379 // functions are ignored. However, if no operand has a class
2380 // type, only those non-member functions in the lookup set
Eli Friedman44b83ee2009-08-05 19:21:58 +00002381 // that have a first parameter of type T1 or "reference to
2382 // (possibly cv-qualified) T1", when T1 is an enumeration
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002383 // type, or (if there is a right operand) a second parameter
Eli Friedman44b83ee2009-08-05 19:21:58 +00002384 // of type T2 or "reference to (possibly cv-qualified) T2",
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002385 // when T2 is an enumeration type, are candidate functions.
2386 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
John McCall27b18f82009-11-17 02:14:36 +00002387 LookupResult Operators(*this, OpName, SourceLocation(), LookupOperatorName);
2388 LookupName(Operators, S);
Mike Stump11289f42009-09-09 15:08:12 +00002389
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002390 assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
2391
John McCall9f3059a2009-10-09 21:13:30 +00002392 if (Operators.empty())
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002393 return;
2394
2395 for (LookupResult::iterator Op = Operators.begin(), OpEnd = Operators.end();
2396 Op != OpEnd; ++Op) {
Douglas Gregor645d76f2010-04-25 20:25:43 +00002397 NamedDecl *Found = (*Op)->getUnderlyingDecl();
2398 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Found)) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002399 if (IsAcceptableNonMemberOperatorCandidate(FD, T1, T2, Context))
Douglas Gregor645d76f2010-04-25 20:25:43 +00002400 Functions.addDecl(*Op, Op.getAccess()); // FIXME: canonical FD
Mike Stump11289f42009-09-09 15:08:12 +00002401 } else if (FunctionTemplateDecl *FunTmpl
Douglas Gregor645d76f2010-04-25 20:25:43 +00002402 = dyn_cast<FunctionTemplateDecl>(Found)) {
Douglas Gregor15448f82009-06-27 21:05:07 +00002403 // FIXME: friend operators?
Mike Stump11289f42009-09-09 15:08:12 +00002404 // FIXME: do we need to check IsAcceptableNonMemberOperatorCandidate,
Douglas Gregor15448f82009-06-27 21:05:07 +00002405 // later?
2406 if (!FunTmpl->getDeclContext()->isRecord())
Douglas Gregor645d76f2010-04-25 20:25:43 +00002407 Functions.addDecl(*Op, Op.getAccess());
Douglas Gregor15448f82009-06-27 21:05:07 +00002408 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002409 }
2410}
2411
Alexis Hunt1da39282011-06-24 02:11:39 +00002412Sema::SpecialMemberOverloadResult *Sema::LookupSpecialMember(CXXRecordDecl *RD,
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002413 CXXSpecialMember SM,
2414 bool ConstArg,
2415 bool VolatileArg,
2416 bool RValueThis,
2417 bool ConstThis,
2418 bool VolatileThis) {
Richard Smith7d125a12012-11-27 21:20:31 +00002419 assert(CanDeclareSpecialMemberFunction(RD) &&
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002420 "doing special member lookup into record that isn't fully complete");
Richard Smith7d125a12012-11-27 21:20:31 +00002421 RD = RD->getDefinition();
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002422 if (RValueThis || ConstThis || VolatileThis)
2423 assert((SM == CXXCopyAssignment || SM == CXXMoveAssignment) &&
2424 "constructors and destructors always have unqualified lvalue this");
2425 if (ConstArg || VolatileArg)
2426 assert((SM != CXXDefaultConstructor && SM != CXXDestructor) &&
2427 "parameter-less special members can't have qualified arguments");
2428
2429 llvm::FoldingSetNodeID ID;
Alexis Hunt1da39282011-06-24 02:11:39 +00002430 ID.AddPointer(RD);
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002431 ID.AddInteger(SM);
2432 ID.AddInteger(ConstArg);
2433 ID.AddInteger(VolatileArg);
2434 ID.AddInteger(RValueThis);
2435 ID.AddInteger(ConstThis);
2436 ID.AddInteger(VolatileThis);
2437
2438 void *InsertPoint;
2439 SpecialMemberOverloadResult *Result =
2440 SpecialMemberCache.FindNodeOrInsertPos(ID, InsertPoint);
2441
2442 // This was already cached
2443 if (Result)
2444 return Result;
2445
Alexis Huntba8e18d2011-06-07 00:11:58 +00002446 Result = BumpAlloc.Allocate<SpecialMemberOverloadResult>();
2447 Result = new (Result) SpecialMemberOverloadResult(ID);
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002448 SpecialMemberCache.InsertNode(Result, InsertPoint);
2449
2450 if (SM == CXXDestructor) {
Richard Smith2be35f52012-12-01 02:35:44 +00002451 if (RD->needsImplicitDestructor())
Alexis Hunt1da39282011-06-24 02:11:39 +00002452 DeclareImplicitDestructor(RD);
2453 CXXDestructorDecl *DD = RD->getDestructor();
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002454 assert(DD && "record without a destructor");
2455 Result->setMethod(DD);
Richard Smith852265f2012-03-30 20:53:28 +00002456 Result->setKind(DD->isDeleted() ?
2457 SpecialMemberOverloadResult::NoMemberOrDeleted :
Richard Smith83c478d2012-04-20 18:46:14 +00002458 SpecialMemberOverloadResult::Success);
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002459 return Result;
2460 }
2461
Alexis Hunteef8ee02011-06-10 03:50:41 +00002462 // Prepare for overload resolution. Here we construct a synthetic argument
2463 // if necessary and make sure that implicit functions are declared.
Alexis Hunt1da39282011-06-24 02:11:39 +00002464 CanQualType CanTy = Context.getCanonicalType(Context.getTagDeclType(RD));
Alexis Hunteef8ee02011-06-10 03:50:41 +00002465 DeclarationName Name;
2466 Expr *Arg = 0;
2467 unsigned NumArgs;
2468
Richard Smith83c478d2012-04-20 18:46:14 +00002469 QualType ArgType = CanTy;
2470 ExprValueKind VK = VK_LValue;
2471
Alexis Hunteef8ee02011-06-10 03:50:41 +00002472 if (SM == CXXDefaultConstructor) {
2473 Name = Context.DeclarationNames.getCXXConstructorName(CanTy);
2474 NumArgs = 0;
Alexis Hunt1da39282011-06-24 02:11:39 +00002475 if (RD->needsImplicitDefaultConstructor())
2476 DeclareImplicitDefaultConstructor(RD);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002477 } else {
2478 if (SM == CXXCopyConstructor || SM == CXXMoveConstructor) {
2479 Name = Context.DeclarationNames.getCXXConstructorName(CanTy);
Richard Smith2be35f52012-12-01 02:35:44 +00002480 if (RD->needsImplicitCopyConstructor())
Alexis Hunt1da39282011-06-24 02:11:39 +00002481 DeclareImplicitCopyConstructor(RD);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002482 if (getLangOpts().CPlusPlus11 && RD->needsImplicitMoveConstructor())
Sebastian Redl22653ba2011-08-30 19:58:05 +00002483 DeclareImplicitMoveConstructor(RD);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002484 } else {
2485 Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Richard Smith2be35f52012-12-01 02:35:44 +00002486 if (RD->needsImplicitCopyAssignment())
Alexis Hunt1da39282011-06-24 02:11:39 +00002487 DeclareImplicitCopyAssignment(RD);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002488 if (getLangOpts().CPlusPlus11 && RD->needsImplicitMoveAssignment())
Sebastian Redl22653ba2011-08-30 19:58:05 +00002489 DeclareImplicitMoveAssignment(RD);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002490 }
2491
Alexis Hunteef8ee02011-06-10 03:50:41 +00002492 if (ConstArg)
2493 ArgType.addConst();
2494 if (VolatileArg)
2495 ArgType.addVolatile();
2496
2497 // This isn't /really/ specified by the standard, but it's implied
2498 // we should be working from an RValue in the case of move to ensure
2499 // that we prefer to bind to rvalue references, and an LValue in the
2500 // case of copy to ensure we don't bind to rvalue references.
2501 // Possibly an XValue is actually correct in the case of move, but
2502 // there is no semantic difference for class types in this restricted
2503 // case.
Alexis Hunt46d1ce22011-06-22 22:13:13 +00002504 if (SM == CXXCopyConstructor || SM == CXXCopyAssignment)
Alexis Hunteef8ee02011-06-10 03:50:41 +00002505 VK = VK_LValue;
2506 else
2507 VK = VK_RValue;
Richard Smith83c478d2012-04-20 18:46:14 +00002508 }
Alexis Hunteef8ee02011-06-10 03:50:41 +00002509
Richard Smith83c478d2012-04-20 18:46:14 +00002510 OpaqueValueExpr FakeArg(SourceLocation(), ArgType, VK);
2511
2512 if (SM != CXXDefaultConstructor) {
Alexis Hunteef8ee02011-06-10 03:50:41 +00002513 NumArgs = 1;
Richard Smith83c478d2012-04-20 18:46:14 +00002514 Arg = &FakeArg;
Alexis Hunteef8ee02011-06-10 03:50:41 +00002515 }
2516
2517 // Create the object argument
2518 QualType ThisTy = CanTy;
2519 if (ConstThis)
2520 ThisTy.addConst();
2521 if (VolatileThis)
2522 ThisTy.addVolatile();
Alexis Hunt080709f2011-06-23 00:26:20 +00002523 Expr::Classification Classification =
Richard Smith83c478d2012-04-20 18:46:14 +00002524 OpaqueValueExpr(SourceLocation(), ThisTy,
2525 RValueThis ? VK_RValue : VK_LValue).Classify(Context);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002526
2527 // Now we perform lookup on the name we computed earlier and do overload
2528 // resolution. Lookup is only performed directly into the class since there
2529 // will always be a (possibly implicit) declaration to shadow any others.
Nick Lewycky56412332014-01-11 02:37:12 +00002530 OverloadCandidateSet OCS(RD->getLocation());
David Blaikieff7d47a2012-12-19 00:45:41 +00002531 DeclContext::lookup_result R = RD->lookup(Name);
David Blaikieff7d47a2012-12-19 00:45:41 +00002532 assert(!R.empty() &&
Alexis Hunteef8ee02011-06-10 03:50:41 +00002533 "lookup for a constructor or assignment operator was empty");
Chandler Carruth7deaae72013-08-18 07:20:52 +00002534
2535 // Copy the candidates as our processing of them may load new declarations
2536 // from an external source and invalidate lookup_result.
2537 SmallVector<NamedDecl *, 8> Candidates(R.begin(), R.end());
2538
2539 for (SmallVectorImpl<NamedDecl *>::iterator I = Candidates.begin(),
Richard Smithd55889a2013-09-09 16:55:27 +00002540 E = Candidates.end();
Chandler Carruth7deaae72013-08-18 07:20:52 +00002541 I != E; ++I) {
2542 NamedDecl *Cand = *I;
Alexis Hunt080709f2011-06-23 00:26:20 +00002543
Alexis Hunt1da39282011-06-24 02:11:39 +00002544 if (Cand->isInvalidDecl())
Alexis Hunteef8ee02011-06-10 03:50:41 +00002545 continue;
2546
Alexis Hunt1da39282011-06-24 02:11:39 +00002547 if (UsingShadowDecl *U = dyn_cast<UsingShadowDecl>(Cand)) {
2548 // FIXME: [namespace.udecl]p15 says that we should only consider a
2549 // using declaration here if it does not match a declaration in the
2550 // derived class. We do not implement this correctly in other cases
2551 // either.
2552 Cand = U->getTargetDecl();
2553
2554 if (Cand->isInvalidDecl())
2555 continue;
2556 }
2557
2558 if (CXXMethodDecl *M = dyn_cast<CXXMethodDecl>(Cand)) {
Alexis Hunt080709f2011-06-23 00:26:20 +00002559 if (SM == CXXCopyAssignment || SM == CXXMoveAssignment)
Alexis Hunt1da39282011-06-24 02:11:39 +00002560 AddMethodCandidate(M, DeclAccessPair::make(M, AS_public), RD, ThisTy,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002561 Classification, llvm::makeArrayRef(&Arg, NumArgs),
2562 OCS, true);
Alexis Hunt080709f2011-06-23 00:26:20 +00002563 else
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002564 AddOverloadCandidate(M, DeclAccessPair::make(M, AS_public),
2565 llvm::makeArrayRef(&Arg, NumArgs), OCS, true);
Alexis Hunt2949f022011-06-22 02:58:46 +00002566 } else if (FunctionTemplateDecl *Tmpl =
Alexis Hunt1da39282011-06-24 02:11:39 +00002567 dyn_cast<FunctionTemplateDecl>(Cand)) {
Alexis Hunt080709f2011-06-23 00:26:20 +00002568 if (SM == CXXCopyAssignment || SM == CXXMoveAssignment)
2569 AddMethodTemplateCandidate(Tmpl, DeclAccessPair::make(Tmpl, AS_public),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002570 RD, 0, ThisTy, Classification,
2571 llvm::makeArrayRef(&Arg, NumArgs),
Alexis Hunt080709f2011-06-23 00:26:20 +00002572 OCS, true);
2573 else
2574 AddTemplateOverloadCandidate(Tmpl, DeclAccessPair::make(Tmpl, AS_public),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002575 0, llvm::makeArrayRef(&Arg, NumArgs),
2576 OCS, true);
Alexis Hunt1da39282011-06-24 02:11:39 +00002577 } else {
2578 assert(isa<UsingDecl>(Cand) && "illegal Kind of operator = Decl");
Alexis Hunteef8ee02011-06-10 03:50:41 +00002579 }
2580 }
2581
2582 OverloadCandidateSet::iterator Best;
2583 switch (OCS.BestViableFunction(*this, SourceLocation(), Best)) {
2584 case OR_Success:
2585 Result->setMethod(cast<CXXMethodDecl>(Best->Function));
Richard Smith83c478d2012-04-20 18:46:14 +00002586 Result->setKind(SpecialMemberOverloadResult::Success);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002587 break;
2588
2589 case OR_Deleted:
2590 Result->setMethod(cast<CXXMethodDecl>(Best->Function));
Richard Smith852265f2012-03-30 20:53:28 +00002591 Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002592 break;
2593
2594 case OR_Ambiguous:
Richard Smith852265f2012-03-30 20:53:28 +00002595 Result->setMethod(0);
2596 Result->setKind(SpecialMemberOverloadResult::Ambiguous);
2597 break;
2598
Alexis Hunteef8ee02011-06-10 03:50:41 +00002599 case OR_No_Viable_Function:
2600 Result->setMethod(0);
Richard Smith852265f2012-03-30 20:53:28 +00002601 Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002602 break;
2603 }
2604
2605 return Result;
2606}
2607
2608/// \brief Look up the default constructor for the given class.
2609CXXConstructorDecl *Sema::LookupDefaultConstructor(CXXRecordDecl *Class) {
Alexis Hunt899bd442011-06-10 04:44:37 +00002610 SpecialMemberOverloadResult *Result =
Alexis Hunteef8ee02011-06-10 03:50:41 +00002611 LookupSpecialMember(Class, CXXDefaultConstructor, false, false, false,
2612 false, false);
2613
2614 return cast_or_null<CXXConstructorDecl>(Result->getMethod());
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002615}
2616
Alexis Hunt491ec602011-06-21 23:42:56 +00002617/// \brief Look up the copying constructor for the given class.
2618CXXConstructorDecl *Sema::LookupCopyingConstructor(CXXRecordDecl *Class,
Richard Smith83c478d2012-04-20 18:46:14 +00002619 unsigned Quals) {
Alexis Hunt899bd442011-06-10 04:44:37 +00002620 assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2621 "non-const, non-volatile qualifiers for copy ctor arg");
2622 SpecialMemberOverloadResult *Result =
2623 LookupSpecialMember(Class, CXXCopyConstructor, Quals & Qualifiers::Const,
2624 Quals & Qualifiers::Volatile, false, false, false);
2625
Alexis Hunt899bd442011-06-10 04:44:37 +00002626 return cast_or_null<CXXConstructorDecl>(Result->getMethod());
2627}
2628
Sebastian Redl22653ba2011-08-30 19:58:05 +00002629/// \brief Look up the moving constructor for the given class.
Richard Smith1c6461e2012-07-18 03:36:00 +00002630CXXConstructorDecl *Sema::LookupMovingConstructor(CXXRecordDecl *Class,
2631 unsigned Quals) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00002632 SpecialMemberOverloadResult *Result =
Richard Smith1c6461e2012-07-18 03:36:00 +00002633 LookupSpecialMember(Class, CXXMoveConstructor, Quals & Qualifiers::Const,
2634 Quals & Qualifiers::Volatile, false, false, false);
Sebastian Redl22653ba2011-08-30 19:58:05 +00002635
2636 return cast_or_null<CXXConstructorDecl>(Result->getMethod());
2637}
2638
Douglas Gregor52b72822010-07-02 23:12:18 +00002639/// \brief Look up the constructors for the given class.
2640DeclContext::lookup_result Sema::LookupConstructors(CXXRecordDecl *Class) {
Alexis Hunteef8ee02011-06-10 03:50:41 +00002641 // If the implicit constructors have not yet been declared, do so now.
Richard Smith7d125a12012-11-27 21:20:31 +00002642 if (CanDeclareSpecialMemberFunction(Class)) {
Alexis Huntea6f0322011-05-11 22:34:38 +00002643 if (Class->needsImplicitDefaultConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +00002644 DeclareImplicitDefaultConstructor(Class);
Richard Smith2be35f52012-12-01 02:35:44 +00002645 if (Class->needsImplicitCopyConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +00002646 DeclareImplicitCopyConstructor(Class);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002647 if (getLangOpts().CPlusPlus11 && Class->needsImplicitMoveConstructor())
Sebastian Redl22653ba2011-08-30 19:58:05 +00002648 DeclareImplicitMoveConstructor(Class);
Douglas Gregor9672f922010-07-03 00:47:00 +00002649 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002650
Douglas Gregor52b72822010-07-02 23:12:18 +00002651 CanQualType T = Context.getCanonicalType(Context.getTypeDeclType(Class));
2652 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(T);
2653 return Class->lookup(Name);
2654}
2655
Alexis Hunt491ec602011-06-21 23:42:56 +00002656/// \brief Look up the copying assignment operator for the given class.
2657CXXMethodDecl *Sema::LookupCopyingAssignment(CXXRecordDecl *Class,
2658 unsigned Quals, bool RValueThis,
Richard Smith83c478d2012-04-20 18:46:14 +00002659 unsigned ThisQuals) {
Alexis Hunt491ec602011-06-21 23:42:56 +00002660 assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2661 "non-const, non-volatile qualifiers for copy assignment arg");
2662 assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2663 "non-const, non-volatile qualifiers for copy assignment this");
2664 SpecialMemberOverloadResult *Result =
2665 LookupSpecialMember(Class, CXXCopyAssignment, Quals & Qualifiers::Const,
2666 Quals & Qualifiers::Volatile, RValueThis,
2667 ThisQuals & Qualifiers::Const,
2668 ThisQuals & Qualifiers::Volatile);
2669
Alexis Hunt491ec602011-06-21 23:42:56 +00002670 return Result->getMethod();
2671}
2672
Sebastian Redl22653ba2011-08-30 19:58:05 +00002673/// \brief Look up the moving assignment operator for the given class.
2674CXXMethodDecl *Sema::LookupMovingAssignment(CXXRecordDecl *Class,
Richard Smith1c6461e2012-07-18 03:36:00 +00002675 unsigned Quals,
Sebastian Redl22653ba2011-08-30 19:58:05 +00002676 bool RValueThis,
2677 unsigned ThisQuals) {
2678 assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2679 "non-const, non-volatile qualifiers for copy assignment this");
2680 SpecialMemberOverloadResult *Result =
Richard Smith1c6461e2012-07-18 03:36:00 +00002681 LookupSpecialMember(Class, CXXMoveAssignment, Quals & Qualifiers::Const,
2682 Quals & Qualifiers::Volatile, RValueThis,
Sebastian Redl22653ba2011-08-30 19:58:05 +00002683 ThisQuals & Qualifiers::Const,
2684 ThisQuals & Qualifiers::Volatile);
2685
2686 return Result->getMethod();
2687}
2688
Douglas Gregore71edda2010-07-01 22:47:18 +00002689/// \brief Look for the destructor of the given class.
2690///
Alexis Hunt967ea7c2011-06-03 21:10:40 +00002691/// During semantic analysis, this routine should be used in lieu of
2692/// CXXRecordDecl::getDestructor().
Douglas Gregore71edda2010-07-01 22:47:18 +00002693///
2694/// \returns The destructor for this class.
2695CXXDestructorDecl *Sema::LookupDestructor(CXXRecordDecl *Class) {
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002696 return cast<CXXDestructorDecl>(LookupSpecialMember(Class, CXXDestructor,
2697 false, false, false,
2698 false, false)->getMethod());
Douglas Gregore71edda2010-07-01 22:47:18 +00002699}
2700
Richard Smithbcc22fc2012-03-09 08:00:36 +00002701/// LookupLiteralOperator - Determine which literal operator should be used for
2702/// a user-defined literal, per C++11 [lex.ext].
2703///
2704/// Normal overload resolution is not used to select which literal operator to
2705/// call for a user-defined literal. Look up the provided literal operator name,
2706/// and filter the results to the appropriate set for the given argument types.
2707Sema::LiteralOperatorLookupResult
2708Sema::LookupLiteralOperator(Scope *S, LookupResult &R,
2709 ArrayRef<QualType> ArgTys,
Richard Smithb8b41d32013-10-07 19:57:58 +00002710 bool AllowRaw, bool AllowTemplate,
2711 bool AllowStringTemplate) {
Richard Smithbcc22fc2012-03-09 08:00:36 +00002712 LookupName(R, S);
2713 assert(R.getResultKind() != LookupResult::Ambiguous &&
2714 "literal operator lookup can't be ambiguous");
2715
2716 // Filter the lookup results appropriately.
2717 LookupResult::Filter F = R.makeFilter();
2718
Richard Smithbcc22fc2012-03-09 08:00:36 +00002719 bool FoundRaw = false;
Richard Smithb8b41d32013-10-07 19:57:58 +00002720 bool FoundTemplate = false;
2721 bool FoundStringTemplate = false;
Richard Smithbcc22fc2012-03-09 08:00:36 +00002722 bool FoundExactMatch = false;
2723
2724 while (F.hasNext()) {
2725 Decl *D = F.next();
2726 if (UsingShadowDecl *USD = dyn_cast<UsingShadowDecl>(D))
2727 D = USD->getTargetDecl();
2728
Douglas Gregorc1970572013-04-10 05:18:00 +00002729 // If the declaration we found is invalid, skip it.
2730 if (D->isInvalidDecl()) {
2731 F.erase();
2732 continue;
2733 }
2734
Richard Smithb8b41d32013-10-07 19:57:58 +00002735 bool IsRaw = false;
2736 bool IsTemplate = false;
2737 bool IsStringTemplate = false;
2738 bool IsExactMatch = false;
2739
Richard Smithbcc22fc2012-03-09 08:00:36 +00002740 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2741 if (FD->getNumParams() == 1 &&
2742 FD->getParamDecl(0)->getType()->getAs<PointerType>())
2743 IsRaw = true;
Richard Smith550de452013-01-15 07:12:59 +00002744 else if (FD->getNumParams() == ArgTys.size()) {
Richard Smithbcc22fc2012-03-09 08:00:36 +00002745 IsExactMatch = true;
2746 for (unsigned ArgIdx = 0; ArgIdx != ArgTys.size(); ++ArgIdx) {
2747 QualType ParamTy = FD->getParamDecl(ArgIdx)->getType();
2748 if (!Context.hasSameUnqualifiedType(ArgTys[ArgIdx], ParamTy)) {
2749 IsExactMatch = false;
2750 break;
2751 }
2752 }
2753 }
2754 }
Richard Smithb8b41d32013-10-07 19:57:58 +00002755 if (FunctionTemplateDecl *FD = dyn_cast<FunctionTemplateDecl>(D)) {
2756 TemplateParameterList *Params = FD->getTemplateParameters();
2757 if (Params->size() == 1)
2758 IsTemplate = true;
2759 else
2760 IsStringTemplate = true;
2761 }
Richard Smithbcc22fc2012-03-09 08:00:36 +00002762
2763 if (IsExactMatch) {
2764 FoundExactMatch = true;
Richard Smithb8b41d32013-10-07 19:57:58 +00002765 AllowRaw = false;
2766 AllowTemplate = false;
2767 AllowStringTemplate = false;
2768 if (FoundRaw || FoundTemplate || FoundStringTemplate) {
Richard Smithbcc22fc2012-03-09 08:00:36 +00002769 // Go through again and remove the raw and template decls we've
2770 // already found.
2771 F.restart();
Richard Smithb8b41d32013-10-07 19:57:58 +00002772 FoundRaw = FoundTemplate = FoundStringTemplate = false;
Richard Smithbcc22fc2012-03-09 08:00:36 +00002773 }
Richard Smithb8b41d32013-10-07 19:57:58 +00002774 } else if (AllowRaw && IsRaw) {
2775 FoundRaw = true;
2776 } else if (AllowTemplate && IsTemplate) {
2777 FoundTemplate = true;
2778 } else if (AllowStringTemplate && IsStringTemplate) {
2779 FoundStringTemplate = true;
Richard Smithbcc22fc2012-03-09 08:00:36 +00002780 } else {
2781 F.erase();
2782 }
2783 }
2784
2785 F.done();
2786
2787 // C++11 [lex.ext]p3, p4: If S contains a literal operator with a matching
2788 // parameter type, that is used in preference to a raw literal operator
2789 // or literal operator template.
2790 if (FoundExactMatch)
2791 return LOLR_Cooked;
2792
2793 // C++11 [lex.ext]p3, p4: S shall contain a raw literal operator or a literal
2794 // operator template, but not both.
2795 if (FoundRaw && FoundTemplate) {
2796 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
Alp Tokera2794f92014-01-22 07:29:52 +00002797 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
2798 NoteOverloadCandidate((*I)->getUnderlyingDecl()->getAsFunction());
Richard Smithbcc22fc2012-03-09 08:00:36 +00002799 return LOLR_Error;
2800 }
2801
2802 if (FoundRaw)
2803 return LOLR_Raw;
2804
2805 if (FoundTemplate)
2806 return LOLR_Template;
2807
Richard Smithb8b41d32013-10-07 19:57:58 +00002808 if (FoundStringTemplate)
2809 return LOLR_StringTemplate;
2810
Richard Smithbcc22fc2012-03-09 08:00:36 +00002811 // Didn't find anything we could use.
2812 Diag(R.getNameLoc(), diag::err_ovl_no_viable_literal_operator)
2813 << R.getLookupName() << (int)ArgTys.size() << ArgTys[0]
Richard Smithb8b41d32013-10-07 19:57:58 +00002814 << (ArgTys.size() == 2 ? ArgTys[1] : QualType()) << AllowRaw
2815 << (AllowTemplate || AllowStringTemplate);
Richard Smithbcc22fc2012-03-09 08:00:36 +00002816 return LOLR_Error;
2817}
2818
John McCall8fe68082010-01-26 07:16:45 +00002819void ADLResult::insert(NamedDecl *New) {
2820 NamedDecl *&Old = Decls[cast<NamedDecl>(New->getCanonicalDecl())];
2821
2822 // If we haven't yet seen a decl for this key, or the last decl
2823 // was exactly this one, we're done.
2824 if (Old == 0 || Old == New) {
2825 Old = New;
2826 return;
2827 }
2828
2829 // Otherwise, decide which is a more recent redeclaration.
Alp Tokera2794f92014-01-22 07:29:52 +00002830 FunctionDecl *OldFD = Old->getAsFunction();
2831 FunctionDecl *NewFD = New->getAsFunction();
John McCall8fe68082010-01-26 07:16:45 +00002832
2833 FunctionDecl *Cursor = NewFD;
2834 while (true) {
Douglas Gregorec9fd132012-01-14 16:38:05 +00002835 Cursor = Cursor->getPreviousDecl();
John McCall8fe68082010-01-26 07:16:45 +00002836
2837 // If we got to the end without finding OldFD, OldFD is the newer
2838 // declaration; leave things as they are.
2839 if (!Cursor) return;
2840
2841 // If we do find OldFD, then NewFD is newer.
2842 if (Cursor == OldFD) break;
2843
2844 // Otherwise, keep looking.
2845 }
2846
2847 Old = New;
2848}
2849
Sebastian Redlc057f422009-10-23 19:23:15 +00002850void Sema::ArgumentDependentLookup(DeclarationName Name, bool Operator,
Robert Wilhelm16e94b92013-08-09 18:02:13 +00002851 SourceLocation Loc, ArrayRef<Expr *> Args,
Richard Smithb6626742012-10-18 17:56:02 +00002852 ADLResult &Result) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002853 // Find all of the associated namespaces and classes based on the
2854 // arguments we have.
2855 AssociatedNamespaceSet AssociatedNamespaces;
2856 AssociatedClassSet AssociatedClasses;
John McCall7d8b0412012-08-24 20:38:34 +00002857 FindAssociatedClassesAndNamespaces(Loc, Args,
John McCallc7e8e792009-08-07 22:18:02 +00002858 AssociatedNamespaces,
2859 AssociatedClasses);
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002860
Sebastian Redlc057f422009-10-23 19:23:15 +00002861 QualType T1, T2;
2862 if (Operator) {
2863 T1 = Args[0]->getType();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002864 if (Args.size() >= 2)
Sebastian Redlc057f422009-10-23 19:23:15 +00002865 T2 = Args[1]->getType();
2866 }
2867
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002868 // C++ [basic.lookup.argdep]p3:
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002869 // Let X be the lookup set produced by unqualified lookup (3.4.1)
2870 // and let Y be the lookup set produced by argument dependent
2871 // lookup (defined as follows). If X contains [...] then Y is
2872 // empty. Otherwise Y is the set of declarations found in the
2873 // namespaces associated with the argument types as described
2874 // below. The set of declarations found by the lookup of the name
2875 // is the union of X and Y.
2876 //
2877 // Here, we compute Y and add its members to the overloaded
2878 // candidate set.
2879 for (AssociatedNamespaceSet::iterator NS = AssociatedNamespaces.begin(),
Mike Stump11289f42009-09-09 15:08:12 +00002880 NSEnd = AssociatedNamespaces.end();
2881 NS != NSEnd; ++NS) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002882 // When considering an associated namespace, the lookup is the
2883 // same as the lookup performed when the associated namespace is
2884 // used as a qualifier (3.4.3.2) except that:
2885 //
2886 // -- Any using-directives in the associated namespace are
2887 // ignored.
2888 //
John McCallc7e8e792009-08-07 22:18:02 +00002889 // -- Any namespace-scope friend functions declared in
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002890 // associated classes are visible within their respective
2891 // namespaces even if they are not visible during an ordinary
2892 // lookup (11.4).
David Blaikieff7d47a2012-12-19 00:45:41 +00002893 DeclContext::lookup_result R = (*NS)->lookup(Name);
2894 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
2895 ++I) {
John McCall4c4c1df2010-01-26 03:27:55 +00002896 NamedDecl *D = *I;
John McCallaa74a0c2009-08-28 07:59:38 +00002897 // If the only declaration here is an ordinary friend, consider
2898 // it only if it was declared in an associated classes.
Richard Smith541b38b2013-09-20 01:15:31 +00002899 if ((D->getIdentifierNamespace() & Decl::IDNS_Ordinary) == 0) {
2900 // If it's neither ordinarily visible nor a friend, we can't find it.
2901 if ((D->getIdentifierNamespace() & Decl::IDNS_OrdinaryFriend) == 0)
2902 continue;
2903
Richard Smith64017682013-07-17 23:53:16 +00002904 bool DeclaredInAssociatedClass = false;
2905 for (Decl *DI = D; DI; DI = DI->getPreviousDecl()) {
2906 DeclContext *LexDC = DI->getLexicalDeclContext();
2907 if (isa<CXXRecordDecl>(LexDC) &&
2908 AssociatedClasses.count(cast<CXXRecordDecl>(LexDC))) {
2909 DeclaredInAssociatedClass = true;
2910 break;
2911 }
2912 }
2913 if (!DeclaredInAssociatedClass)
John McCalld1e9d832009-08-11 06:59:38 +00002914 continue;
2915 }
Mike Stump11289f42009-09-09 15:08:12 +00002916
John McCall91f61fc2010-01-26 06:04:06 +00002917 if (isa<UsingShadowDecl>(D))
2918 D = cast<UsingShadowDecl>(D)->getTargetDecl();
John McCall4c4c1df2010-01-26 03:27:55 +00002919
John McCall91f61fc2010-01-26 06:04:06 +00002920 if (isa<FunctionDecl>(D)) {
2921 if (Operator &&
2922 !IsAcceptableNonMemberOperatorCandidate(cast<FunctionDecl>(D),
2923 T1, T2, Context))
2924 continue;
John McCall8fe68082010-01-26 07:16:45 +00002925 } else if (!isa<FunctionTemplateDecl>(D))
2926 continue;
2927
2928 Result.insert(D);
Douglas Gregor6127ca42009-06-23 20:14:09 +00002929 }
2930 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002931}
Douglas Gregor2d435302009-12-30 17:04:44 +00002932
2933//----------------------------------------------------------------------------
2934// Search for all visible declarations.
2935//----------------------------------------------------------------------------
2936VisibleDeclConsumer::~VisibleDeclConsumer() { }
2937
Richard Smithe156254d2013-08-20 20:35:18 +00002938bool VisibleDeclConsumer::includeHiddenDecls() const { return false; }
2939
Douglas Gregor2d435302009-12-30 17:04:44 +00002940namespace {
2941
2942class ShadowContextRAII;
2943
2944class VisibleDeclsRecord {
2945public:
2946 /// \brief An entry in the shadow map, which is optimized to store a
2947 /// single declaration (the common case) but can also store a list
2948 /// of declarations.
Chris Lattner83cfc7c2011-07-18 01:54:02 +00002949 typedef llvm::TinyPtrVector<NamedDecl*> ShadowMapEntry;
Douglas Gregor2d435302009-12-30 17:04:44 +00002950
2951private:
2952 /// \brief A mapping from declaration names to the declarations that have
2953 /// this name within a particular scope.
2954 typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
2955
2956 /// \brief A list of shadow maps, which is used to model name hiding.
2957 std::list<ShadowMap> ShadowMaps;
2958
2959 /// \brief The declaration contexts we have already visited.
2960 llvm::SmallPtrSet<DeclContext *, 8> VisitedContexts;
2961
2962 friend class ShadowContextRAII;
2963
2964public:
2965 /// \brief Determine whether we have already visited this context
2966 /// (and, if not, note that we are going to visit that context now).
2967 bool visitedContext(DeclContext *Ctx) {
2968 return !VisitedContexts.insert(Ctx);
2969 }
2970
Douglas Gregor39982192010-08-15 06:18:01 +00002971 bool alreadyVisitedContext(DeclContext *Ctx) {
2972 return VisitedContexts.count(Ctx);
2973 }
2974
Douglas Gregor2d435302009-12-30 17:04:44 +00002975 /// \brief Determine whether the given declaration is hidden in the
2976 /// current scope.
2977 ///
2978 /// \returns the declaration that hides the given declaration, or
2979 /// NULL if no such declaration exists.
2980 NamedDecl *checkHidden(NamedDecl *ND);
2981
2982 /// \brief Add a declaration to the current shadow map.
Chris Lattner83cfc7c2011-07-18 01:54:02 +00002983 void add(NamedDecl *ND) {
2984 ShadowMaps.back()[ND->getDeclName()].push_back(ND);
2985 }
Douglas Gregor2d435302009-12-30 17:04:44 +00002986};
2987
2988/// \brief RAII object that records when we've entered a shadow context.
2989class ShadowContextRAII {
2990 VisibleDeclsRecord &Visible;
2991
2992 typedef VisibleDeclsRecord::ShadowMap ShadowMap;
2993
2994public:
2995 ShadowContextRAII(VisibleDeclsRecord &Visible) : Visible(Visible) {
2996 Visible.ShadowMaps.push_back(ShadowMap());
2997 }
2998
2999 ~ShadowContextRAII() {
Douglas Gregor2d435302009-12-30 17:04:44 +00003000 Visible.ShadowMaps.pop_back();
3001 }
3002};
3003
3004} // end anonymous namespace
3005
Douglas Gregor2d435302009-12-30 17:04:44 +00003006NamedDecl *VisibleDeclsRecord::checkHidden(NamedDecl *ND) {
Douglas Gregor0235c422010-01-14 00:06:47 +00003007 // Look through using declarations.
3008 ND = ND->getUnderlyingDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003009
Douglas Gregor2d435302009-12-30 17:04:44 +00003010 unsigned IDNS = ND->getIdentifierNamespace();
3011 std::list<ShadowMap>::reverse_iterator SM = ShadowMaps.rbegin();
3012 for (std::list<ShadowMap>::reverse_iterator SMEnd = ShadowMaps.rend();
3013 SM != SMEnd; ++SM) {
3014 ShadowMap::iterator Pos = SM->find(ND->getDeclName());
3015 if (Pos == SM->end())
3016 continue;
3017
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003018 for (ShadowMapEntry::iterator I = Pos->second.begin(),
Douglas Gregor2d435302009-12-30 17:04:44 +00003019 IEnd = Pos->second.end();
3020 I != IEnd; ++I) {
3021 // A tag declaration does not hide a non-tag declaration.
John McCalle87beb22010-04-23 18:46:30 +00003022 if ((*I)->hasTagIdentifierNamespace() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003023 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
Douglas Gregor2d435302009-12-30 17:04:44 +00003024 Decl::IDNS_ObjCProtocol)))
3025 continue;
3026
3027 // Protocols are in distinct namespaces from everything else.
3028 if ((((*I)->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
3029 || (IDNS & Decl::IDNS_ObjCProtocol)) &&
3030 (*I)->getIdentifierNamespace() != IDNS)
3031 continue;
3032
Douglas Gregor09bbc652010-01-14 15:47:35 +00003033 // Functions and function templates in the same scope overload
3034 // rather than hide. FIXME: Look for hiding based on function
3035 // signatures!
Alp Tokera2794f92014-01-22 07:29:52 +00003036 if ((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate() &&
3037 ND->getUnderlyingDecl()->isFunctionOrFunctionTemplate() &&
Douglas Gregor09bbc652010-01-14 15:47:35 +00003038 SM == ShadowMaps.rbegin())
Douglas Gregor200c99d2010-01-14 03:35:48 +00003039 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003040
Douglas Gregor2d435302009-12-30 17:04:44 +00003041 // We've found a declaration that hides this one.
3042 return *I;
3043 }
3044 }
3045
3046 return 0;
3047}
3048
3049static void LookupVisibleDecls(DeclContext *Ctx, LookupResult &Result,
3050 bool QualifiedNameLookup,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003051 bool InBaseClass,
Douglas Gregor2d435302009-12-30 17:04:44 +00003052 VisibleDeclConsumer &Consumer,
3053 VisibleDeclsRecord &Visited) {
Douglas Gregor0c8a1722010-02-04 23:42:48 +00003054 if (!Ctx)
3055 return;
3056
Douglas Gregor2d435302009-12-30 17:04:44 +00003057 // Make sure we don't visit the same context twice.
3058 if (Visited.visitedContext(Ctx->getPrimaryContext()))
3059 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003060
Douglas Gregor7454c562010-07-02 20:37:36 +00003061 if (CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(Ctx))
3062 Result.getSema().ForceDeclarationOfImplicitMembers(Class);
3063
Douglas Gregor2d435302009-12-30 17:04:44 +00003064 // Enumerate all of the results in this context.
Aaron Ballman576114e2014-03-14 15:28:49 +00003065 for (const auto &R : Ctx->lookups()) {
3066 for (auto *I : R) {
3067 if (NamedDecl *ND = dyn_cast<NamedDecl>(I)) {
Douglas Gregor4a814562011-12-14 16:03:29 +00003068 if ((ND = Result.getAcceptableDecl(ND))) {
Erik Verbruggen2e657ff2011-10-06 07:27:49 +00003069 Consumer.FoundDecl(ND, Visited.checkHidden(ND), Ctx, InBaseClass);
Douglas Gregor2d435302009-12-30 17:04:44 +00003070 Visited.add(ND);
3071 }
Douglas Gregora3b23b02010-12-09 21:44:02 +00003072 }
Douglas Gregor2d435302009-12-30 17:04:44 +00003073 }
3074 }
3075
3076 // Traverse using directives for qualified name lookup.
3077 if (QualifiedNameLookup) {
3078 ShadowContextRAII Shadow(Visited);
Aaron Ballman63ab7602014-03-07 13:44:44 +00003079 for (auto I : Ctx->getUsingDirectives()) {
3080 LookupVisibleDecls(I->getNominatedNamespace(), Result,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003081 QualifiedNameLookup, InBaseClass, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00003082 }
3083 }
3084
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003085 // Traverse the contexts of inherited C++ classes.
Douglas Gregor2d435302009-12-30 17:04:44 +00003086 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) {
John McCall67da35c2010-02-04 22:26:26 +00003087 if (!Record->hasDefinition())
3088 return;
3089
Aaron Ballman574705e2014-03-13 15:41:46 +00003090 for (const auto &B : Record->bases()) {
3091 QualType BaseType = B.getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003092
Douglas Gregor2d435302009-12-30 17:04:44 +00003093 // Don't look into dependent bases, because name lookup can't look
3094 // there anyway.
3095 if (BaseType->isDependentType())
3096 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003097
Douglas Gregor2d435302009-12-30 17:04:44 +00003098 const RecordType *Record = BaseType->getAs<RecordType>();
3099 if (!Record)
3100 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003101
Douglas Gregor2d435302009-12-30 17:04:44 +00003102 // FIXME: It would be nice to be able to determine whether referencing
3103 // a particular member would be ambiguous. For example, given
3104 //
3105 // struct A { int member; };
3106 // struct B { int member; };
3107 // struct C : A, B { };
3108 //
3109 // void f(C *c) { c->### }
3110 //
3111 // accessing 'member' would result in an ambiguity. However, we
3112 // could be smart enough to qualify the member with the base
3113 // class, e.g.,
3114 //
3115 // c->B::member
3116 //
3117 // or
3118 //
3119 // c->A::member
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003120
Douglas Gregor2d435302009-12-30 17:04:44 +00003121 // Find results in this base class (and its bases).
3122 ShadowContextRAII Shadow(Visited);
3123 LookupVisibleDecls(Record->getDecl(), Result, QualifiedNameLookup,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003124 true, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00003125 }
3126 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003127
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003128 // Traverse the contexts of Objective-C classes.
3129 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Ctx)) {
3130 // Traverse categories.
Aaron Ballman3fe486a2014-03-13 21:23:55 +00003131 for (auto *Cat : IFace->visible_categories()) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003132 ShadowContextRAII Shadow(Visited);
Aaron Ballman3fe486a2014-03-13 21:23:55 +00003133 LookupVisibleDecls(Cat, Result, QualifiedNameLookup, false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003134 Consumer, Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003135 }
3136
3137 // Traverse protocols.
Aaron Ballmana9f49e32014-03-13 20:55:22 +00003138 for (auto *I : IFace->all_referenced_protocols()) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003139 ShadowContextRAII Shadow(Visited);
Aaron Ballmana9f49e32014-03-13 20:55:22 +00003140 LookupVisibleDecls(I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003141 Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003142 }
3143
3144 // Traverse the superclass.
3145 if (IFace->getSuperClass()) {
3146 ShadowContextRAII Shadow(Visited);
3147 LookupVisibleDecls(IFace->getSuperClass(), Result, QualifiedNameLookup,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003148 true, Consumer, Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003149 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003150
Douglas Gregor0b59e802010-04-19 18:02:19 +00003151 // If there is an implementation, traverse it. We do this to find
3152 // synthesized ivars.
3153 if (IFace->getImplementation()) {
3154 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003155 LookupVisibleDecls(IFace->getImplementation(), Result,
Nick Lewycky13668f22012-04-03 20:26:45 +00003156 QualifiedNameLookup, InBaseClass, Consumer, Visited);
Douglas Gregor0b59e802010-04-19 18:02:19 +00003157 }
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003158 } else if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Ctx)) {
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00003159 for (auto *I : Protocol->protocols()) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003160 ShadowContextRAII Shadow(Visited);
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00003161 LookupVisibleDecls(I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003162 Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003163 }
3164 } else if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Ctx)) {
Aaron Ballman19a41762014-03-14 12:55:57 +00003165 for (auto *I : Category->protocols()) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003166 ShadowContextRAII Shadow(Visited);
Aaron Ballman19a41762014-03-14 12:55:57 +00003167 LookupVisibleDecls(I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003168 Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003169 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003170
Douglas Gregor0b59e802010-04-19 18:02:19 +00003171 // If there is an implementation, traverse it.
3172 if (Category->getImplementation()) {
3173 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003174 LookupVisibleDecls(Category->getImplementation(), Result,
Douglas Gregor0b59e802010-04-19 18:02:19 +00003175 QualifiedNameLookup, true, Consumer, Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003176 }
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003177 }
Douglas Gregor2d435302009-12-30 17:04:44 +00003178}
3179
3180static void LookupVisibleDecls(Scope *S, LookupResult &Result,
3181 UnqualUsingDirectiveSet &UDirs,
3182 VisibleDeclConsumer &Consumer,
3183 VisibleDeclsRecord &Visited) {
3184 if (!S)
3185 return;
3186
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003187 if (!S->getEntity() ||
3188 (!S->getParent() &&
Ted Kremenekc37877d2013-10-08 17:08:03 +00003189 !Visited.alreadyVisitedContext(S->getEntity())) ||
3190 (S->getEntity())->isFunctionOrMethod()) {
Richard Smith541b38b2013-09-20 01:15:31 +00003191 FindLocalExternScope FindLocals(Result);
Douglas Gregor712dcfe2010-01-07 00:31:29 +00003192 // Walk through the declarations in this Scope.
3193 for (Scope::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
3194 D != DEnd; ++D) {
John McCall48871652010-08-21 09:40:31 +00003195 if (NamedDecl *ND = dyn_cast<NamedDecl>(*D))
Douglas Gregor4a814562011-12-14 16:03:29 +00003196 if ((ND = Result.getAcceptableDecl(ND))) {
Erik Verbruggen2e657ff2011-10-06 07:27:49 +00003197 Consumer.FoundDecl(ND, Visited.checkHidden(ND), 0, false);
Douglas Gregor712dcfe2010-01-07 00:31:29 +00003198 Visited.add(ND);
3199 }
3200 }
3201 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003202
Douglas Gregor66230062010-03-15 14:33:29 +00003203 // FIXME: C++ [temp.local]p8
Douglas Gregor2d435302009-12-30 17:04:44 +00003204 DeclContext *Entity = 0;
Douglas Gregor4f248632010-01-01 17:44:25 +00003205 if (S->getEntity()) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003206 // Look into this scope's declaration context, along with any of its
3207 // parent lookup contexts (e.g., enclosing classes), up to the point
3208 // where we hit the context stored in the next outer scope.
Ted Kremenekc37877d2013-10-08 17:08:03 +00003209 Entity = S->getEntity();
Douglas Gregor66230062010-03-15 14:33:29 +00003210 DeclContext *OuterCtx = findOuterContext(S).first; // FIXME
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003211
Douglas Gregorea166062010-03-15 15:26:48 +00003212 for (DeclContext *Ctx = Entity; Ctx && !Ctx->Equals(OuterCtx);
Douglas Gregor2d435302009-12-30 17:04:44 +00003213 Ctx = Ctx->getLookupParent()) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003214 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
3215 if (Method->isInstanceMethod()) {
3216 // For instance methods, look for ivars in the method's interface.
3217 LookupResult IvarResult(Result.getSema(), Result.getLookupName(),
3218 Result.getNameLoc(), Sema::LookupMemberName);
Douglas Gregor05fcf842010-11-02 20:36:02 +00003219 if (ObjCInterfaceDecl *IFace = Method->getClassInterface()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003220 LookupVisibleDecls(IFace, IvarResult, /*QualifiedNameLookup=*/false,
Richard Smithe156254d2013-08-20 20:35:18 +00003221 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor05fcf842010-11-02 20:36:02 +00003222 }
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003223 }
3224
3225 // We've already performed all of the name lookup that we need
3226 // to for Objective-C methods; the next context will be the
3227 // outer scope.
3228 break;
3229 }
3230
Douglas Gregor2d435302009-12-30 17:04:44 +00003231 if (Ctx->isFunctionOrMethod())
3232 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003233
3234 LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003235 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00003236 }
3237 } else if (!S->getParent()) {
3238 // Look into the translation unit scope. We walk through the translation
3239 // unit's declaration context, because the Scope itself won't have all of
3240 // the declarations if we loaded a precompiled header.
3241 // FIXME: We would like the translation unit's Scope object to point to the
3242 // translation unit, so we don't need this special "if" branch. However,
3243 // doing so would force the normal C++ name-lookup code to look into the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003244 // translation unit decl when the IdentifierInfo chains would suffice.
Douglas Gregor2d435302009-12-30 17:04:44 +00003245 // Once we fix that problem (which is part of a more general "don't look
Douglas Gregor712dcfe2010-01-07 00:31:29 +00003246 // in DeclContexts unless we have to" optimization), we can eliminate this.
Douglas Gregor2d435302009-12-30 17:04:44 +00003247 Entity = Result.getSema().Context.getTranslationUnitDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003248 LookupVisibleDecls(Entity, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003249 /*InBaseClass=*/false, Consumer, Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003250 }
3251
Douglas Gregor2d435302009-12-30 17:04:44 +00003252 if (Entity) {
3253 // Lookup visible declarations in any namespaces found by using
3254 // directives.
3255 UnqualUsingDirectiveSet::const_iterator UI, UEnd;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00003256 std::tie(UI, UEnd) = UDirs.getNamespacesFor(Entity);
Douglas Gregor2d435302009-12-30 17:04:44 +00003257 for (; UI != UEnd; ++UI)
3258 LookupVisibleDecls(const_cast<DeclContext *>(UI->getNominatedNamespace()),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003259 Result, /*QualifiedNameLookup=*/false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003260 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00003261 }
3262
3263 // Lookup names in the parent scope.
3264 ShadowContextRAII Shadow(Visited);
3265 LookupVisibleDecls(S->getParent(), Result, UDirs, Consumer, Visited);
3266}
3267
3268void Sema::LookupVisibleDecls(Scope *S, LookupNameKind Kind,
Douglas Gregor39982192010-08-15 06:18:01 +00003269 VisibleDeclConsumer &Consumer,
3270 bool IncludeGlobalScope) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003271 // Determine the set of using directives available during
3272 // unqualified name lookup.
3273 Scope *Initial = S;
3274 UnqualUsingDirectiveSet UDirs;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003275 if (getLangOpts().CPlusPlus) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003276 // Find the first namespace or translation-unit scope.
3277 while (S && !isNamespaceOrTranslationUnitScope(S))
3278 S = S->getParent();
3279
3280 UDirs.visitScopeChain(Initial, S);
3281 }
3282 UDirs.done();
3283
3284 // Look for visible declarations.
3285 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
Richard Smithe156254d2013-08-20 20:35:18 +00003286 Result.setAllowHidden(Consumer.includeHiddenDecls());
Douglas Gregor2d435302009-12-30 17:04:44 +00003287 VisibleDeclsRecord Visited;
Douglas Gregor39982192010-08-15 06:18:01 +00003288 if (!IncludeGlobalScope)
3289 Visited.visitedContext(Context.getTranslationUnitDecl());
Douglas Gregor2d435302009-12-30 17:04:44 +00003290 ShadowContextRAII Shadow(Visited);
3291 ::LookupVisibleDecls(Initial, Result, UDirs, Consumer, Visited);
3292}
3293
3294void Sema::LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
Douglas Gregor39982192010-08-15 06:18:01 +00003295 VisibleDeclConsumer &Consumer,
3296 bool IncludeGlobalScope) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003297 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
Richard Smithe156254d2013-08-20 20:35:18 +00003298 Result.setAllowHidden(Consumer.includeHiddenDecls());
Douglas Gregor2d435302009-12-30 17:04:44 +00003299 VisibleDeclsRecord Visited;
Douglas Gregor39982192010-08-15 06:18:01 +00003300 if (!IncludeGlobalScope)
3301 Visited.visitedContext(Context.getTranslationUnitDecl());
Douglas Gregor2d435302009-12-30 17:04:44 +00003302 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003303 ::LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/true,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003304 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00003305}
3306
Chris Lattner43e7f312011-02-18 02:08:43 +00003307/// LookupOrCreateLabel - Do a name lookup of a label with the specified name.
Abramo Bagnara1c3af962011-03-05 18:21:20 +00003308/// If GnuLabelLoc is a valid source location, then this is a definition
3309/// of an __label__ label name, otherwise it is a normal label definition
3310/// or use.
Chris Lattner43e7f312011-02-18 02:08:43 +00003311LabelDecl *Sema::LookupOrCreateLabel(IdentifierInfo *II, SourceLocation Loc,
Abramo Bagnara1c3af962011-03-05 18:21:20 +00003312 SourceLocation GnuLabelLoc) {
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003313 // Do a lookup to see if we have a label with this name already.
Chris Lattner43e7f312011-02-18 02:08:43 +00003314 NamedDecl *Res = 0;
Abramo Bagnara1c3af962011-03-05 18:21:20 +00003315
3316 if (GnuLabelLoc.isValid()) {
3317 // Local label definitions always shadow existing labels.
3318 Res = LabelDecl::Create(Context, CurContext, Loc, II, GnuLabelLoc);
3319 Scope *S = CurScope;
3320 PushOnScopeChains(Res, S, true);
3321 return cast<LabelDecl>(Res);
3322 }
3323
3324 // Not a GNU local label.
3325 Res = LookupSingleName(CurScope, II, Loc, LookupLabel, NotForRedeclaration);
3326 // If we found a label, check to see if it is in the same context as us.
3327 // When in a Block, we don't want to reuse a label in an enclosing function.
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003328 if (Res && Res->getDeclContext() != CurContext)
3329 Res = 0;
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003330 if (Res == 0) {
3331 // If not forward referenced or defined already, create the backing decl.
Abramo Bagnara1c3af962011-03-05 18:21:20 +00003332 Res = LabelDecl::Create(Context, CurContext, Loc, II);
3333 Scope *S = CurScope->getFnParent();
Chris Lattner9ba479b2011-02-18 21:16:39 +00003334 assert(S && "Not in a function?");
3335 PushOnScopeChains(Res, S, true);
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003336 }
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003337 return cast<LabelDecl>(Res);
3338}
3339
3340//===----------------------------------------------------------------------===//
Douglas Gregor2d435302009-12-30 17:04:44 +00003341// Typo correction
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003342//===----------------------------------------------------------------------===//
Douglas Gregor2d435302009-12-30 17:04:44 +00003343
3344namespace {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003345
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003346typedef SmallVector<TypoCorrection, 1> TypoResultList;
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00003347typedef llvm::StringMap<TypoResultList, llvm::BumpPtrAllocator> TypoResultsMap;
Benjamin Kramer73faad62012-04-14 08:26:28 +00003348typedef std::map<unsigned, TypoResultsMap> TypoEditDistanceMap;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003349
3350static const unsigned MaxTypoDistanceResultSets = 5;
3351
Douglas Gregor2d435302009-12-30 17:04:44 +00003352class TypoCorrectionConsumer : public VisibleDeclConsumer {
3353 /// \brief The name written that is a typo in the source.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003354 StringRef Typo;
Douglas Gregor2d435302009-12-30 17:04:44 +00003355
3356 /// \brief The results found that have the smallest edit distance
3357 /// found (so far) with the typo name.
Douglas Gregor0afa7f62010-10-14 20:34:08 +00003358 ///
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003359 /// The pointer value being set to the current DeclContext indicates
3360 /// whether there is a keyword with this name.
Kaelyn Uhrain34fab552012-05-31 23:32:58 +00003361 TypoEditDistanceMap CorrectionResults;
Douglas Gregor2d435302009-12-30 17:04:44 +00003362
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003363 Sema &SemaRef;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003364
Douglas Gregor2d435302009-12-30 17:04:44 +00003365public:
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003366 explicit TypoCorrectionConsumer(Sema &SemaRef, IdentifierInfo *Typo)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003367 : Typo(Typo->getName()),
Richard Smithe156254d2013-08-20 20:35:18 +00003368 SemaRef(SemaRef) {}
3369
Craig Toppere14c0f82014-03-12 04:55:44 +00003370 bool includeHiddenDecls() const override { return true; }
Douglas Gregor2d435302009-12-30 17:04:44 +00003371
Craig Toppere14c0f82014-03-12 04:55:44 +00003372 void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, DeclContext *Ctx,
3373 bool InBaseClass) override;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003374 void FoundName(StringRef Name);
3375 void addKeywordResult(StringRef Keyword);
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00003376 void addName(StringRef Name, NamedDecl *ND, NestedNameSpecifier *NNS = NULL,
3377 bool isKeyword = false);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003378 void addCorrection(TypoCorrection Correction);
Douglas Gregor2d435302009-12-30 17:04:44 +00003379
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003380 typedef TypoResultsMap::iterator result_iterator;
3381 typedef TypoEditDistanceMap::iterator distance_iterator;
Kaelyn Uhrain34fab552012-05-31 23:32:58 +00003382 distance_iterator begin() { return CorrectionResults.begin(); }
3383 distance_iterator end() { return CorrectionResults.end(); }
3384 void erase(distance_iterator I) { CorrectionResults.erase(I); }
3385 unsigned size() const { return CorrectionResults.size(); }
3386 bool empty() const { return CorrectionResults.empty(); }
Douglas Gregor2d435302009-12-30 17:04:44 +00003387
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00003388 TypoResultList &operator[](StringRef Name) {
Kaelyn Uhrain34fab552012-05-31 23:32:58 +00003389 return CorrectionResults.begin()->second[Name];
Douglas Gregoraf9eb592010-10-15 13:35:25 +00003390 }
3391
Kaelyn Uhrain0a16a8e2012-02-14 18:56:48 +00003392 unsigned getBestEditDistance(bool Normalized) {
Kaelyn Uhrain34fab552012-05-31 23:32:58 +00003393 if (CorrectionResults.empty())
Kaelyn Uhrain0a16a8e2012-02-14 18:56:48 +00003394 return (std::numeric_limits<unsigned>::max)();
3395
Kaelyn Uhrain34fab552012-05-31 23:32:58 +00003396 unsigned BestED = CorrectionResults.begin()->first;
Kaelyn Uhrain0a16a8e2012-02-14 18:56:48 +00003397 return Normalized ? TypoCorrection::NormalizeEditDistance(BestED) : BestED;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003398 }
Kaelyn Uhrain34fab552012-05-31 23:32:58 +00003399
3400 TypoResultsMap &getBestResults() {
3401 return CorrectionResults.begin()->second;
3402 }
3403
Douglas Gregor2d435302009-12-30 17:04:44 +00003404};
3405
3406}
3407
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003408void TypoCorrectionConsumer::FoundDecl(NamedDecl *ND, NamedDecl *Hiding,
Erik Verbruggen2e657ff2011-10-06 07:27:49 +00003409 DeclContext *Ctx, bool InBaseClass) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003410 // Don't consider hidden names for typo correction.
3411 if (Hiding)
3412 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003413
Douglas Gregor2d435302009-12-30 17:04:44 +00003414 // Only consider entities with identifiers for names, ignoring
3415 // special names (constructors, overloaded operators, selectors,
3416 // etc.).
3417 IdentifierInfo *Name = ND->getIdentifier();
3418 if (!Name)
3419 return;
3420
Richard Smithe156254d2013-08-20 20:35:18 +00003421 // Only consider visible declarations and declarations from modules with
3422 // names that exactly match.
3423 if (!LookupResult::isVisible(SemaRef, ND) && Name->getName() != Typo &&
3424 !findAcceptableDecl(SemaRef, ND))
3425 return;
3426
Douglas Gregor57756ea2010-10-14 22:11:03 +00003427 FoundName(Name->getName());
3428}
3429
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003430void TypoCorrectionConsumer::FoundName(StringRef Name) {
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00003431 // Compute the edit distance between the typo and the name of this
3432 // entity, and add the identifier to the list of results.
3433 addName(Name, NULL);
3434}
3435
3436void TypoCorrectionConsumer::addKeywordResult(StringRef Keyword) {
3437 // Compute the edit distance between the typo and this keyword,
3438 // and add the keyword to the list of results.
3439 addName(Keyword, NULL, NULL, true);
3440}
3441
3442void TypoCorrectionConsumer::addName(StringRef Name, NamedDecl *ND,
3443 NestedNameSpecifier *NNS, bool isKeyword) {
Douglas Gregor93910a52010-10-19 19:39:10 +00003444 // Use a simple length-based heuristic to determine the minimum possible
3445 // edit distance. If the minimum isn't good enough, bail out early.
3446 unsigned MinED = abs((int)Name.size() - (int)Typo.size());
Kaelyn Uhrain1c75d402012-02-07 01:32:58 +00003447 if (MinED && Typo.size() / MinED < 3)
Douglas Gregor93910a52010-10-19 19:39:10 +00003448 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003449
Douglas Gregorc1fb15e2010-10-19 22:14:33 +00003450 // Compute an upper bound on the allowable edit distance, so that the
3451 // edit-distance algorithm can short-circuit.
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00003452 unsigned UpperBound = (Typo.size() + 2) / 3 + 1;
3453 unsigned ED = Typo.edit_distance(Name, true, UpperBound);
3454 if (ED >= UpperBound) return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003455
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00003456 TypoCorrection TC(&SemaRef.Context.Idents.get(Name), ND, NNS, ED);
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00003457 if (isKeyword) TC.makeKeyword();
3458 addCorrection(TC);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003459}
3460
3461void TypoCorrectionConsumer::addCorrection(TypoCorrection Correction) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003462 StringRef Name = Correction.getCorrectionAsIdentifierInfo()->getName();
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00003463 TypoResultList &CList =
3464 CorrectionResults[Correction.getEditDistance(false)][Name];
Chandler Carruth7d85c9b2011-06-28 22:48:40 +00003465
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00003466 if (!CList.empty() && !CList.back().isResolved())
3467 CList.pop_back();
3468 if (NamedDecl *NewND = Correction.getCorrectionDecl()) {
3469 std::string CorrectionStr = Correction.getAsString(SemaRef.getLangOpts());
3470 for (TypoResultList::iterator RI = CList.begin(), RIEnd = CList.end();
3471 RI != RIEnd; ++RI) {
3472 // If the Correction refers to a decl already in the result list,
3473 // replace the existing result if the string representation of Correction
3474 // comes before the current result alphabetically, then stop as there is
3475 // nothing more to be done to add Correction to the candidate set.
3476 if (RI->getCorrectionDecl() == NewND) {
3477 if (CorrectionStr < RI->getAsString(SemaRef.getLangOpts()))
3478 *RI = Correction;
3479 return;
3480 }
3481 }
3482 }
3483 if (CList.empty() || Correction.isResolved())
3484 CList.push_back(Correction);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003485
Kaelyn Uhrain34fab552012-05-31 23:32:58 +00003486 while (CorrectionResults.size() > MaxTypoDistanceResultSets)
Benjamin Kramer167e9992014-03-02 12:20:24 +00003487 erase(std::prev(CorrectionResults.end()));
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003488}
3489
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003490// Fill the supplied vector with the IdentifierInfo pointers for each piece of
3491// the given NestedNameSpecifier (i.e. given a NestedNameSpecifier "foo::bar::",
3492// fill the vector with the IdentifierInfo pointers for "foo" and "bar").
3493static void getNestedNameSpecifierIdentifiers(
3494 NestedNameSpecifier *NNS,
3495 SmallVectorImpl<const IdentifierInfo*> &Identifiers) {
3496 if (NestedNameSpecifier *Prefix = NNS->getPrefix())
3497 getNestedNameSpecifierIdentifiers(Prefix, Identifiers);
3498 else
3499 Identifiers.clear();
3500
3501 const IdentifierInfo *II = NULL;
3502
3503 switch (NNS->getKind()) {
3504 case NestedNameSpecifier::Identifier:
3505 II = NNS->getAsIdentifier();
3506 break;
3507
3508 case NestedNameSpecifier::Namespace:
3509 if (NNS->getAsNamespace()->isAnonymousNamespace())
3510 return;
3511 II = NNS->getAsNamespace()->getIdentifier();
3512 break;
3513
3514 case NestedNameSpecifier::NamespaceAlias:
3515 II = NNS->getAsNamespaceAlias()->getIdentifier();
3516 break;
3517
3518 case NestedNameSpecifier::TypeSpecWithTemplate:
3519 case NestedNameSpecifier::TypeSpec:
3520 II = QualType(NNS->getAsType(), 0).getBaseTypeIdentifier();
3521 break;
3522
3523 case NestedNameSpecifier::Global:
3524 return;
3525 }
3526
3527 if (II)
3528 Identifiers.push_back(II);
3529}
3530
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003531namespace {
3532
3533class SpecifierInfo {
3534 public:
3535 DeclContext* DeclCtx;
3536 NestedNameSpecifier* NameSpecifier;
3537 unsigned EditDistance;
3538
3539 SpecifierInfo(DeclContext *Ctx, NestedNameSpecifier *NNS, unsigned ED)
3540 : DeclCtx(Ctx), NameSpecifier(NNS), EditDistance(ED) {}
3541};
3542
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003543typedef SmallVector<DeclContext*, 4> DeclContextList;
3544typedef SmallVector<SpecifierInfo, 16> SpecifierInfoList;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003545
3546class NamespaceSpecifierSet {
3547 ASTContext &Context;
3548 DeclContextList CurContextChain;
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00003549 std::string CurNameSpecifier;
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003550 SmallVector<const IdentifierInfo*, 4> CurContextIdentifiers;
3551 SmallVector<const IdentifierInfo*, 4> CurNameSpecifierIdentifiers;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003552 bool isSorted;
3553
3554 SpecifierInfoList Specifiers;
3555 llvm::SmallSetVector<unsigned, 4> Distances;
3556 llvm::DenseMap<unsigned, SpecifierInfoList> DistanceMap;
3557
3558 /// \brief Helper for building the list of DeclContexts between the current
3559 /// context and the top of the translation unit
3560 static DeclContextList BuildContextChain(DeclContext *Start);
3561
3562 void SortNamespaces();
3563
3564 public:
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003565 NamespaceSpecifierSet(ASTContext &Context, DeclContext *CurContext,
3566 CXXScopeSpec *CurScopeSpec)
Benjamin Kramerde1d6232011-07-05 09:46:31 +00003567 : Context(Context), CurContextChain(BuildContextChain(CurContext)),
Kaelyn Uhrain52dd02d2013-06-24 17:49:03 +00003568 isSorted(false) {
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00003569 if (NestedNameSpecifier *NNS =
3570 CurScopeSpec ? CurScopeSpec->getScopeRep() : 0) {
3571 llvm::raw_string_ostream SpecifierOStream(CurNameSpecifier);
3572 NNS->print(SpecifierOStream, Context.getPrintingPolicy());
3573
3574 getNestedNameSpecifierIdentifiers(NNS, CurNameSpecifierIdentifiers);
3575 }
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003576 // Build the list of identifiers that would be used for an absolute
Benjamin Kramer474261a2012-06-02 10:20:41 +00003577 // (from the global context) NestedNameSpecifier referring to the current
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003578 // context.
3579 for (DeclContextList::reverse_iterator C = CurContextChain.rbegin(),
3580 CEnd = CurContextChain.rend();
3581 C != CEnd; ++C) {
3582 if (NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(*C))
3583 CurContextIdentifiers.push_back(ND->getIdentifier());
3584 }
Kaelyn Uhrain52dd02d2013-06-24 17:49:03 +00003585
3586 // Add the global context as a NestedNameSpecifier
3587 Distances.insert(1);
3588 DistanceMap[1].push_back(
3589 SpecifierInfo(cast<DeclContext>(Context.getTranslationUnitDecl()),
3590 NestedNameSpecifier::GlobalSpecifier(Context), 1));
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003591 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003592
Kaelyn Uhrain5315a462013-10-19 00:04:49 +00003593 /// \brief Add the DeclContext (a namespace or record) to the set, computing
3594 /// the corresponding NestedNameSpecifier and its distance in the process.
3595 void AddNameSpecifier(DeclContext *Ctx);
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00003596
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003597 typedef SpecifierInfoList::iterator iterator;
3598 iterator begin() {
3599 if (!isSorted) SortNamespaces();
3600 return Specifiers.begin();
3601 }
3602 iterator end() { return Specifiers.end(); }
3603};
3604
3605}
3606
3607DeclContextList NamespaceSpecifierSet::BuildContextChain(DeclContext *Start) {
Nick Lewycky0d9b3192013-04-08 21:55:21 +00003608 assert(Start && "Building a context chain from a null context");
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003609 DeclContextList Chain;
3610 for (DeclContext *DC = Start->getPrimaryContext(); DC != NULL;
3611 DC = DC->getLookupParent()) {
3612 NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(DC);
3613 if (!DC->isInlineNamespace() && !DC->isTransparentContext() &&
3614 !(ND && ND->isAnonymousNamespace()))
3615 Chain.push_back(DC->getPrimaryContext());
3616 }
3617 return Chain;
3618}
3619
3620void NamespaceSpecifierSet::SortNamespaces() {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003621 SmallVector<unsigned, 4> sortedDistances;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003622 sortedDistances.append(Distances.begin(), Distances.end());
3623
3624 if (sortedDistances.size() > 1)
3625 std::sort(sortedDistances.begin(), sortedDistances.end());
3626
3627 Specifiers.clear();
Craig Topper2341c0d2013-07-04 03:08:24 +00003628 for (SmallVectorImpl<unsigned>::iterator DI = sortedDistances.begin(),
3629 DIEnd = sortedDistances.end();
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003630 DI != DIEnd; ++DI) {
3631 SpecifierInfoList &SpecList = DistanceMap[*DI];
3632 Specifiers.append(SpecList.begin(), SpecList.end());
3633 }
3634
3635 isSorted = true;
3636}
3637
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00003638static unsigned BuildNestedNameSpecifier(ASTContext &Context,
3639 DeclContextList &DeclChain,
3640 NestedNameSpecifier *&NNS) {
3641 unsigned NumSpecifiers = 0;
3642 for (DeclContextList::reverse_iterator C = DeclChain.rbegin(),
3643 CEnd = DeclChain.rend();
3644 C != CEnd; ++C) {
3645 if (NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(*C)) {
3646 NNS = NestedNameSpecifier::Create(Context, NNS, ND);
3647 ++NumSpecifiers;
3648 } else if (RecordDecl *RD = dyn_cast_or_null<RecordDecl>(*C)) {
3649 NNS = NestedNameSpecifier::Create(Context, NNS, RD->isTemplateDecl(),
3650 RD->getTypeForDecl());
3651 ++NumSpecifiers;
3652 }
3653 }
3654 return NumSpecifiers;
3655}
3656
Kaelyn Uhrain5315a462013-10-19 00:04:49 +00003657void NamespaceSpecifierSet::AddNameSpecifier(DeclContext *Ctx) {
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00003658 NestedNameSpecifier *NNS = NULL;
3659 unsigned NumSpecifiers = 0;
3660 DeclContextList NamespaceDeclChain(BuildContextChain(Ctx));
3661 DeclContextList FullNamespaceDeclChain(NamespaceDeclChain);
3662
3663 // Eliminate common elements from the two DeclContext chains.
3664 for (DeclContextList::reverse_iterator C = CurContextChain.rbegin(),
3665 CEnd = CurContextChain.rend();
3666 C != CEnd && !NamespaceDeclChain.empty() &&
3667 NamespaceDeclChain.back() == *C; ++C) {
3668 NamespaceDeclChain.pop_back();
3669 }
3670
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00003671 // Build the NestedNameSpecifier from what is left of the NamespaceDeclChain
3672 NumSpecifiers = BuildNestedNameSpecifier(Context, NamespaceDeclChain, NNS);
3673
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00003674 // Add an explicit leading '::' specifier if needed.
3675 if (NamespaceDeclChain.empty()) {
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00003676 // Rebuild the NestedNameSpecifier as a globally-qualified specifier.
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00003677 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00003678 NumSpecifiers =
3679 BuildNestedNameSpecifier(Context, FullNamespaceDeclChain, NNS);
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00003680 } else if (NamedDecl *ND =
3681 dyn_cast_or_null<NamedDecl>(NamespaceDeclChain.back())) {
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00003682 IdentifierInfo *Name = ND->getIdentifier();
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00003683 bool SameNameSpecifier = false;
3684 if (std::find(CurNameSpecifierIdentifiers.begin(),
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00003685 CurNameSpecifierIdentifiers.end(),
3686 Name) != CurNameSpecifierIdentifiers.end()) {
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00003687 std::string NewNameSpecifier;
3688 llvm::raw_string_ostream SpecifierOStream(NewNameSpecifier);
3689 SmallVector<const IdentifierInfo *, 4> NewNameSpecifierIdentifiers;
3690 getNestedNameSpecifierIdentifiers(NNS, NewNameSpecifierIdentifiers);
3691 NNS->print(SpecifierOStream, Context.getPrintingPolicy());
3692 SpecifierOStream.flush();
3693 SameNameSpecifier = NewNameSpecifier == CurNameSpecifier;
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00003694 }
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00003695 if (SameNameSpecifier ||
3696 std::find(CurContextIdentifiers.begin(), CurContextIdentifiers.end(),
3697 Name) != CurContextIdentifiers.end()) {
3698 // Rebuild the NestedNameSpecifier as a globally-qualified specifier.
3699 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
3700 NumSpecifiers =
3701 BuildNestedNameSpecifier(Context, FullNamespaceDeclChain, NNS);
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00003702 }
3703 }
3704
3705 // If the built NestedNameSpecifier would be replacing an existing
3706 // NestedNameSpecifier, use the number of component identifiers that
3707 // would need to be changed as the edit distance instead of the number
3708 // of components in the built NestedNameSpecifier.
3709 if (NNS && !CurNameSpecifierIdentifiers.empty()) {
3710 SmallVector<const IdentifierInfo*, 4> NewNameSpecifierIdentifiers;
3711 getNestedNameSpecifierIdentifiers(NNS, NewNameSpecifierIdentifiers);
3712 NumSpecifiers = llvm::ComputeEditDistance(
3713 ArrayRef<const IdentifierInfo *>(CurNameSpecifierIdentifiers),
3714 ArrayRef<const IdentifierInfo *>(NewNameSpecifierIdentifiers));
3715 }
3716
3717 isSorted = false;
3718 Distances.insert(NumSpecifiers);
3719 DistanceMap[NumSpecifiers].push_back(SpecifierInfo(Ctx, NNS, NumSpecifiers));
3720}
3721
Douglas Gregord507d772010-10-20 03:06:34 +00003722/// \brief Perform name lookup for a possible result for typo correction.
3723static void LookupPotentialTypoResult(Sema &SemaRef,
3724 LookupResult &Res,
3725 IdentifierInfo *Name,
3726 Scope *S, CXXScopeSpec *SS,
3727 DeclContext *MemberContext,
3728 bool EnteringContext,
Richard Smithe156254d2013-08-20 20:35:18 +00003729 bool isObjCIvarLookup,
3730 bool FindHidden) {
Douglas Gregord507d772010-10-20 03:06:34 +00003731 Res.suppressDiagnostics();
3732 Res.clear();
3733 Res.setLookupName(Name);
Richard Smithe156254d2013-08-20 20:35:18 +00003734 Res.setAllowHidden(FindHidden);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003735 if (MemberContext) {
Douglas Gregord507d772010-10-20 03:06:34 +00003736 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(MemberContext)) {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003737 if (isObjCIvarLookup) {
Douglas Gregord507d772010-10-20 03:06:34 +00003738 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(Name)) {
3739 Res.addDecl(Ivar);
3740 Res.resolveKind();
3741 return;
3742 }
3743 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003744
Douglas Gregord507d772010-10-20 03:06:34 +00003745 if (ObjCPropertyDecl *Prop = Class->FindPropertyDeclaration(Name)) {
3746 Res.addDecl(Prop);
3747 Res.resolveKind();
3748 return;
3749 }
3750 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003751
Douglas Gregord507d772010-10-20 03:06:34 +00003752 SemaRef.LookupQualifiedName(Res, MemberContext);
3753 return;
3754 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003755
3756 SemaRef.LookupParsedName(Res, S, SS, /*AllowBuiltinCreation=*/false,
Douglas Gregord507d772010-10-20 03:06:34 +00003757 EnteringContext);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003758
Douglas Gregord507d772010-10-20 03:06:34 +00003759 // Fake ivar lookup; this should really be part of
3760 // LookupParsedName.
3761 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) {
3762 if (Method->isInstanceMethod() && Method->getClassInterface() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003763 (Res.empty() ||
Douglas Gregord507d772010-10-20 03:06:34 +00003764 (Res.isSingleResult() &&
3765 Res.getFoundDecl()->isDefinedOutsideFunctionOrMethod()))) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003766 if (ObjCIvarDecl *IV
Douglas Gregord507d772010-10-20 03:06:34 +00003767 = Method->getClassInterface()->lookupInstanceVariable(Name)) {
3768 Res.addDecl(IV);
3769 Res.resolveKind();
3770 }
3771 }
3772 }
3773}
3774
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003775/// \brief Add keywords to the consumer as possible typo corrections.
3776static void AddKeywordsToConsumer(Sema &SemaRef,
3777 TypoCorrectionConsumer &Consumer,
Richard Smithb3a1df02012-06-08 21:35:42 +00003778 Scope *S, CorrectionCandidateCallback &CCC,
3779 bool AfterNestedNameSpecifier) {
3780 if (AfterNestedNameSpecifier) {
3781 // For 'X::', we know exactly which keywords can appear next.
3782 Consumer.addKeywordResult("template");
3783 if (CCC.WantExpressionKeywords)
3784 Consumer.addKeywordResult("operator");
3785 return;
3786 }
3787
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003788 if (CCC.WantObjCSuper)
3789 Consumer.addKeywordResult("super");
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003790
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003791 if (CCC.WantTypeSpecifiers) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003792 // Add type-specifier keywords to the set of results.
Craig Topperd6d31ac2013-07-15 08:24:27 +00003793 static const char *const CTypeSpecs[] = {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003794 "char", "const", "double", "enum", "float", "int", "long", "short",
Douglas Gregor3b22a882011-07-01 21:27:45 +00003795 "signed", "struct", "union", "unsigned", "void", "volatile",
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003796 "_Complex", "_Imaginary",
3797 // storage-specifiers as well
3798 "extern", "inline", "static", "typedef"
3799 };
3800
Craig Toppere5ce8312013-07-15 03:38:40 +00003801 const unsigned NumCTypeSpecs = llvm::array_lengthof(CTypeSpecs);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003802 for (unsigned I = 0; I != NumCTypeSpecs; ++I)
3803 Consumer.addKeywordResult(CTypeSpecs[I]);
3804
David Blaikiebbafb8a2012-03-11 07:00:24 +00003805 if (SemaRef.getLangOpts().C99)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003806 Consumer.addKeywordResult("restrict");
David Blaikiebbafb8a2012-03-11 07:00:24 +00003807 if (SemaRef.getLangOpts().Bool || SemaRef.getLangOpts().CPlusPlus)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003808 Consumer.addKeywordResult("bool");
David Blaikiebbafb8a2012-03-11 07:00:24 +00003809 else if (SemaRef.getLangOpts().C99)
Douglas Gregor3b22a882011-07-01 21:27:45 +00003810 Consumer.addKeywordResult("_Bool");
3811
David Blaikiebbafb8a2012-03-11 07:00:24 +00003812 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003813 Consumer.addKeywordResult("class");
3814 Consumer.addKeywordResult("typename");
3815 Consumer.addKeywordResult("wchar_t");
3816
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003817 if (SemaRef.getLangOpts().CPlusPlus11) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003818 Consumer.addKeywordResult("char16_t");
3819 Consumer.addKeywordResult("char32_t");
3820 Consumer.addKeywordResult("constexpr");
3821 Consumer.addKeywordResult("decltype");
3822 Consumer.addKeywordResult("thread_local");
3823 }
3824 }
3825
David Blaikiebbafb8a2012-03-11 07:00:24 +00003826 if (SemaRef.getLangOpts().GNUMode)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003827 Consumer.addKeywordResult("typeof");
3828 }
3829
David Blaikiebbafb8a2012-03-11 07:00:24 +00003830 if (CCC.WantCXXNamedCasts && SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003831 Consumer.addKeywordResult("const_cast");
3832 Consumer.addKeywordResult("dynamic_cast");
3833 Consumer.addKeywordResult("reinterpret_cast");
3834 Consumer.addKeywordResult("static_cast");
3835 }
3836
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003837 if (CCC.WantExpressionKeywords) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003838 Consumer.addKeywordResult("sizeof");
David Blaikiebbafb8a2012-03-11 07:00:24 +00003839 if (SemaRef.getLangOpts().Bool || SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003840 Consumer.addKeywordResult("false");
3841 Consumer.addKeywordResult("true");
3842 }
3843
David Blaikiebbafb8a2012-03-11 07:00:24 +00003844 if (SemaRef.getLangOpts().CPlusPlus) {
Craig Topperd6d31ac2013-07-15 08:24:27 +00003845 static const char *const CXXExprs[] = {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003846 "delete", "new", "operator", "throw", "typeid"
3847 };
Craig Toppere5ce8312013-07-15 03:38:40 +00003848 const unsigned NumCXXExprs = llvm::array_lengthof(CXXExprs);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003849 for (unsigned I = 0; I != NumCXXExprs; ++I)
3850 Consumer.addKeywordResult(CXXExprs[I]);
3851
3852 if (isa<CXXMethodDecl>(SemaRef.CurContext) &&
3853 cast<CXXMethodDecl>(SemaRef.CurContext)->isInstance())
3854 Consumer.addKeywordResult("this");
3855
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003856 if (SemaRef.getLangOpts().CPlusPlus11) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003857 Consumer.addKeywordResult("alignof");
3858 Consumer.addKeywordResult("nullptr");
3859 }
3860 }
Jordan Rose58d54722012-06-30 21:33:57 +00003861
3862 if (SemaRef.getLangOpts().C11) {
3863 // FIXME: We should not suggest _Alignof if the alignof macro
3864 // is present.
3865 Consumer.addKeywordResult("_Alignof");
3866 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003867 }
3868
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003869 if (CCC.WantRemainingKeywords) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003870 if (SemaRef.getCurFunctionOrMethodDecl() || SemaRef.getCurBlock()) {
3871 // Statements.
Craig Topperd6d31ac2013-07-15 08:24:27 +00003872 static const char *const CStmts[] = {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003873 "do", "else", "for", "goto", "if", "return", "switch", "while" };
Craig Toppere5ce8312013-07-15 03:38:40 +00003874 const unsigned NumCStmts = llvm::array_lengthof(CStmts);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003875 for (unsigned I = 0; I != NumCStmts; ++I)
3876 Consumer.addKeywordResult(CStmts[I]);
3877
David Blaikiebbafb8a2012-03-11 07:00:24 +00003878 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003879 Consumer.addKeywordResult("catch");
3880 Consumer.addKeywordResult("try");
3881 }
3882
3883 if (S && S->getBreakParent())
3884 Consumer.addKeywordResult("break");
3885
3886 if (S && S->getContinueParent())
3887 Consumer.addKeywordResult("continue");
3888
3889 if (!SemaRef.getCurFunction()->SwitchStack.empty()) {
3890 Consumer.addKeywordResult("case");
3891 Consumer.addKeywordResult("default");
3892 }
3893 } else {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003894 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003895 Consumer.addKeywordResult("namespace");
3896 Consumer.addKeywordResult("template");
3897 }
3898
3899 if (S && S->isClassScope()) {
3900 Consumer.addKeywordResult("explicit");
3901 Consumer.addKeywordResult("friend");
3902 Consumer.addKeywordResult("mutable");
3903 Consumer.addKeywordResult("private");
3904 Consumer.addKeywordResult("protected");
3905 Consumer.addKeywordResult("public");
3906 Consumer.addKeywordResult("virtual");
3907 }
3908 }
3909
David Blaikiebbafb8a2012-03-11 07:00:24 +00003910 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003911 Consumer.addKeywordResult("using");
3912
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003913 if (SemaRef.getLangOpts().CPlusPlus11)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003914 Consumer.addKeywordResult("static_assert");
3915 }
3916 }
3917}
3918
Kaelyn Uhrain0a16a8e2012-02-14 18:56:48 +00003919static bool isCandidateViable(CorrectionCandidateCallback &CCC,
3920 TypoCorrection &Candidate) {
3921 Candidate.setCallbackDistance(CCC.RankCandidate(Candidate));
3922 return Candidate.getEditDistance(false) != TypoCorrection::InvalidDistance;
3923}
3924
Richard Smithe156254d2013-08-20 20:35:18 +00003925/// \brief Check whether the declarations found for a typo correction are
3926/// visible, and if none of them are, convert the correction to an 'import
3927/// a module' correction.
3928static void checkCorrectionVisibility(Sema &SemaRef, TypoCorrection &TC,
3929 DeclarationName TypoName) {
3930 if (TC.begin() == TC.end())
3931 return;
3932
3933 TypoCorrection::decl_iterator DI = TC.begin(), DE = TC.end();
3934
3935 for (/**/; DI != DE; ++DI)
3936 if (!LookupResult::isVisible(SemaRef, *DI))
3937 break;
3938 // Nothing to do if all decls are visible.
3939 if (DI == DE)
3940 return;
3941
3942 llvm::SmallVector<NamedDecl*, 4> NewDecls(TC.begin(), DI);
3943 bool AnyVisibleDecls = !NewDecls.empty();
3944
3945 for (/**/; DI != DE; ++DI) {
3946 NamedDecl *VisibleDecl = *DI;
3947 if (!LookupResult::isVisible(SemaRef, *DI))
3948 VisibleDecl = findAcceptableDecl(SemaRef, *DI);
3949
3950 if (VisibleDecl) {
3951 if (!AnyVisibleDecls) {
3952 // Found a visible decl, discard all hidden ones.
3953 AnyVisibleDecls = true;
3954 NewDecls.clear();
3955 }
3956 NewDecls.push_back(VisibleDecl);
3957 } else if (!AnyVisibleDecls && !(*DI)->isModulePrivate())
3958 NewDecls.push_back(*DI);
3959 }
3960
3961 if (NewDecls.empty())
3962 TC = TypoCorrection();
3963 else {
3964 TC.setCorrectionDecls(NewDecls);
3965 TC.setRequiresImport(!AnyVisibleDecls);
3966 }
3967}
3968
Douglas Gregor2d435302009-12-30 17:04:44 +00003969/// \brief Try to "correct" a typo in the source code by finding
3970/// visible declarations whose names are similar to the name that was
3971/// present in the source code.
3972///
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003973/// \param TypoName the \c DeclarationNameInfo structure that contains
3974/// the name that was present in the source code along with its location.
3975///
3976/// \param LookupKind the name-lookup criteria used to search for the name.
Douglas Gregor2d435302009-12-30 17:04:44 +00003977///
3978/// \param S the scope in which name lookup occurs.
3979///
3980/// \param SS the nested-name-specifier that precedes the name we're
3981/// looking for, if present.
3982///
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003983/// \param CCC A CorrectionCandidateCallback object that provides further
3984/// validation of typo correction candidates. It also provides flags for
3985/// determining the set of keywords permitted.
3986///
Douglas Gregoraf2bd472009-12-31 07:42:17 +00003987/// \param MemberContext if non-NULL, the context in which to look for
3988/// a member access expression.
3989///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003990/// \param EnteringContext whether we're entering the context described by
Douglas Gregor598b08f2009-12-31 05:20:13 +00003991/// the nested-name-specifier SS.
3992///
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003993/// \param OPT when non-NULL, the search for visible declarations will
3994/// also walk the protocols in the qualified interfaces of \p OPT.
3995///
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003996/// \returns a \c TypoCorrection containing the corrected name if the typo
3997/// along with information such as the \c NamedDecl where the corrected name
3998/// was declared, and any additional \c NestedNameSpecifier needed to access
3999/// it (C++ only). The \c TypoCorrection is empty if there is no correction.
4000TypoCorrection Sema::CorrectTypo(const DeclarationNameInfo &TypoName,
4001 Sema::LookupNameKind LookupKind,
4002 Scope *S, CXXScopeSpec *SS,
Kaelyn Uhrain4e8942c2012-01-31 23:49:25 +00004003 CorrectionCandidateCallback &CCC,
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004004 DeclContext *MemberContext,
4005 bool EnteringContext,
Kaelyn Uhrain0e238442013-09-27 19:40:08 +00004006 const ObjCObjectPointerType *OPT,
4007 bool RecordFailure) {
Kaelyn Uhrainf0aabda2013-08-12 19:54:38 +00004008 // Always let the ExternalSource have the first chance at correction, even
4009 // if we would otherwise have given up.
4010 if (ExternalSource) {
4011 if (TypoCorrection Correction = ExternalSource->CorrectTypo(
4012 TypoName, LookupKind, S, SS, CCC, MemberContext, EnteringContext, OPT))
4013 return Correction;
4014 }
4015
Richard Smith1fff95c2013-09-12 23:28:08 +00004016 if (Diags.hasFatalErrorOccurred() || !getLangOpts().SpellChecking ||
4017 DisableTypoCorrection)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004018 return TypoCorrection();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004019
Francois Pichet9c391132011-12-03 15:55:29 +00004020 // In Microsoft mode, don't perform typo correction in a template member
4021 // function dependent context because it interferes with the "lookup into
4022 // dependent bases of class templates" feature.
Alp Tokerbfa39342014-01-14 12:51:41 +00004023 if (getLangOpts().MSVCCompat && CurContext->isDependentContext() &&
Francois Pichet9c391132011-12-03 15:55:29 +00004024 isa<CXXMethodDecl>(CurContext))
4025 return TypoCorrection();
4026
Douglas Gregor2d435302009-12-30 17:04:44 +00004027 // We only attempt to correct typos for identifiers.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004028 IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo();
Douglas Gregor2d435302009-12-30 17:04:44 +00004029 if (!Typo)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004030 return TypoCorrection();
Douglas Gregor2d435302009-12-30 17:04:44 +00004031
4032 // If the scope specifier itself was invalid, don't try to correct
4033 // typos.
4034 if (SS && SS->isInvalid())
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004035 return TypoCorrection();
Douglas Gregor2d435302009-12-30 17:04:44 +00004036
4037 // Never try to correct typos during template deduction or
4038 // instantiation.
4039 if (!ActiveTemplateInstantiations.empty())
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004040 return TypoCorrection();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004041
Argyrios Kyrtzidis3e56dd42013-03-14 22:56:43 +00004042 // Don't try to correct 'super'.
4043 if (S && S->isInObjcMethodScope() && Typo == getSuperIdentifier())
4044 return TypoCorrection();
4045
Kaelyn Uhrain0e238442013-09-27 19:40:08 +00004046 // Abort if typo correction already failed for this specific typo.
4047 IdentifierSourceLocations::iterator locs = TypoCorrectionFailures.find(Typo);
4048 if (locs != TypoCorrectionFailures.end() &&
Aaron Ballman7fc6e1b2013-10-05 19:56:07 +00004049 locs->second.count(TypoName.getLoc()))
Kaelyn Uhrain0e238442013-09-27 19:40:08 +00004050 return TypoCorrection();
4051
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00004052 // Don't try to correct the identifier "vector" when in AltiVec mode.
4053 // TODO: Figure out why typo correction misbehaves in this case, fix it, and
4054 // remove this workaround.
4055 if (getLangOpts().AltiVec && Typo->isStr("vector"))
4056 return TypoCorrection();
4057
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00004058 NamespaceSpecifierSet Namespaces(Context, CurContext, SS);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004059
4060 TypoCorrectionConsumer Consumer(*this, Typo);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004061
Kaelyn Uhrain0a16a8e2012-02-14 18:56:48 +00004062 // If a callback object considers an empty typo correction candidate to be
4063 // viable, assume it does not do any actual validation of the candidates.
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00004064 TypoCorrection EmptyCorrection;
Kaelyn Uhrain0a16a8e2012-02-14 18:56:48 +00004065 bool ValidatingCallback = !isCandidateViable(CCC, EmptyCorrection);
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00004066
Douglas Gregor280e1ee2010-04-14 20:04:41 +00004067 // Perform name lookup to find visible, similarly-named entities.
Douglas Gregor87074f12010-10-20 01:32:02 +00004068 bool IsUnqualifiedLookup = false;
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00004069 DeclContext *QualifiedDC = MemberContext;
Douglas Gregor35b0bac2010-01-03 18:01:57 +00004070 if (MemberContext) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004071 LookupVisibleDecls(MemberContext, LookupKind, Consumer);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00004072
4073 // Look in qualified interfaces.
4074 if (OPT) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004075 for (ObjCObjectPointerType::qual_iterator
4076 I = OPT->qual_begin(), E = OPT->qual_end();
Douglas Gregor35b0bac2010-01-03 18:01:57 +00004077 I != E; ++I)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004078 LookupVisibleDecls(*I, LookupKind, Consumer);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00004079 }
4080 } else if (SS && SS->isSet()) {
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00004081 QualifiedDC = computeDeclContext(*SS, EnteringContext);
4082 if (!QualifiedDC)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004083 return TypoCorrection();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004084
Douglas Gregor87074f12010-10-20 01:32:02 +00004085 // Provide a stop gap for files that are just seriously broken. Trying
4086 // to correct all typos can turn into a HUGE performance penalty, causing
4087 // some files to take minutes to get rejected by the parser.
4088 if (TyposCorrected + UnqualifiedTyposCorrected.size() >= 20)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004089 return TypoCorrection();
Douglas Gregor87074f12010-10-20 01:32:02 +00004090 ++TyposCorrected;
4091
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00004092 LookupVisibleDecls(QualifiedDC, LookupKind, Consumer);
Douglas Gregor2d435302009-12-30 17:04:44 +00004093 } else {
Douglas Gregor87074f12010-10-20 01:32:02 +00004094 IsUnqualifiedLookup = true;
4095 UnqualifiedTyposCorrectedMap::iterator Cached
4096 = UnqualifiedTyposCorrected.find(Typo);
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00004097 if (Cached != UnqualifiedTyposCorrected.end()) {
4098 // Add the cached value, unless it's a keyword or fails validation. In the
4099 // keyword case, we'll end up adding the keyword below.
4100 if (Cached->second) {
4101 if (!Cached->second.isKeyword() &&
Serge Pavlovc0cd80f2013-10-14 14:05:48 +00004102 isCandidateViable(CCC, Cached->second)) {
4103 // Do not use correction that is unaccessible in the given scope.
Serge Pavlove8ae13f2013-10-15 14:24:32 +00004104 NamedDecl *CorrectionDecl = Cached->second.getCorrectionDecl();
Serge Pavlovc0cd80f2013-10-14 14:05:48 +00004105 DeclarationNameInfo NameInfo(CorrectionDecl->getDeclName(),
4106 CorrectionDecl->getLocation());
4107 LookupResult R(*this, NameInfo, LookupOrdinaryName);
4108 if (LookupName(R, S))
4109 Consumer.addCorrection(Cached->second);
4110 }
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00004111 } else {
4112 // Only honor no-correction cache hits when a callback that will validate
4113 // correction candidates is not being used.
4114 if (!ValidatingCallback)
4115 return TypoCorrection();
4116 }
4117 }
4118 if (Cached == UnqualifiedTyposCorrected.end()) {
Douglas Gregor87074f12010-10-20 01:32:02 +00004119 // Provide a stop gap for files that are just seriously broken. Trying
4120 // to correct all typos can turn into a HUGE performance penalty, causing
4121 // some files to take minutes to get rejected by the parser.
4122 if (TyposCorrected + UnqualifiedTyposCorrected.size() >= 20)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004123 return TypoCorrection();
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00004124 }
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00004125 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004126
Douglas Gregorb11f9452012-03-26 16:54:18 +00004127 // Determine whether we are going to search in the various namespaces for
4128 // corrections.
4129 bool SearchNamespaces
Kaelyn Uhrainf4657d52012-04-03 18:20:11 +00004130 = getLangOpts().CPlusPlus &&
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +00004131 (IsUnqualifiedLookup || (SS && SS->isSet()));
Richard Smithe156254d2013-08-20 20:35:18 +00004132 // In a few cases we *only* want to search for corrections based on just
Kaelyn Uhrain493ea632012-06-06 20:54:51 +00004133 // adding or changing the nested name specifier.
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00004134 unsigned TypoLen = Typo->getName().size();
4135 bool AllowOnlyNNSChanges = TypoLen < 3;
4136
Douglas Gregorb11f9452012-03-26 16:54:18 +00004137 if (IsUnqualifiedLookup || SearchNamespaces) {
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00004138 // For unqualified lookup, look through all of the names that we have
4139 // seen in this translation unit.
Kaelyn Uhrain1c75d402012-02-07 01:32:58 +00004140 // FIXME: Re-add the ability to skip very unlikely potential corrections.
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00004141 for (IdentifierTable::iterator I = Context.Idents.begin(),
4142 IEnd = Context.Idents.end();
4143 I != IEnd; ++I)
4144 Consumer.FoundName(I->getKey());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004145
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00004146 // Walk through identifiers in external identifier sources.
Kaelyn Uhrain1c75d402012-02-07 01:32:58 +00004147 // FIXME: Re-add the ability to skip very unlikely potential corrections.
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00004148 if (IdentifierInfoLookup *External
4149 = Context.Idents.getExternalIdentifierLookup()) {
Ahmed Charlesb8984322014-03-07 20:03:18 +00004150 std::unique_ptr<IdentifierIterator> Iter(External->getIdentifiers());
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00004151 do {
4152 StringRef Name = Iter->Next();
4153 if (Name.empty())
4154 break;
Douglas Gregor57756ea2010-10-14 22:11:03 +00004155
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00004156 Consumer.FoundName(Name);
4157 } while (true);
Douglas Gregor57756ea2010-10-14 22:11:03 +00004158 }
Douglas Gregor2d435302009-12-30 17:04:44 +00004159 }
4160
Richard Smithb3a1df02012-06-08 21:35:42 +00004161 AddKeywordsToConsumer(*this, Consumer, S, CCC, SS && SS->isNotEmpty());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004162
Douglas Gregor280e1ee2010-04-14 20:04:41 +00004163 // If we haven't found anything, we're done.
Kaelyn Uhrain0e238442013-09-27 19:40:08 +00004164 if (Consumer.empty())
4165 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure,
4166 IsUnqualifiedLookup);
Douglas Gregor2d435302009-12-30 17:04:44 +00004167
Kaelyn Uhrain493ea632012-06-06 20:54:51 +00004168 // Make sure the best edit distance (prior to adding any namespace qualifiers)
4169 // is not more that about a third of the length of the typo's identifier.
Kaelyn Uhrain0a16a8e2012-02-14 18:56:48 +00004170 unsigned ED = Consumer.getBestEditDistance(true);
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00004171 if (ED > 0 && TypoLen / ED < 3)
Kaelyn Uhrain0e238442013-09-27 19:40:08 +00004172 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure,
4173 IsUnqualifiedLookup);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004174
Douglas Gregorb11f9452012-03-26 16:54:18 +00004175 // Build the NestedNameSpecifiers for the KnownNamespaces, if we're going
4176 // to search those namespaces.
4177 if (SearchNamespaces) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004178 // Load any externally-known namespaces.
4179 if (ExternalSource && !LoadedExternalKnownNamespaces) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004180 SmallVector<NamespaceDecl *, 4> ExternalKnownNamespaces;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004181 LoadedExternalKnownNamespaces = true;
4182 ExternalSource->ReadKnownNamespaces(ExternalKnownNamespaces);
4183 for (unsigned I = 0, N = ExternalKnownNamespaces.size(); I != N; ++I)
4184 KnownNamespaces[ExternalKnownNamespaces[I]] = true;
4185 }
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00004186
4187 for (llvm::MapVector<NamespaceDecl*, bool>::iterator
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004188 KNI = KnownNamespaces.begin(),
4189 KNIEnd = KnownNamespaces.end();
4190 KNI != KNIEnd; ++KNI)
Kaelyn Uhrain5315a462013-10-19 00:04:49 +00004191 Namespaces.AddNameSpecifier(KNI->first);
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00004192
Kaelyn Uhrain0e353552014-02-09 21:47:04 +00004193 bool SSIsTemplate = false;
4194 if (NestedNameSpecifier *NNS =
4195 (SS && SS->isValid()) ? SS->getScopeRep() : 0) {
4196 if (const Type *T = NNS->getAsType())
4197 SSIsTemplate = T->getTypeClass() == Type::TemplateSpecialization;
4198 }
Aaron Ballmane42430e2014-03-14 21:11:14 +00004199 for (const auto *TI : Context.types()) {
4200 if (CXXRecordDecl *CD = TI->getAsCXXRecordDecl()) {
Kaelyn Uhrain5315a462013-10-19 00:04:49 +00004201 CD = CD->getCanonicalDecl();
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00004202 if (!CD->isDependentType() && !CD->isAnonymousStructOrUnion() &&
Kaelyn Uhrain21a66172014-02-05 18:57:51 +00004203 !CD->isUnion() && CD->getIdentifier() &&
Kaelyn Uhrain0e353552014-02-09 21:47:04 +00004204 (SSIsTemplate || !isa<ClassTemplateSpecializationDecl>(CD)) &&
Kaelyn Uhrain5315a462013-10-19 00:04:49 +00004205 (CD->isBeingDefined() || CD->isCompleteDefinition()))
4206 Namespaces.AddNameSpecifier(CD);
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00004207 }
4208 }
Douglas Gregor87074f12010-10-20 01:32:02 +00004209 }
Douglas Gregor0afa7f62010-10-14 20:34:08 +00004210
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00004211 // Weed out any names that could not be found by name lookup or, if a
4212 // CorrectionCandidateCallback object was provided, failed validation.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004213 SmallVector<TypoCorrection, 16> QualifiedResults;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004214 LookupResult TmpRes(*this, TypoName, LookupKind);
4215 TmpRes.suppressDiagnostics();
4216 while (!Consumer.empty()) {
4217 TypoCorrectionConsumer::distance_iterator DI = Consumer.begin();
Benjamin Kramer73faad62012-04-14 08:26:28 +00004218 for (TypoCorrectionConsumer::result_iterator I = DI->second.begin(),
4219 IEnd = DI->second.end();
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004220 I != IEnd; /* Increment in loop. */) {
Kaelyn Uhrain493ea632012-06-06 20:54:51 +00004221 // If we only want nested name specifier corrections, ignore potential
4222 // corrections that have a different base identifier from the typo.
4223 if (AllowOnlyNNSChanges &&
4224 I->second.front().getCorrectionAsIdentifierInfo() != Typo) {
4225 TypoCorrectionConsumer::result_iterator Prev = I;
4226 ++I;
4227 DI->second.erase(Prev);
4228 continue;
4229 }
4230
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00004231 // If the item already has been looked up or is a keyword, keep it.
4232 // If a validator callback object was given, drop the correction
4233 // unless it passes validation.
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00004234 bool Viable = false;
Benjamin Kramera2dcac12012-07-27 10:21:08 +00004235 for (TypoResultList::iterator RI = I->second.begin();
4236 RI != I->second.end(); /* Increment in loop. */) {
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00004237 TypoResultList::iterator Prev = RI;
4238 ++RI;
4239 if (Prev->isResolved()) {
4240 if (!isCandidateViable(CCC, *Prev))
Benjamin Kramera2dcac12012-07-27 10:21:08 +00004241 RI = I->second.erase(Prev);
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00004242 else
4243 Viable = true;
4244 }
4245 }
4246 if (Viable || I->second.empty()) {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00004247 TypoCorrectionConsumer::result_iterator Prev = I;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004248 ++I;
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00004249 if (!Viable)
Benjamin Kramer73faad62012-04-14 08:26:28 +00004250 DI->second.erase(Prev);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004251 continue;
Douglas Gregor0afa7f62010-10-14 20:34:08 +00004252 }
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00004253 assert(I->second.size() == 1 && "Expected a single unresolved candidate");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004254
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004255 // Perform name lookup on this name.
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00004256 TypoCorrection &Candidate = I->second.front();
4257 IdentifierInfo *Name = Candidate.getCorrectionAsIdentifierInfo();
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00004258 DeclContext *TempMemberContext = MemberContext;
4259 CXXScopeSpec *TempSS = SS;
4260retry_lookup:
4261 LookupPotentialTypoResult(*this, TmpRes, Name, S, TempSS,
4262 TempMemberContext, EnteringContext,
Richard Smithe156254d2013-08-20 20:35:18 +00004263 CCC.IsObjCIvarLookup,
4264 Name == TypoName.getName() &&
4265 !Candidate.WillReplaceSpecifier());
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004266
4267 switch (TmpRes.getResultKind()) {
4268 case LookupResult::NotFound:
4269 case LookupResult::NotFoundInCurrentInstantiation:
Kaelyn Uhrain5a43b462011-09-07 20:25:59 +00004270 case LookupResult::FoundUnresolvedValue:
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00004271 if (TempSS) {
4272 // Immediately retry the lookup without the given CXXScopeSpec
4273 TempSS = NULL;
4274 Candidate.WillReplaceSpecifier(true);
4275 goto retry_lookup;
4276 }
4277 if (TempMemberContext) {
4278 if (SS && !TempSS)
4279 TempSS = SS;
4280 TempMemberContext = NULL;
4281 goto retry_lookup;
4282 }
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00004283 QualifiedResults.push_back(Candidate);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004284 // We didn't find this name in our scope, or didn't like what we found;
4285 // ignore it.
4286 {
4287 TypoCorrectionConsumer::result_iterator Next = I;
4288 ++Next;
Benjamin Kramer73faad62012-04-14 08:26:28 +00004289 DI->second.erase(I);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004290 I = Next;
4291 }
4292 break;
4293
4294 case LookupResult::Ambiguous:
4295 // We don't deal with ambiguities.
Kaelyn Uhrain0e238442013-09-27 19:40:08 +00004296 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004297
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00004298 case LookupResult::FoundOverloaded: {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00004299 TypoCorrectionConsumer::result_iterator Prev = I;
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00004300 // Store all of the Decls for overloaded symbols
4301 for (LookupResult::iterator TRD = TmpRes.begin(),
4302 TRDEnd = TmpRes.end();
4303 TRD != TRDEnd; ++TRD)
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00004304 Candidate.addCorrectionDecl(*TRD);
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00004305 ++I;
Kaelyn Uhrainb18b0c02013-07-02 23:47:35 +00004306 if (!isCandidateViable(CCC, Candidate)) {
4307 QualifiedResults.push_back(Candidate);
Benjamin Kramer73faad62012-04-14 08:26:28 +00004308 DI->second.erase(Prev);
Kaelyn Uhrainb18b0c02013-07-02 23:47:35 +00004309 }
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00004310 break;
4311 }
4312
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00004313 case LookupResult::Found: {
4314 TypoCorrectionConsumer::result_iterator Prev = I;
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00004315 Candidate.setCorrectionDecl(TmpRes.getAsSingle<NamedDecl>());
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004316 ++I;
Kaelyn Uhrainb18b0c02013-07-02 23:47:35 +00004317 if (!isCandidateViable(CCC, Candidate)) {
4318 QualifiedResults.push_back(Candidate);
Benjamin Kramer73faad62012-04-14 08:26:28 +00004319 DI->second.erase(Prev);
Kaelyn Uhrainb18b0c02013-07-02 23:47:35 +00004320 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004321 break;
4322 }
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00004323
4324 }
Douglas Gregor0afa7f62010-10-14 20:34:08 +00004325 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004326
Benjamin Kramer73faad62012-04-14 08:26:28 +00004327 if (DI->second.empty())
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004328 Consumer.erase(DI);
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00004329 else if (!getLangOpts().CPlusPlus || QualifiedResults.empty() || !DI->first)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004330 // If there are results in the closest possible bucket, stop
4331 break;
4332
4333 // Only perform the qualified lookups for C++
Douglas Gregorb11f9452012-03-26 16:54:18 +00004334 if (SearchNamespaces) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004335 TmpRes.suppressDiagnostics();
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004336 for (SmallVector<TypoCorrection,
4337 16>::iterator QRI = QualifiedResults.begin(),
4338 QRIEnd = QualifiedResults.end();
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004339 QRI != QRIEnd; ++QRI) {
4340 for (NamespaceSpecifierSet::iterator NI = Namespaces.begin(),
4341 NIEnd = Namespaces.end();
4342 NI != NIEnd; ++NI) {
4343 DeclContext *Ctx = NI->DeclCtx;
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00004344 const Type *NSType = NI->NameSpecifier->getAsType();
4345
4346 // If the current NestedNameSpecifier refers to a class and the
4347 // current correction candidate is the name of that class, then skip
4348 // it as it is unlikely a qualified version of the class' constructor
4349 // is an appropriate correction.
4350 if (CXXRecordDecl *NSDecl =
4351 NSType ? NSType->getAsCXXRecordDecl() : 0) {
4352 if (NSDecl->getIdentifier() == QRI->getCorrectionAsIdentifierInfo())
4353 continue;
4354 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004355
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00004356 TypoCorrection TC(*QRI);
4357 TC.ClearCorrectionDecls();
4358 TC.setCorrectionSpecifier(NI->NameSpecifier);
4359 TC.setQualifierDistance(NI->EditDistance);
4360 TC.setCallbackDistance(0); // Reset the callback distance
4361
4362 // If the current correction candidate and namespace combination are
4363 // too far away from the original typo based on the normalized edit
4364 // distance, then skip performing a qualified name lookup.
4365 unsigned TmpED = TC.getEditDistance(true);
4366 if (QRI->getCorrectionAsIdentifierInfo() != Typo &&
4367 TmpED && TypoLen / TmpED < 3)
4368 continue;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004369
4370 TmpRes.clear();
Kaelyn Uhrain0a16a8e2012-02-14 18:56:48 +00004371 TmpRes.setLookupName(QRI->getCorrectionAsIdentifierInfo());
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004372 if (!LookupQualifiedName(TmpRes, Ctx)) continue;
4373
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00004374 // Any corrections added below will be validated in subsequent
4375 // iterations of the main while() loop over the Consumer's contents.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004376 switch (TmpRes.getResultKind()) {
Kaelyn Uhrainb18b0c02013-07-02 23:47:35 +00004377 case LookupResult::Found:
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00004378 case LookupResult::FoundOverloaded: {
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +00004379 if (SS && SS->isValid()) {
4380 std::string NewQualified = TC.getAsString(getLangOpts());
4381 std::string OldQualified;
4382 llvm::raw_string_ostream OldOStream(OldQualified);
4383 SS->getScopeRep()->print(OldOStream, getPrintingPolicy());
4384 OldOStream << TypoName;
4385 // If correction candidate would be an identical written qualified
4386 // identifer, then the existing CXXScopeSpec probably included a
4387 // typedef that didn't get accounted for properly.
4388 if (OldOStream.str() == NewQualified)
4389 break;
4390 }
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00004391 for (LookupResult::iterator TRD = TmpRes.begin(),
4392 TRDEnd = TmpRes.end();
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00004393 TRD != TRDEnd; ++TRD) {
4394 if (CheckMemberAccess(TC.getCorrectionRange().getBegin(),
4395 NSType ? NSType->getAsCXXRecordDecl() : 0,
Eli Friedman3be1a1c2013-10-01 02:44:48 +00004396 TRD.getPair()) == AR_accessible)
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00004397 TC.addCorrectionDecl(*TRD);
4398 }
4399 if (TC.isResolved())
4400 Consumer.addCorrection(TC);
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00004401 break;
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00004402 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004403 case LookupResult::NotFound:
4404 case LookupResult::NotFoundInCurrentInstantiation:
4405 case LookupResult::Ambiguous:
Kaelyn Uhrain5a43b462011-09-07 20:25:59 +00004406 case LookupResult::FoundUnresolvedValue:
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004407 break;
4408 }
4409 }
4410 }
4411 }
4412
4413 QualifiedResults.clear();
4414 }
4415
4416 // No corrections remain...
Kaelyn Uhrain0e238442013-09-27 19:40:08 +00004417 if (Consumer.empty())
4418 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004419
Kaelyn Uhrain34fab552012-05-31 23:32:58 +00004420 TypoResultsMap &BestResults = Consumer.getBestResults();
4421 ED = Consumer.getBestEditDistance(true);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004422
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00004423 if (!AllowOnlyNNSChanges && ED > 0 && TypoLen / ED < 3) {
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00004424 // If this was an unqualified lookup and we believe the callback
4425 // object wouldn't have filtered out possible corrections, note
4426 // that no correction was found.
Kaelyn Uhrain0e238442013-09-27 19:40:08 +00004427 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure,
4428 IsUnqualifiedLookup && !ValidatingCallback);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004429 }
4430
Douglas Gregor0afa7f62010-10-14 20:34:08 +00004431 // If only a single name remains, return that result.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004432 if (BestResults.size() == 1) {
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00004433 const TypoResultList &CorrectionList = BestResults.begin()->second;
4434 const TypoCorrection &Result = CorrectionList.front();
Kaelyn Uhrain0e238442013-09-27 19:40:08 +00004435 if (CorrectionList.size() != 1)
4436 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004437
Douglas Gregor2a1d72d2010-10-26 17:18:00 +00004438 // Don't correct to a keyword that's the same as the typo; the keyword
4439 // wasn't actually in scope.
Kaelyn Uhrain0e238442013-09-27 19:40:08 +00004440 if (ED == 0 && Result.isKeyword())
4441 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004442
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004443 // Record the correction for unqualified lookup.
4444 if (IsUnqualifiedLookup)
4445 UnqualifiedTyposCorrected[Typo] = Result;
4446
David Blaikie04ea41c2012-10-12 20:00:44 +00004447 TypoCorrection TC = Result;
4448 TC.setCorrectionRange(SS, TypoName);
Richard Smithe156254d2013-08-20 20:35:18 +00004449 checkCorrectionVisibility(*this, TC, TypoName.getName());
David Blaikie04ea41c2012-10-12 20:00:44 +00004450 return TC;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004451 }
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00004452 else if (BestResults.size() > 1
4453 // Ugly hack equivalent to CTC == CTC_ObjCMessageReceiver;
4454 // WantObjCSuper is only true for CTC_ObjCMessageReceiver and for
4455 // some instances of CTC_Unknown, while WantRemainingKeywords is true
4456 // for CTC_Unknown but not for CTC_ObjCMessageReceiver.
Kaelyn Uhrain4e8942c2012-01-31 23:49:25 +00004457 && CCC.WantObjCSuper && !CCC.WantRemainingKeywords
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00004458 && BestResults["super"].front().isKeyword()) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004459 // Prefer 'super' when we're completing in a message-receiver
4460 // context.
4461
4462 // Don't correct to a keyword that's the same as the typo; the keyword
4463 // wasn't actually in scope.
Kaelyn Uhrain0e238442013-09-27 19:40:08 +00004464 if (ED == 0)
4465 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004466
Douglas Gregor87074f12010-10-20 01:32:02 +00004467 // Record the correction for unqualified lookup.
4468 if (IsUnqualifiedLookup)
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00004469 UnqualifiedTyposCorrected[Typo] = BestResults["super"].front();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004470
David Blaikie04ea41c2012-10-12 20:00:44 +00004471 TypoCorrection TC = BestResults["super"].front();
4472 TC.setCorrectionRange(SS, TypoName);
4473 return TC;
Douglas Gregoraf9eb592010-10-15 13:35:25 +00004474 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004475
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00004476 // If this was an unqualified lookup and we believe the callback object did
4477 // not filter out possible corrections, note that no correction was found.
4478 if (IsUnqualifiedLookup && !ValidatingCallback)
Douglas Gregor87074f12010-10-20 01:32:02 +00004479 (void)UnqualifiedTyposCorrected[Typo];
4480
Kaelyn Uhrain0e238442013-09-27 19:40:08 +00004481 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004482}
4483
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00004484void TypoCorrection::addCorrectionDecl(NamedDecl *CDecl) {
4485 if (!CDecl) return;
4486
4487 if (isKeyword())
4488 CorrectionDecls.clear();
4489
Kaelyn Uhrainf60b55a2012-11-19 18:49:53 +00004490 CorrectionDecls.push_back(CDecl->getUnderlyingDecl());
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00004491
4492 if (!CorrectionName)
4493 CorrectionName = CDecl->getDeclName();
4494}
4495
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004496std::string TypoCorrection::getAsString(const LangOptions &LO) const {
4497 if (CorrectionNameSpec) {
4498 std::string tmpBuffer;
4499 llvm::raw_string_ostream PrefixOStream(tmpBuffer);
4500 CorrectionNameSpec->print(PrefixOStream, PrintingPolicy(LO));
David Blaikied4da8722013-05-14 21:04:00 +00004501 PrefixOStream << CorrectionName;
Benjamin Kramer73faad62012-04-14 08:26:28 +00004502 return PrefixOStream.str();
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004503 }
4504
4505 return CorrectionName.getAsString();
Douglas Gregor2d435302009-12-30 17:04:44 +00004506}
Kaelyn Uhrain989b7ca2013-04-03 16:59:49 +00004507
4508bool CorrectionCandidateCallback::ValidateCandidate(const TypoCorrection &candidate) {
4509 if (!candidate.isResolved())
4510 return true;
4511
4512 if (candidate.isKeyword())
4513 return WantTypeSpecifiers || WantExpressionKeywords || WantCXXNamedCasts ||
4514 WantRemainingKeywords || WantObjCSuper;
4515
4516 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
4517 CDeclEnd = candidate.end();
4518 CDecl != CDeclEnd; ++CDecl) {
4519 if (!isa<TypeDecl>(*CDecl))
4520 return true;
4521 }
4522
4523 return WantTypeSpecifiers;
4524}
Kaelyn Uhrain53e72192013-07-08 23:13:39 +00004525
4526FunctionCallFilterCCC::FunctionCallFilterCCC(Sema &SemaRef, unsigned NumArgs,
Kaelyn Uhrainb4b14752014-02-28 18:12:42 +00004527 bool HasExplicitTemplateArgs,
4528 bool AllowNonStaticMethods)
4529 : NumArgs(NumArgs), HasExplicitTemplateArgs(HasExplicitTemplateArgs),
4530 AllowNonStaticMethods(AllowNonStaticMethods),
4531 CurContext(SemaRef.CurContext) {
Kaelyn Uhrain53e72192013-07-08 23:13:39 +00004532 WantTypeSpecifiers = SemaRef.getLangOpts().CPlusPlus;
4533 WantRemainingKeywords = false;
4534}
4535
4536bool FunctionCallFilterCCC::ValidateCandidate(const TypoCorrection &candidate) {
4537 if (!candidate.getCorrectionDecl())
4538 return candidate.isKeyword();
4539
4540 for (TypoCorrection::const_decl_iterator DI = candidate.begin(),
4541 DIEnd = candidate.end();
4542 DI != DIEnd; ++DI) {
4543 FunctionDecl *FD = 0;
4544 NamedDecl *ND = (*DI)->getUnderlyingDecl();
4545 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
4546 FD = FTD->getTemplatedDecl();
4547 if (!HasExplicitTemplateArgs && !FD) {
4548 if (!(FD = dyn_cast<FunctionDecl>(ND)) && isa<ValueDecl>(ND)) {
4549 // If the Decl is neither a function nor a template function,
4550 // determine if it is a pointer or reference to a function. If so,
4551 // check against the number of arguments expected for the pointee.
4552 QualType ValType = cast<ValueDecl>(ND)->getType();
4553 if (ValType->isAnyPointerType() || ValType->isReferenceType())
4554 ValType = ValType->getPointeeType();
4555 if (const FunctionProtoType *FPT = ValType->getAs<FunctionProtoType>())
Alp Toker9cacbab2014-01-20 20:26:09 +00004556 if (FPT->getNumParams() == NumArgs)
Kaelyn Uhrain53e72192013-07-08 23:13:39 +00004557 return true;
4558 }
4559 }
Kaelyn Uhrainb4b14752014-02-28 18:12:42 +00004560
4561 // Skip the current candidate if it is not a FunctionDecl or does not accept
4562 // the current number of arguments.
4563 if (!FD || !(FD->getNumParams() >= NumArgs &&
4564 FD->getMinRequiredArguments() <= NumArgs))
4565 continue;
4566
4567 // If the current candidate is a non-static C++ method and non-static
4568 // methods are being excluded, then skip the candidate unless the current
4569 // DeclContext is a method in the same class or a descendent class of the
4570 // candidate's parent class.
4571 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
4572 if (!AllowNonStaticMethods && !MD->isStatic()) {
4573 CXXMethodDecl *CurMD = dyn_cast_or_null<CXXMethodDecl>(CurContext);
4574 CXXRecordDecl *CurRD =
4575 CurMD ? CurMD->getParent()->getCanonicalDecl() : 0;
4576 CXXRecordDecl *RD = MD->getParent()->getCanonicalDecl();
4577 if (!CurRD || (CurRD != RD && !CurRD->isDerivedFrom(RD)))
4578 continue;
4579 }
4580 }
4581 return true;
Kaelyn Uhrain53e72192013-07-08 23:13:39 +00004582 }
4583 return false;
4584}
Richard Smithf9b15102013-08-17 00:46:16 +00004585
4586void Sema::diagnoseTypo(const TypoCorrection &Correction,
4587 const PartialDiagnostic &TypoDiag,
4588 bool ErrorRecovery) {
4589 diagnoseTypo(Correction, TypoDiag, PDiag(diag::note_previous_decl),
4590 ErrorRecovery);
4591}
4592
Richard Smithe156254d2013-08-20 20:35:18 +00004593/// Find which declaration we should import to provide the definition of
4594/// the given declaration.
4595static const NamedDecl *getDefinitionToImport(const NamedDecl *D) {
4596 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
4597 return VD->getDefinition();
4598 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
4599 return FD->isDefined(FD) ? FD : 0;
4600 if (const TagDecl *TD = dyn_cast<TagDecl>(D))
4601 return TD->getDefinition();
4602 if (const ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(D))
4603 return ID->getDefinition();
4604 if (const ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D))
4605 return PD->getDefinition();
4606 if (const TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
4607 return getDefinitionToImport(TD->getTemplatedDecl());
4608 return 0;
4609}
4610
Richard Smithf9b15102013-08-17 00:46:16 +00004611/// \brief Diagnose a successfully-corrected typo. Separated from the correction
4612/// itself to allow external validation of the result, etc.
4613///
4614/// \param Correction The result of performing typo correction.
4615/// \param TypoDiag The diagnostic to produce. This will have the corrected
4616/// string added to it (and usually also a fixit).
4617/// \param PrevNote A note to use when indicating the location of the entity to
4618/// which we are correcting. Will have the correction string added to it.
4619/// \param ErrorRecovery If \c true (the default), the caller is going to
4620/// recover from the typo as if the corrected string had been typed.
4621/// In this case, \c PDiag must be an error, and we will attach a fixit
4622/// to it.
4623void Sema::diagnoseTypo(const TypoCorrection &Correction,
4624 const PartialDiagnostic &TypoDiag,
4625 const PartialDiagnostic &PrevNote,
4626 bool ErrorRecovery) {
4627 std::string CorrectedStr = Correction.getAsString(getLangOpts());
4628 std::string CorrectedQuotedStr = Correction.getQuoted(getLangOpts());
4629 FixItHint FixTypo = FixItHint::CreateReplacement(
4630 Correction.getCorrectionRange(), CorrectedStr);
4631
Richard Smithe156254d2013-08-20 20:35:18 +00004632 // Maybe we're just missing a module import.
4633 if (Correction.requiresImport()) {
4634 NamedDecl *Decl = Correction.getCorrectionDecl();
4635 assert(Decl && "import required but no declaration to import");
4636
4637 // Suggest importing a module providing the definition of this entity, if
4638 // possible.
4639 const NamedDecl *Def = getDefinitionToImport(Decl);
4640 if (!Def)
4641 Def = Decl;
4642 Module *Owner = Def->getOwningModule();
4643 assert(Owner && "definition of hidden declaration is not in a module");
4644
4645 Diag(Correction.getCorrectionRange().getBegin(),
4646 diag::err_module_private_declaration)
4647 << Def << Owner->getFullModuleName();
4648 Diag(Def->getLocation(), diag::note_previous_declaration);
4649
4650 // Recover by implicitly importing this module.
4651 if (!isSFINAEContext() && ErrorRecovery)
4652 createImplicitModuleImport(Correction.getCorrectionRange().getBegin(),
4653 Owner);
4654 return;
4655 }
4656
Richard Smithf9b15102013-08-17 00:46:16 +00004657 Diag(Correction.getCorrectionRange().getBegin(), TypoDiag)
4658 << CorrectedQuotedStr << (ErrorRecovery ? FixTypo : FixItHint());
4659
4660 NamedDecl *ChosenDecl =
4661 Correction.isKeyword() ? 0 : Correction.getCorrectionDecl();
4662 if (PrevNote.getDiagID() && ChosenDecl)
4663 Diag(ChosenDecl->getLocation(), PrevNote)
4664 << CorrectedQuotedStr << (ErrorRecovery ? FixItHint() : FixTypo);
4665}