blob: f1eb52241585911436241e21377e9e49790236e6 [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()) {
John McCallf6c8a4e2009-11-10 07:01:13 +0000109 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity())) {
110 DeclContext *EffectiveDC = (Ctx->isFileContext() ? Ctx : InnermostFileDC);
111 visit(Ctx, EffectiveDC);
112 } else {
113 Scope::udir_iterator I = S->using_directives_begin(),
114 End = S->using_directives_end();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000115
John McCallf6c8a4e2009-11-10 07:01:13 +0000116 for (; I != End; ++I)
John McCall48871652010-08-21 09:40:31 +0000117 visit(*I, InnermostFileDC);
John McCallf6c8a4e2009-11-10 07:01:13 +0000118 }
Douglas Gregor889ceb72009-02-03 19:21:40 +0000119 }
120 }
John McCallf6c8a4e2009-11-10 07:01:13 +0000121
122 // Visits a context and collect all of its using directives
123 // recursively. Treats all using directives as if they were
124 // declared in the context.
125 //
126 // A given context is only every visited once, so it is important
127 // that contexts be visited from the inside out in order to get
128 // the effective DCs right.
129 void visit(DeclContext *DC, DeclContext *EffectiveDC) {
130 if (!visited.insert(DC))
131 return;
132
133 addUsingDirectives(DC, EffectiveDC);
134 }
135
136 // Visits a using directive and collects all of its using
137 // directives recursively. Treats all using directives as if they
138 // were declared in the effective DC.
139 void visit(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
140 DeclContext *NS = UD->getNominatedNamespace();
141 if (!visited.insert(NS))
142 return;
143
144 addUsingDirective(UD, EffectiveDC);
145 addUsingDirectives(NS, EffectiveDC);
146 }
147
148 // Adds all the using directives in a context (and those nominated
149 // by its using directives, transitively) as if they appeared in
150 // the given effective context.
151 void addUsingDirectives(DeclContext *DC, DeclContext *EffectiveDC) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000152 SmallVector<DeclContext*,4> queue;
John McCallf6c8a4e2009-11-10 07:01:13 +0000153 while (true) {
154 DeclContext::udir_iterator I, End;
155 for (llvm::tie(I, End) = DC->getUsingDirectives(); I != End; ++I) {
156 UsingDirectiveDecl *UD = *I;
157 DeclContext *NS = UD->getNominatedNamespace();
158 if (visited.insert(NS)) {
159 addUsingDirective(UD, EffectiveDC);
160 queue.push_back(NS);
161 }
162 }
163
164 if (queue.empty())
165 return;
166
167 DC = queue.back();
168 queue.pop_back();
169 }
170 }
171
172 // Add a using directive as if it had been declared in the given
173 // context. This helps implement C++ [namespace.udir]p3:
174 // The using-directive is transitive: if a scope contains a
175 // using-directive that nominates a second namespace that itself
176 // contains using-directives, the effect is as if the
177 // using-directives from the second namespace also appeared in
178 // the first.
179 void addUsingDirective(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
180 // Find the common ancestor between the effective context and
181 // the nominated namespace.
182 DeclContext *Common = UD->getNominatedNamespace();
183 while (!Common->Encloses(EffectiveDC))
184 Common = Common->getParent();
John McCall9757d032009-11-10 09:20:04 +0000185 Common = Common->getPrimaryContext();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000186
John McCallf6c8a4e2009-11-10 07:01:13 +0000187 list.push_back(UnqualUsingEntry(UD->getNominatedNamespace(), Common));
188 }
189
190 void done() {
191 std::sort(list.begin(), list.end(), UnqualUsingEntry::Comparator());
192 }
193
John McCallf6c8a4e2009-11-10 07:01:13 +0000194 typedef ListTy::const_iterator const_iterator;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000195
John McCallf6c8a4e2009-11-10 07:01:13 +0000196 const_iterator begin() const { return list.begin(); }
197 const_iterator end() const { return list.end(); }
198
199 std::pair<const_iterator,const_iterator>
200 getNamespacesFor(DeclContext *DC) const {
John McCall9757d032009-11-10 09:20:04 +0000201 return std::equal_range(begin(), end(), DC->getPrimaryContext(),
John McCallf6c8a4e2009-11-10 07:01:13 +0000202 UnqualUsingEntry::Comparator());
203 }
204 };
Douglas Gregor889ceb72009-02-03 19:21:40 +0000205}
206
Douglas Gregor889ceb72009-02-03 19:21:40 +0000207// Retrieve the set of identifier namespaces that correspond to a
208// specific kind of name lookup.
John McCallea305ed2009-12-18 10:40:03 +0000209static inline unsigned getIDNS(Sema::LookupNameKind NameKind,
210 bool CPlusPlus,
211 bool Redeclaration) {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000212 unsigned IDNS = 0;
213 switch (NameKind) {
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +0000214 case Sema::LookupObjCImplicitSelfParam:
Douglas Gregor889ceb72009-02-03 19:21:40 +0000215 case Sema::LookupOrdinaryName:
Douglas Gregoreddf4332009-02-24 20:03:32 +0000216 case Sema::LookupRedeclarationWithLinkage:
Douglas Gregor889ceb72009-02-03 19:21:40 +0000217 IDNS = Decl::IDNS_Ordinary;
John McCallea305ed2009-12-18 10:40:03 +0000218 if (CPlusPlus) {
John McCalle87beb22010-04-23 18:46:30 +0000219 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Member | Decl::IDNS_Namespace;
Chris Lattnerebb5c6c2011-02-18 01:27:55 +0000220 if (Redeclaration)
221 IDNS |= Decl::IDNS_TagFriend | Decl::IDNS_OrdinaryFriend;
John McCallea305ed2009-12-18 10:40:03 +0000222 }
Douglas Gregor889ceb72009-02-03 19:21:40 +0000223 break;
224
John McCallb9467b62010-04-24 01:30:58 +0000225 case Sema::LookupOperatorName:
226 // Operator lookup is its own crazy thing; it is not the same
227 // as (e.g.) looking up an operator name for redeclaration.
228 assert(!Redeclaration && "cannot do redeclaration operator lookup");
229 IDNS = Decl::IDNS_NonMemberOperator;
230 break;
231
Douglas Gregor889ceb72009-02-03 19:21:40 +0000232 case Sema::LookupTagName:
John McCalle87beb22010-04-23 18:46:30 +0000233 if (CPlusPlus) {
234 IDNS = Decl::IDNS_Type;
235
236 // When looking for a redeclaration of a tag name, we add:
237 // 1) TagFriend to find undeclared friend decls
238 // 2) Namespace because they can't "overload" with tag decls.
239 // 3) Tag because it includes class templates, which can't
240 // "overload" with tag decls.
241 if (Redeclaration)
242 IDNS |= Decl::IDNS_Tag | Decl::IDNS_TagFriend | Decl::IDNS_Namespace;
243 } else {
244 IDNS = Decl::IDNS_Tag;
245 }
Douglas Gregor889ceb72009-02-03 19:21:40 +0000246 break;
Chris Lattnerebb5c6c2011-02-18 01:27:55 +0000247 case Sema::LookupLabel:
248 IDNS = Decl::IDNS_Label;
249 break;
250
Douglas Gregor889ceb72009-02-03 19:21:40 +0000251 case Sema::LookupMemberName:
252 IDNS = Decl::IDNS_Member;
253 if (CPlusPlus)
Mike Stump11289f42009-09-09 15:08:12 +0000254 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Ordinary;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000255 break;
256
257 case Sema::LookupNestedNameSpecifierName:
John McCalle87beb22010-04-23 18:46:30 +0000258 IDNS = Decl::IDNS_Type | Decl::IDNS_Namespace;
259 break;
260
Douglas Gregor889ceb72009-02-03 19:21:40 +0000261 case Sema::LookupNamespaceName:
John McCalle87beb22010-04-23 18:46:30 +0000262 IDNS = Decl::IDNS_Namespace;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000263 break;
Douglas Gregorde9f17e2009-04-23 23:18:26 +0000264
John McCall84d87672009-12-10 09:41:52 +0000265 case Sema::LookupUsingDeclName:
266 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag
267 | Decl::IDNS_Member | Decl::IDNS_Using;
268 break;
269
Douglas Gregor79947a22009-04-24 00:11:27 +0000270 case Sema::LookupObjCProtocolName:
271 IDNS = Decl::IDNS_ObjCProtocol;
272 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000273
Douglas Gregor39982192010-08-15 06:18:01 +0000274 case Sema::LookupAnyName:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000275 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Member
Douglas Gregor39982192010-08-15 06:18:01 +0000276 | Decl::IDNS_Using | Decl::IDNS_Namespace | Decl::IDNS_ObjCProtocol
277 | Decl::IDNS_Type;
278 break;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000279 }
280 return IDNS;
281}
282
John McCallea305ed2009-12-18 10:40:03 +0000283void LookupResult::configure() {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000284 IDNS = getIDNS(LookupKind, SemaRef.getLangOpts().CPlusPlus,
John McCallea305ed2009-12-18 10:40:03 +0000285 isForRedeclaration());
Douglas Gregorbcf0a472010-03-24 05:07:21 +0000286
287 // If we're looking for one of the allocation or deallocation
288 // operators, make sure that the implicitly-declared new and delete
289 // operators can be found.
290 if (!isForRedeclaration()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000291 switch (NameInfo.getName().getCXXOverloadedOperator()) {
Douglas Gregorbcf0a472010-03-24 05:07:21 +0000292 case OO_New:
293 case OO_Delete:
294 case OO_Array_New:
295 case OO_Array_Delete:
296 SemaRef.DeclareGlobalNewDelete();
297 break;
298
299 default:
300 break;
301 }
302 }
John McCallea305ed2009-12-18 10:40:03 +0000303}
304
Daniel Dunbar9e19f132012-03-08 01:43:06 +0000305void LookupResult::sanityImpl() const {
306 // Note that this function is never called by NDEBUG builds. See
307 // LookupResult::sanity().
John McCall19c1bfd2010-08-25 05:32:35 +0000308 assert(ResultKind != NotFound || Decls.size() == 0);
309 assert(ResultKind != Found || Decls.size() == 1);
310 assert(ResultKind != FoundOverloaded || Decls.size() > 1 ||
311 (Decls.size() == 1 &&
312 isa<FunctionTemplateDecl>((*begin())->getUnderlyingDecl())));
313 assert(ResultKind != FoundUnresolvedValue || sanityCheckUnresolved());
314 assert(ResultKind != Ambiguous || Decls.size() > 1 ||
Douglas Gregorc0d24902010-10-22 22:08:47 +0000315 (Decls.size() == 1 && (Ambiguity == AmbiguousBaseSubobjects ||
316 Ambiguity == AmbiguousBaseSubobjectTypes)));
John McCall19c1bfd2010-08-25 05:32:35 +0000317 assert((Paths != NULL) == (ResultKind == Ambiguous &&
318 (Ambiguity == AmbiguousBaseSubobjectTypes ||
319 Ambiguity == AmbiguousBaseSubobjects)));
320}
John McCall19c1bfd2010-08-25 05:32:35 +0000321
John McCall9f3059a2009-10-09 21:13:30 +0000322// Necessary because CXXBasePaths is not complete in Sema.h
John McCall5cebab12009-11-18 07:57:50 +0000323void LookupResult::deletePaths(CXXBasePaths *Paths) {
John McCall9f3059a2009-10-09 21:13:30 +0000324 delete Paths;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000325}
326
Douglas Gregor4a814562011-12-14 16:03:29 +0000327static NamedDecl *getVisibleDecl(NamedDecl *D);
328
329NamedDecl *LookupResult::getAcceptableDeclSlow(NamedDecl *D) const {
330 return getVisibleDecl(D);
331}
332
John McCall283b9012009-11-22 00:44:51 +0000333/// Resolves the result kind of this lookup.
John McCall5cebab12009-11-18 07:57:50 +0000334void LookupResult::resolveKind() {
John McCall9f3059a2009-10-09 21:13:30 +0000335 unsigned N = Decls.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000336
John McCall9f3059a2009-10-09 21:13:30 +0000337 // Fast case: no possible ambiguity.
John McCall1f82f242009-11-18 22:49:29 +0000338 if (N == 0) {
John McCall7fe6e9c2010-01-15 21:27:01 +0000339 assert(ResultKind == NotFound || ResultKind == NotFoundInCurrentInstantiation);
John McCall1f82f242009-11-18 22:49:29 +0000340 return;
341 }
342
John McCall283b9012009-11-22 00:44:51 +0000343 // If there's a single decl, we need to examine it to decide what
344 // kind of lookup this is.
John McCalle61f2ba2009-11-18 02:36:19 +0000345 if (N == 1) {
Douglas Gregor516d6722010-04-25 21:15:30 +0000346 NamedDecl *D = (*Decls.begin())->getUnderlyingDecl();
347 if (isa<FunctionTemplateDecl>(D))
John McCall283b9012009-11-22 00:44:51 +0000348 ResultKind = FoundOverloaded;
Douglas Gregor516d6722010-04-25 21:15:30 +0000349 else if (isa<UnresolvedUsingValueDecl>(D))
John McCalle61f2ba2009-11-18 02:36:19 +0000350 ResultKind = FoundUnresolvedValue;
351 return;
352 }
John McCall9f3059a2009-10-09 21:13:30 +0000353
John McCall6538c932009-10-10 05:48:19 +0000354 // Don't do any extra resolution if we've already resolved as ambiguous.
John McCall27b18f82009-11-17 02:14:36 +0000355 if (ResultKind == Ambiguous) return;
John McCall6538c932009-10-10 05:48:19 +0000356
John McCall9f3059a2009-10-09 21:13:30 +0000357 llvm::SmallPtrSet<NamedDecl*, 16> Unique;
Douglas Gregor13e65872010-08-11 14:45:53 +0000358 llvm::SmallPtrSet<QualType, 16> UniqueTypes;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000359
John McCall9f3059a2009-10-09 21:13:30 +0000360 bool Ambiguous = false;
361 bool HasTag = false, HasFunction = false, HasNonFunction = false;
John McCall283b9012009-11-22 00:44:51 +0000362 bool HasFunctionTemplate = false, HasUnresolved = false;
John McCall9f3059a2009-10-09 21:13:30 +0000363
364 unsigned UniqueTagIndex = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000365
John McCall9f3059a2009-10-09 21:13:30 +0000366 unsigned I = 0;
367 while (I < N) {
John McCallf0f1cf02009-11-17 07:50:12 +0000368 NamedDecl *D = Decls[I]->getUnderlyingDecl();
369 D = cast<NamedDecl>(D->getCanonicalDecl());
John McCall9f3059a2009-10-09 21:13:30 +0000370
Douglas Gregor13e65872010-08-11 14:45:53 +0000371 // Redeclarations of types via typedef can occur both within a scope
372 // and, through using declarations and directives, across scopes. There is
373 // no ambiguity if they all refer to the same type, so unique based on the
374 // canonical type.
375 if (TypeDecl *TD = dyn_cast<TypeDecl>(D)) {
376 if (!TD->getDeclContext()->isRecord()) {
377 QualType T = SemaRef.Context.getTypeDeclType(TD);
378 if (!UniqueTypes.insert(SemaRef.Context.getCanonicalType(T))) {
379 // The type is not unique; pull something off the back and continue
380 // at this index.
381 Decls[I] = Decls[--N];
382 continue;
383 }
384 }
385 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000386
John McCallf0f1cf02009-11-17 07:50:12 +0000387 if (!Unique.insert(D)) {
John McCall9f3059a2009-10-09 21:13:30 +0000388 // If it's not unique, pull something off the back (and
389 // continue at this index).
390 Decls[I] = Decls[--N];
Douglas Gregor13e65872010-08-11 14:45:53 +0000391 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000392 }
393
Douglas Gregor13e65872010-08-11 14:45:53 +0000394 // Otherwise, do some decl type analysis and then continue.
John McCalle61f2ba2009-11-18 02:36:19 +0000395
Douglas Gregor13e65872010-08-11 14:45:53 +0000396 if (isa<UnresolvedUsingValueDecl>(D)) {
397 HasUnresolved = true;
398 } else if (isa<TagDecl>(D)) {
399 if (HasTag)
400 Ambiguous = true;
401 UniqueTagIndex = I;
402 HasTag = true;
403 } else if (isa<FunctionTemplateDecl>(D)) {
404 HasFunction = true;
405 HasFunctionTemplate = true;
406 } else if (isa<FunctionDecl>(D)) {
407 HasFunction = true;
408 } else {
409 if (HasNonFunction)
410 Ambiguous = true;
411 HasNonFunction = true;
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000412 }
Douglas Gregor13e65872010-08-11 14:45:53 +0000413 I++;
Mike Stump11289f42009-09-09 15:08:12 +0000414 }
Douglas Gregor38feed82009-04-24 02:57:34 +0000415
John McCall9f3059a2009-10-09 21:13:30 +0000416 // C++ [basic.scope.hiding]p2:
417 // A class name or enumeration name can be hidden by the name of
418 // an object, function, or enumerator declared in the same
419 // scope. If a class or enumeration name and an object, function,
420 // or enumerator are declared in the same scope (in any order)
421 // with the same name, the class or enumeration name is hidden
422 // wherever the object, function, or enumerator name is visible.
423 // But it's still an error if there are distinct tag types found,
424 // even if they're not visible. (ref?)
John McCall80053822009-12-03 00:58:24 +0000425 if (HideTags && HasTag && !Ambiguous &&
Douglas Gregore63d0872010-10-23 16:06:17 +0000426 (HasFunction || HasNonFunction || HasUnresolved)) {
427 if (Decls[UniqueTagIndex]->getDeclContext()->getRedeclContext()->Equals(
428 Decls[UniqueTagIndex? 0 : N-1]->getDeclContext()->getRedeclContext()))
429 Decls[UniqueTagIndex] = Decls[--N];
430 else
431 Ambiguous = true;
432 }
Anders Carlsson8d0f6b72009-06-26 03:37:05 +0000433
John McCall9f3059a2009-10-09 21:13:30 +0000434 Decls.set_size(N);
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000435
John McCall80053822009-12-03 00:58:24 +0000436 if (HasNonFunction && (HasFunction || HasUnresolved))
John McCall9f3059a2009-10-09 21:13:30 +0000437 Ambiguous = true;
Douglas Gregorf23311d2009-01-17 01:13:24 +0000438
John McCall9f3059a2009-10-09 21:13:30 +0000439 if (Ambiguous)
John McCall6538c932009-10-10 05:48:19 +0000440 setAmbiguous(LookupResult::AmbiguousReference);
John McCalle61f2ba2009-11-18 02:36:19 +0000441 else if (HasUnresolved)
442 ResultKind = LookupResult::FoundUnresolvedValue;
John McCall283b9012009-11-22 00:44:51 +0000443 else if (N > 1 || HasFunctionTemplate)
John McCall27b18f82009-11-17 02:14:36 +0000444 ResultKind = LookupResult::FoundOverloaded;
John McCall9f3059a2009-10-09 21:13:30 +0000445 else
John McCall27b18f82009-11-17 02:14:36 +0000446 ResultKind = LookupResult::Found;
Douglas Gregor34074322009-01-14 22:20:51 +0000447}
448
John McCall5cebab12009-11-18 07:57:50 +0000449void LookupResult::addDeclsFromBasePaths(const CXXBasePaths &P) {
John McCall5b0829a2010-02-10 09:31:12 +0000450 CXXBasePaths::const_paths_iterator I, E;
John McCall9f3059a2009-10-09 21:13:30 +0000451 DeclContext::lookup_iterator DI, DE;
452 for (I = P.begin(), E = P.end(); I != E; ++I)
453 for (llvm::tie(DI,DE) = I->Decls; DI != DE; ++DI)
454 addDecl(*DI);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +0000455}
456
John McCall5cebab12009-11-18 07:57:50 +0000457void LookupResult::setAmbiguousBaseSubobjects(CXXBasePaths &P) {
John McCall9f3059a2009-10-09 21:13:30 +0000458 Paths = new CXXBasePaths;
459 Paths->swap(P);
460 addDeclsFromBasePaths(*Paths);
461 resolveKind();
John McCall6538c932009-10-10 05:48:19 +0000462 setAmbiguous(AmbiguousBaseSubobjects);
Douglas Gregor0e8fc3c2009-02-02 21:35:47 +0000463}
464
John McCall5cebab12009-11-18 07:57:50 +0000465void LookupResult::setAmbiguousBaseSubobjectTypes(CXXBasePaths &P) {
John McCall9f3059a2009-10-09 21:13:30 +0000466 Paths = new CXXBasePaths;
467 Paths->swap(P);
468 addDeclsFromBasePaths(*Paths);
469 resolveKind();
John McCall6538c932009-10-10 05:48:19 +0000470 setAmbiguous(AmbiguousBaseSubobjectTypes);
John McCall9f3059a2009-10-09 21:13:30 +0000471}
472
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000473void LookupResult::print(raw_ostream &Out) {
John McCall9f3059a2009-10-09 21:13:30 +0000474 Out << Decls.size() << " result(s)";
475 if (isAmbiguous()) Out << ", ambiguous";
476 if (Paths) Out << ", base paths present";
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000477
John McCall9f3059a2009-10-09 21:13:30 +0000478 for (iterator I = begin(), E = end(); I != E; ++I) {
479 Out << "\n";
480 (*I)->print(Out, 2);
481 }
482}
483
Douglas Gregord3a59182010-02-12 05:48:04 +0000484/// \brief Lookup a builtin function, when name lookup would otherwise
485/// fail.
486static bool LookupBuiltin(Sema &S, LookupResult &R) {
487 Sema::LookupNameKind NameKind = R.getLookupKind();
488
489 // If we didn't find a use of this identifier, and if the identifier
490 // corresponds to a compiler builtin, create the decl object for the builtin
491 // now, injecting it into translation unit scope, and return it.
492 if (NameKind == Sema::LookupOrdinaryName ||
493 NameKind == Sema::LookupRedeclarationWithLinkage) {
494 IdentifierInfo *II = R.getLookupName().getAsIdentifierInfo();
495 if (II) {
496 // If this is a builtin on this (or all) targets, create the decl.
497 if (unsigned BuiltinID = II->getBuiltinID()) {
498 // In C++, we don't have any predefined library functions like
499 // 'malloc'. Instead, we'll just error.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000500 if (S.getLangOpts().CPlusPlus &&
Douglas Gregord3a59182010-02-12 05:48:04 +0000501 S.Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
502 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000503
504 if (NamedDecl *D = S.LazilyCreateBuiltin((IdentifierInfo *)II,
505 BuiltinID, S.TUScope,
Douglas Gregorbfe022c2011-01-03 09:37:44 +0000506 R.isForRedeclaration(),
507 R.getNameLoc())) {
Douglas Gregord3a59182010-02-12 05:48:04 +0000508 R.addDecl(D);
Douglas Gregorbfe022c2011-01-03 09:37:44 +0000509 return true;
510 }
511
512 if (R.isForRedeclaration()) {
513 // If we're redeclaring this function anyway, forget that
514 // this was a builtin at all.
515 S.Context.BuiltinInfo.ForgetBuiltin(BuiltinID, S.Context.Idents);
516 }
517
518 return false;
Douglas Gregord3a59182010-02-12 05:48:04 +0000519 }
520 }
521 }
522
523 return false;
524}
525
Douglas Gregor7454c562010-07-02 20:37:36 +0000526/// \brief Determine whether we can declare a special member function within
527/// the class at this point.
528static bool CanDeclareSpecialMemberFunction(ASTContext &Context,
529 const CXXRecordDecl *Class) {
530 // We need to have a definition for the class.
531 if (!Class->getDefinition() || Class->isDependentContext())
532 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000533
Douglas Gregor7454c562010-07-02 20:37:36 +0000534 // We can't be in the middle of defining the class.
535 if (const RecordType *RecordTy
536 = Context.getTypeDeclType(Class)->getAs<RecordType>())
537 return !RecordTy->isBeingDefined();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000538
Douglas Gregor7454c562010-07-02 20:37:36 +0000539 return false;
540}
541
542void Sema::ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class) {
Douglas Gregora6d69502010-07-02 23:41:54 +0000543 if (!CanDeclareSpecialMemberFunction(Context, Class))
544 return;
Douglas Gregor9672f922010-07-03 00:47:00 +0000545
546 // If the default constructor has not yet been declared, do so now.
Alexis Huntea6f0322011-05-11 22:34:38 +0000547 if (Class->needsImplicitDefaultConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +0000548 DeclareImplicitDefaultConstructor(Class);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000549
Douglas Gregora6d69502010-07-02 23:41:54 +0000550 // If the copy constructor has not yet been declared, do so now.
551 if (!Class->hasDeclaredCopyConstructor())
552 DeclareImplicitCopyConstructor(Class);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000553
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000554 // If the copy assignment operator has not yet been declared, do so now.
Douglas Gregora6d69502010-07-02 23:41:54 +0000555 if (!Class->hasDeclaredCopyAssignment())
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000556 DeclareImplicitCopyAssignment(Class);
557
David Blaikiebbafb8a2012-03-11 07:00:24 +0000558 if (getLangOpts().CPlusPlus0x) {
Sebastian Redl22653ba2011-08-30 19:58:05 +0000559 // If the move constructor has not yet been declared, do so now.
560 if (Class->needsImplicitMoveConstructor())
561 DeclareImplicitMoveConstructor(Class); // might not actually do it
562
563 // If the move assignment operator has not yet been declared, do so now.
564 if (Class->needsImplicitMoveAssignment())
565 DeclareImplicitMoveAssignment(Class); // might not actually do it
566 }
567
Douglas Gregor7454c562010-07-02 20:37:36 +0000568 // If the destructor has not yet been declared, do so now.
Douglas Gregora6d69502010-07-02 23:41:54 +0000569 if (!Class->hasDeclaredDestructor())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000570 DeclareImplicitDestructor(Class);
Douglas Gregor7454c562010-07-02 20:37:36 +0000571}
572
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000573/// \brief Determine whether this is the name of an implicitly-declared
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000574/// special member function.
575static bool isImplicitlyDeclaredMemberFunctionName(DeclarationName Name) {
576 switch (Name.getNameKind()) {
Douglas Gregora6d69502010-07-02 23:41:54 +0000577 case DeclarationName::CXXConstructorName:
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000578 case DeclarationName::CXXDestructorName:
579 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000580
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000581 case DeclarationName::CXXOperatorName:
582 return Name.getCXXOverloadedOperator() == OO_Equal;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000583
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000584 default:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000585 break;
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000586 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000587
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000588 return false;
589}
590
591/// \brief If there are any implicit member functions with the given name
592/// that need to be declared in the given declaration context, do so.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000593static void DeclareImplicitMemberFunctionsWithName(Sema &S,
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000594 DeclarationName Name,
595 const DeclContext *DC) {
596 if (!DC)
597 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000598
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000599 switch (Name.getNameKind()) {
Douglas Gregora6d69502010-07-02 23:41:54 +0000600 case DeclarationName::CXXConstructorName:
601 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
Douglas Gregor9672f922010-07-03 00:47:00 +0000602 if (Record->getDefinition() &&
603 CanDeclareSpecialMemberFunction(S.Context, Record)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +0000604 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(Record);
Alexis Huntea6f0322011-05-11 22:34:38 +0000605 if (Record->needsImplicitDefaultConstructor())
Sebastian Redl22653ba2011-08-30 19:58:05 +0000606 S.DeclareImplicitDefaultConstructor(Class);
Douglas Gregor9672f922010-07-03 00:47:00 +0000607 if (!Record->hasDeclaredCopyConstructor())
Sebastian Redl22653ba2011-08-30 19:58:05 +0000608 S.DeclareImplicitCopyConstructor(Class);
David Blaikiebbafb8a2012-03-11 07:00:24 +0000609 if (S.getLangOpts().CPlusPlus0x &&
Sebastian Redl22653ba2011-08-30 19:58:05 +0000610 Record->needsImplicitMoveConstructor())
611 S.DeclareImplicitMoveConstructor(Class);
Douglas Gregor9672f922010-07-03 00:47:00 +0000612 }
Douglas Gregora6d69502010-07-02 23:41:54 +0000613 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000614
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000615 case DeclarationName::CXXDestructorName:
616 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
617 if (Record->getDefinition() && !Record->hasDeclaredDestructor() &&
618 CanDeclareSpecialMemberFunction(S.Context, Record))
619 S.DeclareImplicitDestructor(const_cast<CXXRecordDecl *>(Record));
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000620 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000621
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000622 case DeclarationName::CXXOperatorName:
623 if (Name.getCXXOverloadedOperator() != OO_Equal)
624 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000625
Sebastian Redl22653ba2011-08-30 19:58:05 +0000626 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC)) {
627 if (Record->getDefinition() &&
628 CanDeclareSpecialMemberFunction(S.Context, Record)) {
629 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(Record);
630 if (!Record->hasDeclaredCopyAssignment())
631 S.DeclareImplicitCopyAssignment(Class);
David Blaikiebbafb8a2012-03-11 07:00:24 +0000632 if (S.getLangOpts().CPlusPlus0x &&
Sebastian Redl22653ba2011-08-30 19:58:05 +0000633 Record->needsImplicitMoveAssignment())
634 S.DeclareImplicitMoveAssignment(Class);
635 }
636 }
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000637 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000638
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000639 default:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000640 break;
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000641 }
642}
Douglas Gregor7454c562010-07-02 20:37:36 +0000643
John McCall9f3059a2009-10-09 21:13:30 +0000644// Adds all qualifying matches for a name within a decl context to the
645// given lookup result. Returns true if any matches were found.
Douglas Gregord3a59182010-02-12 05:48:04 +0000646static bool LookupDirect(Sema &S, LookupResult &R, const DeclContext *DC) {
John McCall9f3059a2009-10-09 21:13:30 +0000647 bool Found = false;
648
Douglas Gregor7454c562010-07-02 20:37:36 +0000649 // Lazily declare C++ special member functions.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000650 if (S.getLangOpts().CPlusPlus)
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000651 DeclareImplicitMemberFunctionsWithName(S, R.getLookupName(), DC);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000652
Douglas Gregor7454c562010-07-02 20:37:36 +0000653 // Perform lookup into this declaration context.
John McCallf6c8a4e2009-11-10 07:01:13 +0000654 DeclContext::lookup_const_iterator I, E;
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000655 for (llvm::tie(I, E) = DC->lookup(R.getLookupName()); I != E; ++I) {
John McCall401982f2010-01-20 21:53:11 +0000656 NamedDecl *D = *I;
Douglas Gregor4a814562011-12-14 16:03:29 +0000657 if ((D = R.getAcceptableDecl(D))) {
John McCall401982f2010-01-20 21:53:11 +0000658 R.addDecl(D);
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000659 Found = true;
660 }
661 }
John McCall9f3059a2009-10-09 21:13:30 +0000662
Douglas Gregord3a59182010-02-12 05:48:04 +0000663 if (!Found && DC->isTranslationUnit() && LookupBuiltin(S, R))
664 return true;
665
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000666 if (R.getLookupName().getNameKind()
Chandler Carruth3a693b72010-01-31 11:44:02 +0000667 != DeclarationName::CXXConversionFunctionName ||
668 R.getLookupName().getCXXNameType()->isDependentType() ||
669 !isa<CXXRecordDecl>(DC))
670 return Found;
671
672 // C++ [temp.mem]p6:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000673 // A specialization of a conversion function template is not found by
Chandler Carruth3a693b72010-01-31 11:44:02 +0000674 // name lookup. Instead, any conversion function templates visible in the
675 // context of the use are considered. [...]
676 const CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
John McCallf937c022011-10-07 06:10:15 +0000677 if (!Record->isCompleteDefinition())
Chandler Carruth3a693b72010-01-31 11:44:02 +0000678 return Found;
679
680 const UnresolvedSetImpl *Unresolved = Record->getConversionFunctions();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000681 for (UnresolvedSetImpl::iterator U = Unresolved->begin(),
Chandler Carruth3a693b72010-01-31 11:44:02 +0000682 UEnd = Unresolved->end(); U != UEnd; ++U) {
683 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(*U);
684 if (!ConvTemplate)
685 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000686
Chandler Carruth3a693b72010-01-31 11:44:02 +0000687 // When we're performing lookup for the purposes of redeclaration, just
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000688 // add the conversion function template. When we deduce template
689 // arguments for specializations, we'll end up unifying the return
Chandler Carruth3a693b72010-01-31 11:44:02 +0000690 // type of the new declaration with the type of the function template.
691 if (R.isForRedeclaration()) {
692 R.addDecl(ConvTemplate);
693 Found = true;
694 continue;
695 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000696
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000697 // C++ [temp.mem]p6:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000698 // [...] For each such operator, if argument deduction succeeds
699 // (14.9.2.3), the resulting specialization is used as if found by
Chandler Carruth3a693b72010-01-31 11:44:02 +0000700 // name lookup.
701 //
702 // When referencing a conversion function for any purpose other than
703 // a redeclaration (such that we'll be building an expression with the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000704 // result), perform template argument deduction and place the
Chandler Carruth3a693b72010-01-31 11:44:02 +0000705 // specialization into the result set. We do this to avoid forcing all
706 // callers to perform special deduction for conversion functions.
John McCall19c1bfd2010-08-25 05:32:35 +0000707 TemplateDeductionInfo Info(R.getSema().Context, R.getNameLoc());
Chandler Carruth3a693b72010-01-31 11:44:02 +0000708 FunctionDecl *Specialization = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000709
710 const FunctionProtoType *ConvProto
Chandler Carruth3a693b72010-01-31 11:44:02 +0000711 = ConvTemplate->getTemplatedDecl()->getType()->getAs<FunctionProtoType>();
712 assert(ConvProto && "Nonsensical conversion function template type");
Douglas Gregor3c96a462010-01-12 01:17:50 +0000713
Chandler Carruth3a693b72010-01-31 11:44:02 +0000714 // Compute the type of the function that we would expect the conversion
715 // function to have, if it were to match the name given.
716 // FIXME: Calling convention!
John McCalldb40c7f2010-12-14 08:05:40 +0000717 FunctionProtoType::ExtProtoInfo EPI = ConvProto->getExtProtoInfo();
718 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(CC_Default);
Sebastian Redl7c6c9e92011-03-06 10:52:04 +0000719 EPI.ExceptionSpecType = EST_None;
John McCalldb40c7f2010-12-14 08:05:40 +0000720 EPI.NumExceptions = 0;
Chandler Carruth3a693b72010-01-31 11:44:02 +0000721 QualType ExpectedType
722 = R.getSema().Context.getFunctionType(R.getLookupName().getCXXNameType(),
John McCalldb40c7f2010-12-14 08:05:40 +0000723 0, 0, EPI);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000724
Chandler Carruth3a693b72010-01-31 11:44:02 +0000725 // Perform template argument deduction against the type that we would
726 // expect the function to have.
727 if (R.getSema().DeduceTemplateArguments(ConvTemplate, 0, ExpectedType,
728 Specialization, Info)
729 == Sema::TDK_Success) {
730 R.addDecl(Specialization);
731 Found = true;
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000732 }
733 }
Chandler Carruth3a693b72010-01-31 11:44:02 +0000734
John McCall9f3059a2009-10-09 21:13:30 +0000735 return Found;
736}
737
John McCallf6c8a4e2009-11-10 07:01:13 +0000738// Performs C++ unqualified lookup into the given file context.
John McCall9f3059a2009-10-09 21:13:30 +0000739static bool
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000740CppNamespaceLookup(Sema &S, LookupResult &R, ASTContext &Context,
Douglas Gregord3a59182010-02-12 05:48:04 +0000741 DeclContext *NS, UnqualUsingDirectiveSet &UDirs) {
Douglas Gregor700792c2009-02-05 19:25:20 +0000742
743 assert(NS && NS->isFileContext() && "CppNamespaceLookup() requires namespace!");
744
John McCallf6c8a4e2009-11-10 07:01:13 +0000745 // Perform direct name lookup into the LookupCtx.
Douglas Gregord3a59182010-02-12 05:48:04 +0000746 bool Found = LookupDirect(S, R, NS);
Douglas Gregor700792c2009-02-05 19:25:20 +0000747
John McCallf6c8a4e2009-11-10 07:01:13 +0000748 // Perform direct name lookup into the namespaces nominated by the
749 // using directives whose common ancestor is this namespace.
750 UnqualUsingDirectiveSet::const_iterator UI, UEnd;
751 llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(NS);
Mike Stump11289f42009-09-09 15:08:12 +0000752
John McCallf6c8a4e2009-11-10 07:01:13 +0000753 for (; UI != UEnd; ++UI)
Douglas Gregord3a59182010-02-12 05:48:04 +0000754 if (LookupDirect(S, R, UI->getNominatedNamespace()))
John McCallf6c8a4e2009-11-10 07:01:13 +0000755 Found = true;
John McCall9f3059a2009-10-09 21:13:30 +0000756
757 R.resolveKind();
758
759 return Found;
Douglas Gregor700792c2009-02-05 19:25:20 +0000760}
761
762static bool isNamespaceOrTranslationUnitScope(Scope *S) {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000763 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Douglas Gregor700792c2009-02-05 19:25:20 +0000764 return Ctx->isFileContext();
765 return false;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000766}
Douglas Gregored8f2882009-01-30 01:04:22 +0000767
Douglas Gregor66230062010-03-15 14:33:29 +0000768// Find the next outer declaration context from this scope. This
769// routine actually returns the semantic outer context, which may
770// differ from the lexical context (encoded directly in the Scope
771// stack) when we are parsing a member of a class template. In this
772// case, the second element of the pair will be true, to indicate that
773// name lookup should continue searching in this semantic context when
774// it leaves the current template parameter scope.
775static std::pair<DeclContext *, bool> findOuterContext(Scope *S) {
776 DeclContext *DC = static_cast<DeclContext *>(S->getEntity());
777 DeclContext *Lexical = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000778 for (Scope *OuterS = S->getParent(); OuterS;
Douglas Gregor66230062010-03-15 14:33:29 +0000779 OuterS = OuterS->getParent()) {
780 if (OuterS->getEntity()) {
Douglas Gregorea166062010-03-15 15:26:48 +0000781 Lexical = static_cast<DeclContext *>(OuterS->getEntity());
Douglas Gregor66230062010-03-15 14:33:29 +0000782 break;
783 }
784 }
785
786 // C++ [temp.local]p8:
787 // In the definition of a member of a class template that appears
788 // outside of the namespace containing the class template
789 // definition, the name of a template-parameter hides the name of
790 // a member of this namespace.
791 //
792 // Example:
793 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000794 // namespace N {
795 // class C { };
Douglas Gregor66230062010-03-15 14:33:29 +0000796 //
797 // template<class T> class B {
798 // void f(T);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000799 // };
Douglas Gregor66230062010-03-15 14:33:29 +0000800 // }
801 //
802 // template<class C> void N::B<C>::f(C) {
803 // C b; // C is the template parameter, not N::C
804 // }
805 //
806 // In this example, the lexical context we return is the
807 // TranslationUnit, while the semantic context is the namespace N.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000808 if (!Lexical || !DC || !S->getParent() ||
Douglas Gregor66230062010-03-15 14:33:29 +0000809 !S->getParent()->isTemplateParamScope())
810 return std::make_pair(Lexical, false);
811
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000812 // Find the outermost template parameter scope.
Douglas Gregor66230062010-03-15 14:33:29 +0000813 // For the example, this is the scope for the template parameters of
814 // template<class C>.
815 Scope *OutermostTemplateScope = S->getParent();
816 while (OutermostTemplateScope->getParent() &&
817 OutermostTemplateScope->getParent()->isTemplateParamScope())
818 OutermostTemplateScope = OutermostTemplateScope->getParent();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000819
Douglas Gregor66230062010-03-15 14:33:29 +0000820 // Find the namespace context in which the original scope occurs. In
821 // the example, this is namespace N.
822 DeclContext *Semantic = DC;
823 while (!Semantic->isFileContext())
824 Semantic = Semantic->getParent();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000825
Douglas Gregor66230062010-03-15 14:33:29 +0000826 // Find the declaration context just outside of the template
827 // parameter scope. This is the context in which the template is
828 // being lexically declaration (a namespace context). In the
829 // example, this is the global scope.
830 if (Lexical->isFileContext() && !Lexical->Equals(Semantic) &&
831 Lexical->Encloses(Semantic))
832 return std::make_pair(Semantic, true);
833
834 return std::make_pair(Lexical, false);
Douglas Gregor7f737c02009-09-10 16:57:35 +0000835}
836
John McCall27b18f82009-11-17 02:14:36 +0000837bool Sema::CppLookupName(LookupResult &R, Scope *S) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000838 assert(getLangOpts().CPlusPlus && "Can perform only C++ lookup");
John McCall27b18f82009-11-17 02:14:36 +0000839
840 DeclarationName Name = R.getLookupName();
841
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000842 // If this is the name of an implicitly-declared special member function,
843 // go through the scope stack to implicitly declare
844 if (isImplicitlyDeclaredMemberFunctionName(Name)) {
845 for (Scope *PreS = S; PreS; PreS = PreS->getParent())
846 if (DeclContext *DC = static_cast<DeclContext *>(PreS->getEntity()))
847 DeclareImplicitMemberFunctionsWithName(*this, Name, DC);
848 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000849
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000850 // Implicitly declare member functions with the name we're looking for, if in
851 // fact we are in a scope where it matters.
852
Douglas Gregor889ceb72009-02-03 19:21:40 +0000853 Scope *Initial = S;
Mike Stump11289f42009-09-09 15:08:12 +0000854 IdentifierResolver::iterator
Douglas Gregor889ceb72009-02-03 19:21:40 +0000855 I = IdResolver.begin(Name),
856 IEnd = IdResolver.end();
Douglas Gregored8f2882009-01-30 01:04:22 +0000857
Douglas Gregor889ceb72009-02-03 19:21:40 +0000858 // First we lookup local scope.
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000859 // We don't consider using-directives, as per 7.3.4.p1 [namespace.udir]
Douglas Gregor889ceb72009-02-03 19:21:40 +0000860 // ...During unqualified name lookup (3.4.1), the names appear as if
861 // they were declared in the nearest enclosing namespace which contains
862 // both the using-directive and the nominated namespace.
Eli Friedman44b83ee2009-08-05 19:21:58 +0000863 // [Note: in this context, "contains" means "contains directly or
Mike Stump11289f42009-09-09 15:08:12 +0000864 // indirectly".
Douglas Gregor889ceb72009-02-03 19:21:40 +0000865 //
866 // For example:
867 // namespace A { int i; }
868 // void foo() {
869 // int i;
870 // {
871 // using namespace A;
872 // ++i; // finds local 'i', A::i appears at global scope
873 // }
874 // }
Douglas Gregor2ada0482009-02-04 17:27:36 +0000875 //
Douglas Gregor66230062010-03-15 14:33:29 +0000876 DeclContext *OutsideOfTemplateParamDC = 0;
Douglas Gregor700792c2009-02-05 19:25:20 +0000877 for (; S && !isNamespaceOrTranslationUnitScope(S); S = S->getParent()) {
Douglas Gregor3e51e172010-05-20 20:58:56 +0000878 DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity());
879
Douglas Gregor889ceb72009-02-03 19:21:40 +0000880 // Check whether the IdResolver has anything in this scope.
John McCall9f3059a2009-10-09 21:13:30 +0000881 bool Found = false;
John McCall48871652010-08-21 09:40:31 +0000882 for (; I != IEnd && S->isDeclScope(*I); ++I) {
Douglas Gregor4a814562011-12-14 16:03:29 +0000883 if (NamedDecl *ND = R.getAcceptableDecl(*I)) {
John McCall9f3059a2009-10-09 21:13:30 +0000884 Found = true;
Douglas Gregor4a814562011-12-14 16:03:29 +0000885 R.addDecl(ND);
Douglas Gregor889ceb72009-02-03 19:21:40 +0000886 }
887 }
John McCall9f3059a2009-10-09 21:13:30 +0000888 if (Found) {
889 R.resolveKind();
Douglas Gregor3e51e172010-05-20 20:58:56 +0000890 if (S->isClassScope())
891 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(Ctx))
892 R.setNamingClass(Record);
John McCall9f3059a2009-10-09 21:13:30 +0000893 return true;
894 }
895
Douglas Gregor66230062010-03-15 14:33:29 +0000896 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
897 S->getParent() && !S->getParent()->isTemplateParamScope()) {
898 // We've just searched the last template parameter scope and
899 // found nothing, so look into the the contexts between the
900 // lexical and semantic declaration contexts returned by
901 // findOuterContext(). This implements the name lookup behavior
902 // of C++ [temp.local]p8.
903 Ctx = OutsideOfTemplateParamDC;
904 OutsideOfTemplateParamDC = 0;
905 }
906
907 if (Ctx) {
908 DeclContext *OuterCtx;
909 bool SearchAfterTemplateScope;
910 llvm::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
911 if (SearchAfterTemplateScope)
912 OutsideOfTemplateParamDC = OuterCtx;
913
Douglas Gregorea166062010-03-15 15:26:48 +0000914 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
Douglas Gregor337caf92010-02-19 16:08:35 +0000915 // We do not directly look into transparent contexts, since
916 // those entities will be found in the nearest enclosing
917 // non-transparent context.
918 if (Ctx->isTransparentContext())
Douglas Gregor7f737c02009-09-10 16:57:35 +0000919 continue;
Douglas Gregor337caf92010-02-19 16:08:35 +0000920
921 // We do not look directly into function or method contexts,
922 // since all of the local variables and parameters of the
923 // function/method are present within the Scope.
924 if (Ctx->isFunctionOrMethod()) {
925 // If we have an Objective-C instance method, look for ivars
926 // in the corresponding interface.
927 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
928 if (Method->isInstanceMethod() && Name.getAsIdentifierInfo())
929 if (ObjCInterfaceDecl *Class = Method->getClassInterface()) {
930 ObjCInterfaceDecl *ClassDeclared;
931 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000932 Name.getAsIdentifierInfo(),
Douglas Gregor337caf92010-02-19 16:08:35 +0000933 ClassDeclared)) {
Douglas Gregor4a814562011-12-14 16:03:29 +0000934 if (NamedDecl *ND = R.getAcceptableDecl(Ivar)) {
935 R.addDecl(ND);
Douglas Gregor337caf92010-02-19 16:08:35 +0000936 R.resolveKind();
937 return true;
938 }
939 }
940 }
941 }
942
943 continue;
944 }
945
Douglas Gregor7f737c02009-09-10 16:57:35 +0000946 // Perform qualified name lookup into this context.
947 // FIXME: In some cases, we know that every name that could be found by
948 // this qualified name lookup will also be on the identifier chain. For
949 // example, inside a class without any base classes, we never need to
950 // perform qualified lookup because all of the members are on top of the
951 // identifier chain.
Douglas Gregord0d2ee02010-01-15 01:44:47 +0000952 if (LookupQualifiedName(R, Ctx, /*InUnqualifiedLookup=*/true))
John McCall9f3059a2009-10-09 21:13:30 +0000953 return true;
Douglas Gregorfdca4a72009-03-27 04:21:56 +0000954 }
Douglas Gregor700792c2009-02-05 19:25:20 +0000955 }
Douglas Gregored8f2882009-01-30 01:04:22 +0000956 }
Douglas Gregor889ceb72009-02-03 19:21:40 +0000957
John McCallf6c8a4e2009-11-10 07:01:13 +0000958 // Stop if we ran out of scopes.
959 // FIXME: This really, really shouldn't be happening.
960 if (!S) return false;
961
Argyrios Kyrtzidis706bbf82010-10-29 16:12:50 +0000962 // If we are looking for members, no need to look into global/namespace scope.
963 if (R.getLookupKind() == LookupMemberName)
964 return false;
965
Douglas Gregor700792c2009-02-05 19:25:20 +0000966 // Collect UsingDirectiveDecls in all scopes, and recursively all
Douglas Gregor889ceb72009-02-03 19:21:40 +0000967 // nominated namespaces by those using-directives.
John McCallf6c8a4e2009-11-10 07:01:13 +0000968 //
Mike Stump87c57ac2009-05-16 07:39:55 +0000969 // FIXME: Cache this sorted list in Scope structure, and DeclContext, so we
970 // don't build it for each lookup!
Douglas Gregor889ceb72009-02-03 19:21:40 +0000971
John McCallf6c8a4e2009-11-10 07:01:13 +0000972 UnqualUsingDirectiveSet UDirs;
973 UDirs.visitScopeChain(Initial, S);
974 UDirs.done();
Douglas Gregor889ceb72009-02-03 19:21:40 +0000975
Douglas Gregor700792c2009-02-05 19:25:20 +0000976 // Lookup namespace scope, and global scope.
Douglas Gregor889ceb72009-02-03 19:21:40 +0000977 // Unqualified name lookup in C++ requires looking into scopes
978 // that aren't strictly lexical, and therefore we walk through the
979 // context as well as walking through the scopes.
Douglas Gregor700792c2009-02-05 19:25:20 +0000980
Douglas Gregor889ceb72009-02-03 19:21:40 +0000981 for (; S; S = S->getParent()) {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000982 // Check whether the IdResolver has anything in this scope.
John McCall9f3059a2009-10-09 21:13:30 +0000983 bool Found = false;
John McCall48871652010-08-21 09:40:31 +0000984 for (; I != IEnd && S->isDeclScope(*I); ++I) {
Douglas Gregor4a814562011-12-14 16:03:29 +0000985 if (NamedDecl *ND = R.getAcceptableDecl(*I)) {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000986 // We found something. Look for anything else in our scope
987 // with this same name and in an acceptable identifier
988 // namespace, so that we can construct an overload set if we
989 // need to.
John McCall9f3059a2009-10-09 21:13:30 +0000990 Found = true;
Douglas Gregor4a814562011-12-14 16:03:29 +0000991 R.addDecl(ND);
Douglas Gregor889ceb72009-02-03 19:21:40 +0000992 }
993 }
994
Douglas Gregorf3d3ae62010-05-14 04:53:42 +0000995 if (Found && S->isTemplateParamScope()) {
John McCall9f3059a2009-10-09 21:13:30 +0000996 R.resolveKind();
997 return true;
998 }
999
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001000 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
1001 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
1002 S->getParent() && !S->getParent()->isTemplateParamScope()) {
1003 // We've just searched the last template parameter scope and
1004 // found nothing, so look into the the contexts between the
1005 // lexical and semantic declaration contexts returned by
1006 // findOuterContext(). This implements the name lookup behavior
1007 // of C++ [temp.local]p8.
1008 Ctx = OutsideOfTemplateParamDC;
1009 OutsideOfTemplateParamDC = 0;
1010 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001011
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001012 if (Ctx) {
1013 DeclContext *OuterCtx;
1014 bool SearchAfterTemplateScope;
1015 llvm::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
1016 if (SearchAfterTemplateScope)
1017 OutsideOfTemplateParamDC = OuterCtx;
1018
1019 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
1020 // We do not directly look into transparent contexts, since
1021 // those entities will be found in the nearest enclosing
1022 // non-transparent context.
1023 if (Ctx->isTransparentContext())
1024 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001025
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001026 // If we have a context, and it's not a context stashed in the
1027 // template parameter scope for an out-of-line definition, also
1028 // look into that context.
1029 if (!(Found && S && S->isTemplateParamScope())) {
1030 assert(Ctx->isFileContext() &&
1031 "We should have been looking only at file context here already.");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001032
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001033 // Look into context considering using-directives.
1034 if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs))
1035 Found = true;
1036 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001037
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001038 if (Found) {
1039 R.resolveKind();
1040 return true;
1041 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001042
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001043 if (R.isForRedeclaration() && !Ctx->isTransparentContext())
1044 return false;
1045 }
1046 }
1047
Douglas Gregor3ce74932010-02-05 07:07:10 +00001048 if (R.isForRedeclaration() && Ctx && !Ctx->isTransparentContext())
John McCall9f3059a2009-10-09 21:13:30 +00001049 return false;
Douglas Gregor700792c2009-02-05 19:25:20 +00001050 }
Douglas Gregor889ceb72009-02-03 19:21:40 +00001051
John McCall9f3059a2009-10-09 21:13:30 +00001052 return !R.empty();
Douglas Gregored8f2882009-01-30 01:04:22 +00001053}
1054
Douglas Gregor4a814562011-12-14 16:03:29 +00001055/// \brief Retrieve the visible declaration corresponding to D, if any.
1056///
1057/// This routine determines whether the declaration D is visible in the current
1058/// module, with the current imports. If not, it checks whether any
1059/// redeclaration of D is visible, and if so, returns that declaration.
1060///
1061/// \returns D, or a visible previous declaration of D, whichever is more recent
1062/// and visible. If no declaration of D is visible, returns null.
1063static NamedDecl *getVisibleDecl(NamedDecl *D) {
1064 if (LookupResult::isVisible(D))
1065 return D;
1066
Douglas Gregor54079202012-01-06 22:05:37 +00001067 for (Decl::redecl_iterator RD = D->redecls_begin(), RDEnd = D->redecls_end();
1068 RD != RDEnd; ++RD) {
1069 if (NamedDecl *ND = dyn_cast<NamedDecl>(*RD)) {
1070 if (LookupResult::isVisible(ND))
1071 return ND;
1072 }
Douglas Gregor4a814562011-12-14 16:03:29 +00001073 }
1074
1075 return 0;
1076}
1077
Douglas Gregor34074322009-01-14 22:20:51 +00001078/// @brief Perform unqualified name lookup starting from a given
1079/// scope.
1080///
1081/// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is
1082/// used to find names within the current scope. For example, 'x' in
1083/// @code
1084/// int x;
1085/// int f() {
1086/// return x; // unqualified name look finds 'x' in the global scope
1087/// }
1088/// @endcode
1089///
1090/// Different lookup criteria can find different names. For example, a
1091/// particular scope can have both a struct and a function of the same
1092/// name, and each can be found by certain lookup criteria. For more
1093/// information about lookup criteria, see the documentation for the
1094/// class LookupCriteria.
1095///
1096/// @param S The scope from which unqualified name lookup will
1097/// begin. If the lookup criteria permits, name lookup may also search
1098/// in the parent scopes.
1099///
1100/// @param Name The name of the entity that we are searching for.
1101///
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001102/// @param Loc If provided, the source location where we're performing
Mike Stump11289f42009-09-09 15:08:12 +00001103/// name lookup. At present, this is only used to produce diagnostics when
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001104/// C library functions (like "malloc") are implicitly declared.
Douglas Gregor34074322009-01-14 22:20:51 +00001105///
1106/// @returns The result of name lookup, which includes zero or more
1107/// declarations and possibly additional information used to diagnose
1108/// ambiguities.
John McCall27b18f82009-11-17 02:14:36 +00001109bool Sema::LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation) {
1110 DeclarationName Name = R.getLookupName();
John McCall9f3059a2009-10-09 21:13:30 +00001111 if (!Name) return false;
Douglas Gregor34074322009-01-14 22:20:51 +00001112
John McCall27b18f82009-11-17 02:14:36 +00001113 LookupNameKind NameKind = R.getLookupKind();
1114
David Blaikiebbafb8a2012-03-11 07:00:24 +00001115 if (!getLangOpts().CPlusPlus) {
Douglas Gregor34074322009-01-14 22:20:51 +00001116 // Unqualified name lookup in C/Objective-C is purely lexical, so
1117 // search in the declarations attached to the name.
John McCallea305ed2009-12-18 10:40:03 +00001118 if (NameKind == Sema::LookupRedeclarationWithLinkage) {
Douglas Gregoreddf4332009-02-24 20:03:32 +00001119 // Find the nearest non-transparent declaration scope.
1120 while (!(S->getFlags() & Scope::DeclScope) ||
Mike Stump11289f42009-09-09 15:08:12 +00001121 (S->getEntity() &&
Douglas Gregoreddf4332009-02-24 20:03:32 +00001122 static_cast<DeclContext *>(S->getEntity())
1123 ->isTransparentContext()))
1124 S = S->getParent();
Douglas Gregored8f2882009-01-30 01:04:22 +00001125 }
1126
John McCallea305ed2009-12-18 10:40:03 +00001127 unsigned IDNS = R.getIdentifierNamespace();
1128
Douglas Gregor34074322009-01-14 22:20:51 +00001129 // Scan up the scope chain looking for a decl that matches this
1130 // identifier that is in the appropriate namespace. This search
1131 // should not take long, as shadowing of names is uncommon, and
1132 // deep shadowing is extremely uncommon.
Douglas Gregoreddf4332009-02-24 20:03:32 +00001133 bool LeftStartingScope = false;
1134
Douglas Gregored8f2882009-01-30 01:04:22 +00001135 for (IdentifierResolver::iterator I = IdResolver.begin(Name),
Mike Stump11289f42009-09-09 15:08:12 +00001136 IEnd = IdResolver.end();
Douglas Gregored8f2882009-01-30 01:04:22 +00001137 I != IEnd; ++I)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001138 if ((*I)->isInIdentifierNamespace(IDNS)) {
Douglas Gregoreddf4332009-02-24 20:03:32 +00001139 if (NameKind == LookupRedeclarationWithLinkage) {
1140 // Determine whether this (or a previous) declaration is
1141 // out-of-scope.
John McCall48871652010-08-21 09:40:31 +00001142 if (!LeftStartingScope && !S->isDeclScope(*I))
Douglas Gregoreddf4332009-02-24 20:03:32 +00001143 LeftStartingScope = true;
1144
1145 // If we found something outside of our starting scope that
1146 // does not have linkage, skip it.
1147 if (LeftStartingScope && !((*I)->hasLinkage()))
1148 continue;
1149 }
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00001150 else if (NameKind == LookupObjCImplicitSelfParam &&
1151 !isa<ImplicitParamDecl>(*I))
1152 continue;
1153
Douglas Gregor2a5d1482011-12-02 20:08:44 +00001154 // If this declaration is module-private and it came from an AST
1155 // file, we can't see it.
Douglas Gregor5c193c72012-01-05 01:11:47 +00001156 NamedDecl *D = R.isHiddenDeclarationVisible()? *I : getVisibleDecl(*I);
Douglas Gregor4a814562011-12-14 16:03:29 +00001157 if (!D)
Douglas Gregor2a5d1482011-12-02 20:08:44 +00001158 continue;
Douglas Gregor4a814562011-12-14 16:03:29 +00001159
1160 R.addDecl(D);
John McCall9f3059a2009-10-09 21:13:30 +00001161
Douglas Gregorb59643b2012-01-03 23:26:26 +00001162 // Check whether there are any other declarations with the same name
1163 // and in the same scope.
Douglas Gregor9b7b3912012-01-04 16:44:10 +00001164 if (I != IEnd) {
Douglas Gregor81bd0382012-01-13 23:06:53 +00001165 // Find the scope in which this declaration was declared (if it
1166 // actually exists in a Scope).
1167 while (S && !S->isDeclScope(D))
1168 S = S->getParent();
1169
1170 // If the scope containing the declaration is the translation unit,
1171 // then we'll need to perform our checks based on the matching
1172 // DeclContexts rather than matching scopes.
1173 if (S && isNamespaceOrTranslationUnitScope(S))
1174 S = 0;
1175
1176 // Compute the DeclContext, if we need it.
1177 DeclContext *DC = 0;
1178 if (!S)
1179 DC = (*I)->getDeclContext()->getRedeclContext();
1180
Douglas Gregor9b7b3912012-01-04 16:44:10 +00001181 IdentifierResolver::iterator LastI = I;
1182 for (++LastI; LastI != IEnd; ++LastI) {
Douglas Gregor81bd0382012-01-13 23:06:53 +00001183 if (S) {
1184 // Match based on scope.
1185 if (!S->isDeclScope(*LastI))
1186 break;
1187 } else {
1188 // Match based on DeclContext.
1189 DeclContext *LastDC
1190 = (*LastI)->getDeclContext()->getRedeclContext();
1191 if (!LastDC->Equals(DC))
1192 break;
1193 }
1194
1195 // If the declaration isn't in the right namespace, skip it.
Douglas Gregor9b7b3912012-01-04 16:44:10 +00001196 if (!(*LastI)->isInIdentifierNamespace(IDNS))
1197 continue;
Douglas Gregor81bd0382012-01-13 23:06:53 +00001198
Douglas Gregor5c193c72012-01-05 01:11:47 +00001199 D = R.isHiddenDeclarationVisible()? *LastI : getVisibleDecl(*LastI);
Douglas Gregor9b7b3912012-01-04 16:44:10 +00001200 if (D)
1201 R.addDecl(D);
1202 }
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001203
Douglas Gregor9b7b3912012-01-04 16:44:10 +00001204 R.resolveKind();
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001205 }
John McCall9f3059a2009-10-09 21:13:30 +00001206 return true;
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001207 }
Douglas Gregor34074322009-01-14 22:20:51 +00001208 } else {
Douglas Gregor889ceb72009-02-03 19:21:40 +00001209 // Perform C++ unqualified name lookup.
John McCall27b18f82009-11-17 02:14:36 +00001210 if (CppLookupName(R, S))
John McCall9f3059a2009-10-09 21:13:30 +00001211 return true;
Douglas Gregor34074322009-01-14 22:20:51 +00001212 }
1213
1214 // If we didn't find a use of this identifier, and if the identifier
1215 // corresponds to a compiler builtin, create the decl object for the builtin
1216 // now, injecting it into translation unit scope, and return it.
Axel Naumann43dec142011-04-13 13:19:46 +00001217 if (AllowBuiltinCreation && LookupBuiltin(*this, R))
1218 return true;
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001219
Axel Naumann016538a2011-02-24 16:47:47 +00001220 // If we didn't find a use of this identifier, the ExternalSource
1221 // may be able to handle the situation.
1222 // Note: some lookup failures are expected!
1223 // See e.g. R.isForRedeclaration().
1224 return (ExternalSource && ExternalSource->LookupUnqualified(R, S));
Douglas Gregor34074322009-01-14 22:20:51 +00001225}
1226
John McCall6538c932009-10-10 05:48:19 +00001227/// @brief Perform qualified name lookup in the namespaces nominated by
1228/// using directives by the given context.
1229///
1230/// C++98 [namespace.qual]p2:
1231/// Given X::m (where X is a user-declared namespace), or given ::m
1232/// (where X is the global namespace), let S be the set of all
1233/// declarations of m in X and in the transitive closure of all
1234/// namespaces nominated by using-directives in X and its used
1235/// namespaces, except that using-directives are ignored in any
1236/// namespace, including X, directly containing one or more
1237/// declarations of m. No namespace is searched more than once in
1238/// the lookup of a name. If S is the empty set, the program is
1239/// ill-formed. Otherwise, if S has exactly one member, or if the
1240/// context of the reference is a using-declaration
1241/// (namespace.udecl), S is the required set of declarations of
1242/// m. Otherwise if the use of m is not one that allows a unique
1243/// declaration to be chosen from S, the program is ill-formed.
1244/// C++98 [namespace.qual]p5:
1245/// During the lookup of a qualified namespace member name, if the
1246/// lookup finds more than one declaration of the member, and if one
1247/// declaration introduces a class name or enumeration name and the
1248/// other declarations either introduce the same object, the same
1249/// enumerator or a set of functions, the non-type name hides the
1250/// class or enumeration name if and only if the declarations are
1251/// from the same namespace; otherwise (the declarations are from
1252/// different namespaces), the program is ill-formed.
Douglas Gregord3a59182010-02-12 05:48:04 +00001253static bool LookupQualifiedNameInUsingDirectives(Sema &S, LookupResult &R,
John McCall27b18f82009-11-17 02:14:36 +00001254 DeclContext *StartDC) {
John McCall6538c932009-10-10 05:48:19 +00001255 assert(StartDC->isFileContext() && "start context is not a file context");
1256
1257 DeclContext::udir_iterator I = StartDC->using_directives_begin();
1258 DeclContext::udir_iterator E = StartDC->using_directives_end();
1259
1260 if (I == E) return false;
1261
1262 // We have at least added all these contexts to the queue.
Benjamin Kramer3adbe1c2012-02-23 16:06:01 +00001263 llvm::SmallPtrSet<DeclContext*, 8> Visited;
John McCall6538c932009-10-10 05:48:19 +00001264 Visited.insert(StartDC);
1265
1266 // We have not yet looked into these namespaces, much less added
1267 // their "using-children" to the queue.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001268 SmallVector<NamespaceDecl*, 8> Queue;
John McCall6538c932009-10-10 05:48:19 +00001269
1270 // We have already looked into the initial namespace; seed the queue
1271 // with its using-children.
1272 for (; I != E; ++I) {
John McCallb8be78b2009-11-10 09:25:37 +00001273 NamespaceDecl *ND = (*I)->getNominatedNamespace()->getOriginalNamespace();
Benjamin Kramer3adbe1c2012-02-23 16:06:01 +00001274 if (Visited.insert(ND))
John McCall6538c932009-10-10 05:48:19 +00001275 Queue.push_back(ND);
1276 }
1277
1278 // The easiest way to implement the restriction in [namespace.qual]p5
1279 // is to check whether any of the individual results found a tag
1280 // and, if so, to declare an ambiguity if the final result is not
1281 // a tag.
1282 bool FoundTag = false;
1283 bool FoundNonTag = false;
1284
John McCall5cebab12009-11-18 07:57:50 +00001285 LookupResult LocalR(LookupResult::Temporary, R);
John McCall6538c932009-10-10 05:48:19 +00001286
1287 bool Found = false;
1288 while (!Queue.empty()) {
1289 NamespaceDecl *ND = Queue.back();
1290 Queue.pop_back();
1291
1292 // We go through some convolutions here to avoid copying results
1293 // between LookupResults.
1294 bool UseLocal = !R.empty();
John McCall5cebab12009-11-18 07:57:50 +00001295 LookupResult &DirectR = UseLocal ? LocalR : R;
Douglas Gregord3a59182010-02-12 05:48:04 +00001296 bool FoundDirect = LookupDirect(S, DirectR, ND);
John McCall6538c932009-10-10 05:48:19 +00001297
1298 if (FoundDirect) {
1299 // First do any local hiding.
1300 DirectR.resolveKind();
1301
1302 // If the local result is a tag, remember that.
1303 if (DirectR.isSingleTagDecl())
1304 FoundTag = true;
1305 else
1306 FoundNonTag = true;
1307
1308 // Append the local results to the total results if necessary.
1309 if (UseLocal) {
1310 R.addAllDecls(LocalR);
1311 LocalR.clear();
1312 }
1313 }
1314
1315 // If we find names in this namespace, ignore its using directives.
1316 if (FoundDirect) {
1317 Found = true;
1318 continue;
1319 }
1320
1321 for (llvm::tie(I,E) = ND->getUsingDirectives(); I != E; ++I) {
1322 NamespaceDecl *Nom = (*I)->getNominatedNamespace();
Benjamin Kramer3adbe1c2012-02-23 16:06:01 +00001323 if (Visited.insert(Nom))
John McCall6538c932009-10-10 05:48:19 +00001324 Queue.push_back(Nom);
1325 }
1326 }
1327
1328 if (Found) {
1329 if (FoundTag && FoundNonTag)
1330 R.setAmbiguousQualifiedTagHiding();
1331 else
1332 R.resolveKind();
1333 }
1334
1335 return Found;
1336}
1337
Douglas Gregor39982192010-08-15 06:18:01 +00001338/// \brief Callback that looks for any member of a class with the given name.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001339static bool LookupAnyMember(const CXXBaseSpecifier *Specifier,
Douglas Gregor39982192010-08-15 06:18:01 +00001340 CXXBasePath &Path,
1341 void *Name) {
1342 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001343
Douglas Gregor39982192010-08-15 06:18:01 +00001344 DeclarationName N = DeclarationName::getFromOpaquePtr(Name);
1345 Path.Decls = BaseRecord->lookup(N);
1346 return Path.Decls.first != Path.Decls.second;
1347}
1348
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001349/// \brief Determine whether the given set of member declarations contains only
Douglas Gregorc0d24902010-10-22 22:08:47 +00001350/// static members, nested types, and enumerators.
1351template<typename InputIterator>
1352static bool HasOnlyStaticMembers(InputIterator First, InputIterator Last) {
1353 Decl *D = (*First)->getUnderlyingDecl();
1354 if (isa<VarDecl>(D) || isa<TypeDecl>(D) || isa<EnumConstantDecl>(D))
1355 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001356
Douglas Gregorc0d24902010-10-22 22:08:47 +00001357 if (isa<CXXMethodDecl>(D)) {
1358 // Determine whether all of the methods are static.
1359 bool AllMethodsAreStatic = true;
1360 for(; First != Last; ++First) {
1361 D = (*First)->getUnderlyingDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001362
Douglas Gregorc0d24902010-10-22 22:08:47 +00001363 if (!isa<CXXMethodDecl>(D)) {
1364 assert(isa<TagDecl>(D) && "Non-function must be a tag decl");
1365 break;
1366 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001367
Douglas Gregorc0d24902010-10-22 22:08:47 +00001368 if (!cast<CXXMethodDecl>(D)->isStatic()) {
1369 AllMethodsAreStatic = false;
1370 break;
1371 }
1372 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001373
Douglas Gregorc0d24902010-10-22 22:08:47 +00001374 if (AllMethodsAreStatic)
1375 return true;
1376 }
1377
1378 return false;
1379}
1380
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001381/// \brief Perform qualified name lookup into a given context.
Douglas Gregor34074322009-01-14 22:20:51 +00001382///
1383/// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
1384/// names when the context of those names is explicit specified, e.g.,
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001385/// "std::vector" or "x->member", or as part of unqualified name lookup.
Douglas Gregor34074322009-01-14 22:20:51 +00001386///
1387/// Different lookup criteria can find different names. For example, a
1388/// particular scope can have both a struct and a function of the same
1389/// name, and each can be found by certain lookup criteria. For more
1390/// information about lookup criteria, see the documentation for the
1391/// class LookupCriteria.
1392///
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001393/// \param R captures both the lookup criteria and any lookup results found.
1394///
1395/// \param LookupCtx The context in which qualified name lookup will
Douglas Gregor34074322009-01-14 22:20:51 +00001396/// search. If the lookup criteria permits, name lookup may also search
1397/// in the parent contexts or (for C++ classes) base classes.
1398///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001399/// \param InUnqualifiedLookup true if this is qualified name lookup that
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001400/// occurs as part of unqualified name lookup.
Douglas Gregor34074322009-01-14 22:20:51 +00001401///
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001402/// \returns true if lookup succeeded, false if it failed.
1403bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
1404 bool InUnqualifiedLookup) {
Douglas Gregor34074322009-01-14 22:20:51 +00001405 assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context");
Mike Stump11289f42009-09-09 15:08:12 +00001406
John McCall27b18f82009-11-17 02:14:36 +00001407 if (!R.getLookupName())
John McCall9f3059a2009-10-09 21:13:30 +00001408 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001409
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001410 // Make sure that the declaration context is complete.
1411 assert((!isa<TagDecl>(LookupCtx) ||
1412 LookupCtx->isDependentContext() ||
John McCallf937c022011-10-07 06:10:15 +00001413 cast<TagDecl>(LookupCtx)->isCompleteDefinition() ||
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001414 Context.getTypeDeclType(cast<TagDecl>(LookupCtx))->getAs<TagType>()
1415 ->isBeingDefined()) &&
1416 "Declaration context must already be complete!");
Mike Stump11289f42009-09-09 15:08:12 +00001417
Douglas Gregor34074322009-01-14 22:20:51 +00001418 // Perform qualified name lookup into the LookupCtx.
Douglas Gregord3a59182010-02-12 05:48:04 +00001419 if (LookupDirect(*this, R, LookupCtx)) {
John McCall9f3059a2009-10-09 21:13:30 +00001420 R.resolveKind();
John McCall553c0792010-01-23 00:46:32 +00001421 if (isa<CXXRecordDecl>(LookupCtx))
1422 R.setNamingClass(cast<CXXRecordDecl>(LookupCtx));
John McCall9f3059a2009-10-09 21:13:30 +00001423 return true;
1424 }
Douglas Gregor34074322009-01-14 22:20:51 +00001425
John McCall6538c932009-10-10 05:48:19 +00001426 // Don't descend into implied contexts for redeclarations.
1427 // C++98 [namespace.qual]p6:
1428 // In a declaration for a namespace member in which the
1429 // declarator-id is a qualified-id, given that the qualified-id
1430 // for the namespace member has the form
1431 // nested-name-specifier unqualified-id
1432 // the unqualified-id shall name a member of the namespace
1433 // designated by the nested-name-specifier.
1434 // See also [class.mfct]p5 and [class.static.data]p2.
John McCall27b18f82009-11-17 02:14:36 +00001435 if (R.isForRedeclaration())
John McCall6538c932009-10-10 05:48:19 +00001436 return false;
1437
John McCall27b18f82009-11-17 02:14:36 +00001438 // If this is a namespace, look it up in the implied namespaces.
John McCall6538c932009-10-10 05:48:19 +00001439 if (LookupCtx->isFileContext())
Douglas Gregord3a59182010-02-12 05:48:04 +00001440 return LookupQualifiedNameInUsingDirectives(*this, R, LookupCtx);
John McCall6538c932009-10-10 05:48:19 +00001441
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001442 // If this isn't a C++ class, we aren't allowed to look into base
Douglas Gregorcc2427c2009-09-11 22:57:37 +00001443 // classes, we're done.
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001444 CXXRecordDecl *LookupRec = dyn_cast<CXXRecordDecl>(LookupCtx);
Douglas Gregor5a5fcd82010-07-01 00:21:21 +00001445 if (!LookupRec || !LookupRec->getDefinition())
John McCall9f3059a2009-10-09 21:13:30 +00001446 return false;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001447
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001448 // If we're performing qualified name lookup into a dependent class,
1449 // then we are actually looking into a current instantiation. If we have any
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001450 // dependent base classes, then we either have to delay lookup until
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001451 // template instantiation time (at which point all bases will be available)
1452 // or we have to fail.
1453 if (!InUnqualifiedLookup && LookupRec->isDependentContext() &&
1454 LookupRec->hasAnyDependentBases()) {
1455 R.setNotFoundInCurrentInstantiation();
1456 return false;
1457 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001458
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001459 // Perform lookup into our base classes.
Douglas Gregor36d1b142009-10-06 17:59:45 +00001460 CXXBasePaths Paths;
1461 Paths.setOrigin(LookupRec);
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001462
1463 // Look for this member in our base classes
Douglas Gregor36d1b142009-10-06 17:59:45 +00001464 CXXRecordDecl::BaseMatchesCallback *BaseCallback = 0;
John McCall27b18f82009-11-17 02:14:36 +00001465 switch (R.getLookupKind()) {
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00001466 case LookupObjCImplicitSelfParam:
Douglas Gregor36d1b142009-10-06 17:59:45 +00001467 case LookupOrdinaryName:
1468 case LookupMemberName:
1469 case LookupRedeclarationWithLinkage:
1470 BaseCallback = &CXXRecordDecl::FindOrdinaryMember;
1471 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001472
Douglas Gregor36d1b142009-10-06 17:59:45 +00001473 case LookupTagName:
1474 BaseCallback = &CXXRecordDecl::FindTagMember;
1475 break;
John McCall84d87672009-12-10 09:41:52 +00001476
Douglas Gregor39982192010-08-15 06:18:01 +00001477 case LookupAnyName:
1478 BaseCallback = &LookupAnyMember;
1479 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001480
John McCall84d87672009-12-10 09:41:52 +00001481 case LookupUsingDeclName:
1482 // This lookup is for redeclarations only.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001483
Douglas Gregor36d1b142009-10-06 17:59:45 +00001484 case LookupOperatorName:
1485 case LookupNamespaceName:
1486 case LookupObjCProtocolName:
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001487 case LookupLabel:
Douglas Gregor36d1b142009-10-06 17:59:45 +00001488 // These lookups will never find a member in a C++ class (or base class).
John McCall9f3059a2009-10-09 21:13:30 +00001489 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001490
Douglas Gregor36d1b142009-10-06 17:59:45 +00001491 case LookupNestedNameSpecifierName:
1492 BaseCallback = &CXXRecordDecl::FindNestedNameSpecifierMember;
1493 break;
1494 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001495
John McCall27b18f82009-11-17 02:14:36 +00001496 if (!LookupRec->lookupInBases(BaseCallback,
1497 R.getLookupName().getAsOpaquePtr(), Paths))
John McCall9f3059a2009-10-09 21:13:30 +00001498 return false;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001499
John McCall553c0792010-01-23 00:46:32 +00001500 R.setNamingClass(LookupRec);
1501
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001502 // C++ [class.member.lookup]p2:
1503 // [...] If the resulting set of declarations are not all from
1504 // sub-objects of the same type, or the set has a nonstatic member
1505 // and includes members from distinct sub-objects, there is an
1506 // ambiguity and the program is ill-formed. Otherwise that set is
1507 // the result of the lookup.
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001508 QualType SubobjectType;
Daniel Dunbar435bbe02009-01-15 18:32:35 +00001509 int SubobjectNumber = 0;
John McCalla332b952010-03-18 23:49:19 +00001510 AccessSpecifier SubobjectAccess = AS_none;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001511
Douglas Gregor36d1b142009-10-06 17:59:45 +00001512 for (CXXBasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end();
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001513 Path != PathEnd; ++Path) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00001514 const CXXBasePathElement &PathElement = Path->back();
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001515
John McCall401982f2010-01-20 21:53:11 +00001516 // Pick the best (i.e. most permissive i.e. numerically lowest) access
1517 // across all paths.
1518 SubobjectAccess = std::min(SubobjectAccess, Path->Access);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001519
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001520 // Determine whether we're looking at a distinct sub-object or not.
1521 if (SubobjectType.isNull()) {
John McCall9f3059a2009-10-09 21:13:30 +00001522 // This is the first subobject we've looked at. Record its type.
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001523 SubobjectType = Context.getCanonicalType(PathElement.Base->getType());
1524 SubobjectNumber = PathElement.SubobjectNumber;
Douglas Gregorc0d24902010-10-22 22:08:47 +00001525 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001526 }
1527
Douglas Gregorc0d24902010-10-22 22:08:47 +00001528 if (SubobjectType
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001529 != Context.getCanonicalType(PathElement.Base->getType())) {
1530 // We found members of the given name in two subobjects of
Douglas Gregorc0d24902010-10-22 22:08:47 +00001531 // different types. If the declaration sets aren't the same, this
1532 // this lookup is ambiguous.
1533 if (HasOnlyStaticMembers(Path->Decls.first, Path->Decls.second)) {
1534 CXXBasePaths::paths_iterator FirstPath = Paths.begin();
1535 DeclContext::lookup_iterator FirstD = FirstPath->Decls.first;
1536 DeclContext::lookup_iterator CurrentD = Path->Decls.first;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001537
Douglas Gregorc0d24902010-10-22 22:08:47 +00001538 while (FirstD != FirstPath->Decls.second &&
1539 CurrentD != Path->Decls.second) {
1540 if ((*FirstD)->getUnderlyingDecl()->getCanonicalDecl() !=
1541 (*CurrentD)->getUnderlyingDecl()->getCanonicalDecl())
1542 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001543
Douglas Gregorc0d24902010-10-22 22:08:47 +00001544 ++FirstD;
1545 ++CurrentD;
1546 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001547
Douglas Gregorc0d24902010-10-22 22:08:47 +00001548 if (FirstD == FirstPath->Decls.second &&
1549 CurrentD == Path->Decls.second)
1550 continue;
1551 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001552
John McCall9f3059a2009-10-09 21:13:30 +00001553 R.setAmbiguousBaseSubobjectTypes(Paths);
1554 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001555 }
1556
Douglas Gregorc0d24902010-10-22 22:08:47 +00001557 if (SubobjectNumber != PathElement.SubobjectNumber) {
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001558 // We have a different subobject of the same type.
1559
1560 // C++ [class.member.lookup]p5:
1561 // A static member, a nested type or an enumerator defined in
1562 // a base class T can unambiguously be found even if an object
Mike Stump11289f42009-09-09 15:08:12 +00001563 // has more than one base class subobject of type T.
Douglas Gregorc0d24902010-10-22 22:08:47 +00001564 if (HasOnlyStaticMembers(Path->Decls.first, Path->Decls.second))
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001565 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001566
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001567 // We have found a nonstatic member name in multiple, distinct
1568 // subobjects. Name lookup is ambiguous.
John McCall9f3059a2009-10-09 21:13:30 +00001569 R.setAmbiguousBaseSubobjects(Paths);
1570 return true;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001571 }
1572 }
1573
1574 // Lookup in a base class succeeded; return these results.
1575
John McCall9f3059a2009-10-09 21:13:30 +00001576 DeclContext::lookup_iterator I, E;
John McCall553c0792010-01-23 00:46:32 +00001577 for (llvm::tie(I,E) = Paths.front().Decls; I != E; ++I) {
1578 NamedDecl *D = *I;
1579 AccessSpecifier AS = CXXRecordDecl::MergeAccess(SubobjectAccess,
1580 D->getAccess());
1581 R.addDecl(D, AS);
1582 }
John McCall9f3059a2009-10-09 21:13:30 +00001583 R.resolveKind();
1584 return true;
Douglas Gregor34074322009-01-14 22:20:51 +00001585}
1586
1587/// @brief Performs name lookup for a name that was parsed in the
1588/// source code, and may contain a C++ scope specifier.
1589///
1590/// This routine is a convenience routine meant to be called from
1591/// contexts that receive a name and an optional C++ scope specifier
1592/// (e.g., "N::M::x"). It will then perform either qualified or
1593/// unqualified name lookup (with LookupQualifiedName or LookupName,
1594/// respectively) on the given name and return those results.
1595///
1596/// @param S The scope from which unqualified name lookup will
1597/// begin.
Mike Stump11289f42009-09-09 15:08:12 +00001598///
Douglas Gregore861bac2009-08-25 22:51:20 +00001599/// @param SS An optional C++ scope-specifier, e.g., "::N::M".
Douglas Gregor34074322009-01-14 22:20:51 +00001600///
Douglas Gregore861bac2009-08-25 22:51:20 +00001601/// @param EnteringContext Indicates whether we are going to enter the
1602/// context of the scope-specifier SS (if present).
1603///
John McCall9f3059a2009-10-09 21:13:30 +00001604/// @returns True if any decls were found (but possibly ambiguous)
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001605bool Sema::LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
John McCall27b18f82009-11-17 02:14:36 +00001606 bool AllowBuiltinCreation, bool EnteringContext) {
Douglas Gregore861bac2009-08-25 22:51:20 +00001607 if (SS && SS->isInvalid()) {
1608 // When the scope specifier is invalid, don't even look for
Douglas Gregorc9f9b862009-05-11 19:58:34 +00001609 // anything.
John McCall9f3059a2009-10-09 21:13:30 +00001610 return false;
Douglas Gregore861bac2009-08-25 22:51:20 +00001611 }
Mike Stump11289f42009-09-09 15:08:12 +00001612
Douglas Gregore861bac2009-08-25 22:51:20 +00001613 if (SS && SS->isSet()) {
1614 if (DeclContext *DC = computeDeclContext(*SS, EnteringContext)) {
Mike Stump11289f42009-09-09 15:08:12 +00001615 // We have resolved the scope specifier to a particular declaration
Douglas Gregore861bac2009-08-25 22:51:20 +00001616 // contex, and will perform name lookup in that context.
John McCall0b66eb32010-05-01 00:40:08 +00001617 if (!DC->isDependentContext() && RequireCompleteDeclContext(*SS, DC))
John McCall9f3059a2009-10-09 21:13:30 +00001618 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001619
John McCall27b18f82009-11-17 02:14:36 +00001620 R.setContextRange(SS->getRange());
John McCall27b18f82009-11-17 02:14:36 +00001621 return LookupQualifiedName(R, DC);
Douglas Gregor52537682009-03-19 00:18:19 +00001622 }
Douglas Gregorc9f9b862009-05-11 19:58:34 +00001623
Douglas Gregore861bac2009-08-25 22:51:20 +00001624 // We could not resolve the scope specified to a specific declaration
Mike Stump11289f42009-09-09 15:08:12 +00001625 // context, which means that SS refers to an unknown specialization.
Douglas Gregore861bac2009-08-25 22:51:20 +00001626 // Name lookup can't find anything in this case.
Douglas Gregor89ab56d2011-10-24 22:24:50 +00001627 R.setNotFoundInCurrentInstantiation();
1628 R.setContextRange(SS->getRange());
John McCall9f3059a2009-10-09 21:13:30 +00001629 return false;
Douglas Gregored8f2882009-01-30 01:04:22 +00001630 }
1631
Mike Stump11289f42009-09-09 15:08:12 +00001632 // Perform unqualified name lookup starting in the given scope.
John McCall27b18f82009-11-17 02:14:36 +00001633 return LookupName(R, S, AllowBuiltinCreation);
Douglas Gregor34074322009-01-14 22:20:51 +00001634}
1635
Douglas Gregor889ceb72009-02-03 19:21:40 +00001636
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001637/// @brief Produce a diagnostic describing the ambiguity that resulted
1638/// from name lookup.
1639///
1640/// @param Result The ambiguous name lookup result.
Mike Stump11289f42009-09-09 15:08:12 +00001641///
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001642/// @param Name The name of the entity that name lookup was
1643/// searching for.
1644///
1645/// @param NameLoc The location of the name within the source code.
1646///
1647/// @param LookupRange A source range that provides more
1648/// source-location information concerning the lookup itself. For
1649/// example, this range might highlight a nested-name-specifier that
1650/// precedes the name.
1651///
1652/// @returns true
John McCall27b18f82009-11-17 02:14:36 +00001653bool Sema::DiagnoseAmbiguousLookup(LookupResult &Result) {
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001654 assert(Result.isAmbiguous() && "Lookup result must be ambiguous");
1655
John McCall27b18f82009-11-17 02:14:36 +00001656 DeclarationName Name = Result.getLookupName();
1657 SourceLocation NameLoc = Result.getNameLoc();
1658 SourceRange LookupRange = Result.getContextRange();
1659
John McCall6538c932009-10-10 05:48:19 +00001660 switch (Result.getAmbiguityKind()) {
1661 case LookupResult::AmbiguousBaseSubobjects: {
1662 CXXBasePaths *Paths = Result.getBasePaths();
1663 QualType SubobjectType = Paths->front().back().Base->getType();
1664 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects)
1665 << Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths)
1666 << LookupRange;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001667
John McCall6538c932009-10-10 05:48:19 +00001668 DeclContext::lookup_iterator Found = Paths->front().Decls.first;
1669 while (isa<CXXMethodDecl>(*Found) &&
1670 cast<CXXMethodDecl>(*Found)->isStatic())
1671 ++Found;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001672
John McCall6538c932009-10-10 05:48:19 +00001673 Diag((*Found)->getLocation(), diag::note_ambiguous_member_found);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001674
John McCall6538c932009-10-10 05:48:19 +00001675 return true;
1676 }
Douglas Gregor1c846b02009-01-16 00:38:09 +00001677
John McCall6538c932009-10-10 05:48:19 +00001678 case LookupResult::AmbiguousBaseSubobjectTypes: {
Douglas Gregor889ceb72009-02-03 19:21:40 +00001679 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types)
1680 << Name << LookupRange;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001681
John McCall6538c932009-10-10 05:48:19 +00001682 CXXBasePaths *Paths = Result.getBasePaths();
Douglas Gregor889ceb72009-02-03 19:21:40 +00001683 std::set<Decl *> DeclsPrinted;
John McCall6538c932009-10-10 05:48:19 +00001684 for (CXXBasePaths::paths_iterator Path = Paths->begin(),
1685 PathEnd = Paths->end();
Douglas Gregor889ceb72009-02-03 19:21:40 +00001686 Path != PathEnd; ++Path) {
1687 Decl *D = *Path->Decls.first;
1688 if (DeclsPrinted.insert(D).second)
1689 Diag(D->getLocation(), diag::note_ambiguous_member_found);
1690 }
1691
Douglas Gregor1c846b02009-01-16 00:38:09 +00001692 return true;
Douglas Gregor1c846b02009-01-16 00:38:09 +00001693 }
1694
John McCall6538c932009-10-10 05:48:19 +00001695 case LookupResult::AmbiguousTagHiding: {
1696 Diag(NameLoc, diag::err_ambiguous_tag_hiding) << Name << LookupRange;
Douglas Gregorf23311d2009-01-17 01:13:24 +00001697
John McCall6538c932009-10-10 05:48:19 +00001698 llvm::SmallPtrSet<NamedDecl*,8> TagDecls;
1699
1700 LookupResult::iterator DI, DE = Result.end();
1701 for (DI = Result.begin(); DI != DE; ++DI)
1702 if (TagDecl *TD = dyn_cast<TagDecl>(*DI)) {
1703 TagDecls.insert(TD);
1704 Diag(TD->getLocation(), diag::note_hidden_tag);
1705 }
1706
1707 for (DI = Result.begin(); DI != DE; ++DI)
1708 if (!isa<TagDecl>(*DI))
1709 Diag((*DI)->getLocation(), diag::note_hiding_object);
1710
1711 // For recovery purposes, go ahead and implement the hiding.
John McCallad371252010-01-20 00:46:10 +00001712 LookupResult::Filter F = Result.makeFilter();
1713 while (F.hasNext()) {
1714 if (TagDecls.count(F.next()))
1715 F.erase();
1716 }
1717 F.done();
John McCall6538c932009-10-10 05:48:19 +00001718
1719 return true;
1720 }
1721
1722 case LookupResult::AmbiguousReference: {
1723 Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001724
John McCall6538c932009-10-10 05:48:19 +00001725 LookupResult::iterator DI = Result.begin(), DE = Result.end();
1726 for (; DI != DE; ++DI)
1727 Diag((*DI)->getLocation(), diag::note_ambiguous_candidate) << *DI;
John McCall9f3059a2009-10-09 21:13:30 +00001728
John McCall6538c932009-10-10 05:48:19 +00001729 return true;
1730 }
1731 }
1732
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00001733 llvm_unreachable("unknown ambiguity kind");
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001734}
Douglas Gregore254f902009-02-04 00:32:51 +00001735
John McCallf24d7bb2010-05-28 18:45:08 +00001736namespace {
1737 struct AssociatedLookup {
1738 AssociatedLookup(Sema &S,
1739 Sema::AssociatedNamespaceSet &Namespaces,
1740 Sema::AssociatedClassSet &Classes)
1741 : S(S), Namespaces(Namespaces), Classes(Classes) {
1742 }
1743
1744 Sema &S;
1745 Sema::AssociatedNamespaceSet &Namespaces;
1746 Sema::AssociatedClassSet &Classes;
1747 };
1748}
1749
Mike Stump11289f42009-09-09 15:08:12 +00001750static void
John McCallf24d7bb2010-05-28 18:45:08 +00001751addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType T);
John McCallc7e8e792009-08-07 22:18:02 +00001752
Douglas Gregor8b895222010-04-30 07:08:38 +00001753static void CollectEnclosingNamespace(Sema::AssociatedNamespaceSet &Namespaces,
1754 DeclContext *Ctx) {
1755 // Add the associated namespace for this class.
1756
1757 // We don't use DeclContext::getEnclosingNamespaceContext() as this may
1758 // be a locally scoped record.
1759
Sebastian Redlbd595762010-08-31 20:53:31 +00001760 // We skip out of inline namespaces. The innermost non-inline namespace
1761 // contains all names of all its nested inline namespaces anyway, so we can
1762 // replace the entire inline namespace tree with its root.
1763 while (Ctx->isRecord() || Ctx->isTransparentContext() ||
1764 Ctx->isInlineNamespace())
Douglas Gregor8b895222010-04-30 07:08:38 +00001765 Ctx = Ctx->getParent();
1766
John McCallc7e8e792009-08-07 22:18:02 +00001767 if (Ctx->isFileContext())
Douglas Gregor8b895222010-04-30 07:08:38 +00001768 Namespaces.insert(Ctx->getPrimaryContext());
John McCallc7e8e792009-08-07 22:18:02 +00001769}
Douglas Gregor197e5f72009-07-08 07:51:57 +00001770
Mike Stump11289f42009-09-09 15:08:12 +00001771// \brief Add the associated classes and namespaces for argument-dependent
Douglas Gregor197e5f72009-07-08 07:51:57 +00001772// lookup that involves a template argument (C++ [basic.lookup.koenig]p2).
Mike Stump11289f42009-09-09 15:08:12 +00001773static void
John McCallf24d7bb2010-05-28 18:45:08 +00001774addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
1775 const TemplateArgument &Arg) {
Douglas Gregor197e5f72009-07-08 07:51:57 +00001776 // C++ [basic.lookup.koenig]p2, last bullet:
Mike Stump11289f42009-09-09 15:08:12 +00001777 // -- [...] ;
Douglas Gregor197e5f72009-07-08 07:51:57 +00001778 switch (Arg.getKind()) {
1779 case TemplateArgument::Null:
1780 break;
Mike Stump11289f42009-09-09 15:08:12 +00001781
Douglas Gregor197e5f72009-07-08 07:51:57 +00001782 case TemplateArgument::Type:
1783 // [...] the namespaces and classes associated with the types of the
1784 // template arguments provided for template type parameters (excluding
1785 // template template parameters)
John McCallf24d7bb2010-05-28 18:45:08 +00001786 addAssociatedClassesAndNamespaces(Result, Arg.getAsType());
Douglas Gregor197e5f72009-07-08 07:51:57 +00001787 break;
Mike Stump11289f42009-09-09 15:08:12 +00001788
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001789 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00001790 case TemplateArgument::TemplateExpansion: {
Mike Stump11289f42009-09-09 15:08:12 +00001791 // [...] the namespaces in which any template template arguments are
1792 // defined; and the classes in which any member templates used as
Douglas Gregor197e5f72009-07-08 07:51:57 +00001793 // template template arguments are defined.
Douglas Gregore4ff4b52011-01-05 18:58:31 +00001794 TemplateName Template = Arg.getAsTemplateOrTemplatePattern();
Mike Stump11289f42009-09-09 15:08:12 +00001795 if (ClassTemplateDecl *ClassTemplate
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001796 = dyn_cast<ClassTemplateDecl>(Template.getAsTemplateDecl())) {
Douglas Gregor197e5f72009-07-08 07:51:57 +00001797 DeclContext *Ctx = ClassTemplate->getDeclContext();
1798 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00001799 Result.Classes.insert(EnclosingClass);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001800 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00001801 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001802 }
1803 break;
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001804 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001805
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001806 case TemplateArgument::Declaration:
Douglas Gregor197e5f72009-07-08 07:51:57 +00001807 case TemplateArgument::Integral:
1808 case TemplateArgument::Expression:
Mike Stump11289f42009-09-09 15:08:12 +00001809 // [Note: non-type template arguments do not contribute to the set of
Douglas Gregor197e5f72009-07-08 07:51:57 +00001810 // associated namespaces. ]
1811 break;
Mike Stump11289f42009-09-09 15:08:12 +00001812
Douglas Gregor197e5f72009-07-08 07:51:57 +00001813 case TemplateArgument::Pack:
1814 for (TemplateArgument::pack_iterator P = Arg.pack_begin(),
1815 PEnd = Arg.pack_end();
1816 P != PEnd; ++P)
John McCallf24d7bb2010-05-28 18:45:08 +00001817 addAssociatedClassesAndNamespaces(Result, *P);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001818 break;
1819 }
1820}
1821
Douglas Gregore254f902009-02-04 00:32:51 +00001822// \brief Add the associated classes and namespaces for
Mike Stump11289f42009-09-09 15:08:12 +00001823// argument-dependent lookup with an argument of class type
1824// (C++ [basic.lookup.koenig]p2).
1825static void
John McCallf24d7bb2010-05-28 18:45:08 +00001826addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
1827 CXXRecordDecl *Class) {
1828
1829 // Just silently ignore anything whose name is __va_list_tag.
1830 if (Class->getDeclName() == Result.S.VAListTagName)
1831 return;
1832
Douglas Gregore254f902009-02-04 00:32:51 +00001833 // C++ [basic.lookup.koenig]p2:
1834 // [...]
1835 // -- If T is a class type (including unions), its associated
1836 // classes are: the class itself; the class of which it is a
1837 // member, if any; and its direct and indirect base
1838 // classes. Its associated namespaces are the namespaces in
Mike Stump11289f42009-09-09 15:08:12 +00001839 // which its associated classes are defined.
Douglas Gregore254f902009-02-04 00:32:51 +00001840
1841 // Add the class of which it is a member, if any.
1842 DeclContext *Ctx = Class->getDeclContext();
1843 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00001844 Result.Classes.insert(EnclosingClass);
Douglas Gregore254f902009-02-04 00:32:51 +00001845 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00001846 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Mike Stump11289f42009-09-09 15:08:12 +00001847
Douglas Gregore254f902009-02-04 00:32:51 +00001848 // Add the class itself. If we've already seen this class, we don't
1849 // need to visit base classes.
John McCallf24d7bb2010-05-28 18:45:08 +00001850 if (!Result.Classes.insert(Class))
Douglas Gregore254f902009-02-04 00:32:51 +00001851 return;
1852
Mike Stump11289f42009-09-09 15:08:12 +00001853 // -- If T is a template-id, its associated namespaces and classes are
1854 // the namespace in which the template is defined; for member
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00001855 // templates, the member template's class; the namespaces and classes
Mike Stump11289f42009-09-09 15:08:12 +00001856 // associated with the types of the template arguments provided for
Douglas Gregor197e5f72009-07-08 07:51:57 +00001857 // template type parameters (excluding template template parameters); the
Mike Stump11289f42009-09-09 15:08:12 +00001858 // namespaces in which any template template arguments are defined; and
1859 // the classes in which any member templates used as template template
1860 // arguments are defined. [Note: non-type template arguments do not
Douglas Gregor197e5f72009-07-08 07:51:57 +00001861 // contribute to the set of associated namespaces. ]
Mike Stump11289f42009-09-09 15:08:12 +00001862 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregor197e5f72009-07-08 07:51:57 +00001863 = dyn_cast<ClassTemplateSpecializationDecl>(Class)) {
1864 DeclContext *Ctx = Spec->getSpecializedTemplate()->getDeclContext();
1865 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00001866 Result.Classes.insert(EnclosingClass);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001867 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00001868 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Mike Stump11289f42009-09-09 15:08:12 +00001869
Douglas Gregor197e5f72009-07-08 07:51:57 +00001870 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
1871 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
John McCallf24d7bb2010-05-28 18:45:08 +00001872 addAssociatedClassesAndNamespaces(Result, TemplateArgs[I]);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001873 }
Mike Stump11289f42009-09-09 15:08:12 +00001874
John McCall67da35c2010-02-04 22:26:26 +00001875 // Only recurse into base classes for complete types.
1876 if (!Class->hasDefinition()) {
1877 // FIXME: we might need to instantiate templates here
1878 return;
1879 }
1880
Douglas Gregore254f902009-02-04 00:32:51 +00001881 // Add direct and indirect base classes along with their associated
1882 // namespaces.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001883 SmallVector<CXXRecordDecl *, 32> Bases;
Douglas Gregore254f902009-02-04 00:32:51 +00001884 Bases.push_back(Class);
1885 while (!Bases.empty()) {
1886 // Pop this class off the stack.
1887 Class = Bases.back();
1888 Bases.pop_back();
1889
1890 // Visit the base classes.
1891 for (CXXRecordDecl::base_class_iterator Base = Class->bases_begin(),
1892 BaseEnd = Class->bases_end();
1893 Base != BaseEnd; ++Base) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001894 const RecordType *BaseType = Base->getType()->getAs<RecordType>();
Sebastian Redlc45c03c2009-10-25 09:35:33 +00001895 // In dependent contexts, we do ADL twice, and the first time around,
1896 // the base type might be a dependent TemplateSpecializationType, or a
1897 // TemplateTypeParmType. If that happens, simply ignore it.
1898 // FIXME: If we want to support export, we probably need to add the
1899 // namespace of the template in a TemplateSpecializationType, or even
1900 // the classes and namespaces of known non-dependent arguments.
1901 if (!BaseType)
1902 continue;
Douglas Gregore254f902009-02-04 00:32:51 +00001903 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(BaseType->getDecl());
John McCallf24d7bb2010-05-28 18:45:08 +00001904 if (Result.Classes.insert(BaseDecl)) {
Douglas Gregore254f902009-02-04 00:32:51 +00001905 // Find the associated namespace for this base class.
1906 DeclContext *BaseCtx = BaseDecl->getDeclContext();
John McCallf24d7bb2010-05-28 18:45:08 +00001907 CollectEnclosingNamespace(Result.Namespaces, BaseCtx);
Douglas Gregore254f902009-02-04 00:32:51 +00001908
1909 // Make sure we visit the bases of this base class.
1910 if (BaseDecl->bases_begin() != BaseDecl->bases_end())
1911 Bases.push_back(BaseDecl);
1912 }
1913 }
1914 }
1915}
1916
1917// \brief Add the associated classes and namespaces for
1918// argument-dependent lookup with an argument of type T
Mike Stump11289f42009-09-09 15:08:12 +00001919// (C++ [basic.lookup.koenig]p2).
1920static void
John McCallf24d7bb2010-05-28 18:45:08 +00001921addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType Ty) {
Douglas Gregore254f902009-02-04 00:32:51 +00001922 // C++ [basic.lookup.koenig]p2:
1923 //
1924 // For each argument type T in the function call, there is a set
1925 // of zero or more associated namespaces and a set of zero or more
1926 // associated classes to be considered. The sets of namespaces and
1927 // classes is determined entirely by the types of the function
1928 // arguments (and the namespace of any template template
1929 // argument). Typedef names and using-declarations used to specify
1930 // the types do not contribute to this set. The sets of namespaces
1931 // and classes are determined in the following way:
Douglas Gregore254f902009-02-04 00:32:51 +00001932
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001933 SmallVector<const Type *, 16> Queue;
John McCall0af3d3b2010-05-28 06:08:54 +00001934 const Type *T = Ty->getCanonicalTypeInternal().getTypePtr();
1935
Douglas Gregore254f902009-02-04 00:32:51 +00001936 while (true) {
John McCall0af3d3b2010-05-28 06:08:54 +00001937 switch (T->getTypeClass()) {
1938
1939#define TYPE(Class, Base)
1940#define DEPENDENT_TYPE(Class, Base) case Type::Class:
1941#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
1942#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
1943#define ABSTRACT_TYPE(Class, Base)
1944#include "clang/AST/TypeNodes.def"
1945 // T is canonical. We can also ignore dependent types because
1946 // we don't need to do ADL at the definition point, but if we
1947 // wanted to implement template export (or if we find some other
1948 // use for associated classes and namespaces...) this would be
1949 // wrong.
Douglas Gregore254f902009-02-04 00:32:51 +00001950 break;
Douglas Gregore254f902009-02-04 00:32:51 +00001951
John McCall0af3d3b2010-05-28 06:08:54 +00001952 // -- If T is a pointer to U or an array of U, its associated
1953 // namespaces and classes are those associated with U.
1954 case Type::Pointer:
1955 T = cast<PointerType>(T)->getPointeeType().getTypePtr();
1956 continue;
1957 case Type::ConstantArray:
1958 case Type::IncompleteArray:
1959 case Type::VariableArray:
1960 T = cast<ArrayType>(T)->getElementType().getTypePtr();
1961 continue;
Douglas Gregore254f902009-02-04 00:32:51 +00001962
John McCall0af3d3b2010-05-28 06:08:54 +00001963 // -- If T is a fundamental type, its associated sets of
1964 // namespaces and classes are both empty.
1965 case Type::Builtin:
1966 break;
1967
1968 // -- If T is a class type (including unions), its associated
1969 // classes are: the class itself; the class of which it is a
1970 // member, if any; and its direct and indirect base
1971 // classes. Its associated namespaces are the namespaces in
1972 // which its associated classes are defined.
1973 case Type::Record: {
1974 CXXRecordDecl *Class
1975 = cast<CXXRecordDecl>(cast<RecordType>(T)->getDecl());
John McCallf24d7bb2010-05-28 18:45:08 +00001976 addAssociatedClassesAndNamespaces(Result, Class);
John McCall0af3d3b2010-05-28 06:08:54 +00001977 break;
Douglas Gregor89ee6822009-02-28 01:32:25 +00001978 }
Douglas Gregorfe60c142010-05-20 02:26:51 +00001979
John McCall0af3d3b2010-05-28 06:08:54 +00001980 // -- If T is an enumeration type, its associated namespace is
1981 // the namespace in which it is defined. If it is class
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00001982 // member, its associated class is the member's class; else
John McCall0af3d3b2010-05-28 06:08:54 +00001983 // it has no associated class.
1984 case Type::Enum: {
1985 EnumDecl *Enum = cast<EnumType>(T)->getDecl();
Douglas Gregore254f902009-02-04 00:32:51 +00001986
John McCall0af3d3b2010-05-28 06:08:54 +00001987 DeclContext *Ctx = Enum->getDeclContext();
1988 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00001989 Result.Classes.insert(EnclosingClass);
Douglas Gregore254f902009-02-04 00:32:51 +00001990
John McCall0af3d3b2010-05-28 06:08:54 +00001991 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00001992 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Douglas Gregore254f902009-02-04 00:32:51 +00001993
John McCall0af3d3b2010-05-28 06:08:54 +00001994 break;
1995 }
1996
1997 // -- If T is a function type, its associated namespaces and
1998 // classes are those associated with the function parameter
1999 // types and those associated with the return type.
2000 case Type::FunctionProto: {
2001 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
2002 for (FunctionProtoType::arg_type_iterator Arg = Proto->arg_type_begin(),
2003 ArgEnd = Proto->arg_type_end();
2004 Arg != ArgEnd; ++Arg)
2005 Queue.push_back(Arg->getTypePtr());
2006 // fallthrough
2007 }
2008 case Type::FunctionNoProto: {
2009 const FunctionType *FnType = cast<FunctionType>(T);
2010 T = FnType->getResultType().getTypePtr();
2011 continue;
2012 }
2013
2014 // -- If T is a pointer to a member function of a class X, its
2015 // associated namespaces and classes are those associated
2016 // with the function parameter types and return type,
2017 // together with those associated with X.
2018 //
2019 // -- If T is a pointer to a data member of class X, its
2020 // associated namespaces and classes are those associated
2021 // with the member type together with those associated with
2022 // X.
2023 case Type::MemberPointer: {
2024 const MemberPointerType *MemberPtr = cast<MemberPointerType>(T);
2025
2026 // Queue up the class type into which this points.
2027 Queue.push_back(MemberPtr->getClass());
2028
2029 // And directly continue with the pointee type.
2030 T = MemberPtr->getPointeeType().getTypePtr();
2031 continue;
2032 }
2033
2034 // As an extension, treat this like a normal pointer.
2035 case Type::BlockPointer:
2036 T = cast<BlockPointerType>(T)->getPointeeType().getTypePtr();
2037 continue;
2038
2039 // References aren't covered by the standard, but that's such an
2040 // obvious defect that we cover them anyway.
2041 case Type::LValueReference:
2042 case Type::RValueReference:
2043 T = cast<ReferenceType>(T)->getPointeeType().getTypePtr();
2044 continue;
2045
2046 // These are fundamental types.
2047 case Type::Vector:
2048 case Type::ExtVector:
2049 case Type::Complex:
2050 break;
2051
Douglas Gregor8e936662011-04-12 01:02:45 +00002052 // If T is an Objective-C object or interface type, or a pointer to an
2053 // object or interface type, the associated namespace is the global
2054 // namespace.
John McCall0af3d3b2010-05-28 06:08:54 +00002055 case Type::ObjCObject:
2056 case Type::ObjCInterface:
2057 case Type::ObjCObjectPointer:
Douglas Gregor8e936662011-04-12 01:02:45 +00002058 Result.Namespaces.insert(Result.S.Context.getTranslationUnitDecl());
John McCall0af3d3b2010-05-28 06:08:54 +00002059 break;
Eli Friedman0dfb8892011-10-06 23:00:33 +00002060
2061 // Atomic types are just wrappers; use the associations of the
2062 // contained type.
2063 case Type::Atomic:
2064 T = cast<AtomicType>(T)->getValueType().getTypePtr();
2065 continue;
John McCall0af3d3b2010-05-28 06:08:54 +00002066 }
2067
2068 if (Queue.empty()) break;
2069 T = Queue.back();
2070 Queue.pop_back();
Douglas Gregore254f902009-02-04 00:32:51 +00002071 }
Douglas Gregore254f902009-02-04 00:32:51 +00002072}
2073
2074/// \brief Find the associated classes and namespaces for
2075/// argument-dependent lookup for a call with the given set of
2076/// arguments.
2077///
2078/// This routine computes the sets of associated classes and associated
Mike Stump11289f42009-09-09 15:08:12 +00002079/// namespaces searched by argument-dependent lookup
Douglas Gregore254f902009-02-04 00:32:51 +00002080/// (C++ [basic.lookup.argdep]) for a given set of arguments.
Mike Stump11289f42009-09-09 15:08:12 +00002081void
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002082Sema::FindAssociatedClassesAndNamespaces(llvm::ArrayRef<Expr *> Args,
Douglas Gregore254f902009-02-04 00:32:51 +00002083 AssociatedNamespaceSet &AssociatedNamespaces,
John McCallc7e8e792009-08-07 22:18:02 +00002084 AssociatedClassSet &AssociatedClasses) {
Douglas Gregore254f902009-02-04 00:32:51 +00002085 AssociatedNamespaces.clear();
2086 AssociatedClasses.clear();
2087
John McCallf24d7bb2010-05-28 18:45:08 +00002088 AssociatedLookup Result(*this, AssociatedNamespaces, AssociatedClasses);
2089
Douglas Gregore254f902009-02-04 00:32:51 +00002090 // C++ [basic.lookup.koenig]p2:
2091 // For each argument type T in the function call, there is a set
2092 // of zero or more associated namespaces and a set of zero or more
2093 // associated classes to be considered. The sets of namespaces and
2094 // classes is determined entirely by the types of the function
2095 // arguments (and the namespace of any template template
Mike Stump11289f42009-09-09 15:08:12 +00002096 // argument).
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002097 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
Douglas Gregore254f902009-02-04 00:32:51 +00002098 Expr *Arg = Args[ArgIdx];
2099
2100 if (Arg->getType() != Context.OverloadTy) {
John McCallf24d7bb2010-05-28 18:45:08 +00002101 addAssociatedClassesAndNamespaces(Result, Arg->getType());
Douglas Gregore254f902009-02-04 00:32:51 +00002102 continue;
2103 }
2104
2105 // [...] In addition, if the argument is the name or address of a
2106 // set of overloaded functions and/or function templates, its
2107 // associated classes and namespaces are the union of those
2108 // associated with each of the members of the set: the namespace
2109 // in which the function or function template is defined and the
2110 // classes and namespaces associated with its (non-dependent)
2111 // parameter types and return type.
Douglas Gregorbe759252009-07-08 10:57:20 +00002112 Arg = Arg->IgnoreParens();
John McCalld14a8642009-11-21 08:51:07 +00002113 if (UnaryOperator *unaryOp = dyn_cast<UnaryOperator>(Arg))
John McCalle3027922010-08-25 11:45:40 +00002114 if (unaryOp->getOpcode() == UO_AddrOf)
John McCalld14a8642009-11-21 08:51:07 +00002115 Arg = unaryOp->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00002116
John McCallf24d7bb2010-05-28 18:45:08 +00002117 UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Arg);
2118 if (!ULE) continue;
John McCalld14a8642009-11-21 08:51:07 +00002119
John McCallf24d7bb2010-05-28 18:45:08 +00002120 for (UnresolvedSetIterator I = ULE->decls_begin(), E = ULE->decls_end();
2121 I != E; ++I) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00002122 // Look through any using declarations to find the underlying function.
2123 NamedDecl *Fn = (*I)->getUnderlyingDecl();
Douglas Gregore254f902009-02-04 00:32:51 +00002124
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00002125 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(Fn);
2126 if (!FDecl)
2127 FDecl = cast<FunctionTemplateDecl>(Fn)->getTemplatedDecl();
Douglas Gregore254f902009-02-04 00:32:51 +00002128
2129 // Add the classes and namespaces associated with the parameter
2130 // types and return type of this function.
John McCallf24d7bb2010-05-28 18:45:08 +00002131 addAssociatedClassesAndNamespaces(Result, FDecl->getType());
Douglas Gregore254f902009-02-04 00:32:51 +00002132 }
2133 }
2134}
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002135
2136/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
2137/// an acceptable non-member overloaded operator for a call whose
2138/// arguments have types T1 (and, if non-empty, T2). This routine
2139/// implements the check in C++ [over.match.oper]p3b2 concerning
2140/// enumeration types.
Mike Stump11289f42009-09-09 15:08:12 +00002141static bool
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002142IsAcceptableNonMemberOperatorCandidate(FunctionDecl *Fn,
2143 QualType T1, QualType T2,
2144 ASTContext &Context) {
Douglas Gregor0950e412009-03-13 21:01:28 +00002145 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
2146 return true;
2147
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002148 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
2149 return true;
2150
John McCall9dd450b2009-09-21 23:43:11 +00002151 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002152 if (Proto->getNumArgs() < 1)
2153 return false;
2154
2155 if (T1->isEnumeralType()) {
2156 QualType ArgType = Proto->getArgType(0).getNonReferenceType();
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002157 if (Context.hasSameUnqualifiedType(T1, ArgType))
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002158 return true;
2159 }
2160
2161 if (Proto->getNumArgs() < 2)
2162 return false;
2163
2164 if (!T2.isNull() && T2->isEnumeralType()) {
2165 QualType ArgType = Proto->getArgType(1).getNonReferenceType();
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002166 if (Context.hasSameUnqualifiedType(T2, ArgType))
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002167 return true;
2168 }
2169
2170 return false;
2171}
2172
John McCall5cebab12009-11-18 07:57:50 +00002173NamedDecl *Sema::LookupSingleName(Scope *S, DeclarationName Name,
Douglas Gregorb2ccf012010-04-15 22:33:43 +00002174 SourceLocation Loc,
John McCall5cebab12009-11-18 07:57:50 +00002175 LookupNameKind NameKind,
2176 RedeclarationKind Redecl) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +00002177 LookupResult R(*this, Name, Loc, NameKind, Redecl);
John McCall5cebab12009-11-18 07:57:50 +00002178 LookupName(R, S);
John McCall67c00872009-12-02 08:25:40 +00002179 return R.getAsSingle<NamedDecl>();
John McCall5cebab12009-11-18 07:57:50 +00002180}
2181
Douglas Gregorde9f17e2009-04-23 23:18:26 +00002182/// \brief Find the protocol with the given name, if any.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002183ObjCProtocolDecl *Sema::LookupProtocol(IdentifierInfo *II,
Douglas Gregor32c17572012-01-01 20:30:41 +00002184 SourceLocation IdLoc,
2185 RedeclarationKind Redecl) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +00002186 Decl *D = LookupSingleName(TUScope, II, IdLoc,
Douglas Gregor32c17572012-01-01 20:30:41 +00002187 LookupObjCProtocolName, Redecl);
Douglas Gregorde9f17e2009-04-23 23:18:26 +00002188 return cast_or_null<ObjCProtocolDecl>(D);
2189}
2190
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002191void Sema::LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
Mike Stump11289f42009-09-09 15:08:12 +00002192 QualType T1, QualType T2,
John McCall4c4c1df2010-01-26 03:27:55 +00002193 UnresolvedSetImpl &Functions) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002194 // C++ [over.match.oper]p3:
2195 // -- The set of non-member candidates is the result of the
2196 // unqualified lookup of operator@ in the context of the
2197 // expression according to the usual rules for name lookup in
2198 // unqualified function calls (3.4.2) except that all member
2199 // functions are ignored. However, if no operand has a class
2200 // type, only those non-member functions in the lookup set
Eli Friedman44b83ee2009-08-05 19:21:58 +00002201 // that have a first parameter of type T1 or "reference to
2202 // (possibly cv-qualified) T1", when T1 is an enumeration
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002203 // type, or (if there is a right operand) a second parameter
Eli Friedman44b83ee2009-08-05 19:21:58 +00002204 // of type T2 or "reference to (possibly cv-qualified) T2",
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002205 // when T2 is an enumeration type, are candidate functions.
2206 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
John McCall27b18f82009-11-17 02:14:36 +00002207 LookupResult Operators(*this, OpName, SourceLocation(), LookupOperatorName);
2208 LookupName(Operators, S);
Mike Stump11289f42009-09-09 15:08:12 +00002209
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002210 assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
2211
John McCall9f3059a2009-10-09 21:13:30 +00002212 if (Operators.empty())
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002213 return;
2214
2215 for (LookupResult::iterator Op = Operators.begin(), OpEnd = Operators.end();
2216 Op != OpEnd; ++Op) {
Douglas Gregor645d76f2010-04-25 20:25:43 +00002217 NamedDecl *Found = (*Op)->getUnderlyingDecl();
2218 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Found)) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002219 if (IsAcceptableNonMemberOperatorCandidate(FD, T1, T2, Context))
Douglas Gregor645d76f2010-04-25 20:25:43 +00002220 Functions.addDecl(*Op, Op.getAccess()); // FIXME: canonical FD
Mike Stump11289f42009-09-09 15:08:12 +00002221 } else if (FunctionTemplateDecl *FunTmpl
Douglas Gregor645d76f2010-04-25 20:25:43 +00002222 = dyn_cast<FunctionTemplateDecl>(Found)) {
Douglas Gregor15448f82009-06-27 21:05:07 +00002223 // FIXME: friend operators?
Mike Stump11289f42009-09-09 15:08:12 +00002224 // FIXME: do we need to check IsAcceptableNonMemberOperatorCandidate,
Douglas Gregor15448f82009-06-27 21:05:07 +00002225 // later?
2226 if (!FunTmpl->getDeclContext()->isRecord())
Douglas Gregor645d76f2010-04-25 20:25:43 +00002227 Functions.addDecl(*Op, Op.getAccess());
Douglas Gregor15448f82009-06-27 21:05:07 +00002228 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002229 }
2230}
2231
Alexis Hunt1da39282011-06-24 02:11:39 +00002232Sema::SpecialMemberOverloadResult *Sema::LookupSpecialMember(CXXRecordDecl *RD,
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002233 CXXSpecialMember SM,
2234 bool ConstArg,
2235 bool VolatileArg,
2236 bool RValueThis,
2237 bool ConstThis,
2238 bool VolatileThis) {
Alexis Hunt1da39282011-06-24 02:11:39 +00002239 RD = RD->getDefinition();
2240 assert((RD && !RD->isBeingDefined()) &&
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002241 "doing special member lookup into record that isn't fully complete");
2242 if (RValueThis || ConstThis || VolatileThis)
2243 assert((SM == CXXCopyAssignment || SM == CXXMoveAssignment) &&
2244 "constructors and destructors always have unqualified lvalue this");
2245 if (ConstArg || VolatileArg)
2246 assert((SM != CXXDefaultConstructor && SM != CXXDestructor) &&
2247 "parameter-less special members can't have qualified arguments");
2248
2249 llvm::FoldingSetNodeID ID;
Alexis Hunt1da39282011-06-24 02:11:39 +00002250 ID.AddPointer(RD);
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002251 ID.AddInteger(SM);
2252 ID.AddInteger(ConstArg);
2253 ID.AddInteger(VolatileArg);
2254 ID.AddInteger(RValueThis);
2255 ID.AddInteger(ConstThis);
2256 ID.AddInteger(VolatileThis);
2257
2258 void *InsertPoint;
2259 SpecialMemberOverloadResult *Result =
2260 SpecialMemberCache.FindNodeOrInsertPos(ID, InsertPoint);
2261
2262 // This was already cached
2263 if (Result)
2264 return Result;
2265
Alexis Huntba8e18d2011-06-07 00:11:58 +00002266 Result = BumpAlloc.Allocate<SpecialMemberOverloadResult>();
2267 Result = new (Result) SpecialMemberOverloadResult(ID);
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002268 SpecialMemberCache.InsertNode(Result, InsertPoint);
2269
2270 if (SM == CXXDestructor) {
Alexis Hunt1da39282011-06-24 02:11:39 +00002271 if (!RD->hasDeclaredDestructor())
2272 DeclareImplicitDestructor(RD);
2273 CXXDestructorDecl *DD = RD->getDestructor();
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002274 assert(DD && "record without a destructor");
2275 Result->setMethod(DD);
Richard Smithd951a1d2012-02-18 02:02:13 +00002276 Result->setSuccess(!DD->isDeleted());
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002277 Result->setConstParamMatch(false);
2278 return Result;
2279 }
2280
Alexis Hunteef8ee02011-06-10 03:50:41 +00002281 // Prepare for overload resolution. Here we construct a synthetic argument
2282 // if necessary and make sure that implicit functions are declared.
Alexis Hunt1da39282011-06-24 02:11:39 +00002283 CanQualType CanTy = Context.getCanonicalType(Context.getTagDeclType(RD));
Alexis Hunteef8ee02011-06-10 03:50:41 +00002284 DeclarationName Name;
2285 Expr *Arg = 0;
2286 unsigned NumArgs;
2287
2288 if (SM == CXXDefaultConstructor) {
2289 Name = Context.DeclarationNames.getCXXConstructorName(CanTy);
2290 NumArgs = 0;
Alexis Hunt1da39282011-06-24 02:11:39 +00002291 if (RD->needsImplicitDefaultConstructor())
2292 DeclareImplicitDefaultConstructor(RD);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002293 } else {
2294 if (SM == CXXCopyConstructor || SM == CXXMoveConstructor) {
2295 Name = Context.DeclarationNames.getCXXConstructorName(CanTy);
Alexis Hunt1da39282011-06-24 02:11:39 +00002296 if (!RD->hasDeclaredCopyConstructor())
2297 DeclareImplicitCopyConstructor(RD);
David Blaikiebbafb8a2012-03-11 07:00:24 +00002298 if (getLangOpts().CPlusPlus0x && RD->needsImplicitMoveConstructor())
Sebastian Redl22653ba2011-08-30 19:58:05 +00002299 DeclareImplicitMoveConstructor(RD);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002300 } else {
2301 Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Alexis Hunt1da39282011-06-24 02:11:39 +00002302 if (!RD->hasDeclaredCopyAssignment())
2303 DeclareImplicitCopyAssignment(RD);
David Blaikiebbafb8a2012-03-11 07:00:24 +00002304 if (getLangOpts().CPlusPlus0x && RD->needsImplicitMoveAssignment())
Sebastian Redl22653ba2011-08-30 19:58:05 +00002305 DeclareImplicitMoveAssignment(RD);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002306 }
2307
2308 QualType ArgType = CanTy;
2309 if (ConstArg)
2310 ArgType.addConst();
2311 if (VolatileArg)
2312 ArgType.addVolatile();
2313
2314 // This isn't /really/ specified by the standard, but it's implied
2315 // we should be working from an RValue in the case of move to ensure
2316 // that we prefer to bind to rvalue references, and an LValue in the
2317 // case of copy to ensure we don't bind to rvalue references.
2318 // Possibly an XValue is actually correct in the case of move, but
2319 // there is no semantic difference for class types in this restricted
2320 // case.
2321 ExprValueKind VK;
Alexis Hunt46d1ce22011-06-22 22:13:13 +00002322 if (SM == CXXCopyConstructor || SM == CXXCopyAssignment)
Alexis Hunteef8ee02011-06-10 03:50:41 +00002323 VK = VK_LValue;
2324 else
2325 VK = VK_RValue;
2326
2327 NumArgs = 1;
2328 Arg = new (Context) OpaqueValueExpr(SourceLocation(), ArgType, VK);
2329 }
2330
2331 // Create the object argument
2332 QualType ThisTy = CanTy;
2333 if (ConstThis)
2334 ThisTy.addConst();
2335 if (VolatileThis)
2336 ThisTy.addVolatile();
Alexis Hunt080709f2011-06-23 00:26:20 +00002337 Expr::Classification Classification =
Alexis Hunteef8ee02011-06-10 03:50:41 +00002338 (new (Context) OpaqueValueExpr(SourceLocation(), ThisTy,
2339 RValueThis ? VK_RValue : VK_LValue))->
2340 Classify(Context);
2341
2342 // Now we perform lookup on the name we computed earlier and do overload
2343 // resolution. Lookup is only performed directly into the class since there
2344 // will always be a (possibly implicit) declaration to shadow any others.
2345 OverloadCandidateSet OCS((SourceLocation()));
2346 DeclContext::lookup_iterator I, E;
2347 Result->setConstParamMatch(false);
2348
Alexis Hunt1da39282011-06-24 02:11:39 +00002349 llvm::tie(I, E) = RD->lookup(Name);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002350 assert((I != E) &&
2351 "lookup for a constructor or assignment operator was empty");
2352 for ( ; I != E; ++I) {
Alexis Hunt1da39282011-06-24 02:11:39 +00002353 Decl *Cand = *I;
Alexis Hunt080709f2011-06-23 00:26:20 +00002354
Alexis Hunt1da39282011-06-24 02:11:39 +00002355 if (Cand->isInvalidDecl())
Alexis Hunteef8ee02011-06-10 03:50:41 +00002356 continue;
2357
Alexis Hunt1da39282011-06-24 02:11:39 +00002358 if (UsingShadowDecl *U = dyn_cast<UsingShadowDecl>(Cand)) {
2359 // FIXME: [namespace.udecl]p15 says that we should only consider a
2360 // using declaration here if it does not match a declaration in the
2361 // derived class. We do not implement this correctly in other cases
2362 // either.
2363 Cand = U->getTargetDecl();
2364
2365 if (Cand->isInvalidDecl())
2366 continue;
2367 }
2368
2369 if (CXXMethodDecl *M = dyn_cast<CXXMethodDecl>(Cand)) {
Alexis Hunt080709f2011-06-23 00:26:20 +00002370 if (SM == CXXCopyAssignment || SM == CXXMoveAssignment)
Alexis Hunt1da39282011-06-24 02:11:39 +00002371 AddMethodCandidate(M, DeclAccessPair::make(M, AS_public), RD, ThisTy,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002372 Classification, llvm::makeArrayRef(&Arg, NumArgs),
2373 OCS, true);
Alexis Hunt080709f2011-06-23 00:26:20 +00002374 else
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002375 AddOverloadCandidate(M, DeclAccessPair::make(M, AS_public),
2376 llvm::makeArrayRef(&Arg, NumArgs), OCS, true);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002377
2378 // Here we're looking for a const parameter to speed up creation of
2379 // implicit copy methods.
2380 if ((SM == CXXCopyAssignment && M->isCopyAssignmentOperator()) ||
2381 (SM == CXXCopyConstructor &&
2382 cast<CXXConstructorDecl>(M)->isCopyConstructor())) {
2383 QualType ArgType = M->getType()->getAs<FunctionProtoType>()->getArgType(0);
Alexis Hunt491ec602011-06-21 23:42:56 +00002384 if (!ArgType->isReferenceType() ||
2385 ArgType->getPointeeType().isConstQualified())
Alexis Hunteef8ee02011-06-10 03:50:41 +00002386 Result->setConstParamMatch(true);
2387 }
Alexis Hunt2949f022011-06-22 02:58:46 +00002388 } else if (FunctionTemplateDecl *Tmpl =
Alexis Hunt1da39282011-06-24 02:11:39 +00002389 dyn_cast<FunctionTemplateDecl>(Cand)) {
Alexis Hunt080709f2011-06-23 00:26:20 +00002390 if (SM == CXXCopyAssignment || SM == CXXMoveAssignment)
2391 AddMethodTemplateCandidate(Tmpl, DeclAccessPair::make(Tmpl, AS_public),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002392 RD, 0, ThisTy, Classification,
2393 llvm::makeArrayRef(&Arg, NumArgs),
Alexis Hunt080709f2011-06-23 00:26:20 +00002394 OCS, true);
2395 else
2396 AddTemplateOverloadCandidate(Tmpl, DeclAccessPair::make(Tmpl, AS_public),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002397 0, llvm::makeArrayRef(&Arg, NumArgs),
2398 OCS, true);
Alexis Hunt1da39282011-06-24 02:11:39 +00002399 } else {
2400 assert(isa<UsingDecl>(Cand) && "illegal Kind of operator = Decl");
Alexis Hunteef8ee02011-06-10 03:50:41 +00002401 }
2402 }
2403
2404 OverloadCandidateSet::iterator Best;
2405 switch (OCS.BestViableFunction(*this, SourceLocation(), Best)) {
2406 case OR_Success:
2407 Result->setMethod(cast<CXXMethodDecl>(Best->Function));
2408 Result->setSuccess(true);
2409 break;
2410
2411 case OR_Deleted:
2412 Result->setMethod(cast<CXXMethodDecl>(Best->Function));
2413 Result->setSuccess(false);
2414 break;
2415
2416 case OR_Ambiguous:
2417 case OR_No_Viable_Function:
2418 Result->setMethod(0);
2419 Result->setSuccess(false);
2420 break;
2421 }
2422
2423 return Result;
2424}
2425
2426/// \brief Look up the default constructor for the given class.
2427CXXConstructorDecl *Sema::LookupDefaultConstructor(CXXRecordDecl *Class) {
Alexis Hunt899bd442011-06-10 04:44:37 +00002428 SpecialMemberOverloadResult *Result =
Alexis Hunteef8ee02011-06-10 03:50:41 +00002429 LookupSpecialMember(Class, CXXDefaultConstructor, false, false, false,
2430 false, false);
2431
2432 return cast_or_null<CXXConstructorDecl>(Result->getMethod());
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002433}
2434
Alexis Hunt491ec602011-06-21 23:42:56 +00002435/// \brief Look up the copying constructor for the given class.
2436CXXConstructorDecl *Sema::LookupCopyingConstructor(CXXRecordDecl *Class,
2437 unsigned Quals,
2438 bool *ConstParamMatch) {
Alexis Hunt899bd442011-06-10 04:44:37 +00002439 assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2440 "non-const, non-volatile qualifiers for copy ctor arg");
2441 SpecialMemberOverloadResult *Result =
2442 LookupSpecialMember(Class, CXXCopyConstructor, Quals & Qualifiers::Const,
2443 Quals & Qualifiers::Volatile, false, false, false);
2444
2445 if (ConstParamMatch)
2446 *ConstParamMatch = Result->hasConstParamMatch();
2447
2448 return cast_or_null<CXXConstructorDecl>(Result->getMethod());
2449}
2450
Sebastian Redl22653ba2011-08-30 19:58:05 +00002451/// \brief Look up the moving constructor for the given class.
2452CXXConstructorDecl *Sema::LookupMovingConstructor(CXXRecordDecl *Class) {
2453 SpecialMemberOverloadResult *Result =
2454 LookupSpecialMember(Class, CXXMoveConstructor, false,
2455 false, false, false, false);
2456
2457 return cast_or_null<CXXConstructorDecl>(Result->getMethod());
2458}
2459
Douglas Gregor52b72822010-07-02 23:12:18 +00002460/// \brief Look up the constructors for the given class.
2461DeclContext::lookup_result Sema::LookupConstructors(CXXRecordDecl *Class) {
Alexis Hunteef8ee02011-06-10 03:50:41 +00002462 // If the implicit constructors have not yet been declared, do so now.
Douglas Gregor9672f922010-07-03 00:47:00 +00002463 if (CanDeclareSpecialMemberFunction(Context, Class)) {
Alexis Huntea6f0322011-05-11 22:34:38 +00002464 if (Class->needsImplicitDefaultConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +00002465 DeclareImplicitDefaultConstructor(Class);
2466 if (!Class->hasDeclaredCopyConstructor())
2467 DeclareImplicitCopyConstructor(Class);
David Blaikiebbafb8a2012-03-11 07:00:24 +00002468 if (getLangOpts().CPlusPlus0x && Class->needsImplicitMoveConstructor())
Sebastian Redl22653ba2011-08-30 19:58:05 +00002469 DeclareImplicitMoveConstructor(Class);
Douglas Gregor9672f922010-07-03 00:47:00 +00002470 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002471
Douglas Gregor52b72822010-07-02 23:12:18 +00002472 CanQualType T = Context.getCanonicalType(Context.getTypeDeclType(Class));
2473 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(T);
2474 return Class->lookup(Name);
2475}
2476
Alexis Hunt491ec602011-06-21 23:42:56 +00002477/// \brief Look up the copying assignment operator for the given class.
2478CXXMethodDecl *Sema::LookupCopyingAssignment(CXXRecordDecl *Class,
2479 unsigned Quals, bool RValueThis,
2480 unsigned ThisQuals,
2481 bool *ConstParamMatch) {
2482 assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2483 "non-const, non-volatile qualifiers for copy assignment arg");
2484 assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2485 "non-const, non-volatile qualifiers for copy assignment this");
2486 SpecialMemberOverloadResult *Result =
2487 LookupSpecialMember(Class, CXXCopyAssignment, Quals & Qualifiers::Const,
2488 Quals & Qualifiers::Volatile, RValueThis,
2489 ThisQuals & Qualifiers::Const,
2490 ThisQuals & Qualifiers::Volatile);
2491
2492 if (ConstParamMatch)
2493 *ConstParamMatch = Result->hasConstParamMatch();
2494
2495 return Result->getMethod();
2496}
2497
Sebastian Redl22653ba2011-08-30 19:58:05 +00002498/// \brief Look up the moving assignment operator for the given class.
2499CXXMethodDecl *Sema::LookupMovingAssignment(CXXRecordDecl *Class,
2500 bool RValueThis,
2501 unsigned ThisQuals) {
2502 assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2503 "non-const, non-volatile qualifiers for copy assignment this");
2504 SpecialMemberOverloadResult *Result =
2505 LookupSpecialMember(Class, CXXMoveAssignment, false, false, RValueThis,
2506 ThisQuals & Qualifiers::Const,
2507 ThisQuals & Qualifiers::Volatile);
2508
2509 return Result->getMethod();
2510}
2511
Douglas Gregore71edda2010-07-01 22:47:18 +00002512/// \brief Look for the destructor of the given class.
2513///
Alexis Hunt967ea7c2011-06-03 21:10:40 +00002514/// During semantic analysis, this routine should be used in lieu of
2515/// CXXRecordDecl::getDestructor().
Douglas Gregore71edda2010-07-01 22:47:18 +00002516///
2517/// \returns The destructor for this class.
2518CXXDestructorDecl *Sema::LookupDestructor(CXXRecordDecl *Class) {
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002519 return cast<CXXDestructorDecl>(LookupSpecialMember(Class, CXXDestructor,
2520 false, false, false,
2521 false, false)->getMethod());
Douglas Gregore71edda2010-07-01 22:47:18 +00002522}
2523
Richard Smithbcc22fc2012-03-09 08:00:36 +00002524/// LookupLiteralOperator - Determine which literal operator should be used for
2525/// a user-defined literal, per C++11 [lex.ext].
2526///
2527/// Normal overload resolution is not used to select which literal operator to
2528/// call for a user-defined literal. Look up the provided literal operator name,
2529/// and filter the results to the appropriate set for the given argument types.
2530Sema::LiteralOperatorLookupResult
2531Sema::LookupLiteralOperator(Scope *S, LookupResult &R,
2532 ArrayRef<QualType> ArgTys,
2533 bool AllowRawAndTemplate) {
2534 LookupName(R, S);
2535 assert(R.getResultKind() != LookupResult::Ambiguous &&
2536 "literal operator lookup can't be ambiguous");
2537
2538 // Filter the lookup results appropriately.
2539 LookupResult::Filter F = R.makeFilter();
2540
2541 bool FoundTemplate = false;
2542 bool FoundRaw = false;
2543 bool FoundExactMatch = false;
2544
2545 while (F.hasNext()) {
2546 Decl *D = F.next();
2547 if (UsingShadowDecl *USD = dyn_cast<UsingShadowDecl>(D))
2548 D = USD->getTargetDecl();
2549
2550 bool IsTemplate = isa<FunctionTemplateDecl>(D);
2551 bool IsRaw = false;
2552 bool IsExactMatch = false;
2553
2554 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2555 if (FD->getNumParams() == 1 &&
2556 FD->getParamDecl(0)->getType()->getAs<PointerType>())
2557 IsRaw = true;
2558 else {
2559 IsExactMatch = true;
2560 for (unsigned ArgIdx = 0; ArgIdx != ArgTys.size(); ++ArgIdx) {
2561 QualType ParamTy = FD->getParamDecl(ArgIdx)->getType();
2562 if (!Context.hasSameUnqualifiedType(ArgTys[ArgIdx], ParamTy)) {
2563 IsExactMatch = false;
2564 break;
2565 }
2566 }
2567 }
2568 }
2569
2570 if (IsExactMatch) {
2571 FoundExactMatch = true;
2572 AllowRawAndTemplate = false;
2573 if (FoundRaw || FoundTemplate) {
2574 // Go through again and remove the raw and template decls we've
2575 // already found.
2576 F.restart();
2577 FoundRaw = FoundTemplate = false;
2578 }
2579 } else if (AllowRawAndTemplate && (IsTemplate || IsRaw)) {
2580 FoundTemplate |= IsTemplate;
2581 FoundRaw |= IsRaw;
2582 } else {
2583 F.erase();
2584 }
2585 }
2586
2587 F.done();
2588
2589 // C++11 [lex.ext]p3, p4: If S contains a literal operator with a matching
2590 // parameter type, that is used in preference to a raw literal operator
2591 // or literal operator template.
2592 if (FoundExactMatch)
2593 return LOLR_Cooked;
2594
2595 // C++11 [lex.ext]p3, p4: S shall contain a raw literal operator or a literal
2596 // operator template, but not both.
2597 if (FoundRaw && FoundTemplate) {
2598 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
2599 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2600 Decl *D = *I;
2601 if (UsingShadowDecl *USD = dyn_cast<UsingShadowDecl>(D))
2602 D = USD->getTargetDecl();
2603 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
2604 D = FunTmpl->getTemplatedDecl();
2605 NoteOverloadCandidate(cast<FunctionDecl>(D));
2606 }
2607 return LOLR_Error;
2608 }
2609
2610 if (FoundRaw)
2611 return LOLR_Raw;
2612
2613 if (FoundTemplate)
2614 return LOLR_Template;
2615
2616 // Didn't find anything we could use.
2617 Diag(R.getNameLoc(), diag::err_ovl_no_viable_literal_operator)
2618 << R.getLookupName() << (int)ArgTys.size() << ArgTys[0]
2619 << (ArgTys.size() == 2 ? ArgTys[1] : QualType()) << AllowRawAndTemplate;
2620 return LOLR_Error;
2621}
2622
John McCall8fe68082010-01-26 07:16:45 +00002623void ADLResult::insert(NamedDecl *New) {
2624 NamedDecl *&Old = Decls[cast<NamedDecl>(New->getCanonicalDecl())];
2625
2626 // If we haven't yet seen a decl for this key, or the last decl
2627 // was exactly this one, we're done.
2628 if (Old == 0 || Old == New) {
2629 Old = New;
2630 return;
2631 }
2632
2633 // Otherwise, decide which is a more recent redeclaration.
2634 FunctionDecl *OldFD, *NewFD;
2635 if (isa<FunctionTemplateDecl>(New)) {
2636 OldFD = cast<FunctionTemplateDecl>(Old)->getTemplatedDecl();
2637 NewFD = cast<FunctionTemplateDecl>(New)->getTemplatedDecl();
2638 } else {
2639 OldFD = cast<FunctionDecl>(Old);
2640 NewFD = cast<FunctionDecl>(New);
2641 }
2642
2643 FunctionDecl *Cursor = NewFD;
2644 while (true) {
Douglas Gregorec9fd132012-01-14 16:38:05 +00002645 Cursor = Cursor->getPreviousDecl();
John McCall8fe68082010-01-26 07:16:45 +00002646
2647 // If we got to the end without finding OldFD, OldFD is the newer
2648 // declaration; leave things as they are.
2649 if (!Cursor) return;
2650
2651 // If we do find OldFD, then NewFD is newer.
2652 if (Cursor == OldFD) break;
2653
2654 // Otherwise, keep looking.
2655 }
2656
2657 Old = New;
2658}
2659
Sebastian Redlc057f422009-10-23 19:23:15 +00002660void Sema::ArgumentDependentLookup(DeclarationName Name, bool Operator,
Richard Smithe06a2c12012-02-25 06:24:24 +00002661 SourceLocation Loc,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002662 llvm::ArrayRef<Expr *> Args,
Richard Smith02e85f32011-04-14 22:09:26 +00002663 ADLResult &Result,
2664 bool StdNamespaceIsAssociated) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002665 // Find all of the associated namespaces and classes based on the
2666 // arguments we have.
2667 AssociatedNamespaceSet AssociatedNamespaces;
2668 AssociatedClassSet AssociatedClasses;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002669 FindAssociatedClassesAndNamespaces(Args,
John McCallc7e8e792009-08-07 22:18:02 +00002670 AssociatedNamespaces,
2671 AssociatedClasses);
Richard Smith02e85f32011-04-14 22:09:26 +00002672 if (StdNamespaceIsAssociated && StdNamespace)
2673 AssociatedNamespaces.insert(getStdNamespace());
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002674
Sebastian Redlc057f422009-10-23 19:23:15 +00002675 QualType T1, T2;
2676 if (Operator) {
2677 T1 = Args[0]->getType();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002678 if (Args.size() >= 2)
Sebastian Redlc057f422009-10-23 19:23:15 +00002679 T2 = Args[1]->getType();
2680 }
2681
Richard Smithe06a2c12012-02-25 06:24:24 +00002682 // Try to complete all associated classes, in case they contain a
2683 // declaration of a friend function.
2684 for (AssociatedClassSet::iterator C = AssociatedClasses.begin(),
2685 CEnd = AssociatedClasses.end();
2686 C != CEnd; ++C)
2687 RequireCompleteType(Loc, Context.getRecordType(*C), 0);
2688
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002689 // C++ [basic.lookup.argdep]p3:
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002690 // Let X be the lookup set produced by unqualified lookup (3.4.1)
2691 // and let Y be the lookup set produced by argument dependent
2692 // lookup (defined as follows). If X contains [...] then Y is
2693 // empty. Otherwise Y is the set of declarations found in the
2694 // namespaces associated with the argument types as described
2695 // below. The set of declarations found by the lookup of the name
2696 // is the union of X and Y.
2697 //
2698 // Here, we compute Y and add its members to the overloaded
2699 // candidate set.
2700 for (AssociatedNamespaceSet::iterator NS = AssociatedNamespaces.begin(),
Mike Stump11289f42009-09-09 15:08:12 +00002701 NSEnd = AssociatedNamespaces.end();
2702 NS != NSEnd; ++NS) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002703 // When considering an associated namespace, the lookup is the
2704 // same as the lookup performed when the associated namespace is
2705 // used as a qualifier (3.4.3.2) except that:
2706 //
2707 // -- Any using-directives in the associated namespace are
2708 // ignored.
2709 //
John McCallc7e8e792009-08-07 22:18:02 +00002710 // -- Any namespace-scope friend functions declared in
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002711 // associated classes are visible within their respective
2712 // namespaces even if they are not visible during an ordinary
2713 // lookup (11.4).
2714 DeclContext::lookup_iterator I, E;
John McCalld1e9d832009-08-11 06:59:38 +00002715 for (llvm::tie(I, E) = (*NS)->lookup(Name); I != E; ++I) {
John McCall4c4c1df2010-01-26 03:27:55 +00002716 NamedDecl *D = *I;
John McCallaa74a0c2009-08-28 07:59:38 +00002717 // If the only declaration here is an ordinary friend, consider
2718 // it only if it was declared in an associated classes.
2719 if (D->getIdentifierNamespace() == Decl::IDNS_OrdinaryFriend) {
John McCalld1e9d832009-08-11 06:59:38 +00002720 DeclContext *LexDC = D->getLexicalDeclContext();
2721 if (!AssociatedClasses.count(cast<CXXRecordDecl>(LexDC)))
2722 continue;
2723 }
Mike Stump11289f42009-09-09 15:08:12 +00002724
John McCall91f61fc2010-01-26 06:04:06 +00002725 if (isa<UsingShadowDecl>(D))
2726 D = cast<UsingShadowDecl>(D)->getTargetDecl();
John McCall4c4c1df2010-01-26 03:27:55 +00002727
John McCall91f61fc2010-01-26 06:04:06 +00002728 if (isa<FunctionDecl>(D)) {
2729 if (Operator &&
2730 !IsAcceptableNonMemberOperatorCandidate(cast<FunctionDecl>(D),
2731 T1, T2, Context))
2732 continue;
John McCall8fe68082010-01-26 07:16:45 +00002733 } else if (!isa<FunctionTemplateDecl>(D))
2734 continue;
2735
2736 Result.insert(D);
Douglas Gregor6127ca42009-06-23 20:14:09 +00002737 }
2738 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002739}
Douglas Gregor2d435302009-12-30 17:04:44 +00002740
2741//----------------------------------------------------------------------------
2742// Search for all visible declarations.
2743//----------------------------------------------------------------------------
2744VisibleDeclConsumer::~VisibleDeclConsumer() { }
2745
2746namespace {
2747
2748class ShadowContextRAII;
2749
2750class VisibleDeclsRecord {
2751public:
2752 /// \brief An entry in the shadow map, which is optimized to store a
2753 /// single declaration (the common case) but can also store a list
2754 /// of declarations.
Chris Lattner83cfc7c2011-07-18 01:54:02 +00002755 typedef llvm::TinyPtrVector<NamedDecl*> ShadowMapEntry;
Douglas Gregor2d435302009-12-30 17:04:44 +00002756
2757private:
2758 /// \brief A mapping from declaration names to the declarations that have
2759 /// this name within a particular scope.
2760 typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
2761
2762 /// \brief A list of shadow maps, which is used to model name hiding.
2763 std::list<ShadowMap> ShadowMaps;
2764
2765 /// \brief The declaration contexts we have already visited.
2766 llvm::SmallPtrSet<DeclContext *, 8> VisitedContexts;
2767
2768 friend class ShadowContextRAII;
2769
2770public:
2771 /// \brief Determine whether we have already visited this context
2772 /// (and, if not, note that we are going to visit that context now).
2773 bool visitedContext(DeclContext *Ctx) {
2774 return !VisitedContexts.insert(Ctx);
2775 }
2776
Douglas Gregor39982192010-08-15 06:18:01 +00002777 bool alreadyVisitedContext(DeclContext *Ctx) {
2778 return VisitedContexts.count(Ctx);
2779 }
2780
Douglas Gregor2d435302009-12-30 17:04:44 +00002781 /// \brief Determine whether the given declaration is hidden in the
2782 /// current scope.
2783 ///
2784 /// \returns the declaration that hides the given declaration, or
2785 /// NULL if no such declaration exists.
2786 NamedDecl *checkHidden(NamedDecl *ND);
2787
2788 /// \brief Add a declaration to the current shadow map.
Chris Lattner83cfc7c2011-07-18 01:54:02 +00002789 void add(NamedDecl *ND) {
2790 ShadowMaps.back()[ND->getDeclName()].push_back(ND);
2791 }
Douglas Gregor2d435302009-12-30 17:04:44 +00002792};
2793
2794/// \brief RAII object that records when we've entered a shadow context.
2795class ShadowContextRAII {
2796 VisibleDeclsRecord &Visible;
2797
2798 typedef VisibleDeclsRecord::ShadowMap ShadowMap;
2799
2800public:
2801 ShadowContextRAII(VisibleDeclsRecord &Visible) : Visible(Visible) {
2802 Visible.ShadowMaps.push_back(ShadowMap());
2803 }
2804
2805 ~ShadowContextRAII() {
Douglas Gregor2d435302009-12-30 17:04:44 +00002806 Visible.ShadowMaps.pop_back();
2807 }
2808};
2809
2810} // end anonymous namespace
2811
Douglas Gregor2d435302009-12-30 17:04:44 +00002812NamedDecl *VisibleDeclsRecord::checkHidden(NamedDecl *ND) {
Douglas Gregor0235c422010-01-14 00:06:47 +00002813 // Look through using declarations.
2814 ND = ND->getUnderlyingDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002815
Douglas Gregor2d435302009-12-30 17:04:44 +00002816 unsigned IDNS = ND->getIdentifierNamespace();
2817 std::list<ShadowMap>::reverse_iterator SM = ShadowMaps.rbegin();
2818 for (std::list<ShadowMap>::reverse_iterator SMEnd = ShadowMaps.rend();
2819 SM != SMEnd; ++SM) {
2820 ShadowMap::iterator Pos = SM->find(ND->getDeclName());
2821 if (Pos == SM->end())
2822 continue;
2823
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002824 for (ShadowMapEntry::iterator I = Pos->second.begin(),
Douglas Gregor2d435302009-12-30 17:04:44 +00002825 IEnd = Pos->second.end();
2826 I != IEnd; ++I) {
2827 // A tag declaration does not hide a non-tag declaration.
John McCalle87beb22010-04-23 18:46:30 +00002828 if ((*I)->hasTagIdentifierNamespace() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002829 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
Douglas Gregor2d435302009-12-30 17:04:44 +00002830 Decl::IDNS_ObjCProtocol)))
2831 continue;
2832
2833 // Protocols are in distinct namespaces from everything else.
2834 if ((((*I)->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
2835 || (IDNS & Decl::IDNS_ObjCProtocol)) &&
2836 (*I)->getIdentifierNamespace() != IDNS)
2837 continue;
2838
Douglas Gregor09bbc652010-01-14 15:47:35 +00002839 // Functions and function templates in the same scope overload
2840 // rather than hide. FIXME: Look for hiding based on function
2841 // signatures!
Douglas Gregor200c99d2010-01-14 03:35:48 +00002842 if ((*I)->isFunctionOrFunctionTemplate() &&
Douglas Gregor09bbc652010-01-14 15:47:35 +00002843 ND->isFunctionOrFunctionTemplate() &&
2844 SM == ShadowMaps.rbegin())
Douglas Gregor200c99d2010-01-14 03:35:48 +00002845 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002846
Douglas Gregor2d435302009-12-30 17:04:44 +00002847 // We've found a declaration that hides this one.
2848 return *I;
2849 }
2850 }
2851
2852 return 0;
2853}
2854
2855static void LookupVisibleDecls(DeclContext *Ctx, LookupResult &Result,
2856 bool QualifiedNameLookup,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002857 bool InBaseClass,
Douglas Gregor2d435302009-12-30 17:04:44 +00002858 VisibleDeclConsumer &Consumer,
2859 VisibleDeclsRecord &Visited) {
Douglas Gregor0c8a1722010-02-04 23:42:48 +00002860 if (!Ctx)
2861 return;
2862
Douglas Gregor2d435302009-12-30 17:04:44 +00002863 // Make sure we don't visit the same context twice.
2864 if (Visited.visitedContext(Ctx->getPrimaryContext()))
2865 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002866
Douglas Gregor7454c562010-07-02 20:37:36 +00002867 if (CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(Ctx))
2868 Result.getSema().ForceDeclarationOfImplicitMembers(Class);
2869
Douglas Gregor2d435302009-12-30 17:04:44 +00002870 // Enumerate all of the results in this context.
Douglas Gregore57e7522012-01-07 09:11:48 +00002871 llvm::SmallVector<DeclContext *, 2> Contexts;
2872 Ctx->collectAllContexts(Contexts);
2873 for (unsigned I = 0, N = Contexts.size(); I != N; ++I) {
2874 DeclContext *CurCtx = Contexts[I];
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002875 for (DeclContext::decl_iterator D = CurCtx->decls_begin(),
Douglas Gregor2d435302009-12-30 17:04:44 +00002876 DEnd = CurCtx->decls_end();
2877 D != DEnd; ++D) {
Douglas Gregora3b23b02010-12-09 21:44:02 +00002878 if (NamedDecl *ND = dyn_cast<NamedDecl>(*D)) {
Douglas Gregor4a814562011-12-14 16:03:29 +00002879 if ((ND = Result.getAcceptableDecl(ND))) {
Erik Verbruggen2e657ff2011-10-06 07:27:49 +00002880 Consumer.FoundDecl(ND, Visited.checkHidden(ND), Ctx, InBaseClass);
Douglas Gregor2d435302009-12-30 17:04:44 +00002881 Visited.add(ND);
2882 }
Douglas Gregora3b23b02010-12-09 21:44:02 +00002883 }
Douglas Gregor04246572011-02-16 01:39:26 +00002884
Sebastian Redlbd595762010-08-31 20:53:31 +00002885 // Visit transparent contexts and inline namespaces inside this context.
Douglas Gregor2d435302009-12-30 17:04:44 +00002886 if (DeclContext *InnerCtx = dyn_cast<DeclContext>(*D)) {
Sebastian Redlbd595762010-08-31 20:53:31 +00002887 if (InnerCtx->isTransparentContext() || InnerCtx->isInlineNamespace())
Douglas Gregor09bbc652010-01-14 15:47:35 +00002888 LookupVisibleDecls(InnerCtx, Result, QualifiedNameLookup, InBaseClass,
Douglas Gregor2d435302009-12-30 17:04:44 +00002889 Consumer, Visited);
2890 }
2891 }
2892 }
2893
2894 // Traverse using directives for qualified name lookup.
2895 if (QualifiedNameLookup) {
2896 ShadowContextRAII Shadow(Visited);
2897 DeclContext::udir_iterator I, E;
2898 for (llvm::tie(I, E) = Ctx->getUsingDirectives(); I != E; ++I) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002899 LookupVisibleDecls((*I)->getNominatedNamespace(), Result,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002900 QualifiedNameLookup, InBaseClass, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00002901 }
2902 }
2903
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002904 // Traverse the contexts of inherited C++ classes.
Douglas Gregor2d435302009-12-30 17:04:44 +00002905 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) {
John McCall67da35c2010-02-04 22:26:26 +00002906 if (!Record->hasDefinition())
2907 return;
2908
Douglas Gregor2d435302009-12-30 17:04:44 +00002909 for (CXXRecordDecl::base_class_iterator B = Record->bases_begin(),
2910 BEnd = Record->bases_end();
2911 B != BEnd; ++B) {
2912 QualType BaseType = B->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002913
Douglas Gregor2d435302009-12-30 17:04:44 +00002914 // Don't look into dependent bases, because name lookup can't look
2915 // there anyway.
2916 if (BaseType->isDependentType())
2917 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002918
Douglas Gregor2d435302009-12-30 17:04:44 +00002919 const RecordType *Record = BaseType->getAs<RecordType>();
2920 if (!Record)
2921 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002922
Douglas Gregor2d435302009-12-30 17:04:44 +00002923 // FIXME: It would be nice to be able to determine whether referencing
2924 // a particular member would be ambiguous. For example, given
2925 //
2926 // struct A { int member; };
2927 // struct B { int member; };
2928 // struct C : A, B { };
2929 //
2930 // void f(C *c) { c->### }
2931 //
2932 // accessing 'member' would result in an ambiguity. However, we
2933 // could be smart enough to qualify the member with the base
2934 // class, e.g.,
2935 //
2936 // c->B::member
2937 //
2938 // or
2939 //
2940 // c->A::member
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002941
Douglas Gregor2d435302009-12-30 17:04:44 +00002942 // Find results in this base class (and its bases).
2943 ShadowContextRAII Shadow(Visited);
2944 LookupVisibleDecls(Record->getDecl(), Result, QualifiedNameLookup,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002945 true, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00002946 }
2947 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002948
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002949 // Traverse the contexts of Objective-C classes.
2950 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Ctx)) {
2951 // Traverse categories.
2952 for (ObjCCategoryDecl *Category = IFace->getCategoryList();
2953 Category; Category = Category->getNextClassCategory()) {
2954 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002955 LookupVisibleDecls(Category, Result, QualifiedNameLookup, false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002956 Consumer, Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002957 }
2958
2959 // Traverse protocols.
Ted Kremenek0ef508d2010-09-01 01:21:15 +00002960 for (ObjCInterfaceDecl::all_protocol_iterator
2961 I = IFace->all_referenced_protocol_begin(),
2962 E = IFace->all_referenced_protocol_end(); I != E; ++I) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002963 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002964 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002965 Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002966 }
2967
2968 // Traverse the superclass.
2969 if (IFace->getSuperClass()) {
2970 ShadowContextRAII Shadow(Visited);
2971 LookupVisibleDecls(IFace->getSuperClass(), Result, QualifiedNameLookup,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002972 true, Consumer, Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002973 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002974
Douglas Gregor0b59e802010-04-19 18:02:19 +00002975 // If there is an implementation, traverse it. We do this to find
2976 // synthesized ivars.
2977 if (IFace->getImplementation()) {
2978 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002979 LookupVisibleDecls(IFace->getImplementation(), Result,
Douglas Gregor0b59e802010-04-19 18:02:19 +00002980 QualifiedNameLookup, true, Consumer, Visited);
2981 }
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002982 } else if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Ctx)) {
2983 for (ObjCProtocolDecl::protocol_iterator I = Protocol->protocol_begin(),
2984 E = Protocol->protocol_end(); I != E; ++I) {
2985 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002986 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002987 Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002988 }
2989 } else if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Ctx)) {
2990 for (ObjCCategoryDecl::protocol_iterator I = Category->protocol_begin(),
2991 E = Category->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 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002996
Douglas Gregor0b59e802010-04-19 18:02:19 +00002997 // If there is an implementation, traverse it.
2998 if (Category->getImplementation()) {
2999 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003000 LookupVisibleDecls(Category->getImplementation(), Result,
Douglas Gregor0b59e802010-04-19 18:02:19 +00003001 QualifiedNameLookup, true, Consumer, Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003002 }
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003003 }
Douglas Gregor2d435302009-12-30 17:04:44 +00003004}
3005
3006static void LookupVisibleDecls(Scope *S, LookupResult &Result,
3007 UnqualUsingDirectiveSet &UDirs,
3008 VisibleDeclConsumer &Consumer,
3009 VisibleDeclsRecord &Visited) {
3010 if (!S)
3011 return;
3012
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003013 if (!S->getEntity() ||
3014 (!S->getParent() &&
Douglas Gregor39982192010-08-15 06:18:01 +00003015 !Visited.alreadyVisitedContext((DeclContext *)S->getEntity())) ||
Douglas Gregor712dcfe2010-01-07 00:31:29 +00003016 ((DeclContext *)S->getEntity())->isFunctionOrMethod()) {
3017 // Walk through the declarations in this Scope.
3018 for (Scope::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
3019 D != DEnd; ++D) {
John McCall48871652010-08-21 09:40:31 +00003020 if (NamedDecl *ND = dyn_cast<NamedDecl>(*D))
Douglas Gregor4a814562011-12-14 16:03:29 +00003021 if ((ND = Result.getAcceptableDecl(ND))) {
Erik Verbruggen2e657ff2011-10-06 07:27:49 +00003022 Consumer.FoundDecl(ND, Visited.checkHidden(ND), 0, false);
Douglas Gregor712dcfe2010-01-07 00:31:29 +00003023 Visited.add(ND);
3024 }
3025 }
3026 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003027
Douglas Gregor66230062010-03-15 14:33:29 +00003028 // FIXME: C++ [temp.local]p8
Douglas Gregor2d435302009-12-30 17:04:44 +00003029 DeclContext *Entity = 0;
Douglas Gregor4f248632010-01-01 17:44:25 +00003030 if (S->getEntity()) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003031 // Look into this scope's declaration context, along with any of its
3032 // parent lookup contexts (e.g., enclosing classes), up to the point
3033 // where we hit the context stored in the next outer scope.
3034 Entity = (DeclContext *)S->getEntity();
Douglas Gregor66230062010-03-15 14:33:29 +00003035 DeclContext *OuterCtx = findOuterContext(S).first; // FIXME
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003036
Douglas Gregorea166062010-03-15 15:26:48 +00003037 for (DeclContext *Ctx = Entity; Ctx && !Ctx->Equals(OuterCtx);
Douglas Gregor2d435302009-12-30 17:04:44 +00003038 Ctx = Ctx->getLookupParent()) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003039 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
3040 if (Method->isInstanceMethod()) {
3041 // For instance methods, look for ivars in the method's interface.
3042 LookupResult IvarResult(Result.getSema(), Result.getLookupName(),
3043 Result.getNameLoc(), Sema::LookupMemberName);
Douglas Gregor05fcf842010-11-02 20:36:02 +00003044 if (ObjCInterfaceDecl *IFace = Method->getClassInterface()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003045 LookupVisibleDecls(IFace, IvarResult, /*QualifiedNameLookup=*/false,
Fariborz Jahanian97d744b2011-08-31 22:24:06 +00003046 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor05fcf842010-11-02 20:36:02 +00003047 }
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003048 }
3049
3050 // We've already performed all of the name lookup that we need
3051 // to for Objective-C methods; the next context will be the
3052 // outer scope.
3053 break;
3054 }
3055
Douglas Gregor2d435302009-12-30 17:04:44 +00003056 if (Ctx->isFunctionOrMethod())
3057 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003058
3059 LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003060 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00003061 }
3062 } else if (!S->getParent()) {
3063 // Look into the translation unit scope. We walk through the translation
3064 // unit's declaration context, because the Scope itself won't have all of
3065 // the declarations if we loaded a precompiled header.
3066 // FIXME: We would like the translation unit's Scope object to point to the
3067 // translation unit, so we don't need this special "if" branch. However,
3068 // doing so would force the normal C++ name-lookup code to look into the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003069 // translation unit decl when the IdentifierInfo chains would suffice.
Douglas Gregor2d435302009-12-30 17:04:44 +00003070 // Once we fix that problem (which is part of a more general "don't look
Douglas Gregor712dcfe2010-01-07 00:31:29 +00003071 // in DeclContexts unless we have to" optimization), we can eliminate this.
Douglas Gregor2d435302009-12-30 17:04:44 +00003072 Entity = Result.getSema().Context.getTranslationUnitDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003073 LookupVisibleDecls(Entity, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003074 /*InBaseClass=*/false, Consumer, Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003075 }
3076
Douglas Gregor2d435302009-12-30 17:04:44 +00003077 if (Entity) {
3078 // Lookup visible declarations in any namespaces found by using
3079 // directives.
3080 UnqualUsingDirectiveSet::const_iterator UI, UEnd;
3081 llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(Entity);
3082 for (; UI != UEnd; ++UI)
3083 LookupVisibleDecls(const_cast<DeclContext *>(UI->getNominatedNamespace()),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003084 Result, /*QualifiedNameLookup=*/false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003085 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00003086 }
3087
3088 // Lookup names in the parent scope.
3089 ShadowContextRAII Shadow(Visited);
3090 LookupVisibleDecls(S->getParent(), Result, UDirs, Consumer, Visited);
3091}
3092
3093void Sema::LookupVisibleDecls(Scope *S, LookupNameKind Kind,
Douglas Gregor39982192010-08-15 06:18:01 +00003094 VisibleDeclConsumer &Consumer,
3095 bool IncludeGlobalScope) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003096 // Determine the set of using directives available during
3097 // unqualified name lookup.
3098 Scope *Initial = S;
3099 UnqualUsingDirectiveSet UDirs;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003100 if (getLangOpts().CPlusPlus) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003101 // Find the first namespace or translation-unit scope.
3102 while (S && !isNamespaceOrTranslationUnitScope(S))
3103 S = S->getParent();
3104
3105 UDirs.visitScopeChain(Initial, S);
3106 }
3107 UDirs.done();
3108
3109 // Look for visible declarations.
3110 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
3111 VisibleDeclsRecord Visited;
Douglas Gregor39982192010-08-15 06:18:01 +00003112 if (!IncludeGlobalScope)
3113 Visited.visitedContext(Context.getTranslationUnitDecl());
Douglas Gregor2d435302009-12-30 17:04:44 +00003114 ShadowContextRAII Shadow(Visited);
3115 ::LookupVisibleDecls(Initial, Result, UDirs, Consumer, Visited);
3116}
3117
3118void Sema::LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
Douglas Gregor39982192010-08-15 06:18:01 +00003119 VisibleDeclConsumer &Consumer,
3120 bool IncludeGlobalScope) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003121 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
3122 VisibleDeclsRecord Visited;
Douglas Gregor39982192010-08-15 06:18:01 +00003123 if (!IncludeGlobalScope)
3124 Visited.visitedContext(Context.getTranslationUnitDecl());
Douglas Gregor2d435302009-12-30 17:04:44 +00003125 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003126 ::LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/true,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003127 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00003128}
3129
Chris Lattner43e7f312011-02-18 02:08:43 +00003130/// LookupOrCreateLabel - Do a name lookup of a label with the specified name.
Abramo Bagnara1c3af962011-03-05 18:21:20 +00003131/// If GnuLabelLoc is a valid source location, then this is a definition
3132/// of an __label__ label name, otherwise it is a normal label definition
3133/// or use.
Chris Lattner43e7f312011-02-18 02:08:43 +00003134LabelDecl *Sema::LookupOrCreateLabel(IdentifierInfo *II, SourceLocation Loc,
Abramo Bagnara1c3af962011-03-05 18:21:20 +00003135 SourceLocation GnuLabelLoc) {
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003136 // Do a lookup to see if we have a label with this name already.
Chris Lattner43e7f312011-02-18 02:08:43 +00003137 NamedDecl *Res = 0;
Abramo Bagnara1c3af962011-03-05 18:21:20 +00003138
3139 if (GnuLabelLoc.isValid()) {
3140 // Local label definitions always shadow existing labels.
3141 Res = LabelDecl::Create(Context, CurContext, Loc, II, GnuLabelLoc);
3142 Scope *S = CurScope;
3143 PushOnScopeChains(Res, S, true);
3144 return cast<LabelDecl>(Res);
3145 }
3146
3147 // Not a GNU local label.
3148 Res = LookupSingleName(CurScope, II, Loc, LookupLabel, NotForRedeclaration);
3149 // If we found a label, check to see if it is in the same context as us.
3150 // When in a Block, we don't want to reuse a label in an enclosing function.
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003151 if (Res && Res->getDeclContext() != CurContext)
3152 Res = 0;
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003153 if (Res == 0) {
3154 // If not forward referenced or defined already, create the backing decl.
Abramo Bagnara1c3af962011-03-05 18:21:20 +00003155 Res = LabelDecl::Create(Context, CurContext, Loc, II);
3156 Scope *S = CurScope->getFnParent();
Chris Lattner9ba479b2011-02-18 21:16:39 +00003157 assert(S && "Not in a function?");
3158 PushOnScopeChains(Res, S, true);
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003159 }
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003160 return cast<LabelDecl>(Res);
3161}
3162
3163//===----------------------------------------------------------------------===//
Douglas Gregor2d435302009-12-30 17:04:44 +00003164// Typo correction
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003165//===----------------------------------------------------------------------===//
Douglas Gregor2d435302009-12-30 17:04:44 +00003166
3167namespace {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003168
3169typedef llvm::StringMap<TypoCorrection, llvm::BumpPtrAllocator> TypoResultsMap;
Douglas Gregor29cdc6b2011-06-28 16:44:39 +00003170typedef std::map<unsigned, TypoResultsMap *> TypoEditDistanceMap;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003171
3172static const unsigned MaxTypoDistanceResultSets = 5;
3173
Douglas Gregor2d435302009-12-30 17:04:44 +00003174class TypoCorrectionConsumer : public VisibleDeclConsumer {
3175 /// \brief The name written that is a typo in the source.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003176 StringRef Typo;
Douglas Gregor2d435302009-12-30 17:04:44 +00003177
3178 /// \brief The results found that have the smallest edit distance
3179 /// found (so far) with the typo name.
Douglas Gregor0afa7f62010-10-14 20:34:08 +00003180 ///
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003181 /// The pointer value being set to the current DeclContext indicates
3182 /// whether there is a keyword with this name.
3183 TypoEditDistanceMap BestResults;
Douglas Gregor2d435302009-12-30 17:04:44 +00003184
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003185 Sema &SemaRef;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003186
Douglas Gregor2d435302009-12-30 17:04:44 +00003187public:
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003188 explicit TypoCorrectionConsumer(Sema &SemaRef, IdentifierInfo *Typo)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003189 : Typo(Typo->getName()),
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003190 SemaRef(SemaRef) { }
Douglas Gregor2d435302009-12-30 17:04:44 +00003191
Douglas Gregor29cdc6b2011-06-28 16:44:39 +00003192 ~TypoCorrectionConsumer() {
3193 for (TypoEditDistanceMap::iterator I = BestResults.begin(),
3194 IEnd = BestResults.end();
3195 I != IEnd;
3196 ++I)
3197 delete I->second;
3198 }
3199
Erik Verbruggen2e657ff2011-10-06 07:27:49 +00003200 virtual void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, DeclContext *Ctx,
3201 bool InBaseClass);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003202 void FoundName(StringRef Name);
3203 void addKeywordResult(StringRef Keyword);
3204 void addName(StringRef Name, NamedDecl *ND, unsigned Distance,
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00003205 NestedNameSpecifier *NNS=NULL, bool isKeyword=false);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003206 void addCorrection(TypoCorrection Correction);
Douglas Gregor2d435302009-12-30 17:04:44 +00003207
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003208 typedef TypoResultsMap::iterator result_iterator;
3209 typedef TypoEditDistanceMap::iterator distance_iterator;
3210 distance_iterator begin() { return BestResults.begin(); }
3211 distance_iterator end() { return BestResults.end(); }
3212 void erase(distance_iterator I) { BestResults.erase(I); }
Douglas Gregor0afa7f62010-10-14 20:34:08 +00003213 unsigned size() const { return BestResults.size(); }
3214 bool empty() const { return BestResults.empty(); }
Douglas Gregor2d435302009-12-30 17:04:44 +00003215
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003216 TypoCorrection &operator[](StringRef Name) {
Douglas Gregor29cdc6b2011-06-28 16:44:39 +00003217 return (*BestResults.begin()->second)[Name];
Douglas Gregoraf9eb592010-10-15 13:35:25 +00003218 }
3219
Kaelyn Uhrain0a16a8e2012-02-14 18:56:48 +00003220 unsigned getBestEditDistance(bool Normalized) {
3221 if (BestResults.empty())
3222 return (std::numeric_limits<unsigned>::max)();
3223
3224 unsigned BestED = BestResults.begin()->first;
3225 return Normalized ? TypoCorrection::NormalizeEditDistance(BestED) : BestED;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003226 }
Douglas Gregor2d435302009-12-30 17:04:44 +00003227};
3228
3229}
3230
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003231void TypoCorrectionConsumer::FoundDecl(NamedDecl *ND, NamedDecl *Hiding,
Erik Verbruggen2e657ff2011-10-06 07:27:49 +00003232 DeclContext *Ctx, bool InBaseClass) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003233 // Don't consider hidden names for typo correction.
3234 if (Hiding)
3235 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003236
Douglas Gregor2d435302009-12-30 17:04:44 +00003237 // Only consider entities with identifiers for names, ignoring
3238 // special names (constructors, overloaded operators, selectors,
3239 // etc.).
3240 IdentifierInfo *Name = ND->getIdentifier();
3241 if (!Name)
3242 return;
3243
Douglas Gregor57756ea2010-10-14 22:11:03 +00003244 FoundName(Name->getName());
3245}
3246
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003247void TypoCorrectionConsumer::FoundName(StringRef Name) {
Douglas Gregor93910a52010-10-19 19:39:10 +00003248 // Use a simple length-based heuristic to determine the minimum possible
3249 // edit distance. If the minimum isn't good enough, bail out early.
3250 unsigned MinED = abs((int)Name.size() - (int)Typo.size());
Kaelyn Uhrain1c75d402012-02-07 01:32:58 +00003251 if (MinED && Typo.size() / MinED < 3)
Douglas Gregor93910a52010-10-19 19:39:10 +00003252 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003253
Douglas Gregorc1fb15e2010-10-19 22:14:33 +00003254 // Compute an upper bound on the allowable edit distance, so that the
3255 // edit-distance algorithm can short-circuit.
Kaelyn Uhrain1c75d402012-02-07 01:32:58 +00003256 unsigned UpperBound = (Typo.size() + 2) / 3;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003257
Douglas Gregor2d435302009-12-30 17:04:44 +00003258 // Compute the edit distance between the typo and the name of this
Kaelyn Uhrain1c75d402012-02-07 01:32:58 +00003259 // entity, and add the identifier to the list of results.
3260 addName(Name, NULL, Typo.edit_distance(Name, true, UpperBound));
Douglas Gregor2d435302009-12-30 17:04:44 +00003261}
3262
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003263void TypoCorrectionConsumer::addKeywordResult(StringRef Keyword) {
Kaelyn Uhrain1c75d402012-02-07 01:32:58 +00003264 // Compute the edit distance between the typo and this keyword,
3265 // and add the keyword to the list of results.
3266 addName(Keyword, NULL, Typo.edit_distance(Keyword), NULL, true);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003267}
3268
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003269void TypoCorrectionConsumer::addName(StringRef Name,
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003270 NamedDecl *ND,
3271 unsigned Distance,
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00003272 NestedNameSpecifier *NNS,
3273 bool isKeyword) {
3274 TypoCorrection TC(&SemaRef.Context.Idents.get(Name), ND, NNS, Distance);
3275 if (isKeyword) TC.makeKeyword();
3276 addCorrection(TC);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003277}
3278
3279void TypoCorrectionConsumer::addCorrection(TypoCorrection Correction) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003280 StringRef Name = Correction.getCorrectionAsIdentifierInfo()->getName();
Kaelyn Uhrain0a16a8e2012-02-14 18:56:48 +00003281 TypoResultsMap *& Map = BestResults[Correction.getEditDistance(false)];
Douglas Gregor29cdc6b2011-06-28 16:44:39 +00003282 if (!Map)
3283 Map = new TypoResultsMap;
Chandler Carruth7d85c9b2011-06-28 22:48:40 +00003284
3285 TypoCorrection &CurrentCorrection = (*Map)[Name];
3286 if (!CurrentCorrection ||
3287 // FIXME: The following should be rolled up into an operator< on
3288 // TypoCorrection with a more principled definition.
3289 CurrentCorrection.isKeyword() < Correction.isKeyword() ||
David Blaikiebbafb8a2012-03-11 07:00:24 +00003290 Correction.getAsString(SemaRef.getLangOpts()) <
3291 CurrentCorrection.getAsString(SemaRef.getLangOpts()))
Chandler Carruth7d85c9b2011-06-28 22:48:40 +00003292 CurrentCorrection = Correction;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003293
3294 while (BestResults.size() > MaxTypoDistanceResultSets) {
Douglas Gregor29cdc6b2011-06-28 16:44:39 +00003295 TypoEditDistanceMap::iterator Last = BestResults.end();
3296 --Last;
3297 delete Last->second;
3298 BestResults.erase(Last);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003299 }
3300}
3301
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003302// Fill the supplied vector with the IdentifierInfo pointers for each piece of
3303// the given NestedNameSpecifier (i.e. given a NestedNameSpecifier "foo::bar::",
3304// fill the vector with the IdentifierInfo pointers for "foo" and "bar").
3305static void getNestedNameSpecifierIdentifiers(
3306 NestedNameSpecifier *NNS,
3307 SmallVectorImpl<const IdentifierInfo*> &Identifiers) {
3308 if (NestedNameSpecifier *Prefix = NNS->getPrefix())
3309 getNestedNameSpecifierIdentifiers(Prefix, Identifiers);
3310 else
3311 Identifiers.clear();
3312
3313 const IdentifierInfo *II = NULL;
3314
3315 switch (NNS->getKind()) {
3316 case NestedNameSpecifier::Identifier:
3317 II = NNS->getAsIdentifier();
3318 break;
3319
3320 case NestedNameSpecifier::Namespace:
3321 if (NNS->getAsNamespace()->isAnonymousNamespace())
3322 return;
3323 II = NNS->getAsNamespace()->getIdentifier();
3324 break;
3325
3326 case NestedNameSpecifier::NamespaceAlias:
3327 II = NNS->getAsNamespaceAlias()->getIdentifier();
3328 break;
3329
3330 case NestedNameSpecifier::TypeSpecWithTemplate:
3331 case NestedNameSpecifier::TypeSpec:
3332 II = QualType(NNS->getAsType(), 0).getBaseTypeIdentifier();
3333 break;
3334
3335 case NestedNameSpecifier::Global:
3336 return;
3337 }
3338
3339 if (II)
3340 Identifiers.push_back(II);
3341}
3342
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003343namespace {
3344
3345class SpecifierInfo {
3346 public:
3347 DeclContext* DeclCtx;
3348 NestedNameSpecifier* NameSpecifier;
3349 unsigned EditDistance;
3350
3351 SpecifierInfo(DeclContext *Ctx, NestedNameSpecifier *NNS, unsigned ED)
3352 : DeclCtx(Ctx), NameSpecifier(NNS), EditDistance(ED) {}
3353};
3354
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003355typedef SmallVector<DeclContext*, 4> DeclContextList;
3356typedef SmallVector<SpecifierInfo, 16> SpecifierInfoList;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003357
3358class NamespaceSpecifierSet {
3359 ASTContext &Context;
3360 DeclContextList CurContextChain;
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003361 SmallVector<const IdentifierInfo*, 4> CurContextIdentifiers;
3362 SmallVector<const IdentifierInfo*, 4> CurNameSpecifierIdentifiers;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003363 bool isSorted;
3364
3365 SpecifierInfoList Specifiers;
3366 llvm::SmallSetVector<unsigned, 4> Distances;
3367 llvm::DenseMap<unsigned, SpecifierInfoList> DistanceMap;
3368
3369 /// \brief Helper for building the list of DeclContexts between the current
3370 /// context and the top of the translation unit
3371 static DeclContextList BuildContextChain(DeclContext *Start);
3372
3373 void SortNamespaces();
3374
3375 public:
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003376 NamespaceSpecifierSet(ASTContext &Context, DeclContext *CurContext,
3377 CXXScopeSpec *CurScopeSpec)
Benjamin Kramerde1d6232011-07-05 09:46:31 +00003378 : Context(Context), CurContextChain(BuildContextChain(CurContext)),
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003379 isSorted(true) {
3380 if (CurScopeSpec && CurScopeSpec->getScopeRep())
3381 getNestedNameSpecifierIdentifiers(CurScopeSpec->getScopeRep(),
3382 CurNameSpecifierIdentifiers);
3383 // Build the list of identifiers that would be used for an absolute
3384 // (from the global context) NestedNameSpecifier refering to the current
3385 // context.
3386 for (DeclContextList::reverse_iterator C = CurContextChain.rbegin(),
3387 CEnd = CurContextChain.rend();
3388 C != CEnd; ++C) {
3389 if (NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(*C))
3390 CurContextIdentifiers.push_back(ND->getIdentifier());
3391 }
3392 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003393
3394 /// \brief Add the namespace to the set, computing the corresponding
3395 /// NestedNameSpecifier and its distance in the process.
3396 void AddNamespace(NamespaceDecl *ND);
3397
3398 typedef SpecifierInfoList::iterator iterator;
3399 iterator begin() {
3400 if (!isSorted) SortNamespaces();
3401 return Specifiers.begin();
3402 }
3403 iterator end() { return Specifiers.end(); }
3404};
3405
3406}
3407
3408DeclContextList NamespaceSpecifierSet::BuildContextChain(DeclContext *Start) {
Chandler Carruthb198e5a2011-06-28 21:43:34 +00003409 assert(Start && "Bulding a context chain from a null context");
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003410 DeclContextList Chain;
3411 for (DeclContext *DC = Start->getPrimaryContext(); DC != NULL;
3412 DC = DC->getLookupParent()) {
3413 NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(DC);
3414 if (!DC->isInlineNamespace() && !DC->isTransparentContext() &&
3415 !(ND && ND->isAnonymousNamespace()))
3416 Chain.push_back(DC->getPrimaryContext());
3417 }
3418 return Chain;
3419}
3420
3421void NamespaceSpecifierSet::SortNamespaces() {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003422 SmallVector<unsigned, 4> sortedDistances;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003423 sortedDistances.append(Distances.begin(), Distances.end());
3424
3425 if (sortedDistances.size() > 1)
3426 std::sort(sortedDistances.begin(), sortedDistances.end());
3427
3428 Specifiers.clear();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003429 for (SmallVector<unsigned, 4>::iterator DI = sortedDistances.begin(),
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003430 DIEnd = sortedDistances.end();
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003431 DI != DIEnd; ++DI) {
3432 SpecifierInfoList &SpecList = DistanceMap[*DI];
3433 Specifiers.append(SpecList.begin(), SpecList.end());
3434 }
3435
3436 isSorted = true;
3437}
3438
3439void NamespaceSpecifierSet::AddNamespace(NamespaceDecl *ND) {
Chandler Carruthb198e5a2011-06-28 21:43:34 +00003440 DeclContext *Ctx = cast<DeclContext>(ND);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003441 NestedNameSpecifier *NNS = NULL;
3442 unsigned NumSpecifiers = 0;
3443 DeclContextList NamespaceDeclChain(BuildContextChain(Ctx));
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003444 DeclContextList FullNamespaceDeclChain(NamespaceDeclChain);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003445
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003446 // Eliminate common elements from the two DeclContext chains.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003447 for (DeclContextList::reverse_iterator C = CurContextChain.rbegin(),
3448 CEnd = CurContextChain.rend();
Chandler Carruthb198e5a2011-06-28 21:43:34 +00003449 C != CEnd && !NamespaceDeclChain.empty() &&
3450 NamespaceDeclChain.back() == *C; ++C) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003451 NamespaceDeclChain.pop_back();
3452 }
3453
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003454 // Add an explicit leading '::' specifier if needed.
3455 if (NamespaceDecl *ND =
Kaelyn Uhrain618f97c2012-02-15 22:59:03 +00003456 NamespaceDeclChain.empty() ? NULL :
3457 dyn_cast_or_null<NamespaceDecl>(NamespaceDeclChain.back())) {
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003458 IdentifierInfo *Name = ND->getIdentifier();
3459 if (std::find(CurContextIdentifiers.begin(), CurContextIdentifiers.end(),
3460 Name) != CurContextIdentifiers.end() ||
3461 std::find(CurNameSpecifierIdentifiers.begin(),
3462 CurNameSpecifierIdentifiers.end(),
3463 Name) != CurNameSpecifierIdentifiers.end()) {
3464 NamespaceDeclChain = FullNamespaceDeclChain;
3465 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
3466 }
3467 }
3468
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003469 // Build the NestedNameSpecifier from what is left of the NamespaceDeclChain
3470 for (DeclContextList::reverse_iterator C = NamespaceDeclChain.rbegin(),
3471 CEnd = NamespaceDeclChain.rend();
3472 C != CEnd; ++C) {
3473 NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(*C);
3474 if (ND) {
3475 NNS = NestedNameSpecifier::Create(Context, NNS, ND);
3476 ++NumSpecifiers;
3477 }
3478 }
3479
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003480 // If the built NestedNameSpecifier would be replacing an existing
3481 // NestedNameSpecifier, use the number of component identifiers that
3482 // would need to be changed as the edit distance instead of the number
3483 // of components in the built NestedNameSpecifier.
3484 if (NNS && !CurNameSpecifierIdentifiers.empty()) {
3485 SmallVector<const IdentifierInfo*, 4> NewNameSpecifierIdentifiers;
3486 getNestedNameSpecifierIdentifiers(NNS, NewNameSpecifierIdentifiers);
3487 NumSpecifiers = llvm::ComputeEditDistance(
3488 llvm::ArrayRef<const IdentifierInfo*>(CurNameSpecifierIdentifiers),
3489 llvm::ArrayRef<const IdentifierInfo*>(NewNameSpecifierIdentifiers));
3490 }
3491
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003492 isSorted = false;
3493 Distances.insert(NumSpecifiers);
3494 DistanceMap[NumSpecifiers].push_back(SpecifierInfo(Ctx, NNS, NumSpecifiers));
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003495}
3496
Douglas Gregord507d772010-10-20 03:06:34 +00003497/// \brief Perform name lookup for a possible result for typo correction.
3498static void LookupPotentialTypoResult(Sema &SemaRef,
3499 LookupResult &Res,
3500 IdentifierInfo *Name,
3501 Scope *S, CXXScopeSpec *SS,
3502 DeclContext *MemberContext,
3503 bool EnteringContext,
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003504 bool isObjCIvarLookup) {
Douglas Gregord507d772010-10-20 03:06:34 +00003505 Res.suppressDiagnostics();
3506 Res.clear();
3507 Res.setLookupName(Name);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003508 if (MemberContext) {
Douglas Gregord507d772010-10-20 03:06:34 +00003509 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(MemberContext)) {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003510 if (isObjCIvarLookup) {
Douglas Gregord507d772010-10-20 03:06:34 +00003511 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(Name)) {
3512 Res.addDecl(Ivar);
3513 Res.resolveKind();
3514 return;
3515 }
3516 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003517
Douglas Gregord507d772010-10-20 03:06:34 +00003518 if (ObjCPropertyDecl *Prop = Class->FindPropertyDeclaration(Name)) {
3519 Res.addDecl(Prop);
3520 Res.resolveKind();
3521 return;
3522 }
3523 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003524
Douglas Gregord507d772010-10-20 03:06:34 +00003525 SemaRef.LookupQualifiedName(Res, MemberContext);
3526 return;
3527 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003528
3529 SemaRef.LookupParsedName(Res, S, SS, /*AllowBuiltinCreation=*/false,
Douglas Gregord507d772010-10-20 03:06:34 +00003530 EnteringContext);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003531
Douglas Gregord507d772010-10-20 03:06:34 +00003532 // Fake ivar lookup; this should really be part of
3533 // LookupParsedName.
3534 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) {
3535 if (Method->isInstanceMethod() && Method->getClassInterface() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003536 (Res.empty() ||
Douglas Gregord507d772010-10-20 03:06:34 +00003537 (Res.isSingleResult() &&
3538 Res.getFoundDecl()->isDefinedOutsideFunctionOrMethod()))) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003539 if (ObjCIvarDecl *IV
Douglas Gregord507d772010-10-20 03:06:34 +00003540 = Method->getClassInterface()->lookupInstanceVariable(Name)) {
3541 Res.addDecl(IV);
3542 Res.resolveKind();
3543 }
3544 }
3545 }
3546}
3547
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003548/// \brief Add keywords to the consumer as possible typo corrections.
3549static void AddKeywordsToConsumer(Sema &SemaRef,
3550 TypoCorrectionConsumer &Consumer,
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003551 Scope *S, CorrectionCandidateCallback &CCC) {
3552 if (CCC.WantObjCSuper)
3553 Consumer.addKeywordResult("super");
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003554
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003555 if (CCC.WantTypeSpecifiers) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003556 // Add type-specifier keywords to the set of results.
3557 const char *CTypeSpecs[] = {
3558 "char", "const", "double", "enum", "float", "int", "long", "short",
Douglas Gregor3b22a882011-07-01 21:27:45 +00003559 "signed", "struct", "union", "unsigned", "void", "volatile",
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003560 "_Complex", "_Imaginary",
3561 // storage-specifiers as well
3562 "extern", "inline", "static", "typedef"
3563 };
3564
3565 const unsigned NumCTypeSpecs = sizeof(CTypeSpecs) / sizeof(CTypeSpecs[0]);
3566 for (unsigned I = 0; I != NumCTypeSpecs; ++I)
3567 Consumer.addKeywordResult(CTypeSpecs[I]);
3568
David Blaikiebbafb8a2012-03-11 07:00:24 +00003569 if (SemaRef.getLangOpts().C99)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003570 Consumer.addKeywordResult("restrict");
David Blaikiebbafb8a2012-03-11 07:00:24 +00003571 if (SemaRef.getLangOpts().Bool || SemaRef.getLangOpts().CPlusPlus)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003572 Consumer.addKeywordResult("bool");
David Blaikiebbafb8a2012-03-11 07:00:24 +00003573 else if (SemaRef.getLangOpts().C99)
Douglas Gregor3b22a882011-07-01 21:27:45 +00003574 Consumer.addKeywordResult("_Bool");
3575
David Blaikiebbafb8a2012-03-11 07:00:24 +00003576 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003577 Consumer.addKeywordResult("class");
3578 Consumer.addKeywordResult("typename");
3579 Consumer.addKeywordResult("wchar_t");
3580
David Blaikiebbafb8a2012-03-11 07:00:24 +00003581 if (SemaRef.getLangOpts().CPlusPlus0x) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003582 Consumer.addKeywordResult("char16_t");
3583 Consumer.addKeywordResult("char32_t");
3584 Consumer.addKeywordResult("constexpr");
3585 Consumer.addKeywordResult("decltype");
3586 Consumer.addKeywordResult("thread_local");
3587 }
3588 }
3589
David Blaikiebbafb8a2012-03-11 07:00:24 +00003590 if (SemaRef.getLangOpts().GNUMode)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003591 Consumer.addKeywordResult("typeof");
3592 }
3593
David Blaikiebbafb8a2012-03-11 07:00:24 +00003594 if (CCC.WantCXXNamedCasts && SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003595 Consumer.addKeywordResult("const_cast");
3596 Consumer.addKeywordResult("dynamic_cast");
3597 Consumer.addKeywordResult("reinterpret_cast");
3598 Consumer.addKeywordResult("static_cast");
3599 }
3600
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003601 if (CCC.WantExpressionKeywords) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003602 Consumer.addKeywordResult("sizeof");
David Blaikiebbafb8a2012-03-11 07:00:24 +00003603 if (SemaRef.getLangOpts().Bool || SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003604 Consumer.addKeywordResult("false");
3605 Consumer.addKeywordResult("true");
3606 }
3607
David Blaikiebbafb8a2012-03-11 07:00:24 +00003608 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003609 const char *CXXExprs[] = {
3610 "delete", "new", "operator", "throw", "typeid"
3611 };
3612 const unsigned NumCXXExprs = sizeof(CXXExprs) / sizeof(CXXExprs[0]);
3613 for (unsigned I = 0; I != NumCXXExprs; ++I)
3614 Consumer.addKeywordResult(CXXExprs[I]);
3615
3616 if (isa<CXXMethodDecl>(SemaRef.CurContext) &&
3617 cast<CXXMethodDecl>(SemaRef.CurContext)->isInstance())
3618 Consumer.addKeywordResult("this");
3619
David Blaikiebbafb8a2012-03-11 07:00:24 +00003620 if (SemaRef.getLangOpts().CPlusPlus0x) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003621 Consumer.addKeywordResult("alignof");
3622 Consumer.addKeywordResult("nullptr");
3623 }
3624 }
3625 }
3626
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003627 if (CCC.WantRemainingKeywords) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003628 if (SemaRef.getCurFunctionOrMethodDecl() || SemaRef.getCurBlock()) {
3629 // Statements.
3630 const char *CStmts[] = {
3631 "do", "else", "for", "goto", "if", "return", "switch", "while" };
3632 const unsigned NumCStmts = sizeof(CStmts) / sizeof(CStmts[0]);
3633 for (unsigned I = 0; I != NumCStmts; ++I)
3634 Consumer.addKeywordResult(CStmts[I]);
3635
David Blaikiebbafb8a2012-03-11 07:00:24 +00003636 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003637 Consumer.addKeywordResult("catch");
3638 Consumer.addKeywordResult("try");
3639 }
3640
3641 if (S && S->getBreakParent())
3642 Consumer.addKeywordResult("break");
3643
3644 if (S && S->getContinueParent())
3645 Consumer.addKeywordResult("continue");
3646
3647 if (!SemaRef.getCurFunction()->SwitchStack.empty()) {
3648 Consumer.addKeywordResult("case");
3649 Consumer.addKeywordResult("default");
3650 }
3651 } else {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003652 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003653 Consumer.addKeywordResult("namespace");
3654 Consumer.addKeywordResult("template");
3655 }
3656
3657 if (S && S->isClassScope()) {
3658 Consumer.addKeywordResult("explicit");
3659 Consumer.addKeywordResult("friend");
3660 Consumer.addKeywordResult("mutable");
3661 Consumer.addKeywordResult("private");
3662 Consumer.addKeywordResult("protected");
3663 Consumer.addKeywordResult("public");
3664 Consumer.addKeywordResult("virtual");
3665 }
3666 }
3667
David Blaikiebbafb8a2012-03-11 07:00:24 +00003668 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003669 Consumer.addKeywordResult("using");
3670
David Blaikiebbafb8a2012-03-11 07:00:24 +00003671 if (SemaRef.getLangOpts().CPlusPlus0x)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003672 Consumer.addKeywordResult("static_assert");
3673 }
3674 }
3675}
3676
Kaelyn Uhrain0a16a8e2012-02-14 18:56:48 +00003677static bool isCandidateViable(CorrectionCandidateCallback &CCC,
3678 TypoCorrection &Candidate) {
3679 Candidate.setCallbackDistance(CCC.RankCandidate(Candidate));
3680 return Candidate.getEditDistance(false) != TypoCorrection::InvalidDistance;
3681}
3682
Douglas Gregor2d435302009-12-30 17:04:44 +00003683/// \brief Try to "correct" a typo in the source code by finding
3684/// visible declarations whose names are similar to the name that was
3685/// present in the source code.
3686///
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003687/// \param TypoName the \c DeclarationNameInfo structure that contains
3688/// the name that was present in the source code along with its location.
3689///
3690/// \param LookupKind the name-lookup criteria used to search for the name.
Douglas Gregor2d435302009-12-30 17:04:44 +00003691///
3692/// \param S the scope in which name lookup occurs.
3693///
3694/// \param SS the nested-name-specifier that precedes the name we're
3695/// looking for, if present.
3696///
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003697/// \param CCC A CorrectionCandidateCallback object that provides further
3698/// validation of typo correction candidates. It also provides flags for
3699/// determining the set of keywords permitted.
3700///
Douglas Gregoraf2bd472009-12-31 07:42:17 +00003701/// \param MemberContext if non-NULL, the context in which to look for
3702/// a member access expression.
3703///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003704/// \param EnteringContext whether we're entering the context described by
Douglas Gregor598b08f2009-12-31 05:20:13 +00003705/// the nested-name-specifier SS.
3706///
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003707/// \param OPT when non-NULL, the search for visible declarations will
3708/// also walk the protocols in the qualified interfaces of \p OPT.
3709///
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003710/// \returns a \c TypoCorrection containing the corrected name if the typo
3711/// along with information such as the \c NamedDecl where the corrected name
3712/// was declared, and any additional \c NestedNameSpecifier needed to access
3713/// it (C++ only). The \c TypoCorrection is empty if there is no correction.
3714TypoCorrection Sema::CorrectTypo(const DeclarationNameInfo &TypoName,
3715 Sema::LookupNameKind LookupKind,
3716 Scope *S, CXXScopeSpec *SS,
Kaelyn Uhrain4e8942c2012-01-31 23:49:25 +00003717 CorrectionCandidateCallback &CCC,
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003718 DeclContext *MemberContext,
3719 bool EnteringContext,
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003720 const ObjCObjectPointerType *OPT) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003721 if (Diags.hasFatalErrorOccurred() || !getLangOpts().SpellChecking)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003722 return TypoCorrection();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003723
Francois Pichet9c391132011-12-03 15:55:29 +00003724 // In Microsoft mode, don't perform typo correction in a template member
3725 // function dependent context because it interferes with the "lookup into
3726 // dependent bases of class templates" feature.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003727 if (getLangOpts().MicrosoftMode && CurContext->isDependentContext() &&
Francois Pichet9c391132011-12-03 15:55:29 +00003728 isa<CXXMethodDecl>(CurContext))
3729 return TypoCorrection();
3730
Douglas Gregor2d435302009-12-30 17:04:44 +00003731 // We only attempt to correct typos for identifiers.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003732 IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo();
Douglas Gregor2d435302009-12-30 17:04:44 +00003733 if (!Typo)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003734 return TypoCorrection();
Douglas Gregor2d435302009-12-30 17:04:44 +00003735
3736 // If the scope specifier itself was invalid, don't try to correct
3737 // typos.
3738 if (SS && SS->isInvalid())
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003739 return TypoCorrection();
Douglas Gregor2d435302009-12-30 17:04:44 +00003740
3741 // Never try to correct typos during template deduction or
3742 // instantiation.
3743 if (!ActiveTemplateInstantiations.empty())
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003744 return TypoCorrection();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003745
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003746 NamespaceSpecifierSet Namespaces(Context, CurContext, SS);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003747
3748 TypoCorrectionConsumer Consumer(*this, Typo);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003749
Kaelyn Uhrain0a16a8e2012-02-14 18:56:48 +00003750 // If a callback object considers an empty typo correction candidate to be
3751 // viable, assume it does not do any actual validation of the candidates.
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00003752 TypoCorrection EmptyCorrection;
Kaelyn Uhrain0a16a8e2012-02-14 18:56:48 +00003753 bool ValidatingCallback = !isCandidateViable(CCC, EmptyCorrection);
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00003754
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003755 // Perform name lookup to find visible, similarly-named entities.
Douglas Gregor87074f12010-10-20 01:32:02 +00003756 bool IsUnqualifiedLookup = false;
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003757 DeclContext *QualifiedDC = MemberContext;
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003758 if (MemberContext) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003759 LookupVisibleDecls(MemberContext, LookupKind, Consumer);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003760
3761 // Look in qualified interfaces.
3762 if (OPT) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003763 for (ObjCObjectPointerType::qual_iterator
3764 I = OPT->qual_begin(), E = OPT->qual_end();
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003765 I != E; ++I)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003766 LookupVisibleDecls(*I, LookupKind, Consumer);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003767 }
3768 } else if (SS && SS->isSet()) {
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003769 QualifiedDC = computeDeclContext(*SS, EnteringContext);
3770 if (!QualifiedDC)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003771 return TypoCorrection();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003772
Douglas Gregor87074f12010-10-20 01:32:02 +00003773 // Provide a stop gap for files that are just seriously broken. Trying
3774 // to correct all typos can turn into a HUGE performance penalty, causing
3775 // some files to take minutes to get rejected by the parser.
3776 if (TyposCorrected + UnqualifiedTyposCorrected.size() >= 20)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003777 return TypoCorrection();
Douglas Gregor87074f12010-10-20 01:32:02 +00003778 ++TyposCorrected;
3779
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003780 LookupVisibleDecls(QualifiedDC, LookupKind, Consumer);
Douglas Gregor2d435302009-12-30 17:04:44 +00003781 } else {
Douglas Gregor87074f12010-10-20 01:32:02 +00003782 IsUnqualifiedLookup = true;
3783 UnqualifiedTyposCorrectedMap::iterator Cached
3784 = UnqualifiedTyposCorrected.find(Typo);
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00003785 if (Cached != UnqualifiedTyposCorrected.end()) {
3786 // Add the cached value, unless it's a keyword or fails validation. In the
3787 // keyword case, we'll end up adding the keyword below.
3788 if (Cached->second) {
3789 if (!Cached->second.isKeyword() &&
Kaelyn Uhrain0a16a8e2012-02-14 18:56:48 +00003790 isCandidateViable(CCC, Cached->second))
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00003791 Consumer.addCorrection(Cached->second);
3792 } else {
3793 // Only honor no-correction cache hits when a callback that will validate
3794 // correction candidates is not being used.
3795 if (!ValidatingCallback)
3796 return TypoCorrection();
3797 }
3798 }
3799 if (Cached == UnqualifiedTyposCorrected.end()) {
Douglas Gregor87074f12010-10-20 01:32:02 +00003800 // Provide a stop gap for files that are just seriously broken. Trying
3801 // to correct all typos can turn into a HUGE performance penalty, causing
3802 // some files to take minutes to get rejected by the parser.
3803 if (TyposCorrected + UnqualifiedTyposCorrected.size() >= 20)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003804 return TypoCorrection();
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00003805 }
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003806 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003807
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003808 if (IsUnqualifiedLookup || (QualifiedDC && QualifiedDC->isNamespace())) {
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00003809 // For unqualified lookup, look through all of the names that we have
3810 // seen in this translation unit.
Kaelyn Uhrain1c75d402012-02-07 01:32:58 +00003811 // FIXME: Re-add the ability to skip very unlikely potential corrections.
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00003812 for (IdentifierTable::iterator I = Context.Idents.begin(),
3813 IEnd = Context.Idents.end();
3814 I != IEnd; ++I)
3815 Consumer.FoundName(I->getKey());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003816
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00003817 // Walk through identifiers in external identifier sources.
Kaelyn Uhrain1c75d402012-02-07 01:32:58 +00003818 // FIXME: Re-add the ability to skip very unlikely potential corrections.
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00003819 if (IdentifierInfoLookup *External
3820 = Context.Idents.getExternalIdentifierLookup()) {
Dylan Noblesmithe2778992012-02-05 02:12:40 +00003821 OwningPtr<IdentifierIterator> Iter(External->getIdentifiers());
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00003822 do {
3823 StringRef Name = Iter->Next();
3824 if (Name.empty())
3825 break;
Douglas Gregor57756ea2010-10-14 22:11:03 +00003826
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00003827 Consumer.FoundName(Name);
3828 } while (true);
Douglas Gregor57756ea2010-10-14 22:11:03 +00003829 }
Douglas Gregor2d435302009-12-30 17:04:44 +00003830 }
3831
Kaelyn Uhrain4e8942c2012-01-31 23:49:25 +00003832 AddKeywordsToConsumer(*this, Consumer, S, CCC);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003833
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003834 // If we haven't found anything, we're done.
Douglas Gregor87074f12010-10-20 01:32:02 +00003835 if (Consumer.empty()) {
3836 // If this was an unqualified lookup, note that no correction was found.
3837 if (IsUnqualifiedLookup)
3838 (void)UnqualifiedTyposCorrected[Typo];
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003839
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003840 return TypoCorrection();
Douglas Gregor87074f12010-10-20 01:32:02 +00003841 }
Douglas Gregor2d435302009-12-30 17:04:44 +00003842
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003843 // Make sure that the user typed at least 3 characters for each correction
Douglas Gregor0afa7f62010-10-14 20:34:08 +00003844 // made. Otherwise, we don't even both looking at the results.
Kaelyn Uhrain0a16a8e2012-02-14 18:56:48 +00003845 unsigned ED = Consumer.getBestEditDistance(true);
Douglas Gregor87074f12010-10-20 01:32:02 +00003846 if (ED > 0 && Typo->getName().size() / ED < 3) {
3847 // If this was an unqualified lookup, note that no correction was found.
Douglas Gregoraf1daa92010-10-27 14:20:34 +00003848 if (IsUnqualifiedLookup)
Douglas Gregor87074f12010-10-20 01:32:02 +00003849 (void)UnqualifiedTyposCorrected[Typo];
3850
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003851 return TypoCorrection();
3852 }
3853
3854 // Build the NestedNameSpecifiers for the KnownNamespaces
David Blaikiebbafb8a2012-03-11 07:00:24 +00003855 if (getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003856 // Load any externally-known namespaces.
3857 if (ExternalSource && !LoadedExternalKnownNamespaces) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003858 SmallVector<NamespaceDecl *, 4> ExternalKnownNamespaces;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003859 LoadedExternalKnownNamespaces = true;
3860 ExternalSource->ReadKnownNamespaces(ExternalKnownNamespaces);
3861 for (unsigned I = 0, N = ExternalKnownNamespaces.size(); I != N; ++I)
3862 KnownNamespaces[ExternalKnownNamespaces[I]] = true;
3863 }
3864
3865 for (llvm::DenseMap<NamespaceDecl*, bool>::iterator
3866 KNI = KnownNamespaces.begin(),
3867 KNIEnd = KnownNamespaces.end();
3868 KNI != KNIEnd; ++KNI)
3869 Namespaces.AddNamespace(KNI->first);
Douglas Gregor87074f12010-10-20 01:32:02 +00003870 }
Douglas Gregor0afa7f62010-10-14 20:34:08 +00003871
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003872 // Weed out any names that could not be found by name lookup or, if a
3873 // CorrectionCandidateCallback object was provided, failed validation.
Kaelyn Uhrain0a16a8e2012-02-14 18:56:48 +00003874 llvm::SmallVector<TypoCorrection, 16> QualifiedResults;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003875 LookupResult TmpRes(*this, TypoName, LookupKind);
3876 TmpRes.suppressDiagnostics();
3877 while (!Consumer.empty()) {
3878 TypoCorrectionConsumer::distance_iterator DI = Consumer.begin();
3879 unsigned ED = DI->first;
Douglas Gregor29cdc6b2011-06-28 16:44:39 +00003880 for (TypoCorrectionConsumer::result_iterator I = DI->second->begin(),
3881 IEnd = DI->second->end();
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003882 I != IEnd; /* Increment in loop. */) {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003883 // If the item already has been looked up or is a keyword, keep it.
3884 // If a validator callback object was given, drop the correction
3885 // unless it passes validation.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003886 if (I->second.isResolved()) {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003887 TypoCorrectionConsumer::result_iterator Prev = I;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003888 ++I;
Kaelyn Uhrain0a16a8e2012-02-14 18:56:48 +00003889 if (!isCandidateViable(CCC, Prev->second))
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003890 DI->second->erase(Prev);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003891 continue;
Douglas Gregor0afa7f62010-10-14 20:34:08 +00003892 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003893
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003894 // Perform name lookup on this name.
3895 IdentifierInfo *Name = I->second.getCorrectionAsIdentifierInfo();
3896 LookupPotentialTypoResult(*this, TmpRes, Name, S, SS, MemberContext,
Kaelyn Uhrain4e8942c2012-01-31 23:49:25 +00003897 EnteringContext, CCC.IsObjCIvarLookup);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003898
3899 switch (TmpRes.getResultKind()) {
3900 case LookupResult::NotFound:
3901 case LookupResult::NotFoundInCurrentInstantiation:
Kaelyn Uhrain5a43b462011-09-07 20:25:59 +00003902 case LookupResult::FoundUnresolvedValue:
Kaelyn Uhrain0a16a8e2012-02-14 18:56:48 +00003903 QualifiedResults.push_back(I->second);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003904 // We didn't find this name in our scope, or didn't like what we found;
3905 // ignore it.
3906 {
3907 TypoCorrectionConsumer::result_iterator Next = I;
3908 ++Next;
Douglas Gregor29cdc6b2011-06-28 16:44:39 +00003909 DI->second->erase(I);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003910 I = Next;
3911 }
3912 break;
3913
3914 case LookupResult::Ambiguous:
3915 // We don't deal with ambiguities.
3916 return TypoCorrection();
3917
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00003918 case LookupResult::FoundOverloaded: {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003919 TypoCorrectionConsumer::result_iterator Prev = I;
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00003920 // Store all of the Decls for overloaded symbols
3921 for (LookupResult::iterator TRD = TmpRes.begin(),
3922 TRDEnd = TmpRes.end();
3923 TRD != TRDEnd; ++TRD)
3924 I->second.addCorrectionDecl(*TRD);
3925 ++I;
Kaelyn Uhrain0a16a8e2012-02-14 18:56:48 +00003926 if (!isCandidateViable(CCC, Prev->second))
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003927 DI->second->erase(Prev);
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00003928 break;
3929 }
3930
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003931 case LookupResult::Found: {
3932 TypoCorrectionConsumer::result_iterator Prev = I;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003933 I->second.setCorrectionDecl(TmpRes.getAsSingle<NamedDecl>());
3934 ++I;
Kaelyn Uhrain0a16a8e2012-02-14 18:56:48 +00003935 if (!isCandidateViable(CCC, Prev->second))
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003936 DI->second->erase(Prev);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003937 break;
3938 }
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003939
3940 }
Douglas Gregor0afa7f62010-10-14 20:34:08 +00003941 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003942
Douglas Gregor29cdc6b2011-06-28 16:44:39 +00003943 if (DI->second->empty())
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003944 Consumer.erase(DI);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003945 else if (!getLangOpts().CPlusPlus || QualifiedResults.empty() || !ED)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003946 // If there are results in the closest possible bucket, stop
3947 break;
3948
3949 // Only perform the qualified lookups for C++
David Blaikiebbafb8a2012-03-11 07:00:24 +00003950 if (getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003951 TmpRes.suppressDiagnostics();
Kaelyn Uhrain0a16a8e2012-02-14 18:56:48 +00003952 for (llvm::SmallVector<TypoCorrection,
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003953 16>::iterator QRI = QualifiedResults.begin(),
3954 QRIEnd = QualifiedResults.end();
3955 QRI != QRIEnd; ++QRI) {
3956 for (NamespaceSpecifierSet::iterator NI = Namespaces.begin(),
3957 NIEnd = Namespaces.end();
3958 NI != NIEnd; ++NI) {
3959 DeclContext *Ctx = NI->DeclCtx;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003960
Kaelyn Uhrain1c75d402012-02-07 01:32:58 +00003961 // FIXME: Stop searching once the namespaces are too far away to create
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003962 // acceptable corrections for this identifier (since the namespaces
Kaelyn Uhrain1c75d402012-02-07 01:32:58 +00003963 // are sorted in ascending order by edit distance).
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003964
3965 TmpRes.clear();
Kaelyn Uhrain0a16a8e2012-02-14 18:56:48 +00003966 TmpRes.setLookupName(QRI->getCorrectionAsIdentifierInfo());
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003967 if (!LookupQualifiedName(TmpRes, Ctx)) continue;
3968
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003969 // Any corrections added below will be validated in subsequent
3970 // iterations of the main while() loop over the Consumer's contents.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003971 switch (TmpRes.getResultKind()) {
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003972 case LookupResult::Found: {
3973 TypoCorrection TC(*QRI);
3974 TC.setCorrectionDecl(TmpRes.getAsSingle<NamedDecl>());
3975 TC.setCorrectionSpecifier(NI->NameSpecifier);
3976 TC.setQualifierDistance(NI->EditDistance);
3977 Consumer.addCorrection(TC);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003978 break;
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003979 }
3980 case LookupResult::FoundOverloaded: {
3981 TypoCorrection TC(*QRI);
3982 TC.setCorrectionSpecifier(NI->NameSpecifier);
3983 TC.setQualifierDistance(NI->EditDistance);
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00003984 for (LookupResult::iterator TRD = TmpRes.begin(),
3985 TRDEnd = TmpRes.end();
3986 TRD != TRDEnd; ++TRD)
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003987 TC.addCorrectionDecl(*TRD);
3988 Consumer.addCorrection(TC);
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00003989 break;
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003990 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003991 case LookupResult::NotFound:
3992 case LookupResult::NotFoundInCurrentInstantiation:
3993 case LookupResult::Ambiguous:
Kaelyn Uhrain5a43b462011-09-07 20:25:59 +00003994 case LookupResult::FoundUnresolvedValue:
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003995 break;
3996 }
3997 }
3998 }
3999 }
4000
4001 QualifiedResults.clear();
4002 }
4003
4004 // No corrections remain...
4005 if (Consumer.empty()) return TypoCorrection();
4006
Douglas Gregor29cdc6b2011-06-28 16:44:39 +00004007 TypoResultsMap &BestResults = *Consumer.begin()->second;
Kaelyn Uhrain0a16a8e2012-02-14 18:56:48 +00004008 ED = TypoCorrection::NormalizeEditDistance(Consumer.begin()->first);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004009
4010 if (ED > 0 && Typo->getName().size() / ED < 3) {
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00004011 // If this was an unqualified lookup and we believe the callback
4012 // object wouldn't have filtered out possible corrections, note
4013 // that no correction was found.
4014 if (IsUnqualifiedLookup && !ValidatingCallback)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004015 (void)UnqualifiedTyposCorrected[Typo];
4016
4017 return TypoCorrection();
4018 }
4019
Douglas Gregor0afa7f62010-10-14 20:34:08 +00004020 // If only a single name remains, return that result.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004021 if (BestResults.size() == 1) {
4022 const llvm::StringMapEntry<TypoCorrection> &Correction = *(BestResults.begin());
4023 const TypoCorrection &Result = Correction.second;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004024
Douglas Gregor2a1d72d2010-10-26 17:18:00 +00004025 // Don't correct to a keyword that's the same as the typo; the keyword
4026 // wasn't actually in scope.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004027 if (ED == 0 && Result.isKeyword()) return TypoCorrection();
4028
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004029 // Record the correction for unqualified lookup.
4030 if (IsUnqualifiedLookup)
4031 UnqualifiedTyposCorrected[Typo] = Result;
4032
4033 return Result;
4034 }
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00004035 else if (BestResults.size() > 1
4036 // Ugly hack equivalent to CTC == CTC_ObjCMessageReceiver;
4037 // WantObjCSuper is only true for CTC_ObjCMessageReceiver and for
4038 // some instances of CTC_Unknown, while WantRemainingKeywords is true
4039 // for CTC_Unknown but not for CTC_ObjCMessageReceiver.
Kaelyn Uhrain4e8942c2012-01-31 23:49:25 +00004040 && CCC.WantObjCSuper && !CCC.WantRemainingKeywords
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004041 && BestResults["super"].isKeyword()) {
4042 // Prefer 'super' when we're completing in a message-receiver
4043 // context.
4044
4045 // Don't correct to a keyword that's the same as the typo; the keyword
4046 // wasn't actually in scope.
4047 if (ED == 0) return TypoCorrection();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004048
Douglas Gregor87074f12010-10-20 01:32:02 +00004049 // Record the correction for unqualified lookup.
4050 if (IsUnqualifiedLookup)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004051 UnqualifiedTyposCorrected[Typo] = BestResults["super"];
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004052
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004053 return BestResults["super"];
Douglas Gregoraf9eb592010-10-15 13:35:25 +00004054 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004055
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00004056 // If this was an unqualified lookup and we believe the callback object did
4057 // not filter out possible corrections, note that no correction was found.
4058 if (IsUnqualifiedLookup && !ValidatingCallback)
Douglas Gregor87074f12010-10-20 01:32:02 +00004059 (void)UnqualifiedTyposCorrected[Typo];
4060
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004061 return TypoCorrection();
4062}
4063
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00004064void TypoCorrection::addCorrectionDecl(NamedDecl *CDecl) {
4065 if (!CDecl) return;
4066
4067 if (isKeyword())
4068 CorrectionDecls.clear();
4069
4070 CorrectionDecls.push_back(CDecl);
4071
4072 if (!CorrectionName)
4073 CorrectionName = CDecl->getDeclName();
4074}
4075
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004076std::string TypoCorrection::getAsString(const LangOptions &LO) const {
4077 if (CorrectionNameSpec) {
4078 std::string tmpBuffer;
4079 llvm::raw_string_ostream PrefixOStream(tmpBuffer);
4080 CorrectionNameSpec->print(PrefixOStream, PrintingPolicy(LO));
4081 return PrefixOStream.str() + CorrectionName.getAsString();
4082 }
4083
4084 return CorrectionName.getAsString();
Douglas Gregor2d435302009-12-30 17:04:44 +00004085}