blob: a8d7b1e971b5ddfdae277890a29323e03f8dc6d8 [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/Sema.h"
John McCall83024632010-08-25 22:03:47 +000015#include "clang/Sema/SemaInternal.h"
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000016#include "clang/Sema/Lookup.h"
Alexis Hunt4ac55e32011-06-04 04:32:43 +000017#include "clang/Sema/Overload.h"
John McCall8b0666c2010-08-20 18:27:03 +000018#include "clang/Sema/DeclSpec.h"
John McCallcc14d1f2010-08-24 08:50:51 +000019#include "clang/Sema/Scope.h"
John McCallaab3e412010-08-25 08:40:02 +000020#include "clang/Sema/ScopeInfo.h"
John McCall19c1bfd2010-08-25 05:32:35 +000021#include "clang/Sema/TemplateDeduction.h"
Axel Naumann016538a2011-02-24 16:47:47 +000022#include "clang/Sema/ExternalSemaSource.h"
Douglas Gregorc2fa1692011-06-28 16:20:02 +000023#include "clang/Sema/TypoCorrection.h"
Douglas Gregor960b5bc2009-01-15 00:26:24 +000024#include "clang/AST/ASTContext.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000025#include "clang/AST/CXXInheritance.h"
Douglas Gregor34074322009-01-14 22:20:51 +000026#include "clang/AST/Decl.h"
27#include "clang/AST/DeclCXX.h"
28#include "clang/AST/DeclObjC.h"
Douglas Gregorc9f9b862009-05-11 19:58:34 +000029#include "clang/AST/DeclTemplate.h"
Douglas Gregore254f902009-02-04 00:32:51 +000030#include "clang/AST/Expr.h"
Douglas Gregorbe759252009-07-08 10:57:20 +000031#include "clang/AST/ExprCXX.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000032#include "clang/Basic/Builtins.h"
Douglas Gregor34074322009-01-14 22:20:51 +000033#include "clang/Basic/LangOptions.h"
Douglas Gregorcdd11d42012-02-01 17:04:21 +000034#include "llvm/ADT/SetVector.h"
Douglas Gregor34074322009-01-14 22:20:51 +000035#include "llvm/ADT/STLExtras.h"
Douglas Gregore254f902009-02-04 00:32:51 +000036#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor0afa7f62010-10-14 20:34:08 +000037#include "llvm/ADT/StringMap.h"
Chris Lattner83cfc7c2011-07-18 01:54:02 +000038#include "llvm/ADT/TinyPtrVector.h"
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +000039#include "llvm/ADT/edit_distance.h"
John McCall6538c932009-10-10 05:48:19 +000040#include "llvm/Support/ErrorHandling.h"
Douglas Gregor0afa7f62010-10-14 20:34:08 +000041#include <limits>
Douglas Gregor2d435302009-12-30 17:04:44 +000042#include <list>
Douglas Gregor1c846b02009-01-16 00:38:09 +000043#include <set>
Douglas Gregor889ceb72009-02-03 19:21:40 +000044#include <vector>
45#include <iterator>
46#include <utility>
47#include <algorithm>
Douglas Gregorc2fa1692011-06-28 16:20:02 +000048#include <map>
Douglas Gregor34074322009-01-14 22:20:51 +000049
50using namespace clang;
John McCall19c1bfd2010-08-25 05:32:35 +000051using namespace sema;
Douglas Gregor34074322009-01-14 22:20:51 +000052
John McCallf6c8a4e2009-11-10 07:01:13 +000053namespace {
54 class UnqualUsingEntry {
55 const DeclContext *Nominated;
56 const DeclContext *CommonAncestor;
Douglas Gregor889ceb72009-02-03 19:21:40 +000057
John McCallf6c8a4e2009-11-10 07:01:13 +000058 public:
59 UnqualUsingEntry(const DeclContext *Nominated,
60 const DeclContext *CommonAncestor)
61 : Nominated(Nominated), CommonAncestor(CommonAncestor) {
62 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000063
John McCallf6c8a4e2009-11-10 07:01:13 +000064 const DeclContext *getCommonAncestor() const {
65 return CommonAncestor;
66 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000067
John McCallf6c8a4e2009-11-10 07:01:13 +000068 const DeclContext *getNominatedNamespace() const {
69 return Nominated;
70 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000071
John McCallf6c8a4e2009-11-10 07:01:13 +000072 // Sort by the pointer value of the common ancestor.
73 struct Comparator {
74 bool operator()(const UnqualUsingEntry &L, const UnqualUsingEntry &R) {
75 return L.getCommonAncestor() < R.getCommonAncestor();
76 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000077
John McCallf6c8a4e2009-11-10 07:01:13 +000078 bool operator()(const UnqualUsingEntry &E, const DeclContext *DC) {
79 return E.getCommonAncestor() < DC;
80 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000081
John McCallf6c8a4e2009-11-10 07:01:13 +000082 bool operator()(const DeclContext *DC, const UnqualUsingEntry &E) {
83 return DC < E.getCommonAncestor();
84 }
85 };
86 };
Douglas Gregor889ceb72009-02-03 19:21:40 +000087
John McCallf6c8a4e2009-11-10 07:01:13 +000088 /// A collection of using directives, as used by C++ unqualified
89 /// lookup.
90 class UnqualUsingDirectiveSet {
Chris Lattner0e62c1c2011-07-23 10:55:15 +000091 typedef SmallVector<UnqualUsingEntry, 8> ListTy;
Douglas Gregor889ceb72009-02-03 19:21:40 +000092
John McCallf6c8a4e2009-11-10 07:01:13 +000093 ListTy list;
94 llvm::SmallPtrSet<DeclContext*, 8> visited;
Douglas Gregor889ceb72009-02-03 19:21:40 +000095
John McCallf6c8a4e2009-11-10 07:01:13 +000096 public:
97 UnqualUsingDirectiveSet() {}
Douglas Gregor889ceb72009-02-03 19:21:40 +000098
John McCallf6c8a4e2009-11-10 07:01:13 +000099 void visitScopeChain(Scope *S, Scope *InnermostFileScope) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000100 // C++ [namespace.udir]p1:
John McCallf6c8a4e2009-11-10 07:01:13 +0000101 // During unqualified name lookup, the names appear as if they
102 // were declared in the nearest enclosing namespace which contains
103 // both the using-directive and the nominated namespace.
104 DeclContext *InnermostFileDC
105 = static_cast<DeclContext*>(InnermostFileScope->getEntity());
106 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.
Richard Smith05afe5e2012-03-13 03:12:56 +0000112 DeclContext *Ctx = static_cast<DeclContext*>(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) {
156 DeclContext::udir_iterator I, End;
157 for (llvm::tie(I, End) = DC->getUsingDirectives(); I != End; ++I) {
158 UsingDirectiveDecl *UD = *I;
159 DeclContext *NS = UD->getNominatedNamespace();
160 if (visited.insert(NS)) {
161 addUsingDirective(UD, EffectiveDC);
162 queue.push_back(NS);
163 }
164 }
165
166 if (queue.empty())
167 return;
168
169 DC = queue.back();
170 queue.pop_back();
171 }
172 }
173
174 // Add a using directive as if it had been declared in the given
175 // context. This helps implement C++ [namespace.udir]p3:
176 // The using-directive is transitive: if a scope contains a
177 // using-directive that nominates a second namespace that itself
178 // contains using-directives, the effect is as if the
179 // using-directives from the second namespace also appeared in
180 // the first.
181 void addUsingDirective(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
182 // Find the common ancestor between the effective context and
183 // the nominated namespace.
184 DeclContext *Common = UD->getNominatedNamespace();
185 while (!Common->Encloses(EffectiveDC))
186 Common = Common->getParent();
John McCall9757d032009-11-10 09:20:04 +0000187 Common = Common->getPrimaryContext();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000188
John McCallf6c8a4e2009-11-10 07:01:13 +0000189 list.push_back(UnqualUsingEntry(UD->getNominatedNamespace(), Common));
190 }
191
192 void done() {
193 std::sort(list.begin(), list.end(), UnqualUsingEntry::Comparator());
194 }
195
John McCallf6c8a4e2009-11-10 07:01:13 +0000196 typedef ListTy::const_iterator const_iterator;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000197
John McCallf6c8a4e2009-11-10 07:01:13 +0000198 const_iterator begin() const { return list.begin(); }
199 const_iterator end() const { return list.end(); }
200
201 std::pair<const_iterator,const_iterator>
202 getNamespacesFor(DeclContext *DC) const {
John McCall9757d032009-11-10 09:20:04 +0000203 return std::equal_range(begin(), end(), DC->getPrimaryContext(),
John McCallf6c8a4e2009-11-10 07:01:13 +0000204 UnqualUsingEntry::Comparator());
205 }
206 };
Douglas Gregor889ceb72009-02-03 19:21:40 +0000207}
208
Douglas Gregor889ceb72009-02-03 19:21:40 +0000209// Retrieve the set of identifier namespaces that correspond to a
210// specific kind of name lookup.
John McCallea305ed2009-12-18 10:40:03 +0000211static inline unsigned getIDNS(Sema::LookupNameKind NameKind,
212 bool CPlusPlus,
213 bool Redeclaration) {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000214 unsigned IDNS = 0;
215 switch (NameKind) {
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +0000216 case Sema::LookupObjCImplicitSelfParam:
Douglas Gregor889ceb72009-02-03 19:21:40 +0000217 case Sema::LookupOrdinaryName:
Douglas Gregoreddf4332009-02-24 20:03:32 +0000218 case Sema::LookupRedeclarationWithLinkage:
Douglas Gregor889ceb72009-02-03 19:21:40 +0000219 IDNS = Decl::IDNS_Ordinary;
John McCallea305ed2009-12-18 10:40:03 +0000220 if (CPlusPlus) {
John McCalle87beb22010-04-23 18:46:30 +0000221 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Member | Decl::IDNS_Namespace;
Chris Lattnerebb5c6c2011-02-18 01:27:55 +0000222 if (Redeclaration)
223 IDNS |= Decl::IDNS_TagFriend | Decl::IDNS_OrdinaryFriend;
John McCallea305ed2009-12-18 10:40:03 +0000224 }
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
289 // 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 if (!isForRedeclaration()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000293 switch (NameInfo.getName().getCXXOverloadedOperator()) {
Douglas Gregorbcf0a472010-03-24 05:07:21 +0000294 case OO_New:
295 case OO_Delete:
296 case OO_Array_New:
297 case OO_Array_Delete:
298 SemaRef.DeclareGlobalNewDelete();
299 break;
300
301 default:
302 break;
303 }
304 }
John McCallea305ed2009-12-18 10:40:03 +0000305}
306
Daniel Dunbar9e19f132012-03-08 01:43:06 +0000307void LookupResult::sanityImpl() const {
308 // Note that this function is never called by NDEBUG builds. See
309 // LookupResult::sanity().
John McCall19c1bfd2010-08-25 05:32:35 +0000310 assert(ResultKind != NotFound || Decls.size() == 0);
311 assert(ResultKind != Found || Decls.size() == 1);
312 assert(ResultKind != FoundOverloaded || Decls.size() > 1 ||
313 (Decls.size() == 1 &&
314 isa<FunctionTemplateDecl>((*begin())->getUnderlyingDecl())));
315 assert(ResultKind != FoundUnresolvedValue || sanityCheckUnresolved());
316 assert(ResultKind != Ambiguous || Decls.size() > 1 ||
Douglas Gregorc0d24902010-10-22 22:08:47 +0000317 (Decls.size() == 1 && (Ambiguity == AmbiguousBaseSubobjects ||
318 Ambiguity == AmbiguousBaseSubobjectTypes)));
John McCall19c1bfd2010-08-25 05:32:35 +0000319 assert((Paths != NULL) == (ResultKind == Ambiguous &&
320 (Ambiguity == AmbiguousBaseSubobjectTypes ||
321 Ambiguity == AmbiguousBaseSubobjects)));
322}
John McCall19c1bfd2010-08-25 05:32:35 +0000323
John McCall9f3059a2009-10-09 21:13:30 +0000324// Necessary because CXXBasePaths is not complete in Sema.h
John McCall5cebab12009-11-18 07:57:50 +0000325void LookupResult::deletePaths(CXXBasePaths *Paths) {
John McCall9f3059a2009-10-09 21:13:30 +0000326 delete Paths;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000327}
328
Douglas Gregor4a814562011-12-14 16:03:29 +0000329static NamedDecl *getVisibleDecl(NamedDecl *D);
330
331NamedDecl *LookupResult::getAcceptableDeclSlow(NamedDecl *D) const {
332 return getVisibleDecl(D);
333}
334
John McCall283b9012009-11-22 00:44:51 +0000335/// Resolves the result kind of this lookup.
John McCall5cebab12009-11-18 07:57:50 +0000336void LookupResult::resolveKind() {
John McCall9f3059a2009-10-09 21:13:30 +0000337 unsigned N = Decls.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000338
John McCall9f3059a2009-10-09 21:13:30 +0000339 // Fast case: no possible ambiguity.
John McCall1f82f242009-11-18 22:49:29 +0000340 if (N == 0) {
John McCall7fe6e9c2010-01-15 21:27:01 +0000341 assert(ResultKind == NotFound || ResultKind == NotFoundInCurrentInstantiation);
John McCall1f82f242009-11-18 22:49:29 +0000342 return;
343 }
344
John McCall283b9012009-11-22 00:44:51 +0000345 // If there's a single decl, we need to examine it to decide what
346 // kind of lookup this is.
John McCalle61f2ba2009-11-18 02:36:19 +0000347 if (N == 1) {
Douglas Gregor516d6722010-04-25 21:15:30 +0000348 NamedDecl *D = (*Decls.begin())->getUnderlyingDecl();
349 if (isa<FunctionTemplateDecl>(D))
John McCall283b9012009-11-22 00:44:51 +0000350 ResultKind = FoundOverloaded;
Douglas Gregor516d6722010-04-25 21:15:30 +0000351 else if (isa<UnresolvedUsingValueDecl>(D))
John McCalle61f2ba2009-11-18 02:36:19 +0000352 ResultKind = FoundUnresolvedValue;
353 return;
354 }
John McCall9f3059a2009-10-09 21:13:30 +0000355
John McCall6538c932009-10-10 05:48:19 +0000356 // Don't do any extra resolution if we've already resolved as ambiguous.
John McCall27b18f82009-11-17 02:14:36 +0000357 if (ResultKind == Ambiguous) return;
John McCall6538c932009-10-10 05:48:19 +0000358
John McCall9f3059a2009-10-09 21:13:30 +0000359 llvm::SmallPtrSet<NamedDecl*, 16> Unique;
Douglas Gregor13e65872010-08-11 14:45:53 +0000360 llvm::SmallPtrSet<QualType, 16> UniqueTypes;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000361
John McCall9f3059a2009-10-09 21:13:30 +0000362 bool Ambiguous = false;
363 bool HasTag = false, HasFunction = false, HasNonFunction = false;
John McCall283b9012009-11-22 00:44:51 +0000364 bool HasFunctionTemplate = false, HasUnresolved = false;
John McCall9f3059a2009-10-09 21:13:30 +0000365
366 unsigned UniqueTagIndex = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000367
John McCall9f3059a2009-10-09 21:13:30 +0000368 unsigned I = 0;
369 while (I < N) {
John McCallf0f1cf02009-11-17 07:50:12 +0000370 NamedDecl *D = Decls[I]->getUnderlyingDecl();
371 D = cast<NamedDecl>(D->getCanonicalDecl());
John McCall9f3059a2009-10-09 21:13:30 +0000372
Douglas Gregor13e65872010-08-11 14:45:53 +0000373 // Redeclarations of types via typedef can occur both within a scope
374 // and, through using declarations and directives, across scopes. There is
375 // no ambiguity if they all refer to the same type, so unique based on the
376 // canonical type.
377 if (TypeDecl *TD = dyn_cast<TypeDecl>(D)) {
378 if (!TD->getDeclContext()->isRecord()) {
379 QualType T = SemaRef.Context.getTypeDeclType(TD);
380 if (!UniqueTypes.insert(SemaRef.Context.getCanonicalType(T))) {
381 // The type is not unique; pull something off the back and continue
382 // at this index.
383 Decls[I] = Decls[--N];
384 continue;
385 }
386 }
387 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000388
John McCallf0f1cf02009-11-17 07:50:12 +0000389 if (!Unique.insert(D)) {
John McCall9f3059a2009-10-09 21:13:30 +0000390 // If it's not unique, pull something off the back (and
391 // continue at this index).
392 Decls[I] = Decls[--N];
Douglas Gregor13e65872010-08-11 14:45:53 +0000393 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000394 }
395
Douglas Gregor13e65872010-08-11 14:45:53 +0000396 // Otherwise, do some decl type analysis and then continue.
John McCalle61f2ba2009-11-18 02:36:19 +0000397
Douglas Gregor13e65872010-08-11 14:45:53 +0000398 if (isa<UnresolvedUsingValueDecl>(D)) {
399 HasUnresolved = true;
400 } else if (isa<TagDecl>(D)) {
401 if (HasTag)
402 Ambiguous = true;
403 UniqueTagIndex = I;
404 HasTag = true;
405 } else if (isa<FunctionTemplateDecl>(D)) {
406 HasFunction = true;
407 HasFunctionTemplate = true;
408 } else if (isa<FunctionDecl>(D)) {
409 HasFunction = true;
410 } else {
411 if (HasNonFunction)
412 Ambiguous = true;
413 HasNonFunction = true;
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000414 }
Douglas Gregor13e65872010-08-11 14:45:53 +0000415 I++;
Mike Stump11289f42009-09-09 15:08:12 +0000416 }
Douglas Gregor38feed82009-04-24 02:57:34 +0000417
John McCall9f3059a2009-10-09 21:13:30 +0000418 // C++ [basic.scope.hiding]p2:
419 // A class name or enumeration name can be hidden by the name of
420 // an object, function, or enumerator declared in the same
421 // scope. If a class or enumeration name and an object, function,
422 // or enumerator are declared in the same scope (in any order)
423 // with the same name, the class or enumeration name is hidden
424 // wherever the object, function, or enumerator name is visible.
425 // But it's still an error if there are distinct tag types found,
426 // even if they're not visible. (ref?)
John McCall80053822009-12-03 00:58:24 +0000427 if (HideTags && HasTag && !Ambiguous &&
Douglas Gregore63d0872010-10-23 16:06:17 +0000428 (HasFunction || HasNonFunction || HasUnresolved)) {
429 if (Decls[UniqueTagIndex]->getDeclContext()->getRedeclContext()->Equals(
430 Decls[UniqueTagIndex? 0 : N-1]->getDeclContext()->getRedeclContext()))
431 Decls[UniqueTagIndex] = Decls[--N];
432 else
433 Ambiguous = true;
434 }
Anders Carlsson8d0f6b72009-06-26 03:37:05 +0000435
John McCall9f3059a2009-10-09 21:13:30 +0000436 Decls.set_size(N);
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000437
John McCall80053822009-12-03 00:58:24 +0000438 if (HasNonFunction && (HasFunction || HasUnresolved))
John McCall9f3059a2009-10-09 21:13:30 +0000439 Ambiguous = true;
Douglas Gregorf23311d2009-01-17 01:13:24 +0000440
John McCall9f3059a2009-10-09 21:13:30 +0000441 if (Ambiguous)
John McCall6538c932009-10-10 05:48:19 +0000442 setAmbiguous(LookupResult::AmbiguousReference);
John McCalle61f2ba2009-11-18 02:36:19 +0000443 else if (HasUnresolved)
444 ResultKind = LookupResult::FoundUnresolvedValue;
John McCall283b9012009-11-22 00:44:51 +0000445 else if (N > 1 || HasFunctionTemplate)
John McCall27b18f82009-11-17 02:14:36 +0000446 ResultKind = LookupResult::FoundOverloaded;
John McCall9f3059a2009-10-09 21:13:30 +0000447 else
John McCall27b18f82009-11-17 02:14:36 +0000448 ResultKind = LookupResult::Found;
Douglas Gregor34074322009-01-14 22:20:51 +0000449}
450
John McCall5cebab12009-11-18 07:57:50 +0000451void LookupResult::addDeclsFromBasePaths(const CXXBasePaths &P) {
John McCall5b0829a2010-02-10 09:31:12 +0000452 CXXBasePaths::const_paths_iterator I, E;
John McCall9f3059a2009-10-09 21:13:30 +0000453 DeclContext::lookup_iterator DI, DE;
454 for (I = P.begin(), E = P.end(); I != E; ++I)
455 for (llvm::tie(DI,DE) = I->Decls; DI != DE; ++DI)
456 addDecl(*DI);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +0000457}
458
John McCall5cebab12009-11-18 07:57:50 +0000459void LookupResult::setAmbiguousBaseSubobjects(CXXBasePaths &P) {
John McCall9f3059a2009-10-09 21:13:30 +0000460 Paths = new CXXBasePaths;
461 Paths->swap(P);
462 addDeclsFromBasePaths(*Paths);
463 resolveKind();
John McCall6538c932009-10-10 05:48:19 +0000464 setAmbiguous(AmbiguousBaseSubobjects);
Douglas Gregor0e8fc3c2009-02-02 21:35:47 +0000465}
466
John McCall5cebab12009-11-18 07:57:50 +0000467void LookupResult::setAmbiguousBaseSubobjectTypes(CXXBasePaths &P) {
John McCall9f3059a2009-10-09 21:13:30 +0000468 Paths = new CXXBasePaths;
469 Paths->swap(P);
470 addDeclsFromBasePaths(*Paths);
471 resolveKind();
John McCall6538c932009-10-10 05:48:19 +0000472 setAmbiguous(AmbiguousBaseSubobjectTypes);
John McCall9f3059a2009-10-09 21:13:30 +0000473}
474
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000475void LookupResult::print(raw_ostream &Out) {
John McCall9f3059a2009-10-09 21:13:30 +0000476 Out << Decls.size() << " result(s)";
477 if (isAmbiguous()) Out << ", ambiguous";
478 if (Paths) Out << ", base paths present";
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000479
John McCall9f3059a2009-10-09 21:13:30 +0000480 for (iterator I = begin(), E = end(); I != E; ++I) {
481 Out << "\n";
482 (*I)->print(Out, 2);
483 }
484}
485
Douglas Gregord3a59182010-02-12 05:48:04 +0000486/// \brief Lookup a builtin function, when name lookup would otherwise
487/// fail.
488static bool LookupBuiltin(Sema &S, LookupResult &R) {
489 Sema::LookupNameKind NameKind = R.getLookupKind();
490
491 // If we didn't find a use of this identifier, and if the identifier
492 // corresponds to a compiler builtin, create the decl object for the builtin
493 // now, injecting it into translation unit scope, and return it.
494 if (NameKind == Sema::LookupOrdinaryName ||
495 NameKind == Sema::LookupRedeclarationWithLinkage) {
496 IdentifierInfo *II = R.getLookupName().getAsIdentifierInfo();
497 if (II) {
498 // If this is a builtin on this (or all) targets, create the decl.
499 if (unsigned BuiltinID = II->getBuiltinID()) {
500 // In C++, we don't have any predefined library functions like
501 // 'malloc'. Instead, we'll just error.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000502 if (S.getLangOpts().CPlusPlus &&
Douglas Gregord3a59182010-02-12 05:48:04 +0000503 S.Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
504 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000505
506 if (NamedDecl *D = S.LazilyCreateBuiltin((IdentifierInfo *)II,
507 BuiltinID, S.TUScope,
Douglas Gregorbfe022c2011-01-03 09:37:44 +0000508 R.isForRedeclaration(),
509 R.getNameLoc())) {
Douglas Gregord3a59182010-02-12 05:48:04 +0000510 R.addDecl(D);
Douglas Gregorbfe022c2011-01-03 09:37:44 +0000511 return true;
512 }
513
514 if (R.isForRedeclaration()) {
515 // If we're redeclaring this function anyway, forget that
516 // this was a builtin at all.
517 S.Context.BuiltinInfo.ForgetBuiltin(BuiltinID, S.Context.Idents);
518 }
519
520 return false;
Douglas Gregord3a59182010-02-12 05:48:04 +0000521 }
522 }
523 }
524
525 return false;
526}
527
Douglas Gregor7454c562010-07-02 20:37:36 +0000528/// \brief Determine whether we can declare a special member function within
529/// the class at this point.
530static bool CanDeclareSpecialMemberFunction(ASTContext &Context,
531 const CXXRecordDecl *Class) {
532 // We need to have a definition for the class.
533 if (!Class->getDefinition() || Class->isDependentContext())
534 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000535
Douglas Gregor7454c562010-07-02 20:37:36 +0000536 // We can't be in the middle of defining the class.
537 if (const RecordType *RecordTy
538 = Context.getTypeDeclType(Class)->getAs<RecordType>())
539 return !RecordTy->isBeingDefined();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000540
Douglas Gregor7454c562010-07-02 20:37:36 +0000541 return false;
542}
543
544void Sema::ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class) {
Douglas Gregora6d69502010-07-02 23:41:54 +0000545 if (!CanDeclareSpecialMemberFunction(Context, Class))
546 return;
Douglas Gregor9672f922010-07-03 00:47:00 +0000547
548 // If the default constructor has not yet been declared, do so now.
Alexis Huntea6f0322011-05-11 22:34:38 +0000549 if (Class->needsImplicitDefaultConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +0000550 DeclareImplicitDefaultConstructor(Class);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000551
Douglas Gregora6d69502010-07-02 23:41:54 +0000552 // If the copy constructor has not yet been declared, do so now.
553 if (!Class->hasDeclaredCopyConstructor())
554 DeclareImplicitCopyConstructor(Class);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000555
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000556 // If the copy assignment operator has not yet been declared, do so now.
Douglas Gregora6d69502010-07-02 23:41:54 +0000557 if (!Class->hasDeclaredCopyAssignment())
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000558 DeclareImplicitCopyAssignment(Class);
559
David Blaikiebbafb8a2012-03-11 07:00:24 +0000560 if (getLangOpts().CPlusPlus0x) {
Sebastian Redl22653ba2011-08-30 19:58:05 +0000561 // If the move constructor has not yet been declared, do so now.
562 if (Class->needsImplicitMoveConstructor())
563 DeclareImplicitMoveConstructor(Class); // might not actually do it
564
565 // If the move assignment operator has not yet been declared, do so now.
566 if (Class->needsImplicitMoveAssignment())
567 DeclareImplicitMoveAssignment(Class); // might not actually do it
568 }
569
Douglas Gregor7454c562010-07-02 20:37:36 +0000570 // If the destructor has not yet been declared, do so now.
Douglas Gregora6d69502010-07-02 23:41:54 +0000571 if (!Class->hasDeclaredDestructor())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000572 DeclareImplicitDestructor(Class);
Douglas Gregor7454c562010-07-02 20:37:36 +0000573}
574
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000575/// \brief Determine whether this is the name of an implicitly-declared
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000576/// special member function.
577static bool isImplicitlyDeclaredMemberFunctionName(DeclarationName Name) {
578 switch (Name.getNameKind()) {
Douglas Gregora6d69502010-07-02 23:41:54 +0000579 case DeclarationName::CXXConstructorName:
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000580 case DeclarationName::CXXDestructorName:
581 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000582
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000583 case DeclarationName::CXXOperatorName:
584 return Name.getCXXOverloadedOperator() == OO_Equal;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000585
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000586 default:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000587 break;
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000588 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000589
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000590 return false;
591}
592
593/// \brief If there are any implicit member functions with the given name
594/// that need to be declared in the given declaration context, do so.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000595static void DeclareImplicitMemberFunctionsWithName(Sema &S,
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000596 DeclarationName Name,
597 const DeclContext *DC) {
598 if (!DC)
599 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000600
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000601 switch (Name.getNameKind()) {
Douglas Gregora6d69502010-07-02 23:41:54 +0000602 case DeclarationName::CXXConstructorName:
603 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
Douglas Gregor9672f922010-07-03 00:47:00 +0000604 if (Record->getDefinition() &&
605 CanDeclareSpecialMemberFunction(S.Context, Record)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +0000606 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(Record);
Alexis Huntea6f0322011-05-11 22:34:38 +0000607 if (Record->needsImplicitDefaultConstructor())
Sebastian Redl22653ba2011-08-30 19:58:05 +0000608 S.DeclareImplicitDefaultConstructor(Class);
Douglas Gregor9672f922010-07-03 00:47:00 +0000609 if (!Record->hasDeclaredCopyConstructor())
Sebastian Redl22653ba2011-08-30 19:58:05 +0000610 S.DeclareImplicitCopyConstructor(Class);
David Blaikiebbafb8a2012-03-11 07:00:24 +0000611 if (S.getLangOpts().CPlusPlus0x &&
Sebastian Redl22653ba2011-08-30 19:58:05 +0000612 Record->needsImplicitMoveConstructor())
613 S.DeclareImplicitMoveConstructor(Class);
Douglas Gregor9672f922010-07-03 00:47:00 +0000614 }
Douglas Gregora6d69502010-07-02 23:41:54 +0000615 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000616
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000617 case DeclarationName::CXXDestructorName:
618 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
619 if (Record->getDefinition() && !Record->hasDeclaredDestructor() &&
620 CanDeclareSpecialMemberFunction(S.Context, Record))
621 S.DeclareImplicitDestructor(const_cast<CXXRecordDecl *>(Record));
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000622 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000623
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000624 case DeclarationName::CXXOperatorName:
625 if (Name.getCXXOverloadedOperator() != OO_Equal)
626 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000627
Sebastian Redl22653ba2011-08-30 19:58:05 +0000628 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC)) {
629 if (Record->getDefinition() &&
630 CanDeclareSpecialMemberFunction(S.Context, Record)) {
631 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(Record);
632 if (!Record->hasDeclaredCopyAssignment())
633 S.DeclareImplicitCopyAssignment(Class);
David Blaikiebbafb8a2012-03-11 07:00:24 +0000634 if (S.getLangOpts().CPlusPlus0x &&
Sebastian Redl22653ba2011-08-30 19:58:05 +0000635 Record->needsImplicitMoveAssignment())
636 S.DeclareImplicitMoveAssignment(Class);
637 }
638 }
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 default:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000642 break;
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000643 }
644}
Douglas Gregor7454c562010-07-02 20:37:36 +0000645
John McCall9f3059a2009-10-09 21:13:30 +0000646// Adds all qualifying matches for a name within a decl context to the
647// given lookup result. Returns true if any matches were found.
Douglas Gregord3a59182010-02-12 05:48:04 +0000648static bool LookupDirect(Sema &S, LookupResult &R, const DeclContext *DC) {
John McCall9f3059a2009-10-09 21:13:30 +0000649 bool Found = false;
650
Douglas Gregor7454c562010-07-02 20:37:36 +0000651 // Lazily declare C++ special member functions.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000652 if (S.getLangOpts().CPlusPlus)
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000653 DeclareImplicitMemberFunctionsWithName(S, R.getLookupName(), DC);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000654
Douglas Gregor7454c562010-07-02 20:37:36 +0000655 // Perform lookup into this declaration context.
John McCallf6c8a4e2009-11-10 07:01:13 +0000656 DeclContext::lookup_const_iterator I, E;
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000657 for (llvm::tie(I, E) = DC->lookup(R.getLookupName()); I != E; ++I) {
John McCall401982f2010-01-20 21:53:11 +0000658 NamedDecl *D = *I;
Douglas Gregor4a814562011-12-14 16:03:29 +0000659 if ((D = R.getAcceptableDecl(D))) {
John McCall401982f2010-01-20 21:53:11 +0000660 R.addDecl(D);
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000661 Found = true;
662 }
663 }
John McCall9f3059a2009-10-09 21:13:30 +0000664
Douglas Gregord3a59182010-02-12 05:48:04 +0000665 if (!Found && DC->isTranslationUnit() && LookupBuiltin(S, R))
666 return true;
667
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000668 if (R.getLookupName().getNameKind()
Chandler Carruth3a693b72010-01-31 11:44:02 +0000669 != DeclarationName::CXXConversionFunctionName ||
670 R.getLookupName().getCXXNameType()->isDependentType() ||
671 !isa<CXXRecordDecl>(DC))
672 return Found;
673
674 // C++ [temp.mem]p6:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000675 // A specialization of a conversion function template is not found by
Chandler Carruth3a693b72010-01-31 11:44:02 +0000676 // name lookup. Instead, any conversion function templates visible in the
677 // context of the use are considered. [...]
678 const CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
John McCallf937c022011-10-07 06:10:15 +0000679 if (!Record->isCompleteDefinition())
Chandler Carruth3a693b72010-01-31 11:44:02 +0000680 return Found;
681
682 const UnresolvedSetImpl *Unresolved = Record->getConversionFunctions();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000683 for (UnresolvedSetImpl::iterator U = Unresolved->begin(),
Chandler Carruth3a693b72010-01-31 11:44:02 +0000684 UEnd = Unresolved->end(); U != UEnd; ++U) {
685 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(*U);
686 if (!ConvTemplate)
687 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000688
Chandler Carruth3a693b72010-01-31 11:44:02 +0000689 // When we're performing lookup for the purposes of redeclaration, just
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000690 // add the conversion function template. When we deduce template
691 // arguments for specializations, we'll end up unifying the return
Chandler Carruth3a693b72010-01-31 11:44:02 +0000692 // type of the new declaration with the type of the function template.
693 if (R.isForRedeclaration()) {
694 R.addDecl(ConvTemplate);
695 Found = true;
696 continue;
697 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000698
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000699 // C++ [temp.mem]p6:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000700 // [...] For each such operator, if argument deduction succeeds
701 // (14.9.2.3), the resulting specialization is used as if found by
Chandler Carruth3a693b72010-01-31 11:44:02 +0000702 // name lookup.
703 //
704 // When referencing a conversion function for any purpose other than
705 // a redeclaration (such that we'll be building an expression with the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000706 // result), perform template argument deduction and place the
Chandler Carruth3a693b72010-01-31 11:44:02 +0000707 // specialization into the result set. We do this to avoid forcing all
708 // callers to perform special deduction for conversion functions.
John McCall19c1bfd2010-08-25 05:32:35 +0000709 TemplateDeductionInfo Info(R.getSema().Context, R.getNameLoc());
Chandler Carruth3a693b72010-01-31 11:44:02 +0000710 FunctionDecl *Specialization = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000711
712 const FunctionProtoType *ConvProto
Chandler Carruth3a693b72010-01-31 11:44:02 +0000713 = ConvTemplate->getTemplatedDecl()->getType()->getAs<FunctionProtoType>();
714 assert(ConvProto && "Nonsensical conversion function template type");
Douglas Gregor3c96a462010-01-12 01:17:50 +0000715
Chandler Carruth3a693b72010-01-31 11:44:02 +0000716 // Compute the type of the function that we would expect the conversion
717 // function to have, if it were to match the name given.
718 // FIXME: Calling convention!
John McCalldb40c7f2010-12-14 08:05:40 +0000719 FunctionProtoType::ExtProtoInfo EPI = ConvProto->getExtProtoInfo();
720 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(CC_Default);
Sebastian Redl7c6c9e92011-03-06 10:52:04 +0000721 EPI.ExceptionSpecType = EST_None;
John McCalldb40c7f2010-12-14 08:05:40 +0000722 EPI.NumExceptions = 0;
Chandler Carruth3a693b72010-01-31 11:44:02 +0000723 QualType ExpectedType
724 = R.getSema().Context.getFunctionType(R.getLookupName().getCXXNameType(),
John McCalldb40c7f2010-12-14 08:05:40 +0000725 0, 0, EPI);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000726
Chandler Carruth3a693b72010-01-31 11:44:02 +0000727 // Perform template argument deduction against the type that we would
728 // expect the function to have.
729 if (R.getSema().DeduceTemplateArguments(ConvTemplate, 0, ExpectedType,
730 Specialization, Info)
731 == Sema::TDK_Success) {
732 R.addDecl(Specialization);
733 Found = true;
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000734 }
735 }
Chandler Carruth3a693b72010-01-31 11:44:02 +0000736
John McCall9f3059a2009-10-09 21:13:30 +0000737 return Found;
738}
739
John McCallf6c8a4e2009-11-10 07:01:13 +0000740// Performs C++ unqualified lookup into the given file context.
John McCall9f3059a2009-10-09 21:13:30 +0000741static bool
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000742CppNamespaceLookup(Sema &S, LookupResult &R, ASTContext &Context,
Douglas Gregord3a59182010-02-12 05:48:04 +0000743 DeclContext *NS, UnqualUsingDirectiveSet &UDirs) {
Douglas Gregor700792c2009-02-05 19:25:20 +0000744
745 assert(NS && NS->isFileContext() && "CppNamespaceLookup() requires namespace!");
746
John McCallf6c8a4e2009-11-10 07:01:13 +0000747 // Perform direct name lookup into the LookupCtx.
Douglas Gregord3a59182010-02-12 05:48:04 +0000748 bool Found = LookupDirect(S, R, NS);
Douglas Gregor700792c2009-02-05 19:25:20 +0000749
John McCallf6c8a4e2009-11-10 07:01:13 +0000750 // Perform direct name lookup into the namespaces nominated by the
751 // using directives whose common ancestor is this namespace.
752 UnqualUsingDirectiveSet::const_iterator UI, UEnd;
753 llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(NS);
Mike Stump11289f42009-09-09 15:08:12 +0000754
John McCallf6c8a4e2009-11-10 07:01:13 +0000755 for (; UI != UEnd; ++UI)
Douglas Gregord3a59182010-02-12 05:48:04 +0000756 if (LookupDirect(S, R, UI->getNominatedNamespace()))
John McCallf6c8a4e2009-11-10 07:01:13 +0000757 Found = true;
John McCall9f3059a2009-10-09 21:13:30 +0000758
759 R.resolveKind();
760
761 return Found;
Douglas Gregor700792c2009-02-05 19:25:20 +0000762}
763
764static bool isNamespaceOrTranslationUnitScope(Scope *S) {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000765 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Douglas Gregor700792c2009-02-05 19:25:20 +0000766 return Ctx->isFileContext();
767 return false;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000768}
Douglas Gregored8f2882009-01-30 01:04:22 +0000769
Douglas Gregor66230062010-03-15 14:33:29 +0000770// Find the next outer declaration context from this scope. This
771// routine actually returns the semantic outer context, which may
772// differ from the lexical context (encoded directly in the Scope
773// stack) when we are parsing a member of a class template. In this
774// case, the second element of the pair will be true, to indicate that
775// name lookup should continue searching in this semantic context when
776// it leaves the current template parameter scope.
777static std::pair<DeclContext *, bool> findOuterContext(Scope *S) {
778 DeclContext *DC = static_cast<DeclContext *>(S->getEntity());
779 DeclContext *Lexical = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000780 for (Scope *OuterS = S->getParent(); OuterS;
Douglas Gregor66230062010-03-15 14:33:29 +0000781 OuterS = OuterS->getParent()) {
782 if (OuterS->getEntity()) {
Douglas Gregorea166062010-03-15 15:26:48 +0000783 Lexical = static_cast<DeclContext *>(OuterS->getEntity());
Douglas Gregor66230062010-03-15 14:33:29 +0000784 break;
785 }
786 }
787
788 // C++ [temp.local]p8:
789 // In the definition of a member of a class template that appears
790 // outside of the namespace containing the class template
791 // definition, the name of a template-parameter hides the name of
792 // a member of this namespace.
793 //
794 // Example:
795 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000796 // namespace N {
797 // class C { };
Douglas Gregor66230062010-03-15 14:33:29 +0000798 //
799 // template<class T> class B {
800 // void f(T);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000801 // };
Douglas Gregor66230062010-03-15 14:33:29 +0000802 // }
803 //
804 // template<class C> void N::B<C>::f(C) {
805 // C b; // C is the template parameter, not N::C
806 // }
807 //
808 // In this example, the lexical context we return is the
809 // TranslationUnit, while the semantic context is the namespace N.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000810 if (!Lexical || !DC || !S->getParent() ||
Douglas Gregor66230062010-03-15 14:33:29 +0000811 !S->getParent()->isTemplateParamScope())
812 return std::make_pair(Lexical, false);
813
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000814 // Find the outermost template parameter scope.
Douglas Gregor66230062010-03-15 14:33:29 +0000815 // For the example, this is the scope for the template parameters of
816 // template<class C>.
817 Scope *OutermostTemplateScope = S->getParent();
818 while (OutermostTemplateScope->getParent() &&
819 OutermostTemplateScope->getParent()->isTemplateParamScope())
820 OutermostTemplateScope = OutermostTemplateScope->getParent();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000821
Douglas Gregor66230062010-03-15 14:33:29 +0000822 // Find the namespace context in which the original scope occurs. In
823 // the example, this is namespace N.
824 DeclContext *Semantic = DC;
825 while (!Semantic->isFileContext())
826 Semantic = Semantic->getParent();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000827
Douglas Gregor66230062010-03-15 14:33:29 +0000828 // Find the declaration context just outside of the template
829 // parameter scope. This is the context in which the template is
830 // being lexically declaration (a namespace context). In the
831 // example, this is the global scope.
832 if (Lexical->isFileContext() && !Lexical->Equals(Semantic) &&
833 Lexical->Encloses(Semantic))
834 return std::make_pair(Semantic, true);
835
836 return std::make_pair(Lexical, false);
Douglas Gregor7f737c02009-09-10 16:57:35 +0000837}
838
John McCall27b18f82009-11-17 02:14:36 +0000839bool Sema::CppLookupName(LookupResult &R, Scope *S) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000840 assert(getLangOpts().CPlusPlus && "Can perform only C++ lookup");
John McCall27b18f82009-11-17 02:14:36 +0000841
842 DeclarationName Name = R.getLookupName();
843
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000844 // If this is the name of an implicitly-declared special member function,
845 // go through the scope stack to implicitly declare
846 if (isImplicitlyDeclaredMemberFunctionName(Name)) {
847 for (Scope *PreS = S; PreS; PreS = PreS->getParent())
848 if (DeclContext *DC = static_cast<DeclContext *>(PreS->getEntity()))
849 DeclareImplicitMemberFunctionsWithName(*this, Name, DC);
850 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000851
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000852 // Implicitly declare member functions with the name we're looking for, if in
853 // fact we are in a scope where it matters.
854
Douglas Gregor889ceb72009-02-03 19:21:40 +0000855 Scope *Initial = S;
Mike Stump11289f42009-09-09 15:08:12 +0000856 IdentifierResolver::iterator
Douglas Gregor889ceb72009-02-03 19:21:40 +0000857 I = IdResolver.begin(Name),
858 IEnd = IdResolver.end();
Douglas Gregored8f2882009-01-30 01:04:22 +0000859
Douglas Gregor889ceb72009-02-03 19:21:40 +0000860 // First we lookup local scope.
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000861 // We don't consider using-directives, as per 7.3.4.p1 [namespace.udir]
Douglas Gregor889ceb72009-02-03 19:21:40 +0000862 // ...During unqualified name lookup (3.4.1), the names appear as if
863 // they were declared in the nearest enclosing namespace which contains
864 // both the using-directive and the nominated namespace.
Eli Friedman44b83ee2009-08-05 19:21:58 +0000865 // [Note: in this context, "contains" means "contains directly or
Mike Stump11289f42009-09-09 15:08:12 +0000866 // indirectly".
Douglas Gregor889ceb72009-02-03 19:21:40 +0000867 //
868 // For example:
869 // namespace A { int i; }
870 // void foo() {
871 // int i;
872 // {
873 // using namespace A;
874 // ++i; // finds local 'i', A::i appears at global scope
875 // }
876 // }
Douglas Gregor2ada0482009-02-04 17:27:36 +0000877 //
Douglas Gregor66230062010-03-15 14:33:29 +0000878 DeclContext *OutsideOfTemplateParamDC = 0;
Douglas Gregor700792c2009-02-05 19:25:20 +0000879 for (; S && !isNamespaceOrTranslationUnitScope(S); S = S->getParent()) {
Douglas Gregor3e51e172010-05-20 20:58:56 +0000880 DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity());
881
Douglas Gregor889ceb72009-02-03 19:21:40 +0000882 // Check whether the IdResolver has anything in this scope.
John McCall9f3059a2009-10-09 21:13:30 +0000883 bool Found = false;
John McCall48871652010-08-21 09:40:31 +0000884 for (; I != IEnd && S->isDeclScope(*I); ++I) {
Douglas Gregor4a814562011-12-14 16:03:29 +0000885 if (NamedDecl *ND = R.getAcceptableDecl(*I)) {
John McCall9f3059a2009-10-09 21:13:30 +0000886 Found = true;
Douglas Gregor4a814562011-12-14 16:03:29 +0000887 R.addDecl(ND);
Douglas Gregor889ceb72009-02-03 19:21:40 +0000888 }
889 }
John McCall9f3059a2009-10-09 21:13:30 +0000890 if (Found) {
891 R.resolveKind();
Douglas Gregor3e51e172010-05-20 20:58:56 +0000892 if (S->isClassScope())
893 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(Ctx))
894 R.setNamingClass(Record);
John McCall9f3059a2009-10-09 21:13:30 +0000895 return true;
896 }
897
Douglas Gregor66230062010-03-15 14:33:29 +0000898 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
899 S->getParent() && !S->getParent()->isTemplateParamScope()) {
900 // We've just searched the last template parameter scope and
901 // found nothing, so look into the the contexts between the
902 // lexical and semantic declaration contexts returned by
903 // findOuterContext(). This implements the name lookup behavior
904 // of C++ [temp.local]p8.
905 Ctx = OutsideOfTemplateParamDC;
906 OutsideOfTemplateParamDC = 0;
907 }
908
909 if (Ctx) {
910 DeclContext *OuterCtx;
911 bool SearchAfterTemplateScope;
912 llvm::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
913 if (SearchAfterTemplateScope)
914 OutsideOfTemplateParamDC = OuterCtx;
915
Douglas Gregorea166062010-03-15 15:26:48 +0000916 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
Douglas Gregor337caf92010-02-19 16:08:35 +0000917 // We do not directly look into transparent contexts, since
918 // those entities will be found in the nearest enclosing
919 // non-transparent context.
920 if (Ctx->isTransparentContext())
Douglas Gregor7f737c02009-09-10 16:57:35 +0000921 continue;
Douglas Gregor337caf92010-02-19 16:08:35 +0000922
923 // We do not look directly into function or method contexts,
924 // since all of the local variables and parameters of the
925 // function/method are present within the Scope.
926 if (Ctx->isFunctionOrMethod()) {
927 // If we have an Objective-C instance method, look for ivars
928 // in the corresponding interface.
929 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
930 if (Method->isInstanceMethod() && Name.getAsIdentifierInfo())
931 if (ObjCInterfaceDecl *Class = Method->getClassInterface()) {
932 ObjCInterfaceDecl *ClassDeclared;
933 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000934 Name.getAsIdentifierInfo(),
Douglas Gregor337caf92010-02-19 16:08:35 +0000935 ClassDeclared)) {
Douglas Gregor4a814562011-12-14 16:03:29 +0000936 if (NamedDecl *ND = R.getAcceptableDecl(Ivar)) {
937 R.addDecl(ND);
Douglas Gregor337caf92010-02-19 16:08:35 +0000938 R.resolveKind();
939 return true;
940 }
941 }
942 }
943 }
944
945 continue;
946 }
947
Douglas Gregor7f737c02009-09-10 16:57:35 +0000948 // Perform qualified name lookup into this context.
949 // FIXME: In some cases, we know that every name that could be found by
950 // this qualified name lookup will also be on the identifier chain. For
951 // example, inside a class without any base classes, we never need to
952 // perform qualified lookup because all of the members are on top of the
953 // identifier chain.
Douglas Gregord0d2ee02010-01-15 01:44:47 +0000954 if (LookupQualifiedName(R, Ctx, /*InUnqualifiedLookup=*/true))
John McCall9f3059a2009-10-09 21:13:30 +0000955 return true;
Douglas Gregorfdca4a72009-03-27 04:21:56 +0000956 }
Douglas Gregor700792c2009-02-05 19:25:20 +0000957 }
Douglas Gregored8f2882009-01-30 01:04:22 +0000958 }
Douglas Gregor889ceb72009-02-03 19:21:40 +0000959
John McCallf6c8a4e2009-11-10 07:01:13 +0000960 // Stop if we ran out of scopes.
961 // FIXME: This really, really shouldn't be happening.
962 if (!S) return false;
963
Argyrios Kyrtzidis706bbf82010-10-29 16:12:50 +0000964 // If we are looking for members, no need to look into global/namespace scope.
965 if (R.getLookupKind() == LookupMemberName)
966 return false;
967
Douglas Gregor700792c2009-02-05 19:25:20 +0000968 // Collect UsingDirectiveDecls in all scopes, and recursively all
Douglas Gregor889ceb72009-02-03 19:21:40 +0000969 // nominated namespaces by those using-directives.
John McCallf6c8a4e2009-11-10 07:01:13 +0000970 //
Mike Stump87c57ac2009-05-16 07:39:55 +0000971 // FIXME: Cache this sorted list in Scope structure, and DeclContext, so we
972 // don't build it for each lookup!
Douglas Gregor889ceb72009-02-03 19:21:40 +0000973
John McCallf6c8a4e2009-11-10 07:01:13 +0000974 UnqualUsingDirectiveSet UDirs;
975 UDirs.visitScopeChain(Initial, S);
976 UDirs.done();
Douglas Gregor889ceb72009-02-03 19:21:40 +0000977
Douglas Gregor700792c2009-02-05 19:25:20 +0000978 // Lookup namespace scope, and global scope.
Douglas Gregor889ceb72009-02-03 19:21:40 +0000979 // Unqualified name lookup in C++ requires looking into scopes
980 // that aren't strictly lexical, and therefore we walk through the
981 // context as well as walking through the scopes.
Douglas Gregor700792c2009-02-05 19:25:20 +0000982
Douglas Gregor889ceb72009-02-03 19:21:40 +0000983 for (; S; S = S->getParent()) {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000984 // Check whether the IdResolver has anything in this scope.
John McCall9f3059a2009-10-09 21:13:30 +0000985 bool Found = false;
John McCall48871652010-08-21 09:40:31 +0000986 for (; I != IEnd && S->isDeclScope(*I); ++I) {
Douglas Gregor4a814562011-12-14 16:03:29 +0000987 if (NamedDecl *ND = R.getAcceptableDecl(*I)) {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000988 // We found something. Look for anything else in our scope
989 // with this same name and in an acceptable identifier
990 // namespace, so that we can construct an overload set if we
991 // need to.
John McCall9f3059a2009-10-09 21:13:30 +0000992 Found = true;
Douglas Gregor4a814562011-12-14 16:03:29 +0000993 R.addDecl(ND);
Douglas Gregor889ceb72009-02-03 19:21:40 +0000994 }
995 }
996
Douglas Gregorf3d3ae62010-05-14 04:53:42 +0000997 if (Found && S->isTemplateParamScope()) {
John McCall9f3059a2009-10-09 21:13:30 +0000998 R.resolveKind();
999 return true;
1000 }
1001
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001002 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
1003 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
1004 S->getParent() && !S->getParent()->isTemplateParamScope()) {
1005 // We've just searched the last template parameter scope and
1006 // found nothing, so look into the the contexts between the
1007 // lexical and semantic declaration contexts returned by
1008 // findOuterContext(). This implements the name lookup behavior
1009 // of C++ [temp.local]p8.
1010 Ctx = OutsideOfTemplateParamDC;
1011 OutsideOfTemplateParamDC = 0;
1012 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001013
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001014 if (Ctx) {
1015 DeclContext *OuterCtx;
1016 bool SearchAfterTemplateScope;
1017 llvm::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
1018 if (SearchAfterTemplateScope)
1019 OutsideOfTemplateParamDC = OuterCtx;
1020
1021 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
1022 // We do not directly look into transparent contexts, since
1023 // those entities will be found in the nearest enclosing
1024 // non-transparent context.
1025 if (Ctx->isTransparentContext())
1026 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001027
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001028 // If we have a context, and it's not a context stashed in the
1029 // template parameter scope for an out-of-line definition, also
1030 // look into that context.
1031 if (!(Found && S && S->isTemplateParamScope())) {
1032 assert(Ctx->isFileContext() &&
1033 "We should have been looking only at file context here already.");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001034
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001035 // Look into context considering using-directives.
1036 if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs))
1037 Found = true;
1038 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001039
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001040 if (Found) {
1041 R.resolveKind();
1042 return true;
1043 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001044
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001045 if (R.isForRedeclaration() && !Ctx->isTransparentContext())
1046 return false;
1047 }
1048 }
1049
Douglas Gregor3ce74932010-02-05 07:07:10 +00001050 if (R.isForRedeclaration() && Ctx && !Ctx->isTransparentContext())
John McCall9f3059a2009-10-09 21:13:30 +00001051 return false;
Douglas Gregor700792c2009-02-05 19:25:20 +00001052 }
Douglas Gregor889ceb72009-02-03 19:21:40 +00001053
John McCall9f3059a2009-10-09 21:13:30 +00001054 return !R.empty();
Douglas Gregored8f2882009-01-30 01:04:22 +00001055}
1056
Douglas Gregor4a814562011-12-14 16:03:29 +00001057/// \brief Retrieve the visible declaration corresponding to D, if any.
1058///
1059/// This routine determines whether the declaration D is visible in the current
1060/// module, with the current imports. If not, it checks whether any
1061/// redeclaration of D is visible, and if so, returns that declaration.
1062///
1063/// \returns D, or a visible previous declaration of D, whichever is more recent
1064/// and visible. If no declaration of D is visible, returns null.
1065static NamedDecl *getVisibleDecl(NamedDecl *D) {
1066 if (LookupResult::isVisible(D))
1067 return D;
1068
Douglas Gregor54079202012-01-06 22:05:37 +00001069 for (Decl::redecl_iterator RD = D->redecls_begin(), RDEnd = D->redecls_end();
1070 RD != RDEnd; ++RD) {
1071 if (NamedDecl *ND = dyn_cast<NamedDecl>(*RD)) {
1072 if (LookupResult::isVisible(ND))
1073 return ND;
1074 }
Douglas Gregor4a814562011-12-14 16:03:29 +00001075 }
1076
1077 return 0;
1078}
1079
Douglas Gregor34074322009-01-14 22:20:51 +00001080/// @brief Perform unqualified name lookup starting from a given
1081/// scope.
1082///
1083/// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is
1084/// used to find names within the current scope. For example, 'x' in
1085/// @code
1086/// int x;
1087/// int f() {
1088/// return x; // unqualified name look finds 'x' in the global scope
1089/// }
1090/// @endcode
1091///
1092/// Different lookup criteria can find different names. For example, a
1093/// particular scope can have both a struct and a function of the same
1094/// name, and each can be found by certain lookup criteria. For more
1095/// information about lookup criteria, see the documentation for the
1096/// class LookupCriteria.
1097///
1098/// @param S The scope from which unqualified name lookup will
1099/// begin. If the lookup criteria permits, name lookup may also search
1100/// in the parent scopes.
1101///
1102/// @param Name The name of the entity that we are searching for.
1103///
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001104/// @param Loc If provided, the source location where we're performing
Mike Stump11289f42009-09-09 15:08:12 +00001105/// name lookup. At present, this is only used to produce diagnostics when
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001106/// C library functions (like "malloc") are implicitly declared.
Douglas Gregor34074322009-01-14 22:20:51 +00001107///
1108/// @returns The result of name lookup, which includes zero or more
1109/// declarations and possibly additional information used to diagnose
1110/// ambiguities.
John McCall27b18f82009-11-17 02:14:36 +00001111bool Sema::LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation) {
1112 DeclarationName Name = R.getLookupName();
John McCall9f3059a2009-10-09 21:13:30 +00001113 if (!Name) return false;
Douglas Gregor34074322009-01-14 22:20:51 +00001114
John McCall27b18f82009-11-17 02:14:36 +00001115 LookupNameKind NameKind = R.getLookupKind();
1116
David Blaikiebbafb8a2012-03-11 07:00:24 +00001117 if (!getLangOpts().CPlusPlus) {
Douglas Gregor34074322009-01-14 22:20:51 +00001118 // Unqualified name lookup in C/Objective-C is purely lexical, so
1119 // search in the declarations attached to the name.
John McCallea305ed2009-12-18 10:40:03 +00001120 if (NameKind == Sema::LookupRedeclarationWithLinkage) {
Douglas Gregoreddf4332009-02-24 20:03:32 +00001121 // Find the nearest non-transparent declaration scope.
1122 while (!(S->getFlags() & Scope::DeclScope) ||
Mike Stump11289f42009-09-09 15:08:12 +00001123 (S->getEntity() &&
Douglas Gregoreddf4332009-02-24 20:03:32 +00001124 static_cast<DeclContext *>(S->getEntity())
1125 ->isTransparentContext()))
1126 S = S->getParent();
Douglas Gregored8f2882009-01-30 01:04:22 +00001127 }
1128
John McCallea305ed2009-12-18 10:40:03 +00001129 unsigned IDNS = R.getIdentifierNamespace();
1130
Douglas Gregor34074322009-01-14 22:20:51 +00001131 // Scan up the scope chain looking for a decl that matches this
1132 // identifier that is in the appropriate namespace. This search
1133 // should not take long, as shadowing of names is uncommon, and
1134 // deep shadowing is extremely uncommon.
Douglas Gregoreddf4332009-02-24 20:03:32 +00001135 bool LeftStartingScope = false;
1136
Douglas Gregored8f2882009-01-30 01:04:22 +00001137 for (IdentifierResolver::iterator I = IdResolver.begin(Name),
Mike Stump11289f42009-09-09 15:08:12 +00001138 IEnd = IdResolver.end();
Douglas Gregored8f2882009-01-30 01:04:22 +00001139 I != IEnd; ++I)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001140 if ((*I)->isInIdentifierNamespace(IDNS)) {
Douglas Gregoreddf4332009-02-24 20:03:32 +00001141 if (NameKind == LookupRedeclarationWithLinkage) {
1142 // Determine whether this (or a previous) declaration is
1143 // out-of-scope.
John McCall48871652010-08-21 09:40:31 +00001144 if (!LeftStartingScope && !S->isDeclScope(*I))
Douglas Gregoreddf4332009-02-24 20:03:32 +00001145 LeftStartingScope = true;
1146
1147 // If we found something outside of our starting scope that
1148 // does not have linkage, skip it.
1149 if (LeftStartingScope && !((*I)->hasLinkage()))
1150 continue;
1151 }
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00001152 else if (NameKind == LookupObjCImplicitSelfParam &&
1153 !isa<ImplicitParamDecl>(*I))
1154 continue;
1155
Douglas Gregor2a5d1482011-12-02 20:08:44 +00001156 // If this declaration is module-private and it came from an AST
1157 // file, we can't see it.
Douglas Gregor5c193c72012-01-05 01:11:47 +00001158 NamedDecl *D = R.isHiddenDeclarationVisible()? *I : getVisibleDecl(*I);
Douglas Gregor4a814562011-12-14 16:03:29 +00001159 if (!D)
Douglas Gregor2a5d1482011-12-02 20:08:44 +00001160 continue;
Douglas Gregor4a814562011-12-14 16:03:29 +00001161
1162 R.addDecl(D);
John McCall9f3059a2009-10-09 21:13:30 +00001163
Douglas Gregorb59643b2012-01-03 23:26:26 +00001164 // Check whether there are any other declarations with the same name
1165 // and in the same scope.
Douglas Gregor9b7b3912012-01-04 16:44:10 +00001166 if (I != IEnd) {
Douglas Gregor81bd0382012-01-13 23:06:53 +00001167 // Find the scope in which this declaration was declared (if it
1168 // actually exists in a Scope).
1169 while (S && !S->isDeclScope(D))
1170 S = S->getParent();
1171
1172 // If the scope containing the declaration is the translation unit,
1173 // then we'll need to perform our checks based on the matching
1174 // DeclContexts rather than matching scopes.
1175 if (S && isNamespaceOrTranslationUnitScope(S))
1176 S = 0;
1177
1178 // Compute the DeclContext, if we need it.
1179 DeclContext *DC = 0;
1180 if (!S)
1181 DC = (*I)->getDeclContext()->getRedeclContext();
1182
Douglas Gregor9b7b3912012-01-04 16:44:10 +00001183 IdentifierResolver::iterator LastI = I;
1184 for (++LastI; LastI != IEnd; ++LastI) {
Douglas Gregor81bd0382012-01-13 23:06:53 +00001185 if (S) {
1186 // Match based on scope.
1187 if (!S->isDeclScope(*LastI))
1188 break;
1189 } else {
1190 // Match based on DeclContext.
1191 DeclContext *LastDC
1192 = (*LastI)->getDeclContext()->getRedeclContext();
1193 if (!LastDC->Equals(DC))
1194 break;
1195 }
1196
1197 // If the declaration isn't in the right namespace, skip it.
Douglas Gregor9b7b3912012-01-04 16:44:10 +00001198 if (!(*LastI)->isInIdentifierNamespace(IDNS))
1199 continue;
Douglas Gregor81bd0382012-01-13 23:06:53 +00001200
Douglas Gregor5c193c72012-01-05 01:11:47 +00001201 D = R.isHiddenDeclarationVisible()? *LastI : getVisibleDecl(*LastI);
Douglas Gregor9b7b3912012-01-04 16:44:10 +00001202 if (D)
1203 R.addDecl(D);
1204 }
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001205
Douglas Gregor9b7b3912012-01-04 16:44:10 +00001206 R.resolveKind();
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001207 }
John McCall9f3059a2009-10-09 21:13:30 +00001208 return true;
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001209 }
Douglas Gregor34074322009-01-14 22:20:51 +00001210 } else {
Douglas Gregor889ceb72009-02-03 19:21:40 +00001211 // Perform C++ unqualified name lookup.
John McCall27b18f82009-11-17 02:14:36 +00001212 if (CppLookupName(R, S))
John McCall9f3059a2009-10-09 21:13:30 +00001213 return true;
Douglas Gregor34074322009-01-14 22:20:51 +00001214 }
1215
1216 // If we didn't find a use of this identifier, and if the identifier
1217 // corresponds to a compiler builtin, create the decl object for the builtin
1218 // now, injecting it into translation unit scope, and return it.
Axel Naumann43dec142011-04-13 13:19:46 +00001219 if (AllowBuiltinCreation && LookupBuiltin(*this, R))
1220 return true;
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001221
Axel Naumann016538a2011-02-24 16:47:47 +00001222 // If we didn't find a use of this identifier, the ExternalSource
1223 // may be able to handle the situation.
1224 // Note: some lookup failures are expected!
1225 // See e.g. R.isForRedeclaration().
1226 return (ExternalSource && ExternalSource->LookupUnqualified(R, S));
Douglas Gregor34074322009-01-14 22:20:51 +00001227}
1228
John McCall6538c932009-10-10 05:48:19 +00001229/// @brief Perform qualified name lookup in the namespaces nominated by
1230/// using directives by the given context.
1231///
1232/// C++98 [namespace.qual]p2:
1233/// Given X::m (where X is a user-declared namespace), or given ::m
1234/// (where X is the global namespace), let S be the set of all
1235/// declarations of m in X and in the transitive closure of all
1236/// namespaces nominated by using-directives in X and its used
1237/// namespaces, except that using-directives are ignored in any
1238/// namespace, including X, directly containing one or more
1239/// declarations of m. No namespace is searched more than once in
1240/// the lookup of a name. If S is the empty set, the program is
1241/// ill-formed. Otherwise, if S has exactly one member, or if the
1242/// context of the reference is a using-declaration
1243/// (namespace.udecl), S is the required set of declarations of
1244/// m. Otherwise if the use of m is not one that allows a unique
1245/// declaration to be chosen from S, the program is ill-formed.
1246/// C++98 [namespace.qual]p5:
1247/// During the lookup of a qualified namespace member name, if the
1248/// lookup finds more than one declaration of the member, and if one
1249/// declaration introduces a class name or enumeration name and the
1250/// other declarations either introduce the same object, the same
1251/// enumerator or a set of functions, the non-type name hides the
1252/// class or enumeration name if and only if the declarations are
1253/// from the same namespace; otherwise (the declarations are from
1254/// different namespaces), the program is ill-formed.
Douglas Gregord3a59182010-02-12 05:48:04 +00001255static bool LookupQualifiedNameInUsingDirectives(Sema &S, LookupResult &R,
John McCall27b18f82009-11-17 02:14:36 +00001256 DeclContext *StartDC) {
John McCall6538c932009-10-10 05:48:19 +00001257 assert(StartDC->isFileContext() && "start context is not a file context");
1258
1259 DeclContext::udir_iterator I = StartDC->using_directives_begin();
1260 DeclContext::udir_iterator E = StartDC->using_directives_end();
1261
1262 if (I == E) return false;
1263
1264 // We have at least added all these contexts to the queue.
Benjamin Kramer3adbe1c2012-02-23 16:06:01 +00001265 llvm::SmallPtrSet<DeclContext*, 8> Visited;
John McCall6538c932009-10-10 05:48:19 +00001266 Visited.insert(StartDC);
1267
1268 // We have not yet looked into these namespaces, much less added
1269 // their "using-children" to the queue.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001270 SmallVector<NamespaceDecl*, 8> Queue;
John McCall6538c932009-10-10 05:48:19 +00001271
1272 // We have already looked into the initial namespace; seed the queue
1273 // with its using-children.
1274 for (; I != E; ++I) {
John McCallb8be78b2009-11-10 09:25:37 +00001275 NamespaceDecl *ND = (*I)->getNominatedNamespace()->getOriginalNamespace();
Benjamin Kramer3adbe1c2012-02-23 16:06:01 +00001276 if (Visited.insert(ND))
John McCall6538c932009-10-10 05:48:19 +00001277 Queue.push_back(ND);
1278 }
1279
1280 // The easiest way to implement the restriction in [namespace.qual]p5
1281 // is to check whether any of the individual results found a tag
1282 // and, if so, to declare an ambiguity if the final result is not
1283 // a tag.
1284 bool FoundTag = false;
1285 bool FoundNonTag = false;
1286
John McCall5cebab12009-11-18 07:57:50 +00001287 LookupResult LocalR(LookupResult::Temporary, R);
John McCall6538c932009-10-10 05:48:19 +00001288
1289 bool Found = false;
1290 while (!Queue.empty()) {
1291 NamespaceDecl *ND = Queue.back();
1292 Queue.pop_back();
1293
1294 // We go through some convolutions here to avoid copying results
1295 // between LookupResults.
1296 bool UseLocal = !R.empty();
John McCall5cebab12009-11-18 07:57:50 +00001297 LookupResult &DirectR = UseLocal ? LocalR : R;
Douglas Gregord3a59182010-02-12 05:48:04 +00001298 bool FoundDirect = LookupDirect(S, DirectR, ND);
John McCall6538c932009-10-10 05:48:19 +00001299
1300 if (FoundDirect) {
1301 // First do any local hiding.
1302 DirectR.resolveKind();
1303
1304 // If the local result is a tag, remember that.
1305 if (DirectR.isSingleTagDecl())
1306 FoundTag = true;
1307 else
1308 FoundNonTag = true;
1309
1310 // Append the local results to the total results if necessary.
1311 if (UseLocal) {
1312 R.addAllDecls(LocalR);
1313 LocalR.clear();
1314 }
1315 }
1316
1317 // If we find names in this namespace, ignore its using directives.
1318 if (FoundDirect) {
1319 Found = true;
1320 continue;
1321 }
1322
1323 for (llvm::tie(I,E) = ND->getUsingDirectives(); I != E; ++I) {
1324 NamespaceDecl *Nom = (*I)->getNominatedNamespace();
Benjamin Kramer3adbe1c2012-02-23 16:06:01 +00001325 if (Visited.insert(Nom))
John McCall6538c932009-10-10 05:48:19 +00001326 Queue.push_back(Nom);
1327 }
1328 }
1329
1330 if (Found) {
1331 if (FoundTag && FoundNonTag)
1332 R.setAmbiguousQualifiedTagHiding();
1333 else
1334 R.resolveKind();
1335 }
1336
1337 return Found;
1338}
1339
Douglas Gregor39982192010-08-15 06:18:01 +00001340/// \brief Callback that looks for any member of a class with the given name.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001341static bool LookupAnyMember(const CXXBaseSpecifier *Specifier,
Douglas Gregor39982192010-08-15 06:18:01 +00001342 CXXBasePath &Path,
1343 void *Name) {
1344 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001345
Douglas Gregor39982192010-08-15 06:18:01 +00001346 DeclarationName N = DeclarationName::getFromOpaquePtr(Name);
1347 Path.Decls = BaseRecord->lookup(N);
1348 return Path.Decls.first != Path.Decls.second;
1349}
1350
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001351/// \brief Determine whether the given set of member declarations contains only
Douglas Gregorc0d24902010-10-22 22:08:47 +00001352/// static members, nested types, and enumerators.
1353template<typename InputIterator>
1354static bool HasOnlyStaticMembers(InputIterator First, InputIterator Last) {
1355 Decl *D = (*First)->getUnderlyingDecl();
1356 if (isa<VarDecl>(D) || isa<TypeDecl>(D) || isa<EnumConstantDecl>(D))
1357 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001358
Douglas Gregorc0d24902010-10-22 22:08:47 +00001359 if (isa<CXXMethodDecl>(D)) {
1360 // Determine whether all of the methods are static.
1361 bool AllMethodsAreStatic = true;
1362 for(; First != Last; ++First) {
1363 D = (*First)->getUnderlyingDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001364
Douglas Gregorc0d24902010-10-22 22:08:47 +00001365 if (!isa<CXXMethodDecl>(D)) {
1366 assert(isa<TagDecl>(D) && "Non-function must be a tag decl");
1367 break;
1368 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001369
Douglas Gregorc0d24902010-10-22 22:08:47 +00001370 if (!cast<CXXMethodDecl>(D)->isStatic()) {
1371 AllMethodsAreStatic = false;
1372 break;
1373 }
1374 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001375
Douglas Gregorc0d24902010-10-22 22:08:47 +00001376 if (AllMethodsAreStatic)
1377 return true;
1378 }
1379
1380 return false;
1381}
1382
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001383/// \brief Perform qualified name lookup into a given context.
Douglas Gregor34074322009-01-14 22:20:51 +00001384///
1385/// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
1386/// names when the context of those names is explicit specified, e.g.,
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001387/// "std::vector" or "x->member", or as part of unqualified name lookup.
Douglas Gregor34074322009-01-14 22:20:51 +00001388///
1389/// Different lookup criteria can find different names. For example, a
1390/// particular scope can have both a struct and a function of the same
1391/// name, and each can be found by certain lookup criteria. For more
1392/// information about lookup criteria, see the documentation for the
1393/// class LookupCriteria.
1394///
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001395/// \param R captures both the lookup criteria and any lookup results found.
1396///
1397/// \param LookupCtx The context in which qualified name lookup will
Douglas Gregor34074322009-01-14 22:20:51 +00001398/// search. If the lookup criteria permits, name lookup may also search
1399/// in the parent contexts or (for C++ classes) base classes.
1400///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001401/// \param InUnqualifiedLookup true if this is qualified name lookup that
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001402/// occurs as part of unqualified name lookup.
Douglas Gregor34074322009-01-14 22:20:51 +00001403///
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001404/// \returns true if lookup succeeded, false if it failed.
1405bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
1406 bool InUnqualifiedLookup) {
Douglas Gregor34074322009-01-14 22:20:51 +00001407 assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context");
Mike Stump11289f42009-09-09 15:08:12 +00001408
John McCall27b18f82009-11-17 02:14:36 +00001409 if (!R.getLookupName())
John McCall9f3059a2009-10-09 21:13:30 +00001410 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001411
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001412 // Make sure that the declaration context is complete.
1413 assert((!isa<TagDecl>(LookupCtx) ||
1414 LookupCtx->isDependentContext() ||
John McCallf937c022011-10-07 06:10:15 +00001415 cast<TagDecl>(LookupCtx)->isCompleteDefinition() ||
Richard Smith7d137e32012-03-23 03:33:32 +00001416 cast<TagDecl>(LookupCtx)->isBeingDefined()) &&
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001417 "Declaration context must already be complete!");
Mike Stump11289f42009-09-09 15:08:12 +00001418
Douglas Gregor34074322009-01-14 22:20:51 +00001419 // Perform qualified name lookup into the LookupCtx.
Douglas Gregord3a59182010-02-12 05:48:04 +00001420 if (LookupDirect(*this, R, LookupCtx)) {
John McCall9f3059a2009-10-09 21:13:30 +00001421 R.resolveKind();
John McCall553c0792010-01-23 00:46:32 +00001422 if (isa<CXXRecordDecl>(LookupCtx))
1423 R.setNamingClass(cast<CXXRecordDecl>(LookupCtx));
John McCall9f3059a2009-10-09 21:13:30 +00001424 return true;
1425 }
Douglas Gregor34074322009-01-14 22:20:51 +00001426
John McCall6538c932009-10-10 05:48:19 +00001427 // Don't descend into implied contexts for redeclarations.
1428 // C++98 [namespace.qual]p6:
1429 // In a declaration for a namespace member in which the
1430 // declarator-id is a qualified-id, given that the qualified-id
1431 // for the namespace member has the form
1432 // nested-name-specifier unqualified-id
1433 // the unqualified-id shall name a member of the namespace
1434 // designated by the nested-name-specifier.
1435 // See also [class.mfct]p5 and [class.static.data]p2.
John McCall27b18f82009-11-17 02:14:36 +00001436 if (R.isForRedeclaration())
John McCall6538c932009-10-10 05:48:19 +00001437 return false;
1438
John McCall27b18f82009-11-17 02:14:36 +00001439 // If this is a namespace, look it up in the implied namespaces.
John McCall6538c932009-10-10 05:48:19 +00001440 if (LookupCtx->isFileContext())
Douglas Gregord3a59182010-02-12 05:48:04 +00001441 return LookupQualifiedNameInUsingDirectives(*this, R, LookupCtx);
John McCall6538c932009-10-10 05:48:19 +00001442
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001443 // If this isn't a C++ class, we aren't allowed to look into base
Douglas Gregorcc2427c2009-09-11 22:57:37 +00001444 // classes, we're done.
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001445 CXXRecordDecl *LookupRec = dyn_cast<CXXRecordDecl>(LookupCtx);
Douglas Gregor5a5fcd82010-07-01 00:21:21 +00001446 if (!LookupRec || !LookupRec->getDefinition())
John McCall9f3059a2009-10-09 21:13:30 +00001447 return false;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001448
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001449 // If we're performing qualified name lookup into a dependent class,
1450 // then we are actually looking into a current instantiation. If we have any
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001451 // dependent base classes, then we either have to delay lookup until
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001452 // template instantiation time (at which point all bases will be available)
1453 // or we have to fail.
1454 if (!InUnqualifiedLookup && LookupRec->isDependentContext() &&
1455 LookupRec->hasAnyDependentBases()) {
1456 R.setNotFoundInCurrentInstantiation();
1457 return false;
1458 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001459
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001460 // Perform lookup into our base classes.
Douglas Gregor36d1b142009-10-06 17:59:45 +00001461 CXXBasePaths Paths;
1462 Paths.setOrigin(LookupRec);
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001463
1464 // Look for this member in our base classes
Douglas Gregor36d1b142009-10-06 17:59:45 +00001465 CXXRecordDecl::BaseMatchesCallback *BaseCallback = 0;
John McCall27b18f82009-11-17 02:14:36 +00001466 switch (R.getLookupKind()) {
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00001467 case LookupObjCImplicitSelfParam:
Douglas Gregor36d1b142009-10-06 17:59:45 +00001468 case LookupOrdinaryName:
1469 case LookupMemberName:
1470 case LookupRedeclarationWithLinkage:
1471 BaseCallback = &CXXRecordDecl::FindOrdinaryMember;
1472 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001473
Douglas Gregor36d1b142009-10-06 17:59:45 +00001474 case LookupTagName:
1475 BaseCallback = &CXXRecordDecl::FindTagMember;
1476 break;
John McCall84d87672009-12-10 09:41:52 +00001477
Douglas Gregor39982192010-08-15 06:18:01 +00001478 case LookupAnyName:
1479 BaseCallback = &LookupAnyMember;
1480 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001481
John McCall84d87672009-12-10 09:41:52 +00001482 case LookupUsingDeclName:
1483 // This lookup is for redeclarations only.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001484
Douglas Gregor36d1b142009-10-06 17:59:45 +00001485 case LookupOperatorName:
1486 case LookupNamespaceName:
1487 case LookupObjCProtocolName:
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001488 case LookupLabel:
Douglas Gregor36d1b142009-10-06 17:59:45 +00001489 // These lookups will never find a member in a C++ class (or base class).
John McCall9f3059a2009-10-09 21:13:30 +00001490 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001491
Douglas Gregor36d1b142009-10-06 17:59:45 +00001492 case LookupNestedNameSpecifierName:
1493 BaseCallback = &CXXRecordDecl::FindNestedNameSpecifierMember;
1494 break;
1495 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001496
John McCall27b18f82009-11-17 02:14:36 +00001497 if (!LookupRec->lookupInBases(BaseCallback,
1498 R.getLookupName().getAsOpaquePtr(), Paths))
John McCall9f3059a2009-10-09 21:13:30 +00001499 return false;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001500
John McCall553c0792010-01-23 00:46:32 +00001501 R.setNamingClass(LookupRec);
1502
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001503 // C++ [class.member.lookup]p2:
1504 // [...] If the resulting set of declarations are not all from
1505 // sub-objects of the same type, or the set has a nonstatic member
1506 // and includes members from distinct sub-objects, there is an
1507 // ambiguity and the program is ill-formed. Otherwise that set is
1508 // the result of the lookup.
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001509 QualType SubobjectType;
Daniel Dunbar435bbe02009-01-15 18:32:35 +00001510 int SubobjectNumber = 0;
John McCalla332b952010-03-18 23:49:19 +00001511 AccessSpecifier SubobjectAccess = AS_none;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001512
Douglas Gregor36d1b142009-10-06 17:59:45 +00001513 for (CXXBasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end();
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001514 Path != PathEnd; ++Path) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00001515 const CXXBasePathElement &PathElement = Path->back();
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001516
John McCall401982f2010-01-20 21:53:11 +00001517 // Pick the best (i.e. most permissive i.e. numerically lowest) access
1518 // across all paths.
1519 SubobjectAccess = std::min(SubobjectAccess, Path->Access);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001520
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001521 // Determine whether we're looking at a distinct sub-object or not.
1522 if (SubobjectType.isNull()) {
John McCall9f3059a2009-10-09 21:13:30 +00001523 // This is the first subobject we've looked at. Record its type.
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001524 SubobjectType = Context.getCanonicalType(PathElement.Base->getType());
1525 SubobjectNumber = PathElement.SubobjectNumber;
Douglas Gregorc0d24902010-10-22 22:08:47 +00001526 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001527 }
1528
Douglas Gregorc0d24902010-10-22 22:08:47 +00001529 if (SubobjectType
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001530 != Context.getCanonicalType(PathElement.Base->getType())) {
1531 // We found members of the given name in two subobjects of
Douglas Gregorc0d24902010-10-22 22:08:47 +00001532 // different types. If the declaration sets aren't the same, this
1533 // this lookup is ambiguous.
1534 if (HasOnlyStaticMembers(Path->Decls.first, Path->Decls.second)) {
1535 CXXBasePaths::paths_iterator FirstPath = Paths.begin();
1536 DeclContext::lookup_iterator FirstD = FirstPath->Decls.first;
1537 DeclContext::lookup_iterator CurrentD = Path->Decls.first;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001538
Douglas Gregorc0d24902010-10-22 22:08:47 +00001539 while (FirstD != FirstPath->Decls.second &&
1540 CurrentD != Path->Decls.second) {
1541 if ((*FirstD)->getUnderlyingDecl()->getCanonicalDecl() !=
1542 (*CurrentD)->getUnderlyingDecl()->getCanonicalDecl())
1543 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001544
Douglas Gregorc0d24902010-10-22 22:08:47 +00001545 ++FirstD;
1546 ++CurrentD;
1547 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001548
Douglas Gregorc0d24902010-10-22 22:08:47 +00001549 if (FirstD == FirstPath->Decls.second &&
1550 CurrentD == Path->Decls.second)
1551 continue;
1552 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001553
John McCall9f3059a2009-10-09 21:13:30 +00001554 R.setAmbiguousBaseSubobjectTypes(Paths);
1555 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001556 }
1557
Douglas Gregorc0d24902010-10-22 22:08:47 +00001558 if (SubobjectNumber != PathElement.SubobjectNumber) {
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001559 // We have a different subobject of the same type.
1560
1561 // C++ [class.member.lookup]p5:
1562 // A static member, a nested type or an enumerator defined in
1563 // a base class T can unambiguously be found even if an object
Mike Stump11289f42009-09-09 15:08:12 +00001564 // has more than one base class subobject of type T.
Douglas Gregorc0d24902010-10-22 22:08:47 +00001565 if (HasOnlyStaticMembers(Path->Decls.first, Path->Decls.second))
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001566 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001567
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001568 // We have found a nonstatic member name in multiple, distinct
1569 // subobjects. Name lookup is ambiguous.
John McCall9f3059a2009-10-09 21:13:30 +00001570 R.setAmbiguousBaseSubobjects(Paths);
1571 return true;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001572 }
1573 }
1574
1575 // Lookup in a base class succeeded; return these results.
1576
John McCall9f3059a2009-10-09 21:13:30 +00001577 DeclContext::lookup_iterator I, E;
John McCall553c0792010-01-23 00:46:32 +00001578 for (llvm::tie(I,E) = Paths.front().Decls; I != E; ++I) {
1579 NamedDecl *D = *I;
1580 AccessSpecifier AS = CXXRecordDecl::MergeAccess(SubobjectAccess,
1581 D->getAccess());
1582 R.addDecl(D, AS);
1583 }
John McCall9f3059a2009-10-09 21:13:30 +00001584 R.resolveKind();
1585 return true;
Douglas Gregor34074322009-01-14 22:20:51 +00001586}
1587
1588/// @brief Performs name lookup for a name that was parsed in the
1589/// source code, and may contain a C++ scope specifier.
1590///
1591/// This routine is a convenience routine meant to be called from
1592/// contexts that receive a name and an optional C++ scope specifier
1593/// (e.g., "N::M::x"). It will then perform either qualified or
1594/// unqualified name lookup (with LookupQualifiedName or LookupName,
1595/// respectively) on the given name and return those results.
1596///
1597/// @param S The scope from which unqualified name lookup will
1598/// begin.
Mike Stump11289f42009-09-09 15:08:12 +00001599///
Douglas Gregore861bac2009-08-25 22:51:20 +00001600/// @param SS An optional C++ scope-specifier, e.g., "::N::M".
Douglas Gregor34074322009-01-14 22:20:51 +00001601///
Douglas Gregore861bac2009-08-25 22:51:20 +00001602/// @param EnteringContext Indicates whether we are going to enter the
1603/// context of the scope-specifier SS (if present).
1604///
John McCall9f3059a2009-10-09 21:13:30 +00001605/// @returns True if any decls were found (but possibly ambiguous)
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001606bool Sema::LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
John McCall27b18f82009-11-17 02:14:36 +00001607 bool AllowBuiltinCreation, bool EnteringContext) {
Douglas Gregore861bac2009-08-25 22:51:20 +00001608 if (SS && SS->isInvalid()) {
1609 // When the scope specifier is invalid, don't even look for
Douglas Gregorc9f9b862009-05-11 19:58:34 +00001610 // anything.
John McCall9f3059a2009-10-09 21:13:30 +00001611 return false;
Douglas Gregore861bac2009-08-25 22:51:20 +00001612 }
Mike Stump11289f42009-09-09 15:08:12 +00001613
Douglas Gregore861bac2009-08-25 22:51:20 +00001614 if (SS && SS->isSet()) {
1615 if (DeclContext *DC = computeDeclContext(*SS, EnteringContext)) {
Mike Stump11289f42009-09-09 15:08:12 +00001616 // We have resolved the scope specifier to a particular declaration
Douglas Gregore861bac2009-08-25 22:51:20 +00001617 // contex, and will perform name lookup in that context.
John McCall0b66eb32010-05-01 00:40:08 +00001618 if (!DC->isDependentContext() && RequireCompleteDeclContext(*SS, DC))
John McCall9f3059a2009-10-09 21:13:30 +00001619 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001620
John McCall27b18f82009-11-17 02:14:36 +00001621 R.setContextRange(SS->getRange());
John McCall27b18f82009-11-17 02:14:36 +00001622 return LookupQualifiedName(R, DC);
Douglas Gregor52537682009-03-19 00:18:19 +00001623 }
Douglas Gregorc9f9b862009-05-11 19:58:34 +00001624
Douglas Gregore861bac2009-08-25 22:51:20 +00001625 // We could not resolve the scope specified to a specific declaration
Mike Stump11289f42009-09-09 15:08:12 +00001626 // context, which means that SS refers to an unknown specialization.
Douglas Gregore861bac2009-08-25 22:51:20 +00001627 // Name lookup can't find anything in this case.
Douglas Gregor89ab56d2011-10-24 22:24:50 +00001628 R.setNotFoundInCurrentInstantiation();
1629 R.setContextRange(SS->getRange());
John McCall9f3059a2009-10-09 21:13:30 +00001630 return false;
Douglas Gregored8f2882009-01-30 01:04:22 +00001631 }
1632
Mike Stump11289f42009-09-09 15:08:12 +00001633 // Perform unqualified name lookup starting in the given scope.
John McCall27b18f82009-11-17 02:14:36 +00001634 return LookupName(R, S, AllowBuiltinCreation);
Douglas Gregor34074322009-01-14 22:20:51 +00001635}
1636
Douglas Gregor889ceb72009-02-03 19:21:40 +00001637
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001638/// @brief Produce a diagnostic describing the ambiguity that resulted
1639/// from name lookup.
1640///
1641/// @param Result The ambiguous name lookup result.
Mike Stump11289f42009-09-09 15:08:12 +00001642///
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001643/// @param Name The name of the entity that name lookup was
1644/// searching for.
1645///
1646/// @param NameLoc The location of the name within the source code.
1647///
1648/// @param LookupRange A source range that provides more
1649/// source-location information concerning the lookup itself. For
1650/// example, this range might highlight a nested-name-specifier that
1651/// precedes the name.
1652///
1653/// @returns true
John McCall27b18f82009-11-17 02:14:36 +00001654bool Sema::DiagnoseAmbiguousLookup(LookupResult &Result) {
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001655 assert(Result.isAmbiguous() && "Lookup result must be ambiguous");
1656
John McCall27b18f82009-11-17 02:14:36 +00001657 DeclarationName Name = Result.getLookupName();
1658 SourceLocation NameLoc = Result.getNameLoc();
1659 SourceRange LookupRange = Result.getContextRange();
1660
John McCall6538c932009-10-10 05:48:19 +00001661 switch (Result.getAmbiguityKind()) {
1662 case LookupResult::AmbiguousBaseSubobjects: {
1663 CXXBasePaths *Paths = Result.getBasePaths();
1664 QualType SubobjectType = Paths->front().back().Base->getType();
1665 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects)
1666 << Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths)
1667 << LookupRange;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001668
John McCall6538c932009-10-10 05:48:19 +00001669 DeclContext::lookup_iterator Found = Paths->front().Decls.first;
1670 while (isa<CXXMethodDecl>(*Found) &&
1671 cast<CXXMethodDecl>(*Found)->isStatic())
1672 ++Found;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001673
John McCall6538c932009-10-10 05:48:19 +00001674 Diag((*Found)->getLocation(), diag::note_ambiguous_member_found);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001675
John McCall6538c932009-10-10 05:48:19 +00001676 return true;
1677 }
Douglas Gregor1c846b02009-01-16 00:38:09 +00001678
John McCall6538c932009-10-10 05:48:19 +00001679 case LookupResult::AmbiguousBaseSubobjectTypes: {
Douglas Gregor889ceb72009-02-03 19:21:40 +00001680 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types)
1681 << Name << LookupRange;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001682
John McCall6538c932009-10-10 05:48:19 +00001683 CXXBasePaths *Paths = Result.getBasePaths();
Douglas Gregor889ceb72009-02-03 19:21:40 +00001684 std::set<Decl *> DeclsPrinted;
John McCall6538c932009-10-10 05:48:19 +00001685 for (CXXBasePaths::paths_iterator Path = Paths->begin(),
1686 PathEnd = Paths->end();
Douglas Gregor889ceb72009-02-03 19:21:40 +00001687 Path != PathEnd; ++Path) {
1688 Decl *D = *Path->Decls.first;
1689 if (DeclsPrinted.insert(D).second)
1690 Diag(D->getLocation(), diag::note_ambiguous_member_found);
1691 }
1692
Douglas Gregor1c846b02009-01-16 00:38:09 +00001693 return true;
Douglas Gregor1c846b02009-01-16 00:38:09 +00001694 }
1695
John McCall6538c932009-10-10 05:48:19 +00001696 case LookupResult::AmbiguousTagHiding: {
1697 Diag(NameLoc, diag::err_ambiguous_tag_hiding) << Name << LookupRange;
Douglas Gregorf23311d2009-01-17 01:13:24 +00001698
John McCall6538c932009-10-10 05:48:19 +00001699 llvm::SmallPtrSet<NamedDecl*,8> TagDecls;
1700
1701 LookupResult::iterator DI, DE = Result.end();
1702 for (DI = Result.begin(); DI != DE; ++DI)
1703 if (TagDecl *TD = dyn_cast<TagDecl>(*DI)) {
1704 TagDecls.insert(TD);
1705 Diag(TD->getLocation(), diag::note_hidden_tag);
1706 }
1707
1708 for (DI = Result.begin(); DI != DE; ++DI)
1709 if (!isa<TagDecl>(*DI))
1710 Diag((*DI)->getLocation(), diag::note_hiding_object);
1711
1712 // For recovery purposes, go ahead and implement the hiding.
John McCallad371252010-01-20 00:46:10 +00001713 LookupResult::Filter F = Result.makeFilter();
1714 while (F.hasNext()) {
1715 if (TagDecls.count(F.next()))
1716 F.erase();
1717 }
1718 F.done();
John McCall6538c932009-10-10 05:48:19 +00001719
1720 return true;
1721 }
1722
1723 case LookupResult::AmbiguousReference: {
1724 Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001725
John McCall6538c932009-10-10 05:48:19 +00001726 LookupResult::iterator DI = Result.begin(), DE = Result.end();
1727 for (; DI != DE; ++DI)
1728 Diag((*DI)->getLocation(), diag::note_ambiguous_candidate) << *DI;
John McCall9f3059a2009-10-09 21:13:30 +00001729
John McCall6538c932009-10-10 05:48:19 +00001730 return true;
1731 }
1732 }
1733
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00001734 llvm_unreachable("unknown ambiguity kind");
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001735}
Douglas Gregore254f902009-02-04 00:32:51 +00001736
John McCallf24d7bb2010-05-28 18:45:08 +00001737namespace {
1738 struct AssociatedLookup {
1739 AssociatedLookup(Sema &S,
1740 Sema::AssociatedNamespaceSet &Namespaces,
1741 Sema::AssociatedClassSet &Classes)
1742 : S(S), Namespaces(Namespaces), Classes(Classes) {
1743 }
1744
1745 Sema &S;
1746 Sema::AssociatedNamespaceSet &Namespaces;
1747 Sema::AssociatedClassSet &Classes;
1748 };
1749}
1750
Mike Stump11289f42009-09-09 15:08:12 +00001751static void
John McCallf24d7bb2010-05-28 18:45:08 +00001752addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType T);
John McCallc7e8e792009-08-07 22:18:02 +00001753
Douglas Gregor8b895222010-04-30 07:08:38 +00001754static void CollectEnclosingNamespace(Sema::AssociatedNamespaceSet &Namespaces,
1755 DeclContext *Ctx) {
1756 // Add the associated namespace for this class.
1757
1758 // We don't use DeclContext::getEnclosingNamespaceContext() as this may
1759 // be a locally scoped record.
1760
Sebastian Redlbd595762010-08-31 20:53:31 +00001761 // We skip out of inline namespaces. The innermost non-inline namespace
1762 // contains all names of all its nested inline namespaces anyway, so we can
1763 // replace the entire inline namespace tree with its root.
1764 while (Ctx->isRecord() || Ctx->isTransparentContext() ||
1765 Ctx->isInlineNamespace())
Douglas Gregor8b895222010-04-30 07:08:38 +00001766 Ctx = Ctx->getParent();
1767
John McCallc7e8e792009-08-07 22:18:02 +00001768 if (Ctx->isFileContext())
Douglas Gregor8b895222010-04-30 07:08:38 +00001769 Namespaces.insert(Ctx->getPrimaryContext());
John McCallc7e8e792009-08-07 22:18:02 +00001770}
Douglas Gregor197e5f72009-07-08 07:51:57 +00001771
Mike Stump11289f42009-09-09 15:08:12 +00001772// \brief Add the associated classes and namespaces for argument-dependent
Douglas Gregor197e5f72009-07-08 07:51:57 +00001773// lookup that involves a template argument (C++ [basic.lookup.koenig]p2).
Mike Stump11289f42009-09-09 15:08:12 +00001774static void
John McCallf24d7bb2010-05-28 18:45:08 +00001775addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
1776 const TemplateArgument &Arg) {
Douglas Gregor197e5f72009-07-08 07:51:57 +00001777 // C++ [basic.lookup.koenig]p2, last bullet:
Mike Stump11289f42009-09-09 15:08:12 +00001778 // -- [...] ;
Douglas Gregor197e5f72009-07-08 07:51:57 +00001779 switch (Arg.getKind()) {
1780 case TemplateArgument::Null:
1781 break;
Mike Stump11289f42009-09-09 15:08:12 +00001782
Douglas Gregor197e5f72009-07-08 07:51:57 +00001783 case TemplateArgument::Type:
1784 // [...] the namespaces and classes associated with the types of the
1785 // template arguments provided for template type parameters (excluding
1786 // template template parameters)
John McCallf24d7bb2010-05-28 18:45:08 +00001787 addAssociatedClassesAndNamespaces(Result, Arg.getAsType());
Douglas Gregor197e5f72009-07-08 07:51:57 +00001788 break;
Mike Stump11289f42009-09-09 15:08:12 +00001789
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001790 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00001791 case TemplateArgument::TemplateExpansion: {
Mike Stump11289f42009-09-09 15:08:12 +00001792 // [...] the namespaces in which any template template arguments are
1793 // defined; and the classes in which any member templates used as
Douglas Gregor197e5f72009-07-08 07:51:57 +00001794 // template template arguments are defined.
Douglas Gregore4ff4b52011-01-05 18:58:31 +00001795 TemplateName Template = Arg.getAsTemplateOrTemplatePattern();
Mike Stump11289f42009-09-09 15:08:12 +00001796 if (ClassTemplateDecl *ClassTemplate
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001797 = dyn_cast<ClassTemplateDecl>(Template.getAsTemplateDecl())) {
Douglas Gregor197e5f72009-07-08 07:51:57 +00001798 DeclContext *Ctx = ClassTemplate->getDeclContext();
1799 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00001800 Result.Classes.insert(EnclosingClass);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001801 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00001802 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001803 }
1804 break;
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001805 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001806
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001807 case TemplateArgument::Declaration:
Douglas Gregor197e5f72009-07-08 07:51:57 +00001808 case TemplateArgument::Integral:
1809 case TemplateArgument::Expression:
Mike Stump11289f42009-09-09 15:08:12 +00001810 // [Note: non-type template arguments do not contribute to the set of
Douglas Gregor197e5f72009-07-08 07:51:57 +00001811 // associated namespaces. ]
1812 break;
Mike Stump11289f42009-09-09 15:08:12 +00001813
Douglas Gregor197e5f72009-07-08 07:51:57 +00001814 case TemplateArgument::Pack:
1815 for (TemplateArgument::pack_iterator P = Arg.pack_begin(),
1816 PEnd = Arg.pack_end();
1817 P != PEnd; ++P)
John McCallf24d7bb2010-05-28 18:45:08 +00001818 addAssociatedClassesAndNamespaces(Result, *P);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001819 break;
1820 }
1821}
1822
Douglas Gregore254f902009-02-04 00:32:51 +00001823// \brief Add the associated classes and namespaces for
Mike Stump11289f42009-09-09 15:08:12 +00001824// argument-dependent lookup with an argument of class type
1825// (C++ [basic.lookup.koenig]p2).
1826static void
John McCallf24d7bb2010-05-28 18:45:08 +00001827addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
1828 CXXRecordDecl *Class) {
1829
1830 // Just silently ignore anything whose name is __va_list_tag.
1831 if (Class->getDeclName() == Result.S.VAListTagName)
1832 return;
1833
Douglas Gregore254f902009-02-04 00:32:51 +00001834 // C++ [basic.lookup.koenig]p2:
1835 // [...]
1836 // -- If T is a class type (including unions), its associated
1837 // classes are: the class itself; the class of which it is a
1838 // member, if any; and its direct and indirect base
1839 // classes. Its associated namespaces are the namespaces in
Mike Stump11289f42009-09-09 15:08:12 +00001840 // which its associated classes are defined.
Douglas Gregore254f902009-02-04 00:32:51 +00001841
1842 // Add the class of which it is a member, if any.
1843 DeclContext *Ctx = Class->getDeclContext();
1844 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00001845 Result.Classes.insert(EnclosingClass);
Douglas Gregore254f902009-02-04 00:32:51 +00001846 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00001847 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Mike Stump11289f42009-09-09 15:08:12 +00001848
Douglas Gregore254f902009-02-04 00:32:51 +00001849 // Add the class itself. If we've already seen this class, we don't
1850 // need to visit base classes.
John McCallf24d7bb2010-05-28 18:45:08 +00001851 if (!Result.Classes.insert(Class))
Douglas Gregore254f902009-02-04 00:32:51 +00001852 return;
1853
Mike Stump11289f42009-09-09 15:08:12 +00001854 // -- If T is a template-id, its associated namespaces and classes are
1855 // the namespace in which the template is defined; for member
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00001856 // templates, the member template's class; the namespaces and classes
Mike Stump11289f42009-09-09 15:08:12 +00001857 // associated with the types of the template arguments provided for
Douglas Gregor197e5f72009-07-08 07:51:57 +00001858 // template type parameters (excluding template template parameters); the
Mike Stump11289f42009-09-09 15:08:12 +00001859 // namespaces in which any template template arguments are defined; and
1860 // the classes in which any member templates used as template template
1861 // arguments are defined. [Note: non-type template arguments do not
Douglas Gregor197e5f72009-07-08 07:51:57 +00001862 // contribute to the set of associated namespaces. ]
Mike Stump11289f42009-09-09 15:08:12 +00001863 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregor197e5f72009-07-08 07:51:57 +00001864 = dyn_cast<ClassTemplateSpecializationDecl>(Class)) {
1865 DeclContext *Ctx = Spec->getSpecializedTemplate()->getDeclContext();
1866 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00001867 Result.Classes.insert(EnclosingClass);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001868 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00001869 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Mike Stump11289f42009-09-09 15:08:12 +00001870
Douglas Gregor197e5f72009-07-08 07:51:57 +00001871 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
1872 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
John McCallf24d7bb2010-05-28 18:45:08 +00001873 addAssociatedClassesAndNamespaces(Result, TemplateArgs[I]);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001874 }
Mike Stump11289f42009-09-09 15:08:12 +00001875
John McCall67da35c2010-02-04 22:26:26 +00001876 // Only recurse into base classes for complete types.
1877 if (!Class->hasDefinition()) {
1878 // FIXME: we might need to instantiate templates here
1879 return;
1880 }
1881
Douglas Gregore254f902009-02-04 00:32:51 +00001882 // Add direct and indirect base classes along with their associated
1883 // namespaces.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001884 SmallVector<CXXRecordDecl *, 32> Bases;
Douglas Gregore254f902009-02-04 00:32:51 +00001885 Bases.push_back(Class);
1886 while (!Bases.empty()) {
1887 // Pop this class off the stack.
1888 Class = Bases.back();
1889 Bases.pop_back();
1890
1891 // Visit the base classes.
1892 for (CXXRecordDecl::base_class_iterator Base = Class->bases_begin(),
1893 BaseEnd = Class->bases_end();
1894 Base != BaseEnd; ++Base) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001895 const RecordType *BaseType = Base->getType()->getAs<RecordType>();
Sebastian Redlc45c03c2009-10-25 09:35:33 +00001896 // In dependent contexts, we do ADL twice, and the first time around,
1897 // the base type might be a dependent TemplateSpecializationType, or a
1898 // TemplateTypeParmType. If that happens, simply ignore it.
1899 // FIXME: If we want to support export, we probably need to add the
1900 // namespace of the template in a TemplateSpecializationType, or even
1901 // the classes and namespaces of known non-dependent arguments.
1902 if (!BaseType)
1903 continue;
Douglas Gregore254f902009-02-04 00:32:51 +00001904 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(BaseType->getDecl());
John McCallf24d7bb2010-05-28 18:45:08 +00001905 if (Result.Classes.insert(BaseDecl)) {
Douglas Gregore254f902009-02-04 00:32:51 +00001906 // Find the associated namespace for this base class.
1907 DeclContext *BaseCtx = BaseDecl->getDeclContext();
John McCallf24d7bb2010-05-28 18:45:08 +00001908 CollectEnclosingNamespace(Result.Namespaces, BaseCtx);
Douglas Gregore254f902009-02-04 00:32:51 +00001909
1910 // Make sure we visit the bases of this base class.
1911 if (BaseDecl->bases_begin() != BaseDecl->bases_end())
1912 Bases.push_back(BaseDecl);
1913 }
1914 }
1915 }
1916}
1917
1918// \brief Add the associated classes and namespaces for
1919// argument-dependent lookup with an argument of type T
Mike Stump11289f42009-09-09 15:08:12 +00001920// (C++ [basic.lookup.koenig]p2).
1921static void
John McCallf24d7bb2010-05-28 18:45:08 +00001922addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType Ty) {
Douglas Gregore254f902009-02-04 00:32:51 +00001923 // C++ [basic.lookup.koenig]p2:
1924 //
1925 // For each argument type T in the function call, there is a set
1926 // of zero or more associated namespaces and a set of zero or more
1927 // associated classes to be considered. The sets of namespaces and
1928 // classes is determined entirely by the types of the function
1929 // arguments (and the namespace of any template template
1930 // argument). Typedef names and using-declarations used to specify
1931 // the types do not contribute to this set. The sets of namespaces
1932 // and classes are determined in the following way:
Douglas Gregore254f902009-02-04 00:32:51 +00001933
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001934 SmallVector<const Type *, 16> Queue;
John McCall0af3d3b2010-05-28 06:08:54 +00001935 const Type *T = Ty->getCanonicalTypeInternal().getTypePtr();
1936
Douglas Gregore254f902009-02-04 00:32:51 +00001937 while (true) {
John McCall0af3d3b2010-05-28 06:08:54 +00001938 switch (T->getTypeClass()) {
1939
1940#define TYPE(Class, Base)
1941#define DEPENDENT_TYPE(Class, Base) case Type::Class:
1942#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
1943#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
1944#define ABSTRACT_TYPE(Class, Base)
1945#include "clang/AST/TypeNodes.def"
1946 // T is canonical. We can also ignore dependent types because
1947 // we don't need to do ADL at the definition point, but if we
1948 // wanted to implement template export (or if we find some other
1949 // use for associated classes and namespaces...) this would be
1950 // wrong.
Douglas Gregore254f902009-02-04 00:32:51 +00001951 break;
Douglas Gregore254f902009-02-04 00:32:51 +00001952
John McCall0af3d3b2010-05-28 06:08:54 +00001953 // -- If T is a pointer to U or an array of U, its associated
1954 // namespaces and classes are those associated with U.
1955 case Type::Pointer:
1956 T = cast<PointerType>(T)->getPointeeType().getTypePtr();
1957 continue;
1958 case Type::ConstantArray:
1959 case Type::IncompleteArray:
1960 case Type::VariableArray:
1961 T = cast<ArrayType>(T)->getElementType().getTypePtr();
1962 continue;
Douglas Gregore254f902009-02-04 00:32:51 +00001963
John McCall0af3d3b2010-05-28 06:08:54 +00001964 // -- If T is a fundamental type, its associated sets of
1965 // namespaces and classes are both empty.
1966 case Type::Builtin:
1967 break;
1968
1969 // -- If T is a class type (including unions), its associated
1970 // classes are: the class itself; the class of which it is a
1971 // member, if any; and its direct and indirect base
1972 // classes. Its associated namespaces are the namespaces in
1973 // which its associated classes are defined.
1974 case Type::Record: {
1975 CXXRecordDecl *Class
1976 = cast<CXXRecordDecl>(cast<RecordType>(T)->getDecl());
John McCallf24d7bb2010-05-28 18:45:08 +00001977 addAssociatedClassesAndNamespaces(Result, Class);
John McCall0af3d3b2010-05-28 06:08:54 +00001978 break;
Douglas Gregor89ee6822009-02-28 01:32:25 +00001979 }
Douglas Gregorfe60c142010-05-20 02:26:51 +00001980
John McCall0af3d3b2010-05-28 06:08:54 +00001981 // -- If T is an enumeration type, its associated namespace is
1982 // the namespace in which it is defined. If it is class
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00001983 // member, its associated class is the member's class; else
John McCall0af3d3b2010-05-28 06:08:54 +00001984 // it has no associated class.
1985 case Type::Enum: {
1986 EnumDecl *Enum = cast<EnumType>(T)->getDecl();
Douglas Gregore254f902009-02-04 00:32:51 +00001987
John McCall0af3d3b2010-05-28 06:08:54 +00001988 DeclContext *Ctx = Enum->getDeclContext();
1989 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00001990 Result.Classes.insert(EnclosingClass);
Douglas Gregore254f902009-02-04 00:32:51 +00001991
John McCall0af3d3b2010-05-28 06:08:54 +00001992 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00001993 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Douglas Gregore254f902009-02-04 00:32:51 +00001994
John McCall0af3d3b2010-05-28 06:08:54 +00001995 break;
1996 }
1997
1998 // -- If T is a function type, its associated namespaces and
1999 // classes are those associated with the function parameter
2000 // types and those associated with the return type.
2001 case Type::FunctionProto: {
2002 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
2003 for (FunctionProtoType::arg_type_iterator Arg = Proto->arg_type_begin(),
2004 ArgEnd = Proto->arg_type_end();
2005 Arg != ArgEnd; ++Arg)
2006 Queue.push_back(Arg->getTypePtr());
2007 // fallthrough
2008 }
2009 case Type::FunctionNoProto: {
2010 const FunctionType *FnType = cast<FunctionType>(T);
2011 T = FnType->getResultType().getTypePtr();
2012 continue;
2013 }
2014
2015 // -- If T is a pointer to a member function of a class X, its
2016 // associated namespaces and classes are those associated
2017 // with the function parameter types and return type,
2018 // together with those associated with X.
2019 //
2020 // -- If T is a pointer to a data member of class X, its
2021 // associated namespaces and classes are those associated
2022 // with the member type together with those associated with
2023 // X.
2024 case Type::MemberPointer: {
2025 const MemberPointerType *MemberPtr = cast<MemberPointerType>(T);
2026
2027 // Queue up the class type into which this points.
2028 Queue.push_back(MemberPtr->getClass());
2029
2030 // And directly continue with the pointee type.
2031 T = MemberPtr->getPointeeType().getTypePtr();
2032 continue;
2033 }
2034
2035 // As an extension, treat this like a normal pointer.
2036 case Type::BlockPointer:
2037 T = cast<BlockPointerType>(T)->getPointeeType().getTypePtr();
2038 continue;
2039
2040 // References aren't covered by the standard, but that's such an
2041 // obvious defect that we cover them anyway.
2042 case Type::LValueReference:
2043 case Type::RValueReference:
2044 T = cast<ReferenceType>(T)->getPointeeType().getTypePtr();
2045 continue;
2046
2047 // These are fundamental types.
2048 case Type::Vector:
2049 case Type::ExtVector:
2050 case Type::Complex:
2051 break;
2052
Douglas Gregor8e936662011-04-12 01:02:45 +00002053 // If T is an Objective-C object or interface type, or a pointer to an
2054 // object or interface type, the associated namespace is the global
2055 // namespace.
John McCall0af3d3b2010-05-28 06:08:54 +00002056 case Type::ObjCObject:
2057 case Type::ObjCInterface:
2058 case Type::ObjCObjectPointer:
Douglas Gregor8e936662011-04-12 01:02:45 +00002059 Result.Namespaces.insert(Result.S.Context.getTranslationUnitDecl());
John McCall0af3d3b2010-05-28 06:08:54 +00002060 break;
Eli Friedman0dfb8892011-10-06 23:00:33 +00002061
2062 // Atomic types are just wrappers; use the associations of the
2063 // contained type.
2064 case Type::Atomic:
2065 T = cast<AtomicType>(T)->getValueType().getTypePtr();
2066 continue;
John McCall0af3d3b2010-05-28 06:08:54 +00002067 }
2068
2069 if (Queue.empty()) break;
2070 T = Queue.back();
2071 Queue.pop_back();
Douglas Gregore254f902009-02-04 00:32:51 +00002072 }
Douglas Gregore254f902009-02-04 00:32:51 +00002073}
2074
2075/// \brief Find the associated classes and namespaces for
2076/// argument-dependent lookup for a call with the given set of
2077/// arguments.
2078///
2079/// This routine computes the sets of associated classes and associated
Mike Stump11289f42009-09-09 15:08:12 +00002080/// namespaces searched by argument-dependent lookup
Douglas Gregore254f902009-02-04 00:32:51 +00002081/// (C++ [basic.lookup.argdep]) for a given set of arguments.
Mike Stump11289f42009-09-09 15:08:12 +00002082void
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002083Sema::FindAssociatedClassesAndNamespaces(llvm::ArrayRef<Expr *> Args,
Douglas Gregore254f902009-02-04 00:32:51 +00002084 AssociatedNamespaceSet &AssociatedNamespaces,
John McCallc7e8e792009-08-07 22:18:02 +00002085 AssociatedClassSet &AssociatedClasses) {
Douglas Gregore254f902009-02-04 00:32:51 +00002086 AssociatedNamespaces.clear();
2087 AssociatedClasses.clear();
2088
John McCallf24d7bb2010-05-28 18:45:08 +00002089 AssociatedLookup Result(*this, AssociatedNamespaces, AssociatedClasses);
2090
Douglas Gregore254f902009-02-04 00:32:51 +00002091 // C++ [basic.lookup.koenig]p2:
2092 // For each argument type T in the function call, there is a set
2093 // of zero or more associated namespaces and a set of zero or more
2094 // associated classes to be considered. The sets of namespaces and
2095 // classes is determined entirely by the types of the function
2096 // arguments (and the namespace of any template template
Mike Stump11289f42009-09-09 15:08:12 +00002097 // argument).
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002098 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
Douglas Gregore254f902009-02-04 00:32:51 +00002099 Expr *Arg = Args[ArgIdx];
2100
2101 if (Arg->getType() != Context.OverloadTy) {
John McCallf24d7bb2010-05-28 18:45:08 +00002102 addAssociatedClassesAndNamespaces(Result, Arg->getType());
Douglas Gregore254f902009-02-04 00:32:51 +00002103 continue;
2104 }
2105
2106 // [...] In addition, if the argument is the name or address of a
2107 // set of overloaded functions and/or function templates, its
2108 // associated classes and namespaces are the union of those
2109 // associated with each of the members of the set: the namespace
2110 // in which the function or function template is defined and the
2111 // classes and namespaces associated with its (non-dependent)
2112 // parameter types and return type.
Douglas Gregorbe759252009-07-08 10:57:20 +00002113 Arg = Arg->IgnoreParens();
John McCalld14a8642009-11-21 08:51:07 +00002114 if (UnaryOperator *unaryOp = dyn_cast<UnaryOperator>(Arg))
John McCalle3027922010-08-25 11:45:40 +00002115 if (unaryOp->getOpcode() == UO_AddrOf)
John McCalld14a8642009-11-21 08:51:07 +00002116 Arg = unaryOp->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00002117
John McCallf24d7bb2010-05-28 18:45:08 +00002118 UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Arg);
2119 if (!ULE) continue;
John McCalld14a8642009-11-21 08:51:07 +00002120
John McCallf24d7bb2010-05-28 18:45:08 +00002121 for (UnresolvedSetIterator I = ULE->decls_begin(), E = ULE->decls_end();
2122 I != E; ++I) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00002123 // Look through any using declarations to find the underlying function.
2124 NamedDecl *Fn = (*I)->getUnderlyingDecl();
Douglas Gregore254f902009-02-04 00:32:51 +00002125
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00002126 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(Fn);
2127 if (!FDecl)
2128 FDecl = cast<FunctionTemplateDecl>(Fn)->getTemplatedDecl();
Douglas Gregore254f902009-02-04 00:32:51 +00002129
2130 // Add the classes and namespaces associated with the parameter
2131 // types and return type of this function.
John McCallf24d7bb2010-05-28 18:45:08 +00002132 addAssociatedClassesAndNamespaces(Result, FDecl->getType());
Douglas Gregore254f902009-02-04 00:32:51 +00002133 }
2134 }
2135}
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002136
2137/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
2138/// an acceptable non-member overloaded operator for a call whose
2139/// arguments have types T1 (and, if non-empty, T2). This routine
2140/// implements the check in C++ [over.match.oper]p3b2 concerning
2141/// enumeration types.
Mike Stump11289f42009-09-09 15:08:12 +00002142static bool
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002143IsAcceptableNonMemberOperatorCandidate(FunctionDecl *Fn,
2144 QualType T1, QualType T2,
2145 ASTContext &Context) {
Douglas Gregor0950e412009-03-13 21:01:28 +00002146 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
2147 return true;
2148
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002149 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
2150 return true;
2151
John McCall9dd450b2009-09-21 23:43:11 +00002152 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002153 if (Proto->getNumArgs() < 1)
2154 return false;
2155
2156 if (T1->isEnumeralType()) {
2157 QualType ArgType = Proto->getArgType(0).getNonReferenceType();
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002158 if (Context.hasSameUnqualifiedType(T1, ArgType))
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002159 return true;
2160 }
2161
2162 if (Proto->getNumArgs() < 2)
2163 return false;
2164
2165 if (!T2.isNull() && T2->isEnumeralType()) {
2166 QualType ArgType = Proto->getArgType(1).getNonReferenceType();
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002167 if (Context.hasSameUnqualifiedType(T2, ArgType))
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002168 return true;
2169 }
2170
2171 return false;
2172}
2173
John McCall5cebab12009-11-18 07:57:50 +00002174NamedDecl *Sema::LookupSingleName(Scope *S, DeclarationName Name,
Douglas Gregorb2ccf012010-04-15 22:33:43 +00002175 SourceLocation Loc,
John McCall5cebab12009-11-18 07:57:50 +00002176 LookupNameKind NameKind,
2177 RedeclarationKind Redecl) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +00002178 LookupResult R(*this, Name, Loc, NameKind, Redecl);
John McCall5cebab12009-11-18 07:57:50 +00002179 LookupName(R, S);
John McCall67c00872009-12-02 08:25:40 +00002180 return R.getAsSingle<NamedDecl>();
John McCall5cebab12009-11-18 07:57:50 +00002181}
2182
Douglas Gregorde9f17e2009-04-23 23:18:26 +00002183/// \brief Find the protocol with the given name, if any.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002184ObjCProtocolDecl *Sema::LookupProtocol(IdentifierInfo *II,
Douglas Gregor32c17572012-01-01 20:30:41 +00002185 SourceLocation IdLoc,
2186 RedeclarationKind Redecl) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +00002187 Decl *D = LookupSingleName(TUScope, II, IdLoc,
Douglas Gregor32c17572012-01-01 20:30:41 +00002188 LookupObjCProtocolName, Redecl);
Douglas Gregorde9f17e2009-04-23 23:18:26 +00002189 return cast_or_null<ObjCProtocolDecl>(D);
2190}
2191
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002192void Sema::LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
Mike Stump11289f42009-09-09 15:08:12 +00002193 QualType T1, QualType T2,
John McCall4c4c1df2010-01-26 03:27:55 +00002194 UnresolvedSetImpl &Functions) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002195 // C++ [over.match.oper]p3:
2196 // -- The set of non-member candidates is the result of the
2197 // unqualified lookup of operator@ in the context of the
2198 // expression according to the usual rules for name lookup in
2199 // unqualified function calls (3.4.2) except that all member
2200 // functions are ignored. However, if no operand has a class
2201 // type, only those non-member functions in the lookup set
Eli Friedman44b83ee2009-08-05 19:21:58 +00002202 // that have a first parameter of type T1 or "reference to
2203 // (possibly cv-qualified) T1", when T1 is an enumeration
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002204 // type, or (if there is a right operand) a second parameter
Eli Friedman44b83ee2009-08-05 19:21:58 +00002205 // of type T2 or "reference to (possibly cv-qualified) T2",
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002206 // when T2 is an enumeration type, are candidate functions.
2207 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
John McCall27b18f82009-11-17 02:14:36 +00002208 LookupResult Operators(*this, OpName, SourceLocation(), LookupOperatorName);
2209 LookupName(Operators, S);
Mike Stump11289f42009-09-09 15:08:12 +00002210
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002211 assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
2212
John McCall9f3059a2009-10-09 21:13:30 +00002213 if (Operators.empty())
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002214 return;
2215
2216 for (LookupResult::iterator Op = Operators.begin(), OpEnd = Operators.end();
2217 Op != OpEnd; ++Op) {
Douglas Gregor645d76f2010-04-25 20:25:43 +00002218 NamedDecl *Found = (*Op)->getUnderlyingDecl();
2219 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Found)) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002220 if (IsAcceptableNonMemberOperatorCandidate(FD, T1, T2, Context))
Douglas Gregor645d76f2010-04-25 20:25:43 +00002221 Functions.addDecl(*Op, Op.getAccess()); // FIXME: canonical FD
Mike Stump11289f42009-09-09 15:08:12 +00002222 } else if (FunctionTemplateDecl *FunTmpl
Douglas Gregor645d76f2010-04-25 20:25:43 +00002223 = dyn_cast<FunctionTemplateDecl>(Found)) {
Douglas Gregor15448f82009-06-27 21:05:07 +00002224 // FIXME: friend operators?
Mike Stump11289f42009-09-09 15:08:12 +00002225 // FIXME: do we need to check IsAcceptableNonMemberOperatorCandidate,
Douglas Gregor15448f82009-06-27 21:05:07 +00002226 // later?
2227 if (!FunTmpl->getDeclContext()->isRecord())
Douglas Gregor645d76f2010-04-25 20:25:43 +00002228 Functions.addDecl(*Op, Op.getAccess());
Douglas Gregor15448f82009-06-27 21:05:07 +00002229 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002230 }
2231}
2232
Alexis Hunt1da39282011-06-24 02:11:39 +00002233Sema::SpecialMemberOverloadResult *Sema::LookupSpecialMember(CXXRecordDecl *RD,
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002234 CXXSpecialMember SM,
2235 bool ConstArg,
2236 bool VolatileArg,
2237 bool RValueThis,
2238 bool ConstThis,
2239 bool VolatileThis) {
Alexis Hunt1da39282011-06-24 02:11:39 +00002240 RD = RD->getDefinition();
2241 assert((RD && !RD->isBeingDefined()) &&
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002242 "doing special member lookup into record that isn't fully complete");
2243 if (RValueThis || ConstThis || VolatileThis)
2244 assert((SM == CXXCopyAssignment || SM == CXXMoveAssignment) &&
2245 "constructors and destructors always have unqualified lvalue this");
2246 if (ConstArg || VolatileArg)
2247 assert((SM != CXXDefaultConstructor && SM != CXXDestructor) &&
2248 "parameter-less special members can't have qualified arguments");
2249
2250 llvm::FoldingSetNodeID ID;
Alexis Hunt1da39282011-06-24 02:11:39 +00002251 ID.AddPointer(RD);
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002252 ID.AddInteger(SM);
2253 ID.AddInteger(ConstArg);
2254 ID.AddInteger(VolatileArg);
2255 ID.AddInteger(RValueThis);
2256 ID.AddInteger(ConstThis);
2257 ID.AddInteger(VolatileThis);
2258
2259 void *InsertPoint;
2260 SpecialMemberOverloadResult *Result =
2261 SpecialMemberCache.FindNodeOrInsertPos(ID, InsertPoint);
2262
2263 // This was already cached
2264 if (Result)
2265 return Result;
2266
Alexis Huntba8e18d2011-06-07 00:11:58 +00002267 Result = BumpAlloc.Allocate<SpecialMemberOverloadResult>();
2268 Result = new (Result) SpecialMemberOverloadResult(ID);
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002269 SpecialMemberCache.InsertNode(Result, InsertPoint);
2270
2271 if (SM == CXXDestructor) {
Alexis Hunt1da39282011-06-24 02:11:39 +00002272 if (!RD->hasDeclaredDestructor())
2273 DeclareImplicitDestructor(RD);
2274 CXXDestructorDecl *DD = RD->getDestructor();
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002275 assert(DD && "record without a destructor");
2276 Result->setMethod(DD);
Richard Smith852265f2012-03-30 20:53:28 +00002277 Result->setKind(DD->isDeleted() ?
2278 SpecialMemberOverloadResult::NoMemberOrDeleted :
2279 SpecialMemberOverloadResult::SuccessNonConst);
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002280 return Result;
2281 }
2282
Alexis Hunteef8ee02011-06-10 03:50:41 +00002283 // Prepare for overload resolution. Here we construct a synthetic argument
2284 // if necessary and make sure that implicit functions are declared.
Alexis Hunt1da39282011-06-24 02:11:39 +00002285 CanQualType CanTy = Context.getCanonicalType(Context.getTagDeclType(RD));
Alexis Hunteef8ee02011-06-10 03:50:41 +00002286 DeclarationName Name;
2287 Expr *Arg = 0;
2288 unsigned NumArgs;
2289
2290 if (SM == CXXDefaultConstructor) {
2291 Name = Context.DeclarationNames.getCXXConstructorName(CanTy);
2292 NumArgs = 0;
Alexis Hunt1da39282011-06-24 02:11:39 +00002293 if (RD->needsImplicitDefaultConstructor())
2294 DeclareImplicitDefaultConstructor(RD);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002295 } else {
2296 if (SM == CXXCopyConstructor || SM == CXXMoveConstructor) {
2297 Name = Context.DeclarationNames.getCXXConstructorName(CanTy);
Alexis Hunt1da39282011-06-24 02:11:39 +00002298 if (!RD->hasDeclaredCopyConstructor())
2299 DeclareImplicitCopyConstructor(RD);
David Blaikiebbafb8a2012-03-11 07:00:24 +00002300 if (getLangOpts().CPlusPlus0x && RD->needsImplicitMoveConstructor())
Sebastian Redl22653ba2011-08-30 19:58:05 +00002301 DeclareImplicitMoveConstructor(RD);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002302 } else {
2303 Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Alexis Hunt1da39282011-06-24 02:11:39 +00002304 if (!RD->hasDeclaredCopyAssignment())
2305 DeclareImplicitCopyAssignment(RD);
David Blaikiebbafb8a2012-03-11 07:00:24 +00002306 if (getLangOpts().CPlusPlus0x && RD->needsImplicitMoveAssignment())
Sebastian Redl22653ba2011-08-30 19:58:05 +00002307 DeclareImplicitMoveAssignment(RD);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002308 }
2309
2310 QualType ArgType = CanTy;
2311 if (ConstArg)
2312 ArgType.addConst();
2313 if (VolatileArg)
2314 ArgType.addVolatile();
2315
2316 // This isn't /really/ specified by the standard, but it's implied
2317 // we should be working from an RValue in the case of move to ensure
2318 // that we prefer to bind to rvalue references, and an LValue in the
2319 // case of copy to ensure we don't bind to rvalue references.
2320 // Possibly an XValue is actually correct in the case of move, but
2321 // there is no semantic difference for class types in this restricted
2322 // case.
2323 ExprValueKind VK;
Alexis Hunt46d1ce22011-06-22 22:13:13 +00002324 if (SM == CXXCopyConstructor || SM == CXXCopyAssignment)
Alexis Hunteef8ee02011-06-10 03:50:41 +00002325 VK = VK_LValue;
2326 else
2327 VK = VK_RValue;
2328
2329 NumArgs = 1;
2330 Arg = new (Context) OpaqueValueExpr(SourceLocation(), ArgType, VK);
2331 }
2332
2333 // Create the object argument
2334 QualType ThisTy = CanTy;
2335 if (ConstThis)
2336 ThisTy.addConst();
2337 if (VolatileThis)
2338 ThisTy.addVolatile();
Alexis Hunt080709f2011-06-23 00:26:20 +00002339 Expr::Classification Classification =
Alexis Hunteef8ee02011-06-10 03:50:41 +00002340 (new (Context) OpaqueValueExpr(SourceLocation(), ThisTy,
2341 RValueThis ? VK_RValue : VK_LValue))->
2342 Classify(Context);
2343
2344 // Now we perform lookup on the name we computed earlier and do overload
2345 // resolution. Lookup is only performed directly into the class since there
2346 // will always be a (possibly implicit) declaration to shadow any others.
2347 OverloadCandidateSet OCS((SourceLocation()));
2348 DeclContext::lookup_iterator I, E;
Richard Smith852265f2012-03-30 20:53:28 +00002349 SpecialMemberOverloadResult::Kind SuccessKind =
2350 SpecialMemberOverloadResult::SuccessNonConst;
Alexis Hunteef8ee02011-06-10 03:50:41 +00002351
Alexis Hunt1da39282011-06-24 02:11:39 +00002352 llvm::tie(I, E) = RD->lookup(Name);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002353 assert((I != E) &&
2354 "lookup for a constructor or assignment operator was empty");
2355 for ( ; I != E; ++I) {
Alexis Hunt1da39282011-06-24 02:11:39 +00002356 Decl *Cand = *I;
Alexis Hunt080709f2011-06-23 00:26:20 +00002357
Alexis Hunt1da39282011-06-24 02:11:39 +00002358 if (Cand->isInvalidDecl())
Alexis Hunteef8ee02011-06-10 03:50:41 +00002359 continue;
2360
Alexis Hunt1da39282011-06-24 02:11:39 +00002361 if (UsingShadowDecl *U = dyn_cast<UsingShadowDecl>(Cand)) {
2362 // FIXME: [namespace.udecl]p15 says that we should only consider a
2363 // using declaration here if it does not match a declaration in the
2364 // derived class. We do not implement this correctly in other cases
2365 // either.
2366 Cand = U->getTargetDecl();
2367
2368 if (Cand->isInvalidDecl())
2369 continue;
2370 }
2371
2372 if (CXXMethodDecl *M = dyn_cast<CXXMethodDecl>(Cand)) {
Alexis Hunt080709f2011-06-23 00:26:20 +00002373 if (SM == CXXCopyAssignment || SM == CXXMoveAssignment)
Alexis Hunt1da39282011-06-24 02:11:39 +00002374 AddMethodCandidate(M, DeclAccessPair::make(M, AS_public), RD, ThisTy,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002375 Classification, llvm::makeArrayRef(&Arg, NumArgs),
2376 OCS, true);
Alexis Hunt080709f2011-06-23 00:26:20 +00002377 else
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002378 AddOverloadCandidate(M, DeclAccessPair::make(M, AS_public),
2379 llvm::makeArrayRef(&Arg, NumArgs), OCS, true);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002380
2381 // Here we're looking for a const parameter to speed up creation of
2382 // implicit copy methods.
2383 if ((SM == CXXCopyAssignment && M->isCopyAssignmentOperator()) ||
2384 (SM == CXXCopyConstructor &&
2385 cast<CXXConstructorDecl>(M)->isCopyConstructor())) {
2386 QualType ArgType = M->getType()->getAs<FunctionProtoType>()->getArgType(0);
Alexis Hunt491ec602011-06-21 23:42:56 +00002387 if (!ArgType->isReferenceType() ||
2388 ArgType->getPointeeType().isConstQualified())
Richard Smith852265f2012-03-30 20:53:28 +00002389 SuccessKind = SpecialMemberOverloadResult::SuccessConst;
Alexis Hunteef8ee02011-06-10 03:50:41 +00002390 }
Alexis Hunt2949f022011-06-22 02:58:46 +00002391 } else if (FunctionTemplateDecl *Tmpl =
Alexis Hunt1da39282011-06-24 02:11:39 +00002392 dyn_cast<FunctionTemplateDecl>(Cand)) {
Alexis Hunt080709f2011-06-23 00:26:20 +00002393 if (SM == CXXCopyAssignment || SM == CXXMoveAssignment)
2394 AddMethodTemplateCandidate(Tmpl, DeclAccessPair::make(Tmpl, AS_public),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002395 RD, 0, ThisTy, Classification,
2396 llvm::makeArrayRef(&Arg, NumArgs),
Alexis Hunt080709f2011-06-23 00:26:20 +00002397 OCS, true);
2398 else
2399 AddTemplateOverloadCandidate(Tmpl, DeclAccessPair::make(Tmpl, AS_public),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002400 0, llvm::makeArrayRef(&Arg, NumArgs),
2401 OCS, true);
Alexis Hunt1da39282011-06-24 02:11:39 +00002402 } else {
2403 assert(isa<UsingDecl>(Cand) && "illegal Kind of operator = Decl");
Alexis Hunteef8ee02011-06-10 03:50:41 +00002404 }
2405 }
2406
2407 OverloadCandidateSet::iterator Best;
2408 switch (OCS.BestViableFunction(*this, SourceLocation(), Best)) {
2409 case OR_Success:
2410 Result->setMethod(cast<CXXMethodDecl>(Best->Function));
Richard Smith852265f2012-03-30 20:53:28 +00002411 Result->setKind(SuccessKind);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002412 break;
2413
2414 case OR_Deleted:
2415 Result->setMethod(cast<CXXMethodDecl>(Best->Function));
Richard Smith852265f2012-03-30 20:53:28 +00002416 Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002417 break;
2418
2419 case OR_Ambiguous:
Richard Smith852265f2012-03-30 20:53:28 +00002420 Result->setMethod(0);
2421 Result->setKind(SpecialMemberOverloadResult::Ambiguous);
2422 break;
2423
Alexis Hunteef8ee02011-06-10 03:50:41 +00002424 case OR_No_Viable_Function:
2425 Result->setMethod(0);
Richard Smith852265f2012-03-30 20:53:28 +00002426 Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002427 break;
2428 }
2429
2430 return Result;
2431}
2432
2433/// \brief Look up the default constructor for the given class.
2434CXXConstructorDecl *Sema::LookupDefaultConstructor(CXXRecordDecl *Class) {
Alexis Hunt899bd442011-06-10 04:44:37 +00002435 SpecialMemberOverloadResult *Result =
Alexis Hunteef8ee02011-06-10 03:50:41 +00002436 LookupSpecialMember(Class, CXXDefaultConstructor, false, false, false,
2437 false, false);
2438
2439 return cast_or_null<CXXConstructorDecl>(Result->getMethod());
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002440}
2441
Alexis Hunt491ec602011-06-21 23:42:56 +00002442/// \brief Look up the copying constructor for the given class.
2443CXXConstructorDecl *Sema::LookupCopyingConstructor(CXXRecordDecl *Class,
2444 unsigned Quals,
2445 bool *ConstParamMatch) {
Alexis Hunt899bd442011-06-10 04:44:37 +00002446 assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2447 "non-const, non-volatile qualifiers for copy ctor arg");
2448 SpecialMemberOverloadResult *Result =
2449 LookupSpecialMember(Class, CXXCopyConstructor, Quals & Qualifiers::Const,
2450 Quals & Qualifiers::Volatile, false, false, false);
2451
2452 if (ConstParamMatch)
2453 *ConstParamMatch = Result->hasConstParamMatch();
2454
2455 return cast_or_null<CXXConstructorDecl>(Result->getMethod());
2456}
2457
Sebastian Redl22653ba2011-08-30 19:58:05 +00002458/// \brief Look up the moving constructor for the given class.
2459CXXConstructorDecl *Sema::LookupMovingConstructor(CXXRecordDecl *Class) {
2460 SpecialMemberOverloadResult *Result =
2461 LookupSpecialMember(Class, CXXMoveConstructor, false,
2462 false, false, false, false);
2463
2464 return cast_or_null<CXXConstructorDecl>(Result->getMethod());
2465}
2466
Douglas Gregor52b72822010-07-02 23:12:18 +00002467/// \brief Look up the constructors for the given class.
2468DeclContext::lookup_result Sema::LookupConstructors(CXXRecordDecl *Class) {
Alexis Hunteef8ee02011-06-10 03:50:41 +00002469 // If the implicit constructors have not yet been declared, do so now.
Douglas Gregor9672f922010-07-03 00:47:00 +00002470 if (CanDeclareSpecialMemberFunction(Context, Class)) {
Alexis Huntea6f0322011-05-11 22:34:38 +00002471 if (Class->needsImplicitDefaultConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +00002472 DeclareImplicitDefaultConstructor(Class);
2473 if (!Class->hasDeclaredCopyConstructor())
2474 DeclareImplicitCopyConstructor(Class);
David Blaikiebbafb8a2012-03-11 07:00:24 +00002475 if (getLangOpts().CPlusPlus0x && Class->needsImplicitMoveConstructor())
Sebastian Redl22653ba2011-08-30 19:58:05 +00002476 DeclareImplicitMoveConstructor(Class);
Douglas Gregor9672f922010-07-03 00:47:00 +00002477 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002478
Douglas Gregor52b72822010-07-02 23:12:18 +00002479 CanQualType T = Context.getCanonicalType(Context.getTypeDeclType(Class));
2480 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(T);
2481 return Class->lookup(Name);
2482}
2483
Alexis Hunt491ec602011-06-21 23:42:56 +00002484/// \brief Look up the copying assignment operator for the given class.
2485CXXMethodDecl *Sema::LookupCopyingAssignment(CXXRecordDecl *Class,
2486 unsigned Quals, bool RValueThis,
2487 unsigned ThisQuals,
2488 bool *ConstParamMatch) {
2489 assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2490 "non-const, non-volatile qualifiers for copy assignment arg");
2491 assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2492 "non-const, non-volatile qualifiers for copy assignment this");
2493 SpecialMemberOverloadResult *Result =
2494 LookupSpecialMember(Class, CXXCopyAssignment, Quals & Qualifiers::Const,
2495 Quals & Qualifiers::Volatile, RValueThis,
2496 ThisQuals & Qualifiers::Const,
2497 ThisQuals & Qualifiers::Volatile);
2498
2499 if (ConstParamMatch)
2500 *ConstParamMatch = Result->hasConstParamMatch();
2501
2502 return Result->getMethod();
2503}
2504
Sebastian Redl22653ba2011-08-30 19:58:05 +00002505/// \brief Look up the moving assignment operator for the given class.
2506CXXMethodDecl *Sema::LookupMovingAssignment(CXXRecordDecl *Class,
2507 bool RValueThis,
2508 unsigned ThisQuals) {
2509 assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2510 "non-const, non-volatile qualifiers for copy assignment this");
2511 SpecialMemberOverloadResult *Result =
2512 LookupSpecialMember(Class, CXXMoveAssignment, false, false, RValueThis,
2513 ThisQuals & Qualifiers::Const,
2514 ThisQuals & Qualifiers::Volatile);
2515
2516 return Result->getMethod();
2517}
2518
Douglas Gregore71edda2010-07-01 22:47:18 +00002519/// \brief Look for the destructor of the given class.
2520///
Alexis Hunt967ea7c2011-06-03 21:10:40 +00002521/// During semantic analysis, this routine should be used in lieu of
2522/// CXXRecordDecl::getDestructor().
Douglas Gregore71edda2010-07-01 22:47:18 +00002523///
2524/// \returns The destructor for this class.
2525CXXDestructorDecl *Sema::LookupDestructor(CXXRecordDecl *Class) {
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002526 return cast<CXXDestructorDecl>(LookupSpecialMember(Class, CXXDestructor,
2527 false, false, false,
2528 false, false)->getMethod());
Douglas Gregore71edda2010-07-01 22:47:18 +00002529}
2530
Richard Smithbcc22fc2012-03-09 08:00:36 +00002531/// LookupLiteralOperator - Determine which literal operator should be used for
2532/// a user-defined literal, per C++11 [lex.ext].
2533///
2534/// Normal overload resolution is not used to select which literal operator to
2535/// call for a user-defined literal. Look up the provided literal operator name,
2536/// and filter the results to the appropriate set for the given argument types.
2537Sema::LiteralOperatorLookupResult
2538Sema::LookupLiteralOperator(Scope *S, LookupResult &R,
2539 ArrayRef<QualType> ArgTys,
2540 bool AllowRawAndTemplate) {
2541 LookupName(R, S);
2542 assert(R.getResultKind() != LookupResult::Ambiguous &&
2543 "literal operator lookup can't be ambiguous");
2544
2545 // Filter the lookup results appropriately.
2546 LookupResult::Filter F = R.makeFilter();
2547
2548 bool FoundTemplate = false;
2549 bool FoundRaw = false;
2550 bool FoundExactMatch = false;
2551
2552 while (F.hasNext()) {
2553 Decl *D = F.next();
2554 if (UsingShadowDecl *USD = dyn_cast<UsingShadowDecl>(D))
2555 D = USD->getTargetDecl();
2556
2557 bool IsTemplate = isa<FunctionTemplateDecl>(D);
2558 bool IsRaw = false;
2559 bool IsExactMatch = false;
2560
2561 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2562 if (FD->getNumParams() == 1 &&
2563 FD->getParamDecl(0)->getType()->getAs<PointerType>())
2564 IsRaw = true;
2565 else {
2566 IsExactMatch = true;
2567 for (unsigned ArgIdx = 0; ArgIdx != ArgTys.size(); ++ArgIdx) {
2568 QualType ParamTy = FD->getParamDecl(ArgIdx)->getType();
2569 if (!Context.hasSameUnqualifiedType(ArgTys[ArgIdx], ParamTy)) {
2570 IsExactMatch = false;
2571 break;
2572 }
2573 }
2574 }
2575 }
2576
2577 if (IsExactMatch) {
2578 FoundExactMatch = true;
2579 AllowRawAndTemplate = false;
2580 if (FoundRaw || FoundTemplate) {
2581 // Go through again and remove the raw and template decls we've
2582 // already found.
2583 F.restart();
2584 FoundRaw = FoundTemplate = false;
2585 }
2586 } else if (AllowRawAndTemplate && (IsTemplate || IsRaw)) {
2587 FoundTemplate |= IsTemplate;
2588 FoundRaw |= IsRaw;
2589 } else {
2590 F.erase();
2591 }
2592 }
2593
2594 F.done();
2595
2596 // C++11 [lex.ext]p3, p4: If S contains a literal operator with a matching
2597 // parameter type, that is used in preference to a raw literal operator
2598 // or literal operator template.
2599 if (FoundExactMatch)
2600 return LOLR_Cooked;
2601
2602 // C++11 [lex.ext]p3, p4: S shall contain a raw literal operator or a literal
2603 // operator template, but not both.
2604 if (FoundRaw && FoundTemplate) {
2605 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
2606 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2607 Decl *D = *I;
2608 if (UsingShadowDecl *USD = dyn_cast<UsingShadowDecl>(D))
2609 D = USD->getTargetDecl();
2610 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
2611 D = FunTmpl->getTemplatedDecl();
2612 NoteOverloadCandidate(cast<FunctionDecl>(D));
2613 }
2614 return LOLR_Error;
2615 }
2616
2617 if (FoundRaw)
2618 return LOLR_Raw;
2619
2620 if (FoundTemplate)
2621 return LOLR_Template;
2622
2623 // Didn't find anything we could use.
2624 Diag(R.getNameLoc(), diag::err_ovl_no_viable_literal_operator)
2625 << R.getLookupName() << (int)ArgTys.size() << ArgTys[0]
2626 << (ArgTys.size() == 2 ? ArgTys[1] : QualType()) << AllowRawAndTemplate;
2627 return LOLR_Error;
2628}
2629
John McCall8fe68082010-01-26 07:16:45 +00002630void ADLResult::insert(NamedDecl *New) {
2631 NamedDecl *&Old = Decls[cast<NamedDecl>(New->getCanonicalDecl())];
2632
2633 // If we haven't yet seen a decl for this key, or the last decl
2634 // was exactly this one, we're done.
2635 if (Old == 0 || Old == New) {
2636 Old = New;
2637 return;
2638 }
2639
2640 // Otherwise, decide which is a more recent redeclaration.
2641 FunctionDecl *OldFD, *NewFD;
2642 if (isa<FunctionTemplateDecl>(New)) {
2643 OldFD = cast<FunctionTemplateDecl>(Old)->getTemplatedDecl();
2644 NewFD = cast<FunctionTemplateDecl>(New)->getTemplatedDecl();
2645 } else {
2646 OldFD = cast<FunctionDecl>(Old);
2647 NewFD = cast<FunctionDecl>(New);
2648 }
2649
2650 FunctionDecl *Cursor = NewFD;
2651 while (true) {
Douglas Gregorec9fd132012-01-14 16:38:05 +00002652 Cursor = Cursor->getPreviousDecl();
John McCall8fe68082010-01-26 07:16:45 +00002653
2654 // If we got to the end without finding OldFD, OldFD is the newer
2655 // declaration; leave things as they are.
2656 if (!Cursor) return;
2657
2658 // If we do find OldFD, then NewFD is newer.
2659 if (Cursor == OldFD) break;
2660
2661 // Otherwise, keep looking.
2662 }
2663
2664 Old = New;
2665}
2666
Sebastian Redlc057f422009-10-23 19:23:15 +00002667void Sema::ArgumentDependentLookup(DeclarationName Name, bool Operator,
Richard Smithe06a2c12012-02-25 06:24:24 +00002668 SourceLocation Loc,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002669 llvm::ArrayRef<Expr *> Args,
Richard Smith02e85f32011-04-14 22:09:26 +00002670 ADLResult &Result,
2671 bool StdNamespaceIsAssociated) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002672 // Find all of the associated namespaces and classes based on the
2673 // arguments we have.
2674 AssociatedNamespaceSet AssociatedNamespaces;
2675 AssociatedClassSet AssociatedClasses;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002676 FindAssociatedClassesAndNamespaces(Args,
John McCallc7e8e792009-08-07 22:18:02 +00002677 AssociatedNamespaces,
2678 AssociatedClasses);
Richard Smith02e85f32011-04-14 22:09:26 +00002679 if (StdNamespaceIsAssociated && StdNamespace)
2680 AssociatedNamespaces.insert(getStdNamespace());
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002681
Sebastian Redlc057f422009-10-23 19:23:15 +00002682 QualType T1, T2;
2683 if (Operator) {
2684 T1 = Args[0]->getType();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002685 if (Args.size() >= 2)
Sebastian Redlc057f422009-10-23 19:23:15 +00002686 T2 = Args[1]->getType();
2687 }
2688
Richard Smithe06a2c12012-02-25 06:24:24 +00002689 // Try to complete all associated classes, in case they contain a
2690 // declaration of a friend function.
2691 for (AssociatedClassSet::iterator C = AssociatedClasses.begin(),
2692 CEnd = AssociatedClasses.end();
2693 C != CEnd; ++C)
2694 RequireCompleteType(Loc, Context.getRecordType(*C), 0);
2695
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002696 // C++ [basic.lookup.argdep]p3:
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002697 // Let X be the lookup set produced by unqualified lookup (3.4.1)
2698 // and let Y be the lookup set produced by argument dependent
2699 // lookup (defined as follows). If X contains [...] then Y is
2700 // empty. Otherwise Y is the set of declarations found in the
2701 // namespaces associated with the argument types as described
2702 // below. The set of declarations found by the lookup of the name
2703 // is the union of X and Y.
2704 //
2705 // Here, we compute Y and add its members to the overloaded
2706 // candidate set.
2707 for (AssociatedNamespaceSet::iterator NS = AssociatedNamespaces.begin(),
Mike Stump11289f42009-09-09 15:08:12 +00002708 NSEnd = AssociatedNamespaces.end();
2709 NS != NSEnd; ++NS) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002710 // When considering an associated namespace, the lookup is the
2711 // same as the lookup performed when the associated namespace is
2712 // used as a qualifier (3.4.3.2) except that:
2713 //
2714 // -- Any using-directives in the associated namespace are
2715 // ignored.
2716 //
John McCallc7e8e792009-08-07 22:18:02 +00002717 // -- Any namespace-scope friend functions declared in
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002718 // associated classes are visible within their respective
2719 // namespaces even if they are not visible during an ordinary
2720 // lookup (11.4).
2721 DeclContext::lookup_iterator I, E;
John McCalld1e9d832009-08-11 06:59:38 +00002722 for (llvm::tie(I, E) = (*NS)->lookup(Name); I != E; ++I) {
John McCall4c4c1df2010-01-26 03:27:55 +00002723 NamedDecl *D = *I;
John McCallaa74a0c2009-08-28 07:59:38 +00002724 // If the only declaration here is an ordinary friend, consider
2725 // it only if it was declared in an associated classes.
2726 if (D->getIdentifierNamespace() == Decl::IDNS_OrdinaryFriend) {
John McCalld1e9d832009-08-11 06:59:38 +00002727 DeclContext *LexDC = D->getLexicalDeclContext();
2728 if (!AssociatedClasses.count(cast<CXXRecordDecl>(LexDC)))
2729 continue;
2730 }
Mike Stump11289f42009-09-09 15:08:12 +00002731
John McCall91f61fc2010-01-26 06:04:06 +00002732 if (isa<UsingShadowDecl>(D))
2733 D = cast<UsingShadowDecl>(D)->getTargetDecl();
John McCall4c4c1df2010-01-26 03:27:55 +00002734
John McCall91f61fc2010-01-26 06:04:06 +00002735 if (isa<FunctionDecl>(D)) {
2736 if (Operator &&
2737 !IsAcceptableNonMemberOperatorCandidate(cast<FunctionDecl>(D),
2738 T1, T2, Context))
2739 continue;
John McCall8fe68082010-01-26 07:16:45 +00002740 } else if (!isa<FunctionTemplateDecl>(D))
2741 continue;
2742
2743 Result.insert(D);
Douglas Gregor6127ca42009-06-23 20:14:09 +00002744 }
2745 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002746}
Douglas Gregor2d435302009-12-30 17:04:44 +00002747
2748//----------------------------------------------------------------------------
2749// Search for all visible declarations.
2750//----------------------------------------------------------------------------
2751VisibleDeclConsumer::~VisibleDeclConsumer() { }
2752
2753namespace {
2754
2755class ShadowContextRAII;
2756
2757class VisibleDeclsRecord {
2758public:
2759 /// \brief An entry in the shadow map, which is optimized to store a
2760 /// single declaration (the common case) but can also store a list
2761 /// of declarations.
Chris Lattner83cfc7c2011-07-18 01:54:02 +00002762 typedef llvm::TinyPtrVector<NamedDecl*> ShadowMapEntry;
Douglas Gregor2d435302009-12-30 17:04:44 +00002763
2764private:
2765 /// \brief A mapping from declaration names to the declarations that have
2766 /// this name within a particular scope.
2767 typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
2768
2769 /// \brief A list of shadow maps, which is used to model name hiding.
2770 std::list<ShadowMap> ShadowMaps;
2771
2772 /// \brief The declaration contexts we have already visited.
2773 llvm::SmallPtrSet<DeclContext *, 8> VisitedContexts;
2774
2775 friend class ShadowContextRAII;
2776
2777public:
2778 /// \brief Determine whether we have already visited this context
2779 /// (and, if not, note that we are going to visit that context now).
2780 bool visitedContext(DeclContext *Ctx) {
2781 return !VisitedContexts.insert(Ctx);
2782 }
2783
Douglas Gregor39982192010-08-15 06:18:01 +00002784 bool alreadyVisitedContext(DeclContext *Ctx) {
2785 return VisitedContexts.count(Ctx);
2786 }
2787
Douglas Gregor2d435302009-12-30 17:04:44 +00002788 /// \brief Determine whether the given declaration is hidden in the
2789 /// current scope.
2790 ///
2791 /// \returns the declaration that hides the given declaration, or
2792 /// NULL if no such declaration exists.
2793 NamedDecl *checkHidden(NamedDecl *ND);
2794
2795 /// \brief Add a declaration to the current shadow map.
Chris Lattner83cfc7c2011-07-18 01:54:02 +00002796 void add(NamedDecl *ND) {
2797 ShadowMaps.back()[ND->getDeclName()].push_back(ND);
2798 }
Douglas Gregor2d435302009-12-30 17:04:44 +00002799};
2800
2801/// \brief RAII object that records when we've entered a shadow context.
2802class ShadowContextRAII {
2803 VisibleDeclsRecord &Visible;
2804
2805 typedef VisibleDeclsRecord::ShadowMap ShadowMap;
2806
2807public:
2808 ShadowContextRAII(VisibleDeclsRecord &Visible) : Visible(Visible) {
2809 Visible.ShadowMaps.push_back(ShadowMap());
2810 }
2811
2812 ~ShadowContextRAII() {
Douglas Gregor2d435302009-12-30 17:04:44 +00002813 Visible.ShadowMaps.pop_back();
2814 }
2815};
2816
2817} // end anonymous namespace
2818
Douglas Gregor2d435302009-12-30 17:04:44 +00002819NamedDecl *VisibleDeclsRecord::checkHidden(NamedDecl *ND) {
Douglas Gregor0235c422010-01-14 00:06:47 +00002820 // Look through using declarations.
2821 ND = ND->getUnderlyingDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002822
Douglas Gregor2d435302009-12-30 17:04:44 +00002823 unsigned IDNS = ND->getIdentifierNamespace();
2824 std::list<ShadowMap>::reverse_iterator SM = ShadowMaps.rbegin();
2825 for (std::list<ShadowMap>::reverse_iterator SMEnd = ShadowMaps.rend();
2826 SM != SMEnd; ++SM) {
2827 ShadowMap::iterator Pos = SM->find(ND->getDeclName());
2828 if (Pos == SM->end())
2829 continue;
2830
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002831 for (ShadowMapEntry::iterator I = Pos->second.begin(),
Douglas Gregor2d435302009-12-30 17:04:44 +00002832 IEnd = Pos->second.end();
2833 I != IEnd; ++I) {
2834 // A tag declaration does not hide a non-tag declaration.
John McCalle87beb22010-04-23 18:46:30 +00002835 if ((*I)->hasTagIdentifierNamespace() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002836 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
Douglas Gregor2d435302009-12-30 17:04:44 +00002837 Decl::IDNS_ObjCProtocol)))
2838 continue;
2839
2840 // Protocols are in distinct namespaces from everything else.
2841 if ((((*I)->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
2842 || (IDNS & Decl::IDNS_ObjCProtocol)) &&
2843 (*I)->getIdentifierNamespace() != IDNS)
2844 continue;
2845
Douglas Gregor09bbc652010-01-14 15:47:35 +00002846 // Functions and function templates in the same scope overload
2847 // rather than hide. FIXME: Look for hiding based on function
2848 // signatures!
Douglas Gregor200c99d2010-01-14 03:35:48 +00002849 if ((*I)->isFunctionOrFunctionTemplate() &&
Douglas Gregor09bbc652010-01-14 15:47:35 +00002850 ND->isFunctionOrFunctionTemplate() &&
2851 SM == ShadowMaps.rbegin())
Douglas Gregor200c99d2010-01-14 03:35:48 +00002852 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002853
Douglas Gregor2d435302009-12-30 17:04:44 +00002854 // We've found a declaration that hides this one.
2855 return *I;
2856 }
2857 }
2858
2859 return 0;
2860}
2861
2862static void LookupVisibleDecls(DeclContext *Ctx, LookupResult &Result,
2863 bool QualifiedNameLookup,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002864 bool InBaseClass,
Douglas Gregor2d435302009-12-30 17:04:44 +00002865 VisibleDeclConsumer &Consumer,
2866 VisibleDeclsRecord &Visited) {
Douglas Gregor0c8a1722010-02-04 23:42:48 +00002867 if (!Ctx)
2868 return;
2869
Douglas Gregor2d435302009-12-30 17:04:44 +00002870 // Make sure we don't visit the same context twice.
2871 if (Visited.visitedContext(Ctx->getPrimaryContext()))
2872 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002873
Douglas Gregor7454c562010-07-02 20:37:36 +00002874 if (CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(Ctx))
2875 Result.getSema().ForceDeclarationOfImplicitMembers(Class);
2876
Douglas Gregor2d435302009-12-30 17:04:44 +00002877 // Enumerate all of the results in this context.
Douglas Gregore57e7522012-01-07 09:11:48 +00002878 llvm::SmallVector<DeclContext *, 2> Contexts;
2879 Ctx->collectAllContexts(Contexts);
2880 for (unsigned I = 0, N = Contexts.size(); I != N; ++I) {
2881 DeclContext *CurCtx = Contexts[I];
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002882 for (DeclContext::decl_iterator D = CurCtx->decls_begin(),
Douglas Gregor2d435302009-12-30 17:04:44 +00002883 DEnd = CurCtx->decls_end();
2884 D != DEnd; ++D) {
Douglas Gregora3b23b02010-12-09 21:44:02 +00002885 if (NamedDecl *ND = dyn_cast<NamedDecl>(*D)) {
Douglas Gregor4a814562011-12-14 16:03:29 +00002886 if ((ND = Result.getAcceptableDecl(ND))) {
Erik Verbruggen2e657ff2011-10-06 07:27:49 +00002887 Consumer.FoundDecl(ND, Visited.checkHidden(ND), Ctx, InBaseClass);
Douglas Gregor2d435302009-12-30 17:04:44 +00002888 Visited.add(ND);
2889 }
Douglas Gregora3b23b02010-12-09 21:44:02 +00002890 }
Douglas Gregor04246572011-02-16 01:39:26 +00002891
Sebastian Redlbd595762010-08-31 20:53:31 +00002892 // Visit transparent contexts and inline namespaces inside this context.
Douglas Gregor2d435302009-12-30 17:04:44 +00002893 if (DeclContext *InnerCtx = dyn_cast<DeclContext>(*D)) {
Sebastian Redlbd595762010-08-31 20:53:31 +00002894 if (InnerCtx->isTransparentContext() || InnerCtx->isInlineNamespace())
Douglas Gregor09bbc652010-01-14 15:47:35 +00002895 LookupVisibleDecls(InnerCtx, Result, QualifiedNameLookup, InBaseClass,
Douglas Gregor2d435302009-12-30 17:04:44 +00002896 Consumer, Visited);
2897 }
2898 }
2899 }
2900
2901 // Traverse using directives for qualified name lookup.
2902 if (QualifiedNameLookup) {
2903 ShadowContextRAII Shadow(Visited);
2904 DeclContext::udir_iterator I, E;
2905 for (llvm::tie(I, E) = Ctx->getUsingDirectives(); I != E; ++I) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002906 LookupVisibleDecls((*I)->getNominatedNamespace(), Result,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002907 QualifiedNameLookup, InBaseClass, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00002908 }
2909 }
2910
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002911 // Traverse the contexts of inherited C++ classes.
Douglas Gregor2d435302009-12-30 17:04:44 +00002912 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) {
John McCall67da35c2010-02-04 22:26:26 +00002913 if (!Record->hasDefinition())
2914 return;
2915
Douglas Gregor2d435302009-12-30 17:04:44 +00002916 for (CXXRecordDecl::base_class_iterator B = Record->bases_begin(),
2917 BEnd = Record->bases_end();
2918 B != BEnd; ++B) {
2919 QualType BaseType = B->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002920
Douglas Gregor2d435302009-12-30 17:04:44 +00002921 // Don't look into dependent bases, because name lookup can't look
2922 // there anyway.
2923 if (BaseType->isDependentType())
2924 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002925
Douglas Gregor2d435302009-12-30 17:04:44 +00002926 const RecordType *Record = BaseType->getAs<RecordType>();
2927 if (!Record)
2928 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002929
Douglas Gregor2d435302009-12-30 17:04:44 +00002930 // FIXME: It would be nice to be able to determine whether referencing
2931 // a particular member would be ambiguous. For example, given
2932 //
2933 // struct A { int member; };
2934 // struct B { int member; };
2935 // struct C : A, B { };
2936 //
2937 // void f(C *c) { c->### }
2938 //
2939 // accessing 'member' would result in an ambiguity. However, we
2940 // could be smart enough to qualify the member with the base
2941 // class, e.g.,
2942 //
2943 // c->B::member
2944 //
2945 // or
2946 //
2947 // c->A::member
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002948
Douglas Gregor2d435302009-12-30 17:04:44 +00002949 // Find results in this base class (and its bases).
2950 ShadowContextRAII Shadow(Visited);
2951 LookupVisibleDecls(Record->getDecl(), Result, QualifiedNameLookup,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002952 true, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00002953 }
2954 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002955
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002956 // Traverse the contexts of Objective-C classes.
2957 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Ctx)) {
2958 // Traverse categories.
2959 for (ObjCCategoryDecl *Category = IFace->getCategoryList();
2960 Category; Category = Category->getNextClassCategory()) {
2961 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002962 LookupVisibleDecls(Category, Result, QualifiedNameLookup, false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002963 Consumer, Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002964 }
2965
2966 // Traverse protocols.
Ted Kremenek0ef508d2010-09-01 01:21:15 +00002967 for (ObjCInterfaceDecl::all_protocol_iterator
2968 I = IFace->all_referenced_protocol_begin(),
2969 E = IFace->all_referenced_protocol_end(); I != E; ++I) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002970 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002971 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002972 Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002973 }
2974
2975 // Traverse the superclass.
2976 if (IFace->getSuperClass()) {
2977 ShadowContextRAII Shadow(Visited);
2978 LookupVisibleDecls(IFace->getSuperClass(), Result, QualifiedNameLookup,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002979 true, Consumer, Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002980 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002981
Douglas Gregor0b59e802010-04-19 18:02:19 +00002982 // If there is an implementation, traverse it. We do this to find
2983 // synthesized ivars.
2984 if (IFace->getImplementation()) {
2985 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002986 LookupVisibleDecls(IFace->getImplementation(), Result,
Douglas Gregor0b59e802010-04-19 18:02:19 +00002987 QualifiedNameLookup, true, Consumer, Visited);
2988 }
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002989 } else if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Ctx)) {
2990 for (ObjCProtocolDecl::protocol_iterator I = Protocol->protocol_begin(),
2991 E = Protocol->protocol_end(); I != E; ++I) {
2992 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002993 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002994 Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002995 }
2996 } else if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Ctx)) {
2997 for (ObjCCategoryDecl::protocol_iterator I = Category->protocol_begin(),
2998 E = Category->protocol_end(); I != E; ++I) {
2999 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003000 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003001 Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003002 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003003
Douglas Gregor0b59e802010-04-19 18:02:19 +00003004 // If there is an implementation, traverse it.
3005 if (Category->getImplementation()) {
3006 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003007 LookupVisibleDecls(Category->getImplementation(), Result,
Douglas Gregor0b59e802010-04-19 18:02:19 +00003008 QualifiedNameLookup, true, Consumer, Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003009 }
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003010 }
Douglas Gregor2d435302009-12-30 17:04:44 +00003011}
3012
3013static void LookupVisibleDecls(Scope *S, LookupResult &Result,
3014 UnqualUsingDirectiveSet &UDirs,
3015 VisibleDeclConsumer &Consumer,
3016 VisibleDeclsRecord &Visited) {
3017 if (!S)
3018 return;
3019
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003020 if (!S->getEntity() ||
3021 (!S->getParent() &&
Douglas Gregor39982192010-08-15 06:18:01 +00003022 !Visited.alreadyVisitedContext((DeclContext *)S->getEntity())) ||
Douglas Gregor712dcfe2010-01-07 00:31:29 +00003023 ((DeclContext *)S->getEntity())->isFunctionOrMethod()) {
3024 // Walk through the declarations in this Scope.
3025 for (Scope::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
3026 D != DEnd; ++D) {
John McCall48871652010-08-21 09:40:31 +00003027 if (NamedDecl *ND = dyn_cast<NamedDecl>(*D))
Douglas Gregor4a814562011-12-14 16:03:29 +00003028 if ((ND = Result.getAcceptableDecl(ND))) {
Erik Verbruggen2e657ff2011-10-06 07:27:49 +00003029 Consumer.FoundDecl(ND, Visited.checkHidden(ND), 0, false);
Douglas Gregor712dcfe2010-01-07 00:31:29 +00003030 Visited.add(ND);
3031 }
3032 }
3033 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003034
Douglas Gregor66230062010-03-15 14:33:29 +00003035 // FIXME: C++ [temp.local]p8
Douglas Gregor2d435302009-12-30 17:04:44 +00003036 DeclContext *Entity = 0;
Douglas Gregor4f248632010-01-01 17:44:25 +00003037 if (S->getEntity()) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003038 // Look into this scope's declaration context, along with any of its
3039 // parent lookup contexts (e.g., enclosing classes), up to the point
3040 // where we hit the context stored in the next outer scope.
3041 Entity = (DeclContext *)S->getEntity();
Douglas Gregor66230062010-03-15 14:33:29 +00003042 DeclContext *OuterCtx = findOuterContext(S).first; // FIXME
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003043
Douglas Gregorea166062010-03-15 15:26:48 +00003044 for (DeclContext *Ctx = Entity; Ctx && !Ctx->Equals(OuterCtx);
Douglas Gregor2d435302009-12-30 17:04:44 +00003045 Ctx = Ctx->getLookupParent()) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003046 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
3047 if (Method->isInstanceMethod()) {
3048 // For instance methods, look for ivars in the method's interface.
3049 LookupResult IvarResult(Result.getSema(), Result.getLookupName(),
3050 Result.getNameLoc(), Sema::LookupMemberName);
Douglas Gregor05fcf842010-11-02 20:36:02 +00003051 if (ObjCInterfaceDecl *IFace = Method->getClassInterface()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003052 LookupVisibleDecls(IFace, IvarResult, /*QualifiedNameLookup=*/false,
Fariborz Jahanian97d744b2011-08-31 22:24:06 +00003053 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor05fcf842010-11-02 20:36:02 +00003054 }
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003055 }
3056
3057 // We've already performed all of the name lookup that we need
3058 // to for Objective-C methods; the next context will be the
3059 // outer scope.
3060 break;
3061 }
3062
Douglas Gregor2d435302009-12-30 17:04:44 +00003063 if (Ctx->isFunctionOrMethod())
3064 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003065
3066 LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003067 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00003068 }
3069 } else if (!S->getParent()) {
3070 // Look into the translation unit scope. We walk through the translation
3071 // unit's declaration context, because the Scope itself won't have all of
3072 // the declarations if we loaded a precompiled header.
3073 // FIXME: We would like the translation unit's Scope object to point to the
3074 // translation unit, so we don't need this special "if" branch. However,
3075 // doing so would force the normal C++ name-lookup code to look into the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003076 // translation unit decl when the IdentifierInfo chains would suffice.
Douglas Gregor2d435302009-12-30 17:04:44 +00003077 // Once we fix that problem (which is part of a more general "don't look
Douglas Gregor712dcfe2010-01-07 00:31:29 +00003078 // in DeclContexts unless we have to" optimization), we can eliminate this.
Douglas Gregor2d435302009-12-30 17:04:44 +00003079 Entity = Result.getSema().Context.getTranslationUnitDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003080 LookupVisibleDecls(Entity, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003081 /*InBaseClass=*/false, Consumer, Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003082 }
3083
Douglas Gregor2d435302009-12-30 17:04:44 +00003084 if (Entity) {
3085 // Lookup visible declarations in any namespaces found by using
3086 // directives.
3087 UnqualUsingDirectiveSet::const_iterator UI, UEnd;
3088 llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(Entity);
3089 for (; UI != UEnd; ++UI)
3090 LookupVisibleDecls(const_cast<DeclContext *>(UI->getNominatedNamespace()),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003091 Result, /*QualifiedNameLookup=*/false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003092 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00003093 }
3094
3095 // Lookup names in the parent scope.
3096 ShadowContextRAII Shadow(Visited);
3097 LookupVisibleDecls(S->getParent(), Result, UDirs, Consumer, Visited);
3098}
3099
3100void Sema::LookupVisibleDecls(Scope *S, LookupNameKind Kind,
Douglas Gregor39982192010-08-15 06:18:01 +00003101 VisibleDeclConsumer &Consumer,
3102 bool IncludeGlobalScope) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003103 // Determine the set of using directives available during
3104 // unqualified name lookup.
3105 Scope *Initial = S;
3106 UnqualUsingDirectiveSet UDirs;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003107 if (getLangOpts().CPlusPlus) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003108 // Find the first namespace or translation-unit scope.
3109 while (S && !isNamespaceOrTranslationUnitScope(S))
3110 S = S->getParent();
3111
3112 UDirs.visitScopeChain(Initial, S);
3113 }
3114 UDirs.done();
3115
3116 // Look for visible declarations.
3117 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
3118 VisibleDeclsRecord Visited;
Douglas Gregor39982192010-08-15 06:18:01 +00003119 if (!IncludeGlobalScope)
3120 Visited.visitedContext(Context.getTranslationUnitDecl());
Douglas Gregor2d435302009-12-30 17:04:44 +00003121 ShadowContextRAII Shadow(Visited);
3122 ::LookupVisibleDecls(Initial, Result, UDirs, Consumer, Visited);
3123}
3124
3125void Sema::LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
Douglas Gregor39982192010-08-15 06:18:01 +00003126 VisibleDeclConsumer &Consumer,
3127 bool IncludeGlobalScope) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003128 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
3129 VisibleDeclsRecord Visited;
Douglas Gregor39982192010-08-15 06:18:01 +00003130 if (!IncludeGlobalScope)
3131 Visited.visitedContext(Context.getTranslationUnitDecl());
Douglas Gregor2d435302009-12-30 17:04:44 +00003132 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003133 ::LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/true,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003134 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00003135}
3136
Chris Lattner43e7f312011-02-18 02:08:43 +00003137/// LookupOrCreateLabel - Do a name lookup of a label with the specified name.
Abramo Bagnara1c3af962011-03-05 18:21:20 +00003138/// If GnuLabelLoc is a valid source location, then this is a definition
3139/// of an __label__ label name, otherwise it is a normal label definition
3140/// or use.
Chris Lattner43e7f312011-02-18 02:08:43 +00003141LabelDecl *Sema::LookupOrCreateLabel(IdentifierInfo *II, SourceLocation Loc,
Abramo Bagnara1c3af962011-03-05 18:21:20 +00003142 SourceLocation GnuLabelLoc) {
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003143 // Do a lookup to see if we have a label with this name already.
Chris Lattner43e7f312011-02-18 02:08:43 +00003144 NamedDecl *Res = 0;
Abramo Bagnara1c3af962011-03-05 18:21:20 +00003145
3146 if (GnuLabelLoc.isValid()) {
3147 // Local label definitions always shadow existing labels.
3148 Res = LabelDecl::Create(Context, CurContext, Loc, II, GnuLabelLoc);
3149 Scope *S = CurScope;
3150 PushOnScopeChains(Res, S, true);
3151 return cast<LabelDecl>(Res);
3152 }
3153
3154 // Not a GNU local label.
3155 Res = LookupSingleName(CurScope, II, Loc, LookupLabel, NotForRedeclaration);
3156 // If we found a label, check to see if it is in the same context as us.
3157 // When in a Block, we don't want to reuse a label in an enclosing function.
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003158 if (Res && Res->getDeclContext() != CurContext)
3159 Res = 0;
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003160 if (Res == 0) {
3161 // If not forward referenced or defined already, create the backing decl.
Abramo Bagnara1c3af962011-03-05 18:21:20 +00003162 Res = LabelDecl::Create(Context, CurContext, Loc, II);
3163 Scope *S = CurScope->getFnParent();
Chris Lattner9ba479b2011-02-18 21:16:39 +00003164 assert(S && "Not in a function?");
3165 PushOnScopeChains(Res, S, true);
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003166 }
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003167 return cast<LabelDecl>(Res);
3168}
3169
3170//===----------------------------------------------------------------------===//
Douglas Gregor2d435302009-12-30 17:04:44 +00003171// Typo correction
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003172//===----------------------------------------------------------------------===//
Douglas Gregor2d435302009-12-30 17:04:44 +00003173
3174namespace {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003175
3176typedef llvm::StringMap<TypoCorrection, llvm::BumpPtrAllocator> TypoResultsMap;
Douglas Gregor29cdc6b2011-06-28 16:44:39 +00003177typedef std::map<unsigned, TypoResultsMap *> TypoEditDistanceMap;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003178
3179static const unsigned MaxTypoDistanceResultSets = 5;
3180
Douglas Gregor2d435302009-12-30 17:04:44 +00003181class TypoCorrectionConsumer : public VisibleDeclConsumer {
3182 /// \brief The name written that is a typo in the source.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003183 StringRef Typo;
Douglas Gregor2d435302009-12-30 17:04:44 +00003184
3185 /// \brief The results found that have the smallest edit distance
3186 /// found (so far) with the typo name.
Douglas Gregor0afa7f62010-10-14 20:34:08 +00003187 ///
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003188 /// The pointer value being set to the current DeclContext indicates
3189 /// whether there is a keyword with this name.
3190 TypoEditDistanceMap BestResults;
Douglas Gregor2d435302009-12-30 17:04:44 +00003191
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003192 Sema &SemaRef;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003193
Douglas Gregor2d435302009-12-30 17:04:44 +00003194public:
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003195 explicit TypoCorrectionConsumer(Sema &SemaRef, IdentifierInfo *Typo)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003196 : Typo(Typo->getName()),
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003197 SemaRef(SemaRef) { }
Douglas Gregor2d435302009-12-30 17:04:44 +00003198
Douglas Gregor29cdc6b2011-06-28 16:44:39 +00003199 ~TypoCorrectionConsumer() {
3200 for (TypoEditDistanceMap::iterator I = BestResults.begin(),
3201 IEnd = BestResults.end();
3202 I != IEnd;
3203 ++I)
3204 delete I->second;
3205 }
3206
Erik Verbruggen2e657ff2011-10-06 07:27:49 +00003207 virtual void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, DeclContext *Ctx,
3208 bool InBaseClass);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003209 void FoundName(StringRef Name);
3210 void addKeywordResult(StringRef Keyword);
3211 void addName(StringRef Name, NamedDecl *ND, unsigned Distance,
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00003212 NestedNameSpecifier *NNS=NULL, bool isKeyword=false);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003213 void addCorrection(TypoCorrection Correction);
Douglas Gregor2d435302009-12-30 17:04:44 +00003214
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003215 typedef TypoResultsMap::iterator result_iterator;
3216 typedef TypoEditDistanceMap::iterator distance_iterator;
3217 distance_iterator begin() { return BestResults.begin(); }
3218 distance_iterator end() { return BestResults.end(); }
3219 void erase(distance_iterator I) { BestResults.erase(I); }
Douglas Gregor0afa7f62010-10-14 20:34:08 +00003220 unsigned size() const { return BestResults.size(); }
3221 bool empty() const { return BestResults.empty(); }
Douglas Gregor2d435302009-12-30 17:04:44 +00003222
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003223 TypoCorrection &operator[](StringRef Name) {
Douglas Gregor29cdc6b2011-06-28 16:44:39 +00003224 return (*BestResults.begin()->second)[Name];
Douglas Gregoraf9eb592010-10-15 13:35:25 +00003225 }
3226
Kaelyn Uhrain0a16a8e2012-02-14 18:56:48 +00003227 unsigned getBestEditDistance(bool Normalized) {
3228 if (BestResults.empty())
3229 return (std::numeric_limits<unsigned>::max)();
3230
3231 unsigned BestED = BestResults.begin()->first;
3232 return Normalized ? TypoCorrection::NormalizeEditDistance(BestED) : BestED;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003233 }
Douglas Gregor2d435302009-12-30 17:04:44 +00003234};
3235
3236}
3237
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003238void TypoCorrectionConsumer::FoundDecl(NamedDecl *ND, NamedDecl *Hiding,
Erik Verbruggen2e657ff2011-10-06 07:27:49 +00003239 DeclContext *Ctx, bool InBaseClass) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003240 // Don't consider hidden names for typo correction.
3241 if (Hiding)
3242 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003243
Douglas Gregor2d435302009-12-30 17:04:44 +00003244 // Only consider entities with identifiers for names, ignoring
3245 // special names (constructors, overloaded operators, selectors,
3246 // etc.).
3247 IdentifierInfo *Name = ND->getIdentifier();
3248 if (!Name)
3249 return;
3250
Douglas Gregor57756ea2010-10-14 22:11:03 +00003251 FoundName(Name->getName());
3252}
3253
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003254void TypoCorrectionConsumer::FoundName(StringRef Name) {
Douglas Gregor93910a52010-10-19 19:39:10 +00003255 // Use a simple length-based heuristic to determine the minimum possible
3256 // edit distance. If the minimum isn't good enough, bail out early.
3257 unsigned MinED = abs((int)Name.size() - (int)Typo.size());
Kaelyn Uhrain1c75d402012-02-07 01:32:58 +00003258 if (MinED && Typo.size() / MinED < 3)
Douglas Gregor93910a52010-10-19 19:39:10 +00003259 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003260
Douglas Gregorc1fb15e2010-10-19 22:14:33 +00003261 // Compute an upper bound on the allowable edit distance, so that the
3262 // edit-distance algorithm can short-circuit.
Kaelyn Uhrain1c75d402012-02-07 01:32:58 +00003263 unsigned UpperBound = (Typo.size() + 2) / 3;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003264
Douglas Gregor2d435302009-12-30 17:04:44 +00003265 // Compute the edit distance between the typo and the name of this
Kaelyn Uhrain1c75d402012-02-07 01:32:58 +00003266 // entity, and add the identifier to the list of results.
3267 addName(Name, NULL, Typo.edit_distance(Name, true, UpperBound));
Douglas Gregor2d435302009-12-30 17:04:44 +00003268}
3269
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003270void TypoCorrectionConsumer::addKeywordResult(StringRef Keyword) {
Kaelyn Uhrain1c75d402012-02-07 01:32:58 +00003271 // Compute the edit distance between the typo and this keyword,
3272 // and add the keyword to the list of results.
3273 addName(Keyword, NULL, Typo.edit_distance(Keyword), NULL, true);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003274}
3275
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003276void TypoCorrectionConsumer::addName(StringRef Name,
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003277 NamedDecl *ND,
3278 unsigned Distance,
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00003279 NestedNameSpecifier *NNS,
3280 bool isKeyword) {
3281 TypoCorrection TC(&SemaRef.Context.Idents.get(Name), ND, NNS, Distance);
3282 if (isKeyword) TC.makeKeyword();
3283 addCorrection(TC);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003284}
3285
3286void TypoCorrectionConsumer::addCorrection(TypoCorrection Correction) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003287 StringRef Name = Correction.getCorrectionAsIdentifierInfo()->getName();
Kaelyn Uhrain0a16a8e2012-02-14 18:56:48 +00003288 TypoResultsMap *& Map = BestResults[Correction.getEditDistance(false)];
Douglas Gregor29cdc6b2011-06-28 16:44:39 +00003289 if (!Map)
3290 Map = new TypoResultsMap;
Chandler Carruth7d85c9b2011-06-28 22:48:40 +00003291
3292 TypoCorrection &CurrentCorrection = (*Map)[Name];
3293 if (!CurrentCorrection ||
3294 // FIXME: The following should be rolled up into an operator< on
3295 // TypoCorrection with a more principled definition.
3296 CurrentCorrection.isKeyword() < Correction.isKeyword() ||
David Blaikiebbafb8a2012-03-11 07:00:24 +00003297 Correction.getAsString(SemaRef.getLangOpts()) <
3298 CurrentCorrection.getAsString(SemaRef.getLangOpts()))
Chandler Carruth7d85c9b2011-06-28 22:48:40 +00003299 CurrentCorrection = Correction;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003300
3301 while (BestResults.size() > MaxTypoDistanceResultSets) {
Douglas Gregor29cdc6b2011-06-28 16:44:39 +00003302 TypoEditDistanceMap::iterator Last = BestResults.end();
3303 --Last;
3304 delete Last->second;
3305 BestResults.erase(Last);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003306 }
3307}
3308
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003309// Fill the supplied vector with the IdentifierInfo pointers for each piece of
3310// the given NestedNameSpecifier (i.e. given a NestedNameSpecifier "foo::bar::",
3311// fill the vector with the IdentifierInfo pointers for "foo" and "bar").
3312static void getNestedNameSpecifierIdentifiers(
3313 NestedNameSpecifier *NNS,
3314 SmallVectorImpl<const IdentifierInfo*> &Identifiers) {
3315 if (NestedNameSpecifier *Prefix = NNS->getPrefix())
3316 getNestedNameSpecifierIdentifiers(Prefix, Identifiers);
3317 else
3318 Identifiers.clear();
3319
3320 const IdentifierInfo *II = NULL;
3321
3322 switch (NNS->getKind()) {
3323 case NestedNameSpecifier::Identifier:
3324 II = NNS->getAsIdentifier();
3325 break;
3326
3327 case NestedNameSpecifier::Namespace:
3328 if (NNS->getAsNamespace()->isAnonymousNamespace())
3329 return;
3330 II = NNS->getAsNamespace()->getIdentifier();
3331 break;
3332
3333 case NestedNameSpecifier::NamespaceAlias:
3334 II = NNS->getAsNamespaceAlias()->getIdentifier();
3335 break;
3336
3337 case NestedNameSpecifier::TypeSpecWithTemplate:
3338 case NestedNameSpecifier::TypeSpec:
3339 II = QualType(NNS->getAsType(), 0).getBaseTypeIdentifier();
3340 break;
3341
3342 case NestedNameSpecifier::Global:
3343 return;
3344 }
3345
3346 if (II)
3347 Identifiers.push_back(II);
3348}
3349
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003350namespace {
3351
3352class SpecifierInfo {
3353 public:
3354 DeclContext* DeclCtx;
3355 NestedNameSpecifier* NameSpecifier;
3356 unsigned EditDistance;
3357
3358 SpecifierInfo(DeclContext *Ctx, NestedNameSpecifier *NNS, unsigned ED)
3359 : DeclCtx(Ctx), NameSpecifier(NNS), EditDistance(ED) {}
3360};
3361
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003362typedef SmallVector<DeclContext*, 4> DeclContextList;
3363typedef SmallVector<SpecifierInfo, 16> SpecifierInfoList;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003364
3365class NamespaceSpecifierSet {
3366 ASTContext &Context;
3367 DeclContextList CurContextChain;
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003368 SmallVector<const IdentifierInfo*, 4> CurContextIdentifiers;
3369 SmallVector<const IdentifierInfo*, 4> CurNameSpecifierIdentifiers;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003370 bool isSorted;
3371
3372 SpecifierInfoList Specifiers;
3373 llvm::SmallSetVector<unsigned, 4> Distances;
3374 llvm::DenseMap<unsigned, SpecifierInfoList> DistanceMap;
3375
3376 /// \brief Helper for building the list of DeclContexts between the current
3377 /// context and the top of the translation unit
3378 static DeclContextList BuildContextChain(DeclContext *Start);
3379
3380 void SortNamespaces();
3381
3382 public:
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003383 NamespaceSpecifierSet(ASTContext &Context, DeclContext *CurContext,
3384 CXXScopeSpec *CurScopeSpec)
Benjamin Kramerde1d6232011-07-05 09:46:31 +00003385 : Context(Context), CurContextChain(BuildContextChain(CurContext)),
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003386 isSorted(true) {
3387 if (CurScopeSpec && CurScopeSpec->getScopeRep())
3388 getNestedNameSpecifierIdentifiers(CurScopeSpec->getScopeRep(),
3389 CurNameSpecifierIdentifiers);
3390 // Build the list of identifiers that would be used for an absolute
3391 // (from the global context) NestedNameSpecifier refering to the current
3392 // context.
3393 for (DeclContextList::reverse_iterator C = CurContextChain.rbegin(),
3394 CEnd = CurContextChain.rend();
3395 C != CEnd; ++C) {
3396 if (NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(*C))
3397 CurContextIdentifiers.push_back(ND->getIdentifier());
3398 }
3399 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003400
3401 /// \brief Add the namespace to the set, computing the corresponding
3402 /// NestedNameSpecifier and its distance in the process.
3403 void AddNamespace(NamespaceDecl *ND);
3404
3405 typedef SpecifierInfoList::iterator iterator;
3406 iterator begin() {
3407 if (!isSorted) SortNamespaces();
3408 return Specifiers.begin();
3409 }
3410 iterator end() { return Specifiers.end(); }
3411};
3412
3413}
3414
3415DeclContextList NamespaceSpecifierSet::BuildContextChain(DeclContext *Start) {
Chandler Carruthb198e5a2011-06-28 21:43:34 +00003416 assert(Start && "Bulding a context chain from a null context");
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003417 DeclContextList Chain;
3418 for (DeclContext *DC = Start->getPrimaryContext(); DC != NULL;
3419 DC = DC->getLookupParent()) {
3420 NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(DC);
3421 if (!DC->isInlineNamespace() && !DC->isTransparentContext() &&
3422 !(ND && ND->isAnonymousNamespace()))
3423 Chain.push_back(DC->getPrimaryContext());
3424 }
3425 return Chain;
3426}
3427
3428void NamespaceSpecifierSet::SortNamespaces() {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003429 SmallVector<unsigned, 4> sortedDistances;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003430 sortedDistances.append(Distances.begin(), Distances.end());
3431
3432 if (sortedDistances.size() > 1)
3433 std::sort(sortedDistances.begin(), sortedDistances.end());
3434
3435 Specifiers.clear();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003436 for (SmallVector<unsigned, 4>::iterator DI = sortedDistances.begin(),
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003437 DIEnd = sortedDistances.end();
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003438 DI != DIEnd; ++DI) {
3439 SpecifierInfoList &SpecList = DistanceMap[*DI];
3440 Specifiers.append(SpecList.begin(), SpecList.end());
3441 }
3442
3443 isSorted = true;
3444}
3445
3446void NamespaceSpecifierSet::AddNamespace(NamespaceDecl *ND) {
Chandler Carruthb198e5a2011-06-28 21:43:34 +00003447 DeclContext *Ctx = cast<DeclContext>(ND);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003448 NestedNameSpecifier *NNS = NULL;
3449 unsigned NumSpecifiers = 0;
3450 DeclContextList NamespaceDeclChain(BuildContextChain(Ctx));
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003451 DeclContextList FullNamespaceDeclChain(NamespaceDeclChain);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003452
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003453 // Eliminate common elements from the two DeclContext chains.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003454 for (DeclContextList::reverse_iterator C = CurContextChain.rbegin(),
3455 CEnd = CurContextChain.rend();
Chandler Carruthb198e5a2011-06-28 21:43:34 +00003456 C != CEnd && !NamespaceDeclChain.empty() &&
3457 NamespaceDeclChain.back() == *C; ++C) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003458 NamespaceDeclChain.pop_back();
3459 }
3460
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003461 // Add an explicit leading '::' specifier if needed.
3462 if (NamespaceDecl *ND =
Kaelyn Uhrain618f97c2012-02-15 22:59:03 +00003463 NamespaceDeclChain.empty() ? NULL :
3464 dyn_cast_or_null<NamespaceDecl>(NamespaceDeclChain.back())) {
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003465 IdentifierInfo *Name = ND->getIdentifier();
3466 if (std::find(CurContextIdentifiers.begin(), CurContextIdentifiers.end(),
3467 Name) != CurContextIdentifiers.end() ||
3468 std::find(CurNameSpecifierIdentifiers.begin(),
3469 CurNameSpecifierIdentifiers.end(),
3470 Name) != CurNameSpecifierIdentifiers.end()) {
3471 NamespaceDeclChain = FullNamespaceDeclChain;
3472 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
3473 }
3474 }
3475
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003476 // Build the NestedNameSpecifier from what is left of the NamespaceDeclChain
3477 for (DeclContextList::reverse_iterator C = NamespaceDeclChain.rbegin(),
3478 CEnd = NamespaceDeclChain.rend();
3479 C != CEnd; ++C) {
3480 NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(*C);
3481 if (ND) {
3482 NNS = NestedNameSpecifier::Create(Context, NNS, ND);
3483 ++NumSpecifiers;
3484 }
3485 }
3486
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003487 // If the built NestedNameSpecifier would be replacing an existing
3488 // NestedNameSpecifier, use the number of component identifiers that
3489 // would need to be changed as the edit distance instead of the number
3490 // of components in the built NestedNameSpecifier.
3491 if (NNS && !CurNameSpecifierIdentifiers.empty()) {
3492 SmallVector<const IdentifierInfo*, 4> NewNameSpecifierIdentifiers;
3493 getNestedNameSpecifierIdentifiers(NNS, NewNameSpecifierIdentifiers);
3494 NumSpecifiers = llvm::ComputeEditDistance(
3495 llvm::ArrayRef<const IdentifierInfo*>(CurNameSpecifierIdentifiers),
3496 llvm::ArrayRef<const IdentifierInfo*>(NewNameSpecifierIdentifiers));
3497 }
3498
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003499 isSorted = false;
3500 Distances.insert(NumSpecifiers);
3501 DistanceMap[NumSpecifiers].push_back(SpecifierInfo(Ctx, NNS, NumSpecifiers));
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003502}
3503
Douglas Gregord507d772010-10-20 03:06:34 +00003504/// \brief Perform name lookup for a possible result for typo correction.
3505static void LookupPotentialTypoResult(Sema &SemaRef,
3506 LookupResult &Res,
3507 IdentifierInfo *Name,
3508 Scope *S, CXXScopeSpec *SS,
3509 DeclContext *MemberContext,
3510 bool EnteringContext,
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003511 bool isObjCIvarLookup) {
Douglas Gregord507d772010-10-20 03:06:34 +00003512 Res.suppressDiagnostics();
3513 Res.clear();
3514 Res.setLookupName(Name);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003515 if (MemberContext) {
Douglas Gregord507d772010-10-20 03:06:34 +00003516 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(MemberContext)) {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003517 if (isObjCIvarLookup) {
Douglas Gregord507d772010-10-20 03:06:34 +00003518 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(Name)) {
3519 Res.addDecl(Ivar);
3520 Res.resolveKind();
3521 return;
3522 }
3523 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003524
Douglas Gregord507d772010-10-20 03:06:34 +00003525 if (ObjCPropertyDecl *Prop = Class->FindPropertyDeclaration(Name)) {
3526 Res.addDecl(Prop);
3527 Res.resolveKind();
3528 return;
3529 }
3530 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003531
Douglas Gregord507d772010-10-20 03:06:34 +00003532 SemaRef.LookupQualifiedName(Res, MemberContext);
3533 return;
3534 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003535
3536 SemaRef.LookupParsedName(Res, S, SS, /*AllowBuiltinCreation=*/false,
Douglas Gregord507d772010-10-20 03:06:34 +00003537 EnteringContext);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003538
Douglas Gregord507d772010-10-20 03:06:34 +00003539 // Fake ivar lookup; this should really be part of
3540 // LookupParsedName.
3541 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) {
3542 if (Method->isInstanceMethod() && Method->getClassInterface() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003543 (Res.empty() ||
Douglas Gregord507d772010-10-20 03:06:34 +00003544 (Res.isSingleResult() &&
3545 Res.getFoundDecl()->isDefinedOutsideFunctionOrMethod()))) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003546 if (ObjCIvarDecl *IV
Douglas Gregord507d772010-10-20 03:06:34 +00003547 = Method->getClassInterface()->lookupInstanceVariable(Name)) {
3548 Res.addDecl(IV);
3549 Res.resolveKind();
3550 }
3551 }
3552 }
3553}
3554
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003555/// \brief Add keywords to the consumer as possible typo corrections.
3556static void AddKeywordsToConsumer(Sema &SemaRef,
3557 TypoCorrectionConsumer &Consumer,
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003558 Scope *S, CorrectionCandidateCallback &CCC) {
3559 if (CCC.WantObjCSuper)
3560 Consumer.addKeywordResult("super");
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003561
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003562 if (CCC.WantTypeSpecifiers) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003563 // Add type-specifier keywords to the set of results.
3564 const char *CTypeSpecs[] = {
3565 "char", "const", "double", "enum", "float", "int", "long", "short",
Douglas Gregor3b22a882011-07-01 21:27:45 +00003566 "signed", "struct", "union", "unsigned", "void", "volatile",
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003567 "_Complex", "_Imaginary",
3568 // storage-specifiers as well
3569 "extern", "inline", "static", "typedef"
3570 };
3571
3572 const unsigned NumCTypeSpecs = sizeof(CTypeSpecs) / sizeof(CTypeSpecs[0]);
3573 for (unsigned I = 0; I != NumCTypeSpecs; ++I)
3574 Consumer.addKeywordResult(CTypeSpecs[I]);
3575
David Blaikiebbafb8a2012-03-11 07:00:24 +00003576 if (SemaRef.getLangOpts().C99)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003577 Consumer.addKeywordResult("restrict");
David Blaikiebbafb8a2012-03-11 07:00:24 +00003578 if (SemaRef.getLangOpts().Bool || SemaRef.getLangOpts().CPlusPlus)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003579 Consumer.addKeywordResult("bool");
David Blaikiebbafb8a2012-03-11 07:00:24 +00003580 else if (SemaRef.getLangOpts().C99)
Douglas Gregor3b22a882011-07-01 21:27:45 +00003581 Consumer.addKeywordResult("_Bool");
3582
David Blaikiebbafb8a2012-03-11 07:00:24 +00003583 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003584 Consumer.addKeywordResult("class");
3585 Consumer.addKeywordResult("typename");
3586 Consumer.addKeywordResult("wchar_t");
3587
David Blaikiebbafb8a2012-03-11 07:00:24 +00003588 if (SemaRef.getLangOpts().CPlusPlus0x) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003589 Consumer.addKeywordResult("char16_t");
3590 Consumer.addKeywordResult("char32_t");
3591 Consumer.addKeywordResult("constexpr");
3592 Consumer.addKeywordResult("decltype");
3593 Consumer.addKeywordResult("thread_local");
3594 }
3595 }
3596
David Blaikiebbafb8a2012-03-11 07:00:24 +00003597 if (SemaRef.getLangOpts().GNUMode)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003598 Consumer.addKeywordResult("typeof");
3599 }
3600
David Blaikiebbafb8a2012-03-11 07:00:24 +00003601 if (CCC.WantCXXNamedCasts && SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003602 Consumer.addKeywordResult("const_cast");
3603 Consumer.addKeywordResult("dynamic_cast");
3604 Consumer.addKeywordResult("reinterpret_cast");
3605 Consumer.addKeywordResult("static_cast");
3606 }
3607
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003608 if (CCC.WantExpressionKeywords) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003609 Consumer.addKeywordResult("sizeof");
David Blaikiebbafb8a2012-03-11 07:00:24 +00003610 if (SemaRef.getLangOpts().Bool || SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003611 Consumer.addKeywordResult("false");
3612 Consumer.addKeywordResult("true");
3613 }
3614
David Blaikiebbafb8a2012-03-11 07:00:24 +00003615 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003616 const char *CXXExprs[] = {
3617 "delete", "new", "operator", "throw", "typeid"
3618 };
3619 const unsigned NumCXXExprs = sizeof(CXXExprs) / sizeof(CXXExprs[0]);
3620 for (unsigned I = 0; I != NumCXXExprs; ++I)
3621 Consumer.addKeywordResult(CXXExprs[I]);
3622
3623 if (isa<CXXMethodDecl>(SemaRef.CurContext) &&
3624 cast<CXXMethodDecl>(SemaRef.CurContext)->isInstance())
3625 Consumer.addKeywordResult("this");
3626
David Blaikiebbafb8a2012-03-11 07:00:24 +00003627 if (SemaRef.getLangOpts().CPlusPlus0x) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003628 Consumer.addKeywordResult("alignof");
3629 Consumer.addKeywordResult("nullptr");
3630 }
3631 }
3632 }
3633
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003634 if (CCC.WantRemainingKeywords) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003635 if (SemaRef.getCurFunctionOrMethodDecl() || SemaRef.getCurBlock()) {
3636 // Statements.
3637 const char *CStmts[] = {
3638 "do", "else", "for", "goto", "if", "return", "switch", "while" };
3639 const unsigned NumCStmts = sizeof(CStmts) / sizeof(CStmts[0]);
3640 for (unsigned I = 0; I != NumCStmts; ++I)
3641 Consumer.addKeywordResult(CStmts[I]);
3642
David Blaikiebbafb8a2012-03-11 07:00:24 +00003643 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003644 Consumer.addKeywordResult("catch");
3645 Consumer.addKeywordResult("try");
3646 }
3647
3648 if (S && S->getBreakParent())
3649 Consumer.addKeywordResult("break");
3650
3651 if (S && S->getContinueParent())
3652 Consumer.addKeywordResult("continue");
3653
3654 if (!SemaRef.getCurFunction()->SwitchStack.empty()) {
3655 Consumer.addKeywordResult("case");
3656 Consumer.addKeywordResult("default");
3657 }
3658 } else {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003659 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003660 Consumer.addKeywordResult("namespace");
3661 Consumer.addKeywordResult("template");
3662 }
3663
3664 if (S && S->isClassScope()) {
3665 Consumer.addKeywordResult("explicit");
3666 Consumer.addKeywordResult("friend");
3667 Consumer.addKeywordResult("mutable");
3668 Consumer.addKeywordResult("private");
3669 Consumer.addKeywordResult("protected");
3670 Consumer.addKeywordResult("public");
3671 Consumer.addKeywordResult("virtual");
3672 }
3673 }
3674
David Blaikiebbafb8a2012-03-11 07:00:24 +00003675 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003676 Consumer.addKeywordResult("using");
3677
David Blaikiebbafb8a2012-03-11 07:00:24 +00003678 if (SemaRef.getLangOpts().CPlusPlus0x)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003679 Consumer.addKeywordResult("static_assert");
3680 }
3681 }
3682}
3683
Kaelyn Uhrain0a16a8e2012-02-14 18:56:48 +00003684static bool isCandidateViable(CorrectionCandidateCallback &CCC,
3685 TypoCorrection &Candidate) {
3686 Candidate.setCallbackDistance(CCC.RankCandidate(Candidate));
3687 return Candidate.getEditDistance(false) != TypoCorrection::InvalidDistance;
3688}
3689
Douglas Gregor2d435302009-12-30 17:04:44 +00003690/// \brief Try to "correct" a typo in the source code by finding
3691/// visible declarations whose names are similar to the name that was
3692/// present in the source code.
3693///
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003694/// \param TypoName the \c DeclarationNameInfo structure that contains
3695/// the name that was present in the source code along with its location.
3696///
3697/// \param LookupKind the name-lookup criteria used to search for the name.
Douglas Gregor2d435302009-12-30 17:04:44 +00003698///
3699/// \param S the scope in which name lookup occurs.
3700///
3701/// \param SS the nested-name-specifier that precedes the name we're
3702/// looking for, if present.
3703///
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003704/// \param CCC A CorrectionCandidateCallback object that provides further
3705/// validation of typo correction candidates. It also provides flags for
3706/// determining the set of keywords permitted.
3707///
Douglas Gregoraf2bd472009-12-31 07:42:17 +00003708/// \param MemberContext if non-NULL, the context in which to look for
3709/// a member access expression.
3710///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003711/// \param EnteringContext whether we're entering the context described by
Douglas Gregor598b08f2009-12-31 05:20:13 +00003712/// the nested-name-specifier SS.
3713///
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003714/// \param OPT when non-NULL, the search for visible declarations will
3715/// also walk the protocols in the qualified interfaces of \p OPT.
3716///
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003717/// \returns a \c TypoCorrection containing the corrected name if the typo
3718/// along with information such as the \c NamedDecl where the corrected name
3719/// was declared, and any additional \c NestedNameSpecifier needed to access
3720/// it (C++ only). The \c TypoCorrection is empty if there is no correction.
3721TypoCorrection Sema::CorrectTypo(const DeclarationNameInfo &TypoName,
3722 Sema::LookupNameKind LookupKind,
3723 Scope *S, CXXScopeSpec *SS,
Kaelyn Uhrain4e8942c2012-01-31 23:49:25 +00003724 CorrectionCandidateCallback &CCC,
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003725 DeclContext *MemberContext,
3726 bool EnteringContext,
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003727 const ObjCObjectPointerType *OPT) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003728 if (Diags.hasFatalErrorOccurred() || !getLangOpts().SpellChecking)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003729 return TypoCorrection();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003730
Francois Pichet9c391132011-12-03 15:55:29 +00003731 // In Microsoft mode, don't perform typo correction in a template member
3732 // function dependent context because it interferes with the "lookup into
3733 // dependent bases of class templates" feature.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003734 if (getLangOpts().MicrosoftMode && CurContext->isDependentContext() &&
Francois Pichet9c391132011-12-03 15:55:29 +00003735 isa<CXXMethodDecl>(CurContext))
3736 return TypoCorrection();
3737
Douglas Gregor2d435302009-12-30 17:04:44 +00003738 // We only attempt to correct typos for identifiers.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003739 IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo();
Douglas Gregor2d435302009-12-30 17:04:44 +00003740 if (!Typo)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003741 return TypoCorrection();
Douglas Gregor2d435302009-12-30 17:04:44 +00003742
3743 // If the scope specifier itself was invalid, don't try to correct
3744 // typos.
3745 if (SS && SS->isInvalid())
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003746 return TypoCorrection();
Douglas Gregor2d435302009-12-30 17:04:44 +00003747
3748 // Never try to correct typos during template deduction or
3749 // instantiation.
3750 if (!ActiveTemplateInstantiations.empty())
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003751 return TypoCorrection();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003752
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003753 NamespaceSpecifierSet Namespaces(Context, CurContext, SS);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003754
3755 TypoCorrectionConsumer Consumer(*this, Typo);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003756
Kaelyn Uhrain0a16a8e2012-02-14 18:56:48 +00003757 // If a callback object considers an empty typo correction candidate to be
3758 // viable, assume it does not do any actual validation of the candidates.
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00003759 TypoCorrection EmptyCorrection;
Kaelyn Uhrain0a16a8e2012-02-14 18:56:48 +00003760 bool ValidatingCallback = !isCandidateViable(CCC, EmptyCorrection);
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00003761
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003762 // Perform name lookup to find visible, similarly-named entities.
Douglas Gregor87074f12010-10-20 01:32:02 +00003763 bool IsUnqualifiedLookup = false;
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003764 DeclContext *QualifiedDC = MemberContext;
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003765 if (MemberContext) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003766 LookupVisibleDecls(MemberContext, LookupKind, Consumer);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003767
3768 // Look in qualified interfaces.
3769 if (OPT) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003770 for (ObjCObjectPointerType::qual_iterator
3771 I = OPT->qual_begin(), E = OPT->qual_end();
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003772 I != E; ++I)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003773 LookupVisibleDecls(*I, LookupKind, Consumer);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003774 }
3775 } else if (SS && SS->isSet()) {
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003776 QualifiedDC = computeDeclContext(*SS, EnteringContext);
3777 if (!QualifiedDC)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003778 return TypoCorrection();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003779
Douglas Gregor87074f12010-10-20 01:32:02 +00003780 // Provide a stop gap for files that are just seriously broken. Trying
3781 // to correct all typos can turn into a HUGE performance penalty, causing
3782 // some files to take minutes to get rejected by the parser.
3783 if (TyposCorrected + UnqualifiedTyposCorrected.size() >= 20)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003784 return TypoCorrection();
Douglas Gregor87074f12010-10-20 01:32:02 +00003785 ++TyposCorrected;
3786
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003787 LookupVisibleDecls(QualifiedDC, LookupKind, Consumer);
Douglas Gregor2d435302009-12-30 17:04:44 +00003788 } else {
Douglas Gregor87074f12010-10-20 01:32:02 +00003789 IsUnqualifiedLookup = true;
3790 UnqualifiedTyposCorrectedMap::iterator Cached
3791 = UnqualifiedTyposCorrected.find(Typo);
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00003792 if (Cached != UnqualifiedTyposCorrected.end()) {
3793 // Add the cached value, unless it's a keyword or fails validation. In the
3794 // keyword case, we'll end up adding the keyword below.
3795 if (Cached->second) {
3796 if (!Cached->second.isKeyword() &&
Kaelyn Uhrain0a16a8e2012-02-14 18:56:48 +00003797 isCandidateViable(CCC, Cached->second))
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00003798 Consumer.addCorrection(Cached->second);
3799 } else {
3800 // Only honor no-correction cache hits when a callback that will validate
3801 // correction candidates is not being used.
3802 if (!ValidatingCallback)
3803 return TypoCorrection();
3804 }
3805 }
3806 if (Cached == UnqualifiedTyposCorrected.end()) {
Douglas Gregor87074f12010-10-20 01:32:02 +00003807 // Provide a stop gap for files that are just seriously broken. Trying
3808 // to correct all typos can turn into a HUGE performance penalty, causing
3809 // some files to take minutes to get rejected by the parser.
3810 if (TyposCorrected + UnqualifiedTyposCorrected.size() >= 20)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003811 return TypoCorrection();
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00003812 }
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003813 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003814
Douglas Gregorb11f9452012-03-26 16:54:18 +00003815 // Determine whether we are going to search in the various namespaces for
3816 // corrections.
3817 bool SearchNamespaces
3818 = getLangOpts().CPlusPlus && CCC.AllowAddedQualifier &&
3819 (IsUnqualifiedLookup || (QualifiedDC && QualifiedDC->isNamespace()));
3820
3821 if (IsUnqualifiedLookup || SearchNamespaces) {
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00003822 // For unqualified lookup, look through all of the names that we have
3823 // seen in this translation unit.
Kaelyn Uhrain1c75d402012-02-07 01:32:58 +00003824 // FIXME: Re-add the ability to skip very unlikely potential corrections.
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00003825 for (IdentifierTable::iterator I = Context.Idents.begin(),
3826 IEnd = Context.Idents.end();
3827 I != IEnd; ++I)
3828 Consumer.FoundName(I->getKey());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003829
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00003830 // Walk through identifiers in external identifier sources.
Kaelyn Uhrain1c75d402012-02-07 01:32:58 +00003831 // FIXME: Re-add the ability to skip very unlikely potential corrections.
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00003832 if (IdentifierInfoLookup *External
3833 = Context.Idents.getExternalIdentifierLookup()) {
Dylan Noblesmithe2778992012-02-05 02:12:40 +00003834 OwningPtr<IdentifierIterator> Iter(External->getIdentifiers());
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00003835 do {
3836 StringRef Name = Iter->Next();
3837 if (Name.empty())
3838 break;
Douglas Gregor57756ea2010-10-14 22:11:03 +00003839
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00003840 Consumer.FoundName(Name);
3841 } while (true);
Douglas Gregor57756ea2010-10-14 22:11:03 +00003842 }
Douglas Gregor2d435302009-12-30 17:04:44 +00003843 }
3844
Kaelyn Uhrain4e8942c2012-01-31 23:49:25 +00003845 AddKeywordsToConsumer(*this, Consumer, S, CCC);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003846
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003847 // If we haven't found anything, we're done.
Douglas Gregor87074f12010-10-20 01:32:02 +00003848 if (Consumer.empty()) {
3849 // If this was an unqualified lookup, note that no correction was found.
3850 if (IsUnqualifiedLookup)
3851 (void)UnqualifiedTyposCorrected[Typo];
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003852
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003853 return TypoCorrection();
Douglas Gregor87074f12010-10-20 01:32:02 +00003854 }
Douglas Gregor2d435302009-12-30 17:04:44 +00003855
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003856 // Make sure that the user typed at least 3 characters for each correction
Douglas Gregor0afa7f62010-10-14 20:34:08 +00003857 // made. Otherwise, we don't even both looking at the results.
Kaelyn Uhrain0a16a8e2012-02-14 18:56:48 +00003858 unsigned ED = Consumer.getBestEditDistance(true);
Douglas Gregor87074f12010-10-20 01:32:02 +00003859 if (ED > 0 && Typo->getName().size() / ED < 3) {
3860 // If this was an unqualified lookup, note that no correction was found.
Douglas Gregoraf1daa92010-10-27 14:20:34 +00003861 if (IsUnqualifiedLookup)
Douglas Gregor87074f12010-10-20 01:32:02 +00003862 (void)UnqualifiedTyposCorrected[Typo];
3863
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003864 return TypoCorrection();
3865 }
3866
Douglas Gregorb11f9452012-03-26 16:54:18 +00003867 // Build the NestedNameSpecifiers for the KnownNamespaces, if we're going
3868 // to search those namespaces.
3869 if (SearchNamespaces) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003870 // Load any externally-known namespaces.
3871 if (ExternalSource && !LoadedExternalKnownNamespaces) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003872 SmallVector<NamespaceDecl *, 4> ExternalKnownNamespaces;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003873 LoadedExternalKnownNamespaces = true;
3874 ExternalSource->ReadKnownNamespaces(ExternalKnownNamespaces);
3875 for (unsigned I = 0, N = ExternalKnownNamespaces.size(); I != N; ++I)
3876 KnownNamespaces[ExternalKnownNamespaces[I]] = true;
3877 }
3878
3879 for (llvm::DenseMap<NamespaceDecl*, bool>::iterator
3880 KNI = KnownNamespaces.begin(),
3881 KNIEnd = KnownNamespaces.end();
3882 KNI != KNIEnd; ++KNI)
3883 Namespaces.AddNamespace(KNI->first);
Douglas Gregor87074f12010-10-20 01:32:02 +00003884 }
Douglas Gregor0afa7f62010-10-14 20:34:08 +00003885
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003886 // Weed out any names that could not be found by name lookup or, if a
3887 // CorrectionCandidateCallback object was provided, failed validation.
Kaelyn Uhrain0a16a8e2012-02-14 18:56:48 +00003888 llvm::SmallVector<TypoCorrection, 16> QualifiedResults;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003889 LookupResult TmpRes(*this, TypoName, LookupKind);
3890 TmpRes.suppressDiagnostics();
3891 while (!Consumer.empty()) {
3892 TypoCorrectionConsumer::distance_iterator DI = Consumer.begin();
3893 unsigned ED = DI->first;
Douglas Gregor29cdc6b2011-06-28 16:44:39 +00003894 for (TypoCorrectionConsumer::result_iterator I = DI->second->begin(),
3895 IEnd = DI->second->end();
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003896 I != IEnd; /* Increment in loop. */) {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003897 // If the item already has been looked up or is a keyword, keep it.
3898 // If a validator callback object was given, drop the correction
3899 // unless it passes validation.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003900 if (I->second.isResolved()) {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003901 TypoCorrectionConsumer::result_iterator Prev = I;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003902 ++I;
Kaelyn Uhrain0a16a8e2012-02-14 18:56:48 +00003903 if (!isCandidateViable(CCC, Prev->second))
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003904 DI->second->erase(Prev);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003905 continue;
Douglas Gregor0afa7f62010-10-14 20:34:08 +00003906 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003907
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003908 // Perform name lookup on this name.
3909 IdentifierInfo *Name = I->second.getCorrectionAsIdentifierInfo();
3910 LookupPotentialTypoResult(*this, TmpRes, Name, S, SS, MemberContext,
Kaelyn Uhrain4e8942c2012-01-31 23:49:25 +00003911 EnteringContext, CCC.IsObjCIvarLookup);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003912
3913 switch (TmpRes.getResultKind()) {
3914 case LookupResult::NotFound:
3915 case LookupResult::NotFoundInCurrentInstantiation:
Kaelyn Uhrain5a43b462011-09-07 20:25:59 +00003916 case LookupResult::FoundUnresolvedValue:
Kaelyn Uhrain0a16a8e2012-02-14 18:56:48 +00003917 QualifiedResults.push_back(I->second);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003918 // We didn't find this name in our scope, or didn't like what we found;
3919 // ignore it.
3920 {
3921 TypoCorrectionConsumer::result_iterator Next = I;
3922 ++Next;
Douglas Gregor29cdc6b2011-06-28 16:44:39 +00003923 DI->second->erase(I);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003924 I = Next;
3925 }
3926 break;
3927
3928 case LookupResult::Ambiguous:
3929 // We don't deal with ambiguities.
3930 return TypoCorrection();
3931
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00003932 case LookupResult::FoundOverloaded: {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003933 TypoCorrectionConsumer::result_iterator Prev = I;
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00003934 // Store all of the Decls for overloaded symbols
3935 for (LookupResult::iterator TRD = TmpRes.begin(),
3936 TRDEnd = TmpRes.end();
3937 TRD != TRDEnd; ++TRD)
3938 I->second.addCorrectionDecl(*TRD);
3939 ++I;
Kaelyn Uhrain0a16a8e2012-02-14 18:56:48 +00003940 if (!isCandidateViable(CCC, Prev->second))
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003941 DI->second->erase(Prev);
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00003942 break;
3943 }
3944
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003945 case LookupResult::Found: {
3946 TypoCorrectionConsumer::result_iterator Prev = I;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003947 I->second.setCorrectionDecl(TmpRes.getAsSingle<NamedDecl>());
3948 ++I;
Kaelyn Uhrain0a16a8e2012-02-14 18:56:48 +00003949 if (!isCandidateViable(CCC, Prev->second))
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003950 DI->second->erase(Prev);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003951 break;
3952 }
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003953
3954 }
Douglas Gregor0afa7f62010-10-14 20:34:08 +00003955 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003956
Douglas Gregor29cdc6b2011-06-28 16:44:39 +00003957 if (DI->second->empty())
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003958 Consumer.erase(DI);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003959 else if (!getLangOpts().CPlusPlus || QualifiedResults.empty() || !ED)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003960 // If there are results in the closest possible bucket, stop
3961 break;
3962
3963 // Only perform the qualified lookups for C++
Douglas Gregorb11f9452012-03-26 16:54:18 +00003964 if (SearchNamespaces) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003965 TmpRes.suppressDiagnostics();
Kaelyn Uhrain0a16a8e2012-02-14 18:56:48 +00003966 for (llvm::SmallVector<TypoCorrection,
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003967 16>::iterator QRI = QualifiedResults.begin(),
3968 QRIEnd = QualifiedResults.end();
3969 QRI != QRIEnd; ++QRI) {
3970 for (NamespaceSpecifierSet::iterator NI = Namespaces.begin(),
3971 NIEnd = Namespaces.end();
3972 NI != NIEnd; ++NI) {
3973 DeclContext *Ctx = NI->DeclCtx;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003974
Kaelyn Uhrain1c75d402012-02-07 01:32:58 +00003975 // FIXME: Stop searching once the namespaces are too far away to create
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003976 // acceptable corrections for this identifier (since the namespaces
Kaelyn Uhrain1c75d402012-02-07 01:32:58 +00003977 // are sorted in ascending order by edit distance).
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003978
3979 TmpRes.clear();
Kaelyn Uhrain0a16a8e2012-02-14 18:56:48 +00003980 TmpRes.setLookupName(QRI->getCorrectionAsIdentifierInfo());
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003981 if (!LookupQualifiedName(TmpRes, Ctx)) continue;
3982
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003983 // Any corrections added below will be validated in subsequent
3984 // iterations of the main while() loop over the Consumer's contents.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003985 switch (TmpRes.getResultKind()) {
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003986 case LookupResult::Found: {
3987 TypoCorrection TC(*QRI);
3988 TC.setCorrectionDecl(TmpRes.getAsSingle<NamedDecl>());
3989 TC.setCorrectionSpecifier(NI->NameSpecifier);
3990 TC.setQualifierDistance(NI->EditDistance);
3991 Consumer.addCorrection(TC);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003992 break;
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003993 }
3994 case LookupResult::FoundOverloaded: {
3995 TypoCorrection TC(*QRI);
3996 TC.setCorrectionSpecifier(NI->NameSpecifier);
3997 TC.setQualifierDistance(NI->EditDistance);
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00003998 for (LookupResult::iterator TRD = TmpRes.begin(),
3999 TRDEnd = TmpRes.end();
4000 TRD != TRDEnd; ++TRD)
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00004001 TC.addCorrectionDecl(*TRD);
4002 Consumer.addCorrection(TC);
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00004003 break;
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00004004 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004005 case LookupResult::NotFound:
4006 case LookupResult::NotFoundInCurrentInstantiation:
4007 case LookupResult::Ambiguous:
Kaelyn Uhrain5a43b462011-09-07 20:25:59 +00004008 case LookupResult::FoundUnresolvedValue:
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004009 break;
4010 }
4011 }
4012 }
4013 }
4014
4015 QualifiedResults.clear();
4016 }
4017
4018 // No corrections remain...
4019 if (Consumer.empty()) return TypoCorrection();
4020
Douglas Gregor29cdc6b2011-06-28 16:44:39 +00004021 TypoResultsMap &BestResults = *Consumer.begin()->second;
Kaelyn Uhrain0a16a8e2012-02-14 18:56:48 +00004022 ED = TypoCorrection::NormalizeEditDistance(Consumer.begin()->first);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004023
4024 if (ED > 0 && Typo->getName().size() / ED < 3) {
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00004025 // If this was an unqualified lookup and we believe the callback
4026 // object wouldn't have filtered out possible corrections, note
4027 // that no correction was found.
4028 if (IsUnqualifiedLookup && !ValidatingCallback)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004029 (void)UnqualifiedTyposCorrected[Typo];
4030
4031 return TypoCorrection();
4032 }
4033
Douglas Gregor0afa7f62010-10-14 20:34:08 +00004034 // If only a single name remains, return that result.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004035 if (BestResults.size() == 1) {
4036 const llvm::StringMapEntry<TypoCorrection> &Correction = *(BestResults.begin());
4037 const TypoCorrection &Result = Correction.second;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004038
Douglas Gregor2a1d72d2010-10-26 17:18:00 +00004039 // Don't correct to a keyword that's the same as the typo; the keyword
4040 // wasn't actually in scope.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004041 if (ED == 0 && Result.isKeyword()) return TypoCorrection();
4042
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004043 // Record the correction for unqualified lookup.
4044 if (IsUnqualifiedLookup)
4045 UnqualifiedTyposCorrected[Typo] = Result;
4046
4047 return Result;
4048 }
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00004049 else if (BestResults.size() > 1
4050 // Ugly hack equivalent to CTC == CTC_ObjCMessageReceiver;
4051 // WantObjCSuper is only true for CTC_ObjCMessageReceiver and for
4052 // some instances of CTC_Unknown, while WantRemainingKeywords is true
4053 // for CTC_Unknown but not for CTC_ObjCMessageReceiver.
Kaelyn Uhrain4e8942c2012-01-31 23:49:25 +00004054 && CCC.WantObjCSuper && !CCC.WantRemainingKeywords
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004055 && BestResults["super"].isKeyword()) {
4056 // Prefer 'super' when we're completing in a message-receiver
4057 // context.
4058
4059 // Don't correct to a keyword that's the same as the typo; the keyword
4060 // wasn't actually in scope.
4061 if (ED == 0) return TypoCorrection();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004062
Douglas Gregor87074f12010-10-20 01:32:02 +00004063 // Record the correction for unqualified lookup.
4064 if (IsUnqualifiedLookup)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004065 UnqualifiedTyposCorrected[Typo] = BestResults["super"];
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004066
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004067 return BestResults["super"];
Douglas Gregoraf9eb592010-10-15 13:35:25 +00004068 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004069
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00004070 // If this was an unqualified lookup and we believe the callback object did
4071 // not filter out possible corrections, note that no correction was found.
4072 if (IsUnqualifiedLookup && !ValidatingCallback)
Douglas Gregor87074f12010-10-20 01:32:02 +00004073 (void)UnqualifiedTyposCorrected[Typo];
4074
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004075 return TypoCorrection();
4076}
4077
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00004078void TypoCorrection::addCorrectionDecl(NamedDecl *CDecl) {
4079 if (!CDecl) return;
4080
4081 if (isKeyword())
4082 CorrectionDecls.clear();
4083
4084 CorrectionDecls.push_back(CDecl);
4085
4086 if (!CorrectionName)
4087 CorrectionName = CDecl->getDeclName();
4088}
4089
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004090std::string TypoCorrection::getAsString(const LangOptions &LO) const {
4091 if (CorrectionNameSpec) {
4092 std::string tmpBuffer;
4093 llvm::raw_string_ostream PrefixOStream(tmpBuffer);
4094 CorrectionNameSpec->print(PrefixOStream, PrintingPolicy(LO));
4095 return PrefixOStream.str() + CorrectionName.getAsString();
4096 }
4097
4098 return CorrectionName.getAsString();
Douglas Gregor2d435302009-12-30 17:04:44 +00004099}