blob: 44181b141dd91fb4156d17edd4c0e8fd59694fab [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() {
Chris Lattnerebb5c6c2011-02-18 01:27:55 +0000284 IDNS = getIDNS(LookupKind, SemaRef.getLangOptions().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
John McCall19c1bfd2010-08-25 05:32:35 +0000305void LookupResult::sanity() const {
306 assert(ResultKind != NotFound || Decls.size() == 0);
307 assert(ResultKind != Found || Decls.size() == 1);
308 assert(ResultKind != FoundOverloaded || Decls.size() > 1 ||
309 (Decls.size() == 1 &&
310 isa<FunctionTemplateDecl>((*begin())->getUnderlyingDecl())));
311 assert(ResultKind != FoundUnresolvedValue || sanityCheckUnresolved());
312 assert(ResultKind != Ambiguous || Decls.size() > 1 ||
Douglas Gregorc0d24902010-10-22 22:08:47 +0000313 (Decls.size() == 1 && (Ambiguity == AmbiguousBaseSubobjects ||
314 Ambiguity == AmbiguousBaseSubobjectTypes)));
John McCall19c1bfd2010-08-25 05:32:35 +0000315 assert((Paths != NULL) == (ResultKind == Ambiguous &&
316 (Ambiguity == AmbiguousBaseSubobjectTypes ||
317 Ambiguity == AmbiguousBaseSubobjects)));
318}
John McCall19c1bfd2010-08-25 05:32:35 +0000319
John McCall9f3059a2009-10-09 21:13:30 +0000320// Necessary because CXXBasePaths is not complete in Sema.h
John McCall5cebab12009-11-18 07:57:50 +0000321void LookupResult::deletePaths(CXXBasePaths *Paths) {
John McCall9f3059a2009-10-09 21:13:30 +0000322 delete Paths;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000323}
324
Douglas Gregor4a814562011-12-14 16:03:29 +0000325static NamedDecl *getVisibleDecl(NamedDecl *D);
326
327NamedDecl *LookupResult::getAcceptableDeclSlow(NamedDecl *D) const {
328 return getVisibleDecl(D);
329}
330
John McCall283b9012009-11-22 00:44:51 +0000331/// Resolves the result kind of this lookup.
John McCall5cebab12009-11-18 07:57:50 +0000332void LookupResult::resolveKind() {
John McCall9f3059a2009-10-09 21:13:30 +0000333 unsigned N = Decls.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000334
John McCall9f3059a2009-10-09 21:13:30 +0000335 // Fast case: no possible ambiguity.
John McCall1f82f242009-11-18 22:49:29 +0000336 if (N == 0) {
John McCall7fe6e9c2010-01-15 21:27:01 +0000337 assert(ResultKind == NotFound || ResultKind == NotFoundInCurrentInstantiation);
John McCall1f82f242009-11-18 22:49:29 +0000338 return;
339 }
340
John McCall283b9012009-11-22 00:44:51 +0000341 // If there's a single decl, we need to examine it to decide what
342 // kind of lookup this is.
John McCalle61f2ba2009-11-18 02:36:19 +0000343 if (N == 1) {
Douglas Gregor516d6722010-04-25 21:15:30 +0000344 NamedDecl *D = (*Decls.begin())->getUnderlyingDecl();
345 if (isa<FunctionTemplateDecl>(D))
John McCall283b9012009-11-22 00:44:51 +0000346 ResultKind = FoundOverloaded;
Douglas Gregor516d6722010-04-25 21:15:30 +0000347 else if (isa<UnresolvedUsingValueDecl>(D))
John McCalle61f2ba2009-11-18 02:36:19 +0000348 ResultKind = FoundUnresolvedValue;
349 return;
350 }
John McCall9f3059a2009-10-09 21:13:30 +0000351
John McCall6538c932009-10-10 05:48:19 +0000352 // Don't do any extra resolution if we've already resolved as ambiguous.
John McCall27b18f82009-11-17 02:14:36 +0000353 if (ResultKind == Ambiguous) return;
John McCall6538c932009-10-10 05:48:19 +0000354
John McCall9f3059a2009-10-09 21:13:30 +0000355 llvm::SmallPtrSet<NamedDecl*, 16> Unique;
Douglas Gregor13e65872010-08-11 14:45:53 +0000356 llvm::SmallPtrSet<QualType, 16> UniqueTypes;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000357
John McCall9f3059a2009-10-09 21:13:30 +0000358 bool Ambiguous = false;
359 bool HasTag = false, HasFunction = false, HasNonFunction = false;
John McCall283b9012009-11-22 00:44:51 +0000360 bool HasFunctionTemplate = false, HasUnresolved = false;
John McCall9f3059a2009-10-09 21:13:30 +0000361
362 unsigned UniqueTagIndex = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000363
John McCall9f3059a2009-10-09 21:13:30 +0000364 unsigned I = 0;
365 while (I < N) {
John McCallf0f1cf02009-11-17 07:50:12 +0000366 NamedDecl *D = Decls[I]->getUnderlyingDecl();
367 D = cast<NamedDecl>(D->getCanonicalDecl());
John McCall9f3059a2009-10-09 21:13:30 +0000368
Douglas Gregor13e65872010-08-11 14:45:53 +0000369 // Redeclarations of types via typedef can occur both within a scope
370 // and, through using declarations and directives, across scopes. There is
371 // no ambiguity if they all refer to the same type, so unique based on the
372 // canonical type.
373 if (TypeDecl *TD = dyn_cast<TypeDecl>(D)) {
374 if (!TD->getDeclContext()->isRecord()) {
375 QualType T = SemaRef.Context.getTypeDeclType(TD);
376 if (!UniqueTypes.insert(SemaRef.Context.getCanonicalType(T))) {
377 // The type is not unique; pull something off the back and continue
378 // at this index.
379 Decls[I] = Decls[--N];
380 continue;
381 }
382 }
383 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000384
John McCallf0f1cf02009-11-17 07:50:12 +0000385 if (!Unique.insert(D)) {
John McCall9f3059a2009-10-09 21:13:30 +0000386 // If it's not unique, pull something off the back (and
387 // continue at this index).
388 Decls[I] = Decls[--N];
Douglas Gregor13e65872010-08-11 14:45:53 +0000389 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000390 }
391
Douglas Gregor13e65872010-08-11 14:45:53 +0000392 // Otherwise, do some decl type analysis and then continue.
John McCalle61f2ba2009-11-18 02:36:19 +0000393
Douglas Gregor13e65872010-08-11 14:45:53 +0000394 if (isa<UnresolvedUsingValueDecl>(D)) {
395 HasUnresolved = true;
396 } else if (isa<TagDecl>(D)) {
397 if (HasTag)
398 Ambiguous = true;
399 UniqueTagIndex = I;
400 HasTag = true;
401 } else if (isa<FunctionTemplateDecl>(D)) {
402 HasFunction = true;
403 HasFunctionTemplate = true;
404 } else if (isa<FunctionDecl>(D)) {
405 HasFunction = true;
406 } else {
407 if (HasNonFunction)
408 Ambiguous = true;
409 HasNonFunction = true;
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000410 }
Douglas Gregor13e65872010-08-11 14:45:53 +0000411 I++;
Mike Stump11289f42009-09-09 15:08:12 +0000412 }
Douglas Gregor38feed82009-04-24 02:57:34 +0000413
John McCall9f3059a2009-10-09 21:13:30 +0000414 // C++ [basic.scope.hiding]p2:
415 // A class name or enumeration name can be hidden by the name of
416 // an object, function, or enumerator declared in the same
417 // scope. If a class or enumeration name and an object, function,
418 // or enumerator are declared in the same scope (in any order)
419 // with the same name, the class or enumeration name is hidden
420 // wherever the object, function, or enumerator name is visible.
421 // But it's still an error if there are distinct tag types found,
422 // even if they're not visible. (ref?)
John McCall80053822009-12-03 00:58:24 +0000423 if (HideTags && HasTag && !Ambiguous &&
Douglas Gregore63d0872010-10-23 16:06:17 +0000424 (HasFunction || HasNonFunction || HasUnresolved)) {
425 if (Decls[UniqueTagIndex]->getDeclContext()->getRedeclContext()->Equals(
426 Decls[UniqueTagIndex? 0 : N-1]->getDeclContext()->getRedeclContext()))
427 Decls[UniqueTagIndex] = Decls[--N];
428 else
429 Ambiguous = true;
430 }
Anders Carlsson8d0f6b72009-06-26 03:37:05 +0000431
John McCall9f3059a2009-10-09 21:13:30 +0000432 Decls.set_size(N);
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000433
John McCall80053822009-12-03 00:58:24 +0000434 if (HasNonFunction && (HasFunction || HasUnresolved))
John McCall9f3059a2009-10-09 21:13:30 +0000435 Ambiguous = true;
Douglas Gregorf23311d2009-01-17 01:13:24 +0000436
John McCall9f3059a2009-10-09 21:13:30 +0000437 if (Ambiguous)
John McCall6538c932009-10-10 05:48:19 +0000438 setAmbiguous(LookupResult::AmbiguousReference);
John McCalle61f2ba2009-11-18 02:36:19 +0000439 else if (HasUnresolved)
440 ResultKind = LookupResult::FoundUnresolvedValue;
John McCall283b9012009-11-22 00:44:51 +0000441 else if (N > 1 || HasFunctionTemplate)
John McCall27b18f82009-11-17 02:14:36 +0000442 ResultKind = LookupResult::FoundOverloaded;
John McCall9f3059a2009-10-09 21:13:30 +0000443 else
John McCall27b18f82009-11-17 02:14:36 +0000444 ResultKind = LookupResult::Found;
Douglas Gregor34074322009-01-14 22:20:51 +0000445}
446
John McCall5cebab12009-11-18 07:57:50 +0000447void LookupResult::addDeclsFromBasePaths(const CXXBasePaths &P) {
John McCall5b0829a2010-02-10 09:31:12 +0000448 CXXBasePaths::const_paths_iterator I, E;
John McCall9f3059a2009-10-09 21:13:30 +0000449 DeclContext::lookup_iterator DI, DE;
450 for (I = P.begin(), E = P.end(); I != E; ++I)
451 for (llvm::tie(DI,DE) = I->Decls; DI != DE; ++DI)
452 addDecl(*DI);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +0000453}
454
John McCall5cebab12009-11-18 07:57:50 +0000455void LookupResult::setAmbiguousBaseSubobjects(CXXBasePaths &P) {
John McCall9f3059a2009-10-09 21:13:30 +0000456 Paths = new CXXBasePaths;
457 Paths->swap(P);
458 addDeclsFromBasePaths(*Paths);
459 resolveKind();
John McCall6538c932009-10-10 05:48:19 +0000460 setAmbiguous(AmbiguousBaseSubobjects);
Douglas Gregor0e8fc3c2009-02-02 21:35:47 +0000461}
462
John McCall5cebab12009-11-18 07:57:50 +0000463void LookupResult::setAmbiguousBaseSubobjectTypes(CXXBasePaths &P) {
John McCall9f3059a2009-10-09 21:13:30 +0000464 Paths = new CXXBasePaths;
465 Paths->swap(P);
466 addDeclsFromBasePaths(*Paths);
467 resolveKind();
John McCall6538c932009-10-10 05:48:19 +0000468 setAmbiguous(AmbiguousBaseSubobjectTypes);
John McCall9f3059a2009-10-09 21:13:30 +0000469}
470
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000471void LookupResult::print(raw_ostream &Out) {
John McCall9f3059a2009-10-09 21:13:30 +0000472 Out << Decls.size() << " result(s)";
473 if (isAmbiguous()) Out << ", ambiguous";
474 if (Paths) Out << ", base paths present";
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000475
John McCall9f3059a2009-10-09 21:13:30 +0000476 for (iterator I = begin(), E = end(); I != E; ++I) {
477 Out << "\n";
478 (*I)->print(Out, 2);
479 }
480}
481
Douglas Gregord3a59182010-02-12 05:48:04 +0000482/// \brief Lookup a builtin function, when name lookup would otherwise
483/// fail.
484static bool LookupBuiltin(Sema &S, LookupResult &R) {
485 Sema::LookupNameKind NameKind = R.getLookupKind();
486
487 // If we didn't find a use of this identifier, and if the identifier
488 // corresponds to a compiler builtin, create the decl object for the builtin
489 // now, injecting it into translation unit scope, and return it.
490 if (NameKind == Sema::LookupOrdinaryName ||
491 NameKind == Sema::LookupRedeclarationWithLinkage) {
492 IdentifierInfo *II = R.getLookupName().getAsIdentifierInfo();
493 if (II) {
494 // If this is a builtin on this (or all) targets, create the decl.
495 if (unsigned BuiltinID = II->getBuiltinID()) {
496 // In C++, we don't have any predefined library functions like
497 // 'malloc'. Instead, we'll just error.
498 if (S.getLangOptions().CPlusPlus &&
499 S.Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
500 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000501
502 if (NamedDecl *D = S.LazilyCreateBuiltin((IdentifierInfo *)II,
503 BuiltinID, S.TUScope,
Douglas Gregorbfe022c2011-01-03 09:37:44 +0000504 R.isForRedeclaration(),
505 R.getNameLoc())) {
Douglas Gregord3a59182010-02-12 05:48:04 +0000506 R.addDecl(D);
Douglas Gregorbfe022c2011-01-03 09:37:44 +0000507 return true;
508 }
509
510 if (R.isForRedeclaration()) {
511 // If we're redeclaring this function anyway, forget that
512 // this was a builtin at all.
513 S.Context.BuiltinInfo.ForgetBuiltin(BuiltinID, S.Context.Idents);
514 }
515
516 return false;
Douglas Gregord3a59182010-02-12 05:48:04 +0000517 }
518 }
519 }
520
521 return false;
522}
523
Douglas Gregor7454c562010-07-02 20:37:36 +0000524/// \brief Determine whether we can declare a special member function within
525/// the class at this point.
526static bool CanDeclareSpecialMemberFunction(ASTContext &Context,
527 const CXXRecordDecl *Class) {
John McCall2ded5d22010-08-11 23:52:36 +0000528 // Don't do it if the class is invalid.
529 if (Class->isInvalidDecl())
530 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000531
Douglas Gregor7454c562010-07-02 20:37:36 +0000532 // We need to have a definition for the class.
533 if (!Class->getDefinition() || Class->isDependentContext())
534 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000535
Douglas Gregor7454c562010-07-02 20:37:36 +0000536 // We can't be in the middle of defining the class.
537 if (const RecordType *RecordTy
538 = Context.getTypeDeclType(Class)->getAs<RecordType>())
539 return !RecordTy->isBeingDefined();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000540
Douglas Gregor7454c562010-07-02 20:37:36 +0000541 return false;
542}
543
544void Sema::ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class) {
Douglas Gregora6d69502010-07-02 23:41:54 +0000545 if (!CanDeclareSpecialMemberFunction(Context, Class))
546 return;
Douglas Gregor9672f922010-07-03 00:47:00 +0000547
548 // If the default constructor has not yet been declared, do so now.
Alexis Huntea6f0322011-05-11 22:34:38 +0000549 if (Class->needsImplicitDefaultConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +0000550 DeclareImplicitDefaultConstructor(Class);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000551
Douglas Gregora6d69502010-07-02 23:41:54 +0000552 // If the copy constructor has not yet been declared, do so now.
553 if (!Class->hasDeclaredCopyConstructor())
554 DeclareImplicitCopyConstructor(Class);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000555
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000556 // If the copy assignment operator has not yet been declared, do so now.
Douglas Gregora6d69502010-07-02 23:41:54 +0000557 if (!Class->hasDeclaredCopyAssignment())
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000558 DeclareImplicitCopyAssignment(Class);
559
Sebastian Redl22653ba2011-08-30 19:58:05 +0000560 if (getLangOptions().CPlusPlus0x) {
561 // If the move constructor has not yet been declared, do so now.
562 if (Class->needsImplicitMoveConstructor())
563 DeclareImplicitMoveConstructor(Class); // might not actually do it
564
565 // If the move assignment operator has not yet been declared, do so now.
566 if (Class->needsImplicitMoveAssignment())
567 DeclareImplicitMoveAssignment(Class); // might not actually do it
568 }
569
Douglas Gregor7454c562010-07-02 20:37:36 +0000570 // If the destructor has not yet been declared, do so now.
Douglas Gregora6d69502010-07-02 23:41:54 +0000571 if (!Class->hasDeclaredDestructor())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000572 DeclareImplicitDestructor(Class);
Douglas Gregor7454c562010-07-02 20:37:36 +0000573}
574
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000575/// \brief Determine whether this is the name of an implicitly-declared
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000576/// special member function.
577static bool isImplicitlyDeclaredMemberFunctionName(DeclarationName Name) {
578 switch (Name.getNameKind()) {
Douglas Gregora6d69502010-07-02 23:41:54 +0000579 case DeclarationName::CXXConstructorName:
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000580 case DeclarationName::CXXDestructorName:
581 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000582
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000583 case DeclarationName::CXXOperatorName:
584 return Name.getCXXOverloadedOperator() == OO_Equal;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000585
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000586 default:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000587 break;
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000588 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000589
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000590 return false;
591}
592
593/// \brief If there are any implicit member functions with the given name
594/// that need to be declared in the given declaration context, do so.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000595static void DeclareImplicitMemberFunctionsWithName(Sema &S,
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000596 DeclarationName Name,
597 const DeclContext *DC) {
598 if (!DC)
599 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000600
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000601 switch (Name.getNameKind()) {
Douglas Gregora6d69502010-07-02 23:41:54 +0000602 case DeclarationName::CXXConstructorName:
603 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
Douglas Gregor9672f922010-07-03 00:47:00 +0000604 if (Record->getDefinition() &&
605 CanDeclareSpecialMemberFunction(S.Context, Record)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +0000606 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(Record);
Alexis Huntea6f0322011-05-11 22:34:38 +0000607 if (Record->needsImplicitDefaultConstructor())
Sebastian Redl22653ba2011-08-30 19:58:05 +0000608 S.DeclareImplicitDefaultConstructor(Class);
Douglas Gregor9672f922010-07-03 00:47:00 +0000609 if (!Record->hasDeclaredCopyConstructor())
Sebastian Redl22653ba2011-08-30 19:58:05 +0000610 S.DeclareImplicitCopyConstructor(Class);
611 if (S.getLangOptions().CPlusPlus0x &&
612 Record->needsImplicitMoveConstructor())
613 S.DeclareImplicitMoveConstructor(Class);
Douglas Gregor9672f922010-07-03 00:47:00 +0000614 }
Douglas Gregora6d69502010-07-02 23:41:54 +0000615 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000616
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000617 case DeclarationName::CXXDestructorName:
618 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
619 if (Record->getDefinition() && !Record->hasDeclaredDestructor() &&
620 CanDeclareSpecialMemberFunction(S.Context, Record))
621 S.DeclareImplicitDestructor(const_cast<CXXRecordDecl *>(Record));
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000622 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000623
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000624 case DeclarationName::CXXOperatorName:
625 if (Name.getCXXOverloadedOperator() != OO_Equal)
626 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000627
Sebastian Redl22653ba2011-08-30 19:58:05 +0000628 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC)) {
629 if (Record->getDefinition() &&
630 CanDeclareSpecialMemberFunction(S.Context, Record)) {
631 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(Record);
632 if (!Record->hasDeclaredCopyAssignment())
633 S.DeclareImplicitCopyAssignment(Class);
634 if (S.getLangOptions().CPlusPlus0x &&
635 Record->needsImplicitMoveAssignment())
636 S.DeclareImplicitMoveAssignment(Class);
637 }
638 }
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000639 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000640
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000641 default:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000642 break;
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000643 }
644}
Douglas Gregor7454c562010-07-02 20:37:36 +0000645
John McCall9f3059a2009-10-09 21:13:30 +0000646// Adds all qualifying matches for a name within a decl context to the
647// given lookup result. Returns true if any matches were found.
Douglas Gregord3a59182010-02-12 05:48:04 +0000648static bool LookupDirect(Sema &S, LookupResult &R, const DeclContext *DC) {
John McCall9f3059a2009-10-09 21:13:30 +0000649 bool Found = false;
650
Douglas Gregor7454c562010-07-02 20:37:36 +0000651 // Lazily declare C++ special member functions.
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000652 if (S.getLangOptions().CPlusPlus)
653 DeclareImplicitMemberFunctionsWithName(S, R.getLookupName(), DC);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000654
Douglas Gregor7454c562010-07-02 20:37:36 +0000655 // Perform lookup into this declaration context.
John McCallf6c8a4e2009-11-10 07:01:13 +0000656 DeclContext::lookup_const_iterator I, E;
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000657 for (llvm::tie(I, E) = DC->lookup(R.getLookupName()); I != E; ++I) {
John McCall401982f2010-01-20 21:53:11 +0000658 NamedDecl *D = *I;
Douglas Gregor4a814562011-12-14 16:03:29 +0000659 if ((D = R.getAcceptableDecl(D))) {
John McCall401982f2010-01-20 21:53:11 +0000660 R.addDecl(D);
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000661 Found = true;
662 }
663 }
John McCall9f3059a2009-10-09 21:13:30 +0000664
Douglas Gregord3a59182010-02-12 05:48:04 +0000665 if (!Found && DC->isTranslationUnit() && LookupBuiltin(S, R))
666 return true;
667
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000668 if (R.getLookupName().getNameKind()
Chandler Carruth3a693b72010-01-31 11:44:02 +0000669 != DeclarationName::CXXConversionFunctionName ||
670 R.getLookupName().getCXXNameType()->isDependentType() ||
671 !isa<CXXRecordDecl>(DC))
672 return Found;
673
674 // C++ [temp.mem]p6:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000675 // A specialization of a conversion function template is not found by
Chandler Carruth3a693b72010-01-31 11:44:02 +0000676 // name lookup. Instead, any conversion function templates visible in the
677 // context of the use are considered. [...]
678 const CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
John McCallf937c022011-10-07 06:10:15 +0000679 if (!Record->isCompleteDefinition())
Chandler Carruth3a693b72010-01-31 11:44:02 +0000680 return Found;
681
682 const UnresolvedSetImpl *Unresolved = Record->getConversionFunctions();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000683 for (UnresolvedSetImpl::iterator U = Unresolved->begin(),
Chandler Carruth3a693b72010-01-31 11:44:02 +0000684 UEnd = Unresolved->end(); U != UEnd; ++U) {
685 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(*U);
686 if (!ConvTemplate)
687 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000688
Chandler Carruth3a693b72010-01-31 11:44:02 +0000689 // When we're performing lookup for the purposes of redeclaration, just
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000690 // add the conversion function template. When we deduce template
691 // arguments for specializations, we'll end up unifying the return
Chandler Carruth3a693b72010-01-31 11:44:02 +0000692 // type of the new declaration with the type of the function template.
693 if (R.isForRedeclaration()) {
694 R.addDecl(ConvTemplate);
695 Found = true;
696 continue;
697 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000698
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000699 // C++ [temp.mem]p6:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000700 // [...] For each such operator, if argument deduction succeeds
701 // (14.9.2.3), the resulting specialization is used as if found by
Chandler Carruth3a693b72010-01-31 11:44:02 +0000702 // name lookup.
703 //
704 // When referencing a conversion function for any purpose other than
705 // a redeclaration (such that we'll be building an expression with the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000706 // result), perform template argument deduction and place the
Chandler Carruth3a693b72010-01-31 11:44:02 +0000707 // specialization into the result set. We do this to avoid forcing all
708 // callers to perform special deduction for conversion functions.
John McCall19c1bfd2010-08-25 05:32:35 +0000709 TemplateDeductionInfo Info(R.getSema().Context, R.getNameLoc());
Chandler Carruth3a693b72010-01-31 11:44:02 +0000710 FunctionDecl *Specialization = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000711
712 const FunctionProtoType *ConvProto
Chandler Carruth3a693b72010-01-31 11:44:02 +0000713 = ConvTemplate->getTemplatedDecl()->getType()->getAs<FunctionProtoType>();
714 assert(ConvProto && "Nonsensical conversion function template type");
Douglas Gregor3c96a462010-01-12 01:17:50 +0000715
Chandler Carruth3a693b72010-01-31 11:44:02 +0000716 // Compute the type of the function that we would expect the conversion
717 // function to have, if it were to match the name given.
718 // FIXME: Calling convention!
John McCalldb40c7f2010-12-14 08:05:40 +0000719 FunctionProtoType::ExtProtoInfo EPI = ConvProto->getExtProtoInfo();
720 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(CC_Default);
Sebastian Redl7c6c9e92011-03-06 10:52:04 +0000721 EPI.ExceptionSpecType = EST_None;
John McCalldb40c7f2010-12-14 08:05:40 +0000722 EPI.NumExceptions = 0;
Chandler Carruth3a693b72010-01-31 11:44:02 +0000723 QualType ExpectedType
724 = R.getSema().Context.getFunctionType(R.getLookupName().getCXXNameType(),
John McCalldb40c7f2010-12-14 08:05:40 +0000725 0, 0, EPI);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000726
Chandler Carruth3a693b72010-01-31 11:44:02 +0000727 // Perform template argument deduction against the type that we would
728 // expect the function to have.
729 if (R.getSema().DeduceTemplateArguments(ConvTemplate, 0, ExpectedType,
730 Specialization, Info)
731 == Sema::TDK_Success) {
732 R.addDecl(Specialization);
733 Found = true;
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000734 }
735 }
Chandler Carruth3a693b72010-01-31 11:44:02 +0000736
John McCall9f3059a2009-10-09 21:13:30 +0000737 return Found;
738}
739
John McCallf6c8a4e2009-11-10 07:01:13 +0000740// Performs C++ unqualified lookup into the given file context.
John McCall9f3059a2009-10-09 21:13:30 +0000741static bool
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000742CppNamespaceLookup(Sema &S, LookupResult &R, ASTContext &Context,
Douglas Gregord3a59182010-02-12 05:48:04 +0000743 DeclContext *NS, UnqualUsingDirectiveSet &UDirs) {
Douglas Gregor700792c2009-02-05 19:25:20 +0000744
745 assert(NS && NS->isFileContext() && "CppNamespaceLookup() requires namespace!");
746
John McCallf6c8a4e2009-11-10 07:01:13 +0000747 // Perform direct name lookup into the LookupCtx.
Douglas Gregord3a59182010-02-12 05:48:04 +0000748 bool Found = LookupDirect(S, R, NS);
Douglas Gregor700792c2009-02-05 19:25:20 +0000749
John McCallf6c8a4e2009-11-10 07:01:13 +0000750 // Perform direct name lookup into the namespaces nominated by the
751 // using directives whose common ancestor is this namespace.
752 UnqualUsingDirectiveSet::const_iterator UI, UEnd;
753 llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(NS);
Mike Stump11289f42009-09-09 15:08:12 +0000754
John McCallf6c8a4e2009-11-10 07:01:13 +0000755 for (; UI != UEnd; ++UI)
Douglas Gregord3a59182010-02-12 05:48:04 +0000756 if (LookupDirect(S, R, UI->getNominatedNamespace()))
John McCallf6c8a4e2009-11-10 07:01:13 +0000757 Found = true;
John McCall9f3059a2009-10-09 21:13:30 +0000758
759 R.resolveKind();
760
761 return Found;
Douglas Gregor700792c2009-02-05 19:25:20 +0000762}
763
764static bool isNamespaceOrTranslationUnitScope(Scope *S) {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000765 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Douglas Gregor700792c2009-02-05 19:25:20 +0000766 return Ctx->isFileContext();
767 return false;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000768}
Douglas Gregored8f2882009-01-30 01:04:22 +0000769
Douglas Gregor66230062010-03-15 14:33:29 +0000770// Find the next outer declaration context from this scope. This
771// routine actually returns the semantic outer context, which may
772// differ from the lexical context (encoded directly in the Scope
773// stack) when we are parsing a member of a class template. In this
774// case, the second element of the pair will be true, to indicate that
775// name lookup should continue searching in this semantic context when
776// it leaves the current template parameter scope.
777static std::pair<DeclContext *, bool> findOuterContext(Scope *S) {
778 DeclContext *DC = static_cast<DeclContext *>(S->getEntity());
779 DeclContext *Lexical = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000780 for (Scope *OuterS = S->getParent(); OuterS;
Douglas Gregor66230062010-03-15 14:33:29 +0000781 OuterS = OuterS->getParent()) {
782 if (OuterS->getEntity()) {
Douglas Gregorea166062010-03-15 15:26:48 +0000783 Lexical = static_cast<DeclContext *>(OuterS->getEntity());
Douglas Gregor66230062010-03-15 14:33:29 +0000784 break;
785 }
786 }
787
788 // C++ [temp.local]p8:
789 // In the definition of a member of a class template that appears
790 // outside of the namespace containing the class template
791 // definition, the name of a template-parameter hides the name of
792 // a member of this namespace.
793 //
794 // Example:
795 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000796 // namespace N {
797 // class C { };
Douglas Gregor66230062010-03-15 14:33:29 +0000798 //
799 // template<class T> class B {
800 // void f(T);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000801 // };
Douglas Gregor66230062010-03-15 14:33:29 +0000802 // }
803 //
804 // template<class C> void N::B<C>::f(C) {
805 // C b; // C is the template parameter, not N::C
806 // }
807 //
808 // In this example, the lexical context we return is the
809 // TranslationUnit, while the semantic context is the namespace N.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000810 if (!Lexical || !DC || !S->getParent() ||
Douglas Gregor66230062010-03-15 14:33:29 +0000811 !S->getParent()->isTemplateParamScope())
812 return std::make_pair(Lexical, false);
813
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000814 // Find the outermost template parameter scope.
Douglas Gregor66230062010-03-15 14:33:29 +0000815 // For the example, this is the scope for the template parameters of
816 // template<class C>.
817 Scope *OutermostTemplateScope = S->getParent();
818 while (OutermostTemplateScope->getParent() &&
819 OutermostTemplateScope->getParent()->isTemplateParamScope())
820 OutermostTemplateScope = OutermostTemplateScope->getParent();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000821
Douglas Gregor66230062010-03-15 14:33:29 +0000822 // Find the namespace context in which the original scope occurs. In
823 // the example, this is namespace N.
824 DeclContext *Semantic = DC;
825 while (!Semantic->isFileContext())
826 Semantic = Semantic->getParent();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000827
Douglas Gregor66230062010-03-15 14:33:29 +0000828 // Find the declaration context just outside of the template
829 // parameter scope. This is the context in which the template is
830 // being lexically declaration (a namespace context). In the
831 // example, this is the global scope.
832 if (Lexical->isFileContext() && !Lexical->Equals(Semantic) &&
833 Lexical->Encloses(Semantic))
834 return std::make_pair(Semantic, true);
835
836 return std::make_pair(Lexical, false);
Douglas Gregor7f737c02009-09-10 16:57:35 +0000837}
838
John McCall27b18f82009-11-17 02:14:36 +0000839bool Sema::CppLookupName(LookupResult &R, Scope *S) {
John McCallea305ed2009-12-18 10:40:03 +0000840 assert(getLangOptions().CPlusPlus && "Can perform only C++ lookup");
John McCall27b18f82009-11-17 02:14:36 +0000841
842 DeclarationName Name = R.getLookupName();
843
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000844 // If this is the name of an implicitly-declared special member function,
845 // go through the scope stack to implicitly declare
846 if (isImplicitlyDeclaredMemberFunctionName(Name)) {
847 for (Scope *PreS = S; PreS; PreS = PreS->getParent())
848 if (DeclContext *DC = static_cast<DeclContext *>(PreS->getEntity()))
849 DeclareImplicitMemberFunctionsWithName(*this, Name, DC);
850 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000851
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000852 // Implicitly declare member functions with the name we're looking for, if in
853 // fact we are in a scope where it matters.
854
Douglas Gregor889ceb72009-02-03 19:21:40 +0000855 Scope *Initial = S;
Mike Stump11289f42009-09-09 15:08:12 +0000856 IdentifierResolver::iterator
Douglas Gregor889ceb72009-02-03 19:21:40 +0000857 I = IdResolver.begin(Name),
858 IEnd = IdResolver.end();
Douglas Gregored8f2882009-01-30 01:04:22 +0000859
Douglas Gregor889ceb72009-02-03 19:21:40 +0000860 // First we lookup local scope.
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000861 // We don't consider using-directives, as per 7.3.4.p1 [namespace.udir]
Douglas Gregor889ceb72009-02-03 19:21:40 +0000862 // ...During unqualified name lookup (3.4.1), the names appear as if
863 // they were declared in the nearest enclosing namespace which contains
864 // both the using-directive and the nominated namespace.
Eli Friedman44b83ee2009-08-05 19:21:58 +0000865 // [Note: in this context, "contains" means "contains directly or
Mike Stump11289f42009-09-09 15:08:12 +0000866 // indirectly".
Douglas Gregor889ceb72009-02-03 19:21:40 +0000867 //
868 // For example:
869 // namespace A { int i; }
870 // void foo() {
871 // int i;
872 // {
873 // using namespace A;
874 // ++i; // finds local 'i', A::i appears at global scope
875 // }
876 // }
Douglas Gregor2ada0482009-02-04 17:27:36 +0000877 //
Douglas Gregor66230062010-03-15 14:33:29 +0000878 DeclContext *OutsideOfTemplateParamDC = 0;
Douglas Gregor700792c2009-02-05 19:25:20 +0000879 for (; S && !isNamespaceOrTranslationUnitScope(S); S = S->getParent()) {
Douglas Gregor3e51e172010-05-20 20:58:56 +0000880 DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity());
881
Douglas Gregor889ceb72009-02-03 19:21:40 +0000882 // Check whether the IdResolver has anything in this scope.
John McCall9f3059a2009-10-09 21:13:30 +0000883 bool Found = false;
John McCall48871652010-08-21 09:40:31 +0000884 for (; I != IEnd && S->isDeclScope(*I); ++I) {
Douglas Gregor4a814562011-12-14 16:03:29 +0000885 if (NamedDecl *ND = R.getAcceptableDecl(*I)) {
John McCall9f3059a2009-10-09 21:13:30 +0000886 Found = true;
Douglas Gregor4a814562011-12-14 16:03:29 +0000887 R.addDecl(ND);
Douglas Gregor889ceb72009-02-03 19:21:40 +0000888 }
889 }
John McCall9f3059a2009-10-09 21:13:30 +0000890 if (Found) {
891 R.resolveKind();
Douglas Gregor3e51e172010-05-20 20:58:56 +0000892 if (S->isClassScope())
893 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(Ctx))
894 R.setNamingClass(Record);
John McCall9f3059a2009-10-09 21:13:30 +0000895 return true;
896 }
897
Douglas Gregor66230062010-03-15 14:33:29 +0000898 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
899 S->getParent() && !S->getParent()->isTemplateParamScope()) {
900 // We've just searched the last template parameter scope and
901 // found nothing, so look into the the contexts between the
902 // lexical and semantic declaration contexts returned by
903 // findOuterContext(). This implements the name lookup behavior
904 // of C++ [temp.local]p8.
905 Ctx = OutsideOfTemplateParamDC;
906 OutsideOfTemplateParamDC = 0;
907 }
908
909 if (Ctx) {
910 DeclContext *OuterCtx;
911 bool SearchAfterTemplateScope;
912 llvm::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
913 if (SearchAfterTemplateScope)
914 OutsideOfTemplateParamDC = OuterCtx;
915
Douglas Gregorea166062010-03-15 15:26:48 +0000916 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
Douglas Gregor337caf92010-02-19 16:08:35 +0000917 // We do not directly look into transparent contexts, since
918 // those entities will be found in the nearest enclosing
919 // non-transparent context.
920 if (Ctx->isTransparentContext())
Douglas Gregor7f737c02009-09-10 16:57:35 +0000921 continue;
Douglas Gregor337caf92010-02-19 16:08:35 +0000922
923 // We do not look directly into function or method contexts,
924 // since all of the local variables and parameters of the
925 // function/method are present within the Scope.
926 if (Ctx->isFunctionOrMethod()) {
927 // If we have an Objective-C instance method, look for ivars
928 // in the corresponding interface.
929 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
930 if (Method->isInstanceMethod() && Name.getAsIdentifierInfo())
931 if (ObjCInterfaceDecl *Class = Method->getClassInterface()) {
932 ObjCInterfaceDecl *ClassDeclared;
933 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000934 Name.getAsIdentifierInfo(),
Douglas Gregor337caf92010-02-19 16:08:35 +0000935 ClassDeclared)) {
Douglas Gregor4a814562011-12-14 16:03:29 +0000936 if (NamedDecl *ND = R.getAcceptableDecl(Ivar)) {
937 R.addDecl(ND);
Douglas Gregor337caf92010-02-19 16:08:35 +0000938 R.resolveKind();
939 return true;
940 }
941 }
942 }
943 }
944
945 continue;
946 }
947
Douglas Gregor7f737c02009-09-10 16:57:35 +0000948 // Perform qualified name lookup into this context.
949 // FIXME: In some cases, we know that every name that could be found by
950 // this qualified name lookup will also be on the identifier chain. For
951 // example, inside a class without any base classes, we never need to
952 // perform qualified lookup because all of the members are on top of the
953 // identifier chain.
Douglas Gregord0d2ee02010-01-15 01:44:47 +0000954 if (LookupQualifiedName(R, Ctx, /*InUnqualifiedLookup=*/true))
John McCall9f3059a2009-10-09 21:13:30 +0000955 return true;
Douglas Gregorfdca4a72009-03-27 04:21:56 +0000956 }
Douglas Gregor700792c2009-02-05 19:25:20 +0000957 }
Douglas Gregored8f2882009-01-30 01:04:22 +0000958 }
Douglas Gregor889ceb72009-02-03 19:21:40 +0000959
John McCallf6c8a4e2009-11-10 07:01:13 +0000960 // Stop if we ran out of scopes.
961 // FIXME: This really, really shouldn't be happening.
962 if (!S) return false;
963
Argyrios Kyrtzidis706bbf82010-10-29 16:12:50 +0000964 // If we are looking for members, no need to look into global/namespace scope.
965 if (R.getLookupKind() == LookupMemberName)
966 return false;
967
Douglas Gregor700792c2009-02-05 19:25:20 +0000968 // Collect UsingDirectiveDecls in all scopes, and recursively all
Douglas Gregor889ceb72009-02-03 19:21:40 +0000969 // nominated namespaces by those using-directives.
John McCallf6c8a4e2009-11-10 07:01:13 +0000970 //
Mike Stump87c57ac2009-05-16 07:39:55 +0000971 // FIXME: Cache this sorted list in Scope structure, and DeclContext, so we
972 // don't build it for each lookup!
Douglas Gregor889ceb72009-02-03 19:21:40 +0000973
John McCallf6c8a4e2009-11-10 07:01:13 +0000974 UnqualUsingDirectiveSet UDirs;
975 UDirs.visitScopeChain(Initial, S);
976 UDirs.done();
Douglas Gregor889ceb72009-02-03 19:21:40 +0000977
Douglas Gregor700792c2009-02-05 19:25:20 +0000978 // Lookup namespace scope, and global scope.
Douglas Gregor889ceb72009-02-03 19:21:40 +0000979 // Unqualified name lookup in C++ requires looking into scopes
980 // that aren't strictly lexical, and therefore we walk through the
981 // context as well as walking through the scopes.
Douglas Gregor700792c2009-02-05 19:25:20 +0000982
Douglas Gregor889ceb72009-02-03 19:21:40 +0000983 for (; S; S = S->getParent()) {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000984 // Check whether the IdResolver has anything in this scope.
John McCall9f3059a2009-10-09 21:13:30 +0000985 bool Found = false;
John McCall48871652010-08-21 09:40:31 +0000986 for (; I != IEnd && S->isDeclScope(*I); ++I) {
Douglas Gregor4a814562011-12-14 16:03:29 +0000987 if (NamedDecl *ND = R.getAcceptableDecl(*I)) {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000988 // We found something. Look for anything else in our scope
989 // with this same name and in an acceptable identifier
990 // namespace, so that we can construct an overload set if we
991 // need to.
John McCall9f3059a2009-10-09 21:13:30 +0000992 Found = true;
Douglas Gregor4a814562011-12-14 16:03:29 +0000993 R.addDecl(ND);
Douglas Gregor889ceb72009-02-03 19:21:40 +0000994 }
995 }
996
Douglas Gregorf3d3ae62010-05-14 04:53:42 +0000997 if (Found && S->isTemplateParamScope()) {
John McCall9f3059a2009-10-09 21:13:30 +0000998 R.resolveKind();
999 return true;
1000 }
1001
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001002 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
1003 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
1004 S->getParent() && !S->getParent()->isTemplateParamScope()) {
1005 // We've just searched the last template parameter scope and
1006 // found nothing, so look into the the contexts between the
1007 // lexical and semantic declaration contexts returned by
1008 // findOuterContext(). This implements the name lookup behavior
1009 // of C++ [temp.local]p8.
1010 Ctx = OutsideOfTemplateParamDC;
1011 OutsideOfTemplateParamDC = 0;
1012 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001013
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001014 if (Ctx) {
1015 DeclContext *OuterCtx;
1016 bool SearchAfterTemplateScope;
1017 llvm::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
1018 if (SearchAfterTemplateScope)
1019 OutsideOfTemplateParamDC = OuterCtx;
1020
1021 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
1022 // We do not directly look into transparent contexts, since
1023 // those entities will be found in the nearest enclosing
1024 // non-transparent context.
1025 if (Ctx->isTransparentContext())
1026 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001027
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001028 // If we have a context, and it's not a context stashed in the
1029 // template parameter scope for an out-of-line definition, also
1030 // look into that context.
1031 if (!(Found && S && S->isTemplateParamScope())) {
1032 assert(Ctx->isFileContext() &&
1033 "We should have been looking only at file context here already.");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001034
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001035 // Look into context considering using-directives.
1036 if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs))
1037 Found = true;
1038 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001039
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001040 if (Found) {
1041 R.resolveKind();
1042 return true;
1043 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001044
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001045 if (R.isForRedeclaration() && !Ctx->isTransparentContext())
1046 return false;
1047 }
1048 }
1049
Douglas Gregor3ce74932010-02-05 07:07:10 +00001050 if (R.isForRedeclaration() && Ctx && !Ctx->isTransparentContext())
John McCall9f3059a2009-10-09 21:13:30 +00001051 return false;
Douglas Gregor700792c2009-02-05 19:25:20 +00001052 }
Douglas Gregor889ceb72009-02-03 19:21:40 +00001053
John McCall9f3059a2009-10-09 21:13:30 +00001054 return !R.empty();
Douglas Gregored8f2882009-01-30 01:04:22 +00001055}
1056
Douglas Gregor4a814562011-12-14 16:03:29 +00001057/// \brief Retrieve the visible declaration corresponding to D, if any.
1058///
1059/// This routine determines whether the declaration D is visible in the current
1060/// module, with the current imports. If not, it checks whether any
1061/// redeclaration of D is visible, and if so, returns that declaration.
1062///
1063/// \returns D, or a visible previous declaration of D, whichever is more recent
1064/// and visible. If no declaration of D is visible, returns null.
1065static NamedDecl *getVisibleDecl(NamedDecl *D) {
1066 if (LookupResult::isVisible(D))
1067 return D;
1068
Douglas Gregor54079202012-01-06 22:05:37 +00001069 for (Decl::redecl_iterator RD = D->redecls_begin(), RDEnd = D->redecls_end();
1070 RD != RDEnd; ++RD) {
1071 if (NamedDecl *ND = dyn_cast<NamedDecl>(*RD)) {
1072 if (LookupResult::isVisible(ND))
1073 return ND;
1074 }
Douglas Gregor4a814562011-12-14 16:03:29 +00001075 }
1076
1077 return 0;
1078}
1079
Douglas Gregor34074322009-01-14 22:20:51 +00001080/// @brief Perform unqualified name lookup starting from a given
1081/// scope.
1082///
1083/// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is
1084/// used to find names within the current scope. For example, 'x' in
1085/// @code
1086/// int x;
1087/// int f() {
1088/// return x; // unqualified name look finds 'x' in the global scope
1089/// }
1090/// @endcode
1091///
1092/// Different lookup criteria can find different names. For example, a
1093/// particular scope can have both a struct and a function of the same
1094/// name, and each can be found by certain lookup criteria. For more
1095/// information about lookup criteria, see the documentation for the
1096/// class LookupCriteria.
1097///
1098/// @param S The scope from which unqualified name lookup will
1099/// begin. If the lookup criteria permits, name lookup may also search
1100/// in the parent scopes.
1101///
1102/// @param Name The name of the entity that we are searching for.
1103///
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001104/// @param Loc If provided, the source location where we're performing
Mike Stump11289f42009-09-09 15:08:12 +00001105/// name lookup. At present, this is only used to produce diagnostics when
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001106/// C library functions (like "malloc") are implicitly declared.
Douglas Gregor34074322009-01-14 22:20:51 +00001107///
1108/// @returns The result of name lookup, which includes zero or more
1109/// declarations and possibly additional information used to diagnose
1110/// ambiguities.
John McCall27b18f82009-11-17 02:14:36 +00001111bool Sema::LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation) {
1112 DeclarationName Name = R.getLookupName();
John McCall9f3059a2009-10-09 21:13:30 +00001113 if (!Name) return false;
Douglas Gregor34074322009-01-14 22:20:51 +00001114
John McCall27b18f82009-11-17 02:14:36 +00001115 LookupNameKind NameKind = R.getLookupKind();
1116
Douglas Gregor34074322009-01-14 22:20:51 +00001117 if (!getLangOptions().CPlusPlus) {
1118 // Unqualified name lookup in C/Objective-C is purely lexical, so
1119 // search in the declarations attached to the name.
John McCallea305ed2009-12-18 10:40:03 +00001120 if (NameKind == Sema::LookupRedeclarationWithLinkage) {
Douglas Gregoreddf4332009-02-24 20:03:32 +00001121 // Find the nearest non-transparent declaration scope.
1122 while (!(S->getFlags() & Scope::DeclScope) ||
Mike Stump11289f42009-09-09 15:08:12 +00001123 (S->getEntity() &&
Douglas Gregoreddf4332009-02-24 20:03:32 +00001124 static_cast<DeclContext *>(S->getEntity())
1125 ->isTransparentContext()))
1126 S = S->getParent();
Douglas Gregored8f2882009-01-30 01:04:22 +00001127 }
1128
John McCallea305ed2009-12-18 10:40:03 +00001129 unsigned IDNS = R.getIdentifierNamespace();
1130
Douglas Gregor34074322009-01-14 22:20:51 +00001131 // Scan up the scope chain looking for a decl that matches this
1132 // identifier that is in the appropriate namespace. This search
1133 // should not take long, as shadowing of names is uncommon, and
1134 // deep shadowing is extremely uncommon.
Douglas Gregoreddf4332009-02-24 20:03:32 +00001135 bool LeftStartingScope = false;
1136
Douglas Gregored8f2882009-01-30 01:04:22 +00001137 for (IdentifierResolver::iterator I = IdResolver.begin(Name),
Mike Stump11289f42009-09-09 15:08:12 +00001138 IEnd = IdResolver.end();
Douglas Gregored8f2882009-01-30 01:04:22 +00001139 I != IEnd; ++I)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001140 if ((*I)->isInIdentifierNamespace(IDNS)) {
Douglas Gregoreddf4332009-02-24 20:03:32 +00001141 if (NameKind == LookupRedeclarationWithLinkage) {
1142 // Determine whether this (or a previous) declaration is
1143 // out-of-scope.
John McCall48871652010-08-21 09:40:31 +00001144 if (!LeftStartingScope && !S->isDeclScope(*I))
Douglas Gregoreddf4332009-02-24 20:03:32 +00001145 LeftStartingScope = true;
1146
1147 // If we found something outside of our starting scope that
1148 // does not have linkage, skip it.
1149 if (LeftStartingScope && !((*I)->hasLinkage()))
1150 continue;
1151 }
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00001152 else if (NameKind == LookupObjCImplicitSelfParam &&
1153 !isa<ImplicitParamDecl>(*I))
1154 continue;
1155
Douglas Gregor2a5d1482011-12-02 20:08:44 +00001156 // If this declaration is module-private and it came from an AST
1157 // file, we can't see it.
Douglas Gregor5c193c72012-01-05 01:11:47 +00001158 NamedDecl *D = R.isHiddenDeclarationVisible()? *I : getVisibleDecl(*I);
Douglas Gregor4a814562011-12-14 16:03:29 +00001159 if (!D)
Douglas Gregor2a5d1482011-12-02 20:08:44 +00001160 continue;
Douglas Gregor4a814562011-12-14 16:03:29 +00001161
1162 R.addDecl(D);
John McCall9f3059a2009-10-09 21:13:30 +00001163
Douglas Gregorb59643b2012-01-03 23:26:26 +00001164 // Check whether there are any other declarations with the same name
1165 // and in the same scope.
Douglas Gregor9b7b3912012-01-04 16:44:10 +00001166 if (I != IEnd) {
Douglas Gregor81bd0382012-01-13 23:06:53 +00001167 // Find the scope in which this declaration was declared (if it
1168 // actually exists in a Scope).
1169 while (S && !S->isDeclScope(D))
1170 S = S->getParent();
1171
1172 // If the scope containing the declaration is the translation unit,
1173 // then we'll need to perform our checks based on the matching
1174 // DeclContexts rather than matching scopes.
1175 if (S && isNamespaceOrTranslationUnitScope(S))
1176 S = 0;
1177
1178 // Compute the DeclContext, if we need it.
1179 DeclContext *DC = 0;
1180 if (!S)
1181 DC = (*I)->getDeclContext()->getRedeclContext();
1182
Douglas Gregor9b7b3912012-01-04 16:44:10 +00001183 IdentifierResolver::iterator LastI = I;
1184 for (++LastI; LastI != IEnd; ++LastI) {
Douglas Gregor81bd0382012-01-13 23:06:53 +00001185 if (S) {
1186 // Match based on scope.
1187 if (!S->isDeclScope(*LastI))
1188 break;
1189 } else {
1190 // Match based on DeclContext.
1191 DeclContext *LastDC
1192 = (*LastI)->getDeclContext()->getRedeclContext();
1193 if (!LastDC->Equals(DC))
1194 break;
1195 }
1196
1197 // If the declaration isn't in the right namespace, skip it.
Douglas Gregor9b7b3912012-01-04 16:44:10 +00001198 if (!(*LastI)->isInIdentifierNamespace(IDNS))
1199 continue;
Douglas Gregor81bd0382012-01-13 23:06:53 +00001200
Douglas Gregor5c193c72012-01-05 01:11:47 +00001201 D = R.isHiddenDeclarationVisible()? *LastI : getVisibleDecl(*LastI);
Douglas Gregor9b7b3912012-01-04 16:44:10 +00001202 if (D)
1203 R.addDecl(D);
1204 }
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001205
Douglas Gregor9b7b3912012-01-04 16:44:10 +00001206 R.resolveKind();
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001207 }
John McCall9f3059a2009-10-09 21:13:30 +00001208 return true;
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001209 }
Douglas Gregor34074322009-01-14 22:20:51 +00001210 } else {
Douglas Gregor889ceb72009-02-03 19:21:40 +00001211 // Perform C++ unqualified name lookup.
John McCall27b18f82009-11-17 02:14:36 +00001212 if (CppLookupName(R, S))
John McCall9f3059a2009-10-09 21:13:30 +00001213 return true;
Douglas Gregor34074322009-01-14 22:20:51 +00001214 }
1215
1216 // If we didn't find a use of this identifier, and if the identifier
1217 // corresponds to a compiler builtin, create the decl object for the builtin
1218 // now, injecting it into translation unit scope, and return it.
Axel Naumann43dec142011-04-13 13:19:46 +00001219 if (AllowBuiltinCreation && LookupBuiltin(*this, R))
1220 return true;
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001221
Axel Naumann016538a2011-02-24 16:47:47 +00001222 // If we didn't find a use of this identifier, the ExternalSource
1223 // may be able to handle the situation.
1224 // Note: some lookup failures are expected!
1225 // See e.g. R.isForRedeclaration().
1226 return (ExternalSource && ExternalSource->LookupUnqualified(R, S));
Douglas Gregor34074322009-01-14 22:20:51 +00001227}
1228
John McCall6538c932009-10-10 05:48:19 +00001229/// @brief Perform qualified name lookup in the namespaces nominated by
1230/// using directives by the given context.
1231///
1232/// C++98 [namespace.qual]p2:
1233/// Given X::m (where X is a user-declared namespace), or given ::m
1234/// (where X is the global namespace), let S be the set of all
1235/// declarations of m in X and in the transitive closure of all
1236/// namespaces nominated by using-directives in X and its used
1237/// namespaces, except that using-directives are ignored in any
1238/// namespace, including X, directly containing one or more
1239/// declarations of m. No namespace is searched more than once in
1240/// the lookup of a name. If S is the empty set, the program is
1241/// ill-formed. Otherwise, if S has exactly one member, or if the
1242/// context of the reference is a using-declaration
1243/// (namespace.udecl), S is the required set of declarations of
1244/// m. Otherwise if the use of m is not one that allows a unique
1245/// declaration to be chosen from S, the program is ill-formed.
1246/// C++98 [namespace.qual]p5:
1247/// During the lookup of a qualified namespace member name, if the
1248/// lookup finds more than one declaration of the member, and if one
1249/// declaration introduces a class name or enumeration name and the
1250/// other declarations either introduce the same object, the same
1251/// enumerator or a set of functions, the non-type name hides the
1252/// class or enumeration name if and only if the declarations are
1253/// from the same namespace; otherwise (the declarations are from
1254/// different namespaces), the program is ill-formed.
Douglas Gregord3a59182010-02-12 05:48:04 +00001255static bool LookupQualifiedNameInUsingDirectives(Sema &S, LookupResult &R,
John McCall27b18f82009-11-17 02:14:36 +00001256 DeclContext *StartDC) {
John McCall6538c932009-10-10 05:48:19 +00001257 assert(StartDC->isFileContext() && "start context is not a file context");
1258
1259 DeclContext::udir_iterator I = StartDC->using_directives_begin();
1260 DeclContext::udir_iterator E = StartDC->using_directives_end();
1261
1262 if (I == E) return false;
1263
1264 // We have at least added all these contexts to the queue.
Benjamin Kramer3adbe1c2012-02-23 16:06:01 +00001265 llvm::SmallPtrSet<DeclContext*, 8> Visited;
John McCall6538c932009-10-10 05:48:19 +00001266 Visited.insert(StartDC);
1267
1268 // We have not yet looked into these namespaces, much less added
1269 // their "using-children" to the queue.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001270 SmallVector<NamespaceDecl*, 8> Queue;
John McCall6538c932009-10-10 05:48:19 +00001271
1272 // We have already looked into the initial namespace; seed the queue
1273 // with its using-children.
1274 for (; I != E; ++I) {
John McCallb8be78b2009-11-10 09:25:37 +00001275 NamespaceDecl *ND = (*I)->getNominatedNamespace()->getOriginalNamespace();
Benjamin Kramer3adbe1c2012-02-23 16:06:01 +00001276 if (Visited.insert(ND))
John McCall6538c932009-10-10 05:48:19 +00001277 Queue.push_back(ND);
1278 }
1279
1280 // The easiest way to implement the restriction in [namespace.qual]p5
1281 // is to check whether any of the individual results found a tag
1282 // and, if so, to declare an ambiguity if the final result is not
1283 // a tag.
1284 bool FoundTag = false;
1285 bool FoundNonTag = false;
1286
John McCall5cebab12009-11-18 07:57:50 +00001287 LookupResult LocalR(LookupResult::Temporary, R);
John McCall6538c932009-10-10 05:48:19 +00001288
1289 bool Found = false;
1290 while (!Queue.empty()) {
1291 NamespaceDecl *ND = Queue.back();
1292 Queue.pop_back();
1293
1294 // We go through some convolutions here to avoid copying results
1295 // between LookupResults.
1296 bool UseLocal = !R.empty();
John McCall5cebab12009-11-18 07:57:50 +00001297 LookupResult &DirectR = UseLocal ? LocalR : R;
Douglas Gregord3a59182010-02-12 05:48:04 +00001298 bool FoundDirect = LookupDirect(S, DirectR, ND);
John McCall6538c932009-10-10 05:48:19 +00001299
1300 if (FoundDirect) {
1301 // First do any local hiding.
1302 DirectR.resolveKind();
1303
1304 // If the local result is a tag, remember that.
1305 if (DirectR.isSingleTagDecl())
1306 FoundTag = true;
1307 else
1308 FoundNonTag = true;
1309
1310 // Append the local results to the total results if necessary.
1311 if (UseLocal) {
1312 R.addAllDecls(LocalR);
1313 LocalR.clear();
1314 }
1315 }
1316
1317 // If we find names in this namespace, ignore its using directives.
1318 if (FoundDirect) {
1319 Found = true;
1320 continue;
1321 }
1322
1323 for (llvm::tie(I,E) = ND->getUsingDirectives(); I != E; ++I) {
1324 NamespaceDecl *Nom = (*I)->getNominatedNamespace();
Benjamin Kramer3adbe1c2012-02-23 16:06:01 +00001325 if (Visited.insert(Nom))
John McCall6538c932009-10-10 05:48:19 +00001326 Queue.push_back(Nom);
1327 }
1328 }
1329
1330 if (Found) {
1331 if (FoundTag && FoundNonTag)
1332 R.setAmbiguousQualifiedTagHiding();
1333 else
1334 R.resolveKind();
1335 }
1336
1337 return Found;
1338}
1339
Douglas Gregor39982192010-08-15 06:18:01 +00001340/// \brief Callback that looks for any member of a class with the given name.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001341static bool LookupAnyMember(const CXXBaseSpecifier *Specifier,
Douglas Gregor39982192010-08-15 06:18:01 +00001342 CXXBasePath &Path,
1343 void *Name) {
1344 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001345
Douglas Gregor39982192010-08-15 06:18:01 +00001346 DeclarationName N = DeclarationName::getFromOpaquePtr(Name);
1347 Path.Decls = BaseRecord->lookup(N);
1348 return Path.Decls.first != Path.Decls.second;
1349}
1350
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001351/// \brief Determine whether the given set of member declarations contains only
Douglas Gregorc0d24902010-10-22 22:08:47 +00001352/// static members, nested types, and enumerators.
1353template<typename InputIterator>
1354static bool HasOnlyStaticMembers(InputIterator First, InputIterator Last) {
1355 Decl *D = (*First)->getUnderlyingDecl();
1356 if (isa<VarDecl>(D) || isa<TypeDecl>(D) || isa<EnumConstantDecl>(D))
1357 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001358
Douglas Gregorc0d24902010-10-22 22:08:47 +00001359 if (isa<CXXMethodDecl>(D)) {
1360 // Determine whether all of the methods are static.
1361 bool AllMethodsAreStatic = true;
1362 for(; First != Last; ++First) {
1363 D = (*First)->getUnderlyingDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001364
Douglas Gregorc0d24902010-10-22 22:08:47 +00001365 if (!isa<CXXMethodDecl>(D)) {
1366 assert(isa<TagDecl>(D) && "Non-function must be a tag decl");
1367 break;
1368 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001369
Douglas Gregorc0d24902010-10-22 22:08:47 +00001370 if (!cast<CXXMethodDecl>(D)->isStatic()) {
1371 AllMethodsAreStatic = false;
1372 break;
1373 }
1374 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001375
Douglas Gregorc0d24902010-10-22 22:08:47 +00001376 if (AllMethodsAreStatic)
1377 return true;
1378 }
1379
1380 return false;
1381}
1382
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001383/// \brief Perform qualified name lookup into a given context.
Douglas Gregor34074322009-01-14 22:20:51 +00001384///
1385/// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
1386/// names when the context of those names is explicit specified, e.g.,
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001387/// "std::vector" or "x->member", or as part of unqualified name lookup.
Douglas Gregor34074322009-01-14 22:20:51 +00001388///
1389/// Different lookup criteria can find different names. For example, a
1390/// particular scope can have both a struct and a function of the same
1391/// name, and each can be found by certain lookup criteria. For more
1392/// information about lookup criteria, see the documentation for the
1393/// class LookupCriteria.
1394///
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001395/// \param R captures both the lookup criteria and any lookup results found.
1396///
1397/// \param LookupCtx The context in which qualified name lookup will
Douglas Gregor34074322009-01-14 22:20:51 +00001398/// search. If the lookup criteria permits, name lookup may also search
1399/// in the parent contexts or (for C++ classes) base classes.
1400///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001401/// \param InUnqualifiedLookup true if this is qualified name lookup that
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001402/// occurs as part of unqualified name lookup.
Douglas Gregor34074322009-01-14 22:20:51 +00001403///
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001404/// \returns true if lookup succeeded, false if it failed.
1405bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
1406 bool InUnqualifiedLookup) {
Douglas Gregor34074322009-01-14 22:20:51 +00001407 assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context");
Mike Stump11289f42009-09-09 15:08:12 +00001408
John McCall27b18f82009-11-17 02:14:36 +00001409 if (!R.getLookupName())
John McCall9f3059a2009-10-09 21:13:30 +00001410 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001411
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001412 // Make sure that the declaration context is complete.
1413 assert((!isa<TagDecl>(LookupCtx) ||
1414 LookupCtx->isDependentContext() ||
John McCallf937c022011-10-07 06:10:15 +00001415 cast<TagDecl>(LookupCtx)->isCompleteDefinition() ||
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001416 Context.getTypeDeclType(cast<TagDecl>(LookupCtx))->getAs<TagType>()
1417 ->isBeingDefined()) &&
1418 "Declaration context must already be complete!");
Mike Stump11289f42009-09-09 15:08:12 +00001419
Douglas Gregor34074322009-01-14 22:20:51 +00001420 // Perform qualified name lookup into the LookupCtx.
Douglas Gregord3a59182010-02-12 05:48:04 +00001421 if (LookupDirect(*this, R, LookupCtx)) {
John McCall9f3059a2009-10-09 21:13:30 +00001422 R.resolveKind();
John McCall553c0792010-01-23 00:46:32 +00001423 if (isa<CXXRecordDecl>(LookupCtx))
1424 R.setNamingClass(cast<CXXRecordDecl>(LookupCtx));
John McCall9f3059a2009-10-09 21:13:30 +00001425 return true;
1426 }
Douglas Gregor34074322009-01-14 22:20:51 +00001427
John McCall6538c932009-10-10 05:48:19 +00001428 // Don't descend into implied contexts for redeclarations.
1429 // C++98 [namespace.qual]p6:
1430 // In a declaration for a namespace member in which the
1431 // declarator-id is a qualified-id, given that the qualified-id
1432 // for the namespace member has the form
1433 // nested-name-specifier unqualified-id
1434 // the unqualified-id shall name a member of the namespace
1435 // designated by the nested-name-specifier.
1436 // See also [class.mfct]p5 and [class.static.data]p2.
John McCall27b18f82009-11-17 02:14:36 +00001437 if (R.isForRedeclaration())
John McCall6538c932009-10-10 05:48:19 +00001438 return false;
1439
John McCall27b18f82009-11-17 02:14:36 +00001440 // If this is a namespace, look it up in the implied namespaces.
John McCall6538c932009-10-10 05:48:19 +00001441 if (LookupCtx->isFileContext())
Douglas Gregord3a59182010-02-12 05:48:04 +00001442 return LookupQualifiedNameInUsingDirectives(*this, R, LookupCtx);
John McCall6538c932009-10-10 05:48:19 +00001443
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001444 // If this isn't a C++ class, we aren't allowed to look into base
Douglas Gregorcc2427c2009-09-11 22:57:37 +00001445 // classes, we're done.
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001446 CXXRecordDecl *LookupRec = dyn_cast<CXXRecordDecl>(LookupCtx);
Douglas Gregor5a5fcd82010-07-01 00:21:21 +00001447 if (!LookupRec || !LookupRec->getDefinition())
John McCall9f3059a2009-10-09 21:13:30 +00001448 return false;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001449
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001450 // If we're performing qualified name lookup into a dependent class,
1451 // then we are actually looking into a current instantiation. If we have any
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001452 // dependent base classes, then we either have to delay lookup until
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001453 // template instantiation time (at which point all bases will be available)
1454 // or we have to fail.
1455 if (!InUnqualifiedLookup && LookupRec->isDependentContext() &&
1456 LookupRec->hasAnyDependentBases()) {
1457 R.setNotFoundInCurrentInstantiation();
1458 return false;
1459 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001460
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001461 // Perform lookup into our base classes.
Douglas Gregor36d1b142009-10-06 17:59:45 +00001462 CXXBasePaths Paths;
1463 Paths.setOrigin(LookupRec);
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001464
1465 // Look for this member in our base classes
Douglas Gregor36d1b142009-10-06 17:59:45 +00001466 CXXRecordDecl::BaseMatchesCallback *BaseCallback = 0;
John McCall27b18f82009-11-17 02:14:36 +00001467 switch (R.getLookupKind()) {
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00001468 case LookupObjCImplicitSelfParam:
Douglas Gregor36d1b142009-10-06 17:59:45 +00001469 case LookupOrdinaryName:
1470 case LookupMemberName:
1471 case LookupRedeclarationWithLinkage:
1472 BaseCallback = &CXXRecordDecl::FindOrdinaryMember;
1473 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001474
Douglas Gregor36d1b142009-10-06 17:59:45 +00001475 case LookupTagName:
1476 BaseCallback = &CXXRecordDecl::FindTagMember;
1477 break;
John McCall84d87672009-12-10 09:41:52 +00001478
Douglas Gregor39982192010-08-15 06:18:01 +00001479 case LookupAnyName:
1480 BaseCallback = &LookupAnyMember;
1481 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001482
John McCall84d87672009-12-10 09:41:52 +00001483 case LookupUsingDeclName:
1484 // This lookup is for redeclarations only.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001485
Douglas Gregor36d1b142009-10-06 17:59:45 +00001486 case LookupOperatorName:
1487 case LookupNamespaceName:
1488 case LookupObjCProtocolName:
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001489 case LookupLabel:
Douglas Gregor36d1b142009-10-06 17:59:45 +00001490 // These lookups will never find a member in a C++ class (or base class).
John McCall9f3059a2009-10-09 21:13:30 +00001491 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001492
Douglas Gregor36d1b142009-10-06 17:59:45 +00001493 case LookupNestedNameSpecifierName:
1494 BaseCallback = &CXXRecordDecl::FindNestedNameSpecifierMember;
1495 break;
1496 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001497
John McCall27b18f82009-11-17 02:14:36 +00001498 if (!LookupRec->lookupInBases(BaseCallback,
1499 R.getLookupName().getAsOpaquePtr(), Paths))
John McCall9f3059a2009-10-09 21:13:30 +00001500 return false;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001501
John McCall553c0792010-01-23 00:46:32 +00001502 R.setNamingClass(LookupRec);
1503
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001504 // C++ [class.member.lookup]p2:
1505 // [...] If the resulting set of declarations are not all from
1506 // sub-objects of the same type, or the set has a nonstatic member
1507 // and includes members from distinct sub-objects, there is an
1508 // ambiguity and the program is ill-formed. Otherwise that set is
1509 // the result of the lookup.
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001510 QualType SubobjectType;
Daniel Dunbar435bbe02009-01-15 18:32:35 +00001511 int SubobjectNumber = 0;
John McCalla332b952010-03-18 23:49:19 +00001512 AccessSpecifier SubobjectAccess = AS_none;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001513
Douglas Gregor36d1b142009-10-06 17:59:45 +00001514 for (CXXBasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end();
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001515 Path != PathEnd; ++Path) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00001516 const CXXBasePathElement &PathElement = Path->back();
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001517
John McCall401982f2010-01-20 21:53:11 +00001518 // Pick the best (i.e. most permissive i.e. numerically lowest) access
1519 // across all paths.
1520 SubobjectAccess = std::min(SubobjectAccess, Path->Access);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001521
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001522 // Determine whether we're looking at a distinct sub-object or not.
1523 if (SubobjectType.isNull()) {
John McCall9f3059a2009-10-09 21:13:30 +00001524 // This is the first subobject we've looked at. Record its type.
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001525 SubobjectType = Context.getCanonicalType(PathElement.Base->getType());
1526 SubobjectNumber = PathElement.SubobjectNumber;
Douglas Gregorc0d24902010-10-22 22:08:47 +00001527 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001528 }
1529
Douglas Gregorc0d24902010-10-22 22:08:47 +00001530 if (SubobjectType
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001531 != Context.getCanonicalType(PathElement.Base->getType())) {
1532 // We found members of the given name in two subobjects of
Douglas Gregorc0d24902010-10-22 22:08:47 +00001533 // different types. If the declaration sets aren't the same, this
1534 // this lookup is ambiguous.
1535 if (HasOnlyStaticMembers(Path->Decls.first, Path->Decls.second)) {
1536 CXXBasePaths::paths_iterator FirstPath = Paths.begin();
1537 DeclContext::lookup_iterator FirstD = FirstPath->Decls.first;
1538 DeclContext::lookup_iterator CurrentD = Path->Decls.first;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001539
Douglas Gregorc0d24902010-10-22 22:08:47 +00001540 while (FirstD != FirstPath->Decls.second &&
1541 CurrentD != Path->Decls.second) {
1542 if ((*FirstD)->getUnderlyingDecl()->getCanonicalDecl() !=
1543 (*CurrentD)->getUnderlyingDecl()->getCanonicalDecl())
1544 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001545
Douglas Gregorc0d24902010-10-22 22:08:47 +00001546 ++FirstD;
1547 ++CurrentD;
1548 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001549
Douglas Gregorc0d24902010-10-22 22:08:47 +00001550 if (FirstD == FirstPath->Decls.second &&
1551 CurrentD == Path->Decls.second)
1552 continue;
1553 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001554
John McCall9f3059a2009-10-09 21:13:30 +00001555 R.setAmbiguousBaseSubobjectTypes(Paths);
1556 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001557 }
1558
Douglas Gregorc0d24902010-10-22 22:08:47 +00001559 if (SubobjectNumber != PathElement.SubobjectNumber) {
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001560 // We have a different subobject of the same type.
1561
1562 // C++ [class.member.lookup]p5:
1563 // A static member, a nested type or an enumerator defined in
1564 // a base class T can unambiguously be found even if an object
Mike Stump11289f42009-09-09 15:08:12 +00001565 // has more than one base class subobject of type T.
Douglas Gregorc0d24902010-10-22 22:08:47 +00001566 if (HasOnlyStaticMembers(Path->Decls.first, Path->Decls.second))
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001567 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001568
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001569 // We have found a nonstatic member name in multiple, distinct
1570 // subobjects. Name lookup is ambiguous.
John McCall9f3059a2009-10-09 21:13:30 +00001571 R.setAmbiguousBaseSubobjects(Paths);
1572 return true;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001573 }
1574 }
1575
1576 // Lookup in a base class succeeded; return these results.
1577
John McCall9f3059a2009-10-09 21:13:30 +00001578 DeclContext::lookup_iterator I, E;
John McCall553c0792010-01-23 00:46:32 +00001579 for (llvm::tie(I,E) = Paths.front().Decls; I != E; ++I) {
1580 NamedDecl *D = *I;
1581 AccessSpecifier AS = CXXRecordDecl::MergeAccess(SubobjectAccess,
1582 D->getAccess());
1583 R.addDecl(D, AS);
1584 }
John McCall9f3059a2009-10-09 21:13:30 +00001585 R.resolveKind();
1586 return true;
Douglas Gregor34074322009-01-14 22:20:51 +00001587}
1588
1589/// @brief Performs name lookup for a name that was parsed in the
1590/// source code, and may contain a C++ scope specifier.
1591///
1592/// This routine is a convenience routine meant to be called from
1593/// contexts that receive a name and an optional C++ scope specifier
1594/// (e.g., "N::M::x"). It will then perform either qualified or
1595/// unqualified name lookup (with LookupQualifiedName or LookupName,
1596/// respectively) on the given name and return those results.
1597///
1598/// @param S The scope from which unqualified name lookup will
1599/// begin.
Mike Stump11289f42009-09-09 15:08:12 +00001600///
Douglas Gregore861bac2009-08-25 22:51:20 +00001601/// @param SS An optional C++ scope-specifier, e.g., "::N::M".
Douglas Gregor34074322009-01-14 22:20:51 +00001602///
Douglas Gregore861bac2009-08-25 22:51:20 +00001603/// @param EnteringContext Indicates whether we are going to enter the
1604/// context of the scope-specifier SS (if present).
1605///
John McCall9f3059a2009-10-09 21:13:30 +00001606/// @returns True if any decls were found (but possibly ambiguous)
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001607bool Sema::LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
John McCall27b18f82009-11-17 02:14:36 +00001608 bool AllowBuiltinCreation, bool EnteringContext) {
Douglas Gregore861bac2009-08-25 22:51:20 +00001609 if (SS && SS->isInvalid()) {
1610 // When the scope specifier is invalid, don't even look for
Douglas Gregorc9f9b862009-05-11 19:58:34 +00001611 // anything.
John McCall9f3059a2009-10-09 21:13:30 +00001612 return false;
Douglas Gregore861bac2009-08-25 22:51:20 +00001613 }
Mike Stump11289f42009-09-09 15:08:12 +00001614
Douglas Gregore861bac2009-08-25 22:51:20 +00001615 if (SS && SS->isSet()) {
1616 if (DeclContext *DC = computeDeclContext(*SS, EnteringContext)) {
Mike Stump11289f42009-09-09 15:08:12 +00001617 // We have resolved the scope specifier to a particular declaration
Douglas Gregore861bac2009-08-25 22:51:20 +00001618 // contex, and will perform name lookup in that context.
John McCall0b66eb32010-05-01 00:40:08 +00001619 if (!DC->isDependentContext() && RequireCompleteDeclContext(*SS, DC))
John McCall9f3059a2009-10-09 21:13:30 +00001620 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001621
John McCall27b18f82009-11-17 02:14:36 +00001622 R.setContextRange(SS->getRange());
John McCall27b18f82009-11-17 02:14:36 +00001623 return LookupQualifiedName(R, DC);
Douglas Gregor52537682009-03-19 00:18:19 +00001624 }
Douglas Gregorc9f9b862009-05-11 19:58:34 +00001625
Douglas Gregore861bac2009-08-25 22:51:20 +00001626 // We could not resolve the scope specified to a specific declaration
Mike Stump11289f42009-09-09 15:08:12 +00001627 // context, which means that SS refers to an unknown specialization.
Douglas Gregore861bac2009-08-25 22:51:20 +00001628 // Name lookup can't find anything in this case.
Douglas Gregor89ab56d2011-10-24 22:24:50 +00001629 R.setNotFoundInCurrentInstantiation();
1630 R.setContextRange(SS->getRange());
John McCall9f3059a2009-10-09 21:13:30 +00001631 return false;
Douglas Gregored8f2882009-01-30 01:04:22 +00001632 }
1633
Mike Stump11289f42009-09-09 15:08:12 +00001634 // Perform unqualified name lookup starting in the given scope.
John McCall27b18f82009-11-17 02:14:36 +00001635 return LookupName(R, S, AllowBuiltinCreation);
Douglas Gregor34074322009-01-14 22:20:51 +00001636}
1637
Douglas Gregor889ceb72009-02-03 19:21:40 +00001638
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001639/// @brief Produce a diagnostic describing the ambiguity that resulted
1640/// from name lookup.
1641///
1642/// @param Result The ambiguous name lookup result.
Mike Stump11289f42009-09-09 15:08:12 +00001643///
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001644/// @param Name The name of the entity that name lookup was
1645/// searching for.
1646///
1647/// @param NameLoc The location of the name within the source code.
1648///
1649/// @param LookupRange A source range that provides more
1650/// source-location information concerning the lookup itself. For
1651/// example, this range might highlight a nested-name-specifier that
1652/// precedes the name.
1653///
1654/// @returns true
John McCall27b18f82009-11-17 02:14:36 +00001655bool Sema::DiagnoseAmbiguousLookup(LookupResult &Result) {
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001656 assert(Result.isAmbiguous() && "Lookup result must be ambiguous");
1657
John McCall27b18f82009-11-17 02:14:36 +00001658 DeclarationName Name = Result.getLookupName();
1659 SourceLocation NameLoc = Result.getNameLoc();
1660 SourceRange LookupRange = Result.getContextRange();
1661
John McCall6538c932009-10-10 05:48:19 +00001662 switch (Result.getAmbiguityKind()) {
1663 case LookupResult::AmbiguousBaseSubobjects: {
1664 CXXBasePaths *Paths = Result.getBasePaths();
1665 QualType SubobjectType = Paths->front().back().Base->getType();
1666 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects)
1667 << Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths)
1668 << LookupRange;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001669
John McCall6538c932009-10-10 05:48:19 +00001670 DeclContext::lookup_iterator Found = Paths->front().Decls.first;
1671 while (isa<CXXMethodDecl>(*Found) &&
1672 cast<CXXMethodDecl>(*Found)->isStatic())
1673 ++Found;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001674
John McCall6538c932009-10-10 05:48:19 +00001675 Diag((*Found)->getLocation(), diag::note_ambiguous_member_found);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001676
John McCall6538c932009-10-10 05:48:19 +00001677 return true;
1678 }
Douglas Gregor1c846b02009-01-16 00:38:09 +00001679
John McCall6538c932009-10-10 05:48:19 +00001680 case LookupResult::AmbiguousBaseSubobjectTypes: {
Douglas Gregor889ceb72009-02-03 19:21:40 +00001681 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types)
1682 << Name << LookupRange;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001683
John McCall6538c932009-10-10 05:48:19 +00001684 CXXBasePaths *Paths = Result.getBasePaths();
Douglas Gregor889ceb72009-02-03 19:21:40 +00001685 std::set<Decl *> DeclsPrinted;
John McCall6538c932009-10-10 05:48:19 +00001686 for (CXXBasePaths::paths_iterator Path = Paths->begin(),
1687 PathEnd = Paths->end();
Douglas Gregor889ceb72009-02-03 19:21:40 +00001688 Path != PathEnd; ++Path) {
1689 Decl *D = *Path->Decls.first;
1690 if (DeclsPrinted.insert(D).second)
1691 Diag(D->getLocation(), diag::note_ambiguous_member_found);
1692 }
1693
Douglas Gregor1c846b02009-01-16 00:38:09 +00001694 return true;
Douglas Gregor1c846b02009-01-16 00:38:09 +00001695 }
1696
John McCall6538c932009-10-10 05:48:19 +00001697 case LookupResult::AmbiguousTagHiding: {
1698 Diag(NameLoc, diag::err_ambiguous_tag_hiding) << Name << LookupRange;
Douglas Gregorf23311d2009-01-17 01:13:24 +00001699
John McCall6538c932009-10-10 05:48:19 +00001700 llvm::SmallPtrSet<NamedDecl*,8> TagDecls;
1701
1702 LookupResult::iterator DI, DE = Result.end();
1703 for (DI = Result.begin(); DI != DE; ++DI)
1704 if (TagDecl *TD = dyn_cast<TagDecl>(*DI)) {
1705 TagDecls.insert(TD);
1706 Diag(TD->getLocation(), diag::note_hidden_tag);
1707 }
1708
1709 for (DI = Result.begin(); DI != DE; ++DI)
1710 if (!isa<TagDecl>(*DI))
1711 Diag((*DI)->getLocation(), diag::note_hiding_object);
1712
1713 // For recovery purposes, go ahead and implement the hiding.
John McCallad371252010-01-20 00:46:10 +00001714 LookupResult::Filter F = Result.makeFilter();
1715 while (F.hasNext()) {
1716 if (TagDecls.count(F.next()))
1717 F.erase();
1718 }
1719 F.done();
John McCall6538c932009-10-10 05:48:19 +00001720
1721 return true;
1722 }
1723
1724 case LookupResult::AmbiguousReference: {
1725 Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001726
John McCall6538c932009-10-10 05:48:19 +00001727 LookupResult::iterator DI = Result.begin(), DE = Result.end();
1728 for (; DI != DE; ++DI)
1729 Diag((*DI)->getLocation(), diag::note_ambiguous_candidate) << *DI;
John McCall9f3059a2009-10-09 21:13:30 +00001730
John McCall6538c932009-10-10 05:48:19 +00001731 return true;
1732 }
1733 }
1734
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00001735 llvm_unreachable("unknown ambiguity kind");
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001736}
Douglas Gregore254f902009-02-04 00:32:51 +00001737
John McCallf24d7bb2010-05-28 18:45:08 +00001738namespace {
1739 struct AssociatedLookup {
1740 AssociatedLookup(Sema &S,
1741 Sema::AssociatedNamespaceSet &Namespaces,
1742 Sema::AssociatedClassSet &Classes)
1743 : S(S), Namespaces(Namespaces), Classes(Classes) {
1744 }
1745
1746 Sema &S;
1747 Sema::AssociatedNamespaceSet &Namespaces;
1748 Sema::AssociatedClassSet &Classes;
1749 };
1750}
1751
Mike Stump11289f42009-09-09 15:08:12 +00001752static void
John McCallf24d7bb2010-05-28 18:45:08 +00001753addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType T);
John McCallc7e8e792009-08-07 22:18:02 +00001754
Douglas Gregor8b895222010-04-30 07:08:38 +00001755static void CollectEnclosingNamespace(Sema::AssociatedNamespaceSet &Namespaces,
1756 DeclContext *Ctx) {
1757 // Add the associated namespace for this class.
1758
1759 // We don't use DeclContext::getEnclosingNamespaceContext() as this may
1760 // be a locally scoped record.
1761
Sebastian Redlbd595762010-08-31 20:53:31 +00001762 // We skip out of inline namespaces. The innermost non-inline namespace
1763 // contains all names of all its nested inline namespaces anyway, so we can
1764 // replace the entire inline namespace tree with its root.
1765 while (Ctx->isRecord() || Ctx->isTransparentContext() ||
1766 Ctx->isInlineNamespace())
Douglas Gregor8b895222010-04-30 07:08:38 +00001767 Ctx = Ctx->getParent();
1768
John McCallc7e8e792009-08-07 22:18:02 +00001769 if (Ctx->isFileContext())
Douglas Gregor8b895222010-04-30 07:08:38 +00001770 Namespaces.insert(Ctx->getPrimaryContext());
John McCallc7e8e792009-08-07 22:18:02 +00001771}
Douglas Gregor197e5f72009-07-08 07:51:57 +00001772
Mike Stump11289f42009-09-09 15:08:12 +00001773// \brief Add the associated classes and namespaces for argument-dependent
Douglas Gregor197e5f72009-07-08 07:51:57 +00001774// lookup that involves a template argument (C++ [basic.lookup.koenig]p2).
Mike Stump11289f42009-09-09 15:08:12 +00001775static void
John McCallf24d7bb2010-05-28 18:45:08 +00001776addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
1777 const TemplateArgument &Arg) {
Douglas Gregor197e5f72009-07-08 07:51:57 +00001778 // C++ [basic.lookup.koenig]p2, last bullet:
Mike Stump11289f42009-09-09 15:08:12 +00001779 // -- [...] ;
Douglas Gregor197e5f72009-07-08 07:51:57 +00001780 switch (Arg.getKind()) {
1781 case TemplateArgument::Null:
1782 break;
Mike Stump11289f42009-09-09 15:08:12 +00001783
Douglas Gregor197e5f72009-07-08 07:51:57 +00001784 case TemplateArgument::Type:
1785 // [...] the namespaces and classes associated with the types of the
1786 // template arguments provided for template type parameters (excluding
1787 // template template parameters)
John McCallf24d7bb2010-05-28 18:45:08 +00001788 addAssociatedClassesAndNamespaces(Result, Arg.getAsType());
Douglas Gregor197e5f72009-07-08 07:51:57 +00001789 break;
Mike Stump11289f42009-09-09 15:08:12 +00001790
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001791 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00001792 case TemplateArgument::TemplateExpansion: {
Mike Stump11289f42009-09-09 15:08:12 +00001793 // [...] the namespaces in which any template template arguments are
1794 // defined; and the classes in which any member templates used as
Douglas Gregor197e5f72009-07-08 07:51:57 +00001795 // template template arguments are defined.
Douglas Gregore4ff4b52011-01-05 18:58:31 +00001796 TemplateName Template = Arg.getAsTemplateOrTemplatePattern();
Mike Stump11289f42009-09-09 15:08:12 +00001797 if (ClassTemplateDecl *ClassTemplate
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001798 = dyn_cast<ClassTemplateDecl>(Template.getAsTemplateDecl())) {
Douglas Gregor197e5f72009-07-08 07:51:57 +00001799 DeclContext *Ctx = ClassTemplate->getDeclContext();
1800 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00001801 Result.Classes.insert(EnclosingClass);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001802 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00001803 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001804 }
1805 break;
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001806 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001807
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001808 case TemplateArgument::Declaration:
Douglas Gregor197e5f72009-07-08 07:51:57 +00001809 case TemplateArgument::Integral:
1810 case TemplateArgument::Expression:
Mike Stump11289f42009-09-09 15:08:12 +00001811 // [Note: non-type template arguments do not contribute to the set of
Douglas Gregor197e5f72009-07-08 07:51:57 +00001812 // associated namespaces. ]
1813 break;
Mike Stump11289f42009-09-09 15:08:12 +00001814
Douglas Gregor197e5f72009-07-08 07:51:57 +00001815 case TemplateArgument::Pack:
1816 for (TemplateArgument::pack_iterator P = Arg.pack_begin(),
1817 PEnd = Arg.pack_end();
1818 P != PEnd; ++P)
John McCallf24d7bb2010-05-28 18:45:08 +00001819 addAssociatedClassesAndNamespaces(Result, *P);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001820 break;
1821 }
1822}
1823
Douglas Gregore254f902009-02-04 00:32:51 +00001824// \brief Add the associated classes and namespaces for
Mike Stump11289f42009-09-09 15:08:12 +00001825// argument-dependent lookup with an argument of class type
1826// (C++ [basic.lookup.koenig]p2).
1827static void
John McCallf24d7bb2010-05-28 18:45:08 +00001828addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
1829 CXXRecordDecl *Class) {
1830
1831 // Just silently ignore anything whose name is __va_list_tag.
1832 if (Class->getDeclName() == Result.S.VAListTagName)
1833 return;
1834
Douglas Gregore254f902009-02-04 00:32:51 +00001835 // C++ [basic.lookup.koenig]p2:
1836 // [...]
1837 // -- If T is a class type (including unions), its associated
1838 // classes are: the class itself; the class of which it is a
1839 // member, if any; and its direct and indirect base
1840 // classes. Its associated namespaces are the namespaces in
Mike Stump11289f42009-09-09 15:08:12 +00001841 // which its associated classes are defined.
Douglas Gregore254f902009-02-04 00:32:51 +00001842
1843 // Add the class of which it is a member, if any.
1844 DeclContext *Ctx = Class->getDeclContext();
1845 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00001846 Result.Classes.insert(EnclosingClass);
Douglas Gregore254f902009-02-04 00:32:51 +00001847 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00001848 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Mike Stump11289f42009-09-09 15:08:12 +00001849
Douglas Gregore254f902009-02-04 00:32:51 +00001850 // Add the class itself. If we've already seen this class, we don't
1851 // need to visit base classes.
John McCallf24d7bb2010-05-28 18:45:08 +00001852 if (!Result.Classes.insert(Class))
Douglas Gregore254f902009-02-04 00:32:51 +00001853 return;
1854
Mike Stump11289f42009-09-09 15:08:12 +00001855 // -- If T is a template-id, its associated namespaces and classes are
1856 // the namespace in which the template is defined; for member
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00001857 // templates, the member template's class; the namespaces and classes
Mike Stump11289f42009-09-09 15:08:12 +00001858 // associated with the types of the template arguments provided for
Douglas Gregor197e5f72009-07-08 07:51:57 +00001859 // template type parameters (excluding template template parameters); the
Mike Stump11289f42009-09-09 15:08:12 +00001860 // namespaces in which any template template arguments are defined; and
1861 // the classes in which any member templates used as template template
1862 // arguments are defined. [Note: non-type template arguments do not
Douglas Gregor197e5f72009-07-08 07:51:57 +00001863 // contribute to the set of associated namespaces. ]
Mike Stump11289f42009-09-09 15:08:12 +00001864 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregor197e5f72009-07-08 07:51:57 +00001865 = dyn_cast<ClassTemplateSpecializationDecl>(Class)) {
1866 DeclContext *Ctx = Spec->getSpecializedTemplate()->getDeclContext();
1867 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00001868 Result.Classes.insert(EnclosingClass);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001869 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00001870 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Mike Stump11289f42009-09-09 15:08:12 +00001871
Douglas Gregor197e5f72009-07-08 07:51:57 +00001872 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
1873 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
John McCallf24d7bb2010-05-28 18:45:08 +00001874 addAssociatedClassesAndNamespaces(Result, TemplateArgs[I]);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001875 }
Mike Stump11289f42009-09-09 15:08:12 +00001876
John McCall67da35c2010-02-04 22:26:26 +00001877 // Only recurse into base classes for complete types.
1878 if (!Class->hasDefinition()) {
1879 // FIXME: we might need to instantiate templates here
1880 return;
1881 }
1882
Douglas Gregore254f902009-02-04 00:32:51 +00001883 // Add direct and indirect base classes along with their associated
1884 // namespaces.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001885 SmallVector<CXXRecordDecl *, 32> Bases;
Douglas Gregore254f902009-02-04 00:32:51 +00001886 Bases.push_back(Class);
1887 while (!Bases.empty()) {
1888 // Pop this class off the stack.
1889 Class = Bases.back();
1890 Bases.pop_back();
1891
1892 // Visit the base classes.
1893 for (CXXRecordDecl::base_class_iterator Base = Class->bases_begin(),
1894 BaseEnd = Class->bases_end();
1895 Base != BaseEnd; ++Base) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001896 const RecordType *BaseType = Base->getType()->getAs<RecordType>();
Sebastian Redlc45c03c2009-10-25 09:35:33 +00001897 // In dependent contexts, we do ADL twice, and the first time around,
1898 // the base type might be a dependent TemplateSpecializationType, or a
1899 // TemplateTypeParmType. If that happens, simply ignore it.
1900 // FIXME: If we want to support export, we probably need to add the
1901 // namespace of the template in a TemplateSpecializationType, or even
1902 // the classes and namespaces of known non-dependent arguments.
1903 if (!BaseType)
1904 continue;
Douglas Gregore254f902009-02-04 00:32:51 +00001905 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(BaseType->getDecl());
John McCallf24d7bb2010-05-28 18:45:08 +00001906 if (Result.Classes.insert(BaseDecl)) {
Douglas Gregore254f902009-02-04 00:32:51 +00001907 // Find the associated namespace for this base class.
1908 DeclContext *BaseCtx = BaseDecl->getDeclContext();
John McCallf24d7bb2010-05-28 18:45:08 +00001909 CollectEnclosingNamespace(Result.Namespaces, BaseCtx);
Douglas Gregore254f902009-02-04 00:32:51 +00001910
1911 // Make sure we visit the bases of this base class.
1912 if (BaseDecl->bases_begin() != BaseDecl->bases_end())
1913 Bases.push_back(BaseDecl);
1914 }
1915 }
1916 }
1917}
1918
1919// \brief Add the associated classes and namespaces for
1920// argument-dependent lookup with an argument of type T
Mike Stump11289f42009-09-09 15:08:12 +00001921// (C++ [basic.lookup.koenig]p2).
1922static void
John McCallf24d7bb2010-05-28 18:45:08 +00001923addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType Ty) {
Douglas Gregore254f902009-02-04 00:32:51 +00001924 // C++ [basic.lookup.koenig]p2:
1925 //
1926 // For each argument type T in the function call, there is a set
1927 // of zero or more associated namespaces and a set of zero or more
1928 // associated classes to be considered. The sets of namespaces and
1929 // classes is determined entirely by the types of the function
1930 // arguments (and the namespace of any template template
1931 // argument). Typedef names and using-declarations used to specify
1932 // the types do not contribute to this set. The sets of namespaces
1933 // and classes are determined in the following way:
Douglas Gregore254f902009-02-04 00:32:51 +00001934
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001935 SmallVector<const Type *, 16> Queue;
John McCall0af3d3b2010-05-28 06:08:54 +00001936 const Type *T = Ty->getCanonicalTypeInternal().getTypePtr();
1937
Douglas Gregore254f902009-02-04 00:32:51 +00001938 while (true) {
John McCall0af3d3b2010-05-28 06:08:54 +00001939 switch (T->getTypeClass()) {
1940
1941#define TYPE(Class, Base)
1942#define DEPENDENT_TYPE(Class, Base) case Type::Class:
1943#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
1944#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
1945#define ABSTRACT_TYPE(Class, Base)
1946#include "clang/AST/TypeNodes.def"
1947 // T is canonical. We can also ignore dependent types because
1948 // we don't need to do ADL at the definition point, but if we
1949 // wanted to implement template export (or if we find some other
1950 // use for associated classes and namespaces...) this would be
1951 // wrong.
Douglas Gregore254f902009-02-04 00:32:51 +00001952 break;
Douglas Gregore254f902009-02-04 00:32:51 +00001953
John McCall0af3d3b2010-05-28 06:08:54 +00001954 // -- If T is a pointer to U or an array of U, its associated
1955 // namespaces and classes are those associated with U.
1956 case Type::Pointer:
1957 T = cast<PointerType>(T)->getPointeeType().getTypePtr();
1958 continue;
1959 case Type::ConstantArray:
1960 case Type::IncompleteArray:
1961 case Type::VariableArray:
1962 T = cast<ArrayType>(T)->getElementType().getTypePtr();
1963 continue;
Douglas Gregore254f902009-02-04 00:32:51 +00001964
John McCall0af3d3b2010-05-28 06:08:54 +00001965 // -- If T is a fundamental type, its associated sets of
1966 // namespaces and classes are both empty.
1967 case Type::Builtin:
1968 break;
1969
1970 // -- If T is a class type (including unions), its associated
1971 // classes are: the class itself; the class of which it is a
1972 // member, if any; and its direct and indirect base
1973 // classes. Its associated namespaces are the namespaces in
1974 // which its associated classes are defined.
1975 case Type::Record: {
1976 CXXRecordDecl *Class
1977 = cast<CXXRecordDecl>(cast<RecordType>(T)->getDecl());
John McCallf24d7bb2010-05-28 18:45:08 +00001978 addAssociatedClassesAndNamespaces(Result, Class);
John McCall0af3d3b2010-05-28 06:08:54 +00001979 break;
Douglas Gregor89ee6822009-02-28 01:32:25 +00001980 }
Douglas Gregorfe60c142010-05-20 02:26:51 +00001981
John McCall0af3d3b2010-05-28 06:08:54 +00001982 // -- If T is an enumeration type, its associated namespace is
1983 // the namespace in which it is defined. If it is class
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00001984 // member, its associated class is the member's class; else
John McCall0af3d3b2010-05-28 06:08:54 +00001985 // it has no associated class.
1986 case Type::Enum: {
1987 EnumDecl *Enum = cast<EnumType>(T)->getDecl();
Douglas Gregore254f902009-02-04 00:32:51 +00001988
John McCall0af3d3b2010-05-28 06:08:54 +00001989 DeclContext *Ctx = Enum->getDeclContext();
1990 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00001991 Result.Classes.insert(EnclosingClass);
Douglas Gregore254f902009-02-04 00:32:51 +00001992
John McCall0af3d3b2010-05-28 06:08:54 +00001993 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00001994 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Douglas Gregore254f902009-02-04 00:32:51 +00001995
John McCall0af3d3b2010-05-28 06:08:54 +00001996 break;
1997 }
1998
1999 // -- If T is a function type, its associated namespaces and
2000 // classes are those associated with the function parameter
2001 // types and those associated with the return type.
2002 case Type::FunctionProto: {
2003 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
2004 for (FunctionProtoType::arg_type_iterator Arg = Proto->arg_type_begin(),
2005 ArgEnd = Proto->arg_type_end();
2006 Arg != ArgEnd; ++Arg)
2007 Queue.push_back(Arg->getTypePtr());
2008 // fallthrough
2009 }
2010 case Type::FunctionNoProto: {
2011 const FunctionType *FnType = cast<FunctionType>(T);
2012 T = FnType->getResultType().getTypePtr();
2013 continue;
2014 }
2015
2016 // -- If T is a pointer to a member function of a class X, its
2017 // associated namespaces and classes are those associated
2018 // with the function parameter types and return type,
2019 // together with those associated with X.
2020 //
2021 // -- If T is a pointer to a data member of class X, its
2022 // associated namespaces and classes are those associated
2023 // with the member type together with those associated with
2024 // X.
2025 case Type::MemberPointer: {
2026 const MemberPointerType *MemberPtr = cast<MemberPointerType>(T);
2027
2028 // Queue up the class type into which this points.
2029 Queue.push_back(MemberPtr->getClass());
2030
2031 // And directly continue with the pointee type.
2032 T = MemberPtr->getPointeeType().getTypePtr();
2033 continue;
2034 }
2035
2036 // As an extension, treat this like a normal pointer.
2037 case Type::BlockPointer:
2038 T = cast<BlockPointerType>(T)->getPointeeType().getTypePtr();
2039 continue;
2040
2041 // References aren't covered by the standard, but that's such an
2042 // obvious defect that we cover them anyway.
2043 case Type::LValueReference:
2044 case Type::RValueReference:
2045 T = cast<ReferenceType>(T)->getPointeeType().getTypePtr();
2046 continue;
2047
2048 // These are fundamental types.
2049 case Type::Vector:
2050 case Type::ExtVector:
2051 case Type::Complex:
2052 break;
2053
Douglas Gregor8e936662011-04-12 01:02:45 +00002054 // If T is an Objective-C object or interface type, or a pointer to an
2055 // object or interface type, the associated namespace is the global
2056 // namespace.
John McCall0af3d3b2010-05-28 06:08:54 +00002057 case Type::ObjCObject:
2058 case Type::ObjCInterface:
2059 case Type::ObjCObjectPointer:
Douglas Gregor8e936662011-04-12 01:02:45 +00002060 Result.Namespaces.insert(Result.S.Context.getTranslationUnitDecl());
John McCall0af3d3b2010-05-28 06:08:54 +00002061 break;
Eli Friedman0dfb8892011-10-06 23:00:33 +00002062
2063 // Atomic types are just wrappers; use the associations of the
2064 // contained type.
2065 case Type::Atomic:
2066 T = cast<AtomicType>(T)->getValueType().getTypePtr();
2067 continue;
John McCall0af3d3b2010-05-28 06:08:54 +00002068 }
2069
2070 if (Queue.empty()) break;
2071 T = Queue.back();
2072 Queue.pop_back();
Douglas Gregore254f902009-02-04 00:32:51 +00002073 }
Douglas Gregore254f902009-02-04 00:32:51 +00002074}
2075
2076/// \brief Find the associated classes and namespaces for
2077/// argument-dependent lookup for a call with the given set of
2078/// arguments.
2079///
2080/// This routine computes the sets of associated classes and associated
Mike Stump11289f42009-09-09 15:08:12 +00002081/// namespaces searched by argument-dependent lookup
Douglas Gregore254f902009-02-04 00:32:51 +00002082/// (C++ [basic.lookup.argdep]) for a given set of arguments.
Mike Stump11289f42009-09-09 15:08:12 +00002083void
Douglas Gregore254f902009-02-04 00:32:51 +00002084Sema::FindAssociatedClassesAndNamespaces(Expr **Args, unsigned NumArgs,
2085 AssociatedNamespaceSet &AssociatedNamespaces,
John McCallc7e8e792009-08-07 22:18:02 +00002086 AssociatedClassSet &AssociatedClasses) {
Douglas Gregore254f902009-02-04 00:32:51 +00002087 AssociatedNamespaces.clear();
2088 AssociatedClasses.clear();
2089
John McCallf24d7bb2010-05-28 18:45:08 +00002090 AssociatedLookup Result(*this, AssociatedNamespaces, AssociatedClasses);
2091
Douglas Gregore254f902009-02-04 00:32:51 +00002092 // C++ [basic.lookup.koenig]p2:
2093 // For each argument type T in the function call, there is a set
2094 // of zero or more associated namespaces and a set of zero or more
2095 // associated classes to be considered. The sets of namespaces and
2096 // classes is determined entirely by the types of the function
2097 // arguments (and the namespace of any template template
Mike Stump11289f42009-09-09 15:08:12 +00002098 // argument).
Douglas Gregore254f902009-02-04 00:32:51 +00002099 for (unsigned ArgIdx = 0; ArgIdx != NumArgs; ++ArgIdx) {
2100 Expr *Arg = Args[ArgIdx];
2101
2102 if (Arg->getType() != Context.OverloadTy) {
John McCallf24d7bb2010-05-28 18:45:08 +00002103 addAssociatedClassesAndNamespaces(Result, Arg->getType());
Douglas Gregore254f902009-02-04 00:32:51 +00002104 continue;
2105 }
2106
2107 // [...] In addition, if the argument is the name or address of a
2108 // set of overloaded functions and/or function templates, its
2109 // associated classes and namespaces are the union of those
2110 // associated with each of the members of the set: the namespace
2111 // in which the function or function template is defined and the
2112 // classes and namespaces associated with its (non-dependent)
2113 // parameter types and return type.
Douglas Gregorbe759252009-07-08 10:57:20 +00002114 Arg = Arg->IgnoreParens();
John McCalld14a8642009-11-21 08:51:07 +00002115 if (UnaryOperator *unaryOp = dyn_cast<UnaryOperator>(Arg))
John McCalle3027922010-08-25 11:45:40 +00002116 if (unaryOp->getOpcode() == UO_AddrOf)
John McCalld14a8642009-11-21 08:51:07 +00002117 Arg = unaryOp->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00002118
John McCallf24d7bb2010-05-28 18:45:08 +00002119 UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Arg);
2120 if (!ULE) continue;
John McCalld14a8642009-11-21 08:51:07 +00002121
John McCallf24d7bb2010-05-28 18:45:08 +00002122 for (UnresolvedSetIterator I = ULE->decls_begin(), E = ULE->decls_end();
2123 I != E; ++I) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00002124 // Look through any using declarations to find the underlying function.
2125 NamedDecl *Fn = (*I)->getUnderlyingDecl();
Douglas Gregore254f902009-02-04 00:32:51 +00002126
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00002127 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(Fn);
2128 if (!FDecl)
2129 FDecl = cast<FunctionTemplateDecl>(Fn)->getTemplatedDecl();
Douglas Gregore254f902009-02-04 00:32:51 +00002130
2131 // Add the classes and namespaces associated with the parameter
2132 // types and return type of this function.
John McCallf24d7bb2010-05-28 18:45:08 +00002133 addAssociatedClassesAndNamespaces(Result, FDecl->getType());
Douglas Gregore254f902009-02-04 00:32:51 +00002134 }
2135 }
2136}
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002137
2138/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
2139/// an acceptable non-member overloaded operator for a call whose
2140/// arguments have types T1 (and, if non-empty, T2). This routine
2141/// implements the check in C++ [over.match.oper]p3b2 concerning
2142/// enumeration types.
Mike Stump11289f42009-09-09 15:08:12 +00002143static bool
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002144IsAcceptableNonMemberOperatorCandidate(FunctionDecl *Fn,
2145 QualType T1, QualType T2,
2146 ASTContext &Context) {
Douglas Gregor0950e412009-03-13 21:01:28 +00002147 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
2148 return true;
2149
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002150 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
2151 return true;
2152
John McCall9dd450b2009-09-21 23:43:11 +00002153 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002154 if (Proto->getNumArgs() < 1)
2155 return false;
2156
2157 if (T1->isEnumeralType()) {
2158 QualType ArgType = Proto->getArgType(0).getNonReferenceType();
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002159 if (Context.hasSameUnqualifiedType(T1, ArgType))
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002160 return true;
2161 }
2162
2163 if (Proto->getNumArgs() < 2)
2164 return false;
2165
2166 if (!T2.isNull() && T2->isEnumeralType()) {
2167 QualType ArgType = Proto->getArgType(1).getNonReferenceType();
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002168 if (Context.hasSameUnqualifiedType(T2, ArgType))
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002169 return true;
2170 }
2171
2172 return false;
2173}
2174
John McCall5cebab12009-11-18 07:57:50 +00002175NamedDecl *Sema::LookupSingleName(Scope *S, DeclarationName Name,
Douglas Gregorb2ccf012010-04-15 22:33:43 +00002176 SourceLocation Loc,
John McCall5cebab12009-11-18 07:57:50 +00002177 LookupNameKind NameKind,
2178 RedeclarationKind Redecl) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +00002179 LookupResult R(*this, Name, Loc, NameKind, Redecl);
John McCall5cebab12009-11-18 07:57:50 +00002180 LookupName(R, S);
John McCall67c00872009-12-02 08:25:40 +00002181 return R.getAsSingle<NamedDecl>();
John McCall5cebab12009-11-18 07:57:50 +00002182}
2183
Douglas Gregorde9f17e2009-04-23 23:18:26 +00002184/// \brief Find the protocol with the given name, if any.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002185ObjCProtocolDecl *Sema::LookupProtocol(IdentifierInfo *II,
Douglas Gregor32c17572012-01-01 20:30:41 +00002186 SourceLocation IdLoc,
2187 RedeclarationKind Redecl) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +00002188 Decl *D = LookupSingleName(TUScope, II, IdLoc,
Douglas Gregor32c17572012-01-01 20:30:41 +00002189 LookupObjCProtocolName, Redecl);
Douglas Gregorde9f17e2009-04-23 23:18:26 +00002190 return cast_or_null<ObjCProtocolDecl>(D);
2191}
2192
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002193void Sema::LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
Mike Stump11289f42009-09-09 15:08:12 +00002194 QualType T1, QualType T2,
John McCall4c4c1df2010-01-26 03:27:55 +00002195 UnresolvedSetImpl &Functions) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002196 // C++ [over.match.oper]p3:
2197 // -- The set of non-member candidates is the result of the
2198 // unqualified lookup of operator@ in the context of the
2199 // expression according to the usual rules for name lookup in
2200 // unqualified function calls (3.4.2) except that all member
2201 // functions are ignored. However, if no operand has a class
2202 // type, only those non-member functions in the lookup set
Eli Friedman44b83ee2009-08-05 19:21:58 +00002203 // that have a first parameter of type T1 or "reference to
2204 // (possibly cv-qualified) T1", when T1 is an enumeration
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002205 // type, or (if there is a right operand) a second parameter
Eli Friedman44b83ee2009-08-05 19:21:58 +00002206 // of type T2 or "reference to (possibly cv-qualified) T2",
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002207 // when T2 is an enumeration type, are candidate functions.
2208 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
John McCall27b18f82009-11-17 02:14:36 +00002209 LookupResult Operators(*this, OpName, SourceLocation(), LookupOperatorName);
2210 LookupName(Operators, S);
Mike Stump11289f42009-09-09 15:08:12 +00002211
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002212 assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
2213
John McCall9f3059a2009-10-09 21:13:30 +00002214 if (Operators.empty())
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002215 return;
2216
2217 for (LookupResult::iterator Op = Operators.begin(), OpEnd = Operators.end();
2218 Op != OpEnd; ++Op) {
Douglas Gregor645d76f2010-04-25 20:25:43 +00002219 NamedDecl *Found = (*Op)->getUnderlyingDecl();
2220 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Found)) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002221 if (IsAcceptableNonMemberOperatorCandidate(FD, T1, T2, Context))
Douglas Gregor645d76f2010-04-25 20:25:43 +00002222 Functions.addDecl(*Op, Op.getAccess()); // FIXME: canonical FD
Mike Stump11289f42009-09-09 15:08:12 +00002223 } else if (FunctionTemplateDecl *FunTmpl
Douglas Gregor645d76f2010-04-25 20:25:43 +00002224 = dyn_cast<FunctionTemplateDecl>(Found)) {
Douglas Gregor15448f82009-06-27 21:05:07 +00002225 // FIXME: friend operators?
Mike Stump11289f42009-09-09 15:08:12 +00002226 // FIXME: do we need to check IsAcceptableNonMemberOperatorCandidate,
Douglas Gregor15448f82009-06-27 21:05:07 +00002227 // later?
2228 if (!FunTmpl->getDeclContext()->isRecord())
Douglas Gregor645d76f2010-04-25 20:25:43 +00002229 Functions.addDecl(*Op, Op.getAccess());
Douglas Gregor15448f82009-06-27 21:05:07 +00002230 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002231 }
2232}
2233
Alexis Hunt1da39282011-06-24 02:11:39 +00002234Sema::SpecialMemberOverloadResult *Sema::LookupSpecialMember(CXXRecordDecl *RD,
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002235 CXXSpecialMember SM,
2236 bool ConstArg,
2237 bool VolatileArg,
2238 bool RValueThis,
2239 bool ConstThis,
2240 bool VolatileThis) {
Alexis Hunt1da39282011-06-24 02:11:39 +00002241 RD = RD->getDefinition();
2242 assert((RD && !RD->isBeingDefined()) &&
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002243 "doing special member lookup into record that isn't fully complete");
2244 if (RValueThis || ConstThis || VolatileThis)
2245 assert((SM == CXXCopyAssignment || SM == CXXMoveAssignment) &&
2246 "constructors and destructors always have unqualified lvalue this");
2247 if (ConstArg || VolatileArg)
2248 assert((SM != CXXDefaultConstructor && SM != CXXDestructor) &&
2249 "parameter-less special members can't have qualified arguments");
2250
2251 llvm::FoldingSetNodeID ID;
Alexis Hunt1da39282011-06-24 02:11:39 +00002252 ID.AddPointer(RD);
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002253 ID.AddInteger(SM);
2254 ID.AddInteger(ConstArg);
2255 ID.AddInteger(VolatileArg);
2256 ID.AddInteger(RValueThis);
2257 ID.AddInteger(ConstThis);
2258 ID.AddInteger(VolatileThis);
2259
2260 void *InsertPoint;
2261 SpecialMemberOverloadResult *Result =
2262 SpecialMemberCache.FindNodeOrInsertPos(ID, InsertPoint);
2263
2264 // This was already cached
2265 if (Result)
2266 return Result;
2267
Alexis Huntba8e18d2011-06-07 00:11:58 +00002268 Result = BumpAlloc.Allocate<SpecialMemberOverloadResult>();
2269 Result = new (Result) SpecialMemberOverloadResult(ID);
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002270 SpecialMemberCache.InsertNode(Result, InsertPoint);
2271
2272 if (SM == CXXDestructor) {
Alexis Hunt1da39282011-06-24 02:11:39 +00002273 if (!RD->hasDeclaredDestructor())
2274 DeclareImplicitDestructor(RD);
2275 CXXDestructorDecl *DD = RD->getDestructor();
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002276 assert(DD && "record without a destructor");
2277 Result->setMethod(DD);
Richard Smithd951a1d2012-02-18 02:02:13 +00002278 Result->setSuccess(!DD->isDeleted());
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002279 Result->setConstParamMatch(false);
2280 return Result;
2281 }
2282
Alexis Hunteef8ee02011-06-10 03:50:41 +00002283 // Prepare for overload resolution. Here we construct a synthetic argument
2284 // if necessary and make sure that implicit functions are declared.
Alexis Hunt1da39282011-06-24 02:11:39 +00002285 CanQualType CanTy = Context.getCanonicalType(Context.getTagDeclType(RD));
Alexis Hunteef8ee02011-06-10 03:50:41 +00002286 DeclarationName Name;
2287 Expr *Arg = 0;
2288 unsigned NumArgs;
2289
2290 if (SM == CXXDefaultConstructor) {
2291 Name = Context.DeclarationNames.getCXXConstructorName(CanTy);
2292 NumArgs = 0;
Alexis Hunt1da39282011-06-24 02:11:39 +00002293 if (RD->needsImplicitDefaultConstructor())
2294 DeclareImplicitDefaultConstructor(RD);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002295 } else {
2296 if (SM == CXXCopyConstructor || SM == CXXMoveConstructor) {
2297 Name = Context.DeclarationNames.getCXXConstructorName(CanTy);
Alexis Hunt1da39282011-06-24 02:11:39 +00002298 if (!RD->hasDeclaredCopyConstructor())
2299 DeclareImplicitCopyConstructor(RD);
Sebastian Redl22653ba2011-08-30 19:58:05 +00002300 if (getLangOptions().CPlusPlus0x && RD->needsImplicitMoveConstructor())
2301 DeclareImplicitMoveConstructor(RD);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002302 } else {
2303 Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Alexis Hunt1da39282011-06-24 02:11:39 +00002304 if (!RD->hasDeclaredCopyAssignment())
2305 DeclareImplicitCopyAssignment(RD);
Sebastian Redl22653ba2011-08-30 19:58:05 +00002306 if (getLangOptions().CPlusPlus0x && RD->needsImplicitMoveAssignment())
2307 DeclareImplicitMoveAssignment(RD);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002308 }
2309
2310 QualType ArgType = CanTy;
2311 if (ConstArg)
2312 ArgType.addConst();
2313 if (VolatileArg)
2314 ArgType.addVolatile();
2315
2316 // This isn't /really/ specified by the standard, but it's implied
2317 // we should be working from an RValue in the case of move to ensure
2318 // that we prefer to bind to rvalue references, and an LValue in the
2319 // case of copy to ensure we don't bind to rvalue references.
2320 // Possibly an XValue is actually correct in the case of move, but
2321 // there is no semantic difference for class types in this restricted
2322 // case.
2323 ExprValueKind VK;
Alexis Hunt46d1ce22011-06-22 22:13:13 +00002324 if (SM == CXXCopyConstructor || SM == CXXCopyAssignment)
Alexis Hunteef8ee02011-06-10 03:50:41 +00002325 VK = VK_LValue;
2326 else
2327 VK = VK_RValue;
2328
2329 NumArgs = 1;
2330 Arg = new (Context) OpaqueValueExpr(SourceLocation(), ArgType, VK);
2331 }
2332
2333 // Create the object argument
2334 QualType ThisTy = CanTy;
2335 if (ConstThis)
2336 ThisTy.addConst();
2337 if (VolatileThis)
2338 ThisTy.addVolatile();
Alexis Hunt080709f2011-06-23 00:26:20 +00002339 Expr::Classification Classification =
Alexis Hunteef8ee02011-06-10 03:50:41 +00002340 (new (Context) OpaqueValueExpr(SourceLocation(), ThisTy,
2341 RValueThis ? VK_RValue : VK_LValue))->
2342 Classify(Context);
2343
2344 // Now we perform lookup on the name we computed earlier and do overload
2345 // resolution. Lookup is only performed directly into the class since there
2346 // will always be a (possibly implicit) declaration to shadow any others.
2347 OverloadCandidateSet OCS((SourceLocation()));
2348 DeclContext::lookup_iterator I, E;
2349 Result->setConstParamMatch(false);
2350
Alexis Hunt1da39282011-06-24 02:11:39 +00002351 llvm::tie(I, E) = RD->lookup(Name);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002352 assert((I != E) &&
2353 "lookup for a constructor or assignment operator was empty");
2354 for ( ; I != E; ++I) {
Alexis Hunt1da39282011-06-24 02:11:39 +00002355 Decl *Cand = *I;
Alexis Hunt080709f2011-06-23 00:26:20 +00002356
Alexis Hunt1da39282011-06-24 02:11:39 +00002357 if (Cand->isInvalidDecl())
Alexis Hunteef8ee02011-06-10 03:50:41 +00002358 continue;
2359
Alexis Hunt1da39282011-06-24 02:11:39 +00002360 if (UsingShadowDecl *U = dyn_cast<UsingShadowDecl>(Cand)) {
2361 // FIXME: [namespace.udecl]p15 says that we should only consider a
2362 // using declaration here if it does not match a declaration in the
2363 // derived class. We do not implement this correctly in other cases
2364 // either.
2365 Cand = U->getTargetDecl();
2366
2367 if (Cand->isInvalidDecl())
2368 continue;
2369 }
2370
2371 if (CXXMethodDecl *M = dyn_cast<CXXMethodDecl>(Cand)) {
Alexis Hunt080709f2011-06-23 00:26:20 +00002372 if (SM == CXXCopyAssignment || SM == CXXMoveAssignment)
Alexis Hunt1da39282011-06-24 02:11:39 +00002373 AddMethodCandidate(M, DeclAccessPair::make(M, AS_public), RD, ThisTy,
Alexis Hunt080709f2011-06-23 00:26:20 +00002374 Classification, &Arg, NumArgs, OCS, true);
2375 else
2376 AddOverloadCandidate(M, DeclAccessPair::make(M, AS_public), &Arg,
2377 NumArgs, OCS, true);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002378
2379 // Here we're looking for a const parameter to speed up creation of
2380 // implicit copy methods.
2381 if ((SM == CXXCopyAssignment && M->isCopyAssignmentOperator()) ||
2382 (SM == CXXCopyConstructor &&
2383 cast<CXXConstructorDecl>(M)->isCopyConstructor())) {
2384 QualType ArgType = M->getType()->getAs<FunctionProtoType>()->getArgType(0);
Alexis Hunt491ec602011-06-21 23:42:56 +00002385 if (!ArgType->isReferenceType() ||
2386 ArgType->getPointeeType().isConstQualified())
Alexis Hunteef8ee02011-06-10 03:50:41 +00002387 Result->setConstParamMatch(true);
2388 }
Alexis Hunt2949f022011-06-22 02:58:46 +00002389 } else if (FunctionTemplateDecl *Tmpl =
Alexis Hunt1da39282011-06-24 02:11:39 +00002390 dyn_cast<FunctionTemplateDecl>(Cand)) {
Alexis Hunt080709f2011-06-23 00:26:20 +00002391 if (SM == CXXCopyAssignment || SM == CXXMoveAssignment)
2392 AddMethodTemplateCandidate(Tmpl, DeclAccessPair::make(Tmpl, AS_public),
Alexis Hunt1da39282011-06-24 02:11:39 +00002393 RD, 0, ThisTy, Classification, &Arg, NumArgs,
Alexis Hunt080709f2011-06-23 00:26:20 +00002394 OCS, true);
2395 else
2396 AddTemplateOverloadCandidate(Tmpl, DeclAccessPair::make(Tmpl, AS_public),
2397 0, &Arg, NumArgs, OCS, true);
Alexis Hunt1da39282011-06-24 02:11:39 +00002398 } else {
2399 assert(isa<UsingDecl>(Cand) && "illegal Kind of operator = Decl");
Alexis Hunteef8ee02011-06-10 03:50:41 +00002400 }
2401 }
2402
2403 OverloadCandidateSet::iterator Best;
2404 switch (OCS.BestViableFunction(*this, SourceLocation(), Best)) {
2405 case OR_Success:
2406 Result->setMethod(cast<CXXMethodDecl>(Best->Function));
2407 Result->setSuccess(true);
2408 break;
2409
2410 case OR_Deleted:
2411 Result->setMethod(cast<CXXMethodDecl>(Best->Function));
2412 Result->setSuccess(false);
2413 break;
2414
2415 case OR_Ambiguous:
2416 case OR_No_Viable_Function:
2417 Result->setMethod(0);
2418 Result->setSuccess(false);
2419 break;
2420 }
2421
2422 return Result;
2423}
2424
2425/// \brief Look up the default constructor for the given class.
2426CXXConstructorDecl *Sema::LookupDefaultConstructor(CXXRecordDecl *Class) {
Alexis Hunt899bd442011-06-10 04:44:37 +00002427 SpecialMemberOverloadResult *Result =
Alexis Hunteef8ee02011-06-10 03:50:41 +00002428 LookupSpecialMember(Class, CXXDefaultConstructor, false, false, false,
2429 false, false);
2430
2431 return cast_or_null<CXXConstructorDecl>(Result->getMethod());
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002432}
2433
Alexis Hunt491ec602011-06-21 23:42:56 +00002434/// \brief Look up the copying constructor for the given class.
2435CXXConstructorDecl *Sema::LookupCopyingConstructor(CXXRecordDecl *Class,
2436 unsigned Quals,
2437 bool *ConstParamMatch) {
Alexis Hunt899bd442011-06-10 04:44:37 +00002438 assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2439 "non-const, non-volatile qualifiers for copy ctor arg");
2440 SpecialMemberOverloadResult *Result =
2441 LookupSpecialMember(Class, CXXCopyConstructor, Quals & Qualifiers::Const,
2442 Quals & Qualifiers::Volatile, false, false, false);
2443
2444 if (ConstParamMatch)
2445 *ConstParamMatch = Result->hasConstParamMatch();
2446
2447 return cast_or_null<CXXConstructorDecl>(Result->getMethod());
2448}
2449
Sebastian Redl22653ba2011-08-30 19:58:05 +00002450/// \brief Look up the moving constructor for the given class.
2451CXXConstructorDecl *Sema::LookupMovingConstructor(CXXRecordDecl *Class) {
2452 SpecialMemberOverloadResult *Result =
2453 LookupSpecialMember(Class, CXXMoveConstructor, false,
2454 false, false, false, false);
2455
2456 return cast_or_null<CXXConstructorDecl>(Result->getMethod());
2457}
2458
Douglas Gregor52b72822010-07-02 23:12:18 +00002459/// \brief Look up the constructors for the given class.
2460DeclContext::lookup_result Sema::LookupConstructors(CXXRecordDecl *Class) {
Alexis Hunteef8ee02011-06-10 03:50:41 +00002461 // If the implicit constructors have not yet been declared, do so now.
Douglas Gregor9672f922010-07-03 00:47:00 +00002462 if (CanDeclareSpecialMemberFunction(Context, Class)) {
Alexis Huntea6f0322011-05-11 22:34:38 +00002463 if (Class->needsImplicitDefaultConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +00002464 DeclareImplicitDefaultConstructor(Class);
2465 if (!Class->hasDeclaredCopyConstructor())
2466 DeclareImplicitCopyConstructor(Class);
Sebastian Redl22653ba2011-08-30 19:58:05 +00002467 if (getLangOptions().CPlusPlus0x && Class->needsImplicitMoveConstructor())
2468 DeclareImplicitMoveConstructor(Class);
Douglas Gregor9672f922010-07-03 00:47:00 +00002469 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002470
Douglas Gregor52b72822010-07-02 23:12:18 +00002471 CanQualType T = Context.getCanonicalType(Context.getTypeDeclType(Class));
2472 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(T);
2473 return Class->lookup(Name);
2474}
2475
Alexis Hunt491ec602011-06-21 23:42:56 +00002476/// \brief Look up the copying assignment operator for the given class.
2477CXXMethodDecl *Sema::LookupCopyingAssignment(CXXRecordDecl *Class,
2478 unsigned Quals, bool RValueThis,
2479 unsigned ThisQuals,
2480 bool *ConstParamMatch) {
2481 assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2482 "non-const, non-volatile qualifiers for copy assignment arg");
2483 assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2484 "non-const, non-volatile qualifiers for copy assignment this");
2485 SpecialMemberOverloadResult *Result =
2486 LookupSpecialMember(Class, CXXCopyAssignment, Quals & Qualifiers::Const,
2487 Quals & Qualifiers::Volatile, RValueThis,
2488 ThisQuals & Qualifiers::Const,
2489 ThisQuals & Qualifiers::Volatile);
2490
2491 if (ConstParamMatch)
2492 *ConstParamMatch = Result->hasConstParamMatch();
2493
2494 return Result->getMethod();
2495}
2496
Sebastian Redl22653ba2011-08-30 19:58:05 +00002497/// \brief Look up the moving assignment operator for the given class.
2498CXXMethodDecl *Sema::LookupMovingAssignment(CXXRecordDecl *Class,
2499 bool RValueThis,
2500 unsigned ThisQuals) {
2501 assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2502 "non-const, non-volatile qualifiers for copy assignment this");
2503 SpecialMemberOverloadResult *Result =
2504 LookupSpecialMember(Class, CXXMoveAssignment, false, false, RValueThis,
2505 ThisQuals & Qualifiers::Const,
2506 ThisQuals & Qualifiers::Volatile);
2507
2508 return Result->getMethod();
2509}
2510
Douglas Gregore71edda2010-07-01 22:47:18 +00002511/// \brief Look for the destructor of the given class.
2512///
Alexis Hunt967ea7c2011-06-03 21:10:40 +00002513/// During semantic analysis, this routine should be used in lieu of
2514/// CXXRecordDecl::getDestructor().
Douglas Gregore71edda2010-07-01 22:47:18 +00002515///
2516/// \returns The destructor for this class.
2517CXXDestructorDecl *Sema::LookupDestructor(CXXRecordDecl *Class) {
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002518 return cast<CXXDestructorDecl>(LookupSpecialMember(Class, CXXDestructor,
2519 false, false, false,
2520 false, false)->getMethod());
Douglas Gregore71edda2010-07-01 22:47:18 +00002521}
2522
John McCall8fe68082010-01-26 07:16:45 +00002523void ADLResult::insert(NamedDecl *New) {
2524 NamedDecl *&Old = Decls[cast<NamedDecl>(New->getCanonicalDecl())];
2525
2526 // If we haven't yet seen a decl for this key, or the last decl
2527 // was exactly this one, we're done.
2528 if (Old == 0 || Old == New) {
2529 Old = New;
2530 return;
2531 }
2532
2533 // Otherwise, decide which is a more recent redeclaration.
2534 FunctionDecl *OldFD, *NewFD;
2535 if (isa<FunctionTemplateDecl>(New)) {
2536 OldFD = cast<FunctionTemplateDecl>(Old)->getTemplatedDecl();
2537 NewFD = cast<FunctionTemplateDecl>(New)->getTemplatedDecl();
2538 } else {
2539 OldFD = cast<FunctionDecl>(Old);
2540 NewFD = cast<FunctionDecl>(New);
2541 }
2542
2543 FunctionDecl *Cursor = NewFD;
2544 while (true) {
Douglas Gregorec9fd132012-01-14 16:38:05 +00002545 Cursor = Cursor->getPreviousDecl();
John McCall8fe68082010-01-26 07:16:45 +00002546
2547 // If we got to the end without finding OldFD, OldFD is the newer
2548 // declaration; leave things as they are.
2549 if (!Cursor) return;
2550
2551 // If we do find OldFD, then NewFD is newer.
2552 if (Cursor == OldFD) break;
2553
2554 // Otherwise, keep looking.
2555 }
2556
2557 Old = New;
2558}
2559
Sebastian Redlc057f422009-10-23 19:23:15 +00002560void Sema::ArgumentDependentLookup(DeclarationName Name, bool Operator,
Richard Smithe06a2c12012-02-25 06:24:24 +00002561 SourceLocation Loc,
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002562 Expr **Args, unsigned NumArgs,
Richard Smith02e85f32011-04-14 22:09:26 +00002563 ADLResult &Result,
2564 bool StdNamespaceIsAssociated) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002565 // Find all of the associated namespaces and classes based on the
2566 // arguments we have.
2567 AssociatedNamespaceSet AssociatedNamespaces;
2568 AssociatedClassSet AssociatedClasses;
Mike Stump11289f42009-09-09 15:08:12 +00002569 FindAssociatedClassesAndNamespaces(Args, NumArgs,
John McCallc7e8e792009-08-07 22:18:02 +00002570 AssociatedNamespaces,
2571 AssociatedClasses);
Richard Smith02e85f32011-04-14 22:09:26 +00002572 if (StdNamespaceIsAssociated && StdNamespace)
2573 AssociatedNamespaces.insert(getStdNamespace());
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002574
Sebastian Redlc057f422009-10-23 19:23:15 +00002575 QualType T1, T2;
2576 if (Operator) {
2577 T1 = Args[0]->getType();
2578 if (NumArgs >= 2)
2579 T2 = Args[1]->getType();
2580 }
2581
Richard Smithe06a2c12012-02-25 06:24:24 +00002582 // Try to complete all associated classes, in case they contain a
2583 // declaration of a friend function.
2584 for (AssociatedClassSet::iterator C = AssociatedClasses.begin(),
2585 CEnd = AssociatedClasses.end();
2586 C != CEnd; ++C)
2587 RequireCompleteType(Loc, Context.getRecordType(*C), 0);
2588
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002589 // C++ [basic.lookup.argdep]p3:
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002590 // Let X be the lookup set produced by unqualified lookup (3.4.1)
2591 // and let Y be the lookup set produced by argument dependent
2592 // lookup (defined as follows). If X contains [...] then Y is
2593 // empty. Otherwise Y is the set of declarations found in the
2594 // namespaces associated with the argument types as described
2595 // below. The set of declarations found by the lookup of the name
2596 // is the union of X and Y.
2597 //
2598 // Here, we compute Y and add its members to the overloaded
2599 // candidate set.
2600 for (AssociatedNamespaceSet::iterator NS = AssociatedNamespaces.begin(),
Mike Stump11289f42009-09-09 15:08:12 +00002601 NSEnd = AssociatedNamespaces.end();
2602 NS != NSEnd; ++NS) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002603 // When considering an associated namespace, the lookup is the
2604 // same as the lookup performed when the associated namespace is
2605 // used as a qualifier (3.4.3.2) except that:
2606 //
2607 // -- Any using-directives in the associated namespace are
2608 // ignored.
2609 //
John McCallc7e8e792009-08-07 22:18:02 +00002610 // -- Any namespace-scope friend functions declared in
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002611 // associated classes are visible within their respective
2612 // namespaces even if they are not visible during an ordinary
2613 // lookup (11.4).
2614 DeclContext::lookup_iterator I, E;
John McCalld1e9d832009-08-11 06:59:38 +00002615 for (llvm::tie(I, E) = (*NS)->lookup(Name); I != E; ++I) {
John McCall4c4c1df2010-01-26 03:27:55 +00002616 NamedDecl *D = *I;
John McCallaa74a0c2009-08-28 07:59:38 +00002617 // If the only declaration here is an ordinary friend, consider
2618 // it only if it was declared in an associated classes.
2619 if (D->getIdentifierNamespace() == Decl::IDNS_OrdinaryFriend) {
John McCalld1e9d832009-08-11 06:59:38 +00002620 DeclContext *LexDC = D->getLexicalDeclContext();
2621 if (!AssociatedClasses.count(cast<CXXRecordDecl>(LexDC)))
2622 continue;
2623 }
Mike Stump11289f42009-09-09 15:08:12 +00002624
John McCall91f61fc2010-01-26 06:04:06 +00002625 if (isa<UsingShadowDecl>(D))
2626 D = cast<UsingShadowDecl>(D)->getTargetDecl();
John McCall4c4c1df2010-01-26 03:27:55 +00002627
John McCall91f61fc2010-01-26 06:04:06 +00002628 if (isa<FunctionDecl>(D)) {
2629 if (Operator &&
2630 !IsAcceptableNonMemberOperatorCandidate(cast<FunctionDecl>(D),
2631 T1, T2, Context))
2632 continue;
John McCall8fe68082010-01-26 07:16:45 +00002633 } else if (!isa<FunctionTemplateDecl>(D))
2634 continue;
2635
2636 Result.insert(D);
Douglas Gregor6127ca42009-06-23 20:14:09 +00002637 }
2638 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002639}
Douglas Gregor2d435302009-12-30 17:04:44 +00002640
2641//----------------------------------------------------------------------------
2642// Search for all visible declarations.
2643//----------------------------------------------------------------------------
2644VisibleDeclConsumer::~VisibleDeclConsumer() { }
2645
2646namespace {
2647
2648class ShadowContextRAII;
2649
2650class VisibleDeclsRecord {
2651public:
2652 /// \brief An entry in the shadow map, which is optimized to store a
2653 /// single declaration (the common case) but can also store a list
2654 /// of declarations.
Chris Lattner83cfc7c2011-07-18 01:54:02 +00002655 typedef llvm::TinyPtrVector<NamedDecl*> ShadowMapEntry;
Douglas Gregor2d435302009-12-30 17:04:44 +00002656
2657private:
2658 /// \brief A mapping from declaration names to the declarations that have
2659 /// this name within a particular scope.
2660 typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
2661
2662 /// \brief A list of shadow maps, which is used to model name hiding.
2663 std::list<ShadowMap> ShadowMaps;
2664
2665 /// \brief The declaration contexts we have already visited.
2666 llvm::SmallPtrSet<DeclContext *, 8> VisitedContexts;
2667
2668 friend class ShadowContextRAII;
2669
2670public:
2671 /// \brief Determine whether we have already visited this context
2672 /// (and, if not, note that we are going to visit that context now).
2673 bool visitedContext(DeclContext *Ctx) {
2674 return !VisitedContexts.insert(Ctx);
2675 }
2676
Douglas Gregor39982192010-08-15 06:18:01 +00002677 bool alreadyVisitedContext(DeclContext *Ctx) {
2678 return VisitedContexts.count(Ctx);
2679 }
2680
Douglas Gregor2d435302009-12-30 17:04:44 +00002681 /// \brief Determine whether the given declaration is hidden in the
2682 /// current scope.
2683 ///
2684 /// \returns the declaration that hides the given declaration, or
2685 /// NULL if no such declaration exists.
2686 NamedDecl *checkHidden(NamedDecl *ND);
2687
2688 /// \brief Add a declaration to the current shadow map.
Chris Lattner83cfc7c2011-07-18 01:54:02 +00002689 void add(NamedDecl *ND) {
2690 ShadowMaps.back()[ND->getDeclName()].push_back(ND);
2691 }
Douglas Gregor2d435302009-12-30 17:04:44 +00002692};
2693
2694/// \brief RAII object that records when we've entered a shadow context.
2695class ShadowContextRAII {
2696 VisibleDeclsRecord &Visible;
2697
2698 typedef VisibleDeclsRecord::ShadowMap ShadowMap;
2699
2700public:
2701 ShadowContextRAII(VisibleDeclsRecord &Visible) : Visible(Visible) {
2702 Visible.ShadowMaps.push_back(ShadowMap());
2703 }
2704
2705 ~ShadowContextRAII() {
Douglas Gregor2d435302009-12-30 17:04:44 +00002706 Visible.ShadowMaps.pop_back();
2707 }
2708};
2709
2710} // end anonymous namespace
2711
Douglas Gregor2d435302009-12-30 17:04:44 +00002712NamedDecl *VisibleDeclsRecord::checkHidden(NamedDecl *ND) {
Douglas Gregor0235c422010-01-14 00:06:47 +00002713 // Look through using declarations.
2714 ND = ND->getUnderlyingDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002715
Douglas Gregor2d435302009-12-30 17:04:44 +00002716 unsigned IDNS = ND->getIdentifierNamespace();
2717 std::list<ShadowMap>::reverse_iterator SM = ShadowMaps.rbegin();
2718 for (std::list<ShadowMap>::reverse_iterator SMEnd = ShadowMaps.rend();
2719 SM != SMEnd; ++SM) {
2720 ShadowMap::iterator Pos = SM->find(ND->getDeclName());
2721 if (Pos == SM->end())
2722 continue;
2723
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002724 for (ShadowMapEntry::iterator I = Pos->second.begin(),
Douglas Gregor2d435302009-12-30 17:04:44 +00002725 IEnd = Pos->second.end();
2726 I != IEnd; ++I) {
2727 // A tag declaration does not hide a non-tag declaration.
John McCalle87beb22010-04-23 18:46:30 +00002728 if ((*I)->hasTagIdentifierNamespace() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002729 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
Douglas Gregor2d435302009-12-30 17:04:44 +00002730 Decl::IDNS_ObjCProtocol)))
2731 continue;
2732
2733 // Protocols are in distinct namespaces from everything else.
2734 if ((((*I)->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
2735 || (IDNS & Decl::IDNS_ObjCProtocol)) &&
2736 (*I)->getIdentifierNamespace() != IDNS)
2737 continue;
2738
Douglas Gregor09bbc652010-01-14 15:47:35 +00002739 // Functions and function templates in the same scope overload
2740 // rather than hide. FIXME: Look for hiding based on function
2741 // signatures!
Douglas Gregor200c99d2010-01-14 03:35:48 +00002742 if ((*I)->isFunctionOrFunctionTemplate() &&
Douglas Gregor09bbc652010-01-14 15:47:35 +00002743 ND->isFunctionOrFunctionTemplate() &&
2744 SM == ShadowMaps.rbegin())
Douglas Gregor200c99d2010-01-14 03:35:48 +00002745 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002746
Douglas Gregor2d435302009-12-30 17:04:44 +00002747 // We've found a declaration that hides this one.
2748 return *I;
2749 }
2750 }
2751
2752 return 0;
2753}
2754
2755static void LookupVisibleDecls(DeclContext *Ctx, LookupResult &Result,
2756 bool QualifiedNameLookup,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002757 bool InBaseClass,
Douglas Gregor2d435302009-12-30 17:04:44 +00002758 VisibleDeclConsumer &Consumer,
2759 VisibleDeclsRecord &Visited) {
Douglas Gregor0c8a1722010-02-04 23:42:48 +00002760 if (!Ctx)
2761 return;
2762
Douglas Gregor2d435302009-12-30 17:04:44 +00002763 // Make sure we don't visit the same context twice.
2764 if (Visited.visitedContext(Ctx->getPrimaryContext()))
2765 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002766
Douglas Gregor7454c562010-07-02 20:37:36 +00002767 if (CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(Ctx))
2768 Result.getSema().ForceDeclarationOfImplicitMembers(Class);
2769
Douglas Gregor2d435302009-12-30 17:04:44 +00002770 // Enumerate all of the results in this context.
Douglas Gregore57e7522012-01-07 09:11:48 +00002771 llvm::SmallVector<DeclContext *, 2> Contexts;
2772 Ctx->collectAllContexts(Contexts);
2773 for (unsigned I = 0, N = Contexts.size(); I != N; ++I) {
2774 DeclContext *CurCtx = Contexts[I];
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002775 for (DeclContext::decl_iterator D = CurCtx->decls_begin(),
Douglas Gregor2d435302009-12-30 17:04:44 +00002776 DEnd = CurCtx->decls_end();
2777 D != DEnd; ++D) {
Douglas Gregora3b23b02010-12-09 21:44:02 +00002778 if (NamedDecl *ND = dyn_cast<NamedDecl>(*D)) {
Douglas Gregor4a814562011-12-14 16:03:29 +00002779 if ((ND = Result.getAcceptableDecl(ND))) {
Erik Verbruggen2e657ff2011-10-06 07:27:49 +00002780 Consumer.FoundDecl(ND, Visited.checkHidden(ND), Ctx, InBaseClass);
Douglas Gregor2d435302009-12-30 17:04:44 +00002781 Visited.add(ND);
2782 }
Douglas Gregora3b23b02010-12-09 21:44:02 +00002783 }
Douglas Gregor04246572011-02-16 01:39:26 +00002784
Sebastian Redlbd595762010-08-31 20:53:31 +00002785 // Visit transparent contexts and inline namespaces inside this context.
Douglas Gregor2d435302009-12-30 17:04:44 +00002786 if (DeclContext *InnerCtx = dyn_cast<DeclContext>(*D)) {
Sebastian Redlbd595762010-08-31 20:53:31 +00002787 if (InnerCtx->isTransparentContext() || InnerCtx->isInlineNamespace())
Douglas Gregor09bbc652010-01-14 15:47:35 +00002788 LookupVisibleDecls(InnerCtx, Result, QualifiedNameLookup, InBaseClass,
Douglas Gregor2d435302009-12-30 17:04:44 +00002789 Consumer, Visited);
2790 }
2791 }
2792 }
2793
2794 // Traverse using directives for qualified name lookup.
2795 if (QualifiedNameLookup) {
2796 ShadowContextRAII Shadow(Visited);
2797 DeclContext::udir_iterator I, E;
2798 for (llvm::tie(I, E) = Ctx->getUsingDirectives(); I != E; ++I) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002799 LookupVisibleDecls((*I)->getNominatedNamespace(), Result,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002800 QualifiedNameLookup, InBaseClass, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00002801 }
2802 }
2803
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002804 // Traverse the contexts of inherited C++ classes.
Douglas Gregor2d435302009-12-30 17:04:44 +00002805 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) {
John McCall67da35c2010-02-04 22:26:26 +00002806 if (!Record->hasDefinition())
2807 return;
2808
Douglas Gregor2d435302009-12-30 17:04:44 +00002809 for (CXXRecordDecl::base_class_iterator B = Record->bases_begin(),
2810 BEnd = Record->bases_end();
2811 B != BEnd; ++B) {
2812 QualType BaseType = B->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002813
Douglas Gregor2d435302009-12-30 17:04:44 +00002814 // Don't look into dependent bases, because name lookup can't look
2815 // there anyway.
2816 if (BaseType->isDependentType())
2817 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002818
Douglas Gregor2d435302009-12-30 17:04:44 +00002819 const RecordType *Record = BaseType->getAs<RecordType>();
2820 if (!Record)
2821 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002822
Douglas Gregor2d435302009-12-30 17:04:44 +00002823 // FIXME: It would be nice to be able to determine whether referencing
2824 // a particular member would be ambiguous. For example, given
2825 //
2826 // struct A { int member; };
2827 // struct B { int member; };
2828 // struct C : A, B { };
2829 //
2830 // void f(C *c) { c->### }
2831 //
2832 // accessing 'member' would result in an ambiguity. However, we
2833 // could be smart enough to qualify the member with the base
2834 // class, e.g.,
2835 //
2836 // c->B::member
2837 //
2838 // or
2839 //
2840 // c->A::member
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002841
Douglas Gregor2d435302009-12-30 17:04:44 +00002842 // Find results in this base class (and its bases).
2843 ShadowContextRAII Shadow(Visited);
2844 LookupVisibleDecls(Record->getDecl(), Result, QualifiedNameLookup,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002845 true, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00002846 }
2847 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002848
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002849 // Traverse the contexts of Objective-C classes.
2850 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Ctx)) {
2851 // Traverse categories.
2852 for (ObjCCategoryDecl *Category = IFace->getCategoryList();
2853 Category; Category = Category->getNextClassCategory()) {
2854 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002855 LookupVisibleDecls(Category, Result, QualifiedNameLookup, false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002856 Consumer, Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002857 }
2858
2859 // Traverse protocols.
Ted Kremenek0ef508d2010-09-01 01:21:15 +00002860 for (ObjCInterfaceDecl::all_protocol_iterator
2861 I = IFace->all_referenced_protocol_begin(),
2862 E = IFace->all_referenced_protocol_end(); I != E; ++I) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002863 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002864 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002865 Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002866 }
2867
2868 // Traverse the superclass.
2869 if (IFace->getSuperClass()) {
2870 ShadowContextRAII Shadow(Visited);
2871 LookupVisibleDecls(IFace->getSuperClass(), Result, QualifiedNameLookup,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002872 true, Consumer, Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002873 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002874
Douglas Gregor0b59e802010-04-19 18:02:19 +00002875 // If there is an implementation, traverse it. We do this to find
2876 // synthesized ivars.
2877 if (IFace->getImplementation()) {
2878 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002879 LookupVisibleDecls(IFace->getImplementation(), Result,
Douglas Gregor0b59e802010-04-19 18:02:19 +00002880 QualifiedNameLookup, true, Consumer, Visited);
2881 }
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002882 } else if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Ctx)) {
2883 for (ObjCProtocolDecl::protocol_iterator I = Protocol->protocol_begin(),
2884 E = Protocol->protocol_end(); I != E; ++I) {
2885 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002886 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002887 Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002888 }
2889 } else if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Ctx)) {
2890 for (ObjCCategoryDecl::protocol_iterator I = Category->protocol_begin(),
2891 E = Category->protocol_end(); I != E; ++I) {
2892 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002893 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002894 Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002895 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002896
Douglas Gregor0b59e802010-04-19 18:02:19 +00002897 // If there is an implementation, traverse it.
2898 if (Category->getImplementation()) {
2899 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002900 LookupVisibleDecls(Category->getImplementation(), Result,
Douglas Gregor0b59e802010-04-19 18:02:19 +00002901 QualifiedNameLookup, true, Consumer, Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002902 }
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002903 }
Douglas Gregor2d435302009-12-30 17:04:44 +00002904}
2905
2906static void LookupVisibleDecls(Scope *S, LookupResult &Result,
2907 UnqualUsingDirectiveSet &UDirs,
2908 VisibleDeclConsumer &Consumer,
2909 VisibleDeclsRecord &Visited) {
2910 if (!S)
2911 return;
2912
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002913 if (!S->getEntity() ||
2914 (!S->getParent() &&
Douglas Gregor39982192010-08-15 06:18:01 +00002915 !Visited.alreadyVisitedContext((DeclContext *)S->getEntity())) ||
Douglas Gregor712dcfe2010-01-07 00:31:29 +00002916 ((DeclContext *)S->getEntity())->isFunctionOrMethod()) {
2917 // Walk through the declarations in this Scope.
2918 for (Scope::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
2919 D != DEnd; ++D) {
John McCall48871652010-08-21 09:40:31 +00002920 if (NamedDecl *ND = dyn_cast<NamedDecl>(*D))
Douglas Gregor4a814562011-12-14 16:03:29 +00002921 if ((ND = Result.getAcceptableDecl(ND))) {
Erik Verbruggen2e657ff2011-10-06 07:27:49 +00002922 Consumer.FoundDecl(ND, Visited.checkHidden(ND), 0, false);
Douglas Gregor712dcfe2010-01-07 00:31:29 +00002923 Visited.add(ND);
2924 }
2925 }
2926 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002927
Douglas Gregor66230062010-03-15 14:33:29 +00002928 // FIXME: C++ [temp.local]p8
Douglas Gregor2d435302009-12-30 17:04:44 +00002929 DeclContext *Entity = 0;
Douglas Gregor4f248632010-01-01 17:44:25 +00002930 if (S->getEntity()) {
Douglas Gregor2d435302009-12-30 17:04:44 +00002931 // Look into this scope's declaration context, along with any of its
2932 // parent lookup contexts (e.g., enclosing classes), up to the point
2933 // where we hit the context stored in the next outer scope.
2934 Entity = (DeclContext *)S->getEntity();
Douglas Gregor66230062010-03-15 14:33:29 +00002935 DeclContext *OuterCtx = findOuterContext(S).first; // FIXME
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002936
Douglas Gregorea166062010-03-15 15:26:48 +00002937 for (DeclContext *Ctx = Entity; Ctx && !Ctx->Equals(OuterCtx);
Douglas Gregor2d435302009-12-30 17:04:44 +00002938 Ctx = Ctx->getLookupParent()) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002939 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
2940 if (Method->isInstanceMethod()) {
2941 // For instance methods, look for ivars in the method's interface.
2942 LookupResult IvarResult(Result.getSema(), Result.getLookupName(),
2943 Result.getNameLoc(), Sema::LookupMemberName);
Douglas Gregor05fcf842010-11-02 20:36:02 +00002944 if (ObjCInterfaceDecl *IFace = Method->getClassInterface()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002945 LookupVisibleDecls(IFace, IvarResult, /*QualifiedNameLookup=*/false,
Fariborz Jahanian97d744b2011-08-31 22:24:06 +00002946 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor05fcf842010-11-02 20:36:02 +00002947 }
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002948 }
2949
2950 // We've already performed all of the name lookup that we need
2951 // to for Objective-C methods; the next context will be the
2952 // outer scope.
2953 break;
2954 }
2955
Douglas Gregor2d435302009-12-30 17:04:44 +00002956 if (Ctx->isFunctionOrMethod())
2957 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002958
2959 LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002960 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00002961 }
2962 } else if (!S->getParent()) {
2963 // Look into the translation unit scope. We walk through the translation
2964 // unit's declaration context, because the Scope itself won't have all of
2965 // the declarations if we loaded a precompiled header.
2966 // FIXME: We would like the translation unit's Scope object to point to the
2967 // translation unit, so we don't need this special "if" branch. However,
2968 // doing so would force the normal C++ name-lookup code to look into the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002969 // translation unit decl when the IdentifierInfo chains would suffice.
Douglas Gregor2d435302009-12-30 17:04:44 +00002970 // Once we fix that problem (which is part of a more general "don't look
Douglas Gregor712dcfe2010-01-07 00:31:29 +00002971 // in DeclContexts unless we have to" optimization), we can eliminate this.
Douglas Gregor2d435302009-12-30 17:04:44 +00002972 Entity = Result.getSema().Context.getTranslationUnitDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002973 LookupVisibleDecls(Entity, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002974 /*InBaseClass=*/false, Consumer, Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002975 }
2976
Douglas Gregor2d435302009-12-30 17:04:44 +00002977 if (Entity) {
2978 // Lookup visible declarations in any namespaces found by using
2979 // directives.
2980 UnqualUsingDirectiveSet::const_iterator UI, UEnd;
2981 llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(Entity);
2982 for (; UI != UEnd; ++UI)
2983 LookupVisibleDecls(const_cast<DeclContext *>(UI->getNominatedNamespace()),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002984 Result, /*QualifiedNameLookup=*/false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002985 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00002986 }
2987
2988 // Lookup names in the parent scope.
2989 ShadowContextRAII Shadow(Visited);
2990 LookupVisibleDecls(S->getParent(), Result, UDirs, Consumer, Visited);
2991}
2992
2993void Sema::LookupVisibleDecls(Scope *S, LookupNameKind Kind,
Douglas Gregor39982192010-08-15 06:18:01 +00002994 VisibleDeclConsumer &Consumer,
2995 bool IncludeGlobalScope) {
Douglas Gregor2d435302009-12-30 17:04:44 +00002996 // Determine the set of using directives available during
2997 // unqualified name lookup.
2998 Scope *Initial = S;
2999 UnqualUsingDirectiveSet UDirs;
3000 if (getLangOptions().CPlusPlus) {
3001 // Find the first namespace or translation-unit scope.
3002 while (S && !isNamespaceOrTranslationUnitScope(S))
3003 S = S->getParent();
3004
3005 UDirs.visitScopeChain(Initial, S);
3006 }
3007 UDirs.done();
3008
3009 // Look for visible declarations.
3010 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
3011 VisibleDeclsRecord Visited;
Douglas Gregor39982192010-08-15 06:18:01 +00003012 if (!IncludeGlobalScope)
3013 Visited.visitedContext(Context.getTranslationUnitDecl());
Douglas Gregor2d435302009-12-30 17:04:44 +00003014 ShadowContextRAII Shadow(Visited);
3015 ::LookupVisibleDecls(Initial, Result, UDirs, Consumer, Visited);
3016}
3017
3018void Sema::LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
Douglas Gregor39982192010-08-15 06:18:01 +00003019 VisibleDeclConsumer &Consumer,
3020 bool IncludeGlobalScope) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003021 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
3022 VisibleDeclsRecord Visited;
Douglas Gregor39982192010-08-15 06:18:01 +00003023 if (!IncludeGlobalScope)
3024 Visited.visitedContext(Context.getTranslationUnitDecl());
Douglas Gregor2d435302009-12-30 17:04:44 +00003025 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003026 ::LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/true,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003027 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00003028}
3029
Chris Lattner43e7f312011-02-18 02:08:43 +00003030/// LookupOrCreateLabel - Do a name lookup of a label with the specified name.
Abramo Bagnara1c3af962011-03-05 18:21:20 +00003031/// If GnuLabelLoc is a valid source location, then this is a definition
3032/// of an __label__ label name, otherwise it is a normal label definition
3033/// or use.
Chris Lattner43e7f312011-02-18 02:08:43 +00003034LabelDecl *Sema::LookupOrCreateLabel(IdentifierInfo *II, SourceLocation Loc,
Abramo Bagnara1c3af962011-03-05 18:21:20 +00003035 SourceLocation GnuLabelLoc) {
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003036 // Do a lookup to see if we have a label with this name already.
Chris Lattner43e7f312011-02-18 02:08:43 +00003037 NamedDecl *Res = 0;
Abramo Bagnara1c3af962011-03-05 18:21:20 +00003038
3039 if (GnuLabelLoc.isValid()) {
3040 // Local label definitions always shadow existing labels.
3041 Res = LabelDecl::Create(Context, CurContext, Loc, II, GnuLabelLoc);
3042 Scope *S = CurScope;
3043 PushOnScopeChains(Res, S, true);
3044 return cast<LabelDecl>(Res);
3045 }
3046
3047 // Not a GNU local label.
3048 Res = LookupSingleName(CurScope, II, Loc, LookupLabel, NotForRedeclaration);
3049 // If we found a label, check to see if it is in the same context as us.
3050 // When in a Block, we don't want to reuse a label in an enclosing function.
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003051 if (Res && Res->getDeclContext() != CurContext)
3052 Res = 0;
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003053 if (Res == 0) {
3054 // If not forward referenced or defined already, create the backing decl.
Abramo Bagnara1c3af962011-03-05 18:21:20 +00003055 Res = LabelDecl::Create(Context, CurContext, Loc, II);
3056 Scope *S = CurScope->getFnParent();
Chris Lattner9ba479b2011-02-18 21:16:39 +00003057 assert(S && "Not in a function?");
3058 PushOnScopeChains(Res, S, true);
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003059 }
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003060 return cast<LabelDecl>(Res);
3061}
3062
3063//===----------------------------------------------------------------------===//
Douglas Gregor2d435302009-12-30 17:04:44 +00003064// Typo correction
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003065//===----------------------------------------------------------------------===//
Douglas Gregor2d435302009-12-30 17:04:44 +00003066
3067namespace {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003068
3069typedef llvm::StringMap<TypoCorrection, llvm::BumpPtrAllocator> TypoResultsMap;
Douglas Gregor29cdc6b2011-06-28 16:44:39 +00003070typedef std::map<unsigned, TypoResultsMap *> TypoEditDistanceMap;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003071
3072static const unsigned MaxTypoDistanceResultSets = 5;
3073
Douglas Gregor2d435302009-12-30 17:04:44 +00003074class TypoCorrectionConsumer : public VisibleDeclConsumer {
3075 /// \brief The name written that is a typo in the source.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003076 StringRef Typo;
Douglas Gregor2d435302009-12-30 17:04:44 +00003077
3078 /// \brief The results found that have the smallest edit distance
3079 /// found (so far) with the typo name.
Douglas Gregor0afa7f62010-10-14 20:34:08 +00003080 ///
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003081 /// The pointer value being set to the current DeclContext indicates
3082 /// whether there is a keyword with this name.
3083 TypoEditDistanceMap BestResults;
Douglas Gregor2d435302009-12-30 17:04:44 +00003084
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003085 Sema &SemaRef;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003086
Douglas Gregor2d435302009-12-30 17:04:44 +00003087public:
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003088 explicit TypoCorrectionConsumer(Sema &SemaRef, IdentifierInfo *Typo)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003089 : Typo(Typo->getName()),
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003090 SemaRef(SemaRef) { }
Douglas Gregor2d435302009-12-30 17:04:44 +00003091
Douglas Gregor29cdc6b2011-06-28 16:44:39 +00003092 ~TypoCorrectionConsumer() {
3093 for (TypoEditDistanceMap::iterator I = BestResults.begin(),
3094 IEnd = BestResults.end();
3095 I != IEnd;
3096 ++I)
3097 delete I->second;
3098 }
3099
Erik Verbruggen2e657ff2011-10-06 07:27:49 +00003100 virtual void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, DeclContext *Ctx,
3101 bool InBaseClass);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003102 void FoundName(StringRef Name);
3103 void addKeywordResult(StringRef Keyword);
3104 void addName(StringRef Name, NamedDecl *ND, unsigned Distance,
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00003105 NestedNameSpecifier *NNS=NULL, bool isKeyword=false);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003106 void addCorrection(TypoCorrection Correction);
Douglas Gregor2d435302009-12-30 17:04:44 +00003107
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003108 typedef TypoResultsMap::iterator result_iterator;
3109 typedef TypoEditDistanceMap::iterator distance_iterator;
3110 distance_iterator begin() { return BestResults.begin(); }
3111 distance_iterator end() { return BestResults.end(); }
3112 void erase(distance_iterator I) { BestResults.erase(I); }
Douglas Gregor0afa7f62010-10-14 20:34:08 +00003113 unsigned size() const { return BestResults.size(); }
3114 bool empty() const { return BestResults.empty(); }
Douglas Gregor2d435302009-12-30 17:04:44 +00003115
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003116 TypoCorrection &operator[](StringRef Name) {
Douglas Gregor29cdc6b2011-06-28 16:44:39 +00003117 return (*BestResults.begin()->second)[Name];
Douglas Gregoraf9eb592010-10-15 13:35:25 +00003118 }
3119
Kaelyn Uhrain0a16a8e2012-02-14 18:56:48 +00003120 unsigned getBestEditDistance(bool Normalized) {
3121 if (BestResults.empty())
3122 return (std::numeric_limits<unsigned>::max)();
3123
3124 unsigned BestED = BestResults.begin()->first;
3125 return Normalized ? TypoCorrection::NormalizeEditDistance(BestED) : BestED;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003126 }
Douglas Gregor2d435302009-12-30 17:04:44 +00003127};
3128
3129}
3130
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003131void TypoCorrectionConsumer::FoundDecl(NamedDecl *ND, NamedDecl *Hiding,
Erik Verbruggen2e657ff2011-10-06 07:27:49 +00003132 DeclContext *Ctx, bool InBaseClass) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003133 // Don't consider hidden names for typo correction.
3134 if (Hiding)
3135 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003136
Douglas Gregor2d435302009-12-30 17:04:44 +00003137 // Only consider entities with identifiers for names, ignoring
3138 // special names (constructors, overloaded operators, selectors,
3139 // etc.).
3140 IdentifierInfo *Name = ND->getIdentifier();
3141 if (!Name)
3142 return;
3143
Douglas Gregor57756ea2010-10-14 22:11:03 +00003144 FoundName(Name->getName());
3145}
3146
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003147void TypoCorrectionConsumer::FoundName(StringRef Name) {
Douglas Gregor93910a52010-10-19 19:39:10 +00003148 // Use a simple length-based heuristic to determine the minimum possible
3149 // edit distance. If the minimum isn't good enough, bail out early.
3150 unsigned MinED = abs((int)Name.size() - (int)Typo.size());
Kaelyn Uhrain1c75d402012-02-07 01:32:58 +00003151 if (MinED && Typo.size() / MinED < 3)
Douglas Gregor93910a52010-10-19 19:39:10 +00003152 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003153
Douglas Gregorc1fb15e2010-10-19 22:14:33 +00003154 // Compute an upper bound on the allowable edit distance, so that the
3155 // edit-distance algorithm can short-circuit.
Kaelyn Uhrain1c75d402012-02-07 01:32:58 +00003156 unsigned UpperBound = (Typo.size() + 2) / 3;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003157
Douglas Gregor2d435302009-12-30 17:04:44 +00003158 // Compute the edit distance between the typo and the name of this
Kaelyn Uhrain1c75d402012-02-07 01:32:58 +00003159 // entity, and add the identifier to the list of results.
3160 addName(Name, NULL, Typo.edit_distance(Name, true, UpperBound));
Douglas Gregor2d435302009-12-30 17:04:44 +00003161}
3162
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003163void TypoCorrectionConsumer::addKeywordResult(StringRef Keyword) {
Kaelyn Uhrain1c75d402012-02-07 01:32:58 +00003164 // Compute the edit distance between the typo and this keyword,
3165 // and add the keyword to the list of results.
3166 addName(Keyword, NULL, Typo.edit_distance(Keyword), NULL, true);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003167}
3168
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003169void TypoCorrectionConsumer::addName(StringRef Name,
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003170 NamedDecl *ND,
3171 unsigned Distance,
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00003172 NestedNameSpecifier *NNS,
3173 bool isKeyword) {
3174 TypoCorrection TC(&SemaRef.Context.Idents.get(Name), ND, NNS, Distance);
3175 if (isKeyword) TC.makeKeyword();
3176 addCorrection(TC);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003177}
3178
3179void TypoCorrectionConsumer::addCorrection(TypoCorrection Correction) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003180 StringRef Name = Correction.getCorrectionAsIdentifierInfo()->getName();
Kaelyn Uhrain0a16a8e2012-02-14 18:56:48 +00003181 TypoResultsMap *& Map = BestResults[Correction.getEditDistance(false)];
Douglas Gregor29cdc6b2011-06-28 16:44:39 +00003182 if (!Map)
3183 Map = new TypoResultsMap;
Chandler Carruth7d85c9b2011-06-28 22:48:40 +00003184
3185 TypoCorrection &CurrentCorrection = (*Map)[Name];
3186 if (!CurrentCorrection ||
3187 // FIXME: The following should be rolled up into an operator< on
3188 // TypoCorrection with a more principled definition.
3189 CurrentCorrection.isKeyword() < Correction.isKeyword() ||
3190 Correction.getAsString(SemaRef.getLangOptions()) <
3191 CurrentCorrection.getAsString(SemaRef.getLangOptions()))
3192 CurrentCorrection = Correction;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003193
3194 while (BestResults.size() > MaxTypoDistanceResultSets) {
Douglas Gregor29cdc6b2011-06-28 16:44:39 +00003195 TypoEditDistanceMap::iterator Last = BestResults.end();
3196 --Last;
3197 delete Last->second;
3198 BestResults.erase(Last);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003199 }
3200}
3201
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003202// Fill the supplied vector with the IdentifierInfo pointers for each piece of
3203// the given NestedNameSpecifier (i.e. given a NestedNameSpecifier "foo::bar::",
3204// fill the vector with the IdentifierInfo pointers for "foo" and "bar").
3205static void getNestedNameSpecifierIdentifiers(
3206 NestedNameSpecifier *NNS,
3207 SmallVectorImpl<const IdentifierInfo*> &Identifiers) {
3208 if (NestedNameSpecifier *Prefix = NNS->getPrefix())
3209 getNestedNameSpecifierIdentifiers(Prefix, Identifiers);
3210 else
3211 Identifiers.clear();
3212
3213 const IdentifierInfo *II = NULL;
3214
3215 switch (NNS->getKind()) {
3216 case NestedNameSpecifier::Identifier:
3217 II = NNS->getAsIdentifier();
3218 break;
3219
3220 case NestedNameSpecifier::Namespace:
3221 if (NNS->getAsNamespace()->isAnonymousNamespace())
3222 return;
3223 II = NNS->getAsNamespace()->getIdentifier();
3224 break;
3225
3226 case NestedNameSpecifier::NamespaceAlias:
3227 II = NNS->getAsNamespaceAlias()->getIdentifier();
3228 break;
3229
3230 case NestedNameSpecifier::TypeSpecWithTemplate:
3231 case NestedNameSpecifier::TypeSpec:
3232 II = QualType(NNS->getAsType(), 0).getBaseTypeIdentifier();
3233 break;
3234
3235 case NestedNameSpecifier::Global:
3236 return;
3237 }
3238
3239 if (II)
3240 Identifiers.push_back(II);
3241}
3242
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003243namespace {
3244
3245class SpecifierInfo {
3246 public:
3247 DeclContext* DeclCtx;
3248 NestedNameSpecifier* NameSpecifier;
3249 unsigned EditDistance;
3250
3251 SpecifierInfo(DeclContext *Ctx, NestedNameSpecifier *NNS, unsigned ED)
3252 : DeclCtx(Ctx), NameSpecifier(NNS), EditDistance(ED) {}
3253};
3254
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003255typedef SmallVector<DeclContext*, 4> DeclContextList;
3256typedef SmallVector<SpecifierInfo, 16> SpecifierInfoList;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003257
3258class NamespaceSpecifierSet {
3259 ASTContext &Context;
3260 DeclContextList CurContextChain;
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003261 SmallVector<const IdentifierInfo*, 4> CurContextIdentifiers;
3262 SmallVector<const IdentifierInfo*, 4> CurNameSpecifierIdentifiers;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003263 bool isSorted;
3264
3265 SpecifierInfoList Specifiers;
3266 llvm::SmallSetVector<unsigned, 4> Distances;
3267 llvm::DenseMap<unsigned, SpecifierInfoList> DistanceMap;
3268
3269 /// \brief Helper for building the list of DeclContexts between the current
3270 /// context and the top of the translation unit
3271 static DeclContextList BuildContextChain(DeclContext *Start);
3272
3273 void SortNamespaces();
3274
3275 public:
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003276 NamespaceSpecifierSet(ASTContext &Context, DeclContext *CurContext,
3277 CXXScopeSpec *CurScopeSpec)
Benjamin Kramerde1d6232011-07-05 09:46:31 +00003278 : Context(Context), CurContextChain(BuildContextChain(CurContext)),
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003279 isSorted(true) {
3280 if (CurScopeSpec && CurScopeSpec->getScopeRep())
3281 getNestedNameSpecifierIdentifiers(CurScopeSpec->getScopeRep(),
3282 CurNameSpecifierIdentifiers);
3283 // Build the list of identifiers that would be used for an absolute
3284 // (from the global context) NestedNameSpecifier refering to the current
3285 // context.
3286 for (DeclContextList::reverse_iterator C = CurContextChain.rbegin(),
3287 CEnd = CurContextChain.rend();
3288 C != CEnd; ++C) {
3289 if (NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(*C))
3290 CurContextIdentifiers.push_back(ND->getIdentifier());
3291 }
3292 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003293
3294 /// \brief Add the namespace to the set, computing the corresponding
3295 /// NestedNameSpecifier and its distance in the process.
3296 void AddNamespace(NamespaceDecl *ND);
3297
3298 typedef SpecifierInfoList::iterator iterator;
3299 iterator begin() {
3300 if (!isSorted) SortNamespaces();
3301 return Specifiers.begin();
3302 }
3303 iterator end() { return Specifiers.end(); }
3304};
3305
3306}
3307
3308DeclContextList NamespaceSpecifierSet::BuildContextChain(DeclContext *Start) {
Chandler Carruthb198e5a2011-06-28 21:43:34 +00003309 assert(Start && "Bulding a context chain from a null context");
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003310 DeclContextList Chain;
3311 for (DeclContext *DC = Start->getPrimaryContext(); DC != NULL;
3312 DC = DC->getLookupParent()) {
3313 NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(DC);
3314 if (!DC->isInlineNamespace() && !DC->isTransparentContext() &&
3315 !(ND && ND->isAnonymousNamespace()))
3316 Chain.push_back(DC->getPrimaryContext());
3317 }
3318 return Chain;
3319}
3320
3321void NamespaceSpecifierSet::SortNamespaces() {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003322 SmallVector<unsigned, 4> sortedDistances;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003323 sortedDistances.append(Distances.begin(), Distances.end());
3324
3325 if (sortedDistances.size() > 1)
3326 std::sort(sortedDistances.begin(), sortedDistances.end());
3327
3328 Specifiers.clear();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003329 for (SmallVector<unsigned, 4>::iterator DI = sortedDistances.begin(),
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003330 DIEnd = sortedDistances.end();
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003331 DI != DIEnd; ++DI) {
3332 SpecifierInfoList &SpecList = DistanceMap[*DI];
3333 Specifiers.append(SpecList.begin(), SpecList.end());
3334 }
3335
3336 isSorted = true;
3337}
3338
3339void NamespaceSpecifierSet::AddNamespace(NamespaceDecl *ND) {
Chandler Carruthb198e5a2011-06-28 21:43:34 +00003340 DeclContext *Ctx = cast<DeclContext>(ND);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003341 NestedNameSpecifier *NNS = NULL;
3342 unsigned NumSpecifiers = 0;
3343 DeclContextList NamespaceDeclChain(BuildContextChain(Ctx));
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003344 DeclContextList FullNamespaceDeclChain(NamespaceDeclChain);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003345
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003346 // Eliminate common elements from the two DeclContext chains.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003347 for (DeclContextList::reverse_iterator C = CurContextChain.rbegin(),
3348 CEnd = CurContextChain.rend();
Chandler Carruthb198e5a2011-06-28 21:43:34 +00003349 C != CEnd && !NamespaceDeclChain.empty() &&
3350 NamespaceDeclChain.back() == *C; ++C) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003351 NamespaceDeclChain.pop_back();
3352 }
3353
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003354 // Add an explicit leading '::' specifier if needed.
3355 if (NamespaceDecl *ND =
Kaelyn Uhrain618f97c2012-02-15 22:59:03 +00003356 NamespaceDeclChain.empty() ? NULL :
3357 dyn_cast_or_null<NamespaceDecl>(NamespaceDeclChain.back())) {
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003358 IdentifierInfo *Name = ND->getIdentifier();
3359 if (std::find(CurContextIdentifiers.begin(), CurContextIdentifiers.end(),
3360 Name) != CurContextIdentifiers.end() ||
3361 std::find(CurNameSpecifierIdentifiers.begin(),
3362 CurNameSpecifierIdentifiers.end(),
3363 Name) != CurNameSpecifierIdentifiers.end()) {
3364 NamespaceDeclChain = FullNamespaceDeclChain;
3365 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
3366 }
3367 }
3368
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003369 // Build the NestedNameSpecifier from what is left of the NamespaceDeclChain
3370 for (DeclContextList::reverse_iterator C = NamespaceDeclChain.rbegin(),
3371 CEnd = NamespaceDeclChain.rend();
3372 C != CEnd; ++C) {
3373 NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(*C);
3374 if (ND) {
3375 NNS = NestedNameSpecifier::Create(Context, NNS, ND);
3376 ++NumSpecifiers;
3377 }
3378 }
3379
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003380 // If the built NestedNameSpecifier would be replacing an existing
3381 // NestedNameSpecifier, use the number of component identifiers that
3382 // would need to be changed as the edit distance instead of the number
3383 // of components in the built NestedNameSpecifier.
3384 if (NNS && !CurNameSpecifierIdentifiers.empty()) {
3385 SmallVector<const IdentifierInfo*, 4> NewNameSpecifierIdentifiers;
3386 getNestedNameSpecifierIdentifiers(NNS, NewNameSpecifierIdentifiers);
3387 NumSpecifiers = llvm::ComputeEditDistance(
3388 llvm::ArrayRef<const IdentifierInfo*>(CurNameSpecifierIdentifiers),
3389 llvm::ArrayRef<const IdentifierInfo*>(NewNameSpecifierIdentifiers));
3390 }
3391
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003392 isSorted = false;
3393 Distances.insert(NumSpecifiers);
3394 DistanceMap[NumSpecifiers].push_back(SpecifierInfo(Ctx, NNS, NumSpecifiers));
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003395}
3396
Douglas Gregord507d772010-10-20 03:06:34 +00003397/// \brief Perform name lookup for a possible result for typo correction.
3398static void LookupPotentialTypoResult(Sema &SemaRef,
3399 LookupResult &Res,
3400 IdentifierInfo *Name,
3401 Scope *S, CXXScopeSpec *SS,
3402 DeclContext *MemberContext,
3403 bool EnteringContext,
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003404 bool isObjCIvarLookup) {
Douglas Gregord507d772010-10-20 03:06:34 +00003405 Res.suppressDiagnostics();
3406 Res.clear();
3407 Res.setLookupName(Name);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003408 if (MemberContext) {
Douglas Gregord507d772010-10-20 03:06:34 +00003409 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(MemberContext)) {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003410 if (isObjCIvarLookup) {
Douglas Gregord507d772010-10-20 03:06:34 +00003411 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(Name)) {
3412 Res.addDecl(Ivar);
3413 Res.resolveKind();
3414 return;
3415 }
3416 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003417
Douglas Gregord507d772010-10-20 03:06:34 +00003418 if (ObjCPropertyDecl *Prop = Class->FindPropertyDeclaration(Name)) {
3419 Res.addDecl(Prop);
3420 Res.resolveKind();
3421 return;
3422 }
3423 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003424
Douglas Gregord507d772010-10-20 03:06:34 +00003425 SemaRef.LookupQualifiedName(Res, MemberContext);
3426 return;
3427 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003428
3429 SemaRef.LookupParsedName(Res, S, SS, /*AllowBuiltinCreation=*/false,
Douglas Gregord507d772010-10-20 03:06:34 +00003430 EnteringContext);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003431
Douglas Gregord507d772010-10-20 03:06:34 +00003432 // Fake ivar lookup; this should really be part of
3433 // LookupParsedName.
3434 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) {
3435 if (Method->isInstanceMethod() && Method->getClassInterface() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003436 (Res.empty() ||
Douglas Gregord507d772010-10-20 03:06:34 +00003437 (Res.isSingleResult() &&
3438 Res.getFoundDecl()->isDefinedOutsideFunctionOrMethod()))) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003439 if (ObjCIvarDecl *IV
Douglas Gregord507d772010-10-20 03:06:34 +00003440 = Method->getClassInterface()->lookupInstanceVariable(Name)) {
3441 Res.addDecl(IV);
3442 Res.resolveKind();
3443 }
3444 }
3445 }
3446}
3447
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003448/// \brief Add keywords to the consumer as possible typo corrections.
3449static void AddKeywordsToConsumer(Sema &SemaRef,
3450 TypoCorrectionConsumer &Consumer,
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003451 Scope *S, CorrectionCandidateCallback &CCC) {
3452 if (CCC.WantObjCSuper)
3453 Consumer.addKeywordResult("super");
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003454
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003455 if (CCC.WantTypeSpecifiers) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003456 // Add type-specifier keywords to the set of results.
3457 const char *CTypeSpecs[] = {
3458 "char", "const", "double", "enum", "float", "int", "long", "short",
Douglas Gregor3b22a882011-07-01 21:27:45 +00003459 "signed", "struct", "union", "unsigned", "void", "volatile",
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003460 "_Complex", "_Imaginary",
3461 // storage-specifiers as well
3462 "extern", "inline", "static", "typedef"
3463 };
3464
3465 const unsigned NumCTypeSpecs = sizeof(CTypeSpecs) / sizeof(CTypeSpecs[0]);
3466 for (unsigned I = 0; I != NumCTypeSpecs; ++I)
3467 Consumer.addKeywordResult(CTypeSpecs[I]);
3468
3469 if (SemaRef.getLangOptions().C99)
3470 Consumer.addKeywordResult("restrict");
3471 if (SemaRef.getLangOptions().Bool || SemaRef.getLangOptions().CPlusPlus)
3472 Consumer.addKeywordResult("bool");
Douglas Gregor3b22a882011-07-01 21:27:45 +00003473 else if (SemaRef.getLangOptions().C99)
3474 Consumer.addKeywordResult("_Bool");
3475
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003476 if (SemaRef.getLangOptions().CPlusPlus) {
3477 Consumer.addKeywordResult("class");
3478 Consumer.addKeywordResult("typename");
3479 Consumer.addKeywordResult("wchar_t");
3480
3481 if (SemaRef.getLangOptions().CPlusPlus0x) {
3482 Consumer.addKeywordResult("char16_t");
3483 Consumer.addKeywordResult("char32_t");
3484 Consumer.addKeywordResult("constexpr");
3485 Consumer.addKeywordResult("decltype");
3486 Consumer.addKeywordResult("thread_local");
3487 }
3488 }
3489
3490 if (SemaRef.getLangOptions().GNUMode)
3491 Consumer.addKeywordResult("typeof");
3492 }
3493
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003494 if (CCC.WantCXXNamedCasts && SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003495 Consumer.addKeywordResult("const_cast");
3496 Consumer.addKeywordResult("dynamic_cast");
3497 Consumer.addKeywordResult("reinterpret_cast");
3498 Consumer.addKeywordResult("static_cast");
3499 }
3500
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003501 if (CCC.WantExpressionKeywords) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003502 Consumer.addKeywordResult("sizeof");
3503 if (SemaRef.getLangOptions().Bool || SemaRef.getLangOptions().CPlusPlus) {
3504 Consumer.addKeywordResult("false");
3505 Consumer.addKeywordResult("true");
3506 }
3507
3508 if (SemaRef.getLangOptions().CPlusPlus) {
3509 const char *CXXExprs[] = {
3510 "delete", "new", "operator", "throw", "typeid"
3511 };
3512 const unsigned NumCXXExprs = sizeof(CXXExprs) / sizeof(CXXExprs[0]);
3513 for (unsigned I = 0; I != NumCXXExprs; ++I)
3514 Consumer.addKeywordResult(CXXExprs[I]);
3515
3516 if (isa<CXXMethodDecl>(SemaRef.CurContext) &&
3517 cast<CXXMethodDecl>(SemaRef.CurContext)->isInstance())
3518 Consumer.addKeywordResult("this");
3519
3520 if (SemaRef.getLangOptions().CPlusPlus0x) {
3521 Consumer.addKeywordResult("alignof");
3522 Consumer.addKeywordResult("nullptr");
3523 }
3524 }
3525 }
3526
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003527 if (CCC.WantRemainingKeywords) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003528 if (SemaRef.getCurFunctionOrMethodDecl() || SemaRef.getCurBlock()) {
3529 // Statements.
3530 const char *CStmts[] = {
3531 "do", "else", "for", "goto", "if", "return", "switch", "while" };
3532 const unsigned NumCStmts = sizeof(CStmts) / sizeof(CStmts[0]);
3533 for (unsigned I = 0; I != NumCStmts; ++I)
3534 Consumer.addKeywordResult(CStmts[I]);
3535
3536 if (SemaRef.getLangOptions().CPlusPlus) {
3537 Consumer.addKeywordResult("catch");
3538 Consumer.addKeywordResult("try");
3539 }
3540
3541 if (S && S->getBreakParent())
3542 Consumer.addKeywordResult("break");
3543
3544 if (S && S->getContinueParent())
3545 Consumer.addKeywordResult("continue");
3546
3547 if (!SemaRef.getCurFunction()->SwitchStack.empty()) {
3548 Consumer.addKeywordResult("case");
3549 Consumer.addKeywordResult("default");
3550 }
3551 } else {
3552 if (SemaRef.getLangOptions().CPlusPlus) {
3553 Consumer.addKeywordResult("namespace");
3554 Consumer.addKeywordResult("template");
3555 }
3556
3557 if (S && S->isClassScope()) {
3558 Consumer.addKeywordResult("explicit");
3559 Consumer.addKeywordResult("friend");
3560 Consumer.addKeywordResult("mutable");
3561 Consumer.addKeywordResult("private");
3562 Consumer.addKeywordResult("protected");
3563 Consumer.addKeywordResult("public");
3564 Consumer.addKeywordResult("virtual");
3565 }
3566 }
3567
3568 if (SemaRef.getLangOptions().CPlusPlus) {
3569 Consumer.addKeywordResult("using");
3570
3571 if (SemaRef.getLangOptions().CPlusPlus0x)
3572 Consumer.addKeywordResult("static_assert");
3573 }
3574 }
3575}
3576
Kaelyn Uhrain0a16a8e2012-02-14 18:56:48 +00003577static bool isCandidateViable(CorrectionCandidateCallback &CCC,
3578 TypoCorrection &Candidate) {
3579 Candidate.setCallbackDistance(CCC.RankCandidate(Candidate));
3580 return Candidate.getEditDistance(false) != TypoCorrection::InvalidDistance;
3581}
3582
Douglas Gregor2d435302009-12-30 17:04:44 +00003583/// \brief Try to "correct" a typo in the source code by finding
3584/// visible declarations whose names are similar to the name that was
3585/// present in the source code.
3586///
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003587/// \param TypoName the \c DeclarationNameInfo structure that contains
3588/// the name that was present in the source code along with its location.
3589///
3590/// \param LookupKind the name-lookup criteria used to search for the name.
Douglas Gregor2d435302009-12-30 17:04:44 +00003591///
3592/// \param S the scope in which name lookup occurs.
3593///
3594/// \param SS the nested-name-specifier that precedes the name we're
3595/// looking for, if present.
3596///
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003597/// \param CCC A CorrectionCandidateCallback object that provides further
3598/// validation of typo correction candidates. It also provides flags for
3599/// determining the set of keywords permitted.
3600///
Douglas Gregoraf2bd472009-12-31 07:42:17 +00003601/// \param MemberContext if non-NULL, the context in which to look for
3602/// a member access expression.
3603///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003604/// \param EnteringContext whether we're entering the context described by
Douglas Gregor598b08f2009-12-31 05:20:13 +00003605/// the nested-name-specifier SS.
3606///
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003607/// \param OPT when non-NULL, the search for visible declarations will
3608/// also walk the protocols in the qualified interfaces of \p OPT.
3609///
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003610/// \returns a \c TypoCorrection containing the corrected name if the typo
3611/// along with information such as the \c NamedDecl where the corrected name
3612/// was declared, and any additional \c NestedNameSpecifier needed to access
3613/// it (C++ only). The \c TypoCorrection is empty if there is no correction.
3614TypoCorrection Sema::CorrectTypo(const DeclarationNameInfo &TypoName,
3615 Sema::LookupNameKind LookupKind,
3616 Scope *S, CXXScopeSpec *SS,
Kaelyn Uhrain4e8942c2012-01-31 23:49:25 +00003617 CorrectionCandidateCallback &CCC,
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003618 DeclContext *MemberContext,
3619 bool EnteringContext,
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003620 const ObjCObjectPointerType *OPT) {
Douglas Gregor8ed0c0b2010-07-09 17:35:33 +00003621 if (Diags.hasFatalErrorOccurred() || !getLangOptions().SpellChecking)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003622 return TypoCorrection();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003623
Francois Pichet9c391132011-12-03 15:55:29 +00003624 // In Microsoft mode, don't perform typo correction in a template member
3625 // function dependent context because it interferes with the "lookup into
3626 // dependent bases of class templates" feature.
3627 if (getLangOptions().MicrosoftMode && CurContext->isDependentContext() &&
3628 isa<CXXMethodDecl>(CurContext))
3629 return TypoCorrection();
3630
Douglas Gregor2d435302009-12-30 17:04:44 +00003631 // We only attempt to correct typos for identifiers.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003632 IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo();
Douglas Gregor2d435302009-12-30 17:04:44 +00003633 if (!Typo)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003634 return TypoCorrection();
Douglas Gregor2d435302009-12-30 17:04:44 +00003635
3636 // If the scope specifier itself was invalid, don't try to correct
3637 // typos.
3638 if (SS && SS->isInvalid())
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003639 return TypoCorrection();
Douglas Gregor2d435302009-12-30 17:04:44 +00003640
3641 // Never try to correct typos during template deduction or
3642 // instantiation.
3643 if (!ActiveTemplateInstantiations.empty())
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003644 return TypoCorrection();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003645
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003646 NamespaceSpecifierSet Namespaces(Context, CurContext, SS);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003647
3648 TypoCorrectionConsumer Consumer(*this, Typo);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003649
Kaelyn Uhrain0a16a8e2012-02-14 18:56:48 +00003650 // If a callback object considers an empty typo correction candidate to be
3651 // viable, assume it does not do any actual validation of the candidates.
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00003652 TypoCorrection EmptyCorrection;
Kaelyn Uhrain0a16a8e2012-02-14 18:56:48 +00003653 bool ValidatingCallback = !isCandidateViable(CCC, EmptyCorrection);
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00003654
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003655 // Perform name lookup to find visible, similarly-named entities.
Douglas Gregor87074f12010-10-20 01:32:02 +00003656 bool IsUnqualifiedLookup = false;
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003657 DeclContext *QualifiedDC = MemberContext;
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003658 if (MemberContext) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003659 LookupVisibleDecls(MemberContext, LookupKind, Consumer);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003660
3661 // Look in qualified interfaces.
3662 if (OPT) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003663 for (ObjCObjectPointerType::qual_iterator
3664 I = OPT->qual_begin(), E = OPT->qual_end();
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003665 I != E; ++I)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003666 LookupVisibleDecls(*I, LookupKind, Consumer);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003667 }
3668 } else if (SS && SS->isSet()) {
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003669 QualifiedDC = computeDeclContext(*SS, EnteringContext);
3670 if (!QualifiedDC)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003671 return TypoCorrection();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003672
Douglas Gregor87074f12010-10-20 01:32:02 +00003673 // Provide a stop gap for files that are just seriously broken. Trying
3674 // to correct all typos can turn into a HUGE performance penalty, causing
3675 // some files to take minutes to get rejected by the parser.
3676 if (TyposCorrected + UnqualifiedTyposCorrected.size() >= 20)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003677 return TypoCorrection();
Douglas Gregor87074f12010-10-20 01:32:02 +00003678 ++TyposCorrected;
3679
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003680 LookupVisibleDecls(QualifiedDC, LookupKind, Consumer);
Douglas Gregor2d435302009-12-30 17:04:44 +00003681 } else {
Douglas Gregor87074f12010-10-20 01:32:02 +00003682 IsUnqualifiedLookup = true;
3683 UnqualifiedTyposCorrectedMap::iterator Cached
3684 = UnqualifiedTyposCorrected.find(Typo);
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00003685 if (Cached != UnqualifiedTyposCorrected.end()) {
3686 // Add the cached value, unless it's a keyword or fails validation. In the
3687 // keyword case, we'll end up adding the keyword below.
3688 if (Cached->second) {
3689 if (!Cached->second.isKeyword() &&
Kaelyn Uhrain0a16a8e2012-02-14 18:56:48 +00003690 isCandidateViable(CCC, Cached->second))
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00003691 Consumer.addCorrection(Cached->second);
3692 } else {
3693 // Only honor no-correction cache hits when a callback that will validate
3694 // correction candidates is not being used.
3695 if (!ValidatingCallback)
3696 return TypoCorrection();
3697 }
3698 }
3699 if (Cached == UnqualifiedTyposCorrected.end()) {
Douglas Gregor87074f12010-10-20 01:32:02 +00003700 // Provide a stop gap for files that are just seriously broken. Trying
3701 // to correct all typos can turn into a HUGE performance penalty, causing
3702 // some files to take minutes to get rejected by the parser.
3703 if (TyposCorrected + UnqualifiedTyposCorrected.size() >= 20)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003704 return TypoCorrection();
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00003705 }
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003706 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003707
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003708 if (IsUnqualifiedLookup || (QualifiedDC && QualifiedDC->isNamespace())) {
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00003709 // For unqualified lookup, look through all of the names that we have
3710 // seen in this translation unit.
Kaelyn Uhrain1c75d402012-02-07 01:32:58 +00003711 // FIXME: Re-add the ability to skip very unlikely potential corrections.
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00003712 for (IdentifierTable::iterator I = Context.Idents.begin(),
3713 IEnd = Context.Idents.end();
3714 I != IEnd; ++I)
3715 Consumer.FoundName(I->getKey());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003716
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00003717 // Walk through identifiers in external identifier sources.
Kaelyn Uhrain1c75d402012-02-07 01:32:58 +00003718 // FIXME: Re-add the ability to skip very unlikely potential corrections.
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00003719 if (IdentifierInfoLookup *External
3720 = Context.Idents.getExternalIdentifierLookup()) {
Dylan Noblesmithe2778992012-02-05 02:12:40 +00003721 OwningPtr<IdentifierIterator> Iter(External->getIdentifiers());
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00003722 do {
3723 StringRef Name = Iter->Next();
3724 if (Name.empty())
3725 break;
Douglas Gregor57756ea2010-10-14 22:11:03 +00003726
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00003727 Consumer.FoundName(Name);
3728 } while (true);
Douglas Gregor57756ea2010-10-14 22:11:03 +00003729 }
Douglas Gregor2d435302009-12-30 17:04:44 +00003730 }
3731
Kaelyn Uhrain4e8942c2012-01-31 23:49:25 +00003732 AddKeywordsToConsumer(*this, Consumer, S, CCC);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003733
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003734 // If we haven't found anything, we're done.
Douglas Gregor87074f12010-10-20 01:32:02 +00003735 if (Consumer.empty()) {
3736 // If this was an unqualified lookup, note that no correction was found.
3737 if (IsUnqualifiedLookup)
3738 (void)UnqualifiedTyposCorrected[Typo];
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003739
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003740 return TypoCorrection();
Douglas Gregor87074f12010-10-20 01:32:02 +00003741 }
Douglas Gregor2d435302009-12-30 17:04:44 +00003742
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003743 // Make sure that the user typed at least 3 characters for each correction
Douglas Gregor0afa7f62010-10-14 20:34:08 +00003744 // made. Otherwise, we don't even both looking at the results.
Kaelyn Uhrain0a16a8e2012-02-14 18:56:48 +00003745 unsigned ED = Consumer.getBestEditDistance(true);
Douglas Gregor87074f12010-10-20 01:32:02 +00003746 if (ED > 0 && Typo->getName().size() / ED < 3) {
3747 // If this was an unqualified lookup, note that no correction was found.
Douglas Gregoraf1daa92010-10-27 14:20:34 +00003748 if (IsUnqualifiedLookup)
Douglas Gregor87074f12010-10-20 01:32:02 +00003749 (void)UnqualifiedTyposCorrected[Typo];
3750
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003751 return TypoCorrection();
3752 }
3753
3754 // Build the NestedNameSpecifiers for the KnownNamespaces
3755 if (getLangOptions().CPlusPlus) {
3756 // Load any externally-known namespaces.
3757 if (ExternalSource && !LoadedExternalKnownNamespaces) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003758 SmallVector<NamespaceDecl *, 4> ExternalKnownNamespaces;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003759 LoadedExternalKnownNamespaces = true;
3760 ExternalSource->ReadKnownNamespaces(ExternalKnownNamespaces);
3761 for (unsigned I = 0, N = ExternalKnownNamespaces.size(); I != N; ++I)
3762 KnownNamespaces[ExternalKnownNamespaces[I]] = true;
3763 }
3764
3765 for (llvm::DenseMap<NamespaceDecl*, bool>::iterator
3766 KNI = KnownNamespaces.begin(),
3767 KNIEnd = KnownNamespaces.end();
3768 KNI != KNIEnd; ++KNI)
3769 Namespaces.AddNamespace(KNI->first);
Douglas Gregor87074f12010-10-20 01:32:02 +00003770 }
Douglas Gregor0afa7f62010-10-14 20:34:08 +00003771
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003772 // Weed out any names that could not be found by name lookup or, if a
3773 // CorrectionCandidateCallback object was provided, failed validation.
Kaelyn Uhrain0a16a8e2012-02-14 18:56:48 +00003774 llvm::SmallVector<TypoCorrection, 16> QualifiedResults;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003775 LookupResult TmpRes(*this, TypoName, LookupKind);
3776 TmpRes.suppressDiagnostics();
3777 while (!Consumer.empty()) {
3778 TypoCorrectionConsumer::distance_iterator DI = Consumer.begin();
3779 unsigned ED = DI->first;
Douglas Gregor29cdc6b2011-06-28 16:44:39 +00003780 for (TypoCorrectionConsumer::result_iterator I = DI->second->begin(),
3781 IEnd = DI->second->end();
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003782 I != IEnd; /* Increment in loop. */) {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003783 // If the item already has been looked up or is a keyword, keep it.
3784 // If a validator callback object was given, drop the correction
3785 // unless it passes validation.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003786 if (I->second.isResolved()) {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003787 TypoCorrectionConsumer::result_iterator Prev = I;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003788 ++I;
Kaelyn Uhrain0a16a8e2012-02-14 18:56:48 +00003789 if (!isCandidateViable(CCC, Prev->second))
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003790 DI->second->erase(Prev);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003791 continue;
Douglas Gregor0afa7f62010-10-14 20:34:08 +00003792 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003793
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003794 // Perform name lookup on this name.
3795 IdentifierInfo *Name = I->second.getCorrectionAsIdentifierInfo();
3796 LookupPotentialTypoResult(*this, TmpRes, Name, S, SS, MemberContext,
Kaelyn Uhrain4e8942c2012-01-31 23:49:25 +00003797 EnteringContext, CCC.IsObjCIvarLookup);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003798
3799 switch (TmpRes.getResultKind()) {
3800 case LookupResult::NotFound:
3801 case LookupResult::NotFoundInCurrentInstantiation:
Kaelyn Uhrain5a43b462011-09-07 20:25:59 +00003802 case LookupResult::FoundUnresolvedValue:
Kaelyn Uhrain0a16a8e2012-02-14 18:56:48 +00003803 QualifiedResults.push_back(I->second);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003804 // We didn't find this name in our scope, or didn't like what we found;
3805 // ignore it.
3806 {
3807 TypoCorrectionConsumer::result_iterator Next = I;
3808 ++Next;
Douglas Gregor29cdc6b2011-06-28 16:44:39 +00003809 DI->second->erase(I);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003810 I = Next;
3811 }
3812 break;
3813
3814 case LookupResult::Ambiguous:
3815 // We don't deal with ambiguities.
3816 return TypoCorrection();
3817
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00003818 case LookupResult::FoundOverloaded: {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003819 TypoCorrectionConsumer::result_iterator Prev = I;
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00003820 // Store all of the Decls for overloaded symbols
3821 for (LookupResult::iterator TRD = TmpRes.begin(),
3822 TRDEnd = TmpRes.end();
3823 TRD != TRDEnd; ++TRD)
3824 I->second.addCorrectionDecl(*TRD);
3825 ++I;
Kaelyn Uhrain0a16a8e2012-02-14 18:56:48 +00003826 if (!isCandidateViable(CCC, Prev->second))
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003827 DI->second->erase(Prev);
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00003828 break;
3829 }
3830
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003831 case LookupResult::Found: {
3832 TypoCorrectionConsumer::result_iterator Prev = I;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003833 I->second.setCorrectionDecl(TmpRes.getAsSingle<NamedDecl>());
3834 ++I;
Kaelyn Uhrain0a16a8e2012-02-14 18:56:48 +00003835 if (!isCandidateViable(CCC, Prev->second))
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003836 DI->second->erase(Prev);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003837 break;
3838 }
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003839
3840 }
Douglas Gregor0afa7f62010-10-14 20:34:08 +00003841 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003842
Douglas Gregor29cdc6b2011-06-28 16:44:39 +00003843 if (DI->second->empty())
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003844 Consumer.erase(DI);
3845 else if (!getLangOptions().CPlusPlus || QualifiedResults.empty() || !ED)
3846 // If there are results in the closest possible bucket, stop
3847 break;
3848
3849 // Only perform the qualified lookups for C++
3850 if (getLangOptions().CPlusPlus) {
3851 TmpRes.suppressDiagnostics();
Kaelyn Uhrain0a16a8e2012-02-14 18:56:48 +00003852 for (llvm::SmallVector<TypoCorrection,
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003853 16>::iterator QRI = QualifiedResults.begin(),
3854 QRIEnd = QualifiedResults.end();
3855 QRI != QRIEnd; ++QRI) {
3856 for (NamespaceSpecifierSet::iterator NI = Namespaces.begin(),
3857 NIEnd = Namespaces.end();
3858 NI != NIEnd; ++NI) {
3859 DeclContext *Ctx = NI->DeclCtx;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003860
Kaelyn Uhrain1c75d402012-02-07 01:32:58 +00003861 // FIXME: Stop searching once the namespaces are too far away to create
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003862 // acceptable corrections for this identifier (since the namespaces
Kaelyn Uhrain1c75d402012-02-07 01:32:58 +00003863 // are sorted in ascending order by edit distance).
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003864
3865 TmpRes.clear();
Kaelyn Uhrain0a16a8e2012-02-14 18:56:48 +00003866 TmpRes.setLookupName(QRI->getCorrectionAsIdentifierInfo());
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003867 if (!LookupQualifiedName(TmpRes, Ctx)) continue;
3868
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003869 // Any corrections added below will be validated in subsequent
3870 // iterations of the main while() loop over the Consumer's contents.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003871 switch (TmpRes.getResultKind()) {
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003872 case LookupResult::Found: {
3873 TypoCorrection TC(*QRI);
3874 TC.setCorrectionDecl(TmpRes.getAsSingle<NamedDecl>());
3875 TC.setCorrectionSpecifier(NI->NameSpecifier);
3876 TC.setQualifierDistance(NI->EditDistance);
3877 Consumer.addCorrection(TC);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003878 break;
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003879 }
3880 case LookupResult::FoundOverloaded: {
3881 TypoCorrection TC(*QRI);
3882 TC.setCorrectionSpecifier(NI->NameSpecifier);
3883 TC.setQualifierDistance(NI->EditDistance);
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00003884 for (LookupResult::iterator TRD = TmpRes.begin(),
3885 TRDEnd = TmpRes.end();
3886 TRD != TRDEnd; ++TRD)
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003887 TC.addCorrectionDecl(*TRD);
3888 Consumer.addCorrection(TC);
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00003889 break;
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003890 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003891 case LookupResult::NotFound:
3892 case LookupResult::NotFoundInCurrentInstantiation:
3893 case LookupResult::Ambiguous:
Kaelyn Uhrain5a43b462011-09-07 20:25:59 +00003894 case LookupResult::FoundUnresolvedValue:
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003895 break;
3896 }
3897 }
3898 }
3899 }
3900
3901 QualifiedResults.clear();
3902 }
3903
3904 // No corrections remain...
3905 if (Consumer.empty()) return TypoCorrection();
3906
Douglas Gregor29cdc6b2011-06-28 16:44:39 +00003907 TypoResultsMap &BestResults = *Consumer.begin()->second;
Kaelyn Uhrain0a16a8e2012-02-14 18:56:48 +00003908 ED = TypoCorrection::NormalizeEditDistance(Consumer.begin()->first);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003909
3910 if (ED > 0 && Typo->getName().size() / ED < 3) {
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00003911 // If this was an unqualified lookup and we believe the callback
3912 // object wouldn't have filtered out possible corrections, note
3913 // that no correction was found.
3914 if (IsUnqualifiedLookup && !ValidatingCallback)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003915 (void)UnqualifiedTyposCorrected[Typo];
3916
3917 return TypoCorrection();
3918 }
3919
Douglas Gregor0afa7f62010-10-14 20:34:08 +00003920 // If only a single name remains, return that result.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003921 if (BestResults.size() == 1) {
3922 const llvm::StringMapEntry<TypoCorrection> &Correction = *(BestResults.begin());
3923 const TypoCorrection &Result = Correction.second;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003924
Douglas Gregor2a1d72d2010-10-26 17:18:00 +00003925 // Don't correct to a keyword that's the same as the typo; the keyword
3926 // wasn't actually in scope.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003927 if (ED == 0 && Result.isKeyword()) return TypoCorrection();
3928
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003929 // Record the correction for unqualified lookup.
3930 if (IsUnqualifiedLookup)
3931 UnqualifiedTyposCorrected[Typo] = Result;
3932
3933 return Result;
3934 }
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003935 else if (BestResults.size() > 1
3936 // Ugly hack equivalent to CTC == CTC_ObjCMessageReceiver;
3937 // WantObjCSuper is only true for CTC_ObjCMessageReceiver and for
3938 // some instances of CTC_Unknown, while WantRemainingKeywords is true
3939 // for CTC_Unknown but not for CTC_ObjCMessageReceiver.
Kaelyn Uhrain4e8942c2012-01-31 23:49:25 +00003940 && CCC.WantObjCSuper && !CCC.WantRemainingKeywords
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003941 && BestResults["super"].isKeyword()) {
3942 // Prefer 'super' when we're completing in a message-receiver
3943 // context.
3944
3945 // Don't correct to a keyword that's the same as the typo; the keyword
3946 // wasn't actually in scope.
3947 if (ED == 0) return TypoCorrection();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003948
Douglas Gregor87074f12010-10-20 01:32:02 +00003949 // Record the correction for unqualified lookup.
3950 if (IsUnqualifiedLookup)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003951 UnqualifiedTyposCorrected[Typo] = BestResults["super"];
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003952
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003953 return BestResults["super"];
Douglas Gregoraf9eb592010-10-15 13:35:25 +00003954 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003955
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00003956 // If this was an unqualified lookup and we believe the callback object did
3957 // not filter out possible corrections, note that no correction was found.
3958 if (IsUnqualifiedLookup && !ValidatingCallback)
Douglas Gregor87074f12010-10-20 01:32:02 +00003959 (void)UnqualifiedTyposCorrected[Typo];
3960
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003961 return TypoCorrection();
3962}
3963
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00003964void TypoCorrection::addCorrectionDecl(NamedDecl *CDecl) {
3965 if (!CDecl) return;
3966
3967 if (isKeyword())
3968 CorrectionDecls.clear();
3969
3970 CorrectionDecls.push_back(CDecl);
3971
3972 if (!CorrectionName)
3973 CorrectionName = CDecl->getDeclName();
3974}
3975
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003976std::string TypoCorrection::getAsString(const LangOptions &LO) const {
3977 if (CorrectionNameSpec) {
3978 std::string tmpBuffer;
3979 llvm::raw_string_ostream PrefixOStream(tmpBuffer);
3980 CorrectionNameSpec->print(PrefixOStream, PrintingPolicy(LO));
3981 return PrefixOStream.str() + CorrectionName.getAsString();
3982 }
3983
3984 return CorrectionName.getAsString();
Douglas Gregor2d435302009-12-30 17:04:44 +00003985}