blob: d1b6ef104d3a6a06f2869a819b63f439475ad830 [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"
John McCall8b0666c2010-08-20 18:27:03 +000017#include "clang/Sema/DeclSpec.h"
John McCallcc14d1f2010-08-24 08:50:51 +000018#include "clang/Sema/Scope.h"
John McCallaab3e412010-08-25 08:40:02 +000019#include "clang/Sema/ScopeInfo.h"
John McCall19c1bfd2010-08-25 05:32:35 +000020#include "clang/Sema/TemplateDeduction.h"
Axel Naumann016538a2011-02-24 16:47:47 +000021#include "clang/Sema/ExternalSemaSource.h"
Douglas Gregor960b5bc2009-01-15 00:26:24 +000022#include "clang/AST/ASTContext.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000023#include "clang/AST/CXXInheritance.h"
Douglas Gregor34074322009-01-14 22:20:51 +000024#include "clang/AST/Decl.h"
25#include "clang/AST/DeclCXX.h"
26#include "clang/AST/DeclObjC.h"
Douglas Gregorc9f9b862009-05-11 19:58:34 +000027#include "clang/AST/DeclTemplate.h"
Douglas Gregore254f902009-02-04 00:32:51 +000028#include "clang/AST/Expr.h"
Douglas Gregorbe759252009-07-08 10:57:20 +000029#include "clang/AST/ExprCXX.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000030#include "clang/Basic/Builtins.h"
Douglas Gregor34074322009-01-14 22:20:51 +000031#include "clang/Basic/LangOptions.h"
John McCalla1e130b2010-08-25 07:03:20 +000032#include "llvm/ADT/DenseSet.h"
Douglas Gregor34074322009-01-14 22:20:51 +000033#include "llvm/ADT/STLExtras.h"
Douglas Gregore254f902009-02-04 00:32:51 +000034#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor0afa7f62010-10-14 20:34:08 +000035#include "llvm/ADT/StringMap.h"
John McCall6538c932009-10-10 05:48:19 +000036#include "llvm/Support/ErrorHandling.h"
Douglas Gregor0afa7f62010-10-14 20:34:08 +000037#include <limits>
Douglas Gregor2d435302009-12-30 17:04:44 +000038#include <list>
Douglas Gregor1c846b02009-01-16 00:38:09 +000039#include <set>
Douglas Gregor889ceb72009-02-03 19:21:40 +000040#include <vector>
41#include <iterator>
42#include <utility>
43#include <algorithm>
Douglas Gregor34074322009-01-14 22:20:51 +000044
45using namespace clang;
John McCall19c1bfd2010-08-25 05:32:35 +000046using namespace sema;
Douglas Gregor34074322009-01-14 22:20:51 +000047
John McCallf6c8a4e2009-11-10 07:01:13 +000048namespace {
49 class UnqualUsingEntry {
50 const DeclContext *Nominated;
51 const DeclContext *CommonAncestor;
Douglas Gregor889ceb72009-02-03 19:21:40 +000052
John McCallf6c8a4e2009-11-10 07:01:13 +000053 public:
54 UnqualUsingEntry(const DeclContext *Nominated,
55 const DeclContext *CommonAncestor)
56 : Nominated(Nominated), CommonAncestor(CommonAncestor) {
57 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000058
John McCallf6c8a4e2009-11-10 07:01:13 +000059 const DeclContext *getCommonAncestor() const {
60 return CommonAncestor;
61 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000062
John McCallf6c8a4e2009-11-10 07:01:13 +000063 const DeclContext *getNominatedNamespace() const {
64 return Nominated;
65 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000066
John McCallf6c8a4e2009-11-10 07:01:13 +000067 // Sort by the pointer value of the common ancestor.
68 struct Comparator {
69 bool operator()(const UnqualUsingEntry &L, const UnqualUsingEntry &R) {
70 return L.getCommonAncestor() < R.getCommonAncestor();
71 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000072
John McCallf6c8a4e2009-11-10 07:01:13 +000073 bool operator()(const UnqualUsingEntry &E, const DeclContext *DC) {
74 return E.getCommonAncestor() < DC;
75 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000076
John McCallf6c8a4e2009-11-10 07:01:13 +000077 bool operator()(const DeclContext *DC, const UnqualUsingEntry &E) {
78 return DC < E.getCommonAncestor();
79 }
80 };
81 };
Douglas Gregor889ceb72009-02-03 19:21:40 +000082
John McCallf6c8a4e2009-11-10 07:01:13 +000083 /// A collection of using directives, as used by C++ unqualified
84 /// lookup.
85 class UnqualUsingDirectiveSet {
86 typedef llvm::SmallVector<UnqualUsingEntry, 8> ListTy;
Douglas Gregor889ceb72009-02-03 19:21:40 +000087
John McCallf6c8a4e2009-11-10 07:01:13 +000088 ListTy list;
89 llvm::SmallPtrSet<DeclContext*, 8> visited;
Douglas Gregor889ceb72009-02-03 19:21:40 +000090
John McCallf6c8a4e2009-11-10 07:01:13 +000091 public:
92 UnqualUsingDirectiveSet() {}
Douglas Gregor889ceb72009-02-03 19:21:40 +000093
John McCallf6c8a4e2009-11-10 07:01:13 +000094 void visitScopeChain(Scope *S, Scope *InnermostFileScope) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000095 // C++ [namespace.udir]p1:
John McCallf6c8a4e2009-11-10 07:01:13 +000096 // During unqualified name lookup, the names appear as if they
97 // were declared in the nearest enclosing namespace which contains
98 // both the using-directive and the nominated namespace.
99 DeclContext *InnermostFileDC
100 = static_cast<DeclContext*>(InnermostFileScope->getEntity());
101 assert(InnermostFileDC && InnermostFileDC->isFileContext());
Douglas Gregor889ceb72009-02-03 19:21:40 +0000102
John McCallf6c8a4e2009-11-10 07:01:13 +0000103 for (; S; S = S->getParent()) {
John McCallf6c8a4e2009-11-10 07:01:13 +0000104 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity())) {
105 DeclContext *EffectiveDC = (Ctx->isFileContext() ? Ctx : InnermostFileDC);
106 visit(Ctx, EffectiveDC);
107 } else {
108 Scope::udir_iterator I = S->using_directives_begin(),
109 End = S->using_directives_end();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000110
John McCallf6c8a4e2009-11-10 07:01:13 +0000111 for (; I != End; ++I)
John McCall48871652010-08-21 09:40:31 +0000112 visit(*I, InnermostFileDC);
John McCallf6c8a4e2009-11-10 07:01:13 +0000113 }
Douglas Gregor889ceb72009-02-03 19:21:40 +0000114 }
115 }
John McCallf6c8a4e2009-11-10 07:01:13 +0000116
117 // Visits a context and collect all of its using directives
118 // recursively. Treats all using directives as if they were
119 // declared in the context.
120 //
121 // A given context is only every visited once, so it is important
122 // that contexts be visited from the inside out in order to get
123 // the effective DCs right.
124 void visit(DeclContext *DC, DeclContext *EffectiveDC) {
125 if (!visited.insert(DC))
126 return;
127
128 addUsingDirectives(DC, EffectiveDC);
129 }
130
131 // Visits a using directive and collects all of its using
132 // directives recursively. Treats all using directives as if they
133 // were declared in the effective DC.
134 void visit(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
135 DeclContext *NS = UD->getNominatedNamespace();
136 if (!visited.insert(NS))
137 return;
138
139 addUsingDirective(UD, EffectiveDC);
140 addUsingDirectives(NS, EffectiveDC);
141 }
142
143 // Adds all the using directives in a context (and those nominated
144 // by its using directives, transitively) as if they appeared in
145 // the given effective context.
146 void addUsingDirectives(DeclContext *DC, DeclContext *EffectiveDC) {
147 llvm::SmallVector<DeclContext*,4> queue;
148 while (true) {
149 DeclContext::udir_iterator I, End;
150 for (llvm::tie(I, End) = DC->getUsingDirectives(); I != End; ++I) {
151 UsingDirectiveDecl *UD = *I;
152 DeclContext *NS = UD->getNominatedNamespace();
153 if (visited.insert(NS)) {
154 addUsingDirective(UD, EffectiveDC);
155 queue.push_back(NS);
156 }
157 }
158
159 if (queue.empty())
160 return;
161
162 DC = queue.back();
163 queue.pop_back();
164 }
165 }
166
167 // Add a using directive as if it had been declared in the given
168 // context. This helps implement C++ [namespace.udir]p3:
169 // The using-directive is transitive: if a scope contains a
170 // using-directive that nominates a second namespace that itself
171 // contains using-directives, the effect is as if the
172 // using-directives from the second namespace also appeared in
173 // the first.
174 void addUsingDirective(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
175 // Find the common ancestor between the effective context and
176 // the nominated namespace.
177 DeclContext *Common = UD->getNominatedNamespace();
178 while (!Common->Encloses(EffectiveDC))
179 Common = Common->getParent();
John McCall9757d032009-11-10 09:20:04 +0000180 Common = Common->getPrimaryContext();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000181
John McCallf6c8a4e2009-11-10 07:01:13 +0000182 list.push_back(UnqualUsingEntry(UD->getNominatedNamespace(), Common));
183 }
184
185 void done() {
186 std::sort(list.begin(), list.end(), UnqualUsingEntry::Comparator());
187 }
188
John McCallf6c8a4e2009-11-10 07:01:13 +0000189 typedef ListTy::const_iterator const_iterator;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000190
John McCallf6c8a4e2009-11-10 07:01:13 +0000191 const_iterator begin() const { return list.begin(); }
192 const_iterator end() const { return list.end(); }
193
194 std::pair<const_iterator,const_iterator>
195 getNamespacesFor(DeclContext *DC) const {
John McCall9757d032009-11-10 09:20:04 +0000196 return std::equal_range(begin(), end(), DC->getPrimaryContext(),
John McCallf6c8a4e2009-11-10 07:01:13 +0000197 UnqualUsingEntry::Comparator());
198 }
199 };
Douglas Gregor889ceb72009-02-03 19:21:40 +0000200}
201
Douglas Gregor889ceb72009-02-03 19:21:40 +0000202// Retrieve the set of identifier namespaces that correspond to a
203// specific kind of name lookup.
John McCallea305ed2009-12-18 10:40:03 +0000204static inline unsigned getIDNS(Sema::LookupNameKind NameKind,
205 bool CPlusPlus,
206 bool Redeclaration) {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000207 unsigned IDNS = 0;
208 switch (NameKind) {
209 case Sema::LookupOrdinaryName:
Douglas Gregoreddf4332009-02-24 20:03:32 +0000210 case Sema::LookupRedeclarationWithLinkage:
Douglas Gregor889ceb72009-02-03 19:21:40 +0000211 IDNS = Decl::IDNS_Ordinary;
John McCallea305ed2009-12-18 10:40:03 +0000212 if (CPlusPlus) {
John McCalle87beb22010-04-23 18:46:30 +0000213 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Member | Decl::IDNS_Namespace;
Chris Lattnerebb5c6c2011-02-18 01:27:55 +0000214 if (Redeclaration)
215 IDNS |= Decl::IDNS_TagFriend | Decl::IDNS_OrdinaryFriend;
John McCallea305ed2009-12-18 10:40:03 +0000216 }
Douglas Gregor889ceb72009-02-03 19:21:40 +0000217 break;
218
John McCallb9467b62010-04-24 01:30:58 +0000219 case Sema::LookupOperatorName:
220 // Operator lookup is its own crazy thing; it is not the same
221 // as (e.g.) looking up an operator name for redeclaration.
222 assert(!Redeclaration && "cannot do redeclaration operator lookup");
223 IDNS = Decl::IDNS_NonMemberOperator;
224 break;
225
Douglas Gregor889ceb72009-02-03 19:21:40 +0000226 case Sema::LookupTagName:
John McCalle87beb22010-04-23 18:46:30 +0000227 if (CPlusPlus) {
228 IDNS = Decl::IDNS_Type;
229
230 // When looking for a redeclaration of a tag name, we add:
231 // 1) TagFriend to find undeclared friend decls
232 // 2) Namespace because they can't "overload" with tag decls.
233 // 3) Tag because it includes class templates, which can't
234 // "overload" with tag decls.
235 if (Redeclaration)
236 IDNS |= Decl::IDNS_Tag | Decl::IDNS_TagFriend | Decl::IDNS_Namespace;
237 } else {
238 IDNS = Decl::IDNS_Tag;
239 }
Douglas Gregor889ceb72009-02-03 19:21:40 +0000240 break;
Chris Lattnerebb5c6c2011-02-18 01:27:55 +0000241 case Sema::LookupLabel:
242 IDNS = Decl::IDNS_Label;
243 break;
244
Douglas Gregor889ceb72009-02-03 19:21:40 +0000245 case Sema::LookupMemberName:
246 IDNS = Decl::IDNS_Member;
247 if (CPlusPlus)
Mike Stump11289f42009-09-09 15:08:12 +0000248 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Ordinary;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000249 break;
250
251 case Sema::LookupNestedNameSpecifierName:
John McCalle87beb22010-04-23 18:46:30 +0000252 IDNS = Decl::IDNS_Type | Decl::IDNS_Namespace;
253 break;
254
Douglas Gregor889ceb72009-02-03 19:21:40 +0000255 case Sema::LookupNamespaceName:
John McCalle87beb22010-04-23 18:46:30 +0000256 IDNS = Decl::IDNS_Namespace;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000257 break;
Douglas Gregorde9f17e2009-04-23 23:18:26 +0000258
John McCall84d87672009-12-10 09:41:52 +0000259 case Sema::LookupUsingDeclName:
260 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag
261 | Decl::IDNS_Member | Decl::IDNS_Using;
262 break;
263
Douglas Gregor79947a22009-04-24 00:11:27 +0000264 case Sema::LookupObjCProtocolName:
265 IDNS = Decl::IDNS_ObjCProtocol;
266 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000267
Douglas Gregor39982192010-08-15 06:18:01 +0000268 case Sema::LookupAnyName:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000269 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Member
Douglas Gregor39982192010-08-15 06:18:01 +0000270 | Decl::IDNS_Using | Decl::IDNS_Namespace | Decl::IDNS_ObjCProtocol
271 | Decl::IDNS_Type;
272 break;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000273 }
274 return IDNS;
275}
276
John McCallea305ed2009-12-18 10:40:03 +0000277void LookupResult::configure() {
Chris Lattnerebb5c6c2011-02-18 01:27:55 +0000278 IDNS = getIDNS(LookupKind, SemaRef.getLangOptions().CPlusPlus,
John McCallea305ed2009-12-18 10:40:03 +0000279 isForRedeclaration());
Douglas Gregorbcf0a472010-03-24 05:07:21 +0000280
281 // If we're looking for one of the allocation or deallocation
282 // operators, make sure that the implicitly-declared new and delete
283 // operators can be found.
284 if (!isForRedeclaration()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000285 switch (NameInfo.getName().getCXXOverloadedOperator()) {
Douglas Gregorbcf0a472010-03-24 05:07:21 +0000286 case OO_New:
287 case OO_Delete:
288 case OO_Array_New:
289 case OO_Array_Delete:
290 SemaRef.DeclareGlobalNewDelete();
291 break;
292
293 default:
294 break;
295 }
296 }
John McCallea305ed2009-12-18 10:40:03 +0000297}
298
John McCall19c1bfd2010-08-25 05:32:35 +0000299void LookupResult::sanity() const {
300 assert(ResultKind != NotFound || Decls.size() == 0);
301 assert(ResultKind != Found || Decls.size() == 1);
302 assert(ResultKind != FoundOverloaded || Decls.size() > 1 ||
303 (Decls.size() == 1 &&
304 isa<FunctionTemplateDecl>((*begin())->getUnderlyingDecl())));
305 assert(ResultKind != FoundUnresolvedValue || sanityCheckUnresolved());
306 assert(ResultKind != Ambiguous || Decls.size() > 1 ||
Douglas Gregorc0d24902010-10-22 22:08:47 +0000307 (Decls.size() == 1 && (Ambiguity == AmbiguousBaseSubobjects ||
308 Ambiguity == AmbiguousBaseSubobjectTypes)));
John McCall19c1bfd2010-08-25 05:32:35 +0000309 assert((Paths != NULL) == (ResultKind == Ambiguous &&
310 (Ambiguity == AmbiguousBaseSubobjectTypes ||
311 Ambiguity == AmbiguousBaseSubobjects)));
312}
John McCall19c1bfd2010-08-25 05:32:35 +0000313
John McCall9f3059a2009-10-09 21:13:30 +0000314// Necessary because CXXBasePaths is not complete in Sema.h
John McCall5cebab12009-11-18 07:57:50 +0000315void LookupResult::deletePaths(CXXBasePaths *Paths) {
John McCall9f3059a2009-10-09 21:13:30 +0000316 delete Paths;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000317}
318
John McCall283b9012009-11-22 00:44:51 +0000319/// Resolves the result kind of this lookup.
John McCall5cebab12009-11-18 07:57:50 +0000320void LookupResult::resolveKind() {
John McCall9f3059a2009-10-09 21:13:30 +0000321 unsigned N = Decls.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000322
John McCall9f3059a2009-10-09 21:13:30 +0000323 // Fast case: no possible ambiguity.
John McCall1f82f242009-11-18 22:49:29 +0000324 if (N == 0) {
John McCall7fe6e9c2010-01-15 21:27:01 +0000325 assert(ResultKind == NotFound || ResultKind == NotFoundInCurrentInstantiation);
John McCall1f82f242009-11-18 22:49:29 +0000326 return;
327 }
328
John McCall283b9012009-11-22 00:44:51 +0000329 // If there's a single decl, we need to examine it to decide what
330 // kind of lookup this is.
John McCalle61f2ba2009-11-18 02:36:19 +0000331 if (N == 1) {
Douglas Gregor516d6722010-04-25 21:15:30 +0000332 NamedDecl *D = (*Decls.begin())->getUnderlyingDecl();
333 if (isa<FunctionTemplateDecl>(D))
John McCall283b9012009-11-22 00:44:51 +0000334 ResultKind = FoundOverloaded;
Douglas Gregor516d6722010-04-25 21:15:30 +0000335 else if (isa<UnresolvedUsingValueDecl>(D))
John McCalle61f2ba2009-11-18 02:36:19 +0000336 ResultKind = FoundUnresolvedValue;
337 return;
338 }
John McCall9f3059a2009-10-09 21:13:30 +0000339
John McCall6538c932009-10-10 05:48:19 +0000340 // Don't do any extra resolution if we've already resolved as ambiguous.
John McCall27b18f82009-11-17 02:14:36 +0000341 if (ResultKind == Ambiguous) return;
John McCall6538c932009-10-10 05:48:19 +0000342
John McCall9f3059a2009-10-09 21:13:30 +0000343 llvm::SmallPtrSet<NamedDecl*, 16> Unique;
Douglas Gregor13e65872010-08-11 14:45:53 +0000344 llvm::SmallPtrSet<QualType, 16> UniqueTypes;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000345
John McCall9f3059a2009-10-09 21:13:30 +0000346 bool Ambiguous = false;
347 bool HasTag = false, HasFunction = false, HasNonFunction = false;
John McCall283b9012009-11-22 00:44:51 +0000348 bool HasFunctionTemplate = false, HasUnresolved = false;
John McCall9f3059a2009-10-09 21:13:30 +0000349
350 unsigned UniqueTagIndex = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000351
John McCall9f3059a2009-10-09 21:13:30 +0000352 unsigned I = 0;
353 while (I < N) {
John McCallf0f1cf02009-11-17 07:50:12 +0000354 NamedDecl *D = Decls[I]->getUnderlyingDecl();
355 D = cast<NamedDecl>(D->getCanonicalDecl());
John McCall9f3059a2009-10-09 21:13:30 +0000356
Douglas Gregor13e65872010-08-11 14:45:53 +0000357 // Redeclarations of types via typedef can occur both within a scope
358 // and, through using declarations and directives, across scopes. There is
359 // no ambiguity if they all refer to the same type, so unique based on the
360 // canonical type.
361 if (TypeDecl *TD = dyn_cast<TypeDecl>(D)) {
362 if (!TD->getDeclContext()->isRecord()) {
363 QualType T = SemaRef.Context.getTypeDeclType(TD);
364 if (!UniqueTypes.insert(SemaRef.Context.getCanonicalType(T))) {
365 // The type is not unique; pull something off the back and continue
366 // at this index.
367 Decls[I] = Decls[--N];
368 continue;
369 }
370 }
371 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000372
John McCallf0f1cf02009-11-17 07:50:12 +0000373 if (!Unique.insert(D)) {
John McCall9f3059a2009-10-09 21:13:30 +0000374 // If it's not unique, pull something off the back (and
375 // continue at this index).
376 Decls[I] = Decls[--N];
Douglas Gregor13e65872010-08-11 14:45:53 +0000377 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000378 }
379
Douglas Gregor13e65872010-08-11 14:45:53 +0000380 // Otherwise, do some decl type analysis and then continue.
John McCalle61f2ba2009-11-18 02:36:19 +0000381
Douglas Gregor13e65872010-08-11 14:45:53 +0000382 if (isa<UnresolvedUsingValueDecl>(D)) {
383 HasUnresolved = true;
384 } else if (isa<TagDecl>(D)) {
385 if (HasTag)
386 Ambiguous = true;
387 UniqueTagIndex = I;
388 HasTag = true;
389 } else if (isa<FunctionTemplateDecl>(D)) {
390 HasFunction = true;
391 HasFunctionTemplate = true;
392 } else if (isa<FunctionDecl>(D)) {
393 HasFunction = true;
394 } else {
395 if (HasNonFunction)
396 Ambiguous = true;
397 HasNonFunction = true;
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000398 }
Douglas Gregor13e65872010-08-11 14:45:53 +0000399 I++;
Mike Stump11289f42009-09-09 15:08:12 +0000400 }
Douglas Gregor38feed82009-04-24 02:57:34 +0000401
John McCall9f3059a2009-10-09 21:13:30 +0000402 // C++ [basic.scope.hiding]p2:
403 // A class name or enumeration name can be hidden by the name of
404 // an object, function, or enumerator declared in the same
405 // scope. If a class or enumeration name and an object, function,
406 // or enumerator are declared in the same scope (in any order)
407 // with the same name, the class or enumeration name is hidden
408 // wherever the object, function, or enumerator name is visible.
409 // But it's still an error if there are distinct tag types found,
410 // even if they're not visible. (ref?)
John McCall80053822009-12-03 00:58:24 +0000411 if (HideTags && HasTag && !Ambiguous &&
Douglas Gregore63d0872010-10-23 16:06:17 +0000412 (HasFunction || HasNonFunction || HasUnresolved)) {
413 if (Decls[UniqueTagIndex]->getDeclContext()->getRedeclContext()->Equals(
414 Decls[UniqueTagIndex? 0 : N-1]->getDeclContext()->getRedeclContext()))
415 Decls[UniqueTagIndex] = Decls[--N];
416 else
417 Ambiguous = true;
418 }
Anders Carlsson8d0f6b72009-06-26 03:37:05 +0000419
John McCall9f3059a2009-10-09 21:13:30 +0000420 Decls.set_size(N);
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000421
John McCall80053822009-12-03 00:58:24 +0000422 if (HasNonFunction && (HasFunction || HasUnresolved))
John McCall9f3059a2009-10-09 21:13:30 +0000423 Ambiguous = true;
Douglas Gregorf23311d2009-01-17 01:13:24 +0000424
John McCall9f3059a2009-10-09 21:13:30 +0000425 if (Ambiguous)
John McCall6538c932009-10-10 05:48:19 +0000426 setAmbiguous(LookupResult::AmbiguousReference);
John McCalle61f2ba2009-11-18 02:36:19 +0000427 else if (HasUnresolved)
428 ResultKind = LookupResult::FoundUnresolvedValue;
John McCall283b9012009-11-22 00:44:51 +0000429 else if (N > 1 || HasFunctionTemplate)
John McCall27b18f82009-11-17 02:14:36 +0000430 ResultKind = LookupResult::FoundOverloaded;
John McCall9f3059a2009-10-09 21:13:30 +0000431 else
John McCall27b18f82009-11-17 02:14:36 +0000432 ResultKind = LookupResult::Found;
Douglas Gregor34074322009-01-14 22:20:51 +0000433}
434
John McCall5cebab12009-11-18 07:57:50 +0000435void LookupResult::addDeclsFromBasePaths(const CXXBasePaths &P) {
John McCall5b0829a2010-02-10 09:31:12 +0000436 CXXBasePaths::const_paths_iterator I, E;
John McCall9f3059a2009-10-09 21:13:30 +0000437 DeclContext::lookup_iterator DI, DE;
438 for (I = P.begin(), E = P.end(); I != E; ++I)
439 for (llvm::tie(DI,DE) = I->Decls; DI != DE; ++DI)
440 addDecl(*DI);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +0000441}
442
John McCall5cebab12009-11-18 07:57:50 +0000443void LookupResult::setAmbiguousBaseSubobjects(CXXBasePaths &P) {
John McCall9f3059a2009-10-09 21:13:30 +0000444 Paths = new CXXBasePaths;
445 Paths->swap(P);
446 addDeclsFromBasePaths(*Paths);
447 resolveKind();
John McCall6538c932009-10-10 05:48:19 +0000448 setAmbiguous(AmbiguousBaseSubobjects);
Douglas Gregor0e8fc3c2009-02-02 21:35:47 +0000449}
450
John McCall5cebab12009-11-18 07:57:50 +0000451void LookupResult::setAmbiguousBaseSubobjectTypes(CXXBasePaths &P) {
John McCall9f3059a2009-10-09 21:13:30 +0000452 Paths = new CXXBasePaths;
453 Paths->swap(P);
454 addDeclsFromBasePaths(*Paths);
455 resolveKind();
John McCall6538c932009-10-10 05:48:19 +0000456 setAmbiguous(AmbiguousBaseSubobjectTypes);
John McCall9f3059a2009-10-09 21:13:30 +0000457}
458
John McCall5cebab12009-11-18 07:57:50 +0000459void LookupResult::print(llvm::raw_ostream &Out) {
John McCall9f3059a2009-10-09 21:13:30 +0000460 Out << Decls.size() << " result(s)";
461 if (isAmbiguous()) Out << ", ambiguous";
462 if (Paths) Out << ", base paths present";
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000463
John McCall9f3059a2009-10-09 21:13:30 +0000464 for (iterator I = begin(), E = end(); I != E; ++I) {
465 Out << "\n";
466 (*I)->print(Out, 2);
467 }
468}
469
Douglas Gregord3a59182010-02-12 05:48:04 +0000470/// \brief Lookup a builtin function, when name lookup would otherwise
471/// fail.
472static bool LookupBuiltin(Sema &S, LookupResult &R) {
473 Sema::LookupNameKind NameKind = R.getLookupKind();
474
475 // If we didn't find a use of this identifier, and if the identifier
476 // corresponds to a compiler builtin, create the decl object for the builtin
477 // now, injecting it into translation unit scope, and return it.
478 if (NameKind == Sema::LookupOrdinaryName ||
479 NameKind == Sema::LookupRedeclarationWithLinkage) {
480 IdentifierInfo *II = R.getLookupName().getAsIdentifierInfo();
481 if (II) {
482 // If this is a builtin on this (or all) targets, create the decl.
483 if (unsigned BuiltinID = II->getBuiltinID()) {
484 // In C++, we don't have any predefined library functions like
485 // 'malloc'. Instead, we'll just error.
486 if (S.getLangOptions().CPlusPlus &&
487 S.Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
488 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000489
490 if (NamedDecl *D = S.LazilyCreateBuiltin((IdentifierInfo *)II,
491 BuiltinID, S.TUScope,
Douglas Gregorbfe022c2011-01-03 09:37:44 +0000492 R.isForRedeclaration(),
493 R.getNameLoc())) {
Douglas Gregord3a59182010-02-12 05:48:04 +0000494 R.addDecl(D);
Douglas Gregorbfe022c2011-01-03 09:37:44 +0000495 return true;
496 }
497
498 if (R.isForRedeclaration()) {
499 // If we're redeclaring this function anyway, forget that
500 // this was a builtin at all.
501 S.Context.BuiltinInfo.ForgetBuiltin(BuiltinID, S.Context.Idents);
502 }
503
504 return false;
Douglas Gregord3a59182010-02-12 05:48:04 +0000505 }
506 }
507 }
508
509 return false;
510}
511
Douglas Gregor7454c562010-07-02 20:37:36 +0000512/// \brief Determine whether we can declare a special member function within
513/// the class at this point.
514static bool CanDeclareSpecialMemberFunction(ASTContext &Context,
515 const CXXRecordDecl *Class) {
John McCall2ded5d22010-08-11 23:52:36 +0000516 // Don't do it if the class is invalid.
517 if (Class->isInvalidDecl())
518 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000519
Douglas Gregor7454c562010-07-02 20:37:36 +0000520 // We need to have a definition for the class.
521 if (!Class->getDefinition() || Class->isDependentContext())
522 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000523
Douglas Gregor7454c562010-07-02 20:37:36 +0000524 // We can't be in the middle of defining the class.
525 if (const RecordType *RecordTy
526 = Context.getTypeDeclType(Class)->getAs<RecordType>())
527 return !RecordTy->isBeingDefined();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000528
Douglas Gregor7454c562010-07-02 20:37:36 +0000529 return false;
530}
531
532void Sema::ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class) {
Douglas Gregora6d69502010-07-02 23:41:54 +0000533 if (!CanDeclareSpecialMemberFunction(Context, Class))
534 return;
Douglas Gregor9672f922010-07-03 00:47:00 +0000535
536 // If the default constructor has not yet been declared, do so now.
537 if (!Class->hasDeclaredDefaultConstructor())
538 DeclareImplicitDefaultConstructor(Class);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000539
Douglas Gregora6d69502010-07-02 23:41:54 +0000540 // If the copy constructor has not yet been declared, do so now.
541 if (!Class->hasDeclaredCopyConstructor())
542 DeclareImplicitCopyConstructor(Class);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000543
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000544 // If the copy assignment operator has not yet been declared, do so now.
Douglas Gregora6d69502010-07-02 23:41:54 +0000545 if (!Class->hasDeclaredCopyAssignment())
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000546 DeclareImplicitCopyAssignment(Class);
547
Douglas Gregor7454c562010-07-02 20:37:36 +0000548 // If the destructor has not yet been declared, do so now.
Douglas Gregora6d69502010-07-02 23:41:54 +0000549 if (!Class->hasDeclaredDestructor())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000550 DeclareImplicitDestructor(Class);
Douglas Gregor7454c562010-07-02 20:37:36 +0000551}
552
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000553/// \brief Determine whether this is the name of an implicitly-declared
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000554/// special member function.
555static bool isImplicitlyDeclaredMemberFunctionName(DeclarationName Name) {
556 switch (Name.getNameKind()) {
Douglas Gregora6d69502010-07-02 23:41:54 +0000557 case DeclarationName::CXXConstructorName:
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000558 case DeclarationName::CXXDestructorName:
559 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000560
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000561 case DeclarationName::CXXOperatorName:
562 return Name.getCXXOverloadedOperator() == OO_Equal;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000563
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000564 default:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000565 break;
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000566 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000567
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000568 return false;
569}
570
571/// \brief If there are any implicit member functions with the given name
572/// that need to be declared in the given declaration context, do so.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000573static void DeclareImplicitMemberFunctionsWithName(Sema &S,
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000574 DeclarationName Name,
575 const DeclContext *DC) {
576 if (!DC)
577 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000578
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000579 switch (Name.getNameKind()) {
Douglas Gregora6d69502010-07-02 23:41:54 +0000580 case DeclarationName::CXXConstructorName:
581 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
Douglas Gregor9672f922010-07-03 00:47:00 +0000582 if (Record->getDefinition() &&
583 CanDeclareSpecialMemberFunction(S.Context, Record)) {
584 if (!Record->hasDeclaredDefaultConstructor())
585 S.DeclareImplicitDefaultConstructor(
586 const_cast<CXXRecordDecl *>(Record));
587 if (!Record->hasDeclaredCopyConstructor())
588 S.DeclareImplicitCopyConstructor(const_cast<CXXRecordDecl *>(Record));
589 }
Douglas Gregora6d69502010-07-02 23:41:54 +0000590 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000591
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000592 case DeclarationName::CXXDestructorName:
593 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
594 if (Record->getDefinition() && !Record->hasDeclaredDestructor() &&
595 CanDeclareSpecialMemberFunction(S.Context, Record))
596 S.DeclareImplicitDestructor(const_cast<CXXRecordDecl *>(Record));
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000597 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000598
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000599 case DeclarationName::CXXOperatorName:
600 if (Name.getCXXOverloadedOperator() != OO_Equal)
601 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000602
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000603 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
604 if (Record->getDefinition() && !Record->hasDeclaredCopyAssignment() &&
605 CanDeclareSpecialMemberFunction(S.Context, Record))
606 S.DeclareImplicitCopyAssignment(const_cast<CXXRecordDecl *>(Record));
607 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000608
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000609 default:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000610 break;
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000611 }
612}
Douglas Gregor7454c562010-07-02 20:37:36 +0000613
John McCall9f3059a2009-10-09 21:13:30 +0000614// Adds all qualifying matches for a name within a decl context to the
615// given lookup result. Returns true if any matches were found.
Douglas Gregord3a59182010-02-12 05:48:04 +0000616static bool LookupDirect(Sema &S, LookupResult &R, const DeclContext *DC) {
John McCall9f3059a2009-10-09 21:13:30 +0000617 bool Found = false;
618
Douglas Gregor7454c562010-07-02 20:37:36 +0000619 // Lazily declare C++ special member functions.
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000620 if (S.getLangOptions().CPlusPlus)
621 DeclareImplicitMemberFunctionsWithName(S, R.getLookupName(), DC);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000622
Douglas Gregor7454c562010-07-02 20:37:36 +0000623 // Perform lookup into this declaration context.
John McCallf6c8a4e2009-11-10 07:01:13 +0000624 DeclContext::lookup_const_iterator I, E;
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000625 for (llvm::tie(I, E) = DC->lookup(R.getLookupName()); I != E; ++I) {
John McCall401982f2010-01-20 21:53:11 +0000626 NamedDecl *D = *I;
627 if (R.isAcceptableDecl(D)) {
628 R.addDecl(D);
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000629 Found = true;
630 }
631 }
John McCall9f3059a2009-10-09 21:13:30 +0000632
Douglas Gregord3a59182010-02-12 05:48:04 +0000633 if (!Found && DC->isTranslationUnit() && LookupBuiltin(S, R))
634 return true;
635
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000636 if (R.getLookupName().getNameKind()
Chandler Carruth3a693b72010-01-31 11:44:02 +0000637 != DeclarationName::CXXConversionFunctionName ||
638 R.getLookupName().getCXXNameType()->isDependentType() ||
639 !isa<CXXRecordDecl>(DC))
640 return Found;
641
642 // C++ [temp.mem]p6:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000643 // A specialization of a conversion function template is not found by
Chandler Carruth3a693b72010-01-31 11:44:02 +0000644 // name lookup. Instead, any conversion function templates visible in the
645 // context of the use are considered. [...]
646 const CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
647 if (!Record->isDefinition())
648 return Found;
649
650 const UnresolvedSetImpl *Unresolved = Record->getConversionFunctions();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000651 for (UnresolvedSetImpl::iterator U = Unresolved->begin(),
Chandler Carruth3a693b72010-01-31 11:44:02 +0000652 UEnd = Unresolved->end(); U != UEnd; ++U) {
653 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(*U);
654 if (!ConvTemplate)
655 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000656
Chandler Carruth3a693b72010-01-31 11:44:02 +0000657 // When we're performing lookup for the purposes of redeclaration, just
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000658 // add the conversion function template. When we deduce template
659 // arguments for specializations, we'll end up unifying the return
Chandler Carruth3a693b72010-01-31 11:44:02 +0000660 // type of the new declaration with the type of the function template.
661 if (R.isForRedeclaration()) {
662 R.addDecl(ConvTemplate);
663 Found = true;
664 continue;
665 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000666
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000667 // C++ [temp.mem]p6:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000668 // [...] For each such operator, if argument deduction succeeds
669 // (14.9.2.3), the resulting specialization is used as if found by
Chandler Carruth3a693b72010-01-31 11:44:02 +0000670 // name lookup.
671 //
672 // When referencing a conversion function for any purpose other than
673 // a redeclaration (such that we'll be building an expression with the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000674 // result), perform template argument deduction and place the
Chandler Carruth3a693b72010-01-31 11:44:02 +0000675 // specialization into the result set. We do this to avoid forcing all
676 // callers to perform special deduction for conversion functions.
John McCall19c1bfd2010-08-25 05:32:35 +0000677 TemplateDeductionInfo Info(R.getSema().Context, R.getNameLoc());
Chandler Carruth3a693b72010-01-31 11:44:02 +0000678 FunctionDecl *Specialization = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000679
680 const FunctionProtoType *ConvProto
Chandler Carruth3a693b72010-01-31 11:44:02 +0000681 = ConvTemplate->getTemplatedDecl()->getType()->getAs<FunctionProtoType>();
682 assert(ConvProto && "Nonsensical conversion function template type");
Douglas Gregor3c96a462010-01-12 01:17:50 +0000683
Chandler Carruth3a693b72010-01-31 11:44:02 +0000684 // Compute the type of the function that we would expect the conversion
685 // function to have, if it were to match the name given.
686 // FIXME: Calling convention!
John McCalldb40c7f2010-12-14 08:05:40 +0000687 FunctionProtoType::ExtProtoInfo EPI = ConvProto->getExtProtoInfo();
688 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(CC_Default);
689 EPI.HasExceptionSpec = false;
690 EPI.HasAnyExceptionSpec = false;
691 EPI.NumExceptions = 0;
Chandler Carruth3a693b72010-01-31 11:44:02 +0000692 QualType ExpectedType
693 = R.getSema().Context.getFunctionType(R.getLookupName().getCXXNameType(),
John McCalldb40c7f2010-12-14 08:05:40 +0000694 0, 0, EPI);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000695
Chandler Carruth3a693b72010-01-31 11:44:02 +0000696 // Perform template argument deduction against the type that we would
697 // expect the function to have.
698 if (R.getSema().DeduceTemplateArguments(ConvTemplate, 0, ExpectedType,
699 Specialization, Info)
700 == Sema::TDK_Success) {
701 R.addDecl(Specialization);
702 Found = true;
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000703 }
704 }
Chandler Carruth3a693b72010-01-31 11:44:02 +0000705
John McCall9f3059a2009-10-09 21:13:30 +0000706 return Found;
707}
708
John McCallf6c8a4e2009-11-10 07:01:13 +0000709// Performs C++ unqualified lookup into the given file context.
John McCall9f3059a2009-10-09 21:13:30 +0000710static bool
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000711CppNamespaceLookup(Sema &S, LookupResult &R, ASTContext &Context,
Douglas Gregord3a59182010-02-12 05:48:04 +0000712 DeclContext *NS, UnqualUsingDirectiveSet &UDirs) {
Douglas Gregor700792c2009-02-05 19:25:20 +0000713
714 assert(NS && NS->isFileContext() && "CppNamespaceLookup() requires namespace!");
715
John McCallf6c8a4e2009-11-10 07:01:13 +0000716 // Perform direct name lookup into the LookupCtx.
Douglas Gregord3a59182010-02-12 05:48:04 +0000717 bool Found = LookupDirect(S, R, NS);
Douglas Gregor700792c2009-02-05 19:25:20 +0000718
John McCallf6c8a4e2009-11-10 07:01:13 +0000719 // Perform direct name lookup into the namespaces nominated by the
720 // using directives whose common ancestor is this namespace.
721 UnqualUsingDirectiveSet::const_iterator UI, UEnd;
722 llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(NS);
Mike Stump11289f42009-09-09 15:08:12 +0000723
John McCallf6c8a4e2009-11-10 07:01:13 +0000724 for (; UI != UEnd; ++UI)
Douglas Gregord3a59182010-02-12 05:48:04 +0000725 if (LookupDirect(S, R, UI->getNominatedNamespace()))
John McCallf6c8a4e2009-11-10 07:01:13 +0000726 Found = true;
John McCall9f3059a2009-10-09 21:13:30 +0000727
728 R.resolveKind();
729
730 return Found;
Douglas Gregor700792c2009-02-05 19:25:20 +0000731}
732
733static bool isNamespaceOrTranslationUnitScope(Scope *S) {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000734 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Douglas Gregor700792c2009-02-05 19:25:20 +0000735 return Ctx->isFileContext();
736 return false;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000737}
Douglas Gregored8f2882009-01-30 01:04:22 +0000738
Douglas Gregor66230062010-03-15 14:33:29 +0000739// Find the next outer declaration context from this scope. This
740// routine actually returns the semantic outer context, which may
741// differ from the lexical context (encoded directly in the Scope
742// stack) when we are parsing a member of a class template. In this
743// case, the second element of the pair will be true, to indicate that
744// name lookup should continue searching in this semantic context when
745// it leaves the current template parameter scope.
746static std::pair<DeclContext *, bool> findOuterContext(Scope *S) {
747 DeclContext *DC = static_cast<DeclContext *>(S->getEntity());
748 DeclContext *Lexical = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000749 for (Scope *OuterS = S->getParent(); OuterS;
Douglas Gregor66230062010-03-15 14:33:29 +0000750 OuterS = OuterS->getParent()) {
751 if (OuterS->getEntity()) {
Douglas Gregorea166062010-03-15 15:26:48 +0000752 Lexical = static_cast<DeclContext *>(OuterS->getEntity());
Douglas Gregor66230062010-03-15 14:33:29 +0000753 break;
754 }
755 }
756
757 // C++ [temp.local]p8:
758 // In the definition of a member of a class template that appears
759 // outside of the namespace containing the class template
760 // definition, the name of a template-parameter hides the name of
761 // a member of this namespace.
762 //
763 // Example:
764 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000765 // namespace N {
766 // class C { };
Douglas Gregor66230062010-03-15 14:33:29 +0000767 //
768 // template<class T> class B {
769 // void f(T);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000770 // };
Douglas Gregor66230062010-03-15 14:33:29 +0000771 // }
772 //
773 // template<class C> void N::B<C>::f(C) {
774 // C b; // C is the template parameter, not N::C
775 // }
776 //
777 // In this example, the lexical context we return is the
778 // TranslationUnit, while the semantic context is the namespace N.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000779 if (!Lexical || !DC || !S->getParent() ||
Douglas Gregor66230062010-03-15 14:33:29 +0000780 !S->getParent()->isTemplateParamScope())
781 return std::make_pair(Lexical, false);
782
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000783 // Find the outermost template parameter scope.
Douglas Gregor66230062010-03-15 14:33:29 +0000784 // For the example, this is the scope for the template parameters of
785 // template<class C>.
786 Scope *OutermostTemplateScope = S->getParent();
787 while (OutermostTemplateScope->getParent() &&
788 OutermostTemplateScope->getParent()->isTemplateParamScope())
789 OutermostTemplateScope = OutermostTemplateScope->getParent();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000790
Douglas Gregor66230062010-03-15 14:33:29 +0000791 // Find the namespace context in which the original scope occurs. In
792 // the example, this is namespace N.
793 DeclContext *Semantic = DC;
794 while (!Semantic->isFileContext())
795 Semantic = Semantic->getParent();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000796
Douglas Gregor66230062010-03-15 14:33:29 +0000797 // Find the declaration context just outside of the template
798 // parameter scope. This is the context in which the template is
799 // being lexically declaration (a namespace context). In the
800 // example, this is the global scope.
801 if (Lexical->isFileContext() && !Lexical->Equals(Semantic) &&
802 Lexical->Encloses(Semantic))
803 return std::make_pair(Semantic, true);
804
805 return std::make_pair(Lexical, false);
Douglas Gregor7f737c02009-09-10 16:57:35 +0000806}
807
John McCall27b18f82009-11-17 02:14:36 +0000808bool Sema::CppLookupName(LookupResult &R, Scope *S) {
John McCallea305ed2009-12-18 10:40:03 +0000809 assert(getLangOptions().CPlusPlus && "Can perform only C++ lookup");
John McCall27b18f82009-11-17 02:14:36 +0000810
811 DeclarationName Name = R.getLookupName();
812
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000813 // If this is the name of an implicitly-declared special member function,
814 // go through the scope stack to implicitly declare
815 if (isImplicitlyDeclaredMemberFunctionName(Name)) {
816 for (Scope *PreS = S; PreS; PreS = PreS->getParent())
817 if (DeclContext *DC = static_cast<DeclContext *>(PreS->getEntity()))
818 DeclareImplicitMemberFunctionsWithName(*this, Name, DC);
819 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000820
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000821 // Implicitly declare member functions with the name we're looking for, if in
822 // fact we are in a scope where it matters.
823
Douglas Gregor889ceb72009-02-03 19:21:40 +0000824 Scope *Initial = S;
Mike Stump11289f42009-09-09 15:08:12 +0000825 IdentifierResolver::iterator
Douglas Gregor889ceb72009-02-03 19:21:40 +0000826 I = IdResolver.begin(Name),
827 IEnd = IdResolver.end();
Douglas Gregored8f2882009-01-30 01:04:22 +0000828
Douglas Gregor889ceb72009-02-03 19:21:40 +0000829 // First we lookup local scope.
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000830 // We don't consider using-directives, as per 7.3.4.p1 [namespace.udir]
Douglas Gregor889ceb72009-02-03 19:21:40 +0000831 // ...During unqualified name lookup (3.4.1), the names appear as if
832 // they were declared in the nearest enclosing namespace which contains
833 // both the using-directive and the nominated namespace.
Eli Friedman44b83ee2009-08-05 19:21:58 +0000834 // [Note: in this context, "contains" means "contains directly or
Mike Stump11289f42009-09-09 15:08:12 +0000835 // indirectly".
Douglas Gregor889ceb72009-02-03 19:21:40 +0000836 //
837 // For example:
838 // namespace A { int i; }
839 // void foo() {
840 // int i;
841 // {
842 // using namespace A;
843 // ++i; // finds local 'i', A::i appears at global scope
844 // }
845 // }
Douglas Gregor2ada0482009-02-04 17:27:36 +0000846 //
Douglas Gregor66230062010-03-15 14:33:29 +0000847 DeclContext *OutsideOfTemplateParamDC = 0;
Douglas Gregor700792c2009-02-05 19:25:20 +0000848 for (; S && !isNamespaceOrTranslationUnitScope(S); S = S->getParent()) {
Douglas Gregor3e51e172010-05-20 20:58:56 +0000849 DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity());
850
Douglas Gregor889ceb72009-02-03 19:21:40 +0000851 // Check whether the IdResolver has anything in this scope.
John McCall9f3059a2009-10-09 21:13:30 +0000852 bool Found = false;
John McCall48871652010-08-21 09:40:31 +0000853 for (; I != IEnd && S->isDeclScope(*I); ++I) {
John McCallea305ed2009-12-18 10:40:03 +0000854 if (R.isAcceptableDecl(*I)) {
John McCall9f3059a2009-10-09 21:13:30 +0000855 Found = true;
856 R.addDecl(*I);
Douglas Gregor889ceb72009-02-03 19:21:40 +0000857 }
858 }
John McCall9f3059a2009-10-09 21:13:30 +0000859 if (Found) {
860 R.resolveKind();
Douglas Gregor3e51e172010-05-20 20:58:56 +0000861 if (S->isClassScope())
862 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(Ctx))
863 R.setNamingClass(Record);
John McCall9f3059a2009-10-09 21:13:30 +0000864 return true;
865 }
866
Douglas Gregor66230062010-03-15 14:33:29 +0000867 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
868 S->getParent() && !S->getParent()->isTemplateParamScope()) {
869 // We've just searched the last template parameter scope and
870 // found nothing, so look into the the contexts between the
871 // lexical and semantic declaration contexts returned by
872 // findOuterContext(). This implements the name lookup behavior
873 // of C++ [temp.local]p8.
874 Ctx = OutsideOfTemplateParamDC;
875 OutsideOfTemplateParamDC = 0;
876 }
877
878 if (Ctx) {
879 DeclContext *OuterCtx;
880 bool SearchAfterTemplateScope;
881 llvm::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
882 if (SearchAfterTemplateScope)
883 OutsideOfTemplateParamDC = OuterCtx;
884
Douglas Gregorea166062010-03-15 15:26:48 +0000885 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
Douglas Gregor337caf92010-02-19 16:08:35 +0000886 // We do not directly look into transparent contexts, since
887 // those entities will be found in the nearest enclosing
888 // non-transparent context.
889 if (Ctx->isTransparentContext())
Douglas Gregor7f737c02009-09-10 16:57:35 +0000890 continue;
Douglas Gregor337caf92010-02-19 16:08:35 +0000891
892 // We do not look directly into function or method contexts,
893 // since all of the local variables and parameters of the
894 // function/method are present within the Scope.
895 if (Ctx->isFunctionOrMethod()) {
896 // If we have an Objective-C instance method, look for ivars
897 // in the corresponding interface.
898 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
899 if (Method->isInstanceMethod() && Name.getAsIdentifierInfo())
900 if (ObjCInterfaceDecl *Class = Method->getClassInterface()) {
901 ObjCInterfaceDecl *ClassDeclared;
902 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000903 Name.getAsIdentifierInfo(),
Douglas Gregor337caf92010-02-19 16:08:35 +0000904 ClassDeclared)) {
905 if (R.isAcceptableDecl(Ivar)) {
906 R.addDecl(Ivar);
907 R.resolveKind();
908 return true;
909 }
910 }
911 }
912 }
913
914 continue;
915 }
916
Douglas Gregor7f737c02009-09-10 16:57:35 +0000917 // Perform qualified name lookup into this context.
918 // FIXME: In some cases, we know that every name that could be found by
919 // this qualified name lookup will also be on the identifier chain. For
920 // example, inside a class without any base classes, we never need to
921 // perform qualified lookup because all of the members are on top of the
922 // identifier chain.
Douglas Gregord0d2ee02010-01-15 01:44:47 +0000923 if (LookupQualifiedName(R, Ctx, /*InUnqualifiedLookup=*/true))
John McCall9f3059a2009-10-09 21:13:30 +0000924 return true;
Douglas Gregorfdca4a72009-03-27 04:21:56 +0000925 }
Douglas Gregor700792c2009-02-05 19:25:20 +0000926 }
Douglas Gregored8f2882009-01-30 01:04:22 +0000927 }
Douglas Gregor889ceb72009-02-03 19:21:40 +0000928
John McCallf6c8a4e2009-11-10 07:01:13 +0000929 // Stop if we ran out of scopes.
930 // FIXME: This really, really shouldn't be happening.
931 if (!S) return false;
932
Argyrios Kyrtzidis706bbf82010-10-29 16:12:50 +0000933 // If we are looking for members, no need to look into global/namespace scope.
934 if (R.getLookupKind() == LookupMemberName)
935 return false;
936
Douglas Gregor700792c2009-02-05 19:25:20 +0000937 // Collect UsingDirectiveDecls in all scopes, and recursively all
Douglas Gregor889ceb72009-02-03 19:21:40 +0000938 // nominated namespaces by those using-directives.
John McCallf6c8a4e2009-11-10 07:01:13 +0000939 //
Mike Stump87c57ac2009-05-16 07:39:55 +0000940 // FIXME: Cache this sorted list in Scope structure, and DeclContext, so we
941 // don't build it for each lookup!
Douglas Gregor889ceb72009-02-03 19:21:40 +0000942
John McCallf6c8a4e2009-11-10 07:01:13 +0000943 UnqualUsingDirectiveSet UDirs;
944 UDirs.visitScopeChain(Initial, S);
945 UDirs.done();
Douglas Gregor889ceb72009-02-03 19:21:40 +0000946
Douglas Gregor700792c2009-02-05 19:25:20 +0000947 // Lookup namespace scope, and global scope.
Douglas Gregor889ceb72009-02-03 19:21:40 +0000948 // Unqualified name lookup in C++ requires looking into scopes
949 // that aren't strictly lexical, and therefore we walk through the
950 // context as well as walking through the scopes.
Douglas Gregor700792c2009-02-05 19:25:20 +0000951
Douglas Gregor889ceb72009-02-03 19:21:40 +0000952 for (; S; S = S->getParent()) {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000953 // Check whether the IdResolver has anything in this scope.
John McCall9f3059a2009-10-09 21:13:30 +0000954 bool Found = false;
John McCall48871652010-08-21 09:40:31 +0000955 for (; I != IEnd && S->isDeclScope(*I); ++I) {
John McCallea305ed2009-12-18 10:40:03 +0000956 if (R.isAcceptableDecl(*I)) {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000957 // We found something. Look for anything else in our scope
958 // with this same name and in an acceptable identifier
959 // namespace, so that we can construct an overload set if we
960 // need to.
John McCall9f3059a2009-10-09 21:13:30 +0000961 Found = true;
962 R.addDecl(*I);
Douglas Gregor889ceb72009-02-03 19:21:40 +0000963 }
964 }
965
Douglas Gregorf3d3ae62010-05-14 04:53:42 +0000966 if (Found && S->isTemplateParamScope()) {
John McCall9f3059a2009-10-09 21:13:30 +0000967 R.resolveKind();
968 return true;
969 }
970
Douglas Gregorf3d3ae62010-05-14 04:53:42 +0000971 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
972 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
973 S->getParent() && !S->getParent()->isTemplateParamScope()) {
974 // We've just searched the last template parameter scope and
975 // found nothing, so look into the the contexts between the
976 // lexical and semantic declaration contexts returned by
977 // findOuterContext(). This implements the name lookup behavior
978 // of C++ [temp.local]p8.
979 Ctx = OutsideOfTemplateParamDC;
980 OutsideOfTemplateParamDC = 0;
981 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000982
Douglas Gregorf3d3ae62010-05-14 04:53:42 +0000983 if (Ctx) {
984 DeclContext *OuterCtx;
985 bool SearchAfterTemplateScope;
986 llvm::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
987 if (SearchAfterTemplateScope)
988 OutsideOfTemplateParamDC = OuterCtx;
989
990 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
991 // We do not directly look into transparent contexts, since
992 // those entities will be found in the nearest enclosing
993 // non-transparent context.
994 if (Ctx->isTransparentContext())
995 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000996
Douglas Gregorf3d3ae62010-05-14 04:53:42 +0000997 // If we have a context, and it's not a context stashed in the
998 // template parameter scope for an out-of-line definition, also
999 // look into that context.
1000 if (!(Found && S && S->isTemplateParamScope())) {
1001 assert(Ctx->isFileContext() &&
1002 "We should have been looking only at file context here already.");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001003
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001004 // Look into context considering using-directives.
1005 if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs))
1006 Found = true;
1007 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001008
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001009 if (Found) {
1010 R.resolveKind();
1011 return true;
1012 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001013
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001014 if (R.isForRedeclaration() && !Ctx->isTransparentContext())
1015 return false;
1016 }
1017 }
1018
Douglas Gregor3ce74932010-02-05 07:07:10 +00001019 if (R.isForRedeclaration() && Ctx && !Ctx->isTransparentContext())
John McCall9f3059a2009-10-09 21:13:30 +00001020 return false;
Douglas Gregor700792c2009-02-05 19:25:20 +00001021 }
Douglas Gregor889ceb72009-02-03 19:21:40 +00001022
John McCall9f3059a2009-10-09 21:13:30 +00001023 return !R.empty();
Douglas Gregored8f2882009-01-30 01:04:22 +00001024}
1025
Douglas Gregor34074322009-01-14 22:20:51 +00001026/// @brief Perform unqualified name lookup starting from a given
1027/// scope.
1028///
1029/// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is
1030/// used to find names within the current scope. For example, 'x' in
1031/// @code
1032/// int x;
1033/// int f() {
1034/// return x; // unqualified name look finds 'x' in the global scope
1035/// }
1036/// @endcode
1037///
1038/// Different lookup criteria can find different names. For example, a
1039/// particular scope can have both a struct and a function of the same
1040/// name, and each can be found by certain lookup criteria. For more
1041/// information about lookup criteria, see the documentation for the
1042/// class LookupCriteria.
1043///
1044/// @param S The scope from which unqualified name lookup will
1045/// begin. If the lookup criteria permits, name lookup may also search
1046/// in the parent scopes.
1047///
1048/// @param Name The name of the entity that we are searching for.
1049///
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001050/// @param Loc If provided, the source location where we're performing
Mike Stump11289f42009-09-09 15:08:12 +00001051/// name lookup. At present, this is only used to produce diagnostics when
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001052/// C library functions (like "malloc") are implicitly declared.
Douglas Gregor34074322009-01-14 22:20:51 +00001053///
1054/// @returns The result of name lookup, which includes zero or more
1055/// declarations and possibly additional information used to diagnose
1056/// ambiguities.
John McCall27b18f82009-11-17 02:14:36 +00001057bool Sema::LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation) {
1058 DeclarationName Name = R.getLookupName();
John McCall9f3059a2009-10-09 21:13:30 +00001059 if (!Name) return false;
Douglas Gregor34074322009-01-14 22:20:51 +00001060
John McCall27b18f82009-11-17 02:14:36 +00001061 LookupNameKind NameKind = R.getLookupKind();
1062
Douglas Gregor34074322009-01-14 22:20:51 +00001063 if (!getLangOptions().CPlusPlus) {
1064 // Unqualified name lookup in C/Objective-C is purely lexical, so
1065 // search in the declarations attached to the name.
John McCallea305ed2009-12-18 10:40:03 +00001066 if (NameKind == Sema::LookupRedeclarationWithLinkage) {
Douglas Gregoreddf4332009-02-24 20:03:32 +00001067 // Find the nearest non-transparent declaration scope.
1068 while (!(S->getFlags() & Scope::DeclScope) ||
Mike Stump11289f42009-09-09 15:08:12 +00001069 (S->getEntity() &&
Douglas Gregoreddf4332009-02-24 20:03:32 +00001070 static_cast<DeclContext *>(S->getEntity())
1071 ->isTransparentContext()))
1072 S = S->getParent();
Douglas Gregored8f2882009-01-30 01:04:22 +00001073 }
1074
John McCallea305ed2009-12-18 10:40:03 +00001075 unsigned IDNS = R.getIdentifierNamespace();
1076
Douglas Gregor34074322009-01-14 22:20:51 +00001077 // Scan up the scope chain looking for a decl that matches this
1078 // identifier that is in the appropriate namespace. This search
1079 // should not take long, as shadowing of names is uncommon, and
1080 // deep shadowing is extremely uncommon.
Douglas Gregoreddf4332009-02-24 20:03:32 +00001081 bool LeftStartingScope = false;
1082
Douglas Gregored8f2882009-01-30 01:04:22 +00001083 for (IdentifierResolver::iterator I = IdResolver.begin(Name),
Mike Stump11289f42009-09-09 15:08:12 +00001084 IEnd = IdResolver.end();
Douglas Gregored8f2882009-01-30 01:04:22 +00001085 I != IEnd; ++I)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001086 if ((*I)->isInIdentifierNamespace(IDNS)) {
Douglas Gregoreddf4332009-02-24 20:03:32 +00001087 if (NameKind == LookupRedeclarationWithLinkage) {
1088 // Determine whether this (or a previous) declaration is
1089 // out-of-scope.
John McCall48871652010-08-21 09:40:31 +00001090 if (!LeftStartingScope && !S->isDeclScope(*I))
Douglas Gregoreddf4332009-02-24 20:03:32 +00001091 LeftStartingScope = true;
1092
1093 // If we found something outside of our starting scope that
1094 // does not have linkage, skip it.
1095 if (LeftStartingScope && !((*I)->hasLinkage()))
1096 continue;
1097 }
1098
John McCall9f3059a2009-10-09 21:13:30 +00001099 R.addDecl(*I);
1100
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001101 if ((*I)->getAttr<OverloadableAttr>()) {
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001102 // If this declaration has the "overloadable" attribute, we
1103 // might have a set of overloaded functions.
1104
1105 // Figure out what scope the identifier is in.
Chris Lattner83f095c2009-03-28 19:18:32 +00001106 while (!(S->getFlags() & Scope::DeclScope) ||
John McCall48871652010-08-21 09:40:31 +00001107 !S->isDeclScope(*I))
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001108 S = S->getParent();
1109
1110 // Find the last declaration in this scope (with the same
1111 // name, naturally).
1112 IdentifierResolver::iterator LastI = I;
1113 for (++LastI; LastI != IEnd; ++LastI) {
John McCall48871652010-08-21 09:40:31 +00001114 if (!S->isDeclScope(*LastI))
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001115 break;
John McCall9f3059a2009-10-09 21:13:30 +00001116 R.addDecl(*LastI);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001117 }
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001118 }
1119
John McCall9f3059a2009-10-09 21:13:30 +00001120 R.resolveKind();
1121
1122 return true;
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001123 }
Douglas Gregor34074322009-01-14 22:20:51 +00001124 } else {
Douglas Gregor889ceb72009-02-03 19:21:40 +00001125 // Perform C++ unqualified name lookup.
John McCall27b18f82009-11-17 02:14:36 +00001126 if (CppLookupName(R, S))
John McCall9f3059a2009-10-09 21:13:30 +00001127 return true;
Douglas Gregor34074322009-01-14 22:20:51 +00001128 }
1129
1130 // If we didn't find a use of this identifier, and if the identifier
1131 // corresponds to a compiler builtin, create the decl object for the builtin
1132 // now, injecting it into translation unit scope, and return it.
Douglas Gregord3a59182010-02-12 05:48:04 +00001133 if (AllowBuiltinCreation)
1134 return LookupBuiltin(*this, R);
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001135
Axel Naumann016538a2011-02-24 16:47:47 +00001136 // If we didn't find a use of this identifier, the ExternalSource
1137 // may be able to handle the situation.
1138 // Note: some lookup failures are expected!
1139 // See e.g. R.isForRedeclaration().
1140 return (ExternalSource && ExternalSource->LookupUnqualified(R, S));
Douglas Gregor34074322009-01-14 22:20:51 +00001141}
1142
John McCall6538c932009-10-10 05:48:19 +00001143/// @brief Perform qualified name lookup in the namespaces nominated by
1144/// using directives by the given context.
1145///
1146/// C++98 [namespace.qual]p2:
1147/// Given X::m (where X is a user-declared namespace), or given ::m
1148/// (where X is the global namespace), let S be the set of all
1149/// declarations of m in X and in the transitive closure of all
1150/// namespaces nominated by using-directives in X and its used
1151/// namespaces, except that using-directives are ignored in any
1152/// namespace, including X, directly containing one or more
1153/// declarations of m. No namespace is searched more than once in
1154/// the lookup of a name. If S is the empty set, the program is
1155/// ill-formed. Otherwise, if S has exactly one member, or if the
1156/// context of the reference is a using-declaration
1157/// (namespace.udecl), S is the required set of declarations of
1158/// m. Otherwise if the use of m is not one that allows a unique
1159/// declaration to be chosen from S, the program is ill-formed.
1160/// C++98 [namespace.qual]p5:
1161/// During the lookup of a qualified namespace member name, if the
1162/// lookup finds more than one declaration of the member, and if one
1163/// declaration introduces a class name or enumeration name and the
1164/// other declarations either introduce the same object, the same
1165/// enumerator or a set of functions, the non-type name hides the
1166/// class or enumeration name if and only if the declarations are
1167/// from the same namespace; otherwise (the declarations are from
1168/// different namespaces), the program is ill-formed.
Douglas Gregord3a59182010-02-12 05:48:04 +00001169static bool LookupQualifiedNameInUsingDirectives(Sema &S, LookupResult &R,
John McCall27b18f82009-11-17 02:14:36 +00001170 DeclContext *StartDC) {
John McCall6538c932009-10-10 05:48:19 +00001171 assert(StartDC->isFileContext() && "start context is not a file context");
1172
1173 DeclContext::udir_iterator I = StartDC->using_directives_begin();
1174 DeclContext::udir_iterator E = StartDC->using_directives_end();
1175
1176 if (I == E) return false;
1177
1178 // We have at least added all these contexts to the queue.
1179 llvm::DenseSet<DeclContext*> Visited;
1180 Visited.insert(StartDC);
1181
1182 // We have not yet looked into these namespaces, much less added
1183 // their "using-children" to the queue.
1184 llvm::SmallVector<NamespaceDecl*, 8> Queue;
1185
1186 // We have already looked into the initial namespace; seed the queue
1187 // with its using-children.
1188 for (; I != E; ++I) {
John McCallb8be78b2009-11-10 09:25:37 +00001189 NamespaceDecl *ND = (*I)->getNominatedNamespace()->getOriginalNamespace();
John McCall6538c932009-10-10 05:48:19 +00001190 if (Visited.insert(ND).second)
1191 Queue.push_back(ND);
1192 }
1193
1194 // The easiest way to implement the restriction in [namespace.qual]p5
1195 // is to check whether any of the individual results found a tag
1196 // and, if so, to declare an ambiguity if the final result is not
1197 // a tag.
1198 bool FoundTag = false;
1199 bool FoundNonTag = false;
1200
John McCall5cebab12009-11-18 07:57:50 +00001201 LookupResult LocalR(LookupResult::Temporary, R);
John McCall6538c932009-10-10 05:48:19 +00001202
1203 bool Found = false;
1204 while (!Queue.empty()) {
1205 NamespaceDecl *ND = Queue.back();
1206 Queue.pop_back();
1207
1208 // We go through some convolutions here to avoid copying results
1209 // between LookupResults.
1210 bool UseLocal = !R.empty();
John McCall5cebab12009-11-18 07:57:50 +00001211 LookupResult &DirectR = UseLocal ? LocalR : R;
Douglas Gregord3a59182010-02-12 05:48:04 +00001212 bool FoundDirect = LookupDirect(S, DirectR, ND);
John McCall6538c932009-10-10 05:48:19 +00001213
1214 if (FoundDirect) {
1215 // First do any local hiding.
1216 DirectR.resolveKind();
1217
1218 // If the local result is a tag, remember that.
1219 if (DirectR.isSingleTagDecl())
1220 FoundTag = true;
1221 else
1222 FoundNonTag = true;
1223
1224 // Append the local results to the total results if necessary.
1225 if (UseLocal) {
1226 R.addAllDecls(LocalR);
1227 LocalR.clear();
1228 }
1229 }
1230
1231 // If we find names in this namespace, ignore its using directives.
1232 if (FoundDirect) {
1233 Found = true;
1234 continue;
1235 }
1236
1237 for (llvm::tie(I,E) = ND->getUsingDirectives(); I != E; ++I) {
1238 NamespaceDecl *Nom = (*I)->getNominatedNamespace();
1239 if (Visited.insert(Nom).second)
1240 Queue.push_back(Nom);
1241 }
1242 }
1243
1244 if (Found) {
1245 if (FoundTag && FoundNonTag)
1246 R.setAmbiguousQualifiedTagHiding();
1247 else
1248 R.resolveKind();
1249 }
1250
1251 return Found;
1252}
1253
Douglas Gregor39982192010-08-15 06:18:01 +00001254/// \brief Callback that looks for any member of a class with the given name.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001255static bool LookupAnyMember(const CXXBaseSpecifier *Specifier,
Douglas Gregor39982192010-08-15 06:18:01 +00001256 CXXBasePath &Path,
1257 void *Name) {
1258 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001259
Douglas Gregor39982192010-08-15 06:18:01 +00001260 DeclarationName N = DeclarationName::getFromOpaquePtr(Name);
1261 Path.Decls = BaseRecord->lookup(N);
1262 return Path.Decls.first != Path.Decls.second;
1263}
1264
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001265/// \brief Determine whether the given set of member declarations contains only
Douglas Gregorc0d24902010-10-22 22:08:47 +00001266/// static members, nested types, and enumerators.
1267template<typename InputIterator>
1268static bool HasOnlyStaticMembers(InputIterator First, InputIterator Last) {
1269 Decl *D = (*First)->getUnderlyingDecl();
1270 if (isa<VarDecl>(D) || isa<TypeDecl>(D) || isa<EnumConstantDecl>(D))
1271 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001272
Douglas Gregorc0d24902010-10-22 22:08:47 +00001273 if (isa<CXXMethodDecl>(D)) {
1274 // Determine whether all of the methods are static.
1275 bool AllMethodsAreStatic = true;
1276 for(; First != Last; ++First) {
1277 D = (*First)->getUnderlyingDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001278
Douglas Gregorc0d24902010-10-22 22:08:47 +00001279 if (!isa<CXXMethodDecl>(D)) {
1280 assert(isa<TagDecl>(D) && "Non-function must be a tag decl");
1281 break;
1282 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001283
Douglas Gregorc0d24902010-10-22 22:08:47 +00001284 if (!cast<CXXMethodDecl>(D)->isStatic()) {
1285 AllMethodsAreStatic = false;
1286 break;
1287 }
1288 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001289
Douglas Gregorc0d24902010-10-22 22:08:47 +00001290 if (AllMethodsAreStatic)
1291 return true;
1292 }
1293
1294 return false;
1295}
1296
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001297/// \brief Perform qualified name lookup into a given context.
Douglas Gregor34074322009-01-14 22:20:51 +00001298///
1299/// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
1300/// names when the context of those names is explicit specified, e.g.,
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001301/// "std::vector" or "x->member", or as part of unqualified name lookup.
Douglas Gregor34074322009-01-14 22:20:51 +00001302///
1303/// Different lookup criteria can find different names. For example, a
1304/// particular scope can have both a struct and a function of the same
1305/// name, and each can be found by certain lookup criteria. For more
1306/// information about lookup criteria, see the documentation for the
1307/// class LookupCriteria.
1308///
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001309/// \param R captures both the lookup criteria and any lookup results found.
1310///
1311/// \param LookupCtx The context in which qualified name lookup will
Douglas Gregor34074322009-01-14 22:20:51 +00001312/// search. If the lookup criteria permits, name lookup may also search
1313/// in the parent contexts or (for C++ classes) base classes.
1314///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001315/// \param InUnqualifiedLookup true if this is qualified name lookup that
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001316/// occurs as part of unqualified name lookup.
Douglas Gregor34074322009-01-14 22:20:51 +00001317///
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001318/// \returns true if lookup succeeded, false if it failed.
1319bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
1320 bool InUnqualifiedLookup) {
Douglas Gregor34074322009-01-14 22:20:51 +00001321 assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context");
Mike Stump11289f42009-09-09 15:08:12 +00001322
John McCall27b18f82009-11-17 02:14:36 +00001323 if (!R.getLookupName())
John McCall9f3059a2009-10-09 21:13:30 +00001324 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001325
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001326 // Make sure that the declaration context is complete.
1327 assert((!isa<TagDecl>(LookupCtx) ||
1328 LookupCtx->isDependentContext() ||
1329 cast<TagDecl>(LookupCtx)->isDefinition() ||
1330 Context.getTypeDeclType(cast<TagDecl>(LookupCtx))->getAs<TagType>()
1331 ->isBeingDefined()) &&
1332 "Declaration context must already be complete!");
Mike Stump11289f42009-09-09 15:08:12 +00001333
Douglas Gregor34074322009-01-14 22:20:51 +00001334 // Perform qualified name lookup into the LookupCtx.
Douglas Gregord3a59182010-02-12 05:48:04 +00001335 if (LookupDirect(*this, R, LookupCtx)) {
John McCall9f3059a2009-10-09 21:13:30 +00001336 R.resolveKind();
John McCall553c0792010-01-23 00:46:32 +00001337 if (isa<CXXRecordDecl>(LookupCtx))
1338 R.setNamingClass(cast<CXXRecordDecl>(LookupCtx));
John McCall9f3059a2009-10-09 21:13:30 +00001339 return true;
1340 }
Douglas Gregor34074322009-01-14 22:20:51 +00001341
John McCall6538c932009-10-10 05:48:19 +00001342 // Don't descend into implied contexts for redeclarations.
1343 // C++98 [namespace.qual]p6:
1344 // In a declaration for a namespace member in which the
1345 // declarator-id is a qualified-id, given that the qualified-id
1346 // for the namespace member has the form
1347 // nested-name-specifier unqualified-id
1348 // the unqualified-id shall name a member of the namespace
1349 // designated by the nested-name-specifier.
1350 // See also [class.mfct]p5 and [class.static.data]p2.
John McCall27b18f82009-11-17 02:14:36 +00001351 if (R.isForRedeclaration())
John McCall6538c932009-10-10 05:48:19 +00001352 return false;
1353
John McCall27b18f82009-11-17 02:14:36 +00001354 // If this is a namespace, look it up in the implied namespaces.
John McCall6538c932009-10-10 05:48:19 +00001355 if (LookupCtx->isFileContext())
Douglas Gregord3a59182010-02-12 05:48:04 +00001356 return LookupQualifiedNameInUsingDirectives(*this, R, LookupCtx);
John McCall6538c932009-10-10 05:48:19 +00001357
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001358 // If this isn't a C++ class, we aren't allowed to look into base
Douglas Gregorcc2427c2009-09-11 22:57:37 +00001359 // classes, we're done.
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001360 CXXRecordDecl *LookupRec = dyn_cast<CXXRecordDecl>(LookupCtx);
Douglas Gregor5a5fcd82010-07-01 00:21:21 +00001361 if (!LookupRec || !LookupRec->getDefinition())
John McCall9f3059a2009-10-09 21:13:30 +00001362 return false;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001363
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001364 // If we're performing qualified name lookup into a dependent class,
1365 // then we are actually looking into a current instantiation. If we have any
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001366 // dependent base classes, then we either have to delay lookup until
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001367 // template instantiation time (at which point all bases will be available)
1368 // or we have to fail.
1369 if (!InUnqualifiedLookup && LookupRec->isDependentContext() &&
1370 LookupRec->hasAnyDependentBases()) {
1371 R.setNotFoundInCurrentInstantiation();
1372 return false;
1373 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001374
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001375 // Perform lookup into our base classes.
Douglas Gregor36d1b142009-10-06 17:59:45 +00001376 CXXBasePaths Paths;
1377 Paths.setOrigin(LookupRec);
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001378
1379 // Look for this member in our base classes
Douglas Gregor36d1b142009-10-06 17:59:45 +00001380 CXXRecordDecl::BaseMatchesCallback *BaseCallback = 0;
John McCall27b18f82009-11-17 02:14:36 +00001381 switch (R.getLookupKind()) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00001382 case LookupOrdinaryName:
1383 case LookupMemberName:
1384 case LookupRedeclarationWithLinkage:
1385 BaseCallback = &CXXRecordDecl::FindOrdinaryMember;
1386 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001387
Douglas Gregor36d1b142009-10-06 17:59:45 +00001388 case LookupTagName:
1389 BaseCallback = &CXXRecordDecl::FindTagMember;
1390 break;
John McCall84d87672009-12-10 09:41:52 +00001391
Douglas Gregor39982192010-08-15 06:18:01 +00001392 case LookupAnyName:
1393 BaseCallback = &LookupAnyMember;
1394 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001395
John McCall84d87672009-12-10 09:41:52 +00001396 case LookupUsingDeclName:
1397 // This lookup is for redeclarations only.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001398
Douglas Gregor36d1b142009-10-06 17:59:45 +00001399 case LookupOperatorName:
1400 case LookupNamespaceName:
1401 case LookupObjCProtocolName:
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001402 case LookupLabel:
Douglas Gregor36d1b142009-10-06 17:59:45 +00001403 // These lookups will never find a member in a C++ class (or base class).
John McCall9f3059a2009-10-09 21:13:30 +00001404 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001405
Douglas Gregor36d1b142009-10-06 17:59:45 +00001406 case LookupNestedNameSpecifierName:
1407 BaseCallback = &CXXRecordDecl::FindNestedNameSpecifierMember;
1408 break;
1409 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001410
John McCall27b18f82009-11-17 02:14:36 +00001411 if (!LookupRec->lookupInBases(BaseCallback,
1412 R.getLookupName().getAsOpaquePtr(), Paths))
John McCall9f3059a2009-10-09 21:13:30 +00001413 return false;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001414
John McCall553c0792010-01-23 00:46:32 +00001415 R.setNamingClass(LookupRec);
1416
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001417 // C++ [class.member.lookup]p2:
1418 // [...] If the resulting set of declarations are not all from
1419 // sub-objects of the same type, or the set has a nonstatic member
1420 // and includes members from distinct sub-objects, there is an
1421 // ambiguity and the program is ill-formed. Otherwise that set is
1422 // the result of the lookup.
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001423 QualType SubobjectType;
Daniel Dunbar435bbe02009-01-15 18:32:35 +00001424 int SubobjectNumber = 0;
John McCalla332b952010-03-18 23:49:19 +00001425 AccessSpecifier SubobjectAccess = AS_none;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001426
Douglas Gregor36d1b142009-10-06 17:59:45 +00001427 for (CXXBasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end();
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001428 Path != PathEnd; ++Path) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00001429 const CXXBasePathElement &PathElement = Path->back();
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001430
John McCall401982f2010-01-20 21:53:11 +00001431 // Pick the best (i.e. most permissive i.e. numerically lowest) access
1432 // across all paths.
1433 SubobjectAccess = std::min(SubobjectAccess, Path->Access);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001434
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001435 // Determine whether we're looking at a distinct sub-object or not.
1436 if (SubobjectType.isNull()) {
John McCall9f3059a2009-10-09 21:13:30 +00001437 // This is the first subobject we've looked at. Record its type.
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001438 SubobjectType = Context.getCanonicalType(PathElement.Base->getType());
1439 SubobjectNumber = PathElement.SubobjectNumber;
Douglas Gregorc0d24902010-10-22 22:08:47 +00001440 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001441 }
1442
Douglas Gregorc0d24902010-10-22 22:08:47 +00001443 if (SubobjectType
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001444 != Context.getCanonicalType(PathElement.Base->getType())) {
1445 // We found members of the given name in two subobjects of
Douglas Gregorc0d24902010-10-22 22:08:47 +00001446 // different types. If the declaration sets aren't the same, this
1447 // this lookup is ambiguous.
1448 if (HasOnlyStaticMembers(Path->Decls.first, Path->Decls.second)) {
1449 CXXBasePaths::paths_iterator FirstPath = Paths.begin();
1450 DeclContext::lookup_iterator FirstD = FirstPath->Decls.first;
1451 DeclContext::lookup_iterator CurrentD = Path->Decls.first;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001452
Douglas Gregorc0d24902010-10-22 22:08:47 +00001453 while (FirstD != FirstPath->Decls.second &&
1454 CurrentD != Path->Decls.second) {
1455 if ((*FirstD)->getUnderlyingDecl()->getCanonicalDecl() !=
1456 (*CurrentD)->getUnderlyingDecl()->getCanonicalDecl())
1457 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001458
Douglas Gregorc0d24902010-10-22 22:08:47 +00001459 ++FirstD;
1460 ++CurrentD;
1461 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001462
Douglas Gregorc0d24902010-10-22 22:08:47 +00001463 if (FirstD == FirstPath->Decls.second &&
1464 CurrentD == Path->Decls.second)
1465 continue;
1466 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001467
John McCall9f3059a2009-10-09 21:13:30 +00001468 R.setAmbiguousBaseSubobjectTypes(Paths);
1469 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001470 }
1471
Douglas Gregorc0d24902010-10-22 22:08:47 +00001472 if (SubobjectNumber != PathElement.SubobjectNumber) {
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001473 // We have a different subobject of the same type.
1474
1475 // C++ [class.member.lookup]p5:
1476 // A static member, a nested type or an enumerator defined in
1477 // a base class T can unambiguously be found even if an object
Mike Stump11289f42009-09-09 15:08:12 +00001478 // has more than one base class subobject of type T.
Douglas Gregorc0d24902010-10-22 22:08:47 +00001479 if (HasOnlyStaticMembers(Path->Decls.first, Path->Decls.second))
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001480 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001481
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001482 // We have found a nonstatic member name in multiple, distinct
1483 // subobjects. Name lookup is ambiguous.
John McCall9f3059a2009-10-09 21:13:30 +00001484 R.setAmbiguousBaseSubobjects(Paths);
1485 return true;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001486 }
1487 }
1488
1489 // Lookup in a base class succeeded; return these results.
1490
John McCall9f3059a2009-10-09 21:13:30 +00001491 DeclContext::lookup_iterator I, E;
John McCall553c0792010-01-23 00:46:32 +00001492 for (llvm::tie(I,E) = Paths.front().Decls; I != E; ++I) {
1493 NamedDecl *D = *I;
1494 AccessSpecifier AS = CXXRecordDecl::MergeAccess(SubobjectAccess,
1495 D->getAccess());
1496 R.addDecl(D, AS);
1497 }
John McCall9f3059a2009-10-09 21:13:30 +00001498 R.resolveKind();
1499 return true;
Douglas Gregor34074322009-01-14 22:20:51 +00001500}
1501
1502/// @brief Performs name lookup for a name that was parsed in the
1503/// source code, and may contain a C++ scope specifier.
1504///
1505/// This routine is a convenience routine meant to be called from
1506/// contexts that receive a name and an optional C++ scope specifier
1507/// (e.g., "N::M::x"). It will then perform either qualified or
1508/// unqualified name lookup (with LookupQualifiedName or LookupName,
1509/// respectively) on the given name and return those results.
1510///
1511/// @param S The scope from which unqualified name lookup will
1512/// begin.
Mike Stump11289f42009-09-09 15:08:12 +00001513///
Douglas Gregore861bac2009-08-25 22:51:20 +00001514/// @param SS An optional C++ scope-specifier, e.g., "::N::M".
Douglas Gregor34074322009-01-14 22:20:51 +00001515///
Douglas Gregore861bac2009-08-25 22:51:20 +00001516/// @param EnteringContext Indicates whether we are going to enter the
1517/// context of the scope-specifier SS (if present).
1518///
John McCall9f3059a2009-10-09 21:13:30 +00001519/// @returns True if any decls were found (but possibly ambiguous)
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001520bool Sema::LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
John McCall27b18f82009-11-17 02:14:36 +00001521 bool AllowBuiltinCreation, bool EnteringContext) {
Douglas Gregore861bac2009-08-25 22:51:20 +00001522 if (SS && SS->isInvalid()) {
1523 // When the scope specifier is invalid, don't even look for
Douglas Gregorc9f9b862009-05-11 19:58:34 +00001524 // anything.
John McCall9f3059a2009-10-09 21:13:30 +00001525 return false;
Douglas Gregore861bac2009-08-25 22:51:20 +00001526 }
Mike Stump11289f42009-09-09 15:08:12 +00001527
Douglas Gregore861bac2009-08-25 22:51:20 +00001528 if (SS && SS->isSet()) {
1529 if (DeclContext *DC = computeDeclContext(*SS, EnteringContext)) {
Mike Stump11289f42009-09-09 15:08:12 +00001530 // We have resolved the scope specifier to a particular declaration
Douglas Gregore861bac2009-08-25 22:51:20 +00001531 // contex, and will perform name lookup in that context.
John McCall0b66eb32010-05-01 00:40:08 +00001532 if (!DC->isDependentContext() && RequireCompleteDeclContext(*SS, DC))
John McCall9f3059a2009-10-09 21:13:30 +00001533 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001534
John McCall27b18f82009-11-17 02:14:36 +00001535 R.setContextRange(SS->getRange());
1536
1537 return LookupQualifiedName(R, DC);
Douglas Gregor52537682009-03-19 00:18:19 +00001538 }
Douglas Gregorc9f9b862009-05-11 19:58:34 +00001539
Douglas Gregore861bac2009-08-25 22:51:20 +00001540 // We could not resolve the scope specified to a specific declaration
Mike Stump11289f42009-09-09 15:08:12 +00001541 // context, which means that SS refers to an unknown specialization.
Douglas Gregore861bac2009-08-25 22:51:20 +00001542 // Name lookup can't find anything in this case.
John McCall9f3059a2009-10-09 21:13:30 +00001543 return false;
Douglas Gregored8f2882009-01-30 01:04:22 +00001544 }
1545
Mike Stump11289f42009-09-09 15:08:12 +00001546 // Perform unqualified name lookup starting in the given scope.
John McCall27b18f82009-11-17 02:14:36 +00001547 return LookupName(R, S, AllowBuiltinCreation);
Douglas Gregor34074322009-01-14 22:20:51 +00001548}
1549
Douglas Gregor889ceb72009-02-03 19:21:40 +00001550
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001551/// @brief Produce a diagnostic describing the ambiguity that resulted
1552/// from name lookup.
1553///
1554/// @param Result The ambiguous name lookup result.
Mike Stump11289f42009-09-09 15:08:12 +00001555///
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001556/// @param Name The name of the entity that name lookup was
1557/// searching for.
1558///
1559/// @param NameLoc The location of the name within the source code.
1560///
1561/// @param LookupRange A source range that provides more
1562/// source-location information concerning the lookup itself. For
1563/// example, this range might highlight a nested-name-specifier that
1564/// precedes the name.
1565///
1566/// @returns true
John McCall27b18f82009-11-17 02:14:36 +00001567bool Sema::DiagnoseAmbiguousLookup(LookupResult &Result) {
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001568 assert(Result.isAmbiguous() && "Lookup result must be ambiguous");
1569
John McCall27b18f82009-11-17 02:14:36 +00001570 DeclarationName Name = Result.getLookupName();
1571 SourceLocation NameLoc = Result.getNameLoc();
1572 SourceRange LookupRange = Result.getContextRange();
1573
John McCall6538c932009-10-10 05:48:19 +00001574 switch (Result.getAmbiguityKind()) {
1575 case LookupResult::AmbiguousBaseSubobjects: {
1576 CXXBasePaths *Paths = Result.getBasePaths();
1577 QualType SubobjectType = Paths->front().back().Base->getType();
1578 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects)
1579 << Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths)
1580 << LookupRange;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001581
John McCall6538c932009-10-10 05:48:19 +00001582 DeclContext::lookup_iterator Found = Paths->front().Decls.first;
1583 while (isa<CXXMethodDecl>(*Found) &&
1584 cast<CXXMethodDecl>(*Found)->isStatic())
1585 ++Found;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001586
John McCall6538c932009-10-10 05:48:19 +00001587 Diag((*Found)->getLocation(), diag::note_ambiguous_member_found);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001588
John McCall6538c932009-10-10 05:48:19 +00001589 return true;
1590 }
Douglas Gregor1c846b02009-01-16 00:38:09 +00001591
John McCall6538c932009-10-10 05:48:19 +00001592 case LookupResult::AmbiguousBaseSubobjectTypes: {
Douglas Gregor889ceb72009-02-03 19:21:40 +00001593 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types)
1594 << Name << LookupRange;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001595
John McCall6538c932009-10-10 05:48:19 +00001596 CXXBasePaths *Paths = Result.getBasePaths();
Douglas Gregor889ceb72009-02-03 19:21:40 +00001597 std::set<Decl *> DeclsPrinted;
John McCall6538c932009-10-10 05:48:19 +00001598 for (CXXBasePaths::paths_iterator Path = Paths->begin(),
1599 PathEnd = Paths->end();
Douglas Gregor889ceb72009-02-03 19:21:40 +00001600 Path != PathEnd; ++Path) {
1601 Decl *D = *Path->Decls.first;
1602 if (DeclsPrinted.insert(D).second)
1603 Diag(D->getLocation(), diag::note_ambiguous_member_found);
1604 }
1605
Douglas Gregor1c846b02009-01-16 00:38:09 +00001606 return true;
Douglas Gregor1c846b02009-01-16 00:38:09 +00001607 }
1608
John McCall6538c932009-10-10 05:48:19 +00001609 case LookupResult::AmbiguousTagHiding: {
1610 Diag(NameLoc, diag::err_ambiguous_tag_hiding) << Name << LookupRange;
Douglas Gregorf23311d2009-01-17 01:13:24 +00001611
John McCall6538c932009-10-10 05:48:19 +00001612 llvm::SmallPtrSet<NamedDecl*,8> TagDecls;
1613
1614 LookupResult::iterator DI, DE = Result.end();
1615 for (DI = Result.begin(); DI != DE; ++DI)
1616 if (TagDecl *TD = dyn_cast<TagDecl>(*DI)) {
1617 TagDecls.insert(TD);
1618 Diag(TD->getLocation(), diag::note_hidden_tag);
1619 }
1620
1621 for (DI = Result.begin(); DI != DE; ++DI)
1622 if (!isa<TagDecl>(*DI))
1623 Diag((*DI)->getLocation(), diag::note_hiding_object);
1624
1625 // For recovery purposes, go ahead and implement the hiding.
John McCallad371252010-01-20 00:46:10 +00001626 LookupResult::Filter F = Result.makeFilter();
1627 while (F.hasNext()) {
1628 if (TagDecls.count(F.next()))
1629 F.erase();
1630 }
1631 F.done();
John McCall6538c932009-10-10 05:48:19 +00001632
1633 return true;
1634 }
1635
1636 case LookupResult::AmbiguousReference: {
1637 Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001638
John McCall6538c932009-10-10 05:48:19 +00001639 LookupResult::iterator DI = Result.begin(), DE = Result.end();
1640 for (; DI != DE; ++DI)
1641 Diag((*DI)->getLocation(), diag::note_ambiguous_candidate) << *DI;
John McCall9f3059a2009-10-09 21:13:30 +00001642
John McCall6538c932009-10-10 05:48:19 +00001643 return true;
1644 }
1645 }
1646
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00001647 llvm_unreachable("unknown ambiguity kind");
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001648 return true;
1649}
Douglas Gregore254f902009-02-04 00:32:51 +00001650
John McCallf24d7bb2010-05-28 18:45:08 +00001651namespace {
1652 struct AssociatedLookup {
1653 AssociatedLookup(Sema &S,
1654 Sema::AssociatedNamespaceSet &Namespaces,
1655 Sema::AssociatedClassSet &Classes)
1656 : S(S), Namespaces(Namespaces), Classes(Classes) {
1657 }
1658
1659 Sema &S;
1660 Sema::AssociatedNamespaceSet &Namespaces;
1661 Sema::AssociatedClassSet &Classes;
1662 };
1663}
1664
Mike Stump11289f42009-09-09 15:08:12 +00001665static void
John McCallf24d7bb2010-05-28 18:45:08 +00001666addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType T);
John McCallc7e8e792009-08-07 22:18:02 +00001667
Douglas Gregor8b895222010-04-30 07:08:38 +00001668static void CollectEnclosingNamespace(Sema::AssociatedNamespaceSet &Namespaces,
1669 DeclContext *Ctx) {
1670 // Add the associated namespace for this class.
1671
1672 // We don't use DeclContext::getEnclosingNamespaceContext() as this may
1673 // be a locally scoped record.
1674
Sebastian Redlbd595762010-08-31 20:53:31 +00001675 // We skip out of inline namespaces. The innermost non-inline namespace
1676 // contains all names of all its nested inline namespaces anyway, so we can
1677 // replace the entire inline namespace tree with its root.
1678 while (Ctx->isRecord() || Ctx->isTransparentContext() ||
1679 Ctx->isInlineNamespace())
Douglas Gregor8b895222010-04-30 07:08:38 +00001680 Ctx = Ctx->getParent();
1681
John McCallc7e8e792009-08-07 22:18:02 +00001682 if (Ctx->isFileContext())
Douglas Gregor8b895222010-04-30 07:08:38 +00001683 Namespaces.insert(Ctx->getPrimaryContext());
John McCallc7e8e792009-08-07 22:18:02 +00001684}
Douglas Gregor197e5f72009-07-08 07:51:57 +00001685
Mike Stump11289f42009-09-09 15:08:12 +00001686// \brief Add the associated classes and namespaces for argument-dependent
Douglas Gregor197e5f72009-07-08 07:51:57 +00001687// lookup that involves a template argument (C++ [basic.lookup.koenig]p2).
Mike Stump11289f42009-09-09 15:08:12 +00001688static void
John McCallf24d7bb2010-05-28 18:45:08 +00001689addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
1690 const TemplateArgument &Arg) {
Douglas Gregor197e5f72009-07-08 07:51:57 +00001691 // C++ [basic.lookup.koenig]p2, last bullet:
Mike Stump11289f42009-09-09 15:08:12 +00001692 // -- [...] ;
Douglas Gregor197e5f72009-07-08 07:51:57 +00001693 switch (Arg.getKind()) {
1694 case TemplateArgument::Null:
1695 break;
Mike Stump11289f42009-09-09 15:08:12 +00001696
Douglas Gregor197e5f72009-07-08 07:51:57 +00001697 case TemplateArgument::Type:
1698 // [...] the namespaces and classes associated with the types of the
1699 // template arguments provided for template type parameters (excluding
1700 // template template parameters)
John McCallf24d7bb2010-05-28 18:45:08 +00001701 addAssociatedClassesAndNamespaces(Result, Arg.getAsType());
Douglas Gregor197e5f72009-07-08 07:51:57 +00001702 break;
Mike Stump11289f42009-09-09 15:08:12 +00001703
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001704 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00001705 case TemplateArgument::TemplateExpansion: {
Mike Stump11289f42009-09-09 15:08:12 +00001706 // [...] the namespaces in which any template template arguments are
1707 // defined; and the classes in which any member templates used as
Douglas Gregor197e5f72009-07-08 07:51:57 +00001708 // template template arguments are defined.
Douglas Gregore4ff4b52011-01-05 18:58:31 +00001709 TemplateName Template = Arg.getAsTemplateOrTemplatePattern();
Mike Stump11289f42009-09-09 15:08:12 +00001710 if (ClassTemplateDecl *ClassTemplate
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001711 = dyn_cast<ClassTemplateDecl>(Template.getAsTemplateDecl())) {
Douglas Gregor197e5f72009-07-08 07:51:57 +00001712 DeclContext *Ctx = ClassTemplate->getDeclContext();
1713 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00001714 Result.Classes.insert(EnclosingClass);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001715 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00001716 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001717 }
1718 break;
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001719 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001720
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001721 case TemplateArgument::Declaration:
Douglas Gregor197e5f72009-07-08 07:51:57 +00001722 case TemplateArgument::Integral:
1723 case TemplateArgument::Expression:
Mike Stump11289f42009-09-09 15:08:12 +00001724 // [Note: non-type template arguments do not contribute to the set of
Douglas Gregor197e5f72009-07-08 07:51:57 +00001725 // associated namespaces. ]
1726 break;
Mike Stump11289f42009-09-09 15:08:12 +00001727
Douglas Gregor197e5f72009-07-08 07:51:57 +00001728 case TemplateArgument::Pack:
1729 for (TemplateArgument::pack_iterator P = Arg.pack_begin(),
1730 PEnd = Arg.pack_end();
1731 P != PEnd; ++P)
John McCallf24d7bb2010-05-28 18:45:08 +00001732 addAssociatedClassesAndNamespaces(Result, *P);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001733 break;
1734 }
1735}
1736
Douglas Gregore254f902009-02-04 00:32:51 +00001737// \brief Add the associated classes and namespaces for
Mike Stump11289f42009-09-09 15:08:12 +00001738// argument-dependent lookup with an argument of class type
1739// (C++ [basic.lookup.koenig]p2).
1740static void
John McCallf24d7bb2010-05-28 18:45:08 +00001741addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
1742 CXXRecordDecl *Class) {
1743
1744 // Just silently ignore anything whose name is __va_list_tag.
1745 if (Class->getDeclName() == Result.S.VAListTagName)
1746 return;
1747
Douglas Gregore254f902009-02-04 00:32:51 +00001748 // C++ [basic.lookup.koenig]p2:
1749 // [...]
1750 // -- If T is a class type (including unions), its associated
1751 // classes are: the class itself; the class of which it is a
1752 // member, if any; and its direct and indirect base
1753 // classes. Its associated namespaces are the namespaces in
Mike Stump11289f42009-09-09 15:08:12 +00001754 // which its associated classes are defined.
Douglas Gregore254f902009-02-04 00:32:51 +00001755
1756 // Add the class of which it is a member, if any.
1757 DeclContext *Ctx = Class->getDeclContext();
1758 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00001759 Result.Classes.insert(EnclosingClass);
Douglas Gregore254f902009-02-04 00:32:51 +00001760 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00001761 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Mike Stump11289f42009-09-09 15:08:12 +00001762
Douglas Gregore254f902009-02-04 00:32:51 +00001763 // Add the class itself. If we've already seen this class, we don't
1764 // need to visit base classes.
John McCallf24d7bb2010-05-28 18:45:08 +00001765 if (!Result.Classes.insert(Class))
Douglas Gregore254f902009-02-04 00:32:51 +00001766 return;
1767
Mike Stump11289f42009-09-09 15:08:12 +00001768 // -- If T is a template-id, its associated namespaces and classes are
1769 // the namespace in which the template is defined; for member
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00001770 // templates, the member template's class; the namespaces and classes
Mike Stump11289f42009-09-09 15:08:12 +00001771 // associated with the types of the template arguments provided for
Douglas Gregor197e5f72009-07-08 07:51:57 +00001772 // template type parameters (excluding template template parameters); the
Mike Stump11289f42009-09-09 15:08:12 +00001773 // namespaces in which any template template arguments are defined; and
1774 // the classes in which any member templates used as template template
1775 // arguments are defined. [Note: non-type template arguments do not
Douglas Gregor197e5f72009-07-08 07:51:57 +00001776 // contribute to the set of associated namespaces. ]
Mike Stump11289f42009-09-09 15:08:12 +00001777 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregor197e5f72009-07-08 07:51:57 +00001778 = dyn_cast<ClassTemplateSpecializationDecl>(Class)) {
1779 DeclContext *Ctx = Spec->getSpecializedTemplate()->getDeclContext();
1780 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00001781 Result.Classes.insert(EnclosingClass);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001782 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00001783 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Mike Stump11289f42009-09-09 15:08:12 +00001784
Douglas Gregor197e5f72009-07-08 07:51:57 +00001785 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
1786 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
John McCallf24d7bb2010-05-28 18:45:08 +00001787 addAssociatedClassesAndNamespaces(Result, TemplateArgs[I]);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001788 }
Mike Stump11289f42009-09-09 15:08:12 +00001789
John McCall67da35c2010-02-04 22:26:26 +00001790 // Only recurse into base classes for complete types.
1791 if (!Class->hasDefinition()) {
1792 // FIXME: we might need to instantiate templates here
1793 return;
1794 }
1795
Douglas Gregore254f902009-02-04 00:32:51 +00001796 // Add direct and indirect base classes along with their associated
1797 // namespaces.
1798 llvm::SmallVector<CXXRecordDecl *, 32> Bases;
1799 Bases.push_back(Class);
1800 while (!Bases.empty()) {
1801 // Pop this class off the stack.
1802 Class = Bases.back();
1803 Bases.pop_back();
1804
1805 // Visit the base classes.
1806 for (CXXRecordDecl::base_class_iterator Base = Class->bases_begin(),
1807 BaseEnd = Class->bases_end();
1808 Base != BaseEnd; ++Base) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001809 const RecordType *BaseType = Base->getType()->getAs<RecordType>();
Sebastian Redlc45c03c2009-10-25 09:35:33 +00001810 // In dependent contexts, we do ADL twice, and the first time around,
1811 // the base type might be a dependent TemplateSpecializationType, or a
1812 // TemplateTypeParmType. If that happens, simply ignore it.
1813 // FIXME: If we want to support export, we probably need to add the
1814 // namespace of the template in a TemplateSpecializationType, or even
1815 // the classes and namespaces of known non-dependent arguments.
1816 if (!BaseType)
1817 continue;
Douglas Gregore254f902009-02-04 00:32:51 +00001818 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(BaseType->getDecl());
John McCallf24d7bb2010-05-28 18:45:08 +00001819 if (Result.Classes.insert(BaseDecl)) {
Douglas Gregore254f902009-02-04 00:32:51 +00001820 // Find the associated namespace for this base class.
1821 DeclContext *BaseCtx = BaseDecl->getDeclContext();
John McCallf24d7bb2010-05-28 18:45:08 +00001822 CollectEnclosingNamespace(Result.Namespaces, BaseCtx);
Douglas Gregore254f902009-02-04 00:32:51 +00001823
1824 // Make sure we visit the bases of this base class.
1825 if (BaseDecl->bases_begin() != BaseDecl->bases_end())
1826 Bases.push_back(BaseDecl);
1827 }
1828 }
1829 }
1830}
1831
1832// \brief Add the associated classes and namespaces for
1833// argument-dependent lookup with an argument of type T
Mike Stump11289f42009-09-09 15:08:12 +00001834// (C++ [basic.lookup.koenig]p2).
1835static void
John McCallf24d7bb2010-05-28 18:45:08 +00001836addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType Ty) {
Douglas Gregore254f902009-02-04 00:32:51 +00001837 // C++ [basic.lookup.koenig]p2:
1838 //
1839 // For each argument type T in the function call, there is a set
1840 // of zero or more associated namespaces and a set of zero or more
1841 // associated classes to be considered. The sets of namespaces and
1842 // classes is determined entirely by the types of the function
1843 // arguments (and the namespace of any template template
1844 // argument). Typedef names and using-declarations used to specify
1845 // the types do not contribute to this set. The sets of namespaces
1846 // and classes are determined in the following way:
Douglas Gregore254f902009-02-04 00:32:51 +00001847
John McCall0af3d3b2010-05-28 06:08:54 +00001848 llvm::SmallVector<const Type *, 16> Queue;
1849 const Type *T = Ty->getCanonicalTypeInternal().getTypePtr();
1850
Douglas Gregore254f902009-02-04 00:32:51 +00001851 while (true) {
John McCall0af3d3b2010-05-28 06:08:54 +00001852 switch (T->getTypeClass()) {
1853
1854#define TYPE(Class, Base)
1855#define DEPENDENT_TYPE(Class, Base) case Type::Class:
1856#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
1857#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
1858#define ABSTRACT_TYPE(Class, Base)
1859#include "clang/AST/TypeNodes.def"
1860 // T is canonical. We can also ignore dependent types because
1861 // we don't need to do ADL at the definition point, but if we
1862 // wanted to implement template export (or if we find some other
1863 // use for associated classes and namespaces...) this would be
1864 // wrong.
Douglas Gregore254f902009-02-04 00:32:51 +00001865 break;
Douglas Gregore254f902009-02-04 00:32:51 +00001866
John McCall0af3d3b2010-05-28 06:08:54 +00001867 // -- If T is a pointer to U or an array of U, its associated
1868 // namespaces and classes are those associated with U.
1869 case Type::Pointer:
1870 T = cast<PointerType>(T)->getPointeeType().getTypePtr();
1871 continue;
1872 case Type::ConstantArray:
1873 case Type::IncompleteArray:
1874 case Type::VariableArray:
1875 T = cast<ArrayType>(T)->getElementType().getTypePtr();
1876 continue;
Douglas Gregore254f902009-02-04 00:32:51 +00001877
John McCall0af3d3b2010-05-28 06:08:54 +00001878 // -- If T is a fundamental type, its associated sets of
1879 // namespaces and classes are both empty.
1880 case Type::Builtin:
1881 break;
1882
1883 // -- If T is a class type (including unions), its associated
1884 // classes are: the class itself; the class of which it is a
1885 // member, if any; and its direct and indirect base
1886 // classes. Its associated namespaces are the namespaces in
1887 // which its associated classes are defined.
1888 case Type::Record: {
1889 CXXRecordDecl *Class
1890 = cast<CXXRecordDecl>(cast<RecordType>(T)->getDecl());
John McCallf24d7bb2010-05-28 18:45:08 +00001891 addAssociatedClassesAndNamespaces(Result, Class);
John McCall0af3d3b2010-05-28 06:08:54 +00001892 break;
Douglas Gregor89ee6822009-02-28 01:32:25 +00001893 }
Douglas Gregorfe60c142010-05-20 02:26:51 +00001894
John McCall0af3d3b2010-05-28 06:08:54 +00001895 // -- If T is an enumeration type, its associated namespace is
1896 // the namespace in which it is defined. If it is class
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00001897 // member, its associated class is the member's class; else
John McCall0af3d3b2010-05-28 06:08:54 +00001898 // it has no associated class.
1899 case Type::Enum: {
1900 EnumDecl *Enum = cast<EnumType>(T)->getDecl();
Douglas Gregore254f902009-02-04 00:32:51 +00001901
John McCall0af3d3b2010-05-28 06:08:54 +00001902 DeclContext *Ctx = Enum->getDeclContext();
1903 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00001904 Result.Classes.insert(EnclosingClass);
Douglas Gregore254f902009-02-04 00:32:51 +00001905
John McCall0af3d3b2010-05-28 06:08:54 +00001906 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00001907 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Douglas Gregore254f902009-02-04 00:32:51 +00001908
John McCall0af3d3b2010-05-28 06:08:54 +00001909 break;
1910 }
1911
1912 // -- If T is a function type, its associated namespaces and
1913 // classes are those associated with the function parameter
1914 // types and those associated with the return type.
1915 case Type::FunctionProto: {
1916 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
1917 for (FunctionProtoType::arg_type_iterator Arg = Proto->arg_type_begin(),
1918 ArgEnd = Proto->arg_type_end();
1919 Arg != ArgEnd; ++Arg)
1920 Queue.push_back(Arg->getTypePtr());
1921 // fallthrough
1922 }
1923 case Type::FunctionNoProto: {
1924 const FunctionType *FnType = cast<FunctionType>(T);
1925 T = FnType->getResultType().getTypePtr();
1926 continue;
1927 }
1928
1929 // -- If T is a pointer to a member function of a class X, its
1930 // associated namespaces and classes are those associated
1931 // with the function parameter types and return type,
1932 // together with those associated with X.
1933 //
1934 // -- If T is a pointer to a data member of class X, its
1935 // associated namespaces and classes are those associated
1936 // with the member type together with those associated with
1937 // X.
1938 case Type::MemberPointer: {
1939 const MemberPointerType *MemberPtr = cast<MemberPointerType>(T);
1940
1941 // Queue up the class type into which this points.
1942 Queue.push_back(MemberPtr->getClass());
1943
1944 // And directly continue with the pointee type.
1945 T = MemberPtr->getPointeeType().getTypePtr();
1946 continue;
1947 }
1948
1949 // As an extension, treat this like a normal pointer.
1950 case Type::BlockPointer:
1951 T = cast<BlockPointerType>(T)->getPointeeType().getTypePtr();
1952 continue;
1953
1954 // References aren't covered by the standard, but that's such an
1955 // obvious defect that we cover them anyway.
1956 case Type::LValueReference:
1957 case Type::RValueReference:
1958 T = cast<ReferenceType>(T)->getPointeeType().getTypePtr();
1959 continue;
1960
1961 // These are fundamental types.
1962 case Type::Vector:
1963 case Type::ExtVector:
1964 case Type::Complex:
1965 break;
1966
1967 // These are ignored by ADL.
1968 case Type::ObjCObject:
1969 case Type::ObjCInterface:
1970 case Type::ObjCObjectPointer:
1971 break;
1972 }
1973
1974 if (Queue.empty()) break;
1975 T = Queue.back();
1976 Queue.pop_back();
Douglas Gregore254f902009-02-04 00:32:51 +00001977 }
Douglas Gregore254f902009-02-04 00:32:51 +00001978}
1979
1980/// \brief Find the associated classes and namespaces for
1981/// argument-dependent lookup for a call with the given set of
1982/// arguments.
1983///
1984/// This routine computes the sets of associated classes and associated
Mike Stump11289f42009-09-09 15:08:12 +00001985/// namespaces searched by argument-dependent lookup
Douglas Gregore254f902009-02-04 00:32:51 +00001986/// (C++ [basic.lookup.argdep]) for a given set of arguments.
Mike Stump11289f42009-09-09 15:08:12 +00001987void
Douglas Gregore254f902009-02-04 00:32:51 +00001988Sema::FindAssociatedClassesAndNamespaces(Expr **Args, unsigned NumArgs,
1989 AssociatedNamespaceSet &AssociatedNamespaces,
John McCallc7e8e792009-08-07 22:18:02 +00001990 AssociatedClassSet &AssociatedClasses) {
Douglas Gregore254f902009-02-04 00:32:51 +00001991 AssociatedNamespaces.clear();
1992 AssociatedClasses.clear();
1993
John McCallf24d7bb2010-05-28 18:45:08 +00001994 AssociatedLookup Result(*this, AssociatedNamespaces, AssociatedClasses);
1995
Douglas Gregore254f902009-02-04 00:32:51 +00001996 // C++ [basic.lookup.koenig]p2:
1997 // For each argument type T in the function call, there is a set
1998 // of zero or more associated namespaces and a set of zero or more
1999 // associated classes to be considered. The sets of namespaces and
2000 // classes is determined entirely by the types of the function
2001 // arguments (and the namespace of any template template
Mike Stump11289f42009-09-09 15:08:12 +00002002 // argument).
Douglas Gregore254f902009-02-04 00:32:51 +00002003 for (unsigned ArgIdx = 0; ArgIdx != NumArgs; ++ArgIdx) {
2004 Expr *Arg = Args[ArgIdx];
2005
2006 if (Arg->getType() != Context.OverloadTy) {
John McCallf24d7bb2010-05-28 18:45:08 +00002007 addAssociatedClassesAndNamespaces(Result, Arg->getType());
Douglas Gregore254f902009-02-04 00:32:51 +00002008 continue;
2009 }
2010
2011 // [...] In addition, if the argument is the name or address of a
2012 // set of overloaded functions and/or function templates, its
2013 // associated classes and namespaces are the union of those
2014 // associated with each of the members of the set: the namespace
2015 // in which the function or function template is defined and the
2016 // classes and namespaces associated with its (non-dependent)
2017 // parameter types and return type.
Douglas Gregorbe759252009-07-08 10:57:20 +00002018 Arg = Arg->IgnoreParens();
John McCalld14a8642009-11-21 08:51:07 +00002019 if (UnaryOperator *unaryOp = dyn_cast<UnaryOperator>(Arg))
John McCalle3027922010-08-25 11:45:40 +00002020 if (unaryOp->getOpcode() == UO_AddrOf)
John McCalld14a8642009-11-21 08:51:07 +00002021 Arg = unaryOp->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00002022
John McCallf24d7bb2010-05-28 18:45:08 +00002023 UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Arg);
2024 if (!ULE) continue;
John McCalld14a8642009-11-21 08:51:07 +00002025
John McCallf24d7bb2010-05-28 18:45:08 +00002026 for (UnresolvedSetIterator I = ULE->decls_begin(), E = ULE->decls_end();
2027 I != E; ++I) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00002028 // Look through any using declarations to find the underlying function.
2029 NamedDecl *Fn = (*I)->getUnderlyingDecl();
Douglas Gregore254f902009-02-04 00:32:51 +00002030
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00002031 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(Fn);
2032 if (!FDecl)
2033 FDecl = cast<FunctionTemplateDecl>(Fn)->getTemplatedDecl();
Douglas Gregore254f902009-02-04 00:32:51 +00002034
2035 // Add the classes and namespaces associated with the parameter
2036 // types and return type of this function.
John McCallf24d7bb2010-05-28 18:45:08 +00002037 addAssociatedClassesAndNamespaces(Result, FDecl->getType());
Douglas Gregore254f902009-02-04 00:32:51 +00002038 }
2039 }
2040}
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002041
2042/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
2043/// an acceptable non-member overloaded operator for a call whose
2044/// arguments have types T1 (and, if non-empty, T2). This routine
2045/// implements the check in C++ [over.match.oper]p3b2 concerning
2046/// enumeration types.
Mike Stump11289f42009-09-09 15:08:12 +00002047static bool
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002048IsAcceptableNonMemberOperatorCandidate(FunctionDecl *Fn,
2049 QualType T1, QualType T2,
2050 ASTContext &Context) {
Douglas Gregor0950e412009-03-13 21:01:28 +00002051 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
2052 return true;
2053
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002054 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
2055 return true;
2056
John McCall9dd450b2009-09-21 23:43:11 +00002057 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002058 if (Proto->getNumArgs() < 1)
2059 return false;
2060
2061 if (T1->isEnumeralType()) {
2062 QualType ArgType = Proto->getArgType(0).getNonReferenceType();
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002063 if (Context.hasSameUnqualifiedType(T1, ArgType))
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002064 return true;
2065 }
2066
2067 if (Proto->getNumArgs() < 2)
2068 return false;
2069
2070 if (!T2.isNull() && T2->isEnumeralType()) {
2071 QualType ArgType = Proto->getArgType(1).getNonReferenceType();
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002072 if (Context.hasSameUnqualifiedType(T2, ArgType))
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002073 return true;
2074 }
2075
2076 return false;
2077}
2078
John McCall5cebab12009-11-18 07:57:50 +00002079NamedDecl *Sema::LookupSingleName(Scope *S, DeclarationName Name,
Douglas Gregorb2ccf012010-04-15 22:33:43 +00002080 SourceLocation Loc,
John McCall5cebab12009-11-18 07:57:50 +00002081 LookupNameKind NameKind,
2082 RedeclarationKind Redecl) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +00002083 LookupResult R(*this, Name, Loc, NameKind, Redecl);
John McCall5cebab12009-11-18 07:57:50 +00002084 LookupName(R, S);
John McCall67c00872009-12-02 08:25:40 +00002085 return R.getAsSingle<NamedDecl>();
John McCall5cebab12009-11-18 07:57:50 +00002086}
2087
Douglas Gregorde9f17e2009-04-23 23:18:26 +00002088/// \brief Find the protocol with the given name, if any.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002089ObjCProtocolDecl *Sema::LookupProtocol(IdentifierInfo *II,
Douglas Gregorb2ccf012010-04-15 22:33:43 +00002090 SourceLocation IdLoc) {
2091 Decl *D = LookupSingleName(TUScope, II, IdLoc,
2092 LookupObjCProtocolName);
Douglas Gregorde9f17e2009-04-23 23:18:26 +00002093 return cast_or_null<ObjCProtocolDecl>(D);
2094}
2095
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002096void Sema::LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
Mike Stump11289f42009-09-09 15:08:12 +00002097 QualType T1, QualType T2,
John McCall4c4c1df2010-01-26 03:27:55 +00002098 UnresolvedSetImpl &Functions) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002099 // C++ [over.match.oper]p3:
2100 // -- The set of non-member candidates is the result of the
2101 // unqualified lookup of operator@ in the context of the
2102 // expression according to the usual rules for name lookup in
2103 // unqualified function calls (3.4.2) except that all member
2104 // functions are ignored. However, if no operand has a class
2105 // type, only those non-member functions in the lookup set
Eli Friedman44b83ee2009-08-05 19:21:58 +00002106 // that have a first parameter of type T1 or "reference to
2107 // (possibly cv-qualified) T1", when T1 is an enumeration
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002108 // type, or (if there is a right operand) a second parameter
Eli Friedman44b83ee2009-08-05 19:21:58 +00002109 // of type T2 or "reference to (possibly cv-qualified) T2",
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002110 // when T2 is an enumeration type, are candidate functions.
2111 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
John McCall27b18f82009-11-17 02:14:36 +00002112 LookupResult Operators(*this, OpName, SourceLocation(), LookupOperatorName);
2113 LookupName(Operators, S);
Mike Stump11289f42009-09-09 15:08:12 +00002114
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002115 assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
2116
John McCall9f3059a2009-10-09 21:13:30 +00002117 if (Operators.empty())
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002118 return;
2119
2120 for (LookupResult::iterator Op = Operators.begin(), OpEnd = Operators.end();
2121 Op != OpEnd; ++Op) {
Douglas Gregor645d76f2010-04-25 20:25:43 +00002122 NamedDecl *Found = (*Op)->getUnderlyingDecl();
2123 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Found)) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002124 if (IsAcceptableNonMemberOperatorCandidate(FD, T1, T2, Context))
Douglas Gregor645d76f2010-04-25 20:25:43 +00002125 Functions.addDecl(*Op, Op.getAccess()); // FIXME: canonical FD
Mike Stump11289f42009-09-09 15:08:12 +00002126 } else if (FunctionTemplateDecl *FunTmpl
Douglas Gregor645d76f2010-04-25 20:25:43 +00002127 = dyn_cast<FunctionTemplateDecl>(Found)) {
Douglas Gregor15448f82009-06-27 21:05:07 +00002128 // FIXME: friend operators?
Mike Stump11289f42009-09-09 15:08:12 +00002129 // FIXME: do we need to check IsAcceptableNonMemberOperatorCandidate,
Douglas Gregor15448f82009-06-27 21:05:07 +00002130 // later?
2131 if (!FunTmpl->getDeclContext()->isRecord())
Douglas Gregor645d76f2010-04-25 20:25:43 +00002132 Functions.addDecl(*Op, Op.getAccess());
Douglas Gregor15448f82009-06-27 21:05:07 +00002133 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002134 }
2135}
2136
Douglas Gregor52b72822010-07-02 23:12:18 +00002137/// \brief Look up the constructors for the given class.
2138DeclContext::lookup_result Sema::LookupConstructors(CXXRecordDecl *Class) {
Douglas Gregora6d69502010-07-02 23:41:54 +00002139 // If the copy constructor has not yet been declared, do so now.
Douglas Gregor9672f922010-07-03 00:47:00 +00002140 if (CanDeclareSpecialMemberFunction(Context, Class)) {
2141 if (!Class->hasDeclaredDefaultConstructor())
2142 DeclareImplicitDefaultConstructor(Class);
2143 if (!Class->hasDeclaredCopyConstructor())
2144 DeclareImplicitCopyConstructor(Class);
2145 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002146
Douglas Gregor52b72822010-07-02 23:12:18 +00002147 CanQualType T = Context.getCanonicalType(Context.getTypeDeclType(Class));
2148 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(T);
2149 return Class->lookup(Name);
2150}
2151
Douglas Gregore71edda2010-07-01 22:47:18 +00002152/// \brief Look for the destructor of the given class.
2153///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002154/// During semantic analysis, this routine should be used in lieu of
Douglas Gregore71edda2010-07-01 22:47:18 +00002155/// CXXRecordDecl::getDestructor().
2156///
2157/// \returns The destructor for this class.
2158CXXDestructorDecl *Sema::LookupDestructor(CXXRecordDecl *Class) {
Douglas Gregor7454c562010-07-02 20:37:36 +00002159 // If the destructor has not yet been declared, do so now.
2160 if (CanDeclareSpecialMemberFunction(Context, Class) &&
2161 !Class->hasDeclaredDestructor())
2162 DeclareImplicitDestructor(Class);
2163
Douglas Gregore71edda2010-07-01 22:47:18 +00002164 return Class->getDestructor();
2165}
2166
John McCall8fe68082010-01-26 07:16:45 +00002167void ADLResult::insert(NamedDecl *New) {
2168 NamedDecl *&Old = Decls[cast<NamedDecl>(New->getCanonicalDecl())];
2169
2170 // If we haven't yet seen a decl for this key, or the last decl
2171 // was exactly this one, we're done.
2172 if (Old == 0 || Old == New) {
2173 Old = New;
2174 return;
2175 }
2176
2177 // Otherwise, decide which is a more recent redeclaration.
2178 FunctionDecl *OldFD, *NewFD;
2179 if (isa<FunctionTemplateDecl>(New)) {
2180 OldFD = cast<FunctionTemplateDecl>(Old)->getTemplatedDecl();
2181 NewFD = cast<FunctionTemplateDecl>(New)->getTemplatedDecl();
2182 } else {
2183 OldFD = cast<FunctionDecl>(Old);
2184 NewFD = cast<FunctionDecl>(New);
2185 }
2186
2187 FunctionDecl *Cursor = NewFD;
2188 while (true) {
2189 Cursor = Cursor->getPreviousDeclaration();
2190
2191 // If we got to the end without finding OldFD, OldFD is the newer
2192 // declaration; leave things as they are.
2193 if (!Cursor) return;
2194
2195 // If we do find OldFD, then NewFD is newer.
2196 if (Cursor == OldFD) break;
2197
2198 // Otherwise, keep looking.
2199 }
2200
2201 Old = New;
2202}
2203
Sebastian Redlc057f422009-10-23 19:23:15 +00002204void Sema::ArgumentDependentLookup(DeclarationName Name, bool Operator,
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002205 Expr **Args, unsigned NumArgs,
John McCall8fe68082010-01-26 07:16:45 +00002206 ADLResult &Result) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002207 // Find all of the associated namespaces and classes based on the
2208 // arguments we have.
2209 AssociatedNamespaceSet AssociatedNamespaces;
2210 AssociatedClassSet AssociatedClasses;
Mike Stump11289f42009-09-09 15:08:12 +00002211 FindAssociatedClassesAndNamespaces(Args, NumArgs,
John McCallc7e8e792009-08-07 22:18:02 +00002212 AssociatedNamespaces,
2213 AssociatedClasses);
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002214
Sebastian Redlc057f422009-10-23 19:23:15 +00002215 QualType T1, T2;
2216 if (Operator) {
2217 T1 = Args[0]->getType();
2218 if (NumArgs >= 2)
2219 T2 = Args[1]->getType();
2220 }
2221
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002222 // C++ [basic.lookup.argdep]p3:
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002223 // Let X be the lookup set produced by unqualified lookup (3.4.1)
2224 // and let Y be the lookup set produced by argument dependent
2225 // lookup (defined as follows). If X contains [...] then Y is
2226 // empty. Otherwise Y is the set of declarations found in the
2227 // namespaces associated with the argument types as described
2228 // below. The set of declarations found by the lookup of the name
2229 // is the union of X and Y.
2230 //
2231 // Here, we compute Y and add its members to the overloaded
2232 // candidate set.
2233 for (AssociatedNamespaceSet::iterator NS = AssociatedNamespaces.begin(),
Mike Stump11289f42009-09-09 15:08:12 +00002234 NSEnd = AssociatedNamespaces.end();
2235 NS != NSEnd; ++NS) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002236 // When considering an associated namespace, the lookup is the
2237 // same as the lookup performed when the associated namespace is
2238 // used as a qualifier (3.4.3.2) except that:
2239 //
2240 // -- Any using-directives in the associated namespace are
2241 // ignored.
2242 //
John McCallc7e8e792009-08-07 22:18:02 +00002243 // -- Any namespace-scope friend functions declared in
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002244 // associated classes are visible within their respective
2245 // namespaces even if they are not visible during an ordinary
2246 // lookup (11.4).
2247 DeclContext::lookup_iterator I, E;
John McCalld1e9d832009-08-11 06:59:38 +00002248 for (llvm::tie(I, E) = (*NS)->lookup(Name); I != E; ++I) {
John McCall4c4c1df2010-01-26 03:27:55 +00002249 NamedDecl *D = *I;
John McCallaa74a0c2009-08-28 07:59:38 +00002250 // If the only declaration here is an ordinary friend, consider
2251 // it only if it was declared in an associated classes.
2252 if (D->getIdentifierNamespace() == Decl::IDNS_OrdinaryFriend) {
John McCalld1e9d832009-08-11 06:59:38 +00002253 DeclContext *LexDC = D->getLexicalDeclContext();
2254 if (!AssociatedClasses.count(cast<CXXRecordDecl>(LexDC)))
2255 continue;
2256 }
Mike Stump11289f42009-09-09 15:08:12 +00002257
John McCall91f61fc2010-01-26 06:04:06 +00002258 if (isa<UsingShadowDecl>(D))
2259 D = cast<UsingShadowDecl>(D)->getTargetDecl();
John McCall4c4c1df2010-01-26 03:27:55 +00002260
John McCall91f61fc2010-01-26 06:04:06 +00002261 if (isa<FunctionDecl>(D)) {
2262 if (Operator &&
2263 !IsAcceptableNonMemberOperatorCandidate(cast<FunctionDecl>(D),
2264 T1, T2, Context))
2265 continue;
John McCall8fe68082010-01-26 07:16:45 +00002266 } else if (!isa<FunctionTemplateDecl>(D))
2267 continue;
2268
2269 Result.insert(D);
Douglas Gregor6127ca42009-06-23 20:14:09 +00002270 }
2271 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002272}
Douglas Gregor2d435302009-12-30 17:04:44 +00002273
2274//----------------------------------------------------------------------------
2275// Search for all visible declarations.
2276//----------------------------------------------------------------------------
2277VisibleDeclConsumer::~VisibleDeclConsumer() { }
2278
2279namespace {
2280
2281class ShadowContextRAII;
2282
2283class VisibleDeclsRecord {
2284public:
2285 /// \brief An entry in the shadow map, which is optimized to store a
2286 /// single declaration (the common case) but can also store a list
2287 /// of declarations.
2288 class ShadowMapEntry {
2289 typedef llvm::SmallVector<NamedDecl *, 4> DeclVector;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002290
Douglas Gregor2d435302009-12-30 17:04:44 +00002291 /// \brief Contains either the solitary NamedDecl * or a vector
2292 /// of declarations.
2293 llvm::PointerUnion<NamedDecl *, DeclVector*> DeclOrVector;
2294
2295 public:
2296 ShadowMapEntry() : DeclOrVector() { }
2297
2298 void Add(NamedDecl *ND);
2299 void Destroy();
2300
2301 // Iteration.
Argyrios Kyrtzidis12f146a2011-02-19 04:02:34 +00002302 typedef NamedDecl * const *iterator;
Douglas Gregor2d435302009-12-30 17:04:44 +00002303 iterator begin();
2304 iterator end();
2305 };
2306
2307private:
2308 /// \brief A mapping from declaration names to the declarations that have
2309 /// this name within a particular scope.
2310 typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
2311
2312 /// \brief A list of shadow maps, which is used to model name hiding.
2313 std::list<ShadowMap> ShadowMaps;
2314
2315 /// \brief The declaration contexts we have already visited.
2316 llvm::SmallPtrSet<DeclContext *, 8> VisitedContexts;
2317
2318 friend class ShadowContextRAII;
2319
2320public:
2321 /// \brief Determine whether we have already visited this context
2322 /// (and, if not, note that we are going to visit that context now).
2323 bool visitedContext(DeclContext *Ctx) {
2324 return !VisitedContexts.insert(Ctx);
2325 }
2326
Douglas Gregor39982192010-08-15 06:18:01 +00002327 bool alreadyVisitedContext(DeclContext *Ctx) {
2328 return VisitedContexts.count(Ctx);
2329 }
2330
Douglas Gregor2d435302009-12-30 17:04:44 +00002331 /// \brief Determine whether the given declaration is hidden in the
2332 /// current scope.
2333 ///
2334 /// \returns the declaration that hides the given declaration, or
2335 /// NULL if no such declaration exists.
2336 NamedDecl *checkHidden(NamedDecl *ND);
2337
2338 /// \brief Add a declaration to the current shadow map.
2339 void add(NamedDecl *ND) { ShadowMaps.back()[ND->getDeclName()].Add(ND); }
2340};
2341
2342/// \brief RAII object that records when we've entered a shadow context.
2343class ShadowContextRAII {
2344 VisibleDeclsRecord &Visible;
2345
2346 typedef VisibleDeclsRecord::ShadowMap ShadowMap;
2347
2348public:
2349 ShadowContextRAII(VisibleDeclsRecord &Visible) : Visible(Visible) {
2350 Visible.ShadowMaps.push_back(ShadowMap());
2351 }
2352
2353 ~ShadowContextRAII() {
2354 for (ShadowMap::iterator E = Visible.ShadowMaps.back().begin(),
2355 EEnd = Visible.ShadowMaps.back().end();
2356 E != EEnd;
2357 ++E)
2358 E->second.Destroy();
2359
2360 Visible.ShadowMaps.pop_back();
2361 }
2362};
2363
2364} // end anonymous namespace
2365
2366void VisibleDeclsRecord::ShadowMapEntry::Add(NamedDecl *ND) {
2367 if (DeclOrVector.isNull()) {
2368 // 0 - > 1 elements: just set the single element information.
2369 DeclOrVector = ND;
2370 return;
2371 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002372
Douglas Gregor2d435302009-12-30 17:04:44 +00002373 if (NamedDecl *PrevND = DeclOrVector.dyn_cast<NamedDecl *>()) {
2374 // 1 -> 2 elements: create the vector of results and push in the
2375 // existing declaration.
2376 DeclVector *Vec = new DeclVector;
2377 Vec->push_back(PrevND);
2378 DeclOrVector = Vec;
2379 }
2380
2381 // Add the new element to the end of the vector.
2382 DeclOrVector.get<DeclVector*>()->push_back(ND);
2383}
2384
2385void VisibleDeclsRecord::ShadowMapEntry::Destroy() {
2386 if (DeclVector *Vec = DeclOrVector.dyn_cast<DeclVector *>()) {
2387 delete Vec;
2388 DeclOrVector = ((NamedDecl *)0);
2389 }
2390}
2391
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002392VisibleDeclsRecord::ShadowMapEntry::iterator
Douglas Gregor2d435302009-12-30 17:04:44 +00002393VisibleDeclsRecord::ShadowMapEntry::begin() {
2394 if (DeclOrVector.isNull())
2395 return 0;
2396
Argyrios Kyrtzidis12f146a2011-02-19 04:02:34 +00002397 if (DeclOrVector.is<NamedDecl *>())
2398 return DeclOrVector.getAddrOf<NamedDecl *>();
Douglas Gregor2d435302009-12-30 17:04:44 +00002399
2400 return DeclOrVector.get<DeclVector *>()->begin();
2401}
2402
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002403VisibleDeclsRecord::ShadowMapEntry::iterator
Douglas Gregor2d435302009-12-30 17:04:44 +00002404VisibleDeclsRecord::ShadowMapEntry::end() {
2405 if (DeclOrVector.isNull())
2406 return 0;
2407
2408 if (DeclOrVector.dyn_cast<NamedDecl *>())
2409 return &reinterpret_cast<NamedDecl*&>(DeclOrVector) + 1;
2410
2411 return DeclOrVector.get<DeclVector *>()->end();
2412}
2413
2414NamedDecl *VisibleDeclsRecord::checkHidden(NamedDecl *ND) {
Douglas Gregor0235c422010-01-14 00:06:47 +00002415 // Look through using declarations.
2416 ND = ND->getUnderlyingDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002417
Douglas Gregor2d435302009-12-30 17:04:44 +00002418 unsigned IDNS = ND->getIdentifierNamespace();
2419 std::list<ShadowMap>::reverse_iterator SM = ShadowMaps.rbegin();
2420 for (std::list<ShadowMap>::reverse_iterator SMEnd = ShadowMaps.rend();
2421 SM != SMEnd; ++SM) {
2422 ShadowMap::iterator Pos = SM->find(ND->getDeclName());
2423 if (Pos == SM->end())
2424 continue;
2425
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002426 for (ShadowMapEntry::iterator I = Pos->second.begin(),
Douglas Gregor2d435302009-12-30 17:04:44 +00002427 IEnd = Pos->second.end();
2428 I != IEnd; ++I) {
2429 // A tag declaration does not hide a non-tag declaration.
John McCalle87beb22010-04-23 18:46:30 +00002430 if ((*I)->hasTagIdentifierNamespace() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002431 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
Douglas Gregor2d435302009-12-30 17:04:44 +00002432 Decl::IDNS_ObjCProtocol)))
2433 continue;
2434
2435 // Protocols are in distinct namespaces from everything else.
2436 if ((((*I)->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
2437 || (IDNS & Decl::IDNS_ObjCProtocol)) &&
2438 (*I)->getIdentifierNamespace() != IDNS)
2439 continue;
2440
Douglas Gregor09bbc652010-01-14 15:47:35 +00002441 // Functions and function templates in the same scope overload
2442 // rather than hide. FIXME: Look for hiding based on function
2443 // signatures!
Douglas Gregor200c99d2010-01-14 03:35:48 +00002444 if ((*I)->isFunctionOrFunctionTemplate() &&
Douglas Gregor09bbc652010-01-14 15:47:35 +00002445 ND->isFunctionOrFunctionTemplate() &&
2446 SM == ShadowMaps.rbegin())
Douglas Gregor200c99d2010-01-14 03:35:48 +00002447 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002448
Douglas Gregor2d435302009-12-30 17:04:44 +00002449 // We've found a declaration that hides this one.
2450 return *I;
2451 }
2452 }
2453
2454 return 0;
2455}
2456
2457static void LookupVisibleDecls(DeclContext *Ctx, LookupResult &Result,
2458 bool QualifiedNameLookup,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002459 bool InBaseClass,
Douglas Gregor2d435302009-12-30 17:04:44 +00002460 VisibleDeclConsumer &Consumer,
2461 VisibleDeclsRecord &Visited) {
Douglas Gregor0c8a1722010-02-04 23:42:48 +00002462 if (!Ctx)
2463 return;
2464
Douglas Gregor2d435302009-12-30 17:04:44 +00002465 // Make sure we don't visit the same context twice.
2466 if (Visited.visitedContext(Ctx->getPrimaryContext()))
2467 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002468
Douglas Gregor7454c562010-07-02 20:37:36 +00002469 if (CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(Ctx))
2470 Result.getSema().ForceDeclarationOfImplicitMembers(Class);
2471
Douglas Gregor2d435302009-12-30 17:04:44 +00002472 // Enumerate all of the results in this context.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002473 for (DeclContext *CurCtx = Ctx->getPrimaryContext(); CurCtx;
Douglas Gregor2d435302009-12-30 17:04:44 +00002474 CurCtx = CurCtx->getNextContext()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002475 for (DeclContext::decl_iterator D = CurCtx->decls_begin(),
Douglas Gregor2d435302009-12-30 17:04:44 +00002476 DEnd = CurCtx->decls_end();
2477 D != DEnd; ++D) {
Douglas Gregora3b23b02010-12-09 21:44:02 +00002478 if (NamedDecl *ND = dyn_cast<NamedDecl>(*D)) {
Douglas Gregor2d435302009-12-30 17:04:44 +00002479 if (Result.isAcceptableDecl(ND)) {
Douglas Gregor09bbc652010-01-14 15:47:35 +00002480 Consumer.FoundDecl(ND, Visited.checkHidden(ND), InBaseClass);
Douglas Gregor2d435302009-12-30 17:04:44 +00002481 Visited.add(ND);
2482 }
Douglas Gregora3b23b02010-12-09 21:44:02 +00002483 } else if (ObjCForwardProtocolDecl *ForwardProto
2484 = dyn_cast<ObjCForwardProtocolDecl>(*D)) {
2485 for (ObjCForwardProtocolDecl::protocol_iterator
2486 P = ForwardProto->protocol_begin(),
2487 PEnd = ForwardProto->protocol_end();
2488 P != PEnd;
2489 ++P) {
2490 if (Result.isAcceptableDecl(*P)) {
2491 Consumer.FoundDecl(*P, Visited.checkHidden(*P), InBaseClass);
2492 Visited.add(*P);
2493 }
2494 }
Douglas Gregor04246572011-02-16 01:39:26 +00002495 } else if (ObjCClassDecl *Class = dyn_cast<ObjCClassDecl>(*D)) {
2496 for (ObjCClassDecl::iterator I = Class->begin(), IEnd = Class->end();
2497 I != IEnd; ++I) {
2498 ObjCInterfaceDecl *IFace = I->getInterface();
2499 if (Result.isAcceptableDecl(IFace)) {
2500 Consumer.FoundDecl(IFace, Visited.checkHidden(IFace), InBaseClass);
2501 Visited.add(IFace);
2502 }
2503 }
Douglas Gregora3b23b02010-12-09 21:44:02 +00002504 }
Douglas Gregor04246572011-02-16 01:39:26 +00002505
Sebastian Redlbd595762010-08-31 20:53:31 +00002506 // Visit transparent contexts and inline namespaces inside this context.
Douglas Gregor2d435302009-12-30 17:04:44 +00002507 if (DeclContext *InnerCtx = dyn_cast<DeclContext>(*D)) {
Sebastian Redlbd595762010-08-31 20:53:31 +00002508 if (InnerCtx->isTransparentContext() || InnerCtx->isInlineNamespace())
Douglas Gregor09bbc652010-01-14 15:47:35 +00002509 LookupVisibleDecls(InnerCtx, Result, QualifiedNameLookup, InBaseClass,
Douglas Gregor2d435302009-12-30 17:04:44 +00002510 Consumer, Visited);
2511 }
2512 }
2513 }
2514
2515 // Traverse using directives for qualified name lookup.
2516 if (QualifiedNameLookup) {
2517 ShadowContextRAII Shadow(Visited);
2518 DeclContext::udir_iterator I, E;
2519 for (llvm::tie(I, E) = Ctx->getUsingDirectives(); I != E; ++I) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002520 LookupVisibleDecls((*I)->getNominatedNamespace(), Result,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002521 QualifiedNameLookup, InBaseClass, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00002522 }
2523 }
2524
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002525 // Traverse the contexts of inherited C++ classes.
Douglas Gregor2d435302009-12-30 17:04:44 +00002526 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) {
John McCall67da35c2010-02-04 22:26:26 +00002527 if (!Record->hasDefinition())
2528 return;
2529
Douglas Gregor2d435302009-12-30 17:04:44 +00002530 for (CXXRecordDecl::base_class_iterator B = Record->bases_begin(),
2531 BEnd = Record->bases_end();
2532 B != BEnd; ++B) {
2533 QualType BaseType = B->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002534
Douglas Gregor2d435302009-12-30 17:04:44 +00002535 // Don't look into dependent bases, because name lookup can't look
2536 // there anyway.
2537 if (BaseType->isDependentType())
2538 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002539
Douglas Gregor2d435302009-12-30 17:04:44 +00002540 const RecordType *Record = BaseType->getAs<RecordType>();
2541 if (!Record)
2542 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002543
Douglas Gregor2d435302009-12-30 17:04:44 +00002544 // FIXME: It would be nice to be able to determine whether referencing
2545 // a particular member would be ambiguous. For example, given
2546 //
2547 // struct A { int member; };
2548 // struct B { int member; };
2549 // struct C : A, B { };
2550 //
2551 // void f(C *c) { c->### }
2552 //
2553 // accessing 'member' would result in an ambiguity. However, we
2554 // could be smart enough to qualify the member with the base
2555 // class, e.g.,
2556 //
2557 // c->B::member
2558 //
2559 // or
2560 //
2561 // c->A::member
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002562
Douglas Gregor2d435302009-12-30 17:04:44 +00002563 // Find results in this base class (and its bases).
2564 ShadowContextRAII Shadow(Visited);
2565 LookupVisibleDecls(Record->getDecl(), Result, QualifiedNameLookup,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002566 true, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00002567 }
2568 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002569
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002570 // Traverse the contexts of Objective-C classes.
2571 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Ctx)) {
2572 // Traverse categories.
2573 for (ObjCCategoryDecl *Category = IFace->getCategoryList();
2574 Category; Category = Category->getNextClassCategory()) {
2575 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002576 LookupVisibleDecls(Category, Result, QualifiedNameLookup, false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002577 Consumer, Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002578 }
2579
2580 // Traverse protocols.
Ted Kremenek0ef508d2010-09-01 01:21:15 +00002581 for (ObjCInterfaceDecl::all_protocol_iterator
2582 I = IFace->all_referenced_protocol_begin(),
2583 E = IFace->all_referenced_protocol_end(); I != E; ++I) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002584 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002585 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002586 Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002587 }
2588
2589 // Traverse the superclass.
2590 if (IFace->getSuperClass()) {
2591 ShadowContextRAII Shadow(Visited);
2592 LookupVisibleDecls(IFace->getSuperClass(), Result, QualifiedNameLookup,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002593 true, Consumer, Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002594 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002595
Douglas Gregor0b59e802010-04-19 18:02:19 +00002596 // If there is an implementation, traverse it. We do this to find
2597 // synthesized ivars.
2598 if (IFace->getImplementation()) {
2599 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002600 LookupVisibleDecls(IFace->getImplementation(), Result,
Douglas Gregor0b59e802010-04-19 18:02:19 +00002601 QualifiedNameLookup, true, Consumer, Visited);
2602 }
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002603 } else if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Ctx)) {
2604 for (ObjCProtocolDecl::protocol_iterator I = Protocol->protocol_begin(),
2605 E = Protocol->protocol_end(); I != E; ++I) {
2606 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002607 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002608 Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002609 }
2610 } else if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Ctx)) {
2611 for (ObjCCategoryDecl::protocol_iterator I = Category->protocol_begin(),
2612 E = Category->protocol_end(); I != E; ++I) {
2613 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002614 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002615 Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002616 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002617
Douglas Gregor0b59e802010-04-19 18:02:19 +00002618 // If there is an implementation, traverse it.
2619 if (Category->getImplementation()) {
2620 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002621 LookupVisibleDecls(Category->getImplementation(), Result,
Douglas Gregor0b59e802010-04-19 18:02:19 +00002622 QualifiedNameLookup, true, Consumer, Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002623 }
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002624 }
Douglas Gregor2d435302009-12-30 17:04:44 +00002625}
2626
2627static void LookupVisibleDecls(Scope *S, LookupResult &Result,
2628 UnqualUsingDirectiveSet &UDirs,
2629 VisibleDeclConsumer &Consumer,
2630 VisibleDeclsRecord &Visited) {
2631 if (!S)
2632 return;
2633
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002634 if (!S->getEntity() ||
2635 (!S->getParent() &&
Douglas Gregor39982192010-08-15 06:18:01 +00002636 !Visited.alreadyVisitedContext((DeclContext *)S->getEntity())) ||
Douglas Gregor712dcfe2010-01-07 00:31:29 +00002637 ((DeclContext *)S->getEntity())->isFunctionOrMethod()) {
2638 // Walk through the declarations in this Scope.
2639 for (Scope::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
2640 D != DEnd; ++D) {
John McCall48871652010-08-21 09:40:31 +00002641 if (NamedDecl *ND = dyn_cast<NamedDecl>(*D))
Douglas Gregor712dcfe2010-01-07 00:31:29 +00002642 if (Result.isAcceptableDecl(ND)) {
Douglas Gregor09bbc652010-01-14 15:47:35 +00002643 Consumer.FoundDecl(ND, Visited.checkHidden(ND), false);
Douglas Gregor712dcfe2010-01-07 00:31:29 +00002644 Visited.add(ND);
2645 }
2646 }
2647 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002648
Douglas Gregor66230062010-03-15 14:33:29 +00002649 // FIXME: C++ [temp.local]p8
Douglas Gregor2d435302009-12-30 17:04:44 +00002650 DeclContext *Entity = 0;
Douglas Gregor4f248632010-01-01 17:44:25 +00002651 if (S->getEntity()) {
Douglas Gregor2d435302009-12-30 17:04:44 +00002652 // Look into this scope's declaration context, along with any of its
2653 // parent lookup contexts (e.g., enclosing classes), up to the point
2654 // where we hit the context stored in the next outer scope.
2655 Entity = (DeclContext *)S->getEntity();
Douglas Gregor66230062010-03-15 14:33:29 +00002656 DeclContext *OuterCtx = findOuterContext(S).first; // FIXME
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002657
Douglas Gregorea166062010-03-15 15:26:48 +00002658 for (DeclContext *Ctx = Entity; Ctx && !Ctx->Equals(OuterCtx);
Douglas Gregor2d435302009-12-30 17:04:44 +00002659 Ctx = Ctx->getLookupParent()) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002660 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
2661 if (Method->isInstanceMethod()) {
2662 // For instance methods, look for ivars in the method's interface.
2663 LookupResult IvarResult(Result.getSema(), Result.getLookupName(),
2664 Result.getNameLoc(), Sema::LookupMemberName);
Douglas Gregor05fcf842010-11-02 20:36:02 +00002665 if (ObjCInterfaceDecl *IFace = Method->getClassInterface()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002666 LookupVisibleDecls(IFace, IvarResult, /*QualifiedNameLookup=*/false,
Douglas Gregor0c8a1722010-02-04 23:42:48 +00002667 /*InBaseClass=*/false, Consumer, Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002668
Douglas Gregor05fcf842010-11-02 20:36:02 +00002669 // Look for properties from which we can synthesize ivars, if
2670 // permitted.
2671 if (Result.getSema().getLangOptions().ObjCNonFragileABI2 &&
2672 IFace->getImplementation() &&
2673 Result.getLookupKind() == Sema::LookupOrdinaryName) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002674 for (ObjCInterfaceDecl::prop_iterator
Douglas Gregor05fcf842010-11-02 20:36:02 +00002675 P = IFace->prop_begin(),
2676 PEnd = IFace->prop_end();
2677 P != PEnd; ++P) {
2678 if (Result.getSema().canSynthesizeProvisionalIvar(*P) &&
2679 !IFace->lookupInstanceVariable((*P)->getIdentifier())) {
2680 Consumer.FoundDecl(*P, Visited.checkHidden(*P), false);
2681 Visited.add(*P);
2682 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002683 }
2684 }
Douglas Gregor05fcf842010-11-02 20:36:02 +00002685 }
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002686 }
2687
2688 // We've already performed all of the name lookup that we need
2689 // to for Objective-C methods; the next context will be the
2690 // outer scope.
2691 break;
2692 }
2693
Douglas Gregor2d435302009-12-30 17:04:44 +00002694 if (Ctx->isFunctionOrMethod())
2695 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002696
2697 LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002698 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00002699 }
2700 } else if (!S->getParent()) {
2701 // Look into the translation unit scope. We walk through the translation
2702 // unit's declaration context, because the Scope itself won't have all of
2703 // the declarations if we loaded a precompiled header.
2704 // FIXME: We would like the translation unit's Scope object to point to the
2705 // translation unit, so we don't need this special "if" branch. However,
2706 // doing so would force the normal C++ name-lookup code to look into the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002707 // translation unit decl when the IdentifierInfo chains would suffice.
Douglas Gregor2d435302009-12-30 17:04:44 +00002708 // Once we fix that problem (which is part of a more general "don't look
Douglas Gregor712dcfe2010-01-07 00:31:29 +00002709 // in DeclContexts unless we have to" optimization), we can eliminate this.
Douglas Gregor2d435302009-12-30 17:04:44 +00002710 Entity = Result.getSema().Context.getTranslationUnitDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002711 LookupVisibleDecls(Entity, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002712 /*InBaseClass=*/false, Consumer, Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002713 }
2714
Douglas Gregor2d435302009-12-30 17:04:44 +00002715 if (Entity) {
2716 // Lookup visible declarations in any namespaces found by using
2717 // directives.
2718 UnqualUsingDirectiveSet::const_iterator UI, UEnd;
2719 llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(Entity);
2720 for (; UI != UEnd; ++UI)
2721 LookupVisibleDecls(const_cast<DeclContext *>(UI->getNominatedNamespace()),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002722 Result, /*QualifiedNameLookup=*/false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002723 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00002724 }
2725
2726 // Lookup names in the parent scope.
2727 ShadowContextRAII Shadow(Visited);
2728 LookupVisibleDecls(S->getParent(), Result, UDirs, Consumer, Visited);
2729}
2730
2731void Sema::LookupVisibleDecls(Scope *S, LookupNameKind Kind,
Douglas Gregor39982192010-08-15 06:18:01 +00002732 VisibleDeclConsumer &Consumer,
2733 bool IncludeGlobalScope) {
Douglas Gregor2d435302009-12-30 17:04:44 +00002734 // Determine the set of using directives available during
2735 // unqualified name lookup.
2736 Scope *Initial = S;
2737 UnqualUsingDirectiveSet UDirs;
2738 if (getLangOptions().CPlusPlus) {
2739 // Find the first namespace or translation-unit scope.
2740 while (S && !isNamespaceOrTranslationUnitScope(S))
2741 S = S->getParent();
2742
2743 UDirs.visitScopeChain(Initial, S);
2744 }
2745 UDirs.done();
2746
2747 // Look for visible declarations.
2748 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
2749 VisibleDeclsRecord Visited;
Douglas Gregor39982192010-08-15 06:18:01 +00002750 if (!IncludeGlobalScope)
2751 Visited.visitedContext(Context.getTranslationUnitDecl());
Douglas Gregor2d435302009-12-30 17:04:44 +00002752 ShadowContextRAII Shadow(Visited);
2753 ::LookupVisibleDecls(Initial, Result, UDirs, Consumer, Visited);
2754}
2755
2756void Sema::LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
Douglas Gregor39982192010-08-15 06:18:01 +00002757 VisibleDeclConsumer &Consumer,
2758 bool IncludeGlobalScope) {
Douglas Gregor2d435302009-12-30 17:04:44 +00002759 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
2760 VisibleDeclsRecord Visited;
Douglas Gregor39982192010-08-15 06:18:01 +00002761 if (!IncludeGlobalScope)
2762 Visited.visitedContext(Context.getTranslationUnitDecl());
Douglas Gregor2d435302009-12-30 17:04:44 +00002763 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002764 ::LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/true,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002765 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00002766}
2767
Chris Lattner43e7f312011-02-18 02:08:43 +00002768/// LookupOrCreateLabel - Do a name lookup of a label with the specified name.
Abramo Bagnara1c3af962011-03-05 18:21:20 +00002769/// If GnuLabelLoc is a valid source location, then this is a definition
2770/// of an __label__ label name, otherwise it is a normal label definition
2771/// or use.
Chris Lattner43e7f312011-02-18 02:08:43 +00002772LabelDecl *Sema::LookupOrCreateLabel(IdentifierInfo *II, SourceLocation Loc,
Abramo Bagnara1c3af962011-03-05 18:21:20 +00002773 SourceLocation GnuLabelLoc) {
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00002774 // Do a lookup to see if we have a label with this name already.
Chris Lattner43e7f312011-02-18 02:08:43 +00002775 NamedDecl *Res = 0;
Abramo Bagnara1c3af962011-03-05 18:21:20 +00002776
2777 if (GnuLabelLoc.isValid()) {
2778 // Local label definitions always shadow existing labels.
2779 Res = LabelDecl::Create(Context, CurContext, Loc, II, GnuLabelLoc);
2780 Scope *S = CurScope;
2781 PushOnScopeChains(Res, S, true);
2782 return cast<LabelDecl>(Res);
2783 }
2784
2785 // Not a GNU local label.
2786 Res = LookupSingleName(CurScope, II, Loc, LookupLabel, NotForRedeclaration);
2787 // If we found a label, check to see if it is in the same context as us.
2788 // When in a Block, we don't want to reuse a label in an enclosing function.
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00002789 if (Res && Res->getDeclContext() != CurContext)
2790 Res = 0;
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00002791 if (Res == 0) {
2792 // If not forward referenced or defined already, create the backing decl.
Abramo Bagnara1c3af962011-03-05 18:21:20 +00002793 Res = LabelDecl::Create(Context, CurContext, Loc, II);
2794 Scope *S = CurScope->getFnParent();
Chris Lattner9ba479b2011-02-18 21:16:39 +00002795 assert(S && "Not in a function?");
2796 PushOnScopeChains(Res, S, true);
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00002797 }
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00002798 return cast<LabelDecl>(Res);
2799}
2800
2801//===----------------------------------------------------------------------===//
Douglas Gregor2d435302009-12-30 17:04:44 +00002802// Typo correction
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00002803//===----------------------------------------------------------------------===//
Douglas Gregor2d435302009-12-30 17:04:44 +00002804
2805namespace {
2806class TypoCorrectionConsumer : public VisibleDeclConsumer {
2807 /// \brief The name written that is a typo in the source.
2808 llvm::StringRef Typo;
2809
2810 /// \brief The results found that have the smallest edit distance
2811 /// found (so far) with the typo name.
Douglas Gregor0afa7f62010-10-14 20:34:08 +00002812 ///
2813 /// The boolean value indicates whether there is a keyword with this name.
2814 llvm::StringMap<bool, llvm::BumpPtrAllocator> BestResults;
Douglas Gregor2d435302009-12-30 17:04:44 +00002815
2816 /// \brief The best edit distance found so far.
2817 unsigned BestEditDistance;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002818
Douglas Gregor2d435302009-12-30 17:04:44 +00002819public:
2820 explicit TypoCorrectionConsumer(IdentifierInfo *Typo)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002821 : Typo(Typo->getName()),
Douglas Gregor0afa7f62010-10-14 20:34:08 +00002822 BestEditDistance((std::numeric_limits<unsigned>::max)()) { }
Douglas Gregor2d435302009-12-30 17:04:44 +00002823
Douglas Gregor09bbc652010-01-14 15:47:35 +00002824 virtual void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, bool InBaseClass);
Douglas Gregor57756ea2010-10-14 22:11:03 +00002825 void FoundName(llvm::StringRef Name);
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002826 void addKeywordResult(ASTContext &Context, llvm::StringRef Keyword);
Douglas Gregor2d435302009-12-30 17:04:44 +00002827
Douglas Gregor0afa7f62010-10-14 20:34:08 +00002828 typedef llvm::StringMap<bool, llvm::BumpPtrAllocator>::iterator iterator;
2829 iterator begin() { return BestResults.begin(); }
2830 iterator end() { return BestResults.end(); }
2831 void erase(iterator I) { BestResults.erase(I); }
2832 unsigned size() const { return BestResults.size(); }
2833 bool empty() const { return BestResults.empty(); }
Douglas Gregor2d435302009-12-30 17:04:44 +00002834
Douglas Gregoraf9eb592010-10-15 13:35:25 +00002835 bool &operator[](llvm::StringRef Name) {
2836 return BestResults[Name];
2837 }
2838
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002839 unsigned getBestEditDistance() const { return BestEditDistance; }
Douglas Gregor2d435302009-12-30 17:04:44 +00002840};
2841
2842}
2843
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002844void TypoCorrectionConsumer::FoundDecl(NamedDecl *ND, NamedDecl *Hiding,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002845 bool InBaseClass) {
Douglas Gregor2d435302009-12-30 17:04:44 +00002846 // Don't consider hidden names for typo correction.
2847 if (Hiding)
2848 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002849
Douglas Gregor2d435302009-12-30 17:04:44 +00002850 // Only consider entities with identifiers for names, ignoring
2851 // special names (constructors, overloaded operators, selectors,
2852 // etc.).
2853 IdentifierInfo *Name = ND->getIdentifier();
2854 if (!Name)
2855 return;
2856
Douglas Gregor57756ea2010-10-14 22:11:03 +00002857 FoundName(Name->getName());
2858}
2859
2860void TypoCorrectionConsumer::FoundName(llvm::StringRef Name) {
Douglas Gregorc1fb15e2010-10-19 22:14:33 +00002861 using namespace std;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002862
Douglas Gregor93910a52010-10-19 19:39:10 +00002863 // Use a simple length-based heuristic to determine the minimum possible
2864 // edit distance. If the minimum isn't good enough, bail out early.
2865 unsigned MinED = abs((int)Name.size() - (int)Typo.size());
2866 if (MinED > BestEditDistance || (MinED && Typo.size() / MinED < 3))
2867 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002868
Douglas Gregorc1fb15e2010-10-19 22:14:33 +00002869 // Compute an upper bound on the allowable edit distance, so that the
2870 // edit-distance algorithm can short-circuit.
2871 unsigned UpperBound = min(unsigned((Typo.size() + 2) / 3), BestEditDistance);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002872
Douglas Gregor2d435302009-12-30 17:04:44 +00002873 // Compute the edit distance between the typo and the name of this
2874 // entity. If this edit distance is not worse than the best edit
2875 // distance we've seen so far, add it to the list of results.
Douglas Gregorc1fb15e2010-10-19 22:14:33 +00002876 unsigned ED = Typo.edit_distance(Name, true, UpperBound);
Douglas Gregor57756ea2010-10-14 22:11:03 +00002877 if (ED == 0)
2878 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002879
Douglas Gregor0afa7f62010-10-14 20:34:08 +00002880 if (ED < BestEditDistance) {
2881 // This result is better than any we've seen before; clear out
2882 // the previous results.
2883 BestResults.clear();
Douglas Gregor2d435302009-12-30 17:04:44 +00002884 BestEditDistance = ED;
Douglas Gregor0afa7f62010-10-14 20:34:08 +00002885 } else if (ED > BestEditDistance) {
2886 // This result is worse than the best results we've seen so far;
2887 // ignore it.
2888 return;
2889 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002890
Douglas Gregor0afa7f62010-10-14 20:34:08 +00002891 // Add this name to the list of results. By not assigning a value, we
2892 // keep the current value if we've seen this name before (either as a
2893 // keyword or as a declaration), or get the default value (not a keyword)
2894 // if we haven't seen it before.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002895 (void)BestResults[Name];
Douglas Gregor2d435302009-12-30 17:04:44 +00002896}
2897
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002898void TypoCorrectionConsumer::addKeywordResult(ASTContext &Context,
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002899 llvm::StringRef Keyword) {
2900 // Compute the edit distance between the typo and this keyword.
2901 // If this edit distance is not worse than the best edit
2902 // distance we've seen so far, add it to the list of results.
2903 unsigned ED = Typo.edit_distance(Keyword);
Douglas Gregor0afa7f62010-10-14 20:34:08 +00002904 if (ED < BestEditDistance) {
2905 BestResults.clear();
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002906 BestEditDistance = ED;
Douglas Gregor0afa7f62010-10-14 20:34:08 +00002907 } else if (ED > BestEditDistance) {
2908 // This result is worse than the best results we've seen so far;
2909 // ignore it.
2910 return;
2911 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002912
Douglas Gregor0afa7f62010-10-14 20:34:08 +00002913 BestResults[Keyword] = true;
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002914}
2915
Douglas Gregord507d772010-10-20 03:06:34 +00002916/// \brief Perform name lookup for a possible result for typo correction.
2917static void LookupPotentialTypoResult(Sema &SemaRef,
2918 LookupResult &Res,
2919 IdentifierInfo *Name,
2920 Scope *S, CXXScopeSpec *SS,
2921 DeclContext *MemberContext,
2922 bool EnteringContext,
2923 Sema::CorrectTypoContext CTC) {
2924 Res.suppressDiagnostics();
2925 Res.clear();
2926 Res.setLookupName(Name);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002927 if (MemberContext) {
Douglas Gregord507d772010-10-20 03:06:34 +00002928 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(MemberContext)) {
2929 if (CTC == Sema::CTC_ObjCIvarLookup) {
2930 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(Name)) {
2931 Res.addDecl(Ivar);
2932 Res.resolveKind();
2933 return;
2934 }
2935 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002936
Douglas Gregord507d772010-10-20 03:06:34 +00002937 if (ObjCPropertyDecl *Prop = Class->FindPropertyDeclaration(Name)) {
2938 Res.addDecl(Prop);
2939 Res.resolveKind();
2940 return;
2941 }
2942 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002943
Douglas Gregord507d772010-10-20 03:06:34 +00002944 SemaRef.LookupQualifiedName(Res, MemberContext);
2945 return;
2946 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002947
2948 SemaRef.LookupParsedName(Res, S, SS, /*AllowBuiltinCreation=*/false,
Douglas Gregord507d772010-10-20 03:06:34 +00002949 EnteringContext);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002950
Douglas Gregord507d772010-10-20 03:06:34 +00002951 // Fake ivar lookup; this should really be part of
2952 // LookupParsedName.
2953 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) {
2954 if (Method->isInstanceMethod() && Method->getClassInterface() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002955 (Res.empty() ||
Douglas Gregord507d772010-10-20 03:06:34 +00002956 (Res.isSingleResult() &&
2957 Res.getFoundDecl()->isDefinedOutsideFunctionOrMethod()))) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002958 if (ObjCIvarDecl *IV
Douglas Gregord507d772010-10-20 03:06:34 +00002959 = Method->getClassInterface()->lookupInstanceVariable(Name)) {
2960 Res.addDecl(IV);
2961 Res.resolveKind();
2962 }
2963 }
2964 }
2965}
2966
Douglas Gregor2d435302009-12-30 17:04:44 +00002967/// \brief Try to "correct" a typo in the source code by finding
2968/// visible declarations whose names are similar to the name that was
2969/// present in the source code.
2970///
2971/// \param Res the \c LookupResult structure that contains the name
2972/// that was present in the source code along with the name-lookup
2973/// criteria used to search for the name. On success, this structure
2974/// will contain the results of name lookup.
2975///
2976/// \param S the scope in which name lookup occurs.
2977///
2978/// \param SS the nested-name-specifier that precedes the name we're
2979/// looking for, if present.
2980///
Douglas Gregoraf2bd472009-12-31 07:42:17 +00002981/// \param MemberContext if non-NULL, the context in which to look for
2982/// a member access expression.
2983///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002984/// \param EnteringContext whether we're entering the context described by
Douglas Gregor598b08f2009-12-31 05:20:13 +00002985/// the nested-name-specifier SS.
2986///
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002987/// \param CTC The context in which typo correction occurs, which impacts the
2988/// set of keywords permitted.
2989///
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002990/// \param OPT when non-NULL, the search for visible declarations will
2991/// also walk the protocols in the qualified interfaces of \p OPT.
2992///
Douglas Gregorfd0e2e32010-04-14 17:09:22 +00002993/// \returns the corrected name if the typo was corrected, otherwise returns an
2994/// empty \c DeclarationName. When a typo was corrected, the result structure
2995/// may contain the results of name lookup for the correct name or it may be
2996/// empty.
2997DeclarationName Sema::CorrectTypo(LookupResult &Res, Scope *S, CXXScopeSpec *SS,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002998 DeclContext *MemberContext,
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002999 bool EnteringContext,
3000 CorrectTypoContext CTC,
3001 const ObjCObjectPointerType *OPT) {
Douglas Gregor8ed0c0b2010-07-09 17:35:33 +00003002 if (Diags.hasFatalErrorOccurred() || !getLangOptions().SpellChecking)
Douglas Gregorfd0e2e32010-04-14 17:09:22 +00003003 return DeclarationName();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003004
Douglas Gregor2d435302009-12-30 17:04:44 +00003005 // We only attempt to correct typos for identifiers.
3006 IdentifierInfo *Typo = Res.getLookupName().getAsIdentifierInfo();
3007 if (!Typo)
Douglas Gregorfd0e2e32010-04-14 17:09:22 +00003008 return DeclarationName();
Douglas Gregor2d435302009-12-30 17:04:44 +00003009
3010 // If the scope specifier itself was invalid, don't try to correct
3011 // typos.
3012 if (SS && SS->isInvalid())
Douglas Gregorfd0e2e32010-04-14 17:09:22 +00003013 return DeclarationName();
Douglas Gregor2d435302009-12-30 17:04:44 +00003014
3015 // Never try to correct typos during template deduction or
3016 // instantiation.
3017 if (!ActiveTemplateInstantiations.empty())
Douglas Gregorfd0e2e32010-04-14 17:09:22 +00003018 return DeclarationName();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003019
Douglas Gregor2d435302009-12-30 17:04:44 +00003020 TypoCorrectionConsumer Consumer(Typo);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003021
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003022 // Perform name lookup to find visible, similarly-named entities.
Douglas Gregor87074f12010-10-20 01:32:02 +00003023 bool IsUnqualifiedLookup = false;
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003024 if (MemberContext) {
Douglas Gregoraf2bd472009-12-31 07:42:17 +00003025 LookupVisibleDecls(MemberContext, Res.getLookupKind(), Consumer);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003026
3027 // Look in qualified interfaces.
3028 if (OPT) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003029 for (ObjCObjectPointerType::qual_iterator
3030 I = OPT->qual_begin(), E = OPT->qual_end();
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003031 I != E; ++I)
3032 LookupVisibleDecls(*I, Res.getLookupKind(), Consumer);
3033 }
3034 } else if (SS && SS->isSet()) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003035 DeclContext *DC = computeDeclContext(*SS, EnteringContext);
3036 if (!DC)
Douglas Gregorfd0e2e32010-04-14 17:09:22 +00003037 return DeclarationName();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003038
Douglas Gregor87074f12010-10-20 01:32:02 +00003039 // Provide a stop gap for files that are just seriously broken. Trying
3040 // to correct all typos can turn into a HUGE performance penalty, causing
3041 // some files to take minutes to get rejected by the parser.
3042 if (TyposCorrected + UnqualifiedTyposCorrected.size() >= 20)
3043 return DeclarationName();
3044 ++TyposCorrected;
3045
Douglas Gregor2d435302009-12-30 17:04:44 +00003046 LookupVisibleDecls(DC, Res.getLookupKind(), Consumer);
3047 } else {
Douglas Gregor87074f12010-10-20 01:32:02 +00003048 IsUnqualifiedLookup = true;
3049 UnqualifiedTyposCorrectedMap::iterator Cached
3050 = UnqualifiedTyposCorrected.find(Typo);
3051 if (Cached == UnqualifiedTyposCorrected.end()) {
3052 // Provide a stop gap for files that are just seriously broken. Trying
3053 // to correct all typos can turn into a HUGE performance penalty, causing
3054 // some files to take minutes to get rejected by the parser.
3055 if (TyposCorrected + UnqualifiedTyposCorrected.size() >= 20)
3056 return DeclarationName();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003057
Douglas Gregor87074f12010-10-20 01:32:02 +00003058 // For unqualified lookup, look through all of the names that we have
3059 // seen in this translation unit.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003060 for (IdentifierTable::iterator I = Context.Idents.begin(),
Douglas Gregor87074f12010-10-20 01:32:02 +00003061 IEnd = Context.Idents.end();
3062 I != IEnd; ++I)
3063 Consumer.FoundName(I->getKey());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003064
Douglas Gregor87074f12010-10-20 01:32:02 +00003065 // Walk through identifiers in external identifier sources.
3066 if (IdentifierInfoLookup *External
Douglas Gregor57756ea2010-10-14 22:11:03 +00003067 = Context.Idents.getExternalIdentifierLookup()) {
Ted Kremenekb4ea9a82010-11-07 06:11:33 +00003068 llvm::OwningPtr<IdentifierIterator> Iter(External->getIdentifiers());
Douglas Gregor87074f12010-10-20 01:32:02 +00003069 do {
3070 llvm::StringRef Name = Iter->Next();
3071 if (Name.empty())
3072 break;
Douglas Gregor57756ea2010-10-14 22:11:03 +00003073
Douglas Gregor87074f12010-10-20 01:32:02 +00003074 Consumer.FoundName(Name);
3075 } while (true);
3076 }
3077 } else {
3078 // Use the cached value, unless it's a keyword. In the keyword case, we'll
3079 // end up adding the keyword below.
3080 if (Cached->second.first.empty())
3081 return DeclarationName();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003082
Douglas Gregor87074f12010-10-20 01:32:02 +00003083 if (!Cached->second.second)
3084 Consumer.FoundName(Cached->second.first);
Douglas Gregor57756ea2010-10-14 22:11:03 +00003085 }
Douglas Gregor2d435302009-12-30 17:04:44 +00003086 }
3087
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003088 // Add context-dependent keywords.
3089 bool WantTypeSpecifiers = false;
3090 bool WantExpressionKeywords = false;
3091 bool WantCXXNamedCasts = false;
3092 bool WantRemainingKeywords = false;
3093 switch (CTC) {
3094 case CTC_Unknown:
3095 WantTypeSpecifiers = true;
3096 WantExpressionKeywords = true;
3097 WantCXXNamedCasts = true;
3098 WantRemainingKeywords = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003099
Douglas Gregor5fd04d42010-05-18 16:14:23 +00003100 if (ObjCMethodDecl *Method = getCurMethodDecl())
3101 if (Method->getClassInterface() &&
3102 Method->getClassInterface()->getSuperClass())
3103 Consumer.addKeywordResult(Context, "super");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003104
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003105 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003106
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003107 case CTC_NoKeywords:
3108 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003109
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003110 case CTC_Type:
3111 WantTypeSpecifiers = true;
3112 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003113
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003114 case CTC_ObjCMessageReceiver:
3115 Consumer.addKeywordResult(Context, "super");
3116 // Fall through to handle message receivers like expressions.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003117
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003118 case CTC_Expression:
3119 if (getLangOptions().CPlusPlus)
3120 WantTypeSpecifiers = true;
3121 WantExpressionKeywords = true;
3122 // Fall through to get C++ named casts.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003123
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003124 case CTC_CXXCasts:
3125 WantCXXNamedCasts = true;
3126 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003127
Douglas Gregord507d772010-10-20 03:06:34 +00003128 case CTC_ObjCPropertyLookup:
3129 // FIXME: Add "isa"?
3130 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003131
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003132 case CTC_MemberLookup:
3133 if (getLangOptions().CPlusPlus)
3134 Consumer.addKeywordResult(Context, "template");
3135 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003136
Douglas Gregord507d772010-10-20 03:06:34 +00003137 case CTC_ObjCIvarLookup:
3138 break;
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003139 }
3140
3141 if (WantTypeSpecifiers) {
3142 // Add type-specifier keywords to the set of results.
3143 const char *CTypeSpecs[] = {
3144 "char", "const", "double", "enum", "float", "int", "long", "short",
3145 "signed", "struct", "union", "unsigned", "void", "volatile", "_Bool",
3146 "_Complex", "_Imaginary",
3147 // storage-specifiers as well
3148 "extern", "inline", "static", "typedef"
3149 };
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003150
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003151 const unsigned NumCTypeSpecs = sizeof(CTypeSpecs) / sizeof(CTypeSpecs[0]);
3152 for (unsigned I = 0; I != NumCTypeSpecs; ++I)
3153 Consumer.addKeywordResult(Context, CTypeSpecs[I]);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003154
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003155 if (getLangOptions().C99)
3156 Consumer.addKeywordResult(Context, "restrict");
3157 if (getLangOptions().Bool || getLangOptions().CPlusPlus)
3158 Consumer.addKeywordResult(Context, "bool");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003159
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003160 if (getLangOptions().CPlusPlus) {
3161 Consumer.addKeywordResult(Context, "class");
3162 Consumer.addKeywordResult(Context, "typename");
3163 Consumer.addKeywordResult(Context, "wchar_t");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003164
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003165 if (getLangOptions().CPlusPlus0x) {
3166 Consumer.addKeywordResult(Context, "char16_t");
3167 Consumer.addKeywordResult(Context, "char32_t");
3168 Consumer.addKeywordResult(Context, "constexpr");
3169 Consumer.addKeywordResult(Context, "decltype");
3170 Consumer.addKeywordResult(Context, "thread_local");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003171 }
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003172 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003173
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003174 if (getLangOptions().GNUMode)
3175 Consumer.addKeywordResult(Context, "typeof");
3176 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003177
Douglas Gregor86ad0852010-05-18 16:30:22 +00003178 if (WantCXXNamedCasts && getLangOptions().CPlusPlus) {
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003179 Consumer.addKeywordResult(Context, "const_cast");
3180 Consumer.addKeywordResult(Context, "dynamic_cast");
3181 Consumer.addKeywordResult(Context, "reinterpret_cast");
3182 Consumer.addKeywordResult(Context, "static_cast");
3183 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003184
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003185 if (WantExpressionKeywords) {
3186 Consumer.addKeywordResult(Context, "sizeof");
3187 if (getLangOptions().Bool || getLangOptions().CPlusPlus) {
3188 Consumer.addKeywordResult(Context, "false");
3189 Consumer.addKeywordResult(Context, "true");
3190 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003191
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003192 if (getLangOptions().CPlusPlus) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003193 const char *CXXExprs[] = {
3194 "delete", "new", "operator", "throw", "typeid"
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003195 };
3196 const unsigned NumCXXExprs = sizeof(CXXExprs) / sizeof(CXXExprs[0]);
3197 for (unsigned I = 0; I != NumCXXExprs; ++I)
3198 Consumer.addKeywordResult(Context, CXXExprs[I]);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003199
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003200 if (isa<CXXMethodDecl>(CurContext) &&
3201 cast<CXXMethodDecl>(CurContext)->isInstance())
3202 Consumer.addKeywordResult(Context, "this");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003203
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003204 if (getLangOptions().CPlusPlus0x) {
3205 Consumer.addKeywordResult(Context, "alignof");
3206 Consumer.addKeywordResult(Context, "nullptr");
3207 }
3208 }
3209 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003210
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003211 if (WantRemainingKeywords) {
3212 if (getCurFunctionOrMethodDecl() || getCurBlock()) {
3213 // Statements.
3214 const char *CStmts[] = {
3215 "do", "else", "for", "goto", "if", "return", "switch", "while" };
3216 const unsigned NumCStmts = sizeof(CStmts) / sizeof(CStmts[0]);
3217 for (unsigned I = 0; I != NumCStmts; ++I)
3218 Consumer.addKeywordResult(Context, CStmts[I]);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003219
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003220 if (getLangOptions().CPlusPlus) {
3221 Consumer.addKeywordResult(Context, "catch");
3222 Consumer.addKeywordResult(Context, "try");
3223 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003224
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003225 if (S && S->getBreakParent())
3226 Consumer.addKeywordResult(Context, "break");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003227
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003228 if (S && S->getContinueParent())
3229 Consumer.addKeywordResult(Context, "continue");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003230
John McCallaab3e412010-08-25 08:40:02 +00003231 if (!getCurFunction()->SwitchStack.empty()) {
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003232 Consumer.addKeywordResult(Context, "case");
3233 Consumer.addKeywordResult(Context, "default");
3234 }
3235 } else {
3236 if (getLangOptions().CPlusPlus) {
3237 Consumer.addKeywordResult(Context, "namespace");
3238 Consumer.addKeywordResult(Context, "template");
3239 }
3240
3241 if (S && S->isClassScope()) {
3242 Consumer.addKeywordResult(Context, "explicit");
3243 Consumer.addKeywordResult(Context, "friend");
3244 Consumer.addKeywordResult(Context, "mutable");
3245 Consumer.addKeywordResult(Context, "private");
3246 Consumer.addKeywordResult(Context, "protected");
3247 Consumer.addKeywordResult(Context, "public");
3248 Consumer.addKeywordResult(Context, "virtual");
3249 }
3250 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003251
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003252 if (getLangOptions().CPlusPlus) {
3253 Consumer.addKeywordResult(Context, "using");
3254
3255 if (getLangOptions().CPlusPlus0x)
3256 Consumer.addKeywordResult(Context, "static_assert");
3257 }
3258 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003259
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003260 // If we haven't found anything, we're done.
Douglas Gregor87074f12010-10-20 01:32:02 +00003261 if (Consumer.empty()) {
3262 // If this was an unqualified lookup, note that no correction was found.
3263 if (IsUnqualifiedLookup)
3264 (void)UnqualifiedTyposCorrected[Typo];
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003265
Douglas Gregorfd0e2e32010-04-14 17:09:22 +00003266 return DeclarationName();
Douglas Gregor87074f12010-10-20 01:32:02 +00003267 }
Douglas Gregor2d435302009-12-30 17:04:44 +00003268
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003269 // Make sure that the user typed at least 3 characters for each correction
Douglas Gregor0afa7f62010-10-14 20:34:08 +00003270 // made. Otherwise, we don't even both looking at the results.
Douglas Gregor2a1d72d2010-10-26 17:18:00 +00003271
3272 // We also suppress exact matches; those should be handled by a
3273 // different mechanism (e.g., one that introduces qualification in
3274 // C++).
Douglas Gregor0afa7f62010-10-14 20:34:08 +00003275 unsigned ED = Consumer.getBestEditDistance();
Douglas Gregor87074f12010-10-20 01:32:02 +00003276 if (ED > 0 && Typo->getName().size() / ED < 3) {
3277 // If this was an unqualified lookup, note that no correction was found.
Douglas Gregoraf1daa92010-10-27 14:20:34 +00003278 if (IsUnqualifiedLookup)
Douglas Gregor87074f12010-10-20 01:32:02 +00003279 (void)UnqualifiedTyposCorrected[Typo];
3280
Douglas Gregor0afa7f62010-10-14 20:34:08 +00003281 return DeclarationName();
Douglas Gregor87074f12010-10-20 01:32:02 +00003282 }
Douglas Gregor0afa7f62010-10-14 20:34:08 +00003283
3284 // Weed out any names that could not be found by name lookup.
Douglas Gregor26c55782010-10-15 16:49:56 +00003285 bool LastLookupWasAccepted = false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003286 for (TypoCorrectionConsumer::iterator I = Consumer.begin(),
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003287 IEnd = Consumer.end();
Douglas Gregor0afa7f62010-10-14 20:34:08 +00003288 I != IEnd; /* Increment in loop. */) {
3289 // Keywords are always found.
3290 if (I->second) {
3291 ++I;
3292 continue;
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003293 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003294
Douglas Gregor0afa7f62010-10-14 20:34:08 +00003295 // Perform name lookup on this name.
3296 IdentifierInfo *Name = &Context.Idents.get(I->getKey());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003297 LookupPotentialTypoResult(*this, Res, Name, S, SS, MemberContext,
Douglas Gregord507d772010-10-20 03:06:34 +00003298 EnteringContext, CTC);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003299
Douglas Gregor0afa7f62010-10-14 20:34:08 +00003300 switch (Res.getResultKind()) {
3301 case LookupResult::NotFound:
3302 case LookupResult::NotFoundInCurrentInstantiation:
3303 case LookupResult::Ambiguous:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003304 // We didn't find this name in our scope, or didn't like what we found;
Douglas Gregor0afa7f62010-10-14 20:34:08 +00003305 // ignore it.
3306 Res.suppressDiagnostics();
3307 {
3308 TypoCorrectionConsumer::iterator Next = I;
3309 ++Next;
3310 Consumer.erase(I);
3311 I = Next;
3312 }
Douglas Gregor26c55782010-10-15 16:49:56 +00003313 LastLookupWasAccepted = false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003314 break;
3315
Douglas Gregor0afa7f62010-10-14 20:34:08 +00003316 case LookupResult::Found:
3317 case LookupResult::FoundOverloaded:
3318 case LookupResult::FoundUnresolvedValue:
3319 ++I;
Douglas Gregord507d772010-10-20 03:06:34 +00003320 LastLookupWasAccepted = true;
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003321 break;
Douglas Gregor0afa7f62010-10-14 20:34:08 +00003322 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003323
Douglas Gregor0afa7f62010-10-14 20:34:08 +00003324 if (Res.isAmbiguous()) {
3325 // We don't deal with ambiguities.
3326 Res.suppressDiagnostics();
3327 Res.clear();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003328 return DeclarationName();
3329 }
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003330 }
Douglas Gregor2d435302009-12-30 17:04:44 +00003331
Douglas Gregor0afa7f62010-10-14 20:34:08 +00003332 // If only a single name remains, return that result.
Douglas Gregor26c55782010-10-15 16:49:56 +00003333 if (Consumer.size() == 1) {
3334 IdentifierInfo *Name = &Context.Idents.get(Consumer.begin()->getKey());
Douglas Gregor1f32ebe2010-10-20 01:01:57 +00003335 if (Consumer.begin()->second) {
3336 Res.suppressDiagnostics();
3337 Res.clear();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003338
Douglas Gregor2a1d72d2010-10-26 17:18:00 +00003339 // Don't correct to a keyword that's the same as the typo; the keyword
3340 // wasn't actually in scope.
3341 if (ED == 0) {
3342 Res.setLookupName(Typo);
3343 return DeclarationName();
3344 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003345
Douglas Gregor1f32ebe2010-10-20 01:01:57 +00003346 } else if (!LastLookupWasAccepted) {
Douglas Gregor26c55782010-10-15 16:49:56 +00003347 // Perform name lookup on this name.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003348 LookupPotentialTypoResult(*this, Res, Name, S, SS, MemberContext,
Douglas Gregord507d772010-10-20 03:06:34 +00003349 EnteringContext, CTC);
Douglas Gregor26c55782010-10-15 16:49:56 +00003350 }
3351
Douglas Gregor87074f12010-10-20 01:32:02 +00003352 // Record the correction for unqualified lookup.
3353 if (IsUnqualifiedLookup)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003354 UnqualifiedTyposCorrected[Typo]
Douglas Gregord507d772010-10-20 03:06:34 +00003355 = std::make_pair(Name->getName(), Consumer.begin()->second);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003356
3357 return &Context.Idents.get(Consumer.begin()->getKey());
Douglas Gregor26c55782010-10-15 16:49:56 +00003358 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003359 else if (Consumer.size() > 1 && CTC == CTC_ObjCMessageReceiver
Douglas Gregoraf9eb592010-10-15 13:35:25 +00003360 && Consumer["super"]) {
3361 // Prefix 'super' when we're completing in a message-receiver
3362 // context.
3363 Res.suppressDiagnostics();
3364 Res.clear();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003365
Douglas Gregor2a1d72d2010-10-26 17:18:00 +00003366 // Don't correct to a keyword that's the same as the typo; the keyword
3367 // wasn't actually in scope.
3368 if (ED == 0) {
3369 Res.setLookupName(Typo);
3370 return DeclarationName();
3371 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003372
Douglas Gregor87074f12010-10-20 01:32:02 +00003373 // Record the correction for unqualified lookup.
3374 if (IsUnqualifiedLookup)
3375 UnqualifiedTyposCorrected[Typo]
Douglas Gregord507d772010-10-20 03:06:34 +00003376 = std::make_pair("super", Consumer.begin()->second);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003377
Douglas Gregoraf9eb592010-10-15 13:35:25 +00003378 return &Context.Idents.get("super");
3379 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003380
Douglas Gregor0afa7f62010-10-14 20:34:08 +00003381 Res.suppressDiagnostics();
3382 Res.setLookupName(Typo);
Douglas Gregor2d435302009-12-30 17:04:44 +00003383 Res.clear();
Douglas Gregor87074f12010-10-20 01:32:02 +00003384 // Record the correction for unqualified lookup.
3385 if (IsUnqualifiedLookup)
3386 (void)UnqualifiedTyposCorrected[Typo];
3387
Douglas Gregorfd0e2e32010-04-14 17:09:22 +00003388 return DeclarationName();
Douglas Gregor2d435302009-12-30 17:04:44 +00003389}